<commit_before>/* Copyright (C) 2017 Canonical Ltd. */
'use strict';

const React = require('react');

const HeaderLogo = require('./header-logo');
const SvgIcon = require('../svg-icon/svg-icon');

const jsTestUtils = require('../../utils/component-test-utils');

describe('HeaderLogo', function() {

  it('renders for gisf', () => {
    const showProfile = sinon.stub();
    const renderer = jsTestUtils.shallowRender(
      <HeaderLogo
        gisf={true}
        homePath="/"
        showProfile={showProfile} />, true);
    const output = renderer.getRenderOutput();
    const expected = (

        <SvgIcon className="svg-icon"
          height="35"
          name="juju-logo" width="90" />
      );
    expect(output).toEqualJSX(expected);
  });

  it('renders for gijoe', () => {
    const showProfile = sinon.stub();
    const renderer = jsTestUtils.shallowRender(
      <HeaderLogo
        gisf={false}
        homePath="/u/hatch"
        showProfile={showProfile} />, true);
    const output = renderer.getRenderOutput();
    const expected = (

        <SvgIcon className="svg-icon"
          height="35"
          name="juju-logo" width="90" />
      );
    expect(output).toEqualJSX(expected);
  });

  it('calls showProfile on click in gijoe', () => {
    const showProfile = sinon.stub();
    const preventDefault = sinon.stub();
    const renderer = jsTestUtils.shallowRender(
      <HeaderLogo
        gisf={false}
        homePath="/u/hatch"
        showProfile={showProfile} />, true);
    const output = renderer.getRenderOutput();
    // Call the click handler
    output.props.onClick({preventDefault});
    assert.equal(preventDefault.callCount, 1);
    assert.equal(showProfile.callCount, 1);
  });

  it('does not call showProfile on click in gisf', () => {
    const showProfile = sinon.stub();
    const preventDefault = sinon.stub();
    const renderer = jsTestUtils.shallowRender(
      <HeaderLogo
        gisf={true}
        homePath="/u/hatch"
        showProfile={showProfile} />, true);
    const output = renderer.getRenderOutput();
    // Call the click handler
    output.props.onClick({preventDefault});
    assert.equal(preventDefault.callCount, 0);
    assert.equal(showProfile.callCount, 0);
  });
});
<commit_msg>Update header logo tests to use enzyme.<commit_after>/* Copyright (C) 2017 Canonical Ltd. */
'use strict';

const React = require('react');
const enzyme = require('enzyme');

const HeaderLogo = require('./header-logo');
const SvgIcon = require('../svg-icon/svg-icon');

describe('HeaderLogo', function() {

  const renderComponent = (options = {}) => enzyme.shallow(
    <HeaderLogo
      gisf={options.gisf === undefined ? true : options.gisf}
      homePath={options.homePath || '/'}
      showProfile={options.showProfile || sinon.stub()} />
  );

  it('renders', () => {
    const wrapper = renderComponent();
    const expected = (

        <SvgIcon className="svg-icon"
          height="35"
          name="juju-logo" width="90" />
      );
    assert.compareJSX(wrapper, expected);
  });

  it('calls showProfile on click in gijoe', () => {
    const showProfile = sinon.stub();
    const preventDefault = sinon.stub();
    const wrapper = renderComponent({
      gisf: false,
      showProfile
    });
    // Call the click handler
    wrapper.props().onClick({preventDefault});
    assert.equal(preventDefault.callCount, 1);
    assert.equal(showProfile.callCount, 1);
  });

  it('does not call showProfile on click in gisf', () => {
    const showProfile = sinon.stub();
    const preventDefault = sinon.stub();
    const wrapper = renderComponent({ showProfile });
    // Call the click handler
    wrapper.props().onClick({preventDefault});
    assert.equal(preventDefault.callCount, 0);
    assert.equal(showProfile.callCount, 0);
  });
});
<|endoftext|>


<commit_before>define(["dojo/_base/declare", "dojo/_base/lang", "ppwcode/oddsAndEnds/js"],
  function(declare, lang, js) {

    var _PreconditionViolationError = declare([Error], {
      instance: null,
      method: null,
      condition: null,
      constructor: function(instance, method, condition) {
        this.instance = instance;
        this.method = method;
        this.condition = condition;
      },
      toString: function() {
        return "Precondition violation: " + this.condition +
          " (on " + this.instance.toString() + " in method " + this.method + ")";
      }
    });

    var _ContractMixin = declare(null, {
      _c_invar: [],

      _c_pre: function(condition) {
        if (! condition.apply(this)) {
          throw new _PreconditionViolationError(this, this._c_pre.caller, condition);
        }
      },

      _c_prop: function(subject, propName) {
        // summary:
        //   the property subject[propName] exists
        // description:
        //   if there is only 1 argument, subject is taken to be this
        var pName;
        var s;
        if (arguments.length < 2) {
          pName = subject;
          s = this;
        }
        else {
          pName = propName;
          s = subject;
        }
        return js.getAllKeys(s).some(function(k) {return k === pName;});
      },

      _c_prop_mandatory: function(subject, propName) {
        // summary:
        //   the property subject[propName] is mandatory (exists and not-null)
        // description:
        //   if there is only 1 argument, subject is taken to be this
        var pName;
        var s;
        if (arguments.length < 2) {
          pName = subject;
          s = this;
        }
        else {
          pName = propName;
          s = subject;
        }
        return this._c_prop(s, pName) && s[pName] !== null;
      },

      _c_prop_mandatory_string: function(subject, propName) {
        // summary:
        //   the property subject[propName] is a non-empty string
        // description:
        //   if there is only 1 argument, subject is taken to be this
        var pName;
        var s;
        if (arguments.length < 2) {
          pName = subject;
          s = this;
        }
        else {
          pName = propName;
          s = subject;
        }
        var exists = this._c_prop_mandatory(s, pName);
        if (exists) {
          var value = s[pName];
          return typeof value === "string" && value != "";
        }
        else {
          return false;
        }
      },

      _c_prop_number: function(subject, propName) {
        // summary:
        //   the property subject[propName] is defined, and if it is not-null, it is a number
        // description:
        //   if there is only 1 argument, subject is taken to be this
        var pName;
        var s;
        if (arguments.length < 2) {
          pName = subject;
          s = this;
        }
        else {
          pName = propName;
          s = subject;
        }
        var exists = this._c_prop(s, pName);
        if (exists) {
          var value = s[pName];
          return value == null || typeof value === "number";
        }
        else {
          return false;
        }
      },

      _c_prop_bool: function(subject, propName) {
        // summary:
        //   the property subject[propName] is defined, and if it is not-null, it is a bool
        // description:
        //   if there is only 1 argument, subject is taken to be this
        var pName;
        var s;
        if (arguments.length < 2) {
          pName = subject;
          s = this;
        }
        else {
          pName = propName;
          s = subject;
        }
        var exists = this._c_prop(s, pName);
        if (exists) {
          var value = s[pName];
          return value == null || typeof value === "boolean";
        }
        else {
          return false;
        }
      },

      _c_prop_string: function(subject, propName) {
        // summary:
        //   the property subject[propName] is defined, and if it is not-null, it is a string
        // description:
        //   if there is only 1 argument, subject is taken to be this
        var pName;
        var s;
        if (arguments.length < 2) {
          pName = subject;
          s = this;
        }
        else {
          pName = propName;
          s = subject;
        }
        var exists = this._c_prop(s, pName);
        if (exists) {
          var value = s[pName];
          return value == null || lang.isString(value);
        }
        else {
          return false;
        }
      },

      _c_prop_array: function(subject, propName) {
        // summary:
        //   the property subject[propName] is defined, and if it is not-null, it is an Array
        // description:
        //   if there is only 1 argument, subject is taken to be this
        var pName;
        var s;
        if (arguments.length < 2) {
          pName = subject;
          s = this;
        }
        else {
          pName = propName;
          s = subject;
        }
        var exists = this._c_prop(s, pName);
        if (exists) {
          var value = s[pName];
          return value == null || lang.isArray(value);
        }
        else {
          return false;
        }
      },

      _c_prop_function: function(subject, propName) {
        // summary:
        //   the property subject[propName] is defined, and if it is not-null, it is a Function
        // description:
        //   if there is only 1 argument, subject is taken to be this
        var pName;
        var s;
        if (arguments.length < 2) {
          pName = subject;
          s = this;
        }
        else {
          pName = propName;
          s = subject;
        }
        var exists = this._c_prop(s, pName);
        if (exists) {
          var value = s[pName];
          return value == null || lang.isFunction(value);
        }
        else {
          return false;
        }
      },

      _c_prop_instance: function(subject, propName, Constructor) {
        // summary:
        //   the property subject[propName] is defined, and if it is not-null, it is an
        //   instance of the Dojo declared type Constructor (isInstanceOf) or an
        //   EnumerationValue (isValueOf).
        // description:
        //   if there is only 1 argument, subject is taken to be this

        var pName;
        var s;
        var Constr;
        if (arguments.length < 3) {
          pName = subject;
          s = this;
          Constr = propName;
        }
        else {
          pName = propName;
          s = subject;
          Constr = Constructor;
        }

        var exists = this._c_prop(s, pName);
        if (exists) {
          var value = s[pName];
          if (!value) {
            return true;
          }
          else if (js.typeOf(Constr) === "function") {
            return value.isInstanceOf ? value.isInstanceOf(Constr) : value instanceof Constr;
          }
          else if (js.typeOf(Constr) === "object") {
            // value must be an EnumerationValue, but we cannot test that here, because that would
            // create a dependency loop
            return value.isValueOf && value.isValueOf(Constr);
          }
          else {
            throw "ERROR: Constructor must be a Constructor function, or EnumerationValue definition";
          }
        }
        else {
          return false;
        }
      },

      _c_ABSTRACT: function() {
        // summary:
        //   use this to annotate a function as abstract
        // description:
        //   This method throws an exception "ABSTRACT".
        //
        //   An abstract method should be mentioned, to have a hook for documentation.
        //   Yet, an meaningful implementation is not possible.
        //   To detect errors early, and to avoid code inspection warnings, you
        //   can call this body in the abstract method. Because the method should
        //   be overwritten for every concrete subclass, this code should never be called.
        //
        //   Often, abstract methods also have parameters. These will not be used in the
        //   body of the abstract method declaration (the hook for the documentation),
        //   which will trigger code inspection warnings. To avoid these, you should
        //   add those parameters as arguments to this call.
        throw "ABSTRACT";
      },

      _c_NOP: function() {
        // summary:
        //   use this to annotate a function as having no body whatsoever
        // description:
        //   This method does NOP.
        //
        //   Methods like this must sometimes be mentioned, as a NOP implementation
        //   of an abstract method in some subclass, or in other circumstances.
        //   Using this method instead of a comment helps in avoiding unnecessary
        //   code inspection warnings.
        //
        //   Often, such NOP methods also have parameters. These will not be used in the
        //   empty body, which will trigger code inspection warnings. To avoid these, you
        //   should add those parameters as arguments to this call.
      }

    }
  );

  return _ContractMixin;
});
<commit_msg>test for integer values<commit_after>define(["dojo/_base/declare", "dojo/_base/lang", "ppwcode/oddsAndEnds/js"],
  function(declare, lang, js) {

    var _PreconditionViolationError = declare([Error], {
      instance: null,
      method: null,
      condition: null,
      constructor: function(instance, method, condition) {
        this.instance = instance;
        this.method = method;
        this.condition = condition;
      },
      toString: function() {
        return "Precondition violation: " + this.condition +
          " (on " + this.instance.toString() + " in method " + this.method + ")";
      }
    });

    var _ContractMixin = declare(null, {
      _c_invar: [],

      _c_pre: function(condition) {
        if (! condition.apply(this)) {
          throw new _PreconditionViolationError(this, this._c_pre.caller, condition);
        }
      },

      _c_prop: function(subject, propName) {
        // summary:
        //   the property subject[propName] exists
        // description:
        //   if there is only 1 argument, subject is taken to be this
        var pName;
        var s;
        if (arguments.length < 2) {
          pName = subject;
          s = this;
        }
        else {
          pName = propName;
          s = subject;
        }
        return js.getAllKeys(s).some(function(k) {return k === pName;});
      },

      _c_prop_mandatory: function(subject, propName) {
        // summary:
        //   the property subject[propName] is mandatory (exists and not-null)
        // description:
        //   if there is only 1 argument, subject is taken to be this
        var pName;
        var s;
        if (arguments.length < 2) {
          pName = subject;
          s = this;
        }
        else {
          pName = propName;
          s = subject;
        }
        return this._c_prop(s, pName) && s[pName] !== null;
      },

      _c_prop_mandatory_string: function(subject, propName) {
        // summary:
        //   the property subject[propName] is a non-empty string
        // description:
        //   if there is only 1 argument, subject is taken to be this
        var pName;
        var s;
        if (arguments.length < 2) {
          pName = subject;
          s = this;
        }
        else {
          pName = propName;
          s = subject;
        }
        var exists = this._c_prop_mandatory(s, pName);
        if (exists) {
          var value = s[pName];
          return typeof value === "string" && value != "";
        }
        else {
          return false;
        }
      },

      _c_prop_number: function(subject, propName) {
        // summary:
        //   the property subject[propName] is defined, and if it is not-null, it is a number
        // description:
        //   if there is only 1 argument, subject is taken to be this
        var pName;
        var s;
        if (arguments.length < 2) {
          pName = subject;
          s = this;
        }
        else {
          pName = propName;
          s = subject;
        }
        var exists = this._c_prop(s, pName);
        if (exists) {
          var value = s[pName];
          return value == null || typeof value === "number";
        }
        else {
          return false;
        }
      },

      _c_prop_int: function(subject, propName) {
        // summary:
        //   the property subject[propName] is defined, and if it is not-null, it is an integer
        // description:
        //   if there is only 1 argument, subject is taken to be this
        var pName;
        var s;
        if (arguments.length < 2) {
          pName = subject;
          s = this;
        }
        else {
          pName = propName;
          s = subject;
        }
        return this._c_prop_number(s, pName) && js.isInt(s[pName]);
      },

      _c_prop_bool: function(subject, propName) {
        // summary:
        //   the property subject[propName] is defined, and if it is not-null, it is a bool
        // description:
        //   if there is only 1 argument, subject is taken to be this
        var pName;
        var s;
        if (arguments.length < 2) {
          pName = subject;
          s = this;
        }
        else {
          pName = propName;
          s = subject;
        }
        var exists = this._c_prop(s, pName);
        if (exists) {
          var value = s[pName];
          return value == null || typeof value === "boolean";
        }
        else {
          return false;
        }
      },

      _c_prop_string: function(subject, propName) {
        // summary:
        //   the property subject[propName] is defined, and if it is not-null, it is a string
        // description:
        //   if there is only 1 argument, subject is taken to be this
        var pName;
        var s;
        if (arguments.length < 2) {
          pName = subject;
          s = this;
        }
        else {
          pName = propName;
          s = subject;
        }
        var exists = this._c_prop(s, pName);
        if (exists) {
          var value = s[pName];
          return value == null || lang.isString(value);
        }
        else {
          return false;
        }
      },

      _c_prop_array: function(subject, propName) {
        // summary:
        //   the property subject[propName] is defined, and if it is not-null, it is an Array
        // description:
        //   if there is only 1 argument, subject is taken to be this
        var pName;
        var s;
        if (arguments.length < 2) {
          pName = subject;
          s = this;
        }
        else {
          pName = propName;
          s = subject;
        }
        var exists = this._c_prop(s, pName);
        if (exists) {
          var value = s[pName];
          return value == null || lang.isArray(value);
        }
        else {
          return false;
        }
      },

      _c_prop_function: function(subject, propName) {
        // summary:
        //   the property subject[propName] is defined, and if it is not-null, it is a Function
        // description:
        //   if there is only 1 argument, subject is taken to be this
        var pName;
        var s;
        if (arguments.length < 2) {
          pName = subject;
          s = this;
        }
        else {
          pName = propName;
          s = subject;
        }
        var exists = this._c_prop(s, pName);
        if (exists) {
          var value = s[pName];
          return value == null || lang.isFunction(value);
        }
        else {
          return false;
        }
      },

      _c_prop_instance: function(subject, propName, Constructor) {
        // summary:
        //   the property subject[propName] is defined, and if it is not-null, it is an
        //   instance of the Dojo declared type Constructor (isInstanceOf) or an
        //   EnumerationValue (isValueOf).
        // description:
        //   if there is only 1 argument, subject is taken to be this

        var pName;
        var s;
        var Constr;
        if (arguments.length < 3) {
          pName = subject;
          s = this;
          Constr = propName;
        }
        else {
          pName = propName;
          s = subject;
          Constr = Constructor;
        }

        var exists = this._c_prop(s, pName);
        if (exists) {
          var value = s[pName];
          if (!value) {
            return true;
          }
          else if (js.typeOf(Constr) === "function") {
            return value.isInstanceOf ? value.isInstanceOf(Constr) : value instanceof Constr;
          }
          else if (js.typeOf(Constr) === "object") {
            // value must be an EnumerationValue, but we cannot test that here, because that would
            // create a dependency loop
            return value.isValueOf && value.isValueOf(Constr);
          }
          else {
            throw "ERROR: Constructor must be a Constructor function, or EnumerationValue definition";
          }
        }
        else {
          return false;
        }
      },

      _c_ABSTRACT: function() {
        // summary:
        //   use this to annotate a function as abstract
        // description:
        //   This method throws an exception "ABSTRACT".
        //
        //   An abstract method should be mentioned, to have a hook for documentation.
        //   Yet, an meaningful implementation is not possible.
        //   To detect errors early, and to avoid code inspection warnings, you
        //   can call this body in the abstract method. Because the method should
        //   be overwritten for every concrete subclass, this code should never be called.
        //
        //   Often, abstract methods also have parameters. These will not be used in the
        //   body of the abstract method declaration (the hook for the documentation),
        //   which will trigger code inspection warnings. To avoid these, you should
        //   add those parameters as arguments to this call.
        throw "ABSTRACT";
      },

      _c_NOP: function() {
        // summary:
        //   use this to annotate a function as having no body whatsoever
        // description:
        //   This method does NOP.
        //
        //   Methods like this must sometimes be mentioned, as a NOP implementation
        //   of an abstract method in some subclass, or in other circumstances.
        //   Using this method instead of a comment helps in avoiding unnecessary
        //   code inspection warnings.
        //
        //   Often, such NOP methods also have parameters. These will not be used in the
        //   empty body, which will trigger code inspection warnings. To avoid these, you
        //   should add those parameters as arguments to this call.
      }

    }
  );

  return _ContractMixin;
});
<|endoftext|>


<commit_before>//some Users Module
    var facebook = require('./facebookComunication.js'),
         setTime = require('./setTime.js'),
        mongo = require('./mongoFunctions.js');

var time = new setTime();
function redirect(req,callback){
    //console.log('redirect');
     //var reqCookie=req.cookies.cookieName; //cookie
       // console.log('this user dialog');
        //console
        facebook.createPersonToken(req.query['code'],function(token){
            facebook.getInfoAboutToken(token,function(returnData){
                console.log('return data',returnData);
                var id=returnData['data'].user_id; //id
                //cookie.addNewSession(id,reqCookie);
                console.log('id: '+id);
                console.log('token: '+token);
                //if()
                //mongo.findById(id,)
                console.log('test id',id);
                facebook.addName(token,function(name){
                    console.log('test name',name);
                    facebook.getPicture(token,function(picture){
                        console.log('test pic',picture);
                        facebook.savePerson(id,token,name,picture,function(){

                            setImmediate(function() {
                                callback(id);
                            });
                        })
                    })
                    //in the future will get name
                });
                /*
                facebook.checkIfLongTokenExist(id,function(comunicat){
                    if(comunicat != 'ok'){
                        facebook.tokenToLongLife(token,function(x){
                            console.log('some long');
                            console.log(x);

                            mongo.modifyById(id,'person',{longToken:x},function(){})

                        });

                        mongo.findById(id,'person',function(z){
                            console.log(z);
                        })
                    }

                });
                */
                //data['user_id']=returnData['data'].user_id;
                //facebook.saveIdAndAccesToken
            });
        });
}
var pageSettings = {
    fields:{
        cancelled:'typ',
        note:'komentarz',
        periods:'lekcja',
        subjects:'przedmiot',
        teachers:'nauczyciel',
        classes:'klasa',
        classrooms:'sala',
        groupnames:'grupa',
        changes:'zmiany',
        //brak:'brak',
        substitution_types:'rodzaj'
    },
    event:{
        changeDisplayEvents :{
            'home':[['navbar_home','navbar_homeD'],'homePage'],
            'substitution':[['navbar_substitution','navbar_substitutionD'],'substitutionList'],
            'about':[['navbar_photo','navbar_photoD'],'about1'],
            'settings':[['navbar_settings','navbar_settingsD'],'settingsMenu']

        }
    },
    events:['homePage','substitutionList','settingsMenu','about1'],
    formValues:['all','no']

}

    //var reqCookie=req.cookies.cookieName;
    //var userId=cookie.findIfSessionExist(reqCookie);
function postCall(userId,body,callback){

    var res='';
    //console.log('Mode: '+req.body['mode']);
    //var body=req.body;

        if(body.mode=='getSettings'){
            //console.log(id);
            mongo.findById(userId,'person',function(err,doc){
                if (err){console.log('prolem with settings: ',userId)};
                console.log('Settings file: ',doc);
                var params = (doc['settings']);
                if(params == ''){params={setClass:'all',notification:'no'}}
                var table=[];
                table[0]=params.setClass;
                table[1]=params.notification;
                pageSettings['formValues']=table;
                res = pageSettings;
                setImmediate(function() {
                    callback(res);
                });
                //console.log('response Settings',res);
            })
        }
        else if(body.mode=='getChanges'){
                //console.log('response Changes')
            if(body['param']=='today'){
                time.todayIs();
            }
            else{
                time.tommorowIs();
            }
            console.log('requested date: ',time.displayTime());
            mongo.findById(time.displayTime(),'substitutions',function(err,obj){
                //console.log(err,obj);
                if(err){console.log('err in sending substitutions')}
                var objToSend={};
                objToSend['substitution']=obj['substitution'];
                if(obj['date'] == undefined){obj['date']='31-12-2016'}
                objToSend['date']=obj['date'];
                res = objToSend;
                setImmediate(function() {
                    callback(res);
                });
            });
        }
        else if(body.mode=='classList'){
                //console.log('response Changes')
            if(body['param']=='today'){
                time.todayIs();
            }
            else{
                time.tommorowIs();
            }
            //console.log('requested date: ',time.displayTime());
            mongo.findById(time.displayTime(),'substitutions',function(err,obj){
                //console.log(err,obj);
                if(err){console.log('err in sending substitutions')}
                res = obj['userList'];
                setImmediate(function() {
                    callback(res);
                });
            });
        }
        else if(body.mode=='message'){

            mongo.save(['messages',{id:userId,message:body.param,time:new Date()}],function(){
                res = 'thanks for your message, we will read it soon';
                setImmediate(function() {
                    callback(res);
                });
            });
        }
        else if(body.mode=='saveSettings'){
            if(userId!="0000"){
                console.log('saving chnges to: '+userId);
                var form={};
                form['setClass'] = body.setClass;
                form['notification'] = body.notification;
                 mongo.modifyById(userId,'person',{settings:form},function(){
                    res = 'ok';
                    setImmediate(function() {
                        callback(res);
                    });

                 })
            }
            else{
                res = 'ok';
                setImmediate(function() {
                        callback(res);
                });
            }
        }
        else if(body.mode=='picture'){
            if(userId != "0000"){
                 mongo.findById(userId,'person',function(err,obj){
                //console.log(err,obj);
                if(err){console.log('err in sending picture')}
                     console.log('some fond object:',obj.picture);
                res = obj['picture'];
                setImmediate(function() {
                    callback(res);
                });
            });
            }
            else{
                res = '/img/unknown.gif';
                setImmediate(function() {
                        callback(res);
                });
            }
        }
        else{
            res = 'no matches in postCall'
            setImmediate(function() {
                callback(res);
            });
        };
        //console.log('hi',res);

}
exports.postCall = postCall;
exports.redirect = redirect;<commit_msg>Changed info after sending a message<commit_after>//some Users Module
    var facebook = require('./facebookComunication.js'),
         setTime = require('./setTime.js'),
        mongo = require('./mongoFunctions.js');

var time = new setTime();
function redirect(req,callback){
    //console.log('redirect');
     //var reqCookie=req.cookies.cookieName; //cookie
       // console.log('this user dialog');
        //console
        facebook.createPersonToken(req.query['code'],function(token){
            facebook.getInfoAboutToken(token,function(returnData){
                console.log('return data',returnData);
                var id=returnData['data'].user_id; //id
                //cookie.addNewSession(id,reqCookie);
                console.log('id: '+id);
                console.log('token: '+token);
                //if()
                //mongo.findById(id,)
                console.log('test id',id);
                facebook.addName(token,function(name){
                    console.log('test name',name);
                    facebook.getPicture(token,function(picture){
                        console.log('test pic',picture);
                        facebook.savePerson(id,token,name,picture,function(){

                            setImmediate(function() {
                                callback(id);
                            });
                        })
                    })
                    //in the future will get name
                });
                /*
                facebook.checkIfLongTokenExist(id,function(comunicat){
                    if(comunicat != 'ok'){
                        facebook.tokenToLongLife(token,function(x){
                            console.log('some long');
                            console.log(x);

                            mongo.modifyById(id,'person',{longToken:x},function(){})

                        });

                        mongo.findById(id,'person',function(z){
                            console.log(z);
                        })
                    }

                });
                */
                //data['user_id']=returnData['data'].user_id;
                //facebook.saveIdAndAccesToken
            });
        });
}
var pageSettings = {
    fields:{
        cancelled:'typ',
        note:'komentarz',
        periods:'lekcja',
        subjects:'przedmiot',
        teachers:'nauczyciel',
        classes:'klasa',
        classrooms:'sala',
        groupnames:'grupa',
        changes:'zmiany',
        //brak:'brak',
        substitution_types:'rodzaj'
    },
    event:{
        changeDisplayEvents :{
            'home':[['navbar_home','navbar_homeD'],'homePage'],
            'substitution':[['navbar_substitution','navbar_substitutionD'],'substitutionList'],
            'about':[['navbar_photo','navbar_photoD'],'about1'],
            'settings':[['navbar_settings','navbar_settingsD'],'settingsMenu']

        }
    },
    events:['homePage','substitutionList','settingsMenu','about1'],
    formValues:['all','no']

}

    //var reqCookie=req.cookies.cookieName;
    //var userId=cookie.findIfSessionExist(reqCookie);
function postCall(userId,body,callback){

    var res='';
    //console.log('Mode: '+req.body['mode']);
    //var body=req.body;

        if(body.mode=='getSettings'){
            //console.log(id);
            mongo.findById(userId,'person',function(err,doc){
                if (err){console.log('prolem with settings: ',userId)};
                console.log('Settings file: ',doc);
                var params = (doc['settings']);
                if(params == ''){params={setClass:'all',notification:'no'}}
                var table=[];
                table[0]=params.setClass;
                table[1]=params.notification;
                pageSettings['formValues']=table;
                res = pageSettings;
                setImmediate(function() {
                    callback(res);
                });
                //console.log('response Settings',res);
            })
        }
        else if(body.mode=='getChanges'){
                //console.log('response Changes')
            if(body['param']=='today'){
                time.todayIs();
            }
            else{
                time.tommorowIs();
            }
            console.log('requested date: ',time.displayTime());
            mongo.findById(time.displayTime(),'substitutions',function(err,obj){
                //console.log(err,obj);
                if(err){console.log('err in sending substitutions')}
                var objToSend={};
                objToSend['substitution']=obj['substitution'];
                if(obj['date'] == undefined){obj['date']='31-12-2016'}
                objToSend['date']=obj['date'];
                res = objToSend;
                setImmediate(function() {
                    callback(res);
                });
            });
        }
        else if(body.mode=='classList'){
                //console.log('response Changes')
            if(body['param']=='today'){
                time.todayIs();
            }
            else{
                time.tommorowIs();
            }
            //console.log('requested date: ',time.displayTime());
            mongo.findById(time.displayTime(),'substitutions',function(err,obj){
                //console.log(err,obj);
                if(err){console.log('err in sending substitutions')}
                res = obj['userList'];
                setImmediate(function() {
                    callback(res);
                });
            });
        }
        else if(body.mode=='message'){

            mongo.save(['messages',{id:userId,message:body.param,time:new Date()}],function(){
                res = 'Dziękujemy za wiadomość';
                setImmediate(function() {
                    callback(res);
                });
            });
        }
        else if(body.mode=='saveSettings'){
            if(userId!="0000"){
                console.log('saving chnges to: '+userId);
                var form={};
                form['setClass'] = body.setClass;
                form['notification'] = body.notification;
                 mongo.modifyById(userId,'person',{settings:form},function(){
                    res = 'ok';
                    setImmediate(function() {
                        callback(res);
                    });

                 })
            }
            else{
                res = 'ok';
                setImmediate(function() {
                        callback(res);
                });
            }
        }
        else if(body.mode=='picture'){
            if(userId != "0000"){
                 mongo.findById(userId,'person',function(err,obj){
                //console.log(err,obj);
                if(err){console.log('err in sending picture')}
                     console.log('some fond object:',obj.picture);
                res = obj['picture'];
                setImmediate(function() {
                    callback(res);
                });
            });
            }
            else{
                res = '/img/unknown.gif';
                setImmediate(function() {
                        callback(res);
                });
            }
        }
        else{
            res = 'no matches in postCall'
            setImmediate(function() {
                callback(res);
            });
        };
        //console.log('hi',res);

}
exports.postCall = postCall;
exports.redirect = redirect;
<|endoftext|>


<commit_before>var parse = function(uptime){
	var minutes = Math.round(uptime / 60) % 60;
	var hours = Math.round(uptime / 60 / 60) % 24;
	var days = Math.round(uptime / 60 / 60 / 24);
	var seconds = Math.round(uptime) % 60;

	uptime = [];
	if (days >= 1) {
		uptime.push('' + days + ' day' + (days > 1 ? 's' : ''));
	}
	if (hours >= 1) {
		uptime.push('' + hours +' hour' + (hours > 1 ? 's' : ''));
	}
	if (minutes >= 1) {
		uptime.push('' + minutes + ' minute' + (minutes > 1 ? 's' : ''));
	}
	if (seconds >= 1) {
		uptime.push('' + seconds + ' second' + (seconds > 1 ? 's' : ''));
	}
	uptime = uptime.join(', ');
	return uptime;
}
var uptime = function(bot, channel){
	var time = (new Date().getTime() - bot.startTime) / 1000;
	IRC.message(channel, 'Bot has been online for: ' + parse(time));
}
exports.init = function(plugins, bot){
	bot.addCommand('uptime', '', 'Shows uptime of bot', USER_LEVEL_GLOBAL, true);
	plugins.listen(this, 'command', function(args){
		if(args.command && args.command == 'uptime'){
			uptime(bot, args.channel);
		}
	});
}<commit_msg>uptime cleanup<commit_after>var parse = function(uptime){
	var minutes = Math.round(uptime / 60) % 60;
	var hours = Math.round(uptime / 60 / 60) % 24;
	var days = Math.round(uptime / 60 / 60 / 24);
	var seconds = Math.round(uptime) % 60;

	uptime = [];
	if (days >= 1) {
		uptime.push(days + ' day' + (days > 1 ? 's' : ''));
	}
	if (hours >= 1) {
		uptime.push(hours +' hour' + (hours > 1 ? 's' : ''));
	}
	if (minutes >= 1) {
		uptime.push(minutes + ' minute' + (minutes > 1 ? 's' : ''));
	}
	if (seconds >= 1) {
		uptime.push(seconds + ' second' + (seconds > 1 ? 's' : ''));
	}
	uptime = uptime.join(', ');
	return uptime;
}

exports.init = function(plugins, bot){
	bot.addCommand('uptime', '', 'Shows uptime of bot', USER_LEVEL_GLOBAL, true);
	plugins.listen(this, 'command', function(args){
		if(args.command == 'uptime'){
			var time = (new Date().getTime() - bot.startTime) / 1000;
			IRC.message(args.channel, 'Bot has been online for: ' + parse(time));
		}
	});
}
<|endoftext|>


<commit_before>/*
 * Util helpers
 */
define(['jquery'], function ($) {

    var utils = {};

    /**
     * Sorts a given fields dict based on a list of fieldDefs
     * @memberOf utils
     * @name utils#sortFields
     * @param {object} fields
     * @param {Array} fieldDefs
     * @param {Boolean} onlyFormFields (optional)
     * @param {int} limit (optional)
     * @return {Array} list of dicts
     */
    utils.sortFields = function(fields, fieldDefs, onlyFormFields, limit) {
        var sortedFields = [],
            fieldDef = null,
            fieldValue = null,
            fieldText = null;

        // Work on copy of fieldDefs array
        fieldDefs = fieldDefs.slice();

        // Return only form field definitions?
        if (onlyFormFields!=null) {
            fieldDefs = fieldDefs.filter(function(def) { return (def.form==onlyFormFields); });
        }

        // Create a Field dict for each field definition
        for (var i=0;i<fieldDefs.length;i++) {
            fieldDef = fieldDefs[i];
            fieldValue = fields[fieldDef.name];
            sortedFields.push($.extend({value: fieldValue}, fieldDef));

            if( (limit!=null) &&
                (sortedFields.length>=limit)) {
                break;
            }
        }

        return sortedFields;
    };

    /**
     * Stringifies an object while first sorting the keys
     * Ensures we can use it to check object equality
     * http://stackoverflow.com/questions/16167581/sort-object-properties-and-json-stringify
     * @memberOf  utils
     * @name  utils#stringifyOrdered
     * @method
     * @param obj
     * @return {string}
     */
    utils.stringifyOrdered = function(obj) {
        keys = [];
        if (obj) {
            for (var key in obj) {
                keys.push(key);
            }
        }
        keys.sort();
        var tObj = {};
        var key;
        for (var index in keys) {
            key = keys[index];
            tObj[key] = obj[key];
        }
        return JSON.stringify(tObj);
    };

    /**
     * Checks if two objects are equal
     * Mimics behaviour from http://underscorejs.org/#isEqual
     * @memberOf  utils
     * @name  utils#areEqual
     * @method
     * @param obj1
     * @param obj2
     * @return {boolean}
     */
    utils.areEqual = function(obj1, obj2) {
        return utils.stringifyOrdered(obj1 || {}) == utils.stringifyOrdered(obj2 || {});
    };

    /**
     * Turns an integer into a compact text to show in a badge
     * @memberOf  utils
     * @name  utils#badgeify
     * @method
     * @param  {int} count
     * @return {string}
     */
    utils.badgeify = function(count) {
        if (count>100) {
            return "99+";
        } else if (count>10) {
            return "10+";
        } else if (count>0) {
            return ""+count;
        } else {
            return "";
        }
    };

    /**
     * Turns a firstName lastName into a fistname.lastname login
     * @memberOf utils
     * @name  utils#getLoginName
     * @method
     * @param  {string} firstName
     * @param  {string} lastName
     * @return {string}
     */
    utils.getLoginName = function(firstName, lastName) {
        var patt = /[\s-]*/igm;
        return  firstName.latinise().toLowerCase().replace(patt, '') + "." + lastName.latinise().toLowerCase().replace(patt, '');
    };

    /**
     * Gets a parameter from the querystring (returns null if not found)
     * @memberOf utils
     * @name  utils#getUrlParam
     * @method
     * @param  {string} name
     * @param {string} default
     * @return {string}
     */
    utils.getUrlParam = function(name, def) {
        name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
        var regexS = "[\\?&]"+name+"=([^&#]*)";
        var regex = new RegExp( regexS );
        var results = regex.exec( window.location.href );
        return (results) ? decodeURIComponent(results[1].replace(/\+/g, " ")) : def;
    };

    // jQuery extension method
    $.urlParam = utils.getUrlParam;

    /**
     * getParsedLines
     * @memberOf utils
     * @name  utils#getParsedLines
     * @method
     * @param  {string} text
     * @return {Array}
     */
    utils.getParsedLines = function(text){
        if( (text) &&
            (text.length > 0)) {
            var customs = text.split(/\s*([,;\r\n]+|\s\s)\s*/);
            return customs.filter(function(cust, idx, arr) {
                return (
                (cust.length>0) &&
                (cust.indexOf(',')<0) &&
                (cust.indexOf(';')<0) &&
                ($.trim(cust).length>0) &&
                (arr.indexOf(cust) >= idx));
            });
        } else {
            return [];
        }
    };

    /**
     * getFriendlyFileName
     * @memberOf utils
     * @name  utils#getFriendlyFileName
     * @method
     * @param  {string} name
     * @return {string}
     */
    utils.getFriendlyFileName = function(name){
        return name.replace(/[^a-z0-9]/gi, '_').toLowerCase();
    }

    /**
     * getFriendlyKind
     * @memberOf utils
     * @name  utils#getFriendlyKind
     * @method
     * @param {object} kind
     * @return {string}
     */
     utils.getFriendlyKind = function(kind){
       var friendlyKind = null;

       if(kind == "string") {
         friendlyKind = "single line text";
       }

       if(kind == "text") {
         friendlyKind = "multi line text";
       }

       return friendlyKind;
     };

    return utils;

});
<commit_msg>fixed indentation for getFriendlyKind function<commit_after>/*
 * Util helpers
 */
define(['jquery'], function ($) {

    var utils = {};

    /**
     * Sorts a given fields dict based on a list of fieldDefs
     * @memberOf utils
     * @name utils#sortFields
     * @param {object} fields
     * @param {Array} fieldDefs
     * @param {Boolean} onlyFormFields (optional)
     * @param {int} limit (optional)
     * @return {Array} list of dicts
     */
    utils.sortFields = function(fields, fieldDefs, onlyFormFields, limit) {
        var sortedFields = [],
            fieldDef = null,
            fieldValue = null,
            fieldText = null;

        // Work on copy of fieldDefs array
        fieldDefs = fieldDefs.slice();

        // Return only form field definitions?
        if (onlyFormFields!=null) {
            fieldDefs = fieldDefs.filter(function(def) { return (def.form==onlyFormFields); });
        }

        // Create a Field dict for each field definition
        for (var i=0;i<fieldDefs.length;i++) {
            fieldDef = fieldDefs[i];
            fieldValue = fields[fieldDef.name];
            sortedFields.push($.extend({value: fieldValue}, fieldDef));

            if( (limit!=null) &&
                (sortedFields.length>=limit)) {
                break;
            }
        }

        return sortedFields;
    };

    /**
     * Stringifies an object while first sorting the keys
     * Ensures we can use it to check object equality
     * http://stackoverflow.com/questions/16167581/sort-object-properties-and-json-stringify
     * @memberOf  utils
     * @name  utils#stringifyOrdered
     * @method
     * @param obj
     * @return {string}
     */
    utils.stringifyOrdered = function(obj) {
        keys = [];
        if (obj) {
            for (var key in obj) {
                keys.push(key);
            }
        }
        keys.sort();
        var tObj = {};
        var key;
        for (var index in keys) {
            key = keys[index];
            tObj[key] = obj[key];
        }
        return JSON.stringify(tObj);
    };

    /**
     * Checks if two objects are equal
     * Mimics behaviour from http://underscorejs.org/#isEqual
     * @memberOf  utils
     * @name  utils#areEqual
     * @method
     * @param obj1
     * @param obj2
     * @return {boolean}
     */
    utils.areEqual = function(obj1, obj2) {
        return utils.stringifyOrdered(obj1 || {}) == utils.stringifyOrdered(obj2 || {});
    };

    /**
     * Turns an integer into a compact text to show in a badge
     * @memberOf  utils
     * @name  utils#badgeify
     * @method
     * @param  {int} count
     * @return {string}
     */
    utils.badgeify = function(count) {
        if (count>100) {
            return "99+";
        } else if (count>10) {
            return "10+";
        } else if (count>0) {
            return ""+count;
        } else {
            return "";
        }
    };

    /**
     * Turns a firstName lastName into a fistname.lastname login
     * @memberOf utils
     * @name  utils#getLoginName
     * @method
     * @param  {string} firstName
     * @param  {string} lastName
     * @return {string}
     */
    utils.getLoginName = function(firstName, lastName) {
        var patt = /[\s-]*/igm;
        return  firstName.latinise().toLowerCase().replace(patt, '') + "." + lastName.latinise().toLowerCase().replace(patt, '');
    };

    /**
     * Gets a parameter from the querystring (returns null if not found)
     * @memberOf utils
     * @name  utils#getUrlParam
     * @method
     * @param  {string} name
     * @param {string} default
     * @return {string}
     */
    utils.getUrlParam = function(name, def) {
        name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
        var regexS = "[\\?&]"+name+"=([^&#]*)";
        var regex = new RegExp( regexS );
        var results = regex.exec( window.location.href );
        return (results) ? decodeURIComponent(results[1].replace(/\+/g, " ")) : def;
    };

    // jQuery extension method
    $.urlParam = utils.getUrlParam;

    /**
     * getParsedLines
     * @memberOf utils
     * @name  utils#getParsedLines
     * @method
     * @param  {string} text
     * @return {Array}
     */
    utils.getParsedLines = function(text){
        if( (text) &&
            (text.length > 0)) {
            var customs = text.split(/\s*([,;\r\n]+|\s\s)\s*/);
            return customs.filter(function(cust, idx, arr) {
                return (
                (cust.length>0) &&
                (cust.indexOf(',')<0) &&
                (cust.indexOf(';')<0) &&
                ($.trim(cust).length>0) &&
                (arr.indexOf(cust) >= idx));
            });
        } else {
            return [];
        }
    };

    /**
     * getFriendlyFileName
     * @memberOf utils
     * @name  utils#getFriendlyFileName
     * @method
     * @param  {string} name
     * @return {string}
     */
    utils.getFriendlyFileName = function(name){
        return name.replace(/[^a-z0-9]/gi, '_').toLowerCase();
    }

    /**
     * getFriendlyKind
     * @memberOf utils
     * @name  utils#getFriendlyKind
     * @method
     * @param {object} kind
     * @return {string}
     */
    utils.getFriendlyKind = function(kind){
        var friendlyKind = null;

        if(kind == "string") {
            friendlyKind = "single line text";
        }

        if(kind == "text") {
           friendlyKind = "multi line text";
        }

        return friendlyKind;
     };

     return utils;

});
<|endoftext|>


<commit_before>var g_navbar = new Navbar();
function initializeNavbar()
{
    g_navbar.addKeyPoint("#home", true);
    g_navbar.addKeyPoint("#about", true);
    g_navbar.addKeyPoint("#skills", false);
    g_navbar.addKeyPoint("#portfolio", true);
    g_navbar.addKeyPoint("#contact", false);
    g_navbar.addKeyPoint("#main-footer", false);
    $(window).on('scroll', Navbar.onScroll);
}

window.onload = function()
{
    var content = $("#content");
    content.append(document.querySelector("#link-home").import.querySelector("#home"));
    content.append(document.querySelector("#link-about").import.querySelector("#about"));
    content.append(document.querySelector("#link-skills").import.querySelector("#skills"));
    content.append(document.querySelector("#link-portfolio").import.querySelector("#portfolio"));
    content.append(document.querySelector("#link-contact").import.querySelector("#contact"));

    initializeNavbar();

    $(function() {
        $.scrollify({
            section : ".section"
        });
    });
};
<commit_msg>- Refactoring<commit_after>function includeHTMLFiles()
{
    var content = $("#content");
    content.append(document.querySelector("#link-home").import.querySelector("#home"));
    content.append(document.querySelector("#link-about").import.querySelector("#about"));
    content.append(document.querySelector("#link-skills").import.querySelector("#skills"));
    content.append(document.querySelector("#link-portfolio").import.querySelector("#portfolio"));
    content.append(document.querySelector("#link-contact").import.querySelector("#contact"));
}

var g_navbar = new Navbar();
function initializeNavbar()
{
    g_navbar.addKeyPoint("#home", true);
    g_navbar.addKeyPoint("#about", true);
    g_navbar.addKeyPoint("#skills", false);
    g_navbar.addKeyPoint("#portfolio", true);
    g_navbar.addKeyPoint("#contact", false);
    g_navbar.addKeyPoint("#main-footer", false);
    $(window).on('scroll', Navbar.onScroll);
}

function setupScrollify()
{
    $(function() {
        $.scrollify({
            section : ".section"
        });
    });
}

window.onload = function()
{
    includeHTMLFiles();
    initializeNavbar();
    setupScrollify();
};
<|endoftext|>


<commit_before>pc.extend(pc, function () {
    var DEFAULTS = {
        minWidth: 0,
        minHeight: 0,
        maxWidth: null,
        maxHeight: null,
        fitWidthProportion: 0,
        fitHeightProportion: 0,
    };

    /**
     * @component
     * @name pc.LayoutChildComponent
     * @description Create a new LayoutChildComponent
     * @class A LayoutChildComponent enables the Entity to control the sizing applied to it by its parent {@link pc.LayoutGroup}.
     * @param {pc.LayoutChildComponentSystem} system The ComponentSystem that created this Component
     * @param {pc.Entity} entity The Entity that this Component is attached to.
     * @extends pc.Component
     * TODO Add properties
     */
    var LayoutChildComponent = function LayoutChildComponent(system, entity) {
        this._minWidth = DEFAULTS.minWidth;
        this._minHeight = DEFAULTS.minHeight;
        this._maxWidth = DEFAULTS.maxWidth;
        this._maxHeight = DEFAULTS.maxHeight;
        this._fitWidthProportion = DEFAULTS.fitWidthProportion;
        this._fitHeightProportion = DEFAULTS.fitHeightProportion;
    };
    LayoutChildComponent = pc.inherits(LayoutChildComponent, pc.Component);

    // These are exposed for use by layout-calculator.js in the case where an
    // element does not have a LayoutChildComponent.
    LayoutChildComponent.DEFAULTS = DEFAULTS;

    function defineResizeProperty(name) {
        var _name = '_' + name;

        Object.defineProperty(LayoutChildComponent.prototype, name, {
            get: function () {
                return this[_name];
            },

            set: function (value) {
                if (this[_name] !== value) {
                    this[_name] = value;
                    this.fire('set:' + name, this[_name]);
                    this.fire('resize');
                }
            }
        });
    }

    defineResizeProperty('minWidth');
    defineResizeProperty('minHeight');
    defineResizeProperty('maxWidth');
    defineResizeProperty('maxHeight');
    defineResizeProperty('fitWidthProportion');
    defineResizeProperty('fitHeightProportion');

    return {
        LayoutChildComponent: LayoutChildComponent
    };
}());
<commit_msg>Add LayoutChildComponent documentation<commit_after>pc.extend(pc, function () {
    var DEFAULTS = {
        minWidth: 0,
        minHeight: 0,
        maxWidth: null,
        maxHeight: null,
        fitWidthProportion: 0,
        fitHeightProportion: 0,
    };

    /**
     * @component
     * @name pc.LayoutChildComponent
     * @description Create a new LayoutChildComponent
     * @class A LayoutChildComponent enables the Entity to control the sizing applied to it by its parent {@link pc.LayoutGroupComponent}.
     * @param {pc.LayoutChildComponentSystem} system The ComponentSystem that created this Component
     * @param {pc.Entity} entity The Entity that this Component is attached to.
     * @extends pc.Component
     * @property {Number} minWidth The minimum width the element should be rendered at.
     * @property {Number} minHeight The minimum height the element should be rendered at.
     * @property {Number} maxWidth The maximum width the element should be rendered at.
     * @property {Number} maxHeight The maximum height the element should be rendered at.
     * @property {Number} fitWidthProportion The amount of additional horizontal space that the element should take up, if necessary to satisfy a Stretch/Shrink fitting calculation. This is specified as a proportion, taking into account the proportion values of other siblings.
     * @property {Number} fitHeightProportion The amount of additional vertical space that the element should take up, if necessary to satisfy a Stretch/Shrink fitting calculation. This is specified as a proportion, taking into account the proportion values of other siblings.
     */
    var LayoutChildComponent = function LayoutChildComponent(system, entity) {
        this._minWidth = DEFAULTS.minWidth;
        this._minHeight = DEFAULTS.minHeight;
        this._maxWidth = DEFAULTS.maxWidth;
        this._maxHeight = DEFAULTS.maxHeight;
        this._fitWidthProportion = DEFAULTS.fitWidthProportion;
        this._fitHeightProportion = DEFAULTS.fitHeightProportion;
    };
    LayoutChildComponent = pc.inherits(LayoutChildComponent, pc.Component);

    // These are exposed for use by layout-calculator.js in the case where an
    // element does not have a LayoutChildComponent.
    LayoutChildComponent.DEFAULTS = DEFAULTS;

    function defineResizeProperty(name) {
        var _name = '_' + name;

        Object.defineProperty(LayoutChildComponent.prototype, name, {
            get: function () {
                return this[_name];
            },

            set: function (value) {
                if (this[_name] !== value) {
                    this[_name] = value;
                    this.fire('set:' + name, this[_name]);
                    this.fire('resize');
                }
            }
        });
    }

    defineResizeProperty('minWidth');
    defineResizeProperty('minHeight');
    defineResizeProperty('maxWidth');
    defineResizeProperty('maxHeight');
    defineResizeProperty('fitWidthProportion');
    defineResizeProperty('fitHeightProportion');

    return {
        LayoutChildComponent: LayoutChildComponent
    };
}());
<|endoftext|>


<commit_before>/**
  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you under the Apache License, Version 2.0 (the
  "License"); you may not use this file except in compliance
  with the License.  You may obtain a copy of the License at

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

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

var cordova = require('cordova-lib').cordova;
var Q = require('q');

// Returns the promise from the raw Cordova command.
exports.runCmd = function runCmd(cmd) {
  var msg = cmd[0];
  cmd.slice(1).forEach(function(arg) {
    if (typeof arg != 'string') {
      return;
    }
    if (arg.indexOf(' ') != -1) {
      msg += ' "' + arg + '"';
    } else {
      msg += ' ' + arg;
    }
  });
  // Hack to remove the obj passed to the cordova create command.
  console.log('## Running Cordova Command: ' + msg);
  return cordova.raw[cmd[0]].apply(cordova, cmd.slice(1));
};

// Chains a list of cordova commands, returning a promise.
exports.runAllCmds = function runAllCmds(commands) {
  return commands.reduce(function(soFar, f) {
    return soFar.then(function() {
      return exports.runCmd(f);
    });
  }, Q());
};

<commit_msg>Don't print stack for CordovaError<commit_after>/**
  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you under the Apache License, Version 2.0 (the
  "License"); you may not use this file except in compliance
  with the License.  You may obtain a copy of the License at

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

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

var cordova = require('cordova-lib').cordova;
var Q = require('q');

// Returns the promise from the raw Cordova command.
exports.runCmd = function runCmd(cmd) {
  var msg = cmd[0];
  cmd.slice(1).forEach(function(arg) {
    if (typeof arg != 'string') {
      return;
    }
    if (arg.indexOf(' ') != -1) {
      msg += ' "' + arg + '"';
    } else {
      msg += ' ' + arg;
    }
  });
  console.log('## Running Cordova Command: ' + msg);
  return cordova.raw[cmd[0]].apply(cordova, cmd.slice(1))
  .fail(function(err) {
    if (err.name == 'CordovaError') {
        return Q.reject(err.message);
    } else {
        return Q.reject(err.stack);
    }
  });
};

// Chains a list of cordova commands, returning a promise.
exports.runAllCmds = function runAllCmds(commands) {
  return commands.reduce(function(soFar, f) {
    return soFar.then(function() {
      return exports.runCmd(f);
    });
  }, Q());
};

<|endoftext|>


<commit_before>'use strict';

angular.module('hrr10MjbeApp')
  .controller('DashboardCtrl', function($scope, $state, Teacher) {
    $scope.selectedClass = "";

    $scope.classname = "";
    $scope.addCount = '0';
    $scope.inviteCount = '0';
    var addCount = 0;
    var inviteCount = 0;

    //reloads stuff
    $scope.refresh = function() {
      Teacher.getClasses(function(classes) {
        $scope.listedClasses = classes;
        Teacher.getRequests(function(requests) {
          //this is pretty hacky. the pending students are stored seperately on the server, but now we want to show
          //them as part of a particular class, so we scan through and populate them here
          for (var i = 0; i < requests.length; i++) {
            for (var j = 0; j < classes.length; j++) {
              if (requests[i].class._id === classes[j]._id) {
                classes[j].students.push({
                  name: requests[i].student.name,
                  email: requests[i].student.email,
                  status: 'pending'
                })
              }
            }
          }
          $scope.classes = JSON.stringify(classes);
          //select first class as default
          $scope.activeClass = classes[0]._id.toString();
        })
      });
    }

    //submits invitation
    $scope.submit = function() {
      Teacher.sendInvite($scope.email, $scope.activeClass, function(result) {
        if (result === 200) {
          $scope.refresh();
        } else {
          //TODO this won't do anything anymore
          $scope.invitations = [{
            student: 'error'
          }];
        }
      })
    }

    //submits new class
    $scope.submitClass = function() {
      Teacher.addClass($scope.classname, function(res) {
        if (res === -1) {
          return alert('duplicate class');
        }
        Teacher.getClasses(function(classes) {
          $scope.listedClasses = classes;
          $scope.classes = JSON.stringify(classes.map(function(val) {
            return {
              _id: val._id,
              name: val.name
            };
          }));
        });
      });
    }

    $scope.polymerChange = function() {
      if (Number.parseInt($scope.addCount) > addCount) {
        $scope.submitClass();
        addCount++;
      }

      if (Number.parseInt($scope.inviteCount) > inviteCount) {
        $scope.submit();
        inviteCount++;
      }
    }

    $scope.refresh();
  });
<commit_msg>fix jumping to first class bug<commit_after>'use strict';

angular.module('hrr10MjbeApp')
  .controller('DashboardCtrl', function($scope, $state, Teacher) {
    $scope.selectedClass = "";

    $scope.classname = "";
    $scope.addCount = '0';
    $scope.inviteCount = '0';
    var addCount = 0;
    var inviteCount = 0;
    var first = true;

    //reloads stuff
    $scope.refresh = function() {
      Teacher.getClasses(function(classes) {
        $scope.listedClasses = classes;
        Teacher.getRequests(function(requests) {
          //this is pretty hacky. the pending students are stored seperately on the server, but now we want to show
          //them as part of a particular class, so we scan through and populate them here
          for (var i = 0; i < requests.length; i++) {
            for (var j = 0; j < classes.length; j++) {
              if (requests[i].class._id === classes[j]._id) {
                classes[j].students.push({
                  name: requests[i].student.name,
                  email: requests[i].student.email,
                  status: 'pending'
                })
              }
            }
          }
          $scope.classes = JSON.stringify(classes);
          //select first class as default
          if (first) {
            $scope.activeClass = classes[0]._id.toString();
            first = false;
          }
        })
      });
    }

    //submits invitation
    $scope.submit = function() {
      Teacher.sendInvite($scope.email, $scope.activeClass, function(result) {
        if (result === 200) {
          $scope.refresh();
        } else {
          //TODO this won't do anything anymore
          $scope.invitations = [{
            student: 'error'
          }];
        }
      })
    }

    //submits new class
    $scope.submitClass = function() {
      Teacher.addClass($scope.classname, function(res) {
        if (res === -1) {
          return alert('duplicate class');
        }
        Teacher.getClasses(function(classes) {
          $scope.listedClasses = classes;
          $scope.classes = JSON.stringify(classes.map(function(val) {
            return {
              _id: val._id,
              name: val.name
            };
          }));
        });
      });
    }

    $scope.polymerChange = function() {
      if (Number.parseInt($scope.addCount) > addCount) {
        $scope.submitClass();
        addCount++;
      }

      if (Number.parseInt($scope.inviteCount) > inviteCount) {
        $scope.submit();
        inviteCount++;
      }
    }

    $scope.refresh();
  });
<|endoftext|>


<commit_before>;(function(){

  var __filename = (function(){
    var scripts = document.getElementsByTagName('script');
    var a = document.createElement('a');
    a.href = scripts[scripts.length-1].src;
    return a.pathname;
  }());

  var __dirname = __filename.split('/').reverse().slice(1).reverse().join('/');

  document.head.appendChild(function(){
    var link = document.createElement('link');
    link.rel = 'stylesheet';
    link.href = __dirname + '/../vendor/jasmine/jasmine.css';
    return link;
  }());

  var cacheBust = '?_=' + Date.now().toString(36);

  window.ReactWebWorker_URL = __dirname + '/../src/test/worker.js' + cacheBust;

  document.write('<script src="' + __dirname + '/../build/jasmine.js' + cacheBust + '"><\/script>');
  document.write('<script src="' + __dirname + '/../build/react.js' + cacheBust + '"><\/script>');
  document.write('<script src="' + __dirname + '/../build/react-test.js' + cacheBust + '"><\/script>');
  document.write('<script src="' + __dirname + '/../node_modules/jasmine-tapreporter/src/tapreporter.js' + cacheBust + '"><\/script>');
  document.write('<script src="' + __dirname + '/../test/the-files-to-test.generated.js' + cacheBust + '"><\/script>');
  document.write('<script src="' + __dirname + '/../test/jasmine-execute.js' + cacheBust + '"><\/script>');

}());
<commit_msg>Make it easier to repro tests in the wild<commit_after>;(function(){
  console.log('# ' + location);

  var __filename = (function(){
    var scripts = document.getElementsByTagName('script');
    var a = document.createElement('a');
    a.href = scripts[scripts.length-1].src;
    return a.pathname;
  }());

  var __dirname = __filename.split('/').reverse().slice(1).reverse().join('/');

  document.head.appendChild(function(){
    var link = document.createElement('link');
    link.rel = 'stylesheet';
    link.href = __dirname + '/../vendor/jasmine/jasmine.css';
    return link;
  }());

  var cacheBust = '?_=' + Date.now().toString(36);

  window.ReactWebWorker_URL = __dirname + '/../src/test/worker.js' + cacheBust;

  document.write('<script src="' + __dirname + '/../build/jasmine.js' + cacheBust + '"><\/script>');
  document.write('<script src="' + __dirname + '/../build/react.js' + cacheBust + '"><\/script>');
  document.write('<script src="' + __dirname + '/../build/react-test.js' + cacheBust + '"><\/script>');
  document.write('<script src="' + __dirname + '/../node_modules/jasmine-tapreporter/src/tapreporter.js' + cacheBust + '"><\/script>');
  document.write('<script src="' + __dirname + '/../test/the-files-to-test.generated.js' + cacheBust + '"><\/script>');
  document.write('<script src="' + __dirname + '/../test/jasmine-execute.js' + cacheBust + '"><\/script>');

}());
<|endoftext|>


<commit_before>'use strict';
var React = require('react');
var _ = require('underscore');
var moment = require('moment');
var modal = require('../libs/bootstrap/modal');
var panel = require('../libs/bootstrap/panel');
var form = require('../libs/bootstrap/form');
var globals = require('./globals');
var parseAndLogError = require('./mixins').parseAndLogError;

var Panel = panel.Panel;
var Modal = modal.Modal;
var ModalMixin = modal.ModalMixin;
var Form = form.Form;
var FormMixin = form.FormMixin;
var Input = form.Input;
var external_url_map = globals.external_url_map;

var CurationMixin = module.exports.CurationMixin = {
    getInitialState: function() {
        return {
            currOmimId: '' // Currently set OMIM ID
        };
    },

    updateOmimId: function(gdmUuid, newOmimId) {
        this.getRestData(
            '/gdm/' + gdmUuid + '/?frame=object'
        ).then(gdmObj => {
            console.log(gdmObj.uuid);
            // We'll get 422 (Unprocessible entity) if we PUT any of these fields:
            if (gdmObj.uuid) { delete gdmObj.uuid; }
            if (gdmObj['@id']) { delete gdmObj['@id']; }
            if (gdmObj['@type']) { delete gdmObj['@type']; }

            gdmObj.omimId = newOmimId;
            return this.putRestData('/gdm/' + this.state.currGdm.uuid, gdmObj);
        }).then(data => {
            this.setState({currOmimId: newOmimId});
        }).catch(e => {
            console.log('UPDATEOMIMID %o', e);
            parseAndLogError.bind(undefined, 'putRequest');
        });
    }
};

var CuratorPage = module.exports.CuratorPage = React.createClass({
    render: function() {
        var context = this.props.context;

        var CuratorPageView = globals.curator_page.lookup(context, context.name);
        var content = <CuratorPageView {...this.props} />;
        return (

{content}

        );
    }
});

globals.content_views.register(CuratorPage, 'curator_page');

// Curation data header for Gene:Disease
var RecordHeader = module.exports.RecordHeader = React.createClass({
    propTypes: {
        gdm: React.PropTypes.object, // GDM data to display
        omimId: React.PropTypes.string, // OMIM ID to display
        updateOmimId: React.PropTypes.func // Function to call when OMIM ID changes
    },

    render: function() {
        var gdm = this.props.gdm;

        if (gdm && Object.keys(gdm).length > 0 && gdm['@type'][0] === 'gdm') {
            var gene = this.props.gdm.gene;
            var disease = this.props.gdm.disease;
            var mode = this.props.gdm.modeInheritance.match(/^(.*?)(?: \(HP:[0-9]*?\)){0,1}$/)[1];

            return (

{gene.symbol} – {disease.term}

{mode}

                            <GeneRecordHeader gene={gene} />
                            <DiseaseRecordHeader gdm={this.props.gdm} omimId={this.props.omimId} updateOmimId={this.props.updateOmimId} />
                            <CuratorRecordHeader gdm={this.props.gdm} />

            );
        } else {
            return null;
        }
    }
});

// Displays the PM item summary, with authors, title, citation
var PmidSummary = module.exports.PmidSummary = React.createClass({
    propTypes: {
        article: React.PropTypes.object, // Article object to display
        displayJournal: React.PropTypes.bool // T to display article journal
    },

    render: function() {
        var authors;
        var article = this.props.article;
        var date = (/^([\d]{4})(.*?)$/).exec(article.date);

        if (article.authors && article.authors.length) {
            authors = article.authors[0] + (article.authors.length > 1 ? ' et al. ' : '. ');
        }

        return (

                {authors}
                {article.title + ' '}
                {this.props.displayJournal ? {article.journal + '. '} : null}
                {date[1]}{date[2]}

        );
    }
});

var CurationPalette = module.exports.CurationPalette = React.createClass({
    propTypes: {
        annotation: React.PropTypes.object.isRequired, // Current annotation that owns the article
        gdm: React.PropTypes.object.isRequired, // Current GDM that owns the given annotation
        session: React.PropTypes.object // Session object
    },

    render: function() {
        var annotation = this.props.annotation;
        var session = this.props.session;
        var curatorMatch = annotation.owner === (session && session.user_properties && session.user_properties.email);
        var url = curatorMatch ? ('/group-curation/?gdm=' + this.props.gdm.uuid + '&evidence=' + this.props.annotation.uuid) : null;

        return (
            <Panel panelClassName="panel-evidence-groups" title={'Evidence for PMID:' + this.props.annotation.article.pmid}>
                <Panel title={<CurationPaletteTitles title="Group" url={url} />} panelClassName="panel-evidence">
                    {annotation.groups && annotation.groups.map(function(group) {
                        return (

{group.label}

{annotation.owner}

{moment(annotation.dateTime).format('YYYY MMM DD, h:mm a')}

                                View{curatorMatch ?  | Edit : null}

                        );
                    }.bind(this))}
                </Panel>
            </Panel>
        );
    }
});

// Title for each section of the curation palette. Contains the title and an Add button.
var CurationPaletteTitles = React.createClass({
    propTypes: {
        title: React.PropTypes.string, // Title to display
        url: React.PropTypes.string // URL for panel title click to go to.
    },

    render: function() {
        return (

                {this.props.url ?

{this.props.title}

                :

{this.props.title}

                }

        );
    }
});

// Display the gene section of the curation data
var GeneRecordHeader = React.createClass({
    propTypes: {
        gene: React.PropTypes.object // Object to display
    },

    render: function() {
        var gene = this.props.gene;

        return (

                    {gene ?

{gene.symbol}

HGNC Symbol: {gene.symbol}

NCBI Gene ID: {gene.entrezId}

                    : null}

        );
    }
});

// Display the disease section of the curation data
var DiseaseRecordHeader = React.createClass({
    mixins: [ModalMixin],

    propTypes: {
        gdm: React.PropTypes.object, // Object to display
        omimId: React.PropTypes.string, // OMIM ID to display
        updateOmimId: React.PropTypes.func // Function to call when OMIM ID changes
    },

    render: function() {
        var gdm = this.props.gdm;
        var disease = gdm.disease;
        var addEdit = this.props.omimId ? 'Edit' : 'Add';

        return (

                    {disease ?

{disease.term}

Orphanet ID: {'ORPHA' + disease.orphaNumber}

                                OMIM ID: {this.props.omimId ?

                                        {this.props.omimId}

                                : null}
                                <Modal title="Add/Change OMIM ID" wrapperClassName="edit-omim-modal">
                                    [<a modal={<AddOmimIdModal gdm={gdm} closeModal={this.closeModal} updateOmimId={this.props.updateOmimId} />} href="#">{addEdit}]
                                </Modal>

                    : null}

        );
    }
});

// The content of the Add PMID(s) modal dialog box
var AddOmimIdModal = React.createClass({
    mixins: [FormMixin],

    propTypes: {
        gdm: React.PropTypes.object.isRequired, // GDM being affected
        closeModal: React.PropTypes.func.isRequired, // Function to call to close the modal
        updateOmimId: React.PropTypes.func.isRequired // Function to call when we have a new OMIM ID
    },

    // Form content validation
    validateForm: function() {
        // Start with default validation
        var valid = this.validateDefault();

        // Valid if the field has only 10 or fewer digits
        if (valid) {
            valid = this.getFormValue('omimid').match(/^[0-9]{1,10}$/i);
            if (!valid) {
                this.setFormErrors('omimid', 'Only numbers allowed');
            }
        }
        return valid;
    },

    // Called when the modal form’s submit button is clicked. Handles validation and updating the OMIM in the GDM.
    submitForm: function(e) {
        e.preventDefault(); e.stopPropagation(); // Don't run through HTML submit handler
        this.saveFormValue('omimid', this.refs.omimid.getValue());
        if (this.validateForm()) {
            // Form is valid -- we have a good OMIM ID. Close the modal and update the current GDM's OMIM ID
            this.props.closeModal();
            var enteredOmimId = this.getFormValue('omimid');
                this.props.updateOmimId(this.props.gdm.uuid, enteredOmimId);
        }
    },

    // Called when the modal form's cancel button is clicked. Just closes the modal like
    // nothing happened.
    cancelForm: function(e) {
        e.preventDefault(); e.stopPropagation(); // Don't run through HTML submit handler
        this.props.closeModal();
    },

    render: function() {
        return (
            <Form submitHandler={this.submitForm} formClassName="form-std">

                    <Input type="text" ref="omimid" label="Enter an OMIM ID"
                        error={this.getFormError('omimid')} clearError={this.clrFormErrors.bind(null, 'omim')}
                        labelClassName="control-label" groupClassName="form-group" required />

                    <Input type="cancel" inputClassName="btn-default btn-inline-spacer" cancelHandler={this.cancelForm} />
                    <Input type="submit" inputClassName="btn-primary btn-inline-spacer" title="Add/Change OMIM ID" />

            </Form>
        );
    }
});

// Display the curator data of the curation data
var CuratorRecordHeader = React.createClass({
    propTypes: {
        gdm: React.PropTypes.object // GDM with curator data to display
    },

    // Return the latest annotation in the given GDM
    findLatestAnnotation: function() {
        var annotations = this.props.gdm.annotations;
        var latestAnnotation = {};
        var latestTime = 0;
        if (annotations && annotations.length) {
            annotations.forEach(function(annotation) {
                // Get Unix timestamp version of annotation's time and compare against the saved version.
                var time = moment(annotation.dateTime).format('x');
                if (latestTime < time) {
                    latestAnnotation = annotation;
                    latestTime = time;
                }
            });
        }
        return latestAnnotation;
    },

    render: function() {
        var gdm = this.props.gdm;
        var annotationOwners = _.uniq(gdm.annotations.map(function(annotation) {
            return annotation.owner;
        })).sort();
        var latestAnnotation = this.findLatestAnnotation();

        return (

                    {gdm ?

Status:

{gdm.status}

Creator:

{gdm.owner} – {moment(gdm.dateTime).format('YYYY MMM DD, h:mm a')}

                            {annotationOwners && annotationOwners.length ?

Participants:

                                        {annotationOwners.map(function(owner, i) {
                                            return (

                                                    {i > 0 ? ', ' : ''}
                                                    {owner}

                                            );
                                        })}

Last edited:

{latestAnnotation.owner} — {moment(latestAnnotation.dateTime).format('YYYY MMM DD, h:mm a')}

                            : null}

                    : null}

        );
    }
});

// Display buttons to bring up the PubMed and doi-specified web pages.
// For now, no doi is available
var PmidDoiButtons = module.exports.PmidDoiButtons = React.createClass({
    propTypes: {
        pmid: React.PropTypes.string // Numeric string PMID for PubMed page
    },

    render: function() {
        var pmid = this.props.pmid;

        return (

                {pmid ? PubMed : null}

        );
    }
});
<commit_msg>Fix undefined object error<commit_after>'use strict';
var React = require('react');
var _ = require('underscore');
var moment = require('moment');
var modal = require('../libs/bootstrap/modal');
var panel = require('../libs/bootstrap/panel');
var form = require('../libs/bootstrap/form');
var globals = require('./globals');
var parseAndLogError = require('./mixins').parseAndLogError;

var Panel = panel.Panel;
var Modal = modal.Modal;
var ModalMixin = modal.ModalMixin;
var Form = form.Form;
var FormMixin = form.FormMixin;
var Input = form.Input;
var external_url_map = globals.external_url_map;

var CurationMixin = module.exports.CurationMixin = {
    getInitialState: function() {
        return {
            currOmimId: '' // Currently set OMIM ID
        };
    },

    updateOmimId: function(gdmUuid, newOmimId) {
        this.getRestData(
            '/gdm/' + gdmUuid + '/?frame=object'
        ).then(gdmObj => {
            // We'll get 422 (Unprocessible entity) if we PUT any of these fields:
            if (gdmObj.uuid) { delete gdmObj.uuid; }
            if (gdmObj['@id']) { delete gdmObj['@id']; }
            if (gdmObj['@type']) { delete gdmObj['@type']; }

            gdmObj.omimId = newOmimId;
            return this.putRestData('/gdm/' + gdmUuid, gdmObj);
        }).then(data => {
            this.setState({currOmimId: newOmimId});
        }).catch(e => {
            console.log('UPDATEOMIMID %o', e);
            parseAndLogError.bind(undefined, 'putRequest');
        });
    }
};

var CuratorPage = module.exports.CuratorPage = React.createClass({
    render: function() {
        var context = this.props.context;

        var CuratorPageView = globals.curator_page.lookup(context, context.name);
        var content = <CuratorPageView {...this.props} />;
        return (

{content}

        );
    }
});

globals.content_views.register(CuratorPage, 'curator_page');

// Curation data header for Gene:Disease
var RecordHeader = module.exports.RecordHeader = React.createClass({
    propTypes: {
        gdm: React.PropTypes.object, // GDM data to display
        omimId: React.PropTypes.string, // OMIM ID to display
        updateOmimId: React.PropTypes.func // Function to call when OMIM ID changes
    },

    render: function() {
        var gdm = this.props.gdm;

        if (gdm && Object.keys(gdm).length > 0 && gdm['@type'][0] === 'gdm') {
            var gene = this.props.gdm.gene;
            var disease = this.props.gdm.disease;
            var mode = this.props.gdm.modeInheritance.match(/^(.*?)(?: \(HP:[0-9]*?\)){0,1}$/)[1];

            return (

{gene.symbol} – {disease.term}

{mode}

                            <GeneRecordHeader gene={gene} />
                            <DiseaseRecordHeader gdm={this.props.gdm} omimId={this.props.omimId} updateOmimId={this.props.updateOmimId} />
                            <CuratorRecordHeader gdm={this.props.gdm} />

            );
        } else {
            return null;
        }
    }
});

// Displays the PM item summary, with authors, title, citation
var PmidSummary = module.exports.PmidSummary = React.createClass({
    propTypes: {
        article: React.PropTypes.object, // Article object to display
        displayJournal: React.PropTypes.bool // T to display article journal
    },

    render: function() {
        var authors;
        var article = this.props.article;
        var date = (/^([\d]{4})(.*?)$/).exec(article.date);

        if (article.authors && article.authors.length) {
            authors = article.authors[0] + (article.authors.length > 1 ? ' et al. ' : '. ');
        }

        return (

                {authors}
                {article.title + ' '}
                {this.props.displayJournal ? {article.journal + '. '} : null}
                {date[1]}{date[2]}

        );
    }
});

var CurationPalette = module.exports.CurationPalette = React.createClass({
    propTypes: {
        annotation: React.PropTypes.object.isRequired, // Current annotation that owns the article
        gdm: React.PropTypes.object.isRequired, // Current GDM that owns the given annotation
        session: React.PropTypes.object // Session object
    },

    render: function() {
        var annotation = this.props.annotation;
        var session = this.props.session;
        var curatorMatch = annotation.owner === (session && session.user_properties && session.user_properties.email);
        var url = curatorMatch ? ('/group-curation/?gdm=' + this.props.gdm.uuid + '&evidence=' + this.props.annotation.uuid) : null;

        return (
            <Panel panelClassName="panel-evidence-groups" title={'Evidence for PMID:' + this.props.annotation.article.pmid}>
                <Panel title={<CurationPaletteTitles title="Group" url={url} />} panelClassName="panel-evidence">
                    {annotation.groups && annotation.groups.map(function(group) {
                        return (

{group.label}

{annotation.owner}

{moment(annotation.dateTime).format('YYYY MMM DD, h:mm a')}

                                View{curatorMatch ?  | Edit : null}

                        );
                    }.bind(this))}
                </Panel>
            </Panel>
        );
    }
});

// Title for each section of the curation palette. Contains the title and an Add button.
var CurationPaletteTitles = React.createClass({
    propTypes: {
        title: React.PropTypes.string, // Title to display
        url: React.PropTypes.string // URL for panel title click to go to.
    },

    render: function() {
        return (

                {this.props.url ?

{this.props.title}

                :

{this.props.title}

                }

        );
    }
});

// Display the gene section of the curation data
var GeneRecordHeader = React.createClass({
    propTypes: {
        gene: React.PropTypes.object // Object to display
    },

    render: function() {
        var gene = this.props.gene;

        return (

                    {gene ?

{gene.symbol}

HGNC Symbol: {gene.symbol}

NCBI Gene ID: {gene.entrezId}

                    : null}

        );
    }
});

// Display the disease section of the curation data
var DiseaseRecordHeader = React.createClass({
    mixins: [ModalMixin],

    propTypes: {
        gdm: React.PropTypes.object, // Object to display
        omimId: React.PropTypes.string, // OMIM ID to display
        updateOmimId: React.PropTypes.func // Function to call when OMIM ID changes
    },

    render: function() {
        var gdm = this.props.gdm;
        var disease = gdm.disease;
        var addEdit = this.props.omimId ? 'Edit' : 'Add';

        return (

                    {disease ?

{disease.term}

Orphanet ID: {'ORPHA' + disease.orphaNumber}

                                OMIM ID: {this.props.omimId ?

                                        {this.props.omimId}

                                : null}
                                <Modal title="Add/Change OMIM ID" wrapperClassName="edit-omim-modal">
                                    [<a modal={<AddOmimIdModal gdm={gdm} closeModal={this.closeModal} updateOmimId={this.props.updateOmimId} />} href="#">{addEdit}]
                                </Modal>

                    : null}

        );
    }
});

// The content of the Add PMID(s) modal dialog box
var AddOmimIdModal = React.createClass({
    mixins: [FormMixin],

    propTypes: {
        gdm: React.PropTypes.object.isRequired, // GDM being affected
        closeModal: React.PropTypes.func.isRequired, // Function to call to close the modal
        updateOmimId: React.PropTypes.func.isRequired // Function to call when we have a new OMIM ID
    },

    // Form content validation
    validateForm: function() {
        // Start with default validation
        var valid = this.validateDefault();

        // Valid if the field has only 10 or fewer digits
        if (valid) {
            valid = this.getFormValue('omimid').match(/^[0-9]{1,10}$/i);
            if (!valid) {
                this.setFormErrors('omimid', 'Only numbers allowed');
            }
        }
        return valid;
    },

    // Called when the modal form’s submit button is clicked. Handles validation and updating the OMIM in the GDM.
    submitForm: function(e) {
        e.preventDefault(); e.stopPropagation(); // Don't run through HTML submit handler
        this.saveFormValue('omimid', this.refs.omimid.getValue());
        if (this.validateForm()) {
            // Form is valid -- we have a good OMIM ID. Close the modal and update the current GDM's OMIM ID
            this.props.closeModal();
            var enteredOmimId = this.getFormValue('omimid');
                this.props.updateOmimId(this.props.gdm.uuid, enteredOmimId);
        }
    },

    // Called when the modal form's cancel button is clicked. Just closes the modal like
    // nothing happened.
    cancelForm: function(e) {
        e.preventDefault(); e.stopPropagation(); // Don't run through HTML submit handler
        this.props.closeModal();
    },

    render: function() {
        return (
            <Form submitHandler={this.submitForm} formClassName="form-std">

                    <Input type="text" ref="omimid" label="Enter an OMIM ID"
                        error={this.getFormError('omimid')} clearError={this.clrFormErrors.bind(null, 'omim')}
                        labelClassName="control-label" groupClassName="form-group" required />

                    <Input type="cancel" inputClassName="btn-default btn-inline-spacer" cancelHandler={this.cancelForm} />
                    <Input type="submit" inputClassName="btn-primary btn-inline-spacer" title="Add/Change OMIM ID" />

            </Form>
        );
    }
});

// Display the curator data of the curation data
var CuratorRecordHeader = React.createClass({
    propTypes: {
        gdm: React.PropTypes.object // GDM with curator data to display
    },

    // Return the latest annotation in the given GDM
    findLatestAnnotation: function() {
        var annotations = this.props.gdm.annotations;
        var latestAnnotation = {};
        var latestTime = 0;
        if (annotations && annotations.length) {
            annotations.forEach(function(annotation) {
                // Get Unix timestamp version of annotation's time and compare against the saved version.
                var time = moment(annotation.dateTime).format('x');
                if (latestTime < time) {
                    latestAnnotation = annotation;
                    latestTime = time;
                }
            });
        }
        return latestAnnotation;
    },

    render: function() {
        var gdm = this.props.gdm;
        var annotationOwners = _.uniq(gdm.annotations.map(function(annotation) {
            return annotation.owner;
        })).sort();
        var latestAnnotation = this.findLatestAnnotation();

        return (

                    {gdm ?

Status:

{gdm.status}

Creator:

{gdm.owner} – {moment(gdm.dateTime).format('YYYY MMM DD, h:mm a')}

                            {annotationOwners && annotationOwners.length ?

Participants:

                                        {annotationOwners.map(function(owner, i) {
                                            return (

                                                    {i > 0 ? ', ' : ''}
                                                    {owner}

                                            );
                                        })}

Last edited:

{latestAnnotation.owner} — {moment(latestAnnotation.dateTime).format('YYYY MMM DD, h:mm a')}

                            : null}

                    : null}

        );
    }
});

// Display buttons to bring up the PubMed and doi-specified web pages.
// For now, no doi is available
var PmidDoiButtons = module.exports.PmidDoiButtons = React.createClass({
    propTypes: {
        pmid: React.PropTypes.string // Numeric string PMID for PubMed page
    },

    render: function() {
        var pmid = this.props.pmid;

        return (

                {pmid ? PubMed : null}

        );
    }
});
<|endoftext|>


<commit_before>/**
 * On SVG error, load PNG fallback
 * @return {null}
 */
jQuery('img').error(function() {
	var src = jQuery(this).attr('src');
	if ( src.search('.svg') != -1 ) {
		console.log('It worked!');
		src = src.replace('.svg', '.png');
		jQuery(this).attr('src', src);
	}
});<commit_msg>Removed unnecessary console.log.<commit_after>/**
 * On SVG error, load PNG fallback
 * @return {null}
 */
jQuery('img').error(function() {
	var src = jQuery(this).attr('src');
	if ( src.search('.svg') != -1 ) {
		src = src.replace('.svg', '.png');
		jQuery(this).attr('src', src);
	}
});
<|endoftext|>