<commit_before>var Q = require('q'),
    path = require('path'),
    fs = require('fs'),

    bobble = require('./bobble.js');

exports.getIndex = function (req, res) {
    var url = req.protocol + '://' + req.get('host') + req.originalUrl;
    res.redirect('http://nyanit.com/' + url + 'bobble');
}

exports.generateBobble = function (req, res) {
    var imgSrc = req.file.path;
    bobble.detectFace(req.file.path)
        .then(bobble.generateBobblePermutations)
        .then(bobble.generateGif)
        .then(function () {
        console.log('generate');
        res.redirect(301, '/bobble/' + path.basename(imgSrc, path.extname(imgSrc)));
    })
}

exports.displayBobble = function (req, res) {
    var myImg = 'myanimated.gif';
    console.log(req.params['bobbleId'])
    if (typeof req.params['bobbleId'] !== 'undefined') {
        myImg = req.params['bobbleId'] + '.gif';
    }
    console.log('my image:', myImg);
    // res.end('hello');
    res.render('index', {
        title: 'Bobblehead Generator',
        location: "http://nyanit.com/" + req.get('host') + '/bobble/' + path.basename(myImg, path.extname(myImg)),
        imgs: [myImg]
    });
    // res.end('hello');
}
<commit_msg>remove nyan cat redirect<commit_after>var Q = require('q'),
    path = require('path'),
    fs = require('fs'),

    bobble = require('./bobble.js');

var IS_NYAN = false;

exports.getIndex = function (req, res) {
    var url = req.protocol + '://' + req.get('host') + req.originalUrl;
    res.redirect((IS_NYAN ? 'http://nyanit.com/' : '') + url + 'bobble');
}

exports.generateBobble = function (req, res) {
    var imgSrc = req.file.path;
    bobble.detectFace(req.file.path)
        .then(bobble.generateBobblePermutations)
        .then(bobble.generateGif)
        .then(function () {
        console.log('generate');
        res.redirect(301, '/bobble/' + path.basename(imgSrc, path.extname(imgSrc)));
    })
}

exports.displayBobble = function (req, res) {
    var myImg = 'myanimated.gif';
    console.log(req.params['bobbleId'])
    if (typeof req.params['bobbleId'] !== 'undefined') {
        myImg = req.params['bobbleId'] + '.gif';
    }
    console.log('my image:', myImg);
    // res.end('hello');
    res.render('index', {
        title: 'Bobblehead Generator',
        location: "http://nyanit.com/" + req.get('host') + '/bobble/' + path.basename(myImg, path.extname(myImg)),
        imgs: [myImg]
    });
    // res.end('hello');
}
<|endoftext|>


<commit_before>// Action Creators
// ===================
function toggleBar() {
  return {
    type: 'TOGGLE_BAR'
  }
}

// Redux Reducers
// ===================
var reducers = Redux.combineReducers({
  bar: function(_state, action) {

    var state = _state ? _.clone(_state) : {
      isActive: true
    };

    switch (action.type) {

      case 'TOGGLE_BAR':
        state.isActive = !state.isActive;
        return state;

      default:
        return state;
    }
  }
})

// Redux Store
// ===================
var compose = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : Redux.compose;
var store = compose()(Redux.createStore)(reducers);

// Common Maps
// ===================
var mapStateToProps = function(state) {
  return {
    bar: state.bar
  }
};

// Backbone Models
// ===================
var MydModel = Backbone.Model.extend({
  store: store,
  componentDidReceiveProps: function(update) {
    this.set({
      bar: update.bar
    })
  }
});
var ConnectedModel = MarionetteRedux.connect(mapStateToProps)(MydModel);
var connectedModel = new ConnectedModel();

// Marionette Views
// ===================
var FooView = Marionette.View.extend({
  store: store,
  template: function() {
    return '<button>Toggle</button>'
  },
  ui: {
    button: 'button'
  },
  modelEvents: {
    'change:bar': 'onChangeBar'
  },
  events: {
    'click button': 'onClickButton'
  },
  onClickButton: function() {
    this.props.dispatch(toggleBar())
  },
  onChangeBar: function(model, attrs) {
    if (attrs.isActive) {
      this.ui.button.css({
        color: 'black'
      })
    } else {
      this.ui.button.css({
        color: 'red'
      })
    }
  }
});
var ConnectedFooView = MarionetteRedux.connect()(FooView);

var BarView = Marionette.View.extend({
  store: store,
  template: function() {
    return 'Bar'
  },
  stateEvents: {
    'change:bar': 'onChangeBar'
  },
  componentDidReceiveProps: function(update) {
    this.setState({
      bar: update.bar
    })
  },
  onChangeBar: function(view, state) {
    if(state.isActive) {
      this.$el.show()
    } else {
      this.$el.hide()
    }
  }
});
var ConnectedBarView = MarionetteRedux.connect(mapStateToProps)(BarView);

var RootView = Marionette.View.extend({
  template: function() {
    return '

'
  },
  regions: {
    foo: '#foo',
    bar: '#bar'
  },
  onRender: function() {
    this.showChildView('foo', new ConnectedFooView({
      model: connectedModel
    }));
    this.showChildView('bar', new ConnectedBarView());
  }
});

// Marionette Application
// ==========================
var App = Mn.Application.extend({
  region: '#root-element',

  onStart: function() {
    this.showView(new RootView());
  }
});

var myApp = new App();
myApp.start();<commit_msg>typo fix<commit_after>// Action Creators
// ===================
function toggleBar() {
  return {
    type: 'TOGGLE_BAR'
  }
}

// Redux Reducers
// ===================
var reducers = Redux.combineReducers({
  bar: function(_state, action) {

    var state = _state ? _.clone(_state) : {
      isActive: true
    };

    switch (action.type) {

      case 'TOGGLE_BAR':
        state.isActive = !state.isActive;
        return state;

      default:
        return state;
    }
  }
})

// Redux Store
// ===================
var compose = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : Redux.compose;
var store = compose()(Redux.createStore)(reducers);

// Common Maps
// ===================
var mapStateToProps = function(state) {
  return {
    bar: state.bar
  }
};

// Backbone Models
// ===================
var Model = Backbone.Model.extend({
  store: store,
  componentDidReceiveProps: function(update) {
    this.set({
      bar: update.bar
    })
  }
});
var ConnectedModel = MarionetteRedux.connect(mapStateToProps)(Model);
var connectedModel = new ConnectedModel();

// Marionette Views
// ===================
var FooView = Marionette.View.extend({
  store: store,
  template: function() {
    return '<button>Toggle</button>'
  },
  ui: {
    button: 'button'
  },
  modelEvents: {
    'change:bar': 'onChangeBar'
  },
  events: {
    'click button': 'onClickButton'
  },
  onClickButton: function() {
    this.props.dispatch(toggleBar())
  },
  onChangeBar: function(model, attrs) {
    if (attrs.isActive) {
      this.ui.button.css({
        color: 'black'
      })
    } else {
      this.ui.button.css({
        color: 'red'
      })
    }
  }
});
var ConnectedFooView = MarionetteRedux.connect()(FooView);

var BarView = Marionette.View.extend({
  store: store,
  template: function() {
    return 'Bar'
  },
  stateEvents: {
    'change:bar': 'onChangeBar'
  },
  componentDidReceiveProps: function(update) {
    this.setState({
      bar: update.bar
    })
  },
  onChangeBar: function(view, state) {
    if(state.isActive) {
      this.$el.show()
    } else {
      this.$el.hide()
    }
  }
});
var ConnectedBarView = MarionetteRedux.connect(mapStateToProps)(BarView);

var RootView = Marionette.View.extend({
  template: function() {
    return '

'
  },
  regions: {
    foo: '#foo',
    bar: '#bar'
  },
  onRender: function() {
    this.showChildView('foo', new ConnectedFooView({
      model: connectedModel
    }));
    this.showChildView('bar', new ConnectedBarView());
  }
});

// Marionette Application
// ==========================
var App = Mn.Application.extend({
  region: '#root-element',

  onStart: function() {
    this.showView(new RootView());
  }
});

var myApp = new App();
myApp.start();<|endoftext|>


<commit_before>module.exports = function(clients, logExceptOnTest) {
  var exists = function(clientId) {
    if (clients[clientId] == null) {
      return false;
    }
    logExceptOnTest(clientId, "Client already exists");
    return true;
  };
  return {
    getNewId: function() {
      clients.totalUsers += 1;
      var clientId;
      do {
        clientId = Math.random() * 1000000;
        clientId = Math.floor(clientId);
      } while (exists(clientId));
      clientId = "user" + clientId.toString(10);
      logExceptOnTest("New Client ID " + clientId);
      return clientId;
    }
  };
};
<commit_msg>Fix bug with existing clientIds<commit_after>module.exports = function(clients, logExceptOnTest) {
  var exists = function(clientId) {
    console.log('*** we are checking ....' + clientId);
    if (clientId in clients) {
      logExceptOnTest("*** Client already exists");
      return true;
    }
    logExceptOnTest("*** Client did not already exists");
    return false;
  };
  return {
    getNewId: function() {
      clients.totalUsers += 1;
      var clientId;
      do {
        var randomId = Math.random() * 2;
        randomId = Math.floor(randomId);
        clientId = "user" + randomId.toString(10);
      } while (exists(clientId));
      logExceptOnTest("*** New Client ID " + clientId);
      return clientId;
    }
  };
};
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import {connect} from 'react-redux'
import {bindActionCreators} from 'redux'
import path from 'path'
import Catalog from '../components/Catalog';
import FileAdder from '../components/FileAdder';
import * as mixedActions from '../actions/actions'
import {getSchema} from '../store/schema'
import {List, ListItem} from 'material-ui/List';
import RaisedButton from 'material-ui/RaisedButton';
import {RadioButton, RadioButtonGroup} from 'material-ui/RadioButton';
import * as appActions from '../actions/app'
import _ from 'underscore'
import PropTypes from 'prop-types';
import {grey300} from 'material-ui/styles/colors';
import BusyDialog from '../components/BusyDialog'
import SettingsDialog from '../components/SettingsDialog'
import storage from 'electron-json-storage';
import {initWithPath} from '../store/schema'
import fs from 'fs-extra'

class HomePage extends Component {

  constructor(props) {
    super(props)
    this.state = {
      isCatalogPathInvalid: false,
      isFormsPathInvalid: false,
      isSettingsLoaded: false,
    }

    storage.get('settings', (error, settings) => {
      if (error) throw error;
      const isCatalogPathInvalid = !fs.existsSync(settings.path)
      const isFormsPathInvalid = !fs.existsSync(settings.formsPath)
      if (isCatalogPathInvalid || isFormsPathInvalid) {
        this.setState({
          isCatalogPathInvalid,
          isFormsPathInvalid,
          stateSettings: settings,
        })
        return
      }
      this.setSettingsAndLoadCatalog(settings)
    })
  }

  setSettingsAndLoadCatalog = settings => {
    const {actions} = this.props
    actions.setSettings(settings)
    initWithPath(settings.formPath)
    actions.loadCatalog(settings.path)
    this.setState({
      isSettingsLoaded: true,
      isCatalogPathInvalid: false,
      isFormsPathInvalid: false,
    })
  }

  handleFileCopied = (bookId, newPage) => {
    const {actions, settings} = this.props
    actions.addPage(bookId, newPage)
  }

  render() {
    const {actions, app, bookPages, books, entries, selectedBookId, settings} = this.props
    const {isCatalogPathInvalid, isFormsPathInvalid, stateSettings, isSettingsLoaded} = this.state
    const invalidPath = isCatalogPathInvalid || isFormsPathInvalid
    const isSettingsDialogOpen = isSettingsLoaded && !settings.path || invalidPath
    const headerStyle = {
      position: 'absolute',
      top: 0,
      display: 'flex',
      justifyContent: 'space-between',
      alignItems: 'center',
      height: 200,
      padding: 20,
    }
    const mainStyle = {
      top: 200,
      bottom: 0,
      position: 'absolute',
      left: 0,
      right: 0,
      display: 'flex',
    }
    return (

        <SettingsDialog
            isOpen={isSettingsDialogOpen}
            settings={invalidPath ?  stateSettings : settings}
            isCatalogPathInvalid={isCatalogPathInvalid}
            isFormsPathInvalid={isFormsPathInvalid}
            onSaveSettings={this.setSettingsAndLoadCatalog} />
        <BusyDialog
            isOpen={app.isValidating} />

{Object.keys(books).length} Books

          <BookIndexFilter
              selectedBookId={selectedBookId}
              onWithEntryFilterClick={actions.setWithEntryFilter}
              onEntryValidityFilterClick={actions.setEntryValidityFilter} />
          <BookIndexValidation onValidateClick={actions.validateEntries} />

            <BookList
                books={books}
                onItemClick={actions.selectBook}
                selectedBookId={selectedBookId} />

            <Catalog bookId={selectedBookId} bookPages={bookPages} entries={entries} />

        <FileAdder
            settings={settings}
            onNewBookCreated={newBookName => actions.addNewBookName(newBookName)}
            onFileCopied={this.handleFileCopied} />

    );
  }
}

const BookIndexFilter = ({onWithEntryFilterClick, onEntryValidityFilterClick, selectedBookId}) => (

    <FilterRadioGroup
        disabled={!selectedBookId}
        onChange={onWithEntryFilterClick}
        values={['off', 'with', 'without']}
        labels={['Off', 'With entries', 'No entries']} />
    <FilterRadioGroup
        disabled={!selectedBookId}
        onChange={onEntryValidityFilterClick}
        values={['off', 'valid', 'invalid', 'placeholder']}
        labels={['Off', 'With valid entries', 'With invalid entries', 'With placeholder']} />

)

const FilterRadioGroup = ({values, labels, onChange, disabled}) => (
  <RadioButtonGroup style={{flex: 1}}
      name={values[0]}
      onChange={(e, value) => onChange(value)}
      defaultSelected={values[0]}>
    {values.map((value, i) => {
      return <RadioButton
          disabled={disabled}
          key={value}
          value={value} label={labels[i]}
          style={{marginBottom: 12}} />
    })}
  </RadioButtonGroup>
)

const BookIndexValidation = ({onValidateClick}) => (

    <RaisedButton
        label="validate entries"
        style={{margin: 12}}
        onClick={onValidateClick} />

)

const BookList = ({books, onItemClick, selectedBookId}) => (
  <List>
    {_.map(books, (book, bookId) => {
      const backgroundColor = selectedBookId === bookId ? grey300 : null
      return <ListItem
        key={bookId}
        style={{backgroundColor}}
        onClick={() => onItemClick(bookId)}
        primaryText={bookId}
        secondaryText={`${Object.keys(book).length} pages`} />
    })}
  </List>
)

function mapStateToProps(state) {
  const {app, settings} = state
  const {selectedBookId, withEntryFilterValue, entryValidityFilterValue} = state.app
  const {books, entries} = state.catalog

  const bookPages = _.values(books[selectedBookId]).filter(page => {

    let withEntryFilter
    if (withEntryFilterValue === 'with') {
      withEntryFilter = page.entries.length
    } else if (withEntryFilterValue === 'without') {
      withEntryFilter = !page.entries.length
    } else if (withEntryFilterValue === 'off') {
      withEntryFilter = true
    } else {
      throw 'Invalid value'
    }

    let entryValidityFilter
    if (entryValidityFilterValue === 'valid') {
      entryValidityFilter = page.entries.some(entryId => {
        const entry = entries[entryId]
        return entry.isValidated && entry.isValid
      })
    } else if (entryValidityFilterValue === 'invalid') {
      entryValidityFilter = page.entries.some(entryId => {
        const entry = entries[entryId]
        return entry.isValidated && !entry.isValid
      })
    } else if (entryValidityFilterValue === 'placeholder') {
      entryValidityFilter = page.entries.some(entryId => {
        return entries[entryId].isPlaceholder
      })
    } else if (entryValidityFilterValue === 'off') {
      entryValidityFilter = true
    } else {
      throw 'Invalid value'
    }

    return withEntryFilter && entryValidityFilter
  })
  return {app, books, bookPages, entries, selectedBookId, settings}
}

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators({...appActions, ...mixedActions}, dispatch)
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(HomePage)
<commit_msg>Fix getSchema<commit_after>import React, { Component } from 'react';
import {connect} from 'react-redux'
import {bindActionCreators} from 'redux'
import path from 'path'
import Catalog from '../components/Catalog';
import FileAdder from '../components/FileAdder';
import * as mixedActions from '../actions/actions'
import {getSchema} from '../store/schema'
import {List, ListItem} from 'material-ui/List';
import RaisedButton from 'material-ui/RaisedButton';
import {RadioButton, RadioButtonGroup} from 'material-ui/RadioButton';
import * as appActions from '../actions/app'
import _ from 'underscore'
import PropTypes from 'prop-types';
import {grey300} from 'material-ui/styles/colors';
import BusyDialog from '../components/BusyDialog'
import SettingsDialog from '../components/SettingsDialog'
import storage from 'electron-json-storage';
import {initWithPath} from '../store/schema'
import fs from 'fs-extra'

class HomePage extends Component {

  constructor(props) {
    super(props)
    this.state = {
      isCatalogPathInvalid: false,
      isFormsPathInvalid: false,
      isSettingsLoaded: false,
    }

    storage.get('settings', (error, settings) => {
      if (error) throw error;
      const isCatalogPathInvalid = !fs.existsSync(settings.path)
      const isFormsPathInvalid = !fs.existsSync(settings.formsPath)
      if (isCatalogPathInvalid || isFormsPathInvalid) {
        this.setState({
          isCatalogPathInvalid,
          isFormsPathInvalid,
          stateSettings: settings,
        })
        return
      }
      this.setSettingsAndLoadCatalog(settings)
    })
  }

  setSettingsAndLoadCatalog = settings => {
    const {actions} = this.props
    actions.setSettings(settings)
    initWithPath(settings.formsPath)
    actions.loadCatalog(settings.path)
    this.setState({
      isSettingsLoaded: true,
      isCatalogPathInvalid: false,
      isFormsPathInvalid: false,
    })
  }

  handleFileCopied = (bookId, newPage) => {
    const {actions, settings} = this.props
    actions.addPage(bookId, newPage)
  }

  render() {
    const {actions, app, bookPages, books, entries, selectedBookId, settings} = this.props
    const {isCatalogPathInvalid, isFormsPathInvalid, stateSettings, isSettingsLoaded} = this.state
    const invalidPath = isCatalogPathInvalid || isFormsPathInvalid
    const isSettingsDialogOpen = isSettingsLoaded && !settings.path || invalidPath
    const headerStyle = {
      position: 'absolute',
      top: 0,
      display: 'flex',
      justifyContent: 'space-between',
      alignItems: 'center',
      height: 200,
      padding: 20,
    }
    const mainStyle = {
      top: 200,
      bottom: 0,
      position: 'absolute',
      left: 0,
      right: 0,
      display: 'flex',
    }
    return (

        <SettingsDialog
            isOpen={isSettingsDialogOpen}
            settings={invalidPath ?  stateSettings : settings}
            isCatalogPathInvalid={isCatalogPathInvalid}
            isFormsPathInvalid={isFormsPathInvalid}
            onSaveSettings={this.setSettingsAndLoadCatalog} />
        <BusyDialog
            isOpen={app.isValidating} />

{Object.keys(books).length} Books

          <BookIndexFilter
              selectedBookId={selectedBookId}
              onWithEntryFilterClick={actions.setWithEntryFilter}
              onEntryValidityFilterClick={actions.setEntryValidityFilter} />
          <BookIndexValidation onValidateClick={actions.validateEntries} />

            <BookList
                books={books}
                onItemClick={actions.selectBook}
                selectedBookId={selectedBookId} />

            <Catalog bookId={selectedBookId} bookPages={bookPages} entries={entries} />

        <FileAdder
            settings={settings}
            onNewBookCreated={newBookName => actions.addNewBookName(newBookName)}
            onFileCopied={this.handleFileCopied} />

    );
  }
}

const BookIndexFilter = ({onWithEntryFilterClick, onEntryValidityFilterClick, selectedBookId}) => (

    <FilterRadioGroup
        disabled={!selectedBookId}
        onChange={onWithEntryFilterClick}
        values={['off', 'with', 'without']}
        labels={['Off', 'With entries', 'No entries']} />
    <FilterRadioGroup
        disabled={!selectedBookId}
        onChange={onEntryValidityFilterClick}
        values={['off', 'valid', 'invalid', 'placeholder']}
        labels={['Off', 'With valid entries', 'With invalid entries', 'With placeholder']} />

)

const FilterRadioGroup = ({values, labels, onChange, disabled}) => (
  <RadioButtonGroup style={{flex: 1}}
      name={values[0]}
      onChange={(e, value) => onChange(value)}
      defaultSelected={values[0]}>
    {values.map((value, i) => {
      return <RadioButton
          disabled={disabled}
          key={value}
          value={value} label={labels[i]}
          style={{marginBottom: 12}} />
    })}
  </RadioButtonGroup>
)

const BookIndexValidation = ({onValidateClick}) => (

    <RaisedButton
        label="validate entries"
        style={{margin: 12}}
        onClick={onValidateClick} />

)

const BookList = ({books, onItemClick, selectedBookId}) => (
  <List>
    {_.map(books, (book, bookId) => {
      const backgroundColor = selectedBookId === bookId ? grey300 : null
      return <ListItem
        key={bookId}
        style={{backgroundColor}}
        onClick={() => onItemClick(bookId)}
        primaryText={bookId}
        secondaryText={`${Object.keys(book).length} pages`} />
    })}
  </List>
)

function mapStateToProps(state) {
  const {app, settings} = state
  const {selectedBookId, withEntryFilterValue, entryValidityFilterValue} = state.app
  const {books, entries} = state.catalog

  const bookPages = _.values(books[selectedBookId]).filter(page => {

    let withEntryFilter
    if (withEntryFilterValue === 'with') {
      withEntryFilter = page.entries.length
    } else if (withEntryFilterValue === 'without') {
      withEntryFilter = !page.entries.length
    } else if (withEntryFilterValue === 'off') {
      withEntryFilter = true
    } else {
      throw 'Invalid value'
    }

    let entryValidityFilter
    if (entryValidityFilterValue === 'valid') {
      entryValidityFilter = page.entries.some(entryId => {
        const entry = entries[entryId]
        return entry.isValidated && entry.isValid
      })
    } else if (entryValidityFilterValue === 'invalid') {
      entryValidityFilter = page.entries.some(entryId => {
        const entry = entries[entryId]
        return entry.isValidated && !entry.isValid
      })
    } else if (entryValidityFilterValue === 'placeholder') {
      entryValidityFilter = page.entries.some(entryId => {
        return entries[entryId].isPlaceholder
      })
    } else if (entryValidityFilterValue === 'off') {
      entryValidityFilter = true
    } else {
      throw 'Invalid value'
    }

    return withEntryFilter && entryValidityFilter
  })
  return {app, books, bookPages, entries, selectedBookId, settings}
}

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators({...appActions, ...mixedActions}, dispatch)
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(HomePage)
<|endoftext|>


<commit_before>var mongoose = require('mongoose'),
    User = mongoose.model('User'),
    Account = mongoose.model('Account'),
    Assignment = mongoose.model('Assignment'),
    visTypes = require('./visTypes.js');

exports.view = function(req, res) {
    var assignmentNumber;

    var getUsername = function(users, usernames, cb) {
        if (users.length === 0) return cb(usernames);
        var user = users.pop();
        User
            .findOne({
                "email": user
            })
            .exec(function(err, user) {
                if (err) return null;
                if (user) usernames.push(user.username);
                getUsername(users, usernames, cb);
            });
    };

    var getAssignmentsEmailAndUsernameMap = function(users, usernamesmap, cb) {
        if (users.length === 0) return cb(usernamesmap);
        var user = users.pop();
        User
            .findOne({
                "email": user
            })
            .exec(function(err, user) {
                if (err) return null;
                if (user){
                  // usernames.push(user.username)
                  usernamesmap[user.email] = user.username;
                }
                getAssignmentsEmailAndUsernameMap(users, usernamesmap, cb);
            });
    };

    if (!req.params.assignmentNumber) {
      return next("No assignment number given");
    } else {
      assignmentNumber = req.params.assignmentNumber;

      Assignment
          .find({
              assignmentNumber: assignmentNumber,
              subAssignment: "00",
              shared: true
          }, {
              email: 1,
              assignmentID: 1,
              title: 1,
              description: 1,
              assignmentNumber: 1,
              "data.visual": 1,
              "data.dims": 1,
              vistype: 1,
              shared: 1,
              dateCreated: 1
          })
          .exec(function(err, assignmentResult) {

              if (err) return next(err);
              if (!assignmentResult) return next("could not find " +
                  "assignment " + req.params.assignmentNumber);

              if(assignmentResult.length === 0) {
                  return res.render('assignments/gallery', {
                      "title": "Assignment gallery",
                      "user":req.user,
                      "assignments": "",
                      "assignmentNumber":-1
                  });
              }

              if(assignmentResult.length <= 0) {
                  return res.redirect('/username/'+req.user.username);
              }

              var users = [];
              for (i = 0; i < assignmentResult.length; i++)
                  users.push(assignmentResult[i].email);

              var usernamesmap = {};
              getAssignmentsEmailAndUsernameMap(users, usernamesmap, function(usernamesmap) {

                  for(var assignmentResultItem in assignmentResult){
                      assignmentResult[assignmentResultItem]['username'] = usernamesmap[assignmentResult[assignmentResultItem]['email']];
                      var $thisVistype = visTypes.getVisType(assignmentResult[assignmentResultItem]['data'][0]['visual']);
                      if($thisVistype == "Alist") $thisVistype = visTypes.checkIfHasDims(assignmentResult[assignmentResultItem]['data'][0]);
                      assignmentResult[assignmentResultItem]['vistype'] = $thisVistype;
                  }

                  assignmentResult.sort(function(a, b) {
                      return Date.parse(b.dateCreated) - Date.parse(a.dateCreated);
                      // return parseFloat(a.assignmentID) - parseFloat(b.assignmentID);
                  });

                  return res.render('assignments/gallery', {
                      "title": "Assignment gallery",
                      "user":req.user,
                      "assignmentNumber":req.params.assignmentNumber,
                      "assignments":assignmentResult
                  });
              });
          });
        }
};

exports.recentUploads = function(req, res) {
  Assignment
      .find({
        shared: true,
        subAssignment: "00"
      }, {
          _id: 0,
          email: 1,
          assignmentID: 1,
          title: 1,
          description: 1,
          assignmentNumber: 1,
          "data.visual": 1,
          "data.dims": 1,
          vistype: 1,
          shared: 1,
          dateCreated: 1
      })
      .sort({"dateCreated": -1})
      .limit(5)
      .exec(function(err, recentAssigns) {
          if (err) return next(err);
          if (!recentAssigns) return next("error obtaining recent assignment data");
          res.send(recentAssigns);
      });

};
<commit_msg>Exclude developers assignments to be shown in the latest feeds.<commit_after>var mongoose = require('mongoose'),
    User = mongoose.model('User'),
    Account = mongoose.model('Account'),
    Assignment = mongoose.model('Assignment'),
    visTypes = require('./visTypes.js');

exports.view = function(req, res) {
    var assignmentNumber;

    var getUsername = function(users, usernames, cb) {
        if (users.length === 0) return cb(usernames);
        var user = users.pop();
        User
            .findOne({
                "email": user
            })
            .exec(function(err, user) {
                if (err) return null;
                if (user) usernames.push(user.username);
                getUsername(users, usernames, cb);
            });
    };

    var getAssignmentsEmailAndUsernameMap = function(users, usernamesmap, cb) {
        if (users.length === 0) return cb(usernamesmap);
        var user = users.pop();
        User
            .findOne({
                "email": user
            })
            .exec(function(err, user) {
                if (err) return null;
                if (user){
                  // usernames.push(user.username)
                  usernamesmap[user.email] = user.username;
                }
                getAssignmentsEmailAndUsernameMap(users, usernamesmap, cb);
            });
    };

    if (!req.params.assignmentNumber) {
      return next("No assignment number given");
    } else {
      assignmentNumber = req.params.assignmentNumber;

      Assignment
          .find({
              assignmentNumber: assignmentNumber,
              subAssignment: "00",
              shared: true
          }, {
              email: 1,
              assignmentID: 1,
              title: 1,
              description: 1,
              assignmentNumber: 1,
              "data.visual": 1,
              "data.dims": 1,
              vistype: 1,
              shared: 1,
              dateCreated: 1
          })
          .exec(function(err, assignmentResult) {

              if (err) return next(err);
              if (!assignmentResult) return next("could not find " +
                  "assignment " + req.params.assignmentNumber);

              if(assignmentResult.length === 0) {
                  return res.render('assignments/gallery', {
                      "title": "Assignment gallery",
                      "user":req.user,
                      "assignments": "",
                      "assignmentNumber":-1
                  });
              }

              if(assignmentResult.length <= 0) {
                  return res.redirect('/username/'+req.user.username);
              }

              var users = [];
              for (i = 0; i < assignmentResult.length; i++)
                  users.push(assignmentResult[i].email);

              var usernamesmap = {};
              getAssignmentsEmailAndUsernameMap(users, usernamesmap, function(usernamesmap) {

                  for(var assignmentResultItem in assignmentResult){
                      assignmentResult[assignmentResultItem]['username'] = usernamesmap[assignmentResult[assignmentResultItem]['email']];
                      var $thisVistype = visTypes.getVisType(assignmentResult[assignmentResultItem]['data'][0]['visual']);
                      if($thisVistype == "Alist") $thisVistype = visTypes.checkIfHasDims(assignmentResult[assignmentResultItem]['data'][0]);
                      assignmentResult[assignmentResultItem]['vistype'] = $thisVistype;
                  }

                  assignmentResult.sort(function(a, b) {
                      return Date.parse(b.dateCreated) - Date.parse(a.dateCreated);
                      // return parseFloat(a.assignmentID) - parseFloat(b.assignmentID);
                  });

                  return res.render('assignments/gallery', {
                      "title": "Assignment gallery",
                      "user":req.user,
                      "assignmentNumber":req.params.assignmentNumber,
                      "assignments":assignmentResult
                  });
              });
          });
        }
};

exports.recentUploads = function(req, res) {
  Assignment
      .find({
        shared: true,
        subAssignment: "00",
        email: {$nin : ["lestrell@uncc.edu", "mmehedin@uncc.edu", "krs@uncc.edu"]}
      }, {
          _id: 0,
          email: 1,
          assignmentID: 1,
          title: 1,
          description: 1,
          assignmentNumber: 1,
          "data.visual": 1,
          "data.dims": 1,
          vistype: 1,
          shared: 1,
          dateCreated: 1
      })
      .sort({"dateCreated": -1})
      .limit(5)
      .exec(function(err, recentAssigns) {
          if (err) return next(err);
          if (!recentAssigns) return next("error obtaining recent assignment data");
          res.send(recentAssigns);
      });

};
<|endoftext|>


<commit_before>
/*!
 * Module dependencies.
 */

var _ = require('lodash');
var multiparty = require('multiparty');
var knox = require('knox');
var randomstring = require('randomstring');
var path = require('path');
var easyimage = require('easyimage');
var async = require('async');
var models = require('../models');
var Q = require('q');

var s3Client = knox.createClient({
    secure: false,
    key: process.env.S3_KEY,
    secret: process.env.S3_SECRET,
    bucket: process.env.S3_BUCKET,
});

exports.index = function (req, res, next) {

    models.Session.findAll({
        order: '"createdAt" DESC'
    }).then(function(sessions) {
        res.render('session/index', {
            sessions: sessions
        });
    }).error(next);
};

exports.feed = function (req, res, next) {

    var sessionId = req.params.sid;
    var Session = models.Session;
    var VisualizationType = models.VisualizationType;
    var Visualization = models.Visualization;

    Q.all([
        Session
            .find({
                where: {
                    id: sessionId
                }
            }),
        Visualization
            .findAll({
                where: {
                    SessionId: sessionId
                }
            }),
        VisualizationType.findAll()
    ]).spread(function(session, visualizations, vizTypes) {

        if(!session) {
            return res.status(404).send('Session not found');
        }

        _.each(visualizations, function(viz) {
            console.log(viz.images);
        });

        res.render('session/feed', {
            session: session,
            visualizations: visualizations,
            vizTypes: _.object(_.map(vizTypes, function(item) {
                return [item.name, item];
            }))
        });
    }).fail(next);
};

exports.update = function (req, res, next) {

    var sessionId = req.params.sid;
    var Session = models.Session;

    Session
        .update(req.body, {
            id: sessionId
        }).success(function(sessions) {
            return res.json(sessions);
        }).error(next);

};
exports.updateVisualization = function (req, res, next) {

    var vid = req.params.vid;
    var Visualization = models.Visualization;

    console.log('updating visualization ' + vid);

    Visualization
        .update(req.body, {
            id: vid
        }).success(function(visualizations) {
            return res.status(200).send();
        }).error(function(err) {
            console.log(err);
            return res.status(500).send();
        });

};

exports.read = function (req, res, next) {

    var vizId = req.params.vid;
    var Visualization = models.Visualization;
    var VisualizationType = models.VisualizationType;

    Q.all([
        Visualization.find(vizId),
        VisualizationType.findAll()
    ]).spread(function(viz, vizTypes) {
            res.render('session/visualization', {
                viz: viz,
                vizTypes: _.object(_.map(vizTypes, function(item) {
                    return [item.name, item];
                }))
            });
    }).fail(next);
};

exports.create = function(req, res, next) {

    models.Session
        .create(_.pick(req.body, 'name'))
        .then(function(session) {
            return res.json(session);
        }).error(next);
};

exports.getCreate = function(req, res, next) {
    models.Session
        .create()
        .then(function(session) {
            return res.redirect('/sessions/' + session.id + '/feed/');
        }).error(next);
};

exports.delete = function(req, res, next) {
    var sessionId = req.params.sid;

    models.Session
        .find(sessionId)
        .then(function(session) {
            session.destroy().success(function() {
                return res.json(session);
            }).error(next);
        }).error(next);
};

exports.getDelete = function(req, res, next) {

    var sessionId = req.params.sid;

    models.Session
        .find(sessionId)
        .then(function(session) {
            session.destroy().success(function() {
                return res.redirect('/sessions/');
            }).error(next);
        }).error(next);
};

exports.addData = function (req, res, next) {
    var sessionId = req.params.sid;

    var Visualization = models.Visualization;

    if(req.is('json')) {
        Visualization
            .create({
                data: req.body.data,
                type: req.body.type,
                SessionId: sessionId
            }).then(function(viz) {
                req.io.of('/sessions/' + sessionId)
                    .emit('viz', viz);
                return res.json(viz);
            }).error(next);
    } else {
        var form = new multiparty.Form();

        form.parse(req, function(err, fields, files) {

            _.each(files, function(f) {
                thumbnailAndUpload(f, sessionId, function(err, data) {

                    if(err) {
                        console.log('error in thumbnailAndUpload');
                        return res.status(500).send();
                    }

                    var imgData = data.imgData;

                    console.log(imgData);

                    var type = 'image';
                    if(fields.type) {
                        if(_.isArray(fields.type) || _.isObject(fields.type)) {
                            type = fields.type[0];
                        } else {
                            type = fields.type;
                        }
                    }

                    Visualization
                        .create({
                            type:  type,
                            images: [imgData],
                            SessionId: sessionId
                        }).then(function(viz) {
                            req.io.of('/sessions/' + sessionId)
                                .emit('viz', viz);

                            return res.json(viz);
                        }).error(next);
                });
            });
        });
    }
};

exports.getData = function (req, res, next) {
    var vizId = req.params.vid;

    var Visualization = models.Visualization;

    Visualization
        .find(vizId)
        .then(function(viz) {
            return res.json({
                data: viz.data
            });
        }).error(next);
};

exports.getDataField = function (req, res, next) {

    var vizId = req.params.vid;
    var fieldName = req.params.field;

    console.log('getting data field ' + fieldName);

    models.Visualization
        .getNamedObjectForVisualization(vizId, fieldName)
        .then(function(data) {
            return res.json({
                data: data
            });
        }).error(next);
};

exports.getDataAtIndex = function (req, res, next) {

    var vizId = req.params.vid;
    var fieldName = req.params.field;
    var index = req.params.index;

    models.Visualization
        .getNamedObjectAtIndexForVisualization(vizId, fieldName, index)
        .then(function(data) {
            return res.json({
                data: data[0][fieldName]
            });
        }).error(next);
};

exports.updateData = function (req, res, next) {

    var vizId = req.params.vid;
    var fieldName = req.params.field;

    models.Visualization
        .find(vizId)
        .then(function(viz) {

            if(fieldName) {
                viz.data[fieldName] = req.body.data;
            } else {
                viz.data = req.body.data;
            }

            viz.save()
                .then(function() {
                    return res.json(viz);
                }).error(next);
        }).error(next);
};

exports.appendData = function (req, res, next) {

    var sessionId = req.params.sid;
    var vizId = req.params.vid;
    var fieldName = req.params.field;

    models.Visualization
        .find(vizId)
        .then(function(viz) {
            if(req.is('json')) {

                if(fieldName) {

                    if(_.isArray(viz.data[fieldName])) {
                        viz.data[fieldName].push(req.body.data);
                    } else if(_.isUndefined(viz.data[fieldName])) {
                        console.log(fieldName);
                        viz.data[fieldName] = req.body.data;
                    } else {
                        console.log('unknown field');
                    }
                } else {
                    if(_.isArray(viz.data)) {
                        viz.data.push(req.body.data);
                    } else if(_.isUndefined(viz.data)) {
                        viz.data = req.body.data;
                    } else {
                        console.log('unknown field');
                    }
                }

                viz
                    .save()
                    .then(function() {
                        return res.json(viz);
                    }).error(next);

            } else if(fieldName === 'images') {

                var form = new multiparty.Form();

                form.parse(req, function(err, fields, files) {
                    _.each(files, function(f) {
                        thumbnailAndUpload(f, sessionId, function(err, data) {

                            if(err) {
                                console.log('error in thumbnailAndUpload');
                                return res.status(500).send();
                            }
                            var imgData = data.imgData;
                            var s3Response = data.response;

                            if(viz.images) {
                                viz.images.push(imgData);
                            } else {
                                viz.images = [imgData];
                            }
                            viz
                                .save()
                                .then(function() {
                                    res.statusCode = s3Response.statusCode;
                                    s3Response.pipe(res);
                                });

                            req.io.of('/sessions/' + sessionId)
                                .emit('update', {
                                    vizId: viz.id,
                                    data: imgData
                                });

                        });
                    });
                });
            } else {
                return next(500);
            }

        }).error(next);

};

var thumbnailAndUpload = function(f, sessionId, callback) {

    var maxWidth = 500;
    var maxHeight = 500;

    // Image file info
    var imgPath = f[0].path;
    var extension = path.extname(imgPath).toLowerCase();
    var filenameWithoutExtension = path.basename(imgPath, extension);

    var thumbnailPath;

    if(process.env.NODE_ENV === 'production') {
        thumbnailPath = path.resolve(__dirname + '/../../'  + './tmp/' + filenameWithoutExtension + '_thumbnail' + extension);
    } else {
        thumbnailPath = path.dirname(imgPath) + filenameWithoutExtension + '_thumbnail' + extension;
    }

    // Upload paths for s3
    var uploadName = randomstring.generate();
    var destPath = '/sessions/' + sessionId + '/';
    var originalS3Path = destPath + uploadName;
    var thumbnailS3Path = destPath + uploadName + '_small';

    // s3 headers
    var headers = {
      'x-amz-acl': 'public-read',
    };
    if( extension === '.jpg' || extension === '.jpeg' ) {
        headers['Content-Type'] = 'image/jpeg';
    } else if (extension === '.png') {
        headers['Content-Type'] = 'image/png';
    }

    easyimage
        .info(imgPath)
        .then(function(file) {
            var thumbWidth;
            var thumbHeight;

            console.log('outputing to: ' + thumbnailPath);

            if(file.width > file.height) {
                thumbWidth = Math.min(maxWidth, file.width);
                thumbHeight = file.height * (thumbWidth / file.width);
            } else {
                thumbHeight = Math.min(maxHeight, file.height);
                thumbWidth = file.width * (thumbHeight / file.height);
            }

            return easyimage.resize({
                src: imgPath,
                dst: thumbnailPath,
                width: thumbWidth,
                height: thumbHeight
            });
        }).then(function() {
            async.parallel([
                function(callback) {
                    console.log(imgPath + ':' + originalS3Path);
                    s3Client.putFile(imgPath, originalS3Path, headers, callback);
                },
                function(callback) {
                    console.log(thumbnailPath + ':' + thumbnailS3Path);
                    s3Client.putFile(thumbnailPath, thumbnailS3Path, headers, callback);
                }
            ], function(err, results) {
                var s3Response = results[0];

                var imgURL = 'https://s3.amazonaws.com/' + process.env.S3_BUCKET + originalS3Path;
                // var thumbURL = 'https://s3.amazonaws.com/' + process.env.S3_BUCKET + thumbnailS3Path;

                var imgData = imgURL;

                callback(null, {
                    response: s3Response,
                    imgData: imgData
                });

            });
        }, function(err) {
            console.log(err);
            callback(err);
        });
};<commit_msg>Allow appending of data array<commit_after>
/*!
 * Module dependencies.
 */

var _ = require('lodash');
var multiparty = require('multiparty');
var knox = require('knox');
var randomstring = require('randomstring');
var path = require('path');
var easyimage = require('easyimage');
var async = require('async');
var models = require('../models');
var Q = require('q');

var s3Client = knox.createClient({
    secure: false,
    key: process.env.S3_KEY,
    secret: process.env.S3_SECRET,
    bucket: process.env.S3_BUCKET,
});

exports.index = function (req, res, next) {

    models.Session.findAll({
        order: '"createdAt" DESC'
    }).then(function(sessions) {
        res.render('session/index', {
            sessions: sessions
        });
    }).error(next);
};

exports.feed = function (req, res, next) {

    var sessionId = req.params.sid;
    var Session = models.Session;
    var VisualizationType = models.VisualizationType;
    var Visualization = models.Visualization;

    Q.all([
        Session
            .find({
                where: {
                    id: sessionId
                }
            }),
        Visualization
            .findAll({
                where: {
                    SessionId: sessionId
                }
            }),
        VisualizationType.findAll()
    ]).spread(function(session, visualizations, vizTypes) {

        if(!session) {
            return res.status(404).send('Session not found');
        }

        _.each(visualizations, function(viz) {
            console.log(viz.images);
        });

        res.render('session/feed', {
            session: session,
            visualizations: visualizations,
            vizTypes: _.object(_.map(vizTypes, function(item) {
                return [item.name, item];
            }))
        });
    }).fail(next);
};

exports.update = function (req, res, next) {

    var sessionId = req.params.sid;
    var Session = models.Session;

    Session
        .update(req.body, {
            id: sessionId
        }).success(function(sessions) {
            return res.json(sessions);
        }).error(next);

};
exports.updateVisualization = function (req, res, next) {

    var vid = req.params.vid;
    var Visualization = models.Visualization;

    console.log('updating visualization ' + vid);

    Visualization
        .update(req.body, {
            id: vid
        }).success(function(visualizations) {
            return res.status(200).send();
        }).error(function(err) {
            console.log(err);
            return res.status(500).send();
        });

};

exports.read = function (req, res, next) {

    var vizId = req.params.vid;
    var Visualization = models.Visualization;
    var VisualizationType = models.VisualizationType;

    Q.all([
        Visualization.find(vizId),
        VisualizationType.findAll()
    ]).spread(function(viz, vizTypes) {
            res.render('session/visualization', {
                viz: viz,
                vizTypes: _.object(_.map(vizTypes, function(item) {
                    return [item.name, item];
                }))
            });
    }).fail(next);
};

exports.create = function(req, res, next) {

    models.Session
        .create(_.pick(req.body, 'name'))
        .then(function(session) {
            return res.json(session);
        }).error(next);
};

exports.getCreate = function(req, res, next) {
    models.Session
        .create()
        .then(function(session) {
            return res.redirect('/sessions/' + session.id + '/feed/');
        }).error(next);
};

exports.delete = function(req, res, next) {
    var sessionId = req.params.sid;

    models.Session
        .find(sessionId)
        .then(function(session) {
            session.destroy().success(function() {
                return res.json(session);
            }).error(next);
        }).error(next);
};

exports.getDelete = function(req, res, next) {

    var sessionId = req.params.sid;

    models.Session
        .find(sessionId)
        .then(function(session) {
            session.destroy().success(function() {
                return res.redirect('/sessions/');
            }).error(next);
        }).error(next);
};

exports.addData = function (req, res, next) {
    var sessionId = req.params.sid;

    var Visualization = models.Visualization;

    if(req.is('json')) {
        Visualization
            .create({
                data: req.body.data,
                type: req.body.type,
                SessionId: sessionId
            }).then(function(viz) {
                req.io.of('/sessions/' + sessionId)
                    .emit('viz', viz);
                return res.json(viz);
            }).error(next);
    } else {
        var form = new multiparty.Form();

        form.parse(req, function(err, fields, files) {

            _.each(files, function(f) {
                thumbnailAndUpload(f, sessionId, function(err, data) {

                    if(err) {
                        console.log('error in thumbnailAndUpload');
                        return res.status(500).send();
                    }

                    var imgData = data.imgData;

                    console.log(imgData);

                    var type = 'image';
                    if(fields.type) {
                        if(_.isArray(fields.type) || _.isObject(fields.type)) {
                            type = fields.type[0];
                        } else {
                            type = fields.type;
                        }
                    }

                    Visualization
                        .create({
                            type:  type,
                            images: [imgData],
                            SessionId: sessionId
                        }).then(function(viz) {
                            req.io.of('/sessions/' + sessionId)
                                .emit('viz', viz);

                            return res.json(viz);
                        }).error(next);
                });
            });
        });
    }
};

exports.getData = function (req, res, next) {
    var vizId = req.params.vid;

    var Visualization = models.Visualization;

    Visualization
        .find(vizId)
        .then(function(viz) {
            return res.json({
                data: viz.data
            });
        }).error(next);
};

exports.getDataField = function (req, res, next) {

    var vizId = req.params.vid;
    var fieldName = req.params.field;

    console.log('getting data field ' + fieldName);

    models.Visualization
        .getNamedObjectForVisualization(vizId, fieldName)
        .then(function(data) {
            return res.json({
                data: data
            });
        }).error(next);
};

exports.getDataAtIndex = function (req, res, next) {

    var vizId = req.params.vid;
    var fieldName = req.params.field;
    var index = req.params.index;

    models.Visualization
        .getNamedObjectAtIndexForVisualization(vizId, fieldName, index)
        .then(function(data) {
            return res.json({
                data: data[0][fieldName]
            });
        }).error(next);
};

exports.updateData = function (req, res, next) {

    var vizId = req.params.vid;
    var fieldName = req.params.field;

    models.Visualization
        .find(vizId)
        .then(function(viz) {

            if(fieldName) {
                viz.data[fieldName] = req.body.data;
            } else {
                viz.data = req.body.data;
            }

            viz.save()
                .then(function() {
                    return res.json(viz);
                }).error(next);
        }).error(next);
};

exports.appendData = function (req, res, next) {

    var sessionId = req.params.sid;
    var vizId = req.params.vid;
    var fieldName = req.params.field;

    models.Visualization
        .find(vizId)
        .then(function(viz) {
            if(req.is('json')) {

                if(fieldName) {

                    if(_.isArray(viz.data[fieldName])) {
                        viz.data[fieldName].push(req.body.data);
                    } else if(_.isUndefined(viz.data[fieldName])) {
                        console.log(fieldName);
                        viz.data[fieldName] = req.body.data;
                    } else {
                        console.log('unknown field');
                    }
                } else {
                    if(_.isArray(viz.data)) {
                        if(_.isArray(req.body.data)) {
                            viz.data = viz.data.concat(req.body.data);
                            console.log(viz.data)
                        } else {
                            viz.data.push(req.body.data);
                        }
                    } else if(_.isUndefined(viz.data)) {
                        viz.data = req.body.data;
                    } else {
                        console.log('unknown field');
                    }
                }

                viz
                    .save()
                    .then(function() {
                        return res.json(viz);
                    }).error(next);

            } else if(fieldName === 'images') {

                var form = new multiparty.Form();

                form.parse(req, function(err, fields, files) {
                    _.each(files, function(f) {
                        thumbnailAndUpload(f, sessionId, function(err, data) {

                            if(err) {
                                console.log('error in thumbnailAndUpload');
                                return res.status(500).send();
                            }
                            var imgData = data.imgData;
                            var s3Response = data.response;

                            if(viz.images) {
                                viz.images.push(imgData);
                            } else {
                                viz.images = [imgData];
                            }
                            viz
                                .save()
                                .then(function() {
                                    res.statusCode = s3Response.statusCode;
                                    s3Response.pipe(res);
                                });

                            req.io.of('/sessions/' + sessionId)
                                .emit('update', {
                                    vizId: viz.id,
                                    data: imgData
                                });

                        });
                    });
                });
            } else {
                return next(500);
            }

        }).error(next);

};

var thumbnailAndUpload = function(f, sessionId, callback) {

    var maxWidth = 500;
    var maxHeight = 500;

    // Image file info
    var imgPath = f[0].path;
    var extension = path.extname(imgPath).toLowerCase();
    var filenameWithoutExtension = path.basename(imgPath, extension);

    var thumbnailPath;

    if(process.env.NODE_ENV === 'production') {
        thumbnailPath = path.resolve(__dirname + '/../../'  + './tmp/' + filenameWithoutExtension + '_thumbnail' + extension);
    } else {
        thumbnailPath = path.dirname(imgPath) + filenameWithoutExtension + '_thumbnail' + extension;
    }

    // Upload paths for s3
    var uploadName = randomstring.generate();
    var destPath = '/sessions/' + sessionId + '/';
    var originalS3Path = destPath + uploadName;
    var thumbnailS3Path = destPath + uploadName + '_small';

    // s3 headers
    var headers = {
      'x-amz-acl': 'public-read',
    };
    if( extension === '.jpg' || extension === '.jpeg' ) {
        headers['Content-Type'] = 'image/jpeg';
    } else if (extension === '.png') {
        headers['Content-Type'] = 'image/png';
    }

    easyimage
        .info(imgPath)
        .then(function(file) {
            var thumbWidth;
            var thumbHeight;

            console.log('outputing to: ' + thumbnailPath);

            if(file.width > file.height) {
                thumbWidth = Math.min(maxWidth, file.width);
                thumbHeight = file.height * (thumbWidth / file.width);
            } else {
                thumbHeight = Math.min(maxHeight, file.height);
                thumbWidth = file.width * (thumbHeight / file.height);
            }

            return easyimage.resize({
                src: imgPath,
                dst: thumbnailPath,
                width: thumbWidth,
                height: thumbHeight
            });
        }).then(function() {
            async.parallel([
                function(callback) {
                    console.log(imgPath + ':' + originalS3Path);
                    s3Client.putFile(imgPath, originalS3Path, headers, callback);
                },
                function(callback) {
                    console.log(thumbnailPath + ':' + thumbnailS3Path);
                    s3Client.putFile(thumbnailPath, thumbnailS3Path, headers, callback);
                }
            ], function(err, results) {
                var s3Response = results[0];

                var imgURL = 'https://s3.amazonaws.com/' + process.env.S3_BUCKET + originalS3Path;
                // var thumbURL = 'https://s3.amazonaws.com/' + process.env.S3_BUCKET + thumbnailS3Path;

                var imgData = imgURL;

                callback(null, {
                    response: s3Response,
                    imgData: imgData
                });

            });
        }, function(err) {
            console.log(err);
            callback(err);
        });
};<|endoftext|>


<commit_before>module.exports = function(ukiyoe, app) {

var Source = ukiyoe.db.model("Source"),
    Image = ukiyoe.db.model("Image"),
    utils = require("../../lib/utils"),
    _ = require("lodash"),
    sourceTypes = require("../../data/source-types.json"),
    sourceTypeMap = {},
    exports = {},
    numColumns = 4;

Source.prototype.getURL = function(locale) {
    return app.genURL(locale, "/source/" + this._id);
};

sourceTypes.forEach(function(type) {
    // Create a mapping for the source types
    sourceTypeMap[type.type] = type.name;
});

var clusterSource = function(source, cluster) {
    source.types.forEach(function(type) {
        if (!cluster[type]) {
            cluster[type] = [[]];
        }

        // Get most recently created row
        curRow = cluster[type][ cluster[type].length - 1 ];

        if (curRow.length === numColumns) {
            curRow = [];
            cluster[type].push(curRow);
        }

        curRow.push(source);
    });
};

exports.index = function(req, res) {
    Source.find({}, function(err, sources) {
        if (err) {
            return res.render("500");
        }

        var total = 0;
        var totalEstimated = 0;
        var activeSources = {};
        var estimatedSources = {};

        sources.forEach(function(source) {
            if (source.estNumPrints) {
                totalEstimated += source.estNumPrints;
                clusterSource(source, estimatedSources);
            } else {
                total += source.numPrints;
                clusterSource(source, activeSources);
            }
        });

        res.render("sources/index", {
            title: req.i18n.__("Sources of Japanese Woodblock Prints"),
            sourceTypes: sourceTypes,
            sourceTypeMap: sourceTypeMap,
            activeSources: activeSources,
            estimatedSources: estimatedSources,
            total: total,
            totalEstimated: totalEstimated
        });
    });
};

exports.show = function(req, res) {
    var page = (req.param("page") > 0 ? req.param("page") : 1) - 1;
    var perPage = 100;
    var q = req.param("q") || "";

    var query = {
        query_string: {
            // NOTE: There has got to be a better way to do this.
            query: "source:" + req.source._id
        },
        filtered: {
            filter: {},
            size: perPage,
            from: page * perPage,
        }
    };

    Image.search({query: query}, {hydrate: true, hydrateOptions: {populate: "artists.artist"}}, function(err, results){
        if (err) {
            console.error(err);
            return res.render("500");
        }

        res.render("images/index", {
            title: "Images",
            q: req.param("q"),
            startDate: req.param("startDate") || "1765",
            endDate: req.param("endDate") || "1868",
            images: results.hits,
            page: page + 1,
            pages: Math.ceil(results.total / perPage)
        });
    });
};

exports.load = function(req, res, next, id) {
    Source.findById(id, function(err, source) {
        if (err) {
            return next(err);
        }
        if (!source) {
            return next(new Error("not found"));
        }
        req.source = source;
        next();
    });
};

return exports;
};<commit_msg>Fix source query.<commit_after>module.exports = function(ukiyoe, app) {

var Source = ukiyoe.db.model("Source"),
    Image = ukiyoe.db.model("Image"),
    utils = require("../../lib/utils"),
    _ = require("lodash"),
    sourceTypes = require("../../data/source-types.json"),
    sourceTypeMap = {},
    exports = {},
    numColumns = 4;

Source.prototype.getURL = function(locale) {
    return app.genURL(locale, "/source/" + this._id);
};

sourceTypes.forEach(function(type) {
    // Create a mapping for the source types
    sourceTypeMap[type.type] = type.name;
});

var clusterSource = function(source, cluster) {
    source.types.forEach(function(type) {
        if (!cluster[type]) {
            cluster[type] = [[]];
        }

        // Get most recently created row
        curRow = cluster[type][ cluster[type].length - 1 ];

        if (curRow.length === numColumns) {
            curRow = [];
            cluster[type].push(curRow);
        }

        curRow.push(source);
    });
};

exports.index = function(req, res) {
    Source.find({}, function(err, sources) {
        if (err) {
            return res.render("500");
        }

        var total = 0;
        var totalEstimated = 0;
        var activeSources = {};
        var estimatedSources = {};

        sources.forEach(function(source) {
            if (source.estNumPrints) {
                totalEstimated += source.estNumPrints;
                clusterSource(source, estimatedSources);
            } else {
                total += source.numPrints;
                clusterSource(source, activeSources);
            }
        });

        res.render("sources/index", {
            title: req.i18n.__("Sources of Japanese Woodblock Prints"),
            sourceTypes: sourceTypes,
            sourceTypeMap: sourceTypeMap,
            activeSources: activeSources,
            estimatedSources: estimatedSources,
            total: total,
            totalEstimated: totalEstimated
        });
    });
};

exports.show = function(req, res) {
    var page = (req.param("page") > 0 ? req.param("page") : 1) - 1;
    var perPage = 100;
    var q = req.param("q") || "";

    var query = {
        term: {
            source: req.source._id.toString()
        },
        filtered: {
            filter: {},
            size: perPage,
            from: page * perPage,
        }
    };

    Image.search({query: query}, {hydrate: true, hydrateOptions: {populate: "artists.artist"}}, function(err, results){
        if (err) {
            console.error(err);
            return res.render("500");
        }

        res.render("images/index", {
            title: "Images",
            q: req.param("q"),
            startDate: req.param("startDate") || "1765",
            endDate: req.param("endDate") || "1868",
            images: results.hits,
            page: page + 1,
            pages: Math.ceil(results.total / perPage)
        });
    });
};

exports.load = function(req, res, next, id) {
    Source.findById(id, function(err, source) {
        if (err) {
            return next(err);
        }
        if (!source) {
            return next(new Error("not found"));
        }
        req.source = source;
        next();
    });
};

return exports;
};<|endoftext|>


<commit_before>import React from 'react';
import classNames from 'classnames';

import FlashesStore from '../../../stores/FlashesStore';

class Flash extends React.Component {
  static propTypes = {
    flash: React.PropTypes.shape({
      id: React.PropTypes.number.isRequired,
      type: React.PropTypes.string.isRequired,
      message: React.PropTypes.string.isRequired
    }),
    onRemoveClick: React.PropTypes.func.isRequired
  };

  render() {
    const classes = classNames("py2 px3 rounded flex items-center mb2 bg-gray", {
      "bg-red white": this.props.flash.type === FlashesStore.ERROR,
      "bg-green white": this.props.flash.type === FlashesStore.SUCCESS
    });

    return (

{this.props.flash.message}

        <button onClick={this.handleCloseClick} className="btn px2 mxn2" data-flash-close={true}>Close</button>

    );
  }

  handleCloseClick = () => {
    this.props.onRemoveClick(this.props.flash);
  };
}

export default Flash;
<commit_msg>Better colours (thanks @toolmantim!)<commit_after>import React from 'react';
import classNames from 'classnames';

import FlashesStore from '../../../stores/FlashesStore';

class Flash extends React.Component {
  static propTypes = {
    flash: React.PropTypes.shape({
      id: React.PropTypes.number.isRequired,
      type: React.PropTypes.string.isRequired,
      message: React.PropTypes.string.isRequired
    }),
    onRemoveClick: React.PropTypes.func.isRequired
  };

  render() {
    const classes = classNames("flex items-center mb2 border rounded border-dark-gray", {
      "border-red red": this.props.flash.type === FlashesStore.ERROR,
      "border-lime lime": this.props.flash.type === FlashesStore.SUCCESS
    });

    return (

{this.props.flash.message}

        <button className="btn px4 py3" onClick={this.handleCloseClick} data-flash-close={true}>Close</button>

    );
  }

  handleCloseClick = () => {
    this.props.onRemoveClick(this.props.flash);
  };
}

export default Flash;
<|endoftext|>


<commit_before>import { take, takeLatest, call, put, cancel, select } from 'redux-saga/effects'
import { LOCATION_CHANGE } from 'react-router-redux'
import api from 'services'
import { selectSearchKey } from './selectors'
import { PICTOGRAMS, pictograms, AUTOCOMPLETE, autocomplete } from './actions'

function* pictogramsGetData() {
  try {
    const searchText = yield select(selectSearchKey())
    const response = yield call(api.fetchPictograms, searchText)
    yield put(pictograms.success(response))
  } catch (error) {
    yield put(pictograms.failure(error.message))
  } finally {
    // When done, we tell Redux we're not in the middle of a request any more
    // yield put({type: SENDING_REQUEST, sending: false})
  }
}

function* autoCompleteGetData(action) {
  try {
    const { locale } = action.payload
    const response = yield call(api.keywords, locale)
    const { words } = response
    // order by lenght so autocomplete is better:
    words.sort((a, b) => (a.length - b.length))
    yield put(autocomplete.success(locale, words))
  } catch (error) {
    yield put(autocomplete.failure(error.message))
  } finally {
    // When done, we tell Redux we're not in the middle of a request any more
    // yield put({type: SENDING_REQUEST, sending: false})
  }
}

/**
 * Root saga manages watcher lifecycle
 */
export function* autoCompleteData() {
  const watcher = yield takeLatest(AUTOCOMPLETE.REQUEST, autoCompleteGetData)
  // Suspend execution until location changes
  yield take(LOCATION_CHANGE)
  yield cancel(watcher)
}

export function* pictogramsData() {
  const watcher = yield takeLatest(PICTOGRAMS.REQUEST, pictogramsGetData)
  // Suspend execution until location changes
  yield take(LOCATION_CHANGE)
  yield cancel(watcher)
}

// All sagas to be loaded
export default [pictogramsGetData, autoCompleteData]
<commit_msg>add coment<commit_after>import { take, takeLatest, call, put, cancel, select } from 'redux-saga/effects'
import { LOCATION_CHANGE } from 'react-router-redux'
import api from 'services'
import { selectSearchKey } from './selectors'
import { PICTOGRAMS, pictograms, AUTOCOMPLETE, autocomplete } from './actions'

function* pictogramsGetData() {
  try {
    // TODO: change using action as parameter!!!!!!!
    const searchText = yield select(selectSearchKey())
    const response = yield call(api.fetchPictograms, searchText)
    yield put(pictograms.success(response))
  } catch (error) {
    yield put(pictograms.failure(error.message))
  } finally {
    // When done, we tell Redux we're not in the middle of a request any more
    // yield put({type: SENDING_REQUEST, sending: false})
  }
}

function* autoCompleteGetData(action) {
  try {
    const { locale } = action.payload
    const response = yield call(api.keywords, locale)
    const { words } = response
    // order by lenght so autocomplete is better:
    words.sort((a, b) => (a.length - b.length))
    yield put(autocomplete.success(locale, words))
  } catch (error) {
    yield put(autocomplete.failure(error.message))
  } finally {
    // When done, we tell Redux we're not in the middle of a request any more
    // yield put({type: SENDING_REQUEST, sending: false})
  }
}

/**
 * Root saga manages watcher lifecycle
 */
export function* autoCompleteData() {
  const watcher = yield takeLatest(AUTOCOMPLETE.REQUEST, autoCompleteGetData)
  // Suspend execution until location changes
  yield take(LOCATION_CHANGE)
  yield cancel(watcher)
}

export function* pictogramsData() {
  const watcher = yield takeLatest(PICTOGRAMS.REQUEST, pictogramsGetData)
  // Suspend execution until location changes
  yield take(LOCATION_CHANGE)
  yield cancel(watcher)
}

// All sagas to be loaded
export default [pictogramsGetData, autoCompleteData]
<|endoftext|>


<commit_before>import queryString from 'query-string';
import React, { Component, PropTypes } from 'react';
import Button from 'react-bootstrap/lib/Button';
import Input from 'react-bootstrap/lib/Input';
import Modal from 'react-bootstrap/lib/Modal';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { updatePath } from 'redux-simple-router';

import { closeReservationInfoModal, selectReservationToEdit } from 'actions/uiActions';
import { putReservation } from 'actions/reservationActions';
import TimeRange from 'components/common/TimeRange';
import reservationInfoModalSelector from 'selectors/containers/reservationInfoModalSelector';
import { getName } from 'utils/DataUtils';
import { renderReservationStateLabel } from 'utils/renderUtils';

export class UnconnectedReservationInfoModal extends Component {
  constructor(props) {
    super(props);
    this.handleEdit = this.handleEdit.bind(this);
    this.handleSave = this.handleSave.bind(this);
  }

  handleEdit() {
    const { actions, reservationsToShow, resources } = this.props;
    const reservation = reservationsToShow.length ? reservationsToShow[0] : undefined;
    if (!reservation) {
      return;
    }
    const resource = reservation ? resources[reservationsToShow[0].resource] : {};
    const query = queryString.stringify({
      date: reservation.begin.split('T')[0],
      time: reservation.begin,
    });

    actions.selectReservationToEdit({ reservation, minPeriod: resource.minPeriod });
    actions.closeReservationInfoModal();
    actions.updatePath(`/resources/${reservation.resource}/reservation?${query}`);
  }

  handleSave() {
    const { actions, reservationsToShow } = this.props;
    const reservation = reservationsToShow.length ? reservationsToShow[0] : undefined;
    if (!reservation) {
      return;
    }
    const comments = this.refs.commentsInput.getValue();
    actions.putReservation(Object.assign({}, reservation, { comments }));
    actions.closeReservationInfoModal();
  }

  renderModalContent(reservation, resource) {
    if (!reservation) {
      return null;
    }

    return (

        {renderReservationStateLabel(reservation)}

Nimi:

{reservation.reserverName}

Puhelinnumero:

{reservation.reserverPhoneNumber}

Sähköposti:

{reservation.reserverEmailAddress}

Osoite:

            {reservation.reserverAddressStreet}, {reservation.reserverAddressZip} {reservation.reserverAddressCity}

Laskutusosoite:

            {reservation.billingAddressStreet}, {reservation.billingAddressZip} {reservation.billingAddressCity}

Yhdistys:

{reservation.company}

Y-tunnus:

{reservation.businessId}

Varauksen ajankohta:

<TimeRange begin={reservation.begin} end={reservation.end} />

Tila:

{getName(resource)}

Osallistujamäärä:

{reservation.numberOfParticipants}

Tilaisuuden kuvaus:

{reservation.eventDescription}

        <form>
          <Input
            defaultValue={reservation.comments}
            label="Kommentit:"
            placeholder="Varauksen mahdolliset lisätiedot"
            ref="commentsInput"
            rows={5}
            type="textarea"
          />
        </form>

    );
  }

  render() {
    const {
      actions,
      isEditingReservations,
      reservationsToShow,
      resources,
      show,
    } = this.props;

    const reservation = reservationsToShow.length ? reservationsToShow[0] : undefined;
    const resource = reservation ? resources[reservationsToShow[0].resource] : {};

    return (
      <Modal
        className="reservation-info-modal"
        onHide={actions.closeReservationInfoModal}
        show={show}
      >
        <Modal.Header closeButton>
          <Modal.Title>Varauksen tiedot</Modal.Title>
        </Modal.Header>

        <Modal.Body>
          {this.renderModalContent(reservation, resource)}
        </Modal.Body>

        <Modal.Footer>
          <Button
            bsStyle="default"
            onClick={actions.closeReservationInfoModal}
          >
            Takaisin
          </Button>
          <Button
            bsStyle="primary"
            onClick={this.handleEdit}
          >
            Muokkaa
          </Button>
          <Button
            bsStyle="success"
            disabled={isEditingReservations}
            onClick={this.handleSave}
            type="submit"
          >
            {isEditingReservations ? 'Tallennetaan...' : 'Tallenna'}
          </Button>
        </Modal.Footer>
      </Modal>
    );
  }
}

UnconnectedReservationInfoModal.propTypes = {
  actions: PropTypes.object.isRequired,
  isEditingReservations: PropTypes.bool.isRequired,
  reservationsToShow: PropTypes.array.isRequired,
  resources: PropTypes.object.isRequired,
  show: PropTypes.bool.isRequired,
};

function mapDispatchToProps(dispatch) {
  const actionCreators = {
    closeReservationInfoModal,
    putReservation,
    selectReservationToEdit,
    updatePath,
  };

  return { actions: bindActionCreators(actionCreators, dispatch) };
}

export default connect(reservationInfoModalSelector, mapDispatchToProps)(
  UnconnectedReservationInfoModal
);
<commit_msg>Improve address rendering on reservation info<commit_after>import queryString from 'query-string';
import React, { Component, PropTypes } from 'react';
import Button from 'react-bootstrap/lib/Button';
import Input from 'react-bootstrap/lib/Input';
import Modal from 'react-bootstrap/lib/Modal';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { updatePath } from 'redux-simple-router';

import { closeReservationInfoModal, selectReservationToEdit } from 'actions/uiActions';
import { putReservation } from 'actions/reservationActions';
import TimeRange from 'components/common/TimeRange';
import reservationInfoModalSelector from 'selectors/containers/reservationInfoModalSelector';
import { getName } from 'utils/DataUtils';
import { renderReservationStateLabel } from 'utils/renderUtils';

export class UnconnectedReservationInfoModal extends Component {
  constructor(props) {
    super(props);
    this.handleEdit = this.handleEdit.bind(this);
    this.handleSave = this.handleSave.bind(this);
  }

  getAddress(street, zip, city) {
    const ending = `${zip} ${city}`;
    if (street && (zip || city)) {
      return `${street}, ${ending}`;
    }
    return `${street} ${ending}`;
  }

  handleEdit() {
    const { actions, reservationsToShow, resources } = this.props;
    const reservation = reservationsToShow.length ? reservationsToShow[0] : undefined;
    if (!reservation) {
      return;
    }
    const resource = reservation ? resources[reservationsToShow[0].resource] : {};
    const query = queryString.stringify({
      date: reservation.begin.split('T')[0],
      time: reservation.begin,
    });

    actions.selectReservationToEdit({ reservation, minPeriod: resource.minPeriod });
    actions.closeReservationInfoModal();
    actions.updatePath(`/resources/${reservation.resource}/reservation?${query}`);
  }

  handleSave() {
    const { actions, reservationsToShow } = this.props;
    const reservation = reservationsToShow.length ? reservationsToShow[0] : undefined;
    if (!reservation) {
      return;
    }
    const comments = this.refs.commentsInput.getValue();
    actions.putReservation(Object.assign({}, reservation, { comments }));
    actions.closeReservationInfoModal();
  }

  renderModalContent(reservation, resource) {
    if (!reservation) {
      return null;
    }

    return (

        {renderReservationStateLabel(reservation)}

Nimi:

{reservation.reserverName}

Puhelinnumero:

{reservation.reserverPhoneNumber}

Sähköposti:

{reservation.reserverEmailAddress}

Osoite:

{this.getAddress(reservation.reserverAddressStreet, reservation.reserverAddressZip, reservation.reserverAddressCity)}

Laskutusosoite:

{this.getAddress(reservation.billingAddressStreet, reservation.billingAddressZip, reservation.billingAddressCity)}

Yhdistys:

{reservation.company}

Y-tunnus:

{reservation.businessId}

Varauksen ajankohta:

<TimeRange begin={reservation.begin} end={reservation.end} />

Tila:

{getName(resource)}

Osallistujamäärä:

{reservation.numberOfParticipants}

Tilaisuuden kuvaus:

{reservation.eventDescription}

        <form>
          <Input
            defaultValue={reservation.comments}
            label="Kommentit:"
            placeholder="Varauksen mahdolliset lisätiedot"
            ref="commentsInput"
            rows={5}
            type="textarea"
          />
        </form>

    );
  }

  render() {
    const {
      actions,
      isEditingReservations,
      reservationsToShow,
      resources,
      show,
    } = this.props;

    const reservation = reservationsToShow.length ? reservationsToShow[0] : undefined;
    const resource = reservation ? resources[reservationsToShow[0].resource] : {};

    return (
      <Modal
        className="reservation-info-modal"
        onHide={actions.closeReservationInfoModal}
        show={show}
      >
        <Modal.Header closeButton>
          <Modal.Title>Varauksen tiedot</Modal.Title>
        </Modal.Header>

        <Modal.Body>
          {this.renderModalContent(reservation, resource)}
        </Modal.Body>

        <Modal.Footer>
          <Button
            bsStyle="default"
            onClick={actions.closeReservationInfoModal}
          >
            Takaisin
          </Button>
          <Button
            bsStyle="primary"
            onClick={this.handleEdit}
          >
            Muokkaa
          </Button>
          <Button
            bsStyle="success"
            disabled={isEditingReservations}
            onClick={this.handleSave}
            type="submit"
          >
            {isEditingReservations ? 'Tallennetaan...' : 'Tallenna'}
          </Button>
        </Modal.Footer>
      </Modal>
    );
  }
}

UnconnectedReservationInfoModal.propTypes = {
  actions: PropTypes.object.isRequired,
  isEditingReservations: PropTypes.bool.isRequired,
  reservationsToShow: PropTypes.array.isRequired,
  resources: PropTypes.object.isRequired,
  show: PropTypes.bool.isRequired,
};

function mapDispatchToProps(dispatch) {
  const actionCreators = {
    closeReservationInfoModal,
    putReservation,
    selectReservationToEdit,
    updatePath,
  };

  return { actions: bindActionCreators(actionCreators, dispatch) };
}

export default connect(reservationInfoModalSelector, mapDispatchToProps)(
  UnconnectedReservationInfoModal
);
<|endoftext|>


<commit_before>#!/usr/bin/env node

var YUIConfig = {
    core: '3.2.0',
    //core: '3.3.0pr3',
    gallery: '2010.09.22',
    '2in3': '0.0.3'
};

var yui3 = require('yui3');

yui3.rls({
    //m: 'yui,loader,dd,widget,autocomplete,gallery-yql,yui2-datatable',
    m: 'dd,widget,autocomplete,gallery-yql,yui2-datatable',
    env: 'node,attribute',
    v: '3.2.0',
    gv: '2010.09.22',
    '2in3v': '0.0.3',
    filt: 'DEBUG',
}, function(files) {
    console.log('Callback..');
    console.log(files);
});

<commit_msg>Updated rls example<commit_after>#!/usr/bin/env node

var yui3 = require('yui3');
yui3.rls({
    m: 'yui,loader,dd,widget,autocomplete,gallery-yql,yui2-datatable',
    //m: 'dd,widget,autocomplete,gallery-yql,yui2-datatable',
    //env: 'node,attribute',
    v: '3.3.0pr3',
    gv: '2010.09.22',
    '2in3v': '0.0.3'//,
    //filt: 'RAW',
}, function(files) {
    console.log('Callback..');
    console.log(files);
});

<|endoftext|>


<commit_before>import {stopInfo, lineInfo, linesForStop, stopsForLine} from './ruter-fetcher';

import {
  GraphQLEnumType,
  GraphQLInterfaceType,
  GraphQLObjectType,
  GraphQLList,
  GraphQLNonNull,
  GraphQLSchema,
  GraphQLString,
  GraphQLInt,
  GraphQLFloat,
  GraphQLBoolean,
} from 'graphql';

const TransitType = new GraphQLEnumType({
    name: 'TransitType',
    description: 'One of the types of transit operated by ruter',
    values: {
        TRAM: {
            value: 7,
            description: 'Tram'
        },
        BUS: {
            value: 2,
            description: 'Bus'
        },
        SUBWAY: {
            value: 6,
            description: 'Subway'
        },
        FERRY: {
            value: 1,
            description: 'Ferry'
        }
    }
});

var GeoLocation = new GraphQLObjectType({
    name: 'GeoLocation',
    description: 'geo type',
    fields: {
        latitude: {
            type: GraphQLFloat,
            description: 'latitude'
        },
        longitude: {
            type: GraphQLFloat,
            description: 'longitude'
        }
    }
});

var Line = new GraphQLObjectType({
    name: 'Line',
    description: 'A public transit line',
    fields: () => ({
        id: {
            type: new GraphQLNonNull(GraphQLInt),
            description: 'The id of the line.',
        },
        name: {
            type: new GraphQLNonNull(GraphQLString),
            description: 'The name of the line.',
        },
        transitType: {
            type: new GraphQLNonNull(TransitType),
            description: 'The type or transport of the line.',
        },
        color: {
            type: new GraphQLNonNull(GraphQLString),
            description: 'The color of the line.',
        },
        stops: {
            type: new GraphQLList(new GraphQLNonNull(Stop)),
            description: 'Stops serviced by this line',
            resolve: ({id}, args, source) => stopsForLine(id)
        },
        endPoints: {
            type: GraphQLString,
            description: 'End points for line',
            resolve: ({id}) => stopsForLine(id).then(e => {
                return e[0].name + ' / ' + e[e.length - 1].name;
            })

        }
    }),
    interfaces: [ ]
});

var Stop = new GraphQLObjectType({
    name: 'Stop',
    description: 'A stop',
    fields: () => ({
        id: {
            type: new GraphQLNonNull(GraphQLInt),
            description: 'stop id'
        },
        name: {
            type: new GraphQLNonNull(GraphQLString),
            description: 'desc'
        },
        shortName: {
            type: new GraphQLNonNull(GraphQLString),
            description: 'desc'
        },
        zone: {
            type: new GraphQLNonNull(GraphQLString),
            description: 'desc'
        },
        placeType: {
            type: GraphQLString,
            description: 'desc'
        },
        district: {
            type: new GraphQLNonNull(GraphQLString),
            description: 'desc'
        },
        isHub: {
            type: new GraphQLNonNull(GraphQLBoolean),
            description: 'desc'
        },
        utmX: {
            type: new GraphQLNonNull(GraphQLInt),
            description: 'desc'
        },
        utmY: {
            type: new GraphQLNonNull(GraphQLInt),
            description: 'desc'
        },
        geoLocation: {
            type: GeoLocation,
            description: 'geo point'
        },
        lines: {
            type: new GraphQLList(Line),
            description: 'lines serviced by from stop by type',
            args: {
                transitType: {
                    name: 'transitType',
                    type: new GraphQLList(TransitType)
                },
                id: {
                    name: 'id',
                    type: new GraphQLList(GraphQLInt),
                }
            },
            resolve: ({id: stopId}, {transitType, id: lineId}) => {
                console.log('ergs', transitType, lineId)

                let p = linesForStop(stopId);

                if (transitType) {
                    p = p.then(e => e.filter(y => transitType.indexOf(y.transitType) != -1));
                }

                if (lineId) {
                    p = p.then(e => {
                        console.log(e);
                        return e.filter(y => lineId.indexOf(y.id) != -1 );
                    })
                }

                return p;

            }
        },
        stopVisits: {
            type: new GraphQLList(StopVisit),
            description: 'Pending visits for stop. This is the reealtime info'
        }
    })
});

var StopVisit = new GraphQLObjectType({
    name: 'Visit',
    description: 'llalaaalallalalala',
    fields: () => ({
        journeys: {
            type: new GraphQLNonNull(GraphQLString),
            description: 'desc'
        }
    })
});

export const schema = new GraphQLSchema({
    query: new GraphQLObjectType({
        name: 'Query',
        fields: {
            version: {
                type: GraphQLString,
                resolve: function() {
                    return '1.0';
                }
            },
            utcTime: {
                type: GraphQLString,
                resolve: function() {
                    return new Date().toString();
                }
            },
            stop: {
                type: Stop,
                args: {
                    id: { name: 'id', type: new GraphQLNonNull(GraphQLInt) }
                },
                resolve: (root, {id}, source) => stopInfo(id)
            },
            line: {
                type: Line,
                args: {
                    id: { name: 'id', type: new GraphQLNonNull(GraphQLInt) }
                },
                resolve: (root, {id}, source) => lineInfo(id)
            }

        }
    })
});

<commit_msg>Use consts for types<commit_after>import {stopInfo, lineInfo, linesForStop, stopsForLine} from './ruter-fetcher';

import {
  GraphQLEnumType,
  GraphQLInterfaceType,
  GraphQLObjectType,
  GraphQLList,
  GraphQLNonNull,
  GraphQLSchema,
  GraphQLString,
  GraphQLInt,
  GraphQLFloat,
  GraphQLBoolean,
} from 'graphql';

const TransitType = new GraphQLEnumType({
    name: 'TransitType',
    description: 'One of the types of transit operated by ruter',
    values: {
        TRAM: {
            value: 7,
            description: 'Tram'
        },
        BUS: {
            value: 2,
            description: 'Bus'
        },
        SUBWAY: {
            value: 6,
            description: 'Subway'
        },
        FERRY: {
            value: 1,
            description: 'Ferry'
        }
    }
});

const GeoLocation = new GraphQLObjectType({
    name: 'GeoLocation',
    description: 'geo type',
    fields: {
        latitude: {
            type: GraphQLFloat,
            description: 'latitude'
        },
        longitude: {
            type: GraphQLFloat,
            description: 'longitude'
        }
    }
});

const Line = new GraphQLObjectType({
    name: 'Line',
    description: 'A public transit line',
    fields: () => ({
        id: {
            type: new GraphQLNonNull(GraphQLInt),
            description: 'The id of the line.',
        },
        name: {
            type: new GraphQLNonNull(GraphQLString),
            description: 'The name of the line.',
        },
        transitType: {
            type: new GraphQLNonNull(TransitType),
            description: 'The type or transport of the line.',
        },
        color: {
            type: new GraphQLNonNull(GraphQLString),
            description: 'The color of the line.',
        },
        stops: {
            type: new GraphQLList(new GraphQLNonNull(Stop)),
            description: 'Stops serviced by this line',
            resolve: ({id}, args, source) => stopsForLine(id)
        },
        endPoints: {
            type: GraphQLString,
            description: 'End points for line',
            resolve: ({id}) => stopsForLine(id).then(e => {
                return e[0].name + ' / ' + e[e.length - 1].name;
            })

        }
    }),
    interfaces: [ ]
});

const Stop = new GraphQLObjectType({
    name: 'Stop',
    description: 'A stop',
    fields: () => ({
        id: {
            type: new GraphQLNonNull(GraphQLInt),
            description: 'stop id'
        },
        name: {
            type: new GraphQLNonNull(GraphQLString),
            description: 'desc'
        },
        shortName: {
            type: new GraphQLNonNull(GraphQLString),
            description: 'desc'
        },
        zone: {
            type: new GraphQLNonNull(GraphQLString),
            description: 'desc'
        },
        placeType: {
            type: GraphQLString,
            description: 'desc'
        },
        district: {
            type: new GraphQLNonNull(GraphQLString),
            description: 'desc'
        },
        isHub: {
            type: new GraphQLNonNull(GraphQLBoolean),
            description: 'desc'
        },
        utmX: {
            type: new GraphQLNonNull(GraphQLInt),
            description: 'desc'
        },
        utmY: {
            type: new GraphQLNonNull(GraphQLInt),
            description: 'desc'
        },
        geoLocation: {
            type: GeoLocation,
            description: 'geo point'
        },
        lines: {
            type: new GraphQLList(Line),
            description: 'lines serviced by from stop by type',
            args: {
                transitType: {
                    name: 'transitType',
                    type: new GraphQLList(TransitType)
                },
                id: {
                    name: 'id',
                    type: new GraphQLList(GraphQLInt),
                }
            },
            resolve: ({id: stopId}, {transitType, id: lineId}) => {
                console.log('ergs', transitType, lineId)

                let p = linesForStop(stopId);

                if (transitType) {
                    p = p.then(e => e.filter(y => transitType.indexOf(y.transitType) != -1));
                }

                if (lineId) {
                    p = p.then(e => {
                        console.log(e);
                        return e.filter(y => lineId.indexOf(y.id) != -1 );
                    })
                }

                return p;

            }
        },
        stopVisits: {
            type: new GraphQLList(StopVisit),
            description: 'Pending visits for stop. This is the reealtime info'
        }
    })
});

const StopVisit = new GraphQLObjectType({
    name: 'Visit',
    description: 'llalaaalallalalala',
    fields: () => ({
        journeys: {
            type: new GraphQLNonNull(GraphQLString),
            description: 'desc'
        }
    })
});

export const schema = new GraphQLSchema({
    query: new GraphQLObjectType({
        name: 'Query',
        fields: {
            version: {
                type: GraphQLString,
                resolve: function() {
                    return '1.0';
                }
            },
            utcTime: {
                type: GraphQLString,
                resolve: function() {
                    return new Date().toString();
                }
            },
            stop: {
                type: Stop,
                args: {
                    id: { name: 'id', type: new GraphQLNonNull(GraphQLInt) }
                },
                resolve: (root, {id}, source) => stopInfo(id)
            },
            line: {
                type: Line,
                args: {
                    id: { name: 'id', type: new GraphQLNonNull(GraphQLInt) }
                },
                resolve: (root, {id}, source) => lineInfo(id)
            }

        }
    })
});

<|endoftext|>