<commit_before>var getLowerCaseExtension = function(filename) {
        var extIdx = filename.lastIndexOf(".") + 1;

        if (extIdx > 0) {
            return filename.substr(extIdx, filename.length - extIdx).toLowerCase();
        }
    },

    getResultOfCountLimitValidation = function(limit, files) {
        if (limit > 0 && limit < files.length) {
            return {
                invalid: files.slice(limit, files.length),
                valid: files.slice(0, limit)
            }
        }

        return {invalid: [], valid: files};
    },

    getResultOfExtensionsValidation = function(extensionsStr, files) {
        if (extensionsStr) {
            var negate = extensionsStr.charAt(0) === "!",
                extensions = JSON.parse(extensionsStr.toLowerCase().substr(negate ? 1 : 0)),
                result = {invalid: [], valid: []};

            files.forEach(function(file) {
                var extension = getLowerCaseExtension(file.name);

                if (extensions.indexOf(extension) >= 0) {
                    result[negate ? "invalid" : "valid"].push(file);
                }
                else {
                    result[negate? "valid" : "invalid"].push(file);
                }
            });

            return result;
        }

        return {invalid: [], valid: files};
    },

    getResultOfSizeValidation = function(minSize, maxSize, files) {
        if (!minSize && !maxSize) {
            return {tooBig: [], tooSmall: [], valid: files};
        }

        var valid = []
            tooBig = [],
            tooSmall = [];

        files.forEach(function(file) {
            if (minSize && file.size < minSize) {
                tooSmall.push(file);
            }
            else if (maxSize && file.size > maxSize) {
                tooBig.push(file);
            }
            else {
                valid.push(file);
            }
        });

        return {tooBig: tooBig, tooSmall: tooSmall, valid: valid};
    };

/* globals Polymer */
Polymer("file-input", {
    changeHandler: function() {
        var files = Array.prototype.slice.call(this.$.fileInputInput.files),
            invalid = {count: 0},
            valid = [];

        var sizeValidationResult = getResultOfSizeValidation(this.minSize, this.maxSize, files);
        var extensionValidationResult = getResultOfExtensionsValidation(this.extensions, sizeValidationResult.valid);
        var countLimitValidationResult = getResultOfCountLimitValidation(this.maxFiles, extensionValidationResult.valid);

        if (sizeValidationResult.tooBig.length) {
            invalid["tooBig"] = sizeValidationResult.tooBig;
            invalid.count += sizeValidationResult.tooBig.length;
        }
        if (sizeValidationResult.tooSmall.length) {
            invalid["tooSmall"] = sizeValidationResult.tooSmall;
            invalid.count += sizeValidationResult.tooSmall.length;
        }
        if (extensionValidationResult.invalid.length) {
            invalid["badExtensions"] = extensionValidationResult.invalid;
            invalid.count += extensionValidationResult.invalid.length;
        }
        if (countLimitValidationResult.invalid.length) {
            invalid["tooMany"] = countLimitValidationResult.invalid;
            invalid.count += countLimitValidationResult.invalid.length;
        }

        valid = countLimitValidationResult.valid;

        this.invalidFiles = invalid;
        this.files = valid;

        this.fire("change", {invalid: invalid, valid: valid});
    },

    directory: false,

    files: [],

    invalidFiles: {count: 0},

    maxFiles: 0,

    ready: function() {
        if (this.maxFiles !== 1) {
            this.$.fileInputInput.setAttribute("multiple", "");
        }

        if (this.directory && this.$.fileInputInput.webkitdirectory !== undefined) {
            this.$.fileInputInput.setAttribute("webkitdirectory", "");
        }
    }
});<commit_msg>refactor($best-practices): obj/arrays should be init in create callback<commit_after>var getLowerCaseExtension = function(filename) {
        var extIdx = filename.lastIndexOf(".") + 1;

        if (extIdx > 0) {
            return filename.substr(extIdx, filename.length - extIdx).toLowerCase();
        }
    },

    getResultOfCountLimitValidation = function(limit, files) {
        if (limit > 0 && limit < files.length) {
            return {
                invalid: files.slice(limit, files.length),
                valid: files.slice(0, limit)
            }
        }

        return {invalid: [], valid: files};
    },

    getResultOfExtensionsValidation = function(extensionsStr, files) {
        if (extensionsStr) {
            var negate = extensionsStr.charAt(0) === "!",
                extensions = JSON.parse(extensionsStr.toLowerCase().substr(negate ? 1 : 0)),
                result = {invalid: [], valid: []};

            files.forEach(function(file) {
                var extension = getLowerCaseExtension(file.name);

                if (extensions.indexOf(extension) >= 0) {
                    result[negate ? "invalid" : "valid"].push(file);
                }
                else {
                    result[negate? "valid" : "invalid"].push(file);
                }
            });

            return result;
        }

        return {invalid: [], valid: files};
    },

    getResultOfSizeValidation = function(minSize, maxSize, files) {
        if (!minSize && !maxSize) {
            return {tooBig: [], tooSmall: [], valid: files};
        }

        var valid = []
            tooBig = [],
            tooSmall = [];

        files.forEach(function(file) {
            if (minSize && file.size < minSize) {
                tooSmall.push(file);
            }
            else if (maxSize && file.size > maxSize) {
                tooBig.push(file);
            }
            else {
                valid.push(file);
            }
        });

        return {tooBig: tooBig, tooSmall: tooSmall, valid: valid};
    };

/* globals Polymer */
Polymer("file-input", {
    changeHandler: function() {
        var files = Array.prototype.slice.call(this.$.fileInputInput.files),
            invalid = {count: 0},
            valid = [];

        var sizeValidationResult = getResultOfSizeValidation(this.minSize, this.maxSize, files);
        var extensionValidationResult = getResultOfExtensionsValidation(this.extensions, sizeValidationResult.valid);
        var countLimitValidationResult = getResultOfCountLimitValidation(this.maxFiles, extensionValidationResult.valid);

        if (sizeValidationResult.tooBig.length) {
            invalid["tooBig"] = sizeValidationResult.tooBig;
            invalid.count += sizeValidationResult.tooBig.length;
        }
        if (sizeValidationResult.tooSmall.length) {
            invalid["tooSmall"] = sizeValidationResult.tooSmall;
            invalid.count += sizeValidationResult.tooSmall.length;
        }
        if (extensionValidationResult.invalid.length) {
            invalid["badExtensions"] = extensionValidationResult.invalid;
            invalid.count += extensionValidationResult.invalid.length;
        }
        if (countLimitValidationResult.invalid.length) {
            invalid["tooMany"] = countLimitValidationResult.invalid;
            invalid.count += countLimitValidationResult.invalid.length;
        }

        valid = countLimitValidationResult.valid;

        this.invalidFiles = invalid;
        this.files = valid;

        this.fire("change", {invalid: invalid, valid: valid});
    },

    created: function() {
        this.files = [],
        this.invalidFiles = {count: 0}
    },

    maxFiles: 0,

    maxSize: 0,

    minSize: 0,

    ready: function() {
        if (this.maxFiles !== 1) {
            this.$.fileInputInput.setAttribute("multiple", "");
        }

        if (this.directory && this.$.fileInputInput.webkitdirectory !== undefined) {
            this.$.fileInputInput.setAttribute("webkitdirectory", "");
        }
    }
});<|endoftext|>


<commit_before>'use strict';

var React = require('react-native');
var NavigationBar = require('../Components/NavigationBar');
var Api = require('../Api/Core');
var AppActions = require('../Actions/AppActions');
var reloadApp = require('../Utilities/reloadApp');

var {
  ActivityIndicatorIOS,
  AlertIOS,
  ScrollView,
  StyleSheet,
  TextInput,
  Text,
  TouchableHighlight,
  View,
  StatusBarIOS,
} = React;

var CustomApp = React.createClass({

  getInitialState() {
    return {
      isLoading: false,
      email: '',
      password: '',

    }
  },

  handleSubmit() {
    if(!this.state.url || !this.state.appName) {
      AlertIOS.alert('Error', 'Please fill in all fields',[{text: 'OK'}])
      return;
    }

    this.setState({ isLoading: true });
    reloadApp(this.state.url, this.state.appName);
    this.setState({ isLoading: false });
  },

  render() {
    StatusBarIOS.setStyle('light-content');

    return (
      <View style={styles.mainContainer}>
        <NavigationBar title="Direct URL" />
        <ScrollView>
          <Text style={styles.text}>
            Load your React Native app from any URL, such as your local packager or a javascript bundle.
          </Text>

          <View style={styles.inputContainer}>
            <TextInput
              placeholder="URL"
              keyboardType="url"
              autoCapitalize="none"
              autoCorrect={false}
              returnKeyType="next"
              onSubmitEditing={() => this.refs.appName.focus()}
              style={styles.input}
              onChangeText={(url) => this.setState({url: url})}
            />
          </View>

          <View style={styles.inputContainer}>
            <TextInput
              ref="appName"
              placeholder="APP MODULE NAME"
              returnKeyType="done"
              onSubmitEditing={this.handleSubmit}
              style={styles.input}
              onChangeText={(text) => this.setState({appName: text})}
            />
          </View>

          <TouchableHighlight style={styles.button} onPress={this.handleSubmit}>
            <Text style={styles.buttonText}>LOAD & RUN</Text>
          </TouchableHighlight>

          <Text style={styles.helpText}>The module name should match the registered top level component name.</Text>

          <Text style={styles.helpText}>Your app should React Native <Text style={{fontWeight: 700}}>{global.RN_VERSION_DISPLAY}</Text></Text>

          <ActivityIndicatorIOS
            animating={this.state.isLoading}
            color="#111"
            size="large">
          </ActivityIndicatorIOS>
        </ScrollView>
      </View>
    )
  }
});

var styles = StyleSheet.create({
  mainContainer: {
    flex: 1,
    flexDirection: 'column',
    backgroundColor: 'white'
  },
  text: {
    fontFamily: 'Avenir Next',
    paddingHorizontal: 15,
    marginBottom: 20,
    fontSize: 17,
    textAlign: 'center',
  },
  helpText: {
    marginTop: 10,
    paddingHorizontal: 10,
    color: "#888"
  },
  inputContainer: {
    borderBottomWidth: 1,
    borderColor: '#cccccc',
    margin: 10,
  },
  input: {
    height: 40,
    padding: 5,
    fontSize: 14,
    color: 'black',
  },
  button: {
    backgroundColor: '#712FA9',
    margin: 10
  },
  buttonText: {
    fontSize: 16,
    textAlign: 'center',
    color: 'white',
    padding: 10,
    fontFamily: 'Avenir Next',
  },
});

module.exports = CustomApp;
<commit_msg>fix fontWeight<commit_after>'use strict';

var React = require('react-native');
var NavigationBar = require('../Components/NavigationBar');
var Api = require('../Api/Core');
var AppActions = require('../Actions/AppActions');
var reloadApp = require('../Utilities/reloadApp');

var {
  ActivityIndicatorIOS,
  AlertIOS,
  ScrollView,
  StyleSheet,
  TextInput,
  Text,
  TouchableHighlight,
  View,
  StatusBarIOS,
} = React;

var CustomApp = React.createClass({

  getInitialState() {
    return {
      isLoading: false,
      email: '',
      password: '',

    }
  },

  handleSubmit() {
    if(!this.state.url || !this.state.appName) {
      AlertIOS.alert('Error', 'Please fill in all fields',[{text: 'OK'}])
      return;
    }

    this.setState({ isLoading: true });
    reloadApp(this.state.url, this.state.appName);
    this.setState({ isLoading: false });
  },

  render() {
    StatusBarIOS.setStyle('light-content');

    return (
      <View style={styles.mainContainer}>
        <NavigationBar title="Direct URL" />
        <ScrollView>
          <Text style={styles.text}>
            Load your React Native app from any URL, such as your local packager or a javascript bundle.
          </Text>

          <View style={styles.inputContainer}>
            <TextInput
              placeholder="URL"
              keyboardType="url"
              autoCapitalize="none"
              autoCorrect={false}
              returnKeyType="next"
              onSubmitEditing={() => this.refs.appName.focus()}
              style={styles.input}
              onChangeText={(url) => this.setState({url: url})}
            />
          </View>

          <View style={styles.inputContainer}>
            <TextInput
              ref="appName"
              placeholder="APP MODULE NAME"
              returnKeyType="done"
              onSubmitEditing={this.handleSubmit}
              style={styles.input}
              onChangeText={(text) => this.setState({appName: text})}
            />
          </View>

          <TouchableHighlight style={styles.button} onPress={this.handleSubmit}>
            <Text style={styles.buttonText}>LOAD & RUN</Text>
          </TouchableHighlight>

          <Text style={styles.helpText}>The module name should match the registered top level component name.</Text>

          <Text style={styles.helpText}>Your app should React Native <Text style={{fontWeight: "700"}}>{global.RN_VERSION_DISPLAY}</Text></Text>

          <ActivityIndicatorIOS
            animating={this.state.isLoading}
            color="#111"
            size="large">
          </ActivityIndicatorIOS>
        </ScrollView>
      </View>
    )
  }
});

var styles = StyleSheet.create({
  mainContainer: {
    flex: 1,
    flexDirection: 'column',
    backgroundColor: 'white'
  },
  text: {
    fontFamily: 'Avenir Next',
    paddingHorizontal: 15,
    marginBottom: 20,
    fontSize: 17,
    textAlign: 'center',
  },
  helpText: {
    marginTop: 10,
    paddingHorizontal: 10,
    color: "#888"
  },
  inputContainer: {
    borderBottomWidth: 1,
    borderColor: '#cccccc',
    margin: 10,
  },
  input: {
    height: 40,
    padding: 5,
    fontSize: 14,
    color: 'black',
  },
  button: {
    backgroundColor: '#712FA9',
    margin: 10
  },
  buttonText: {
    fontSize: 16,
    textAlign: 'center',
    color: 'white',
    padding: 10,
    fontFamily: 'Avenir Next',
  },
});

module.exports = CustomApp;
<|endoftext|>


<commit_before>import Vue from 'vue';
import store from '../../../store';

const __ = store.getters['locale/__'];

const addMissingKey = (key) => {
    if (store.state.locale.keyCollector) {
        axios.patch('/api/system/localisation/addKey', { langKey: key });
        store.commit('locale/addKey', key);
    }

    return key;
};

Vue.prototype.__ = (key) => {
    if (!store.state.isInitialised) {
        return key;
    }

    const translation = __(key);

    if (typeof translation === 'undefined') {
        addMissingKey(key);
    }

    return translation || key;
};
<commit_msg>small refactor in __.js<commit_after>import Vue from 'vue';
import store from '../../../store';

const __ = store.getters['locale/__'];

const addMissingKey = (key) => {
    if (store.state.locale.keyCollector) {
        axios.patch('/api/system/localisation/addKey', { langKey: key });
        store.commit('locale/addKey', key);
    }
};

Vue.prototype.__ = (key) => {
    if (!store.state.isInitialised) {
        return key;
    }

    const translation = __(key);

    if (typeof translation === 'undefined') {
        addMissingKey(key);
    }

    return translation || key;
};
<|endoftext|>


<commit_before>// open all dbs
FIND="Discussion Forum";
i=0;
$("a").each(function(){
    str = $(this).text();
    if (str.match(FIND)) {
        console.log(str);
     link = $(this).attr("href");
     console.log(link);
     $.ajax({
           url: link,
     }).done(function(data) {
              val = $("td a", data.responseXML).text(); //can't parse with jquery selector
             console.log(val);
     });
    }
    i = i + 1;
 });

// show all links (works)
FIND = [ "Discussion Forum", "Learning Journal", "Written Assignment", "Self Quiz", "Graded Quiz", "Final Exam" ];
OUT="";
$.each(FIND, function(key, find) {
       OUT= OUT + get(find);
});
document.write(OUT);

function get(FIND) {
RES="
"+FIND+"
";
$("a").each(function(){
    str = $(this).text();
    if (str.match(FIND)) {
        console.log(str);
        link = $(this).attr("href");
         RES=RES+""+link+"

";
    }
 });
 return RES;
}

<commit_msg>Update working.js<commit_after>// open all dbs
FIND="Discussion Forum";
i=0;
$("a").each(function(){
    str = $(this).text();
    if (str.match(FIND)) {
        console.log(str);
     link = $(this).attr("href");
     console.log(link);
     $.ajax({
           url: link,
     }).done(function(data) {
              val = $("td a", data.responseXML).text(); //can't parse with jquery selector
             console.log(val);
     });
    }
    i = i + 1;
 });

// show all links (works)
FIND = [ "Discussion Forum", "Learning Journal", "Written Assignment", "Self Quiz", "Graded Quiz", "Final Exam" ];
OUT="";
$.each(FIND, function(key, find) {
       OUT= OUT + get(find);
});
document.write(OUT);

function get(FIND) {
RES="
"+FIND+"
";
$("a").each(function(){
    str = $(this).text();
    if (str.match(FIND)) {
        console.log(str);
        text = $(this).text();
        url = $(this).attr("href");
         RES=RES+""+text+"

";
    }
 });
 return RES;
}

<|endoftext|>


<commit_before>'use strict';
///////////////////////INICIO SERVER MQTT////////////////////////////////
//Dependencias Broker
var mosca = require('mosca');
//Dependencias WEB Server
var mqtt = require('mqtt');

var ascoltatore = {
    //using ascoltatore
    type: 'mongo',
    url: 'mongodb://localhost:27017/mqtt',
    pubsubCollection: 'ascoltatori',
    mongo: {}
};

var moscaSettings = {
    port: 1883,
    backend: ascoltatore,
    persistence: {
        factory: mosca.persistence.Mongo,
        url: 'mongodb://localhost:27017/mqtt'
    }
};
// fired when the mqtt server is ready
function setup() {
    console.log('Mosca server is up and running');
}

var server = new mosca.Server(moscaSettings);
server.on('ready', setup);

server.on('clientConnected', function(client) {
    console.log('client connected', client.id);
});

// fired when a message is received
server.on('published', function(packet, client) {
    console.log('Published', packet.topic);

});

//in case of an error
process.on('uncaughtException', function(error) {
    return console.log(error.stack);
});

//Server WEB

var socket = require('socket.io');

var mqttbroker = 'localhost';
var mqttport = 1883;

var io = socket.listen(3000);
var mqttclient = mqtt.createClient(mqttport, mqttbroker);

// Reduce socket.io debug output
io.set('log level', 0);

// Configuracion de respuestas de Socket.io. desde la web para el controlador
function publicarEnArduino(data){
    var info = JSON.parse(data);
    var topic = String(info.topic);
    var payload = JSON.stringify(info.payload);
    mqttclient.publish( topic ,payload);
}
io.sockets.on('connection', function (socket) {
    socket.on('subscribe', function (data) {
        mqttclient.subscribe(data.topic);
    });
    socket.on('controlador', function (data) {
        publicarEnArduino(data);
    });
});

// FIN WEB-CONTROLADOR SOCKET.IO

// Mensajes para la web desde arduino
mqttclient.on('message', function(topic, payload) {
    if(topic.indexOf('resp/discover')>=0){
        io.sockets.emit('resp/discover',
            {'topic': topic,
                'payload': payload
            }
        );
    }
    if(topic.indexOf('resp/ard')>=0) {
        io.sockets.emit('mqtt',
            {'topic': topic,
                'payload': payload
            }
        );
    }
});
//FIN MENSAJES PARA LA CONTROLADOR-WEB.
///////////////////////FIN SERVER MQTT////////////////////////////////
/**
 * Module dependencies.
 */
var init = require('./config/init')(),
	config = require('./config/config'),
	mongoose = require('mongoose');

/**
 * Main application entry file.
 * Please note that the order of loading is important.
 */

// Bootstrap db connection
var db = mongoose.connect(config.db);

// Init the express application
var app = require('./config/express')(db);

// Bootstrap passport config
require('./config/passport')();

// Start the app by listening on <port>
app.listen(config.port);

// Expose app
exports = module.exports = app;

// Logging initialization
console.log('MEAN.JS application started on port ' + config.port);

<commit_msg>Agregue una impresion por consola para ver donde llegan los mensajes publicados por el proyecto que simula un lector de huellas.<commit_after>'use strict';
///////////////////////INICIO SERVER MQTT////////////////////////////////
//Dependencias Broker
var mosca = require('mosca');
//Dependencias WEB Server
var mqtt = require('mqtt');

var ascoltatore = {
    //using ascoltatore
    type: 'mongo',
    url: 'mongodb://localhost:27017/mqtt',
    pubsubCollection: 'ascoltatori',
    mongo: {}
};

var moscaSettings = {
    port: 1883,
    backend: ascoltatore,
    persistence: {
        factory: mosca.persistence.Mongo,
        url: 'mongodb://localhost:27017/mqtt'
    }
};
// fired when the mqtt server is ready
function setup() {
    console.log('Mosca server is up and running');
}

var server = new mosca.Server(moscaSettings);
server.on('ready', setup);

server.on('clientConnected', function(client) {
    console.log('client connected', client.id);
});

/**
 * Aca se escuchan todos los mensajes publicados. Y es donde tambien llegan mis mensajes
 * publicados por el lector de huellas.
 */
server.on('published', function(packet, client) {
    if(packet.topic.indexOf('empleados/huella/')>=0) {
        console.log('El topic es: ' + packet.topic);
        console.log('El Payload es: ' + packet.payload);
        console.log('Del Cliente: ' + client.id);
    }
    console.log('Published', packet.topic);

});

//in case of an error
process.on('uncaughtException', function(error) {
    return console.log(error.stack);
});

//Server WEB

var socket = require('socket.io');

var mqttbroker = 'localhost';
var mqttport = 1883;

var io = socket.listen(3000);
var mqttclient = mqtt.createClient(mqttport, mqttbroker);

// Reduce socket.io debug output
io.set('log level', 0);

// Configuracion de respuestas de Socket.io. desde la web para el controlador
function publicarEnArduino(data){
    var info = JSON.parse(data);
    var topic = String(info.topic);
    var payload = JSON.stringify(info.payload);
    mqttclient.publish( topic ,payload);
}
io.sockets.on('connection', function (socket) {
    socket.on('subscribe', function (data) {
        mqttclient.subscribe(data.topic);
    });
    socket.on('controlador', function (data) {
        publicarEnArduino(data);
    });
});

// FIN WEB-CONTROLADOR SOCKET.IO

// Mensajes para la web desde arduino
mqttclient.on('message', function(topic, payload) {
    if(topic.indexOf('resp/discover')>=0){
        io.sockets.emit('resp/discover',
            {'topic': topic,
                'payload': payload
            }
        );
    }
    if(topic.indexOf('resp/ard')>=0) {
        io.sockets.emit('mqtt',
            {'topic': topic,
                'payload': payload
            }
        );
    }
});
//FIN MENSAJES PARA LA CONTROLADOR-WEB.
///////////////////////FIN SERVER MQTT////////////////////////////////
/**
 * Module dependencies.
 */
var init = require('./config/init')(),
	config = require('./config/config'),
	mongoose = require('mongoose');

/**
 * Main application entry file.
 * Please note that the order of loading is important.
 */

// Bootstrap db connection
var db = mongoose.connect(config.db);

// Init the express application
var app = require('./config/express')(db);

// Bootstrap passport config
require('./config/passport')();

// Start the app by listening on <port>
app.listen(config.port);

// Expose app
exports = module.exports = app;

// Logging initialization
console.log('MEAN.JS application started on port ' + config.port);

<|endoftext|>


<commit_before>require.paths.unshift(require('path').join(__dirname, '..'));

var events = require('events');

var definers  = require('resourcer/schema').definers;
var resourcer = require('resourcer');

//
// CRUD
//
this.Resource = function () {};

this.Resource.filter = require('resourcer/resource/view').filter;

this.Resource.views = {};

this.Resource.init = function () {
    this.emit('init', this);
};
this.Resource.register = function () {
    return resourcer.register(this.resourceName, this);
};
this.Resource.unregister = function () {
    return resourcer.unregister(this.resourceName);
};
this.Resource._request = function (method, key, obj) {
    var promise = new(events.EventEmitter),
        that = this,
        args = [method];

    key && args.push(key);
    obj && args.push(obj.properties ? obj.properties : obj);

    promise.addCallbacks = function (callback, promise) {
        this.addListener("success", function (res) {
            that.emit("post" + capitalize(method), obj);
            callback && callback(null, res);
            promise  && promise.emit('success', res);
        });
        this.addListener("error", function (e) {
            that.emit("error", e, obj);
            callback && callback(e);
            promise  && promise.emit('error', e);
        });
        if (! callback) { return this }
    };

    this.emit("pre" + capitalize(method), obj);

    args.push(function (e, result) {
        var Factory;

        if (e) {
            if (e.status >= 500) {
                throw new(Error)(e);
            } else {
                promise.emit("error", e);
            }
        } else {
            if (Array.isArray(result)) {
                result = result.map(function (r) {
                    return resourcer.resourcefy(r);
                });
            } else {
                result = resourcer.resourcefy(result);
            }
            promise.emit("success", result);
        }
    });
    this.connection.request.apply(this.connection, args);

    return promise;
};
this.Resource.get = function (id, callback) {
    return this._request("get", id).addCallbacks(callback);
};
this.Resource.create = function (obj, callback) {
    return this._request("create", obj.key, obj).addCallbacks(callback);
};
this.Resource.save = function (obj, callback) {
    return this._request("save", obj.key, obj).addCallbacks(callback);
};
this.Resource.update = function (key, obj, callback) {
    return this._request("update", key, obj).addCallbacks(callback);
};
this.Resource.all = function (callback) {
    return this._request("all").addCallbacks(callback);
};
this.Resource.view = function (path, params, callback) {
    return this._request("view", path, params).addCallbacks(callback);
};
this.Resource.find = function (conditions, callback) {
    if (typeof(conditions) !== "object") {
        throw new(Error)("ArgumentError: `find` takes an object hash");
    }
    return this._request("find", conditions).addCallbacks(callback);
};
this.Resource.__defineGetter__('connection', function () {
    return this._connection || resourcer.connection;
});
this.Resource.__defineSetter__('connection', function (val) {
    return this._connection = val;
});
this.Resource.__defineGetter__('engine', function () {
    return this._engine || resourcer.engine;
});
this.Resource.__defineSetter__('engine', function (val) {
    return this._engine = val;
});
this.Resource.use     = function () { return resourcer.use.apply(this, arguments) };
this.Resource.connect = function () { return resourcer.connect.apply(this, arguments) };

this.Resource.resource = function (name) {
    return this.resourceName = name;
};
this.Resource.property = function (name, typeOrSchema, schema) {
    var definer = {};
    var type = (function () {
        switch (typeof(typeOrSchema)) {
            case "string":    return typeOrSchema;
            case "function":  return typeOrSchema.name.toLowerCase();
            case "object":    schema = typeOrSchema;
            case "undefined": return "string";
            default:          throw new(Error)("Argument Error");
        }
    })();

    schema = schema || {};
    schema.type = schema.type || type;

    this.schema.properties[name] = definer.property = schema;

    resourcer.mixin(definer, definers.all, definers[schema.type] || {});

    return definer;
};

this.Resource.define = function (schema) {
    return resourcer.mixin(this.schema, schema);
};
this.Resource.__defineGetter__('properties', function () {
    return this.schema.properties;
});
this.Resource.__defineSetter__('key', function (val) {
    return this._key = val;
});
this.Resource.__defineGetter__('key', function () {
    return this._key;
});
this.Resource.delegate = function (method, property) {
    var that = this;
    this[method] = function () {
        return that[property][method].apply(that[property], arguments);
    };
};

//
// Reload a Resource's _design document from the database.
//
this.Resource.reload = function (callback) {
    var design, that = this;

    if (this.connection.protocol === 'database') {
        design = this._design;
        if (design instanceof events.EventEmitter) {
            design.addListener('success', function (doc) {
                callback.call(that);
            });
        } else {
            callback.call(this);
        }
    } else {
        callback.call(this);
    }
};

//
// Prototype
//
this.Resource.prototype = {
    save: function (callback) {
        if (this.isValid()) {
            if (this.isNewRecord) {
                this.constructor.create(this, callback);
            } else {
                this.constructor.save(this, callback);
            }
        } else {
        }
    },
    update: function (obj, callback) {
        this.properties = obj;
        return this.save(callback);
    },
    destroy: function () {},
    isValid: function () {
        return true;
    },
    isNewRecord: true,
    readProperty: function (k) {
        return this._properties[k];
    },
    writeProperty: function (k, val) {
        return this._properties[k] = val;
    }
};
this.Resource.prototype.__defineGetter__('key', function () {
    return this[this.constructor.key];
});
//
// Up
//
this.Resource.prototype.__defineGetter__('properties', function () {
    return this._properties;
});
this.Resource.prototype.__defineSetter__('properties', function (props) {
    var that = this;
    Object.keys(props).forEach(function (k) {
        that[k] = props[k];
    });
    return props;
});

resourcer.resourcefy = function (obj) {
    obj.resource = obj.resource || "Resource";
    if (Factory = this.resources[obj.resource]) {
        return new(Factory)(obj);
    } else {
        throw new(Error)("unrecognised resource");
    }
};

//
// Utilities
//
function capitalize(str) {
    return str && str[0].toUpperCase() + str.slice(1);
}
<commit_msg>(minor) clearer message when resource isn't found<commit_after>require.paths.unshift(require('path').join(__dirname, '..'));

var events = require('events');

var definers  = require('resourcer/schema').definers;
var resourcer = require('resourcer');

//
// CRUD
//
this.Resource = function () {};

this.Resource.filter = require('resourcer/resource/view').filter;

this.Resource.views = {};

this.Resource.init = function () {
    this.emit('init', this);
};
this.Resource.register = function () {
    return resourcer.register(this.resourceName, this);
};
this.Resource.unregister = function () {
    return resourcer.unregister(this.resourceName);
};
this.Resource._request = function (method, key, obj) {
    var promise = new(events.EventEmitter),
        that = this,
        args = [method];

    key && args.push(key);
    obj && args.push(obj.properties ? obj.properties : obj);

    promise.addCallbacks = function (callback, promise) {
        this.addListener("success", function (res) {
            that.emit("post" + capitalize(method), obj);
            callback && callback(null, res);
            promise  && promise.emit('success', res);
        });
        this.addListener("error", function (e) {
            that.emit("error", e, obj);
            callback && callback(e);
            promise  && promise.emit('error', e);
        });
        if (! callback) { return this }
    };

    this.emit("pre" + capitalize(method), obj);

    args.push(function (e, result) {
        var Factory;

        if (e) {
            if (e.status >= 500) {
                throw new(Error)(e);
            } else {
                promise.emit("error", e);
            }
        } else {
            if (Array.isArray(result)) {
                result = result.map(function (r) {
                    return resourcer.resourcefy(r);
                });
            } else {
                result = resourcer.resourcefy(result);
            }
            promise.emit("success", result);
        }
    });
    this.connection.request.apply(this.connection, args);

    return promise;
};
this.Resource.get = function (id, callback) {
    return this._request("get", id).addCallbacks(callback);
};
this.Resource.create = function (obj, callback) {
    return this._request("create", obj.key, obj).addCallbacks(callback);
};
this.Resource.save = function (obj, callback) {
    return this._request("save", obj.key, obj).addCallbacks(callback);
};
this.Resource.update = function (key, obj, callback) {
    return this._request("update", key, obj).addCallbacks(callback);
};
this.Resource.all = function (callback) {
    return this._request("all").addCallbacks(callback);
};
this.Resource.view = function (path, params, callback) {
    return this._request("view", path, params).addCallbacks(callback);
};
this.Resource.find = function (conditions, callback) {
    if (typeof(conditions) !== "object") {
        throw new(Error)("ArgumentError: `find` takes an object hash");
    }
    return this._request("find", conditions).addCallbacks(callback);
};
this.Resource.__defineGetter__('connection', function () {
    return this._connection || resourcer.connection;
});
this.Resource.__defineSetter__('connection', function (val) {
    return this._connection = val;
});
this.Resource.__defineGetter__('engine', function () {
    return this._engine || resourcer.engine;
});
this.Resource.__defineSetter__('engine', function (val) {
    return this._engine = val;
});
this.Resource.use     = function () { return resourcer.use.apply(this, arguments) };
this.Resource.connect = function () { return resourcer.connect.apply(this, arguments) };

this.Resource.resource = function (name) {
    return this.resourceName = name;
};
this.Resource.property = function (name, typeOrSchema, schema) {
    var definer = {};
    var type = (function () {
        switch (typeof(typeOrSchema)) {
            case "string":    return typeOrSchema;
            case "function":  return typeOrSchema.name.toLowerCase();
            case "object":    schema = typeOrSchema;
            case "undefined": return "string";
            default:          throw new(Error)("Argument Error");
        }
    })();

    schema = schema || {};
    schema.type = schema.type || type;

    this.schema.properties[name] = definer.property = schema;

    resourcer.mixin(definer, definers.all, definers[schema.type] || {});

    return definer;
};

this.Resource.define = function (schema) {
    return resourcer.mixin(this.schema, schema);
};
this.Resource.__defineGetter__('properties', function () {
    return this.schema.properties;
});
this.Resource.__defineSetter__('key', function (val) {
    return this._key = val;
});
this.Resource.__defineGetter__('key', function () {
    return this._key;
});
this.Resource.delegate = function (method, property) {
    var that = this;
    this[method] = function () {
        return that[property][method].apply(that[property], arguments);
    };
};

//
// Reload a Resource's _design document from the database.
//
this.Resource.reload = function (callback) {
    var design, that = this;

    if (this.connection.protocol === 'database') {
        design = this._design;
        if (design instanceof events.EventEmitter) {
            design.addListener('success', function (doc) {
                callback.call(that);
            });
        } else {
            callback.call(this);
        }
    } else {
        callback.call(this);
    }
};

//
// Prototype
//
this.Resource.prototype = {
    save: function (callback) {
        if (this.isValid()) {
            if (this.isNewRecord) {
                this.constructor.create(this, callback);
            } else {
                this.constructor.save(this, callback);
            }
        } else {
        }
    },
    update: function (obj, callback) {
        this.properties = obj;
        return this.save(callback);
    },
    destroy: function () {},
    isValid: function () {
        return true;
    },
    isNewRecord: true,
    readProperty: function (k) {
        return this._properties[k];
    },
    writeProperty: function (k, val) {
        return this._properties[k] = val;
    }
};
this.Resource.prototype.__defineGetter__('key', function () {
    return this[this.constructor.key];
});
//
// Up
//
this.Resource.prototype.__defineGetter__('properties', function () {
    return this._properties;
});
this.Resource.prototype.__defineSetter__('properties', function (props) {
    var that = this;
    Object.keys(props).forEach(function (k) {
        that[k] = props[k];
    });
    return props;
});

resourcer.resourcefy = function (obj) {
    obj.resource = obj.resource || "Resource";
    if (Factory = this.resources[obj.resource]) {
        return new(Factory)(obj);
    } else {
        throw new(Error)("unrecognised resource '" + obj.resource + "'");
    }
};

//
// Utilities
//
function capitalize(str) {
    return str && str[0].toUpperCase() + str.slice(1);
}
<|endoftext|>


<commit_before>// @flow

export type Team = {
  id: string,
  name: string,
};

export type Project = {
  id: string,
  name: string,
  rootDocumentId: string,
};

export type DocumentKey = string;
export type BlobId = string;

export type Head = {|
  branch: string,
|};

export type SnapshotStateEntry = {|
  key: DocumentKey,
  blob: BlobId,
  name: string,
|};

export type SnapshotState = Array<SnapshotStateEntry>;
export type SnapshotStateMap = { [DocumentKey]: SnapshotStateEntry };
export type SnapshotId = string;

export type Snapshot = {|
  id: SnapshotId,
  created: Date,
  parent: string,
  author: string,
  name: string,
  description: string,
  state: Array<SnapshotStateEntry>,
|};

export type Branch = {|
  name: string,
  created: Date,
  modified: Date,
  snapshots: Array<string>,
|};

export type StageEntryDelete = {|
  deleted: true,
  key: string,
  name: string,
  blobId: string,
|};

export type StageEntryAdd = {|
  added: true,
  key: string,
  name: string,
  blobId: string,
  blobContent: string,
|};

export type StageEntryModify = {|
  modified: true,
  key: string,
  name: string,
  blobId: string,
  blobContent: string,
|};

export type StageEntry = StageEntryDelete | StageEntryAdd | StageEntryModify;

export type MergeConflict = {|
  name: string,
  key: DocumentKey,
  message: string,
  mineBlob: BlobId | null,
  theirsBlob: BlobId | null,
  choose: BlobId | null,
|};

export type Stage = {
  [DocumentKey]: StageEntry,
};

export type StatusCandidate = {|
  key: DocumentKey,
  name: string,
  document: Object,
|};

export type StatusCandidateMap = { [DocumentKey]: StatusCandidate };

export type Status = {|
  key: string,
  stage: Stage,
  unstaged: {
    [DocumentKey]: StageEntry,
  },
|};
<commit_msg>Fix tests<commit_after>// @flow

export type Team = {
  id: string,
  name: string,
};

export type Project = {
  id: string,
  name: string,
  rootDocumentId: string,
};

export type DocumentKey = string;
export type BlobId = string;

export type Head = {|
  branch: string,
|};

export type SnapshotStateEntry = {|
  key: DocumentKey,
  blob: BlobId,
  name: string,
|};

export type SnapshotState = Array<SnapshotStateEntry>;
export type SnapshotStateMap = { [DocumentKey]: SnapshotStateEntry };
export type SnapshotId = string;

export type Snapshot = {|
  id: SnapshotId,
  created: Date,
  parent: string,
  author: string,
  name: string,
  description: string,
  state: Array<SnapshotStateEntry>,

  // Only exists in Snapshots that are pulled from the server
  authorAccount?: {
    firstName: string,
    lastName: string,
    email: string,
  },
|};

export type Branch = {|
  name: string,
  created: Date,
  modified: Date,
  snapshots: Array<string>,
|};

export type StageEntryDelete = {|
  deleted: true,
  key: string,
  name: string,
  blobId: string,
|};

export type StageEntryAdd = {|
  added: true,
  key: string,
  name: string,
  blobId: string,
  blobContent: string,
|};

export type StageEntryModify = {|
  modified: true,
  key: string,
  name: string,
  blobId: string,
  blobContent: string,
|};

export type StageEntry = StageEntryDelete | StageEntryAdd | StageEntryModify;

export type MergeConflict = {|
  name: string,
  key: DocumentKey,
  message: string,
  mineBlob: BlobId | null,
  theirsBlob: BlobId | null,
  choose: BlobId | null,
|};

export type Stage = {
  [DocumentKey]: StageEntry,
};

export type StatusCandidate = {|
  key: DocumentKey,
  name: string,
  document: Object,
|};

export type StatusCandidateMap = { [DocumentKey]: StatusCandidate };

export type Status = {|
  key: string,
  stage: Stage,
  unstaged: {
    [DocumentKey]: StageEntry,
  },
|};
<|endoftext|>


<commit_before>var child_process = require('child_process');
var net = require('net');
var redis = require('redis');
var utils = require('./utils.js');
const {promisify} = require('util');

// Create a Redis client. This connects to a Redis server running on the local
// machine at the default port.
var redis_client = redis.createClient();

const redisGetAsync = promisify(redis_client.get).bind(redis_client);
const redisSetAsync = promisify(redis_client.set).bind(redis_client);

var portnum = 8070;
if (process.argv.length > 2) {
  portnum = process.argv[2];
}

var server = net.createServer();
server.on('connection', handleConnection);

server.listen(portnum, function() {
  console.log('Serving on port %d', portnum);
});

function handleConnection(conn) {
  var remoteAddress = conn.remoteAddress + ':' + conn.remotePort;
  console.log('peer %s connected', remoteAddress);

  conn.on('data', onConnData);
  conn.once('close', onConnClose);
  conn.on('error', onConnError);

  async function onConnData(d) {
    var num = utils.buf2num(d);
    console.log('num %d', num);

    try {
      var cachekey = 'primecache:' + num;
      var cached = await redisGetAsync(cachekey);

      if (cached === null) {
        var computed = await isPrimeAsync(num);
        await redisSetAsync(cachekey, computed);
        conn.write(computed + '\n');
      } else {
        console.log('cached num %d is %s', num, cached);
        conn.write(cached + '\n');
      }
    } catch (err) {
      // TODO: make error handling consistent with other parts
      console.log('error:', err);
    }
  }

  function onConnClose() {
    console.log('connection from %s closed', remoteAddress);
  }

  function onConnError(err) {
    console.log('connection %s error: %s', remoteAddress, err.message);
  }
}

async function isPrimeAsync(n) {
  return new Promise((resolve, reject) => {
    var child = child_process.fork('./primeworker.js');
    child.send(n);
    child.on('message', message => {
      var result = message.result ? 'prime' : 'composite';
      resolve(result);
    });
    child.on('error', message => {reject(message)});
  });
}
<commit_msg>Add header comment + cleanup<commit_after>// Similar to primeserver-promises, but using async/await.
//
// Requires a Redis server to run in the background, listening on the default
// port.
//
// Eli Bendersky [http://eli.thegreenplace.net]
// This code is in the public domain.
var child_process = require('child_process');
var net = require('net');
var redis = require('redis');
var utils = require('./utils.js');
const {promisify} = require('util');

// Create a Redis client. This connects to a Redis server running on the local
// machine at the default port.
var redis_client = redis.createClient();

const redisGetAsync = promisify(redis_client.get).bind(redis_client);
const redisSetAsync = promisify(redis_client.set).bind(redis_client);

var portnum = 8070;
if (process.argv.length > 2) {
  portnum = process.argv[2];
}

var server = net.createServer();
server.on('connection', handleConnection);

server.listen(portnum, function() {
  console.log('Serving on port %d', portnum);
});

function handleConnection(conn) {
  var remoteAddress = conn.remoteAddress + ':' + conn.remotePort;
  console.log('peer %s connected', remoteAddress);

  conn.on('data', onConnData);
  conn.once('close', onConnClose);
  conn.on('error', onConnError);

  async function onConnData(d) {
    var num = utils.buf2num(d);
    console.log('num %d', num);

    try {
      var cachekey = 'primecache:' + num;
      var cached = await redisGetAsync(cachekey);

      if (cached === null) {
        var computed = await isPrimeAsync(num);
        await redisSetAsync(cachekey, computed);
        conn.write(computed + '\n');
      } else {
        console.log('cached num %d is %s', num, cached);
        conn.write(cached + '\n');
      }
    } catch (err) {
      console.log('error:', err);
    }
  }

  function onConnClose() {
    console.log('connection from %s closed', remoteAddress);
  }

  function onConnError(err) {
    console.log('connection %s error: %s', remoteAddress, err.message);
  }
}

async function isPrimeAsync(n) {
  return new Promise((resolve, reject) => {
    var child = child_process.fork('./primeworker.js');
    child.send(n);
    child.on('message', message => {
      var result = message.result ? 'prime' : 'composite';
      resolve(result);
    });
    child.on('error', message => {reject(message)});
  });
}
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react'
import './FirebaseChat.scss'

import Messages from './Messages'

export default class FirebaseChat extends Component {
  componentWillMount () {
    this.props.checkAuthentication()
  }

  componentDidMount () {
    let user = this.props.chat.user ? this.props.chat.user : prompt('What is your name?')
    user = user === null ? `user${Math.floor(Math.random() * 9000) + 1000}` : user
    this.props.addUser(user)
    this.messageInput.focus()
  }

  shouldComponentUpdate (nextProps) {
    // No Firebase Authentication Found
    if (this.props.chat.isAuthenticated === null && nextProps.chat.isAuthenticated === false) {
      return true
    }

    // Skip First Update Render
    if (!this.props.chat.isAuthenticated && !nextProps.chat.isAuthenticated) {
      return false
    }

    return true
  }

  componentWillUpdate (nextProps) {
    if (this.props.chat.isAuthenticated === null && nextProps.chat.isAuthenticated === false) {
      this.props.authenticateUser()
    }

    // Load Chat History
    if (this.props.chat.isAuthenticated === null && nextProps.chat.isAuthenticated === true) {
      this.props.loadMessages()
    }
  }

  render () {
    const user = this.props.chat.user ? `@${this.props.chat.user}` : ''
    return (

{user}

                <input type='text' className='input is-medium is-expanded' placeholder='Message'
                  ref={(input) => { this.messageInput = input }}
                  onChange={this.props.handleChange} value={this.props.chat.message}
                  onKeyDown={this.props.handleSubmit} />

                  Send

            <Messages user={this.props.chat.user} messages={this.props.chat.messages} />

    )
  }
}

FirebaseChat.propTypes = {
  chat : PropTypes.object.isRequired,
  checkAuthentication: PropTypes.func.isRequired,
  authenticateUser: PropTypes.func.isRequired,
  loadMessages: PropTypes.func.isRequired,
  addUser: PropTypes.func.isRequired,
  handleChange : PropTypes.func.isRequired,
  handleSubmit : PropTypes.func.isRequired
}
<commit_msg>Fixed Lifecycle Issue<commit_after>import React, { Component, PropTypes } from 'react'
import './FirebaseChat.scss'

import Messages from './Messages'

export default class FirebaseChat extends Component {
  componentWillMount () {
    this.props.checkAuthentication()
  }

  componentDidMount () {
    let user = this.props.chat.user ? this.props.chat.user : prompt('What is your name?')
    user = user === null ? `user${Math.floor(Math.random() * 9000) + 1000}` : user
    this.props.addUser(user)
    this.messageInput.focus()
  }

  shouldComponentUpdate (nextProps) {
    // No Firebase Authentication Found
    if (this.props.chat.isAuthenticated === null && nextProps.chat.isAuthenticated === false) {
      return true
    }

    // Skip First Update Render
    if (!this.props.chat.isAuthenticated && !nextProps.chat.isAuthenticated) {
      return false
    }

    return true
  }

  componentWillUpdate (nextProps) {
    if (this.props.chat.isAuthenticated === null && nextProps.chat.isAuthenticated === false) {
      this.props.authenticateUser()
    }

    // Load Chat History
    if (!this.props.chat.isAuthenticated && nextProps.chat.isAuthenticated) {
      this.props.loadMessages()
    }
  }

  render () {
    const user = this.props.chat.user ? `@${this.props.chat.user}` : ''
    return (

{user}

                <input type='text' className='input is-medium is-expanded' placeholder='Message'
                  ref={(input) => { this.messageInput = input }}
                  onChange={this.props.handleChange} value={this.props.chat.message}
                  onKeyDown={this.props.handleSubmit} />

                  Send

            <Messages user={this.props.chat.user} messages={this.props.chat.messages} />

    )
  }
}

FirebaseChat.propTypes = {
  chat : PropTypes.object.isRequired,
  checkAuthentication: PropTypes.func.isRequired,
  authenticateUser: PropTypes.func.isRequired,
  loadMessages: PropTypes.func.isRequired,
  addUser: PropTypes.func.isRequired,
  handleChange : PropTypes.func.isRequired,
  handleSubmit : PropTypes.func.isRequired
}
<|endoftext|>


<commit_before>// Select DOM elements to work with
const welcomeDiv = document.getElementById("WelcomeMessage");
const signInButton = document.getElementById("loginRedirect");
const cardDiv = document.getElementById("card-div");
const mailButton = document.getElementById("readMail");
const profileButton = document.getElementById("seeProfile");
const profileDiv = document.getElementById("profile-div");

function showWelcomeMessage(account) {
    // Reconfiguring DOM elements
    cardDiv.style.display = 'initial';
    welcomeDiv.innerHTML = `Welcome ${account.username}`;
    // signInButton.nextElementSibling.style.display = 'none';
    signInButton.setAttribute("onclick", "signOut();");
    signInButton.setAttribute('class', "btn btn-success ml-auto")
    signInButton.innerHTML = "Sign Out";
}

function updateUI(data, endpoint) {
    console.log('Graph API responded at: ' + new Date().toString());

    if (endpoint === graphConfig.graphMeEndpoint) {
        const title = document.createElement('p');
        title.innerHTML = "Title: " + data.jobTitle;
        const email = document.createElement('p');
        email.innerHTML = "Mail: " + data.mail;
        const phone = document.createElement('p');
        phone.innerHTML = "Phone: " + data.businessPhones[0];
        const address = document.createElement('p');
        address.innerHTML = "Location: " + data.officeLocation;
        profileDiv.appendChild(title);
        profileDiv.appendChild(email);
        profileDiv.appendChild(phone);
        profileDiv.appendChild(address);
    } else if (endpoint === graphConfig.graphMailEndpoint) {
        if (data.value.length < 1) {
            alert("Your mailbox is empty!")
        } else {
            const tabList = document.getElementById("list-tab");
            const tabContent = document.getElementById("nav-tabContent");

            data.value.map((d, i) => {
                // Keeping it simple
                if (i < 10) {
                    const listItem = document.createElement("a");
                    listItem.setAttribute("class", "list-group-item list-group-item-action")
                    listItem.setAttribute("id", "list" + i + "list")
                    listItem.setAttribute("data-toggle", "list")
                    listItem.setAttribute("href", "#list" + i)
                    listItem.setAttribute("role", "tab")
                    listItem.setAttribute("aria-controls", i)
                    listItem.innerHTML = d.subject;
                    tabList.appendChild(listItem)

                    const contentItem = document.createElement("div");
                    contentItem.setAttribute("class", "tab-pane fade")
                    contentItem.setAttribute("id", "list" + i)
                    contentItem.setAttribute("role", "tabpanel")
                    contentItem.setAttribute("aria-labelledby", "list" + i + "list")
                    contentItem.innerHTML = " from: " + d.from.emailAddress.address + "

" + d.bodyPreview + "...";
                    tabContent.appendChild(contentItem);
                }
            });
        }
    }
}

function printRequest(){
    if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.print) {
        window.iOSPrintCapability = true;
    }

    if (window.iOSPrintCapability)
        window.webkit.messageHandlers.print.postMessage('print');
    else
        window.print();
}

function pushRequest(){
    if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers['push-permission']) {
        window.iOSPushCapability = true;
    }

    if (window.iOSPushCapability)
        window.webkit.messageHandlers['push-permission'].postMessage('push-permission');
}
window.addEventListener('push-permission', (message) => {
    if (message && message.detail){
        const buttonWrap = document.getElementById('push-permission-wrap');
        switch (message.detail) {
            case 'granted':
                buttonWrap.getElementsByClassName('badge-success')[0].style = '';
                buttonWrap.getElementsByClassName('badge-danger')[0].style = 'display:none';
                break;
            default:
                buttonWrap.getElementsByClassName('badge-success')[0].style = 'display:none';
                buttonWrap.getElementsByClassName('badge-danger')[0].style = '';
                break;
        }
    }
});
window.addEventListener('push-notification', (message) => {
    if (message && message.detail){
        alert(JSON.stringify(message.detail));
    }
});<commit_msg>improve alert fields for demo<commit_after>// Select DOM elements to work with
const welcomeDiv = document.getElementById("WelcomeMessage");
const signInButton = document.getElementById("loginRedirect");
const cardDiv = document.getElementById("card-div");
const mailButton = document.getElementById("readMail");
const profileButton = document.getElementById("seeProfile");
const profileDiv = document.getElementById("profile-div");

function showWelcomeMessage(account) {
    // Reconfiguring DOM elements
    cardDiv.style.display = 'initial';
    welcomeDiv.innerHTML = `Welcome ${account.username}`;
    // signInButton.nextElementSibling.style.display = 'none';
    signInButton.setAttribute("onclick", "signOut();");
    signInButton.setAttribute('class', "btn btn-success ml-auto")
    signInButton.innerHTML = "Sign Out";
}

function updateUI(data, endpoint) {
    console.log('Graph API responded at: ' + new Date().toString());

    if (endpoint === graphConfig.graphMeEndpoint) {
        const title = document.createElement('p');
        title.innerHTML = "Title: " + data.jobTitle;
        const email = document.createElement('p');
        email.innerHTML = "Mail: " + data.mail;
        const phone = document.createElement('p');
        phone.innerHTML = "Phone: " + data.businessPhones[0];
        const address = document.createElement('p');
        address.innerHTML = "Location: " + data.officeLocation;
        profileDiv.appendChild(title);
        profileDiv.appendChild(email);
        profileDiv.appendChild(phone);
        profileDiv.appendChild(address);
    } else if (endpoint === graphConfig.graphMailEndpoint) {
        if (data.value.length < 1) {
            alert("Your mailbox is empty!")
        } else {
            const tabList = document.getElementById("list-tab");
            const tabContent = document.getElementById("nav-tabContent");

            data.value.map((d, i) => {
                // Keeping it simple
                if (i < 10) {
                    const listItem = document.createElement("a");
                    listItem.setAttribute("class", "list-group-item list-group-item-action")
                    listItem.setAttribute("id", "list" + i + "list")
                    listItem.setAttribute("data-toggle", "list")
                    listItem.setAttribute("href", "#list" + i)
                    listItem.setAttribute("role", "tab")
                    listItem.setAttribute("aria-controls", i)
                    listItem.innerHTML = d.subject;
                    tabList.appendChild(listItem)

                    const contentItem = document.createElement("div");
                    contentItem.setAttribute("class", "tab-pane fade")
                    contentItem.setAttribute("id", "list" + i)
                    contentItem.setAttribute("role", "tabpanel")
                    contentItem.setAttribute("aria-labelledby", "list" + i + "list")
                    contentItem.innerHTML = " from: " + d.from.emailAddress.address + "

" + d.bodyPreview + "...";
                    tabContent.appendChild(contentItem);
                }
            });
        }
    }
}

function printRequest(){
    if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.print) {
        window.iOSPrintCapability = true;
    }

    if (window.iOSPrintCapability)
        window.webkit.messageHandlers.print.postMessage('print');
    else
        window.print();
}

function pushRequest(){
    if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers['push-permission']) {
        window.iOSPushCapability = true;
    }

    if (window.iOSPushCapability)
        window.webkit.messageHandlers['push-permission'].postMessage('push-permission');
}
window.addEventListener('push-permission', (message) => {
    if (message && message.detail){
        const buttonWrap = document.getElementById('push-permission-wrap');
        switch (message.detail) {
            case 'granted':
                buttonWrap.getElementsByClassName('badge-success')[0].style = '';
                buttonWrap.getElementsByClassName('badge-danger')[0].style = 'display:none';
                break;
            default:
                buttonWrap.getElementsByClassName('badge-success')[0].style = 'display:none';
                buttonWrap.getElementsByClassName('badge-danger')[0].style = '';
                break;
        }
    }
});
window.addEventListener('push-notification', (message) => {
    if (message && message.detail) {
        console.log(message.detail);
        if (message.detail.aps && message.detail.aps.alert)
            alert(`${message.detail.aps.alert.title} ${message.detail.aps.alert.body}`);
    }
});<|endoftext|>


<commit_before>/**
 * Created by ststa on 12/3/2016.
 */

function init() {

    //this.player = data.handle;
    //this.position = data.message;
    //
    //console.log(data);
    //this.getInfo = function () {
    //    return this.color + ' ' + this.type + ' apple';
    //};

    // Position Variables
    var x = 0;
    var y = 0;

    // Speed - Velocity
    var vx = 0;
    var vy = 0;

    // Acceleration
    this.ax = 0;
    this.ay = 0;

    var delay = 10;
    var vMultiplier = 0.01;

//TODO make ax and ay get the value from position(data.message)
//var streetaddress= addy.substr(0, addy.indexOf(','));
//    window.ondevicemotion = function (event) {
//        ax = this.position.substr(0, this.position.indexOf('y'));
//        ay = this.position.substr(this.position.indexOf("y") + 1);
    //console.log("Accelerometer data - x: " + event.accelerationIncludingGravity.x + " y: " + event.accelerationIncludingGravity.y + " z: " + event.accelerationIncludingGravity.z);

    //this.moveFish = moveTheFish;
    //
    //function moveTheFish(data) {
    //    var position = data.message;
    //
    //    init.ax = position.substr(0, position.indexOf('y'));
    //    init.ay = position.substr(position.indexOf("y") + 1);
    //}

    setInterval(function () {
        if (!isNaN(init.ay) && !isNaN(init.ax)) {
            vy = vy + -(init.ay);
            vx = vx + init.ax;
            console.log("ay" + init.ay + "ax" + init.ax);

            var ball = document.getElementById("ball");
            y = parseInt(y + vy * vMultiplier);
            x = parseInt(x + vx * vMultiplier);

            if (x < 0) {
                x = 0;
                vx = 0;
            }
            if (y < 0) {
                y = 0;
                vy = 0;
            }
            if (x > window.innerWidth - 20) {
                x = window.innerWidth - 20;
                vx = 0;
            }
            if (y > window.innerHeight - 20) {
                y = window.innerHeight - 20;
                vy = 0;
            }

            ball.style.top = y + "px";
            ball.style.left = x + "px";
        }
    }, delay);
}

function moveFish(data) {
    this.position = data.message;

    init.ax = this.position.substr(0, this.position.indexOf('y'));
    init.ay = this.position.substr(this.position.indexOf("y") + 1);
}

init();<commit_msg>Working till here<commit_after>/**
 * Created by ststa on 12/3/2016.
 */

function init() {

    //this.player = data.handle;
    //this.position = data.message;
    //
    //console.log(data);
    //this.getInfo = function () {
    //    return this.color + ' ' + this.type + ' apple';
    //};

    // Position Variables
    var x = 0;
    var y = 0;

    // Speed - Velocity
    var vx = 0;
    var vy = 0;

    // Acceleration
    this.ax = 0;
    this.ay = 0;

    var delay = 10;
    var vMultiplier = 0.01;

//TODO Figure out why ball moving on the x-axis is not working

    setInterval(function () {
        if (!isNaN(init.ay) && !isNaN(init.ax)) {
            vy = vy + -(init.ay);
            vx = vx + init.ax;
            console.log("ay" + init.ay + "ax" + init.ax);

            var ball = document.getElementById("ball");
            y = parseInt(y + vy * vMultiplier);
            x = parseInt(x + vx * vMultiplier);

            if (x < 0) {
                x = 0;
                vx = 0;
            }
            if (y < 0) {
                y = 0;
                vy = 0;
            }
            if (x > window.innerWidth - 20) {
                x = window.innerWidth - 20;
                vx = 0;
            }
            if (y > window.innerHeight - 20) {
                y = window.innerHeight - 20;
                vy = 0;
            }

            ball.style.top = y + "px";
            ball.style.left = x + "px";
        }
    }, delay);
}

function moveFish(data) {
    this.position = data.message;

    init.ax = this.position.substr(0, this.position.indexOf('y'));
    init.ay = this.position.substr(this.position.indexOf("y") + 1);
}

init();<|endoftext|>


<commit_before>/* eslint max-len: 0 */
/* eslint no-unused-vars: 0*/
import React from 'react';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';

const jobs = [];

function addProducts(quantity) {
  const startId = jobs.length;
  for (let i = 0; i < quantity; i++) {
    const id = startId + i;
    jobs.push({
      id: id,
      name: 'Application_Name_ ' + id,
      active: i % 2 === 0 ? true : false
    });
  }
}

addProducts(5);

class ActiveFormatter extends React.Component {
  render() {
    return (
      <input type='checkbox' checked={ this.props.active }/>
    );
  }
}

function activeFormatter(cell, row, enumObject, index) {
  console.log(`The row index: ${index}`);
  return (
    <ActiveFormatter active={ cell } />
  );
}

export default class GetRowIndexTable extends React.Component {
  render() {
    return (
      <BootstrapTable data={ jobs }>
          <TableHeaderColumn dataField='id' isKey={ true }>Job ID</TableHeaderColumn>
          <TableHeaderColumn dataField='name'>Job Name</TableHeaderColumn>
          <TableHeaderColumn dataField='active' dataFormat={ activeFormatter }>Active</TableHeaderColumn>
      </BootstrapTable>
    );
  }
}
<commit_msg>fix no-console warning<commit_after>/* eslint max-len: 0 */
/* eslint no-unused-vars: 0*/
/* eslint no-console: 0*/
import React from 'react';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';

const jobs = [];

function addProducts(quantity) {
  const startId = jobs.length;
  for (let i = 0; i < quantity; i++) {
    const id = startId + i;
    jobs.push({
      id: id,
      name: 'Application_Name_ ' + id,
      active: i % 2 === 0 ? true : false
    });
  }
}

addProducts(5);

class ActiveFormatter extends React.Component {
  render() {
    return (
      <input type='checkbox' checked={ this.props.active }/>
    );
  }
}

function activeFormatter(cell, row, enumObject, index) {
  console.log(`The row index: ${index}`);
  return (
    <ActiveFormatter active={ cell } />
  );
}

export default class GetRowIndexTable extends React.Component {
  render() {
    return (
      <BootstrapTable data={ jobs }>
          <TableHeaderColumn dataField='id' isKey={ true }>Job ID</TableHeaderColumn>
          <TableHeaderColumn dataField='name'>Job Name</TableHeaderColumn>
          <TableHeaderColumn dataField='active' dataFormat={ activeFormatter }>Active</TableHeaderColumn>
      </BootstrapTable>
    );
  }
}
<|endoftext|>


<commit_before>'use strict';
const assert = require('chai').assert;
const config = require('../api/config.js');
const http = require('http');
const createRetryJsonStream = require('../lib/tolerant-json-stream.js');

describe('tolerant-json-stream', () => {

  describe('when connected to another node', () => {
    let response, server, stream;
    const url = `http://localhost:${config.port}/sets/a,b`;

    beforeEach(done => {
      server = http.createServer();
      server.once('request', (req, res) => {
        response = res;
        done();
      });
      server.listen(config.port, () => {
        stream = createRetryJsonStream(url);
      });
    });

    afterEach(done => {
      stream.stop();
      server.close(done); // waits until retry json has dropped connection
    });

    it('emits connect event', done => {
      response.flushHeaders();
      stream.once('connect', () => done());
    });

    it('emits initial object received from the stream', done => {
      response.write(JSON.stringify({ a: 1 }) + '\r\n');
      stream.once('data', data => {
        assert.equal(data.a, 1);
        done();
      });
    });

    it('emits subsequent objects received from the stream', done => {
      response.write(JSON.stringify({ a: 1 }) + '\r\n');
      stream.once('data', () => {
        response.write(JSON.stringify({ a: 2 }) + '\r\n');
        stream.once('data', data => {
          assert.equal(data.a, 2);
          done();
        });
      });
    });

    describe('when the server ends the current request', () => {
      it('reconnects and receives new data', done => {
        testReconnect(() => response.end(), done);
      });

      it('emits connectionError event', done => {
        response.end();
        stream.once('connectionError', err => {
          assert.instanceOf(err, Error);
          assert.equal(err.message, 'server ended request');
          done();
        });
      });
    });

    describe('when the server destroys the current request', () => {
      it('reconnects and receives new data', done => {
        testReconnect(() => response.destroy(), done);
      });

      it('emits connectionError event', done => {
        response.end();
        stream.once('connectionError', err => {
          assert.instanceOf(err, Error);
          assert.equal(err.message, 'server ended request');
          done();
        });
      });
    });

    describe('when the server dies', () => {
      it('emits connectionError event', done => {
        response.end();
        server.close();
        server.close = (cb) => cb(); // stub so beforeEach doesn't break

        stream.once('connectionError', err => {
          assert.instanceOf(err, Error);
          assert.equal(err.message, 'server ended request');
          done();
        });
      });

      it('emits connectionError for subsequent reconnection failure', done => {
        response.end();
        server.close();
        server.close = (cb) => cb(); // stub so beforeEach doesn't break

        stream.once('connectionError', () => {
          stream.once('connectionError', err => {
            assert.instanceOf(err, Error);
            assert.match(err.message, /ECONNREFUSED/);
            done();
          });
        });
      });

      it('reconnection attempts back off');
    });

    describe('when the server is slow to respond', () => {
      it('should timeout request and try again');
      it('should backoff on retries on timeouts');
    });

    function testReconnect(terminate, done) {
      response.write(JSON.stringify({ a: 1 }) + '\r\n');
      stream.once('data', () => {
        let connected = false;

        // terminate the initial request to kick things off
        terminate();

        // wait for next request to server
        server.once('request', (req, secondResponse) => {
          secondResponse.write(JSON.stringify({ a: 2 }) + '\r\n');
        });

        stream.once('connect', () => connected = true);

        // assert state is emitted
        stream.once('data', data => {
          assert.isTrue(connected);
          assert.equal(data.a, 2);
          done();
        });
      });
    }
  });

  describe('error handling', () => {
    it('expects a node url', () => {
      assert.throws(() => {
        createRetryJsonStream(null, ['a','b']);
      }, 'url is required');
    });

    it('handles bad json data');
  });
});
<commit_msg>tolerant-json-stream: correct connection destroyed test.<commit_after>'use strict';
const assert = require('chai').assert;
const config = require('../api/config.js');
const http = require('http');
const createRetryJsonStream = require('../lib/tolerant-json-stream.js');

describe('tolerant-json-stream', () => {

  describe('when connected to another node', () => {
    let response, server, stream;
    const url = `http://localhost:${config.port}/sets/a,b`;

    beforeEach(done => {
      server = http.createServer();
      server.once('request', (req, res) => {
        response = res;
        done();
      });
      server.listen(config.port, () => {
        stream = createRetryJsonStream(url);
      });
    });

    afterEach(done => {
      stream.stop();
      server.close(done); // waits until retry json has dropped connection
    });

    it('emits connect event', done => {
      response.flushHeaders();
      stream.once('connect', () => done());
    });

    it('emits initial object received from the stream', done => {
      response.write(JSON.stringify({ a: 1 }) + '\r\n');
      stream.once('data', data => {
        assert.equal(data.a, 1);
        done();
      });
    });

    it('emits subsequent objects received from the stream', done => {
      response.write(JSON.stringify({ a: 1 }) + '\r\n');
      stream.once('data', () => {
        response.write(JSON.stringify({ a: 2 }) + '\r\n');
        stream.once('data', data => {
          assert.equal(data.a, 2);
          done();
        });
      });
    });

    describe('when the server ends the current request', () => {
      it('reconnects and receives new data', done => {
        testReconnect(() => response.end(), done);
      });

      it('emits connectionError event', done => {
        response.end();
        stream.once('connectionError', err => {
          assert.instanceOf(err, Error);
          assert.equal(err.message, 'server ended request');
          done();
        });
      });
    });

    describe('when the server destroys the current request', () => {
      it('reconnects and receives new data', done => {
        testReconnect(() => response.destroy(), done);
      });

      it('emits connectionError event', done => {
        response.destroy();
        stream.once('connectionError', err => {
          assert.instanceOf(err, Error);
          assert.equal(err.message, 'socket hang up');
          done();
        });
      });
    });

    describe('when the server dies', () => {
      it('emits connectionError event', done => {
        response.end();
        server.close();
        server.close = (cb) => cb(); // stub so beforeEach doesn't break

        stream.once('connectionError', err => {
          assert.instanceOf(err, Error);
          assert.equal(err.message, 'server ended request');
          done();
        });
      });

      it('emits connectionError for subsequent reconnection failure', done => {
        response.end();
        server.close();
        server.close = (cb) => cb(); // stub so beforeEach doesn't break

        stream.once('connectionError', () => {
          stream.once('connectionError', err => {
            assert.instanceOf(err, Error);
            assert.match(err.message, /ECONNREFUSED/);
            done();
          });
        });
      });

      it('reconnection attempts back off');
    });

    describe('when the server is slow to respond', () => {
      it('should timeout request and try again');
      it('should backoff on retries on timeouts');
    });

    function testReconnect(terminate, done) {
      response.write(JSON.stringify({ a: 1 }) + '\r\n');
      stream.once('data', () => {
        let connected = false;

        // terminate the initial request to kick things off
        terminate();

        // wait for next request to server
        server.once('request', (req, secondResponse) => {
          secondResponse.write(JSON.stringify({ a: 2 }) + '\r\n');
        });

        stream.once('connect', () => connected = true);

        // assert state is emitted
        stream.once('data', data => {
          assert.isTrue(connected);
          assert.equal(data.a, 2);
          done();
        });
      });
    }
  });

  describe('error handling', () => {
    it('expects a node url', () => {
      assert.throws(() => {
        createRetryJsonStream(null, ['a','b']);
      }, 'url is required');
    });

    it('handles bad json data');
  });
});
<|endoftext|>


<commit_before>'use strict';

eventsApp.controller('greetings', function($scope) {
    var stuff = [];

    $scope.sayHi = function() {
        //window.alert("Hello");
        alert(stuff.join());
    };

    this.add = function(add) {
        stuff.push(add);
    };

    this.add("hi");
});

eventsApp.directive("greetings", function () {
    return {
        restrict: 'E',
        replace: true,
        template: "<button class='btn' ng-click='sayHello()'>Say Hello</button>",
        scope: {},
        controller: function($scope) {
            var stuff = [];

            $scope.sayHello = function() {
                //window.alert("Hello");
                alert(stuff.join());
            };

            $scope.add = function(add) {
                stuff.push(add);
            };

            $scope.add("hello");

            this.add = function(add) {
                $scope.add(add);
            }
        },
        //controller: 'greetings',
        //controller: '@',
        //name: 'ctrl'        // controller name attribute to be specified in the directive
    };
}).directive("add1", function() {
    return {
        restrict: 'A',
        require: 'greetings',
        priority: 1,
        link: function(scope, element, attrs, controller) {
            controller.add("1");
        }
    }
}).directive("add2", function() {
    return {
        restrict: 'A',
        require: 'greetings',
        priority: 2,
        link: function(scope, element, attrs, controller) {
            controller.add("2");
        }
    }
}).directive("greetings2", function() {
    return {
        restrict: 'E',
        replace: true,
        template: "<button class='btn' ng-click='sayHi()'>Say Hi</button>",
        scope: {},
        controller: 'greetings'
        //controller: '@',      // this construct won't work with controller sharing
        //name: 'ctrl'
    }
}).directive("addx", function() {
    return {
        restrict: 'A',
        require: 'greetings2',
        link: function(scope, element, attrs, controller) {
            controller.add("x");
        }
    }
});
<commit_msg>directive controller sharing - negative priority<commit_after>'use strict';

eventsApp.controller('greetings', function($scope) {
    var stuff = [];

    $scope.sayHi = function() {
        //window.alert("Hello");
        alert(stuff.join());
    };

    this.add = function(add) {
        stuff.push(add);
    };

    this.add("hi");
});

eventsApp.directive("greetings", function () {
    return {
        restrict: 'E',
        replace: true,
        priority: -1,
        template: "<button class='btn' ng-click='sayHello()'>Say Hello</button>",
        scope: {},
        controller: function($scope) {
            var stuff = [];

            $scope.sayHello = function() {
                //window.alert("Hello");
                alert(stuff.join());
            };

            $scope.add = function(add) {
                stuff.push(add);
            };

            $scope.add("hello");

            this.add = function(add) {
                $scope.add(add);
            }
        },
        //controller: 'greetings',
        //controller: '@',
        //name: 'ctrl'        // controller name attribute to be specified in the directive
    };
}).directive("add1", function() {
    return {
        restrict: 'A',
        require: 'greetings',
        priority: -1,
        terminal: true,
        link: function(scope, element, attrs, controller) {
            controller.add("1");
        }
    }
}).directive("add2", function() {
    return {
        restrict: 'A',
        require: 'greetings',
        priority: -2,
        link: function(scope, element, attrs, controller) {
            controller.add("2");
        }
    }
}).directive("greetings2", function() {
    return {
        restrict: 'E',
        replace: true,
        template: "<button class='btn' ng-click='sayHi()'>Say Hi</button>",
        scope: {},
        controller: 'greetings'
        //controller: '@',      // this construct won't work with controller sharing
        //name: 'ctrl'
    }
}).directive("addx", function() {
    return {
        restrict: 'A',
        require: 'greetings2',
        link: function(scope, element, attrs, controller) {
            controller.add("x");
        }
    }
});
<|endoftext|>


<commit_before>import { asset } from 'react-vr';

import { types as actions }  from '../actions';

const modelDefinitions = {
    CHAIR: {
        source: { obj: asset('collection/chair/dchair_obj.obj')},
        rotationY: 0,
        scale: 0.05,
        distance: -4,
    },
    BED: {
        source: {
            obj: asset('collection/bed/cama.obj'),
            mtl: asset('collection/bed/cama.mtl'),
        },
        rotationY: 0,
        scale: 0.1,
        distance: -4,
    },
    BED_TABLE: {
        source: {
            obj: asset('collection/bed-table/bed-table.obj'),
            mtl: asset('collection/bed-table/bed-table.mtl'),
        },
        rotationY: 0,
        scale: 0.05,
        distance: -4,
    },
    SOFA: {
        source: {
            obj: asset('collection/sofa/sofa1.obj'),
            mtl: asset('collection/sofa/sofa1.mtl'),
        },
        rotationY: 0,
        scale: 0.05,
        distance: -4,
    }
};

const newModel = ({ head, modelType, modelId }) => {
    const defaultParams = modelDefinitions[modelType];
    if (!defaultParams) throw `Unsupported model type: ${modelType}`;

    return {
        ...defaultParams,
        id: modelId,
        headRot: head.rot,
    }
};

const applyHeadRotation = (model, head) => {
    return {
        ...model,
        headRot: head.rot,
    }
};

const moveModel = (model, distance) => {
    const newDistance = model.distance + distance;
    return {
        ...model,
        distance: newDistance <= 0 ? newDistance : 0,
    }
};

const rotateModel = (model, angle) => {
    return {
        ...model,
        rotationY: model.rotationY + angle,
    }
};

export default reduce = (
    state = { models: [], currentModelId: null, focusedModelId: null },
    action
) => {
    switch (action.type) {
        case actions.object.create:
            return {
                models: [...state.models, newModel(action)],
                currentModelId: action.modelId,
                focusedModelId: state.focusedModelId,
            };
        case actions.object.delete:
            return {
                models: state.models.filter((m) => m.id !== action.modelId),
                currentModelId: (
                    state.currentModelId !== action.modelId
                    ? state.currentModelId
                    : null
                ),
                focusedModelId: (
                    state.focusedModelId !== action.modelId
                    ? state.focusedModelId
                    :null
                )
            };
        case actions.object.select:
            return {
                models: state.models,
                currentModelId: action.modelId,
                focusedModelId: state.focusedModelId,
            };
        case actions.object.unselect:
            return {
                models: state.models.map((m) => (
                    m.id === state.currentModelId
                    ? applyHeadRotation(m, action.head)
                    : m
                )),
                currentModelId: null,
                focusedModelId: state.focusedModelId,
            };
        case actions.object.moveCloser:
            return {
                models: state.models.map((m) => (
                    m.id === state.currentModelId
                    ? moveModel(m, 1)
                    : m
                )),
                currentModelId: state.currentModelId,
                focusedModelId: state.focusedModelId,
            };
        case actions.object.moveFurther:
            return {
                models: state.models.map((m) => (
                    m.id === state.currentModelId
                    ? moveModel(m, -1)
                    : m
                )),
                currentModelId: state.currentModelId,
                focusedModelId: state.focusedModelId,
            };
        case actions.object.rotate:
            return {
                models: state.models.map((m) => (
                   m.id === state.currentModelId
                   ? rotateModel(m, 3)
                   : m
                )),
                currentModelId: state.currentModelId,
                focusedModelId: state.focusedModelId,
            };
        case actions.object.focus:
            return {
                models: state.models,
                currentModelId: state.currentModelId,
                focusedModelId: action.modelId,
            };
        case actions.object.blur:
            return {
                models: state.models,
                currentModelId: state.currentModelId,
                focusedModelId: (
                    state.focusedModelId === action.modelId
                    ? null
                    : state.focusedModelId
                ),
            }
    }
    return state;
};<commit_msg>change default distance for objects<commit_after>import { asset } from 'react-vr';

import { types as actions }  from '../actions';

const modelDefinitions = {
    CHAIR: {
        source: { obj: asset('collection/chair/dchair_obj.obj')},
        rotationY: 0,
        scale: 0.05,
        distance: -5,
    },
    BED: {
        source: {
            obj: asset('collection/bed/cama.obj'),
            mtl: asset('collection/bed/cama.mtl'),
        },
        rotationY: 0,
        scale: 0.1,
        distance: -4,
    },
    BED_TABLE: {
        source: {
            obj: asset('collection/bed-table/bed-table.obj'),
            mtl: asset('collection/bed-table/bed-table.mtl'),
        },
        rotationY: 0,
        scale: 0.05,
        distance: -6,
    },
    SOFA: {
        source: {
            obj: asset('collection/sofa/sofa1.obj'),
            mtl: asset('collection/sofa/sofa1.mtl'),
        },
        rotationY: 0,
        scale: 0.05,
        distance: -4,
    }
};

const newModel = ({ head, modelType, modelId }) => {
    const defaultParams = modelDefinitions[modelType];
    if (!defaultParams) throw `Unsupported model type: ${modelType}`;

    return {
        ...defaultParams,
        id: modelId,
        headRot: head.rot,
    }
};

const applyHeadRotation = (model, head) => {
    return {
        ...model,
        headRot: head.rot,
    }
};

const moveModel = (model, distance) => {
    const newDistance = model.distance + distance;
    return {
        ...model,
        distance: newDistance <= 0 ? newDistance : 0,
    }
};

const rotateModel = (model, angle) => {
    return {
        ...model,
        rotationY: model.rotationY + angle,
    }
};

export default reduce = (
    state = { models: [], currentModelId: null, focusedModelId: null },
    action
) => {
    switch (action.type) {
        case actions.object.create:
            return {
                models: [...state.models, newModel(action)],
                currentModelId: action.modelId,
                focusedModelId: state.focusedModelId,
            };
        case actions.object.delete:
            return {
                models: state.models.filter((m) => m.id !== action.modelId),
                currentModelId: (
                    state.currentModelId !== action.modelId
                    ? state.currentModelId
                    : null
                ),
                focusedModelId: (
                    state.focusedModelId !== action.modelId
                    ? state.focusedModelId
                    :null
                )
            };
        case actions.object.select:
            return {
                models: state.models,
                currentModelId: action.modelId,
                focusedModelId: state.focusedModelId,
            };
        case actions.object.unselect:
            return {
                models: state.models.map((m) => (
                    m.id === state.currentModelId
                    ? applyHeadRotation(m, action.head)
                    : m
                )),
                currentModelId: null,
                focusedModelId: state.focusedModelId,
            };
        case actions.object.moveCloser:
            return {
                models: state.models.map((m) => (
                    m.id === state.currentModelId
                    ? moveModel(m, 1)
                    : m
                )),
                currentModelId: state.currentModelId,
                focusedModelId: state.focusedModelId,
            };
        case actions.object.moveFurther:
            return {
                models: state.models.map((m) => (
                    m.id === state.currentModelId
                    ? moveModel(m, -1)
                    : m
                )),
                currentModelId: state.currentModelId,
                focusedModelId: state.focusedModelId,
            };
        case actions.object.rotate:
            return {
                models: state.models.map((m) => (
                   m.id === state.currentModelId
                   ? rotateModel(m, 3)
                   : m
                )),
                currentModelId: state.currentModelId,
                focusedModelId: state.focusedModelId,
            };
        case actions.object.focus:
            return {
                models: state.models,
                currentModelId: state.currentModelId,
                focusedModelId: action.modelId,
            };
        case actions.object.blur:
            return {
                models: state.models,
                currentModelId: state.currentModelId,
                focusedModelId: (
                    state.focusedModelId === action.modelId
                    ? null
                    : state.focusedModelId
                ),
            }
    }
    return state;
};
<|endoftext|>