<commit_before>import React from 'react';
import axios from 'axios';
import apiConfig from '../config/api.js';
import Firebase from 'firebase';

import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import ColorPalette from './ColorPalette';

import Paper from 'material-ui/Paper';
import RaisedButton from 'material-ui/RaisedButton';
import SelectField from 'material-ui/SelectField';
import MenuItem from 'material-ui/MenuItem';

// My component imports
import Header from './Header';
import ExploreFilters from './ExploreFilters';
import ExploreTable from './ExploreTable';
import ExploreSummaryStats from './ExploreSummaryStats';
import Loading from './Loading';
import Histogram from './Histogram';
import HeatmapChart from './HeatmapChart';

var apiRequest = axios.create({
  baseURL: apiConfig.baseURL
});

var Explore = React.createClass({
  getInitialState : function() {
    return {
      'fullData': [],
      'activeData': [],
      'activeSummaryData': [],
      'summaryData':[],
      'histinput':'avg_read_length_summary',
      'filter_params':JSON.stringify({'rules':[]}),
      'loaded':false,
      'processing':false,
      'firebase':{
        'uid':null,
        'name':null,
        'photo':null
      }
    }
  },

  componentWillMount : function() {
    var user = Firebase.auth().currentUser;
    if (user) {
      this.state.firebase.name = user.displayName;
      this.state.firebase.uid = user.uid;
      this.state.firebase.photo = user.photoURL;
      this.setState({"firebase": this.state.firebase});
    }
    var self = this;
    apiRequest.get("/datasets/summary")
    .then(function (response) {
      // store the summary data response
      self.setState({"summaryData": response.data.summary});
      self.setState({"activeSummaryData": response.data.summary});

      // if there aren't too many datasets, just get 'em all
      if (response.data.summary.totalDatasets < 1000) {
        apiRequest.get("/datasets")
        .then(function (response) {
          // store the full response and set loaded to true
          self.setState({"fullData": response.data.datasets,"activeData" : response.data.datasets,"loaded":true});
          self.state.activeData = self.state.fullData;
          self.setState({ });
        })
      } else {
        self.setState({"loaded":true});
      }
    });
  },

  updateActiveSummaryData : function() {
    var self = this;
    self.setState({"processing":true});
    apiRequest.post('/datasets/search/summary', {
      "filter_params":this.state.filter_params
    }).then(function (response) {
      self.setState({"activeSummaryData": response.data.summary,"processing":false});
    });
  },

  triggerGoogleLogin : function() {
    var successfulLogin = this.successfulLogin;
    var provider = new Firebase.auth.GoogleAuthProvider();
    var auth = Firebase.auth().signInWithPopup(provider).then(function(result) {
      var user = result.user;
      successfulLogin(user);
    }).catch(function(error) {
      console.log("couldn't log in for some reason");
      console.log(error);
    });
  },

  triggerLogout : function() {
    var accountComponent = this;
    var auth = Firebase.auth().signOut().then(function() {
      accountComponent.state.firebase.name = null;
      accountComponent.state.firebase.uid = null;
      accountComponent.state.firebase.photo = null;
      accountComponent.setState(accountComponent.state.firebase);
    }, function(error) {
      console.log("couldn't log out for some reason");
      console.log(error);
    });
  },

  successfulLogin : function(user) {
    var self = this;
    self.state.firebase.name = user.displayName;
    self.state.firebase.uid = user.uid;
    self.state.firebase.photo = user.photoURL;
    apiRequest.post('/user/create', {
      "firebase_id":self.state.firebase.uid,
      "admin":0
    }).then(function(response){
      self.setState({"firebase": self.state.firebase});
    });
  },

  updateFilterParams : function(filterStates) {
    filterStates = Object.values(filterStates).filter(function(ruleObject){
      if (ruleObject.value == "All") {
        return false;
      }
      if (("field" in ruleObject) && ("value" in ruleObject) && ("type" in ruleObject)) {
        return true;
      } else {
        return false;
      }
    });
    this.state.filter_params = JSON.stringify({"rules":filterStates});
    this.setState({"filter_params":JSON.stringify({"rules":filterStates})});
    this.updateActiveSummaryData();
  },

  submitDiscovery : function() {
    var self = this;
    apiRequest.post('/discovery/create', {
      "owner_id":this.state.firebase.uid,
      "filter_params":this.state.filter_params
    }).then(function (response) {
      self.props.history.push('/discovery/' + response.data.discovery.id);
    });
  },

  handleHistSelect : function(event,index,value) {
    this.setState({"histinput":value})
  },

  render : function() {
    if (!this.state.loaded) return <Loading/>;

    var mapRender = function(activeSummaryData,isProcessing) {
      if (!isProcessing) {
        if (activeSummaryData.empty) {
          return
Sorry, no matches!

        } else {
          return <HeatmapChart data={activeSummaryData.latlon_map}/>
        }
      } else {
        return

Processing...

      }
    };

    return (

Explore

          <MuiThemeProvider muiTheme={getMuiTheme(ColorPalette)}>

              <Paper className="explore-filter-card">

                    {this.state.firebase.uid ? "Hi, " + this.state.firebase.name + ". Thanks for using MetaSeek!" : "Create an account or log in to save a discovery to your account."}

                  <RaisedButton
                    className="profile-button"
                    onClick={this.state.firebase.uid ? this.submitDiscovery : this.triggerGoogleLogin}
                    primary={true}
                    label={this.state.firebase.uid ? "Save Discovery" : "Log In With Google"}
                  />
                  <RaisedButton
                    className="profile-button"
                    label="Log Out"
                    onClick={this.triggerLogout}
                    primary={true}
                    disabled={!(this.state.firebase.uid)}
                  />

                <ExploreFilters
                  className="explore-filters"
                  updateFilterParams={this.updateFilterParams}
                  summaryData={this.state.activeSummaryData}
                />
              </Paper>
              <Paper className="explore-right-map">

                  {mapRender(this.state.activeSummaryData,this.state.processing)}

              </Paper>
              <Paper className="explore-right-summary">

                  <ExploreSummaryStats summaryData={this.state.activeSummaryData}/>

              </Paper>
              <Paper className="explore-right-histogram">
                  <Histogram summaryData={this.state.activeSummaryData} histinput={this.state.histinput}/>
                  <SelectField value={this.state.histinput} onChange={this.handleHistSelect}>
                    {Object.keys(this.state.activeSummaryData).filter(function(value) {
                      if (value.indexOf('summary') !== -1) {
                        return true;
                      } else {
                        return false;
                      }
                    }).map(function(value, index) {
                        return (
                          <MenuItem key={index} value={value} primaryText={value} />
                        )
                    })}
                  </SelectField>
              </Paper>
              <Paper className="explore-table">
                <ExploreTable activeData={this.state.activeData}/>
              </Paper>

          </MuiThemeProvider>

    )
  }
});

export default Explore;
<commit_msg>debug must select null to 'all' not none<commit_after>import React from 'react';
import axios from 'axios';
import apiConfig from '../config/api.js';
import Firebase from 'firebase';

import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import ColorPalette from './ColorPalette';

import Paper from 'material-ui/Paper';
import RaisedButton from 'material-ui/RaisedButton';
import SelectField from 'material-ui/SelectField';
import MenuItem from 'material-ui/MenuItem';

// My component imports
import Header from './Header';
import ExploreFilters from './ExploreFilters';
import ExploreTable from './ExploreTable';
import ExploreSummaryStats from './ExploreSummaryStats';
import Loading from './Loading';
import Histogram from './Histogram';
import HeatmapChart from './HeatmapChart';

var apiRequest = axios.create({
  baseURL: apiConfig.baseURL
});

var Explore = React.createClass({
  getInitialState : function() {
    return {
      'fullData': [],
      'activeData': [],
      'activeSummaryData': [],
      'summaryData':[],
      'histinput':'avg_read_length_summary',
      'filter_params':JSON.stringify({'rules':[]}),
      'loaded':false,
      'processing':false,
      'firebase':{
        'uid':null,
        'name':null,
        'photo':null
      }
    }
  },

  componentWillMount : function() {
    var user = Firebase.auth().currentUser;
    if (user) {
      this.state.firebase.name = user.displayName;
      this.state.firebase.uid = user.uid;
      this.state.firebase.photo = user.photoURL;
      this.setState({"firebase": this.state.firebase});
    }
    var self = this;
    apiRequest.get("/datasets/summary")
    .then(function (response) {
      // store the summary data response
      self.setState({"summaryData": response.data.summary});
      self.setState({"activeSummaryData": response.data.summary});

      // if there aren't too many datasets, just get 'em all
      if (response.data.summary.totalDatasets < 1000) {
        apiRequest.get("/datasets")
        .then(function (response) {
          // store the full response and set loaded to true
          self.setState({"fullData": response.data.datasets,"activeData" : response.data.datasets,"loaded":true});
          self.state.activeData = self.state.fullData;
          self.setState({ });
        })
      } else {
        self.setState({"loaded":true});
      }
    });
  },

  updateActiveSummaryData : function() {
    var self = this;
    self.setState({"processing":true});
    apiRequest.post('/datasets/search/summary', {
      "filter_params":this.state.filter_params
    }).then(function (response) {
      self.setState({"activeSummaryData": response.data.summary,"processing":false});
    });
  },

  triggerGoogleLogin : function() {
    var successfulLogin = this.successfulLogin;
    var provider = new Firebase.auth.GoogleAuthProvider();
    var auth = Firebase.auth().signInWithPopup(provider).then(function(result) {
      var user = result.user;
      successfulLogin(user);
    }).catch(function(error) {
      console.log("couldn't log in for some reason");
      console.log(error);
    });
  },

  triggerLogout : function() {
    var accountComponent = this;
    var auth = Firebase.auth().signOut().then(function() {
      accountComponent.state.firebase.name = null;
      accountComponent.state.firebase.uid = null;
      accountComponent.state.firebase.photo = null;
      accountComponent.setState(accountComponent.state.firebase);
    }, function(error) {
      console.log("couldn't log out for some reason");
      console.log(error);
    });
  },

  successfulLogin : function(user) {
    var self = this;
    self.state.firebase.name = user.displayName;
    self.state.firebase.uid = user.uid;
    self.state.firebase.photo = user.photoURL;
    apiRequest.post('/user/create', {
      "firebase_id":self.state.firebase.uid,
      "admin":0
    }).then(function(response){
      self.setState({"firebase": self.state.firebase});
    });
  },

  updateFilterParams : function(filterStates) {
    filterStates = Object.values(filterStates).filter(function(ruleObject){
      if (ruleObject.value == "All" || ruleObject.value=='') {
        return false;
      }
      if (("field" in ruleObject) && ("value" in ruleObject) && ("type" in ruleObject)) {
        return true;
      } else {
        return false;
      }
    });
    this.state.filter_params = JSON.stringify({"rules":filterStates});
    this.setState({"filter_params":JSON.stringify({"rules":filterStates})});
    this.updateActiveSummaryData();
  },

  submitDiscovery : function() {
    var self = this;
    apiRequest.post('/discovery/create', {
      "owner_id":this.state.firebase.uid,
      "filter_params":this.state.filter_params
    }).then(function (response) {
      self.props.history.push('/discovery/' + response.data.discovery.id);
    });
  },

  handleHistSelect : function(event,index,value) {
    this.setState({"histinput":value})
  },

  render : function() {
    if (!this.state.loaded) return <Loading/>;

    var mapRender = function(activeSummaryData,isProcessing) {
      if (!isProcessing) {
        if (activeSummaryData.empty) {
          return
Sorry, no matches!

        } else {
          return <HeatmapChart data={activeSummaryData.latlon_map}/>
        }
      } else {
        return

Processing...

      }
    };

    return (

Explore

          <MuiThemeProvider muiTheme={getMuiTheme(ColorPalette)}>

              <Paper className="explore-filter-card">

                    {this.state.firebase.uid ? "Hi, " + this.state.firebase.name + ". Thanks for using MetaSeek!" : "Create an account or log in to save a discovery to your account."}

                  <RaisedButton
                    className="profile-button"
                    onClick={this.state.firebase.uid ? this.submitDiscovery : this.triggerGoogleLogin}
                    primary={true}
                    label={this.state.firebase.uid ? "Save Discovery" : "Log In With Google"}
                  />
                  <RaisedButton
                    className="profile-button"
                    label="Log Out"
                    onClick={this.triggerLogout}
                    primary={true}
                    disabled={!(this.state.firebase.uid)}
                  />

                <ExploreFilters
                  className="explore-filters"
                  updateFilterParams={this.updateFilterParams}
                  summaryData={this.state.activeSummaryData}
                />
              </Paper>
              <Paper className="explore-right-map">

                  {mapRender(this.state.activeSummaryData,this.state.processing)}

              </Paper>
              <Paper className="explore-right-summary">

                  <ExploreSummaryStats summaryData={this.state.activeSummaryData}/>

              </Paper>
              <Paper className="explore-right-histogram">
                  <Histogram summaryData={this.state.activeSummaryData} histinput={this.state.histinput}/>
                  <SelectField value={this.state.histinput} onChange={this.handleHistSelect}>
                    {Object.keys(this.state.activeSummaryData).filter(function(value) {
                      if (value.indexOf('summary') !== -1) {
                        return true;
                      } else {
                        return false;
                      }
                    }).map(function(value, index) {
                        return (
                          <MenuItem key={index} value={value} primaryText={value} />
                        )
                    })}
                  </SelectField>
              </Paper>
              <Paper className="explore-table">
                <ExploreTable activeData={this.state.activeData}/>
              </Paper>

          </MuiThemeProvider>

    )
  }
});

export default Explore;
<|endoftext|>


<commit_before>import React from 'react';
import Cell from './Cell';
import Amount from './Amount';
import ui from 'redux-ui';
import BudgetItemForm from './BudgetItemForm';
import {connect} from 'react-redux';
import asyncActionCreatorsFor from '../actions/asyncActionCreatorsFor';
import moment from 'moment';
import FontAwesome from 'react-fontawesome';
import {amountToCents} from '../utils/amount';
import {Link as RouterLink} from 'react-router';

@ui()
class CategoryRow extends React.Component {
  constructor(props) {
    super(props);
    this.onSubmit = this.onSubmit.bind(this);
    this.editBudgetItem = this.editBudgetItem.bind(this);
    this.clearBudgetItemForm = this.clearBudgetItemForm.bind(this);
  }

  static propTypes = {
    category: React.PropTypes.object.isRequired,
    activity: React.PropTypes.number,
    available: React.PropTypes.number,
    ui: React.PropTypes.object.isRequired,
    updateUI: React.PropTypes.func.isRequired,
    create: React.PropTypes.func.isRequired,
    update: React.PropTypes.func.isRequired,
    budgetItem: React.PropTypes.object,
    onNameClick: React.PropTypes.func
  };

  editBudgetItem() {
    if (!(this.props.budgetItem && this.props.budgetItem.busy)) {
      this.props.updateUI('editingCategoryId', this.props.category.id);
    }
  }

  clearBudgetItemForm() {
    this.props.updateUI('editingCategoryId', null);
  }

  onSubmit(data) {
    const m = moment([this.props.ui.year, this.props.ui.month - 1]);
    if (this.props.budgetItem) {
      this.props.update({
        id: this.props.budgetItem.id,
        month: m.format('YYYY-MM-DD'),
        category_id: this.props.category.id,
        amount: amountToCents(data.amount)
      });
    } else {
      this.props.create({
        month: m.format('YYYY-MM-DD'),
        category_id: this.props.category.id,
        amount: amountToCents(data.amount)
      });
    }
    this.props.updateUI('editingCategoryId', null);
  }

  render() {
    let budgetCell;
    if (this.props.ui.editingCategoryId == this.props.category.id) {
      budgetCell =
        <Cell className="right">
          <BudgetItemForm onBlur={this.clearBudgetItemForm} onSubmit={this.onSubmit} />
        </Cell>;
    } else {
      budgetCell =
        <Cell className="right" onClick={this.editBudgetItem}>
          {this.props.budgetItem && this.props.budgetItem.busy && <FontAwesome name="refresh" spin fixedWidth />}
          <Amount amount={this.props.budgetItem && this.props.budgetItem.amount} />
        </Cell>;
    }

    const m = moment([this.props.ui.year, this.props.ui.month - 1]);

    return (

        <Cell onClick={this.props.onNameClick}>{this.props.category.name}</Cell>
        {budgetCell}

          <RouterLink to={`/account/${m.format('YYYY-MM')}/${this.props.category.id}`}>
            <Amount amount={this.props.activity} />
          </RouterLink>

        <Amount amount={this.props.available} color />

    );
  }
}

export default connect(null, asyncActionCreatorsFor('budget_items'))(CategoryRow);
<commit_msg>Code cleaning<commit_after>import React from 'react';
import Cell from './Cell';
import Amount from './Amount';
import ui from 'redux-ui';
import BudgetItemForm from './BudgetItemForm';
import {connect} from 'react-redux';
import asyncActionCreatorsFor from '../actions/asyncActionCreatorsFor';
import moment from 'moment';
import FontAwesome from 'react-fontawesome';
import {amountToCents} from '../utils/amount';
import {Link as RouterLink} from 'react-router';

@ui()
class CategoryRow extends React.Component {
  constructor(props) {
    super(props);
    this.onSubmit = this.onSubmit.bind(this);
    this.editBudgetItem = this.editBudgetItem.bind(this);
    this.clearBudgetItemForm = this.clearBudgetItemForm.bind(this);
  }

  static propTypes = {
    category: React.PropTypes.object.isRequired,
    activity: React.PropTypes.number,
    available: React.PropTypes.number,
    ui: React.PropTypes.object.isRequired,
    updateUI: React.PropTypes.func.isRequired,
    create: React.PropTypes.func.isRequired,
    update: React.PropTypes.func.isRequired,
    budgetItem: React.PropTypes.object,
    onNameClick: React.PropTypes.func
  };

  editBudgetItem() {
    if (!(this.props.budgetItem && this.props.budgetItem.busy)) {
      this.props.updateUI('editingCategoryId', this.props.category.id);
    }
  }

  clearBudgetItemForm() {
    this.props.updateUI('editingCategoryId', null);
  }

  getSelectedMonthMoment() {
    return moment([this.props.ui.year, this.props.ui.month - 1]);
  }

  onSubmit(data) {
    const m = this.getSelectedMonthMoment().format('YYYY-MM-DD');
    if (this.props.budgetItem) {
      this.props.update({
        id: this.props.budgetItem.id,
        month: m,
        category_id: this.props.category.id,
        amount: amountToCents(data.amount)
      });
    } else {
      this.props.create({
        month: m,
        category_id: this.props.category.id,
        amount: amountToCents(data.amount)
      });
    }
    this.props.updateUI('editingCategoryId', null);
  }

  render() {
    let budgetCell;
    if (this.props.ui.editingCategoryId == this.props.category.id) {
      budgetCell =
        <Cell className="right">
          <BudgetItemForm onBlur={this.clearBudgetItemForm} onSubmit={this.onSubmit} />
        </Cell>;
    } else {
      budgetCell =
        <Cell className="right" onClick={this.editBudgetItem}>
          {this.props.budgetItem && this.props.budgetItem.busy && <FontAwesome name="refresh" spin fixedWidth />}
          <Amount amount={this.props.budgetItem && this.props.budgetItem.amount} />
        </Cell>;
    }

    return (

        <Cell onClick={this.props.onNameClick}>{this.props.category.name}</Cell>
        {budgetCell}

          <RouterLink to={`/account/${this.getSelectedMonthMoment().format('YYYY-MM')}/${this.props.category.id}`}>
            <Amount amount={this.props.activity} />
          </RouterLink>

        <Amount amount={this.props.available} color />

    );
  }
}

export default connect(null, asyncActionCreatorsFor('budget_items'))(CategoryRow);
<|endoftext|>


<commit_before>(function() {
  'use strict';

  exports.farmer = function(req, res, next) {
    var query = req.body;
    var error = '';

    if (query.first_name === undefined || query.last_name === undefined || query.email === undefined ||
      query.password === undefined || query.company_name === undefined || query.address === undefined ||
      query.city === undefined || query.state === undefined || query.zip === undefined || query.phone === undefined ||
      query.farm_size === undefined ) {
        error += 'first_name: ' + query.first_name + '\n';
        error += 'last_name: ' + query.last_name + '\n';
        error += 'email: ' + query.email + '\n';
        error += 'password: ' + query.password + '\n';
        error += 'company_name: ' + query.company_name + '\n';
        error += 'address: ' + query.address + '\n';
        error += 'city: ' + query.city + '\n';
        error += 'state: ' + query.state + '\n';
        error += 'zip: ' + query.zip + '\n';
        error += 'phone: ' + query.phone + '\n';
        error += 'farm_size: ' + query.farm_size + '\n';

        return res.json({message : 'Please check if there are undefined entry your data \n', data: error});
    } else {
      var options = {
        name    : 'Farmer',
        res     : res,
        message : 'Saving data in Farmer',
        details : {
          last_name   : query.last_name,
          email       : query.email,
          password    : query.password,
          company_name: query.company_name,
          address     : query.address,
          city        : query.city,
          state       : query.state,
          zip         : query.zip,
          phone       : query.phone,
          description : query.description,
          farm_size   : query.farm_size,
        }
      };

      io.mongoDB(io.config.dbName)
        .then(io.save_(options));
    }
  };

  exports.buyer = function(req, res, next) {
    var query = req.body;
    var error = '';

    if (query.first_name === undefined || query.last_name === undefined || query.email === undefined ||
      query.password === undefined || query.company_name === undefined || query.address === undefined ||
      query.city === undefined || query.state === undefined || query.zip === undefined || query.phone === undefined ||
      query.monthly_expense === undefined || query.business_type === undefined) {
        error += 'first_name: ' + query.first_name + '\n';
        error += 'last_name: ' + query.last_name + '\n';
        error += 'email: ' + query.email + '\n';
        error += 'password: ' + query.password + '\n';
        error += 'company_name: ' + query.company_name + '\n';
        error += 'address: ' + query.address + '\n';
        error += 'city: ' + query.city + '\n';
        error += 'state: ' + query.state + '\n';
        error += 'zip: ' + query.zip + '\n';
        error += 'phone: ' + query.phone + '\n';
        error += 'monthly_expense: ' + query.monthly_expense + '\n';
        error += 'business_type: ' + query.business_type + '\n';

        return res.json({message : 'Please check if there are undefined entry your data \n', data: error});
    } else {
      var options = {
        name    : 'Buyer',
        res     : res,
        message : 'Saving data in Buyer',
        details : {
          first_name      : query.first_name,
          last_name       : query.last_name,
          email           : query.email,
          password        : query.password,
          company_name    : query.company_name,
          address         : query.address,
          city            : query.city,
          state           : query.state,
          zip             : query.zip,
          phone           : query.phone,
          description     : query.description,
          monthly_expense : query.monthly_expense,
          business_type   : query.business_type
        }
      };

      console.log(io.save_);
      io.mongoDB(io.config.dbName)
        .then(io.save._(options));
    }
  };
}());
<commit_msg>adding service in farmer<commit_after>(function() {
  'use strict';

  exports.farmer = function(req, res, next) {
    var query = req.body;
    var error = '';

    if (query.first_name === undefined || query.last_name === undefined || query.email === undefined ||
      query.password === undefined || query.company_name === undefined || query.address === undefined ||
      query.city === undefined || query.state === undefined || query.zip === undefined || query.phone === undefined ||
      query.farm_size === undefined ) {
        error += 'first_name: ' + query.first_name + '\n';
        error += 'last_name: ' + query.last_name + '\n';
        error += 'email: ' + query.email + '\n';
        error += 'password: ' + query.password + '\n';
        error += 'company_name: ' + query.company_name + '\n';
        error += 'address: ' + query.address + '\n';
        error += 'city: ' + query.city + '\n';
        error += 'state: ' + query.state + '\n';
        error += 'zip: ' + query.zip + '\n';
        error += 'phone: ' + query.phone + '\n';
        error += 'farm_size: ' + query.farm_size + '\n';

        return res.json({message : 'Please check if there are undefined entry your data \n', data: error});
    } else {
      var options = {
        name    : 'Farmer',
        res     : res,
        message : 'Saving data in Farmer',
        details : {
          last_name   : query.last_name,
          email       : query.email,
          password    : query.password,
          company_name: query.company_name,
          address     : query.address,
          city        : query.city,
          state       : query.state,
          zip         : query.zip,
          phone       : query.phone,
          description : query.description,
          farm_size   : query.farm_size,
        }
      };

      io.mongoDB(io.config.dbName)
        .then(io.save._(options));
    }
  };

  exports.buyer = function(req, res, next) {
    var query = req.body;
    var error = '';

    if (query.first_name === undefined || query.last_name === undefined || query.email === undefined ||
      query.password === undefined || query.company_name === undefined || query.address === undefined ||
      query.city === undefined || query.state === undefined || query.zip === undefined || query.phone === undefined ||
      query.monthly_expense === undefined || query.business_type === undefined) {
        error += 'first_name: ' + query.first_name + '\n';
        error += 'last_name: ' + query.last_name + '\n';
        error += 'email: ' + query.email + '\n';
        error += 'password: ' + query.password + '\n';
        error += 'company_name: ' + query.company_name + '\n';
        error += 'address: ' + query.address + '\n';
        error += 'city: ' + query.city + '\n';
        error += 'state: ' + query.state + '\n';
        error += 'zip: ' + query.zip + '\n';
        error += 'phone: ' + query.phone + '\n';
        error += 'monthly_expense: ' + query.monthly_expense + '\n';
        error += 'business_type: ' + query.business_type + '\n';

        return res.json({message : 'Please check if there are undefined entry your data \n', data: error});
    } else {
      var options = {
        name    : 'Buyer',
        res     : res,
        message : 'Saving data in Buyer',
        details : {
          first_name      : query.first_name,
          last_name       : query.last_name,
          email           : query.email,
          password        : query.password,
          company_name    : query.company_name,
          address         : query.address,
          city            : query.city,
          state           : query.state,
          zip             : query.zip,
          phone           : query.phone,
          description     : query.description,
          monthly_expense : query.monthly_expense,
          business_type   : query.business_type
        }
      };

      console.log(io.save_);
      io.mongoDB(io.config.dbName)
        .then(io.save._(options));
    }
  };
}());
<|endoftext|>


<commit_before>// Create new dialog
//
'use strict';

const _ = require('lodash');

let options;
let bloodhound;

function updateOptions() {
  N.MDEdit.parseOptions(_.assign({}, options.parse_options, {
    link_to_title:   options.user_settings.no_mlinks         ? false : options.parse_options.link_to_title,
    link_to_snippet: options.user_settings.no_mlinks         ? false : options.parse_options.link_to_snippet,
    quote_collapse:  options.user_settings.no_quote_collapse ? false : options.parse_options.quote_collapse,
    emoji:           options.user_settings.no_emojis         ? false : options.parse_options.emoji
  }));
}

// Load dependencies
//
N.wire.before(module.apiPath + ':begin', function load_deps() {
  return N.loader.loadAssets([ 'mdedit', 'vendor.typeahead' ]);
});

// Fetch options
//
N.wire.before(module.apiPath + ':begin', function fetch_options() {
  return N.io.rpc('users.dialog.options').then(opt => {
    options = {
      parse_options: opt.parse_options,
      user_settings: {
        no_mlinks: false,
        no_emojis: false,
        no_quote_collapse: false
      }
    };
  });
});

// Show editor and add handlers for editor events
//
//  - params (Object) - specify recipient, text, etc. (optional)
//    - nick (String) - recipient nick
//    - hid  (Number) - recipient hid
//    - ref  (String) - used as a part of draft key (optional)
//    - text (String) - default content of the message box (optional)
//    - meta (Object) - additional arguments passed into RPC method (optional)
//
N.wire.on(module.apiPath + ':begin', function create_dialog(params) {
  const Bloodhound = require('corejs-typeahead/dist/bloodhound.js');

  // build draft key tail
  let key_tail = '';
  if (params) key_tail += params.ref ? params.ref : (params.nick || '');

  let $editor = N.MDEdit.show({
    draftKey: `dialog_create_${N.runtime.user_hid}_${key_tail}`,
    draftCustomFields: {
      // Add `:last` because typeahead create additional field copy
      '.dialogs-create__user-nick-input:last': 'input'
    },
    text: params ? params.text || '' : ''
  });

  let $inputs = $(N.runtime.render(module.apiPath + '.inputs', {
    to: params ? params.nick : ''
  }));

  let $to = $inputs.find('.dialogs-create__user-nick-input');

  updateOptions();

  $editor
    .on('show.nd.mdedit', () => {
      $editor.addClass('dialogs-create-editor');

      if (params.nick) {
        // If user is specified - show dialog without nick field
        //
        // - button in usercard
        // - button on profile page
        //
        $editor.find('.mdedit-header__caption').html(t('title_with_nick', {
          nick: params.nick,
          url: N.router.linkTo('users.member', { user_hid: params.hid })
        }));

      } else {
        // If to user is not specified - show dialog with nick field and modifier
        //
        // - button on dialogs root page
        //
        $editor.find('.mdedit-header__caption').html(t('title'));
        $editor.addClass('dialogs-create-editor__m-with-nick');
      }

      $editor.find('.mdedit-header').append($inputs);
      $editor.find('.mdedit-footer').append(N.runtime.render(module.apiPath + '.options_btn'));

      // If bloodhound not initialized - init
      //
      if (!bloodhound) {
        bloodhound = new Bloodhound({
          remote: {
            url: 'unused', // bloodhound throws if it's not defined
            prepare(nick) { return nick; },
            // Reroute request to rpc
            transport(req, onSuccess, onError) {
              N.io.rpc('common.user_lookup', { nick: req.url })
                .then(onSuccess)
                .catch(onError);
            }
          },
          datumTokenizer(d) {
            return Bloodhound.tokenizers.whitespace(d.nick);
          },
          queryTokenizer: Bloodhound.tokenizers.whitespace
        });

        bloodhound.initialize();
      }

      // Bind typeahead to nick field
      //
      $to.typeahead({ highlight: true }, {
        source: bloodhound.ttAdapter(),
        display: 'nick',
        templates: {
          suggestion(user) {
            return '
' + _.escape(user.name) + '
';
          }
        }
      });
    })
    .on('submit.nd.mdedit', () => {
      $editor.find('.mdedit-btn__submit').addClass('disabled');

      let errors = false;

      if (!$.trim($to.val())) {
        $to.addClass('is-invalid');
        errors = true;
      } else {
        $to.removeClass('is-invalid');
      }

      if (errors) {
        $editor.find('.mdedit-btn__submit').removeClass('disabled');
        return false;
      }

      let dlg_create_params = {
        to:                       $to.val(),
        txt:                      N.MDEdit.text(),
        meta:                     params && params.meta,
        option_no_mlinks:         options.user_settings.no_mlinks,
        option_no_emojis:         options.user_settings.no_emojis,
        option_no_quote_collapse: options.user_settings.no_quote_collapse
      };

      N.io.rpc('users.dialog.create', dlg_create_params)
        .then(res => {
          N.MDEdit.hide({ removeDraft: true });
          N.wire.emit('navigate.to', {
            apiPath: 'users.dialog',
            params: {
              dialog_id: res.dialog_id,
              message_id: res.message_id
            }
          });
        })
        .catch(err => {
          $editor.find('.mdedit-btn__submit').removeClass('disabled');

          if (err.type === 'BAD_NICK') {
            $to.addClass('is-invalid');
          }

          return N.wire.emit('error', err);
        });

      return false;
    });
});

// Open options dialog
//
N.wire.on(module.apiPath + ':options', function show_options_dlg() {
  return N.wire.emit('common.blocks.editor_options_dlg', options.user_settings).then(updateOptions);
});
<commit_msg>Fix error when starting a dialog from dialogs page<commit_after>// Create new dialog
//
'use strict';

const _ = require('lodash');

let options;
let bloodhound;

function updateOptions() {
  N.MDEdit.parseOptions(_.assign({}, options.parse_options, {
    link_to_title:   options.user_settings.no_mlinks         ? false : options.parse_options.link_to_title,
    link_to_snippet: options.user_settings.no_mlinks         ? false : options.parse_options.link_to_snippet,
    quote_collapse:  options.user_settings.no_quote_collapse ? false : options.parse_options.quote_collapse,
    emoji:           options.user_settings.no_emojis         ? false : options.parse_options.emoji
  }));
}

// Load dependencies
//
N.wire.before(module.apiPath + ':begin', function load_deps() {
  return N.loader.loadAssets([ 'mdedit', 'vendor.typeahead' ]);
});

// Fetch options
//
N.wire.before(module.apiPath + ':begin', function fetch_options() {
  return N.io.rpc('users.dialog.options').then(opt => {
    options = {
      parse_options: opt.parse_options,
      user_settings: {
        no_mlinks: false,
        no_emojis: false,
        no_quote_collapse: false
      }
    };
  });
});

// Show editor and add handlers for editor events
//
//  - params (Object) - specify recipient, text, etc. (optional)
//    - nick (String) - recipient nick
//    - hid  (Number) - recipient hid
//    - ref  (String) - used as a part of draft key (optional)
//    - text (String) - default content of the message box (optional)
//    - meta (Object) - additional arguments passed into RPC method (optional)
//
N.wire.on(module.apiPath + ':begin', function create_dialog(params) {
  params = params || {};

  const Bloodhound = require('corejs-typeahead/dist/bloodhound.js');

  // build draft key tail
  let key_tail = params.ref ? params.ref : (params.nick || '');

  let $editor = N.MDEdit.show({
    draftKey: `dialog_create_${N.runtime.user_hid}_${key_tail}`,
    draftCustomFields: {
      // Add `:last` because typeahead create additional field copy
      '.dialogs-create__user-nick-input:last': 'input'
    },
    text: params.text || ''
  });

  let $inputs = $(N.runtime.render(module.apiPath + '.inputs', {
    to: params.nick || ''
  }));

  let $to = $inputs.find('.dialogs-create__user-nick-input');

  updateOptions();

  $editor
    .on('show.nd.mdedit', () => {
      $editor.addClass('dialogs-create-editor');

      if (params.nick) {
        // If user is specified - show dialog without nick field
        //
        // - button in usercard
        // - button on profile page
        //
        $editor.find('.mdedit-header__caption').html(t('title_with_nick', {
          nick: params.nick,
          url: N.router.linkTo('users.member', { user_hid: params.hid })
        }));

      } else {
        // If to user is not specified - show dialog with nick field and modifier
        //
        // - button on dialogs root page
        //
        $editor.find('.mdedit-header__caption').html(t('title'));
        $editor.addClass('dialogs-create-editor__m-with-nick');
      }

      $editor.find('.mdedit-header').append($inputs);
      $editor.find('.mdedit-footer').append(N.runtime.render(module.apiPath + '.options_btn'));

      // If bloodhound not initialized - init
      //
      if (!bloodhound) {
        bloodhound = new Bloodhound({
          remote: {
            url: 'unused', // bloodhound throws if it's not defined
            prepare(nick) { return nick; },
            // Reroute request to rpc
            transport(req, onSuccess, onError) {
              N.io.rpc('common.user_lookup', { nick: req.url })
                .then(onSuccess)
                .catch(onError);
            }
          },
          datumTokenizer(d) {
            return Bloodhound.tokenizers.whitespace(d.nick);
          },
          queryTokenizer: Bloodhound.tokenizers.whitespace
        });

        bloodhound.initialize();
      }

      // Bind typeahead to nick field
      //
      $to.typeahead({ highlight: true }, {
        source: bloodhound.ttAdapter(),
        display: 'nick',
        templates: {
          suggestion(user) {
            return '
' + _.escape(user.name) + '
';
          }
        }
      });
    })
    .on('submit.nd.mdedit', () => {
      $editor.find('.mdedit-btn__submit').addClass('disabled');

      let errors = false;

      if (!$.trim($to.val())) {
        $to.addClass('is-invalid');
        errors = true;
      } else {
        $to.removeClass('is-invalid');
      }

      if (errors) {
        $editor.find('.mdedit-btn__submit').removeClass('disabled');
        return false;
      }

      let dlg_create_params = {
        to:                       $to.val(),
        txt:                      N.MDEdit.text(),
        meta:                     params.meta,
        option_no_mlinks:         options.user_settings.no_mlinks,
        option_no_emojis:         options.user_settings.no_emojis,
        option_no_quote_collapse: options.user_settings.no_quote_collapse
      };

      N.io.rpc('users.dialog.create', dlg_create_params)
        .then(res => {
          N.MDEdit.hide({ removeDraft: true });
          N.wire.emit('navigate.to', {
            apiPath: 'users.dialog',
            params: {
              dialog_id: res.dialog_id,
              message_id: res.message_id
            }
          });
        })
        .catch(err => {
          $editor.find('.mdedit-btn__submit').removeClass('disabled');

          if (err.type === 'BAD_NICK') {
            $to.addClass('is-invalid');
          }

          return N.wire.emit('error', err);
        });

      return false;
    });
});

// Open options dialog
//
N.wire.on(module.apiPath + ':options', function show_options_dlg() {
  return N.wire.emit('common.blocks.editor_options_dlg', options.user_settings).then(updateOptions);
});
<|endoftext|>


<commit_before>girder.models.GroupModel = girder.AccessControlledModel.extend({
    resourceName: 'group',

    /**
     * Send an invitation to this group to the user identified by userId.
     * @param userId The ID of the user to invite.
     * @param accessType The access level to invite them as.
     * @param request Set to true if this is accepting a user's request to join.
     */
    sendInvitation: function (userId, accessType, request) {
        girder.restRequest({
            path: this.resourceName + '/' + this.get('_id') + '/invitation',
            data: {
                userId: userId,
                level: accessType
            },
            type: 'POST',
            error: null
        }).done(_.bind(function (resp) {
            this.set(resp);

            if (!request && userId === girder.currentUser.get('_id')) {
                girder.currentUser.addInvitation(this.get('_id'), accessType);
            }
            this.trigger('g:invited');
        }, this)).error(_.bind(function (err) {
            this.trigger('g:error', err);
        }, this));
    },

    /**
     * Accept an invitation to join a group.
     */
    joinGroup: function () {
        girder.restRequest({
            path: this.resourceName + '/' + this.get('_id') + '/member',
            type: 'POST'
        }).done(_.bind(function (resp) {
            girder.currentUser.addToGroup(this.get('_id'));
            girder.currentUser.removeInvitation(this.get('_id'));

            this.set(resp);

            this.trigger('g:joined');
        }, this)).error(_.bind(function (err) {
            this.trigger('g:error', err);
        }, this));
    },

    requestInvitation: function () {
        girder.restRequest({
            path: this.resourceName + '/' + this.get('_id') + '/member',
            type: 'POST'
        }).done(_.bind(function (resp) {
            this.set(resp);

            this.trigger('g:inviteRequested');
        }, this)).error(_.bind(function (err) {
            this.trigger('g:error', err);
        }, this));
    },

    /**
     * Promote a user to moderator or administrator
     * @param user The user model of the user being promoted
     * @param level The AccessLevel (WRITE or ADMIN) to promote to
     */
    promoteUser: function (user, level) {
        var role;
        if (level === girder.AccessType.WRITE) {
            role = 'moderator';
        }
        else if (level === girder.AccessType.ADMIN) {
            role = 'admin';
        }
        girder.restRequest({
            path: this.resourceName + '/' + this.get('_id') + '/' + role,
            data: {
                userId: user.get('_id')
            },
            type: 'POST'
        }).done(_.bind(function (resp) {
            this.set(resp);

            this.trigger('g:promoted');
        }, this)).error(_.bind(function (err) {
            this.trigger('g:error', err);
        }, this));
    },

    /**
     * Demote a user to ordinary member status. Requires admin privileges
     * @param userId The id of the user to demote.
     * @param level The current access level of the user.
     */
    demoteUser: function (userId, level) {
        var role;
        if (level === girder.AccessType.WRITE) {
            role = 'moderator';
        }
        else if (level === girder.AccessType.ADMIN) {
            role = 'admin';
        }
        girder.restRequest({
            path: this.resourceName + '/' + this.get('_id') + '/' + role +
                '?userId=' + userId,
            type: 'DELETE'
        }).done(_.bind(function (resp) {
            this.set(resp);

            this.trigger('g:demoted');
        }, this)).error(_.bind(function (err) {
            this.trigger('g:error', err);
        }, this));
    },

    /**
     * Remove a member of a group, or if the user is not already a member,
     * this will simply delete any outstanding membership request or
     * invitation for this user.
     * @param userId The ID of the user to remove.
     */
    removeMember: function (userId) {
        girder.restRequest({
            path: this.resourceName + '/' + this.get('_id') +
                  '/member?userId=' + userId,
            type: 'DELETE'
        }).done(_.bind(function (resp) {
            if (userId === girder.currentUser.get('_id')) {
                girder.currentUser.removeFromGroup(this.get('_id'));
            }

            this.set(resp);

            this.trigger('g:removed');
        }, this)).error(_.bind(function (err) {
            this.trigger('g:error', err);
        }, this));
    }
});
<commit_msg>Improve javascript code comments for group model<commit_after>girder.models.GroupModel = girder.AccessControlledModel.extend({
    resourceName: 'group',

    /**
     * Send an invitation to this group to the user identified by userId.
     * Requires moderator (write) access on the group.
     * @param userId The ID of the user to invite.
     * @param accessType The access level to invite them as.
     * @param request Set to true if this is accepting a user's request to join.
     */
    sendInvitation: function (userId, accessType, request) {
        girder.restRequest({
            path: this.resourceName + '/' + this.get('_id') + '/invitation',
            data: {
                userId: userId,
                level: accessType
            },
            type: 'POST',
            error: null
        }).done(_.bind(function (resp) {
            this.set(resp);

            if (!request && userId === girder.currentUser.get('_id')) {
                girder.currentUser.addInvitation(this.get('_id'), accessType);
            }
            this.trigger('g:invited');
        }, this)).error(_.bind(function (err) {
            this.trigger('g:error', err);
        }, this));
    },

    /**
     * Accept an invitation to join a group. Only call this if the user has
     * already been invited to the group.
     */
    joinGroup: function () {
        girder.restRequest({
            path: this.resourceName + '/' + this.get('_id') + '/member',
            type: 'POST'
        }).done(_.bind(function (resp) {
            girder.currentUser.addToGroup(this.get('_id'));
            girder.currentUser.removeInvitation(this.get('_id'));

            this.set(resp);

            this.trigger('g:joined');
        }, this)).error(_.bind(function (err) {
            this.trigger('g:error', err);
        }, this));
    },

    /**
     * This will create an invitation request on this group for the current
     * user. Requires read access on the group. If the user already has an
     * outstanding invitation to this group, call joinGroup instead.
     */
    requestInvitation: function () {
        girder.restRequest({
            path: this.resourceName + '/' + this.get('_id') + '/member',
            type: 'POST'
        }).done(_.bind(function (resp) {
            this.set(resp);

            this.trigger('g:inviteRequested');
        }, this)).error(_.bind(function (err) {
            this.trigger('g:error', err);
        }, this));
    },

    /**
     * Promote a user to moderator or administrator. Requires admin access
     * on the group.
     * @param user The user model of the user being promoted
     * @param level The AccessLevel (WRITE or ADMIN) to promote to
     */
    promoteUser: function (user, level) {
        var role;
        if (level === girder.AccessType.WRITE) {
            role = 'moderator';
        }
        else if (level === girder.AccessType.ADMIN) {
            role = 'admin';
        }
        girder.restRequest({
            path: this.resourceName + '/' + this.get('_id') + '/' + role,
            data: {
                userId: user.get('_id')
            },
            type: 'POST'
        }).done(_.bind(function (resp) {
            this.set(resp);

            this.trigger('g:promoted');
        }, this)).error(_.bind(function (err) {
            this.trigger('g:error', err);
        }, this));
    },

    /**
     * Demote a user to ordinary member status. Requires admin access on the
     * group.
     * @param userId The id of the user to demote.
     * @param level The current access level of the user.
     */
    demoteUser: function (userId, level) {
        var role;
        if (level === girder.AccessType.WRITE) {
            role = 'moderator';
        }
        else if (level === girder.AccessType.ADMIN) {
            role = 'admin';
        }
        girder.restRequest({
            path: this.resourceName + '/' + this.get('_id') + '/' + role +
                '?userId=' + userId,
            type: 'DELETE'
        }).done(_.bind(function (resp) {
            this.set(resp);

            this.trigger('g:demoted');
        }, this)).error(_.bind(function (err) {
            this.trigger('g:error', err);
        }, this));
    },

    /**
     * Remove a member of a group, or if the user is not already a member,
     * this will simply delete any outstanding membership request or
     * invitation for this user.
     * @param userId The ID of the user to remove.
     */
    removeMember: function (userId) {
        girder.restRequest({
            path: this.resourceName + '/' + this.get('_id') +
                  '/member?userId=' + userId,
            type: 'DELETE'
        }).done(_.bind(function (resp) {
            if (userId === girder.currentUser.get('_id')) {
                girder.currentUser.removeFromGroup(this.get('_id'));
            }

            this.set(resp);

            this.trigger('g:removed');
        }, this)).error(_.bind(function (err) {
            this.trigger('g:error', err);
        }, this));
    }
});
<|endoftext|>


<commit_before>var RefreshWeather = function (options) {
  options = options || {};
  options.update_interval = options.update_interval || 1000 * 60 * 120;
  var update_interval;

  function resetWeatherInfo() {
    $(".weather .weather-box span").html("");
    $(".weather .data-field").html("");
    $(".weather .weather-box").removeClass("new-day"); // Remove "day changed" separator line
    $(".weather-all").children().remove();
  }

  function processData(data) {
    resetWeatherInfo();
    if (data.sun) {
      var sunrise = moment(data.sun.sunrise);
      var sunset = moment(data.sun.sunset);
      $(".sun-info").html(" " + sunrise.format("HH:mm") + " (" + sunrise.fromNow() + ")  " + sunset.format("HH:mm") + " (" + sunset.fromNow() + ")");
    }
    var items = $(".weather"),
        current_index = 1,
        first_date = false,
        new_day = false;
    items.find(".temperature-now").html(data.current.feels_like);
    items.find(".wind-now").html(data.current.wind_speed_readable);
    $.each(data.next, function () {
      var this_item = items.find(".weather-" + current_index);
      if (first_date === false) {
        first_date = this.item.date;
      } else if (new_day === false) {
        if (first_date !== this.item.date) {
          this_item.addClass("new-day");
          new_day = true;
        }
      }
      this_item.find(".timestamp").html(this.name);
      this_item.find(".temperature").html(this.item.feels_like);
      this_item.find(".symbol").html("");
      this_item.find(".temperature-unit").html("°C");
      current_index += 1;
    });
    var now = moment(),
        current_index = 13,
        current_row,
        highlight_set = false,
        last_header,
        new_item = "

°C
: m/s
";
    $.each(data.hours, function () {
      if (this.hour % 2 != 0) {
        return true; // continue
      }
      if (current_index > 11) {
        current_index = 0;
        $(".weather-all").append("

");
        current_row = $(".weather-all .row").last();
        last_header = $(".weather-all h2").last();
        last_header.html(this.weekday_fi+" "+this.date);
      }
      current_row.append(new_item);
      var current_item = current_row.find(".col-md-1").last();

      current_item.find(".timestamp").html(this.hour+":00");
      current_item.find(".temperature").html(this.feels_like);
      current_item.find(".symbol").html("");
      current_item.find(".temperature-unit").html("°C");
      current_item.find(".wind-speed").html(Math.round(this.wind_speed / 3.6));
      current_item.find(".wind-direction").html(this.wind_direction);
      if (!highlight_set && this.date == now.format("YYYY-MM-DD") && (now.hour() == this.hour || now.hour() -1 == this.hour)) {
        current_item.addClass("weather-today");
        highlight_set = true;
      }
      current_index += 1;
    });
  }

  function update() {
    $.get("/homecontroller/weather/get_json", function (data) {
      processData(data);
    });
  }

  function onReceiveItemWS(data) {
    processData(data);
  }

  function startInterval() {
    stopInterval();
    update();
    update_interval = setInterval(update, options.update_interval);
    ws_generic.register("weather", onReceiveItemWS);
    ge_refresh.register("weather", update);
  }

  function stopInterval() {
    if (update_interval) {
      update_interval = clearInterval(update_interval);
    }
    ws_generic.deRegister("weather");
    ge_refresh.deRegister("weather");
  }

  this.startInterval = startInterval;
  this.stopInterval = stopInterval;

};

var refresh_weather;
$(document).ready(function () {
  refresh_weather = new RefreshWeather();
  refresh_weather.startInterval();
  $(".open-weather-modal").on("click", function() {
    switchVisibleContent("#weather-modal");
  });
  $("#weather-modal .close").on("click", function() {
    switchVisibleContent("#main-content");
  });

});
<commit_msg>Better check weather data validity<commit_after>var RefreshWeather = function (options) {
  options = options || {};
  options.update_interval = options.update_interval || 1000 * 60 * 120;
  var update_interval;

  function resetWeatherInfo() {
    $(".weather .weather-box span").html("");
    $(".weather .data-field").html("");
    $(".weather .weather-box").removeClass("new-day"); // Remove "day changed" separator line
    $(".weather-all").children().remove();
  }

  function processData(data) {
    resetWeatherInfo();
    if (data.sun) {
      var sunrise = moment(data.sun.sunrise);
      var sunset = moment(data.sun.sunset);
      $(".sun-info").html(" " + sunrise.format("HH:mm") + " (" + sunrise.fromNow() + ")  " + sunset.format("HH:mm") + " (" + sunset.fromNow() + ")");
    }
    var items = $(".weather"),
        current_index = 1,
        first_date = false,
        new_day = false;
    if (data && data.current && data.current.feels_like) {
      items.find(".temperature-now").html(data.current.feels_like);
      items.find(".wind-now").html(data.current.wind_speed_readable);
    }
    $.each(data.next, function () {
      var this_item = items.find(".weather-" + current_index);
      if (first_date === false) {
        first_date = this.item.date;
      } else if (new_day === false) {
        if (first_date !== this.item.date) {
          this_item.addClass("new-day");
          new_day = true;
        }
      }
      this_item.find(".timestamp").html(this.name);
      this_item.find(".temperature").html(this.item.feels_like);
      this_item.find(".symbol").html("");
      this_item.find(".temperature-unit").html("°C");
      current_index += 1;
    });
    var now = moment(),
        current_index = 13,
        current_row,
        highlight_set = false,
        last_header,
        new_item = "

°C
: m/s
";
    $.each(data.hours, function () {
      if (this.hour % 2 != 0) {
        return true; // continue
      }
      if (current_index > 11) {
        current_index = 0;
        $(".weather-all").append("

");
        current_row = $(".weather-all .row").last();
        last_header = $(".weather-all h2").last();
        last_header.html(this.weekday_fi+" "+this.date);
      }
      current_row.append(new_item);
      var current_item = current_row.find(".col-md-1").last();

      current_item.find(".timestamp").html(this.hour+":00");
      current_item.find(".temperature").html(this.feels_like);
      current_item.find(".symbol").html("");
      current_item.find(".temperature-unit").html("°C");
      current_item.find(".wind-speed").html(Math.round(this.wind_speed / 3.6));
      current_item.find(".wind-direction").html(this.wind_direction);
      if (!highlight_set && this.date == now.format("YYYY-MM-DD") && (now.hour() == this.hour || now.hour() -1 == this.hour)) {
        current_item.addClass("weather-today");
        highlight_set = true;
      }
      current_index += 1;
    });
  }

  function update() {
    $.get("/homecontroller/weather/get_json", function (data) {
      processData(data);
    });
  }

  function onReceiveItemWS(data) {
    processData(data);
  }

  function startInterval() {
    stopInterval();
    update();
    update_interval = setInterval(update, options.update_interval);
    ws_generic.register("weather", onReceiveItemWS);
    ge_refresh.register("weather", update);
  }

  function stopInterval() {
    if (update_interval) {
      update_interval = clearInterval(update_interval);
    }
    ws_generic.deRegister("weather");
    ge_refresh.deRegister("weather");
  }

  this.startInterval = startInterval;
  this.stopInterval = stopInterval;

};

var refresh_weather;
$(document).ready(function () {
  refresh_weather = new RefreshWeather();
  refresh_weather.startInterval();
  $(".open-weather-modal").on("click", function() {
    switchVisibleContent("#weather-modal");
  });
  $("#weather-modal .close").on("click", function() {
    switchVisibleContent("#main-content");
  });

});
<|endoftext|>


<commit_before>import {BrowserWindow, Menu, shell } from 'electron';
import winLinuxMenu from './menus/win-linux';
const path = require('path');
const url = require('url');

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
export let mainWindow;
let menu;

export function createWindow(openDevTools) {
    // Create the browser window.
    mainWindow = new BrowserWindow({width: 1060, height: 600});

    // and load the index.html of the app.
    mainWindow.loadURL(url.format({
        pathname: path.join(__dirname, '../app/index.html'),
        protocol: 'file:',
        slashes: true,
    }));

    // Open the DevTools.
    if (openDevTools) {
        mainWindow.webContents.openDevTools();
        require('devtron').install();
    }
    // Prevent opening external links in electron.
    mainWindow.webContents.on('will-navigate', (e, _url) => {
        e.preventDefault();
        shell.openExternal(_url);
    });

    // Emitted when the window is closed.
    mainWindow.on('closed', () => {
        // Dereference the window object, usually you would store windows
        // in an array if your app supports multi windows, this is the time
        // when you should delete the corresponding element.
        mainWindow = null;
    });

    // Menu (only win and linux for now)
    menu = Menu.buildFromTemplate(winLinuxMenu(mainWindow));
    mainWindow.setMenu(menu);

    return mainWindow.webContents;
}
<commit_msg>electron/mainWindow: enable menu<commit_after>import {BrowserWindow, Menu, shell } from 'electron';
import winLinuxMenu from './menus/win-linux';
const path = require('path');
const url = require('url');

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
export let mainWindow;
let menu;

export function createWindow(openDevTools) {
    // Create the browser window.
    mainWindow = new BrowserWindow({width: 1060, height: 600});

    // and load the index.html of the app.
    mainWindow.loadURL(url.format({
        pathname: path.join(__dirname, '../app/index.html'),
        protocol: 'file:',
        slashes: true,
    }));

    // Open the DevTools.
    if (openDevTools) {
        mainWindow.webContents.openDevTools();
        require('devtron').install();
    }
    // Prevent opening external links in electron.
    mainWindow.webContents.on('will-navigate', (e, _url) => {
        e.preventDefault();
        shell.openExternal(_url);
    });

    // Emitted when the window is closed.
    mainWindow.on('closed', () => {
        // Dereference the window object, usually you would store windows
        // in an array if your app supports multi windows, this is the time
        // when you should delete the corresponding element.
        mainWindow = null;
    });

    // Menu (only win and linux for now)
    menu = Menu.buildFromTemplate(winLinuxMenu(mainWindow));
    Menu.setApplicationMenu(menu);
    mainWindow.setMenu(menu);

    return mainWindow.webContents;
}
<|endoftext|>


<commit_before>var auth = require('basic-auth');
var situations = require('../situations');
var jwt = require('jsonwebtoken');
var moment = require('moment');
var Mustache = require('mustache');

var config = require('../../config/config');
var Loiret = require('../../lib/teleservices/loiret');
var OpenFiscaTracer = require('../../lib/teleservices/openfisca-tracer');

moment.locale('fr');

var teleservices = [{
    name: 'loiret_APA_test',
    class: Loiret,
    destination: {
        label: 'du Loiret (test)',
        url: 'https://reflexe45-test.loiret.fr/public/requestv2/accountless/teleprocedure_id/92?code={{token}}'
    }
}, {
    name: 'local_node_test',
    class: Loiret,
    destination: {
        label: 'en local (Node)',
        url: 'http://localhost:3000?code={{token}}'
    },
}, {
    name: 'local_PHP_test',
    class: Loiret,
    destination: {
        label: 'en local (PHP)',
        url: 'http://localhost:8000/basicAuth.php?code={{token}}'
    }
}, {
    name: 'live_node_test',
    class: Loiret,
    destination: {
        label: 'en ligne',
        url: 'http://test.mes-aides.gouv.fr/prefill?code={{token}}'
    }
}, {
    name: 'openfisca_tracer',
    class: OpenFiscaTracer,
    destination: {
        label: 'en ligne',
        url: '{{&openFiscaTracerURL}}/?source={{&baseURL}}/api/situations/via/{{token}}'
    }
}];

function createClass(teleservice, situation) {
    // Create object dynamically, and apply constructor
    var ts = Object.create(teleservice.class.prototype);
    teleservice.class.apply(ts, [ situation ]);

    return ts;
}

exports.names = teleservices.map(function(ts) { return ts.name; });

/*
 * Express callback to expose teleservice data
 */
exports.list = function(req, res) {
    res.json(teleservices);
};

var teleserviceMap = teleservices.reduce(function(obj, ts) {
    obj[ts.name] = ts;
    return obj;
}, {});

function fail(res, msg) {
    return res.status(400).send({ error: msg });
}

/*
 * Each teleservice requires a specific representation of the situation.
 * Users needs to know what data is made available to third parties.
 * This function generated endpoint callback that respond
 * - decorated data with metadata for display and
 * - the appropriate URL to third party teleservice.
 */
exports.metadataResponseGenerator = function(teleservice) {
    return function(req, res) {
        var payload = {
            id: req.situation._id,
            scope: teleservice.name,
            exp: Math.floor(Date.now() / 1000) + (60 * 60), // Expires after one hour
        };

        var token = jwt.sign(payload, req.situation.token);

        return res.json({
            fields: createClass(teleservice, req.situation).toInternal(),
            destination: {
                label: teleservice.destination.label,
                url: Mustache.render(teleservice.destination.url, {
                    token: token,
                    baseURL: req.protocol + '://' + req.get('host'),
                    openFiscaTracerURL: config.openFiscaTracerURL,
                })
            },
        });
    };
};

/*
 * This callback attachs
 * - the token sent (a JWT)
 * - the decoded token as payload (generated in metadataResponseGenerator)
 * - the appropriate teleservice using the scope name
 */
exports.decodePayload = function(req, res, next, token) {
    req.token = token;
    req.payload = jwt.decode(token);
    if (! req.payload) return fail(res, 'Corrupted payload');
    if ((! req.payload.scope) || (! teleserviceMap[req.payload.scope])) return fail(res, 'Invalid scope');

    req.teleservice = teleserviceMap[req.payload.scope];
    next();
};

var tokens = config.teleserviceAccessTokens || {};
/*
 * This callback validates the basic authorization cookie content
 */
exports.checkCredentials = function(req, res, next) {
    var credentials = auth(req);
    if ((! credentials) || (! tokens[credentials.name]) || (credentials.pass != tokens[credentials.name])) {
        res.status(401)
            .setHeader('WWW-Authenticate', 'Basic realm="MesAidesTeleservices"');
        res.send({ error: 'Not autorized'});
    } else {
        next();
    }
};

/*
 * This callback attachs the appropriate situations
 * It requires a payload with an identifier
 */
exports.attachPayloadSituation = function(req, res, next) {
    situations.situation(req, res, next, req.payload.id);
};

/*
 * This callback validates user consent to share data with the third party
 * * The consent is considered given if the token is signed by the token attached to the situation
 * It requires a situation
 */
exports.verifyRequest = function(req, res, next) {
    jwt.verify(req.token, req.situation.token, function(err) {
        if (err) { return fail(res, err); }
        next();
    });
};

/*
 * This function returns a key/value object representing the requested situation to prefill a specific teleservice.
 * At the moment, the key/value pairs are hardcoded but it mimics the expected behavior.
 */
exports.exportRepresentation = function(req, res) {
    return res.json(createClass(req.teleservice, req.situation).toExternal());
};

for (var i = 0; i < teleservices.length; i++) {
    exports[teleservices[i].name] = teleservices[i];
}
<commit_msg>Allow bypassing basic auth.<commit_after>var auth = require('basic-auth');
var situations = require('../situations');
var jwt = require('jsonwebtoken');
var moment = require('moment');
var Mustache = require('mustache');

var config = require('../../config/config');
var Loiret = require('../../lib/teleservices/loiret');
var OpenFiscaTracer = require('../../lib/teleservices/openfisca-tracer');

moment.locale('fr');

var teleservices = [{
    name: 'loiret_APA_test',
    class: Loiret,
    destination: {
        label: 'du Loiret (test)',
        url: 'https://reflexe45-test.loiret.fr/public/requestv2/accountless/teleprocedure_id/92?code={{token}}'
    }
}, {
    name: 'local_node_test',
    class: Loiret,
    destination: {
        label: 'en local (Node)',
        url: 'http://localhost:3000?code={{token}}'
    },
}, {
    name: 'local_PHP_test',
    class: Loiret,
    destination: {
        label: 'en local (PHP)',
        url: 'http://localhost:8000/basicAuth.php?code={{token}}'
    }
}, {
    name: 'live_node_test',
    class: Loiret,
    destination: {
        label: 'en ligne',
        url: 'http://test.mes-aides.gouv.fr/prefill?code={{token}}'
    }
}, {
    name: 'openfisca_tracer',
    class: OpenFiscaTracer,
    public: true,
    destination: {
        label: 'en ligne',
        url: '{{&openFiscaTracerURL}}/?source={{&baseURL}}/api/situations/via/{{token}}'
    }
}];

function createClass(teleservice, situation) {
    // Create object dynamically, and apply constructor
    var ts = Object.create(teleservice.class.prototype);
    teleservice.class.apply(ts, [ situation ]);

    return ts;
}

exports.names = teleservices.map(function(ts) { return ts.name; });

/*
 * Express callback to expose teleservice data
 */
exports.list = function(req, res) {
    res.json(teleservices);
};

var teleserviceMap = teleservices.reduce(function(obj, ts) {
    obj[ts.name] = ts;
    return obj;
}, {});

function fail(res, msg) {
    return res.status(400).send({ error: msg });
}

/*
 * Each teleservice requires a specific representation of the situation.
 * Users needs to know what data is made available to third parties.
 * This function generated endpoint callback that respond
 * - decorated data with metadata for display and
 * - the appropriate URL to third party teleservice.
 */
exports.metadataResponseGenerator = function(teleservice) {
    return function(req, res) {
        var payload = {
            id: req.situation._id,
            scope: teleservice.name,
            exp: Math.floor(Date.now() / 1000) + (60 * 60), // Expires after one hour
        };

        var token = jwt.sign(payload, req.situation.token);

        return res.json({
            fields: createClass(teleservice, req.situation).toInternal(),
            destination: {
                label: teleservice.destination.label,
                url: Mustache.render(teleservice.destination.url, {
                    token: token,
                    baseURL: req.protocol + '://' + req.get('host'),
                    openFiscaTracerURL: config.openFiscaTracerURL,
                })
            },
        });
    };
};

/*
 * This callback attachs
 * - the token sent (a JWT)
 * - the decoded token as payload (generated in metadataResponseGenerator)
 * - the appropriate teleservice using the scope name
 */
exports.decodePayload = function(req, res, next, token) {
    req.token = token;
    req.payload = jwt.decode(token);
    if (! req.payload) return fail(res, 'Corrupted payload');
    if ((! req.payload.scope) || (! teleserviceMap[req.payload.scope])) return fail(res, 'Invalid scope');

    req.teleservice = teleserviceMap[req.payload.scope];
    next();
};

var tokens = config.teleserviceAccessTokens || {};
/*
 * This callback validates the basic authorization cookie content
 */
exports.checkCredentials = function(req, res, next) {

    var isPublic = req.teleservice.hasOwnProperty('public') && req.teleservice.public;
    if (isPublic) {
        next();
        return;
    }

    var credentials = auth(req);
    if ((! credentials) || (! tokens[credentials.name]) || (credentials.pass != tokens[credentials.name])) {
        res.status(401)
            .setHeader('WWW-Authenticate', 'Basic realm="MesAidesTeleservices"');
        res.send({ error: 'Not autorized'});
    } else {
        next();
    }
};

/*
 * This callback attachs the appropriate situations
 * It requires a payload with an identifier
 */
exports.attachPayloadSituation = function(req, res, next) {
    situations.situation(req, res, next, req.payload.id);
};

/*
 * This callback validates user consent to share data with the third party
 * * The consent is considered given if the token is signed by the token attached to the situation
 * It requires a situation
 */
exports.verifyRequest = function(req, res, next) {
    jwt.verify(req.token, req.situation.token, function(err) {
        if (err) { return fail(res, err); }
        next();
    });
};

/*
 * This function returns a key/value object representing the requested situation to prefill a specific teleservice.
 * At the moment, the key/value pairs are hardcoded but it mimics the expected behavior.
 */
exports.exportRepresentation = function(req, res) {
    return res.json(createClass(req.teleservice, req.situation).toExternal());
};

for (var i = 0; i < teleservices.length; i++) {
    exports[teleservices[i].name] = teleservices[i];
}
<|endoftext|>


<commit_before>var pkg = require('../package.json');
var fs = require('fs');

var DISCOURSE_FILE = __dirname + '/DISCOURSE_POST_URL';

module.exports = {
  dist: 'dist',
  releasePostUrl: fs.readFileSync(DISCOURSE_FILE).toString(),
  releasePostFile: DISCOURSE_FILE,

  protractorPort: 8876,

  banner:
    '/*!\n' +
    ' * Copyright 2014 Drifty Co.\n' +
    ' * http://drifty.com/\n' +
    ' *\n' +
    ' * Ionic, v<%= pkg.version %>\n' +
    ' * A powerful HTML5 mobile app framework.\n' +
    ' * http://ionicframework.com/\n' +
    ' *\n' +
    ' * By @maxlynch, @benjsperry, @adamdbradley <3\n' +
    ' *\n' +
    ' * Licensed under the MIT license. Please see LICENSE for more information.\n'+
    ' *\n' +
    ' */\n\n',
  bundleBanner:
    '/*!\n' +
    ' * ionic.bundle.js is a concatenation of:\n' +
    ' * ionic.js, angular.js, angular-animate.js,\n'+
    ' * angular-sanitize.js, angular-ui-router.js,\n'+
    ' * and ionic-angular.js\n'+
    ' */\n\n',
  closureStart: '(function() {\n',
  closureEnd: '\n})();',

  ionicFiles: [
    // Base
    'js/ionic.js',

    // Utils
    'js/utils/dom.js',
    'js/utils/events.js',
    'js/utils/gestures.js',
    'js/utils/platform.js',
    'js/utils/poly.js',
    'js/utils/tap.js',
    'js/utils/activator.js',
    'js/utils/utils.js',
    'js/utils/keyboard.js',
    'js/utils/viewport.js',

    // Views
    'js/views/view.js',
    'js/views/scrollView.js',
    'js/views/headerBarView.js',
    'js/views/listView.js',
    'js/views/modalView.js',
    'js/views/sideMenuView.js',
    'js/views/sliderView.js',
    'js/views/toggleView.js'
  ],

  angularIonicFiles: [
    'js/angular/*.js',
    'js/angular/service/**/*.js',
    'js/angular/controller/**/*.js',
    'js/angular/directive/**/*.js'
  ],

  //Which vendor files to include in dist, used by build
  //Matched relative to config/lib/
  vendorFiles: [
    'js/angular/angular-animate.js',
    'js/angular/angular-animate.min.js',
    'js/angular/angular-resource.js',
    'js/angular/angular-resource.min.js',
    'js/angular/angular-sanitize.js',
    'js/angular/angular-sanitize.min.js',
    'js/angular/angular.js',
    'js/angular/angular.min.js',
    'js/angular-ui/angular-ui-router.js',
    'js/angular-ui/angular-ui-router.min.js',
    'fonts/ionicons.eot',
    'fonts/ionicons.svg',
    'fonts/ionicons.ttf',
    'fonts/ionicons.woff'
  ],

  ionicBundleFiles: [
    'js/ionic.js',
    'js/angular/angular.js',
    'js/angular/angular-animate.js',
    'js/angular/angular-sanitize.js',
    'js/angular-ui/angular-ui-router.js',
    'js/ionic-angular.js'
  ],

  //Exclamation can be no longer than 14 chars
  exclamations: [
    "Aah","Ah","Aha","All right","Aw","Ay","Aye","Bah","Boy","By golly","Boom","Cheerio","Cheers","Come on","Crikey","Dear me","Egads","Fiddle-dee-dee","Gadzooks","Gangway","G'day","Gee whiz","Gesundheit","Get outta here","Gosh","Gracious","Great","Gulp","Ha","Ha-ha","Hah","Harrumph","Hey","Hooray","Hurray","Huzzah","I say","Look","Look here","Long time","Lordy","Most certainly","My my","My word","Oh","Oh-oh","Oh no","Okay","Okey-dokey","Ooh","Oye","Phew","Quite","Ready","Right on","Roger that","Rumble","Say","See ya","Snap","Sup","Ta-da","Take that","Tally ho","Thanks","Toodles","Touche","Tut-tut","Very nice","Very well","Voila","Vroom","Well done","Well, well","Whoa","Whoopee","Whew","Word up","Wow","Wuzzup","Ya","Yea","Yeah","Yippee","Yo","Yoo-hoo","You bet","You don't say","You know","Yow","Yum","Yummy","Zap","Zounds","Zowie"
  ],

  //Message can be no longer than it is. Currently it's 126 chars with the short git urls,
  //and can have up to a 14 char long exclamation prepended.
  releaseMessage: function() {
    return this.exclamations[Math.floor(Math.random()*this.exclamations.length)] + '! ' +
      'Just released @IonicFramework v' + pkg.version + ' "' + pkg.codename + '"! ' +
      this.releasePostUrl;
  },

};
<commit_msg>build fix<commit_after>var pkg = require('../package.json');
var fs = require('fs');

var DISCOURSE_FILE = __dirname + '/DISCOURSE_POST_URL';

module.exports = {
  dist: '../app/ionic/dist',
  releasePostUrl: fs.readFileSync(DISCOURSE_FILE).toString(),
  releasePostFile: DISCOURSE_FILE,

  protractorPort: 8876,

  banner:
    '/*!\n' +
    ' * Copyright 2014 Drifty Co.\n' +
    ' * http://drifty.com/\n' +
    ' *\n' +
    ' * Ionic, v<%= pkg.version %>\n' +
    ' * A powerful HTML5 mobile app framework.\n' +
    ' * http://ionicframework.com/\n' +
    ' *\n' +
    ' * By @maxlynch, @benjsperry, @adamdbradley <3\n' +
    ' *\n' +
    ' * Licensed under the MIT license. Please see LICENSE for more information.\n'+
    ' *\n' +
    ' */\n\n',
  bundleBanner:
    '/*!\n' +
    ' * ionic.bundle.js is a concatenation of:\n' +
    ' * ionic.js, angular.js, angular-animate.js,\n'+
    ' * angular-sanitize.js, angular-ui-router.js,\n'+
    ' * and ionic-angular.js\n'+
    ' */\n\n',
  closureStart: '(function() {\n',
  closureEnd: '\n})();',

  ionicFiles: [
    // Base
    'js/ionic.js',

    // Utils
    'js/utils/dom.js',
    'js/utils/events.js',
    'js/utils/gestures.js',
    'js/utils/platform.js',
    'js/utils/poly.js',
    'js/utils/tap.js',
    'js/utils/activator.js',
    'js/utils/utils.js',
    'js/utils/keyboard.js',
    'js/utils/viewport.js',

    // Views
    'js/views/view.js',
    'js/views/scrollView.js',
    'js/views/headerBarView.js',
    'js/views/listView.js',
    'js/views/modalView.js',
    'js/views/sideMenuView.js',
    'js/views/sliderView.js',
    'js/views/toggleView.js'
  ],

  angularIonicFiles: [
    'js/angular/*.js',
    'js/angular/service/**/*.js',
    'js/angular/controller/**/*.js',
    'js/angular/directive/**/*.js'
  ],

  //Which vendor files to include in dist, used by build
  //Matched relative to config/lib/
  vendorFiles: [
    'js/angular/angular-animate.js',
    'js/angular/angular-animate.min.js',
    'js/angular/angular-resource.js',
    'js/angular/angular-resource.min.js',
    'js/angular/angular-sanitize.js',
    'js/angular/angular-sanitize.min.js',
    'js/angular/angular.js',
    'js/angular/angular.min.js',
    'js/angular-ui/angular-ui-router.js',
    'js/angular-ui/angular-ui-router.min.js',
    'fonts/ionicons.eot',
    'fonts/ionicons.svg',
    'fonts/ionicons.ttf',
    'fonts/ionicons.woff'
  ],

  ionicBundleFiles: [
    'js/ionic.js',
    'js/angular/angular.js',
    'js/angular/angular-animate.js',
    'js/angular/angular-sanitize.js',
    'js/angular-ui/angular-ui-router.js',
    'js/ionic-angular.js'
  ],

  //Exclamation can be no longer than 14 chars
  exclamations: [
    "Aah","Ah","Aha","All right","Aw","Ay","Aye","Bah","Boy","By golly","Boom","Cheerio","Cheers","Come on","Crikey","Dear me","Egads","Fiddle-dee-dee","Gadzooks","Gangway","G'day","Gee whiz","Gesundheit","Get outta here","Gosh","Gracious","Great","Gulp","Ha","Ha-ha","Hah","Harrumph","Hey","Hooray","Hurray","Huzzah","I say","Look","Look here","Long time","Lordy","Most certainly","My my","My word","Oh","Oh-oh","Oh no","Okay","Okey-dokey","Ooh","Oye","Phew","Quite","Ready","Right on","Roger that","Rumble","Say","See ya","Snap","Sup","Ta-da","Take that","Tally ho","Thanks","Toodles","Touche","Tut-tut","Very nice","Very well","Voila","Vroom","Well done","Well, well","Whoa","Whoopee","Whew","Word up","Wow","Wuzzup","Ya","Yea","Yeah","Yippee","Yo","Yoo-hoo","You bet","You don't say","You know","Yow","Yum","Yummy","Zap","Zounds","Zowie"
  ],

  //Message can be no longer than it is. Currently it's 126 chars with the short git urls,
  //and can have up to a 14 char long exclamation prepended.
  releaseMessage: function() {
    return this.exclamations[Math.floor(Math.random()*this.exclamations.length)] + '! ' +
      'Just released @IonicFramework v' + pkg.version + ' "' + pkg.codename + '"! ' +
      this.releasePostUrl;
  },

};
<|endoftext|>


<commit_before>// we have problems if the page has changed the definition of Set or Array
// http://www.polyvore.com/ does this for example
var __brzl_framesDone = new Set();
var __brzl_popup_re = /window.open\(\s*(['"])(.*?)\1/
var __brzl_compileOutlinks = function(frame) {
    __brzl_framesDone.add(frame);
    var outlinks = [];
    try {
        if (frame && frame.document) {
            outlinks = Array.prototype.slice.call(
                frame.document.querySelectorAll('a[href], area[href]'));
            popups = Array.prototype.slice.call(
                frame.document.querySelectorAll('a[onclick]'));
            if (popups && popups.length > 0) {
                for (var p=0; p < popups.length; p++) {
                    m = popups[p].onclick.toString().match(__brzl_popup_re);
                    if (m) {
                        outlinks.push(m[2]);
                    }
                }
            }
            for (var i = 0; i < frame.frames.length; i++) {
                if (frame.frames[i] && !__brzl_framesDone.has(frame.frames[i])) {
                    outlinks = outlinks.concat(
                        __brzl_compileOutlinks(frame.frames[i]));
                }
            }
        }
    } catch (e) {
        console.log("exception looking at frame" + frame + ": " + e);
    }

    return outlinks;
}
__brzl_compileOutlinks(window).join('\n');
<commit_msg>add dblclick (and fix typo)<commit_after>// we have problems if the page has changed the definition of Set or Array
// http://www.polyvore.com/ does this for example
var __brzl_framesDone = new Set();
var __brzl_popup_re = /window.open\(\s*(['"])(.*?)\1/;
var __brzl_compileOutlinks = function(frame) {
    __brzl_framesDone.add(frame);
    var outlinks = [];
    try {
        if (frame && frame.document) {
            outlinks = Array.prototype.slice.call(
                frame.document.querySelectorAll('a[href], area[href]'));
            popups = Array.prototype.slice.call(
                frame.document.querySelectorAll('a[onclick], a[ondblclick]'));
            if (popups && popups.length > 0) {
                for (var p=0; p < popups.length; p++) {
                    if (popups[p].onclick){
                        m = popups[p].onclick.toString().match(__brzl_popup_re);
                    } else {
                        m = popups[p].ondblclick.toString().match(__brzl_popup_re);
                    }
                    if (m) {
                        outlinks.push(m[2]);
                    }
                }
            }
            for (var i = 0; i < frame.frames.length; i++) {
                if (frame.frames[i] && !__brzl_framesDone.has(frame.frames[i])) {
                    outlinks = outlinks.concat(
                        __brzl_compileOutlinks(frame.frames[i]));
                }
            }
        }
    } catch (e) {
        console.log("exception looking at frame" + frame + ": " + e);
    }

    return outlinks;
}
__brzl_compileOutlinks(window).join('\n');
<|endoftext|>


<commit_before>//  Flocking system
//  Based on chapter 6 of Nature of Code by Daniel Shiffman
//  http://natureofcode.com/book/chapter-6-autonomous-agents/
//
//  Rewritten for PaperJS and optimized by Bob Corporaal - https://reefscape.net

var Flock = Base.extend({
  initialize: function() {
    this.boids = []; // Initialize array to hold the boids
    this.l = 0; // Track the number of boids
  },

  addBoid: function(newBoid) {
    this.l++;
    this.boids.push(newBoid);
  },

  run: function() {
    for (var i = 0; i < this.l; i++) {
      this.boids[i].run(this.boids);  // Passing the entire list of boids to each boid individually
    }
  }
});
<commit_msg>send current mouse position to the boids<commit_after>//  Flocking system
//  Based on chapter 6 of Nature of Code by Daniel Shiffman
//  http://natureofcode.com/book/chapter-6-autonomous-agents/
//
//  Rewritten for PaperJS and optimized by Bob Corporaal - https://reefscape.net

var Flock = Base.extend({
  initialize: function() {
    this.boids = []; // Initialize array to hold the boids
    this.l = 0; // Track the number of boids
    this.currentMousePos = new Point();
  },

  addBoid: function(newBoid) {
    this.l++;
    this.boids.push(newBoid);
  },

  run: function() {
    for (var i = 0; i < this.l; i++) {
      this.boids[i].run(this.boids, this.currentMousePos);  // Passing the entire list of boids to each boid individually
    }
  },

  updateMouse: function(mousePos) {
    this.currentMousePos = mousePos;
  }
});
<|endoftext|>


<commit_before>function get(url) {
  // Return a new promise.
  return new Promise(function(resolve, reject) {
    // Do the usual XHR stuff
    var req = new XMLHttpRequest();
    req.open('GET', url);

    req.onload = function() {
      // This is called even on 404 etc
      // so check the status
      if (req.status == 200) {
        // Resolve the promise with the response text
        resolve(req.response);
      }
      else {
        // Otherwise reject with the status text
        // which will hopefully be a meaningful error
        reject(Error(req.statusText));
      }
    };

    // Handle network errors
    req.onerror = function() {
      reject(Error("Network Error"));
    };

    // Make the request
    req.send();
  });
}

function getJSON(url) {
  return get(url).then(JSON.parse);
}

var pairwise = function(list) {
  if (list.length < 2) {
    return [];
  }
  var first = list[0],
        rest = list.slice(1),
      pairs = rest.map(function (x) { return [first, x]; });
  return pairs.concat(pairwise(rest));
};

var calculate_distance = function(p1, p2) {
  return Math.sqrt(Math.pow(p2.x - p1.x, 2) +
                   Math.pow(p2.y - p1.y, 2) +
                   Math.pow(p2.z - p1.z, 2));
};

var calculate_distances = function(p1, points) {
  return points.map(function(p) {
    return calculate_distance(p1, p.position);
  });
};

var calculate_midpoint = function(p1, p2) {
  return {
    x: (p1.x + p2.x) / 2,
    y: (p1.y + p2.y) / 2,
    z: (p1.z + p2.z) / 2
  };
};

var AU = 149597870700;

var systems_promise = new Promise(function(resolve, reject) {
  api_endpoint = 'https://esi.evetech.net/latest/universe/systems/';
  getJSON(api_endpoint).then(function(data) {
    return Promise.all(data.map(id => getJSON(`https://esi.evetech.net/latest/universe/systems/${id}`)));
  }).then(data => {
    var systems = {};
    var names = [];
    data.items.forEach(function(system) {
      systems[system.name] = system.href;
      names.push(system.name);
    });
    systems.order = names.sort();
    resolve(systems);
  });
});

systems_promise.then(function(systems) {
  var element = document.getElementById('system_selector');
  var options = ['<option>Please choose system</option>'];
  systems.order.forEach(function(name) {
    options.push("<option value='" + name + "'>" + name + "</option>");
  });
  element.innerHTML = options.join("\n");
  element.addEventListener('change', function() {
    var name = this.value;
    safe_points_for_system(name).then(function(safe_watch) {
      var data = new vis.DataSet();
      var numbers = [];
      var labels = {};
      safe_watch.planets.forEach(function(planet) {
        var point = planet.position;
        point.style = 1;
        var temp = point.y;
        point.y = point.z;
        point.z = temp;
        labels[point.x + '|' + point.y + '|' + point.z] = planet.name;
        data.add(point);
        numbers.push(Math.abs(point.x), Math.abs(point.y), Math.abs(point.z));
      });
      safe_watch.midpoints.forEach(function(midpoint) {
        var point = midpoint.midpoint;
        point.style = 2;
        var temp = point.y;
        point.y = point.z;
        point.z = temp;
        labels[point.x + '|' + point.y + '|' + point.z] = midpoint.name;
        data.add(point);
      });
      var max = Math.max.apply(null, numbers);
      draw(data, max, labels);
      window.location.hash = '#' + name
    });
  });
  name = window.location.hash.substr(1);
  if (name.length) {
    element.value = name;
    var evt = document.createEvent("HTMLEvents");
    evt.initEvent("change", false, true);
    element.dispatchEvent(evt);
  }
});

var safe_points_for_system = function(system_name) {
  return new Promise(function(resolve, reject) {
    systems_promise.then(function(systems) {
      return getJSON(systems[system_name]);
    }).then(function(system) {
      return Promise.all(
        system.planets.map(function(planet) {
          return planet.href;
        }).map(getJSON)
      );
    }).then(function(planets) {
      planets.push({
        position: { x: 0, y: 0, z: 0 },
        name: 'Sun'
      });
      var pairs = pairwise(planets);
      var midpoints = pairs.map(function(pair) {
        return {
          name: pair[0].name + ' to ' + pair[1].name,
          midpoint: calculate_midpoint(pair[0].position, pair[1].position),
          distance: calculate_distance(pair[0].position, pair[1].position)
        }
      });
      return {
        planets: planets,
        midpoints: midpoints.map(function(mid) {
          return planets.map(function(planet) {
            var midpoint = calculate_midpoint(mid.midpoint, planet.position);
            var distances = calculate_distances(midpoint, planets);
            return {
              name: '(' + mid.name + ') to ' + planet.name,
              midpoint: midpoint,
              distances: distances,
              safe: distances.every(function(d) { return d > 2147483647000 })
            }
          });
        })
      };
    }).then(function(data) {
      final_midpoints = Array.prototype.concat.apply([], data.midpoints);
      data.midpoints = final_midpoints.filter(function(m) {
        return m.safe;
      });
      resolve(data);
    });
  });
};

var draw, graph;

draw = function(data, max, labels) {
  var options = {
    width: '100%',
    height: '100%',
    style: 'dot-color',
    showPerspective: false,
    showGrid: true,
    keepAspectRatio: false,
    verticalRatio: 1.0,
    tooltip: function(point) {
      return labels[point.x + '|' + point.y + '|' + point.z];
    },
    dotSizeRatio: 0.005,
    xValueLabel: function(x) { return Math.round(x / AU) + ' AU'; },
    yValueLabel: function(y) { return Math.round(y / AU) + ' AU'; },
    zValueLabel: function(z) { return Math.round(z / AU) + ' AU'; },
    xMin: -max,
    xMax: max,
    xStep: 5 * AU,
    yMin: -max,
    yMax: max,
    yStep: 5 * AU,
    zMin: -max,
    zMax: max,
    zStep: 5 * AU,
    legendLabel: "Blue: sun and planets; Red: safe spots",
    cameraPosition: {
      horizontal: 0,
      vertical: 0.5 * Math.PI,
      distance: 2.2
    }
  };
  vis.Graph3d.prototype._redrawLegend = function(){};
  var container = document.getElementById('system');
  graph = new vis.Graph3d(container, data, options);
};
<commit_msg>Update main.js<commit_after>function get(url) {
  // Return a new promise.
  return new Promise(function(resolve, reject) {
    // Do the usual XHR stuff
    var req = new XMLHttpRequest();
    req.open('GET', url);

    req.onload = function() {
      // This is called even on 404 etc
      // so check the status
      if (req.status == 200) {
        // Resolve the promise with the response text
        resolve(req.response);
      }
      else {
        // Otherwise reject with the status text
        // which will hopefully be a meaningful error
        reject(Error(req.statusText));
      }
    };

    // Handle network errors
    req.onerror = function() {
      reject(Error("Network Error"));
    };

    // Make the request
    req.send();
  });
}

function getJSON(url) {
  return get(url).then(JSON.parse);
}

var pairwise = function(list) {
  if (list.length < 2) {
    return [];
  }
  var first = list[0],
        rest = list.slice(1),
      pairs = rest.map(function (x) { return [first, x]; });
  return pairs.concat(pairwise(rest));
};

var calculate_distance = function(p1, p2) {
  return Math.sqrt(Math.pow(p2.x - p1.x, 2) +
                   Math.pow(p2.y - p1.y, 2) +
                   Math.pow(p2.z - p1.z, 2));
};

var calculate_distances = function(p1, points) {
  return points.map(function(p) {
    return calculate_distance(p1, p.position);
  });
};

var calculate_midpoint = function(p1, p2) {
  return {
    x: (p1.x + p2.x) / 2,
    y: (p1.y + p2.y) / 2,
    z: (p1.z + p2.z) / 2
  };
};

var AU = 149597870700;

var systems_promise = new Promise(function(resolve, reject) {
  api_endpoint = 'https://esi.evetech.net/latest/universe/systems/';
  getJSON(api_endpoint).then(function(data) {
    return Promise.all(data.map(id => getJSON(`https://esi.evetech.net/latest/universe/systems/${id}`).catch(() => {}));
  }).then(data => {
    var systems = {};
    var names = [];
    data.forEach(function(system) {
      if (!system.name) continue;
      systems[system.name] = system;
      names.push(system.name);
    });
    systems.order = names.sort();
    resolve(systems);
  });
});

systems_promise.then(function(systems) {
  var element = document.getElementById('system_selector');
  var options = ['<option>Please choose system</option>'];
  systems.order.forEach(function(name) {
    options.push("<option value='" + name + "'>" + name + "</option>");
  });
  element.innerHTML = options.join("\n");
  element.addEventListener('change', function() {
    var name = this.value;
    safe_points_for_system(name).then(function(safe_watch) {
      var data = new vis.DataSet();
      var numbers = [];
      var labels = {};
      safe_watch.planets.forEach(function(planet) {
        var point = planet.position;
        point.style = 1;
        var temp = point.y;
        point.y = point.z;
        point.z = temp;
        labels[point.x + '|' + point.y + '|' + point.z] = planet.name;
        data.add(point);
        numbers.push(Math.abs(point.x), Math.abs(point.y), Math.abs(point.z));
      });
      safe_watch.midpoints.forEach(function(midpoint) {
        var point = midpoint.midpoint;
        point.style = 2;
        var temp = point.y;
        point.y = point.z;
        point.z = temp;
        labels[point.x + '|' + point.y + '|' + point.z] = midpoint.name;
        data.add(point);
      });
      var max = Math.max.apply(null, numbers);
      draw(data, max, labels);
      window.location.hash = '#' + name
    });
  });
  name = window.location.hash.substr(1);
  if (name.length) {
    element.value = name;
    var evt = document.createEvent("HTMLEvents");
    evt.initEvent("change", false, true);
    element.dispatchEvent(evt);
  }
});

var safe_points_for_system = function(system_name) {
  return new Promise(function(resolve, reject) {
    systems_promise.then(function(systems) {
      return getJSON(systems[system_name]);
    }).then(function(system) {
      return Promise.all(
        system.planets.map(function(planet) {
          return planet.href;
        }).map(getJSON)
      );
    }).then(function(planets) {
      planets.push({
        position: { x: 0, y: 0, z: 0 },
        name: 'Sun'
      });
      var pairs = pairwise(planets);
      var midpoints = pairs.map(function(pair) {
        return {
          name: pair[0].name + ' to ' + pair[1].name,
          midpoint: calculate_midpoint(pair[0].position, pair[1].position),
          distance: calculate_distance(pair[0].position, pair[1].position)
        }
      });
      return {
        planets: planets,
        midpoints: midpoints.map(function(mid) {
          return planets.map(function(planet) {
            var midpoint = calculate_midpoint(mid.midpoint, planet.position);
            var distances = calculate_distances(midpoint, planets);
            return {
              name: '(' + mid.name + ') to ' + planet.name,
              midpoint: midpoint,
              distances: distances,
              safe: distances.every(function(d) { return d > 2147483647000 })
            }
          });
        })
      };
    }).then(function(data) {
      final_midpoints = Array.prototype.concat.apply([], data.midpoints);
      data.midpoints = final_midpoints.filter(function(m) {
        return m.safe;
      });
      resolve(data);
    });
  });
};

var draw, graph;

draw = function(data, max, labels) {
  var options = {
    width: '100%',
    height: '100%',
    style: 'dot-color',
    showPerspective: false,
    showGrid: true,
    keepAspectRatio: false,
    verticalRatio: 1.0,
    tooltip: function(point) {
      return labels[point.x + '|' + point.y + '|' + point.z];
    },
    dotSizeRatio: 0.005,
    xValueLabel: function(x) { return Math.round(x / AU) + ' AU'; },
    yValueLabel: function(y) { return Math.round(y / AU) + ' AU'; },
    zValueLabel: function(z) { return Math.round(z / AU) + ' AU'; },
    xMin: -max,
    xMax: max,
    xStep: 5 * AU,
    yMin: -max,
    yMax: max,
    yStep: 5 * AU,
    zMin: -max,
    zMax: max,
    zStep: 5 * AU,
    legendLabel: "Blue: sun and planets; Red: safe spots",
    cameraPosition: {
      horizontal: 0,
      vertical: 0.5 * Math.PI,
      distance: 2.2
    }
  };
  vis.Graph3d.prototype._redrawLegend = function(){};
  var container = document.getElementById('system');
  graph = new vis.Graph3d(container, data, options);
};
<|endoftext|>