<commit_before>define([
    'jquery',
    'backbone',
    'arches',
    'models/concept',
    'models/value',
    'models/concept-parents',
    'views/rdm/modals/value-form',
    'views/rdm/modals/related-concept-form',
    'views/rdm/modals/related-member-form',
    'views/rdm/modals/manage-parent-form',
    'views/rdm/modals/import-concept-form',
    'views/rdm/modals/add-child-form',
    'views/rdm/modals/add-image-form',
    'views/concept-graph',
    'viewmodels/alert',
], function($, Backbone, arches, ConceptModel, ValueModel, ConceptParentModel, ValueEditor, RelatedConcept, RelatedMember, ManageParentForm, ImportConcept, AddChildForm, AddImageForm, ConceptGraph, AlertViewModel) {
    return Backbone.View.extend({
        events: {
            'click .concept-report-content *[data-action="viewconcept"]': 'conceptSelected',
            'click .concept-report-content *[data-action="viewddconcept"]': 'dropdownConceptSelected',
            'click .concept-report-content *[data-action="delete-relationship"]': 'deleteClicked',
            'click .concept-report-content *[data-action="delete-value"]': 'deleteClicked',
            'click .concept-report-content *[data-action="delete-concept"]': 'deleteClicked',
            'click a.add-image-link': 'addImageClicked',
            'click a.edit-value': 'editValueClicked',
            'click .confirm-delete-yes': 'deleteConfirmed',
            'click a[data-toggle="#related-concept-form"]': 'addRelatedConceptClicked',
            'click a[data-toggle="#related-member-form"]': 'addRelatedMemberClicked',
            'click a[data-toggle="#add-concept-form"]': 'addChildConcept',
            'click a[data-toggle="#add-top-concept-form"]': 'addChildConcept',
            'click a[data-toggle="#manage-parent-form"]': 'manageParentConcepts',
            'click a[data-toggle="#import-concept-form"]': 'importConcept',
            'click a[data-toggle="#make-collection"]': 'makeCollection',
        },

        initialize: function(options) {
            this.viewModel = options.viewModel;
            this.render();
        },

        render: function() {
            var self = this;
            var conceptid = this.model.get('id');
            var showGraph = self.$el.find(".concept-graph").is(":visible");

            self.$el.find('.concept-report-loading').removeClass('hidden');
            self.$el.find('.concept-report-content').addClass('hidden');

            if (this.xhr){
                this.xhr.abort();
            }

            this.xhr = $.ajax({
                url: arches.urls.concept.replace('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', conceptid),
                data: {
                    'f': 'html',
                    'mode': this.mode
                },
                success: function(response) {
                    self.$el.find('.concept-report-loading').addClass('hidden');
                    self.$el.html(response);

                    var data = self.$el.find('div[name="modeldata"]').data();
                    self.model.set(data);

                    if (self.model.get('id')) {
                        if (self.$el.find(".concept-graph").length > 0) {
                            //Toggle Concept Heirarchy.
                            self.$el.find(".graph-toggle").click(function(){
                                self.$el.find(".concept-tree").toggle(300);
                                self.$el.find(".concept-graph").toggle(300);
                                self.$el.find(".graph-toggle").toggle();
                            });
                            new ConceptGraph({
                                el: self.$el.find(".concept-graph")
                            });
                            if (showGraph) {
                                self.$el.find(".graph-toggle").toggle();
                                self.$el.find(".concept-tree").toggle(0);
                                self.$el.find(".concept-graph").toggle(0);
                            }
                        }
                    }
                }
            });
        },

        deleteClicked: function(e) {
            var self = this;
            var data = $(e.target).data();

            this.confirm_delete_modal = this.$el.find('.confirm-delete-modal');
            this.confirm_delete_modal_yes = this.confirm_delete_modal.find('.confirm-delete-yes');
            this.confirm_delete_modal_yes.removeAttr('disabled');
            this.confirm_delete_modal_yes.data('id', data.id);
            this.confirm_delete_modal_yes.data('nodetype', data.nodetype);
            this.confirm_delete_modal_yes.data('action', data.action);
            this.confirm_delete_modal_yes.data('category', data.category);

            this.confirm_delete_modal.find('.modal-title').text($(e.target).attr('title'));
            this.confirm_delete_modal.find('.modal-body [name="warning-text"]').text(data.message);
            this.confirm_delete_modal.find('.modal-body [name="additional-info"]').text('');
            this.confirm_delete_modal.modal('show');

            if (data.action === 'delete-concept'){
                this.confirm_delete_modal_yes.attr('disabled', 'disabled');
                $.ajax({
                    url: arches.urls.confirm_delete.replace('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', data.id),
                    success: function(response) {
                        self.confirm_delete_modal_yes.removeAttr('disabled');
                        self.confirm_delete_modal.find('.modal-body [name="additional-info"]').html(response);
                    }
                });
            }

        },

        conceptSelected: function(e) {
            var data = $(e.target).data();
            this.trigger('conceptSelected', data.conceptid);
        },

        dropdownConceptSelected: function(e) {
            var data = $(e.target).data();
            this.trigger('dropdownConceptSelected', data.conceptid);
        },

        addChildConcept: function(e){
            this.model.reset();
            var form = new AddChildForm({
                el: $('#add-child-form')[0],
                model: this.model
            });

            form.modal.modal('show');
        },

        addRelatedConceptClicked: function(e){
            this.model.reset();
            var modal = new RelatedConcept({
                el: $('#related-concept-form')[0],
                model: this.model
            });
            modal.modal.modal('show');
        },

        addRelatedMemberClicked: function(e){
            this.model.reset();
            var modal = new RelatedMember({
                el: $('#related-member-form')[0],
                model: this.model
            });
            modal.modal.modal('show');
        },

        manageParentConcepts: function(e){
            var self = this;
            var parentmodel = new ConceptParentModel();
            parentmodel.set('id', this.model.get('id'));

            var modal = new ManageParentForm({
                el: $('#manage-parent-form')[0],
                model: parentmodel
            });
            modal.modal.modal('show');

            parentmodel.on({
                'save': function(){
                    self.trigger('parentsChanged');
                }
            });
        },

        makeCollection: function(e){
            this.model.makeCollection(function(response, status){
                if(status === 'success'){
                    this.viewModel.alert(new AlertViewModel('ep-alert-blue', response.responseJSON.message.title, response.responseJSON.message.text));
                }
                if(status === 'error'){
                    this.viewModel.alert(new AlertViewModel('ep-alert-red', response.responseJSON.message.title, response.responseJSON.message.text));
                }
            }, this);
        },

        importConcept: function(e){
            var self = this;
            this.model.reset();
            var modal = new ImportConcept({
                el: $('#import-concept-form')[0],
                model: this.model
            });
            modal.modal.modal('show');

            modal.on({
                'conceptsImported': function(){
                    self.trigger('conceptsImported');
                }
            });
        },

        addImageClicked: function (e) {
            this.model.reset();
            var self = this;
            var form = new AddImageForm({
                el: this.$el.find('#add-image-form')[0],
                model: this.model
            });

            form.on('dataChanged', function () {
                self.render();
            });
        },

        editValueClicked: function(e) {
            this.model.reset();
            var data = $.extend({
                    conceptid: this.model.get('id')
                },
                $(e.target).data()
            );
            this.model.set('values', [new ValueModel(data)]);
            var editor = new ValueEditor({
                el: this.$el.find('#value-form')[0],
                model: this.model
            });
        },

        deleteConfirmed: function(e) {
            var self = this;
            var data = $(e.target).data();
            var modal = self.$el.find('.confirm-delete-modal');
            var title = modal.find('.modal-title').text();
            this.model.reset();

            if (data.action === 'delete-concept') {
                modal.find('h4').text(' ' + title);
                modal.find('.modal-title').addClass('loading');

                model = new ConceptModel(data)
                self.model.set('subconcepts', [model]);

                self.model.delete(function(response, status){
                    modal.find('h4').text(title);
                    modal.find('.modal-title').removeClass('loading');
                    modal.modal('hide');
                    $('.modal-backdrop.fade.in').remove();  // a hack for now
                    if(!!response.responseJSON.in_use){
                        self.viewModel.alert(new AlertViewModel('ep-alert-blue', response.responseJSON.message.title, response.responseJSON.message.text));
                    }
                }, self);
            }else{
                modal.on('hidden.bs.modal', function () {
                    var model;

                    if (data.action === 'delete-value') {
                        model = new ValueModel(data);
                        model.delete(self.render, self);
                    }
                    if (data.action === 'delete-relationship') {
                        model = new ConceptModel(data);
                        self.model.set('relatedconcepts', [model]);
                        self.model.delete();
                    }

                });
                modal.modal('hide');
            }
        }
    });
});<commit_msg>#1412 Change response object structure<commit_after>define([
    'jquery',
    'backbone',
    'arches',
    'models/concept',
    'models/value',
    'models/concept-parents',
    'views/rdm/modals/value-form',
    'views/rdm/modals/related-concept-form',
    'views/rdm/modals/related-member-form',
    'views/rdm/modals/manage-parent-form',
    'views/rdm/modals/import-concept-form',
    'views/rdm/modals/add-child-form',
    'views/rdm/modals/add-image-form',
    'views/concept-graph',
    'viewmodels/alert',
], function($, Backbone, arches, ConceptModel, ValueModel, ConceptParentModel, ValueEditor, RelatedConcept, RelatedMember, ManageParentForm, ImportConcept, AddChildForm, AddImageForm, ConceptGraph, AlertViewModel) {
    return Backbone.View.extend({
        events: {
            'click .concept-report-content *[data-action="viewconcept"]': 'conceptSelected',
            'click .concept-report-content *[data-action="viewddconcept"]': 'dropdownConceptSelected',
            'click .concept-report-content *[data-action="delete-relationship"]': 'deleteClicked',
            'click .concept-report-content *[data-action="delete-value"]': 'deleteClicked',
            'click .concept-report-content *[data-action="delete-concept"]': 'deleteClicked',
            'click a.add-image-link': 'addImageClicked',
            'click a.edit-value': 'editValueClicked',
            'click .confirm-delete-yes': 'deleteConfirmed',
            'click a[data-toggle="#related-concept-form"]': 'addRelatedConceptClicked',
            'click a[data-toggle="#related-member-form"]': 'addRelatedMemberClicked',
            'click a[data-toggle="#add-concept-form"]': 'addChildConcept',
            'click a[data-toggle="#add-top-concept-form"]': 'addChildConcept',
            'click a[data-toggle="#manage-parent-form"]': 'manageParentConcepts',
            'click a[data-toggle="#import-concept-form"]': 'importConcept',
            'click a[data-toggle="#make-collection"]': 'makeCollection',
        },

        initialize: function(options) {
            this.viewModel = options.viewModel;
            this.render();
        },

        render: function() {
            var self = this;
            var conceptid = this.model.get('id');
            var showGraph = self.$el.find(".concept-graph").is(":visible");

            self.$el.find('.concept-report-loading').removeClass('hidden');
            self.$el.find('.concept-report-content').addClass('hidden');

            if (this.xhr){
                this.xhr.abort();
            }

            this.xhr = $.ajax({
                url: arches.urls.concept.replace('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', conceptid),
                data: {
                    'f': 'html',
                    'mode': this.mode
                },
                success: function(response) {
                    self.$el.find('.concept-report-loading').addClass('hidden');
                    self.$el.html(response);

                    var data = self.$el.find('div[name="modeldata"]').data();
                    self.model.set(data);

                    if (self.model.get('id')) {
                        if (self.$el.find(".concept-graph").length > 0) {
                            //Toggle Concept Heirarchy.
                            self.$el.find(".graph-toggle").click(function(){
                                self.$el.find(".concept-tree").toggle(300);
                                self.$el.find(".concept-graph").toggle(300);
                                self.$el.find(".graph-toggle").toggle();
                            });
                            new ConceptGraph({
                                el: self.$el.find(".concept-graph")
                            });
                            if (showGraph) {
                                self.$el.find(".graph-toggle").toggle();
                                self.$el.find(".concept-tree").toggle(0);
                                self.$el.find(".concept-graph").toggle(0);
                            }
                        }
                    }
                }
            });
        },

        deleteClicked: function(e) {
            var self = this;
            var data = $(e.target).data();

            this.confirm_delete_modal = this.$el.find('.confirm-delete-modal');
            this.confirm_delete_modal_yes = this.confirm_delete_modal.find('.confirm-delete-yes');
            this.confirm_delete_modal_yes.removeAttr('disabled');
            this.confirm_delete_modal_yes.data('id', data.id);
            this.confirm_delete_modal_yes.data('nodetype', data.nodetype);
            this.confirm_delete_modal_yes.data('action', data.action);
            this.confirm_delete_modal_yes.data('category', data.category);

            this.confirm_delete_modal.find('.modal-title').text($(e.target).attr('title'));
            this.confirm_delete_modal.find('.modal-body [name="warning-text"]').text(data.message);
            this.confirm_delete_modal.find('.modal-body [name="additional-info"]').text('');
            this.confirm_delete_modal.modal('show');

            if (data.action === 'delete-concept'){
                this.confirm_delete_modal_yes.attr('disabled', 'disabled');
                $.ajax({
                    url: arches.urls.confirm_delete.replace('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', data.id),
                    success: function(response) {
                        self.confirm_delete_modal_yes.removeAttr('disabled');
                        self.confirm_delete_modal.find('.modal-body [name="additional-info"]').html(response);
                    }
                });
            }

        },

        conceptSelected: function(e) {
            var data = $(e.target).data();
            this.trigger('conceptSelected', data.conceptid);
        },

        dropdownConceptSelected: function(e) {
            var data = $(e.target).data();
            this.trigger('dropdownConceptSelected', data.conceptid);
        },

        addChildConcept: function(e){
            this.model.reset();
            var form = new AddChildForm({
                el: $('#add-child-form')[0],
                model: this.model
            });

            form.modal.modal('show');
        },

        addRelatedConceptClicked: function(e){
            this.model.reset();
            var modal = new RelatedConcept({
                el: $('#related-concept-form')[0],
                model: this.model
            });
            modal.modal.modal('show');
        },

        addRelatedMemberClicked: function(e){
            this.model.reset();
            var modal = new RelatedMember({
                el: $('#related-member-form')[0],
                model: this.model
            });
            modal.modal.modal('show');
        },

        manageParentConcepts: function(e){
            var self = this;
            var parentmodel = new ConceptParentModel();
            parentmodel.set('id', this.model.get('id'));

            var modal = new ManageParentForm({
                el: $('#manage-parent-form')[0],
                model: parentmodel
            });
            modal.modal.modal('show');

            parentmodel.on({
                'save': function(){
                    self.trigger('parentsChanged');
                }
            });
        },

        makeCollection: function(e){
            this.model.makeCollection(function(response, status){
                if(status === 'success'){
                    this.viewModel.alert(new AlertViewModel('ep-alert-blue', response.responseJSON.title, response.responseJSON.message));
                }
                if(status === 'error'){
                    this.viewModel.alert(new AlertViewModel('ep-alert-red', response.responseJSON.message.title, response.responseJSON.message.text));
                }
            }, this);
        },

        importConcept: function(e){
            var self = this;
            this.model.reset();
            var modal = new ImportConcept({
                el: $('#import-concept-form')[0],
                model: this.model
            });
            modal.modal.modal('show');

            modal.on({
                'conceptsImported': function(){
                    self.trigger('conceptsImported');
                }
            });
        },

        addImageClicked: function (e) {
            this.model.reset();
            var self = this;
            var form = new AddImageForm({
                el: this.$el.find('#add-image-form')[0],
                model: this.model
            });

            form.on('dataChanged', function () {
                self.render();
            });
        },

        editValueClicked: function(e) {
            this.model.reset();
            var data = $.extend({
                    conceptid: this.model.get('id')
                },
                $(e.target).data()
            );
            this.model.set('values', [new ValueModel(data)]);
            var editor = new ValueEditor({
                el: this.$el.find('#value-form')[0],
                model: this.model
            });
        },

        deleteConfirmed: function(e) {
            var self = this;
            var data = $(e.target).data();
            var modal = self.$el.find('.confirm-delete-modal');
            var title = modal.find('.modal-title').text();
            this.model.reset();

            if (data.action === 'delete-concept') {
                modal.find('h4').text(' ' + title);
                modal.find('.modal-title').addClass('loading');

                model = new ConceptModel(data)
                self.model.set('subconcepts', [model]);

                self.model.delete(function(response, status){
                    modal.find('h4').text(title);
                    modal.find('.modal-title').removeClass('loading');
                    modal.modal('hide');
                    $('.modal-backdrop.fade.in').remove();  // a hack for now
                    if(!!response.responseJSON.in_use){
                        self.viewModel.alert(new AlertViewModel('ep-alert-blue', response.responseJSON.message.title, response.responseJSON.message.text));
                    }
                }, self);
            }else{
                modal.on('hidden.bs.modal', function () {
                    var model;

                    if (data.action === 'delete-value') {
                        model = new ValueModel(data);
                        model.delete(self.render, self);
                    }
                    if (data.action === 'delete-relationship') {
                        model = new ConceptModel(data);
                        self.model.set('relatedconcepts', [model]);
                        self.model.delete();
                    }

                });
                modal.modal('hide');
            }
        }
    });
});<|endoftext|>


<commit_before>class ValidationError extends Error {

    constructor(validation) {
        super(ValidationError.message);
        this.validation = validation;
        // We don't want to capture the Stack, no useful information there
        this.stack = "";
    }

    // Pretty print the error
    inspect(depth, opts) {

        let validationString = JSON.stringify(this.validation, null, ' ')
            // removes quotes from prop names
            .replace(/\"([^(\")"]+)\":/g,"$1:");

        // ident properly for final string
        const [first, ...rest] = validationString.split('\n');
        const formattedRest = rest.map(s => `  ${s}`);
        validationString = [first, ...formattedRest].join('\n');

        return `{ ${this.toString()}\n  validation: ${validationString}\n}`;
    }

    toString() {
        return `${this.constructor.name}: ${ValidationError.message}`;
    };

    // We don't want to capture the Stack, no useful information there
    captureStackTrace () {}
}

ValidationError.message = "Modern Validator encountered validation error(s).";

module.exports = ValidationError;<commit_msg>remove useless override<commit_after>class ValidationError extends Error {

    constructor(validation) {
        super(ValidationError.message);
        this.validation = validation;
        // We don't want to capture the Stack, no useful information there
        this.stack = "";
    }

    // Pretty print the error
    inspect(depth, opts) {

        let validationString = JSON.stringify(this.validation, null, ' ')
            // removes quotes from prop names
            .replace(/\"([^(\")"]+)\":/g,"$1:");

        // ident properly for final string
        const [first, ...rest] = validationString.split('\n');
        const formattedRest = rest.map(s => `  ${s}`);
        validationString = [first, ...formattedRest].join('\n');

        return `{ ${this.toString()}\n  validation: ${validationString}\n}`;
    }

    toString() {
        return `${this.constructor.name}: ${ValidationError.message}`;
    };
}

ValidationError.message = "Modern Validator encountered validation error(s).";

module.exports = ValidationError;<|endoftext|>


<commit_before>import React, { Component } from 'react';
import ReactSwipe from 'react-swipe';
import { Button } from 'react-bootstrap';

import history from './history';

export default class VenueInfoslider extends Component {

  constructor(props) {
    super(props);
    this.state = {
      VenuesData: props.VenuesData,
      currentVenueKey: props.currentVenueKey,
      startSlide: 0
    };
    console.log('initial Props');
    console.log(props.VenuesData);

    // this.updateWindowDimensions = this.updateWindowDimensions.bind(this);
  }
  val2key(val, markers_array){
    for (var key in markers_array) {
      let array_val = markers_array[key];
      if(array_val.venueId === val){
          return key;
          break;
      }
    }
  }

  componentWillReceiveProps(nextProps) {
    console.log('nextProps.VenuesData');
    console.log(nextProps.VenuesData);
    this.setState({ VenuesData: nextProps.VenuesData });
    let currentVenueSliderIndex = this.val2key(this.state.currentVenueKey, nextProps.VenuesData);
    this.setState({ startSlide: currentVenueSliderIndex });

  }

  showMapDirections(e, venue_key)
  {
    alert("Redirect to Google Maps!");
  }

  showCameraScreen(e, venue_key)
  {
    history.replace('/camera',{venue_key:venue_key});
  }

  goTo(route) {
    // alert(route);
    this.props.history.replace(`/${route}`)
  }

  goToPreviousSlide()
  {
    console.log("Go Previous");
    if(this.swiper)
    {
      console.log("Swiper initialised. Going Previous");
      this.swiper.prev();
    }
    else
    {
      console.log("No Swiper initialised");
    }
  }
  goToNextSlide()
  {
    console.log("Go Next");
    if(this.swiper)
    {
      console.log("Swiper initialised. Going Next");
      this.swiper.next();
    }
    else
    {
      console.log("No Swiper initialised");
    }
  }

  render() {
    if(!this.state.VenuesData.length)
    {
      return (

          Loading Venue Info please wait

      );
    }

    return (

        <Button
          bsStyle="primary"
          className="btn-margin"
          onClick={this.goToPreviousSlide.bind(this)}
        >
          Previous
        </Button>
        <ReactSwipe
          key={this.state.VenuesData.length}
          ref={ref => { this.swiper = ref; }}
          swipeOptions={{continuous: true, startSlide: this.state.startSlide}}
        >
        {
          this.state.VenuesData.map(venue => (

{venue.title}

{venue.description}

                    <Button
                      bsStyle="primary"
                      className="btn-margin"
                      onClick={e => this.showCameraScreen(e, venue.venueID)}
                    >
                      CheckIn here
                    </Button>

                    <Button
                      bsStyle="primary"
                      className="btn-margin"
                      onClick={e => this.showMapDirections(e, venue.venueID)}
                    >
                      Get directions to this venue
                    </Button>

          ))
        }
        </ReactSwipe>
        <Button
          bsStyle="primary"
          className="btn-margin"
          onClick={this.goToNextSlide.bind(this)}
        >
          Next
        </Button>

    );
  }
}<commit_msg>VenueScreen start slide issue solved<commit_after>import React, { Component } from 'react';
import ReactSwipe from 'react-swipe';
import { Button } from 'react-bootstrap';

import history from './history';

export default class VenueInfoslider extends Component {

  constructor(props) {
    super(props);
    let currentVenueSliderIndex = this.val2key(props.currentVenueKey, props.VenuesData);
    this.state = {
      VenuesData: props.VenuesData,
      currentVenueKey: props.currentVenueKey,
      startSlide: currentVenueSliderIndex
    };
    console.log('initial Props');
    console.log(props.VenuesData);

    // this.updateWindowDimensions = this.updateWindowDimensions.bind(this);
  }
  val2key(val, markers_array){
    console.log("Input - markers_array");
    console.log(markers_array);
    for (var key in markers_array) {
      let array_val = markers_array[key];
      // console.log("Val = ");
      // console.log(val);
      // console.log("Venue id - ");
      // console.log(array_val.venueID);
      if(array_val.venueID === val){
          console.log("Returning final key - ");
          console.log(key);
          let int_key = parseInt(key);
          if(int_key==NaN)
          {
            return 0;
          }
          return int_key;
      }
    }
  }

  componentWillReceiveProps(nextProps) {
    console.log('nextProps.VenuesData');
    console.log(nextProps.VenuesData);
    let currentVenueSliderIndex = this.val2key(this.state.currentVenueKey, nextProps.VenuesData);
    console.log('currentVenueSliderIndex');
    console.log(currentVenueSliderIndex);
    this.setState({ startSlide: currentVenueSliderIndex });
    this.setState({ VenuesData: nextProps.VenuesData });

  }

  showMapDirections(e, venue_key)
  {
    alert("Redirect to Google Maps!");
  }

  showCameraScreen(e, venue_key)
  {
    history.replace('/camera',{venue_key:venue_key});
  }

  goTo(route) {
    // alert(route);
    this.props.history.replace(`/${route}`)
  }

  goToPreviousSlide()
  {
    console.log("Go Previous");
    if(this.swiper)
    {
      console.log("Swiper initialised. Going Previous");
      this.swiper.prev();
    }
    else
    {
      console.log("No Swiper initialised");
    }
  }
  goToNextSlide()
  {
    console.log("Go Next");
    if(this.swiper)
    {
      console.log("Swiper initialised. Going Next");
      this.swiper.next();
    }
    else
    {
      console.log("No Swiper initialised");
    }
  }

  render() {
    if(!this.state.VenuesData.length)
    {
      return (

          Loading Venue Info please wait

      );
    }

    return (

        <Button
          bsStyle="primary"
          className="btn-margin"
          onClick={this.goToPreviousSlide.bind(this)}
        >
          Previous
        </Button>
        <ReactSwipe
          key={this.state.VenuesData.length}
          ref={ref => { this.swiper = ref; }}
          swipeOptions={{continuous: true, startSlide: this.state.startSlide}}
        >
        {
          this.state.VenuesData.map(venue => (

{venue.title}

{venue.description}

                    <Button
                      bsStyle="primary"
                      className="btn-margin"
                      onClick={e => this.showCameraScreen(e, venue.venueID)}
                    >
                      CheckIn here
                    </Button>

                    <Button
                      bsStyle="primary"
                      className="btn-margin"
                      onClick={e => this.showMapDirections(e, venue.venueID)}
                    >
                      Get directions to this venue
                    </Button>

          ))
        }
        </ReactSwipe>
        <Button
          bsStyle="primary"
          className="btn-margin"
          onClick={this.goToNextSlide.bind(this)}
        >
          Next
        </Button>

    );
  }
}<|endoftext|>


<commit_before>'use strict';

var srlog = SIREPO.srlog;
var srdbg = SIREPO.srdbg;

SIREPO.appFieldEditors = [
    '
',
      '

',
    '
',
    '
',
      '

',
    '
',
    '
',
      '

',
      '
{{warningText}}
',
    '
',
    '
',
      '

',
    '
',
    '
',
      '

',
    '
',
].join('');

SIREPO.app.factory('webconService', function(appState) {
    var self = {};
    self.analysisParameters = null;

    self.setAnalysisParameters = function(columnInfo) {
        self.analysisParameters = columnInfo;
    };

    return self;
});

SIREPO.app.controller('AnalysisController', function (appState, frameCache, panelState, persistentSimulation, webconService, $scope, $timeout) {
    var self = this;

    function handleStatus(data) {
        if (appState.models.analysisData.file) {
            frameCache.setFrameCount(data.frameCount);
            if (data.columnInfo) {
                webconService.setAnalysisParameters(data.columnInfo);
            }
        }
    }

    self.hasFile = function() {
        return appState.isLoaded() && appState.applicationState().analysisData.file;
    };

    self.isFitterConfigured = function() {
        return appState.models.fitter.equation && appState.models.fitter.variable && appState.models.fitter.parameters;
    };

    appState.whenModelsLoaded($scope, function() {
        $scope.$on('analysisData.changed', function() {
            frameCache.setFrameCount(0);
            if (appState.models.analysisData.file) {
                self.simState.saveAndRunSimulation('analysisData');
            }
        });
    });

    self.simState = persistentSimulation.initSimulationState($scope, 'animation', handleStatus, {
        analysisAnimation: [SIREPO.ANIMATION_ARGS_VERSION + '1', 'x', 'y1', 'y2', 'y3', 'startTime'],
    });
});

SIREPO.app.directive('analysisParameter', function(webconService) {
    return {
        restrict: 'A',
        scope: {
            model: '=',
            field: '=',
            isOptional: '@',
        },
        template: [
            '<select class="form-control" data-ng-model="model[field]" data-ng-options="item[0] as item[1] for item in parameterValues()"></select>',
        ].join(''),
        controller: function($scope) {
            var analysisParameters, parameterValues;
            $scope.parameterValues = function() {
                if (analysisParameters == webconService.analysisParameters) {
                    return parameterValues;
                }
                analysisParameters = webconService.analysisParameters;
                parameterValues = [];
                var visited = {};
                analysisParameters.names.forEach(function(name, idx) {
                    // skip duplicate columns
                    if (! visited[name]) {
                        parameterValues.push(['' + idx, name]);
                        visited[name] = true;
                    }
                });
                parameterValues.sort(function(a, b) {
                    return a[1].localeCompare(b[1]);
                });
                if ($scope.isOptional) {
                    parameterValues.unshift(['none', 'None']);
                }
                return parameterValues;
            };
        },
    };
});

SIREPO.app.directive('appFooter', function() {
    return {
	restrict: 'A',
	scope: {
            nav: '=appFooter',
	},
        template: [
            '

',
	].join(''),
    };
});

SIREPO.app.directive('appHeader', function(appState, panelState) {
    return {
	restrict: 'A',
	scope: {
            nav: '=appHeader',
	},
        template: [
            '

',
            '

',
            '
',
              '<app-header-right-sim-loaded>',
		'
',
                  '
 Analysis
',
		'
',
              '</app-header-right-sim-loaded>',
              '<app-settings>',
		//  '
App-specific setting item
',
              '</app-settings>',
              '<app-header-right-sim-list>',
              '</app-header-right-sim-list>',
            '
',
	].join(''),
    };
});

SIREPO.app.directive('equation', function(appState, webconService) {
    return {
        scope: {
            model: '=',
            field: '='
        },
        template: [
            '
',
                '<input type="text" data-ng-model="model[field]" class="form-control" required>',
            '
',
        ].join(''),
        controller: function ($scope) {
            $scope.webconservice = webconService;

            srdbg('eq', $scope.model[$scope.field], 'tokens', tokenizeEquation());

            function tokenizeEquation() {
                var reserved = ['sin', 'cos', 'tan', 'csc', 'sec', 'cot', 'exp', 'abs'];
                var tokens = $scope.model[$scope.field].split(/[-+*/^|%().0-9\s+]/)
                    .filter(function (t) {
                        return t.length > 0 && reserved.indexOf(t.toLowerCase()) < 0;
                });
                //tokens = tokens.filter(function (t) {
                //    return tokens.indexOf(t) === tokens.lastIndexOf(t);
                //});
                return tokens;
            }
        },
    };
});

SIREPO.app.directive('equationVariables', function() {
    return {
        restrict: 'A',
        scope: {
            field: '=',
            form: '=',
            isVariable: '<',
            model: '=',
        },
        template: [
            '
',
                '<input type="text" data-ng-model="model[field]" data-valid-variable-or-param="" class="form-control" required />',
            '
',
            '
 0">{{warningText}}
',
        ].join(''),
        controller: function($scope, $element) {
            var reserved = ['sin', 'cos', 'tan', 'abs'];

            $scope.equation = $scope.model.equation;
        },
    };
});

SIREPO.app.directive('fitReport', function(appState, mathRendering) {
    return {
        scope: {
            controller: '=parentController',
        },
        template: [
            '

',
            '
',
            '
',
        ].join(''),
        controller: function($scope) {

            $scope.$on('fitter.changed', function() {
                appState.saveChanges('fitReport', function () {
                });
            });
            $scope.$on('fitReport.changed', function() {
                var focusText = $('.focus-hint');
                var str = '';
            });

        },
    };
});<commit_msg>Removed logging<commit_after>'use strict';

var srlog = SIREPO.srlog;
var srdbg = SIREPO.srdbg;

SIREPO.appFieldEditors = [
    '
',
      '

',
    '
',
    '
',
      '

',
    '
',
    '
',
      '

',
      '
{{warningText}}
',
    '
',
    '
',
      '

',
    '
',
    '
',
      '

',
    '
',
].join('');

SIREPO.app.factory('webconService', function(appState) {
    var self = {};
    self.analysisParameters = null;

    self.setAnalysisParameters = function(columnInfo) {
        self.analysisParameters = columnInfo;
    };

    return self;
});

SIREPO.app.controller('AnalysisController', function (appState, frameCache, panelState, persistentSimulation, webconService, $scope, $timeout) {
    var self = this;

    function handleStatus(data) {
        if (appState.models.analysisData.file) {
            frameCache.setFrameCount(data.frameCount);
            if (data.columnInfo) {
                webconService.setAnalysisParameters(data.columnInfo);
            }
        }
    }

    self.hasFile = function() {
        return appState.isLoaded() && appState.applicationState().analysisData.file;
    };

    self.isFitterConfigured = function() {
        return appState.models.fitter.equation && appState.models.fitter.variable && appState.models.fitter.parameters;
    };

    appState.whenModelsLoaded($scope, function() {
        $scope.$on('analysisData.changed', function() {
            frameCache.setFrameCount(0);
            if (appState.models.analysisData.file) {
                self.simState.saveAndRunSimulation('analysisData');
            }
        });
    });

    self.simState = persistentSimulation.initSimulationState($scope, 'animation', handleStatus, {
        analysisAnimation: [SIREPO.ANIMATION_ARGS_VERSION + '1', 'x', 'y1', 'y2', 'y3', 'startTime'],
    });
});

SIREPO.app.directive('analysisParameter', function(webconService) {
    return {
        restrict: 'A',
        scope: {
            model: '=',
            field: '=',
            isOptional: '@',
        },
        template: [
            '<select class="form-control" data-ng-model="model[field]" data-ng-options="item[0] as item[1] for item in parameterValues()"></select>',
        ].join(''),
        controller: function($scope) {
            var analysisParameters, parameterValues;
            $scope.parameterValues = function() {
                if (analysisParameters == webconService.analysisParameters) {
                    return parameterValues;
                }
                analysisParameters = webconService.analysisParameters;
                parameterValues = [];
                var visited = {};
                analysisParameters.names.forEach(function(name, idx) {
                    // skip duplicate columns
                    if (! visited[name]) {
                        parameterValues.push(['' + idx, name]);
                        visited[name] = true;
                    }
                });
                parameterValues.sort(function(a, b) {
                    return a[1].localeCompare(b[1]);
                });
                if ($scope.isOptional) {
                    parameterValues.unshift(['none', 'None']);
                }
                return parameterValues;
            };
        },
    };
});

SIREPO.app.directive('appFooter', function() {
    return {
	restrict: 'A',
	scope: {
            nav: '=appFooter',
	},
        template: [
            '

',
	].join(''),
    };
});

SIREPO.app.directive('appHeader', function(appState, panelState) {
    return {
	restrict: 'A',
	scope: {
            nav: '=appHeader',
	},
        template: [
            '

',
            '

',
            '
',
              '<app-header-right-sim-loaded>',
		'
',
                  '
 Analysis
',
		'
',
              '</app-header-right-sim-loaded>',
              '<app-settings>',
		//  '
App-specific setting item
',
              '</app-settings>',
              '<app-header-right-sim-list>',
              '</app-header-right-sim-list>',
            '
',
	].join(''),
    };
});

SIREPO.app.directive('equation', function(appState, webconService) {
    return {
        scope: {
            model: '=',
            field: '='
        },
        template: [
            '
',
                '<input type="text" data-ng-model="model[field]" class="form-control" required>',
            '
',
        ].join(''),
        controller: function ($scope) {
            $scope.webconservice = webconService;

            //srdbg('eq', $scope.model[$scope.field], 'tokens', tokenizeEquation());

            function tokenizeEquation() {
                var reserved = ['sin', 'cos', 'tan', 'csc', 'sec', 'cot', 'exp', 'abs'];
                var tokens = $scope.model[$scope.field].split(/[-+*/^|%().0-9\s+]/)
                    .filter(function (t) {
                        return t.length > 0 && reserved.indexOf(t.toLowerCase()) < 0;
                });
                //tokens = tokens.filter(function (t) {
                //    return tokens.indexOf(t) === tokens.lastIndexOf(t);
                //});
                return tokens;
            }
        },
    };
});

SIREPO.app.directive('equationVariables', function() {
    return {
        restrict: 'A',
        scope: {
            field: '=',
            form: '=',
            isVariable: '<',
            model: '=',
        },
        template: [
            '
',
                '<input type="text" data-ng-model="model[field]" data-valid-variable-or-param="" class="form-control" required />',
            '
',
            '
 0">{{warningText}}
',
        ].join(''),
        controller: function($scope, $element) {
            var reserved = ['sin', 'cos', 'tan', 'abs'];

            $scope.equation = $scope.model.equation;
        },
    };
});

SIREPO.app.directive('fitReport', function(appState, mathRendering) {
    return {
        scope: {
            controller: '=parentController',
        },
        template: [
            '

',
            '
',
            '
',
        ].join(''),
        controller: function($scope) {

            $scope.$on('fitter.changed', function() {
                appState.saveChanges('fitReport', function () {
                });
            });
            $scope.$on('fitReport.changed', function() {
                var focusText = $('.focus-hint');
                var str = '';
            });

        },
    };
});<|endoftext|>


<commit_before>
/*
A cache for the left/right/top/bottom/width/height values for one or more elements.
Works with both offset (from topleft document) and position (from offsetParent).

options:
- els
- isHorizontal
- isVertical
*/
var CoordCache = FC.CoordCache = Class.extend({

	els: null, // jQuery set (assumed to be siblings)
	forcedOffsetParentEl: null, // options can override the natural offsetParent
	origin: null, // {left,top} position of offsetParent of els
	boundingRect: null, // constrain cordinates to this rectangle. {left,right,top,bottom} or null
	isHorizontal: false, // whether to query for left/right/width
	isVertical: false, // whether to query for top/bottom/height

	// arrays of coordinates (offsets from topleft of document)
	lefts: null,
	rights: null,
	tops: null,
	bottoms: null,

	constructor: function(options) {
		this.els = $(options.els);
		this.isHorizontal = options.isHorizontal;
		this.isVertical = options.isVertical;
		this.forcedOffsetParentEl = options.offsetParent ? $(options.offsetParent) : null;
	},

	// Queries the els for coordinates and stores them.
	// Call this method before using and of the get* methods below.
	build: function() {
		var offsetParentEl = this.forcedOffsetParentEl || this.els.eq(0).offsetParent();

		this.origin = offsetParentEl.offset();
		this.boundingRect = this.queryBoundingRect();

		if (this.isHorizontal) {
			this.buildElHorizontals();
		}
		if (this.isVertical) {
			this.buildElVerticals();
		}
	},

	// Destroys all internal data about coordinates, freeing memory
	clear: function() {
		this.origin = null;
		this.boundingRect = null;
		this.lefts = null;
		this.rights = null;
		this.tops = null;
		this.bottoms = null;
	},

	// Compute and return what the elements' bounding rectangle is, from the user's perspective.
	// Right now, only returns a rectangle if constrained by an overflow:scroll element.
	queryBoundingRect: function() {
		var scrollParentEl = getScrollParent(this.els.eq(0));

		if (!scrollParentEl.is(document)) {
			return getClientRect(scrollParentEl);
		}
	},

	// Populates the left/right internal coordinate arrays
	buildElHorizontals: function() {
		var lefts = [];
		var rights = [];

		this.els.each(function(i, node) {
			var el = $(node);
			var left = el.offset().left;
			var width = el.outerWidth();

			lefts.push(left);
			rights.push(left + width);
		});

		this.lefts = lefts;
		this.rights = rights;
	},

	// Populates the top/bottom internal coordinate arrays
	buildElVerticals: function() {
		var tops = [];
		var bottoms = [];

		this.els.each(function(i, node) {
			var el = $(node);
			var top = el.offset().top;
			var height = el.outerHeight();

			tops.push(top);
			bottoms.push(top + height);
		});

		this.tops = tops;
		this.bottoms = bottoms;
	},

	// Given a left offset (from document left), returns the index of the el that it horizontally intersects.
	// If no intersection is made, or outside of the boundingRect, returns undefined.
	getHorizontalIndex: function(leftOffset) {
		var boundingRect = this.boundingRect;
		var lefts = this.lefts;
		var rights = this.rights;
		var len = lefts.length;
		var i;

		if (!boundingRect || (leftOffset >= boundingRect.left && leftOffset < boundingRect.right)) {
			for (i = 0; i < len; i++) {
				if (leftOffset >= lefts[i] && leftOffset < rights[i]) {
					return i;
				}
			}
		}
	},

	// Given a top offset (from document top), returns the index of the el that it vertically intersects.
	// If no intersection is made, or outside of the boundingRect, returns undefined.
	getVerticalIndex: function(topOffset) {
		var boundingRect = this.boundingRect;
		var tops = this.tops;
		var bottoms = this.bottoms;
		var len = tops.length;
		var i;

		if (!boundingRect || (topOffset >= boundingRect.top && topOffset < boundingRect.bottom)) {
			for (i = 0; i < len; i++) {
				if (topOffset >= tops[i] && topOffset < bottoms[i]) {
					return i;
				}
			}
		}
	},

	// Gets the left offset (from document left) of the element at the given index
	getLeftOffset: function(leftIndex) {
		return this.lefts[leftIndex];
	},

	// Gets the left position (from offsetParent left) of the element at the given index
	getLeftPosition: function(leftIndex) {
		return this.lefts[leftIndex] - this.origin.left;
	},

	// Gets the right offset (from document left) of the element at the given index.
	// This value is NOT relative to the document's right edge, like the CSS concept of "right" would be.
	getRightOffset: function(leftIndex) {
		return this.rights[leftIndex];
	},

	// Gets the right position (from offsetParent left) of the element at the given index.
	// This value is NOT relative to the offsetParent's right edge, like the CSS concept of "right" would be.
	getRightPosition: function(leftIndex) {
		return this.rights[leftIndex] - this.origin.left;
	},

	// Gets the width of the element at the given index
	getWidth: function(leftIndex) {
		return this.rights[leftIndex] - this.lefts[leftIndex];
	},

	// Gets the top offset (from document top) of the element at the given index
	getTopOffset: function(topIndex) {
		return this.tops[topIndex];
	},

	// Gets the top position (from offsetParent top) of the element at the given position
	getTopPosition: function(topIndex) {
		return this.tops[topIndex] - this.origin.top;
	},

	// Gets the bottom offset (from the document top) of the element at the given index.
	// This value is NOT relative to the offsetParent's bottom edge, like the CSS concept of "bottom" would be.
	getBottomOffset: function(topIndex) {
		return this.bottoms[topIndex];
	},

	// Gets the bottom position (from the offsetParent top) of the element at the given index.
	// This value is NOT relative to the offsetParent's bottom edge, like the CSS concept of "bottom" would be.
	getBottomPosition: function(topIndex) {
		return this.bottoms[topIndex] - this.origin.top;
	},

	// Gets the height of the element at the given index
	getHeight: function(topIndex) {
		return this.bottoms[topIndex] - this.tops[topIndex];
	}

});
<commit_msg>CoordCache, safety against being called without being built<commit_after>
/*
A cache for the left/right/top/bottom/width/height values for one or more elements.
Works with both offset (from topleft document) and position (from offsetParent).

options:
- els
- isHorizontal
- isVertical
*/
var CoordCache = FC.CoordCache = Class.extend({

	els: null, // jQuery set (assumed to be siblings)
	forcedOffsetParentEl: null, // options can override the natural offsetParent
	origin: null, // {left,top} position of offsetParent of els
	boundingRect: null, // constrain cordinates to this rectangle. {left,right,top,bottom} or null
	isHorizontal: false, // whether to query for left/right/width
	isVertical: false, // whether to query for top/bottom/height

	// arrays of coordinates (offsets from topleft of document)
	lefts: null,
	rights: null,
	tops: null,
	bottoms: null,

	constructor: function(options) {
		this.els = $(options.els);
		this.isHorizontal = options.isHorizontal;
		this.isVertical = options.isVertical;
		this.forcedOffsetParentEl = options.offsetParent ? $(options.offsetParent) : null;
	},

	// Queries the els for coordinates and stores them.
	// Call this method before using and of the get* methods below.
	build: function() {
		var offsetParentEl = this.forcedOffsetParentEl || this.els.eq(0).offsetParent();

		this.origin = offsetParentEl.offset();
		this.boundingRect = this.queryBoundingRect();

		if (this.isHorizontal) {
			this.buildElHorizontals();
		}
		if (this.isVertical) {
			this.buildElVerticals();
		}
	},

	// Destroys all internal data about coordinates, freeing memory
	clear: function() {
		this.origin = null;
		this.boundingRect = null;
		this.lefts = null;
		this.rights = null;
		this.tops = null;
		this.bottoms = null;
	},

	// When called, if coord caches aren't built, builds them
	ensureBuilt: function() {
		if (!this.origin) {
			this.build();
		}
	},

	// Compute and return what the elements' bounding rectangle is, from the user's perspective.
	// Right now, only returns a rectangle if constrained by an overflow:scroll element.
	queryBoundingRect: function() {
		var scrollParentEl = getScrollParent(this.els.eq(0));

		if (!scrollParentEl.is(document)) {
			return getClientRect(scrollParentEl);
		}
	},

	// Populates the left/right internal coordinate arrays
	buildElHorizontals: function() {
		var lefts = [];
		var rights = [];

		this.els.each(function(i, node) {
			var el = $(node);
			var left = el.offset().left;
			var width = el.outerWidth();

			lefts.push(left);
			rights.push(left + width);
		});

		this.lefts = lefts;
		this.rights = rights;
	},

	// Populates the top/bottom internal coordinate arrays
	buildElVerticals: function() {
		var tops = [];
		var bottoms = [];

		this.els.each(function(i, node) {
			var el = $(node);
			var top = el.offset().top;
			var height = el.outerHeight();

			tops.push(top);
			bottoms.push(top + height);
		});

		this.tops = tops;
		this.bottoms = bottoms;
	},

	// Given a left offset (from document left), returns the index of the el that it horizontally intersects.
	// If no intersection is made, or outside of the boundingRect, returns undefined.
	getHorizontalIndex: function(leftOffset) {
		this.ensureBuilt();

		var boundingRect = this.boundingRect;
		var lefts = this.lefts;
		var rights = this.rights;
		var len = lefts.length;
		var i;

		if (!boundingRect || (leftOffset >= boundingRect.left && leftOffset < boundingRect.right)) {
			for (i = 0; i < len; i++) {
				if (leftOffset >= lefts[i] && leftOffset < rights[i]) {
					return i;
				}
			}
		}
	},

	// Given a top offset (from document top), returns the index of the el that it vertically intersects.
	// If no intersection is made, or outside of the boundingRect, returns undefined.
	getVerticalIndex: function(topOffset) {
		this.ensureBuilt();

		var boundingRect = this.boundingRect;
		var tops = this.tops;
		var bottoms = this.bottoms;
		var len = tops.length;
		var i;

		if (!boundingRect || (topOffset >= boundingRect.top && topOffset < boundingRect.bottom)) {
			for (i = 0; i < len; i++) {
				if (topOffset >= tops[i] && topOffset < bottoms[i]) {
					return i;
				}
			}
		}
	},

	// Gets the left offset (from document left) of the element at the given index
	getLeftOffset: function(leftIndex) {
		this.ensureBuilt();
		return this.lefts[leftIndex];
	},

	// Gets the left position (from offsetParent left) of the element at the given index
	getLeftPosition: function(leftIndex) {
		this.ensureBuilt();
		return this.lefts[leftIndex] - this.origin.left;
	},

	// Gets the right offset (from document left) of the element at the given index.
	// This value is NOT relative to the document's right edge, like the CSS concept of "right" would be.
	getRightOffset: function(leftIndex) {
		this.ensureBuilt();
		return this.rights[leftIndex];
	},

	// Gets the right position (from offsetParent left) of the element at the given index.
	// This value is NOT relative to the offsetParent's right edge, like the CSS concept of "right" would be.
	getRightPosition: function(leftIndex) {
		this.ensureBuilt();
		return this.rights[leftIndex] - this.origin.left;
	},

	// Gets the width of the element at the given index
	getWidth: function(leftIndex) {
		this.ensureBuilt();
		return this.rights[leftIndex] - this.lefts[leftIndex];
	},

	// Gets the top offset (from document top) of the element at the given index
	getTopOffset: function(topIndex) {
		this.ensureBuilt();
		return this.tops[topIndex];
	},

	// Gets the top position (from offsetParent top) of the element at the given position
	getTopPosition: function(topIndex) {
		this.ensureBuilt();
		return this.tops[topIndex] - this.origin.top;
	},

	// Gets the bottom offset (from the document top) of the element at the given index.
	// This value is NOT relative to the offsetParent's bottom edge, like the CSS concept of "bottom" would be.
	getBottomOffset: function(topIndex) {
		this.ensureBuilt();
		return this.bottoms[topIndex];
	},

	// Gets the bottom position (from the offsetParent top) of the element at the given index.
	// This value is NOT relative to the offsetParent's bottom edge, like the CSS concept of "bottom" would be.
	getBottomPosition: function(topIndex) {
		this.ensureBuilt();
		return this.bottoms[topIndex] - this.origin.top;
	},

	// Gets the height of the element at the given index
	getHeight: function(topIndex) {
		this.ensureBuilt();
		return this.bottoms[topIndex] - this.tops[topIndex];
	}

});
<|endoftext|>


<commit_before>export function isSameDay(date, opts) {
  let formatString = 'YYYY';
  const current = moment();
  const currentDate = moment(date, 'YYYY-MM-DD');

  if (opts && opts.anniversary) {
    if (current.format(formatString) <= currentDate.format(formatString)) return false;
  }

  formatString = 'MMDD';

  return current.format(formatString) === currentDate.format(formatString);
}

export function cakeday(createdAt) {
  if (Ember.isEmpty(createdAt)) return false;
  return isSameDay(createdAt, { anniversary: true });
}

export function cakedayBirthday(dateOfBirth) {
  if (Ember.isEmpty(dateOfBirth)) return false;
  return isSameDay(dateOfBirth);
}

export function cakedayTitle(user, currentUser) {
  if (isSameUser(user, currentUser)) {
    return I18n.t("user.anniversary.user_title");
  } else {
    return I18n.t("user.anniversary.title");
  }
}

export function cakedayBirthdayTitle(user, currentUser) {
  if (isSameUser(user, currentUser)) {
    return I18n.t("user.date_of_birth.user_title");
  } else {
    return I18n.t("user.date_of_birth.title");
  }
}

function isSameUser(user, currentUser) {
  if (!currentUser) return false;
  return user.get('id') === currentUser.get('id');
}
<commit_msg>FIX: Moment incorrectly using UTC as the locale.<commit_after>export function isSameDay(date, opts) {
  let formatString = 'YYYY';
  const current = moment();
  const currentDate = moment(date);

  if (opts && opts.anniversary) {
    if (current.format(formatString) <= currentDate.format(formatString)) return false;
  }

  formatString = 'MMDD';

  return current.format(formatString) === currentDate.format(formatString);
}

export function cakeday(createdAt) {
  if (Ember.isEmpty(createdAt)) return false;
  return isSameDay(createdAt, { anniversary: true });
}

export function cakedayBirthday(dateOfBirth) {
  if (Ember.isEmpty(dateOfBirth)) return false;
  return isSameDay(dateOfBirth);
}

export function cakedayTitle(user, currentUser) {
  if (isSameUser(user, currentUser)) {
    return I18n.t("user.anniversary.user_title");
  } else {
    return I18n.t("user.anniversary.title");
  }
}

export function cakedayBirthdayTitle(user, currentUser) {
  if (isSameUser(user, currentUser)) {
    return I18n.t("user.date_of_birth.user_title");
  } else {
    return I18n.t("user.date_of_birth.title");
  }
}

function isSameUser(user, currentUser) {
  if (!currentUser) return false;
  return user.get('id') === currentUser.get('id');
}
<|endoftext|>


<commit_before>(function () {
    angular
        .module('users')
        .controller('UserBrowsingController', UserBrowsingController);

    UserBrowsingController.$inject = [
        'UsersService',
        'Notification',
        'AuthService',
        'ModalService',
        '$location'
    ];

    function UserBrowsingController(UsersService, Notification, AuthService, ModalService, $location) {
        var vm = this;

        vm.user = AuthService.user;
        vm.viewUser = viewUser;
        vm.deleteUser = deleteUser;
        vm.editUser = editUser;
        vm.createNew = createNew;

        vm.onFilter = onFilter;
        var query = {};

        vm.searchForm = {
            name: {
                inputType: 'text',
                label: 'Name',
                matchColumn: 'name',
                matchRule: 'contains'
            },
            surname: {
                inputType: 'text',
                label: 'Surname',
                matchColumn: 'surname',
                matchRule: 'contains'
            }
        };

        function onFilter(q) {
            query = q;

            return UsersService.getUsers(query)
                .then(function (users) {
                    vm.users = users;
                    return vm.users;
                });
        }

        function createNew() {
            openUserForm();
        }

        function viewUser(user) {
            $location.path('/users/' + user.id);
        }

        function editUser(user) {
            openUserForm(user);
        }

        function deleteUser(user) {
            user.remove()
                .then(function () {
                    Notification.success("User deleted");

                    getUsers()
                        .then(refreshList);

                })
                .catch(function () {
                    Notification.warning("Failed to delete user");
                });

        }

        // private
        function openUserForm(user) {
            ModalService
                .openScientillaUserForm(!user ? UsersService.getNewUser() : user.clone())
                .then(function () {
                    return getUsers();
                })
                .then(refreshList);
        }

    }
})();<commit_msg>Fixed bug on refresh list<commit_after>(function () {
    angular
        .module('users')
        .controller('UserBrowsingController', UserBrowsingController);

    UserBrowsingController.$inject = [
        'UsersService',
        'Notification',
        'AuthService',
        'ModalService',
        '$location'
    ];

    function UserBrowsingController(UsersService, Notification, AuthService, ModalService, $location) {
        var vm = this;

        vm.user = AuthService.user;
        vm.viewUser = viewUser;
        vm.deleteUser = deleteUser;
        vm.editUser = editUser;
        vm.createNew = createNew;

        vm.onFilter = onFilter;
        var query = {};

        vm.searchForm = {
            name: {
                inputType: 'text',
                label: 'Name',
                matchColumn: 'name',
                matchRule: 'contains'
            },
            surname: {
                inputType: 'text',
                label: 'Surname',
                matchColumn: 'surname',
                matchRule: 'contains'
            }
        };

        function onFilter(q) {
            query = q;

            return UsersService.getUsers(query)
                .then(function (users) {
                    vm.users = users;
                    return vm.users;
                });
        }

        function createNew() {
            openUserForm();
        }

        function viewUser(user) {
            $location.path('/users/' + user.id);
        }

        function editUser(user) {
            openUserForm(user);
        }

        function deleteUser(user) {
            user.remove()
                .then(function () {
                    Notification.success("User deleted");

                    refreshList();

                })
                .catch(function () {
                    Notification.warning("Failed to delete user");
                });

        }

        // private
        function openUserForm(user) {
            ModalService
                .openScientillaUserForm(!user ? UsersService.getNewUser() : user.clone())
                .then(refreshList);
        }

        function refreshList() {
            onFilter(query);
        }

    }
})();<|endoftext|>


<commit_before>(function (window, $) {
  'use strict';

  var $resultFields, resultFieldsLength, resultFieldsUrl, updateIntervalId;

  $resultFields = $(".result-field");
  resultFieldsLength = $resultFields.length;
  resultFieldsUrl = window.location.pathname + "/populated_result_fields.json";

  function updateResults() {
    $.getJSON(resultFieldsUrl)
      .done(updateResultFields);
  }

  function updateResultFields(populatedFields) {
    var allFieldsPopulated = true;
    $resultFields.each(function () {
      var $this = $(this),
        isPopulated = (populatedFields.indexOf($this.data("resultFieldName")) != -1);
      $(this).toggleClass("result-field--populated", isPopulated);
      allFieldsPopulated = allFieldsPopulated && isPopulated;
    });
    if (allFieldsPopulated) {
      window.clearInterval(updateIntervalId);
      window.location.reload();
    }
  }

  if (resultFieldsLength > 0) {
    updateIntervalId = window.setInterval(updateResults, 200);
  }
}(this, jQuery));
<commit_msg>Slow down the report population check to 150ms<commit_after>(function (window, $) {
  'use strict';

  var $resultFields, resultFieldsLength, resultFieldsUrl, updateIntervalId;

  $resultFields = $(".result-field");
  resultFieldsLength = $resultFields.length;
  resultFieldsUrl = window.location.pathname + "/populated_result_fields.json";

  function updateResults() {
    $.getJSON(resultFieldsUrl)
      .done(updateResultFields);
  }

  function updateResultFields(populatedFields) {
    var allFieldsPopulated = true;
    $resultFields.each(function () {
      var $this = $(this),
        isPopulated = (populatedFields.indexOf($this.data("resultFieldName")) != -1);
      $(this).toggleClass("result-field--populated", isPopulated);
      allFieldsPopulated = allFieldsPopulated && isPopulated;
    });
    if (allFieldsPopulated) {
      window.clearInterval(updateIntervalId);
      window.location.reload();
    }
  }

  if (resultFieldsLength > 0) {
    updateIntervalId = window.setInterval(updateResults, 250);
  }
}(this, jQuery));
<|endoftext|>


<commit_before>import { expect } from 'chai';
const { describe, it } = global;

import StdReactiveVar from '../std-reactive-var.js';

import Tracker from 'trackr';

describe('reactive var only', function() {
  it('should construct the object well', function() {
    const target = new StdReactiveVar(10);

    expect(target._oldValue).to.be.null;
    expect(target._equalFunc).to.be.undefined;
    expect(target._dep).to.be.an.instanceof(Tracker.Dependency);

    expect(target._curValue).to.be.equal(10);

    expect(target._isEqual).to.be.function;
    expect(target.get).to.be.function;
    expect(target.getOld).to.be.function;
    expect(target.getNonReactive).to.be.function;
    expect(target.set).to.be.function;
    expect(target.toString).to.be.function;
    expect(target._numListeners).to.be.function;
  });

  it('_isEqual should work with number', function() {
    const target = new StdReactiveVar(10);

    expect(target._isEqual(10)).to.be.true;
    expect(target._isEqual('10')).to.be.false;
    expect(target._isEqual(11)).to.be.false;
  });

  it('_isEqual should work with object', function() {
    const obj = {};
    const target = new StdReactiveVar(obj);

    expect(target._isEqual(obj)).to.be.false;
    expect(target._isEqual({})).to.be.false;
    expect(target._isEqual(11)).to.be.false;
  });

  it('get should work with number', function() {
    const target = new StdReactiveVar(10);
    expect(target.get()).to.be.equal(10);
  });

  it('get should work with string', function() {
    const target = new StdReactiveVar('10');
    expect(target.get()).to.be.equal('10');
  });

  it('get should work with object', function() {
    const obj = {};
    const target = new StdReactiveVar(obj);
    expect(target.get()).to.be.equal(obj);
  });

  it('get should work with null', function() {
    const target = new StdReactiveVar(null);
    expect(target.get()).to.be.null;
  });

  it('get should work with undefined', function() {
    const target = new StdReactiveVar(undefined);
    expect(target.get()).to.be.undefined;
  });

  it('getOld should work', function() {
    const target = new StdReactiveVar(undefined);

    // XXX not really sure I doing it right here? is using .set to test .getOld is the right way?
    target.set(1);
    expect(target.getOld()).to.be.undefined;

    target.set('1');
    expect(target.getOld()).to.be.equal(1);

    target.set(null);
    expect(target.getOld()).to.be.equal('1');

    target.set(undefined);
    expect(target.getOld()).to.be.null;
  });
});

describe('reactive var with tracker', function() {
  it('', function() {});
});
<commit_msg>Do not lint test file<commit_after>/* eslint-disable */

import { expect } from 'chai';
const { describe, it } = global;

import StdReactiveVar from '../std-reactive-var.js';

import Tracker from 'trackr';

describe('reactive var only', function() {
  it('should construct the object well', function() {
    const target = new StdReactiveVar(10);

    expect(target._oldValue).to.be.null;
    expect(target._equalFunc).to.be.undefined;
    expect(target._dep).to.be.an.instanceof(Tracker.Dependency);

    expect(target._curValue).to.be.equal(10);

    expect(target._isEqual).to.be.function;
    expect(target.get).to.be.function;
    expect(target.getOld).to.be.function;
    expect(target.getNonReactive).to.be.function;
    expect(target.set).to.be.function;
    expect(target.toString).to.be.function;
    expect(target._numListeners).to.be.function;
  });

  it('_isEqual should work with number', function() {
    const target = new StdReactiveVar(10);

    expect(target._isEqual(10)).to.be.true;
    expect(target._isEqual('10')).to.be.false;
    expect(target._isEqual(11)).to.be.false;
  });

  it('_isEqual should work with object', function() {
    const obj = {};
    const target = new StdReactiveVar(obj);

    expect(target._isEqual(obj)).to.be.false;
    expect(target._isEqual({})).to.be.false;
    expect(target._isEqual(11)).to.be.false;
  });

  it('get should work with number', function() {
    const target = new StdReactiveVar(10);
    expect(target.get()).to.be.equal(10);
  });

  it('get should work with string', function() {
    const target = new StdReactiveVar('10');
    expect(target.get()).to.be.equal('10');
  });

  it('get should work with object', function() {
    const obj = {};
    const target = new StdReactiveVar(obj);
    expect(target.get()).to.be.equal(obj);
  });

  it('get should work with null', function() {
    const target = new StdReactiveVar(null);
    expect(target.get()).to.be.null;
  });

  it('get should work with undefined', function() {
    const target = new StdReactiveVar(undefined);
    expect(target.get()).to.be.undefined;
  });

  it('getOld should work', function() {
    const target = new StdReactiveVar(undefined);

    // XXX not really sure I doing it right here? is using .set to test .getOld is the right way?
    target.set(1);
    expect(target.getOld()).to.be.undefined;

    target.set('1');
    expect(target.getOld()).to.be.equal(1);

    target.set(null);
    expect(target.getOld()).to.be.equal('1');

    target.set(undefined);
    expect(target.getOld()).to.be.null;
  });
});

describe('reactive var with tracker', function() {
  it('', function() {});
});
<|endoftext|>


<commit_before>import { isArray } from 'lodash';
import strategies from './strategies';

const defaultTransform = (v = '') => v && v.toLowerCase && v.toLowerCase();
const defaultCastingStrategy = v => (isArray(v) ? v : String(v));

const _columnMatches = ({
  query,
  castingStrategy = defaultCastingStrategy,
  column = {},
  row,
  strategy = strategies.infix,
  transform = defaultTransform
}) => {
  const property = column.property;
  if (!property) {
    return false;
  }
  const value = row[`_${property}`] || row[property];
  if (value == null) {
    return false;
  }
  // Pick resolved value by convention
  const resolvedValue = castingStrategy(value);

  return strategy(transform(query)).evaluate(transform(resolvedValue));
};

export default _columnMatches;
<commit_msg>Allow more information for casting<commit_after>import { isArray } from 'lodash';
import strategies from './strategies';

const defaultTransform = (v = '') => v && v.toLowerCase && v.toLowerCase();
const defaultCastingStrategy = v => (isArray(v) ? v : String(v));

const _columnMatches = ({
  query,
  castingStrategy = defaultCastingStrategy,
  column = {},
  row,
  strategy = strategies.infix,
  transform = defaultTransform
}) => {
  const property = column.property;
  if (!property) {
    return false;
  }
  const value = row[`_${property}`] || row[property];
  if (value == null) {
    return false;
  }
  // Pick resolved value by convention
  const resolvedValue = castingStrategy(value, column);

  return strategy(transform(query)).evaluate(transform(resolvedValue));
};

export default _columnMatches;
<|endoftext|>


<commit_before>import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import NavLink from 'gatsby-link'
import SideBarItem from './SideBarItem'

const Wrapper = styled.div`
  background-color: white;
  transition: all 0.3s ease;
  position: fixed;
  left: 0;
  right: 0;
  width: 300px;
  height: 100vh;
  display: flex;
  flex-direction: column;
  border-right: 1px solid rgba(0, 0, 0, 0.08);
  @media only screen and (max-width: 768px) {
    left: ${props => props.mobileVisible ? 0 : -300}px;
    top: 50px;
    height: calc(100vh - 50px);
    z-index: 4;
    }
`

const Top = styled(NavLink)`
    border-bottom: 1px solid rgba(0, 0, 0, 0.08);
    padding: 50px;
    text-decoration: none;
`
const TopTitle = styled.h1`
    font-size: 1.0rem;
    font-weight: 500;
    color: #333;
    margin-bottom: 0.2rem;
`

const TopDescription = styled.div`
    font-size: 0.7rem;
    color: #666;
    line-height: 1.5;
`

const List = styled.div`
    overflow-y: auto;
`

class SideBar extends React.Component {

    render() {
        return (
            <Wrapper mobileVisible={this.props.mobileSideNavVisible}>
                <Top to="/">
                    <TopTitle>Jaehyun Baek</TopTitle>
                    <TopDescription>
                        Wouldn't it be more consistent to change the direction

                        if I had a different perspective today than yesterday?
              </TopDescription>
                </Top>
                <List>
                    <SideBarItem to="/" text="All Posts" onClick={this.props.onClickSideBarItem} />
                    <SideBarItem to="/category/book" text="book" onClick={this.props.onClickSideBarItem} isSub/>
                    <SideBarItem to="/category/programming" text="programming" onClick={this.props.onClickSideBarItem} isSub/>
                    <SideBarItem to="/category/movie" text="movie" onClick={this.props.onClickSideBarItem} isSub/>
                    <SideBarItem to="/about" text="About" onClick={this.props.onClickSideBarItem} />
                </List>
            </Wrapper>
        );
    }

    onClickTop = () => {
        window.location.href = '/';
    }
}

SideBar.propTypes = {
    onClickSideBarItem: PropTypes.func.isRequired,
    mobileSideNavVisible: PropTypes.bool.isRequired,
}

export default SideBar
<commit_msg>h1 은 페이지당 하나만<commit_after>import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import NavLink from 'gatsby-link'
import SideBarItem from './SideBarItem'

const Wrapper = styled.div`
  background-color: white;
  transition: all 0.3s ease;
  position: fixed;
  left: 0;
  right: 0;
  width: 300px;
  height: 100vh;
  display: flex;
  flex-direction: column;
  border-right: 1px solid rgba(0, 0, 0, 0.08);
  @media only screen and (max-width: 768px) {
    left: ${props => props.mobileVisible ? 0 : -300}px;
    top: 50px;
    height: calc(100vh - 50px);
    z-index: 4;
    }
`

const Top = styled(NavLink)`
    border-bottom: 1px solid rgba(0, 0, 0, 0.08);
    padding: 50px;
    text-decoration: none;
`
const TopTitle = styled.div`
    font-size: 1.0rem;
    font-weight: 500;
    color: #333;
    margin-bottom: 0.2rem;
`

const TopDescription = styled.div`
    font-size: 0.7rem;
    color: #666;
    line-height: 1.5;
`

const List = styled.div`
    overflow-y: auto;
`

class SideBar extends React.Component {

    render() {
        return (
            <Wrapper mobileVisible={this.props.mobileSideNavVisible}>
                <Top to="/">
                    <TopTitle>Jaehyun Baek</TopTitle>
                    <TopDescription>
                        Wouldn't it be more consistent to change the direction

                        if I had a different perspective today than yesterday?
              </TopDescription>
                </Top>
                <List>
                    <SideBarItem to="/" text="All Posts" onClick={this.props.onClickSideBarItem} />
                    <SideBarItem to="/category/book" text="book" onClick={this.props.onClickSideBarItem} isSub/>
                    <SideBarItem to="/category/programming" text="programming" onClick={this.props.onClickSideBarItem} isSub/>
                    <SideBarItem to="/category/movie" text="movie" onClick={this.props.onClickSideBarItem} isSub/>
                    <SideBarItem to="/about" text="About" onClick={this.props.onClickSideBarItem} />
                </List>
            </Wrapper>
        );
    }

    onClickTop = () => {
        window.location.href = '/';
    }
}

SideBar.propTypes = {
    onClickSideBarItem: PropTypes.func.isRequired,
    mobileSideNavVisible: PropTypes.bool.isRequired,
}

export default SideBar
<|endoftext|>


<commit_before>'use strict';

var target; // for new properties
var attributePrefix = '@';

function reset(attrPrefix) {
	target = null;
	attributePrefix = attrPrefix;
}

function clone(obj) {
	 return JSON.parse(JSON.stringify(obj));
}

function hoik(obj,target,key,newKey) {
	if (target && obj && (typeof obj[key] != 'undefined')) {
		if (!newKey) {
			newKey = key;
		}
		target[newKey] = clone(obj[key]);
		delete obj[key];
	}
}

function rename(obj,key,newName) {
	obj[newName] = obj[key];
	delete obj[key];
}

function isEmpty(obj) {
	if (typeof obj !== 'object') return false;
    for (var prop in obj) {
        if ((obj.hasOwnProperty(prop) && (typeof obj[prop] !== 'undefined'))) {
			return false;
		}
    }
 	return true;
}

function toArray(item) {
	if (!(item instanceof Array)) {
		var newitem = [];
		if (item) {
			newitem.push(item);
		}
		return newitem;
	}
	else {
		return item;
	}
}

function mandate(target,name) {
	if (!target.required) target.required = [];
	if (target.required.indexOf(name) < 0) {
		target.required.push(name);
	}
}

function mapType(type) {

	var result = {};

	if (type == 'xs:integer') type = 'integer';

	if (type == 'xs:string') type = 'string';
	if (type == 'xs:NMTOKEN') type = 'string';
	if (type == 'xs:NMTOKENS') type = 'string';
	if (type == 'xs:ENTITY') type = 'string';
	if (type == 'xs:ENTITIES') type = 'string';
	if (type == 'xs:ID') type = 'string';
	if (type == 'xs:IDREF') type = 'string';
	if (type == 'xs:IDREFS') type = 'string';
	if (type == 'xs:token') type = 'string';
	if (type == 'xs:lamguage') type = 'string';
	if (type == 'xs:Name') type = 'string';
	if (type == 'xs:NCName') type = 'string';
	if (type == 'xs:QName') type = 'string';
	if (type == 'xs:normalizedString') type = 'string';
	if (type == 'xs:base64Binary') type = 'string';
	if (type == 'xs:hexBinary') type = 'string';
	if (type == 'xs:NOTATION') type = 'string';

	if (type == 'xs:boolean') type = 'boolean';
	if (type == 'xs:date') {
		type = 'string';
		result.format = 'date-time';
	}
	if (type == 'xs:dateTime') {
		type = 'string';
		result.format = 'date-time';
	}
	if (type == 'xs:positiveInteger') {
		type = 'integer';
		result.minimum = 0;
	}
	if (type == 'xs:decimal') type = 'number';
	if (type == 'xs:double') type = 'number';
	if (type == 'xs:float') type = 'number';
	if (type == 'xs:anyURI') {
		type = 'string';
		//result.format = 'uri'; //XSD allows relative URIs, it seems JSON schema uri format may not?
	}

	result.type = type;
	return result;
}

function doElement(src,parent,key) {
	var type = 'object';
	var name;

	var simpleType;

	var element = src[key];
	if ((typeof element == 'undefined') || (null === element)) {
		console.log('bailing out '+key+' = '+src[key]);
		return false;
	}

	if (element["@name"]) {
		name = element["@name"];
	}
	if (element["@type"]) {
		type = element["@type"];
	}
	else if ((element["@name"]) && (element["xs:simpleType"])) {
		type = element["xs:simpleType"]["xs:restriction"]["@base"];
		simpleType = element["xs:simpleType"]["xs:restriction"];
	}
	else if (element["@ref"]) {
		name = element["@ref"];
		type = element["@ref"];
	}

	if (name && type) {
		//console.log(name+' '+type);

		//var isAttribute = (name.startsWith('@'));
		//var isAttribute = (key == 'xs:attribute'); // could be in an array
		var isAttribute = (element["@isAttr"] == true);

		if (!target) target = parent;
		if (!target.properties) target.properties = {};
		var newTarget = target;

		var minOccurs = 1;
		var maxOccurs = 1;
		if (element["@minOccurs"]) minOccurs = element["@minOccurs"];
		if (element["@maxOccurs"]) maxOccurs = element["@maxOccurs"];
		if (maxOccurs == 'unbounded') maxOccurs = 2;
		if (isAttribute) {
			if ((!element["@use"]) || (element["@use"] != 'required')) minOccurs = 0;
		}

		var typeData = mapType(type);
		if (typeData.type == 'object') {
			typeData.properties = {};
			//console.log('created properties for /'+name);
			newTarget = typeData;
		}

		if (element["xs:simpleType"] && element["xs:simpleType"]["xs:restriction"] && element["xs:simpleType"]["xs:restriction"]["xs:enumeration"]) {
			var source = element["xs:simpleType"]["xs:restriction"]["xs:enumeration"];
			typeData["enum"] = [];
			for (var i=0;i<source.length;i++) {
				typeData["enum"].push(source[i]);
			}
			delete typeData.type; // assert it was a stringish type?
		}
		else if (element["xs:restriction"] && element["xs:restriction"]["xs:enumeration"]) {
			var source = element["xs:restriction"]["xs:enumeration"];
			typeData["enum"] = [];
			for (var i=0;i<source.length;i++) {
				typeData["enum"].push(source[i]);
			}
			delete typeData.type; // assert it was a stringish type?
		}
		else {
			if ((typeData.type == 'string') || (typeData.type == 'boolean') || (typeData.type == 'array') || (typeData.type == 'object')
				|| (typeData.type == 'integer') || (typeData.type == 'number') || (typeData.type == 'null')) {
				//typeData.type = typeData.type;
			}
			else {
				typeData["$ref"] = '#/definitions/'+typeData.type;
				delete typeData.type;
			}
		}

		if (maxOccurs > 1) {
			var newTD = {};
			newTD.type = 'array';
			newTD.items = typeData;
			typeData = newTD;
		}
		if (minOccurs > 0) {
			mandate(target,name);
		}

		if (simpleType) {
			if (simpleType["xs:minLength"]) typeData.minLength = simpleType["xs:minLength"];
			if (simpleType["xs:maxLength"]) typeData.maxLength = simpleType["xs:maxLength"];
		}

		if (isAttribute) {
			var newProp = {};
			newProp[name] = typeData;
			target.properties = Object.assign(newProp,target.properties); // force attributes to top
		}
		else {
			target.properties[name] = typeData;
		}
		target.additionalProperties = false;

		target = newTarget;
	}
}

function moveAttributes(obj,parent,key) {
	if (key == 'xs:attribute') {

		obj[key] = toArray(obj[key]);

		var target;

		if (obj["xs:sequence"] && obj["xs:sequence"]["xs:element"]) {
			obj["xs:sequence"]["xs:element"] = toArray(obj["xs:sequence"]["xs:element"]);
			target = obj["xs:sequence"]["xs:element"];
		}
		if (obj["xs:choice"] && obj["xs:choice"]["xs:element"]) {
			obj["xs:choice"]["xs:element"] = toArray(obj["xs:choice"]["xs:element"]);
			target = obj["xs:choice"]["xs:element"];
		}

		if (target) {
			target = toArray(target);
			for (var i=0;i<obj[key].length;i++) {
				var attr = clone(obj[key][i]);
				if (attributePrefix) {
					attr["@name"] = attributePrefix+attr["@name"];
				}
				attr["@isAttr"] = true;
				target.push(attr);
			}
			delete obj[key];
		}
	}
}

function renameObjects(obj,parent,key) {
	if (key == 'xs:complexType') {
		var name = obj["@name"];
		if (name) {
			//console.log('Rename '+key+' to '+name);
			rename(obj,key,name);
			//delete obj["@name"];
		}
		else console.log('no name');
	}
}

function moveProperties(obj,parent,key) {
	if (key == 'xs:sequence') {
		if (obj[key].properties) {
			obj.properties = obj[key].properties;
			obj.required = obj[key].required;
			obj.additionalProperties = false;
			delete obj[key];
		}
	}
}

function clean(obj,parent,key) {
	if (key == '@minOccurs') delete obj[key];
	if (key == '@maxOccurs') delete obj[key];
	if (key == '@name') delete obj[key];
	if (key == '@type') delete obj[key];
	if (key == 'xs:simpleType') delete obj[key];
	if (key == '@use') delete obj[key];
}

function removeEmpties(obj,parent,key) {
	var count = 0;
	if (isEmpty(obj[key])) {
		delete obj[key];
		count++;
	}
	else {
		if (Array.isArray(obj[key])) {
			var newArray = [];
			for (var i=0;i<obj[key].length;i++) {
				if (typeof obj[key][i] !== 'undefined') {
					newArray.push(obj[key][i]);
				}
				else {
					count++;
				}
			}
			if (newArray.length == 0) {
				delete obj[key];
				count++;
			}
			else {
				obj[key] = newArray;
			}
		}
	}
	return count;
}

function recurse(obj,parent,callback,depthFirst) {

	var oTarget = target;

	for (var key in obj) {
		target = oTarget;
		// skip loop if the property is from prototype
		if (!obj.hasOwnProperty(key)) continue;

		if (!depthFirst) callback(obj,parent,key);

		var array = Array.isArray(obj);

		if (typeof obj[key] === 'object') {
			if (array) {
				for (var i in obj[key]) {
					recurse(obj[key][i],obj[key],callback);
				}
			}
			recurse(obj[key],obj,callback);
		}

		if (depthFirst) callback(obj,parent,key);
	}

	return obj;
}

module.exports = {
	getJsonSchema : function getJsonSchema(src,title,attrPrefix) {
		reset(attrPrefix);

		recurse(src,{},function(src,parent,key) {
			moveAttributes(src,parent,key);
		});

		var obj = {};

		var id = src["xs:schema"]["@targetNamespace"];
		if (!id) {
			id = src["xs:schema"]["@xmlns"];
		}

		//initial root object transformations
		obj.title = title;
		obj.$schema = 'http://json-schema.org/schema#'; //for latest, or 'http://json-schema.org/draft-04/schema#' for v4
		if (id) {
			obj.id = id;
		}

		var rootElement = src["xs:schema"]["xs:element"];
		if (Array.isArray(rootElement)) {
			rootElement = rootElement[0];
		}
		var rootElementName = rootElement["@name"];

		obj.type = 'object';
		obj.properties = clone(rootElement);
		obj.required = [];
		obj.required.push(rootElementName);
		obj.additionalProperties = false;

		recurse(obj.properties,{},function(src,parent,key) {
			moveAttributes(src,parent,key);
		});
		recurse(obj,{},function(obj,parent,key) {
			renameObjects(obj,parent,key);
		});

		recurse(obj.properties,{},function(src,parent,key) {
			doElement(src,parent,key);
		});

		recurse(obj,{},function(obj,parent,key) {
			moveProperties(obj,parent,key);
		});

		// remove rootElement to leave ref'd definitions
		if (Array.isArray(src["xs:schema"]["xs:element"])) {
			delete src["xs:schema"]["xs:element"][0];
		}
		else {
			delete src["xs:schema"]["xs:element"];
		}

		obj.definitions = clone(src);
		obj.definitions.properties = {};
		target = obj.definitions;

		recurse(obj.definitions,{},function(src,parent,key) {
			doElement(src,parent,key);
		});

		// correct for /definitions/properties
		obj.definitions = obj.definitions.properties;

		recurse(obj,{},function(obj,parent,key) {
			clean(obj,parent,key);
		});

		delete(obj.definitions["xs:schema"]);

		var count = 1;
		while (count>0) {
			count = 0;
			recurse(obj,{},function(obj,parent,key) {
				count += removeEmpties(obj,parent,key); // first pass
			});
		}

		return obj;
	}
};<commit_msg>Tag more attributes so optionality is detected<commit_after>'use strict';

var target; // for new properties
var attributePrefix = '@';

function reset(attrPrefix) {
	target = null;
	attributePrefix = attrPrefix;
}

function clone(obj) {
	 return JSON.parse(JSON.stringify(obj));
}

function hoik(obj,target,key,newKey) {
	if (target && obj && (typeof obj[key] != 'undefined')) {
		if (!newKey) {
			newKey = key;
		}
		target[newKey] = clone(obj[key]);
		delete obj[key];
	}
}

function rename(obj,key,newName) {
	obj[newName] = obj[key];
	delete obj[key];
}

function isEmpty(obj) {
	if (typeof obj !== 'object') return false;
    for (var prop in obj) {
        if ((obj.hasOwnProperty(prop) && (typeof obj[prop] !== 'undefined'))) {
			return false;
		}
    }
 	return true;
}

function toArray(item) {
	if (!(item instanceof Array)) {
		var newitem = [];
		if (item) {
			newitem.push(item);
		}
		return newitem;
	}
	else {
		return item;
	}
}

function mandate(target,name) {
	if (!target.required) target.required = [];
	if (target.required.indexOf(name) < 0) {
		target.required.push(name);
	}
}

function mapType(type) {

	var result = {};

	if (type == 'xs:integer') type = 'integer';

	if (type == 'xs:string') type = 'string';
	if (type == 'xs:NMTOKEN') type = 'string';
	if (type == 'xs:NMTOKENS') type = 'string';
	if (type == 'xs:ENTITY') type = 'string';
	if (type == 'xs:ENTITIES') type = 'string';
	if (type == 'xs:ID') type = 'string';
	if (type == 'xs:IDREF') type = 'string';
	if (type == 'xs:IDREFS') type = 'string';
	if (type == 'xs:token') type = 'string';
	if (type == 'xs:lamguage') type = 'string';
	if (type == 'xs:Name') type = 'string';
	if (type == 'xs:NCName') type = 'string';
	if (type == 'xs:QName') type = 'string';
	if (type == 'xs:normalizedString') type = 'string';
	if (type == 'xs:base64Binary') type = 'string';
	if (type == 'xs:hexBinary') type = 'string';
	if (type == 'xs:NOTATION') type = 'string';

	if (type == 'xs:boolean') type = 'boolean';
	if (type == 'xs:date') {
		type = 'string';
		result.format = 'date-time';
	}
	if (type == 'xs:dateTime') {
		type = 'string';
		result.format = 'date-time';
	}
	if (type == 'xs:positiveInteger') {
		type = 'integer';
		result.minimum = 0;
	}
	if (type == 'xs:decimal') type = 'number';
	if (type == 'xs:double') type = 'number';
	if (type == 'xs:float') type = 'number';
	if (type == 'xs:anyURI') {
		type = 'string';
		//result.format = 'uri'; //XSD allows relative URIs, it seems JSON schema uri format may not?
	}

	result.type = type;
	return result;
}

function doElement(src,parent,key) {
	var type = 'object';
	var name;

	var simpleType;

	var element = src[key];
	if ((typeof element == 'undefined') || (null === element)) {
		console.log('bailing out '+key+' = '+src[key]);
		return false;
	}

	if (element["@name"]) {
		name = element["@name"];
	}
	if (element["@type"]) {
		type = element["@type"];
	}
	else if ((element["@name"]) && (element["xs:simpleType"])) {
		type = element["xs:simpleType"]["xs:restriction"]["@base"];
		simpleType = element["xs:simpleType"]["xs:restriction"];
	}
	else if (element["@ref"]) {
		name = element["@ref"];
		type = element["@ref"];
	}

	if (name && type) {
		//console.log(name+' '+type);

		var isAttribute = (element["@isAttr"] == true);

		if (!target) target = parent;
		if (!target.properties) target.properties = {};
		var newTarget = target;

		var minOccurs = 1;
		var maxOccurs = 1;
		if (element["@minOccurs"]) minOccurs = element["@minOccurs"];
		if (element["@maxOccurs"]) maxOccurs = element["@maxOccurs"];
		if (maxOccurs == 'unbounded') maxOccurs = 2;
		if (isAttribute) {
			if ((!element["@use"]) || (element["@use"] != 'required')) minOccurs = 0;
		}

		var typeData = mapType(type);
		if (typeData.type == 'object') {
			typeData.properties = {};
			newTarget = typeData;
		}

		var enumSource;

		if (element["xs:simpleType"] && element["xs:simpleType"]["xs:restriction"] && element["xs:simpleType"]["xs:restriction"]["xs:enumeration"]) {
			var enumSource = element["xs:simpleType"]["xs:restriction"]["xs:enumeration"];
		}
		else if (element["xs:restriction"] && element["xs:restriction"]["xs:enumeration"]) {
			var enumSource = element["xs:restriction"]["xs:enumeration"];
		}

		if (enumSource) {
			typeData["enum"] = [];
			for (var i=0;i<enumSource.length;i++) {
				typeData["enum"].push(enumSource[i]);
			}
			delete typeData.type; // assert it was a stringish type?
		}
		else {
			if ((typeData.type == 'string') || (typeData.type == 'boolean') || (typeData.type == 'array') || (typeData.type == 'object')
				|| (typeData.type == 'integer') || (typeData.type == 'number') || (typeData.type == 'null')) {
				//typeData.type = typeData.type;
			}
			else {
				typeData["$ref"] = '#/definitions/'+typeData.type;
				delete typeData.type;
			}
		}

		if (maxOccurs > 1) {
			var newTD = {};
			newTD.type = 'array';
			newTD.items = typeData;
			typeData = newTD;
		}
		if (minOccurs > 0) {
			mandate(target,name);
		}

		if (simpleType) {
			if (simpleType["xs:minLength"]) typeData.minLength = simpleType["xs:minLength"];
			if (simpleType["xs:maxLength"]) typeData.maxLength = simpleType["xs:maxLength"];
		}

		if (isAttribute) {
			var newProp = {};
			newProp[name] = typeData;
			target.properties = Object.assign(newProp,target.properties); // force attributes to top
		}
		else {
			target.properties[name] = typeData;
		}
		target.additionalProperties = false;

		target = newTarget;
	}
}

function moveAttributes(obj,parent,key) {
	if (key == 'xs:attribute') {

		obj[key] = toArray(obj[key]);

		var target;

		if (obj["xs:sequence"] && obj["xs:sequence"]["xs:element"]) {
			obj["xs:sequence"]["xs:element"] = toArray(obj["xs:sequence"]["xs:element"]);
			target = obj["xs:sequence"]["xs:element"];
		}
		if (obj["xs:choice"] && obj["xs:choice"]["xs:element"]) {
			obj["xs:choice"]["xs:element"] = toArray(obj["xs:choice"]["xs:element"]);
			target = obj["xs:choice"]["xs:element"];
		}

		if (target) target = toArray(target);

		for (var i=0;i<obj[key].length;i++) {
			var attr = clone(obj[key][i]);
			if (attributePrefix) {
				attr["@name"] = attributePrefix+attr["@name"];
			}
			if (typeof attr == 'object') {
				attr["@isAttr"] = true;
			}
			if (target) target.push(attr)
			else obj[key][i] = attr;
		}
		if (target) delete obj[key];
	}
}

function renameObjects(obj,parent,key) {
	if (key == 'xs:complexType') {
		var name = obj["@name"];
		if (name) {
			//console.log('Rename '+key+' to '+name);
			rename(obj,key,name);
			//delete obj["@name"];
		}
		else console.log('no name');
	}
}

function moveProperties(obj,parent,key) {
	if (key == 'xs:sequence') {
		if (obj[key].properties) {
			obj.properties = obj[key].properties;
			obj.required = obj[key].required;
			obj.additionalProperties = false;
			delete obj[key];
		}
	}
}

function clean(obj,parent,key) {
	if (key == '@minOccurs') delete obj[key];
	if (key == '@maxOccurs') delete obj[key];
	if (key == '@name') delete obj[key];
	if (key == '@type') delete obj[key];
	if (key == 'xs:simpleType') delete obj[key];
	if (key == '@use') delete obj[key];
}

function removeEmpties(obj,parent,key) {
	var count = 0;
	if (isEmpty(obj[key])) {
		delete obj[key];
		count++;
	}
	else {
		if (Array.isArray(obj[key])) {
			var newArray = [];
			for (var i=0;i<obj[key].length;i++) {
				if (typeof obj[key][i] !== 'undefined') {
					newArray.push(obj[key][i]);
				}
				else {
					count++;
				}
			}
			if (newArray.length == 0) {
				delete obj[key];
				count++;
			}
			else {
				obj[key] = newArray;
			}
		}
	}
	return count;
}

function recurse(obj,parent,callback,depthFirst) {

	var oTarget = target;

	for (var key in obj) {
		target = oTarget;
		// skip loop if the property is from prototype
		if (!obj.hasOwnProperty(key)) continue;

		if (!depthFirst) callback(obj,parent,key);

		var array = Array.isArray(obj);

		if (typeof obj[key] === 'object') {
			if (array) {
				for (var i in obj[key]) {
					recurse(obj[key][i],obj[key],callback);
				}
			}
			recurse(obj[key],obj,callback);
		}

		if (depthFirst) callback(obj,parent,key);
	}

	return obj;
}

module.exports = {
	getJsonSchema : function getJsonSchema(src,title,attrPrefix) {
		reset(attrPrefix);

		recurse(src,{},function(src,parent,key) {
			moveAttributes(src,parent,key);
		});

		var obj = {};

		var id = src["xs:schema"]["@targetNamespace"];
		if (!id) {
			id = src["xs:schema"]["@xmlns"];
		}

		//initial root object transformations
		obj.title = title;
		obj.$schema = 'http://json-schema.org/schema#'; //for latest, or 'http://json-schema.org/draft-04/schema#' for v4
		if (id) {
			obj.id = id;
		}

		var rootElement = src["xs:schema"]["xs:element"];
		if (Array.isArray(rootElement)) {
			rootElement = rootElement[0];
		}
		var rootElementName = rootElement["@name"];

		obj.type = 'object';
		obj.properties = clone(rootElement);
		obj.required = [];
		obj.required.push(rootElementName);
		obj.additionalProperties = false;

		recurse(obj.properties,{},function(src,parent,key) {
			moveAttributes(src,parent,key);
		});
		recurse(obj,{},function(obj,parent,key) {
			renameObjects(obj,parent,key);
		});

		recurse(obj.properties,{},function(src,parent,key) {
			doElement(src,parent,key);
		});

		recurse(obj,{},function(obj,parent,key) {
			moveProperties(obj,parent,key);
		});

		// remove rootElement to leave ref'd definitions
		if (Array.isArray(src["xs:schema"]["xs:element"])) {
			delete src["xs:schema"]["xs:element"][0];
		}
		else {
			delete src["xs:schema"]["xs:element"];
		}

		obj.definitions = clone(src);
		obj.definitions.properties = {};
		target = obj.definitions;

		recurse(obj.definitions,{},function(src,parent,key) {
			doElement(src,parent,key);
		});

		// correct for /definitions/properties
		obj.definitions = obj.definitions.properties;

		recurse(obj,{},function(obj,parent,key) {
			clean(obj,parent,key);
		});

		delete(obj.definitions["xs:schema"]);

		var count = 1;
		while (count>0) {
			count = 0;
			recurse(obj,{},function(obj,parent,key) {
				count += removeEmpties(obj,parent,key); // first pass
			});
		}

		return obj;
	}
};<|endoftext|>