<commit_before>
/****************************************************************************
 LICENSE: CC BY-NC-SA 4.0 https://creativecommons.org/licenses/by-nc-sa/4.0/
 This is an original driver by Elijah Parker <mail@timelapseplus.com>
 It is free to use in other projects for non-commercial purposes.  For a
 commercial license and consulting, please contact mail@timelapseplus.com
*****************************************************************************/

var util = require('util');
var async = require('async');
var EventEmitter = require('events').EventEmitter;
var ptp = require('../common/ptp-functions.js');
var fs = require('fs');

var driver = new EventEmitter();

driver.name = "Fujifilm";

function _logD() {
    if(arguments.length > 0) {
        arguments[0] = "PTP-FUJI: " + arguments[0];
    }
    console.log.apply(console, arguments);
}

driver.supportedCameras = {
    '04cb:02cb': {
            name: "Fuji X-Pro2",
            supports: {
                shutter: true,
                aperture: true,
                iso: true,
                liveview: true,
                target: true,
                focus: true,
            }
        },
    '04cb:02cd': {
            name: "Fuji X-T2",
            supports: {
                shutter: true,
                aperture: true,
                iso: true,
                liveview: true,
                target: true,
                focus: true,
            }
        },
    '04cb:02d7': {
            name: "Fuji X-H1",
            supports: {
                shutter: true,
                aperture: true,
                iso: true,
                liveview: true,
                target: true,
                focus: true,
            }
        },
    '04cb:02dd': {
            name: "Fuji X-T3",
            supports: {
                shutter: true,
                aperture: true,
                iso: true,
                liveview: true,
                target: true,
                focus: true,
            }
        },
}

var properties = {
    'shutter': {
        name: 'shutter',
        function: ptp.setPropU16,
        code: 0xD219,
        ev: true,
        values: [
            {name: '1s', ev: -6, code: 0},
        ]
    }
}

driver._error = function(camera, error) { // events received
    _logD("ERROR:", error);
};

driver._event = function(camera, data) { // events received
    _logD("EVENT:", data);
    ptp.parseEvent(data, function(type, event, param1, param2, param3) {
        if(event == ptp.PTP_EC_ObjectAdded) {
            _logD("object added:", param1);
        }
    });
};

driver.init = function(camera, callback) {
    ptp.init(camera._dev, function(err, di) {
        async.series([
            function(cb){ptp.setPropU16(camera._dev, 0xd38c, 1, cb);}, // PC mode
            //function(cb){ptp.setPropU16(camera._dev, 0xd207, 2, cb);}  // USB control
        ], function(err) {
            var capture = function() {
                driver.capture(camera, "", {}, function(err, thumb, filename, rawImage){
                    if(err) {
                        if(err != 0x2019) _logD("capture err result:", ptp.hex(err));
                    } else {
                        _logD("captureed image:", filename);
                    }
                    var delay = 1000;
                    if(err == 0x2019) delay = 50;
                    setTimeout(function() {
                        capture();
                    }, delay);
                });
            }
            //capture();
            callback && callback(err);
        });
    });
}

driver.set = function(camera, param, value, callback) {

}

function getImage(camera, timeout, callback) {
    var results = {
        thumb: null,
        filename: null,
        indexNumber: null,
        rawImage: null
    }

    var startTime = Date.now();

    var check = function() {
        if(Date.now() - startTime > timeout) {
            return callback && callback("timeout", results);
        }
        ptp.getPropData(camera._dev, 0xd212, function(err, data) { // wait if busy
            //console.log("data:", data);
            if(data.length >= 4 && data.readUInt16LE(2) == 0xD20E) {
                var getHandles = function() {
                    ptp.getObjectHandles(camera._dev, function(err, handles) {
                        if(handles.length > 0) {
                            var objectId = handles[0];
                            ptp.getObjectInfo(camera._dev, objectId, function(err, oi) {
                                //console.log(oi);
                                var image = null;
                                results.filename = oi.filename;
                                results.indexNumber = objectId;
                                if(camera.thumbnail) {
                                    ptp.getThumb(camera._dev, objectId, function(err, jpeg) {
                                        ptp.deleteObject(camera._dev, objectId, function() {
                                            results.thumb = jpeg;
                                            callback && callback(err, results);
                                        });
                                    })
                                } else {
                                    ptp.getObject(camera._dev, objectId, function(err, image) {
                                        ptp.deleteObject(camera._dev, objectId, function() {
                                            results.thumb = ptp.extractJpeg(image);
                                            results.rawImage = image;
                                            callback && callback(err, results);
                                        });
                                    })
                                }
                            });
                        } else {
                            setTimeout(getHandles, 50);
                        }
                    });
                }
                getHandles();
            } else {
                setTimeout(check, 50);
            }
        });
    }
    check();
}

driver.capture = function(camera, target, options, callback, tries) {
    var targetValue = (!target || target == "camera") ? 2 : 4;
    camera.thumbnail = true;
    var results = {};
    async.series([
        function(cb){ptp.setPropU16(camera._dev, 0xd20c, targetValue, cb);}, // set target
        function(cb){ptp.setPropU16(camera._dev, 0xd208, 0x0200, cb);},
        function(cb){ptp.ptpCapture(camera._dev, [0x0, 0x0], cb);},
        function(cb){
            var check = function() {
                ptp.getPropU16(camera._dev, 0xd209, function(err, data) { // wait if busy
                    if(data == 0x0001) {
                        check();
                    } else {
                        cb(err);
                    }
                });
            }
            check();
        },
        function(cb){ptp.setPropU16(camera._dev, 0xd208, 0x0304, cb);},
        function(cb){ptp.ptpCapture(camera._dev, [0x0, 0x0], cb);},
        function(cb){
            getImage(camera, 60000, function(err, imageResults) {
                results = imageResults;
                cb(err);
            });
        },
    ], function(err) {
        callback && callback(err, results.thumb, results.filename, results.rawImage);
    });
}

driver.captureHDR = function(camera, target, options, frames, stops, darkerOnly, callback) {

}

driver.liveviewMode = function(camera, enable, callback) {

}

driver.liveviewImage = function(camera, nable, callback) {

}

driver.moveFocus = function(camera, steps, resolution, callback) {

}

driver.get = function(camera, param, value, callback) {

}

module.exports = driver;
<commit_msg>usb testing<commit_after>
/****************************************************************************
 LICENSE: CC BY-NC-SA 4.0 https://creativecommons.org/licenses/by-nc-sa/4.0/
 This is an original driver by Elijah Parker <mail@timelapseplus.com>
 It is free to use in other projects for non-commercial purposes.  For a
 commercial license and consulting, please contact mail@timelapseplus.com
*****************************************************************************/

var util = require('util');
var async = require('async');
var EventEmitter = require('events').EventEmitter;
var ptp = require('../common/ptp-functions.js');
var fs = require('fs');

var driver = new EventEmitter();

driver.name = "Fujifilm";

function _logD() {
    if(arguments.length > 0) {
        arguments[0] = "PTP-FUJI: " + arguments[0];
    }
    console.log.apply(console, arguments);
}

driver.supportedCameras = {
    '04cb:02cb': {
            name: "Fuji X-Pro2",
            supports: {
                shutter: true,
                aperture: true,
                iso: true,
                liveview: true,
                target: true,
                focus: true,
            }
        },
    '04cb:02cd': {
            name: "Fuji X-T2",
            supports: {
                shutter: true,
                aperture: true,
                iso: true,
                liveview: true,
                target: true,
                focus: true,
            }
        },
    '04cb:02d7': {
            name: "Fuji X-H1",
            supports: {
                shutter: true,
                aperture: true,
                iso: true,
                liveview: true,
                target: true,
                focus: true,
            }
        },
    '04cb:02dd': {
            name: "Fuji X-T3",
            supports: {
                shutter: true,
                aperture: true,
                iso: true,
                liveview: true,
                target: true,
                focus: true,
            }
        },
}

var properties = {
    'shutter': {
        name: 'shutter',
        function: ptp.setPropU16,
        code: 0xD219,
        ev: true,
        values: [
            {name: '1s', ev: -6, code: 0},
        ]
    }
}

driver._error = function(camera, error) { // events received
    _logD("ERROR:", error);
};

driver._event = function(camera, data) { // events received
    _logD("EVENT:", data);
    ptp.parseEvent(data, function(type, event, param1, param2, param3) {
        if(event == ptp.PTP_EC_ObjectAdded) {
            _logD("object added:", param1);
        }
    });
};

driver.init = function(camera, callback) {
    ptp.init(camera._dev, function(err, di) {
        async.series([
            function(cb){ptp.setPropU16(camera._dev, 0xd38c, 1, cb);}, // PC mode
            function(cb){ptp.setPropU16(camera._dev, 0xd207, 2, cb);}  // USB control
        ], function(err) {
            var capture = function() {
                driver.capture(camera, "", {}, function(err, thumb, filename, rawImage){
                    if(err) {
                        if(err != 0x2019) _logD("capture err result:", ptp.hex(err));
                    } else {
                        _logD("captureed image:", filename);
                    }
                    var delay = 1000;
                    if(err == 0x2019) delay = 50;
                    setTimeout(function() {
                        capture();
                    }, delay);
                });
            }
            capture();
            callback && callback(err);
        });
    });
}

driver.set = function(camera, param, value, callback) {

}

function getImage(camera, timeout, callback) {
    var results = {
        thumb: null,
        filename: null,
        indexNumber: null,
        rawImage: null
    }

    var startTime = Date.now();

    var check = function() {
        if(Date.now() - startTime > timeout) {
            return callback && callback("timeout", results);
        }
        ptp.getPropData(camera._dev, 0xd212, function(err, data) { // wait if busy
            //console.log("data:", data);
            if(data.length >= 4 && data.readUInt16LE(2) == 0xD20E) {
                var getHandles = function() {
                    ptp.getObjectHandles(camera._dev, function(err, handles) {
                        if(handles.length > 0) {
                            var objectId = handles[0];
                            var deleteRemaining = function() {
                                if(handles.length > 1) {
                                    var id = handles.pop();
                                    ptp.deleteObject(camera._dev, id, function(err) {
                                        deleteRemaining();
                                    });
                                }
                            }
                            ptp.getObjectInfo(camera._dev, objectId, function(err, oi) {
                                //console.log(oi);
                                var image = null;
                                results.filename = oi.filename;
                                results.indexNumber = objectId;
                                if(camera.thumbnail) {
                                    ptp.getThumb(camera._dev, objectId, function(err, jpeg) {
                                        ptp.deleteObject(camera._dev, objectId, function() {
                                            results.thumb = jpeg;
                                            callback && callback(err, results);
                                            deleteRemaining();
                                        });
                                    })
                                } else {
                                    ptp.getObject(camera._dev, objectId, function(err, image) {
                                        ptp.deleteObject(camera._dev, objectId, function() {
                                            results.thumb = ptp.extractJpeg(image);
                                            results.rawImage = image;
                                            callback && callback(err, results);
                                            deleteRemaining();
                                        });
                                    })
                                }
                            });
                        } else {
                            setTimeout(getHandles, 50);
                        }
                    });
                }
                getHandles();
            } else {
                setTimeout(check, 50);
            }
        });
    }
    check();
}

driver.capture = function(camera, target, options, callback, tries) {
    var targetValue = (!target || target == "camera") ? 2 : 4;
    camera.thumbnail = true;
    var results = {};
    async.series([
        function(cb){ptp.setPropU16(camera._dev, 0xd20c, targetValue, cb);}, // set target
        function(cb){ptp.setPropU16(camera._dev, 0xd208, 0x0200, cb);},
        function(cb){ptp.ptpCapture(camera._dev, [0x0, 0x0], cb);},
        function(cb){
            var check = function() {
                ptp.getPropU16(camera._dev, 0xd209, function(err, data) { // wait if busy
                    if(data == 0x0001) {
                        check();
                    } else {
                        cb(err);
                    }
                });
            }
            check();
        },
        function(cb){ptp.setPropU16(camera._dev, 0xd208, 0x0304, cb);},
        function(cb){ptp.ptpCapture(camera._dev, [0x0, 0x0], cb);},
        function(cb){
            getImage(camera, 60000, function(err, imageResults) {
                results = imageResults;
                cb(err);
            });
        },
    ], function(err) {
        callback && callback(err, results.thumb, results.filename, results.rawImage);
    });
}

driver.captureHDR = function(camera, target, options, frames, stops, darkerOnly, callback) {

}

driver.liveviewMode = function(camera, enable, callback) {

}

driver.liveviewImage = function(camera, nable, callback) {

}

driver.moveFocus = function(camera, steps, resolution, callback) {

}

driver.get = function(camera, param, value, callback) {

}

module.exports = driver;
<|endoftext|>


<commit_before>/**
 * ResultController
 *
 * @description :: Server-side logic for managing Results
 * @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 */

module.exports = {
	detail: function (req, res) {
		var resultId = req.param ('testResultId');

		runnedTests.find ({
			where: {id: resultId},
			include: [{
				model: responses,
				include: [{
					model: evaluatedAssertions
				}]
			}]
		}).then (function (result) {
			if (!result)
				return res.notFound ();

			return res.ok (result);

		}, function (error) {
			return res.serverError (error);
		})
	},

	overview: function (req, res) {

		var managedEnvironmentIds = Object.keys (req.managedEnvironments);

		// no environments found, no results sent
		if (managedEnvironmentIds.length == 0)
			return res.ok ();

		var age = req.param ('age', false),
			findCriterium = {
				attributes: ['id', 'testsId', 'status', 'updatedAt', 'testName'],
				where: [{environmentsId: {$in: managedEnvironmentIds}}],
				order: [
					['updatedAt', 'DESC']
				]
			};

		if (age) {
			var date = new Date ();
			findCriterium.where.push ({updatedAt: {$gt: new Date (date.getTime () - age * 3600 * 1000)}});
		}

		runnedTests.findAll (findCriterium).then (function (results) {
			return res.ok (results);
		})
	}
};

<commit_msg>FIX: fix dasboard test overview - missing environmentsId in test results did not displayed any tests<commit_after>/**
 * ResultController
 *
 * @description :: Server-side logic for managing Results
 * @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 */

module.exports = {
	detail: function (req, res) {
		var resultId = req.param ('testResultId');

		runnedTests.find ({
			where: {id: resultId},
			include: [{
				model: responses,
				include: [{
					model: evaluatedAssertions
				}]
			}]
		}).then (function (result) {
			if (!result)
				return res.notFound ();

			return res.ok (result);

		}, function (error) {
			return res.serverError (error);
		})
	},

	overview: function (req, res) {

		var managedEnvironmentIds = Object.keys (req.managedEnvironments);

		// no environments found, no results sent
		if (managedEnvironmentIds.length == 0)
			return res.ok ();

		var age = req.param ('age', false),
			findCriterium = {
				attributes: ['id', 'testsId', 'environmentsId', 'status', 'updatedAt', 'testName'],
				where: [{environmentsId: {$in: managedEnvironmentIds}}],
				order: [
					['updatedAt', 'DESC']
				]
			};

		if (age) {
			var date = new Date ();
			findCriterium.where.push ({updatedAt: {$gt: new Date (date.getTime () - age * 3600 * 1000)}});
		}

		runnedTests.findAll (findCriterium).then (function (results) {
			return res.ok (results);
		})
	}
};

<|endoftext|>


<commit_before>App = {
  web3Provider: null,
  contracts: {},

  init: function() {
    return App.initWeb3();
  },

  initWeb3: function() {
    // Initialize web3 and set the provider to the testRPC.
    if (typeof web3 !== 'undefined') {
      App.web3Provider = web3.currentProvider;
      web3 = new Web3(web3.currentProvider);
    } else {
      // set the provider you want from Web3.providers
      App.web3Provider = new web3.providers.HttpProvider('http://localhost:8545');
      web3 = new Web3(App.web3Provider);
    }

    return App.initContract();
  },

  initContract: function() {
    $.getJSON('GraivyApp.json', function(data) {
      // Get the necessary contract artifact file and instantiate it with truffle-contract.
      var GraivyAppArtifact = data;
      App.contracts.GraivyApp = TruffleContract(GraivyAppArtifact);

      // Set the provider for our contract.
      App.contracts.GraivyApp.setProvider(App.web3Provider);

      // Use our contract to retieve and mark the adopted pets.
      return App.getProjectCount();
    });

    return App.bindEvents();
  },

  bindEvents: function() {
    $(document).on('click', '#isProject', App.handleProjectCheck);
    $(document).on('click', '#insertProject', App.handleInsertProject);
    $(document).on('click', '#deleteProject', App.handleDeleteProject);
    $(document).on('click', '#getNumTasks', App.handleGetProjectNumTasks);
  },

  handleInsertProject: function() {
    event.preventDefault();

    var projectAddress = $('#ProjectAddress').val();
    var owner = $('#ProjectOwner').val();
    var qualifications = parseInt($('#ProjectQualifications').val());
    var redundancy = parseInt($('#ProjectRedundancy').val());
    var tasksLocation = $('#ProjectTasksLocation').val();
    var numTasks = parseInt($('#ProjectNumTasks').val());
    var rewardTotal = parseFloat($('#ProjectRewardTotal').val());
    var results = $('#ProjectResults').val();

    console.log('Creating Project...');

    var graivyAppInstance;

    web3.eth.getAccounts(function(error, accounts) {
      if (error) {
        console.log(error);
      }

      var account = accounts[0];

      App.contracts.GraivyApp.deployed().then(function(instance) {
        graivyAppInstance = instance;

        return graivyAppInstance.insertProject(
          projectAddress,
          owner,
          qualifications,
          redundancy,
          tasksLocation,
          numTasks,
          rewardTotal,
          results,
          {from: account, value: web3.toWei(rewardTotal, 'ether')}
        );
      }).then(function(result) {
        alert('Project Created!');
        return App.getProjectCount();
      }).catch(function(err) {
        console.log(err.message);
      });
    });
  },

  handleDeleteProject: function() {
    event.preventDefault();

    var projectAddress = $('#DeleteProjectAddress').val();

    console.log('Deleting Project... ');

    var graivyAppInstance;

    web3.eth.getAccounts(function(error, accounts) {
      if (error) {
        console.log(error);
      }

      var account = accounts[0];

      App.contracts.GraivyApp.deployed().then(function(instance) {
        graivyAppInstance = instance;

        return graivyAppInstance.deleteProject(projectAddress, {from: account});
      }).then(function(result) {
        alert('Project Deleted!');
        return App.getProjectCount();
      }).catch(function(err) {
        console.log(err.message);
      });
    });
  },

  handleGetProjectNumTasks: function() {
    event.preventDefault();

    var projectAddress = $('#GetNumTasksAddy').val();

    console.log('Getting info for Project');

    var graivyAppInstance;

    web3.eth.getAccounts(function(error, accounts) {
      if (error) {
        console.log(error);
      }

      var account = accounts[0];

      App.contracts.GraivyApp.deployed().then(function(instance) {
        graivyAppInstance = instance;

        return graivyAppInstance.getProjectNumTasks(projectAddress);
      }).then(function(result) {
        console.log(result);

        $('#ProjectNumTasksReturned').text(result);
      }).catch(function(err) {
        console.log(err.message);
      });
    });
  },

  handleProjectCheck: function() {
    event.preventDefault();

    var projectAddress = $('#UpdateQualificationsAddress').val();

    console.log('Checking if project: ' + userAddress);

    var graivyAppInstance;

    web3.eth.getAccounts(function(error, accounts) {
      if (error) {
        console.log(error);
      }

      var account = accounts[0];

      App.contracts.GraivyApp.deployed().then(function(instance) {
        graivyAppInstance = instance;

        return graivyAppInstance.isProject(projectAddress);
      }).then(function(result) {
        $('#IsProjectCheck').text(result);
      }).catch(function(err) {
        console.log(err.message);
      });
    });
  },

  getProjectCount: function(adopters) {
    console.log('Getting project count...');

    var graivyAppInstance;

    web3.eth.getAccounts(function(error, accounts) {
      if (error) {
        console.log(error);
      }

      var account = accounts[0];

      App.contracts.GraivyApp.deployed().then(function(instance) {
        graivyAppInstance = instance;

        return graivyAppInstance.getProjectCount();
      }).then(function(result) {
        count = result.c[0];

        $('#GVYProjectCount').text(count);
      }).catch(function(err) {
        console.log(err.message);
      });
    });
  }

};

$(function() {
  $(window).load(function() {
    App.init();
  });
});
<commit_msg>add withdraw/claim<commit_after>App = {
  web3Provider: null,
  contracts: {},

  init: function() {
    return App.initWeb3();
  },

  initWeb3: function() {
    // Initialize web3 and set the provider to the testRPC.
    if (typeof web3 !== 'undefined') {
      App.web3Provider = web3.currentProvider;
      web3 = new Web3(web3.currentProvider);
    } else {
      // set the provider you want from Web3.providers
      App.web3Provider = new web3.providers.HttpProvider('http://localhost:8545');
      web3 = new Web3(App.web3Provider);
    }

    return App.initContract();
  },

  initContract: function() {
    $.getJSON('GraivyApp.json', function(data) {
      // Get the necessary contract artifact file and instantiate it with truffle-contract.
      var GraivyAppArtifact = data;
      App.contracts.GraivyApp = TruffleContract(GraivyAppArtifact);

      // Set the provider for our contract.
      App.contracts.GraivyApp.setProvider(App.web3Provider);

      // Use our contract to retieve and mark the adopted pets.
      return App.getProjectCount();
    });

    return App.bindEvents();
  },

  bindEvents: function() {
    $(document).on('click', '#isProject', App.handleProjectCheck);
    $(document).on('click', '#insertProject', App.handleInsertProject);
    $(document).on('click', '#deleteProject', App.handleDeleteProject);
    $(document).on('click', '#getNumTasks', App.handleGetProjectNumTasks);
    $(document).on('click', '#userClaimReward', App.handleUserClaimReward);
    $(document).on('click', '#userWithdrawReward', App.handleUserWithdrawReward);
  },

  handleInsertProject: function() {
    event.preventDefault();

    var projectAddress = $('#ProjectAddress').val();
    var owner = $('#ProjectOwner').val();
    var qualifications = parseInt($('#ProjectQualifications').val());
    var redundancy = parseInt($('#ProjectRedundancy').val());
    var tasksLocation = $('#ProjectTasksLocation').val();
    var numTasks = parseInt($('#ProjectNumTasks').val());
    var rewardTotal = parseFloat($('#ProjectRewardTotal').val());
    var results = $('#ProjectResults').val();

    console.log('Creating Project...');

    var graivyAppInstance;

    web3.eth.getAccounts(function(error, accounts) {
      if (error) {
        console.log(error);
      }

      var account = accounts[0];

      App.contracts.GraivyApp.deployed().then(function(instance) {
        graivyAppInstance = instance;

        return graivyAppInstance.insertProject(
          projectAddress,
          owner,
          qualifications,
          redundancy,
          tasksLocation,
          numTasks,
          rewardTotal,
          results,
          {from: account, value: web3.toWei(rewardTotal, 'ether')}
        );
      }).then(function(result) {
        alert('Project Created!');
        return App.getProjectCount();
      }).catch(function(err) {
        console.log(err.message);
      });
    });
  },

  handleDeleteProject: function() {
    event.preventDefault();

    var projectAddress = $('#DeleteProjectAddress').val();

    console.log('Deleting Project... ');

    var graivyAppInstance;

    web3.eth.getAccounts(function(error, accounts) {
      if (error) {
        console.log(error);
      }

      var account = accounts[0];

      App.contracts.GraivyApp.deployed().then(function(instance) {
        graivyAppInstance = instance;

        return graivyAppInstance.deleteProject(projectAddress, {from: account});
      }).then(function(result) {
        alert('Project Deleted!');
        return App.getProjectCount();
      }).catch(function(err) {
        console.log(err.message);
      });
    });
  },

  handleGetProjectNumTasks: function() {
    event.preventDefault();

    var projectAddress = $('#GetNumTasksAddy').val();

    console.log('Getting info for Project');

    var graivyAppInstance;

    web3.eth.getAccounts(function(error, accounts) {
      if (error) {
        console.log(error);
      }

      var account = accounts[0];

      App.contracts.GraivyApp.deployed().then(function(instance) {
        graivyAppInstance = instance;

        return graivyAppInstance.getProjectNumTasks(projectAddress);
      }).then(function(result) {
        console.log(result);

        $('#ProjectNumTasksReturned').text(result);
      }).catch(function(err) {
        console.log(err.message);
      });
    });
  },

  handleProjectCheck: function() {
    event.preventDefault();

    var projectAddress = $('#UpdateQualificationsAddress').val();

    console.log('Checking if project: ' + userAddress);

    var graivyAppInstance;

    web3.eth.getAccounts(function(error, accounts) {
      if (error) {
        console.log(error);
      }

      var account = accounts[0];

      App.contracts.GraivyApp.deployed().then(function(instance) {
        graivyAppInstance = instance;

        return graivyAppInstance.isProject(projectAddress);
      }).then(function(result) {
        $('#IsProjectCheck').text(result);
      }).catch(function(err) {
        console.log(err.message);
      });
    });
  },

  getProjectCount: function(adopters) {
    console.log('Getting project count...');

    var graivyAppInstance;

    web3.eth.getAccounts(function(error, accounts) {
      if (error) {
        console.log(error);
      }

      var account = accounts[0];

      App.contracts.GraivyApp.deployed().then(function(instance) {
        graivyAppInstance = instance;

        return graivyAppInstance.getProjectCount();
      }).then(function(result) {
        count = result.c[0];

        $('#GVYProjectCount').text(count);
      }).catch(function(err) {
        console.log(err.message);
      });
    });
  },

  handleUserWithdrawReward: function() {
    event.preventDefault();

    console.log('Withdrawing rewards...');

    var graivyAppInstance;

    web3.eth.getAccounts(function(error, accounts) {
      if (error) {
        console.log(error);
      }

      var account = accounts[0];

      App.contracts.GraivyApp.deployed().then(function(instance) {
        graivyAppInstance = instance;

        return graivyAppInstance.withdrawRewards(
          {from: account}
        );
      }).then(function(result) {
        alert('Rewards withdrawn!');
        return App.getProjectCount();
      }).catch(function(err) {
        console.log(err.message);
      });
    });
  },

  handleUserClaimReward: function() {
    event.preventDefault();

    var projectAddress = $('#ClaimProjectAddress').val();
    var userAddress = $('#ClaimUserAddress').val();
    var numWorks = $('#ClaimNumWorks').val();
    var reward = $('#ClaimReward').val();

    console.log('Claiming rewards...');

    var graivyAppInstance;

    web3.eth.getAccounts(function(error, accounts) {
      if (error) {
        console.log(error);
      }

      var account = accounts[0];

      App.contracts.GraivyApp.deployed().then(function(instance) {
        graivyAppInstance = instance;

        return graivyAppInstance.quickReward(
          projectAddress,
          userAddress,
          numWorks,
          reward
        );
      }).then(function(result) {
        alert('Rewards claimed!');
        return App.getProjectCount();
      }).catch(function(err) {
        console.log(err.message);
      });
    });
  }

};

$(function() {
  $(window).load(function() {
    App.init();
  });
});
<|endoftext|>


<commit_before>var fs = require('fs');
var http = require('http');
var qs = require('querystring');
var path = require('path');
var url = require('url');

var request = require('request');
var b = require('equalitie-bundler');

// The path on the RR to report a bundle that has been completed after the
// request *from* the RR timed out.
const RR_COMPLETE = '/complete';

const configFile = path.join('..', 'config', 'node.json');

// Default configuration settings to use in case the config file doesn't exist.
var defaultConfig = {
  port: 3091,
  requestReceiver: 'http://localhost:3092'
}

var config = defaultConfig;

function bs_log(msg) {
  console.log('[BUNDLE SERVER] ' + msg);
}

// POST to the RR to prompt it to accept a completed bundle.
function reportCompleteBundle(config, data, cb) {
  request({
    url: config.requestReceiver + RR_COMPLETE,
    method: 'POST',
    json: data
  }, cb);
}

// Read the config file into the global `config` object.
// If something goes wrong, we use the default config.
try {
  config = JSON.parse(fs.readFileSync(configFile));
} catch (ex) {
  bs_log('Could not load config; Error: ' + ex.message);
  config = defaultConfig;
  bs_log('Using default configuration');
  console.log(config);
}

var server = http.createServer(function (req, res) {
  var requestedURL = qs.parse(url.parse(req.url).query).url;
  bs_log('Got request to bundle ' + requestedURL);
  var disconnected = false; // A flag set when the request is closed.

  req.on('close', function () {
    disconnected = true;
    bs_log('Request ended prematurely.');
  });

  // Bundle as many resources in requested pages as possible, without any
  // request manipulation
  var bundler = new b.Bundler(requestedURL);
  bundler.on('originalReceived', b.replaceImages);
  bundler.on('originalReceived', b.replaceCSSFiles);
  bundler.on('originalReceived', b.replaceJSFiles);
  bundler.on('originalReceived', b.replaceURLCalls);
  bundler.on('resourceReceived', b.bundleCSSRecursively);

  res.writeHead(200, {'Content-Type': 'application/json'});

  bundler.bundle(function (err, bundle) {
    if (err) {
      if (!disconnected) {
        res.statusCode = 500;
        res.write(JSON.stringify({
          error: err.message
        }));
        res.end();
      }
      bs_log('Encountered error creating bundle for ' + requestedURL);
      bs_log('Error: ' + err.message);
    } else { // !err
      var data = {
        created: new Date(),
        url: requestedURL,
        bundle: bundle
      };
      bs_log('Successfully created bundle for ' + requestedURL);
      if (!disconnected) {
        res.write(JSON.stringify(data));
        res.end();
        bs_log('Sent bundle to RR');
      } else { // disconnected
        // If the connection to the RR is closed before we can send the bundle,
        // rather than letting the bundling effort go to waste, we will POST to
        // the RR to prompt it to accept the now complete bundle.
        bs_log('Reporting bundle completion to RR');
        reportCompleteBundle(config, data, function () {
          res.end();
          bs_log('Sent POST to RR to prompt it to accept bundle');
        });
      }
    }
  });
});

server.listen(config.port);
bs_log('Running bundling server on port ' + config.port);<commit_msg>Implemented PING response functionality in BS<commit_after>var fs = require('fs');
var http = require('http');
var qs = require('querystring');
var path = require('path');
var url = require('url');

var request = require('request');
var b = require('equalitie-bundler');

// The path on the RR to report a bundle that has been completed after the
// request *from* the RR timed out.
const RR_COMPLETE = '/complete';

const configFile = path.join('..', 'config', 'node.json');

// Default configuration settings to use in case the config file doesn't exist.
var defaultConfig = {
  port: 3091,
  requestReceiver: 'http://localhost:3092'
}

var config = defaultConfig;

function bs_log(msg) {
  console.log('[BUNDLE SERVER] ' + msg);
}

// POST to the RR to prompt it to accept a completed bundle.
function reportCompleteBundle(config, data, cb) {
  request({
    url: config.requestReceiver + RR_COMPLETE,
    method: 'POST',
    json: data
  }, cb);
}

// Read the config file into the global `config` object.
// If something goes wrong, we use the default config.
try {
  config = JSON.parse(fs.readFileSync(configFile));
} catch (ex) {
  bs_log('Could not load config; Error: ' + ex.message);
  config = defaultConfig;
  bs_log('Using default configuration');
  console.log(config);
}

var server = http.createServer(function (req, res) {
  //////////////////////////
  // Handle PING requests //
  //////////////////////////
  if (req.url.substring(0, '/ping'.length) === '/ping') {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.write('pong');
    res.end();
    bs_log('Responded to PING request');
    return;
  }

  ////////////////////////////
  // Handle bundle requests //
  ////////////////////////////
  var requestedURL = qs.parse(url.parse(req.url).query).url;
  bs_log('Got request to bundle ' + requestedURL);
  var disconnected = false; // A flag set when the request is closed.

  req.on('close', function () {
    disconnected = true;
    bs_log('Request ended prematurely.');
  });

  // Bundle as many resources in requested pages as possible, without any
  // request manipulation
  var bundler = new b.Bundler(requestedURL);
  bundler.on('originalReceived', b.replaceImages);
  bundler.on('originalReceived', b.replaceCSSFiles);
  bundler.on('originalReceived', b.replaceJSFiles);
  bundler.on('originalReceived', b.replaceURLCalls);
  bundler.on('resourceReceived', b.bundleCSSRecursively);

  res.writeHead(200, {'Content-Type': 'application/json'});

  bundler.bundle(function (err, bundle) {
    if (err) {
      if (!disconnected) {
        res.statusCode = 500;
        res.write(JSON.stringify({
          error: err.message
        }));
        res.end();
      }
      bs_log('Encountered error creating bundle for ' + requestedURL);
      bs_log('Error: ' + err.message);
    } else { // !err
      var data = {
        created: new Date(),
        url: requestedURL,
        bundle: bundle
      };
      bs_log('Successfully created bundle for ' + requestedURL);
      if (!disconnected) {
        res.write(JSON.stringify(data));
        res.end();
        bs_log('Sent bundle to RR');
      } else { // disconnected
        // If the connection to the RR is closed before we can send the bundle,
        // rather than letting the bundling effort go to waste, we will POST to
        // the RR to prompt it to accept the now complete bundle.
        bs_log('Reporting bundle completion to RR');
        reportCompleteBundle(config, data, function () {
          res.end();
          bs_log('Sent POST to RR to prompt it to accept bundle');
        });
      }
    }
  });
});

server.listen(config.port);
bs_log('Running bundling server on port ' + config.port);<|endoftext|>


<commit_before>import React, { Component } from 'react';
import Secretin from 'secretin';
import Modal from 'components/utilities/Modal';
import Button from 'components/utilities/Button';

const LOCAL_STORAGE_ACKNOWLEDGE_VERSION_KEY = 'Secret-in:acknowledgedVersion';
const DEFAULT_DEVELOP_COMMITISH = 'develop';

class Footer extends Component {
  constructor(props) {
    super(props);
    this.hideNews = this.hideNews.bind(this);
    this.showNews = this.showNews.bind(this);
    this.acknowledgeVersion = this.acknowledgeVersion.bind(this);

    // eslint-disable-next-line no-undef
    const commit = SECRETIN_APP_COMMIT;

    const acknowledgedVersion = window.localStorage.getItem(
      LOCAL_STORAGE_ACKNOWLEDGE_VERSION_KEY
    );

    this.state = {
      commit,
      acknowledgedVersion,
      news: [],
      showNews: acknowledgedVersion ? false : true,
    };
    console.log(this.state);
  }

  showNews() {
    this.setState({ showNews: true });
  }

  hideNews() {
    this.setState({ showNews: false });
  }

  acknowledgeVersion() {
    window.localStorage.setItem(
      LOCAL_STORAGE_ACKNOWLEDGE_VERSION_KEY,
      this.state.commit
    );
    this.setState({
      news: [],
      acknowledgeVersion: this.state.commit,
      showNews: false,
    });
  }

  componentDidMount() {
    if (this.state.acknowledgedVersion === null) {
      return;
    }

    const somethingNew =
      this.state.commit !== DEFAULT_DEVELOP_COMMITISH &&
      this.state.acknowledgedVersion !== this.state.commit;
    if (somethingNew) {
      fetch(
        'https://raw.githubusercontent.com/secretin/secretin-website/develop/changelog.json'
      )
        .then(response => {
          return response.json();
        })
        .then(data => {
          const news = [];
          let foundAcknowledgedVersion = false;
          for (const change of data.changelog) {
            if (change.version === this.state.acknowledgedVersion) {
              foundAcknowledgedVersion = true;
              break;
            }
            news.push(change);
          }

          if (foundAcknowledgedVersion) {
            this.setState({ news });
          } else {
            // If we didn't find the acknowledged version, then we didn't updated changelog properly
            // we will just show the last change then
            this.setState({ news: [data.changelog[0]] });
          }
        });
    }
  }

  render() {
    const shortCommit = this.state.commit ? this.state.commit.substr(0, 7) : '';
    const secretinAppVersion = this.state.commit ? (

        <Modal
          show={this.state.showNews}
          onClose={
            this.state.acknowledgedVersion === null ? false : this.hideNews
          }
        >
          {this.state.acknowledgedVersion === null ? (
            <>
              <Modal.Header title="Welcome to Secret-in.me" />
              <Modal.Body>

                      Secret-in.me
                    {' '}
                    is a team-oriented{' '}

                      open source
                    {' '}
                    password manager with a focus on transparency, usability and
                    security.

                    If it's your first time here, you can create a user and
                    start to save your secret.

                    Be careful, all your secrets would be protected with the
                    password you pick. There is no way to retrieve your
                    secret if you forgot your passwor !

                    This secret manager is freely provided with{' '}

                      ❤
                    {' '}
                    by{' '}

                      Bug Builders.

                    If you enjoy it, please consider to{' '}

                      donate !
                    {' '}

                    It'll help us supporting hosting costs (~50$ per
                    months).

              </Modal.Body>
            </>
          ) : (
            <>
              <Modal.Header title="What's new ?" />
              <Modal.Body>
                {this.state.news.map(change => (

{change.title}

{change.description}

                ))}
              </Modal.Body>
            </>
          )}

          <Modal.Footer>
            {this.state.acknowledgedVersion !== null && (
              <Button
                type="reset"
                buttonStyle="default"
                onClick={this.hideNews}
              >
                Close
              </Button>
            )}
            <Button type="submit" onClick={this.acknowledgeVersion}>
              Ok
            </Button>
          </Modal.Footer>
        </Modal>
        {this.state.news.length > 0 && (

            •

        )}

          secretin-app{' '}
          <a
            href={`https://github.com/secretin/secretin-app/commit/${this.state.commit}`}
            rel="noopener noreferrer"
            target="_blank"
          >
            {shortCommit}

    ) : (

        secretin-app dev

    );
    return (

        {secretinAppVersion}

            secretin-lib v{Secretin.version}

                ❤
              {' '}
              Donate

                ❤
              {' '}

    );
  }
}

export default Footer;
<commit_msg>Wording<commit_after>import React, { Component } from 'react';
import Secretin from 'secretin';
import Modal from 'components/utilities/Modal';
import Button from 'components/utilities/Button';

const LOCAL_STORAGE_ACKNOWLEDGE_VERSION_KEY = 'Secret-in:acknowledgedVersion';
const DEFAULT_DEVELOP_COMMITISH = 'develop';

class Footer extends Component {
  constructor(props) {
    super(props);
    this.hideNews = this.hideNews.bind(this);
    this.showNews = this.showNews.bind(this);
    this.acknowledgeVersion = this.acknowledgeVersion.bind(this);

    // eslint-disable-next-line no-undef
    const commit = SECRETIN_APP_COMMIT;

    const acknowledgedVersion = window.localStorage.getItem(
      LOCAL_STORAGE_ACKNOWLEDGE_VERSION_KEY
    );

    this.state = {
      commit,
      acknowledgedVersion,
      news: [],
      showNews: acknowledgedVersion ? false : true,
    };
    console.log(this.state);
  }

  showNews() {
    this.setState({ showNews: true });
  }

  hideNews() {
    this.setState({ showNews: false });
  }

  acknowledgeVersion() {
    window.localStorage.setItem(
      LOCAL_STORAGE_ACKNOWLEDGE_VERSION_KEY,
      this.state.commit
    );
    this.setState({
      news: [],
      acknowledgeVersion: this.state.commit,
      showNews: false,
    });
  }

  componentDidMount() {
    if (this.state.acknowledgedVersion === null) {
      return;
    }

    const somethingNew =
      this.state.commit !== DEFAULT_DEVELOP_COMMITISH &&
      this.state.acknowledgedVersion !== this.state.commit;
    if (somethingNew) {
      fetch(
        'https://raw.githubusercontent.com/secretin/secretin-website/develop/changelog.json'
      )
        .then(response => {
          return response.json();
        })
        .then(data => {
          const news = [];
          let foundAcknowledgedVersion = false;
          for (const change of data.changelog) {
            if (change.version === this.state.acknowledgedVersion) {
              foundAcknowledgedVersion = true;
              break;
            }
            news.push(change);
          }

          if (foundAcknowledgedVersion) {
            this.setState({ news });
          } else {
            // If we didn't find the acknowledged version, then we didn't updated changelog properly
            // we will just show the last change then
            this.setState({ news: [data.changelog[0]] });
          }
        });
    }
  }

  render() {
    const shortCommit = this.state.commit ? this.state.commit.substr(0, 7) : '';
    const secretinAppVersion = this.state.commit ? (

        <Modal
          show={this.state.showNews}
          onClose={
            this.state.acknowledgedVersion === null ? false : this.hideNews
          }
        >
          {this.state.acknowledgedVersion === null ? (
            <>
              <Modal.Header title="Welcome to Secret-in.me" />
              <Modal.Body>

                      Secret-in.me
                    {' '}
                    is a team-oriented{' '}

                      open source
                    {' '}
                    password manager with a focus on transparency, usability and
                    security.

                    If it's your first time here, you can create a user and
                    start saving your secrets.

                    Be careful, all your secrets will be protected by the
                    password you pick. There is no way to retrieve your
                    secrets if you forget your password !

                    This secret manager is freely provided with{' '}

                      ❤
                    {' '}
                    by{' '}

                      Bug Builders.

                    If you enjoy it, please consider {' '}

                      donating !
                    {' '}

                    It'll help us support hosting costs (~50$ per
                    month).

              </Modal.Body>
            </>
          ) : (
            <>
              <Modal.Header title="What's new ?" />
              <Modal.Body>
                {this.state.news.map(change => (

{change.title}

{change.description}

                ))}
              </Modal.Body>
            </>
          )}

          <Modal.Footer>
            {this.state.acknowledgedVersion !== null && (
              <Button
                type="reset"
                buttonStyle="default"
                onClick={this.hideNews}
              >
                Close
              </Button>
            )}
            <Button type="submit" onClick={this.acknowledgeVersion}>
              Ok
            </Button>
          </Modal.Footer>
        </Modal>
        {this.state.news.length > 0 && (

            •

        )}

          secretin-app{' '}
          <a
            href={`https://github.com/secretin/secretin-app/commit/${this.state.commit}`}
            rel="noopener noreferrer"
            target="_blank"
          >
            {shortCommit}

    ) : (

        secretin-app dev

    );
    return (

        {secretinAppVersion}

            secretin-lib v{Secretin.version}

                ❤
              {' '}
              Donate

                ❤
              {' '}

    );
  }
}

export default Footer;
<|endoftext|>


<commit_before>// @flow

/* eslint jsx-a11y/no-static-element-interactions: 0 */

import React from "react";
import CommonMark from "commonmark";
import MarkdownRenderer from "commonmark-react-renderer";

import LatexRenderer from "./latex";

import { Outputs, PromptBuffer, Input } from "./";

type Props = {
  source: string,
  focusAbove: () => void,
  focusBelow: () => void,
  focusEditor: () => void,
  unfocusEditor: () => void,
  cellFocused: boolean,
  editorFocused: boolean,
  children: React$Element<*>
};

type State = {
  view: boolean
};

// TODO: Standardize this as @nteract/markdown-renderer
//       and keep it consistent amongst the markdown transform and in the
//       rendered view of markdown cells
type MDRender = (input: string) => string;
const parser = new CommonMark.Parser();
const renderer = new MarkdownRenderer();
const mdRender: MDRender = input => renderer.render(parser.parse(input));

// TODO: Consider whether this component is really something like two components:
//
//       * a behavioral component that tracks focus (possibly already covered elsewhere)
//       * the actual markdown previewer
//
//       Since I'm really unsure and don't want to write a silly abstraction that
//       only I (@rgbkrk) understand, I'll wait for others to reflect on this
//       within the code base (or leave it alone, which is totally cool too). :)

export default class MarkdownCell extends React.PureComponent<any, State> {
  rendered: ?HTMLElement;

  static defaultProps = {
    cellFocused: false,
    editorFocused: false,
    focusAbove: () => {},
    focusBelow: () => {},
    focusEditor: () => {},
    unfocusEditor: () => {},
    source: ""
  };

  constructor(props: Props): void {
    super(props);
    this.state = {
      view: true
    };
    (this: any).openEditor = this.openEditor.bind(this);
    (this: any).editorKeyDown = this.editorKeyDown.bind(this);
    (this: any).renderedKeyDown = this.renderedKeyDown.bind(this);
    (this: any).closeEditor = this.closeEditor.bind(this);
  }

  componentDidMount(): void {
    this.updateFocus();
  }

  componentWillReceiveProps(nextProps: Props): void {
    this.setState({
      view: !nextProps.editorFocused
    });
  }

  componentDidUpdate(): void {
    this.updateFocus();
  }

  updateFocus(): void {
    if (
      this.rendered &&
      this.state &&
      this.state.view &&
      this.props.cellFocused
    ) {
      this.rendered.focus();
      if (this.props.editorFocused) {
        this.openEditor();
      }
    }
  }

  /**
   * Handles when a keydown event occurs on the unrendered MD cell
   */
  editorKeyDown(e: SyntheticKeyboardEvent<*>): void {
    // TODO: ctrl-enter will set the state view mode, _however_
    //       the focus is still set from above the editor
    //       Suggestion: we need a `this.props.unfocusEditor`
    //       It's either that or we should be setting `view` from
    //       the outside
    const shift = e.shiftKey;
    const ctrl = e.ctrlKey;
    if ((shift || ctrl) && e.key === "Enter") {
      this.closeEditor();
    }
  }

  closeEditor(): void {
    this.setState({ view: true });
    this.props.unfocusEditor();
  }

  openEditor(): void {
    this.setState({ view: false });
    this.props.focusEditor();
  }

  /**
   * Handles when a keydown event occurs on the rendered MD cell
   */
  renderedKeyDown(e: SyntheticKeyboardEvent<*>) {
    const shift = e.shiftKey;
    const ctrl = e.ctrlKey;
    if ((shift || ctrl) && e.key === "Enter") {
      this.closeEditor();
      return;
    }

    switch (e.key) {
      case "ArrowUp":
        this.props.focusAbove();
        break;
      case "ArrowDown":
        this.props.focusBelow();
        break;
      case "Enter":
        this.openEditor();
        e.preventDefault();
        return;
      default:
    }
    return;
  }

  render(): ?React$Element<any> {
    const source = this.props.source;

    return this.state && this.state.view ? (

 {
          this.rendered = rendered;
        }}
      >
        <Outputs>
          <LatexRenderer>
            {mdRender(
              source
                ? source
                : "*Empty markdown cell, double click me to add content.*"
            )}
          </LatexRenderer>
        </Outputs>

    ) : (

        <Input>
          <PromptBuffer />
          {/* The editor */}
          {this.props.children}
        </Input>
        <Outputs hidden={source === ""}>
          <LatexRenderer>{mdRender(source)}</LatexRenderer>
        </Outputs>

    );
  }
}
<commit_msg>allow navigating cells with up/down, enter on md<commit_after>// @flow

/* eslint jsx-a11y/no-static-element-interactions: 0 */
/* eslint jsx-a11y/no-noninteractive-tabindex: 0 */

import React from "react";
import CommonMark from "commonmark";
import MarkdownRenderer from "commonmark-react-renderer";

import LatexRenderer from "./latex";

import { Outputs, PromptBuffer, Input } from "./";

type Props = {
  source: string,
  focusEditor: () => void,
  unfocusEditor: () => void,
  focusAbove: () => void,
  focusBelow: () => void,
  cellFocused: boolean,
  editorFocused: boolean,
  children: React$Element<*>
};

type State = {
  view: boolean
};

// TODO: Standardize this as @nteract/markdown-renderer
//       and keep it consistent amongst the markdown transform and in the
//       rendered view of markdown cells
type MDRender = (input: string) => string;
const parser = new CommonMark.Parser();
const renderer = new MarkdownRenderer();
const mdRender: MDRender = input => renderer.render(parser.parse(input));

const noop = function() {};

// TODO: Consider whether this component is really something like two components:
//
//       * a behavioral component that tracks focus (possibly already covered elsewhere)
//       * the actual markdown previewer
//
//       Since I'm really unsure and don't want to write a silly abstraction that
//       only I (@rgbkrk) understand, I'll wait for others to reflect on this
//       within the code base (or leave it alone, which is totally cool too). :)

export default class MarkdownCell extends React.PureComponent<any, State> {
  rendered: ?HTMLElement;

  static defaultProps = {
    cellFocused: false,
    editorFocused: false,
    focusAbove: noop,
    focusBelow: noop,
    focusEditor: noop,
    unfocusEditor: noop,
    source: ""
  };

  constructor(props: Props): void {
    super(props);
    this.state = {
      view: true
    };
    (this: any).openEditor = this.openEditor.bind(this);
    (this: any).editorKeyDown = this.editorKeyDown.bind(this);
    (this: any).renderedKeyDown = this.renderedKeyDown.bind(this);
    (this: any).closeEditor = this.closeEditor.bind(this);
  }

  componentDidMount(): void {
    this.updateFocus();
  }

  componentWillReceiveProps(nextProps: Props): void {
    this.setState({
      view: !nextProps.editorFocused
    });
  }

  componentDidUpdate(): void {
    this.updateFocus();
  }

  updateFocus(): void {
    if (
      this.rendered &&
      this.state &&
      this.state.view &&
      this.props.cellFocused
    ) {
      this.rendered.focus();
      if (this.props.editorFocused) {
        this.openEditor();
      }
    }
  }

  /**
   * Handles when a keydown event occurs on the unrendered MD cell
   */
  editorKeyDown(e: SyntheticKeyboardEvent<*>): void {
    const shift = e.shiftKey;
    const ctrl = e.ctrlKey;
    if ((shift || ctrl) && e.key === "Enter") {
      this.closeEditor();
    }
  }

  closeEditor(): void {
    this.setState({ view: true });
    this.props.unfocusEditor();
  }

  openEditor(): void {
    this.setState({ view: false });
    this.props.focusEditor();
  }

  /**
   * Handles when a keydown event occurs on the rendered MD cell
   */
  renderedKeyDown(e: SyntheticKeyboardEvent<*>) {
    const shift = e.shiftKey;
    const ctrl = e.ctrlKey;
    if ((shift || ctrl) && e.key === "Enter") {
      this.closeEditor();
      return;
    }

    switch (e.key) {
      case "Enter":
        this.openEditor();
        e.preventDefault();
        return;
      case "ArrowUp":
        this.props.focusAbove();
        break;
      case "ArrowDown":
        this.props.focusBelow();
        break;
      default:
    }
    return;
  }

  render(): ?React$Element<any> {
    const source = this.props.source;

    return this.state && this.state.view ? (

 {
          this.rendered = rendered;
        }}
        tabIndex={this.props.cellFocused ? 0 : null}
        style={{
          outline: "none"
        }}
      >
        <Outputs>
          <LatexRenderer>
            {mdRender(
              source
                ? source
                : "*Empty markdown cell, double click me to add content.*"
            )}
          </LatexRenderer>
        </Outputs>

    ) : (

        <Input>
          <PromptBuffer />
          {/* The editor */}
          {this.props.children}
        </Input>
        <Outputs hidden={source === ""}>
          <LatexRenderer>{mdRender(source)}</LatexRenderer>
        </Outputs>

    );
  }
}
<|endoftext|>


<commit_before>"use script";

function desHabilitarTodo(){
    var checkboxs=document.getElementsByClassName("tutifruti-listo");
    document.getElementById("boton-parar").disabled=true;
    Array.prototype.forEach.call(checkboxs,function(checkbox){
        checkbox.disabled=true;
        var infoPk=JSON.parse(checkbox.getAttribute("tutifruti-pk"));
        var tdCorrespondiente=document.getElementById("categoria_"+infoPk.categoria);
        tdCorrespondiente.contentEditable=false;
    });
}

var ManoActual='no se';

window.addEventListener("load", function(){
    consola.textContent+='\nanda la consola';
    var checkboxs=document.getElementsByClassName("tutifruti-listo");
    Array.prototype.forEach.call(checkboxs,function(checkbox){
      //  consola.textContent+='\n encontro los checkboxes';
        checkbox.addEventListener("click",function(event){
        //    consola.textContent+='\n recibe el click';
            var infoPk=JSON.parse(this.getAttribute("tutifruti-pk"));
            var tdCorrespondiente=document.getElementById("categoria_"+infoPk.categoria);
            if(!tdCorrespondiente.textContent && this.checked){
                this.checked=false;
            }
            tdCorrespondiente.contentEditable=!this.checked;
            consola.textContent+='\n está por enviar el ajax';
            AjaxBestPromise.post({
                url:'services/play',
                data:{ info:JSON.stringify({
                    pk: infoPk,
                    operacion: this.checked?'JUGAR':'BORRAR',
                    palabra:tdCorrespondiente.textContent
                })}
            }).then(function(result){
                consola.textContent+='\n'+result;
            }).catch(function(err){
                consola.textContent+='\n'+err;
            });
        });
    });
    setInterval(function(){
        AjaxBestPromise.post({
            url:'services/status',
            data:{}
        }).then(JSON.parse).then(function(result){
            if(ManoActual==='no se'){
                ManoActual=result.mano;
            }else if(ManoActual!=result.mano){
                history.go(0);
            }
            if(result.jugando){
                document.getElementById("cantidad-jugadores").textContent=result.cant_jugadores;
                result.jugadas.forEach(function(categoria){
                    var e=document.getElementById("status_"+categoria.categoria).textContent=categoria.cant_jugadas;
                });
                document.getElementById("la-letra").textContent=result.letra;
            }else{
                document.getElementById("nueva-mano").style.visibility='visible';
                desHabilitarTodo();
            }
        }).catch(function(err){
            consola.textContent+='\nERR: '+err.stack;
        });
    }, 1000);
    document.getElementById("nueva-mano").addEventListener("click", function(){
        document.getElementById("nueva-mano").textContent="empezando";
        AjaxBestPromise.post({
            url:'services/new',
            data:{}
        }).then(function(result){
            history.go(0);
        }).catch(function(err){
            consola.textContent+='\n'+err;
        });
    });
    document.getElementById("boton-parar").addEventListener("click", function(){
        desHabilitarTodo();
        AjaxBestPromise.post({
            url:'services/stop',
            data:{}
        }).then(function(result){
            consola.textContent+='\n'+result;
        }).catch(function(err){
            consola.textContent+='\n'+err;
        });
    });
    var checkBoxsPuntos=document.getElementsByClassName("tuti-fruti-vale");
    Array.prototype.forEach.call(checkBoxsPuntos,function(checkbox){
        consola.textContent+='\n encontro los checkboxes';
        checkbox.addEventListener("click",function(event){
            consola.textContent+='\n recibe el click';
            var infoPk=JSON.parse(checkbox.getAttribute("tutifruti-pk"));
            var inputCorrespondiente=document.getElementById("puntosPalabra_"+infoPk.categoria);
            inputCorrespondiente.contentEditable=true;
            if(this.checked==false){
                consola.textContent+='\n recibe el SEGUNDO click';
                inputCorrespondiente.setAttribute("contentEditable", false);
                consola.textContent+='\n contenido   '+inputCorrespondiente.contentEditable;
            }
        });
    });
});<commit_msg>setea el puntaje de los div por palabra en cero puntos<commit_after>"use script";

function desHabilitarTodo(){
    var checkboxs=document.getElementsByClassName("tutifruti-listo");
    document.getElementById("boton-parar").disabled=true;
    Array.prototype.forEach.call(checkboxs,function(checkbox){
        checkbox.disabled=true;
        var infoPk=JSON.parse(checkbox.getAttribute("tutifruti-pk"));
        var tdCorrespondiente=document.getElementById("categoria_"+infoPk.categoria);
        tdCorrespondiente.contentEditable=false;
    });
}

var ManoActual='no se';

window.addEventListener("load", function(){
    consola.textContent+='\nanda la consola';
    var checkboxs=document.getElementsByClassName("tutifruti-listo");
    Array.prototype.forEach.call(checkboxs,function(checkbox){
      //  consola.textContent+='\n encontro los checkboxes';
        checkbox.addEventListener("click",function(event){
        //    consola.textContent+='\n recibe el click';
            var infoPk=JSON.parse(this.getAttribute("tutifruti-pk"));
            var tdCorrespondiente=document.getElementById("categoria_"+infoPk.categoria);
            if(!tdCorrespondiente.textContent && this.checked){
                this.checked=false;
            }
            tdCorrespondiente.contentEditable=!this.checked;
            consola.textContent+='\n está por enviar el ajax';
            AjaxBestPromise.post({
                url:'services/play',
                data:{ info:JSON.stringify({
                    pk: infoPk,
                    operacion: this.checked?'JUGAR':'BORRAR',
                    palabra:tdCorrespondiente.textContent
                })}
            }).then(function(result){
                consola.textContent+='\n'+result;
            }).catch(function(err){
                consola.textContent+='\n'+err;
            });
        });
    });
    setInterval(function(){
        AjaxBestPromise.post({
            url:'services/status',
            data:{}
        }).then(JSON.parse).then(function(result){
            if(ManoActual==='no se'){
                ManoActual=result.mano;
            }else if(ManoActual!=result.mano){
                history.go(0);
            }
            if(result.jugando){
                document.getElementById("cantidad-jugadores").textContent=result.cant_jugadores;
                result.jugadas.forEach(function(categoria){
                    var e=document.getElementById("status_"+categoria.categoria).textContent=categoria.cant_jugadas;
                });
                document.getElementById("la-letra").textContent=result.letra;
            }else{
                document.getElementById("nueva-mano").style.visibility='visible';
                desHabilitarTodo();
            }
        }).catch(function(err){
            consola.textContent+='\nERR: '+err.stack;
        });
    }, 1000);
    document.getElementById("nueva-mano").addEventListener("click", function(){
        document.getElementById("nueva-mano").textContent="empezando";
        AjaxBestPromise.post({
            url:'services/new',
            data:{}
        }).then(function(result){
            history.go(0);
        }).catch(function(err){
            consola.textContent+='\n'+err;
        });
    });
    document.getElementById("boton-parar").addEventListener("click", function(){
        desHabilitarTodo();
        AjaxBestPromise.post({
            url:'services/stop',
            data:{}
        }).then(function(result){
            consola.textContent+='\n'+result;
        }).catch(function(err){
            consola.textContent+='\n'+err;
        });
    });
    var checkBoxsPuntos=document.getElementsByClassName("tuti-fruti-vale");
    Array.prototype.forEach.call(checkBoxsPuntos,function(checkbox){
        var infoPk=JSON.parse(checkbox.getAttribute("tutifruti-pk"));
        var divCorrespondiente=document.getElementById("puntosPalabra_"+infoPk.categoria);
        divCorrespondiente.textContent=0;
        checkbox.addEventListener("click",function(event){
            divCorrespondiente.contentEditable=true;
            if(this.checked==false){
                divCorrespondiente.textContent=0;
                divCorrespondiente.setAttribute("contentEditable", false);
            }
        });
    });
});<|endoftext|>


<commit_before>'use strict'

const {STRING, ENUM, DATE} = require('sequelize')

module.exports = db => db.define('order', {
  status: {
    type: ENUM('pending', 'shipping', 'delivered'),
    defaultValue: 'pending'
  },
  dateOrdered: {
    type: DATE,
    validate: {
      notNull: true,
      isDate: true
    }
  },
  dateReceived: DATE
},
  {
    instanceMethods: {
      deliverOrder: function() {
        this.status = 'delivered'
        this.dateReceived = new Date()
      }
    }
  }
)

module.exports.associations = (order, {User}) => {
  order.belongsTo(User)
}
<commit_msg>added findTotalPrice<commit_after>'use strict'

const {STRING, ENUM, DATE} = require('sequelize')

module.exports = db => db.define('order', {
  status: {
    type: ENUM('pending', 'shipping', 'delivered'),
    defaultValue: 'pending'
  },
  dateOrdered: {
    type: DATE,
    validate: {
      notNull: true,
      isDate: true
    }
  },
  dateReceived: DATE
},
  {
    instanceMethods: {
      deliverOrder: function() {
        this.status = 'delivered'
        this.dateReceived = new Date()
      },
      findTotalPrice: function() {
        let totalPrice = 0
        this.getOrderItems({
          where: {
            orderId: this.id
          }
        })
        .then(orders => {
          orders.forEach(order => { totalPrice += order.priceAtPurchase * order.quantity })
        })
        return totalPrice
      }
    }
  }
)

module.exports.associations = (order, {User, orderItem}) => {
  order.belongsTo(User)
  order.hasMany(orderItem)
}
<|endoftext|>


<commit_before>/**
  This view handles rendering of the header of the site

  @class HeaderView
  @extends Discourse.View
  @namespace Discourse
  @module Discourse
**/
Discourse.HeaderView = Discourse.View.extend({
  tagName: 'header',
  classNames: ['d-header', 'clearfix'],
  classNameBindings: ['editingTopic'],
  templateName: 'header',
  topicBinding: 'Discourse.router.topicController.content',

  showDropdown: function($target) {
    var elementId = $target.data('dropdown') || $target.data('notifications'),
        $dropdown = $("#" + elementId),
        $li = $target.closest('li'),
        $ul = $target.closest('ul'),
        $html = $('html');

    var hideDropdown = function() {
      $dropdown.fadeOut('fast');
      $li.removeClass('active');
      $html.data('hide-dropdown', null);
      return $html.off('click.d-dropdown');
    };

    // if a dropdown is active and the user clics on it, close it
    if($li.hasClass('active')) { return hideDropdown(); }
    // otherwhise, mark it as active
    $li.addClass('active');
    // hide the other dropdowns
    $('li', $ul).not($li).removeClass('active');
    $('.d-dropdown').not($dropdown).fadeOut('fast');
    // fade it fast
    $dropdown.fadeIn('fast');
    // autofocus any text input field
    $dropdown.find('input[type=text]').focus().select();

    $html.on('click.d-dropdown', function(e) {
      return $(e.target).closest('.d-dropdown').length > 0 ? true : hideDropdown();
    });

    $html.data('hide-dropdown', hideDropdown);

    return false;
  },

  showNotifications: function() {

    var headerView = this;
    Discourse.ajax('/notifications').then(function(result) {
      headerView.set('notifications', result.map(function(n) {
        return Discourse.Notification.create(n);
      }));

      // We've seen all the notifications now
      Discourse.User.current().set('unread_notifications', 0);
      headerView.showDropdown($('#user-notifications'));
    });
    return false;
  },

  examineDockHeader: function() {
    var $body, offset, outlet;
    if (!this.docAt) {
      outlet = $('#main-outlet');
      if (!(outlet && outlet.length === 1)) return;
      this.docAt = outlet.offset().top;
    }
    offset = window.pageYOffset || $('html').scrollTop();
    if (offset >= this.docAt) {
      if (!this.dockedHeader) {
        $body = $('body');
        $body.addClass('docked');
        this.dockedHeader = true;
      }
    } else {
      if (this.dockedHeader) {
        $('body').removeClass('docked');
        this.dockedHeader = false;
      }
    }
  },

  /**
    Display the correct logo in the header, showing a custom small icon if it exists.

    @property logoHTML
  **/
  logoHTML: function() {
    var result = "
";
    if (this.get('controller.showExtraInfo')) {
      var logo = Discourse.SiteSettings.logo_small_url;
      if (logo && logo.length > 1) {
        result += "";
      } else {
        result += "";
      }
    } else {
      result += "";
    }
    result += "
";
    return new Handlebars.SafeString(result);
  }.property('controller.showExtraInfo'),

  willDestroyElement: function() {
    $(window).unbind('scroll.discourse-dock');
    $(document).unbind('touchmove.discourse-dock');
    this.$('a.unread-private-messages, a.unread-notifications, a[data-notifications]').off('click.notifications');
    this.$('a[data-dropdown]').off('click.dropdown');
  },

  didInsertElement: function() {

    var headerView = this;
    this.$('a[data-dropdown]').on('click.dropdown', function(e) {
      return headerView.showDropdown($(e.currentTarget));
    });
    this.$('a.unread-private-messages, a.unread-notifications, a[data-notifications]').on('click.notifications', function(e) {
      return headerView.showNotifications(e);
    });
    $(window).bind('scroll.discourse-dock', function() {
      headerView.examineDockHeader();
    });
    $(document).bind('touchmove.discourse-dock', function() {
      headerView.examineDockHeader();
    });
    this.examineDockHeader();

    // Delegate ESC to the composer
    $('body').on('keydown.header', function(e) {
      // Hide dropdowns
      if (e.which === 27) {
        headerView.$('li').removeClass('active');
        headerView.$('.d-dropdown').fadeOut('fast');
      }
      if (headerView.get('editingTopic')) {
        if (e.which === 13) {
          headerView.finishedEdit();
        }
        if (e.which === 27) {
          return headerView.cancelEdit();
        }
      }
    });
  }
});

<commit_msg>added a conditional that checks if the logo_url setting is empty. In that case, the logoHTML function returns a header tag with the site_title as its content<commit_after>/**
  This view handles rendering of the header of the site

  @class HeaderView
  @extends Discourse.View
  @namespace Discourse
  @module Discourse
**/
Discourse.HeaderView = Discourse.View.extend({
  tagName: 'header',
  classNames: ['d-header', 'clearfix'],
  classNameBindings: ['editingTopic'],
  templateName: 'header',
  topicBinding: 'Discourse.router.topicController.content',

  showDropdown: function($target) {
    var elementId = $target.data('dropdown') || $target.data('notifications'),
        $dropdown = $("#" + elementId),
        $li = $target.closest('li'),
        $ul = $target.closest('ul'),
        $html = $('html');

    var hideDropdown = function() {
      $dropdown.fadeOut('fast');
      $li.removeClass('active');
      $html.data('hide-dropdown', null);
      return $html.off('click.d-dropdown');
    };

    // if a dropdown is active and the user clics on it, close it
    if($li.hasClass('active')) { return hideDropdown(); }
    // otherwhise, mark it as active
    $li.addClass('active');
    // hide the other dropdowns
    $('li', $ul).not($li).removeClass('active');
    $('.d-dropdown').not($dropdown).fadeOut('fast');
    // fade it fast
    $dropdown.fadeIn('fast');
    // autofocus any text input field
    $dropdown.find('input[type=text]').focus().select();

    $html.on('click.d-dropdown', function(e) {
      return $(e.target).closest('.d-dropdown').length > 0 ? true : hideDropdown();
    });

    $html.data('hide-dropdown', hideDropdown);

    return false;
  },

  showNotifications: function() {

    var headerView = this;
    Discourse.ajax('/notifications').then(function(result) {
      headerView.set('notifications', result.map(function(n) {
        return Discourse.Notification.create(n);
      }));

      // We've seen all the notifications now
      Discourse.User.current().set('unread_notifications', 0);
      headerView.showDropdown($('#user-notifications'));
    });
    return false;
  },

  examineDockHeader: function() {
    var $body, offset, outlet;
    if (!this.docAt) {
      outlet = $('#main-outlet');
      if (!(outlet && outlet.length === 1)) return;
      this.docAt = outlet.offset().top;
    }
    offset = window.pageYOffset || $('html').scrollTop();
    if (offset >= this.docAt) {
      if (!this.dockedHeader) {
        $body = $('body');
        $body.addClass('docked');
        this.dockedHeader = true;
      }
    } else {
      if (this.dockedHeader) {
        $('body').removeClass('docked');
        this.dockedHeader = false;
      }
    }
  },

  /**
    Display the correct logo in the header, showing a custom small icon if it exists.
    In case the logo_url setting is empty, shows the site title as the logo.
    @property logoHTML
  **/
  logoHTML: function() {
    var result = "
";
    if (this.get('controller.showExtraInfo')) {
      var logoSmall = Discourse.SiteSettings.logo_small_url;
      if (logoSmall && logoSmall.length > 1) {
        result += "";
      } else {
        result += "";
      }
    } else {
      var logo = Discourse.SiteSettings.logo_url;
      if(logo && logo.length > 1) {
        result += "";
      } else {
        result += "
" + Discourse.SiteSettings.title + "
"
      }
    }
    result += "
";
    return new Handlebars.SafeString(result);
  }.property('controller.showExtraInfo'),

  willDestroyElement: function() {
    $(window).unbind('scroll.discourse-dock');
    $(document).unbind('touchmove.discourse-dock');
    this.$('a.unread-private-messages, a.unread-notifications, a[data-notifications]').off('click.notifications');
    this.$('a[data-dropdown]').off('click.dropdown');
  },

  didInsertElement: function() {

    var headerView = this;
    this.$('a[data-dropdown]').on('click.dropdown', function(e) {
      return headerView.showDropdown($(e.currentTarget));
    });
    this.$('a.unread-private-messages, a.unread-notifications, a[data-notifications]').on('click.notifications', function(e) {
      return headerView.showNotifications(e);
    });
    $(window).bind('scroll.discourse-dock', function() {
      headerView.examineDockHeader();
    });
    $(document).bind('touchmove.discourse-dock', function() {
      headerView.examineDockHeader();
    });
    this.examineDockHeader();

    // Delegate ESC to the composer
    $('body').on('keydown.header', function(e) {
      // Hide dropdowns
      if (e.which === 27) {
        headerView.$('li').removeClass('active');
        headerView.$('.d-dropdown').fadeOut('fast');
      }
      if (headerView.get('editingTopic')) {
        if (e.which === 13) {
          headerView.finishedEdit();
        }
        if (e.which === 27) {
          return headerView.cancelEdit();
        }
      }
    });
  }
});

<|endoftext|>


<commit_before>import { Link, animateScroll as scroll } from "react-scroll"
import React from "react"
import Hamburger from "./Hamburger"

import "./Navbar.css"

class Navbar extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isHamburgerToggled: false
    };
  }

  handleScroll = () => {
    const {scrollHeight} = this.state;
    const newScrollHeight = window.scrollY;
    const isNavVisable = newScrollHeight <= scrollHeight;
    this.setState({
      scrollHeight: newScrollHeight,
      isNavVisable: isNavVisable,
      isHamburgerToggled: false
    });
  };

  handleNavClassName = () => {
    return !this.state.isNavVisable ? "hidden-nav" : ""
  };

  handleMenuClassName = () => {
    return this.state.isHamburgerToggled ? "nav-li responsive-nav" : "nav-li"
  };

  handleHamburgerClassName = () => {
    return this.state.isHamburgerToggled ? "hidden-icon responsive-hamburger" : "hidden-icon"
  };

  handleClick = () => {
    this.setState({isHamburgerToggled: !this.state.isHamburgerToggled});
  };

  renderHamburger = () => {
    return (
      <Hamburger
        onClick={() => this.handleClick()} onKeyDown={() => this.handleClick}
        isToggled={this.state.isHamburgerToggled}
      />
    );
  };

  componentDidMount() {
    this.setState({scrollHeight: window.scrollY, isNavVisable: true});
    window.addEventListener("scroll", this.handleScroll);
  }

  componentWillUnmount() {
    window.removeEventListener("scroll", this.handleScroll);
  }

  render() {
    return (

          <Link
            className={this.handleMenuClassName()}
            activeClass="active"
            to="home"
            spy={true}
            smooth={true}
            offset={-50}
            duration={500}
          >
             Home
          </Link>
          <Link
            className={this.handleMenuClassName()}
            activeClass="active"
            to="about"
            spy={true}
            smooth={true}
            offset={-50}
            duration={500}
          >
            About
          </Link>
          <Link
            className={this.handleMenuClassName()}
            activeClass="active"
            to="projects"
            spy={true}
            smooth={true}
            offset={-50}
            duration={500}
          >
            Projects
          </Link>
          <Link
            className={this.handleMenuClassName()}
            activeClass="active"
            to="contact"
            spy={true}
            smooth={true}
            offset={-50}
            duration={500}
          >
            Contact
          </Link>
          <button className={this.handleHamburgerClassName()}>
            {this.renderHamburger()}
          </button>

    );
  }
}

export default Navbar;
<commit_msg>Removed unused animateScroll from Navbar<commit_after>import {Link} from "react-scroll"
import React from "react"
import Hamburger from "./Hamburger"

import "./Navbar.css"

class Navbar extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isHamburgerToggled: false
    };
  }

  handleScroll = () => {
    const {scrollHeight} = this.state;
    const newScrollHeight = window.scrollY;
    const isNavVisable = newScrollHeight <= scrollHeight;
    this.setState({
      scrollHeight: newScrollHeight,
      isNavVisable: isNavVisable,
      isHamburgerToggled: false
    });
  };

  handleNavClassName = () => {
    return !this.state.isNavVisable ? "hidden-nav" : ""
  };

  handleMenuClassName = () => {
    return this.state.isHamburgerToggled ? "nav-li responsive-nav" : "nav-li"
  };

  handleHamburgerClassName = () => {
    return this.state.isHamburgerToggled ? "hidden-icon responsive-hamburger" : "hidden-icon"
  };

  handleClick = () => {
    this.setState({isHamburgerToggled: !this.state.isHamburgerToggled});
  };

  renderHamburger = () => {
    return (
      <Hamburger
        onClick={() => this.handleClick()} onKeyDown={() => this.handleClick}
        isToggled={this.state.isHamburgerToggled}
      />
    );
  };

  componentDidMount() {
    this.setState({scrollHeight: window.scrollY, isNavVisable: true});
    window.addEventListener("scroll", this.handleScroll);
  }

  componentWillUnmount() {
    window.removeEventListener("scroll", this.handleScroll);
  }

  render() {
    return (

          <Link
            className={this.handleMenuClassName()}
            activeClass="active"
            to="home"
            spy={true}
            smooth={true}
            offset={-50}
            duration={500}
          >
             Home
          </Link>
          <Link
            className={this.handleMenuClassName()}
            activeClass="active"
            to="about"
            spy={true}
            smooth={true}
            offset={-50}
            duration={500}
          >
            About
          </Link>
          <Link
            className={this.handleMenuClassName()}
            activeClass="active"
            to="projects"
            spy={true}
            smooth={true}
            offset={-50}
            duration={500}
          >
            Projects
          </Link>
          <Link
            className={this.handleMenuClassName()}
            activeClass="active"
            to="contact"
            spy={true}
            smooth={true}
            offset={-50}
            duration={500}
          >
            Contact
          </Link>
          <button className={this.handleHamburgerClassName()}>
            {this.renderHamburger()}
          </button>

    );
  }
}

export default Navbar;
<|endoftext|>


<commit_before>var auth = require('./auth');
var mraa = require('mraa');
var flex = require('./flex');
var lcd = require('./lcd');
var display = new lcd.LCD(0);

auth({ host : "10.10.107.39" }).then(function(ddp){
  flex(3, function(){
    console.log("Flex motion!");
  })
}).done();<commit_msg>Speak at start of Edison<commit_after>var auth = require('./auth');
var mraa = require('mraa');
var flex = require('./flex');
var lcd = require('./lcd');
var display = new lcd.LCD(0);

auth({ host : "10.10.107.39" }).then(function(ddp){
  flex(3, function(){
    console.log("Flex motion!");
  })

  ddp.call(
      'speak',
      ["Ik ben opgestart! Getekend, Thomas.", "Xander"],
      function (err, result) {   // callback which returns the method call results
        console.log('called function, result: ' + result);
      },
      function () {              // callback which fires when server has finished
        console.log('updated');  // sending any updated documents as a result of
        console.log(ddp.collections.users);  // calling this method
      }
    );
}).done();<|endoftext|>


<commit_before>import React from 'react';
import { connect } from 'react-redux';
import TransitionGroup from 'react-addons-css-transition-group';

// These can be overridden by changing the componentClassName prop
import '../../css/styles.css';
import Notif from './Notif';

// This checks to see if object is immutable and properly access it
const getter = (obj, propName) => (obj.get ? obj.get(propName) : obj[propName]);

const Notifs = (props) => {
  const { notifications, className, componentClassName, CustomComponent, transitionEnterTimeout, transitionLeaveTimeout } = props;

  const renderedNotifications = notifications.map((notification) => {
    if (CustomComponent) {
      return <CustomComponent key={getter(notification, 'id')} {...props} />;
    }

    return (
      <Notif
        componentClassName={componentClassName}
        key={getter(notification, 'id')}
        id={getter(notification, 'id')}
        message={getter(notification, 'message')}
        kind={getter(notification, 'kind')}
        {...props}
      />
    );
  });
  const classes = [
    `${componentClassName}__container`,
    className
  ].join(' ').split();

  return (

      <TransitionGroup
        transitionName={`${componentClassName}-transition`}
        transitionEnterTimeout={transitionEnterTimeout}
        transitionLeaveTimeout={transitionLeaveTimeout}
      >
        {renderedNotifications}
      </TransitionGroup>

  );
};

Notifs.defaultProps = {
  className: null,
  componentClassName: 'notif',
  CustomComponent: null,
  transitionEnterTimeout: 600,
  transitionLeaveTimeout: 600,
};

Notifs.propTypes = {
  notifications: React.PropTypes.array.isRequired,
  className: React.PropTypes.string,
  CustomComponent: React.PropTypes.oneOfType([
    React.PropTypes.func,
    React.PropTypes.node,
    React.PropTypes.element
  ]),
  componentClassName: React.PropTypes.string,
  transitionEnterTimeout: React.PropTypes.number,
  transitionLeaveTimeout: React.PropTypes.number,
};

function mapStateToProps(state) {
  return { notifications: state.get ? state.get('notifs') : state.notifs };
}

export default connect(mapStateToProps)(Notifs);
<commit_msg>do not override component props<commit_after>import React from 'react';
import { connect } from 'react-redux';
import TransitionGroup from 'react-addons-css-transition-group';

// These can be overridden by changing the componentClassName prop
import '../../css/styles.css';
import Notif from './Notif';

// This checks to see if object is immutable and properly access it
const getter = (obj, propName) => (obj.get ? obj.get(propName) : obj[propName]);

const Notifs = (props) => {
  const { notifications, className, componentClassName, CustomComponent, transitionEnterTimeout, transitionLeaveTimeout } = props;

  const renderedNotifications = notifications.map((notification) => {
    if (CustomComponent) {
      return <CustomComponent key={getter(notification, 'id')} {...props} />;
    }

    return (
      <Notif
        {...props}
        componentClassName={componentClassName}
        key={getter(notification, 'id')}
        id={getter(notification, 'id')}
        message={getter(notification, 'message')}
        kind={getter(notification, 'kind')}
      />
    );
  });
  const classes = [
    `${componentClassName}__container`,
    className
  ].join(' ').split();

  return (

      <TransitionGroup
        transitionName={`${componentClassName}-transition`}
        transitionEnterTimeout={transitionEnterTimeout}
        transitionLeaveTimeout={transitionLeaveTimeout}
      >
        {renderedNotifications}
      </TransitionGroup>

  );
};

Notifs.defaultProps = {
  className: null,
  componentClassName: 'notif',
  CustomComponent: null,
  transitionEnterTimeout: 600,
  transitionLeaveTimeout: 600,
};

Notifs.propTypes = {
  notifications: React.PropTypes.array.isRequired,
  className: React.PropTypes.string,
  CustomComponent: React.PropTypes.oneOfType([
    React.PropTypes.func,
    React.PropTypes.node,
    React.PropTypes.element
  ]),
  componentClassName: React.PropTypes.string,
  transitionEnterTimeout: React.PropTypes.number,
  transitionLeaveTimeout: React.PropTypes.number,
};

function mapStateToProps(state) {
  return { notifications: state.get ? state.get('notifs') : state.notifs };
}

export default connect(mapStateToProps)(Notifs);
<|endoftext|>


<commit_before>//= require zxcvbn

(function() {
  "use strict"
  var root = this,
      $ = root.jQuery;

  if(typeof root.GOVUK === 'undefined') { root.GOVUK = {}; }

  var PasswordStrengthIndicator = function(options) {
    var instance = this;

    options["password_field"].keyup(function() {
      var password = $(this).val();
      instance.updateStrengthIndicator(password, options);
    });

    $(options["password_strength_guidance"]).attr("aria-live", "polite").attr("aria-atomic", "true");
  };

  PasswordStrengthIndicator.prototype.updateStrengthIndicator = function(password, options) {
    var guidance = [];

    var result = zxcvbn(password, options["weak_words"]);
    if (password.length > 0) {
      if (options["min_password_length"] && password.length < parseInt(options["min_password_length"])) {
        guidance.push('password-too-short');
      }

      var isPasswordNotStrongEnough = (result.score < options["strong_passphrase_boundary"]);

      var aWeakWordFoundInPassword = $(options["weak_words"]).is(function(i, weak_word) {
        return (password.indexOf(weak_word) >= 0);
      });
      if (isPasswordNotStrongEnough && aWeakWordFoundInPassword) {
        guidance.push('parts-of-email');
      }

      if (isPasswordNotStrongEnough) {
        guidance.push('not-strong-enough');
      } else {
        guidance.push('good-password');
      }
    }
    options["update_indicator"](guidance, result.score);
  };

  GOVUK.passwordStrengthPossibleGuidance = [
    'password-too-short',
    'parts-of-email',
    'not-strong-enough',
    'good-password'
  ]

  GOVUK.passwordStrengthIndicator = PasswordStrengthIndicator;

  var PasswordConfirmationIndicator = function(options) {
    var instance = this;

    $.each([options["password_field"], options["password_confirmation_field"]], function(i, password_field) {
      $(password_field).keyup(function() {
        var password = $(options["password_field"]).val();
        var passwordConfirmation = $(options["password_confirmation_field"]).val();
        instance.updateIndicator(password, passwordConfirmation, options);
      });
    });

    $(options["password_confirmation_guidance"]).attr("aria-live", "polite").attr("aria-atomic", "true");
  };

  PasswordConfirmationIndicator.prototype.updateIndicator = function(password, passwordConfirmation, options) {
    var guidance = [];

    if (passwordConfirmation.length > 0) {
      if (password === passwordConfirmation) {
        guidance.push("confirmation-matching");
      } else {
        guidance.push("confirmation-not-matching");
      }
    } else {
      guidance.push("no-password-confirmation-provided");
    }

    options["update_indicator"](guidance);
  };

  GOVUK.passwordConfirmationPossibleGuidance = [
    'confirmation-matching',
    'confirmation-not-matching',
    'no-password-confirmation-provided'
  ]

  GOVUK.passwordConfirmationIndicator = PasswordConfirmationIndicator;
}).call(this);

$(function() {
  $("form #password-control-group input[type=password]").each(function(){
    var $passwordChangePanel = $('#password-change-panel');

    var $passwordField = $(this);
    $passwordField.parent().append('<input type="hidden" id="password-strength-score" name="password-strength-score" value=""/>');

    new GOVUK.passwordStrengthIndicator({
      password_field: $passwordField,
      password_strength_guidance: $('#password-guidance'),

      weak_words: $passwordField.data('weak-words').split(","),
      strong_passphrase_boundary: 4,
      min_password_length: $passwordField.data('min-password-length'),

      update_indicator: function(guidance, strengthScore) {
        $('#password-strength-score').val(strengthScore);

        $passwordChangePanel.removeClass(GOVUK.passwordStrengthPossibleGuidance.join(" "));
        $passwordChangePanel.addClass(guidance.join(" "));

        if ($.inArray('good-password', guidance) >= 0) {
          $passwordField.attr('aria-invalid', "false");
          $('#password-result').removeClass('icon-remove').addClass('icon-ok');
        } else {
          $passwordField.attr('aria-invalid', "true");
          $('#password-result').removeClass('icon-ok').addClass('icon-remove');
        }
      }
    });

    var $passwordConfirmationField = $("form #password-confirmation-control-group input[type=password]");

    new GOVUK.passwordConfirmationIndicator({
      password_field: $passwordField,
      password_confirmation_field: $passwordConfirmationField,
      password_confirmation_guidance: $('#password-confirmation-guidance'),
      update_indicator: function(guidance) {
        $passwordChangePanel.removeClass(GOVUK.passwordConfirmationPossibleGuidance.join(" "));
        $passwordChangePanel.addClass(guidance.join(" "));

        var indicator = $('#password-confirmation-result');
        if ($.inArray('confirmation-not-matching', guidance) >= 0) {
          $passwordConfirmationField.attr('aria-invalid', "true");
          indicator.removeClass('icon-ok').addClass('icon-remove');
          indicator.parent().removeClass('confirmation-matching');
        } else { /* password and confirmation match */
          $passwordConfirmationField.attr('aria-invalid', "false");
          indicator.removeClass('icon-remove');
          // Add tick only if password field is also valid.
          if($passwordField.attr('aria-invalid') == "false") {
            indicator.addClass('icon-ok');
            indicator.parent().addClass('confirmation-matching');
          }
        }
      }
    });
  });
});
<commit_msg>Refactor password strength indicator code<commit_after>//= require zxcvbn

(function() {
  "use strict"
  var root = this,
      $ = root.jQuery;

  if(typeof root.GOVUK === 'undefined') { root.GOVUK = {}; }

  var PasswordStrengthIndicator = function(options) {
    var instance = this;

    $.each([options["password_field"], options["password_confirmation_field"]], function(i, password_field) {
      $(password_field).keyup(function() {
        var password = $(options["password_field"]).val(),
            passwordConfirmation = $(options["password_confirmation_field"]).val();
        instance.updateIndicator(password, passwordConfirmation, options);
      });
    });

    $(options["password_strength_guidance"]).attr("aria-live", "polite").attr("aria-atomic", "true");
  };

  PasswordStrengthIndicator.prototype.updateIndicator = function(password, passwordConfirmation, options) {
    var guidance = [];

    var result = zxcvbn(password, options["weak_words"]);
    if (password.length > 0) {
      if (options["min_password_length"] && password.length < parseInt(options["min_password_length"])) {
        guidance.push('password-too-short');
      }

      var isPasswordNotStrongEnough = (result.score < options["strong_passphrase_boundary"]);

      var aWeakWordFoundInPassword = $(options["weak_words"]).is(function(i, weak_word) {
        return (password.indexOf(weak_word) >= 0);
      });
      if (isPasswordNotStrongEnough && aWeakWordFoundInPassword) {
        guidance.push('parts-of-email');
      }

      if (isPasswordNotStrongEnough) {
        guidance.push('not-strong-enough');
      } else {
        guidance.push('good-password');
      }
    }

    if (passwordConfirmation.length > 0) {
      if (password === passwordConfirmation) {
        guidance.push("confirmation-matching");
      } else {
        guidance.push("confirmation-not-matching");
      }
    } else {
      guidance.push("no-password-confirmation-provided");
    }

    options["update_indicator"](guidance, result.score);
  };

  GOVUK.passwordStrengthPossibleGuidance = [
    'password-too-short',
    'parts-of-email',
    'not-strong-enough',
    'good-password'
  ]

  GOVUK.passwordConfirmationPossibleGuidance = [
    'confirmation-matching',
    'confirmation-not-matching',
    'no-password-confirmation-provided'
  ]

  GOVUK.passwordStrengthIndicator = PasswordStrengthIndicator;
}).call(this);

$(function() {
  $("form #password-control-group input[type=password]").each(function(){
    var $passwordChangePanel = $('#password-change-panel');

    var $passwordField = $(this);
    var $passwordConfirmationField = $("form #password-confirmation-control-group input[type=password]");
    $passwordField.parent().append('<input type="hidden" id="password-strength-score" name="password-strength-score" value=""/>');

    new GOVUK.passwordStrengthIndicator({
      password_field: $passwordField,
      password_strength_guidance: $('#password-guidance'),

      password_confirmation_field: $passwordConfirmationField,
      password_confirmation_guidance: $('#password-confirmation-guidance'),

      weak_words: $passwordField.data('weak-words').split(","),
      strong_passphrase_boundary: 4,
      min_password_length: $passwordField.data('min-password-length'),

      update_indicator: function(guidance, strengthScore) {
        $('#password-strength-score').val(strengthScore);

        $passwordChangePanel.removeClass(GOVUK.passwordStrengthPossibleGuidance.join(" "));
        $passwordChangePanel.addClass(guidance.join(" "));

        if ($.inArray('good-password', guidance) >= 0) {
          $passwordField.attr('aria-invalid', "false");
          $('#password-result').removeClass('icon-remove').addClass('icon-ok');
        } else {
          $passwordField.attr('aria-invalid', "true");
          $('#password-result').removeClass('icon-ok').addClass('icon-remove');
        }

        $passwordChangePanel.removeClass(GOVUK.passwordConfirmationPossibleGuidance.join(" "));
        $passwordChangePanel.addClass(guidance.join(" "));

        var indicator = $('#password-confirmation-result');
        if ($.inArray('confirmation-not-matching', guidance) >= 0) {
          $passwordConfirmationField.attr('aria-invalid', "true");
          indicator.removeClass('icon-ok').addClass('icon-remove');
          indicator.parent().removeClass('confirmation-matching');
        } else { /* password and confirmation match */
          $passwordConfirmationField.attr('aria-invalid', "false");
          indicator.removeClass('icon-remove');
          // Add tick only if password field is also valid.
          if($.inArray('good-password', guidance) >= 0) {
            indicator.addClass('icon-ok');
            indicator.parent().addClass('confirmation-matching');
          }
        }
      }
    });
  });
});
<|endoftext|>