<commit_before>import React, { Component, PropTypes } from 'react';
import Message from './Message';
import UploadImage from './UploadImage';
import { request } from '../actions/actions';

class LoginEmail extends Component {
  constructor(props) {
    super(props);
    this.state = {
      open: false,
      type: 'login', // or 'register'
      message: null,
      name: '',
      email: '',
      password: '',
      password_confirmation: ''
    };
  }

  onFormSubmit(e) {
    e.preventDefault();

    if (this.state.type === 'login') {
      this.loginEmail();
    } else {
      this.registerEmail();
    }
  }

  loginEmail() {
    var that = this;
    var params = {
      'api_user[email]': this.state.email,
      'api_user[password]': this.state.password
    };
    var failureCallback = function(message) {
      that.setState({ open: true, message: message });
    },
    successCallback = function(data) {
      that.setState({ open: false, message: null });
      Checkdesk.history.push('/');
    };
    request('post', 'users/sign_in', failureCallback, successCallback, params);
  }

  registerEmail() {
    var that = this,
        form = document.forms.register;
    var params = {
      'api_user[email]': this.state.email,
      'api_user[name]': this.state.name,
      'api_user[password]': this.state.password,
      'api_user[password_confirmation]': this.state.password_confirmation,
      'api_user[image]': form.image
    };
    var failureCallback = function(message) {
      that.setState({ open: true, message: message });
    },
    successCallback = function(data) {
      that.setState({ open: false, message: null });
      Checkdesk.history.push(window.location.pathname);
    };
    request('post', 'users', failureCallback, successCallback, params);
  }

  handleOpen() {
    this.setState({ open: true }, function() {
      this.focusFirstInput();
    });
  }

  focusFirstInput() {
    const input = document.querySelector(".login-email input");
    if (input) {
      input.focus();
    }
  }

  handleClose() {
    this.setState({ open: false });
    return true;
  }

  handleSwitchType() {
    const type = this.state.type === 'login' ? 'register' : 'login';
    this.setState({ type: type }, function() {
      this.focusFirstInput();
    });
  }

  onImage(file) {
    document.forms.register.image = file;
  }

  handleFieldChange(e) {
    var state = {};
    state[e.target.name] = e.target.value;
    this.setState(state);
  }

  bemClass(baseClass, modifierBoolean, modifierSuffix) {
    return modifierBoolean ? [baseClass, baseClass + modifierSuffix].join(' ') : baseClass;
  }

  render() {
    const { state } = this.props;

    return (

        Sign in with e-mail

          <Message message={this.state.message} />
          <form name={this.state.type} onSubmit={this.onFormSubmit.bind(this)} className='login-email__form'>
            {this.state.type === 'login' ? null : (

                <input type='text' name='name' value={this.state.name} className='login-email__name-input' onChange={this.handleFieldChange.bind(this)} placeholder="Your name" />
                Your name

            )}

              <input type='email' name='email' value={this.state.email} className='login-email__email-input' onChange={this.handleFieldChange.bind(this)} placeholder='Email address' />
              Email address

              <input type='password' name='password' value={this.state.password} className='login-email__password-input' onChange={this.handleFieldChange.bind(this)} placeholder='Password' />
              Password (minimum 8 characters)

            {this.state.type === 'login' ? null : (

                <input type='password' name='password_confirmation' value={this.state.password_confirmation} className='login-email__password-confirmation-input' onChange={this.handleFieldChange.bind(this)} placeholder='Password confirmation' />
                Password confirmation

            )}

            {this.state.type === 'login' ? null : (
              <UploadImage onImage={this.onImage.bind(this)} />
            )}

              <button type="submit" id="submit-register-or-login" onClick={this.onFormSubmit.bind(this)} className={'login-email__submit login-email__submit--' + this.state.type}>
                {this.state.type === 'login' ? 'Sign in »' : 'Sign up »'}
              </button>
              <button type="button" id="register-or-login" onClick={this.handleSwitchType.bind(this)} className='login-email__register-or-login'>
                {this.state.type === 'register' ? 'I already have an account' : 'Create a new account'}
              </button>
              <button type="button" id="cancel-register-or-login" onClick={this.handleClose.bind(this)} className='login-email__cancel'>Sign in with Twitter, Facebook, or Slack</button>

          </form>
          {this.state.type === 'login' ? (
Having trouble logging in? Please email check@meedan.com for assistance.
) : null}

    );
  }
}

export default LoginEmail;
<commit_msg>Linkify email address on email login screen<commit_after>import React, { Component, PropTypes } from 'react';
import Message from './Message';
import UploadImage from './UploadImage';
import { request } from '../actions/actions';
import { Link } from 'react-router';

class LoginEmail extends Component {
  constructor(props) {
    super(props);
    this.state = {
      open: false,
      type: 'login', // or 'register'
      message: null,
      name: '',
      email: '',
      password: '',
      password_confirmation: ''
    };
  }

  onFormSubmit(e) {
    e.preventDefault();

    if (this.state.type === 'login') {
      this.loginEmail();
    } else {
      this.registerEmail();
    }
  }

  loginEmail() {
    var that = this;
    var params = {
      'api_user[email]': this.state.email,
      'api_user[password]': this.state.password
    };
    var failureCallback = function(message) {
      that.setState({ open: true, message: message });
    },
    successCallback = function(data) {
      that.setState({ open: false, message: null });
      Checkdesk.history.push('/');
    };
    request('post', 'users/sign_in', failureCallback, successCallback, params);
  }

  registerEmail() {
    var that = this,
        form = document.forms.register;
    var params = {
      'api_user[email]': this.state.email,
      'api_user[name]': this.state.name,
      'api_user[password]': this.state.password,
      'api_user[password_confirmation]': this.state.password_confirmation,
      'api_user[image]': form.image
    };
    var failureCallback = function(message) {
      that.setState({ open: true, message: message });
    },
    successCallback = function(data) {
      that.setState({ open: false, message: null });
      Checkdesk.history.push(window.location.pathname);
    };
    request('post', 'users', failureCallback, successCallback, params);
  }

  handleOpen() {
    this.setState({ open: true }, function() {
      this.focusFirstInput();
    });
  }

  focusFirstInput() {
    const input = document.querySelector(".login-email input");
    if (input) {
      input.focus();
    }
  }

  handleClose() {
    this.setState({ open: false });
    return true;
  }

  handleSwitchType() {
    const type = this.state.type === 'login' ? 'register' : 'login';
    this.setState({ type: type }, function() {
      this.focusFirstInput();
    });
  }

  onImage(file) {
    document.forms.register.image = file;
  }

  handleFieldChange(e) {
    var state = {};
    state[e.target.name] = e.target.value;
    this.setState(state);
  }

  bemClass(baseClass, modifierBoolean, modifierSuffix) {
    return modifierBoolean ? [baseClass, baseClass + modifierSuffix].join(' ') : baseClass;
  }

  render() {
    const { state } = this.props;

    return (

        Sign in with e-mail

          <Message message={this.state.message} />
          <form name={this.state.type} onSubmit={this.onFormSubmit.bind(this)} className='login-email__form'>
            {this.state.type === 'login' ? null : (

                <input type='text' name='name' value={this.state.name} className='login-email__name-input' onChange={this.handleFieldChange.bind(this)} placeholder="Your name" />
                Your name

            )}

              <input type='email' name='email' value={this.state.email} className='login-email__email-input' onChange={this.handleFieldChange.bind(this)} placeholder='Email address' />
              Email address

              <input type='password' name='password' value={this.state.password} className='login-email__password-input' onChange={this.handleFieldChange.bind(this)} placeholder='Password' />
              Password (minimum 8 characters)

            {this.state.type === 'login' ? null : (

                <input type='password' name='password_confirmation' value={this.state.password_confirmation} className='login-email__password-confirmation-input' onChange={this.handleFieldChange.bind(this)} placeholder='Password confirmation' />
                Password confirmation

            )}

            {this.state.type === 'login' ? null : (
              <UploadImage onImage={this.onImage.bind(this)} />
            )}

              <button type="submit" id="submit-register-or-login" onClick={this.onFormSubmit.bind(this)} className={'login-email__submit login-email__submit--' + this.state.type}>
                {this.state.type === 'login' ? 'Sign in »' : 'Sign up »'}
              </button>
              <button type="button" id="register-or-login" onClick={this.handleSwitchType.bind(this)} className='login-email__register-or-login'>
                {this.state.type === 'register' ? 'I already have an account' : 'Create a new account'}
              </button>
              <button type="button" id="cancel-register-or-login" onClick={this.handleClose.bind(this)} className='login-email__cancel'>Sign in with Twitter, Facebook, or Slack</button>

          </form>
          {this.state.type === 'login' ? (
Having trouble logging in? Please email <Link to='mailto:check@meedan.com'>check@meedan.com</Link> for assistance.
) : null}

    );
  }
}

export default LoginEmail;
<|endoftext|>


<commit_before>"use strict";

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _react = require("react");

var _react2 = _interopRequireDefault(_react);

var _reactAddonsUpdate = require("react-addons-update");

var _reactAddonsUpdate2 = _interopRequireDefault(_reactAddonsUpdate);

var _ToastMessage = require("./ToastMessage");

var _ToastMessage2 = _interopRequireDefault(_ToastMessage);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var ToastContainer = function (_Component) {
  _inherits(ToastContainer, _Component);

  function ToastContainer() {
    var _Object$getPrototypeO;

    var _temp, _this, _ret;

    _classCallCheck(this, ToastContainer);

    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_Object$getPrototypeO = Object.getPrototypeOf(ToastContainer)).call.apply(_Object$getPrototypeO, [this].concat(args))), _this), _this.state = {
      toasts: [],
      toastId: 0,
      previousMessage: null
    }, _temp), _possibleConstructorReturn(_this, _ret);
  }

  _createClass(ToastContainer, [{
    key: "error",
    value: function error(message, title, optionsOverride) {
      this._notify(this.props.toastType.error, message, title, optionsOverride);
    }
  }, {
    key: "info",
    value: function info(message, title, optionsOverride) {
      this._notify(this.props.toastType.info, message, title, optionsOverride);
    }
  }, {
    key: "success",
    value: function success(message, title, optionsOverride) {
      this._notify(this.props.toastType.success, message, title, optionsOverride);
    }
  }, {
    key: "warning",
    value: function warning(message, title, optionsOverride) {
      this._notify(this.props.toastType.warning, message, title, optionsOverride);
    }
  }, {
    key: "clear",
    value: function clear() {
      var _this2 = this;

      Object.keys(this.refs).forEach(function (key) {
        _this2.refs[key].hideToast(false);
      });
    }
  }, {
    key: "render",
    value: function render() {
      var _this3 = this;

      return _react2.default.createElement(
        "div",
        _extends({}, this.props, { "aria-live": "polite", role: "alert" }),
        this.state.toasts.map(function (toast) {
          return _this3.props.toastMessageFactory(toast);
        })
      );
    }
  }, {
    key: "_notify",
    value: function _notify(type, message, title) {
      var _this4 = this;

      var optionsOverride = arguments.length <= 3 || arguments[3] === undefined ? {} : arguments[3];

      if (this.props.preventDuplicates) {
        if (this.state.previousMessage === message) {
          return;
        }
      }
      var key = this.state.toastId++;
      var toastId = key;
      var newToast = (0, _reactAddonsUpdate2.default)(optionsOverride, {
        $merge: {
          type: type,
          title: title,
          message: message,
          toastId: toastId,
          key: key,
          ref: "toasts__" + key,
          handleOnClick: function handleOnClick(e) {
            if ("function" === typeof optionsOverride.handleOnClick) {
              optionsOverride.handleOnClick();
            }
            return _this4._handle_toast_on_click(e);
          },
          handleRemove: this._handle_toast_remove.bind(this)
        }
      });
      var toastOperation = _defineProperty({}, "" + (this.props.newestOnTop ? "$unshift" : "$push"), [newToast]);

      var nextState = (0, _reactAddonsUpdate2.default)(this.state, {
        toasts: toastOperation,
        previousMessage: { $set: message }
      });
      this.setState(nextState);
    }
  }, {
    key: "_handle_toast_on_click",
    value: function _handle_toast_on_click(event) {
      this.props.onClick(event);
      if (event.defaultPrevented) {
        return;
      }
      event.preventDefault();
      event.stopPropagation();
    }
  }, {
    key: "_handle_toast_remove",
    value: function _handle_toast_remove(toastId) {
      var _this5 = this;

      var operationName = "" + (this.props.newestOnTop ? "reduceRight" : "reduce");
      this.state.toasts[operationName](function (found, toast, index) {
        if (found || toast.toastId !== toastId) {
          return false;
        }
        _this5.setState((0, _reactAddonsUpdate2.default)(_this5.state, {
          toasts: { $splice: [[index, 1]] }
        }));
        return true;
      }, false);
    }
  }]);

  return ToastContainer;
}(_react.Component);

ToastContainer.defaultProps = {
  toastType: {
    error: "error",
    info: "info",
    success: "success",
    warning: "warning"
  },
  id: "toast-container",
  toastMessageFactory: _react2.default.createFactory(_ToastMessage2.default),
  preventDuplicates: false,
  newestOnTop: true,
  onClick: function onClick() {}
};
exports.default = ToastContainer;<commit_msg>Return ToastMessage ref on create<commit_after>"use strict";

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _react = require("react");

var _react2 = _interopRequireDefault(_react);

var _reactAddonsUpdate = require("react-addons-update");

var _reactAddonsUpdate2 = _interopRequireDefault(_reactAddonsUpdate);

var _ToastMessage = require("./ToastMessage");

var _ToastMessage2 = _interopRequireDefault(_ToastMessage);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var ToastContainer = function (_Component) {
  _inherits(ToastContainer, _Component);

  function ToastContainer() {
    var _Object$getPrototypeO;

    var _temp, _this, _ret;

    _classCallCheck(this, ToastContainer);

    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_Object$getPrototypeO = Object.getPrototypeOf(ToastContainer)).call.apply(_Object$getPrototypeO, [this].concat(args))), _this), _this.state = {
      toasts: [],
      toastId: 0,
      previousMessage: null
    }, _temp), _possibleConstructorReturn(_this, _ret);
  }

  _createClass(ToastContainer, [{
    key: "error",
    value: function error(message, title, optionsOverride) {
      return this._notify(this.props.toastType.error, message, title, optionsOverride);
    }
  }, {
    key: "info",
    value: function info(message, title, optionsOverride) {
      return this._notify(this.props.toastType.info, message, title, optionsOverride);
    }
  }, {
    key: "success",
    value: function success(message, title, optionsOverride) {
      return this._notify(this.props.toastType.success, message, title, optionsOverride);
    }
  }, {
    key: "warning",
    value: function warning(message, title, optionsOverride) {
      return this._notify(this.props.toastType.warning, message, title, optionsOverride);
    }
  }, {
    key: "clear",
    value: function clear() {
      var _this2 = this;

      Object.keys(this.refs).forEach(function (key) {
        _this2.refs[key].hideToast(false);
      });
    }
  }, {
    key: "render",
    value: function render() {
      var _this3 = this;

      return _react2.default.createElement(
        "div",
        _extends({}, this.props, { "aria-live": "polite", role: "alert" }),
        this.state.toasts.map(function (toast) {
          return _this3.props.toastMessageFactory(toast);
        })
      );
    }
  }, {
    key: "_notify",
    value: function _notify(type, message, title) {
      var _this4 = this;

      var optionsOverride = arguments.length <= 3 || arguments[3] === undefined ? {} : arguments[3];

      if (this.props.preventDuplicates) {
        if (this.state.previousMessage === message) {
          return;
        }
      }
      var key = this.state.toastId++;
      var toastId = key;
      var ref = "toasts__" + key
      var newToast = (0, _reactAddonsUpdate2.default)(optionsOverride, {
        $merge: {
          type: type,
          title: title,
          message: message,
          toastId: toastId,
          key: key,
          ref: ref,
          handleOnClick: function handleOnClick(e) {
            if ("function" === typeof optionsOverride.handleOnClick) {
              optionsOverride.handleOnClick();
            }
            return _this4._handle_toast_on_click(e);
          },
          handleRemove: this._handle_toast_remove.bind(this)
        }
      });
      var toastOperation = _defineProperty({}, "" + (this.props.newestOnTop ? "$unshift" : "$push"), [newToast]);

      var nextState = (0, _reactAddonsUpdate2.default)(this.state, {
        toasts: toastOperation,
        previousMessage: { $set: message }
      });
      this.setState(nextState);

      return ref;
    }
  }, {
    key: "_handle_toast_on_click",
    value: function _handle_toast_on_click(event) {
      this.props.onClick(event);
      if (event.defaultPrevented) {
        return;
      }
      event.preventDefault();
      event.stopPropagation();
    }
  }, {
    key: "_handle_toast_remove",
    value: function _handle_toast_remove(toastId) {
      var _this5 = this;

      var operationName = "" + (this.props.newestOnTop ? "reduceRight" : "reduce");
      this.state.toasts[operationName](function (found, toast, index) {
        if (found || toast.toastId !== toastId) {
          return false;
        }
        _this5.setState((0, _reactAddonsUpdate2.default)(_this5.state, {
          toasts: { $splice: [[index, 1]] }
        }));
        return true;
      }, false);
    }
  }]);

  return ToastContainer;
}(_react.Component);

ToastContainer.defaultProps = {
  toastType: {
    error: "error",
    info: "info",
    success: "success",
    warning: "warning"
  },
  id: "toast-container",
  toastMessageFactory: _react2.default.createFactory(_ToastMessage2.default),
  preventDuplicates: false,
  newestOnTop: true,
  onClick: function onClick() {}
};
exports.default = ToastContainer;
<|endoftext|>


<commit_before>/*
 *  test/universal/standard/_util.js
 *
 *  David Janes
 *  IOTDB
 *  2019-01-07
 *
 *  Copyright [2013-2019] David P. Janes
 *
 *  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.
 */

"use strict"

const _ = require("iotdb-helpers")

/**
 *  The name of the module
 */
exports.name = "APPLICATION.db.movie"

/**
 *  The name of a single movie
 */
exports.one = "movie"

/**
 *  The name of multiple movies
 */
exports.many = "movies"

/**
 *  The name of the primary key in a movie
 */
exports.primary_id = "movie_id"

/**
 */
exports.validate = movie => _.is.Dictionary;
exports.validate.method = "APPLICATION.db.movie._util.validate"
exports.validate.description = "Test if movie is valid"

/**
 *  You must define self.table_schema here
 */
exports.setup = _.promise(self => {
    _.promise.validate(self, exports.setup)

    self.table_schema = {
        "name": "movies",
        "indexes": {
            "year-title-index": [ "year", "title" ],
            "-year-title-index": [ "-year", "title" ],
            "year--title-index": [ "year", "-title" ],
        },
        "keys": [ "title", "year" ],
    }

    self.table_name = self.table_schema.name
})

exports.setup.method = "APPLICATION.db.movie._util.setup"
exports.setup.description = `Setup database for movie`
exports.setup.requires = {
}
exports.setup.accepts = {
}
exports.setup.produces = {
    table_schema: {
        name: _.is.String,
        keys: _.is.Array,
        indexes: _.is.Dictionary,
    },
}

/**
 *  This cleans up one movie
 */
exports.scrub = _.promise(self => {
    _.promise.validate(self, exports.scrub)

    if (!self.movie) {
        self.movie = null
        return
    }

    self.movie = _.d.clone(self.movie)
})

exports.scrub.method = "APPLICATION.db.movie._util.scrub"
exports.scrub.description = `Clean up one movie`
exports.scrub.requires = {
}
exports.scrub.accepts = {
    movie: exports.validate,
}
exports.scrub.produces = {
    movie: exports.validate,
}

/**
 *  This is called after any operation which changes the movie.
 */
exports.updated = _.promise(self => {
    _.promise.validate(self, exports.updated)
})

exports.updated.method = "APPLICATION.db.movie._util.updated"
exports.updated.description = ``
exports.updated.requires = {
}
exports.updated.accepts = {
    movie: exports.validate,
}
exports.updated.produces = {
    movie: exports.validate,
}

/**
 *  This is called after any operation which removes the movie
 */
exports.removed = _.promise(self => {
    _.promise.validate(self, exports.removed)
})

exports.removed.method = "APPLICATION.db.movie._util.removed"
exports.removed.description = ``
exports.removed.requires = {
}
exports.removed.accepts = {
    movie: exports.validate,
}
exports.removed.produces = {
    movie: exports.validate,
}

/**
 *  This creates a new movie.
 *  There will always be a stub movie,
 *  but you must set an ID.
 *  You don't need to do anything that
 *  scrub does.
 */
exports.create = _.promise(self => {
    _.promise.validate(self, exports.create)

    self.movie = _.d.clone(self.movie)
    self.movie.movie_id = _.id.uuid.v4()
})

exports.create.method = "APPLICATION.db.movie._util.create"
exports.create.description = `Finish creating one movie`
exports.create.requires = {
}
exports.create.accepts = {
    movie: exports.validate,
}
exports.create.produces = {
    movie: exports.validate,
}
<commit_msg>no primary key<commit_after>/*
 *  test/universal/standard/_util.js
 *
 *  David Janes
 *  IOTDB
 *  2019-01-07
 *
 *  Copyright [2013-2019] David P. Janes
 *
 *  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.
 */

"use strict"

const _ = require("iotdb-helpers")

/**
 *  The name of the module
 */
exports.name = "APPLICATION.db.movie"

/**
 *  The name of a single movie
 */
exports.one = "movie"

/**
 *  The name of multiple movies
 */
exports.many = "movies"

/**
 *  The name of the primary key in a movie
 */
exports.primary_id = null

/**
 */
exports.validate = movie => _.is.Dictionary;
exports.validate.method = "APPLICATION.db.movie._util.validate"
exports.validate.description = "Test if movie is valid"

/**
 *  You must define self.table_schema here
 */
exports.setup = _.promise(self => {
    _.promise.validate(self, exports.setup)

    self.table_schema = {
        "name": "movies",
        "indexes": {
            "year-title-index": [ "year", "title" ],
            "-year-title-index": [ "-year", "title" ],
            "year--title-index": [ "year", "-title" ],
        },
        "keys": [ "title", "year" ],
    }

    self.table_name = self.table_schema.name
})

exports.setup.method = "APPLICATION.db.movie._util.setup"
exports.setup.description = `Setup database for movie`
exports.setup.requires = {
}
exports.setup.accepts = {
}
exports.setup.produces = {
    table_schema: {
        name: _.is.String,
        keys: _.is.Array,
        indexes: _.is.Dictionary,
    },
}

/**
 *  This cleans up one movie
 */
exports.scrub = _.promise(self => {
    _.promise.validate(self, exports.scrub)

    if (!self.movie) {
        self.movie = null
        return
    }

    self.movie = _.d.clone(self.movie)
})

exports.scrub.method = "APPLICATION.db.movie._util.scrub"
exports.scrub.description = `Clean up one movie`
exports.scrub.requires = {
}
exports.scrub.accepts = {
    movie: exports.validate,
}
exports.scrub.produces = {
    movie: exports.validate,
}

/**
 *  This is called after any operation which changes the movie.
 */
exports.updated = _.promise(self => {
    _.promise.validate(self, exports.updated)
})

exports.updated.method = "APPLICATION.db.movie._util.updated"
exports.updated.description = ``
exports.updated.requires = {
}
exports.updated.accepts = {
    movie: exports.validate,
}
exports.updated.produces = {
    movie: exports.validate,
}

/**
 *  This is called after any operation which removes the movie
 */
exports.removed = _.promise(self => {
    _.promise.validate(self, exports.removed)
})

exports.removed.method = "APPLICATION.db.movie._util.removed"
exports.removed.description = ``
exports.removed.requires = {
}
exports.removed.accepts = {
    movie: exports.validate,
}
exports.removed.produces = {
    movie: exports.validate,
}

/**
 *  This creates a new movie.
 *  There will always be a stub movie,
 *  but you must set an ID.
 *  You don't need to do anything that
 *  scrub does.
 */
exports.create = _.promise(self => {
    _.promise.validate(self, exports.create)

    self.movie = _.d.clone(self.movie)
    self.movie.movie_id = _.id.uuid.v4()
})

exports.create.method = "APPLICATION.db.movie._util.create"
exports.create.description = `Finish creating one movie`
exports.create.requires = {
}
exports.create.accepts = {
    movie: exports.validate,
}
exports.create.produces = {
    movie: exports.validate,
}
<|endoftext|>


<commit_before>const PLEDGERS = {
  golmansax: {
    firstName: 'Holman',
    lastName: 'Gao',
    pledges: [{
      impact: 'donate to youth education programs',
      howOften: 'year on my birthday',
      mission: 'I was fortunate enough to benefit from great programs when I ' +
        'was young and I want to support organizations that empower youth.',
      donations: [
        {
          year: 2015,
          organization: {
            url: 'http://www.mbhsmagnet.org/',
            text: 'Montgomery County ARML Team',
          },
          reason: 'This was an overnight math team field trip that I went to ' +
            'throughout middle and high school, and I loved going every year!',
        },
        {
          year: 2014,
          organization: {
            url: 'https://www.hopechineseschool.org/hcscp/',
            text: 'Hope Chinese School College Park Campus',
          },
          reason: 'I am very grateful to this school and my parents for ' +
            'helping/pushing me to learn Mandarin Chinese',
        },
        {
          year: 2013,
          organization: {
            url: 'http://www.asia.si.edu/events/imaginasia.asp',
            text: 'Smithsonian ImaginAsia Family Program',
          },
          reason: 'I volunteered for this program for six years, and I saw ' +
            'firsthand how empowering art projects can be',
        },
      ],
    }],
  },
};

Object.keys(PLEDGERS).forEach((id) => {
  /* eslint-disable no-param-reassign */
  const pledger = PLEDGERS[id];
  pledger.id = id;
  pledger.fullName = `${pledger.firstName} ${pledger.lastName}`;

  pledger.pledges.forEach((pledge) => {
    pledge.pledgeStatement = `I pledge to ${pledge.impact} every ` +
      `${pledge.howOften}.`;
  });
  /* eslint-enable no-param-reassign */
});

export default PLEDGERS;
<commit_msg>Add 2016<commit_after>const PLEDGERS = {
  golmansax: {
    firstName: 'Holman',
    lastName: 'Gao',
    pledges: [{
      impact: 'donate to youth education programs',
      howOften: 'year on my birthday',
      mission: 'I was fortunate enough to benefit from great programs when I ' +
        'was young and I want to support organizations that empower youth.',
      donations: [
        {
          year: 2016,
          organization: {
            url: 'http://www.mbhsmagnet.org/',
            text: 'Montgomery Blair High School Magnet',
          },
          reason: 'Not only did the Magnet instill in me a hard-working and ' +
            'technical foundation, it also gave me friends who I still see ' +
            'every year',
        },
        {
          year: 2015,
          organization: {
            url: 'http://www.mbhsmagnet.org/',
            text: 'Montgomery County ARML Team',
          },
          reason: 'This was an overnight math team field trip that I went to ' +
            'throughout middle and high school, and I loved going every year!',
        },
        {
          year: 2014,
          organization: {
            url: 'https://www.hopechineseschool.org/hcscp/',
            text: 'Hope Chinese School College Park Campus',
          },
          reason: 'I am very grateful to this school and my parents for ' +
            'helping/pushing me to learn Mandarin Chinese',
        },
        {
          year: 2013,
          organization: {
            url: 'http://www.asia.si.edu/events/imaginasia.asp',
            text: 'Smithsonian ImaginAsia Family Program',
          },
          reason: 'I volunteered for this program for six years, and I saw ' +
            'firsthand how empowering art projects can be',
        },
      ],
    }],
  },
};

Object.keys(PLEDGERS).forEach((id) => {
  /* eslint-disable no-param-reassign */
  const pledger = PLEDGERS[id];
  pledger.id = id;
  pledger.fullName = `${pledger.firstName} ${pledger.lastName}`;

  pledger.pledges.forEach((pledge) => {
    pledge.pledgeStatement = `I pledge to ${pledge.impact} every ` +
      `${pledge.howOften}.`;
  });
  /* eslint-enable no-param-reassign */
});

export default PLEDGERS;
<|endoftext|>


<commit_before>'use strict';

const Adapter = require('../Adapter');
const getArgs = require('getargs');
const promisify = require('../promisify');
const mysql2 = require('mysql2');

class Mysql extends Adapter {

	constructor(config) {
		let instance = mysql2.createConnection(config);
		super(instance);
	}

	/**
	 * Run the sql query as a prepared statement
	 *
	 * @param {String} sql - The sql with placeholders
	 * @param {Array} params - The values to insert into the query
	 * @param {Function} [callback] - Callback to run when a response is recieved
	 * @return {void|Promise} - Returns a promise if no callback is provided
	 */
	execute(/*sql, params, callback*/) {
		let args = getArgs('sql:string, [params]:array, [callback]:function', arguments);

		if (! args.callback) {
			return promisify(this.instance.execute)(args.sql, args.params);
		}

		return this.instance.execute(args.sql, args.params, args.callback);
	}
}

module.exports = Mysql;<commit_msg>Stab in the dark at fixing broken mysql tests<commit_after>'use strict';

const Adapter = require('../Adapter');
const getArgs = require('getargs');
const promisify = require('../promisify');
const mysql2 = require('mysql2');

class Mysql extends Adapter {

	constructor(config) {
		let instance = mysql2.createConnection(config);
		instance.connect();
		super(instance);
	}

	/**
	 * Run the sql query as a prepared statement
	 *
	 * @param {String} sql - The sql with placeholders
	 * @param {Array} params - The values to insert into the query
	 * @param {Function} [callback] - Callback to run when a response is recieved
	 * @return {void|Promise} - Returns a promise if no callback is provided
	 */
	execute(/*sql, params, callback*/) {
		let args = getArgs('sql:string, [params]:array, [callback]:function', arguments);

		if (! args.callback) {
			return promisify(this.instance.execute)(args.sql, args.params);
		}

		return this.instance.execute(args.sql, args.params, args.callback);
	}
}

module.exports = Mysql;<|endoftext|>


<commit_before>// Add support for Retina displays when using element attribute "ng-src".
// This module overrides the built-in directive "ng-src" with one which
// distinguishes between standard or high-resolution (Retina) displays.

(function(angular, undefined) {
'use strict';
var infix = '@2x',
  data_url_regex = /^data:([a-z]+\/[a-z]+(;[a-z\-]+\=[a-z\-]+)?)?(;base64)?,(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;

var ngRetina = angular.module('ngRetina', []).config(function($provide) {
  $provide.decorator('ngSrcDirective', ['$delegate', function($delegate) {
    $delegate[0].compile = function(element, attrs) {
      // intentionally empty to override the built-in directive ng-src
    };
    return $delegate;
  }]);
});

ngRetina.provider('ngRetina', function() {
  this.setInfix = function(value) {
    infix = value;
  };

  this.$get = angular.noop;
});

ngRetina.directive('ngSrc', ['$window', '$http', function($window, $http) {
  var msie = parseInt(((/msie (\d+)/.exec($window.navigator.userAgent.toLowerCase()) || [])[1]), 10);
  var isRetina = (function() {
    var mediaQuery = "(-webkit-min-device-pixel-ratio: 1.5), (min--moz-device-pixel-ratio: 1.5), " +
      "(-o-min-device-pixel-ratio: 3/2), (min-resolution: 1.5dppx)";
    if ($window.devicePixelRatio > 1)
      return true;
    return ($window.matchMedia && $window.matchMedia(mediaQuery).matches);
  })();

  function getHighResolutionURL(url) {
    var parts = url.split('.');
    if (parts.length < 2)
      return url;
    parts[parts.length - 2] += infix;
    return parts.join('.');
  }

  return function(scope, element, attrs) {
    function setImgSrc(img_url) {
      attrs.$set('src', img_url);
      if (msie) element.prop('src', img_url);
    }

    function set2xVariant(img_url) {
      var img_url_2x = $window.sessionStorage.getItem(img_url);
      if (!img_url_2x) {
        img_url_2x = getHighResolutionURL(img_url);
        $http.head(img_url_2x).
        success(function(data, status) {
          setImgSrc(img_url_2x);
          $window.sessionStorage.setItem(img_url, img_url_2x);
        }).
        error(function(data, status, headers, config) {
          setImgSrc(img_url);
          $window.sessionStorage.setItem(img_url, img_url);
        });
      } else {
        setImgSrc(img_url_2x);
      }
    }

    attrs.$observe('ngSrc', function(value) {
      if (!value)
        return;
      if (isRetina && typeof $window.sessionStorage === 'object' && element[0].tagName === 'IMG' && !value.match(data_url_regex)) {
        set2xVariant(value);
      } else {
        setImgSrc(value);
      }
    });
  };
}]);

})(window.angular);
<commit_msg>Update angular-retina.js<commit_after>/*! angular-retina - v0.3.1 - 2014-06-30
 * https://github.com/jrief/angular-retina
 * Copyright (c) 2014 Jacob Rief; Licensed MIT */
// Add support for Retina displays when using element attribute "ng-src".
// This module overrides the built-in directive "ng-src" with one which
// distinguishes between standard or high-resolution (Retina) displays.
(function(angular, undefined) {
    'use strict';
    var infix = '@2x',
        data_url_regex = /^data:([a-z]+\/[a-z]+(;[a-z\-]+\=[a-z\-]+)?)?(;base64)?,(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/i;
    var ngRetina = angular.module('ngRetina', []).config([
        '$provide',
        function($provide) {
            $provide.decorator('ngSrcDirective', [
                '$delegate',
                function($delegate) {
                    $delegate[0].compile = function(element, attrs) {};
                    return $delegate;
                }
            ]);
        }
    ]);
    ngRetina.provider('ngRetina', function() {
        this.setInfix = function(value) {
            infix = value;
        };
        this.$get = angular.noop;
    });
    ngRetina.directive('ngSrc', [
        '$window',
        '$http',
        function($window, $http) {
            var msie = parseInt((/msie (\d+)/.exec($window.navigator.userAgent.toLowerCase()) || [])[1], 10);
            var isRetina = function() {
                var mediaQuery = '(-webkit-min-device-pixel-ratio: 1.5), (min--moz-device-pixel-ratio: 1.5), ' + '(-o-min-device-pixel-ratio: 3/2), (min-resolution: 1.5dppx)';
                if ($window.devicePixelRatio > 1)
                    return true;
                return $window.matchMedia && $window.matchMedia(mediaQuery).matches;
            }();

            function getHighResolutionURL(url) {
                var parts = url.split('.');
                if (parts.length < 2)
                    return url;
                parts[parts.length - 2] += infix;
                return parts.join('.');
            }
            return function(scope, element, attrs) {
                function setImgSrc(img_url) {
                    attrs.$set('src', img_url);
                    if (msie)
                        element.prop('src', img_url);
                }

                function set2xVariant(img_url) {
                    var img_url_2x = $window.sessionStorage.getItem(img_url);
                    if (!img_url_2x) {
                        img_url_2x = getHighResolutionURL(img_url);
                        $http.head(img_url_2x).success(function(data, status) {
                            setImgSrc(img_url_2x);
                            $window.sessionStorage.setItem(img_url, img_url_2x);
                        }).error(function(data, status, headers, config) {
                            setImgSrc(img_url);
                            $window.sessionStorage.setItem(img_url, img_url);
                        });
                    } else {
                        setImgSrc(img_url_2x);
                    }
                }
                attrs.$observe('ngSrc', function(value) {
                    if (!value)
                        return;
                    if (isRetina &&
                        typeof $window.sessionStorage === 'object' &&
                        element[0].tagName === 'IMG' &&
                        attrs.noretina === undefined &&
                        !value.match(data_url_regex)) {
                        set2xVariant(value);
                    } else {
                        setImgSrc(value);
                    }
                });
            };
        }
    ]);
}(window.angular));
<|endoftext|>


<commit_before>// Add support for Retina displays when using element attribute "ng-src".
// This module overrides the built-in directive "ng-src" with one which
// distinguishes between standard or high-resolution (Retina) displays.

(function(angular, undefined) {
'use strict';
var infix = '@2x',
  data_url_regex = /^data:([a-z]+\/[a-z]+(;[a-z\-]+\=[a-z\-]+)?)?(;base64)?,(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/i;

var ngRetina = angular.module('ngRetina', []).config(function($provide) {
  $provide.decorator('ngSrcDirective', ['$delegate', function($delegate) {
    $delegate[0].compile = function(element, attrs) {
      // intentionally empty to override the built-in directive ng-src
    };
    return $delegate;
  }]);
});

ngRetina.provider('ngRetina', function() {
  this.setInfix = function(value) {
    infix = value;
  };

  this.$get = angular.noop;
});

ngRetina.directive('ngSrc', ['$window', '$http', function($window, $http) {
  var msie = parseInt(((/msie (\d+)/.exec($window.navigator.userAgent.toLowerCase()) || [])[1]), 10);
  var isRetina = (function() {
    var mediaQuery = "(-webkit-min-device-pixel-ratio: 1.5), (min--moz-device-pixel-ratio: 1.5), " +
      "(-o-min-device-pixel-ratio: 3/2), (min-resolution: 1.5dppx)";
    if ($window.devicePixelRatio > 1)
      return true;
    return ($window.matchMedia && $window.matchMedia(mediaQuery).matches);
  })();

  function getHighResolutionURL(url) {
    var parts = url.split('.');
    if (parts.length < 2)
      return url;
    parts[parts.length - 2] += infix;
    return parts.join('.');
  }

  return function(scope, element, attrs) {
    function setImgSrc(img_url) {
      attrs.$set('src', img_url);
      if (msie) element.prop('src', img_url);
    }

    function set2xVariant(img_url) {
      var img_url_2x = $window.sessionStorage.getItem(img_url);
      if (!img_url_2x) {
        img_url_2x = getHighResolutionURL(img_url);
        $http.head(img_url_2x).
        success(function(data, status) {
          setImgSrc(img_url_2x);
          $window.sessionStorage.setItem(img_url, img_url_2x);
        }).
        error(function(data, status, headers, config) {
          setImgSrc(img_url);
          $window.sessionStorage.setItem(img_url, img_url);
        });
      } else {
        setImgSrc(img_url_2x);
      }
    }

    attrs.$observe('ngSrc', function(value) {
      if (!value)
        return;
      if (isRetina && typeof $window.sessionStorage === 'object' && element[0].tagName === 'IMG' && !value.match(data_url_regex)) {
        set2xVariant(value);
      } else {
        setImgSrc(value);
      }
    });
  };
}]);

})(window.angular);
<commit_msg>removed useless case-insensitive matching<commit_after>// Add support for Retina displays when using element attribute "ng-src".
// This module overrides the built-in directive "ng-src" with one which
// distinguishes between standard or high-resolution (Retina) displays.

(function(angular, undefined) {
'use strict';
var infix = '@2x',
  data_url_regex = /^data:([a-z]+\/[a-z]+(;[a-z\-]+\=[a-z\-]+)?)?(;base64)?,(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;

var ngRetina = angular.module('ngRetina', []).config(function($provide) {
  $provide.decorator('ngSrcDirective', ['$delegate', function($delegate) {
    $delegate[0].compile = function(element, attrs) {
      // intentionally empty to override the built-in directive ng-src
    };
    return $delegate;
  }]);
});

ngRetina.provider('ngRetina', function() {
  this.setInfix = function(value) {
    infix = value;
  };

  this.$get = angular.noop;
});

ngRetina.directive('ngSrc', ['$window', '$http', function($window, $http) {
  var msie = parseInt(((/msie (\d+)/.exec($window.navigator.userAgent.toLowerCase()) || [])[1]), 10);
  var isRetina = (function() {
    var mediaQuery = "(-webkit-min-device-pixel-ratio: 1.5), (min--moz-device-pixel-ratio: 1.5), " +
      "(-o-min-device-pixel-ratio: 3/2), (min-resolution: 1.5dppx)";
    if ($window.devicePixelRatio > 1)
      return true;
    return ($window.matchMedia && $window.matchMedia(mediaQuery).matches);
  })();

  function getHighResolutionURL(url) {
    var parts = url.split('.');
    if (parts.length < 2)
      return url;
    parts[parts.length - 2] += infix;
    return parts.join('.');
  }

  return function(scope, element, attrs) {
    function setImgSrc(img_url) {
      attrs.$set('src', img_url);
      if (msie) element.prop('src', img_url);
    }

    function set2xVariant(img_url) {
      var img_url_2x = $window.sessionStorage.getItem(img_url);
      if (!img_url_2x) {
        img_url_2x = getHighResolutionURL(img_url);
        $http.head(img_url_2x).
        success(function(data, status) {
          setImgSrc(img_url_2x);
          $window.sessionStorage.setItem(img_url, img_url_2x);
        }).
        error(function(data, status, headers, config) {
          setImgSrc(img_url);
          $window.sessionStorage.setItem(img_url, img_url);
        });
      } else {
        setImgSrc(img_url_2x);
      }
    }

    attrs.$observe('ngSrc', function(value) {
      if (!value)
        return;
      if (isRetina && typeof $window.sessionStorage === 'object' && element[0].tagName === 'IMG' && !value.match(data_url_regex)) {
        set2xVariant(value);
      } else {
        setImgSrc(value);
      }
    });
  };
}]);

})(window.angular);
<|endoftext|>


<commit_before>const FriendlyError = require('./friendly');

/**
 * Has a descriptive message for a command not having proper format
 * @extends {FriendlyError}
 */
class CommandFormatError extends FriendlyError {
	/**
	 * @param {CommandMessage} msg - The command message the error is for
	 */
	constructor(msg) {
		super(
			`Invalid command usage. The \`${msg.command.name}\` command's accepted format is: ${msg.usage(
				msg.command.format,
				msg.guild ? undefined : null,
				msg.guild ? undefined : null
			)}. Use ${msg.usage(
				`help ${msg.command.name}`,
				msg.guild ? undefined : null,
				msg.guild ? undefined : null
			)} for more information.`
		);
		this.name = 'CommandFormatError';
	}
}

module.exports = CommandFormatError;
<commit_msg>Fix #103 (#106)<commit_after>const FriendlyError = require('./friendly');

/**
 * Has a descriptive message for a command not having proper format
 * @extends {FriendlyError}
 */
class CommandFormatError extends FriendlyError {
	/**
	 * @param {CommandMessage} msg - The command message the error is for
	 */
	constructor(msg) {
		super(
			`Invalid command usage. The \`${msg.command.name}\` command's accepted format is: ${msg.usage(
				msg.command.format,
				msg.guild ? undefined : null,
				msg.guild ? undefined : null
			)}. Use ${msg.anyUsage(
				`help ${msg.command.name}`,
				msg.guild ? undefined : null,
				msg.guild ? undefined : null
			)} for more information.`
		);
		this.name = 'CommandFormatError';
	}
}

module.exports = CommandFormatError;
<|endoftext|>


<commit_before>var _ = require('underscore'),
    select = require('cheerio-select'),
    utils = require('../utils'),
    isTag = utils.isTag;

var find = exports.find = function(selector) {
  // TODO: Remove the call to _.uniq when the underlying bug in CSSselect has
  // been resolved:
  // https://github.com/fb55/CSSselect/issues/12
  return this.make(_.uniq(select(selector, [].slice.call(this.children()))));
};

// Get the parent of each element in the current set of matched elements,
// optionally filtered by a selector.
var parent = exports.parent = function(selector) {
  var set = [];
  var $set;

  this.each(function(idx, elem) {
    var parentElem = elem.parent;
    if (set.indexOf(parentElem) < 0 && parentElem.type !== 'root') {
      set.push(parentElem);
    }
  });

  $set = this.make(set);

  if (arguments.length) {
    $set = $set.filter(selector);
  }

  return $set;
};

var parents = exports.parents = function(selector) {
  if (this[0] && this[0].parent) {
    return traverseParents(this, this[0].parent, selector, Infinity);
  }
  return this;
};

// For each element in the set, get the first element that matches the selector
// by testing the element itself and traversing up through its ancestors in the
// DOM tree.
var closest = exports.closest = function(selector) {
  var set = [];

  if (!selector) {
    return this.make(set);
  }

  this.each(function(idx, elem) {
    var closestElem = traverseParents(this, elem, selector, 1)[0];

    // Do not add duplicate elements to the set
    if (closestElem && set.indexOf(closestElem) < 0) {
      set.push(closestElem);
    }
  }.bind(this));

  return this.make(set);
};

var next = exports.next = function() {
  if (!this[0]) { return this; }
  var elem = this[0];
  while ((elem = elem.next)) if (isTag(elem)) return this.make(elem);
  return this.make([]);
};

var nextAll = exports.nextAll = function(selector) {
  if (!this[0]) { return this; }
  var elems = [], elem = this[0];
  while ((elem = elem.next)) if (isTag(elem)) elems.push(elem);
  return this.make(selector ? select(selector, elems) : elems);
};

var prev = exports.prev = function() {
  if (!this[0]) { return this; }
  var elem = this[0];
  while ((elem = elem.prev)) if (isTag(elem)) return this.make(elem);
  return this.make([]);
};

var prevAll = exports.prevAll = function(selector) {
  if (!this[0]) { return this; }
  var elems = [], elem = this[0];
  while ((elem = elem.prev)) if (isTag(elem)) elems.push(elem);
  return this.make(selector ? select(selector, elems) : elems);
};

var siblings = exports.siblings = function(selector) {
  var elems = _.filter(
    this.parent() ? this.parent().children() : this.siblingsAndMe(),
    function(elem) { return isTag(elem) && !this.is(elem); },
    this
  );
  if (selector !== undefined) {
    elems = this.make(select(selector, elems));
  }
  return this.make(elems);
};

var children = exports.children = function(selector) {

  var elems = _.reduce(this, function(memo, elem) {
    return memo.concat(_.filter(elem.children, isTag));
  }, []);

  if (selector === undefined) return this.make(elems);
  else if (_.isNumber(selector)) return this.make(elems[selector]);

  return this.make(elems).filter(selector);
};

var contents = exports.contents = function() {
  return this.make(_.reduce(this, function(all, elem) {
    all.push.apply(all, elem.children);
    return all;
  }, []));
};

var each = exports.each = function(fn) {
  var i = 0, len = this.length;
  while (i < len && fn.call(this.make(this[i]), i, this[i]) !== false) ++i;
  return this;
};

var map = exports.map = function(fn) {
  return this.make(_.reduce(this, function(memo, el, i) {
    var val = fn.call(el, i, el);
    return val == null ? memo : memo.concat(val);
  }, []));
};

var filter = exports.filter = function(match) {
  var make = _.bind(this.make, this);
  var filterFn;

  if (_.isString(match)) {
    filterFn = function(el) {
      return select(match, el)[0] === el;
    };
  } else if (_.isFunction(match)) {
    filterFn = function(el, i) {
      return match.call(make(el), i, el);
    };
  } else if (match.cheerio) {
    filterFn = match.is.bind(match);
  } else {
    filterFn = function(el) {
      return match === el;
    };
  }

  return make(_.filter(this, filterFn));
};

var first = exports.first = function() {
  return this[0] ? this.make(this[0]) : this;
};

var last = exports.last = function() {
  return this[0] ? this.make(this[this.length - 1]) : this;
};

// Reduce the set of matched elements to the one at the specified index.
var eq = exports.eq = function(i) {
  i = +i;
  if (i < 0) i = this.length + i;
  return this[i] ? this.make(this[i]) : this.make([]);
};

var slice = exports.slice = function() {
  return this.make([].slice.apply(this, arguments));
};

function traverseParents(self, elem, selector, limit) {
  var elems = [];
  while (elems.length < limit && elem.type !== 'root') {
    if (!selector || self.make(elem).filter(selector).length) {
      elems.push(elem);
    }
    elem = elem.parent;
  }
  return self.make(elems);
}

// End the most recent filtering operation in the current chain and return the
// set of matched elements to its previous state.
var end = exports.end = function() {
  return this.prevObject || this.make([]);
};
<commit_msg>Simplify internal function<commit_after>var _ = require('underscore'),
    select = require('cheerio-select'),
    utils = require('../utils'),
    isTag = utils.isTag;

var find = exports.find = function(selector) {
  // TODO: Remove the call to _.uniq when the underlying bug in CSSselect has
  // been resolved:
  // https://github.com/fb55/CSSselect/issues/12
  return this.make(_.uniq(select(selector, [].slice.call(this.children()))));
};

// Get the parent of each element in the current set of matched elements,
// optionally filtered by a selector.
var parent = exports.parent = function(selector) {
  var set = [];
  var $set;

  this.each(function(idx, elem) {
    var parentElem = elem.parent;
    if (set.indexOf(parentElem) < 0 && parentElem.type !== 'root') {
      set.push(parentElem);
    }
  });

  $set = this.make(set);

  if (arguments.length) {
    $set = $set.filter(selector);
  }

  return $set;
};

var parents = exports.parents = function(selector) {
  if (this[0] && this[0].parent) {
    return this.make(traverseParents(this, this[0].parent, selector, Infinity));
  }
  return this;
};

// For each element in the set, get the first element that matches the selector
// by testing the element itself and traversing up through its ancestors in the
// DOM tree.
var closest = exports.closest = function(selector) {
  var set = [];

  if (!selector) {
    return this.make(set);
  }

  this.each(function(idx, elem) {
    var closestElem = traverseParents(this, elem, selector, 1)[0];

    // Do not add duplicate elements to the set
    if (closestElem && set.indexOf(closestElem) < 0) {
      set.push(closestElem);
    }
  }.bind(this));

  return this.make(set);
};

var next = exports.next = function() {
  if (!this[0]) { return this; }
  var elem = this[0];
  while ((elem = elem.next)) if (isTag(elem)) return this.make(elem);
  return this.make([]);
};

var nextAll = exports.nextAll = function(selector) {
  if (!this[0]) { return this; }
  var elems = [], elem = this[0];
  while ((elem = elem.next)) if (isTag(elem)) elems.push(elem);
  return this.make(selector ? select(selector, elems) : elems);
};

var prev = exports.prev = function() {
  if (!this[0]) { return this; }
  var elem = this[0];
  while ((elem = elem.prev)) if (isTag(elem)) return this.make(elem);
  return this.make([]);
};

var prevAll = exports.prevAll = function(selector) {
  if (!this[0]) { return this; }
  var elems = [], elem = this[0];
  while ((elem = elem.prev)) if (isTag(elem)) elems.push(elem);
  return this.make(selector ? select(selector, elems) : elems);
};

var siblings = exports.siblings = function(selector) {
  var elems = _.filter(
    this.parent() ? this.parent().children() : this.siblingsAndMe(),
    function(elem) { return isTag(elem) && !this.is(elem); },
    this
  );
  if (selector !== undefined) {
    elems = this.make(select(selector, elems));
  }
  return this.make(elems);
};

var children = exports.children = function(selector) {

  var elems = _.reduce(this, function(memo, elem) {
    return memo.concat(_.filter(elem.children, isTag));
  }, []);

  if (selector === undefined) return this.make(elems);
  else if (_.isNumber(selector)) return this.make(elems[selector]);

  return this.make(elems).filter(selector);
};

var contents = exports.contents = function() {
  return this.make(_.reduce(this, function(all, elem) {
    all.push.apply(all, elem.children);
    return all;
  }, []));
};

var each = exports.each = function(fn) {
  var i = 0, len = this.length;
  while (i < len && fn.call(this.make(this[i]), i, this[i]) !== false) ++i;
  return this;
};

var map = exports.map = function(fn) {
  return this.make(_.reduce(this, function(memo, el, i) {
    var val = fn.call(el, i, el);
    return val == null ? memo : memo.concat(val);
  }, []));
};

var filter = exports.filter = function(match) {
  var make = _.bind(this.make, this);
  var filterFn;

  if (_.isString(match)) {
    filterFn = function(el) {
      return select(match, el)[0] === el;
    };
  } else if (_.isFunction(match)) {
    filterFn = function(el, i) {
      return match.call(make(el), i, el);
    };
  } else if (match.cheerio) {
    filterFn = match.is.bind(match);
  } else {
    filterFn = function(el) {
      return match === el;
    };
  }

  return make(_.filter(this, filterFn));
};

var first = exports.first = function() {
  return this[0] ? this.make(this[0]) : this;
};

var last = exports.last = function() {
  return this[0] ? this.make(this[this.length - 1]) : this;
};

// Reduce the set of matched elements to the one at the specified index.
var eq = exports.eq = function(i) {
  i = +i;
  if (i < 0) i = this.length + i;
  return this[i] ? this.make(this[i]) : this.make([]);
};

var slice = exports.slice = function() {
  return this.make([].slice.apply(this, arguments));
};

function traverseParents(self, elem, selector, limit) {
  var elems = [];
  while (elems.length < limit && elem.type !== 'root') {
    if (!selector || self.make(elem).filter(selector).length) {
      elems.push(elem);
    }
    elem = elem.parent;
  }
  return elems;
}

// End the most recent filtering operation in the current chain and return the
// set of matched elements to its previous state.
var end = exports.end = function() {
  return this.prevObject || this.make([]);
};
<|endoftext|>


<commit_before>angular.module('CarreEntrySystem').service('CARRE', function($http, CONFIG, Auth, RdfFormatter,$q,toastr,$state,$cacheFactory) {

  this.exports = {
    // 'count': countInstance,
    'countAll': countAllInstances,
    'query': apiQuery,
    'cacheQuery': cacheQuery,
    'invalidateCache': invalidateCache,
    'selectQuery': selectQuery,
    'instances': queryInstances,
    'search': searchInstances,
    'delete': deleteInstance
  };

  /*
    PREFIX carreManufacturer: <http://carre.kmi.open.ac.uk/manufacturers/> \n\
    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \n\
    PREFIX sensors: <http://carre.kmi.open.ac.uk/ontology/sensors.owl#> \n\
  */
  /* The prefixes for CARRE*/
  var PREFIXSTR = "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> \n\
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> \n\
PREFIX carreUsers: <https://carre.kmi.open.ac.uk/users/> \n\
PREFIX risk: <http://carre.kmi.open.ac.uk/ontology/risk.owl#> \n\
PREFIX ME: <http://carre.kmi.open.ac.uk/measurement_types/> \n\
PREFIX OB: <http://carre.kmi.open.ac.uk/observables/> \n\
PREFIX RL: <http://carre.kmi.open.ac.uk/risk_elements/> \n\
PREFIX RV: <http://carre.kmi.open.ac.uk/risk_evidences/> \n\
PREFIX RF: <http://carre.kmi.open.ac.uk/risk_factors/> \n\
PREFIX RW: <http://carre.kmi.open.ac.uk/risk_reviews/> \n\
PREFIX MD: <http://carre.kmi.open.ac.uk/medical_experts/> \n\
PREFIX CI: <http://carre.kmi.open.ac.uk/citations/> \n";

  function deleteInstance(id){
    var query = "WITH " + CONFIG.CARRE_ARCHIVE_GRAPH + " DELETE { ?id ?s ?p .  }  WHERE { ?id ?s ?p . FILTER (?id=<"+id+">) }";
    return apiQuery(query);
  /*
      OPTIONAL {    \n\
                 ?object risk:includes_risk_element ?includes_risk_element. \n\
                 ?includes_risk_element risk:has_risk_element_name ?includes_risk_element_name. \n\
                } \n\
                */
  }

  function searchInstances(type, term) {
    if(!type||!term) {
      throw "CARRE Error: Cannot search without type and term!";
    }
    var listQuery = "SELECT * FROM " + CONFIG.CARRE_DEFAULT_GRAPH + " WHERE { \n\
             ?subject a risk:" + type + "; ?predicate ?object. \n\
              OPTIONAL {    \n\
               ?object a risk:citation. \n\
               ?object risk:has_citation_pubmed_identifier ?has_citation_pubmed_identifier  \n\
              } \n\
              OPTIONAL {    \n\
               ?object a risk:observable. \n\
               ?object risk:has_observable_name ?has_observable_name  \n\
              } \n\
              OPTIONAL {    \n\
               ?object a risk:risk_element. \n\
               ?object risk:has_risk_element_name ?has_risk_element_name  \n\
              } \n\
              OPTIONAL {    \n\
               ?object a risk:measurement_type. \n\
               ?object risk:has_measurement_type_name ?has_measurement_type_name  \n\
              } \n\
              OPTIONAL {    \n\
               ?object a risk:risk_factor.  \n\
               ?object risk:has_risk_factor_association_type ?has_risk_factor_association_type. \n\
               ?object risk:has_risk_factor_source ?has_risk_factor_source. \n\
               ?object risk:has_risk_factor_target ?has_risk_factor_target. \n\
               ?has_risk_factor_source risk:has_risk_element_name ?has_source_risk_element_name.  \n\
               ?has_risk_factor_target risk:has_risk_element_name ?has_target_risk_element_name.  \n\
              } \n";

    //add filter to query if a single observable is requested
    listQuery += "FILTER (lcase(str(?object)) = \""+term+"\") }";

    return selectQuery(listQuery);

  }

  function queryInstances(type, ArrayOfIDs) {

    var listQuery = "SELECT * FROM " + CONFIG.CARRE_DEFAULT_GRAPH + " WHERE { \n\
             ?subject a risk:" + type + "; ?predicate ?object. \n\
              OPTIONAL {    \n\
               ?object a risk:citation. \n\
               ?object risk:has_citation_pubmed_identifier ?has_citation_pubmed_identifier  \n\
              } \n\
              OPTIONAL {    \n\
               ?object a risk:observable. \n\
               ?object risk:has_observable_name ?has_observable_name  \n\
               FILTER(lang(?has_observable_name)!='el'&& lang(?has_observable_name)!='lt') \n\
              } \n\
              OPTIONAL {    \n\
               ?object a risk:risk_element. \n\
               ?object risk:has_risk_element_name ?has_risk_element_name  \n\
               FILTER(lang(?has_risk_element_name)!='el'&& lang(?has_risk_element_name)!='lt') \n\
              } \n\
              OPTIONAL {    \n\
               ?object a risk:measurement_type. \n\
               ?object risk:has_measurement_type_name ?has_measurement_type_name  \n\
               FILTER(lang(?has_measurement_type_name)!='el'&& lang(?has_measurement_type_name)!='lt') \n\
              } \n\
              OPTIONAL {    \n\
               ?object a risk:risk_factor.  \n\
               ?object risk:has_risk_factor_association_type ?has_risk_factor_association_type. \n\
               ?object risk:has_risk_factor_source ?has_risk_factor_source. \n\
               ?object risk:has_risk_factor_target ?has_risk_factor_target. \n\
               ?has_risk_factor_source risk:has_risk_element_name ?has_source_risk_element_name.  \n\
               ?has_risk_factor_target risk:has_risk_element_name ?has_target_risk_element_name.  \n\
               FILTER(lang(?has_source_risk_element_name)!='el'&& lang(?has_source_risk_element_name)!='lt') \n\
               FILTER(lang(?has_target_risk_element_name)!='el'&& lang(?has_target_risk_element_name)!='lt') \n\
              } \n";

    // add language filter
    // if(CONFIG.LANG!=='en') {
    //   listQuery += "FILTER ( " + TranslatedPredicates.map(function(predicate) {
    //     return "?lang(?" + predicate + ") = '"+CONFIG.LANG+"'";
    //   }).join("&& ") + "  )\n }";
    //     return selectQuery(listQuery);
    //   }
    //   else {
    //     listQuery += "}";
    //     return selectQuery(listQuery,null,(CONFIG.USECACHE?type+'_all':null));
    //   }
    // }

    //add filter to query if a single observable is requested
    if (ArrayOfIDs) {
      listQuery += "FILTER ( " + ArrayOfIDs.map(function(id) {
        return "?subject=" + id.split('_')[0] + ":" + id;
      }).join("||") + "  )\n }";

      return selectQuery(listQuery);
    }
    else {
      listQuery += "}";

      return selectQuery(listQuery,null,(CONFIG.USECACHE?type+'_all':null));
    }

  }

  /* Dashboard count instances methods */
  function countAllInstances() {
    var query = "SELECT \n\
    (COUNT(?rf) as ?risk_factors) \n\
    (COUNT(?rf_r) as ?risk_factors_unreviewed) \n\
    (COUNT(?rl) as ?risk_elements) \n\
    (COUNT(?rl_r) as ?risk_elements_unreviewed) \n\
    (COUNT(?ob) as ?observables) \n\
    (COUNT(?ob_r) as ?observables_unreviewed) \n\
    (COUNT(?rv) as ?risk_evidences) \n\
    (COUNT(?rv_r) as ?risk_evidences_unreviewed) \n\
    (COUNT(?ci) as ?citations) \n\
    (COUNT(?me) as ?measurement_types)  \n\
    FROM " + CONFIG.CARRE_DEFAULT_GRAPH + " WHERE { \n\
    {?rf a risk:risk_factor} \n\
    UNION { ?rf_r a risk:risk_factor FILTER NOT EXISTS {?rf_r risk:has_reviewer ?anything} } \n\
    UNION {?rl a risk:risk_element} \n\
    UNION { ?rl_r a risk:risk_element FILTER NOT EXISTS {?rl_r risk:has_reviewer ?anything} } \n\
    UNION {?ob a risk:observable} UNION { ?ob_r a risk:observable FILTER NOT EXISTS {?ob_r risk:has_reviewer ?anything} } \n\
    UNION {?rv a risk:risk_evidence} UNION { ?rv_r a risk:risk_evidence FILTER NOT EXISTS {?rv_r risk:has_reviewer ?anything} } \n\
    UNION {?ci a risk:citation} \n\
    UNION {?me a risk:measurement_type}  }";
    if(CONFIG.USECACHE) return cacheQuery(query,null,'count_all');
    else return apiQuery(query);
  }

  /* Easy select query to transform triples to javascript objects */
  function selectQuery(sparqlQuery, raw,cache_id) {
    var props=[
      'subject',
      'predicate',
      'object',
      'has_observable_name',
      'has_risk_element_name',
      'has_measurement_type_name',
      'has_risk_factor_association_type',
      'has_risk_factor_source',
      'has_risk_factor_target',
      'has_source_risk_element_name',
      'has_target_risk_element_name',
      'has_citation_pubmed_identifier'
      ];
    if( cache_id ) {
      // USE CACHE
      return cacheQuery(sparqlQuery,null,cache_id).then(function(res) {
        if (raw) return res;
        // console.log(res.data);
        var results = RdfFormatter.groupByProp(res.data, props, null, 'value');
        if (results.data.length > 0) return RdfFormatter.mappings(results);
        else return [];
      });
    } else {
      return apiQuery(sparqlQuery).then(function(res) {

        console.log("=========NO CACHE===================");

        console.log("Sparql Query: ",sparqlQuery);
        console.log("Raw: ",res.data[0]);
        if (raw) return res;
        var results = RdfFormatter.groupByProp(res.data, props, null, 'value');
        console.log("groupByProp: ",results);
        if (results.data.length > 0) {
          var MappedResults = RdfFormatter.mappings(results);
          console.log("MappedResults: ",results);
          return MappedResults
        } else return [];

        console.log("===========NO CACHE===============");

      });
    }
  }

  /* CORE query method*/
  function apiQuery(sparqlQuery,noprefix) {

    var params = {};
    //add prefixes
    params.sparql = (noprefix?"":PREFIXSTR) + sparqlQuery;
    // use token
    if (Auth.cookie) params.token = Auth.cookie;
    return $http.post(CONFIG.CARRE_API_URL + 'query', params).then(function(res){
      if(res.data==='No JSON object could be decoded') {
        console.error(res);
        toastr.error('
'+res.data+'
','
Oh Error
');
        return $q.reject(res);
      }  else return res;
    }).catch(function(err){
        console.log(err);
        $state.go('500_API_ERROR');
    });

  }

  /* CACHE methods */
  function cacheQuery(sparqlQuery,noprefix,req_url_id) {

    console.info('Final query: ', (noprefix?"":PREFIXSTR) + sparqlQuery);

    var graphName=CONFIG.CARRE_DEFAULT_GRAPH.substring(CONFIG.CARRE_DEFAULT_GRAPH.lastIndexOf("/")+1,CONFIG.CARRE_DEFAULT_GRAPH.lastIndexOf(">"));
    var url=CONFIG.CARRE_CACHE_URL + 'carreapi/'
            +graphName+'_'+req_url_id+'/'
            +encodeURIComponent(CONFIG.CARRE_API_URL+'query')+'/'
            +encodeURIComponent((noprefix?"":PREFIXSTR) + sparqlQuery)
            +(Auth.cookie?'/'+Auth.cookie:'');
    console.log(url);

    return $http.get(url, {"cache":false}).then(function(res){
      if(res.data==='No JSON object could be decoded') {
        console.error(res);
        toastr.error('
'+res.data+'
','
Oh Error
');
        return $q.reject(res);
      }  else {

          //setup client caching
          // CONFIG.CACHED_QUERIES[graphName+'_'+req_url_id]=url;

        return res;
      }
    }).catch(function(err){
        console.log(err);
        $state.go('500_API_ERROR');
    });

  }

  function invalidateCache(req_url_id){
    var graphName=CONFIG.CARRE_DEFAULT_GRAPH.substring(CONFIG.CARRE_DEFAULT_GRAPH.lastIndexOf("/")+1,CONFIG.CARRE_DEFAULT_GRAPH.lastIndexOf(">"));
    var url=CONFIG.CARRE_CACHE_URL + 'refresh_cache/'+graphName+'_'+req_url_id;

    // remove cached url
    // var cached_url=CONFIG.CACHED_QUERIES[graphName+'_'+req_url_id];
    // $cacheFactory.get('$http').remove(cached_url);

    return $http.get(url).then(function(res){
      console.log(res);
    }).catch(function(err){
        console.log(err);
        $state.go('500_API_ERROR');
    });
  }

  return this.exports;
});<commit_msg>add language filter<commit_after>angular.module('CarreEntrySystem').service('CARRE', function($http, CONFIG, Auth, RdfFormatter,$q,toastr,$state,$cacheFactory) {

  this.exports = {
    // 'count': countInstance,
    'countAll': countAllInstances,
    'query': apiQuery,
    'cacheQuery': cacheQuery,
    'invalidateCache': invalidateCache,
    'selectQuery': selectQuery,
    'instances': queryInstances,
    'search': searchInstances,
    'delete': deleteInstance
  };

  /*
    PREFIX carreManufacturer: <http://carre.kmi.open.ac.uk/manufacturers/> \n\
    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \n\
    PREFIX sensors: <http://carre.kmi.open.ac.uk/ontology/sensors.owl#> \n\
  */
  /* The prefixes for CARRE*/
  var PREFIXSTR = "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> \n\
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> \n\
PREFIX carreUsers: <https://carre.kmi.open.ac.uk/users/> \n\
PREFIX risk: <http://carre.kmi.open.ac.uk/ontology/risk.owl#> \n\
PREFIX ME: <http://carre.kmi.open.ac.uk/measurement_types/> \n\
PREFIX OB: <http://carre.kmi.open.ac.uk/observables/> \n\
PREFIX RL: <http://carre.kmi.open.ac.uk/risk_elements/> \n\
PREFIX RV: <http://carre.kmi.open.ac.uk/risk_evidences/> \n\
PREFIX RF: <http://carre.kmi.open.ac.uk/risk_factors/> \n\
PREFIX RW: <http://carre.kmi.open.ac.uk/risk_reviews/> \n\
PREFIX MD: <http://carre.kmi.open.ac.uk/medical_experts/> \n\
PREFIX CI: <http://carre.kmi.open.ac.uk/citations/> \n";

  function deleteInstance(id){
    var query = "WITH " + CONFIG.CARRE_ARCHIVE_GRAPH + " DELETE { ?id ?s ?p .  }  WHERE { ?id ?s ?p . FILTER (?id=<"+id+">) }";
    return apiQuery(query);
  /*
      OPTIONAL {    \n\
                 ?object risk:includes_risk_element ?includes_risk_element. \n\
                 ?includes_risk_element risk:has_risk_element_name ?includes_risk_element_name. \n\
                } \n\
                */
  }

  function searchInstances(type, term) {
    if(!type||!term) {
      throw "CARRE Error: Cannot search without type and term!";
    }
    var listQuery = "SELECT * FROM " + CONFIG.CARRE_DEFAULT_GRAPH + " WHERE { \n\
             ?subject a risk:" + type + "; ?predicate ?object. \n\
              OPTIONAL {    \n\
               ?object a risk:citation. \n\
               ?object risk:has_citation_pubmed_identifier ?has_citation_pubmed_identifier  \n\
              } \n\
              OPTIONAL {    \n\
               ?object a risk:observable. \n\
               ?object risk:has_observable_name ?has_observable_name  \n\
              } \n\
              OPTIONAL {    \n\
               ?object a risk:risk_element. \n\
               ?object risk:has_risk_element_name ?has_risk_element_name  \n\
              } \n\
              OPTIONAL {    \n\
               ?object a risk:measurement_type. \n\
               ?object risk:has_measurement_type_name ?has_measurement_type_name  \n\
              } \n\
              OPTIONAL {    \n\
               ?object a risk:risk_factor.  \n\
               ?object risk:has_risk_factor_association_type ?has_risk_factor_association_type. \n\
               ?object risk:has_risk_factor_source ?has_risk_factor_source. \n\
               ?object risk:has_risk_factor_target ?has_risk_factor_target. \n\
               ?has_risk_factor_source risk:has_risk_element_name ?has_source_risk_element_name.  \n\
               ?has_risk_factor_target risk:has_risk_element_name ?has_target_risk_element_name.  \n\
              } \n";

    //add filter to query if a single observable is requested
    listQuery += "FILTER (lcase(str(?object)) = \""+term+"\") }";

    return selectQuery(listQuery);

  }

  function langFilter(variable_predicate){
    var lang = CONFIG.LANG;
    return "FILTER(lang("+variable_predicate+")=='"+lang+"') \n";
  }

  function queryInstances(type, ArrayOfIDs) {

    var listQuery = "SELECT * FROM " + CONFIG.CARRE_DEFAULT_GRAPH + " WHERE { \n\
             ?subject a risk:" + type + "; ?predicate ?object. \n\
              OPTIONAL {    \n\
               ?object a risk:citation. \n\
               ?object risk:has_citation_pubmed_identifier ?has_citation_pubmed_identifier  \n\
              } \n\
              OPTIONAL {    \n\
               ?object a risk:observable. \n\
               ?object risk:has_observable_name ?has_observable_name  \n\
               FILTER(lang(?has_observable_name)!='el'&& lang(?has_observable_name)!='lt') \n\
              } \n\
              OPTIONAL {    \n\
               ?object a risk:risk_element. \n\
               ?object risk:has_risk_element_name ?has_risk_element_name  \n\
               FILTER(lang(?has_risk_element_name)!='el'&& lang(?has_risk_element_name)!='lt') \n\
              } \n\
              OPTIONAL {    \n\
               ?object a risk:measurement_type. \n\
               ?object risk:has_measurement_type_name ?has_measurement_type_name  \n\
               FILTER(lang(?has_measurement_type_name)!='el'&& lang(?has_measurement_type_name)!='lt') \n\
              } \n\
              OPTIONAL {    \n\
               ?object a risk:risk_factor.  \n\
               ?object risk:has_risk_factor_association_type ?has_risk_factor_association_type. \n\
               ?object risk:has_risk_factor_source ?has_risk_factor_source. \n\
               ?object risk:has_risk_factor_target ?has_risk_factor_target. \n\
               ?has_risk_factor_source risk:has_risk_element_name ?has_source_risk_element_name.  \n\
               ?has_risk_factor_target risk:has_risk_element_name ?has_target_risk_element_name.  \n\
               FILTER(lang(?has_source_risk_element_name)!='el'&& lang(?has_source_risk_element_name)!='lt') \n\
               FILTER(lang(?has_target_risk_element_name)!='el'&& lang(?has_target_risk_element_name)!='lt') \n\
              } \n";

    // add language filter
    // if(CONFIG.LANG!=='en') {
    //   listQuery += "FILTER ( " + TranslatedPredicates.map(function(predicate) {
    //     return "?lang(?" + predicate + ") = '"+CONFIG.LANG+"'";
    //   }).join("&& ") + "  )\n }";
    //     return selectQuery(listQuery);
    //   }
    //   else {
    //     listQuery += "}";
    //     return selectQuery(listQuery,null,(CONFIG.USECACHE?type+'_all':null));
    //   }
    // }

    //add filter to query if a single observable is requested
    if (ArrayOfIDs) {
      listQuery += "FILTER ( " + ArrayOfIDs.map(function(id) {
        return "?subject=" + id.split('_')[0] + ":" + id;
      }).join("||") + "  )\n }";

      return selectQuery(listQuery);
    }
    else {
      listQuery += "}";

      return selectQuery(listQuery,null,(CONFIG.USECACHE?type+'_all':null));
    }

  }

  /* Dashboard count instances methods */
  function countAllInstances() {
    var query = "SELECT \n\
    (COUNT(?rf) as ?risk_factors) \n\
    (COUNT(?rf_r) as ?risk_factors_unreviewed) \n\
    (COUNT(?rl) as ?risk_elements) \n\
    (COUNT(?rl_r) as ?risk_elements_unreviewed) \n\
    (COUNT(?ob) as ?observables) \n\
    (COUNT(?ob_r) as ?observables_unreviewed) \n\
    (COUNT(?rv) as ?risk_evidences) \n\
    (COUNT(?rv_r) as ?risk_evidences_unreviewed) \n\
    (COUNT(?ci) as ?citations) \n\
    (COUNT(?me) as ?measurement_types)  \n\
    FROM " + CONFIG.CARRE_DEFAULT_GRAPH + " WHERE { \n\
    {?rf a risk:risk_factor} \n\
    UNION { ?rf_r a risk:risk_factor FILTER NOT EXISTS {?rf_r risk:has_reviewer ?anything} } \n\
    UNION {?rl a risk:risk_element} \n\
    UNION { ?rl_r a risk:risk_element FILTER NOT EXISTS {?rl_r risk:has_reviewer ?anything} } \n\
    UNION {?ob a risk:observable} UNION { ?ob_r a risk:observable FILTER NOT EXISTS {?ob_r risk:has_reviewer ?anything} } \n\
    UNION {?rv a risk:risk_evidence} UNION { ?rv_r a risk:risk_evidence FILTER NOT EXISTS {?rv_r risk:has_reviewer ?anything} } \n\
    UNION {?ci a risk:citation} \n\
    UNION {?me a risk:measurement_type}  }";
    if(CONFIG.USECACHE) return cacheQuery(query,null,'count_all');
    else return apiQuery(query);
  }

  /* Easy select query to transform triples to javascript objects */
  function selectQuery(sparqlQuery, raw,cache_id) {
    var props=[
      'subject',
      'predicate',
      'object',
      'has_observable_name',
      'has_risk_element_name',
      'has_measurement_type_name',
      'has_risk_factor_association_type',
      'has_risk_factor_source',
      'has_risk_factor_target',
      'has_source_risk_element_name',
      'has_target_risk_element_name',
      'has_citation_pubmed_identifier'
      ];
    if( cache_id ) {
      // USE CACHE
      return cacheQuery(sparqlQuery,null,cache_id).then(function(res) {
        if (raw) return res;
        // console.log(res.data);
        var results = RdfFormatter.groupByProp(res.data, props, null, 'value');
        if (results.data.length > 0) return RdfFormatter.mappings(results);
        else return [];
      });
    } else {
      return apiQuery(sparqlQuery).then(function(res) {

        console.log("=========NO CACHE===================");

        console.log("Sparql Query: ",sparqlQuery);
        console.log("Raw: ",res.data[0]);
        if (raw) return res;
        var results = RdfFormatter.groupByProp(res.data, props, null, 'value');
        console.log("groupByProp: ",results);
        if (results.data.length > 0) {
          var MappedResults = RdfFormatter.mappings(results);
          console.log("MappedResults: ",results);
          return MappedResults
        } else return [];

        console.log("===========NO CACHE===============");

      });
    }
  }

  /* CORE query method*/
  function apiQuery(sparqlQuery,noprefix) {

    var params = {};
    //add prefixes
    params.sparql = (noprefix?"":PREFIXSTR) + sparqlQuery;
    // use token
    if (Auth.cookie) params.token = Auth.cookie;
    return $http.post(CONFIG.CARRE_API_URL + 'query', params).then(function(res){
      if(res.data==='No JSON object could be decoded') {
        console.error(res);
        toastr.error('
'+res.data+'
','
Oh Error
');
        return $q.reject(res);
      }  else return res;
    }).catch(function(err){
        console.log(err);
        $state.go('500_API_ERROR');
    });

  }

  /* CACHE methods */
  function cacheQuery(sparqlQuery,noprefix,req_url_id) {

    console.info('Final query: ', (noprefix?"":PREFIXSTR) + sparqlQuery);

    var graphName=CONFIG.CARRE_DEFAULT_GRAPH.substring(CONFIG.CARRE_DEFAULT_GRAPH.lastIndexOf("/")+1,CONFIG.CARRE_DEFAULT_GRAPH.lastIndexOf(">"));
    var url=CONFIG.CARRE_CACHE_URL + 'carreapi/'
            +graphName+'_'+req_url_id+'/'
            +encodeURIComponent(CONFIG.CARRE_API_URL+'query')+'/'
            +encodeURIComponent((noprefix?"":PREFIXSTR) + sparqlQuery)
            +(Auth.cookie?'/'+Auth.cookie:'');
    console.log(url);

    return $http.get(url, {"cache":false}).then(function(res){
      if(res.data==='No JSON object could be decoded') {
        console.error(res);
        toastr.error('
'+res.data+'
','
Oh Error
');
        return $q.reject(res);
      }  else {

          //setup client caching
          // CONFIG.CACHED_QUERIES[graphName+'_'+req_url_id]=url;

        return res;
      }
    }).catch(function(err){
        console.log(err);
        $state.go('500_API_ERROR');
    });

  }

  function invalidateCache(req_url_id){
    var graphName=CONFIG.CARRE_DEFAULT_GRAPH.substring(CONFIG.CARRE_DEFAULT_GRAPH.lastIndexOf("/")+1,CONFIG.CARRE_DEFAULT_GRAPH.lastIndexOf(">"));
    var url=CONFIG.CARRE_CACHE_URL + 'refresh_cache/'+graphName+'_'+req_url_id;

    // remove cached url
    // var cached_url=CONFIG.CACHED_QUERIES[graphName+'_'+req_url_id];
    // $cacheFactory.get('$http').remove(cached_url);

    return $http.get(url).then(function(res){
      console.log(res);
    }).catch(function(err){
        console.log(err);
        $state.go('500_API_ERROR');
    });
  }

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


<commit_before>/*
 * Copyright 2012 Amadeus s.a.s.
 * 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.
 */
var Aria = require("../Aria");
var ariaJsunitSynEvents = require("./SynEvents");
var ariaJsunitRobot = require("./Robot");
var ariaJsunitTemplateTestCase = require("./TemplateTestCase");

/**
 * Class to be extended to create a template test case using the Robot applet. The applet allows to execute user actions
 * (click, type, move, drag, ...) as if they were done by the user instead of simulating browser events.

 * This test makes sure that the robot is loaded and initialized before starting the template test case
 */
module.exports = Aria.classDefinition({
    $classpath : "aria.jsunit.RobotTestCase",
    $extends : ariaJsunitTemplateTestCase,
    $constructor : function () {
        this.$TemplateTestCase.constructor.call(this);

        /**
         * Events utility to simulate user actions
         * @type aria.jsunit.SynEvents
         */
        this.synEvent = ariaJsunitSynEvents;
    },
    $destructor : function () {
        this.synEvent = null;
        this.$TemplateTestCase.$destructor.call(this);
    },
    $prototype : {
        /**
         * Main method that will run all the test methods attached to the object. This method checks whether the robot
         * is usable before calling the same method from the parent class.
         * @see aria.jsunit.Test
         * @override
         */
        run : function () {
            var robot = ariaJsunitRobot;
            if (!this.skipTest && !robot.isUsable()) {
                this._startTest();
                this.raiseFailure('The robot is not usable');
                this._endTest();
            } else {
                this.$TemplateTestCase.run.call(this);
            }
        },

        /**
         * Helper function, loads the template into the div. Executes the parameter callback once the template has been
         * successfully rendered. This method initializes the robot before calling the same method from the parent
         * class.
         * @param {aria.core.CfgBeans:Callback} cb Callback
         * @protected
         * @override
         */
        _loadTestTemplate : function (cb) {
            var robot = ariaJsunitRobot;
            robot.initRobot({
                fn : this.$TemplateTestCase._loadTestTemplate,
                scope : this,
                resIndex : -1,
                args : cb
            });
        },

        /**
         * Called when the iframe and its dependencies are loaded. This method initializes the robot before calling the
         * same method from the parent class.
         * @param {Object} args
         * @protected
         * @override
         */
        _iframeLoad : function (args) {
            var window = args.iframe.contentWindow;
            window.Aria.load({
                classes : ["aria.jsunit.SynEvents", "aria.jsunit.Robot"],
                oncomplete : {
                    scope : this,
                    fn : function () {
                        var robot = window.aria.jsunit.Robot;
                        robot.initRobot({
                            fn : this.$TemplateTestCase._iframeLoad,
                            scope : this,
                            resIndex : -1,
                            args : args
                        });
                    }
                }
            });
        },

        /**
         * Callback executed when the template/data/moduleCtrl is loaded. This method makes sure the synEvent shortcut
         * is using aria.jsunit.SynEvents from the correct frame, before calling the same method from the parent class.
         * @protected
         * @override
         */
        _templateLoadCB : function () {
            this.synEvent = this.testWindow.aria.jsunit.SynEvents;
            return this.$TemplateTestCase._templateLoadCB.apply(this, arguments);
        }
    }
});
<commit_msg>fix #1314 disable robot for Firefox 3.6<commit_after>/*
 * Copyright 2012 Amadeus s.a.s.
 * 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.
 */
var Aria = require("../Aria");
var ariaJsunitSynEvents = require("./SynEvents");
var ariaJsunitRobot = require("./Robot");
var ariaJsunitTemplateTestCase = require("./TemplateTestCase");

/**
 * Class to be extended to create a template test case using the Robot applet. The applet allows to execute user actions
 * (click, type, move, drag, ...) as if they were done by the user instead of simulating browser events.

 * This test makes sure that the robot is loaded and initialized before starting the template test case
 */
module.exports = Aria.classDefinition({
    $classpath : "aria.jsunit.RobotTestCase",
    $extends : ariaJsunitTemplateTestCase,
    $constructor : function () {
        this.$TemplateTestCase.constructor.call(this);

        /**
         * Events utility to simulate user actions
         * @type aria.jsunit.SynEvents
         */
        this.synEvent = ariaJsunitSynEvents;
    },
    $destructor : function () {
        this.synEvent = null;
        this.$TemplateTestCase.$destructor.call(this);
    },
    $prototype : {
        /**
         * Main method that will run all the test methods attached to the object. This method checks whether the robot
         * is usable before calling the same method from the parent class.
         * @see aria.jsunit.Test
         * @override
         */
        run : function () {
            var robot = ariaJsunitRobot;

            if (!this.skipTest && !robot.isUsable()) {
                this._startTest();
                var isOldFirefox = (aria.core.Browser.isFirefox && aria.core.Browser.majorVersion < 4);
                if (!isOldFirefox) {
                    this._currentTestName = 'RobotTestCase:run';
                    this.raiseFailure('The robot is not usable');
                }
                this._endTest();
            } else {
                this.$TemplateTestCase.run.call(this);
            }
        },

        /**
         * Helper function, loads the template into the div. Executes the parameter callback once the template has been
         * successfully rendered. This method initializes the robot before calling the same method from the parent
         * class.
         * @param {aria.core.CfgBeans:Callback} cb Callback
         * @protected
         * @override
         */
        _loadTestTemplate : function (cb) {
            var robot = ariaJsunitRobot;
            robot.initRobot({
                fn : this.$TemplateTestCase._loadTestTemplate,
                scope : this,
                resIndex : -1,
                args : cb
            });
        },

        /**
         * Called when the iframe and its dependencies are loaded. This method initializes the robot before calling the
         * same method from the parent class.
         * @param {Object} args
         * @protected
         * @override
         */
        _iframeLoad : function (args) {
            var window = args.iframe.contentWindow;
            window.Aria.load({
                classes : ["aria.jsunit.SynEvents", "aria.jsunit.Robot"],
                oncomplete : {
                    scope : this,
                    fn : function () {
                        var robot = window.aria.jsunit.Robot;
                        robot.initRobot({
                            fn : this.$TemplateTestCase._iframeLoad,
                            scope : this,
                            resIndex : -1,
                            args : args
                        });
                    }
                }
            });
        },

        /**
         * Callback executed when the template/data/moduleCtrl is loaded. This method makes sure the synEvent shortcut
         * is using aria.jsunit.SynEvents from the correct frame, before calling the same method from the parent class.
         * @protected
         * @override
         */
        _templateLoadCB : function () {
            this.synEvent = this.testWindow.aria.jsunit.SynEvents;
            return this.$TemplateTestCase._templateLoadCB.apply(this, arguments);
        }
    }
});
<|endoftext|>