I want to know how to write a code for solving equations on Graphical analysis of linear proramming problems, simplex methods, ga
I have not tried anything
Blancer.com Tutorials and projects
Freelance Projects, Design and Programming Tutorials
Category Added in a WPeMatico Campaign
I want to know how to write a code for solving equations on Graphical analysis of linear proramming problems, simplex methods, ga
I have not tried anything
I am using the https://www.npmjs.com/package/rus-diff in my node.js express app to compare two tables in a SQL server database.
However since my tables may be quite large, I want to use a “chunking” approach to avoid OOM, so I refactored my function from
return require('rus-diff').rusDiff(first_array_of_objects, second_array_of_objects);
to look like this, so only 500 rows are compared at once.
compareTwoArrayOfObjects: function (first_array_of_objects, second_array_of_objects, batch_size = 500) {
const rusDiff = require('rus-diff');
const diff = {$set: {}};
let rows_processed = 0;
// Loop over the arrays in batches
while (rows_processed < Math.max(first_array_of_objects.length, second_array_of_objects.length)) {
const first_batch = first_array_of_objects.slice(rows_processed, rows_processed + batch_size);
const second_batch = second_array_of_objects.slice(rows_processed, rows_processed + batch_size);
// Compare the batches using rus-diff
const batch_diff = rusDiff.rusDiff(first_batch, second_batch);
// Merge the batch differences into the overall differences
Object.assign(diff.$set, batch_diff.$set);
// Update the number of rows processed
rows_processed += batch_size;
// Log the percentage completed
const percentage_completed = Math.round(rows_processed / Math.max(first_array_of_objects.length, second_array_of_objects.length) * 100);
console.log(`Processed ${rows_processed} rows (${percentage_completed}%)`);
}
return diff;
}
This compareTwoArrayOfObjects function is used in my route like so:
compareRows: async function (req, res) {
console.log('compare-rows endpoint called');
const {
sourceDB,
destDB,
....
} = req.body;
//console.log(runID, useRunId)
const commonCols = findCommonStrings(columns1, columns2);
try {
const sourcePool = await GetCreateIfNotExistPool(sourceDB);
const destPool = await GetCreateIfNotExistPool(destDB);
const destRows = await getDestRows(destPool, destDB, commonCols, table2, joinKeys, pageSize, schema2, runID, useRunId);
const sourceRows = await getSourceRows(sourcePool, sourceDB, table1, joinKeys, commonCols, destRows, parallelism, schema1);
let tableDiffs = compareTwoArrayOfObjects(sourceRows, destRows);
res.json({
sourceData: sourceRows,
destData: destRows,
isSameObject: Object.keys(tableDiffs).length === 0 ? false : tableDiffs
})
} catch (err) {
console.error(err);
res.status(500).send(err.message);
}
}
The issue Im having is that now my “compareTwoArrayOfObjects” only compares the first chunk. When I call compare rows When it is supposed to loop through both of my arrays and rereturn the difference for all the chunks. Can someone help me figure out if this is an issue with my code? or is “chunking” not allowed with “rus-diff”?
Im trying to create a 64 square checkerboard on the html canvas element in javascript.
The problem is i cant seem to get the boxes to render plus 75 on the x axis (posX) after the first 8 have rendered on the y and i cant seem to understand what im doing wrong.
Here is the code i have been trying.
<body>
<canvas id="mainCanvas" width="600" height="600"></canvas>
<script src="js/main.js" ></script>
</body>
#mainCanvas {
background-color: black; }
const canvas = document.getElementById("mainCanvas");
const ctx = canvas.getContext("2d");
const sWidth = 75;
const sHeight =75;
const sCount = 64;
let posY = 0;
let posX = 0;
function DrawSquare(posX,posY,color){
console.log(`Drawing square at (${posX}, ${posY}) with color ${color}`);
ctx.beginPath();
ctx.rect(posX, posY, sWidth, sHeight);
ctx.fillStyle = color;
ctx.fill();
ctx.closePath();
}
for(let i = 0;i < sCount;i++){
if(i % 2 == 0){
DrawSquare(posX, posY,"white");
console.log("white"+posX)
}else{
DrawSquare(posX, posY,"black");
console.log("black")
}
if(i>7){
if(i%8==0){
posX+=75;
}
}
posY+=75;
}
Any help would be much appreciated and a thanks in advance.
Im trying to code a bot that fetch data from faceit link user give and compare it with users linked Riot Games accounts username. I want to check if user connected his Discord account to Riot Games account and if its connected, I want to fetch his/her username to check if its the same username he/she gave. I couldnt figure out how because as far as I know API is not giving this information to bots. Is there any way to check this?
Note: If needed, Im using node-fetch to request data.
Tried to fetch users linked Riot Games accounts username and compare it with another accounts username whichs connected to Faceit.
Couldnt figure out how to do it since API doesnt give linked accounts of users.
I’ve been trying to make a good search bar for a while now and I can’t find out how.
All of the code professional code that I view is unreadable. I want one that searches html files.
Can someone please just give me an example that I can read?
At first I tried PHP which some people say is a good option(but wasn’t for someone like me)
Recently I tried jQuery which is A lot easier too read; but it searches an array.
I just started learning photoshop scripting with extendscript, and am utterly unable to figure out how to get it to save a file, I looked in a few places on the internet, including here, adobe community forums, scripting ref ebooks, chatgpt, and saw a lot of suggestions from people and robots who seem to have gotten it working, but none of them is working for me.
Here is a list of methods I tried, which are all giving me the same error.
I only included the line of code which threw the error, which is usually the very first line that deals with defining a File object, I can’t even get past that part.
var expFile = new PhotoshopSaveOptions();
Uncaught ReferenceError: PhotoshopSaveOptions is not defined
var pngFile = new File("D:/temp/test.png");
Uncaught ReferenceError: File is not defined
var pngSaveOptions = new PNGSaveOptions();
Uncaught ReferenceError: PNGSaveOptions is not defined
var saveOptions = new JPEGSaveOptions();
Uncaught ReferenceError: JPEGSaveOptions is not defined
var options = new ExportOptionsSaveForWeb(); options.format = SaveDocumentType.PNG;
Uncaught ReferenceError: ExportOptionsSaveForWeb is not defined
var options = new ExportOptions(); options.format = SaveDocumentType.PNG; options.transparency = true;
Uncaught ReferenceError: ExportOptions is not defined
I’ll keep looking and experimenting, but if you have a solution for me, I’d very much appreciate it.
The current firebase function logs the correct value for id_token just before the return statement. But the function returns not that value, but an empty array. Here’s the function:
exports.getIdToken = functions.https.onCall(async (data, context) => {
const flinkeyUserId = data.flinkeyUserId;
var idToken;
const options = {
hostname: 'api-uat.flinkey.de',
path: '/v3/oauth2/token',
method: 'POST',
headers: {
'flinkey-API-Key': flinkeyAPIKey,
'Content-Type': 'application/x-www-form-urlencoded'
}
};
const requestBody = {
username: username,
password: password,
grant_type: 'password'
};
const requestBodyString = new URLSearchParams(requestBody).toString();
const req = https.request(options, res => {
let data = '';
res.on('data', d => {
data += d;
});
res.on('end', async () => {
const accessToken = JSON.parse(data).access_token;
await fetch('https://api-uat.flinkey.de/v3/sdk/token', {
method: 'POST',
headers: {
'flinkey-API-Key': flinkeyAPIKey,
'Authorization': accessToken,
'Content-Type': 'application/json'
},
body: JSON.stringify({
'customerId': customerID,
'userId': flinkeyUserId,
'sdkKey': sdkKey
})
})
.then(response => response.json())
.then(response => {
const id_token = response.id_token;
console.log(id_token);
return idToken = id_token;
})
.catch(error => {
console.error(error);
throw new functions.https.HttpsError('unknown', 'Error getting ID Token.');
});
});
});
req.on('error', error => {
console.error(error);
response.status(500).send(error);
});
req.write(requestBodyString);
req.end();
});
How can I wait for the response and then return the correct value? I think it returns the empty value right after the function is called, and after some time, the correct value is logged.
I want to assign the data retrieved from a promise in a fetch function to a variable where I can use it in the future.
Here is my example :
let x
const getData = async () => await fetch(`API here`).then((res) => res.json()).then((data) => {
x = data;
console.log("data", data);
console.log("first x", x);
});
getData();
console.log(“second x”, x);
The console log shows like this :
data : object contains the data from the API
first x : the same value as data
second x : shows undefined
Is there any other way to assign the data into x and use it outside the promise ?
PS : when I console log getData() it shows the promise object and not the value
Thank you in advance.
I’m currently trying to run a cypress test but unable to get this specific element.
Here is what I’ve tried but I’m running into this error. I thought this was an issue with my timeout. I’ve fixed my timeout but I’m still getting this error. My code is unable to find this. I’m trying to get to Dogs from the select menu but I’m unable to get cypress to locate that element.
Error:Timed out retrying after 4000ms: Expected to find element: ant-select-dropdown-menu-item-selected, but never found it.
cy.get('.ant-select-dropdown-menu-item-selected').click();
<div class="ant-select-selection__rendered"><div unselectable="on" class="ant-select-selection__placeholder" style="display: none; user-select: none;">Select Org</div><div class="ant-select-selection-selected-value" title="Dogs" style="display: block; opacity: 1;">Dogs</div><div class="ant-select-search ant-select-search--inline" style="display: none;"><div class="ant-select-search__field__wrap"><input autocomplete="off" class="ant-select-search__field" value=""><span class="ant-select-search__field__mirror"> </span></div></div></div>
So I have a project involving Rails ActionCable and a Leaflet map. I already have wired up channels for realtime chat and offline/away/online presence. What I am trying to do now is wire up a Leaflet on drag event to send the data back to the server and have ActionCable broadcast the dragging movement to the other clients. I would rather not use a POST since I plan on sending this data up to the server every 0.25 seconds.
map_show.html => has the html elements to display the leaflet map
map_show.js
var map = L.map('map', {crs: L.CRS.Simple, minZoom: 4, maxZoom: 6});
var car = L.marker([10,10], {icon: blueCar}).on('drag', reportLocationToServer).addTo(map);
var myColor = document.getElementById('myColor').getAttribute('data');
// will be throttled eventually
function reportLocationToServer(event){
var marker = event.target;
var location = marker.getLatLng();
var lat = location.lat;
var lng = location.lng;
// send to server the current coords and color
// the server will then broadcast to the other clients
// ?? DragChannel.perform(receive_location, color: myColor, coords: [lng,lat]) ??
console.log('Color: %s Lng: %s Lat: %s', myColor, lng, lat);
}
app/javascripts/channels/drag_channel.js
received(data) {
console.log("FROM RAILS: ", data);
if (data['color'] === myColor) {
// do nothing, I am the one doing the dragging
console.log('My color, coords %s', data['color'], data['coords']);
} else {
car.setLngLat(data['coords']);
}
}
How do I get a JS frontend to send data back to a Rails server using ActionCable?
I messed up the dependencies for my Angular project when I tried to install some @type dependency which is deprecated.
After that, I’ve tried different versions for my dependencies, updating or downgrading them, but no result. After I solve one dependency, I have 10 other error, for 10 different dependencies. I’ve removed my node_modules several times, but no result yet.
Is there any way I can get my project working again? Or should I just start another project?
Currently, this is my package.json file:
{
"name": "angular-ecommerce",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve --ssl=true --ssl-key=./ssl-localhost/localhost.key --ssl-cert=./ssl-localhost/localhost.crt",
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "ng test"
},
"private": true,
"dependencies": {
"@agm/core": "^3.0.0-beta.0",
"@angular/animations": "^15.0.0",
"@angular/common": "^15.2.4",
"@angular/compiler": "^15.0.0",
"@angular/core": "^10.0.0",
"@angular/forms": "^15.0.0",
"@angular/platform-browser": "^15.0.0",
"@angular/platform-browser-dynamic": "^15.0.0",
"@angular/router": "^15.0.0",
"@fortawesome/fontawesome-free": "^6.2.1",
"@ng-bootstrap/ng-bootstrap": "^14.0.1",
"@okta/okta-angular": "^5.2.0",
"@okta/okta-auth-js": "^6.4.0",
"@okta/okta-signin-widget": "^6.2.0",
"bootstrap": "^5.2.3",
"bootstrap-datepicker": "^1.9.0",
"jquery": "^3.6.4",
"rxjs": "^7.4.0",
"stripe": "^8.179.0",
"tslib": "^2.3.0",
"zone.js": "~0.12.0"
},
"devDependencies": {
"@angular-devkit/build-angular": "^15.2.4",
"@angular/cli": "^15.2.4",
"@angular/compiler-cli": "^12.0.0",
"@angular/localize": "^15.1.3",
"jasmine-core": "~4.5.0",
"karma": "~6.4.0",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage": "~2.2.0",
"karma-jasmine": "~5.1.0",
"karma-jasmine-html-reporter": "~2.0.0",
"typescript": "~4.8.2"
}
}
Downgrading, upgrading dependencies, npm audit fix --force, npm update, ng update, all I could find on the internet, nothing works yet
dummy text
A template engine enables you to use static template files in your application. At runtime, the template engine replaces variables in a template file with actual values, and transforms the template into an HTML file sent to the client. This approach makes it easier to design an HTML page.
A template engine enables you to use static template files in your application. At runtime, the template engine replaces variables in a template file with actual values, and transforms the template into an HTML file sent to the client. This approach makes it easier to design an HTML page.
A template engine enables you to use static template files in your application. At runtime, the template engine replaces variables in a template file with actual values, and transforms the template into an HTML file sent to the client. This approach makes it easier to design an HTML page.
A template engine enables you to use static template files in your application. At runtime, the template engine replaces variables in a template file with actual values, and transforms the template into an HTML file sent to the client. This approach makes it easier to design an HTML page.
$Preset = {
regex: {
imports: /{{s*#imports+['|"|`](.*?)['|"|`]s*}}/g,
comment: /{{!--(.*?)--}}/gms,
array: /(.*)->(.*)/g,
open: "{{",
clse: "}}",
},
}
class Preset {
constructor(str, data = {}, fetch = false) {
this.code = str.replace($Preset.regex.comment, "");
this.data = data;
this.fetch = fetch;
this.count = 0;
}
__clean(str) {
str = str.replace(/</g, "<");
str = str.replace(/>/g, ">");
str = str.replace(/"/g, '"');
str = str.replace(/'/g, "'");
str = str.replace(/&/g, "&");
str = str.replace(/n/g, "");
str = str.replace(/s+/g, " ");
return str.trim();
}
__array(args) {
var match = null,
key = "_",
value = args.slice(2).join(" ");
if (match = $Preset.regex.array.exec(value)) {
key = match[1];
value = match[2];
}
return {
key,
value
};
}
__shape(arr) {
return arr
.map((str) => {
str = this.__place(str);
if (str.startsWith("<js:code>")) return str.slice(9);
if (str[0] !== "#") return "$TXT+='{(@>_<@)}';$JSX.push(" + str + ");";
const args = str
.slice(1)
.split(" ")
.map((e) => e.trim().length && e.trim());
const act = args.shift();
const {
key,
value
} = this.__array(args);
switch (act) {
case "if":
$TYPE = "if";
return "if(" + args.join(" ") + "){";
case "elif":
return "} else if(" + args.join(" ") + "){";
case "unless":
return "if(!(" + args.join(" ") + ")){";
case "while":
return "while(" + args.join(" ") + "){";
case "until":
return "while(!(" + args.join(" ") + ")){";
case "switch":
return "switch(" + args.join(" ") + "){";
case "case":
return "break;case " + args.join(" ") + ":";
case "default":
return "break;default:";
case "range":
return "$RANGE(" + args[2] + "," + args[4] + "," + args.includes("through") + ", function(" + args[0] + ", $LOOP){";
case "each":
return "$EACH(" + args[0] + ",function(" + key + "," + value + ", $LOOP){";
case "forelse":
$TYPE = "for";
return "if($LENGTH(" + args[0] + ")){$EACH(" + args[0] + ",function(" + key + "," + value + ", $LOOP){";
case "set":
return "var " + args.join(" ") + ";";
case "alert":
return "alert(" + args.join(" ") + ");";
case "log":
case "info":
case "warn":
case "error":
case "debug":
return "console." + act + "(" + args.join(" ") + ");";
case "else":
return ($TYPE === "for" ? "});" : "") + "}else{";
case "/each":
case "/range":
return "});";
case "js":
case "/js":
return "";
case "/switch":
return "break;}";
case "/if":
case "/while":
case "/unless":
case "/until":
case "/forelse":
return "}";
}
})
.filter((str) => str && str.length > 0);
}
__place(str) {
str = str.replaceAll(/(@loop)(?=(?:[^'"`]|["'`][^'"`]*["'`])*$)/g, "$LOOP");
str = str.replaceAll(/(@self)(?=(?:[^'"`]|["'`][^'"`]*["'`])*$)/g, "$SELF");
str = str.replaceAll(/(@)(?=(?:[^'"`]|["'`][^'"`]*["'`])*$)/g, "$HELPERS.");
str = str.replaceAll(/([.]+[wd-_]+)(?=(?:[^'"`]|["'`][^'"`]*["'`])*$)/g, (e) => "['" + e.slice(1) + "']");
return str;
}
__parse(str) {
const data = {
txt: [],
jsx: [],
};
var state = $Preset.regex.open,
index = -1;
str = this.__clean(str).replaceAll($Preset.regex.comment, "");
while (str.length) {
switch (state) {
case $Preset.regex.open:
index = str.indexOf($Preset.regex.open);
if (index > -1) {
var code = str.slice(0, index);
if (["#js"].includes(data.jsx[data.jsx.length - 1])) data.jsx.push("<js:code>" + code);
else data.txt.push(code);
str = str.slice(index);
state = $Preset.regex.clse;
} else {
str.length && data.txt.push(str);
str = "";
}
case $Preset.regex.clse:
index = str.indexOf($Preset.regex.clse);
if (index > -1) {
index = this.__last(str, index);
var code = str.slice(state.length, index).trim();
data.jsx.push(code);
str = str.slice(index + state.length);
state = $Preset.regex.open;
} else {
str.length && data.jsx.push(str);
str = "";
}
}
}
return data;
}
__last(str, index) {
if (str[index + 2] === $Preset.regex.clse[0]) index = index + 1;
else return index;
return this.__last(str, index);
}
__token(str) {
var code = "";
const data = this.__parse(str);
data.jsx = this.__shape(data.jsx);
data.txt.forEach((e, i) => {
e.trim().length && (code += "$TXT+=`" + e + "`;");
if (data.jsx[i] && data.jsx[i - 1] && data.jsx[i].startsWith("break;") && data.jsx[i - 1].startsWith("switch"))
code += data.jsx[i].substr(6);
else
code += data.jsx[i];
});
return code;
}
__bind(object) {
for (var fn in object) {
if (typeof object[fn] === "function")
object[fn] = object[fn].bind(this.data);
else this.__bind(object[fn]);
}
}
__run(type) {
const str = this.__token(this.code);
this.__bind($HELPERS);
const res = new Function(
"",
"return function($SELF, $HELPERS) {" +
"var $TXT = '', $JSX = [], $EACH = (obj, func) => {if (obj === null) {return obj;}let index = -1;if (Array.isArray(obj)) {const length = obj.length;let count = 1;while (++index < length) {if (func(index, obj[index], {round: count,index: count - 1,}) === false) {break;}count++;}}let key = Object.keys(obj);const length = key.length;let count = 1;while (++index < length) {if (func(key[index], obj[key[index]], {round: count,index: count - 1,}) === false) {break;}count++;}}, $RANGE = (from, to, inc, func) => {to = inc ? (from < to ? to + 1 : to - 1) : to; for (let i = from; from < to ? i < to : i > to; from < to ? i++ : i--) {func(i, {round: i + 1,index: i});}}, $LENGTH = (obj) => {if (obj === null) return obj;if (Array.isArray(obj)) return obj.length;Object.keys(obj).length};" +
" with($SELF || {}) { try {" +
str +
" } catch(e) { console.error(e); }}return [$TXT.split('{(@>_<@)}'), ...$JSX];}"
)()(this.data, $HELPERS);
if (type === "html") {
const parts = res.shift();
return parts.reduce((acc, part, i) => {
return acc + part + (res[i] || "");
}, "");
}
return new Jsx(...res).exec();
}
exec(type) {
if (this.fetch) {
return new Promise(async res => {
this.code = await this.__include(this.code);
res(this.__run(type));
});
}
return this.__run(type);
}
async __fetch(path) {
const newpath = "/views/" + path.replaceAll(".", "/") + ".dust.html";
if (!$MEMORY[path]) {
const r = await fetch(newpath);
$MEMORY[path] = r.status === 200 ? this.__clean(await r.text()) : "";
}
return $MEMORY[path];
}
async __include(code) {
code = code.replace($Preset.regex.comment, "");
const matches = [];
code = code.replace(/{{s*#imports+['|"|`](.*?)['|"|`]s*}}/g, (_, path) => {
const hold = "___import__placement__code__" + (this.count++) + "___"
matches.push({
path,
hold
});
return hold;
});
for (var match of matches) {
var _code = await this.__fetch(match.path);
code = code.replace(match.hold, _code);
code = await this.__include(code);
}
return code;
}
}
i am triyin to make my code more clean and efficent but im stuck
As we can use devServer from webpack to proxy on a target , but if we have to change our proxy we have to rebuild the wholeapp, is there any option to not build again ?
I have a react app ,which i’m building using webpack and serving locally using webpack’s devServer;
my export config (not complete) –
module.exports = () => ({
devServer: {
// Webpack development server. Also handles API proxying for local development
client: {
overlay: true,
},
devMiddleware: {
stats: {
preset: 'minimal',
moduleTrace: true,
errorDetails: true,
assets: false,
},
},
static: {
directory: paths.buildPath,
serveIndex: true,
watch: true,
},
historyApiFallback: {
disableDotRule: true,
},
hot: true,
https: true,
port: PORT,
proxy: {
'/api': {
changeOrigin: true,
secure: false,
target: 'https://example.com',
},
},
},
}
If we see above devServer config we have a proxy target: https://example.com, if i want to change it to https://anotherexample.com when server is running (means i have ran npm start) , it will show no effect.
Now to get these changes reflected , i have to rebuild the app
I get the data from the mongodatabase with app get, without using a button,when i open the page, The label is written to the website with <%= result %>, but I want them to be written to the website when a button is pressed, and I have no idea how to solve this, can you help?
ejs file :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<style>
.democlass {
display: block;
width: 100%;
height: 34px;
padding: 6px 12px;
font-size: 14px;
line-height: 1.42857143;
color: #555;
background-color: #fff;
background-image: none;
border: 1px solid #ccc;
border-radius: 4px;
margin-top: 10px;
margin-bottom: 10px;
}
</style>
<body>
<h1>Posting data to mongo</h1>
<form class="containter" id="container" method="post" action="/">
<div id="divInputs">
<div class="form-group">
<input class="form-control" name="title" id="title1">
</div>
<div class="form-group">
<input class="form-control" name="content" id="title2">
</div>
</div>
<button>add mobgodb</button>
</form>
<button type="button" id="btnCreateInput">Yeni Input</button>
<button type="button" value="Result" onclick="getData()">Birleştir</button>
<form class="containter" method="post" action="/">
</form>
<div>
<br>
<br>
<br>
<p><%= result %></p>
</div>
<script>
let inputCount = 0;
const divInputs = document.getElementById('divInputs');
document.getElementById('btnCreateInput').addEventListener("click", function () {
inputCount++;
const newInput = document.createElement('input');
newInput.type = "text";
newInput.id = "input" + inputCount;
newInput.className = "form-control";
newInput.name = "text" + inputCount;
const newDiv = document.createElement('div');
newDiv.id = "div" + inputCount;
newDiv.className = "form-group";
newDiv.appendChild(newInput);
divInputs.appendChild(newDiv);
})
</script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/browser.min.js"></script>
<script src="server.js"></script>
</body>
</html>
js file :
const express = require('express');
const mongoose = require('mongoose');
const app = express();
const ejs = require('ejs');
app.set('view engine', 'ejs');
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }))
const url = ;
mongoose.connect(url, { useNewUrlParser: true, useUnifiedTopology: true })
.then((result) => console.log("Basarili"))
.catch((err) => console.log(err))
const notesSchema = {
text1: String,
text2: String,
text3: String,
text4: String,
text5: String,
text6: String,
text7: String,
text8: String,
text9: String,
text10: String,
text11: String,
text12: String,
text13: String,
text14: String,
text15: String,
}
const resultsSchema = {
allSentence: String,
time: Number
}
const Result = mongoose.model("Result", resultsSchema);
const Note = mongoose.model("Note", notesSchema);
async function getItems(){
const Items = await Result.find({}).sort({_id:-1}).limit(1);
return Items;
}
app.get("/", function (req, res) {
getItems().then(function(FoundItems){
res.render('index', {resultsList: FoundItems});
});
})
app.post("/", function(req, res) {
let newNote = new Note({
text1: req.body.title,
text2: req.body.content,
text3: req.body.text1,
text4: req.body.text2,
text5: req.body.text3,
text6: req.body.text4,
text7: req.body.text5,
text8: req.body.text6,
text9: req.body.text7,
text10: req.body.text8,
text11: req.body.text9,
text12: req.body.text10,
text13: req.body.text11,
text14: req.body.text12,
text15: req.body.text13,
});
newNote.save();
res.redirect('/');
})
app.listen(5500, function(){
console.log("server is running on 5500");
})
var cumle = "";
async function getData(){
try {
const post = await Result.find({}).sort({_id:-1}).limit(1);
console.log(post);
} catch (error) {
console.log(error.message);
}
}
function display() {
alert("Hello world!");
}
getData();
I try onclik method but it s not working.