<commit_before>/* global describe, it */

var expect = require('chai').expect;
var chai = require('chai');
var sinon = require('sinon');
var factory = require('../../../../com/authorize/http/middleware/evaluate');
var Request = require('../../../../lib/request');
var Response = require('../../../../lib/response');

describe('authorize/http/middleware/evaluate', function() {

  it('should be annotated', function() {
    expect(factory['@implements']).to.be.undefined;
    expect(factory['@singleton']).to.be.undefined;
  });

  var server = {
    _respond: function(txn, res, cb) {
      res.end();
    }
  };

  describe('handler', function() {

    it('should permitting access without scope', function(done) {
      var service = sinon.spy(function(req, res) {
        expect(req).to.be.an.instanceOf(Request);
        expect(req.client).to.deep.equal({
          id: 's6BhdRkqt3',
          name: 'Example Client'
        });
        expect(req.prompt).to.deep.equal([]);
        expect(req.user).to.deep.equal({
          id: '248289761001',
          displayName: 'Jane Doe'
        });
        expect(res).to.be.an.instanceOf(Response);

        res.permit();
      });

      sinon.spy(server, '_respond');
      var handler = factory(null, service, server);

      chai.express.use([ handler ])
        .request(function(req, res) {
          req.state = new Object();
          req.state.complete = sinon.spy();
          req.oauth2 = {
            client: {
              id: 's6BhdRkqt3',
              name: 'Example Client'
            },
            redirectURI: 'https://client.example.com/cb',
            req: {
              type: 'code',
              clientID: 's6BhdRkqt3'
            },
            user: {
              id: '248289761001',
              displayName: 'Jane Doe'
            }
          };
        })
        .finish(function() {
          expect(service).to.have.been.calledOnce;
          expect(this.req.state.complete).to.have.been.calledOnce;
          expect(server._respond).to.have.been.calledOnce;
          expect(server._respond).to.have.been.calledWith({
            client: {
              id: 's6BhdRkqt3',
              name: 'Example Client'
            },
            redirectURI: 'https://client.example.com/cb',
            req: {
              type: 'code',
              clientID: 's6BhdRkqt3'
            },
            user: {
              id: '248289761001',
              displayName: 'Jane Doe'
            },
            res: {
              allow: true,
              issuer: 'undefined://undefined',
              authContext: { sessionID: undefined }
            }
          }, this);
          done();
        })
        .listen();
    }); // should respond when permitting access

    it('permitting access with scope', function(done) {
      var listener = sinon.spy(function(req, res) {
        res.permit([ 'profile', 'email' ]);
      });

      var request, response;

      var prompts = new Object();

      var handler = factory(prompts, listener, server);

      chai.express.use([ handler ])
        .request(function(req, res) {
          request = req;
          req.state = {};
          req.state.complete = sinon.spy();
          req.oauth2 = {};
          req.oauth2.client = {
            id: 's6BhdRkqt3',
            name: 'Example Client'
          };
          req.oauth2.user = {
            id: '248289761001',
            displayName: 'Jane Doe'
          };
          req.oauth2.req = {};

          response = res;
        })
        .finish(function() {
          expect(listener).to.have.been.calledOnce;
          expect(listener.firstCall.args[0]).to.be.an.instanceOf(Request);
          expect(listener.firstCall.args[0].client).to.deep.equal({
            id: 's6BhdRkqt3',
            name: 'Example Client'
          });
          expect(listener.firstCall.args[0].user).to.deep.equal({
            id: '248289761001',
            displayName: 'Jane Doe'
          });
          expect(listener.firstCall.args[1]).to.be.an.instanceOf(Response);

          expect(request.state.complete).to.have.been.called;

          done();
        })
        .listen();

      /*
      it.skip('should respond', function() {
        expect(server._respond).to.have.been.calledOnce;
        expect(server._respond).to.have.been.calledWith({
          client: {
            id: 's6BhdRkqt3',
            name: 'Example Client'
          },
          user: {
            id: '248289761001',
            displayName: 'Jane Doe'
          },
          res: {
            allow: true,
            scope: [ 'profile', 'email' ]
          },
        }, response);
      });
      */
    }); // permitting access with scope

    it('prompting for login', function(done) {
      var listener = sinon.spy(function(req, res) {
        res.prompt('login');
      });

      var prompts = new Object();
      prompts.dispatch = sinon.spy(function(name, req, res, next) {
        res.redirect('/login');
      });

      var request, response;

      var handler = factory(prompts, listener, server);

      chai.express.use([ handler ])
        .request(function(req, res) {
          request = req;
          req.state = {};
          req.state.complete = sinon.spy();
          req.oauth2 = {};
          req.oauth2.client = {
            id: 's6BhdRkqt3',
            name: 'Example Client'
          };
          req.oauth2.req = {};

          response = res;
        })
        .finish(function() {
          expect(listener).to.have.been.calledOnce;
          expect(listener.firstCall.args[0]).to.be.an.instanceOf(Request);
          expect(listener.firstCall.args[0].client).to.deep.equal({
            id: 's6BhdRkqt3',
            name: 'Example Client'
          });
          expect(listener.firstCall.args[0].user).to.be.undefined;
          expect(listener.firstCall.args[1]).to.be.an.instanceOf(Response);

          expect(request.state.complete).to.not.have.been.called;

          expect(prompts.dispatch).to.have.been.calledOnceWith('login');
          //expect(prompt).to.have.been.calledOnceWith(request, response);

          expect(response.statusCode).to.equal(302);
          expect(response.getHeader('Location')).to.equal('/login');

          done();
        })
        .listen();
    }); // prompting for login

  });

});
<commit_msg>Clean up tests.<commit_after>/* global describe, it */

var expect = require('chai').expect;
var chai = require('chai');
var sinon = require('sinon');
var factory = require('../../../../com/authorize/http/middleware/evaluate');
var Request = require('../../../../lib/request');
var Response = require('../../../../lib/response');

describe('authorize/http/middleware/evaluate', function() {

  it('should be annotated', function() {
    expect(factory['@implements']).to.be.undefined;
    expect(factory['@singleton']).to.be.undefined;
  });

  var server = {
    _respond: function(txn, res, cb) {
      res.end();
    }
  };

  describe('handler', function() {

    it('should permit access without scope', function(done) {
      var service = sinon.spy(function(req, res) {
        expect(req).to.be.an.instanceOf(Request);
        expect(req.client).to.deep.equal({
          id: 's6BhdRkqt3',
          name: 'Example Client'
        });
        expect(req.prompt).to.deep.equal([]);
        expect(req.user).to.deep.equal({
          id: '248289761001',
          displayName: 'Jane Doe'
        });
        expect(res).to.be.an.instanceOf(Response);

        res.permit();
      });

      sinon.spy(server, '_respond');
      var handler = factory(null, service, server);

      chai.express.use([ handler ])
        .request(function(req, res) {
          req.state = new Object();
          req.state.complete = sinon.spy();
          req.oauth2 = {
            client: {
              id: 's6BhdRkqt3',
              name: 'Example Client'
            },
            redirectURI: 'https://client.example.com/cb',
            req: {
              type: 'code',
              clientID: 's6BhdRkqt3'
            },
            user: {
              id: '248289761001',
              displayName: 'Jane Doe'
            }
          };
        })
        .finish(function() {
          expect(service).to.have.been.calledOnce;
          expect(this.req.state.complete).to.have.been.calledOnce;
          expect(server._respond).to.have.been.calledOnce;
          expect(server._respond).to.have.been.calledWith({
            client: {
              id: 's6BhdRkqt3',
              name: 'Example Client'
            },
            redirectURI: 'https://client.example.com/cb',
            req: {
              type: 'code',
              clientID: 's6BhdRkqt3'
            },
            user: {
              id: '248289761001',
              displayName: 'Jane Doe'
            },
            res: {
              allow: true,
              issuer: 'undefined://undefined',
              authContext: { sessionID: undefined }
            }
          }, this);
          done();
        })
        .listen();
    }); // should respond when permitting access

    it('should permit access with scope', function(done) {
      var service = sinon.spy(function(req, res) {
        expect(req).to.be.an.instanceOf(Request);
        expect(req.client).to.deep.equal({
          id: 's6BhdRkqt3',
          name: 'Example Client'
        });
        expect(req.prompt).to.deep.equal([]);
        expect(req.user).to.deep.equal({
          id: '248289761001',
          displayName: 'Jane Doe'
        });
        expect(res).to.be.an.instanceOf(Response);

        res.permit([ 'profile', 'email' ]);
      });

      sinon.spy(server, '_respond');
      var handler = factory(null, service, server);

      chai.express.use([ handler ])
        .request(function(req, res) {
          req.state = new Object();
          req.state.complete = sinon.spy();
          req.oauth2 = {
            client: {
              id: 's6BhdRkqt3',
              name: 'Example Client'
            },
            redirectURI: 'https://client.example.com/cb',
            req: {
              type: 'code',
              clientID: 's6BhdRkqt3'
            },
            user: {
              id: '248289761001',
              displayName: 'Jane Doe'
            }
          };
        })
        .finish(function() {
          expect(service).to.have.been.calledOnce;
          expect(this.req.state.complete).to.have.been.calledOnce;
          expect(server._respond).to.have.been.calledOnce;
          expect(server._respond).to.have.been.calledWith({
            client: {
              id: 's6BhdRkqt3',
              name: 'Example Client'
            },
            redirectURI: 'https://client.example.com/cb',
            req: {
              type: 'code',
              clientID: 's6BhdRkqt3'
            },
            user: {
              id: '248289761001',
              displayName: 'Jane Doe'
            },
            res: {
              allow: true,
              scope: [ 'profile', 'email' ],
              issuer: 'undefined://undefined',
              authContext: { sessionID: undefined }
            }
          }, this);
          done();
        })
        .listen();
    }); // should permit access with scope

    it('prompting for login', function(done) {
      var listener = sinon.spy(function(req, res) {
        res.prompt('login');
      });

      var prompts = new Object();
      prompts.dispatch = sinon.spy(function(name, req, res, next) {
        res.redirect('/login');
      });

      var request, response;

      var handler = factory(prompts, listener, server);

      chai.express.use([ handler ])
        .request(function(req, res) {
          request = req;
          req.state = {};
          req.state.complete = sinon.spy();
          req.oauth2 = {};
          req.oauth2.client = {
            id: 's6BhdRkqt3',
            name: 'Example Client'
          };
          req.oauth2.req = {};

          response = res;
        })
        .finish(function() {
          expect(listener).to.have.been.calledOnce;
          expect(listener.firstCall.args[0]).to.be.an.instanceOf(Request);
          expect(listener.firstCall.args[0].client).to.deep.equal({
            id: 's6BhdRkqt3',
            name: 'Example Client'
          });
          expect(listener.firstCall.args[0].user).to.be.undefined;
          expect(listener.firstCall.args[1]).to.be.an.instanceOf(Response);

          expect(request.state.complete).to.not.have.been.called;

          expect(prompts.dispatch).to.have.been.calledOnceWith('login');
          //expect(prompt).to.have.been.calledOnceWith(request, response);

          expect(response.statusCode).to.equal(302);
          expect(response.getHeader('Location')).to.equal('/login');

          done();
        })
        .listen();
    }); // prompting for login

  });

});
<|endoftext|>


<commit_before>console.log('starting function')
exports.handle = function(e, ctx, cb) {
  console.log('processing event: %j', e)
  cb(null, { hello: 'world' })
}
<commit_msg>update hello command<commit_after>console.log("starting function");

exports.handle = function(e, ctx, cb) {
    console.log("processing event: %j", e);
    cb(null, [{
        "to": e.target,
        "body": [
            {"body": "hello "},
            {"mention": e.sender},
            {"body": "!"},
        ]
    }]);
};
<|endoftext|>


<commit_before>'use strict';
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import createReactClass from 'create-react-class';
import moment from 'moment';
import { queryKeyValue, external_url_map } from '../globals';
import { getAffiliationName } from '../../libs/get_affiliation_name';

var _ = require('underscore');

import PopOverComponent from '../../libs/bootstrap/popover';

// Display in-progress or provisional interpretations associated with variant
var CurationRecordCurator = module.exports.CurationRecordCurator = createReactClass({
    propTypes: {
        calculatedPathogenicity: PropTypes.string,
        data: PropTypes.object, // ClinVar data payload
        interpretationUuid: PropTypes.string,
        interpretation: PropTypes.object,
        session: PropTypes.object,
        affiliation: PropTypes.object,
        classificationSnapshots: PropTypes.array
    },

    getInitialState() {
        return {
            variant: this.props.data,
            calculatedPathogenicity: this.props.calculatedPathogenicity,
            interpretationUuid: this.props.interpretationUuid,
            interpretation: this.props.interpretation ? this.props.interpretation : null, // parent interpretation object
            classificationSnapshots: this.props.classificationSnapshots,
        };
    },

    componentWillReceiveProps(nextProps) {
        // this block is for handling props and states when props (external data) is updated after the initial load/rendering
        // when props are updated, update the parent interpreatation object, if applicable
        if (typeof nextProps.interpretation !== undefined && !_.isEqual(nextProps.interpretation, this.props.interpretation)) {
            this.setState({interpretation: nextProps.interpretation, interpretationUuid: nextProps.interpretationUuid});
        }
        if (typeof nextProps.calculatedPathogenicity !== undefined && nextProps.calculatedPathogenicity !== this.props.calculatedPathogenicity) {
            this.setState({calculatedPathogenicity: nextProps.calculatedPathogenicity});
        }
        if (nextProps.classificationSnapshots) {
            this.setState({classificationSnapshots: nextProps.classificationSnapshots});
        }
    },

    // Sort interpretation array, and move current user's as the first element
    getInterpretations(data, session, affiliation) {
        let myInterpretation = null, affiliatedInterpretation = null;
        let otherInterpretations = [];
        if (data && data.associatedInterpretations && data.associatedInterpretations.length) {
            for (let interpretation of data.associatedInterpretations) {
                if (interpretation.affiliation && affiliation && interpretation.affiliation === affiliation.affiliation_id) {
                    affiliatedInterpretation = interpretation;
                } else if (!interpretation.affiliation && !affiliation && interpretation.submitted_by.uuid === session.user_properties.uuid) {
                    myInterpretation = interpretation;
                } else {
                    otherInterpretations.push(interpretation);
                }
            }
        }
        return {
            affiliatedInterpretation: affiliatedInterpretation,
            myInterpretation: myInterpretation,
            otherInterpretations: otherInterpretations
        };
    },

    goToInterpretationPage(e) {
        e.preventDefault(); e.stopPropagation();

        let interpretationData = this.getInterpretations(this.props.data, this.props.session, this.props.affiliation);
        let uuid = interpretationData.affiliatedInterpretation ? interpretationData.affiliatedInterpretation.uuid : interpretationData.myInterpretation.uuid;
        let selectedTab = queryKeyValue('tab', window.location.href);
        let selectedSubtab = queryKeyValue('subtab', window.location.href);
        let url = '/variant-central/?edit=true&variant=' + this.props.data.uuid + '&interpretation=' + uuid + (selectedTab ? '&tab=' + selectedTab : '') + (selectedSubtab ? '&subtab=' + selectedSubtab : '');
        window.location.href = url;
    },

    /**
     * Method to display classification tag/label in the interpretation header
     * @param {string} status - The status of a given classification in an interpretation
     */
    renderClassificationStatusTag(status) {
        let snapshots = this.state.classificationSnapshots;
        let filteredSnapshots = [];
        // Determine whether the classification had been previously approved
        if (snapshots && snapshots.length) {
            filteredSnapshots = snapshots.filter(snapshot => {
                return snapshot.approvalStatus === 'Approved' && snapshot.resourceType === 'classification';
            });
        }
        if (status === 'In progress') {
            return IN PROGRESS;
        } else if (status === 'Provisional') {
            if (filteredSnapshots.length) {
                return (
                    APPROVEDNEW PROVISIONAL
                );
            } else {
                return PROVISIONAL;
            }
        } else if (status === 'Approved') {
            return APPROVED;
        }
    },

    /**
     * Method to render the header of a given classification in the interpretation header
     * @param {object} classification - A given classification in an interpretation
     */
    renderClassificationHeader(classification) {
        return (

                Status:

                    {classification && classification[0].classificationStatus ?
                        this.renderClassificationStatusTag(classification[0].classificationStatus)
                        :
                        this.renderClassificationStatusTag('In progress')
                    }

        );
    },

    render() {
        let variant = this.props.data;
        let session = this.props.session;
        let recordHeader = this.props.recordHeader;
        let interpretationUuid = this.state.interpretationUuid;
        let affiliation = this.props.affiliation;

        let sortedInterpretations = variant && variant.associatedInterpretations && variant.associatedInterpretations.length ? this.getInterpretations(variant, session, affiliation) : null;
        let myInterpretation = this.state.interpretation ? this.state.interpretation
            : (sortedInterpretations && sortedInterpretations.affiliatedInterpretation ? sortedInterpretations.affiliatedInterpretation
                : (sortedInterpretations && sortedInterpretations.myInterpretation ? sortedInterpretations.myInterpretation : null));
        let otherInterpretations = sortedInterpretations && sortedInterpretations.otherInterpretations.length ? sortedInterpretations.otherInterpretations : null;
        let calculatedPathogenicity = this.state.calculatedPathogenicity ? this.state.calculatedPathogenicity
            : (myInterpretation && myInterpretation.provisional_variant && myInterpretation.provisional_variant.length ? myInterpretation.provisional_variant[0].autoClassification : 'None');
        let modifiedPathogenicity = myInterpretation && myInterpretation.provisional_variant && myInterpretation.provisional_variant.length && myInterpretation.provisional_variant[0].alteredClassification ?
            myInterpretation.provisional_variant[0].alteredClassification : 'None';

        return (

                    {interpretationUuid ?

My Interpretation

                            {myInterpretation ?

Disease:
                                        {myInterpretation && myInterpretation.disease ?

                                                {myInterpretation.disease.term}

                                                {!myInterpretation.disease.freetext ?

                                                        (
                                                        {myInterpretation.disease.diseaseId.replace('_', ':')}
                                                        {myInterpretation.disease.description && myInterpretation.disease.description.length ?
                                                            ,
                                                                <PopOverComponent popOverWrapperClass="interpretation-disease-description"
                                                                    actuatorTitle="View definition" popOverRef={ref => (this.popoverDesc = ref)}>
                                                                    {myInterpretation.disease.description}
                                                                </PopOverComponent>

                                                            : null}
                                                        )

                                                    :

                                                        (
                                                        {myInterpretation.disease.phenotypes && myInterpretation.disease.phenotypes.length ?
                                                            <PopOverComponent popOverWrapperClass="gdm-disease-phenotypes"
                                                                actuatorTitle="View HPO term(s)" popOverRef={ref => (this.popoverPhenotypes = ref)}>
                                                                {myInterpretation.disease.phenotypes.join(', ')}
                                                            </PopOverComponent>
                                                            : null}
                                                        {myInterpretation.disease.description && myInterpretation.disease.description.length ?
                                                            {myInterpretation.disease.phenotypes && myInterpretation.disease.phenotypes.length ? ,  : null}
                                                                <PopOverComponent popOverWrapperClass="interpretation-disease-description"
                                                                    actuatorTitle="View definition" popOverRef={ref => (this.popoverDesc = ref)}>
                                                                    {myInterpretation.disease.description}
                                                                </PopOverComponent>

                                                            : null}
                                                        )

                                                }

                                            :
                                            Not associated
                                        }

Calculated Pathogenicity: {calculatedPathogenicity}

Modified Pathogenicity: {modifiedPathogenicity}

                                    {this.renderClassificationHeader(myInterpretation.provisional_variant)}

Last Edited: {moment(myInterpretation.last_modified).format("YYYY MMM DD, h:mm a")}

                                : null}

                        :

All Existing Interpretations

                            {myInterpretation ?

                                                {myInterpretation.disease ? {myInterpretation.disease.term} : No disease}
                                                {myInterpretation.modeInheritance ?
                                                    -
                                                        {myInterpretation.modeInheritance.indexOf('(HP:') === -1 ?
                                                            {myInterpretation.modeInheritance}
                                                            :
                                                            {myInterpretation.modeInheritance.substr(0, myInterpretation.modeInheritance.indexOf('(HP:')-1)}
                                                        }
                                                        ,

                                                    :
                                                    ,
                                                }
                                                {myInterpretation.affiliation ? getAffiliationName(myInterpretation.affiliation) : myInterpretation.submitted_by.title},

                                                    {myInterpretation.provisional_variant && myInterpretation.provisional_variant[0].alteredClassification ?
                                                        ': ' + myInterpretation.provisional_variant[0].alteredClassification : null},

                                                    last edited: {moment(myInterpretation.last_modified).format("YYYY MMM DD, h:mm a")}

                                                {this.renderClassificationHeader(myInterpretation.provisional_variant)}

                                : null}
                            {otherInterpretations && otherInterpretations.length ?

                                    {otherInterpretations.map(function(interpretation, i) {
                                        return (

                                                    {interpretation.disease ? {interpretation.disease.term} : No disease}
                                                    {interpretation.modeInheritance ?
                                                        -
                                                            {interpretation.modeInheritance.indexOf('(HP:') === -1 ?
                                                                {interpretation.modeInheritance}
                                                                :
                                                                {interpretation.modeInheritance.substr(0, interpretation.modeInheritance.indexOf('(HP:')-1)}
                                                            }
                                                        ,
                                                        :
                                                        ', '
                                                    }

                                                        {interpretation.affiliation ?
                                                            {getAffiliationName(interpretation.affiliation)}
                                                            :
                                                            {interpretation.submitted_by.title }
                                                        }

                                                    ,

                                                        {interpretation.provisional_variant && interpretation.provisional_variant[0].alteredClassification ?
                                                            ': ' + interpretation.provisional_variant[0].alteredClassification : null},

                                                    last edited: {moment(interpretation.last_modified).format("YYYY MMM DD, h:mm a")}
                                                    {this.renderClassificationHeader(interpretation.provisional_variant)}

                                        );
                                    })}

                                : null}

                    }

        );
    }
});
<commit_msg>:bug: Fixed bug in which the interpretation classification status is not renderd correctly in the header<commit_after>'use strict';
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import createReactClass from 'create-react-class';
import moment from 'moment';
import { queryKeyValue, external_url_map } from '../globals';
import { getAffiliationName } from '../../libs/get_affiliation_name';

var _ = require('underscore');

import PopOverComponent from '../../libs/bootstrap/popover';

// Display in-progress or provisional interpretations associated with variant
var CurationRecordCurator = module.exports.CurationRecordCurator = createReactClass({
    propTypes: {
        calculatedPathogenicity: PropTypes.string,
        data: PropTypes.object, // ClinVar data payload
        interpretationUuid: PropTypes.string,
        interpretation: PropTypes.object,
        session: PropTypes.object,
        affiliation: PropTypes.object,
        classificationSnapshots: PropTypes.array
    },

    getInitialState() {
        return {
            variant: this.props.data,
            calculatedPathogenicity: this.props.calculatedPathogenicity,
            interpretationUuid: this.props.interpretationUuid,
            interpretation: this.props.interpretation ? this.props.interpretation : null, // parent interpretation object
            classificationSnapshots: this.props.classificationSnapshots
        };
    },

    componentWillReceiveProps(nextProps) {
        // this block is for handling props and states when props (external data) is updated after the initial load/rendering
        // when props are updated, update the parent interpreatation object, if applicable
        if (typeof nextProps.interpretation !== undefined && !_.isEqual(nextProps.interpretation, this.props.interpretation)) {
            this.setState({interpretation: nextProps.interpretation, interpretationUuid: nextProps.interpretationUuid});
        }
        if (typeof nextProps.calculatedPathogenicity !== undefined && nextProps.calculatedPathogenicity !== this.props.calculatedPathogenicity) {
            this.setState({calculatedPathogenicity: nextProps.calculatedPathogenicity});
        }
        if (nextProps.classificationSnapshots) {
            this.setState({classificationSnapshots: nextProps.classificationSnapshots});
        }
    },

    // Sort interpretation array, and move current user's as the first element
    getInterpretations(data, session, affiliation) {
        let myInterpretation = null, affiliatedInterpretation = null;
        let otherInterpretations = [];
        if (data && data.associatedInterpretations && data.associatedInterpretations.length) {
            for (let interpretation of data.associatedInterpretations) {
                if (interpretation.affiliation && affiliation && interpretation.affiliation === affiliation.affiliation_id) {
                    affiliatedInterpretation = interpretation;
                } else if (!interpretation.affiliation && !affiliation && interpretation.submitted_by.uuid === session.user_properties.uuid) {
                    myInterpretation = interpretation;
                } else {
                    otherInterpretations.push(interpretation);
                }
            }
        }
        return {
            affiliatedInterpretation: affiliatedInterpretation,
            myInterpretation: myInterpretation,
            otherInterpretations: otherInterpretations
        };
    },

    goToInterpretationPage(e) {
        e.preventDefault(); e.stopPropagation();

        let interpretationData = this.getInterpretations(this.props.data, this.props.session, this.props.affiliation);
        let uuid = interpretationData.affiliatedInterpretation ? interpretationData.affiliatedInterpretation.uuid : interpretationData.myInterpretation.uuid;
        let selectedTab = queryKeyValue('tab', window.location.href);
        let selectedSubtab = queryKeyValue('subtab', window.location.href);
        let url = '/variant-central/?edit=true&variant=' + this.props.data.uuid + '&interpretation=' + uuid + (selectedTab ? '&tab=' + selectedTab : '') + (selectedSubtab ? '&subtab=' + selectedSubtab : '');
        window.location.href = url;
    },

    /**
     * Method to display classification tag/label in the interpretation header
     * @param {string} status - The status of a given classification in an interpretation
     */
    renderClassificationStatusTag(status) {
        let snapshots = this.state.classificationSnapshots;
        let filteredSnapshots = [];
        // Determine whether the classification had been previously approved
        if (snapshots && snapshots.length) {
            filteredSnapshots = snapshots.filter(snapshot => {
                return snapshot.approvalStatus === 'Approved' && snapshot.resourceType === 'interpretation';
            });
        }
        if (status === 'In progress') {
            return IN PROGRESS;
        } else if (status === 'Provisional') {
            if (filteredSnapshots.length) {
                return (
                    APPROVEDNEW PROVISIONAL
                );
            } else {
                return PROVISIONAL;
            }
        } else if (status === 'Approved') {
            return APPROVED;
        }
    },

    /**
     * Method to render the header of a given classification in the interpretation header
     * @param {object} classification - A given classification in an interpretation
     */
    renderClassificationHeader(classification) {
        return (

                Status:

                    {classification && classification[0].classificationStatus ?
                        this.renderClassificationStatusTag(classification[0].classificationStatus)
                        :
                        this.renderClassificationStatusTag('In progress')
                    }

        );
    },

    render() {
        let variant = this.props.data;
        let session = this.props.session;
        let recordHeader = this.props.recordHeader;
        let interpretationUuid = this.state.interpretationUuid;
        let affiliation = this.props.affiliation;

        let sortedInterpretations = variant && variant.associatedInterpretations && variant.associatedInterpretations.length ? this.getInterpretations(variant, session, affiliation) : null;
        let myInterpretation = this.state.interpretation ? this.state.interpretation
            : (sortedInterpretations && sortedInterpretations.affiliatedInterpretation ? sortedInterpretations.affiliatedInterpretation
                : (sortedInterpretations && sortedInterpretations.myInterpretation ? sortedInterpretations.myInterpretation : null));
        let otherInterpretations = sortedInterpretations && sortedInterpretations.otherInterpretations.length ? sortedInterpretations.otherInterpretations : null;
        let calculatedPathogenicity = this.state.calculatedPathogenicity ? this.state.calculatedPathogenicity
            : (myInterpretation && myInterpretation.provisional_variant && myInterpretation.provisional_variant.length ? myInterpretation.provisional_variant[0].autoClassification : 'None');
        let modifiedPathogenicity = myInterpretation && myInterpretation.provisional_variant && myInterpretation.provisional_variant.length && myInterpretation.provisional_variant[0].alteredClassification ?
            myInterpretation.provisional_variant[0].alteredClassification : 'None';

        return (

                    {interpretationUuid ?

My Interpretation

                            {myInterpretation ?

Disease:
                                        {myInterpretation && myInterpretation.disease ?

                                                {myInterpretation.disease.term}

                                                {!myInterpretation.disease.freetext ?

                                                        (
                                                        {myInterpretation.disease.diseaseId.replace('_', ':')}
                                                        {myInterpretation.disease.description && myInterpretation.disease.description.length ?
                                                            ,
                                                                <PopOverComponent popOverWrapperClass="interpretation-disease-description"
                                                                    actuatorTitle="View definition" popOverRef={ref => (this.popoverDesc = ref)}>
                                                                    {myInterpretation.disease.description}
                                                                </PopOverComponent>

                                                            : null}
                                                        )

                                                    :

                                                        (
                                                        {myInterpretation.disease.phenotypes && myInterpretation.disease.phenotypes.length ?
                                                            <PopOverComponent popOverWrapperClass="gdm-disease-phenotypes"
                                                                actuatorTitle="View HPO term(s)" popOverRef={ref => (this.popoverPhenotypes = ref)}>
                                                                {myInterpretation.disease.phenotypes.join(', ')}
                                                            </PopOverComponent>
                                                            : null}
                                                        {myInterpretation.disease.description && myInterpretation.disease.description.length ?
                                                            {myInterpretation.disease.phenotypes && myInterpretation.disease.phenotypes.length ? ,  : null}
                                                                <PopOverComponent popOverWrapperClass="interpretation-disease-description"
                                                                    actuatorTitle="View definition" popOverRef={ref => (this.popoverDesc = ref)}>
                                                                    {myInterpretation.disease.description}
                                                                </PopOverComponent>

                                                            : null}
                                                        )

                                                }

                                            :
                                            Not associated
                                        }

Calculated Pathogenicity: {calculatedPathogenicity}

Modified Pathogenicity: {modifiedPathogenicity}

                                    {this.renderClassificationHeader(myInterpretation.provisional_variant)}

Last Edited: {moment(myInterpretation.last_modified).format("YYYY MMM DD, h:mm a")}

                                : null}

                        :

All Existing Interpretations

                            {myInterpretation ?

                                                {myInterpretation.disease ? {myInterpretation.disease.term} : No disease}
                                                {myInterpretation.modeInheritance ?
                                                    -
                                                        {myInterpretation.modeInheritance.indexOf('(HP:') === -1 ?
                                                            {myInterpretation.modeInheritance}
                                                            :
                                                            {myInterpretation.modeInheritance.substr(0, myInterpretation.modeInheritance.indexOf('(HP:')-1)}
                                                        }
                                                        ,

                                                    :
                                                    ,
                                                }
                                                {myInterpretation.affiliation ? getAffiliationName(myInterpretation.affiliation) : myInterpretation.submitted_by.title},

                                                    {myInterpretation.provisional_variant && myInterpretation.provisional_variant[0].alteredClassification ?
                                                        ': ' + myInterpretation.provisional_variant[0].alteredClassification : null},

                                                    last edited: {moment(myInterpretation.last_modified).format("YYYY MMM DD, h:mm a")}

                                                {this.renderClassificationHeader(myInterpretation.provisional_variant)}

                                : null}
                            {otherInterpretations && otherInterpretations.length ?

                                    {otherInterpretations.map(function(interpretation, i) {
                                        return (

                                                    {interpretation.disease ? {interpretation.disease.term} : No disease}
                                                    {interpretation.modeInheritance ?
                                                        -
                                                            {interpretation.modeInheritance.indexOf('(HP:') === -1 ?
                                                                {interpretation.modeInheritance}
                                                                :
                                                                {interpretation.modeInheritance.substr(0, interpretation.modeInheritance.indexOf('(HP:')-1)}
                                                            }
                                                        ,
                                                        :
                                                        ', '
                                                    }

                                                        {interpretation.affiliation ?
                                                            {getAffiliationName(interpretation.affiliation)}
                                                            :
                                                            {interpretation.submitted_by.title }
                                                        }

                                                    ,

                                                        {interpretation.provisional_variant && interpretation.provisional_variant[0].alteredClassification ?
                                                            ': ' + interpretation.provisional_variant[0].alteredClassification : null},

                                                    last edited: {moment(interpretation.last_modified).format("YYYY MMM DD, h:mm a")}
                                                    {this.renderClassificationHeader(interpretation.provisional_variant)}

                                        );
                                    })}

                                : null}

                    }

        );
    }
});
<|endoftext|>


<commit_before>var path = require('path');
var glob = require('glob');
var webpack = require('webpack');
var autoprefixer = require('autoprefixer');

var env = process.env.NODE_ENV || 'development';

// Generate entries for all scripts
var scripts = glob.sync('js/*.js');
if (!scripts.length) {
	throw new Error('No scripts found in "js" folder.');
}
if (scripts.indexOf('js/main.js') === -1) {
	throw new Error('Main script not found: "js/main.js".');
}
var entries = {
	main: entries,
};
scripts.forEach(function(script) {
	entries[path.basename(script, '.js')] = './' + script;
});

module.exports = {
	context: process.cwd(),

	entry: entries,

	output: {
		path: path.resolve(process.cwd(), 'public/build'),
		publicPath: '/build/',
		filename: '[name].js',
	},

	resolve: {
		extensions: ['', '.js'],
	},

	resolveLoader: {
		modulesDirectories: [
			path.resolve(__dirname, '../node_modules'),
		],
	},

	plugins: [
		new webpack.DefinePlugin({
			'DEBUG': JSON.stringify(env === 'production' ? 'true' : 'false'),
			'process.env': {
				NODE_ENV: JSON.stringify(env),
			},
		}),
	],

	module: {
		noParse: /\.min\.js/,

		loaders: [
			{
				test: /\.js$/,
				include: [
					path.resolve(process.cwd(), 'js'),
				],
				loader: 'babel-loader',
			},
			{
				test: /\.styl$/,
				loaders: [
					'style',
					'css',
					'postcss',
					'stylus',
				],
			},
		],
	},

	stylus: {
		define: {
			DEBUG: env === 'development',
			embedurl: require('stylus').url(),
		},
		import: [
			path.resolve(process.cwd(), 'styles/config.styl'),
		],
	},

	postcss: function() {
		return [
			autoprefixer({
				browsers: ['last 2 versions', 'not ie < 11', 'not ie_mob < 11'],
			}),
		];
	},
};
<commit_msg>Fix loaders resolving.<commit_after>var path = require('path');
var glob = require('glob');
var webpack = require('webpack');
var autoprefixer = require('autoprefixer');

var env = process.env.NODE_ENV || 'development';

// Generate entries for all scripts
var scripts = glob.sync('js/*.js');
if (!scripts.length) {
	throw new Error('No scripts found in "js" folder.');
}
if (scripts.indexOf('js/main.js') === -1) {
	throw new Error('Main script not found: "js/main.js".');
}
var entries = {
	main: entries,
};
scripts.forEach(function(script) {
	entries[path.basename(script, '.js')] = './' + script;
});

module.exports = {
	context: process.cwd(),

	entry: entries,

	output: {
		path: path.resolve(process.cwd(), 'public/build'),
		publicPath: '/build/',
		filename: '[name].js',
	},

	resolve: {
		extensions: ['', '.js'],
	},

	resolveLoader: {
		modulesDirectories: [
			path.resolve(__dirname, '../node_modules'),
			'node_modules',
		],
	},

	plugins: [
		new webpack.DefinePlugin({
			'DEBUG': JSON.stringify(env === 'production' ? 'true' : 'false'),
			'process.env': {
				NODE_ENV: JSON.stringify(env),
			},
		}),
	],

	module: {
		noParse: /\.min\.js/,

		loaders: [
			{
				test: /\.js$/,
				include: [
					path.resolve(process.cwd(), 'js'),
				],
				loader: 'babel-loader',
			},
			{
				test: /\.styl$/,
				loaders: [
					'style',
					'css',
					'postcss',
					'stylus',
				],
			},
		],
	},

	stylus: {
		define: {
			DEBUG: env === 'development',
			embedurl: require('stylus').url(),
		},
		import: [
			path.resolve(process.cwd(), 'styles/config.styl'),
		],
	},

	postcss: function() {
		return [
			autoprefixer({
				browsers: ['last 2 versions', 'not ie < 11', 'not ie_mob < 11'],
			}),
		];
	},
};
<|endoftext|>


<commit_before>var $template = $(
    '
                                                                      ' +
    '
                                            ' +
    '   <colgroup>                                                                               ' +
    '       <col width="86px">                                                                   ' +
    '       <col width="100%">                                                                   ' +
    '   </colgroup>                                                                              ' +
    '
                                                                     ' +
    '                                         ' +
    '
                                                              ' +
    '
                                                         ' +
    '
                                                          ' +
    '
                                                                         ' +
    '
                                                             ' +
    '
                                                                         ' +
    '
                                                       ' +
    '                   <input class="null" type="radio" value="0">TODO
       ' +
    '                   <input class="init" type="radio" value="1">Черновик
   ' +
    '                   <input class="cont" type="radio" value="2">На контроле
' +
    '                   <input class="best" type="radio" value="3">Итоговый
   ' +
    '
                                                                         ' +
    '             <button class="quote">quote</button>                                           ' +
    '
                                                                             ' +
    '
                                                                                ' +
    '   	                                                                            ' +
    '                                                                                ' +
    '
                                                                   ' +
    '
                                                             ' +
    '
                                                                            ' +
    '
                                                             ' +
    '              <textarea class="trans" tabindex="1"></textarea>                              ' +
    '
                                                                            ' +
    '
                                                                                ' +
    '   	                                                                            ' +
    '
                                                                                ' +
    '
                                                                                ' +
    '
                                                                                '
);

function getData() {
    return JSON.parse(localStorage.getItem('f_data') || '[]');
}

function getDataJSON() {
    return localStorage.getItem('f_data') || '[]';
}

function setData(val) {
    localStorage.setItem('f_data', JSON.stringify(val, null, 4));
}

function getName() {
    return localStorage.getItem('f_name') || '';
}

function setName(val) {
    localStorage.setItem('f_name', val);
}

function getSaveMode() {
    return localStorage.getItem('save_mode') || 'silent';
}

function setSaveMode(val) {
    localStorage.setItem('save_mode', val);
}

var globalColorScheme = ['white', 'black', '#fc3', '#06c'];

function parseFileData() {
    var $linesBox = $('.lines-box');
    var f_data = getData();

    $linesBox.empty();

    for (var i = 0, n = f_data.length; i < n; ++i) {
        var $temp = $template.clone();
        var id = f_data[i].id;
        var st = f_data[i].line.state || 0;
        var en = f_data[i].line.en.replace(/\\n/g, '
');
        var ru = f_data[i].line.ru || '';
        var name = f_data[i].name;

        function recount() {
            var cntArr = [
                Math.round($('.null:checked').length * 10000 / f_data.length) / 100 + '%',
                Math.round($('.init:checked').length * 10000 / f_data.length) / 100 + '%',
                Math.round($('.cont:checked').length * 10000 / f_data.length) / 100 + '%',
                Math.round($('.best:checked').length * 10000 / f_data.length) / 100 + '%'
            ];

            $('.more-stats').text('( ' + cntArr.join(' | ') + ' )');
        }

        function colorMe(me, noRepaintScroll) {
            me.closest('.color-line').css({
                backgroundColor: globalColorScheme[me.val()]
            });
            if (!noRepaintScroll)
                colorScroll();
        }

        var foo = function () {
            var $radio = $(this);
            var $row = $radio.closest('.line-row');
            var oldData = $row.data('linkedObj');

            oldData.line.state = $radio.val();

            $row.data('linkedObj', oldData);

            colorMe($radio);

            recount();
        };

        $temp.find('.en-line').html(en);
        $temp.find('.name').text(name || '<NONAME>');
        $temp.find('.id-code').text('ID:' + id);
        $temp.find('.line-state');
        $temp.find('label input').prop('name', id);
        $temp.find('.null').prop('checked', st == 0).change(foo);
        var $init = $temp.find('.init').prop('checked', st == 1).change(foo);
        var $text = $temp.find('.ru-line').find('textarea').val(ru).change((function () {
            this.prop('checked', true);
            foo.call(this);
            if ($('#silent-save').prop('checked')) {
                silentSave();
            }
        }).bind($init));
        $temp.find('.cont').prop('checked', st == 2).change(foo);
        $temp.find('.best').prop('checked', st == 3).change(foo);
        $temp.find('.quote').click((function () {
            this.val('«' + this.val() + '»');
            this.focus();
            this[0].setSelectionRange(this.val().length - 1, this.val().length - 1);
        }).bind($text));

        $linesBox.append($temp.data('linkedObj', f_data[i]));

        colorMe($temp.find(':checked'), true);
    }

    colorScroll();
    recount();

    $('.stats').text('Всего строк: ' + f_data.length);
}

var dummyFoo = function () {
};

function colorScroll() {
    var $cs = $('.color-scroll');
    var $rows = $('[type="radio"]:checked');

    $cs.empty();

    for (var i = 0, n = $rows.length; i < n; ++i) {
        var $div = $('
').css({
            backgroundColor: globalColorScheme[$($rows[i]).val()],
            position: 'absolute',
            left: 0,
            right: 0,
            top: ((100/n)*i) + '%',
            bottom: ((100/n)*(n-i-1)) + '%'
        });

        $div.appendTo($cs);
    }
}

function silentSave() {
    var rows = $('.line-row');
    var count = rows.length;
    var newData = [];

    function doMyThing() {
        setData(newData);
    }

    rows.each(function (index, element) {
        var line = $(element);
        var rec = line.data('linkedObj');

        rec.line.ru = line.find('textarea').val();
        newData.push(rec);

        if (!--count) doMyThing();
    });
}

$(document).ready(function () {
    parseFileData();

    $('#file-in').change(function () {
        var f_in = this.files[0];
        var reader = new FileReader();

        setName(f_in.name);

        reader.onloadend = function (e) {
            var result = e.currentTarget.result;
            setData(JSON.parse(result));
            parseFileData();
        };

        reader.readAsText(f_in);
    });

    $('#silent-save').prop('checked', getSaveMode() === 'silent').change(function() {
        setSaveMode($(this).prop('checked') ? 'silent' : 'manual');
    });

    $('#just-save').click(function () {
        var rows = $('.line-row');
        var count = rows.length;
        var newData = [];

        function doMyThing() {
            setData(newData);
            alert('saved');
        }

        rows.each(function (index, element) {
            var line = $(element);
            var rec = line.data('linkedObj');

            rec.line.ru = line.find('textarea').val();
            newData.push(rec);

            if (!--count) doMyThing();
        });
    });

    $('#save-file').click(function () {
        var rows = $('.line-row');
        var count = rows.length;
        var newData = [];

        function doMyThing() {
            setData(newData);

            var srtRes = getDataJSON();
            var aFileParts = [srtRes];
            var oMyBlob = new Blob(aFileParts, {type: 'application/json'});

            window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;

            window.requestFileSystem(
                window.TEMPORARY,
                1024 * 1024,
                function (fs) {
                    fs.root.getFile(getName() + '.bin', {create: true}, function (fileEntry) {
                        fileEntry.createWriter(function (fileWriter) {
                            fileWriter.addEventListener("writeend", function () {
                                location.href = fileEntry.toURL();
                            }, false);

                            fileWriter.write(oMyBlob);
                        }, dummyFoo);
                    }, dummyFoo);
                }, dummyFoo
            );
        }

        rows.each(function (index, element) {
            var line = $(element);
            var rec = line.data('linkedObj');

            rec.line.ru = line.find('textarea').val();
            newData.push(rec);

            if (!--count) doMyThing();
        });
    });
});
<commit_msg>improved silent save<commit_after>var $template = $(
    '
                                                                      ' +
    '
                                            ' +
    '   <colgroup>                                                                               ' +
    '       <col width="86px">                                                                   ' +
    '       <col width="100%">                                                                   ' +
    '   </colgroup>                                                                              ' +
    '
                                                                     ' +
    '                                         ' +
    '
                                                              ' +
    '
                                                         ' +
    '
                                                          ' +
    '
                                                                         ' +
    '
                                                             ' +
    '
                                                                         ' +
    '
                                                       ' +
    '                   <input class="null" type="radio" value="0">TODO
       ' +
    '                   <input class="init" type="radio" value="1">Черновик
   ' +
    '                   <input class="cont" type="radio" value="2">На контроле
' +
    '                   <input class="best" type="radio" value="3">Итоговый
   ' +
    '
                                                                         ' +
    '             <button class="quote">quote</button>                                           ' +
    '
                                                                             ' +
    '
                                                                                ' +
    '   	                                                                            ' +
    '                                                                                ' +
    '
                                                                   ' +
    '
                                                             ' +
    '
                                                                            ' +
    '
                                                             ' +
    '              <textarea class="trans" tabindex="1"></textarea>                              ' +
    '
                                                                            ' +
    '
                                                                                ' +
    '   	                                                                            ' +
    '
                                                                                ' +
    '
                                                                                ' +
    '
                                                                                '
);

function getData() {
    return JSON.parse(localStorage.getItem('f_data') || '[]');
}

function getDataJSON() {
    return localStorage.getItem('f_data') || '[]';
}

function setData(val) {
    localStorage.setItem('f_data', JSON.stringify(val, null, 4));
}

function getName() {
    return localStorage.getItem('f_name') || '';
}

function setName(val) {
    localStorage.setItem('f_name', val);
}

function getSaveMode() {
    return localStorage.getItem('save_mode') || 'manual';
}

function setSaveMode(val) {
    localStorage.setItem('save_mode', val);
}

var globalColorScheme = ['white', 'black', '#fc3', '#06c'];

function parseFileData() {
    var $linesBox = $('.lines-box');
    var f_data = getData();

    $linesBox.empty();

    for (var i = 0, n = f_data.length; i < n; ++i) {
        var $temp = $template.clone();
        var id = f_data[i].id;
        var st = f_data[i].line.state || 0;
        var en = f_data[i].line.en.replace(/\\n/g, '
');
        var ru = f_data[i].line.ru || '';
        var name = f_data[i].name;

        function recount() {
            var cntArr = [
                Math.round($('.null:checked').length * 10000 / f_data.length) / 100 + '%',
                Math.round($('.init:checked').length * 10000 / f_data.length) / 100 + '%',
                Math.round($('.cont:checked').length * 10000 / f_data.length) / 100 + '%',
                Math.round($('.best:checked').length * 10000 / f_data.length) / 100 + '%'
            ];

            $('.more-stats').text('( ' + cntArr.join(' | ') + ' )');
        }

        function colorMe(me, noRepaintScroll) {
            me.closest('.color-line').css({
                backgroundColor: globalColorScheme[me.val()]
            });
            if (!noRepaintScroll) {
                colorScroll();

                if ($('#silent-save').prop('checked')) {
                    silentSave();
                }
            }
        }

        var foo = function () {
            var $radio = $(this);
            var $row = $radio.closest('.line-row');
            var oldData = $row.data('linkedObj');

            oldData.line.state = $radio.val();

            $row.data('linkedObj', oldData);

            colorMe($radio);

            recount();
        };

        $temp.find('.en-line').html(en);
        $temp.find('.name').text(name || '<NONAME>');
        $temp.find('.id-code').text('ID:' + id);
        $temp.find('.line-state');
        $temp.find('label input').prop('name', id);
        $temp.find('.null').prop('checked', st == 0).change(foo);
        var $init = $temp.find('.init').prop('checked', st == 1).change(foo);
        var $text = $temp.find('.ru-line').find('textarea').val(ru).change((function () {
            this.prop('checked', true);
            foo.call(this);
        }).bind($init));
        $temp.find('.cont').prop('checked', st == 2).change(foo);
        $temp.find('.best').prop('checked', st == 3).change(foo);
        $temp.find('.quote').click((function () {
            this.val('«' + this.val() + '»');
            this.focus();
            this[0].setSelectionRange(this.val().length - 1, this.val().length - 1);
        }).bind($text));

        $linesBox.append($temp.data('linkedObj', f_data[i]));

        colorMe($temp.find(':checked'), true);
    }

    colorScroll();
    recount();

    $('.stats').text('Всего строк: ' + f_data.length);
}

var dummyFoo = function () {
};

function colorScroll() {
    var $cs = $('.color-scroll');
    var $rows = $('[type="radio"]:checked');

    $cs.empty();

    for (var i = 0, n = $rows.length; i < n; ++i) {
        var $div = $('
').css({
            backgroundColor: globalColorScheme[$($rows[i]).val()],
            position: 'absolute',
            left: 0,
            right: 0,
            top: ((100/n)*i) + '%',
            bottom: ((100/n)*(n-i-1)) + '%'
        });

        $div.appendTo($cs);
    }
}

function silentSave() {
    var rows = $('.line-row');
    var count = rows.length;
    var newData = [];

    function doMyThing() {
        setData(newData);
    }

    rows.each(function (index, element) {
        var line = $(element);
        var rec = line.data('linkedObj');

        rec.line.ru = line.find('textarea').val();
        newData.push(rec);

        if (!--count) doMyThing();
    });
}

$(document).ready(function () {
    parseFileData();

    $('#file-in').change(function () {
        var f_in = this.files[0];
        var reader = new FileReader();

        setName(f_in.name);

        reader.onloadend = function (e) {
            var result = e.currentTarget.result;
            setData(JSON.parse(result));
            parseFileData();
        };

        reader.readAsText(f_in);
    });

    $('#silent-save').prop('checked', getSaveMode() === 'silent').change(function() {
        setSaveMode($(this).prop('checked') ? 'silent' : 'manual');
    });

    $('#just-save').click(function () {
        var rows = $('.line-row');
        var count = rows.length;
        var newData = [];

        function doMyThing() {
            setData(newData);
            alert('saved');
        }

        rows.each(function (index, element) {
            var line = $(element);
            var rec = line.data('linkedObj');

            rec.line.ru = line.find('textarea').val();
            newData.push(rec);

            if (!--count) doMyThing();
        });
    });

    $('#save-file').click(function () {
        var rows = $('.line-row');
        var count = rows.length;
        var newData = [];

        function doMyThing() {
            setData(newData);

            var srtRes = getDataJSON();
            var aFileParts = [srtRes];
            var oMyBlob = new Blob(aFileParts, {type: 'application/json'});

            window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;

            window.requestFileSystem(
                window.TEMPORARY,
                1024 * 1024,
                function (fs) {
                    fs.root.getFile(getName() + '.bin', {create: true}, function (fileEntry) {
                        fileEntry.createWriter(function (fileWriter) {
                            fileWriter.addEventListener("writeend", function () {
                                location.href = fileEntry.toURL();
                            }, false);

                            fileWriter.write(oMyBlob);
                        }, dummyFoo);
                    }, dummyFoo);
                }, dummyFoo
            );
        }

        rows.each(function (index, element) {
            var line = $(element);
            var rec = line.data('linkedObj');

            rec.line.ru = line.find('textarea').val();
            newData.push(rec);

            if (!--count) doMyThing();
        });
    });
});
<|endoftext|>


<commit_before>Package.describe({
  summary: "Url utilities and support for compiling a url into a regular expression.",
  version: "1.0.3",
  git: "https://github.com/eventedmind/iron-url"
});

Package.on_use(function (api) {
  api.use('underscore@1.0.0');

  api.use('iron:core@1.0.3');
  api.imply('iron:core');

  api.add_files('lib/compiler.js');
  api.add_files('lib/url.js');
});

Package.on_test(function (api) {
  api.use('iron:url');
  api.use('tinytest');
  api.use('test-helpers');
  api.add_files('test/url_test.js', ['client', 'server']);
});
<commit_msg>bump version<commit_after>Package.describe({
  summary: "Url utilities and support for compiling a url into a regular expression.",
  version: "1.0.4",
  git: "https://github.com/eventedmind/iron-url"
});

Package.on_use(function (api) {
  api.use('underscore@1.0.0');

  api.use('iron:core@1.0.4');
  api.imply('iron:core');

  api.add_files('lib/compiler.js');
  api.add_files('lib/url.js');
});

Package.on_test(function (api) {
  api.use('iron:url');
  api.use('tinytest');
  api.use('test-helpers');
  api.add_files('test/url_test.js', ['client', 'server']);
});
<|endoftext|>


<commit_before>Countly = {};
Countly.serverUrl = "";
Countly.appKey = "";
Countly.ready = false;
Countly.version = "18.08.2";
var userAgent = navigator.userAgent || navigator.vendor || window.opera;
if (/android/i.test(userAgent)) {
    Countly.isAndroid = true;
    Countly.messagingMode = {"DEVELOPMENT": 2, "PRODUCTION": 0};
}
if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) {
    Countly.isiOS = true;
    Countly.messagingMode = {"DEVELOPMENT": 1, "PRODUCTION": 0, "ADHOC": 2};
}

// countly initialization
Countly.init = function(serverUrl,appKey, deviceId){
    var args = [];
    Countly.serverUrl = serverUrl;
    Countly.appKey = appKey;
    args.push(serverUrl || "");
    args.push(appKey || "");
    if(deviceId){
        args.push(deviceId || "");
    };
    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","init",args);
    if(serverUrl.lastIndexOf('/') === serverUrl.length -1){
        Ajax.ROOT_URL = serverUrl.substring(0, serverUrl.lastIndexOf("/"));
    }else{
        Ajax.ROOT_URL = serverUrl;
    }
    // For push notification, sending token using pure js method.
}

// countly sending various types of events
Countly.sendEvent = function(options){
    var args = [];
    var eventType = "event"; //event, eventWithSum, eventWithSegment, eventWithSumSegment
    var segments = {};

    if(options.eventSum)
        eventType = "eventWithSum";
    if(options.segments)
        eventType = "eventWithSegment";
    if(options.segments && options.eventSum)
        eventType = "eventWithSumSegment";

    args.push(eventType);

    if(options.eventName)
        args.push(options.eventName.toString());
    if(options.eventCount){
        args.push(options.eventCount.toString());
    }else{
        args.push("1");
    }
    if(options.eventSum){
        args.push(options.eventSum.toString());
    }

    if(options.segments){
        segments = options.segments;
    }
    for (var event in segments) {
        args.push(event);
        args.push(segments[event]);
    }
    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","event",args);
}
Countly.recordView = function(recordView){
    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","recordView",[recordView || ""]);
};

// countly enable logger
Countly.setLoggingEnabled = function(){
    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","setloggingenabled",[]);
}

// countly sending user data
Countly.setUserData = function(options){
    var args = [];
    args.push(options.name || "");
    args.push(options.username || "");
    args.push(options.email || "");
    args.push(options.organization || "");
    args.push(options.phone || "");
    args.push(options.picture || "");
    args.push(options.picturePath || "");
    args.push(options.gender || "");
    args.push(options.byear || 0);

    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","setuserdata",args);
}
Countly.getDeviceID = function(successCallback, failureCallback){
    cordova.exec(successCallback, failureCallback,"CountlyCordova","getDeviceID",[]);

}
Countly.sendPushToken = function(options, successCallback, failureCallback){
    successCallback = successCallback || Countly.onSuccess;
    failureCallback = failureCallback || Countly.onError;
    if(!Countly.appKey){
        return failureCallback('Countly sdk is not initialized.')
    }
    Countly.getDeviceID(function(deviceId){
        var data = {
            device_id: deviceId,
            app_key: Countly.appKey,
            token_session: 1,
            test_mode: options.messagingMode,
            android_token: options.token,
            ios_token: options.token
        };
        if (Countly.isAndroid) {
            delete data.ios_token;
        }
        if (Countly.isiOS) {
            delete data.android_token;
        }
        Ajax.post('/i', data, successCallback);

    }, failureCallback);

    // Old method
    // var args = [];
    // args.push(options.registrationId || "");
    // args.push(options.mode || Countly.messagingMode.PRODUCTION);
    // args.push(options.projectId || "");
    // cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","onregistrationid",args);
}
// countly start for android
Countly.start = function(){
    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","start",[]);
}

// countly stop for android
Countly.stop = function(){
    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","stop",[]);
}

// countly deviceready for testing purpose
Countly.deviceready = function(){
    Countly.ready = true;
    //testing
}

// countly dummy success and error event
Countly.onSuccess = function(result){
    // alert(result);
}
Countly.onError = function(error){
     // alert("error");
     // alert(error);
}

// 2017

Countly.setOptionalParametersForInitialization = function(options){

    var args = [];
    args.push(options.city || "");
    args.push(options.country || "");
    args.push(String(options.latitude) || "0.0");
    args.push(String(options.longitude) || "0.0");
    args.push(String(options.ipAddress) || "0.0.0.0");

    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","setOptionalParametersForInitialization",args);
}
Countly.setLocation = function(newDeviceID){
    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","setLocation",[newDeviceID.toString() || ""]);
}
Countly.changeDeviceId = function(newDeviceID, onServer){
    if(onServer === false){
        onServer = "0";
    }else{
        onServer = "1";
    }
    newDeviceID = newDeviceID.toString() || "";
    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","changeDeviceId",[newDeviceID, onServer]);
};

Countly.isCrashReportingEnabled = false;
Countly.enableCrashReporting = function(){
    Countly.isCrashReportingEnabled = true;
    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","enableCrashReporting",[]);
}
Countly.addCrashLog = function(crashLog){
    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","addCrashLog",[crashLog || ""]);
};
Countly.logException = function(exception, nonfatal, segments){
    var exceptionString = "";
    for(var i=0,il=exception.length;i<il;i++){
        exceptionString += "columnNumber: " +exception[i].columnNumber +"\n";
        exceptionString += "fileName: " +exception[i].fileName +"\n";
        exceptionString += "functionName: " +exception[i].functionName +"\n";
        exceptionString += "lineNumber: " +exception[i].lineNumber +"\n";
    }
    var args = [];
    args.push(exceptionString || "");
    args.push(nonfatal || false);
    for(var key in segments){
        args.push(key);
        args.push(segments.toString());
    }
    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","logException",args);
};

Countly.startSession = function(){
    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","startSession",[]);
}

Countly.endSession = function(){
    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","endSession",[]);
}

Countly.enableParameterTamperingProtection = function(salt){
    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","enableParameterTamperingProtection",[salt.toString() || ""]);
}
Countly.startEvent = function(eventName){
    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","startEvent",[eventName.toString() || ""]);
}
Countly.endEvent = function(options){
    if(typeof options === "string")
        options = {eventName: options};
    var args = [];
    var eventType = "event"; //event, eventWithSum, eventWithSegment, eventWithSumSegment
    var segments = {};

    if(options.eventSum)
        eventType = "eventWithSum";
    if(options.segments)
        eventType = "eventWithSegment";
    if(options.segments && options.eventSum)
        eventType = "eventWithSumSegment";

    args.push(eventType);

    if(!options.eventName)
        options.eventName = "";
    args.push(options.eventName.toString());

    if(!options.eventCount)
        options.eventCount = "1";
    args.push(options.eventCount.toString());

    if(!options.eventSum)
        options.eventSum = "0";
    args.push(options.eventSum.toString());

    if(options.segments)
        segments = options.segments;
    for (var event in segments) {
        args.push(event);
        args.push(segments[event]);
    }
    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","endEvent",args);
};

Countly.userData = {};
Countly.userData.setProperty = function(keyName, keyValue){
    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","userData_setProperty",[keyName.toString() || "", keyValue.toString() || ""]);
};
Countly.userData.increment = function(keyName){
    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","userData_increment",[keyName.toString() || ""]);
};
Countly.userData.incrementBy = function(keyName, keyIncrement){
    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","userData_incrementBy",[keyName.toString() || "", keyIncrement.toString() || ""]);
};
Countly.userData.multiply = function(keyName, multiplyValue){
    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","userData_multiply",[keyName.toString() || "", multiplyValue.toString() || ""]);
};
Countly.userData.saveMax = function(keyName, saveMax){
    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","userData_saveMax",[keyName.toString() || "", saveMax.toString() || ""]);
};
Countly.userData.saveMin = function(keyName, saveMin){
    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","userData_saveMin",[keyName.toString() || "", saveMin.toString() || ""]);
};
Countly.userData.setOnce = function(keyName, setOnce){
    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","userData_setOnce",[keyName.toString() || "", setOnce.toString() || ""]);
};

// Rating
// config
Countly.rating = {
    starRatingMessage: "How would you rate the app?",
    starRatingDismissButtonTitle: "Dismiss",
    starRatingSubmitButtonTitle: "Submit",
}
// orginal method
Countly.sendRating = function(rating){
    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","sendRating",[rating.toString()]);
}

// ui related methods
// opens the modal
Countly.askForStarRating = function(callback){
    Countly.rating.create();
    Countly.rating.set(0);
    Countly.rating.callback = callback;
    query('countly-rating-modal').classList.add('open');
}
// closes the modal
Countly.rating.closeModal = function(){
    query('countly-rating-modal').classList.remove('open');
    if(Countly.rating.callback){
        Countly.rating.callback({code: 1, msg: 'The star rating dialog was dismissed.'});
    }
};
// when user selects a star
Countly.rating.success = function(evt){
    var rating = evt.currentTarget.getAttribute('data-rating');
    Countly.rating.rating = rating;
    Countly.rating.set(rating);
    query('countly-modal-dismiss').style.display = 'none';
    query('countly-modal-submit').style.display = 'block';
}
// when user clicks the submits
Countly.rating.send = function(){
    var rating = Countly.rating.rating;
    query('countly-modal-dismiss').style.display = 'block';
    query('countly-modal-submit').style.display = 'none';
    query('countly-rating-modal').classList.remove('open');
    Countly.rating.set(0);
    Countly.sendRating(rating);
    if(Countly.rating.callback){
        Countly.rating.callback({code: 0, msg: 'The user rated the app.', rating: rating});
    }
}
function query(theQuery){
    return document.getElementsByClassName(theQuery)[0];
}
// set's the star in the body
Countly.rating.html = '

Submit
';
Countly.rating.css = '.countly-modal.open{display:block}.countly-modal{width:80%;height:auto;position:fixed;top:10%;left:10%;background-color:#fff;border-radius:20px;z-index:99;border:1px solid #e0e0e0;text-align:center;font-size:2.5rem;display:none}.countly-modal div{margin:20px}.countly-modal-header{margin-top:20px}.countly-modal-divider{position:relative;margin:auto;height:1px;border:1px solid #e0e0e0}.countly-modal-dismiss{color:#47a9f4}.countly-modal-submit{display:none;color:#47a9f4}';
Countly.rating.create = function(){
    var div = query('countly-rating-modal');
    if(div){
        div.parentNode.removeChild(div);
    }
    div = document.createElement('div');
    div.setAttribute('class', 'countly-modal countly-rating-modal');
    div.innerHTML = Countly.rating.html;
    document.body.appendChild(div);

    var style = document.createElement('style');
    style.type = 'text/css';
    style.appendChild(document.createTextNode(Countly.rating.css));
    document.head.appendChild(style);

    query('countly-modal-dismiss').addEventListener('click', Countly.rating.closeModal);
    query('countly-modal-submit').addEventListener('click', Countly.rating.send);
}
Countly.rating.set = function(rating){
    rating = Number(rating);
    var html = '';
    for(var i=1;i<6;i++){
        html += '' +(rating>=i?'&#x2605': '☆') +'';
    }
    query('countly-modal-content').innerHTML = html;
    query('countly-modal-header').innerText = Countly.rating.starRatingMessage;
    query('countly-modal-dismiss').innerText = Countly.rating.starRatingDismissButtonTitle;
    query('countly-modal-submit').innerText = Countly.rating.starRatingSubmitButtonTitle;
    var stars = document.getElementsByClassName('countly-rating-start');
    for(var i=0,il=stars.length;i<il;i++){
        stars[i].addEventListener('click', Countly.rating.success)
    }
};
// Rating

var Ajax = {};
Ajax.post = function(url, data, cb) {
    if(!data)
        data = {};
    var http = new XMLHttpRequest();
    http.open('POST', Ajax.ROOT_URL + url, true);
    if(http.setRequestHeader){
        http.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
    }
    http.onreadystatechange = function() {
        if (http.readyState === 4){
            cb(http.responseText);
        }
    };
    http.send(JSON.stringify(data));
};
window.Countly = Countly;
document.addEventListener("deviceready", Countly.deviceready, false);
<commit_msg>fix: Countly.logException issues<commit_after>Countly = {};
Countly.serverUrl = "";
Countly.appKey = "";
Countly.ready = false;
Countly.version = "18.08.2";
var userAgent = navigator.userAgent || navigator.vendor || window.opera;
if (/android/i.test(userAgent)) {
    Countly.isAndroid = true;
    Countly.messagingMode = {"DEVELOPMENT": 2, "PRODUCTION": 0};
}
if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) {
    Countly.isiOS = true;
    Countly.messagingMode = {"DEVELOPMENT": 1, "PRODUCTION": 0, "ADHOC": 2};
}

// countly initialization
Countly.init = function(serverUrl,appKey, deviceId){
    var args = [];
    Countly.serverUrl = serverUrl;
    Countly.appKey = appKey;
    args.push(serverUrl || "");
    args.push(appKey || "");
    if(deviceId){
        args.push(deviceId || "");
    };
    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","init",args);
    if(serverUrl.lastIndexOf('/') === serverUrl.length -1){
        Ajax.ROOT_URL = serverUrl.substring(0, serverUrl.lastIndexOf("/"));
    }else{
        Ajax.ROOT_URL = serverUrl;
    }
    // For push notification, sending token using pure js method.
}

// countly sending various types of events
Countly.sendEvent = function(options){
    var args = [];
    var eventType = "event"; //event, eventWithSum, eventWithSegment, eventWithSumSegment
    var segments = {};

    if(options.eventSum)
        eventType = "eventWithSum";
    if(options.segments)
        eventType = "eventWithSegment";
    if(options.segments && options.eventSum)
        eventType = "eventWithSumSegment";

    args.push(eventType);

    if(options.eventName)
        args.push(options.eventName.toString());
    if(options.eventCount){
        args.push(options.eventCount.toString());
    }else{
        args.push("1");
    }
    if(options.eventSum){
        args.push(options.eventSum.toString());
    }

    if(options.segments){
        segments = options.segments;
    }
    for (var event in segments) {
        args.push(event);
        args.push(segments[event]);
    }
    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","event",args);
}
Countly.recordView = function(recordView){
    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","recordView",[recordView || ""]);
};

// countly enable logger
Countly.setLoggingEnabled = function(){
    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","setloggingenabled",[]);
}

// countly sending user data
Countly.setUserData = function(options){
    var args = [];
    args.push(options.name || "");
    args.push(options.username || "");
    args.push(options.email || "");
    args.push(options.organization || "");
    args.push(options.phone || "");
    args.push(options.picture || "");
    args.push(options.picturePath || "");
    args.push(options.gender || "");
    args.push(options.byear || 0);

    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","setuserdata",args);
}
Countly.getDeviceID = function(successCallback, failureCallback){
    cordova.exec(successCallback, failureCallback,"CountlyCordova","getDeviceID",[]);

}
Countly.sendPushToken = function(options, successCallback, failureCallback){
    successCallback = successCallback || Countly.onSuccess;
    failureCallback = failureCallback || Countly.onError;
    if(!Countly.appKey){
        return failureCallback('Countly sdk is not initialized.')
    }
    Countly.getDeviceID(function(deviceId){
        var data = {
            device_id: deviceId,
            app_key: Countly.appKey,
            token_session: 1,
            test_mode: options.messagingMode,
            android_token: options.token,
            ios_token: options.token
        };
        if (Countly.isAndroid) {
            delete data.ios_token;
        }
        if (Countly.isiOS) {
            delete data.android_token;
        }
        Ajax.post('/i', data, successCallback);

    }, failureCallback);

    // Old method
    // var args = [];
    // args.push(options.registrationId || "");
    // args.push(options.mode || Countly.messagingMode.PRODUCTION);
    // args.push(options.projectId || "");
    // cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","onregistrationid",args);
}
// countly start for android
Countly.start = function(){
    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","start",[]);
}

// countly stop for android
Countly.stop = function(){
    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","stop",[]);
}

// countly deviceready for testing purpose
Countly.deviceready = function(){
    Countly.ready = true;
    //testing
}

// countly dummy success and error event
Countly.onSuccess = function(result){
    // alert(result);
}
Countly.onError = function(error){
     // alert("error");
     // alert(error);
}

// 2017

Countly.setOptionalParametersForInitialization = function(options){

    var args = [];
    args.push(options.city || "");
    args.push(options.country || "");
    args.push(String(options.latitude) || "0.0");
    args.push(String(options.longitude) || "0.0");
    args.push(String(options.ipAddress) || "0.0.0.0");

    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","setOptionalParametersForInitialization",args);
}
Countly.setLocation = function(newDeviceID){
    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","setLocation",[newDeviceID.toString() || ""]);
}
Countly.changeDeviceId = function(newDeviceID, onServer){
    if(onServer === false){
        onServer = "0";
    }else{
        onServer = "1";
    }
    newDeviceID = newDeviceID.toString() || "";
    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","changeDeviceId",[newDeviceID, onServer]);
};

Countly.isCrashReportingEnabled = false;
Countly.enableCrashReporting = function(){
    Countly.isCrashReportingEnabled = true;
    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","enableCrashReporting",[]);
}
Countly.addCrashLog = function(crashLog){
    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","addCrashLog",[crashLog || ""]);
};
Countly.logException = function(exception, nonfatal, segments){
    var exceptionString = "";
    if (Array.isArray(exceptionString)) {
        for(var i=0, il=exception.length; i<il; i++){
            if (typeof exception[i] === 'string') {
                exceptionString += exception[i] + "\n";
            } else {
                exceptionString += "columnNumber: " +exception[i].columnNumber + "\n";
                exceptionString += "fileName: " +exception[i].fileName + "\n";
                exceptionString += "functionName: " +exception[i].functionName + "\n";
                exceptionString += "lineNumber: " +exception[i].lineNumber + "\n";
            }
        }
    } else if (typeof exceptionString === "string") {
        exceptionString = exception;
    }

    var args = [];
    args.push(exceptionString || "");
    args.push(nonfatal || false);
    for(var key in segments){
        args.push(key);
        args.push(segments[key].toString());
    }
    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","logException",args);
};

Countly.startSession = function(){
    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","startSession",[]);
}

Countly.endSession = function(){
    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","endSession",[]);
}

Countly.enableParameterTamperingProtection = function(salt){
    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","enableParameterTamperingProtection",[salt.toString() || ""]);
}
Countly.startEvent = function(eventName){
    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","startEvent",[eventName.toString() || ""]);
}
Countly.endEvent = function(options){
    if(typeof options === "string")
        options = {eventName: options};
    var args = [];
    var eventType = "event"; //event, eventWithSum, eventWithSegment, eventWithSumSegment
    var segments = {};

    if(options.eventSum)
        eventType = "eventWithSum";
    if(options.segments)
        eventType = "eventWithSegment";
    if(options.segments && options.eventSum)
        eventType = "eventWithSumSegment";

    args.push(eventType);

    if(!options.eventName)
        options.eventName = "";
    args.push(options.eventName.toString());

    if(!options.eventCount)
        options.eventCount = "1";
    args.push(options.eventCount.toString());

    if(!options.eventSum)
        options.eventSum = "0";
    args.push(options.eventSum.toString());

    if(options.segments)
        segments = options.segments;
    for (var event in segments) {
        args.push(event);
        args.push(segments[event]);
    }
    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","endEvent",args);
};

Countly.userData = {};
Countly.userData.setProperty = function(keyName, keyValue){
    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","userData_setProperty",[keyName.toString() || "", keyValue.toString() || ""]);
};
Countly.userData.increment = function(keyName){
    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","userData_increment",[keyName.toString() || ""]);
};
Countly.userData.incrementBy = function(keyName, keyIncrement){
    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","userData_incrementBy",[keyName.toString() || "", keyIncrement.toString() || ""]);
};
Countly.userData.multiply = function(keyName, multiplyValue){
    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","userData_multiply",[keyName.toString() || "", multiplyValue.toString() || ""]);
};
Countly.userData.saveMax = function(keyName, saveMax){
    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","userData_saveMax",[keyName.toString() || "", saveMax.toString() || ""]);
};
Countly.userData.saveMin = function(keyName, saveMin){
    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","userData_saveMin",[keyName.toString() || "", saveMin.toString() || ""]);
};
Countly.userData.setOnce = function(keyName, setOnce){
    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","userData_setOnce",[keyName.toString() || "", setOnce.toString() || ""]);
};

// Rating
// config
Countly.rating = {
    starRatingMessage: "How would you rate the app?",
    starRatingDismissButtonTitle: "Dismiss",
    starRatingSubmitButtonTitle: "Submit",
}
// orginal method
Countly.sendRating = function(rating){
    cordova.exec(Countly.onSuccess,Countly.onError,"CountlyCordova","sendRating",[rating.toString()]);
}

// ui related methods
// opens the modal
Countly.askForStarRating = function(callback){
    Countly.rating.create();
    Countly.rating.set(0);
    Countly.rating.callback = callback;
    query('countly-rating-modal').classList.add('open');
}
// closes the modal
Countly.rating.closeModal = function(){
    query('countly-rating-modal').classList.remove('open');
    if(Countly.rating.callback){
        Countly.rating.callback({code: 1, msg: 'The star rating dialog was dismissed.'});
    }
};
// when user selects a star
Countly.rating.success = function(evt){
    var rating = evt.currentTarget.getAttribute('data-rating');
    Countly.rating.rating = rating;
    Countly.rating.set(rating);
    query('countly-modal-dismiss').style.display = 'none';
    query('countly-modal-submit').style.display = 'block';
}
// when user clicks the submits
Countly.rating.send = function(){
    var rating = Countly.rating.rating;
    query('countly-modal-dismiss').style.display = 'block';
    query('countly-modal-submit').style.display = 'none';
    query('countly-rating-modal').classList.remove('open');
    Countly.rating.set(0);
    Countly.sendRating(rating);
    if(Countly.rating.callback){
        Countly.rating.callback({code: 0, msg: 'The user rated the app.', rating: rating});
    }
}
function query(theQuery){
    return document.getElementsByClassName(theQuery)[0];
}
// set's the star in the body
Countly.rating.html = '

Submit
';
Countly.rating.css = '.countly-modal.open{display:block}.countly-modal{width:80%;height:auto;position:fixed;top:10%;left:10%;background-color:#fff;border-radius:20px;z-index:99;border:1px solid #e0e0e0;text-align:center;font-size:2.5rem;display:none}.countly-modal div{margin:20px}.countly-modal-header{margin-top:20px}.countly-modal-divider{position:relative;margin:auto;height:1px;border:1px solid #e0e0e0}.countly-modal-dismiss{color:#47a9f4}.countly-modal-submit{display:none;color:#47a9f4}';
Countly.rating.create = function(){
    var div = query('countly-rating-modal');
    if(div){
        div.parentNode.removeChild(div);
    }
    div = document.createElement('div');
    div.setAttribute('class', 'countly-modal countly-rating-modal');
    div.innerHTML = Countly.rating.html;
    document.body.appendChild(div);

    var style = document.createElement('style');
    style.type = 'text/css';
    style.appendChild(document.createTextNode(Countly.rating.css));
    document.head.appendChild(style);

    query('countly-modal-dismiss').addEventListener('click', Countly.rating.closeModal);
    query('countly-modal-submit').addEventListener('click', Countly.rating.send);
}
Countly.rating.set = function(rating){
    rating = Number(rating);
    var html = '';
    for(var i=1;i<6;i++){
        html += '' +(rating>=i?'&#x2605': '☆') +'';
    }
    query('countly-modal-content').innerHTML = html;
    query('countly-modal-header').innerText = Countly.rating.starRatingMessage;
    query('countly-modal-dismiss').innerText = Countly.rating.starRatingDismissButtonTitle;
    query('countly-modal-submit').innerText = Countly.rating.starRatingSubmitButtonTitle;
    var stars = document.getElementsByClassName('countly-rating-start');
    for(var i=0,il=stars.length;i<il;i++){
        stars[i].addEventListener('click', Countly.rating.success)
    }
};
// Rating

var Ajax = {};
Ajax.post = function(url, data, cb) {
    if(!data)
        data = {};
    var http = new XMLHttpRequest();
    http.open('POST', Ajax.ROOT_URL + url, true);
    if(http.setRequestHeader){
        http.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
    }
    http.onreadystatechange = function() {
        if (http.readyState === 4){
            cb(http.responseText);
        }
    };
    http.send(JSON.stringify(data));
};
window.Countly = Countly;
document.addEventListener("deviceready", Countly.deviceready, false);
<|endoftext|>