<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var allocCluster = require('./lib/alloc-cluster');
var TChannel = require('../channel');
var RelayHandler = require('../relay_handler');

allocCluster.test('send relay requests', {
    numPeers: 2
}, function t(cluster, assert) {
    var one = cluster.channels[0];
    var two = cluster.channels[1];

    var oneToTwo = one.makeSubChannel({
        serviceName: 'two',
        peers: [two.hostPort]
    });
    oneToTwo.handler = new RelayHandler(oneToTwo);

    var twoSvc = two.makeSubChannel({
        serviceName: 'two'
    });
    twoSvc.register('echo', echo);

    var client = TChannel({
        logger: one.logger
    });
    var twoClient = client.makeSubChannel({
        serviceName: 'two',
        peers: [one.hostPort]
    });

    twoClient.request({
        service: 'two'
    }).send('echo', 'foo', 'bar', function done(err, res, arg2, arg3) {
        assert.ifError(err, 'no unexpected error');
        assert.equal(String(arg2), 'foo', 'expected arg2');
        assert.equal(String(arg3), 'bar', 'expected arg3');
        assert.end();
    });
});

allocCluster.test('relay an error frame', {
    numPeers: 4
}, function t(cluster, assert) {
    var one = cluster.channels[0];
    var two = cluster.channels[1];
    var three = cluster.channels[2];
    var four = cluster.channels[3];

    var oneToTwo = one.makeSubChannel({
        serviceName: 'two',
        peers: [two.hostPort, three.hostPort]
    });
    oneToTwo.handler = new RelayHandler(oneToTwo);
    var fourToTwo = four.makeSubChannel({
        serviceName: 'two',
        peers: [two.hostPort, three.hostPort]
    });
    fourToTwo.handler = new RelayHandler(fourToTwo);

    var twoSvc2 = three.makeSubChannel({
        serviceName: 'two'
    });
    twoSvc2.register('decline', declineError);

    var twoSvc = two.makeSubChannel({
        serviceName: 'two'
    });
    twoSvc.register('decline', declineError);

    var client = TChannel({
        logger: one.logger
    });
    var twoClient = client.makeSubChannel({
        serviceName: 'two',
        peers: [one.hostPort, four.hostPort]
    });

    twoClient.request({
        service: 'two'
    }).send('decline', 'foo', 'bar', function done(err, res, arg2, arg3) {
        assert.equal(err.type, 'tchannel.declined', 'expected declined error');

        assert.end();
    });

    function declineError(req, res, arg2, arg3) {
        res.sendError('Declined', 'lul');
    }
});

function echo(req, res, arg2, arg3) {
    res.sendOk(arg2, arg3);
}
<commit_msg>test/relay: use requestDefaults serviceName to demonstrate the intended path<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var allocCluster = require('./lib/alloc-cluster');
var TChannel = require('../channel');
var RelayHandler = require('../relay_handler');

allocCluster.test('send relay requests', {
    numPeers: 2
}, function t(cluster, assert) {
    var one = cluster.channels[0];
    var two = cluster.channels[1];

    var oneToTwo = one.makeSubChannel({
        serviceName: 'two',
        peers: [two.hostPort]
    });
    oneToTwo.handler = new RelayHandler(oneToTwo);

    var twoSvc = two.makeSubChannel({
        serviceName: 'two'
    });
    twoSvc.register('echo', echo);

    var client = TChannel({
        logger: one.logger
    });
    var twoClient = client.makeSubChannel({
        serviceName: 'two',
        peers: [one.hostPort],
        requestDefaults: {
            serviceName: 'two'
        }
    });

    twoClient.request().send('echo', 'foo', 'bar', function done(err, res, arg2, arg3) {
        assert.ifError(err, 'no unexpected error');
        assert.equal(String(arg2), 'foo', 'expected arg2');
        assert.equal(String(arg3), 'bar', 'expected arg3');
        assert.end();
    });
});

allocCluster.test('relay an error frame', {
    numPeers: 4
}, function t(cluster, assert) {
    var one = cluster.channels[0];
    var two = cluster.channels[1];
    var three = cluster.channels[2];
    var four = cluster.channels[3];

    var oneToTwo = one.makeSubChannel({
        serviceName: 'two',
        peers: [two.hostPort, three.hostPort]
    });
    oneToTwo.handler = new RelayHandler(oneToTwo);
    var fourToTwo = four.makeSubChannel({
        serviceName: 'two',
        peers: [two.hostPort, three.hostPort]
    });
    fourToTwo.handler = new RelayHandler(fourToTwo);

    var twoSvc2 = three.makeSubChannel({
        serviceName: 'two'
    });
    twoSvc2.register('decline', declineError);

    var twoSvc = two.makeSubChannel({
        serviceName: 'two'
    });
    twoSvc.register('decline', declineError);

    var client = TChannel({
        logger: one.logger
    });
    var twoClient = client.makeSubChannel({
        serviceName: 'two',
        peers: [one.hostPort, four.hostPort],
        requestDefaults: {
            serviceName: 'two'
        }
    });

    twoClient.request().send('decline', 'foo', 'bar', function done(err, res, arg2, arg3) {
        assert.equal(err.type, 'tchannel.declined', 'expected declined error');

        assert.end();
    });

    function declineError(req, res, arg2, arg3) {
        res.sendError('Declined', 'lul');
    }
});

function echo(req, res, arg2, arg3) {
    res.sendOk(arg2, arg3);
}
<|endoftext|>


<commit_before>// basic test file demonstrating mocha

var assert = require('assert');

describe("test1", function() {
	it("should pass", function(){
		assert.ok(true)
	});
	it("shouldn also pass", function(){
		assert.notEqual(0, 1)
	});
});
<commit_msg>Removed test1.js<commit_after><|endoftext|>


<commit_before>// @ts-check
const fs = require("fs")
const path = require("path")
const { basePath, isDevelopment } = require("../src/lib/environment")

// Helpers
export function getEntrypoints() {
  return findAssets("src/client/assets")
}

export function findAssets(rootPath) {
  const files = fs.readdirSync(path.join(basePath, rootPath))
  // Filter out .styl files
  const validAssets = file => {
    const isValid = /\.(js|ts|coffee)x?/.test(path.extname(file))
    return isValid
  }

  /**
   * Construct key/value pairs representing Webpack entrypoints; e.g.,
   * { desktop: [ path/to/subapp.asset.js ] }
   */
  const assets = files.filter(validAssets).reduce((assetMap, file) => {
    const fileName = path.basename(file, path.extname(file))
    const asset = {
      [fileName]: [path.join(basePath, rootPath, file)],
    }

    if (isDevelopment) {
      asset[fileName].unshift("webpack-hot-middleware/client?reload=true")
    }

    return {
      ...assetMap,
      ...asset,
    }
  }, {})

  return assets
}
<commit_msg>fix webpack helper exports for production mode<commit_after>// @ts-check
const fs = require("fs")
const path = require("path")
const { basePath, isDevelopment } = require("../src/lib/environment")

// Helpers
function getEntrypoints() {
  return findAssets("src/client/assets")
}

function findAssets(rootPath) {
  const files = fs.readdirSync(path.join(basePath, rootPath))
  // Filter out .styl files
  const validAssets = file => {
    const isValid = /\.(js|ts|coffee)x?/.test(path.extname(file))
    return isValid
  }

  /**
   * Construct key/value pairs representing Webpack entrypoints; e.g.,
   * { desktop: [ path/to/subapp.asset.js ] }
   */
  const assets = files.filter(validAssets).reduce((assetMap, file) => {
    const fileName = path.basename(file, path.extname(file))
    const asset = {
      [fileName]: [path.join(basePath, rootPath, file)],
    }

    if (isDevelopment) {
      asset[fileName].unshift("webpack-hot-middleware/client?reload=true")
    }

    return {
      ...assetMap,
      ...asset,
    }
  }, {})

  return assets
}

module.exports.getEntrypoints = getEntrypoints
<|endoftext|>


<commit_before>'use strict';

var validator = require('validator'),
  fs = require('fs'),
  path = require('path'),
  BoxSDK = require('box-node-sdk'),
  multer = require('multer'),
  cognitiveServices = require('cognitive-services'),
  config = require(path.resolve('./config/config'));

var sdk = new BoxSDK({
  clientID: config.box.clientID,
  clientSecret: config.box.clientSecret,
  appAuth: {
      keyID: config.box.appAuth.publicKeyID,
      privateKey: config.box.appAuth.privateKey,
      passphrase: config.box.appAuth.passphrase
  }
});
//Box Client
var client = sdk.getBasicClient(config.box.appAuth.accessToken);

/**
 * Render the main application page
 */
exports.getAndRunOCR = function (req, res) {
    client.files.get(req.params.file_id, null, function(err, fileinfo) {
        if(err) {
            console.error(err);
            res.status(500).send({message: err.message});
        } else {
            client.files.getReadStream(req.params.file_id, null, function(err, stream) {
                if (err) {
                    // handle error
                    console.error(err);
                    res.status(500).send({message: err.message});
                } else {
                    // write the file to disk
                    var output = fs.createWriteStream('./public/images/downloads/' + fileinfo.name);
                    stream.pipe(output);
                }
            });
        }
    });
};

exports.testOCR = function(req, res) {
    const computerVision = cognitiveServices.computerVision({
        API_KEY: config.azure.cognitiveServicesKey1
    });

    const parameters = {
        language: "unk",
        detectOrientation: "true",
        "content-type": "application/json"
    };
    /* Input passed within the POST body. Supported input methods: raw image binary or image URL.

    Input requirements:

    Supported image formats: JPEG, PNG, GIF, BMP.
    Image file size must be less than 4MB.
    Image dimensions must be between 40 x 40 and 3200 x 3200 pixels, and the image cannot be larger than 100 megapixels.

    */
    const body = {
        'url': 'https://nwrecruiter.azurewebsites.net/downloads/ResumeScreenShot.png'
    };

    computerVision.ocr({
            parameters,
            body
        })
        .then((response) => {
            console.log('Got response', response);
            var out = '';
            var regionsout = [];
            for(var r in response.regions) {
                var regionout = {};
                var region = response.regions[r];
                for(var l in region.lines) {
                    var lineout = {};
                    var line = region.lines[l];
                    for(var w in line.words) {
                        var word = line.words[w].text;
                        out += word + ' ';
                    }
                    out += '\n';
                }
                out += '\n';
            }
            out = out.toLowerCase();
            var matchedKeywords = [];
            for(var k in config.keywords) {
                var keyword = config.keywords[k].toLowerCase();
                if(out.includes(keyword)) {
                    matchedKeywords.push(keyword);
                }
            }
            res.status(200).send({OCR: out, matchedKeywords: matchedKeywords});

        })
        .catch((err) => {
            console.error('Encountered error making request:', err);
            res.status(500).send({message: e.message});
        });
};

exports.getFilesMatchingKeywords = function(req, res) {
    var keywords = req.body.keywords;
    console.log(keywords);
    res.json({message: 'Got keywords ' + keywords.join(',')});
};

exports.uploadFile = function(req, res) {
    console.log("req:");
    console.log(req);
    console.log("req.file:");
    console.log(req.file);
    console.log("req.body:");
    console.log(req.body);
    var upload = multer({ dest: './public/images/uploads' }).single('resumeUpload');
    uploadImage()
      .then(function () {
        var stream = fs.createReadStream('./public/images/uploads/' + req.file.filename);
        client.files.uploadFile('32442834639', req.file.filename, stream, function(err, response){
            if(err) {
                console.error(err);
                res.status(500).send(err);
            } else {
                console.log(response);
                //
                res.json({message: "success"});
            }
        });
      })
      .catch(function (err) {
        res.status(500).send(err);
      });

    function uploadImage () {
        return new Promise(function (resolve, reject) {
            upload(req, res, function (uploadError) {
                if (uploadError) {
                    reject(uploadError);
                } else {
                    resolve();
                }
            });
        });
    }
};

<commit_msg>changed multer single<commit_after>'use strict';

var validator = require('validator'),
  fs = require('fs'),
  path = require('path'),
  BoxSDK = require('box-node-sdk'),
  multer = require('multer'),
  cognitiveServices = require('cognitive-services'),
  config = require(path.resolve('./config/config'));

var sdk = new BoxSDK({
  clientID: config.box.clientID,
  clientSecret: config.box.clientSecret,
  appAuth: {
      keyID: config.box.appAuth.publicKeyID,
      privateKey: config.box.appAuth.privateKey,
      passphrase: config.box.appAuth.passphrase
  }
});
//Box Client
var client = sdk.getBasicClient(config.box.appAuth.accessToken);

/**
 * Render the main application page
 */
exports.getAndRunOCR = function (req, res) {
    client.files.get(req.params.file_id, null, function(err, fileinfo) {
        if(err) {
            console.error(err);
            res.status(500).send({message: err.message});
        } else {
            client.files.getReadStream(req.params.file_id, null, function(err, stream) {
                if (err) {
                    // handle error
                    console.error(err);
                    res.status(500).send({message: err.message});
                } else {
                    // write the file to disk
                    var output = fs.createWriteStream('./public/images/downloads/' + fileinfo.name);
                    stream.pipe(output);
                }
            });
        }
    });
};

exports.testOCR = function(req, res) {
    const computerVision = cognitiveServices.computerVision({
        API_KEY: config.azure.cognitiveServicesKey1
    });

    const parameters = {
        language: "unk",
        detectOrientation: "true",
        "content-type": "application/json"
    };
    /* Input passed within the POST body. Supported input methods: raw image binary or image URL.

    Input requirements:

    Supported image formats: JPEG, PNG, GIF, BMP.
    Image file size must be less than 4MB.
    Image dimensions must be between 40 x 40 and 3200 x 3200 pixels, and the image cannot be larger than 100 megapixels.

    */
    const body = {
        'url': 'https://nwrecruiter.azurewebsites.net/downloads/ResumeScreenShot.png'
    };

    computerVision.ocr({
            parameters,
            body
        })
        .then((response) => {
            console.log('Got response', response);
            var out = '';
            var regionsout = [];
            for(var r in response.regions) {
                var regionout = {};
                var region = response.regions[r];
                for(var l in region.lines) {
                    var lineout = {};
                    var line = region.lines[l];
                    for(var w in line.words) {
                        var word = line.words[w].text;
                        out += word + ' ';
                    }
                    out += '\n';
                }
                out += '\n';
            }
            out = out.toLowerCase();
            var matchedKeywords = [];
            for(var k in config.keywords) {
                var keyword = config.keywords[k].toLowerCase();
                if(out.includes(keyword)) {
                    matchedKeywords.push(keyword);
                }
            }
            res.status(200).send({OCR: out, matchedKeywords: matchedKeywords});

        })
        .catch((err) => {
            console.error('Encountered error making request:', err);
            res.status(500).send({message: e.message});
        });
};

exports.getFilesMatchingKeywords = function(req, res) {
    var keywords = req.body.keywords;
    console.log(req.body);
    console.log(keywords);
    res.json({message: 'Got keywords ' + keywords.join(',')});
};

exports.uploadFile = function(req, res) {
    console.log("req:");
    console.log(req);
    console.log("req.file:");
    console.log(req.file);
    console.log("req.body:");
    console.log(req.body);
    var upload = multer({ dest: './public/images/uploads' }).single('picture');
    uploadImage()
      .then(function () {
        var stream = fs.createReadStream('./public/images/uploads/' + req.file.filename);
        client.files.uploadFile('32442834639', req.file.filename, stream, function(err, response){
            if(err) {
                console.error(err);
                res.status(500).send(err);
            } else {
                console.log(response);
                res.json({message: "success"});
            }
        });
      })
      .catch(function (err) {
        res.status(500).send(err);
      });

    function uploadImage () {
        return new Promise(function (resolve, reject) {
            upload(req, res, function (uploadError) {
                if (uploadError) {
                    reject(uploadError);
                } else {
                    resolve();
                }
            });
        });
    }
};

<|endoftext|>


<commit_before>import lightingShader from './phong-lighting.glsl';

export default {
  name: 'lighting',
  vs: lightingShader,
  getUniforms
};

const INITIAL_MODULE_OPTIONS = {};

function getLightSourceUniforms({ambientLight, pointLights, directionalLights}) {
  const lightSourceUniforms = {};

  if (ambientLight) {
    lightSourceUniforms['lighting_uAmbientLight.color'] = ambientLight.color;
    lightSourceUniforms['lighting_uAmbientLight.intensity'] = ambientLight.intensity;
  } else {
    lightSourceUniforms['lighting_uAmbientLight.color'] = [0, 0, 0];
    lightSourceUniforms['lighting_uAmbientLight.intensity'] = 0.0;
  }

  let index = 0;
  for (const i in pointLights) {
    const pointLight = pointLights[i];
    lightSourceUniforms[`lighting_uPointLight[${index}].color`] = pointLight.color;
    lightSourceUniforms[`lighting_uPointLight[${index}].intensity`] = pointLight.intensity;
    lightSourceUniforms[`lighting_uPointLight[${index}].position`] = pointLight.position;
    index++;
  }
  lightSourceUniforms.lighting_uPointLightCount = pointLights.length;

  index = 0;
  for (const i in directionalLights) {
    const directionalLight = directionalLights[i];
    lightSourceUniforms[`lighting_uDirectionalLight[${index}].color`] = directionalLight.color;
    lightSourceUniforms[`lighting_uDirectionalLight[${index}].intensity`] =
      directionalLight.intensity;
    lightSourceUniforms[`lighting_uDirectionalLight[${index}].direction`] =
      directionalLight.direction;
    index++;
  }
  lightSourceUniforms.lighting_uDirectionalLightCount = directionalLights.length;

  return lightSourceUniforms;
}

function getMaterialUniforms(material) {
  const materialUniforms = {};
  materialUniforms.lighting_uAmbient = material.ambient;
  materialUniforms.lighting_uDiffuse = material.diffuse;
  materialUniforms.lighting_uShininess = material.shininess;
  materialUniforms.lighting_uSpecularColor = material.specularColor;
  return materialUniforms;
}

function getUniforms(opts = INITIAL_MODULE_OPTIONS) {
  if (
    !(
      'ambientLight' in opts ||
      'pointLights' in opts ||
      'directionalLights' in opts ||
      'material' in opts
    )
  ) {
    return {};
  }

  const {ambientLight, pointLights, directionalLights, material} = opts;
  const hasLights =
    ambientLight ||
    (pointLights && pointLights.length > 0) ||
    (directionalLights && directionalLights.length > 0);

  if (!hasLights || !material) {
    return {lighting_uEnabled: false};
  }

  const lightUniforms = Object.assign(
    {},
    getLightSourceUniforms({ambientLight, pointLights, directionalLights}),
    getMaterialUniforms(material),
    {lighting_uEnabled: true}
  );

  return lightUniforms;
}
<commit_msg>use "lightSources" in module parameters (#920)<commit_after>import lightingShader from './phong-lighting.glsl';

export default {
  name: 'lighting',
  vs: lightingShader,
  getUniforms
};

const INITIAL_MODULE_OPTIONS = {};

function getLightSourceUniforms({ambientLight, pointLights, directionalLights}) {
  const lightSourceUniforms = {};

  if (ambientLight) {
    lightSourceUniforms['lighting_uAmbientLight.color'] = ambientLight.color;
    lightSourceUniforms['lighting_uAmbientLight.intensity'] = ambientLight.intensity;
  } else {
    lightSourceUniforms['lighting_uAmbientLight.color'] = [0, 0, 0];
    lightSourceUniforms['lighting_uAmbientLight.intensity'] = 0.0;
  }

  let index = 0;
  for (const i in pointLights) {
    const pointLight = pointLights[i];
    lightSourceUniforms[`lighting_uPointLight[${index}].color`] = pointLight.color;
    lightSourceUniforms[`lighting_uPointLight[${index}].intensity`] = pointLight.intensity;
    lightSourceUniforms[`lighting_uPointLight[${index}].position`] = pointLight.position;
    index++;
  }
  lightSourceUniforms.lighting_uPointLightCount = pointLights.length;

  index = 0;
  for (const i in directionalLights) {
    const directionalLight = directionalLights[i];
    lightSourceUniforms[`lighting_uDirectionalLight[${index}].color`] = directionalLight.color;
    lightSourceUniforms[`lighting_uDirectionalLight[${index}].intensity`] =
      directionalLight.intensity;
    lightSourceUniforms[`lighting_uDirectionalLight[${index}].direction`] =
      directionalLight.direction;
    index++;
  }
  lightSourceUniforms.lighting_uDirectionalLightCount = directionalLights.length;

  return lightSourceUniforms;
}

function getMaterialUniforms(material) {
  const materialUniforms = {};
  materialUniforms.lighting_uAmbient = material.ambient;
  materialUniforms.lighting_uDiffuse = material.diffuse;
  materialUniforms.lighting_uShininess = material.shininess;
  materialUniforms.lighting_uSpecularColor = material.specularColor;
  return materialUniforms;
}

function getUniforms(opts = INITIAL_MODULE_OPTIONS) {
  if (
    !(
      'lightSources' in opts &&
      'material' in opts
    )
  ) {
    return {};
  }

  const {ambientLight, pointLights, directionalLights} = opts.lightSources;
  const {material} = opts;
  const hasLights =
    ambientLight ||
    (pointLights && pointLights.length > 0) ||
    (directionalLights && directionalLights.length > 0);

  if (!hasLights || !material) {
    return {lighting_uEnabled: false};
  }

  const lightUniforms = Object.assign(
    {},
    getLightSourceUniforms({ambientLight, pointLights, directionalLights}),
    getMaterialUniforms(material),
    {lighting_uEnabled: true}
  );

  return lightUniforms;
}
<|endoftext|>


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

var net = require('net');

// From: http://stackoverflow.com/questions/8125507/how-can-i-send-and-receive-websocket-messages-on-the-server-side
function decodeWebSocket (data){
    var datalength = data[1] & 127;
    var indexFirstMask = 2;
    if (datalength == 126) {
        indexFirstMask = 4;
    } else if (datalength == 127) {
        indexFirstMask = 10;
    }
    var masks = data.slice(indexFirstMask,indexFirstMask + 4);
    var i = indexFirstMask + 4;
    var index = 0;
    var output = "";
    while (i < data.length) {
        output += String.fromCharCode(data[i++] ^ masks[index++ % 4]);
    }
    return output;
}

var server = net.createServer(function(socket) {

	var client = new net.Socket();
	client.connect(13001, '172.27.225.89', function() {
	});

	client.on('data', function(data) {
		console.log('<' + (""+data).substring(2));
		socket.write(data);
	});

	client.on('close', function() {
		socket.end();
	});

	socket.on('data', function(data) {
		console.log('>' + (((""+data).charCodeAt(0) == 0xFFFD) ? decodeWebSocket(data) : data));
		client.write(data);
	});

	socket.on('close', function() {
		client.end();
	});
});

server.listen(12345, 'localhost');
<commit_msg>websocket-proxy.js: Added command line arguments<commit_after>#!/usr/bin/env node

var net = require('net');

// From: http://stackoverflow.com/questions/8125507/how-can-i-send-and-receive-websocket-messages-on-the-server-side
function decodeWebSocket (data){
    var datalength = data[1] & 127;
    var indexFirstMask = 2;
    if (datalength == 126) {
        indexFirstMask = 4;
    } else if (datalength == 127) {
        indexFirstMask = 10;
    }
    var masks = data.slice(indexFirstMask,indexFirstMask + 4);
    var i = indexFirstMask + 4;
    var index = 0;
    var output = "";
    while (i < data.length) {
        output += String.fromCharCode(data[i++] ^ masks[index++ % 4]);
    }
    return output;
}

var argv = process.argv.slice(2);
if(argv.length === 3) {

	var localPort = argv[0];
	var remoteHost = argv[1];
	var remotePort = argv[2];

	var server = net.createServer(function(socket) {

		var client = new net.Socket();
		client.connect(remotePort, remoteHost, function() {
		});

		client.on('data', function(data) {
			console.log('<' + (""+data).substring(2));
			socket.write(data);
		});

		client.on('close', function() {
			socket.end();
		});

		socket.on('data', function(data) {
			console.log('>' + (((""+data).charCodeAt(0) == 0xFFFD) ? decodeWebSocket(data) : data));
			client.write(data);
		});

		socket.on('close', function() {
			client.end();
		});
	});

	server.listen(localPort, 'localhost');

	console.log("-=- Websocket Proxy -=-");
	console.log("local port: ", localPort);
	console.log("remote host: ", remoteHost);
	console.log("remote port: ", remotePort);

} else {
	console.log("Usage: ./websocket-proxy <local-port> <remote-host> <remote-port>");
}
<|endoftext|>


<commit_before>// AJAX for POSTing

console.log("hello2");

$(document).ready(function(){
	// Retrieve email from browser's session storage
	var local_email = sessionStorage.getItem("Email_ls");
	if (local_email == null){
		alert('Invalid email or password!');
		window.location = "test.html";

	}
	console.log(local_email);
	$("input#Email").val(local_email);
	console.log("inside");

	// 	'
' +
	// 		'' + alert_msg + '' +
	// 	'
'
	// );

	$("form#login_form").submit(function(event){
		console.log("Hello World2!");
		var passphrase = $("input#Passphrase").val();
		console.log(local_email + passphrase);
		event.preventDefault();
		console.log("Was preventDefault() called: " + event.isDefaultPrevented());

		$.ajax ({
			url	: "http://127.0.0.1:5000/testajax2",
			// url	: "/login1",
			type: "POST",
			data: { 'Email' : local_email,
					'Passphrase': passphrase
			},
			contentType: "application/x-www-form-urlencoded; charset=UTF-8",
			crossOrigin: true,
			success : 	function(response, textStatus, jqXHR) {
							alert_msg = "Success";
							console.log("Success: " + jqXHR.responseText + ' ' + jqXHR.status );
							var email = JSON.parse(jqXHR.responseText)['email'];
							console.log("email = " + email);
							document.write(response);

							window.location = "viewer.html"

							// top.location.href = 'https://155.69.145.226/login1'
							// $("#alert").html(
							// 	'
' +
							// 		'' + alert_msg + '' +
							// 	'
'
							// );
						},

			error 	:	function(jqXHR, textStatus, errorThrown) {
							alert_msg = "Incorrect email or password!";
							console.log("error: " + jqXHR.status + " " + textStatus + ' ' + jqXHR.responseText + ' ' + errorThrown);
							$("#alert").html(
								'
' +
									''+ alert_msg +'' +
								'
'
							);
						}

		}); //Ajax
		// $("#login_form")[0].reset();
	}); //submit
});
<commit_msg>Plugin: Adding support for reading response messages from server<commit_after>// AJAX for POSTing

console.log("hello2");

$(document).ready(function(){
	// Retrieve email from browser's session storage
	var local_email = sessionStorage.getItem("Email_ls");
	if (local_email == null){
		alert('Invalid email or password!');
		window.location = "test.html";

	}
	console.log(local_email);
	$("input#Email").val(local_email);
	console.log("inside");

	// 	'
' +
	// 		'' + alert_msg + '' +
	// 	'
'
	// );

	$("form#login_form").submit(function(event){
		console.log("Hello World2!");
		var passphrase = $("input#Passphrase").val();
		console.log(local_email + passphrase);
		event.preventDefault();
		console.log("Was preventDefault() called: " + event.isDefaultPrevented());

		$.ajax ({
			url	: "http://127.0.0.1:5000/testajax2",
			// url	: "/login1",
			type: "POST",
			data: { 'Email' : local_email,
					'Passphrase': passphrase
			},
			contentType: "application/x-www-form-urlencoded; charset=UTF-8",
			crossOrigin: true,
			success : 	function(response, textStatus, jqXHR) {
							alert_msg = "Success";
							console.log("Success: " + jqXHR.responseText + ' ' + jqXHR.status );
							var status = JSON.parse(jqXHR.responseText)['status'];
							if (status == "OK"){
								console.log("Status: " + status);
								var email = JSON.parse(jqXHR.responseText)['email'];
								console.log("email = " + email);
								document.write(response);
								window.location = "viewer.html"
							}

							console.log("Error!");
							window.location = "test.html"

							// top.location.href = 'https://155.69.145.226/login1'
							// $("#alert").html(
							// 	'
' +
							// 		'' + alert_msg + '' +
							// 	'
'
							// );
						},

			error 	:	function(jqXHR, textStatus, errorThrown) {
							alert_msg = "Incorrect email or password!";
							console.log("error: " + jqXHR.status + " " + textStatus + ' ' + jqXHR.responseText + ' ' + errorThrown);
							$("#alert").html(
								'
' +
									''+ alert_msg +'' +
								'
'
							);
						}

		}); //Ajax
		// $("#login_form")[0].reset();
	}); //submit
});
<|endoftext|>


<commit_before>class Words {
  count(str) {
    const result = {};
    if (!str || str.trim().length === 0) {
      return result;
    }

    const words = str.trim().replace(/\n/g, ' ').replace(/\r/g, ' ').replace(/\t/g, ' ').toLowerCase().split(' ').filter(elem => elem !== ' ');
    words.forEach((word) => {
      if (result[word]) {
        result[word] = result[word] + 1;
      } else {
        result[word] = 1;
      }
    });
    return result;
  }
}

export default Words;
<commit_msg>Fixed the implementation<commit_after>class Words {
  count(str) {
    const result = {};
    if (!str || str.trim().length === 0) {
      return result;
    }

    const words = str.trim().toLowerCase().split(/\s+/g);
    words.forEach(word => result[word] = (result.hasOwnProperty(word) ? result[word] : 0) + 1);
    return result;
  }
}

export default Words;
<|endoftext|>


<commit_before>define(function (require) {

    'use strict';

    var _        = require('underscore');
    var Backbone = require('backbone');

    var Vector2 = require('common/math/vector2');

    /**
     * This is the main class for the CCK model, providing a representation of all
     *   the branches and junctions, and a way of updating the physics.
     */
    var Circuit = Backbone.Model.extend({

        defaults: {

        },

        initialize: function(attributes, options) {
            this.branches  = new Backbone.Collection();
            this.junctions = new Backbone.Collection();

            // Solution from last update, used to look up dynamic circuit properties.
            this.solution = null;

            // Cached objects
            this._splitVec = new Vector2();
            this._splitDesiredDest = new Vector2();
            this._splitDestination = new Vector2();

            this.listenTo(this.branches,  'add remove reset', this.circuitChanged);
            this.listenTo(this.junctions, 'add remove reset', this.circuitChanged);
        },

        addJunction: function(junction) {
            if (!this.junctions.contains(junction))
                junctions.add(junction);
        },

        removeJunction: function(junction) {
            this.junctions.remove(junction);
            this.junction.destroy();
        },

        getAdjacentBranches: function(junction) {
            var branches = [];
            for (var i = 0; i < this.branches.length; i++) {
                if (this.branches.at(i).hasJunction(junction))
                    branches.push(this.branches.at(i));
            }
            return branches;
        },

        hasBranch: function(a, b) {
            for (var i = 0; i < this.branches.length; i++) {
                if (this.branches.at(i).hasJunction(a) && this.branches.at(i).hasJunction(b))
                    return true;
            }
            return false;
        },

        getJunctionNeighbors: function(junction) {
            var neighbors = [];
            for (var i = 0; i < this.branches.length; i++) {
                if (this.branches.at(i).hasJunction(junction))
                    neighbors.push(this.branches.at(i).opposite(junction));
            }
            return neighbors;
        },

        replaceJunction: function(oldJunction, newJunction) {
            for (var i = 0; i < this.branches.length; i++) {
                if (this.branches.at(i).get('startJunction') === oldJunction)
                    this.branches.at(i).set('startJunction', newJunction);
                if (this.branches.at(i).get('endJunction') === oldJunction)
                    this.branches.at(i).set('endJunction', newJunction);
            }
        },

        addBranch: function(component) {
            if (!component)
                throw 'Null component added to circuit.';

            this.branches.add(component);

            this.addJunction(component.get('startJunction'));
            this.addJunction(component.get('endJunction'));
        },

        getBranchNeighbors: function(branch) {
            var n0 = this.getAdjacentBranches(branch.get('startJunction'));
            var n1 = this.getAdjacentBranches(branch.get('endJunction'));
            var neighbors = [];
            var i;
            for (i = 0; i < n0.length; i++) {
                if (n0[i] !== branch)
                    neighbors.push(n0[i]);
            }
            for (i = 0; i < n1.length; i++) {
                if (n1[i] !== branch)
                    neighbors.push(n1[i]);
            }

            return neighbors;
        },

        setSolution: function(solution) {
            this.solution = solution;
        },

        split: function(junction) {
            // Get the set of all branches that are connected at this junction.
            var adjacentBranches = this.getAdjacentBranches(junction);

            var newJunctions = [];
            for (var i = 0; i < adjacentBranches.length; i++) {
                var branch = adjacentBranches[i];
                var opposite = branch.opposite(junction);

                var vec = this._splitVec
                    .set(junction.get('position'))
                    .sub(opposite.get('position'));
                var curLength = vec.length();
                var newLength = Math.abs(curLength - Constants.JUNCTION_RADIUS * 1.5);
                vec.normalize().scale(newLength);

                var desiredDest = this._splitDesiredDest.set(opposite.get('position')).add(vec);
                var destination = this._splitDestination.set(desiredDest);
                if (branch instanceof CircuitComponent)
                    destination.set(junction.get('position'));

                var newJunction = new Junction(destination.x, destination.y);
                branch.replaceJunction(junction, newJunction);
                this.addJunction(newJunction);
                newJunctions.push(newJunction);

                if (branch instanceof CircuitComponent) {
                    var translation = this._splitTranslation
                        .set(desiredDest)
                        .sub(junction.get('position'));
                    var stronglyConnected = this.getStrongConnections(newJunction);
                    var bs = new BranchSet(this, stronglyConnected);
                    bs.translate(translation);
                }
            }

            // Remove what used to be the junction
            this.removeJunction(junction);

            // Trigger the junctions-split event
            this.trigger('junctions-split', junction, newJunctions);

            return newJunctions;
        },

        getStrongConnections: function(junction, wrongDir) {
            var visited = [];

            if (wrongDir)
                visited.push(wrongDir);

            this._getStrongConnections(visited, junction);

            if (wrongDir)
                visited.slice(visited.indexOf(wrongDir, 1));

            return visited;
        },

        _getStrongConnections: function(visited, junction) {
            var adjacentBranches = this.getAdjacentBranches(junction);
            for (var i = 0; i < adjacentBranches.length; i++) {
                var branch = adjacentBranches[i];
                var opposite = branch.opposite(junction);
                if (visited.indexOf(branch) === -1) {
                    if (branch instanceof CircuitComponent) {
                        visited.push(branch);
                        this._getStrongConnections(visited, opposite);
                    }//Wires end the connectivity.
                }
            }
        },

        getConnectedSubgraph: function(junction) {
            var visited = [];
            this._getConnectedSubgraph(visited, junction);
            return visited;;
        },

        _getConnectedSubgraph: function(visited, junction) {
            var adj = this.getAdjacentBranches(junction);
            for (var i = 0; i < adj.length; i++) {
                var branch = adj[i];
                if (branch instanceof Switch && !branch.isClosed()) {
                    // Skip this one.
                }
                else {
                    var opposite = branch.opposite(junction);
                    if (visited.indexOf(branch) === -1) {
                        visited.push(branch);
                        this._getConnectedSubgraph(visited, opposite);
                    }
                }
            }
        },

        removeBranch: function(branch) {
            branches.remove(branch);

            this.removeIfOrphaned(branch.get('startJunction'));
            this.removeIfOrphaned(branch.get('endJunction'));

            branch.destroy();
        },

        removeIfOrphaned: function(junction) {
            if (this.getAdjacentBranches(junction).length === 0)
                this.removeJunction(junction);
        },

        translate: function(components, translation) {
            for (var i = 0; i < components.length; i++)
                components[i].translate(translation);
        },

        getJunctions: function() {
            return this.junctions;
        },

        getJunctions: function(branches) {
            var list = [];
            for (var i = 0; i < branches.length; i++) {
                var branch = branches[i];
                if (list.indexOf(branch.get('startJunction') === -1)
                    list.push(branch.get('startJunction'));
                if (list.indexOf(branch.get('endJunction') === -1)
                    list.push(branch.get('endJunction'));
            }
            return list;
        },

        /**
         * Gets voltage between two connections.
         */
        getVoltage: function(a, b) {
            if (a.equals(b) || !this.getSameComponent(a.getJunction(), b.getJunction())) {
                return 0;
            }
            else {
                var va = a.getVoltageAddon();
                var vb = -b.getVoltageAddon();//this has to be negative, because on the path VA->A->B->VB, the the VB computation is VB to B.
                //used for displaying values e.g. in voltmeter and charts, so use average node voltages instead of instantaneous, see #2270
                var avgVoltageA = solution.getAverageNodeVoltage(this.junctions.indexOf(a.getJunction()));
                var avgVoltageB = solution.getAverageNodeVoltage(this.junctions.indexOf(b.getJunction()));
                var junctionAnswer = avgVoltageB - avgVoltageA;
                return junctionAnswer + va + vb;
            }
        },

        getSameComponent: function(a, b) {
            var branches = this.getConnectedSubgraph(a);
            for (var i = 0; i < branches.length; i++) {
                if (branches[i].hasJunction(b))
                    return true;
            }
            return false;
        },

        isDynamic: function() {
            for (var i = 0; i < this.branches.length; i++) {
                if (this.branches.at(i) instanceof DynamicBranch)
                    return true;
            }
            return false;
        },

        update: function(time, deltaTime) {
            for (var i = 0; i < this.branches.length; i++) {
                if (this.branches.at(i) instanceof DynamicBranch)
                    this.branches.at(i).update(time, deltaTime);
            }
        },

        resetDynamics: function() {
            for (var i = 0; i < this.branches.length; i++) {
                if (this.branches.at(i) instanceof DynamicBranch)
                    this.branches.at(i).resetDynamics();
            }
        },

        setTime: function(time) {
            for (var i = 0; i < this.branches.length; i++) {
                if (this.branches.at(i) instanceof DynamicBranch)
                    this.branches.at(i).setTime(time);
            }
        },

        circuitChanged: function() {
            this.trigger('circuit-changed');
        }

    });

    return Circuit;
});<commit_msg>Finished the Circuit class implementation.<commit_after>define(function (require) {

    'use strict';

    var _        = require('underscore');
    var Backbone = require('backbone');

    var Vector2   = require('common/math/vector2');
    var Rectangle = require('common/math/rectangle');

    /**
     * This is the main class for the CCK model, providing a representation of all
     *   the branches and junctions, and a way of updating the physics.
     */
    var Circuit = Backbone.Model.extend({

        defaults: {

        },

        initialize: function(attributes, options) {
            this.branches  = new Backbone.Collection();
            this.junctions = new Backbone.Collection();

            // Solution from last update, used to look up dynamic circuit properties.
            this.solution = null;

            // Cached objects
            this._splitVec = new Vector2();
            this._splitDesiredDest = new Vector2();
            this._splitDestination = new Vector2();
            this._bestDragMatchVec = new Vector2();
            this._dragMatchObj = {};
            this._getBranchRect = new Rectangle();

            this.listenTo(this.branches,  'add remove reset', this.circuitChanged);
            this.listenTo(this.junctions, 'add remove reset', this.circuitChanged);
        },

        addJunction: function(junction) {
            if (!this.junctions.contains(junction))
                junctions.add(junction);
        },

        removeJunction: function(junction) {
            this.junctions.remove(junction);
            this.junction.destroy();
            this.fireKirkhoffChanged();
        },

        getAdjacentBranches: function(junction) {
            var branches = [];
            for (var i = 0; i < this.branches.length; i++) {
                if (this.branches.at(i).hasJunction(junction))
                    branches.push(this.branches.at(i));
            }
            return branches;
        },

        hasBranch: function(a, b) {
            for (var i = 0; i < this.branches.length; i++) {
                if (this.branches.at(i).hasJunction(a) && this.branches.at(i).hasJunction(b))
                    return true;
            }
            return false;
        },

        getJunctionNeighbors: function(junction) {
            var neighbors = [];
            for (var i = 0; i < this.branches.length; i++) {
                if (this.branches.at(i).hasJunction(junction))
                    neighbors.push(this.branches.at(i).opposite(junction));
            }
            return neighbors;
        },

        replaceJunction: function(oldJunction, newJunction) {
            for (var i = 0; i < this.branches.length; i++) {
                if (this.branches.at(i).get('startJunction') === oldJunction)
                    this.branches.at(i).set('startJunction', newJunction);
                if (this.branches.at(i).get('endJunction') === oldJunction)
                    this.branches.at(i).set('endJunction', newJunction);
            }
        },

        addBranch: function(component) {
            if (!component)
                throw 'Null component added to circuit.';

            this.branches.add(component);

            this.addJunction(component.get('startJunction'));
            this.addJunction(component.get('endJunction'));
        },

        getBranchNeighbors: function(branch) {
            var n0 = this.getAdjacentBranches(branch.get('startJunction'));
            var n1 = this.getAdjacentBranches(branch.get('endJunction'));
            var neighbors = [];
            var i;
            for (i = 0; i < n0.length; i++) {
                if (n0[i] !== branch)
                    neighbors.push(n0[i]);
            }
            for (i = 0; i < n1.length; i++) {
                if (n1[i] !== branch)
                    neighbors.push(n1[i]);
            }

            return neighbors;
        },

        setSolution: function(solution) {
            this.solution = solution;
        },

        split: function(junction) {
            // Get the set of all branches that are connected at this junction.
            var adjacentBranches = this.getAdjacentBranches(junction);

            var newJunctions = [];
            for (var i = 0; i < adjacentBranches.length; i++) {
                var branch = adjacentBranches[i];
                var opposite = branch.opposite(junction);

                var vec = this._splitVec
                    .set(junction.get('position'))
                    .sub(opposite.get('position'));
                var curLength = vec.length();
                var newLength = Math.abs(curLength - Constants.JUNCTION_RADIUS * 1.5);
                vec.normalize().scale(newLength);

                var desiredDest = this._splitDesiredDest.set(opposite.get('position')).add(vec);
                var destination = this._splitDestination.set(desiredDest);
                if (branch instanceof CircuitComponent)
                    destination.set(junction.get('position'));

                var newJunction = new Junction(destination.x, destination.y);
                branch.replaceJunction(junction, newJunction);
                this.addJunction(newJunction);
                newJunctions.push(newJunction);

                if (branch instanceof CircuitComponent) {
                    var translation = this._splitTranslation
                        .set(desiredDest)
                        .sub(junction.get('position'));
                    var stronglyConnected = this.getStrongConnections(newJunction);
                    var bs = new BranchSet(this, stronglyConnected);
                    bs.translate(translation);
                }
            }

            // Remove what used to be the junction
            this.removeJunction(junction);

            // Trigger the junctions-split event
            this.trigger('junctions-split', junction, newJunctions);

            return newJunctions;
        },

        getStrongConnections: function(junction, wrongDir) {
            var visited = [];

            if (wrongDir)
                visited.push(wrongDir);

            this._getStrongConnections(visited, junction);

            if (wrongDir)
                visited.slice(visited.indexOf(wrongDir, 1));

            return visited;
        },

        _getStrongConnections: function(visited, junction) {
            var adjacentBranches = this.getAdjacentBranches(junction);
            for (var i = 0; i < adjacentBranches.length; i++) {
                var branch = adjacentBranches[i];
                var opposite = branch.opposite(junction);
                if (visited.indexOf(branch) === -1) {
                    if (branch instanceof CircuitComponent) {
                        visited.push(branch);
                        this._getStrongConnections(visited, opposite);
                    }//Wires end the connectivity.
                }
            }
        },

        getConnectedSubgraph: function(junction) {
            var visited = [];
            this._getConnectedSubgraph(visited, junction);
            return visited;;
        },

        _getConnectedSubgraph: function(visited, junction) {
            var adj = this.getAdjacentBranches(junction);
            for (var i = 0; i < adj.length; i++) {
                var branch = adj[i];
                if (branch instanceof Switch && !branch.isClosed()) {
                    // Skip this one.
                }
                else {
                    var opposite = branch.opposite(junction);
                    if (visited.indexOf(branch) === -1) {
                        visited.push(branch);
                        this._getConnectedSubgraph(visited, opposite);
                    }
                }
            }
        },

        removeBranch: function(branch) {
            branches.remove(branch);

            this.removeIfOrphaned(branch.get('startJunction'));
            this.removeIfOrphaned(branch.get('endJunction'));

            branch.destroy();
        },

        removeIfOrphaned: function(junction) {
            if (this.getAdjacentBranches(junction).length === 0)
                this.removeJunction(junction);
        },

        translate: function(components, translation) {
            for (var i = 0; i < components.length; i++)
                components[i].translate(translation);
        },

        getJunctions: function() {
            return this.junctions;
        },

        getJunctions: function(branches) {
            var list = [];
            for (var i = 0; i < branches.length; i++) {
                var branch = branches[i];
                if (list.indexOf(branch.get('startJunction') === -1)
                    list.push(branch.get('startJunction'));
                if (list.indexOf(branch.get('endJunction') === -1)
                    list.push(branch.get('endJunction'));
            }
            return list;
        },

        /**
         * Gets voltage between two connections.
         */
        getVoltage: function(a, b) {
            if (a.equals(b) || !this.getSameComponent(a.getJunction(), b.getJunction())) {
                return 0;
            }
            else {
                var va = a.getVoltageAddon();
                var vb = -b.getVoltageAddon();//this has to be negative, because on the path VA->A->B->VB, the the VB computation is VB to B.
                //used for displaying values e.g. in voltmeter and charts, so use average node voltages instead of instantaneous, see #2270
                var avgVoltageA = solution.getAverageNodeVoltage(this.junctions.indexOf(a.getJunction()));
                var avgVoltageB = solution.getAverageNodeVoltage(this.junctions.indexOf(b.getJunction()));
                var junctionAnswer = avgVoltageB - avgVoltageA;
                return junctionAnswer + va + vb;
            }
        },

        getSameComponent: function(a, b) {
            var branches = this.getConnectedSubgraph(a);
            for (var i = 0; i < branches.length; i++) {
                if (branches[i].hasJunction(b))
                    return true;
            }
            return false;
        },

        setSelection: function(branch) {
            this.clearSelection();
            branch.select();
            this.fireSelectionChanged();
        },

        setSelection: function( Junction junction ) {
            this.clearSelection();
            junction.select();
            this.fireSelectionChanged();
        },

        fireSelectionChanged: function() {
            this.trigger('selection-changed');
        },

        clearSelection: function() {
            var i;
            for (i = 0; i < this.branches.length; i++)
                this.branches.at(i).deselect();
            for (i = 0; i < this.junctions.length; i++)
                this.junctions.at(i).deselect();
            this.fireSelectionChanged();
        },

        getSelectedBranches: function() {
            var sel = [];
            for (i = 0; i < this.branches.length; i++) {
                if (this.branches.at(i).get('selected'))
                    sel.push(this.branches.at(i));
            }
            return sel;
        },

        getSelectedJunctions: function() {
            var sel = [];
            for (i = 0; i < this.junctions.length; i++) {
                if (this.junctions.at(i).get('selected'))
                    sel.push(this.junctions.at(i));
            }
            return sel;
        },

        selectAll: function() {
            var i;
            for (i = 0; i < this.branches.length; i++)
                this.branches.at(i).select();
            for (i = 0; i < this.junctions.length; i++)
                this.junctions.at(i).select();
        },

        isDynamic: function() {
            for (var i = 0; i < this.branches.length; i++) {
                if (this.branches.at(i) instanceof DynamicBranch)
                    return true;
            }
            return false;
        },

        update: function(time, deltaTime) {
            for (var i = 0; i < this.branches.length; i++) {
                if (this.branches.at(i) instanceof DynamicBranch)
                    this.branches.at(i).update(time, deltaTime);
            }
        },

        resetDynamics: function() {
            for (var i = 0; i < this.branches.length; i++) {
                if (this.branches.at(i) instanceof DynamicBranch)
                    this.branches.at(i).resetDynamics();
            }
        },

        setTime: function(time) {
            for (var i = 0; i < this.branches.length; i++) {
                if (this.branches.at(i) instanceof DynamicBranch)
                    this.branches.at(i).setTime(time);
            }
        },

        setState: function(newCircuit) {
            this.clear();
            newCircuit.junctions.each(this.addJunction, this);
            newCircuit.branches.each(this.addBranch, this);
        },

        clear: function() {
            while (this.branches.length > 0)
                this.removeBranch(this.branches.first());
            while (this.junctions.length > 0)
                this.removeJunction(this.junctions.first());
        },

        wouldConnectionCauseOverlappingBranches: function(a, b) {
            var neighborsOfA = this.getNeighbors(a);
            var neighborsOfB = this.getNeighbors(b);
            for (var i = 0; i < neighborsOfA.length; i++) {
                for (var j = 0; j < neighborsOfB.length; j++) {
                    if (neighborsOfA[i] === neighborsOfB[j])
                        return true;
                }
            }
            return false;
        },

        collapseJunctions: function(j1, j2) {
            if (!j1.get('position').equals(j2.get('position')))
                throw 'Junctions not at same coordinates.';

            this.removeJunction(j1);
            this.removeJunction(j2);
            var replacement = new Junction({ position: new Vector2(j1.get('position').x, j1.get('position').y) });
            this.addJunction(replacement);
            this.replaceJunction(j1, replacement);
            this.replaceJunction(j2, replacement);

            // Fire notification events so that any listeners are informed.
            this.fireKirkhoffChanged();
            this.trigger('junctions-collapsed', j1, j2, replacement);
        },

        getBestDragMatch: function(draggedJunctions, dx) {
            // If draggedJunctions is actually an array of branches, interpret them as strong connections
            if (draggedJunctions.length && draggedJunctions[0] instanceof Branch)
                draggedJunctions = Circuit.getJunctions(draggedJunctions);

            var all = this.getJunctions();
            var potentialMatches = _.difference(all, draggedJunctions);

            // Make internal nodes ungrabbable for black box, see https://phet.unfuddle.com/a#/projects/9404/tickets/by_number/3602
            for (var i = 0; i < all.length; i++) {
                if (all[i].fixed && this.getAdjacentBranches(all[i]) > 1) {
                    var junctionIndex = potentialMatches.indexOf(all[i]);
                    if (junctionIndex !== -1)
                        potentialMatches.slice(junctionIndex, 1);
                }
            }

            // Now we have all the junctions that are moving,
            // And all the junctions that aren't moving, so we can look for a best match.
            var best = null;
            var draggedJunction;
            var loc = this._bestDragMatchVec;
            var source;
            var target;
            var distance;

            for (var j = 0; j < draggedJunctions.length; j++) {
                draggedJunction = draggedJunctions[j];
                loc.set(draggedJunction.get('position')).add(dx);
                var bestForJunction = this._getBestDragMatch(draggedJunction, loc, potentialMatches);
                if (bestForJunction) {
                    source = draggedJunction;
                    target = bestForJunction;
                    distance = source.getDistance(target);
                    if (best == null || distance < best.distance) {
                        best = this._dragMatchObj;
                        best.source = source;
                        best.target = target;
                        best.distance = distance;
                    }
                }
            }
            return best;
        },

        _getBestDragMatch: function(dragging, loc, targets) {
            var strong = this.getStrongConnections( dragging );
            var closestJunction = null;
            var closestValue = Number.POSITIVE_INFINITY;

            for (var i = 0; i < targets.length; i++) {
                var target = targets[i];
                var dist = loc.distance(target.get('position'));
                if (target !== dragging && !this.hasBranch(dragging, target) && !this.wouldConnectionCauseOverlappingBranches(dragging, target)) {
                    if (closestJunction === null || dist < closestValue) {
                        var legal = !this.contains(strong, target);
                        var STICKY_THRESHOLD = 1;
                        if (dist <= STICKY_THRESHOLD && legal) {
                            closestValue = dist;
                            closestJunction = target;
                        }
                    }
                }
            }

            return closestJunction;
        },

        removedUnusedJunctions: function(junctions) {
            var out = this.getAdjacentBranches(junctions);
            if (out.length === 0)
                this.removeJunction(junctions);
        },

        deleteSelectedBranches: function() {
            for (var i = 0; i < this.branches.length; i++) {
                var branch = this.branches.at(i);
                if (branch.get('selected')) {
                    this.removeBranch(branch);
                    i--;
                }
            }
        },

        contains: function(strong, j) {
            for (var i = 0; i < this.branches.length; i++) {
                if (this.branches.at(i).hasJunction(j))
                    return true;
            }
            return false;
        },

        getConnection: function(tipShape) {
            throw 'not yet implemented';
        },

        getBranch: function(point) {
            return this.detectBranch(this._getBranchRect.set(point.x, point.y, 0.001, 0.001));
        },

        detectBranch: function(shape) {
            throw 'not yet implemented';
        },

        getWires: function() {
            var list = [];
            for (var i = 0; i < this.branches.length; i++) {
                if (this.branches.at(i) instanceof Wire)
                    list.push(this.branches.at(i));
            }
            return list;
        },

        detectJunction: function(tipShape) {
            throw 'not yet implemented';
        },

        bumpAway: function(junction) {
            for (var i = 0; i < 2; i++)
                this.bumpOnce(junction);
        },

        bumpOnce: function(junction) {
            var branches = this.getBranches();
            var strongConnections = this.getStrongConnections(junction);
            for (var i = 0; i < branches.length; i++) {
                var branch = branches[i];
                if (!branch.hasJunction(junction)) {
                    if (branch.getShape().intersects(junction.getShape())) {
                        var vec = branch.getDirectionVector();
                        vec.set(vec.y, -vec.x); // Make it perpendicular to the original
                        vec.normalize().scale(junction.getShape().w);
                        var bs = new BranchSet(this, strongConnections);
                        bs.addJunction(junction);
                        bs.translate(vec);
                        break;
                    }
                }
            }
        },

        fireKirkhoffChanged: function() {
            this.trigger('kirkhoff-changed');
        },

        circuitChanged: function() {
            this.trigger('circuit-changed');
        }

    });

    return Circuit;
});<|endoftext|>


<commit_before>import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import {connect} from 'react-redux'
import logo from '../../../public/assets/logo/ukmhub.png'
import '../../../public/assets/js/login'
import '../../../public/assets/js/bootstrap-notify.js'
import {registerCompanyFetch, loginCompanyFetch} from '../../actions/index.js'
import $ from 'jquery'

let loginInfo = {
  showRegisterInvalid: function (from, align) {
    $.notify({
      icon: 'pe-7s-delete-user',
      message: '
Please input valid email
'

    }, {
      type: 'danger',
      timer: 4000,
      placement: {
        from: from,
        align: align
      }
    })
  },
  showPasswordInvalid: function (from, align) {
    $.notify({
      icon: 'pe-7s-delete-user',
      message: '
Password must be more than 5 character
'
    }, {
      type: 'danger',
      timer: 4000,
      placement: {
        from: from,
        align: align
      }
    })
  },
  showErrorLogin: function (from, align) {
    $.notify({
      icon: 'pe-7s-delete-user',
      message: '
Invalid email/password
'
    }, {
      type: 'danger',
      timer: 4000,
      placement: {
        from: from,
        align: align
      }
    })
  }
}

const emailRegex = /\S+@\S+\.\S+/

class Login extends Component {
  constructor(){
    super()
    this.state = {
      formTitle: 'Login Form',
      emailRegister:'',
      passwordRegister:'',
      emailLogin:'',
      passwordLogin:'',
      forgetPassword:''
    }
  }

  registerClick(){
    $('form').animate({height: "toggle", opacity: "toggle"}, "slow");
    $('#form_id').attr( "style", "max-width: 700px;" );
    this.setState({formTitle: 'Register Form'})
  }

  loginClick(){
    $('form').animate({height: "toggle", opacity: "toggle"}, "slow");
    $('#form_id').attr( "style", "max-width: 400px;" );
  }

  handleRegister(e){
    if(!emailRegex.test(this.state.emailRegister)){
      e.preventDefault()
      loginInfo.showRegisterInvalid('top','center')
    } else if(this.state.passwordRegister.length <= 5){
      e.preventDefault()
      loginInfo.showPasswordInvalid('top','center')
    } else {
      this.props.registerCompanyFetch(this.state.emailRegister,this.state.passwordRegister)
      this.setState({
        emailRegister: '',
        passwordRegister: ''
      })
      setTimeout(function(){
        location.reload()
      }, 1000)
    }
  }

  handleLogin(e){
    e.preventDefault()
    this.props.loginCompanyFetch(this.state.emailLogin,this.state.passwordLogin)
    this.setState({
      emailLogin: '',
      passwordLogin: ''
    })
    setTimeout(function(){
      if(!localStorage.getItem('token')){
        loginInfo.showErrorLogin('top','center')
      } else {
        location.reload()
      }
    },500)
  }

  handleForgetPassword(e){
    e.preventDefault()
    fetch('http://ukmhub-api-prod.ap-southeast-1.elasticbeanstalk.com/api/company/resetPassword', {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({
        email: this.state.forgetPassword
      })
    })
    .then(res => console.log(res))
  }

  handleChange(e){
    let newState = {}
    newState[e.target.name] = e.target.value
    this.setState(newState)
  }

  render () {
    const buttonTextStyle = {
      fontSize: 16
    }
    return (

{this.state.formTitle}

            Connecting and integrate corporate with small & medium companies to incorporate Indonesia.
UKMHUB team

          <form className="login-form">
            <input type="email" placeholder="Email" name="emailLogin" value={this.state.emailLogin} onChange={this.handleChange.bind(this)}/>
            <input type="password" placeholder="Password" name="passwordLogin" value={this.state.passwordLogin} onChange={this.handleChange.bind(this)}/>
              <Link to='/map'>
                <button onClick={this.handleLogin.bind(this)} style={buttonTextStyle}>Login</button>
              </Link>

Not registered?
               Create an account

          </form>

              <form className="register-form">

Register your company to get started in connecting with other companies

                <input type="email" placeholder="Register your company email" name="emailRegister" value={this.state.emailRegister} onChange={this.handleChange.bind(this)}/>
                <input type="password" placeholder="Password" name="passwordRegister" value={this.state.passwordRegister} onChange={this.handleChange.bind(this)}/>
                  <Link to='/profile' >
                    <button style={buttonTextStyle} onClick={this.handleRegister.bind(this)}>Register</button>
                  </Link>

Already registered? Sign In

              </form>

              <form className="forget-password-form">

Forget Password? Click here

                  <input type="email" style={{padding:'10px 15px', marginBottom: 10}} placeholder="Input your company email" name="forgetPassword" value={this.state.forgetPassword} onChange={this.handleChange.bind(this)}/>
                    <button id='register' onClick={this.handleForgetPassword.bind(this)}>Reset Password</button>

              </form>

    )
  }
}

const mapStateToProps = (state) => {
  return {
    loggedInCompany: state.loggedInCompany
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    registerCompanyFetch: (email,password) => dispatch(registerCompanyFetch(email,password)),
    loginCompanyFetch: (email,password) => dispatch(loginCompanyFetch(email,password))
  }
  //return bindActionCreators({addTodo},dispatch)
}

export default connect(mapStateToProps, mapDispatchToProps)(Login)
<commit_msg>fix url login<commit_after>import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import {connect} from 'react-redux'
import logo from '../../../public/assets/logo/ukmhub.png'
import '../../../public/assets/js/login'
import '../../../public/assets/js/bootstrap-notify.js'
import {registerCompanyFetch, loginCompanyFetch} from '../../actions/index.js'
import $ from 'jquery'

let loginInfo = {
  showRegisterInvalid: function (from, align) {
    $.notify({
      icon: 'pe-7s-delete-user',
      message: '
Please input valid email
'

    }, {
      type: 'danger',
      timer: 4000,
      placement: {
        from: from,
        align: align
      }
    })
  },
  showPasswordInvalid: function (from, align) {
    $.notify({
      icon: 'pe-7s-delete-user',
      message: '
Password must be more than 5 character
'
    }, {
      type: 'danger',
      timer: 4000,
      placement: {
        from: from,
        align: align
      }
    })
  },
  showErrorLogin: function (from, align) {
    $.notify({
      icon: 'pe-7s-delete-user',
      message: '
Invalid email/password
'
    }, {
      type: 'danger',
      timer: 4000,
      placement: {
        from: from,
        align: align
      }
    })
  }
}

const emailRegex = /\S+@\S+\.\S+/

class Login extends Component {
  constructor(){
    super()
    this.state = {
      formTitle: 'Login Form',
      emailRegister:'',
      passwordRegister:'',
      emailLogin:'',
      passwordLogin:'',
      forgetPassword:''
    }
  }

  registerClick(){
    $('form').animate({height: "toggle", opacity: "toggle"}, "slow");
    $('#form_id').attr( "style", "max-width: 700px;" );
    this.setState({formTitle: 'Register Form'})
  }

  loginClick(){
    $('form').animate({height: "toggle", opacity: "toggle"}, "slow");
    $('#form_id').attr( "style", "max-width: 400px;" );
  }

  handleRegister(e){
    if(!emailRegex.test(this.state.emailRegister)){
      e.preventDefault()
      loginInfo.showRegisterInvalid('top','center')
    } else if(this.state.passwordRegister.length <= 5){
      e.preventDefault()
      loginInfo.showPasswordInvalid('top','center')
    } else {
      this.props.registerCompanyFetch(this.state.emailRegister,this.state.passwordRegister)
      this.setState({
        emailRegister: '',
        passwordRegister: ''
      })
      setTimeout(function(){
        location.reload()
      }, 1000)
    }
  }

  handleLogin(e){
    e.preventDefault()
    this.props.loginCompanyFetch(this.state.emailLogin,this.state.passwordLogin)
    this.setState({
      emailLogin: '',
      passwordLogin: ''
    })
    setTimeout(function(){
      if(!localStorage.getItem('token')){
        loginInfo.showErrorLogin('top','center')
      } else {
        location.reload()
      }
    },500)
  }

  handleForgetPassword(e){
    e.preventDefault()
    fetch('http://ukmhub-api-dev.ap-southeast-1.elasticbeanstalk.com/api/company/resetPassword', {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({
        email: this.state.forgetPassword
      })
    })
    .then(res => console.log(res))
  }

  handleChange(e){
    let newState = {}
    newState[e.target.name] = e.target.value
    this.setState(newState)
  }

  render () {
    const buttonTextStyle = {
      fontSize: 16
    }
    return (

{this.state.formTitle}

            Connecting and integrate corporate with small & medium companies to incorporate Indonesia.
UKMHUB team

          <form className="login-form">
            <input type="email" placeholder="Email" name="emailLogin" value={this.state.emailLogin} onChange={this.handleChange.bind(this)}/>
            <input type="password" placeholder="Password" name="passwordLogin" value={this.state.passwordLogin} onChange={this.handleChange.bind(this)}/>
              <Link to='/map'>
                <button onClick={this.handleLogin.bind(this)} style={buttonTextStyle}>Login</button>
              </Link>

Not registered?
               Create an account

          </form>

              <form className="register-form">

Register your company to get started in connecting with other companies

                <input type="email" placeholder="Register your company email" name="emailRegister" value={this.state.emailRegister} onChange={this.handleChange.bind(this)}/>
                <input type="password" placeholder="Password" name="passwordRegister" value={this.state.passwordRegister} onChange={this.handleChange.bind(this)}/>
                  <Link to='/profile' >
                    <button style={buttonTextStyle} onClick={this.handleRegister.bind(this)}>Register</button>
                  </Link>

Already registered? Sign In

              </form>

              <form className="forget-password-form">

Forget Password? Click here

                  <input type="email" style={{padding:'10px 15px', marginBottom: 10}} placeholder="Input your company email" name="forgetPassword" value={this.state.forgetPassword} onChange={this.handleChange.bind(this)}/>
                    <button id='register' onClick={this.handleForgetPassword.bind(this)}>Reset Password</button>

              </form>

    )
  }
}

const mapStateToProps = (state) => {
  return {
    loggedInCompany: state.loggedInCompany
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    registerCompanyFetch: (email,password) => dispatch(registerCompanyFetch(email,password)),
    loginCompanyFetch: (email,password) => dispatch(loginCompanyFetch(email,password))
  }
  //return bindActionCreators({addTodo},dispatch)
}

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


<commit_before>
'use strict';

/* Action type constants. */
export const MODAL_CLOSE = 'MODAL_CLOSE';
export const RUN_TEST = 'RUN_TEST';
export const CODE_CHANGED = 'CODE_CHANGED';
export const OUTPUT_CHANGED = 'OUTPUT_CHANGED';
export const TESTS_STARTED = 'TESTS_STARTED';
export const TESTS_FINISHED = 'TESTS_FINISHED';
export const START_CHALLENGE = 'START_CHALLENGE';
export const NEXT_CHALLENGE = 'NEXT_CHALLENGE';

export const TIMER_FINISHED = 'TIMER_FINISHED';
export const TIMER_UPDATED = 'TIMER_UPDATED';
export const TIMER_STARTED = 'TIMER_STARTED';
export const STOP_TIMER = 'STOP_TIMER';

export const FINISH_SESSION = 'FINISH_SESSION';

export const TIMER_MAX_VALUE_CHANGED = 'TIMER_MAX_VALUE_CHANGED';

export const SOLVE_CHALLENGE = 'SOLVE_CHALLENGE';

/* Thunk action which runs the test cases against user code. */
export function runTests(userCode, currChallenge) {
  return dispatch => {
    dispatch(actionTestsStarted());

    // Eval user code inside worker
    // http://stackoverflow.com/questions/9020116/is-it-possible-to-restrict-the-scope-of-a-javascript-function/36255766#36255766
    function createWorker () {
      return new Promise((resolve, reject) => {
        const wk = new Worker('../../public/js/worker.bundle.js');
        wk.postMessage([userCode, currChallenge]);
        wk.onmessage = e => {
          console.log(`worker onmessage result: ${e.data}`);
          resolve(e.data);
        };
      });
    }

    createWorker()
      .then(workerData => {
        dispatch(onOutputChange(workerData[0].output));
        if (workerData.length > 1) {
          dispatch(actionTestsFinished(workerData.slice(1)));
        }
      });
  };
}

let timer = null;

/* Thunk action to start the timer. */
export function startTimer(timerMaxValue) {
  return dispatch => {
    clearInterval(timer);

    const timeStart = new Date().getTime();
    const timerMaxValueInt = parseInt(timerMaxValue, 10);
    dispatch(actionTimerStarted(timeStart));

    timer = setInterval(() => {
      const timeNow = new Date().getTime();
      dispatch(actionTimerUpdated(timeNow));
      const timeElapsed = timeNow - timeStart;
      if (timeElapsed >= timerMaxValueInt) {
        dispatch(stopTimer());
      }
    }, 1000 / 60);
  };
}

export function stopTimer() {
  clearInterval(timer);
  return {
    type: STOP_TIMER
  };
}

/* Dispatched when a user starts running the tests.*/
export function actionTestsStarted() {
  return {
    type: TESTS_STARTED
  };
}

/* Dispatched when the tests finish. */
export function actionTestsFinished(testResults) {
  return {
    type: TESTS_FINISHED,
    testResults
  };
}

export function onModalClose() {
  return {
    type: MODAL_CLOSE
  };
}

export function startChallenge(startTime) {
  return {
    type: START_CHALLENGE,
    startTime
  };
}

export function nextChallenge(startTime) {
  return {
    type: NEXT_CHALLENGE,
    startTime
  };
}

export function onCodeChange(newCode) {
  return {
    type: CODE_CHANGED,
    code: newCode
  };
}

export function actionTimerStarted(startTime) {
  return {
    type: TIMER_STARTED,
    startTime
  };
}

export function actionTimerFinished() {
  return {
    type: TIMER_FINISHED
  };
}

export function actionTimerUpdated(timeNow) {
  return {
    type: TIMER_UPDATED,
    timeNow
  };
}

export function actionTimerMaxValueChanged(timerMaxValue) {
  return {
    type: TIMER_MAX_VALUE_CHANGED,
    timerMaxValue
  };
}

export function onOutputChange(newOutput) {
  return {
    type: OUTPUT_CHANGED,
    userOutput: newOutput
  };
}

export function actionFinishSession() {
  return {
    type: FINISH_SESSION
  };
}

export function actionSolveChallenge() {
  return {
    type: SOLVE_CHALLENGE
  };
}
<commit_msg>move modal action to own file<commit_after>
'use strict';

/* Action type constants. */
export const RUN_TEST = 'RUN_TEST';
export const CODE_CHANGED = 'CODE_CHANGED';
export const OUTPUT_CHANGED = 'OUTPUT_CHANGED';
export const TESTS_STARTED = 'TESTS_STARTED';
export const TESTS_FINISHED = 'TESTS_FINISHED';
export const START_CHALLENGE = 'START_CHALLENGE';
export const NEXT_CHALLENGE = 'NEXT_CHALLENGE';

export const TIMER_FINISHED = 'TIMER_FINISHED';
export const TIMER_UPDATED = 'TIMER_UPDATED';
export const TIMER_STARTED = 'TIMER_STARTED';
export const STOP_TIMER = 'STOP_TIMER';

export const FINISH_SESSION = 'FINISH_SESSION';

export const TIMER_MAX_VALUE_CHANGED = 'TIMER_MAX_VALUE_CHANGED';

export const SOLVE_CHALLENGE = 'SOLVE_CHALLENGE';

/* Thunk action which runs the test cases against user code. */
export function runTests(userCode, currChallenge) {
  return dispatch => {
    dispatch(actionTestsStarted());

    // Eval user code inside worker
    // http://stackoverflow.com/questions/9020116/is-it-possible-to-restrict-the-scope-of-a-javascript-function/36255766#36255766
    function createWorker () {
      return new Promise((resolve, reject) => {
        const wk = new Worker('../../public/js/worker.bundle.js');
        wk.postMessage([userCode, currChallenge]);
        wk.onmessage = e => {
          console.log(`worker onmessage result: ${e.data}`);
          resolve(e.data);
        };
      });
    }

    createWorker()
      .then(workerData => {
        dispatch(onOutputChange(workerData[0].output));
        if (workerData.length > 1) {
          dispatch(actionTestsFinished(workerData.slice(1)));
        }
      });
  };
}

let timer = null;

/* Thunk action to start the timer. */
export function startTimer(timerMaxValue) {
  return dispatch => {
    clearInterval(timer);

    const timeStart = new Date().getTime();
    const timerMaxValueInt = parseInt(timerMaxValue, 10);
    dispatch(actionTimerStarted(timeStart));

    timer = setInterval(() => {
      const timeNow = new Date().getTime();
      dispatch(actionTimerUpdated(timeNow));
      const timeElapsed = timeNow - timeStart;
      if (timeElapsed >= timerMaxValueInt) {
        dispatch(stopTimer());
      }
    }, 1000 / 60);
  };
}

export function stopTimer() {
  clearInterval(timer);
  return {
    type: STOP_TIMER
  };
}

/* Dispatched when a user starts running the tests.*/
export function actionTestsStarted() {
  return {
    type: TESTS_STARTED
  };
}

/* Dispatched when the tests finish. */
export function actionTestsFinished(testResults) {
  return {
    type: TESTS_FINISHED,
    testResults
  };
}

export function startChallenge(startTime) {
  return {
    type: START_CHALLENGE,
    startTime
  };
}

export function nextChallenge(startTime) {
  return {
    type: NEXT_CHALLENGE,
    startTime
  };
}

export function onCodeChange(newCode) {
  return {
    type: CODE_CHANGED,
    code: newCode
  };
}

export function actionTimerStarted(startTime) {
  return {
    type: TIMER_STARTED,
    startTime
  };
}

export function actionTimerFinished() {
  return {
    type: TIMER_FINISHED
  };
}

export function actionTimerUpdated(timeNow) {
  return {
    type: TIMER_UPDATED,
    timeNow
  };
}

export function actionTimerMaxValueChanged(timerMaxValue) {
  return {
    type: TIMER_MAX_VALUE_CHANGED,
    timerMaxValue
  };
}

export function onOutputChange(newOutput) {
  return {
    type: OUTPUT_CHANGED,
    userOutput: newOutput
  };
}

export function actionFinishSession() {
  return {
    type: FINISH_SESSION
  };
}

export function actionSolveChallenge() {
  return {
    type: SOLVE_CHALLENGE
  };
}
<|endoftext|>


<commit_before>
Template.reviewViewspot.helpers({
  vsDetail: function() {
    var mid = Session.get('currentVsId')
    // var detailInfo = ViewSpot.findOne({
    //   '_id': new Mongo.ObjectID(mid)
    // });

    var detailInfo = storageEngine.snapshot('poi.ViewSpot', new Mongo.ObjectID(mid));
    log('输出信息');
    log(detailInfo);
    var vsDetail = [];
    review('ViewSpot', detailInfo, vsDetail);
    createOriginTextMD5(vsDetail);
    return vsDetail;
  },
});

Template.reviewViewspot.events({
  "click .city-name": function(e) {

    var mid = $(e.target).attr('id');
    // 重复点击
    if (mid === Session.get('currentVsId')) {
      return;
    }
    // 是否做了修改
    if (_.keys(Session.get('oplog')).length) {
      var res = confirm('已做修改，尚未提交，放弃本次修改?');
      if (!res) {
        // 不放弃修改
        return;
      }
    }
    Session.set('currentVsId', mid);
    $(e.target).siblings().removeClass('active');
    $(e.target).addClass("active");
    Meteor.subscribe('oplog', 'poi.ViewSpot', new Mongo.ObjectID(mid), 0);

    // Meteor.subscribe("viewspotDetail", mid);
    initOriginMD5Session();
    initOplogSession();

    Meteor.subscribe("Images", mid);
  },
});

createOriginTextMD5 = function(arrayData) {
  var tempObj = {};
  for (var i in arrayData) {
    var temp = arrayData[i];
    var tempValue = temp.value;

    //假如该数据的该字段没有定义，则temp.value为undefined
    tempObj[temp.keyChain] = tempValue ? cmsMd5(tempValue.toString()) : tempValue;
  }
  Session.set('originMD5', tempObj);
};

cmsMd5 = function(string) {
  return CryptoJS.MD5(string).toString();
};

initOplogSession = function() {
  Session.set('oplog', {});
};

initOriginMD5Session = function() {
  Session.set('originMD5', {});
};

// 递归实现自动render模版，
/**
@params: {object} items
@params: {Number} index 数组字段的元素索引
*/

/*
@params: {object} items 以当前结点为根结点的树结构，来自reviewItems
@params: {string} tabName basic/traffic/feature
@params: {object} data 当前树结构对应的数据
@params: {object} outPutData 所有要输出的数据数组
@params: {object} keyChain 当前数据(string or int)对应的键
@params: {object} index
*/
organizeReviewData = function(items, tabName, data, outPutData, keyChain, index) {
  var inheritKey = keyChain || '';
  var keys = _.keys(items); // 当前dom要展示的数据的key
  for (var i in keys) {
    var key = keys[i];
    var zhLabel = items[key][itemIndex.zhDesc];
    var dataType = items[key][itemIndex.dataType];
    var tplData = {};

    //当前数据为字符串(string), 整型(int), 字符串数组(str_array)时
    if (dataType === itemDataType.string || dataType === itemDataType.int || dataType === itemDataType.str_array) {
      var newKey = inheritKey ? (inheritKey + '-' + key) : key;
      tplData = {
          'zhLabel': zhLabel,
          'keyChain': index ? newKey + '-' + (index -1) : newKey,
          'value': data[key],
          'tabName': {},
          'index': index,
          'dataType': dataType,
          'richEditor': items[key][itemIndex.richEditor],
          'strArray': dataType === itemDataType.str_array
        }
        // 放入到特定的Tab中
      tplData.tabName[tabName] = true;
      outPutData.push(tplData);
    }

    //当前数据为对象数组(obj_array)时
    if (dataType === itemDataType.obj_array) {
      var tempData = data[key]; //递归使用的数据
      var tempItems = items[key][itemIndex.childInfo];
      var tempIndex = 0;
      for (var i in tempData) {
        var element = tempData[i];
        tempIndex = tempIndex + 1;
        organizeReviewData(tempItems, tabName, element, outPutData, key, tempIndex);
      }
    }

    // TODO 实现更多的规则
  }
};

/**
 * [review description]
 * @param  {[type]} type       [description]
 * @param  {[type]} data       [description]
 * @param  {[type]} outPutData 返回的数据
 * @return {[type]}            [description]
 */
review = function(type, data, outPutData) {
  var itemsForReview = reviewItems[type];
  var classify = _.keys(itemsForReview);
  for (var index in classify) { // 选择dom区域
    var tabName = classify[index];
    var items = itemsForReview[tabName]; // 当前dom要展示的数据
    organizeReviewData(items, tabName, data, outPutData);
  }
};
<commit_msg>fix empty field not reload textarea<commit_after>
Template.reviewViewspot.helpers({
  vsDetail: function() {
    var mid = Session.get('currentVsId')
    // var detailInfo = ViewSpot.findOne({
    //   '_id': new Mongo.ObjectID(mid)
    // });

    var detailInfo = storageEngine.snapshot('poi.ViewSpot', new Mongo.ObjectID(mid));
    log('输出信息');
    log(detailInfo);
    var vsDetail = [];
    review('ViewSpot', detailInfo, vsDetail);
    createOriginTextMD5(vsDetail);
    log(vsDetail);
    return vsDetail;
  },
});

Template.reviewViewspot.events({
  "click .city-name": function(e) {

    var mid = $(e.target).attr('id');
    // 重复点击
    if (mid === Session.get('currentVsId')) {
      return;
    }
    // 是否做了修改
    if (_.keys(Session.get('oplog')).length) {
      var res = confirm('已做修改，尚未提交，放弃本次修改?');
      if (!res) {
        // 不放弃修改
        return;
      }
    }
    Session.set('currentVsId', mid);
    $(e.target).siblings().removeClass('active');
    $(e.target).addClass("active");
    Meteor.subscribe('oplog', 'poi.ViewSpot', new Mongo.ObjectID(mid), 0);

    // Meteor.subscribe("viewspotDetail", mid);
    initOriginMD5Session();
    initOplogSession();

    Meteor.subscribe("Images", mid);
  },
});

createOriginTextMD5 = function(arrayData) {
  var tempObj = {};
  for (var i in arrayData) {
    var temp = arrayData[i];
    var tempValue = temp.value;

    //假如该数据的该字段没有定义，则temp.value为undefined
    tempObj[temp.keyChain] = tempValue ? cmsMd5(tempValue.toString()) : tempValue;
  }
  Session.set('originMD5', tempObj);
};

cmsMd5 = function(string) {
  return CryptoJS.MD5($.trim(string)).toString();
};

initOplogSession = function() {
  Session.set('oplog', {});
};

initOriginMD5Session = function() {
  Session.set('originMD5', {});
};

// 递归实现自动render模版，
/**
@params: {object} items
@params: {Number} index 数组字段的元素索引
*/

/*
@params: {object} items 以当前结点为根结点的树结构，来自reviewItems
@params: {string} tabName basic/traffic/feature
@params: {object} data 当前树结构对应的数据
@params: {object} outPutData 所有要输出的数据数组
@params: {object} keyChain 当前数据(string or int)对应的键
@params: {object} index
*/
organizeReviewData = function(items, tabName, data, outPutData, keyChain, index) {
  var inheritKey = keyChain || '';
  var keys = _.keys(items); // 当前dom要展示的数据的key
  for (var i in keys) {
    var key = keys[i];
    var zhLabel = items[key][itemIndex.zhDesc];
    var dataType = items[key][itemIndex.dataType];
    var tplData = {};

    //当前数据为字符串(string), 整型(int), 字符串数组(str_array)时
    if (dataType === itemDataType.string || dataType === itemDataType.int || dataType === itemDataType.str_array) {
      var newKey = inheritKey ? (inheritKey + '-' + key) : key;
      tplData = {
          'zhLabel': zhLabel,
          'keyChain': index ? newKey + '-' + (index -1) : newKey,
          'value': data[key] || " ",// 保证所有字段存在数据，否则本次数据为空时，刷新数据时会保留上次的数据
          'tabName': {},
          'index': index,
          'dataType': dataType,
          'richEditor': items[key][itemIndex.richEditor],
          'strArray': dataType === itemDataType.str_array
        }
        // 放入到特定的Tab中
      tplData.tabName[tabName] = true;
      outPutData.push(tplData);
    }

    //当前数据为对象数组(obj_array)时
    if (dataType === itemDataType.obj_array) {
      var tempData = data[key]; //递归使用的数据
      var tempItems = items[key][itemIndex.childInfo];
      var tempIndex = 0;
      for (var i in tempData) {
        var element = tempData[i];
        tempIndex = tempIndex + 1;
        organizeReviewData(tempItems, tabName, element, outPutData, key, tempIndex);
      }
    }

    // TODO 实现更多的规则
  }
};

/**
 * [review description]
 * @param  {[type]} type       [description]
 * @param  {[type]} data       [description]
 * @param  {[type]} outPutData 返回的数据
 * @return {[type]}            [description]
 */
review = function(type, data, outPutData) {
  var itemsForReview = reviewItems[type];
  var classify = _.keys(itemsForReview);
  for (var index in classify) { // 选择dom区域
    var tabName = classify[index];
    var items = itemsForReview[tabName]; // 当前dom要展示的数据
    organizeReviewData(items, tabName, data, outPutData);
  }
};
<|endoftext|>