This commit is contained in:
oitsjustjose 2020-04-09 21:38:51 -04:00
commit aead4d7624
14 changed files with 3268 additions and 0 deletions

106
.gitignore vendored Normal file
View file

@ -0,0 +1,106 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# TypeScript v1 declaration files
typings/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
.env.test
# parcel-bundler cache (https://parceljs.org/)
.cache
# Next.js build output
.next
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and *not* Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
**/.DS_Store

17
.vscode/launch.json vendored Normal file
View file

@ -0,0 +1,17 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "pwa-node",
"request": "launch",
"name": "Launch Program",
"skipFiles": [
"<node_internals>/**"
],
"program": "${workspaceFolder}/index.js"
}
]
}

3
.vscode/settings.json vendored Normal file
View file

@ -0,0 +1,3 @@
{
"git.ignoreLimitWarning": true
}

49
index.js Normal file
View file

@ -0,0 +1,49 @@
const express = require("express");
const bodyParser = require("body-parser");
const path = require("path");
const app = express();
const port = process.env.PORT || 3030;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static(__dirname + "/lib"));
const serial = require("./serial");
const parallel = require("./parallel");
app.get("/", (req, res) => {
res.render(path.join(__dirname, "pages/main.ejs"));
});
app.post("/primes", (req, res) => {
let numPrimes;
try {
numPrimes = parseInt(req.query.num);
} catch (ex) {
numPrimes = 5;
}
let results = {
"serial": {},
"parallel": {}
};
let serialStart = process.hrtime();
serial.getPrimes(numPrimes);
let serialEnd = process.hrtime(serialStart);
results.serial.time = serialEnd;
let parallelStart = process.hrtime();
parallel.getPrimes(numPrimes);
let parallelEnd = process.hrtime(parallelStart);
results.parallel.time = parallelEnd;
res.send(results);
});
app.listen(port, () => console.log("Listening on port " + port));

1115
lib/main-light.css Normal file

File diff suppressed because it is too large Load diff

81
lib/menu.js Normal file
View file

@ -0,0 +1,81 @@
/**
* Uses ZERO Jquery!!
*/
let menuOpen = false;
const toggleSubMenu = (el) => {
let icon = el.querySelector("i.fa");
let isOpen = icon.hasAttribute("submenuOpen") ? parseInt(icon.getAttribute("submenuOpen")) : 0;
document.querySelectorAll(`[for=${el.getAttribute("from")}]`).forEach((elSearched) => {
if (isOpen == 1) {
elSearched.classList.remove("visible");
} else {
elSearched.classList.add("visible");
}
});
if (isOpen == 1) {
icon.style.transition = "transform ease-in-out 250ms";
icon.style.transform = "rotate(0deg)";
icon.setAttribute("submenuOpen", 0);
} else { // Not open..
icon.style.transition = "transform ease-in-out 250ms";
icon.style.transform = "rotate(90deg)";
icon.setAttribute("submenuOpen", 1);
}
};
const toggleMenu = () => {
let menu = document.querySelector(".mobile-menu");
menuOpen = !menuOpen;
if (menuOpen) {
menu.classList.add("visible");
document.body.classList.add("no-scroll");
} else {
menu.classList.remove("visible");
document.body.classList.remove("no-scroll");
}
};
window.addEventListener("DOMContentLoaded", (evt) => {
document.querySelectorAll(".compact.submenu.item").forEach((el) => {
let id = `subMenu_${new Date().getMilliseconds()}`;
el.setAttribute("from", id);
let subMenuItems = [];
el.querySelectorAll(".compact.sub.item").forEach((child) => {
subMenuItems.push(child);
});
subMenuItems.reverse();
subMenuItems.forEach((child) => {
child.setAttribute("for", id);
el.parentElement.insertBefore(child, el.nextSibling);
});
});
// Add .active to clicked on menus
document.querySelectorAll(".dropdown.item").forEach((dropdown) => {
dropdown.addEventListener("click", () => {
if (dropdown.classList.contains("active")) {
dropdown.classList.remove("active");
} else {
dropdown.classList.add("active");
}
});
dropdown.addEventListener("mouseout", () => {
if (dropdown.classList.contains("active")) {
dropdown.classList.remove("active");
}
});
});
});

43
lib/modal.js Normal file
View file

@ -0,0 +1,43 @@
window.addEventListener("DOMContentLoaded", (evt) => {
window.onclick = (event) => {
if (event.target.classList.contains("modal")) {
let modal = event.target;
modal.classList.remove("visible");
modal.removeAttribute("active");
document.body.classList.remove("modal-no-scroll");
}
};
document.querySelectorAll(".modal .close").forEach((closeBtn) => {
closeBtn.addEventListener('click', (evt) => {
let modal = closeBtn.parentElement.parentElement;
modal.classList.remove("visible");
modal.removeAttribute("active");
document.body.classList.remove("modal-no-scroll");
});
});
document.querySelectorAll("[for-modal]").forEach((modalTrigerEl) => {
modalTrigerEl.addEventListener('click', (evt) => {
let modal = document.getElementById(modalTrigerEl.getAttribute("for-modal"));
modal.classList.add("visible");
modal.setAttribute("active", "");
document.body.classList.add("modal-no-scroll");
});
});
// document.querySelectorAll("[for-modal]").forEach((modalTrigerEl) => {
// let modal = document.getElementById(modalTrigerEl.getAttribute("for-modal"));
// modal.classList.remove("visible");
// modal.removeAttribute("active");
// });
document.body.addEventListener('keydown', (evt) => {
if (evt.key == "Escape") {
let modal = document.querySelector(".modal[active]");
modal.classList.remove("visible");
modal.removeAttribute("active");
document.body.classList.remove("modal-no-scroll");
}
});
});

1559
package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

31
package.json Normal file
View file

@ -0,0 +1,31 @@
{
"name": "parallel-node",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": ""
},
"author": "Jose Stovall",
"license": "UNLICENSED",
"bugs": {
"url": "https://no.com"
},
"homepage": "",
"dependencies": {
"benchmark": "^2.1.4",
"body-parser": "^1.19.0",
"ejs": "^2.6.2",
"express": "^4.17.1",
"random-seed": "^0.3.0",
"seedrandom": "^3.0.5",
"webworker-threads": "^0.7.17"
},
"devDependencies": {
"eslint": "^6.0.1"
}
}

118
pages/main.ejs Normal file
View file

@ -0,0 +1,118 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Jose's Parallel Node Service</title>
<link rel="stylesheet" href="/main-light.css">
<style>
body {
margin: 0;
}
.flex-container {
display: flex;
flex-direction: column;
width: 100vw;
height: 100vh;
align-items: center;
justify-content: center;
}
form {
max-width: 1024px;
margin: auto;
}
</style>
<script>
const updateWithData = (jsonData) => {
let results = document.getElementById("results");
results.style.display = "none";
document.getElementById("serial-time").innerText = jsonData.serial.time[1];
document.getElementById("parallel-time").innerText = jsonData.parallel.time[1];
results.style.display = "block";
};
window.addEventListener("DOMContentLoaded", (evt) => {
// Form Validation
let input = document.querySelector("input[type=number]");
input.addEventListener('change', () => {
let numPrimes = parseInt(input.value);
if (numPrimes < 1) {
document.forms[0].primes.value = 1;
}
if (numPrimes > 10) {
document.forms[0].primes.value = 10;
}
});
let submitBtn = document.getElementById("submitBtn");
submitBtn.addEventListener('click', (evt) => {
try {
let numPrimes = parseInt(document.forms[0].primes.value);
if (numPrimes < 1) {
numPrimes = 1;
document.forms[0].primes.value = 1;
}
if (numPrimes > 10) {
numPrimes = 10;
document.forms[0].primes.value = 10;
}
submitBtn.setAttribute("disabled", "");
fetch(`/primes?num=${numPrimes}`, {
method: "POST",
headers: { "Content-Type": "application/json" }
}).then(output => {
if (output.status === 200) {
output.json().then((data) => {
updateWithData(data);
submitBtn.removeAttribute("disabled");
})
}
});
} catch (err) {
console.log(err);
alert("Invalid Number of Primes Given")
}
});
});
</script>
</head>
<body>
<div class="flex-container">
<div class="centered container">
<h2>
Multi-Threaded NodeJS Server Test
</h2>
<form action="/primes" method="POST">
<div class="labelled flex-form">
<label for="primes">How Many Primes to Create:</label>
<input name="primes" type="number" value="5" min="1" , max="10">
</div>
</form>
<p>
(The max is 10 due to server hardware constraints)
</p>
<button id="submitBtn">Submit</button>
</div>
<div class="centered container" id="results" style="display: none;">
<h2>Results</h2>
<p>
Serial Time: <span id="serial-time"></span>ns.
</p>
<p>
Parallel Time: <span id="parallel-time"></span>ns.
</p>
</div>
</div>
</body>
</html>

50
pages/results.ejs Normal file
View file

@ -0,0 +1,50 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Jose's Parallel Node Service</title>
<link rel="stylesheet" href="/main-light.css">
<style>
body {
margin: 0;
}
.flex-container {
display: flex;
flex-direction: column;
width: 100vw;
align-items: center;
justify-content: center;
}
form {
max-width: 1024px;
margin: auto;
}
</style>
<script>
window.addEventListener("DOMContentLoaded", (evt) => {
let results = document.getElementById("results");
let resJSON = location.href.substring(location.href.indexOf("results?json=") + 13, location.href.length);
results.innerText = JSON.stringify(resJSON);
});
</script>
</head>
<body>
<div class="flex-container">
<h2>
Multi-Threaded NodeJS Server Results
</h2>
<code class="centered code" id="results">
hi
</code>
<button class="blue" onclick="location.href='/'">Back</button>
</div>
</body>
</html>

30
parallel.js Normal file
View file

@ -0,0 +1,30 @@
/**
* @author Jose Stovall | oitsjustjose
* @description A file for creating an array of random prime integers, similar to Homework 3
*/
const Threads = require('webworker-threads');
const path = require("path");
const getPrimes = (arrSize) => {
let threads = Threads.createPool(arrSize);
let primes = [];
threads.load(path.join(__dirname, "primefinder.js"), (err, data) => {
if (err) {
console.log(`ERROR: ${err}`);
} else {
primes.push(data);
// Quit once we've gotten the right number of primes!
if (primes.length == arrSize) {
threads.destroy();
}
}
});
};
module.exports = {
"getPrimes": getPrimes
};

28
primefinder.js Normal file
View file

@ -0,0 +1,28 @@
let prime = -1;
const upperLimit = 4294967295;
while (prime === -1) {
let num = Math.round(Math.random() * upperLimit);
if (num === 0 || num === 1 || num % 2 === 0) {
continue;
}
if (num === 2 || num === 3) {
continue;
}
let divisor = 3;
let isValid = true;
while (divisor <= (num / 2)) {
if (num % divisor == 0) {
isValid = false;
break;
}
divisor += 2;
}
if (isValid) {
prime = num;
}
}
this.data = prime;

38
serial.js Normal file
View file

@ -0,0 +1,38 @@
const upperLimit = 4294967295;
const getPrimes = (arrSize) => {
let ret = [];
while (ret.length != arrSize) {
let prime = -1;
while (prime === -1) {
let num = Math.round(Math.random() * upperLimit);
if (num === 0 || num === 1 || num % 2 === 0) {
continue;
}
if (num === 2 || num === 3) {
continue;
}
let divisor = 3;
let isValid = true;
while (divisor <= (num / 2)) {
if (num % divisor == 0) {
isValid = false;
break;
}
divisor += 2;
}
if (isValid) {
prime = num;
}
}
ret.push(prime);
}
return ret;
};
module.exports = {
"getPrimes": getPrimes
};