<commit_before>/**
 * @module Lyria
 * @submodule Scene
 */
define('lyria/scene/director', ['root', 'mixer', 'jquery', 'eventmap', 'lyria/scene', 'lyria/viewport'], function(root, mixer, $, EventMap, Scene, Viewport) {'use strict';

  /**
   * The scene director is the manager for all scenes
   *
   */
  return (function() {

    /**
     * The scene director constructor
     * Attaches a scene director to a container, the parent is optional
     *
     * @class Director
     * @constructor
     *
     * @param {Object} container
     * @param {Object} parent
     */
    function SceneDirector(container, parent) {
      mixer(SceneDirector.prototype, new EventMap());

      if ( container instanceof Viewport) {
        this.viewport = container;
      } else {
        this.viewport = new Viewport(container, {parent: parent});
      }

      /**
       * All scenes
       *
       * @property sceneList
       * @type {Object}
       */
      this.sceneList = {};

      /**
       * The current scene
       *
       * @property currentScene
       * @type {Scene}
       */
      this.currentScene = null;

      /**
       * Define events for scene director
       *
       */
      this.on('render', function() {
        if (this.currentScene) {
          this.currentScene.trigger('render');
        }
      });

      this.on('update', function(dt) {
        if (this.currentScene) {
          this.currentScene.trigger('update', dt);
        }
      });
    }

    // Properties
    SceneDirector.prototype.sceneClassName = 'scene';

    // Methods

    /**
     * Adds a scene to the scene director
     *
     * @method add
     * @param {Object} scene
     * @param {Object} options
     */
    SceneDirector.prototype.add = function(scene, options) {

      if (!( scene instanceof Scene)) {
        if (this.scenes && !$.isEmptyObject(this.scenes)) {
          scene = this.scenes[scene];
        } else {
          // TODO: Don't throw a string. Throw an error
          throw 'No valid scene found.';
        }
      }

      scene.parent = this;
      this.sceneList[scene.name] = scene;

      if (this.viewport.$element) {
        if ($('#' + scene.name).length === 0) {
          this.viewport.$element.prepend($(root.document.createElement('div')).attr('id', scene.name).attr('class', SceneDirector.prototype.sceneClassName));

          if (!scene.isAsync) {
            scene.trigger('added');
          }

        }
      }

      return this;
    };

    /**
     * Shows a specified scene
     *
     * @method show
     * @param {String} scene
     * @param {Object} options
     * @param {Function} callback
     */
    SceneDirector.prototype.show = function(scene, options, callback) {
      this.trigger('scene:change', scene);

      // More than one scene visible at the same time
      if ($('.' + SceneDirector.prototype.sceneClassName + ':visible')) {
        $('.' + SceneDirector.prototype.sceneClassName).hide();
      }

      if (this.currentScene) {
        if (this.currentScene.transition && this.currentScene.length) {
          $('#' + this.currentScene).hide(this.currentScene.transition.length, function() {
            $('.' + SceneDirector.prototype.sceneClassName).hide();
          });
        } else {
          $('.' + SceneDirector.prototype.sceneClassName).hide();
        }

        this.currentScene.trigger('deactivate', options);
      }

      var self = this;

      $.each(this.sceneList, function(key, value) {
        if (key === scene) {

          if (scene.transition && scene.transition.length) {
            $('#' + scene).show(scene.transition.length);
          } else {
            $('#' + scene).show();
          }

          self.currentScene = value;

          self.currentScene.trigger('active', options);

          if (callback) {
            callback(scene);
          }

          return false;
        }
      });
    };

    /**
     * Refreshes a scene
     *
     * @method refresh
     * @param {String} scene
     */
    SceneDirector.prototype.refresh = function(scene) {
      var sceneObj = (scene) ? this.sceneList[scene] : this.currentScene;

      // Re-compile scene template
      sceneObj.refresh();
    };

    return SceneDirector;

  })();
});
<commit_msg>Updated scene director to reference game if needed<commit_after>/**
 * @module Lyria
 * @submodule Scene
 */
define('lyria/scene/director', ['root', 'mixer', 'jquery', 'eventmap', 'lyria/scene', 'lyria/viewport'], function(root, mixer, $, EventMap, Scene, Viewport) {'use strict';

  /**
   * The scene director is the manager for all scenes
   *
   */
  return (function() {

    /**
     * The scene director constructor
     * Attaches a scene director to a container, the parent is optional
     *
     * @class Director
     * @constructor
     *
     * @param {Object} container
     * @param {Object} parent
     */
    function SceneDirector(container, parent) {
      mixer(SceneDirector.prototype, new EventMap());

      if ( container instanceof Viewport) {
        this.viewport = container;
      } else {
        this.viewport = new Viewport(container, {parent: parent});
      }

      /**
       * All scenes
       *
       * @property sceneList
       * @type {Object}
       */
      this.sceneList = {};

      /**
       * The current scene
       *
       * @property currentScene
       * @type {Scene}
       */
      this.currentScene = null;

      /**
       * Define events for scene director
       *
       */
      this.on('render', function() {
        if (this.currentScene) {
          this.currentScene.trigger('render');
        }
      });

      this.on('update', function(dt) {
        if (this.currentScene) {
          this.currentScene.trigger('update', dt);
        }
      });
    }

    // Properties
    SceneDirector.prototype.sceneClassName = 'scene';

    // Methods

    /**
     * Adds a scene to the scene director
     *
     * @method add
     * @param {Object} scene
     * @param {Object} options
     */
    SceneDirector.prototype.add = function(scene, options) {

      if (!( scene instanceof Scene)) {
        if (this.scenes && !$.isEmptyObject(this.scenes)) {
          scene = this.scenes[scene];
        } else {
          // TODO: Don't throw a string. Throw an error
          throw 'No valid scene found.';
        }
      }

      scene.parent = this;

      // Update reference to the game itself
      if (this.parent != null) {
        scene.game = this.parent;
      }

      this.sceneList[scene.name] = scene;

      if (this.viewport.$element) {
        if ($('#' + scene.name).length === 0) {
          this.viewport.$element.prepend($(root.document.createElement('div')).attr('id', scene.name).attr('class', SceneDirector.prototype.sceneClassName));

          if (!scene.isAsync) {
            scene.trigger('added');
          }

        }
      }

      return this;
    };

    /**
     * Shows a specified scene
     *
     * @method show
     * @param {String} scene
     * @param {Object} options
     * @param {Function} callback
     */
    SceneDirector.prototype.show = function(scene, options, callback) {
      this.trigger('scene:change', scene);

      // More than one scene visible at the same time
      if ($('.' + SceneDirector.prototype.sceneClassName + ':visible')) {
        $('.' + SceneDirector.prototype.sceneClassName).hide();
      }

      if (this.currentScene) {
        if (this.currentScene.transition && this.currentScene.length) {
          $('#' + this.currentScene).hide(this.currentScene.transition.length, function() {
            $('.' + SceneDirector.prototype.sceneClassName).hide();
          });
        } else {
          $('.' + SceneDirector.prototype.sceneClassName).hide();
        }

        this.currentScene.trigger('deactivate', options);
      }

      var self = this;

      $.each(this.sceneList, function(key, value) {
        if (key === scene) {

          if (scene.transition && scene.transition.length) {
            $('#' + scene).show(scene.transition.length);
          } else {
            $('#' + scene).show();
          }

          self.currentScene = value;

          self.currentScene.trigger('active', options);

          if (callback) {
            callback(scene);
          }

          return false;
        }
      });
    };

    /**
     * Refreshes a scene
     *
     * @method refresh
     * @param {String} scene
     */
    SceneDirector.prototype.refresh = function(scene) {
      var sceneObj = (scene) ? this.sceneList[scene] : this.currentScene;

      // Re-compile scene template
      sceneObj.refresh();
    };

    return SceneDirector;

  })();
});
<|endoftext|>


<commit_before>/*!
 * modernizr.min.js
 */
// =require vendor/modernizr.min.js

/*!
 * jquery-2.2.3.min.js
 */
// =require vendor/jquery-2.2.3.min.js

// Attempts to preserve comments that likely contain licensing information,
// even if the comment does not have directives such as `@license` or `/*!`.
//
// Implemented via the [`uglify-save-license`](https://github.com/shinnn/uglify-save-license)
// module, this option preserves a comment if one of the following is true:
//
// 1. The comment is in the *first* line of a file
// 2. A regular expression matches the string of the comment.
//    For example: `MIT`, `@license`, or `Copyright`.
// 3. There is a comment at the *previous* line, and it matches 1, 2, or 3.
<commit_msg>Removed jQuery version 2<commit_after>/*!
 * modernizr.min.js
 */
// =require vendor/modernizr.min.js

// =require vendor/semantic-js/semantic.min.js
// =require vendor/semantic-js/components/dropdown.min.js

// Attempts to preserve comments that likely contain licensing information,
// even if the comment does not have directives such as `@license` or `/*!`.
//
// Implemented via the [`uglify-save-license`](https://github.com/shinnn/uglify-save-license)
// module, this option preserves a comment if one of the following is true:
//
// 1. The comment is in the *first* line of a file
// 2. A regular expression matches the string of the comment.
//    For example: `MIT`, `@license`, or `Copyright`.
// 3. There is a comment at the *previous* line, and it matches 1, 2, or 3.
<|endoftext|>


<commit_before>import { connect } from 'react-redux';
import { PureComponent } from 'react';
import nipplejs from 'nipplejs';

class NippleJoystik extends PureComponent {
    componentDidMount(){

      const { onChange } = this.props;

      const options = {
        zone: this.joystick,
        mode: 'static',
        color: 'cyan',
        position: {top: '274px', left: '157px'}
      };

      const manager = nipplejs.create(options);

      manager.on('start end', function(evt, data) {
        console.log('stop all');
        onChange({ x:0, y:0 });
      }).on('move', function(evt, data) {
        let { force, angle: { radian } } = data;

        radian += Math.PI/4;

        const x = -force * Math.cos(radian);
        const y = force * Math.sin(radian);

        onChange({x, y});

      }).on('dir:up plain:up dir:left plain:left dir:down ' +
        'plain:down dir:right plain:right',
        function(evt, data) {
          console.log('stop all');
          onChange({ x:0, y:0 });
        }
      ).on('pressure', function(evt, data) {
        //not used
      });

    }

    render() {
        return

 this.joystick = node} id="nipple-joystick" />

;
    }
};

const connectToPlatform = connect(
  ({ platform:{ offset } }) => ({ x: offset.x, y: offset.y }),
  (dispatch) => ({ onChange: ({ x, y }) => dispatch({ type: 'platformMove', value: { x, y } }) }));

export default connectToPlatform(NippleJoystik);<commit_msg>reverse for nipple joystick<commit_after>import { connect } from 'react-redux';
import { PureComponent } from 'react';
import nipplejs from 'nipplejs';

class NippleJoystik extends PureComponent {
    componentDidMount(){

      const { onChange } = this.props;

      const options = {
        zone: this.joystick,
        mode: 'static',
        color: 'cyan',
        position: {top: '274px', left: '157px'}
      };

      const manager = nipplejs.create(options);

      manager.on('start end', function(evt, data) {
        console.log('stop all');
        onChange({ x:0, y:0 });
      }).on('move', function(evt, data) {
        let { force, angle: { radian } } = data;

        radian += Math.PI/4;

        const x = force * Math.cos(radian);
        const y = -force * Math.sin(radian);

        onChange({x, y});

      }).on('dir:up plain:up dir:left plain:left dir:down ' +
        'plain:down dir:right plain:right',
        function(evt, data) {
          console.log('stop all');
          onChange({ x:0, y:0 });
        }
      ).on('pressure', function(evt, data) {
        //not used
      });

    }

    render() {
        return

 this.joystick = node} id="nipple-joystick" />

;
    }
};

const connectToPlatform = connect(
  ({ platform:{ offset } }) => ({ x: offset.x, y: offset.y }),
  (dispatch) => ({ onChange: ({ x, y }) => dispatch({ type: 'platformMove', value: { x, y } }) }));

export default connectToPlatform(NippleJoystik);<|endoftext|>


<commit_before>import { Settings } from "api"
import AdvancedSelectFilter from "components/advancedSearch/AdvancedSelectFilter"
import AutocompleteFilter from "components/advancedSearch/AutocompleteFilter"
import CheckboxSearchFilter from "components/advancedSearch/CheckboxSearchFilter"
import DateRangeSearch from "components/advancedSearch/DateRangeSearch"
import OrganizationFilter from "components/advancedSearch/OrganizationFilter"
import PositionTypeSearchFilter from "components/advancedSearch/PositionTypeSearchFilter"
import ReportStateSearch from "components/advancedSearch/ReportStateSearch"
import SelectSearchFilter from "components/advancedSearch/SelectSearchFilter"
import TextInputFilter from "components/advancedSearch/TextInputFilter"
import LinkTo from "components/LinkTo"
import { Location, Organization, Person, Position, Tag, Task } from "models"
import pluralize from "pluralize"
import React from "react"
import PEOPLE_ICON from "resources/people.png"

export const POSTITION_POSITION_TYPE_FILTER_KEY = "Position Type"
export const POSTITION_ORGANIZATION_FILTER_KEY = "Organization"

const taskFilters = props => {
  const taskFiltersObj = {
    Organization: {
      component: OrganizationFilter,
      props: {
        queryKey: "responsibleOrgUuid",
        queryIncludeChildOrgsKey: "includeChildrenOrgs"
      }
    },
    Status: {
      component: SelectSearchFilter,
      props: {
        queryKey: "status",
        values: [Task.STATUS.ACTIVE, Task.STATUS.INACTIVE],
        labels: ["Active", "Inactive"]
      }
    }
  }
  const projectedCompletion = Settings.fields.task.projectedCompletion
  if (projectedCompletion) {
    taskFiltersObj[projectedCompletion.label] = {
      component: DateRangeSearch,
      props: {
        queryKey: "projectedCompletion"
      }
    }
  }
  const plannedCompletion = Settings.fields.task.plannedCompletion
  if (plannedCompletion) {
    taskFiltersObj[plannedCompletion.label] = {
      component: DateRangeSearch,
      props: {
        queryKey: "plannedCompletion"
      }
    }
  }
  const customEnum1 = Settings.fields.task.customFieldEnum1
  if (customEnum1) {
    taskFiltersObj[customEnum1.label] = {
      component: SelectSearchFilter,
      props: {
        queryKey: "projectStatus",
        values: Object.keys(customEnum1.enum),
        labels: Object.values(customEnum1.enum)
      }
    }
  }
  const customField = Settings.fields.task.customField
  if (customField) {
    taskFiltersObj[customField.label] = {
      component: TextInputFilter,
      props: {
        queryKey: "customField"
      }
    }
  }

  return taskFiltersObj
}

export default {
  searchFilters: function(positionTypeFilterRef, organizationFilterRef) {
    const filters = {}
    const authorFilters = {
      all: {
        label: "All",
        searchQuery: true,
        queryVars: { role: Person.ROLE.ADVISOR }
      }
    }
    const attendeeFilters = {
      all: {
        label: "All",
        searchQuery: true,
        queryVars: {}
      }
    }
    const renderPersonOverlayRow = item => {
      return (
        <React.Fragment key={item.uuid}>

            <LinkTo person={item} isLink={false} />

            <LinkTo position={item.position} isLink={false} />
            {item.position && item.position.code ? `, ${item.position.code}` : ""}

            <LinkTo
              whenUnspecified=""
              anetLocation={item.position && item.position.location}
              isLink={false}
            />

            {item.position && item.position.organization && (
              <LinkTo organization={item.position.organization} isLink={false} />
            )}

        </React.Fragment>
      )
    }
    filters.Reports = {
      filters: {
        Author: {
          component: AdvancedSelectFilter,
          props: {
            fieldName: "author",
            overlayColumns: ["Name", "Position", "Location", "Organization"],
            overlayRenderRow: renderPersonOverlayRow,
            filterDefs: authorFilters,
            objectType: Person,
            valueKey: "name",
            fields: Person.autocompleteQuery,
            placeholder: "Filter reports by author...",
            addon: PEOPLE_ICON,
            queryKey: "authorUuid"
          }
        },
        Attendee: {
          component: AdvancedSelectFilter,
          props: {
            fieldName: "attendee",
            overlayColumns: ["Name", "Position", "Location", "Organization"],
            overlayRenderRow: renderPersonOverlayRow,
            filterDefs: attendeeFilters,
            objectType: Person,
            valueKey: "name",
            fields: Person.autocompleteQuery,
            placeholder: "Filter reports by attendee...",
            addon: PEOPLE_ICON,
            queryKey: "attendeeUuid"
          }
        },
        "Pending Approval Of": {
          component: AutocompleteFilter,
          props: {
            queryKey: "pendingApprovalOf",
            objectType: Person,
            valueKey: "name",
            fields: Person.autocompleteQuery,
            template: Person.autocompleteTemplate,
            queryParams: { role: Person.ROLE.ADVISOR },
            placeholder: "Filter reports pending approval of..."
          }
        },
        "Author Position": {
          component: AutocompleteFilter,
          props: {
            queryKey: "authorPositionUuid",
            objectType: Position,
            valueKey: "name",
            fields: Position.autocompleteQuery,
            template: Position.autocompleteTemplate,
            queryParams: {
              type: [
                Position.TYPE.ADVISOR,
                Position.TYPE.SUPER_USER,
                Position.TYPE.ADMINISTRATOR
              ]
            },
            placeholder: "Filter reports by author position..."
          }
        },
        "Attendee Position": {
          component: AutocompleteFilter,
          props: {
            queryKey: "attendeePositionUuid",
            objectType: Position,
            valueKey: "name",
            fields: Position.autocompleteQuery,
            template: Position.autocompleteTemplate,
            placeholder: "Filter reports by attendee position..."
          }
        },
        Organization: {
          component: OrganizationFilter,
          props: {
            queryKey: "orgUuid",
            queryIncludeChildOrgsKey: "includeOrgChildren"
          }
        },
        "Engagement Date": {
          component: DateRangeSearch,
          props: {
            queryKey: "engagementDate"
          }
        },
        "Release Date": {
          component: DateRangeSearch,
          props: {
            queryKey: "releasedAt"
          }
        },
        "Creation Date": {
          component: DateRangeSearch,
          props: {
            queryKey: "createdAt"
          }
        },
        "Update Date": {
          component: DateRangeSearch,
          props: {
            queryKey: "updatedAt"
          }
        },
        Location: {
          component: AutocompleteFilter,
          props: {
            queryKey: "locationUuid",
            objectType: Location,
            valueKey: "name",
            fields: Location.autocompleteQuery,
            placeholder: "Filter reports by location..."
          }
        },
        State: {
          component: ReportStateSearch
        },
        [Settings.fields.report.atmosphere]: {
          component: SelectSearchFilter,
          props: {
            queryKey: "atmosphere",
            values: ["POSITIVE", "NEUTRAL", "NEGATIVE"]
          }
        },
        Tag: {
          component: AutocompleteFilter,
          props: {
            queryKey: "tagUuid",
            objectType: Tag,
            valueKey: "name",
            fields: Tag.autocompleteQuery,
            placeholder: "Filter reports by tag..."
          }
        },
        "Sensitive Info": {
          component: CheckboxSearchFilter,
          props: {
            queryKey: "sensitiveInfo"
          }
        }
      }
    }

    const taskShortLabel = Settings.fields.task.shortLabel
    filters.Reports.filters[taskShortLabel] = {
      component: AutocompleteFilter,
      props: {
        queryKey: "taskUuid",
        objectType: Task,
        valueKey: "shortName",
        fields: Task.autocompleteQuery,
        template: Task.autocompleteTemplate,
        placeholder: `Filter reports by ${taskShortLabel}...`
      }
    }

    const countries = Settings.fields.advisor.person.countries || [] // TODO: make search also work with principal countries
    const ranks = Settings.fields.person.ranks || []
    filters.People = {
      filters: {
        Organization: {
          component: OrganizationFilter,
          props: {
            queryKey: "orgUuid",
            queryIncludeChildOrgsKey: "includeChildOrgs"
          }
        },
        Role: {
          component: SelectSearchFilter,
          props: {
            queryKey: "role",
            values: [Person.ROLE.ADVISOR, Person.ROLE.PRINCIPAL],
            labels: [
              Settings.fields.advisor.person.name,
              Settings.fields.principal.person.name
            ]
          }
        },
        Status: {
          component: SelectSearchFilter,
          props: {
            queryKey: "status",
            values: [
              Person.STATUS.ACTIVE,
              Person.STATUS.INACTIVE,
              Person.STATUS.NEW_USER
            ]
          }
        },
        Location: {
          component: AutocompleteFilter,
          props: {
            queryKey: "locationUuid",
            objectType: Location,
            valueKey: "name",
            fields: Location.autocompleteQuery,
            placeholder: "Filter by location..."
          }
        },
        Rank: {
          component: SelectSearchFilter,
          props: {
            queryKey: "rank",
            values: ranks,
            labels: ranks
          }
        },
        Nationality: {
          component: SelectSearchFilter,
          props: {
            queryKey: "country",
            values: countries,
            labels: countries
          }
        }
      }
    }

    filters.Organizations = {
      filters: {
        Status: {
          component: SelectSearchFilter,
          props: {
            queryKey: "status",
            values: [Organization.STATUS.ACTIVE, Organization.STATUS.INACTIVE]
          }
        },
        "Organization Type": {
          component: SelectSearchFilter,
          props: {
            queryKey: "type",
            values: [
              Organization.TYPE.ADVISOR_ORG,
              Organization.TYPE.PRINCIPAL_ORG
            ],
            labels: [
              Settings.fields.advisor.org.name,
              Settings.fields.principal.org.name
            ]
          }
        }
      }
    }

    filters.Positions = {
      filters: {
        [POSTITION_POSITION_TYPE_FILTER_KEY]: {
          component: PositionTypeSearchFilter,
          props: {
            queryKey: "type",
            values: [Position.TYPE.ADVISOR, Position.TYPE.PRINCIPAL],
            labels: [
              Settings.fields.advisor.position.name,
              Settings.fields.principal.position.name
            ],
            ref: positionTypeFilterRef
          }
        },
        [POSTITION_ORGANIZATION_FILTER_KEY]: {
          component: OrganizationFilter,
          props: {
            queryKey: "organizationUuid",
            queryIncludeChildOrgsKey: "includeChildrenOrgs",
            ref: organizationFilterRef
          }
        },
        Status: {
          component: SelectSearchFilter,
          props: {
            queryKey: "status",
            values: [Position.STATUS.ACTIVE, Position.STATUS.INACTIVE]
          }
        },
        Location: {
          component: AutocompleteFilter,
          props: {
            queryKey: "locationUuid",
            objectType: Location,
            valueKey: "name",
            fields: Location.autocompleteQuery,
            placeholder: "Filter by location..."
          }
        },
        "Is Filled?": {
          component: SelectSearchFilter,
          props: {
            queryKey: "isFilled",
            values: ["true", "false"],
            labels: ["Yes", "No"]
          }
        }
      }
    }

    filters.Locations = {
      filters: {
        Status: {
          component: SelectSearchFilter,
          props: {
            queryKey: "status",
            values: [Location.STATUS.ACTIVE, Location.STATUS.INACTIVE]
          }
        }
      }
    }

    // Task filters
    filters[pluralize(taskShortLabel)] = {
      filters: taskFilters()
    }

    return filters
  },
  // filters not being displayed in the advanced search but being used in the search
  extraFilters: function(positionTypeFilterRef, organizationFilterRef) {
    const filters = {}
    filters.Reports = ["includeEngagementDayOfWeek", "sortOrder"]
    return filters
  }
}
<commit_msg>NCI-Agency/anet#1326: Use advanced select widget for author and attendee position report filters<commit_after>import { Settings } from "api"
import AdvancedSelectFilter from "components/advancedSearch/AdvancedSelectFilter"
import AutocompleteFilter from "components/advancedSearch/AutocompleteFilter"
import CheckboxSearchFilter from "components/advancedSearch/CheckboxSearchFilter"
import DateRangeSearch from "components/advancedSearch/DateRangeSearch"
import OrganizationFilter from "components/advancedSearch/OrganizationFilter"
import PositionTypeSearchFilter from "components/advancedSearch/PositionTypeSearchFilter"
import ReportStateSearch from "components/advancedSearch/ReportStateSearch"
import SelectSearchFilter from "components/advancedSearch/SelectSearchFilter"
import TextInputFilter from "components/advancedSearch/TextInputFilter"
import LinkTo from "components/LinkTo"
import { Location, Organization, Person, Position, Tag, Task } from "models"
import pluralize from "pluralize"
import React from "react"
import PEOPLE_ICON from "resources/people.png"
import POSITIONS_ICON from "resources/positions.png"

export const POSTITION_POSITION_TYPE_FILTER_KEY = "Position Type"
export const POSTITION_ORGANIZATION_FILTER_KEY = "Organization"

const taskFilters = props => {
  const taskFiltersObj = {
    Organization: {
      component: OrganizationFilter,
      props: {
        queryKey: "responsibleOrgUuid",
        queryIncludeChildOrgsKey: "includeChildrenOrgs"
      }
    },
    Status: {
      component: SelectSearchFilter,
      props: {
        queryKey: "status",
        values: [Task.STATUS.ACTIVE, Task.STATUS.INACTIVE],
        labels: ["Active", "Inactive"]
      }
    }
  }
  const projectedCompletion = Settings.fields.task.projectedCompletion
  if (projectedCompletion) {
    taskFiltersObj[projectedCompletion.label] = {
      component: DateRangeSearch,
      props: {
        queryKey: "projectedCompletion"
      }
    }
  }
  const plannedCompletion = Settings.fields.task.plannedCompletion
  if (plannedCompletion) {
    taskFiltersObj[plannedCompletion.label] = {
      component: DateRangeSearch,
      props: {
        queryKey: "plannedCompletion"
      }
    }
  }
  const customEnum1 = Settings.fields.task.customFieldEnum1
  if (customEnum1) {
    taskFiltersObj[customEnum1.label] = {
      component: SelectSearchFilter,
      props: {
        queryKey: "projectStatus",
        values: Object.keys(customEnum1.enum),
        labels: Object.values(customEnum1.enum)
      }
    }
  }
  const customField = Settings.fields.task.customField
  if (customField) {
    taskFiltersObj[customField.label] = {
      component: TextInputFilter,
      props: {
        queryKey: "customField"
      }
    }
  }

  return taskFiltersObj
}

const renderPersonOverlayRow = item => {
  return (
    <React.Fragment key={item.uuid}>

        <LinkTo person={item} isLink={false} />

        <LinkTo position={item.position} isLink={false} />
        {item.position && item.position.code ? `, ${item.position.code}` : ""}

        <LinkTo
          whenUnspecified=""
          anetLocation={item.position && item.position.location}
          isLink={false}
        />

        {item.position && item.position.organization && (
          <LinkTo organization={item.position.organization} isLink={false} />
        )}

    </React.Fragment>
  )
}

const renderPositionOverlayRow = item => {
  return (
    <React.Fragment key={item.uuid}>

        <LinkTo person={item.person} isLink={false} />

        <LinkTo position={item} isLink={false} />

    </React.Fragment>
  )
}

const advancedSelectFilterPersonProps = {
  overlayColumns: ["Name", "Position", "Location", "Organization"],
  overlayRenderRow: renderPersonOverlayRow,
  objectType: Person,
  valueKey: "name",
  fields: Person.autocompleteQuery,
  addon: PEOPLE_ICON
}
const advancedSelectFilterPositionProps = {
  overlayColumns: ["Name", "Position", "Location", "Organization"],
  overlayRenderRow: renderPositionOverlayRow,
  objectType: Position,
  valueKey: "name",
  fields: Position.autocompleteQuery,
  addon: POSITIONS_ICON
}

export default {
  searchFilters: function(positionTypeFilterRef, organizationFilterRef) {
    const filters = {}
    const authorFilters = {
      all: {
        label: "All",
        searchQuery: true,
        queryVars: { role: Person.ROLE.ADVISOR }
      }
    }
    const attendeeFilters = {
      all: {
        label: "All",
        searchQuery: true,
        queryVars: {}
      }
    }
    const pendingApprovalOfFilters = authorFilters
    const authorPositionFilters = {
      all: {
        label: "All",
        searchQuery: true,
        queryVars: {
          type: [
            Position.TYPE.ADVISOR,
            Position.TYPE.SUPER_USER,
            Position.TYPE.ADMINISTRATOR
          ]
        }
      }
    }
    const attendeePositionFilters = {
      all: {
        label: "All",
        searchQuery: true,
        queryVars: {}
      }
    }

    filters.Reports = {
      filters: {
        Author: {
          component: AdvancedSelectFilter,
          props: Object.assign({}, advancedSelectFilterPersonProps, {
            fieldName: "author",
            filterDefs: authorFilters,
            placeholder: "Filter reports by author...",
            queryKey: "authorUuid"
          })
        },
        Attendee: {
          component: AdvancedSelectFilter,
          props: Object.assign({}, advancedSelectFilterPersonProps, {
            fieldName: "attendee",
            filterDefs: attendeeFilters,
            placeholder: "Filter reports by attendee...",
            queryKey: "attendeeUuid"
          })
        },
        "Pending Approval Of": {
          component: AdvancedSelectFilter,
          props: Object.assign({}, advancedSelectFilterPersonProps, {
            fieldName: "pendingApprovalOf",
            filterDefs: pendingApprovalOfFilters,
            placeholder: "Filter reports pending approval of...",
            queryKey: "pendingApprovalOf"
          })
        },
        "Author Position": {
          component: AdvancedSelectFilter,
          props: Object.assign({}, advancedSelectFilterPositionProps, {
            fieldName: "authorPosition",
            filterDefs: authorPositionFilters,
            placeholder: "Filter reports by author position...",
            queryKey: "authorPositionUuid"
          })
        },
        "Attendee Position": {
          component: AdvancedSelectFilter,
          props: Object.assign({}, advancedSelectFilterPositionProps, {
            fieldName: "attendeePosition",
            filterDefs: attendeePositionFilters,
            placeholder: "Filter reports by attendee position...",
            queryKey: "attendeePositionUuid"
          })
        },
        Organization: {
          component: OrganizationFilter,
          props: {
            queryKey: "orgUuid",
            queryIncludeChildOrgsKey: "includeOrgChildren"
          }
        },
        "Engagement Date": {
          component: DateRangeSearch,
          props: {
            queryKey: "engagementDate"
          }
        },
        "Release Date": {
          component: DateRangeSearch,
          props: {
            queryKey: "releasedAt"
          }
        },
        "Creation Date": {
          component: DateRangeSearch,
          props: {
            queryKey: "createdAt"
          }
        },
        "Update Date": {
          component: DateRangeSearch,
          props: {
            queryKey: "updatedAt"
          }
        },
        Location: {
          component: AutocompleteFilter,
          props: {
            queryKey: "locationUuid",
            objectType: Location,
            valueKey: "name",
            fields: Location.autocompleteQuery,
            placeholder: "Filter reports by location..."
          }
        },
        State: {
          component: ReportStateSearch
        },
        [Settings.fields.report.atmosphere]: {
          component: SelectSearchFilter,
          props: {
            queryKey: "atmosphere",
            values: ["POSITIVE", "NEUTRAL", "NEGATIVE"]
          }
        },
        Tag: {
          component: AutocompleteFilter,
          props: {
            queryKey: "tagUuid",
            objectType: Tag,
            valueKey: "name",
            fields: Tag.autocompleteQuery,
            placeholder: "Filter reports by tag..."
          }
        },
        "Sensitive Info": {
          component: CheckboxSearchFilter,
          props: {
            queryKey: "sensitiveInfo"
          }
        }
      }
    }

    const taskShortLabel = Settings.fields.task.shortLabel
    filters.Reports.filters[taskShortLabel] = {
      component: AutocompleteFilter,
      props: {
        queryKey: "taskUuid",
        objectType: Task,
        valueKey: "shortName",
        fields: Task.autocompleteQuery,
        template: Task.autocompleteTemplate,
        placeholder: `Filter reports by ${taskShortLabel}...`
      }
    }

    const countries = Settings.fields.advisor.person.countries || [] // TODO: make search also work with principal countries
    const ranks = Settings.fields.person.ranks || []
    filters.People = {
      filters: {
        Organization: {
          component: OrganizationFilter,
          props: {
            queryKey: "orgUuid",
            queryIncludeChildOrgsKey: "includeChildOrgs"
          }
        },
        Role: {
          component: SelectSearchFilter,
          props: {
            queryKey: "role",
            values: [Person.ROLE.ADVISOR, Person.ROLE.PRINCIPAL],
            labels: [
              Settings.fields.advisor.person.name,
              Settings.fields.principal.person.name
            ]
          }
        },
        Status: {
          component: SelectSearchFilter,
          props: {
            queryKey: "status",
            values: [
              Person.STATUS.ACTIVE,
              Person.STATUS.INACTIVE,
              Person.STATUS.NEW_USER
            ]
          }
        },
        Location: {
          component: AutocompleteFilter,
          props: {
            queryKey: "locationUuid",
            objectType: Location,
            valueKey: "name",
            fields: Location.autocompleteQuery,
            placeholder: "Filter by location..."
          }
        },
        Rank: {
          component: SelectSearchFilter,
          props: {
            queryKey: "rank",
            values: ranks,
            labels: ranks
          }
        },
        Nationality: {
          component: SelectSearchFilter,
          props: {
            queryKey: "country",
            values: countries,
            labels: countries
          }
        }
      }
    }

    filters.Organizations = {
      filters: {
        Status: {
          component: SelectSearchFilter,
          props: {
            queryKey: "status",
            values: [Organization.STATUS.ACTIVE, Organization.STATUS.INACTIVE]
          }
        },
        "Organization Type": {
          component: SelectSearchFilter,
          props: {
            queryKey: "type",
            values: [
              Organization.TYPE.ADVISOR_ORG,
              Organization.TYPE.PRINCIPAL_ORG
            ],
            labels: [
              Settings.fields.advisor.org.name,
              Settings.fields.principal.org.name
            ]
          }
        }
      }
    }

    filters.Positions = {
      filters: {
        [POSTITION_POSITION_TYPE_FILTER_KEY]: {
          component: PositionTypeSearchFilter,
          props: {
            queryKey: "type",
            values: [Position.TYPE.ADVISOR, Position.TYPE.PRINCIPAL],
            labels: [
              Settings.fields.advisor.position.name,
              Settings.fields.principal.position.name
            ],
            ref: positionTypeFilterRef
          }
        },
        [POSTITION_ORGANIZATION_FILTER_KEY]: {
          component: OrganizationFilter,
          props: {
            queryKey: "organizationUuid",
            queryIncludeChildOrgsKey: "includeChildrenOrgs",
            ref: organizationFilterRef
          }
        },
        Status: {
          component: SelectSearchFilter,
          props: {
            queryKey: "status",
            values: [Position.STATUS.ACTIVE, Position.STATUS.INACTIVE]
          }
        },
        Location: {
          component: AutocompleteFilter,
          props: {
            queryKey: "locationUuid",
            objectType: Location,
            valueKey: "name",
            fields: Location.autocompleteQuery,
            placeholder: "Filter by location..."
          }
        },
        "Is Filled?": {
          component: SelectSearchFilter,
          props: {
            queryKey: "isFilled",
            values: ["true", "false"],
            labels: ["Yes", "No"]
          }
        }
      }
    }

    filters.Locations = {
      filters: {
        Status: {
          component: SelectSearchFilter,
          props: {
            queryKey: "status",
            values: [Location.STATUS.ACTIVE, Location.STATUS.INACTIVE]
          }
        }
      }
    }

    // Task filters
    filters[pluralize(taskShortLabel)] = {
      filters: taskFilters()
    }

    return filters
  },
  // filters not being displayed in the advanced search but being used in the search
  extraFilters: function(positionTypeFilterRef, organizationFilterRef) {
    const filters = {}
    filters.Reports = ["includeEngagementDayOfWeek", "sortOrder"]
    return filters
  }
}
<|endoftext|>


<commit_before>// @flow

export type ResourceDefinition = {
  path: string,
  propType: ReactPropsCheckType
}
<commit_msg>Removed unused type<commit_after><|endoftext|>


<commit_before>Template.eventEdit.onCreated(function() {
	var instance = this;
	instance.parent = instance.parentInstance();
	instance.selectedRegion = new ReactiveVar(this.data.region || Session.get('region'));
	instance.selectedLocation = new ReactiveVar(this.data.venue || {});

	instance.uploaded = new ReactiveVar([]);

	this.data.editableDescription = makeEditable(
		this.data.description,
		false,
		false,
		mf('event.description.placeholder', 'Describe your event as accurately as possible. This helps people to know how to prepare and what to expect from this meeting (eg. level, prerequisites, activities, teaching methods, what to bring, et cetera)'),
		false
	);
});

Template.eventEdit.onRendered(function() {
	updateTimes(this, false);

	this.$('.js-event-start-date').datepicker({
		weekStart: moment.localeData().firstDayOfWeek(),
		language: moment.locale(),
		autoclose: true,
		startDate: new Date(),
		format: {
			toDisplay: function(date) {
				return moment(date).format('L');
			},
			toValue: function(date) {
				return moment(date, 'L').toDate();
			}
		}
	});
});

Template.eventEdit.helpers({

	hasParentCourse: function() {
		return !! this.courseId;
	},

	localDate: function(date) {
		return moment(date).format("L");
	},

	affectedReplicaCount: function() {
		Template.instance().subscribe('affectedReplica', this._id);
		return Events.find(affectedReplicaSelectors(this)).count();
	},

	regions: function(){
		return Regions.find();
	},

	showRegionSelection: function() {
		// You can select the region for events that are new and not associated
		// with a course
		if (this._id) return false;
		if (this.courseId) return false;
		return true;
	},

	currentRegion: function(region) {
		var currentRegion = Session.get('region');
		return currentRegion && region._id == currentRegion;
	},

	showLocationSelection: function(region) {
		var selectedRegion = Template.instance().selectedRegion.get();
		return selectedRegion && selectedRegion !== 'all';
	},

	disableForPast: function() {
		return this.start > new Date() ? '' : 'disabled';
	},

	isInternal: function() {
		return this.internal ? "checked" : null;
	},

	uploaded: function() {
		return Template.instance().uploaded.get();
	}
});

var readDateTime = function(dateStr, timeStr) {
	return moment(dateStr+' '+timeStr, 'L LT');
};

var getEventStartMoment = function(template) {
	return readDateTime(
		template.$('.js-event-start-date').val(),
		template.$('#editEventStartTime').val()
	);
};

var getEventEndMoment = function(template) {
	var startMoment = getEventStartMoment(template);
	var endMoment = readDateTime(
		startMoment.format('L'),
		template.$('#editEventEndTime').val()
	);

	// If the end time is earlier than the start time, assume the event
	// spans into the next day. This might result in some weird behavior
	// around hour-lapses due to DST (where 1:30 may be 'later'	than 2:00).
	// Well maybe you shouldn't schedule your events to start or end
	// in these politically fucked hours.
	if (endMoment.diff(startMoment) < 0) {
		endMoment = readDateTime(
			startMoment.add(1, 'day').format('L'),
			template.$('#editEventEndTime').val()
		);
	}

	return endMoment;
};

var getEventDuration = function(template) {
	var duration = parseInt(template.$('#editEventDuration').val(), 10);
	return Math.max(0,duration);
};

/* Patch the end time and the duration when start, end or duration changes */
var updateTimes = function(template, updateEnd) {
	var start = getEventStartMoment(template);
	var end = getEventEndMoment(template);
	var duration = getEventDuration(template);
	if (!start.isValid() || !end.isValid()) {
		// If you put into the machine wrong figures, will the right answers come out?
		return;
	}

	if (updateEnd) {
		end = moment(start).add(duration, 'minutes');
	}

	if (end.isBefore(start)) {
		// Let sanity prevail
		end = start;
		duration = 0;
	}

	duration = end.diff(start, 'minutes');
	template.$('#edit_event_startdate').val(start.format('L'));
	template.$('#editEventStartTime').val(start.format('LT'));
	template.$('#editEventEndTime').val(end.format('LT'));
	template.$('#editEventDuration').val(duration.toString());
};

Template.eventEdit.events({
	'change .js-event-add-file': function(event, instance) {
		FS.Utility.eachFile(event, function(file) {
			Files.insert(file, function (err, fileObj) {
				if (err) {
					addMessage(mf('file.upload.error', "Uploading file '" + fileObj.original.name + "; failed"));
				} else {
					var uploaded = instance.uploaded.get();

					uploaded.push({
						_id: fileObj._id,
						file : "/cfs/files/files/" + fileObj._id,
						filename : fileObj.original.name,
						filesize : fileObj.original.size,
					});

					instance.uploaded.set(uploaded);
				}
			});
		});
	},

	'click .js-delete-file': function (event, instance) {
		var fileId = this._id;
		var eventId = instance.data._id;
		var filename = this.filename;

		// check whether the file hasn't been associated with the event yet
		var uploaded = instance.uploaded.get();
		var uploadedClean = _.reject(uploaded, function(file) { return file._id === fileId; });
		if (uploadedClean.length < uploaded.length) {
			// The server does not allow to delete files that are not associated
			// to an event. So we just remove the local reference and hope
			// somebody will clean up stray files on the server
			instance.uploaded.set(uploadedClean);
			return;
		}

		Meteor.call('removeFile', eventId, fileId, function(error) {
			if (error) {
				showServerError("Couldn't remove file '" + filename + "'", error);
			} else {
				addMessage(mf('file.removed', { FILENAME:filename }, 'Removed file {FILENAME}.'), 'success');
			}
		});
	},

	'submit': function(event, instance) {
		event.preventDefault();

		if (pleaseLogin()) return;

		var start = getEventStartMoment(instance);
		if(!start.isValid()) {
			var exampleDate = moment().format('L');
			alert(mf('event.edit.dateFormatWarning', { EXAMPLEDATE: exampleDate }, "Date format must be of the form {EXAMPLEDATE}"));
			return null;
		}
		var end = getEventEndMoment(instance);

		var editevent = {
			title: instance.$('#eventEditTitle').val(),
			venue: instance.selectedLocation.get(),
			room: instance.$('#eventEditRoom').val(),
			start: start.toDate(),
			end:   end.toDate(),
			internal: instance.$('.js-check-event-internal').is(':checked'),
		};

		var newDescription = instance.data.editableDescription.editedContent();
		if (newDescription) editevent.description = newDescription;

		editevent.files = (this.files || []).concat(instance.uploaded.get());

		var eventId = this._id;
		var isNew = !this._id;
		var now = moment();
		if (isNew) {
			eventId = '';

			if (start.isBefore(now)) {
				alert("Date must be in future");
				return;
			}

			if (this.courseId) {
				var course = Courses.findOne(this.courseId);
				editevent.region = course.region;
				editevent.courseId = this.courseId;
			} else {
				editevent.region = instance.selectedRegion.get();
				if (!editevent.region || editevent.region === 'all') {
					alert(mf('event.edit.plzSelectRegion', "Please select the region for this event"));
					return null;
				}

				// We have this 'secret' feature where you can set a group ID
				// in the URL to assign a group to the event on creation
				var groups = [];
				if (Router.current().params.query.group) {
					groups.push(Router.current().params.query.group);
				}
				editevent.groups = groups;
			}
		} else {
			// Don't allow setting dates in the past
			if (start.isBefore(now)) {
				delete editevent.start;
			}
			if (end.isBefore(now)) {
				delete editevent.end;
			}
		}

		var updateReplicas = instance.$("input[name='updateReplicas']").is(':checked');

		Meteor.call('saveEvent', eventId, editevent, updateReplicas, function(error, eventId) {
			if (error) {
				showServerError('Saving the event went wrong', error);
			} else {
				if (isNew) {
					Router.go('showEvent', { _id: eventId });
					addMessage("\u2713 " + mf('_message.saved'), 'success');
				} else {
					addMessage("\u2713 " + mf('_message.saved'), 'success');
				}

				if (updateReplicas) {
					addMessage(mf('event.edit.replicates.success', { TITLE: editevent.title }, 'Replicas of "{TITLE}" also updated.'), 'success');
				}
				instance.parent.editing.set(false);
			}
		});
	},

	'click .js-event-edit-cancel': function (event, instance) {
		if (instance.data.new) history.back();
		instance.parent.editing.set(false);
	},

	'click .js-toggle-duration': function(event, instance){
		Tooltips.hide();
		$('.time-end > *').toggle();
	},

	'change #editEventDuration, change #edit_event_startdate, change #editEventStartTime': function(event, template) {
		updateTimes(template, true);
	},

	'change #editEventEndTime': function(event, template) {
		updateTimes(template, false);
	},

	'change .js-select-region': function(event, instance) {
		instance.selectedRegion.set(instance.$('.js-select-region').val());
	},
});
<commit_msg>add alerts to inform user about missing information ..instead of error messages<commit_after>Template.eventEdit.onCreated(function() {
	var instance = this;
	instance.parent = instance.parentInstance();
	instance.selectedRegion = new ReactiveVar(this.data.region || Session.get('region'));
	instance.selectedLocation = new ReactiveVar(this.data.venue || {});

	instance.uploaded = new ReactiveVar([]);

	this.data.editableDescription = makeEditable(
		this.data.description,
		false,
		false,
		mf('event.description.placeholder', 'Describe your event as accurately as possible. This helps people to know how to prepare and what to expect from this meeting (eg. level, prerequisites, activities, teaching methods, what to bring, et cetera)'),
		false
	);
});

Template.eventEdit.onRendered(function() {
	updateTimes(this, false);

	this.$('.js-event-start-date').datepicker({
		weekStart: moment.localeData().firstDayOfWeek(),
		language: moment.locale(),
		autoclose: true,
		startDate: new Date(),
		format: {
			toDisplay: function(date) {
				return moment(date).format('L');
			},
			toValue: function(date) {
				return moment(date, 'L').toDate();
			}
		}
	});
});

Template.eventEdit.helpers({

	hasParentCourse: function() {
		return !! this.courseId;
	},

	localDate: function(date) {
		return moment(date).format("L");
	},

	affectedReplicaCount: function() {
		Template.instance().subscribe('affectedReplica', this._id);
		return Events.find(affectedReplicaSelectors(this)).count();
	},

	regions: function(){
		return Regions.find();
	},

	showRegionSelection: function() {
		// You can select the region for events that are new and not associated
		// with a course
		if (this._id) return false;
		if (this.courseId) return false;
		return true;
	},

	currentRegion: function(region) {
		var currentRegion = Session.get('region');
		return currentRegion && region._id == currentRegion;
	},

	showLocationSelection: function(region) {
		var selectedRegion = Template.instance().selectedRegion.get();
		return selectedRegion && selectedRegion !== 'all';
	},

	disableForPast: function() {
		return this.start > new Date() ? '' : 'disabled';
	},

	isInternal: function() {
		return this.internal ? "checked" : null;
	},

	uploaded: function() {
		return Template.instance().uploaded.get();
	}
});

var readDateTime = function(dateStr, timeStr) {
	return moment(dateStr+' '+timeStr, 'L LT');
};

var getEventStartMoment = function(template) {
	return readDateTime(
		template.$('.js-event-start-date').val(),
		template.$('#editEventStartTime').val()
	);
};

var getEventEndMoment = function(template) {
	var startMoment = getEventStartMoment(template);
	var endMoment = readDateTime(
		startMoment.format('L'),
		template.$('#editEventEndTime').val()
	);

	// If the end time is earlier than the start time, assume the event
	// spans into the next day. This might result in some weird behavior
	// around hour-lapses due to DST (where 1:30 may be 'later'	than 2:00).
	// Well maybe you shouldn't schedule your events to start or end
	// in these politically fucked hours.
	if (endMoment.diff(startMoment) < 0) {
		endMoment = readDateTime(
			startMoment.add(1, 'day').format('L'),
			template.$('#editEventEndTime').val()
		);
	}

	return endMoment;
};

var getEventDuration = function(template) {
	var duration = parseInt(template.$('#editEventDuration').val(), 10);
	return Math.max(0,duration);
};

/* Patch the end time and the duration when start, end or duration changes */
var updateTimes = function(template, updateEnd) {
	var start = getEventStartMoment(template);
	var end = getEventEndMoment(template);
	var duration = getEventDuration(template);
	if (!start.isValid() || !end.isValid()) {
		// If you put into the machine wrong figures, will the right answers come out?
		return;
	}

	if (updateEnd) {
		end = moment(start).add(duration, 'minutes');
	}

	if (end.isBefore(start)) {
		// Let sanity prevail
		end = start;
		duration = 0;
	}

	duration = end.diff(start, 'minutes');
	template.$('#edit_event_startdate').val(start.format('L'));
	template.$('#editEventStartTime').val(start.format('LT'));
	template.$('#editEventEndTime').val(end.format('LT'));
	template.$('#editEventDuration').val(duration.toString());
};

Template.eventEdit.events({
	'change .js-event-add-file': function(event, instance) {
		FS.Utility.eachFile(event, function(file) {
			Files.insert(file, function (err, fileObj) {
				if (err) {
					addMessage(mf('file.upload.error', "Uploading file '" + fileObj.original.name + "; failed"));
				} else {
					var uploaded = instance.uploaded.get();

					uploaded.push({
						_id: fileObj._id,
						file : "/cfs/files/files/" + fileObj._id,
						filename : fileObj.original.name,
						filesize : fileObj.original.size,
					});

					instance.uploaded.set(uploaded);
				}
			});
		});
	},

	'click .js-delete-file': function (event, instance) {
		var fileId = this._id;
		var eventId = instance.data._id;
		var filename = this.filename;

		// check whether the file hasn't been associated with the event yet
		var uploaded = instance.uploaded.get();
		var uploadedClean = _.reject(uploaded, function(file) { return file._id === fileId; });
		if (uploadedClean.length < uploaded.length) {
			// The server does not allow to delete files that are not associated
			// to an event. So we just remove the local reference and hope
			// somebody will clean up stray files on the server
			instance.uploaded.set(uploadedClean);
			return;
		}

		Meteor.call('removeFile', eventId, fileId, function(error) {
			if (error) {
				showServerError("Couldn't remove file '" + filename + "'", error);
			} else {
				addMessage(mf('file.removed', { FILENAME:filename }, 'Removed file {FILENAME}.'), 'success');
			}
		});
	},

	'submit': function(event, instance) {
		event.preventDefault();

		if (pleaseLogin()) return;

		var start = getEventStartMoment(instance);
		if(!start.isValid()) {
			var exampleDate = moment().format('L');
			alert(mf('event.edit.dateFormatWarning', { EXAMPLEDATE: exampleDate }, "Date format must be of the form {EXAMPLEDATE}"));
			return null;
		}
		var end = getEventEndMoment(instance);

		var editevent = {
			title: instance.$('#eventEditTitle').val(),
			venue: instance.selectedLocation.get(),
			room: instance.$('#eventEditRoom').val(),
			start: start.toDate(),
			end:   end.toDate(),
			internal: instance.$('.js-check-event-internal').is(':checked'),
		};

		var newDescription = instance.data.editableDescription.editedContent();
		if (newDescription) editevent.description = newDescription;

		if (editevent.title.length === 0) {
			alert(mf('event.edit.plzProvideTitle', "Please provide a title"));
			return;
		}

		if (!editevent.description) {
			alert(mf('event.edit.plzProvideDescr', "Please provide a description"));
			return;
		}

		editevent.files = (this.files || []).concat(instance.uploaded.get());

		var eventId = this._id;
		var isNew = !this._id;
		var now = moment();
		if (isNew) {
			eventId = '';

			if (start.isBefore(now)) {
				alert("Date must be in future");
				return;
			}

			if (this.courseId) {
				var course = Courses.findOne(this.courseId);
				editevent.region = course.region;
				editevent.courseId = this.courseId;
			} else {
				editevent.region = instance.selectedRegion.get();
				if (!editevent.region || editevent.region === 'all') {
					alert(mf('event.edit.plzSelectRegion', "Please select the region for this event"));
					return null;
				}

				// We have this 'secret' feature where you can set a group ID
				// in the URL to assign a group to the event on creation
				var groups = [];
				if (Router.current().params.query.group) {
					groups.push(Router.current().params.query.group);
				}
				editevent.groups = groups;
			}
		} else {
			// Don't allow setting dates in the past
			if (start.isBefore(now)) {
				delete editevent.start;
			}
			if (end.isBefore(now)) {
				delete editevent.end;
			}
		}

		var updateReplicas = instance.$("input[name='updateReplicas']").is(':checked');

		Meteor.call('saveEvent', eventId, editevent, updateReplicas, function(error, eventId) {
			if (error) {
				showServerError('Saving the event went wrong', error);
			} else {
				if (isNew) {
					Router.go('showEvent', { _id: eventId });
					addMessage("\u2713 " + mf('_message.saved'), 'success');
				} else {
					addMessage("\u2713 " + mf('_message.saved'), 'success');
				}

				if (updateReplicas) {
					addMessage(mf('event.edit.replicates.success', { TITLE: editevent.title }, 'Replicas of "{TITLE}" also updated.'), 'success');
				}
				instance.parent.editing.set(false);
			}
		});
	},

	'click .js-event-edit-cancel': function (event, instance) {
		if (instance.data.new) history.back();
		instance.parent.editing.set(false);
	},

	'click .js-toggle-duration': function(event, instance){
		Tooltips.hide();
		$('.time-end > *').toggle();
	},

	'change #editEventDuration, change #edit_event_startdate, change #editEventStartTime': function(event, template) {
		updateTimes(template, true);
	},

	'change #editEventEndTime': function(event, template) {
		updateTimes(template, false);
	},

	'change .js-select-region': function(event, instance) {
		instance.selectedRegion.set(instance.$('.js-select-region').val());
	},
});
<|endoftext|>


<commit_before>import {GraphQLNonNull, GraphQLID, GraphQLString} from 'graphql'
import {GraphQLURL, GraphQLDateTime} from 'graphql-custom-types'
import {GraphQLObjectType, GraphQLList} from 'graphql/type'

import {resolveChapter, resolveCycle} from 'src/server/graphql/resolvers'

export default new GraphQLObjectType({
  name: 'ProjectWithReviewResponses',
  description: 'A project which includes any project review survey responses for the current user',
  fields: () => {
    const {Chapter, Cycle, ProjectReviewResponse} = require('src/server/graphql/schemas')

    return {
      id: {type: new GraphQLNonNull(GraphQLID), description: "The project's UUID"},
      name: {type: new GraphQLNonNull(GraphQLString), description: 'The project name'},
      artifactURL: {type: GraphQLURL, description: 'The URL pointing to the output of this project'},
      createdAt: {type: new GraphQLNonNull(GraphQLDateTime), description: 'When this record was created'},
      updatedAt: {type: new GraphQLNonNull(GraphQLDateTime), description: 'When this record was last updated'},
      chapter: {type: Chapter, description: 'The chapter', resolve: resolveChapter},
      cycle: {type: Cycle, description: 'The cycle', resolve: resolveCycle},
      projectReviewResponses: {
        type: new GraphQLList(ProjectReviewResponse),
        description: 'The responses to the named questions on the project review survey',
      },
    }
  },
})
<commit_msg>ProjectWithReviewResponses: include goal info<commit_after>import {GraphQLNonNull, GraphQLID, GraphQLString} from 'graphql'
import {GraphQLURL, GraphQLDateTime} from 'graphql-custom-types'
import {GraphQLObjectType, GraphQLList} from 'graphql/type'

import {resolveChapter, resolveCycle, resolveProjectGoal} from 'src/server/graphql/resolvers'

export default new GraphQLObjectType({
  name: 'ProjectWithReviewResponses',
  description: 'A project which includes any project review survey responses for the current user',
  fields: () => {
    const {Chapter, Cycle, Goal, ProjectReviewResponse} = require('src/server/graphql/schemas')

    return {
      id: {type: new GraphQLNonNull(GraphQLID), description: "The project's UUID"},
      name: {type: new GraphQLNonNull(GraphQLString), description: 'The project name'},
      goal: {type: Goal, description: 'The project goal', resolve: resolveProjectGoal},
      artifactURL: {type: GraphQLURL, description: 'The URL pointing to the output of this project'},
      createdAt: {type: new GraphQLNonNull(GraphQLDateTime), description: 'When this record was created'},
      updatedAt: {type: new GraphQLNonNull(GraphQLDateTime), description: 'When this record was last updated'},
      chapter: {type: Chapter, description: 'The chapter', resolve: resolveChapter},
      cycle: {type: Cycle, description: 'The cycle', resolve: resolveCycle},
      projectReviewResponses: {
        type: new GraphQLList(ProjectReviewResponse),
        description: 'The responses to the named questions on the project review survey',
      },
    }
  },
})
<|endoftext|>


<commit_before>var TelemetryData=require('./models/TelemetryData');
var StatusManager=require('./StatusManager');
var Bitmask=require('./util/Bitmask');
var Validator=require('./util/Validator');
var Logger=require('./util/Logger');

var AircraftStatus=function(){
  this.killModeActive=false;
  this.killModeWarning=false;
  this.armed=false;
  this.initializing=false;
  this.running=false;
  this.manualMode=false;
  this.xbee={//has not been implemented yet from the picpilots side
    status:false,
    timeSinceLost:null
  };
  this.gps={
    status: false,
    timeSinceLost: null
  };
  this.uhf={
    status: false,
    timeSinceLost: null
  };

  this.pastErrorCode=null;
  this.startup_errors={
    POWER_ON_RESET: false,
    BROWN_OUT_RESET: false,
    IDLE_MODE_RESET: false,
    SLEEP_MODE_RESET: false,
    SOFTWARE_WATCH_DOG_RESET: false,
    SOFTWARE_RESET: false,
    EXTERNAL_RESET: false,
    VOLTAGE_REGULATOR_RESET: false,
    ILLEGAL_OPCODE_RESET: false,
    TRAP_RESET: false
  };

  TelemetryData.on('data_received',function(data){
    this.checkErrorCodes(data.startup_error_codes);
    this.checkGPS(data.gps_status);
    this.checkUHFStatus(data.wireless_connection);
    this.checkManualMode(data.wireless_connection);
    this.checkPlaneStatus(data.autopilot_active);
  }.bind(this));

  this.checkPlaneStatus=function(number){
    if(!Validator.isValidNumber(number)){
      Logger.warn('Invalid value for autopilot_active received. Value: '+number);
    }
    else{
      var bitmask=new Bitmask(Number(number));
      this.initializing=bitmask.getBit(0);
      this.armed=bitmask.getBit(1);
      this.running=bitmask.getBit(2);
      this.killModeWarning=bitmask.getBit(3);
      this.killModeActive=bitmask.getBit(4);

      StatusManager.setStatusCode('AIRCRAFT_INITIALIZE',this.initializing);
      StatusManager.setStatusCode('AIRCRAFT_ARMED',this.armed);
      StatusManager.setStatusCode('AIRCRAFT_RUNNING',this.running);
      StatusManager.setStatusCode('AIRCRAFT_KILLMODE_WARNING',this.killModeWarning);
      StatusManager.setStatusCode('AIRCRAFT_KILLMODE',this.killModeActive);
    }
  };

  this.checkUHFStatus=function(data){
    var number=Number(data);
    if(!Validator.isInteger(number)){
      Logger.warn('Invalid value for wireless_connection received. Value: '+data);
    }
    else{
      var bitmask=new Bitmask(number);
      this.uhf.status= bitmask.getBit(1);

      if(this.uhf.status){ //has been turned to true
        this.uhf.timeSinceLost=null;
      }
      else{ //has been turned to false
        this.uhf.timeSinceLost=Date.now();
      }
      StatusManager.setStatusCode('UHF_LOST',!this.uhfStatus);
    }
  };

  this.checkManualMode=function(data){
    var number=Number(data);
    if(!Validator.isInteger(number)){
      Logger.warn('Invalid value for wireless_connection received. Value: '+data);
    }
    else{
      var bitmask=new Bitmask(number);
      this.manualMode= !bitmask.getBit(0);
      StatusManager.setStatusCode('MANUAL_MODE',this.manualMode);
    }
  };

  this.checkGPS=function(data){
    var number=Number(data);
    if(!Validator.isValidNumber(number)){
      Logger.warn('Invalid GPS status received. Status: '+data);
    }
    var connection_status=((number & 0xf0) >> 4)>0; // if theres at least 1 fix
    if (connection_status !== this.gps.status){ //if its a different status
      this.gps.status=connection_status;
      StatusManager.setStatusCode('GPS_LOST',!this.gps.status);
      if(this.gps.status===false){ //if it was set to false, start the timer
        this.gps.timeSinceLost=Date.now();
      }
      else{
        this.gps.timeSinceLost=null;
      }
    }
  };

  this.checkErrorCodes=function(data){
    var dataNumber=Number(data);
    if(!Validator.isInteger(dataNumber)){
      Logger.warn('Invalid data value for errorCodes received. Value : '+data);
    }
    else if(this.pastErrorCode!==dataNumber){ //if we got an error code value thats different from last time
      var error_codes=new Bitmask(dataNumber,10); //shouldnt need this 10
      this.pastErrorCode=dataNumber;

      this.startup_errors.POWER_ON_RESET=error_codes.getBit(0);
      this.startup_errors.BROWN_OUT_RESET=error_codes.getBit(1);
      this.startup_errors.IDLE_MODE_RESET=error_codes.getBit(2);
      this.startup_errors.SLEEP_MODE_RESET=error_codes.getBit(3);
      this.startup_errors.SOFTWARE_WATCH_DOG_RESET=error_codes.getBit(4);
      this.startup_errors.SOFTWARE_RESET=error_codes.getBit(5);
      this.startup_errors.EXTERNAL_RESET=error_codes.getBit(6);
      this.startup_errors.VOLTAGE_REGULATOR_RESET=error_codes.getBit(7);
      this.startup_errors.ILLEGAL_OPCODE_RESET=error_codes.getBit(8);
      this.startup_errors.TRAP_RESET=error_codes.getBit(9);

      StatusManager.setStatusCode('AIRCRAFT_ERROR_POWER_ON_RESET',this.startup_errors.POWER_ON_RESET);
      StatusManager.setStatusCode('AIRCRAFT_ERROR_BROWN_OUT_RESET',this.startup_errors.BROWN_OUT_RESET);
      StatusManager.setStatusCode('AIRCRAFT_ERROR_IDLE_MODE_RESET',this.startup_errors.IDLE_MODE_RESET);
      StatusManager.setStatusCode('AIRCRAFT_ERROR_SLEEP_MODE_RESET',this.startup_errors.SLEEP_MODE_RESET);
      StatusManager.setStatusCode('AIRCRAFT_ERROR_SOFTWARE_WATCH_DOG_RESET',this.startup_errors.SOFTWARE_WATCH_DOG_RESET);
      StatusManager.setStatusCode('AIRCRAFT_ERROR_SOFTWARE_RESET',this.startup_errors.SOFTWARE_RESET);
      StatusManager.setStatusCode('AIRCRAFT_ERROR_EXTERNAL_RESET',this.startup_errors.EXTERNAL_RESET);
      StatusManager.setStatusCode('AIRCRAFT_ERROR_VOLTAGE_REGULATOR_RESET',this.startup_errors.VOLTAGE_REGULATOR_RESET);
      StatusManager.setStatusCode('AIRCRAFT_ERROR_ILLEGAL_OPCODE_RESET',this.startup_errors.ILLEGAL_OPCODE_RESET);
      StatusManager.setStatusCode('AIRCRAFT_ERROR_TRAP_RESET',this.startup_errors.TRAP_RESET);
    }
  }
};

module.exports=new AircraftStatus();<commit_msg>Switched autopilot_active and wireless_connection headers<commit_after>var TelemetryData=require('./models/TelemetryData');
var StatusManager=require('./StatusManager');
var Bitmask=require('./util/Bitmask');
var Validator=require('./util/Validator');
var Logger=require('./util/Logger');

var AircraftStatus=function(){
  this.killModeActive=false;
  this.killModeWarning=false;
  this.armed=false;
  this.initializing=false;
  this.running=false;
  this.manualMode=false;
  this.xbee={//has not been implemented yet from the picpilots side
    status:false,
    timeSinceLost:null
  };
  this.gps={
    status: false,
    timeSinceLost: null
  };
  this.uhf={
    status: false,
    timeSinceLost: null
  };

  this.pastErrorCode=null;
  this.startup_errors={
    POWER_ON_RESET: false,
    BROWN_OUT_RESET: false,
    IDLE_MODE_RESET: false,
    SLEEP_MODE_RESET: false,
    SOFTWARE_WATCH_DOG_RESET: false,
    SOFTWARE_RESET: false,
    EXTERNAL_RESET: false,
    VOLTAGE_REGULATOR_RESET: false,
    ILLEGAL_OPCODE_RESET: false,
    TRAP_RESET: false
  };

  TelemetryData.on('data_received',function(data){
    this.checkErrorCodes(data.startup_error_codes);
    this.checkGPS(data.gps_status);
    this.checkUHFStatus(data.autopilot_active);
    this.checkManualMode(data.autopilot_active);
    this.checkPlaneStatus(data.wireless_connection);
  }.bind(this));

  this.checkPlaneStatus=function(number){
    if(!Validator.isValidNumber(number)){
      Logger.warn('Invalid value for autopilot_active received. Value: '+number);
    }
    else{
      var bitmask=new Bitmask(Number(number));
      this.initializing=bitmask.getBit(0);
      this.armed=bitmask.getBit(1);
      this.running=bitmask.getBit(2);
      this.killModeWarning=bitmask.getBit(3);
      this.killModeActive=bitmask.getBit(4);

      StatusManager.setStatusCode('AIRCRAFT_INITIALIZE',this.initializing);
      StatusManager.setStatusCode('AIRCRAFT_ARMED',this.armed);
      StatusManager.setStatusCode('AIRCRAFT_RUNNING',this.running);
      StatusManager.setStatusCode('AIRCRAFT_KILLMODE_WARNING',this.killModeWarning);
      StatusManager.setStatusCode('AIRCRAFT_KILLMODE',this.killModeActive);
    }
  };

  this.checkUHFStatus=function(data){
    var number=Number(data);
    if(!Validator.isInteger(number)){
      Logger.warn('Invalid value for wireless_connection received. Value: '+data);
    }
    else{
      var bitmask=new Bitmask(number);
      this.uhf.status= bitmask.getBit(1);

      if(this.uhf.status){ //has been turned to true
        this.uhf.timeSinceLost=null;
      }
      else{ //has been turned to false
        this.uhf.timeSinceLost=Date.now();
      }
      StatusManager.setStatusCode('UHF_LOST',!this.uhfStatus);
    }
  };

  this.checkManualMode=function(data){
    var number=Number(data);
    if(!Validator.isInteger(number)){
      Logger.warn('Invalid value for wireless_connection received. Value: '+data);
    }
    else{
      var bitmask=new Bitmask(number);
      this.manualMode= !bitmask.getBit(0);
      StatusManager.setStatusCode('MANUAL_MODE',this.manualMode);
    }
  };

  this.checkGPS=function(data){
    var number=Number(data);
    if(!Validator.isValidNumber(number)){
      Logger.warn('Invalid GPS status received. Status: '+data);
    }
    var connection_status=((number & 0xf0) >> 4)>0; // if theres at least 1 fix
    if (connection_status !== this.gps.status){ //if its a different status
      this.gps.status=connection_status;
      StatusManager.setStatusCode('GPS_LOST',!this.gps.status);
      if(this.gps.status===false){ //if it was set to false, start the timer
        this.gps.timeSinceLost=Date.now();
      }
      else{
        this.gps.timeSinceLost=null;
      }
    }
  };

  this.checkErrorCodes=function(data){
    var dataNumber=Number(data);
    if(!Validator.isInteger(dataNumber)){
      Logger.warn('Invalid data value for errorCodes received. Value : '+data);
    }
    else if(this.pastErrorCode!==dataNumber){ //if we got an error code value thats different from last time
      var error_codes=new Bitmask(dataNumber,10); //shouldnt need this 10
      this.pastErrorCode=dataNumber;

      this.startup_errors.POWER_ON_RESET=error_codes.getBit(0);
      this.startup_errors.BROWN_OUT_RESET=error_codes.getBit(1);
      this.startup_errors.IDLE_MODE_RESET=error_codes.getBit(2);
      this.startup_errors.SLEEP_MODE_RESET=error_codes.getBit(3);
      this.startup_errors.SOFTWARE_WATCH_DOG_RESET=error_codes.getBit(4);
      this.startup_errors.SOFTWARE_RESET=error_codes.getBit(5);
      this.startup_errors.EXTERNAL_RESET=error_codes.getBit(6);
      this.startup_errors.VOLTAGE_REGULATOR_RESET=error_codes.getBit(7);
      this.startup_errors.ILLEGAL_OPCODE_RESET=error_codes.getBit(8);
      this.startup_errors.TRAP_RESET=error_codes.getBit(9);

      StatusManager.setStatusCode('AIRCRAFT_ERROR_POWER_ON_RESET',this.startup_errors.POWER_ON_RESET);
      StatusManager.setStatusCode('AIRCRAFT_ERROR_BROWN_OUT_RESET',this.startup_errors.BROWN_OUT_RESET);
      StatusManager.setStatusCode('AIRCRAFT_ERROR_IDLE_MODE_RESET',this.startup_errors.IDLE_MODE_RESET);
      StatusManager.setStatusCode('AIRCRAFT_ERROR_SLEEP_MODE_RESET',this.startup_errors.SLEEP_MODE_RESET);
      StatusManager.setStatusCode('AIRCRAFT_ERROR_SOFTWARE_WATCH_DOG_RESET',this.startup_errors.SOFTWARE_WATCH_DOG_RESET);
      StatusManager.setStatusCode('AIRCRAFT_ERROR_SOFTWARE_RESET',this.startup_errors.SOFTWARE_RESET);
      StatusManager.setStatusCode('AIRCRAFT_ERROR_EXTERNAL_RESET',this.startup_errors.EXTERNAL_RESET);
      StatusManager.setStatusCode('AIRCRAFT_ERROR_VOLTAGE_REGULATOR_RESET',this.startup_errors.VOLTAGE_REGULATOR_RESET);
      StatusManager.setStatusCode('AIRCRAFT_ERROR_ILLEGAL_OPCODE_RESET',this.startup_errors.ILLEGAL_OPCODE_RESET);
      StatusManager.setStatusCode('AIRCRAFT_ERROR_TRAP_RESET',this.startup_errors.TRAP_RESET);
    }
  }
};

module.exports=new AircraftStatus();<|endoftext|>


<commit_before>/***** adapting backbone-pageable to tastypie */
Backbone.PageableCollection.prototype.parse = function( data ) {
	if ( data && data.meta ) {
		this.meta = data.meta;
	}

	return data && data.objects || data;
};

Backbone.PageableCollection.prototype.url = function( models ) {
	var url = _.isFunction( this.urlRoot ) ? this.urlRoot() : this.urlRoot;
	// If the collection doesn't specify an url, try to obtain one from a model in the collection
	if ( !url ) {
		var model = models && models.length && models[ 0 ];
		url = model && ( _.isFunction( model.urlRoot ) ? model.urlRoot() : model.urlRoot );
	}
	url = url && addSlash( url );

	// Build a url to retrieve a set of models. This assume the last part of each model's idAttribute
	// (set to 'resource_uri') contains the model's id.
	if ( models && models.length ) {
		var ids = _.map( models, function( model ) {
			var parts = _.compact( model.id.split( '/' ) );
			return parts[ parts.length - 1 ];
		});
		url += 'set/' + ids.join( ';' ) + '/';
	}

	return url || null;
};

/***** Changing default backbone-forms *****/
Backbone.Form.editors.TimeDatePicker = Backbone.Form.editors.Text.extend({
    render: function() {
        // Call the parent's render method
        Backbone.Form.editors.Text.prototype.render.call(this);
        // Then make the editor's element a datepicker.
        this.$el.datetimepicker({
            format: 'dd/mm/yyyy hh:mm',
            autoclose: true,
            weekStart: 1
        });

        return this;
    },
    // The set value must correctl
    setValue: function(value) {
        try{
        	this.$el.val(moment(value).format('YYYY-MM-DD HH:MM'));
        } catch (err){
       		this.$el.val(moment().format('YYYY-MM-DD HH:MM'));
        }
    }
});

Backbone.Form.editors.DatePicker = Backbone.Form.editors.Text.extend({
    render: function() {
        // Call the parent's render method
        Backbone.Form.editors.Text.prototype.render.call(this);
        // Then make the editor's element a datepicker.
        this.$el.datepicker({
            format: 'dd/mm/yyyy',
            autoclose: true,
            weekStart: 1
        });

        return this;
    },

    // The set value must correctl
    setValue: function(value) {
    	try{
        	this.$el.val(moment(value).format('DD/MM/YYYY'));
        } catch (err){
       		this.$el.val(moment().format('DD/MM/YYYY'));
        }
    }
});

Backgrid.ActionsCell = Backgrid.Cell.extend({
  template: _.template(""),
    events: {
      "click a.remove": "confirmRemoveRow"
    },
    confirmRemoveRow : function(event){
        var self = this;
        bootbox.confirm("Are you sure to remove this item?", function(result){
            if (result){
                self.removeRow(event);
            }
        });
    },
    removeRow: function(event) {
        var self = this;
        temp=this.model;
        self.model.url = self.model.get('resource_uri');
        self.model.destroy({success: function(model, response){
            var currentRow = $(event.currentTarget).parents('tr');
            currentRow.hide('slow', function(){ currentRow.remove(); });
        }});
    },
    render: function () {
      this.$el.html(this.template());
      this.delegateEvents();
      return this;
    }
});

Backbone.CrudView = Backbone.View.extend({
	render : function(){
		this.$el.html('Loading...');
		var self = this;
		this.collection = new this.CollectionClass();
		this.collection.fetch({
			success : function(collection) {
				self.renderCollection();
			},
			reset: true
		});
	},
	events : {
		'click a.new-item': "newItem",
	},
	newItem : function(event){
		event.preventDefault();
		this.collection.create();
	},
	renderCollection : function(){
		var self = this;
		// Initialize a new Grid instance
		this.grid = new Backgrid.Grid({
		  columns: self.columns,
		  collection: this.collection
		});
		this.grid.listenTo(this.collection,"backgrid:edited",function(e){
			e.url = e.base_url();
			e.save();
		});

		var filter = new Backgrid.Extension.ClientSideFilter({
		  collection: self.collection.fullCollection,
		  fields: ['name']
		});
		this.$el.html(filter.render().$el);

		var template = _.template($("#list_template").html());
		this.$el.append(this.grid.render().$el);
		this.$el.append(template);

		var paginator = new Backgrid.Extension.Paginator({
		  collection: self.collection
		});
		this.$el.append(paginator.render().$el);

	}
});

Backbone.DelosModel = Backbone.Model.extend({
	base_url: function() {
	    var temp_url = Backbone.Model.prototype.url.call(this);
	    return (temp_url.charAt(temp_url.length - 1) == '/' ? temp_url : temp_url+'/');
    },
    str : function(){
    	return this.title;
    },
});<commit_msg>Changing base classes for backbone<commit_after>/***** adapting backbone-pageable to tastypie */
Backbone.PageableCollection.prototype.parse = function( data ) {
	if ( data && data.meta ) {
		this.meta = data.meta;
	}

	return data && data.objects || data;
};

Backbone.PageableCollection.prototype.url = function( models ) {
	var url = _.isFunction( this.urlRoot ) ? this.urlRoot() : this.urlRoot;
	// If the collection doesn't specify an url, try to obtain one from a model in the collection
	if ( !url ) {
		var model = models && models.length && models[ 0 ];
		url = model && ( _.isFunction( model.urlRoot ) ? model.urlRoot() : model.urlRoot );
	}
	url = url && addSlash( url );

	// Build a url to retrieve a set of models. This assume the last part of each model's idAttribute
	// (set to 'resource_uri') contains the model's id.
	if ( models && models.length ) {
		var ids = _.map( models, function( model ) {
			var parts = _.compact( model.id.split( '/' ) );
			return parts[ parts.length - 1 ];
		});
		url += 'set/' + ids.join( ';' ) + '/';
	}

	return url || null;
};

Backbone.FilteredPageableCollection = Backbone.PageableCollection.extend({
  	initialize : function(){
  		Backbone.PageableCollection.prototype.initialize.apply(this);
  		this.filtersEnabled = {};
  	},

  	setFilter : function(name, value){
		this.filtersEnabled[name] = value;
		this.processFilters();
	},

	processFilters : function() {
		var filtered = [],
			fullColl = this.fullCollection,
			allModels = this.fullModels || fullColl.models;
			self = this;
		// Reset the filter to normal
		fullColl.reset(allModels);
		// Keep a copy of *all* the models
		this.fullModels = this.fullModels || fullColl.models.slice(0);

		_.each(this.filtersEnabled, function(value, key){
			if (value != ''){
				filtered = self.filter(function(model) {
					return model.get(key) === value;
				});
				fullColl.reset(filtered, {});
			}
		});
	}
});

/***** Changing default backbone-forms *****/
Backbone.Form.editors.TimeDatePicker = Backbone.Form.editors.Text.extend({
    render: function() {
        // Call the parent's render method
        Backbone.Form.editors.Text.prototype.render.call(this);
        // Then make the editor's element a datepicker.
        this.$el.datetimepicker({
            format: 'dd/mm/yyyy hh:mm',
            autoclose: true,
            weekStart: 1
        });

        return this;
    },
    // The set value must correctl
    setValue: function(value) {
        try{
        	this.$el.val(moment(value).format('YYYY-MM-DD HH:MM'));
        } catch (err){
       		this.$el.val(moment().format('YYYY-MM-DD HH:MM'));
        }
    }
});

Backbone.Form.editors.DatePicker = Backbone.Form.editors.Text.extend({
    render: function() {
        // Call the parent's render method
        Backbone.Form.editors.Text.prototype.render.call(this);
        // Then make the editor's element a datepicker.
        this.$el.datepicker({
            format: 'dd/mm/yyyy',
            autoclose: true,
            weekStart: 1
        });

        return this;
    },

    // The set value must correctl
    setValue: function(value) {
    	try{
        	this.$el.val(moment(value).format('DD/MM/YYYY'));
        } catch (err){
       		this.$el.val(moment().format('DD/MM/YYYY'));
        }
    }
});

Backgrid.ActionsCell = Backgrid.Cell.extend({
  template: _.template(""),
    events: {
      "click a.remove": "confirmRemoveRow"
    },
    confirmRemoveRow : function(event){
        var self = this;
        bootbox.confirm("Tem certeza que deseja remover este registro?", function(result){
            if (result){
                self.removeRow(event);
            }
        });
    },
    removeRow: function(event) {
        var self = this;
        temp=this.model;
        self.model.url = self.model.get('resource_uri');
        self.model.destroy({success: function(model, response){
            var currentRow = $(event.currentTarget).parents('tr');
            currentRow.hide('slow', function(){ currentRow.remove(); });
        }});
    },
    render: function () {
      this.$el.html(this.template());
      this.delegateEvents();
      return this;
    }
});

Backbone.CrudView = Backbone.View.extend({
	render : function(){
		var self = this;
		this.collection = new this.CollectionClass();
		this.collection.fetch({
			success : function(collection) {
				self.renderCollection();
			},
			reset: true
		});
	},
	events : {
		'click a.new-item': "newItem",
	},
	newItem : function(event){
		event.preventDefault();
		this.collection.create();
	},
	renderCollection : function(){
		var self = this;
		// Initialize a new Grid instance
		this.grid = new Backgrid.Grid({
		  columns: self.columns,
		  collection: this.collection
		});
		this.grid.listenTo(this.collection,"backgrid:edited",function(e){
			e.url = e.base_url();
			e.save();
		});

		var filter = new Backgrid.Extension.ClientSideFilter({
		  collection: self.collection.fullCollection,
		  fields: self.filterFields
		});
		this.$el.append(filter.render().$el);

		var template = _.template($("#list_template").html());
		this.$el.append(this.grid.render().$el);
		this.$el.append(template);

		var paginator = new Backgrid.Extension.Paginator({
		  collection: self.collection
		});
		this.$el.append(paginator.render().$el);

	}
});

Backbone.DelosModel = Backbone.Model.extend({
	base_url: function() {
	    var temp_url = Backbone.Model.prototype.url.call(this);
	    return (temp_url.charAt(temp_url.length - 1) == '/' ? temp_url : temp_url+'/');
    },
    str : function(){
    	return this.title;
    },
});

Number.prototype.formatMoney = function(c, d, t){
var n = this,
    c = isNaN(c = Math.abs(c)) ? 2 : c,
    d = d == undefined ? "," : d,
    t = t == undefined ? "." : t,
    s = n < 0 ? "-" : "",
    i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "",
    j = (j = i.length) > 3 ? j % 3 : 0;
   return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
 };<|endoftext|>


<commit_before>import Ember from 'ember';

const { Copyable, computed } = Ember;

export const SymbolType = {
  TERMINAL: 't',
  NON_TERMINAL: 'nt',
  ITEM: 'i'
};

const Symbol = Ember.Object.extend(Copyable, {
  name: '',
  type: '',

  isValidName: computed.notEmpty('name'),

  isTerminal: computed.equal('type', SymbolType.TERMINAL),
  isNonTerminal: computed.equal('type', SymbolType.NON_TERMINAL),
  isValidType: computed.or('isTerminal', 'isNonTerminal'),

  isValid: computed.and('isValidName', 'isValidType'),

  copy() {
    return Symbol.create({
      name: this.get('name'),
      type: this.get('type')
    });
  }
});

export default Symbol;
<commit_msg>Ignore warning about redefinition of Symbol<commit_after>import Ember from 'ember';

const { Copyable, computed } = Ember;

export const SymbolType = {
  TERMINAL: 't',
  NON_TERMINAL: 'nt',
  ITEM: 'i'
};

const Symbol = Ember.Object.extend(Copyable, { // jshint ignore:line
  name: '',
  type: '',

  isValidName: computed.notEmpty('name'),

  isTerminal: computed.equal('type', SymbolType.TERMINAL),
  isNonTerminal: computed.equal('type', SymbolType.NON_TERMINAL),
  isValidType: computed.or('isTerminal', 'isNonTerminal'),

  isValid: computed.and('isValidName', 'isValidType'),

  copy() {
    return Symbol.create({
      name: this.get('name'),
      type: this.get('type')
    });
  }
});

export default Symbol;
<|endoftext|>


<commit_before>/**
 * @module ios-driver
 */

UIAAlert.prototype.defaultButton_origin = UIAAlert.prototype.defaultButton;

/**
 * dismiss the alert.
 */
UIAAlert.prototype.dismiss = function () {
    var button = this.cancelButton();
    if (button.type() === "UIAElementNil") {
        log("cancel is not there,trying default.");
        button = this.defaultButton();
        if (button.type() === "UIAElementNil") {
            log("default button missing, trying zeroth button");
            button = this.buttons()[0];
            if (button.type() === "UIAElementNil") {
                throw new UIAutomationException("this alert doesn't have the normal buttons.", 7);
            }
        }
    } else {
        log("cancel found");
    }

    button.tap();
    UIATarget.localTarget().delay(0.5);

}

/**
 * accept the alert.
 */
UIAAlert.prototype.accept = function () {
    var button = this.defaultButton();
    if (button.type() === "UIAElementNil") {
        var buttons = this.buttons();
        button = buttons[OK];
        if (button.type() === "UIAElementNil" && buttons.length > 0) {
            button = buttons[buttons.length - 1];
            if (button.type() === "UIAElementNil") {
                throw new UIAutomationException("this alert doesn't have a default normal buttons.", 7);
            }
        }
    }
    button.tap();
    UIATarget.localTarget().delay(0.5);
}

/**
 * send the value to the alert, assuming it has a text field.
 * @param value
 */
UIAAlert.prototype.sendKeys = function (value) {
    var criteria = {"OR": [
        {"l10n": "none", "expected": "UIATextField", "matching": "exact", "method": "type"},
        {"l10n": "none", "expected": "UIASecureTextField", "matching": "exact", "method": "type"}
    ]};
    try {
        this.element(-1, criteria);
    } catch (err) {
        throw new UIAutomationException("this alert doesn't accept inputs.", 12);
    }
    var app = UIAutomation.cache.get(1);
    var keyboard = app.keyboard();
    keyboard.typeString(value);

}

UIAAlert.prototype.getText = function () {
    var criteria = {"l10n": "none", "expected": "UIAStaticText", "matching": "exact", "method": "type"};
    var texts = this.elements2(-1, criteria);
    if (texts.length > 1) {
        return texts[1].name();
    } else {
        throw new UIAutomationException("this alert doesn't have any text."+this.tree(false));
    }
}
/**
 * return the default button, but also send an event that the alert disappeared.
 * @return {UIAButton} the default button for the alert.
 */
UIAAlert.prototype.defaultButton = function () {
    var res = this.defaultButton_origin();
    res.tap = function () {
        if (this.isVisible()) {
            var rect = this.rect();
            var x = rect.origin.x + (rect.size.width / 2);
            var y = rect.origin.y + (rect.size.height / 2);
            var point = {
                'x': Math.floor(x),
                'y': Math.floor(y)
            };
            UIATarget.localTarget().tap(point);
            UIAutomation.cache.clearAlert();
        } else {
            throw new UIAutomationException("element is not visible", 11);
        }
    }
    return res;
}
UIAAlert.prototype.cancelButton_origin = UIAAlert.prototype.cancelButton;

/**
 * return the cancel button, but also send an event that the alert disappeared.
 * @return {UIAButton} the cancel button for the alert.
 */
UIAAlert.prototype.cancelButton = function () {
    var res = this.cancelButton_origin();

    res.tap = function () {
        if (this.isVisible()) {
            var rect = this.rect();
            var x = rect.origin.x + (rect.size.width / 2);
            var y = rect.origin.y + (rect.size.height / 2);
            var point = {
                'x': Math.floor(x),
                'y': Math.floor(y)
            };
            UIATarget.localTarget().tap(point);
            UIAutomation.cache.clearAlert();
        } else {
            throw new UIAutomationException("element is not visible", 11);
        }
    }
    return res;
}

UIAAlert.prototype.isSSLWarning = function(){
    if (this.name() === "Cannot Verify Server Identity"){
        return true;
    }
    return false;
}

UIAAlert.prototype.isAlternateKeyboard = function(){
    if (this.name() === "Alternate Keyboards"){
        return true;
    }
    return false;
}
<commit_msg>Fix typo in looking up OK button.<commit_after>/**
 * @module ios-driver
 */

UIAAlert.prototype.defaultButton_origin = UIAAlert.prototype.defaultButton;

/**
 * dismiss the alert.
 */
UIAAlert.prototype.dismiss = function () {
    var button = this.cancelButton();
    if (button.type() === "UIAElementNil") {
        log("cancel is not there,trying default.");
        button = this.defaultButton();
        if (button.type() === "UIAElementNil") {
            log("default button missing, trying zeroth button");
            button = this.buttons()[0];
            if (button.type() === "UIAElementNil") {
                throw new UIAutomationException("this alert doesn't have the normal buttons.", 7);
            }
        }
    } else {
        log("cancel found");
    }

    button.tap();
    UIATarget.localTarget().delay(0.5);

}

/**
 * accept the alert.
 */
UIAAlert.prototype.accept = function () {
    var button = this.defaultButton();
    if (button.type() === "UIAElementNil") {
        var buttons = this.buttons();
        button = buttons["OK"];
        if (button.type() === "UIAElementNil" && buttons.length > 0) {
            button = buttons[buttons.length - 1];
            if (button.type() === "UIAElementNil") {
                throw new UIAutomationException("this alert doesn't have a default normal buttons.", 7);
            }
        }
    }
    button.tap();
    UIATarget.localTarget().delay(0.5);
}

/**
 * send the value to the alert, assuming it has a text field.
 * @param value
 */
UIAAlert.prototype.sendKeys = function (value) {
    var criteria = {"OR": [
        {"l10n": "none", "expected": "UIATextField", "matching": "exact", "method": "type"},
        {"l10n": "none", "expected": "UIASecureTextField", "matching": "exact", "method": "type"}
    ]};
    try {
        this.element(-1, criteria);
    } catch (err) {
        throw new UIAutomationException("this alert doesn't accept inputs.", 12);
    }
    var app = UIAutomation.cache.get(1);
    var keyboard = app.keyboard();
    keyboard.typeString(value);

}

UIAAlert.prototype.getText = function () {
    var criteria = {"l10n": "none", "expected": "UIAStaticText", "matching": "exact", "method": "type"};
    var texts = this.elements2(-1, criteria);
    if (texts.length > 1) {
        return texts[1].name();
    } else {
        throw new UIAutomationException("this alert doesn't have any text."+this.tree(false));
    }
}
/**
 * return the default button, but also send an event that the alert disappeared.
 * @return {UIAButton} the default button for the alert.
 */
UIAAlert.prototype.defaultButton = function () {
    var res = this.defaultButton_origin();
    res.tap = function () {
        if (this.isVisible()) {
            var rect = this.rect();
            var x = rect.origin.x + (rect.size.width / 2);
            var y = rect.origin.y + (rect.size.height / 2);
            var point = {
                'x': Math.floor(x),
                'y': Math.floor(y)
            };
            UIATarget.localTarget().tap(point);
            UIAutomation.cache.clearAlert();
        } else {
            throw new UIAutomationException("element is not visible", 11);
        }
    }
    return res;
}
UIAAlert.prototype.cancelButton_origin = UIAAlert.prototype.cancelButton;

/**
 * return the cancel button, but also send an event that the alert disappeared.
 * @return {UIAButton} the cancel button for the alert.
 */
UIAAlert.prototype.cancelButton = function () {
    var res = this.cancelButton_origin();

    res.tap = function () {
        if (this.isVisible()) {
            var rect = this.rect();
            var x = rect.origin.x + (rect.size.width / 2);
            var y = rect.origin.y + (rect.size.height / 2);
            var point = {
                'x': Math.floor(x),
                'y': Math.floor(y)
            };
            UIATarget.localTarget().tap(point);
            UIAutomation.cache.clearAlert();
        } else {
            throw new UIAutomationException("element is not visible", 11);
        }
    }
    return res;
}

UIAAlert.prototype.isSSLWarning = function(){
    if (this.name() === "Cannot Verify Server Identity"){
        return true;
    }
    return false;
}

UIAAlert.prototype.isAlternateKeyboard = function(){
    if (this.name() === "Alternate Keyboards"){
        return true;
    }
    return false;
}
<|endoftext|>


<commit_before>const { Command, util } = require('discord.js-commando');
const stripIndents = require('common-tags').stripIndents;

const config = require('../../settings');
const Money = require('../../postgreSQL/models/Money');
const Redis = require('../../redis/Redis');

const redis = new Redis();

module.exports = class MoneyLeaderboardCommand extends Command {
	constructor(client) {
		super(client, {
			name: 'money-leaderboard',
			aliases: ['donut-leaderboard', 'donuts-leaderboard'],
			group: 'currency',
			memberName: 'leaderboard',
			description: 'Displays the money members have earned.',
			details: 'Display the amount of money members have earned in a leaderboard.',
			guildOnly: true,

			args: [
				{
					key: 'page',
					prompt: 'What page would you like to view?\n',
					type: 'integer',
					default: 1
				}
			]
		});
	}

	async run(msg, args) {
		const page = args.page;
		let ranking = config.paginationItems * (page - 1);

		const money = await this.findCached();
		const paginated = util.paginate(JSON.parse(money), page, Math.floor(config.paginationItems));

		for (const user of paginated.items) await this.client.fetchUser(user.userID);

		return msg.embed({
			color: 3447003,
			description: stripIndents`
				__**Donut leaderboard, page ${paginated.page}**__

				${paginated.items.map(user => `**${++ranking} -** ${`${this.client.users.get(user.userID).username}#${this.client.users.get(user.userID).discriminator}`} (**${user.money}** 🍩)`).join('\n')}
			`,
			footer: { text: paginated.maxPage > 1 ? 'Use \'donut-leaderboard <page>\' to view a specific page.' : '' }
		});
	}

	async findCached() {
		return redis.db.getAsync('moneyleaderboard').then(async reply => {
			if (reply) {
				return reply;
			} else {
				const money = await Money.findAll({ where: { userID: { $ne: 'SLOTMACHINE' } }, order: 'money DESC' });
				if (!money) return `No money biatch`;

				redis.db.setAsync('moneyleaderboard', JSON.stringify(money));
				redis.db.expire('moneyleaderboard', 3700);

				return JSON.stringify(money);
			}
		});
	}
};
<commit_msg>Fix page f*ckery<commit_after>const { Command, util } = require('discord.js-commando');
const stripIndents = require('common-tags').stripIndents;

const config = require('../../settings');
const Money = require('../../postgreSQL/models/Money');
const Redis = require('../../redis/Redis');

const redis = new Redis();

module.exports = class MoneyLeaderboardCommand extends Command {
	constructor(client) {
		super(client, {
			name: 'money-leaderboard',
			aliases: ['donut-leaderboard', 'donuts-leaderboard'],
			group: 'currency',
			memberName: 'leaderboard',
			description: 'Displays the money members have earned.',
			details: 'Display the amount of money members have earned in a leaderboard.',
			guildOnly: true,

			args: [
				{
					key: 'page',
					prompt: 'What page would you like to view?\n',
					type: 'integer',
					default: 1
				}
			]
		});
	}

	async run(msg, args) {
		const page = args.page;

		const money = await this.findCached();
		const paginated = util.paginate(JSON.parse(money), page, Math.floor(config.paginationItems));
		let ranking = config.paginationItems * (paginated.page - 1);

		for (const user of paginated.items) await this.client.fetchUser(user.userID);

		return msg.embed({
			color: 3447003,
			description: stripIndents`
				__**Donut leaderboard, page ${paginated.page}**__

				${paginated.items.map(user => `**${++ranking} -** ${`${this.client.users.get(user.userID).username}#${this.client.users.get(user.userID).discriminator}`} (**${user.money}** 🍩)`).join('\n')}
			`,
			footer: { text: paginated.maxPage > 1 ? 'Use \'donut-leaderboard <page>\' to view a specific page.' : '' }
		});
	}

	async findCached() {
		return redis.db.getAsync('moneyleaderboard').then(async reply => {
			if (reply) {
				return reply;
			} else {
				const money = await Money.findAll({ where: { userID: { $ne: 'SLOTMACHINE' } }, order: 'money DESC' });
				if (!money) return `No money biatch`;

				redis.db.setAsync('moneyleaderboard', JSON.stringify(money));
				redis.db.expire('moneyleaderboard', 3700);

				return JSON.stringify(money);
			}
		});
	}
};
<|endoftext|>