<commit_before>function each(elems, func) {
  if (!elems instanceof Array) { elems = [elems]; }
  for (var i = elems.length; i--; ) {
    func(elems[i]);
  }
}

function onClick(elems, func) {
  each(elems, function(elem) {
    elem.onclick = func;
  });
}

function toggleMigrationRawContent() {
  var elems = document.querySelectorAll(".pt_migration .pt_migration_header");
  onClick(elems, function() {
    var content = this.nextElementSibling;
    content.style.display = content.style.display === "" ? "block" : "";
  });
}

function closeNotice() {
  var elems = document.querySelectorAll(".pt_close_notice");
  onClick(elems, function() {
    this.parentElement.style.display = "none";
  });
}

function toggleEditRawContent() {
  var elems = document.querySelectorAll(".pt_checkbox");
  onClick(elems, function() {
    var raw_content = document.querySelectorAll(".pt_raw_content");
    var text_area = raw_content[0].children[0];
    text_area.disabled = !(text_area.disabled);
  });
}

function setupMigrations() {
  toggleMigrationRawContent();
  closeNotice();
}

function setupNewMigration() {
  toggleEditRawContent();
}
<commit_msg>sync className to raw_content<commit_after>function each(elems, func) {
  if (!elems instanceof Array) { elems = [elems]; }
  for (var i = elems.length; i--; ) {
    func(elems[i]);
  }
}

function onClick(elems, func) {
  each(elems, function(elem) {
    elem.onclick = func;
  });
}

function toggleMigrationRawContent() {
  var elems = document.querySelectorAll(".pt_migration .pt_migration_header");
  onClick(elems, function() {
    var content = this.nextElementSibling;
    content.style.display = content.style.display === "" ? "block" : "";
  });
}

function closeNotice() {
  var elems = document.querySelectorAll(".pt_close_notice");
  onClick(elems, function() {
    this.parentElement.style.display = "none";
  });
}

function toggleEditRawContent() {
  var elems = document.querySelectorAll(".pt_checkbox");
  onClick(elems, function() {
    var raw_content = document.querySelectorAll(".pt_raw_content");
    var text_area = raw_content[0].children[0];
    text_area.disabled = !(text_area.disabled);
  });
}

function MigrationFile() {
}

MigrationFile.prototype.setClassName = function(className) {
  this.className = className;
};

MigrationFile.prototype.toString = function() {
  return ["class " + this.className + " < ActiveRecord::Migration",
         "  def change",
         "  end",
         "end"].join("\n");
};

function inputClassName() {
  var elems = document.querySelectorAll(".pt_class_name input");
  var file = new MigrationFile();
  elems[0].onkeyup = function() {
    file.setClassName(this.value);
    var area = document.querySelectorAll(".pt_raw_content textarea")[0];
    area.value = file.toString();
  };
}

function setupMigrations() {
  toggleMigrationRawContent();
  closeNotice();
}

function setupNewMigration() {
  toggleEditRawContent();
  inputClassName();
}
<|endoftext|>


<commit_before>applicantControllers.controller('AdminCtrl', ['$scope', 'Admin',
  function($scope, Admin) {
    var vm = this;

    $scope.settings = Admin.query(function(settings) {
      vm.settings = {
        job_location_enable: $scope.settings.rows[0].jobLocation.reston.enabled,
        job_location: $scope.settings.rows[0].jobLocation.reston.values[0].location,
        job_location_dist: $scope.settings.rows[0].jobLocation.reston.values[0].maxDistance,
        resume_length: $scope.settings.rows[0].resumeLength.standardLength.enabled,
        relevance: $scope.settings.rows[0].relevance.relevance.enabled,
        experience_enable: $scope.settings.rows[0].experience.techExperience.enabled,
        experience: $scope.settings.rows[0].experience.techExperience.values[0].positions,
        contact_enable: $scope.settings.rows[0].contactInfo.allInfo.enabled,
        etl_enable: $scope.settings.rows[0].keywords.etl.enabled,
        webApp_enable: $scope.settings.rows[0].keywords.webApp.enabled,
        languages_enable: $scope.settings.rows[0].keywords.languages.enabled,
        dbms_enable: $scope.settings.rows[0].keywords.dbms.enabled,
        mobile_enable: $scope.settings.rows[0].keywords.mobile.enabled,
        bigData_enable: $scope.settings.rows[0].keywords.bigData.enabled,
      }
      console.log($scope.settings.rows[0].experience.techExperience.values[0].positions);
    });

    // console.log($scope.jobLocation);

  	// The model object that we reference
    // on the  element in index.html
    // vm.settings = {};

    // An array of our form fields with configuration
    // and options set. We make reference to this in
    // the 'fields' attribute on the  element
    vm.settingsFields = [
    {
      key: 'job_location_enable',
      type: 'checkbox',
      templateOptions: {
        label: 'Location',
        required: false
      }
    },
    {
      key: 'job_location',
      type: 'input',
      templateOptions: {
        type: 'text',
        label: 'City, State',
        // placeholder: 'Reston, VA',
        required: false
      },
      hideExpression: '!model.job_location_enable'
    },
    {
      key: 'job_location_dist',
      type: 'input',
      templateOptions: {
        type: 'text',
        label: 'Max Distance',
        // placeholder: 'Reston, VA',
        required: false
      },
      hideExpression: '!model.job_location_enable'
    },
    {
      key: 'resume_length',
      type: 'radio',
      templateOptions: {
        label: 'Resume length',
        required: false,
        options: [
          {name: 'True', value: true},
          {name: 'False', value: false}
        ]
      }
    },
    {
      key: 'experience_enable',
      type: 'checkbox',
      templateOptions: {
        label: 'Experience',
        required: false
      }
    },
    {
      key: 'experience',
      type: 'input',
      templateOptions: {
        type: 'text',
        label: 'Positions',
        required: false,
      },
      hideExpression: '!model.experience_enable'
    },
    {
      key: 'experience_deg',
      type: 'input',
      templateOptions: {
        type: 'text',
        label: 'Degrees',
        placeholder: 'tech, computer science, programming',
        required: false,
      },
      hideExpression: '!model.experience_enable'
    },
    {
      key: 'contact_enable',
      type: 'checkbox',
      templateOptions: {
        label: 'Contact Information',
        required: false
      }
    },
    {
      key: 'email',
      type: 'checkbox',
      templateOptions: {
        label: 'Email',
        required: false,
        value: 'email'
      },
      hideExpression: '!model.contact_enable'
    },
    {
      key: 'phone',
      type: 'checkbox',
      templateOptions: {
        label: 'Phone',
        required: false,
        value: 'phone'
      },
      hideExpression: '!model.contact_enable'
    },
    {
      key: 'urls',
      type: 'checkbox',
      templateOptions: {
        label: 'URLs',
        required: false,
        value: 'urls'
      },
      hideExpression: '!model.contact_enable'
    },
    {
      key: 'linkedin',
      type: 'checkbox',
      templateOptions: {
        label: 'LinkedIn',
        required: false,
        value: 'linkedin'
      },
      hideExpression: '!model.contact_enable'
    },
    {
      key: 'github',
      type: 'checkbox',
      templateOptions: {
        label: 'GitHub',
        required: false,
        value: 'github'
      },
      hideExpression: '!model.contact_enable'
    },
    {
      key: 'indeed',
      type: 'checkbox',
      templateOptions: {
        label: 'Indeed',
        required: false,
        value: 'indeed'
      },
      hideExpression: '!model.contact_enable'
    },
    {
      key: 'etl_enable',
      type: 'checkbox',
      templateOptions: {
        label: 'ETL Key Words',
        required: false
      }
    },
    {
      key: 'etl',
      type: 'input',
      templateOptions: {
        type: 'text',
        placeholder: 'ETL, Big Data, Languages',
        required: false
      },
      hideExpression: '!model.etl_enable'
    },
    {
      key: 'webApp_enable',
      type: 'checkbox',
      templateOptions: {
        label: 'Web App Key Words',
        required: false
      }
    },
    {
      key: 'webApp',
      type: 'input',
      templateOptions: {
        type: 'text',
        placeholder: 'ETL, Big Data, Languages',
        required: false
      },
      hideExpression: '!model.webApp_enable'
    },
    {
      key: 'languages_enable',
      type: 'checkbox',
      templateOptions: {
        label: 'Languages Key Words',
        required: false
      }
    },
    {
      key: 'languages',
      type: 'input',
      templateOptions: {
        type: 'text',
        placeholder: 'ETL, Big Data, Languages',
        required: false
      },
      hideExpression: '!model.languages_enable'
    },
    {
      key: 'dbms_enable',
      type: 'checkbox',
      templateOptions: {
        label: 'Database Key Words',
        required: false
      }
    },
    {
      key: 'dbms',
      type: 'input',
      templateOptions: {
        type: 'text',
        placeholder: 'ETL, Big Data, Languages',
        required: false
      },
      hideExpression: '!model.dbms_enable'
    },
    {
      key: 'mobile_enable',
      type: 'checkbox',
      templateOptions: {
        label: 'Mobile Key Words',
        required: false
      }
    },
    {
      key: 'mobile',
      type: 'input',
      templateOptions: {
        type: 'text',
        placeholder: 'ETL, Big Data, Languages',
        required: false
      },
      hideExpression: '!model.mobile_enable'
    },
    {
      key: 'bigData_enable',
      type: 'checkbox',
      templateOptions: {
        label: 'Big Data Key Words',
        required: false
      }
    },
    {
      key: 'bigData',
      type: 'input',
      templateOptions: {
        type: 'text',
        placeholder: 'ETL, Big Data, Languages',
        required: false
      },
      hideExpression: '!model.bigData_enable'
    },
    {
      key: 'relevance',
      type: 'radio',
      templateOptions: {
        label: 'Relevance',
        required: false,
        options: [
          {name: 'True', value: true},
          {name: 'False', value: false}
        ]
      }
    },
    ];

  }
  ]);
<commit_msg>changed to textarea<commit_after>applicantControllers.controller('AdminCtrl', ['$scope', 'Admin',
  function($scope, Admin) {
    var vm = this;

    $scope.settings = Admin.query(function(settings) {
      vm.settings = {
        job_location_enable: $scope.settings.rows[0].jobLocation.reston.enabled,
        job_location: $scope.settings.rows[0].jobLocation.reston.values[0].location,
        job_location_dist: $scope.settings.rows[0].jobLocation.reston.values[0].maxDistance,
        resume_length: $scope.settings.rows[0].resumeLength.standardLength.enabled,
        relevance: $scope.settings.rows[0].relevance.relevance.enabled,
        experience_enable: $scope.settings.rows[0].experience.techExperience.enabled,
        experience: $scope.settings.rows[0].experience.techExperience.values[0].positions,
        contact_enable: $scope.settings.rows[0].contactInfo.allInfo.enabled,
        etl_enable: $scope.settings.rows[0].keywords.etl.enabled,
        webApp_enable: $scope.settings.rows[0].keywords.webApp.enabled,
        languages_enable: $scope.settings.rows[0].keywords.languages.enabled,
        dbms_enable: $scope.settings.rows[0].keywords.dbms.enabled,
        mobile_enable: $scope.settings.rows[0].keywords.mobile.enabled,
        bigData_enable: $scope.settings.rows[0].keywords.bigData.enabled,
      }
      console.log($scope.settings.rows[0].experience.techExperience.values[0].positions);
    });

    // console.log($scope.jobLocation);

  	// The model object that we reference
    // on the  element in index.html
    // vm.settings = {};

    // An array of our form fields with configuration
    // and options set. We make reference to this in
    // the 'fields' attribute on the  element
    vm.settingsFields = [
    {
      key: 'job_location_enable',
      type: 'checkbox',
      templateOptions: {
        label: 'Location',
        required: false
      }
    },
    {
      key: 'job_location',
      type: 'input',
      templateOptions: {
        type: 'text',
        label: 'City, State',
        // placeholder: 'Reston, VA',
        required: false
      },
      hideExpression: '!model.job_location_enable'
    },
    {
      key: 'job_location_dist',
      type: 'input',
      templateOptions: {
        type: 'text',
        label: 'Max Distance',
        // placeholder: 'Reston, VA',
        required: false
      },
      hideExpression: '!model.job_location_enable'
    },
    {
      key: 'resume_length',
      type: 'radio',
      templateOptions: {
        label: 'Resume length',
        required: false,
        options: [
          {name: 'True', value: true},
          {name: 'False', value: false}
        ]
      }
    },
    {
      key: 'experience_enable',
      type: 'checkbox',
      templateOptions: {
        label: 'Experience',
        required: false
      }
    },
    {
      key: 'experience',
      type: 'textarea',
      templateOptions: {
        label: 'Positions',
        required: false,
      },
      hideExpression: '!model.experience_enable'
    },
    {
      key: 'experience_deg',
      type: 'textarea',
      templateOptions: {
        label: 'Degrees',
        placeholder: 'tech, computer science, programming',
        required: false,
      },
      hideExpression: '!model.experience_enable'
    },
    {
      key: 'contact_enable',
      type: 'checkbox',
      templateOptions: {
        label: 'Contact Information',
        required: false
      }
    },
    {
      key: 'email',
      type: 'checkbox',
      templateOptions: {
        label: 'Email',
        required: false,
        value: 'email'
      },
      hideExpression: '!model.contact_enable'
    },
    {
      key: 'phone',
      type: 'checkbox',
      templateOptions: {
        label: 'Phone',
        required: false,
        value: 'phone'
      },
      hideExpression: '!model.contact_enable'
    },
    {
      key: 'urls',
      type: 'checkbox',
      templateOptions: {
        label: 'URLs',
        required: false,
        value: 'urls'
      },
      hideExpression: '!model.contact_enable'
    },
    {
      key: 'linkedin',
      type: 'checkbox',
      templateOptions: {
        label: 'LinkedIn',
        required: false,
        value: 'linkedin'
      },
      hideExpression: '!model.contact_enable'
    },
    {
      key: 'github',
      type: 'checkbox',
      templateOptions: {
        label: 'GitHub',
        required: false,
        value: 'github'
      },
      hideExpression: '!model.contact_enable'
    },
    {
      key: 'indeed',
      type: 'checkbox',
      templateOptions: {
        label: 'Indeed',
        required: false,
        value: 'indeed'
      },
      hideExpression: '!model.contact_enable'
    },
    {
      key: 'etl_enable',
      type: 'checkbox',
      templateOptions: {
        label: 'ETL Key Words',
        required: false
      }
    },
    {
      key: 'etl',
      type: 'input',
      templateOptions: {
        type: 'text',
        placeholder: 'ETL, Big Data, Languages',
        required: false
      },
      hideExpression: '!model.etl_enable'
    },
    {
      key: 'webApp_enable',
      type: 'checkbox',
      templateOptions: {
        label: 'Web App Key Words',
        required: false
      }
    },
    {
      key: 'webApp',
      type: 'input',
      templateOptions: {
        type: 'text',
        placeholder: 'ETL, Big Data, Languages',
        required: false
      },
      hideExpression: '!model.webApp_enable'
    },
    {
      key: 'languages_enable',
      type: 'checkbox',
      templateOptions: {
        label: 'Languages Key Words',
        required: false
      }
    },
    {
      key: 'languages',
      type: 'input',
      templateOptions: {
        type: 'text',
        placeholder: 'ETL, Big Data, Languages',
        required: false
      },
      hideExpression: '!model.languages_enable'
    },
    {
      key: 'dbms_enable',
      type: 'checkbox',
      templateOptions: {
        label: 'Database Key Words',
        required: false
      }
    },
    {
      key: 'dbms',
      type: 'input',
      templateOptions: {
        type: 'text',
        placeholder: 'ETL, Big Data, Languages',
        required: false
      },
      hideExpression: '!model.dbms_enable'
    },
    {
      key: 'mobile_enable',
      type: 'checkbox',
      templateOptions: {
        label: 'Mobile Key Words',
        required: false
      }
    },
    {
      key: 'mobile',
      type: 'input',
      templateOptions: {
        type: 'text',
        placeholder: 'ETL, Big Data, Languages',
        required: false
      },
      hideExpression: '!model.mobile_enable'
    },
    {
      key: 'bigData_enable',
      type: 'checkbox',
      templateOptions: {
        label: 'Big Data Key Words',
        required: false
      }
    },
    {
      key: 'bigData',
      type: 'input',
      templateOptions: {
        type: 'text',
        placeholder: 'ETL, Big Data, Languages',
        required: false
      },
      hideExpression: '!model.bigData_enable'
    },
    {
      key: 'relevance',
      type: 'radio',
      templateOptions: {
        label: 'Relevance',
        required: false,
        options: [
          {name: 'True', value: true},
          {name: 'False', value: false}
        ]
      }
    },
    ];

  }
  ]);
<|endoftext|>


<commit_before>django.jQuery(function($) {
    'use strict';
    $.getScript("/static/node_modules/a-color-picker/dist/acolorpicker.js", function() {});

    function color_selector(id_glossary, id_picker) {
        var bools = {};
        var data = $(id_glossary);
        var thumb = 'thumb_' + id_picker;
        if (data) {
            bools[id_picker] = true;
            var $colordefault = data.val();
            data.parent().append('');
            data.add('#'+ thumb ).on('click', function() {
                if (bools[id_picker]) {
                    data.parent().append('

');
                    data.parent().append('<input id="undo_' + id_picker + '"  type="button" value="Undo">');
                    AColorPicker.from('#' + id_picker).on('change', (picker, color) => {
                        data.val(picker.color);
                        $('#'+ id_picker ).css("background-color", data.val())
                    });
                    bools[id_picker] = false;
                    $('#undo_' + id_picker).on('click', function() {
                        data.val($colordefault);
                        $('#' + id_picker).detach();
                        $('#thumb' + id_picker).css("background-color", data.val());
                        $('#undo_' + id_picker).detach();
                        bools[id_picker] = true;
                    });
                } else {
                    $('#' + id_picker).detach();
                    $('#undo_' + id_picker).detach();
                    bools[id_picker] = true;
                }
            });
        }
    };
    color_selector('#id_glossary_extra_inline_styles\\:color_color', 'id_picker_color');
    color_selector('#id_glossary_extra_inline_styles\\:background-color_color', 'id_picker_backgroundcolor');
});
<commit_msg>modif js color picker<commit_after>django.jQuery(function($) {
    'use strict';
    $.getScript("/static/node_modules/a-color-picker/dist/acolorpicker.js", function() {});

    function color_selector(id_glossary, id_picker) {
        var bools = {};
        var data = $(id_glossary);
        var thumb = 'thumb_' + id_picker;
        if (data) {
            bools[id_picker] = true;
            var $colordefault = data.val();
            data.parent().append('');
            data.add('#'+ thumb ).on('click', function() {
                if (bools[id_picker]) {
                    data.parent().append('

');
                    data.parent().append('<input id="undo_' + id_picker + '"  type="button" value="Undo">');
                    AColorPicker.from('#' + id_picker).on('change', (picker, color) => {
                        data.val(picker.color);
                        $('#'+ thumb).css("background-color", data.val())
                    });
                    bools[id_picker] = false;
                    $('#undo_' + id_picker).on('click', function() {
                        data.val($colordefault);
                        $('#' + id_picker).detach();
                        $('#'+ thumb).css("background-color", data.val());
                        $('#undo_' + id_picker).detach();
                        bools[id_picker] = true;
                    });
                } else {
                    $('#' + id_picker).detach();
                    $('#undo_' + id_picker).detach();
                    bools[id_picker] = true;
                }
            });
        }
    };
    color_selector('#id_glossary_extra_inline_styles\\:color_color', 'id_picker_color');
    color_selector('#id_glossary_extra_inline_styles\\:background-color_color', 'id_picker_backgroundcolor');
});
<|endoftext|>


<commit_before>'use strict';
import React from 'react';
import { Link } from 'react-router';

var ProjectList = React.createClass({
  displayName: 'ProjectList',

  propTypes: {
    fetched: React.PropTypes.bool,
    fetching: React.PropTypes.bool,
    adminAreaId: React.PropTypes.number,
    adminAreaName: React.PropTypes.string,
    projects: React.PropTypes.array,
    meta: React.PropTypes.object,
    error: React.PropTypes.string,
    sliceList: React.PropTypes.bool
  },

  renderViewAllLink: function () {
    if (!this.props.sliceList) return null;
    let {limit, total} = this.props.meta;

    if (total > limit) {
      let url = `/analytics/${this.props.adminAreaId}/projects`;
      return
<Link to={url} className='bttn-view-more'>View all projects</Link>
;
    }
  },

  renderContent: function () {
    let content;
    if (this.props.fetching) {
      content = (
Loading projects...

      );
    } else if (this.props.error) {
      content =
Oops... An error occurred.
;
    } else if (!this.props.meta.total) {
      content =
No errors to show.
;
    }

    if (content) {
      return content;
    }

    return (

              Scope
              Code
              Year
              Road
              Length
              Cost

            {this.props.projects.map(o => {
              return (

                  {o.project_scope}
                  {o.project_code}
                  {o.year}
                  {o.road_name}
                  {o.length_km}
                  {o.project_cost}

              );
            })}

        {this.renderViewAllLink()}

    );
  },

  render: function () {
    if (!this.props.fetched && !this.props.fetching) {
      return null;
    }

    let title = 'Projects';
    if (this.props.fetched && !this.props.fetching && this.props.meta.total) {
      title += ` (${this.props.meta.total})`;
    }

    return (

{title}

          {this.renderContent()}

    );
  }
});

export default ProjectList;
<commit_msg>Add comma separator to project cost<commit_after>'use strict';
import React from 'react';
import { Link } from 'react-router';
import { formatThousands } from '../utils/format';

var ProjectList = React.createClass({
  displayName: 'ProjectList',

  propTypes: {
    fetched: React.PropTypes.bool,
    fetching: React.PropTypes.bool,
    adminAreaId: React.PropTypes.number,
    adminAreaName: React.PropTypes.string,
    projects: React.PropTypes.array,
    meta: React.PropTypes.object,
    error: React.PropTypes.string,
    sliceList: React.PropTypes.bool
  },

  renderViewAllLink: function () {
    if (!this.props.sliceList) return null;
    let {limit, total} = this.props.meta;

    if (total > limit) {
      let url = `/analytics/${this.props.adminAreaId}/projects`;
      return
<Link to={url} className='bttn-view-more'>View all projects</Link>
;
    }
  },

  renderContent: function () {
    let content;
    if (this.props.fetching) {
      content = (
Loading projects...

      );
    } else if (this.props.error) {
      content =
Oops... An error occurred.
;
    } else if (!this.props.meta.total) {
      content =
No errors to show.
;
    }

    if (content) {
      return content;
    }

    return (

              Scope
              Code
              Year
              Road
              Length (km)
              Cost

            {this.props.projects.map(o => {
              return (

                  {o.project_scope}
                  {o.project_code}
                  {o.year}
                  {o.road_name}
                  {o.length_km}
                  {formatThousands(o.project_cost)}

              );
            })}

        {this.renderViewAllLink()}

    );
  },

  render: function () {
    if (!this.props.fetched && !this.props.fetching) {
      return null;
    }

    let title = 'Projects';
    if (this.props.fetched && !this.props.fetching && this.props.meta.total) {
      title += ` (${this.props.meta.total})`;
    }

    return (

{title}

          {this.renderContent()}

    );
  }
});

export default ProjectList;
<|endoftext|>


<commit_before>import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { compose, graphql } from 'react-apollo';
import { connect } from 'react-redux';
import RaisedButton from 'material-ui/RaisedButton';
import Dialog from 'material-ui/Dialog';
import FontIcon from 'material-ui/FontIcon';

import Link from 'components/Link';
import ActionSettingsContainer from 'components/ActionSettingsContainer';

import { notify } from 'actions/NotificationsActions';

import history from 'lib/history';

import CreateActionMutation from 'schemas/mutations/CreateActionMutation.graphql';
import CampaignQuery from 'schemas/queries/CampaignQuery.graphql';

import s from 'styles/Organize.scss';

class CreateAction extends Component {
  static propTypes = {
    campaign: PropTypes.object,
    dispatch: PropTypes.func.isRequired,
    createActionMutation: PropTypes.func.isRequired,
    type: PropTypes.string.isRequired,
    // eslint-disable-next-line react/no-unused-prop-types
    campaignId: PropTypes.string.isRequired,
  };

  static defaultProps = {
    campaign: undefined,
  };

  constructor(props) {
    super(props);

    this.state = {
      modalOpen: false,
      newAction: {
        title: '',
        slug: '',
      },
    };
  }

  createAction = async (data) => {
    const actionData = { ...data, campaignId: this.props.campaignId };

    try {
      const results = await this.props.createActionMutation({
        variables: {
          data: actionData,
        },
        refetchQueries: ['SearchActionsQuery'],
      });

      this.props.dispatch(notify('Opportunity successfully created'));

      this.setState({
        modalOpen: true,
        newAction: results.data.createAction,
      });
    } catch (e) {
      console.error(e);
      this.props.dispatch(
        notify('There was an error with your request. Please reload the page or contact help@uprise.org for support.'),
      );
    }
  };

  render() {
    if (this.props.campaign) {
      const { newAction, modalOpen } = this.state;
      const { campaign, type } = this.props;
      const { createAction } = this;

      const modalActions = [

 {
            event.preventDefault();
            history.push(`/organize/${campaign.slug}/opportunity/${newAction.slug}`);
          }}
          onKeyPress={(event) => {
            event.preventDefault();
            history.push(`/organize/${campaign.slug}/opportunity/${newAction.slug}`);
          }}
          role="button"
          tabIndex="0"
        >
          Manage Opportunity

,
      ];

      return (

{campaign.title}

              {campaign.profile_subheader &&
{campaign.profile_subheader}
}

                <Link to={`/organize/${campaign.slug}`}>{campaign.title}</Link>
                <FontIcon className={['material-icons', 'arrowRight'].join(' ')}>keyboard_arrow_right</FontIcon>
                Create Opportunity

            <ActionSettingsContainer campaign={campaign} type={type} submit={createAction} />

            {modalOpen && (
              <Dialog
                title="Opportunity Created"
                modal
                actions={modalActions}
                actionsContainerClassName={s.modalActionsContainer}
                open={modalOpen}
              >

Congratulations, you have created the opportunity '{newAction.title}'.

                  You can find your opportunity's public profile at {window.location.origin}/opportunity/{
                    newAction.slug
                  }

You can manage your opportunity here:

              </Dialog>
            )}

      );
    }
    return null;
  }
}

const withCampaignQuery = graphql(CampaignQuery, {
  options: (ownProps) => ({
    variables: {
      search: {
        id: ownProps.campaignId,
      },
    },
  }),
  props: ({ data }) => ({
    campaign: data.campaign,
  }),
});

export default compose(connect(), withCampaignQuery, graphql(CreateActionMutation, { name: 'createActionMutation' }))(
  CreateAction,
);
<commit_msg>Add 'Create New Opportunity' to popup after creating opportunity<commit_after>import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { compose, graphql } from 'react-apollo';
import { connect } from 'react-redux';
import RaisedButton from 'material-ui/RaisedButton';
import Dialog from 'material-ui/Dialog';
import FontIcon from 'material-ui/FontIcon';

import Link from 'components/Link';
import ActionSettingsContainer from 'components/ActionSettingsContainer';

import { notify } from 'actions/NotificationsActions';

import history from 'lib/history';

import CreateActionMutation from 'schemas/mutations/CreateActionMutation.graphql';
import CampaignQuery from 'schemas/queries/CampaignQuery.graphql';

import s from 'styles/Organize.scss';

class CreateAction extends Component {
  static propTypes = {
    campaign: PropTypes.object,
    dispatch: PropTypes.func.isRequired,
    createActionMutation: PropTypes.func.isRequired,
    type: PropTypes.string.isRequired,
    // eslint-disable-next-line react/no-unused-prop-types
    campaignId: PropTypes.string.isRequired,
  };

  static defaultProps = {
    campaign: undefined,
  };

  constructor(props) {
    super(props);

    this.state = {
      modalOpen: false,
      newAction: {
        title: '',
        slug: '',
      },
    };
  }

  createAction = async (data) => {
    const actionData = { ...data, campaignId: this.props.campaignId };

    try {
      const results = await this.props.createActionMutation({
        variables: {
          data: actionData,
        },
        refetchQueries: ['SearchActionsQuery'],
      });

      this.props.dispatch(notify('Opportunity successfully created'));

      this.setState({
        modalOpen: true,
        newAction: results.data.createAction,
      });
    } catch (e) {
      console.error(e);
      this.props.dispatch(
        notify('There was an error with your request. Please reload the page or contact help@uprise.org for support.'),
      );
    }
  };

  render() {
    if (this.props.campaign) {
      const { newAction, modalOpen } = this.state;
      const { campaign, type } = this.props;
      const { createAction } = this;

      const modalActions = [

 {
            event.preventDefault();
            history.push(`/organize/${campaign.slug}/opportunity/${newAction.slug}`);
          }}
          onKeyPress={(event) => {
            event.preventDefault();
            history.push(`/organize/${campaign.slug}/opportunity/${newAction.slug}`);
          }}
          role="button"
          tabIndex="0"
        >
          Manage Opportunity

,

 {
            event.preventDefault();
            window.location.reload(true);
          }}
          onKeyPress={(event) => {
            event.preventDefault();
            window.location.reload(true);
          }}
        >
          Create New Opportunity

,
      ];

      return (

{campaign.title}

              {campaign.profile_subheader &&
{campaign.profile_subheader}
}

                <Link to={`/organize/${campaign.slug}`}>{campaign.title}</Link>
                <FontIcon className={['material-icons', 'arrowRight'].join(' ')}>keyboard_arrow_right</FontIcon>
                Create Opportunity

            <ActionSettingsContainer campaign={campaign} type={type} submit={createAction} />

            {modalOpen && (
              <Dialog title="Opportunity Created" modal actions={modalActions} open={modalOpen}>

Congratulations, you have created the opportunity '{newAction.title}'.

                  You can find your opportunity's public profile at {window.location.origin}/opportunity/
                  {newAction.slug}

You can manage your opportunity here:

              </Dialog>
            )}

      );
    }
    return null;
  }
}

const withCampaignQuery = graphql(CampaignQuery, {
  options: (ownProps) => ({
    variables: {
      search: {
        id: ownProps.campaignId,
      },
    },
  }),
  props: ({ data }) => ({
    campaign: data.campaign,
  }),
});

export default compose(
  connect(),
  withCampaignQuery,
  graphql(CreateActionMutation, { name: 'createActionMutation' }),
)(CreateAction);
<|endoftext|>


<commit_before>'use strict';
import React from 'react';
import { connect } from 'react-redux';
import {
  compose,
  getContext
} from 'recompose';
import T from '../components/t';
import { Link } from 'react-router';
import RoadTable from '../containers/road-table-container';
import DistrictList from '../components/district-list';
import {
  fetchAdminInfo
} from '../actions/action-creators';
import config from '../config';
import {
  ADMIN_MAP
} from '../constants';

const renderAdminName = (children, aaId, aaIdSub) => {
  const adminName = aaIdSub ?
  children.find(child => child.id === Number(aaIdSub)).name_en :
  ADMIN_MAP.province[aaId].name;

  return (

{adminName}

  );
};

var AssetsAA = React.createClass({
  displayName: 'AssetsAA',

  propTypes: {
    _fetchAdminInfo: React.PropTypes.func,
    params: React.PropTypes.object,
    language: React.PropTypes.string,
    adminInfo: React.PropTypes.object,
    adminInfoFetched: React.PropTypes.bool
  },

  componentWillMount: function () {
    this.props._fetchAdminInfo(this.props.params.aaId);
  },

  componentWillReceiveProps: function (nextProps) {
    if (this.props.params.aaId !== nextProps.params.aaId) {
      this.props._fetchAdminInfo(nextProps.params.aaId);
    }
  },

  render: function () {
    const { adminInfoFetched, language, adminInfo: { children }, params: { aaId, aaIdSub } } = this.props;

    return (

            {
              children && renderAdminName(children, aaId, aaIdSub)
            }
            {
              !aaIdSub && ADMIN_MAP.province[aaId] &&

                  <a
                    className='button button--secondary-raised-dark'
                    href={`${config.provinceDumpBaseUrl}${ADMIN_MAP.province[aaId].id}.csv`}
                    target="_blank"
                  >
                    <T>Download Roads</T>

            }

          {
            aaIdSub ?

                <Link
                  to={`/${this.props.language}/assets/${aaId}`}
                >
                  {ADMIN_MAP.province[aaId].name}
                </Link>

 :

                <Link
                  to={`/${this.props.language}/assets`}
                >
                  <T>Provinces</T>
                </Link>

          }

            {
              !aaIdSub && adminInfoFetched &&
                <DistrictList
                  districts={children}
                  aaId={aaId}
                  language={language}
                />
            }

            <RoadTable />

    );
  }
});

export default compose(
  getContext({ language: React.PropTypes.string }),
  connect(
    state => ({
      adminInfo: state.adminInfo.data,
      adminInfoFetched: state.adminInfo.fetched
    }),
    dispatch => ({
      _fetchAdminInfo: (id, level) => dispatch(fetchAdminInfo(id, level))
    })
  )
)(AssetsAA);
<commit_msg>Switch admin dumps to shapefile province IDs instead of VPRoMMS province IDs<commit_after>'use strict';
import React from 'react';
import { connect } from 'react-redux';
import {
  compose,
  getContext
} from 'recompose';
import T from '../components/t';
import { Link } from 'react-router';
import RoadTable from '../containers/road-table-container';
import DistrictList from '../components/district-list';
import {
  fetchAdminInfo
} from '../actions/action-creators';
import config from '../config';
import {
  ADMIN_MAP
} from '../constants';

const renderAdminName = (children, aaId, aaIdSub) => {
  const adminName = aaIdSub ?
  children.find(child => child.id === Number(aaIdSub)).name_en :
  ADMIN_MAP.province[aaId].name;

  return (

{adminName}

  );
};

var AssetsAA = React.createClass({
  displayName: 'AssetsAA',

  propTypes: {
    _fetchAdminInfo: React.PropTypes.func,
    params: React.PropTypes.object,
    language: React.PropTypes.string,
    adminInfo: React.PropTypes.object,
    adminInfoFetched: React.PropTypes.bool
  },

  componentWillMount: function () {
    this.props._fetchAdminInfo(this.props.params.aaId);
  },

  componentWillReceiveProps: function (nextProps) {
    if (this.props.params.aaId !== nextProps.params.aaId) {
      this.props._fetchAdminInfo(nextProps.params.aaId);
    }
  },

  render: function () {
    const { adminInfoFetched, language, adminInfo: { children }, params: { aaId, aaIdSub } } = this.props;

    return (

            {
              children && renderAdminName(children, aaId, aaIdSub)
            }
            {
              !aaIdSub && aaId &&

                  <a
                    className='button button--secondary-raised-dark'
                    href={`${config.provinceDumpBaseUrl}${aaId}.csv`}
                    target="_blank"
                  >
                    <T>Download Roads</T>

            }

          {
            aaIdSub ?

                <Link
                  to={`/${this.props.language}/assets/${aaId}`}
                >
                  {ADMIN_MAP.province[aaId].name}
                </Link>

 :

                <Link
                  to={`/${this.props.language}/assets`}
                >
                  <T>Provinces</T>
                </Link>

          }

            {
              !aaIdSub && adminInfoFetched &&
                <DistrictList
                  districts={children}
                  aaId={aaId}
                  language={language}
                />
            }

            <RoadTable />

    );
  }
});

export default compose(
  getContext({ language: React.PropTypes.string }),
  connect(
    state => ({
      adminInfo: state.adminInfo.data,
      adminInfoFetched: state.adminInfo.fetched
    }),
    dispatch => ({
      _fetchAdminInfo: (id, level) => dispatch(fetchAdminInfo(id, level))
    })
  )
)(AssetsAA);
<|endoftext|>


<commit_before><commit_msg>bugfixing<commit_after><|endoftext|>


<commit_before>import { createSelector } from 'reselect';

/**
 * Direct selector to the generalSearchContainer state domain
 */
const selectGeneralSearchContainerDomain = () => (state) => state.get('generalSearchContainer');

/**
 * Other specific selectors
 */

/**
 * Default selector used by GeneralSearchContainer
 */

const makeSelectGeneralSearchContainer = () => createSelector(
  selectGeneralSearchContainerDomain(),
  (substate) => substate.toJS()
);

export default makeSelectGeneralSearchContainer;
export {
  selectGeneralSearchContainerDomain,
};
<commit_msg>Zapped un-needed selector<commit_after><|endoftext|>


<commit_before>var fs = require('fs');

var template = fs.readFileSync('announcement.template.html', 'utf8'),
    anns = require('./announcement.json'),
    defann = anns.default,
    specs = anns.announcements;

function interpolateAnnouncement(spec) {
    return template
        .replace(/\$name\$/g, spec.name)
        .replace(/\$gradient\$/g, spec.gradient)
        .replace(/\$textcolor\$/g, spec.textcolor)
        .replace(/\$mottocolor\$/g, spec.mottocolor);
}

var len = specs.length,
    spec, ann, i;

console.log('Generating ' + len + ' announcements [' + specs.map(function (val) { return val.name; }).join(' ') + ']');
for (i = 0, len = specs.length; i < len; i += 1) {
    spec = specs[i];
    ann = interpolateAnnouncement(spec);
    if (spec.name === defann) {
        fs.writeFileSync('announcement.html', ann);
    } else {
        fs.writeFileSync('variants/' + spec.name + '.html', ann);
    }
}
<commit_msg>Delete generate-announcements.js<commit_after><|endoftext|>


<commit_before>(function() {

    'use strict';

    var yeoman = require('yeoman-generator'),
        chalk = require('chalk');

    module.exports = yeoman.generators.Base.extend({

        constructor: function () {
            yeoman.generators.Base.apply(this, arguments);
        },

        initializing: function() {
            var done = this.async();

            this.log(chalk.cyan('\t \t  ___           __  __     _    _ '));
            this.log(chalk.cyan('\t \t / __| __ __ _ / _|/ _|___| |__| |'));
            this.log(chalk.cyan('\t \t \\__ \\/ _/ _` |  _|  _/ _ \\ / _` |'));
            this.log(chalk.cyan('\t \t |___/\\__\\__,_|_| |_| \\___/_\\__,_| \n'));
            this.log(chalk.cyan('\t \t [        Generating Build       ] \n \n'));
            this.log(chalk.green('Wait until build finish. I will create a zip file with all contents of your project.\n'));
            this.log(chalk.green('At the end of the process choose which type of version you are generating. \n \n'));

            this.spawnCommand('grunt', ['build']).on('exit', done);
        },

        prompting: function() {
            var cb = this.async(),
                prompts = [{
                    type: 'confirm',
                    name: 'hasVersion',
                    message: 'This will increase a version of your project?',
                    default: 0
                }, {
                    type: 'list',
                    name: 'versionType',
                    message: 'What kind of version?',
                    choices: ['Just a fix (Ex: 0.0.1)', 'Minor Version (Ex: 0.1.0)', 'Major Version (Ex: 1.0.0)', 'Pre-release (Ex: 1.0.0-1)'],
                    default: 0,
                    when: function (answers) {
                        return answers.hasVersion;
                    }
                }];

            this.log('\n \n');

            this.prompt(prompts, function(props) {
                for(var item in props) {
                    this[item] = props[item];
                }

                this.log(chalk.yellow(' \n Perfect! \n \n'));

                cb();
            }.bind(this));
        },

        writing: function() {
            if (this.hasVersion) {
                var done = this.async(),
                    version = 'patch';

                if (this.versionType === 'Minor Version (Ex: 0.1.0)') {
                    version = 'minor';
                } else if (this.versionType === 'Major Version (Ex: 1.0.0)') {
                    version = 'major';
                } else if (this.versionType === 'Pre-release (Ex: 1.0.0-1)') {
                    version = 'prerelease';
                }

                this.spawnCommand('grunt', ['bump:' + version]).on('exit', done);
            }
        },

        end: function() {
            this.log(chalk.yellow('\n \n All done! Everything looks fine. Good job! \n \n'));
        }

    });

})();
<commit_msg>Ask for version change at start<commit_after>(function() {

    'use strict';

    var yeoman = require('yeoman-generator'),
        chalk = require('chalk');

    module.exports = yeoman.generators.Base.extend({

        constructor: function () {
            yeoman.generators.Base.apply(this, arguments);
        },

        initializing: function() {
            this.log(chalk.cyan('\t \t  ___           __  __     _    _ '));
            this.log(chalk.cyan('\t \t / __| __ __ _ / _|/ _|___| |__| |'));
            this.log(chalk.cyan('\t \t \\__ \\/ _/ _` |  _|  _/ _ \\ / _` |'));
            this.log(chalk.cyan('\t \t |___/\\__\\__,_|_| |_| \\___/_\\__,_| \n'));
            this.log(chalk.cyan('\t \t [        Generating Build       ] \n \n'));
            this.log(chalk.green('Wait until build finish. I will create a zip file with all contents of your project.\n'));
            this.log(chalk.green('Choose below if this build means a new version and what type. \n \n'));
        },

        prompting: function() {
            var cb = this.async(),
                prompts = [{
                    type: 'confirm',
                    name: 'hasVersion',
                    message: 'This will increase a version of your project?',
                    default: 0
                }, {
                    type: 'list',
                    name: 'versionType',
                    message: 'What kind of version?',
                    choices: ['Just a fix (Ex: 0.0.1)', 'Minor Version (Ex: 0.1.0)', 'Major Version (Ex: 1.0.0)', 'Pre-release (Ex: 1.0.0-1)'],
                    default: 0,
                    when: function (answers) {
                        return answers.hasVersion;
                    }
                }];

            this.prompt(prompts, function(props) {
                for(var item in props) {
                    this[item] = props[item];
                }

                this.log(chalk.yellow(' \n Perfect! \n \n'));

                cb();
            }.bind(this));
        },

        writing: function() {
            if (this.hasVersion) {
                var done = this.async(),
                    version = 'patch';

                if (this.versionType === 'Minor Version (Ex: 0.1.0)') {
                    version = 'minor';
                } else if (this.versionType === 'Major Version (Ex: 1.0.0)') {
                    version = 'major';
                } else if (this.versionType === 'Pre-release (Ex: 1.0.0-1)') {
                    version = 'prerelease';
                }

                this.spawnCommand('grunt', ['bump:' + version]).on('exit', done);
            }
        },

        install: function() {
            var done = this.async();

            this.spawnCommand('grunt', ['build']).on('exit', done);
        },

        end: function() {
            this.log(chalk.yellow('\n \n All done! Everything looks fine. Good job! \n \n'));
        }

    });

})();
<|endoftext|>


<commit_before>var assert = require('assert');

add_dependencies({
    _: 'third/underscore/underscore.js',
    Dict: 'js/dict.js'
});

var ct = require('js/composebox_typeahead.js');

var people_in_realm = [{email: 'othello@zulip.com', full_name: "Othello, Moor of Venice"},
					   {email: 'cordelia@zulip.com', full_name: "Cordelia Lear"}];
var emoji_list = [{emoji_name: "tada", emoji_url: "TBD"},
			      {emoji_name: "moneybags", emoji_url: "TBD"}];

set_global('page_params', {people_list: people_in_realm});
set_global('emoji', {emojis: emoji_list});

(function test_add_topic () {
    ct.add_topic('Denmark', 'civil fears');
    ct.add_topic('devel', 'fading');
    ct.add_topic('denmark', 'acceptance');
    ct.add_topic('denmark', 'Acceptance');
    ct.add_topic('Denmark', 'With Twisted Metal');

    assert.deepEqual(ct.topics_seen_for('Denmark'), ['With Twisted Metal', 'acceptance', 'civil fears']);
}());

(function test_begins_typeahead () {
	// Stub out split_at_cursor that uses $(':focus')
	ct.split_at_cursor = function (word) { return [word, '']; };

    var begin_typehead_this = {options: {completions: {emoji: true,
                                                      mention: true}}};

    function assert_typeahead_equals(input, reference) {
        var returned = ct.compose_content_begins_typeahead.call(begin_typehead_this, input);
        assert.deepEqual(returned, reference);
    }

    assert_typeahead_equals("test", false);
    assert_typeahead_equals("test one two", false);
    assert_typeahead_equals("test *", false);
    assert_typeahead_equals("test @", false);
    assert_typeahead_equals("test no@o", false);
    assert_typeahead_equals("test :-P", false);

    var all_item = { special_item_text: 'all (Notify everyone)', email: 'all', pm_recipient_count: Infinity, full_name: 'all' };
    var people_with_all = people_in_realm.concat([all_item]);

    assert_typeahead_equals("test @o", people_with_all);
    assert_typeahead_equals("test @z", people_with_all);
    assert_typeahead_equals("@zuli", people_with_all);

    assert_typeahead_equals("hi emoji :", false);
    assert_typeahead_equals("hi emoji :ta", emoji_list);
    assert_typeahead_equals("hi emoji :da", emoji_list);

}());
<commit_msg>Fix composebox typeahead tests.<commit_after>var assert = require('assert');

add_dependencies({
    _: 'third/underscore/underscore.js',
    Dict: 'js/dict.js'
});

var ct = require('js/composebox_typeahead.js');

var people_in_realm = [{email: 'othello@zulip.com', full_name: "Othello, Moor of Venice"},
					   {email: 'cordelia@zulip.com', full_name: "Cordelia Lear"}];
var emoji_list = [{emoji_name: "tada", emoji_url: "TBD"},
			      {emoji_name: "moneybags", emoji_url: "TBD"}];

set_global('page_params', {people_list: people_in_realm});
set_global('emoji', {emojis: emoji_list});

(function test_add_topic () {
    ct.add_topic('Denmark', 'civil fears');
    ct.add_topic('devel', 'fading');
    ct.add_topic('denmark', 'acceptance');
    ct.add_topic('denmark', 'Acceptance');
    ct.add_topic('Denmark', 'With Twisted Metal');

    assert.deepEqual(ct.topics_seen_for('Denmark'), ['With Twisted Metal', 'acceptance', 'civil fears']);
}());

(function test_begins_typeahead () {
	// Stub out split_at_cursor that uses $(':focus')
	ct.split_at_cursor = function (word) { return [word, '']; };

    var begin_typehead_this = {options: {completions: {emoji: true,
                                                      mention: true}}};

    function assert_typeahead_equals(input, reference) {
        var returned = ct.compose_content_begins_typeahead.call(begin_typehead_this, input);
        assert.deepEqual(returned, reference);
    }

    assert_typeahead_equals("test", false);
    assert_typeahead_equals("test one two", false);
    assert_typeahead_equals("test *", false);
    assert_typeahead_equals("test @", false);
    assert_typeahead_equals("test no@o", false);
    assert_typeahead_equals("test :-P", false);

    var all_items = [{ special_item_text: 'all (Notify everyone)', email: 'all', pm_recipient_count: Infinity, full_name: 'all' },
                     { special_item_text: 'everyone (Notify everyone)', email: 'everyone', full_name: 'everyone' }];
    var people_with_all = people_in_realm.concat(all_items);

    assert_typeahead_equals("test @o", people_with_all);
    assert_typeahead_equals("test @z", people_with_all);
    assert_typeahead_equals("@zuli", people_with_all);

    assert_typeahead_equals("hi emoji :", false);
    assert_typeahead_equals("hi emoji :ta", emoji_list);
    assert_typeahead_equals("hi emoji :da", emoji_list);

}());
<|endoftext|>


<commit_before>var assert = require('chai').assert;
var sinon = require('sinon');

let PromiseStore = require('../../build').PromiseStore;

describe('PromiseStore', function () {
  describe('.make()', function () {
    it("should track a promise's callbacks", function () {
      var promises = new PromiseStore();
      // There should be no tracked promises.
      assert.lengthOf(promises, 0);

      // Add one promise.
      new Promise(function (resolve, reject) {
        promises.make(randomToken(), resolve, reject);
      });
      assert.lengthOf(promises, 1);
    });

    it('should reject the promise when a token is reused', function () {
      var promises = new PromiseStore();

      var duplicatedToken = randomToken();

      // Add a promise, and an unrelated promise.
      new Promise(function (resolve, reject) {
        promises.make(duplicatedToken, resolve, reject);
      });
      new Promise(function (resolve, reject) {
        promises.make(randomToken(), resolve, reject);
      });
      assert.lengthOf(promises, 2);

      // Now, reuse the token of the first (unresolved) promise:
      (new Promise(function (resolve, reject) {
        promises.make(duplicatedToken, resolve, reject);
      })).then(
        function (resolve) { return promise.reject('Should not have gotten here!'); },
        // It SHOULD reject.
        function (error) {
          assert.isObject(error);
          // It did NOT track a new promise.
          assert.lengthOf(promises, 2);
        }
      );
    });
  });

  describe('.keep()', function () {
    it('should call the resolve() function', function () {
      var promises = new PromiseStore();
      var token = randomToken();
      var promise = new Promise(function (resolve, reject) {
        promises.make(token, resolve, reject);
      });

      // Resolve the promise asynchronously.
      var randomPayload = randomToken();
      doLater(function () {
        assert.lengthOf(promises, 1);
        promises.keep(token, randomPayload);
      });

      return promise.then(function (actual) {
        assert.strictEqual(actual, randomPayload);
        assert.lengthOf(promises, 0);
      });
    });
  });

  describe('.break()', function () {
    it('should call the reject() function', function () {
      var promises = new PromiseStore();
      var token = randomToken();
      var promise = new Promise(function (resolve, reject) {
        promises.make(token, resolve, reject);
      });

      // Resolve the promise asynchronously.
      var error = new Error();
      doLater(function () {
        assert.lengthOf(promises, 1);
        promises.break(token, error);
      });

      // inspired by:
      // https://gist.github.com/haroldtreen/5f1055eee5fcf01da3e0e15b8ec86bf6#gistcomment-2623170
      return promise.then(
        function () { return Promise.reject('should not be called'); },
        function (actualError) {
          assert.strictEqual(actualError, error);
          assert.lengthOf(promises, 0);
        }
      );
    });
  });

  // Do something asynchronously.
  function doLater(callback) {
    return setTimeout(callback, 0);
  }
});
<commit_msg>Test token reuse does not overwrite previous token's promise callbacks.<commit_after>var assert = require('chai').assert;
var sinon = require('sinon');

let PromiseStore = require('../../build').PromiseStore;

describe('PromiseStore', function () {
  describe('.make()', function () {
    it("should track a promise's callbacks", function () {
      var promises = new PromiseStore();
      // There should be no tracked promises.
      assert.lengthOf(promises, 0);

      // Add one promise.
      new Promise(function (resolve, reject) {
        promises.make(randomToken(), resolve, reject);
      });
      assert.lengthOf(promises, 1);
    });

    it('should reject the promise when a token is reused', function () {
      var promises = new PromiseStore();

      var reusedToken = randomToken();
      // These two fakes are to ensure the original is called.
      var originalResolve;
      var overwrittenResolve;

      // Add a promise, and an unrelated promise.
      new Promise(function (resolve, reject) {
        originalResolve = sinon.fake(resolve);
        promises.make(reusedToken, originalResolve, reject);
      });
      new Promise(function (resolve, reject) {
        promises.make(randomToken(), resolve, reject);
      });
      assert.lengthOf(promises, 2);

      // Now, reuse the token of the first (unresolved) promise:
      return (new Promise(function (resolve, reject) {
        overwrittenResolve = sinon.fake(resolve);
        promises.make(reusedToken, overwrittenResolve, reject);
      })).then(
        function (resolve) { return promise.reject('Should not have gotten here!'); },
        // It SHOULD reject.
        function (error) {
          assert.match(error, /existing/i);
          assert.include(error, reusedToken.toString());
          // It did NOT track a new promise.
          assert.lengthOf(promises, 2);
        }
      ).then(function () {
        promises.keep(reusedToken);
        sinon.assert.notCalled(overwrittenResolve);
        sinon.assert.called(originalResolve);
        assert.isTrue(false);
      });
    });
  });

  describe('.keep()', function () {
    it('should call the resolve() function', function () {
      var promises = new PromiseStore();
      var token = randomToken();
      var promise = new Promise(function (resolve, reject) {
        promises.make(token, resolve, reject);
      });

      // Resolve the promise asynchronously.
      var randomPayload = randomToken();
      doLater(function () {
        assert.lengthOf(promises, 1);
        promises.keep(token, randomPayload);
      });

      return promise.then(function (actual) {
        assert.strictEqual(actual, randomPayload);
        assert.lengthOf(promises, 0);
      });
    });
  });

  describe('.break()', function () {
    it('should call the reject() function', function () {
      var promises = new PromiseStore();
      var token = randomToken();
      var promise = new Promise(function (resolve, reject) {
        promises.make(token, resolve, reject);
      });

      // Resolve the promise asynchronously.
      var error = new Error();
      doLater(function () {
        assert.lengthOf(promises, 1);
        promises.break(token, error);
      });

      // inspired by:
      // https://gist.github.com/haroldtreen/5f1055eee5fcf01da3e0e15b8ec86bf6#gistcomment-2623170
      return promise.then(
        function () { return Promise.reject('should not be called'); },
        function (actualError) {
          assert.strictEqual(actualError, error);
          assert.lengthOf(promises, 0);
        }
      );
    });
  });

  // Do something asynchronously.
  function doLater(callback) {
    return setTimeout(callback, 0);
  }
});
<|endoftext|>


<commit_before>const mongoose = require('mongoose');
const moment = require('moment');
const _ = require('underscore');
const Schema = mongoose.Schema;
const async = require('async');
const { getEnergimolnetConsumption } = require('./consumption');

const DYNAMIC_KEYS = [
  'name',
  'email',
  'lng',
  'lat',
  'yearOfConst',
  'area',
  'numOfApartments',
  'meters',
  'ventilationType'
];

const CooperativeSchema = new Schema({
  name: {
    type: String,
    required: true,
    unique: true
  },
  email: String,
  lat: Number,
  lng: Number,
  yearOfConst: Number,
  area: Number,
  numOfApartments: Number,
  ventilationType: [String],
  meters: [{
    mType: String,
    useInCalc: Boolean,
    meterId: String,
  }],
  performances: [
    new Schema({
      year: Number,
      month: Number,
      value: Number,
      area: Number
    })
  ],
  actions: {
    type: [{
      type: Schema.Types.ObjectId,
      ref: 'Action'
    }],
    default: []
  },
  editors: [{
    type: Schema.Types.ObjectId,
    ref: 'User'
  }]
});

/**
 * Add a hook that removes action from it's parent cooperative
 */

CooperativeSchema.pre('remove', next => {
  this.model('Action').remove({ cooperative: this._id }, next);
});

/**
 * Prevent JSON responses from including populated fields
 */

CooperativeSchema.methods.toJSON = function toJSON() {
  const props = this.toObject();

  props.actions = props.actions.map(action => action._id || action);
  props.editors = props.editors.map(editor => editor._id || editor);

  return props;
};

const Cooperatives = mongoose.model('Cooperative', CooperativeSchema);

function getConsumption(cooperative, options, done) {
  const { type, granularity, from, to, normalized } = options;
  const { meters, area } = cooperative;

  getEnergimolnetConsumption(meters, type, granularity, from, to, normalized, (err, results) => {
    if (err) { return done(err); }
    done(null, results.map(value => value / (area ? area : 1)));
  });
}

function calculatePerformance(cooperative, done) {
  const props = cooperative.toObject();

  const now = new Date();

  let performance = cooperative.performances.find(match(now));
  if (!performance) {
    performance = cooperative.performances.find(
      match(moment(now).subtract(1, 'months').toDate())
    );
  }

  if (performance) {
    props.performance = performance.value;
    return done(null, props);
  } else {
    // Get the last 13 months to ensure 12 actual values
    // since the current month may not have any value yet
    const from = moment(now).subtract(12, 'months').format('YYYYMM');
    const to = moment(now).format('YYYYMM');

    getConsumption(props, 'heating', 'month', from, to, true, (err, result) => {
      if (err) { return done(err); }

      const value = result
        // Remove any empty values (i.e. current month)
        .filter(Boolean)
        // Take the last 12 (last year)
        .slice(-12)
        // Summarize consumtion
        .reduce((memo,num) => memo + num, 0);

      props.performance = value;

      if (!value) {
        return done(null, props);
      }

      // Figure out whether the last month is missing
      const missing = result[result.length - 1] ? 0 : 1;

      cooperative.performances.push({
        year: now.getFullYear(),
        month: moment(now).subtract(missing, 'months').month(),
        area: cooperative.area,
        value: value
      });

      cooperative.save(err => {
        if (err) { return done(err); }
        done(null, props);
      });
    });
  }

  /**
   * Create an iterator function that matches given date with
   * year and month of iteratiee properties
   * @param  {Date} date Date to match against
   * @return {function}      Iterator function
   */

  function match(date) {
    const year = date.getFullYear();
    const month = date.getMonth();

    return props => props.year === year && props.month === month;
  }
}

exports.create = function(props, user, done) {
  Cooperatives.create({
    name: props.name,
    email: props.email,
    lng: props.lng,
    lat: props.lat,
    yearOfConst: props.yearOfConst,
    area: props.area,
    numOfApartments: props.numOfApartments,
    meters: props.meters,
    ventilationType: props.ventilationType,
    editors: [ typeof user === 'object' ? user._id : user ]
  }, done);
};

exports.all = function(done) {
  Cooperatives.find({}, (err, cooperatives) => {
    if (err) { return done(err); }
    async.map(
      cooperatives.map(cooperative => cooperative.toObject()),
      calculatePerformance,
      done
    );
  });
};

exports.get = function (id, done) {
  Cooperatives
    .findOne({ _id: id })
    .populate('actions')
    .populate('editors')
    .exec((err, cooperative) => {
      if (err) { return done(err); }
      if (!cooperative) { return done(new Error('Cooperative not found')); }

      calculatePerformance(cooperative.toObject(), err => {
        if (err) { return done(err); }
        done(null, cooperative);
      });
    });
};

exports.getProfile = function(id, done) {
  Cooperatives.findOne({ _id: id }, (err, cooperative) => {
    if (err) { return done(err); }
    if (!cooperative) { return done(new Error('Cooperative not found')); }

    done(null, cooperative);
  });
};

exports.update = function(id, data, done) {
  Cooperatives.findOne({ _id: id }, (err, cooperative) => {
    if (err) { return done(err); }

    const selection = {};
    const areaChanged = data.area && (cooperative.area !== data.area);

    Object.keys(data).filter(key => DYNAMIC_KEYS.includes(key)).forEach(key => {
      selection[key] = data[key];
    });

    // Assign all data to cooperative
    Object.assign(cooperative, selection);

    if (areaChanged) {
      // Remove last perfomance calculation if area has changed
      cooperative.performances.$pop();

      // Recalculate latest performance
      calculatePerformance(cooperative, err => {
        if (err) { return done(err); }
        done(null, cooperative);
      });
    } else {
      cooperative.save(done);
    }
  });
};

exports.addEditor = function(id, user, done) {
  Cooperatives.findOne({ _id: id }, (err, cooperative) => {
    if (err) { return done(err); }
    if (!cooperative) { return done(new Error('Cooperative could not be found')); }
    cooperative.users.push(user._id);
    cooperative.markModified('users');
    cooperative.save(done);
  });
};

exports.deleteEditor = function(id, user, done) {
  Cooperatives.findOne({ _id: id }, (err, cooperative) => {
    if (err) { return done(err); }
    if (!cooperative) { return done(new Error('Cooperative could not be found')); }

    const index = cooperative.editors.findIndex(id => id === user._id);

    cooperative.editors.splice(index, 1);
    cooperative.markModified('editors');
    cooperative.save(done);
  });
};

exports.getAvgConsumption = function (type, granularity, from, to, cb) {
  Cooperatives.find({}, function (err, cooperatives){
    if (err) { return cb(err); }

    async.map(cooperatives, function (cooperative, cb2) {
      getConsumption(
        cooperative,
        { type, granularity, from, to, normalized: false },
        cb2
      );
    }, function (err, coopsData) {
      if (err) { return cb(err); }

      const avg = _.chain(coopsData)
        .reject(_.isEmpty)
        .unzip()
        .map(function(data){
          return _.reduce(data,function(memo, num){
            return memo + num;
          },0)/data.length;
        })
        .value();

      cb(null, avg);
    });
  });
};

exports.addMeter = function(id, meterId, type, useInCalc, cb) {
  Cooperatives.findOne({
    _id:id
  },function(err,cooperative){
    if(err) {
      cb(err);
    } else if (!cooperative){
      cb(new Error('Cooperative not found'));
    } else {
      cooperative.meters.push({
        mType:type,
        meterId: meterId,
        useInCalc: useInCalc
      });
      cooperative.markModified('meters');
      cooperative.save(function(err){
        if (err) { return cb(err); }
        cb(err,cooperative);
      });
    }
  });
};

exports.getConsumption = function(options, cb) {
  Cooperatives.findOne({
    _id: options.id
  },function(err,cooperative){
    if (err) {
      cb(err);
    } else if (!cooperative) {
      cb(new Error('Cooperative not found'));
    } else {
      getConsumption(cooperative, options, cb);
    }
  });
};

exports.getAll = function(cb){
  Cooperatives.find({}, cb);
};

exports.model = Cooperatives;
<commit_msg>Fix escessive objectification<commit_after>const mongoose = require('mongoose');
const moment = require('moment');
const _ = require('underscore');
const Schema = mongoose.Schema;
const async = require('async');
const { getEnergimolnetConsumption } = require('./consumption');

const DYNAMIC_KEYS = [
  'name',
  'email',
  'lng',
  'lat',
  'yearOfConst',
  'area',
  'numOfApartments',
  'meters',
  'ventilationType'
];

const CooperativeSchema = new Schema({
  name: {
    type: String,
    required: true,
    unique: true
  },
  email: String,
  lat: Number,
  lng: Number,
  yearOfConst: Number,
  area: Number,
  numOfApartments: Number,
  ventilationType: [String],
  meters: [{
    mType: String,
    useInCalc: Boolean,
    meterId: String,
  }],
  performances: [
    new Schema({
      year: Number,
      month: Number,
      value: Number,
      area: Number
    })
  ],
  actions: {
    type: [{
      type: Schema.Types.ObjectId,
      ref: 'Action'
    }],
    default: []
  },
  editors: [{
    type: Schema.Types.ObjectId,
    ref: 'User'
  }]
});

/**
 * Add a hook that removes action from it's parent cooperative
 */

CooperativeSchema.pre('remove', next => {
  this.model('Action').remove({ cooperative: this._id }, next);
});

/**
 * Prevent JSON responses from including populated fields
 */

CooperativeSchema.methods.toJSON = function toJSON() {
  const props = this.toObject();

  props.actions = props.actions.map(action => action._id || action);
  props.editors = props.editors.map(editor => editor._id || editor);

  return props;
};

const Cooperatives = mongoose.model('Cooperative', CooperativeSchema);

function getConsumption(cooperative, options, done) {
  const { type, granularity, from, to, normalized } = options;
  const { meters, area } = cooperative;

  getEnergimolnetConsumption(meters, type, granularity, from, to, normalized, (err, results) => {
    if (err) { return done(err); }
    done(null, results.map(value => value / (area ? area : 1)));
  });
}

function calculatePerformance(cooperative, done) {
  const props = cooperative.toObject();

  const now = new Date();

  let performance = cooperative.performances.find(match(now));
  if (!performance) {
    performance = cooperative.performances.find(
      match(moment(now).subtract(1, 'months').toDate())
    );
  }

  if (performance) {
    props.performance = performance.value;
    return done(null, props);
  } else {
    // Get the last 13 months to ensure 12 actual values
    // since the current month may not have any value yet
    const from = moment(now).subtract(12, 'months').format('YYYYMM');
    const to = moment(now).format('YYYYMM');

    getConsumption(props, 'heating', 'month', from, to, true, (err, result) => {
      if (err) { return done(err); }

      const value = result
        // Remove any empty values (i.e. current month)
        .filter(Boolean)
        // Take the last 12 (last year)
        .slice(-12)
        // Summarize consumtion
        .reduce((memo,num) => memo + num, 0);

      props.performance = value;

      if (!value) {
        return done(null, props);
      }

      // Figure out whether the last month is missing
      const missing = result[result.length - 1] ? 0 : 1;

      cooperative.performances.push({
        year: now.getFullYear(),
        month: moment(now).subtract(missing, 'months').month(),
        area: cooperative.area,
        value: value
      });

      cooperative.save(err => {
        if (err) { return done(err); }
        done(null, props);
      });
    });
  }

  /**
   * Create an iterator function that matches given date with
   * year and month of iteratiee properties
   * @param  {Date} date Date to match against
   * @return {function}      Iterator function
   */

  function match(date) {
    const year = date.getFullYear();
    const month = date.getMonth();

    return props => props.year === year && props.month === month;
  }
}

exports.create = function(props, user, done) {
  Cooperatives.create({
    name: props.name,
    email: props.email,
    lng: props.lng,
    lat: props.lat,
    yearOfConst: props.yearOfConst,
    area: props.area,
    numOfApartments: props.numOfApartments,
    meters: props.meters,
    ventilationType: props.ventilationType,
    editors: [ typeof user === 'object' ? user._id : user ]
  }, done);
};

exports.all = function(done) {
  Cooperatives.find({}, (err, cooperatives) => {
    if (err) { return done(err); }
    async.map(
      cooperatives,
      calculatePerformance,
      done
    );
  });
};

exports.get = function (id, done) {
  Cooperatives
    .findOne({ _id: id })
    .populate('actions')
    .populate('editors')
    .exec((err, cooperative) => {
      if (err) { return done(err); }
      if (!cooperative) { return done(new Error('Cooperative not found')); }

      calculatePerformance(cooperative, err => {
        if (err) { return done(err); }
        done(null, cooperative);
      });
    });
};

exports.getProfile = function(id, done) {
  Cooperatives.findOne({ _id: id }, (err, cooperative) => {
    if (err) { return done(err); }
    if (!cooperative) { return done(new Error('Cooperative not found')); }

    done(null, cooperative);
  });
};

exports.update = function(id, data, done) {
  Cooperatives.findOne({ _id: id }, (err, cooperative) => {
    if (err) { return done(err); }

    const selection = {};
    const areaChanged = data.area && (cooperative.area !== data.area);

    Object.keys(data).filter(key => DYNAMIC_KEYS.includes(key)).forEach(key => {
      selection[key] = data[key];
    });

    // Assign all data to cooperative
    Object.assign(cooperative, selection);

    if (areaChanged) {
      // Remove last perfomance calculation if area has changed
      cooperative.performances.$pop();

      // Recalculate latest performance
      calculatePerformance(cooperative, err => {
        if (err) { return done(err); }
        done(null, cooperative);
      });
    } else {
      cooperative.save(done);
    }
  });
};

exports.addEditor = function(id, user, done) {
  Cooperatives.findOne({ _id: id }, (err, cooperative) => {
    if (err) { return done(err); }
    if (!cooperative) { return done(new Error('Cooperative could not be found')); }
    cooperative.users.push(user._id);
    cooperative.markModified('users');
    cooperative.save(done);
  });
};

exports.deleteEditor = function(id, user, done) {
  Cooperatives.findOne({ _id: id }, (err, cooperative) => {
    if (err) { return done(err); }
    if (!cooperative) { return done(new Error('Cooperative could not be found')); }

    const index = cooperative.editors.findIndex(id => id === user._id);

    cooperative.editors.splice(index, 1);
    cooperative.markModified('editors');
    cooperative.save(done);
  });
};

exports.getAvgConsumption = function (type, granularity, from, to, cb) {
  Cooperatives.find({}, function (err, cooperatives){
    if (err) { return cb(err); }

    async.map(cooperatives, function (cooperative, cb2) {
      getConsumption(
        cooperative,
        { type, granularity, from, to, normalized: false },
        cb2
      );
    }, function (err, coopsData) {
      if (err) { return cb(err); }

      const avg = _.chain(coopsData)
        .reject(_.isEmpty)
        .unzip()
        .map(function(data){
          return _.reduce(data,function(memo, num){
            return memo + num;
          },0)/data.length;
        })
        .value();

      cb(null, avg);
    });
  });
};

exports.addMeter = function(id, meterId, type, useInCalc, cb) {
  Cooperatives.findOne({
    _id:id
  },function(err,cooperative){
    if(err) {
      cb(err);
    } else if (!cooperative){
      cb(new Error('Cooperative not found'));
    } else {
      cooperative.meters.push({
        mType:type,
        meterId: meterId,
        useInCalc: useInCalc
      });
      cooperative.markModified('meters');
      cooperative.save(function(err){
        if (err) { return cb(err); }
        cb(err,cooperative);
      });
    }
  });
};

exports.getConsumption = function(options, cb) {
  Cooperatives.findOne({
    _id: options.id
  },function(err,cooperative){
    if (err) {
      cb(err);
    } else if (!cooperative) {
      cb(new Error('Cooperative not found'));
    } else {
      getConsumption(cooperative, options, cb);
    }
  });
};

exports.getAll = function(cb){
  Cooperatives.find({}, cb);
};

exports.model = Cooperatives;
<|endoftext|>


<commit_before>module.exports = function(CompaniesService) {

  'ngInject';

  var self = this;

  this.company = {
    _id: '',
    name: '',
    email: '',
    phone: '',
    address: '',
    city: '',
    country: '',
    owners: ''
  };

  this.data = CompaniesService;

  this.companies = [];

  var getCompanies = function() {
    self.loading = 'get';
    CompaniesService.getCompanies().then(function(response) {
      self.loading = 'false';
      self.companies = response;
    });
  };

  this.companyCopy = angular.copy(this.company);

  this.addCompany = function() {
    self.loading = 'create';
    CompaniesService.createCompany(self.company).then(function(response) {
      self.clearForm(false);
      self.loading = false;
    });
  };

  this.clearForm = function(edit) {
    self.company = angular.copy(self.companyCopy);
  };

  this.deleteCompany = function(id) {
    self.loading = 'delete';
    CompaniesService.deleteCompany(id).then(function(response) {
      self.loading = false;
    });
  };

  this.editCompany = function(company) {
    if (company) {
      self.editMode = company._id;
      self.company = angular.copy(company);
      self.layoutAlign = 'center start';
    } else {
      self.editMode = undefined;
      self.company = angular.copy(self.companyCopy);
      self.layoutAlign = '';
    }
  };

  this.updateCompany = function() {
    self.loading = 'update';
    CompaniesService.updateCompany(self.company).then(function(response) {
      self.loading = false;
      self.editMode = undefined;
      self.company = angular.copy(self.companyCopy);
      self.layoutAlign = '';
    });
  };

  getCompanies();

};
<commit_msg>change owner attribute type on company<commit_after>module.exports = function(CompaniesService) {

  'ngInject';

  var self = this;

  this.company = {
    _id: '',
    name: '',
    email: '',
    phone: '',
    address: '',
    city: '',
    country: '',
    owners: []
  };

  this.data = CompaniesService;

  this.companies = [];

  var getCompanies = function() {
    self.loading = 'get';
    CompaniesService.getCompanies().then(function(response) {
      self.loading = 'false';
      self.companies = response;
    });
  };

  this.companyCopy = angular.copy(this.company);

  this.addCompany = function() {
    self.loading = 'create';
    CompaniesService.createCompany(self.company).then(function(response) {
      self.clearForm(false);
      self.loading = false;
    });
  };

  this.clearForm = function(edit) {
    self.company = angular.copy(self.companyCopy);
  };

  this.deleteCompany = function(id) {
    self.loading = 'delete';
    CompaniesService.deleteCompany(id).then(function(response) {
      self.loading = false;
    });
  };

  this.editCompany = function(company) {
    if (company) {
      self.editMode = company._id;
      self.company = angular.copy(company);
      self.layoutAlign = 'center start';
    } else {
      self.editMode = undefined;
      self.company = angular.copy(self.companyCopy);
      self.layoutAlign = '';
    }
  };

  this.updateCompany = function() {
    self.loading = 'update';
    CompaniesService.updateCompany(self.company).then(function(response) {
      self.loading = false;
      self.editMode = undefined;
      self.company = angular.copy(self.companyCopy);
      self.layoutAlign = '';
    });
  };

  getCompanies();

};
<|endoftext|>


<commit_before>module.exports = function modelLoader(isParent) {
    'use strict';

    if (isParent || process.env.MCTEST) {
        console.log('using mocks/model');
        return require('./mocks/model');
    }

    let ropts = {
        db: 'materialscommons',
        port: 30815
    };

    let r = require('rethinkdbdash')(ropts);
    return require('./db/model')(r);
};
<commit_msg>Add environment variables for testing, database and database server port.<commit_after>module.exports = function modelLoader(isParent) {
    'use strict';

    if (isParent || process.env.MCTEST) {
        return require('./mocks/model');
    }

    let ropts = {
        db: process.env.MCDB || 'materialscommons',
        port: process.env.MCPORT || 30815
    };

    let r = require('rethinkdbdash')(ropts);
    return require('./db/model')(r);
};
<|endoftext|>


<commit_before>// @flow
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { Link } from 'react-router';
import styles from './NetworkStatus.css';
import FontIcon from 'material-ui/FontIcon';
import {red500, green500, cyan500, blue500, pinkA200} from 'material-ui/styles/colors';
import notifier from 'notifier';

const nc = new notifier.NotificationCenter();

export default class NetworkStatus extends React.Component {

  constructor(props) {
    super(props);
    this.state = {connection: true};
  }
  componentDidMount() {
    this.refreshID = setInterval(
      () => this.check(),
      1000
    );
  }
  componentWillUnmount() {
    clearInterval(this.refreshID);
  }
  notifyOnline() {
    nc.notify({
      title: 'You are now Online!',
      message: 'Hearmenow is now able to initiate or accept calls.',
      closeLabel: 'Close',
      wait: true
    });
    console.log("Online");
  }
  notifyOffline() {
    nc.notify({
      title: 'You are now Offline!',
      message: 'Hearmenow is NOT able to initiate or accept calls while offline.',
      closeLabel: 'Close',
      wait: true
    });
    console.log("Offline");
  }
  check() {
    const status = this.state.connection;
    if(navigator.onLine) {
      if(!status){ this.notifyOnline() }
      this.setState({
        connection: true
      });
      return true
    }
    else{
      if(status){ this.notifyOffline() }
      this.setState({
        connection: false
      });
    }
  }

  trigger () {
    var x = this.state.connection ? nofityOnline() : notiftyOffline();
  }
  render() {
    var input = this.state.connection ? <FontIcon className="material-icons" style={styles.icon} color={green500}>adjust</FontIcon> : <FontIcon className="material-icons" style={styles.icon} color={red500}>adjust</FontIcon>;
    return (

         {input}

    );
  }
}
<commit_msg>snackbar<commit_after>// @flow
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { Link } from 'react-router';
import styles from './NetworkStatus.css';
import Snackbar from 'material-ui/Snackbar';
import FontIcon from 'material-ui/FontIcon';
import {red500, green500, cyan500, blue500, pinkA200} from 'material-ui/styles/colors';
import notifier from 'notifier';

const nc = new notifier.NotificationCenter();

export default class NetworkStatus extends React.Component {

  constructor(props) {
    super(props);
    this.state = {connection: true, online_open: false, offline_open: false};
  }
  componentDidMount() {
    this.refreshID = setInterval(
      () => this.check(),
      1000
    );
  }
  componentWillUnmount() {
    clearInterval(this.refreshID);
  }
  notifyOnline() {
    this.setState({
      online_open: true
    });
    console.log("Online");
  }
  notifyOffline() {
    this.setState({
      offline_open: true
    });
    console.log("Offline");
  }
  check() {
    const status = this.state.connection;
    if(navigator.onLine) {
      if(!status){ this.notifyOnline() }
      this.setState({
        connection: true
      });
      return true
    }
    else{
      if(status){ this.notifyOffline() }
      this.setState({
        connection: false
      });
    }
  }

  handleOnlineRequestClose = () => {
    this.setState({
      online_open: false,
    });
  }

  handleOfflineRequestClose = () => {
    this.setState({
      offline_open: false,
    });
  }
  trigger () {
    var x = this.state.connection ? nofityOnline() : notiftyOffline();
  }
  render() {
    var input = this.state.connection ?
<FontIcon className="material-icons" style={styles.icon} color={green500}>adjust</FontIcon>
    <Snackbar
      open={this.state.online_open}
      message="✔📶 You are now online 📶✔"
      autoHideDuration={2000}
      onRequestClose={this.handleOnlineRequestClose}>
    </Snackbar>
:

<FontIcon className="material-icons" style={styles.icon} color={red500}>adjust</FontIcon>
    <Snackbar
      open={!this.state.offline_open}
      message="❌📶 No internet connection 📶❌"
      autoHideDuration={2000}
      onRequestClose={this.handleOfflineRequestClose}>
    </Snackbar>
;
    return (

         {input}

    );
  }
}
<|endoftext|>


<commit_before>var fs = require('fs');
var express = require('express');
var serveStatic = require('serve-static');
var path = require('path');
var pg = require('pg');
var crypto = require('crypto')

var connectMsg = "Info: %s has joined the chatroom.";
var disconnectMsg = "Info: %s has left the chatroom.";
var welcomeMsg = "You are %s!";
var registerMsg = "Register here for your own unique username!";
var userListMsg = "Users online: %s";
var guestUsername = "Guest_%s";
var colors = ["d-re","l-bl","mage","red","pink","blue","teal","oran","d-pu"];

var commands = {"/who":printChannelUserList};
var usersList = {};

function printChannelUserList(socket,data) {
  socket.emit('info', {msg: userListMsg.replace("%s",usersList[data.channel].join(", "))});
}

function generateRandomColor() {
  var color = colors[Math.floor(Math.random() * colors.length)];
  return color;
}

function generateGuestId() {
  var randomInt = Math.floor((Math.random() * 10000) + 1000);
  return guestUsername.replace("%s",randomInt);
}

function getSalt(username,done) {
  var client = new pg.Client(process.env.PUBNUB_DB_URL);
  client.connect();
  var query = client.query("SELECT salt from users where username = $1", [username]);
  var salt = ""
  query.on('row', function(row) {
    salt = row.salt;
    done(salt);
  });
  query.on('end', function() {
    client.end();
  });
}

module.exports.run = function (worker) {
  console.log('   >> Worker PID:', process.pid);
  var app = require('express')();
  var httpServer = worker.httpServer;
  var scServer = worker.scServer;
  app.use(serveStatic(path.resolve(__dirname, 'public')));
  httpServer.on('request', app);

  scServer.on('connection', function (socket) {
    var authToken = socket.getAuthToken();
    //Blocks publish except for server.
    scServer.addMiddleware(scServer.MIDDLEWARE_PUBLISH_IN, function (req, next) {
      next(true);
    });

    socket.on('disconnect', function() {
      //deauth everytime user disconnects.
      socket.deauthenticate();
    })

    socket.on('auth', function(data,res) {
      //Validate user
      var username = generateGuestId();
      if (data.username.substr(0,3) == "reg") {

        data = data.username.split("_");
        var assumedUsername = data.slice(1,data.length-1).join("_");
        getSalt(assumedUsername,function(salt) {

          var hash = crypto.createHmac('sha1', 'chat').update(salt+assumedUsername).digest('hex')
          if (hash == data[data.length-1]) {
            username = assumedUsername;
          }
          socket.setAuthToken({username: username, color: generateRandomColor(), isRegistered: true});
          socket.emit('info', {msg: welcomeMsg.replace("%s",username)});
        });
      } else {
        socket.setAuthToken({username: username, color: generateRandomColor(), isRegistered: false});
        socket.emit('info', {msg: welcomeMsg.replace("%s",username)});
        socket.emit('info', {msg: registerMsg});
      }
    });

    socket.on('chat', function (data) {
      if (!authToken) {
        authToken = socket.getAuthToken();
      }
      if (authToken) {
        var msg = data.msg;
        var cmd = msg.split(" ")[0].toLowerCase();
        if (cmd in commands) {
          commands[cmd](socket,data);
        } else {
          var time = new Date();
          data.username = authToken.username;
          data.color = authToken.color;
          data.time = time.getTime();
          data.type = "message";
          data.isRegistered = authToken.isRegistered;
          scServer.global.publish(data.channel, data);
        }
      }
    });

    socket.on('subscribe', function (data) {
      if (!authToken) {
        authToken = socket.getAuthToken();
      }
      if (authToken){
        if (data in usersList) {
          usersList[data] = usersList[data].filter(function(value) { return value == authToken.username; });
          usersList[data].push(authToken.username);
        } else {
          usersList[data] = [authToken.username];
        }
        scServer.global.publish(data, {type: "info", msg: connectMsg.replace('%s',authToken.username)});
        printChannelUserList(socket,{channel:data});
      }
    });

    socket.on('unsubscribe', function (data) {
      if (!authToken) {
        authToken = socket.getAuthToken();
      }
      if (authToken){
        if (data in usersList) {
          usersList[data] = usersList[data].filter(function(value) { return value != authToken.username; });
        }
        scServer.global.publish(data, {type: "info", msg: disconnectMsg.replace('%s',authToken.username)});
      }
    });

  });

};
<commit_msg>Fix another filter logic.<commit_after>var fs = require('fs');
var express = require('express');
var serveStatic = require('serve-static');
var path = require('path');
var pg = require('pg');
var crypto = require('crypto')

var connectMsg = "Info: %s has joined the chatroom.";
var disconnectMsg = "Info: %s has left the chatroom.";
var welcomeMsg = "You are %s!";
var registerMsg = "Register here for your own unique username!";
var userListMsg = "Users online: %s";
var guestUsername = "Guest_%s";
var colors = ["d-re","l-bl","mage","red","pink","blue","teal","oran","d-pu"];

var commands = {"/who":printChannelUserList};
var usersList = {};

function printChannelUserList(socket,data) {
  socket.emit('info', {msg: userListMsg.replace("%s",usersList[data.channel].join(", "))});
}

function generateRandomColor() {
  var color = colors[Math.floor(Math.random() * colors.length)];
  return color;
}

function generateGuestId() {
  var randomInt = Math.floor((Math.random() * 10000) + 1000);
  return guestUsername.replace("%s",randomInt);
}

function getSalt(username,done) {
  var client = new pg.Client(process.env.PUBNUB_DB_URL);
  client.connect();
  var query = client.query("SELECT salt from users where username = $1", [username]);
  var salt = ""
  query.on('row', function(row) {
    salt = row.salt;
    done(salt);
  });
  query.on('end', function() {
    client.end();
  });
}

module.exports.run = function (worker) {
  console.log('   >> Worker PID:', process.pid);
  var app = require('express')();
  var httpServer = worker.httpServer;
  var scServer = worker.scServer;
  app.use(serveStatic(path.resolve(__dirname, 'public')));
  httpServer.on('request', app);

  scServer.on('connection', function (socket) {
    var authToken = socket.getAuthToken();
    //Blocks publish except for server.
    scServer.addMiddleware(scServer.MIDDLEWARE_PUBLISH_IN, function (req, next) {
      next(true);
    });

    socket.on('disconnect', function() {
      //deauth everytime user disconnects.
      socket.deauthenticate();
    })

    socket.on('auth', function(data,res) {
      //Validate user
      var username = generateGuestId();
      if (data.username.substr(0,3) == "reg") {

        data = data.username.split("_");
        var assumedUsername = data.slice(1,data.length-1).join("_");
        getSalt(assumedUsername,function(salt) {

          var hash = crypto.createHmac('sha1', 'chat').update(salt+assumedUsername).digest('hex')
          if (hash == data[data.length-1]) {
            username = assumedUsername;
          }
          socket.setAuthToken({username: username, color: generateRandomColor(), isRegistered: true});
          socket.emit('info', {msg: welcomeMsg.replace("%s",username)});
        });
      } else {
        socket.setAuthToken({username: username, color: generateRandomColor(), isRegistered: false});
        socket.emit('info', {msg: welcomeMsg.replace("%s",username)});
        socket.emit('info', {msg: registerMsg});
      }
    });

    socket.on('chat', function (data) {
      if (!authToken) {
        authToken = socket.getAuthToken();
      }
      if (authToken) {
        var msg = data.msg;
        var cmd = msg.split(" ")[0].toLowerCase();
        if (cmd in commands) {
          commands[cmd](socket,data);
        } else {
          var time = new Date();
          data.username = authToken.username;
          data.color = authToken.color;
          data.time = time.getTime();
          data.type = "message";
          data.isRegistered = authToken.isRegistered;
          scServer.global.publish(data.channel, data);
        }
      }
    });

    socket.on('subscribe', function (data) {
      if (!authToken) {
        authToken = socket.getAuthToken();
      }
      if (authToken){
        if (data in usersList) {
          usersList[data] = usersList[data].filter(function(value) { return value != authToken.username; });
          usersList[data].push(authToken.username);
        } else {
          usersList[data] = [authToken.username];
        }
        scServer.global.publish(data, {type: "info", msg: connectMsg.replace('%s',authToken.username)});
        printChannelUserList(socket,{channel:data});
      }
    });

    socket.on('unsubscribe', function (data) {
      if (!authToken) {
        authToken = socket.getAuthToken();
      }
      if (authToken){
        if (data in usersList) {
          usersList[data] = usersList[data].filter(function(value) { return value != authToken.username; });
        }
        scServer.global.publish(data, {type: "info", msg: disconnectMsg.replace('%s',authToken.username)});
      }
    });

  });

};
<|endoftext|>