I see a lot of people start a component like:
export default function Example(){XYZ}
Is that the same as writing the function and then exporting at the bottom of the page like so?
function Example(){XYZ};
export default Example
Blancer.com Tutorials and projects
Freelance Projects, Design and Programming Tutorials
Category Added in a WPeMatico Campaign
I see a lot of people start a component like:
export default function Example(){XYZ}
Is that the same as writing the function and then exporting at the bottom of the page like so?
function Example(){XYZ};
export default Example
next build
▲ Next.js 14.2.25
Creating an optimized production build …
✓ Compiled successfully
Linting and checking validity of types ..Failed to compile.
./components/HomeCard.tsx:43:12
Type error: ‘Icon’ cannot be used as a JSX component.
Its return type ‘ReactNode’ is not a valid JSX element.
41 | />
42 | ) : Icon && (
43 |
| ^
44 | )}
45 |
46 |
Next.js build worker exited with code: 1 and signal: null
Linting and checking validity of types . ELIFECYCLE Command failed with exit code 1.
I’m working on a Node.js project using TypeScript and the amqplib package (currently at version 0.10.5). When I try to create a connection and channel in my RabbitMQ configuration file, TypeScript throws the following errors:
import * as amqp from 'amqplib';
import { Connection, Channel } from 'amqplib';
export class RabbitMQConfig {
private static connection: Connection | null = null;
private static channel: Channel | null = null;
public static async connect(): Promise<void> {
if (!this.connection) {
this.connection = await amqp.connect('amqp://localhost');
this.channel = await this.connection.createChannel();
this.connection.on('close', () => {
console.error('RabbitMQ connection closed.');
});
this.connection.on('error', (err) => {
console.error('RabbitMQ connection error:', err);
});
console.log('RabbitMQ connected and channel created successfully.');
}
}
public static getChannel(): Channel {
if (!this.channel) {
throw new Error('RabbitMQ channel is not initialized. Call connect() first.');
}
return this.channel;
}
public static async closeConnection(): Promise<void> {
if (this.channel) {
await this.channel.close();
this.channel = null;
}
if (this.connection) {
await this.connection.close();
this.connection = null;
}
console.log('RabbitMQ connection closed.');
}
}
I don’t know what seems to be the issue since I did try importing the correct module but
TypeScript still complains that the methods close() and createChannel() do not exist on the Connection type.
Any suggestions on how to resolve this type of issue would be greatly appreciated.
import { StaticTimePicker } from '@mui/x-date-pickers/StaticTimePicker';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { DemoContainer } from '@mui/x-date-pickers/internals/demo';
<LocalizationProvider dateAdapter={AdapterDayjs}>
<DemoContainer components={['StaticTimePicker']}>
<StaticTimePicker
value={values.time}
onChange={(newValue) =>
handleChange({ target: { name: 'time', value: newValue } })
}
orientation="landscape"
defaultValue={dayjs(formattedDateTime)}
/>
</DemoContainer>
</LocalizationProvider>
How to change the size of the StaticTimePicker?
I tried by adding sx prop and slotProps as well but it is not working.
Im trying to use classes defined in a scss file in a vue component but doesn’t work
Here are the files:
_zero-state.scss
@use '../../variables' as *;
.zero-state {
display: flex;
flex-flow: column nowrap;
justify-content: center;
align-items: center;
padding: 80px;
&__image {
background-repeat: no-repeat;
background-position: center;
background-size: contain;
width: 208px;
height: 208px;
}
&__header {
margin-top: 20px;
// text-align: center;
}
&__content {
margin-top: 12px;
}
&--empty {
.zero-state__image{
background-image: url('#{$illustrations-path}empty.svg')
}
}
&--search {
.zero-state__image{
background-image: url('#{$illustrations-path}search.svg')
}
}
&--loading {
.zero-state__image{
background-image: url('#{$illustrations-path}empty.svg')
}
}
&--report {
.zero-state__image{
background-image: url('#{$illustrations-path}report.svg')
}
}
&--no-connection {
.zero-state__image{
background-image: url('#{$illustrations-path}no-connection.svg')
}
}
&--not-found-day {
.zero-state__image{
background-image: url('#{$illustrations-path}not-found-day.svg')
}
}
&--not-found-night {
.zero-state__image{
background-image: url('#{$illustrations-path}not-found-night.svg')
}
}
&--danger {
.zero-state__image{
background-image: url('#{$illustrations-path}danger.svg')
}
}
&--ice-pop {
.zero-state__image{
background-image: url('#{$illustrations-path}ice-pop.svg')
}
}
&--lost {
.zero-state__image{
background-image: url('#{$illustrations-path}lost.svg')
}
}
&--fingerprint {
.zero-state__image{
background-image: url('#{$illustrations-path}fingerprint.svg')
}
}
}
main.scss
@forward './variables';
@forward './mixins';
@forward './modules/zero-state/zero-state';
@forward './basics/colors/colors';
@forward './basics/flex/flex';
@forward './basics/typography/typography';
@forward './basics/grid/grid';
@forward './basics/icons/icons';
@forward './basics/logos/logos';
@forward './basics/text/text';
base-zero-state.vue
<script setup>
import { computed } from 'vue'
const props = defineProps({
header: {
type: String,
required: true
},
content: {
type: String,
required: true
},
color: {
type: String,
default: 'black'
},
empty: {
type: Boolean,
default: false
},
report: {
type: Boolean,
default: false
},
noConnection: {
type: Boolean,
default: false
},
notFound: {
type: Boolean,
default: false
},
danger: {
type: Boolean,
default: false
},
icePop: {
type: Boolean,
default: false
},
lost: {
type: Boolean,
default: false
},
fingerprint: {
type: Boolean,
default: false
},
search: {
type: Boolean,
default: false
}
})
const fontColor = computed(() => {
return 'color: ' + props.color
})
const objectClass = computed(() => {
const notFoundClass =
new Date().getHours() > 18 ? 'zero-state--not-found-night' : 'zero-state--not-found-day'
return {
'zero-state': true,
'zero-state--empty': props.empty,
'zero-state--search': props.search,
'zero-state--report': props.report,
'zero-state--danger': props.danger,
'zero-state--ice-pop': props.icePop,
'zero-state--lost': props.lost,
'zero-state--fingerprint': props.fingerprint,
'zero-state--no-connection': props.noConnection,
[notFoundClass]: props.notFound
}
})
</script>
<template>
<div :class="objectClass">
<div class="zero-state__image"></div>
<div class="zero-state__header">
<div :style="fontColor" class="h6-header content-title">{{ header }}</div>
</div>
<div :style="fontColor" class="zero-state__content content-title body-copy-bold grey500">
{{ content }}
</div>
<div class="zero-state__actions"></div>
</div>
</template>
vite.config.js
export default defineConfig({
css: {
preprocessorOptions: {
scss: {
// api: 'modern-compiler', // or "modern"
additionalData: `
@use "@/assets/scss/main.scss" as *;
`
}
}
},
})
package.json
"devDependencies": {
"@mdi/font": "^7.4.47",
"@rushstack/eslint-patch": "^1.2.0",
"@vitejs/plugin-vue": "^5.2.1",
"@vitest/coverage-c8": "^0.31.1",
"@vue/eslint-config-prettier": "^7.1.0",
"@vue/test-utils": "^2.3.2",
"eslint": "^8.39.0",
"eslint-plugin-vue": "^9.11.0",
"jsdom": "^22.0.0",
"prettier": "^2.8.8",
"sass": "^1.85.1",
"vite": "^6.2.1",
"vite-plugin-ejs": "^1.6.4",
"vitest": "^0.31.0"
}
I’ve missing something? I can use the colors defined in @forward ‘./basics/colors/colors’; in the proyect but no the classes defined @forward ‘./modules/zero-state/zero-state’;
I would like to remove classes of an element not with the function document.querySelector("#id").classList.remove("class") but with the function document.querySelector("#id").classes.del("class")
I was able to create an alias for the remove function and now I can use the function document.querySelector("#id").classList.del("class")
Option 1:
DOMTokenList.prototype.del = function () {
return DOMTokenList.prototype.remove.apply(this, Array.prototype.slice.call(arguments));
}
Option 2:
DOMTokenList.prototype.del = DOMTokenList.prototype.remove;
Please tell me which of these options is better.
But then I can’t create an alias for classList.
I tried the following options:
Element.prototype.classes = Element.prototype.classList;
Element.prototype.classes = DOMTokenList;
Element.prototype.classes = Object.create(DOMTokenList);
Element.prototype.classes = new DOMTokenList();
By using SubtleCrypto, I’m trying to create function for encrypting and decrypting data to make my http request and response to be encrypted to protect sensitive data from unauthorized access.
I send request via axios by doing below.
MyComponent.vue
const key = await this.generateKey();
const data = "Protected Request";
const { ciphertext, iv, tag } = await this.encryptData(key, data);
const exportedKey = await this.exportKey(key);
let dataObj = {}
dataObj.ciphertext = Buffer.from(ciphertext).toString('base64')
dataObj.iv = Buffer.from(iv).toString('base64')
dataObj.tag = Buffer.from(tag).toString('base64')
dataObj.key = Buffer.from(exportedKey).toString('base64')
const response = await axios.post('api/fetchingData', dataObj);
let result = response.data
MyController.php
public function store(Request $request){
$ciphertext = base64_decode($request->input('ciphertext'));
$iv = base64_decode($request->input('iv'));
$tag = base64_decode($request->input('tag'));
$key = base64_decode($request->input('key'));
//function to decrypt data.
/** Want to encrypt the return data to protect sensitive information from database */
$returnData = "This is sample return data to be encrypted";
$encryptedResponse = openssl_encrypt(
$returnData,
'aes-256-gcm',
$key,
OPENSSL_RAW_DATA,
$iv,
$tag
);
return response()->json([
'encryptedResponse' => base64_encode($encryptedResponse),
'iv' => base64_encode($iv),
'tag' => base64_encode($tag),
]);
}
If i console.log(result) to check the result, it shows below

Which seems correct, as it really encrypted data.
Now, i want to decrypt this result so i can use it on my webpage(example: table)
I do..
const importedKey = await this.importKey(exportedKey);
const resultData = new Uint8Array(atob(result.encryptedResponse).split("").map(c => c.charCodeAt(0)));
console.log("importedKey:", importedKey);
console.log("resultData:", resultData);
console.log("iv:", iv);
and give me this console result

But when I try to decrypt data, it gives me error below..
“Uncaught (in promise) OperationError”
This is how I do it and my decryptData() function
async fetchData(){
// Other codes(see above)..
const decryptedData = await this.decryptData(importedKey, resultData, iv);
console.log("Decrypted Data Result:", decryptedData);
},
async decryptData(key, encryptedData, myIV) {
try {
const decryptedData = await window.crypto.subtle.decrypt(
{
name: "AES-GCM",
iv: myIV,
tagLength: 128
},
key,
encryptedData // the content
);
return new TextDecoder().decode(decryptedData);
} catch (error) {
console.error("Decryption error:", error);
throw error;
}
},
How to do so I can decrypt the response.data or result? The value of show in console should be “This is sample return data to be encrypted.”, which is came from the encrypted data in controller.
I’m new to Next.js and I’m trying to send an email using an API route, but I’m facing an issue where I cannot access the API.
I have the following structure:
Even when I try to access the API manually by going to "https://localhost:3000/api/send-mail", I get a 404 Not Found error.
I’ve double-checked that the API route is in the correct directory and the file is set up properly with the POST handler. I also confirmed that I’m using the App Router in Next.js, but still, the route seems inaccessible.
Has anyone encountered a similar issue, or could you guide me on what might be causing this problem?
// src/app/api/send-mail/route.ts
import { NextResponse } from 'next/server';
import nodemailer from 'nodemailer';
export async function POST(req: Request) {
const { recipient, body } = await req.json();
if (!recipient || !body) {
return NextResponse.json({ error: 'Recipient and body are required' }, { status: 400 });
}
const transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: parseInt(process.env.SMTP_PORT || '587'),
secure: process.env.SMTP_PORT === '465',
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASS,
},
});
const mailOptions = {
from: process.env.SMTP_USER,
to: recipient,
subject: 'Test Email',
text: body,
};
try {
await transporter.sendMail(mailOptions);
return NextResponse.json({ message: 'Email sent successfully' });
} catch (error) {
return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
}
}
When I attempt to send a request to the API from the client-side, I cannot reach the endpoint.
How to fetch the Folder from Autodesk Construction Cloud?I have been fetched Hub Id and Project ID I want Folder ID and access the folder as shown in saem as ACC? Any JS developer can resolve my query?
I am sure it is something simple that I am not understanding but I don’t see the issue here.
In the code below I am using a button (#clickme) to trigger the file input (#image-input) to open a dialogue box to choose a file. I am doing this so I can style the button. That works. But because of what I am doing inside the change event (converting files and creating a new formData object), it doesn’t actually upload an image. It only works if you click on the actual file input (#file-input).
What am I missing here? How do I allow the use of a button to open the dialogue box but still get my file to upload via AJAX? I get no errors, just no file upload.
I believe the change event isn’t firing.
$("#clickme").on("click", function () {
$("#image-input").trigger("click");
});
$("#image-input").on("change", function (ev) {
var originalFile = ev.target.files[0];
if (
originalFile.type === "image/heic" ||
originalFile.name.toLowerCase().endsWith(".heic")
) {
heic2any({
blob: originalFile,
toType: "image/jpeg",
})
.then(function (resultBlob) {
var convertedFile = new File(
[resultBlob],
originalFile.name.replace(/.heic$/i, ".jpg"),
{ type: "image/jpeg" },
);
var formData = new FormData();
formData.append("image-input", convertedFile, convertedFile.name);
// formData.append('otherField', 'value');
uploadFile(formData);
})
.catch(function (x) {
var error = "Error code: " + x.code + " " + x.message;
console.log(error);
});
} else {
var formData = new FormData();
formData.append("image-input", originalFile, originalFile.name);
uploadFile(formData);
}
});
function uploadFile(formData) {
$.ajax({
url: base_url + "home/upload",
type: "POST",
data: formData,
dataType: "json",
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData: false,
success: function (response) {
console.log(response);
},
error: function (error) {
console.log(error);
},
});
}
I wanna make a website with dark mode, i want this website can still with dark mode, but i dont know to fix it, can anyone to help me?
i’ve been try with this code
const checkbox = document.getElementById("checkbox")
checkbox.addEventListener("change", () => {
document.body.classList.toggle("dark")
localStorage.setItem("checkbox", checkbox)
})
const inputType = () => {
let fullName = document.getElementById("fname").value
let email = document.getElementById("email").value
let messege = document.getElementById("messege").value
}
<form action="" method="post" id="formInput">
<label for="fname">Fullname: </label><br>
<input type="text" id="fname" name="fname"><br><br>
<label for="email">E-Mail: </label><br>
<input type="email" id="email" name="email"><br><br>
<label for="messege">Messege: </label><br>
<textarea name="messege" id="messege"></textarea><br>
<input type="submit" value="Submit" onclick="inputType()">
</form>
I am working on creating a mccabe thiele plotter (a chemical engineering topic) which will take some parameters as input and show a plot (using chartjs)
For this, I need to select one among two options ‘vol’ or ‘datapts’.
In vol mode (relative volatility mode), equilibrium data equi will be calculated from a equation and for datapts mode (equilibrium data), i need to provide equi data:
For toggling selection and automatically updating equi data:
useEffect(() => {
if (vol === 'datapts') addEqui([{x: 0, y: 0}, {x: 1, y: 1}])
else if (vol === 'vol' && alpha > 1) equi_rel_from_alpha();
}, [vol, alpha]);
function equi_rel_from_alpha() {
try {
let newEqui = []
let x
let y_eq
for (let i = round(0); round(i) <= 1; i += 0.1) {
x = round(i)
y_eq = (alpha * x) / (1 + (alpha - 1) * x)
newEqui.push({ x: x, y: Number(y_eq.toFixed(4)) })
}
addEqui(newEqui)
} catch (err) {
setErr('Error in finding equilibrium curve from alpha')
}
}
function round(el) {
return Math.round(el * 100) / 100
}
Azeo is a random function as to calculate how many times the equi data lines will cross y=x line:
const [azeo, setAzeo] = useState([])
function check_azeo(){
const xy = {a: 1, b: -1, c: 0}
const len = equi.length
let azeo_temp = []
let pos = 1
if(len>2){
let p1
let p2
let ln
while(pos+1!=len-1){
p1 = equi[pos]
p2 = equi[pos+1]
if((xy.a*p1.x + xy.b*p1.y + xy.c) == 0){
azeo_temp.push(p1.x)
}
else if((xy.a*p1.x + xy.b*p1.y + xy.c)*(xy.a*p2.x + xy.b*p2.y + xy.c)<0){
ln = line_from_2points(p1, p2)
azeo_temp.push(intersection_of_2lines(xy, ln).x)
}
pos += 1
}
}
setAzeo(azeo_temp)
}
Now once I have selected the mode, there will be parameters provided (D, F, etc.) and mccabe_thiele function will be called based on criteria and mode as below:
useEffect(() => {
if (D && F && xD && xF && q && op_ratio && q && vol && alpha && equi.length > 1) {
if (D > 0 && F > 0 && F > D && xF < 1 && xD < 1 && xF > 0 && xD > 0 && alpha > 1 && F * xF > D * xD && xD > xF && op_ratio > 1) {
if (vol === 'vol') {
setErr('')
mcCabe_thiele()
}
else if (vol === 'datapts') {
if(azeo.length > 0){
setErr('Cant plot for azeotropes')
}
else if (equi.length >= 5) {
setErr('')
mcCabe_thiele()
}
else setErr('Atleast 5 equilibrium points must be provided')
}
}
else if (alpha <= 1) setErr('Relative volatility must be greater than 1')
else if (D <= 0) setErr('Distillate rate must be greater than 0')
else if (F <= 0) setErr('Feed rate must be greater than 0')
else if (F < D) setErr('Feed rate must be greater than distillate rate')
else if (F * xF < D * xD) setErr('You are expecting more than you are feeding')
else if (xD <= xF) setErr('Distillate purity must be more than feed purity')
else if (op_ratio <= 1) setErr('Optimum ratio must be greater than 1')
else if (xD <= 0) setErr('Distillate purity cannot be zero')
else if (xD >= 1) setErr('Distillate cannot be completely pure')
else if (xF <= 0) setErr('Feed cannot be single component')
else if (xF >= 1) setErr('Feed cannot be single component')
}
}, [alpha, D, F, xD, xF, q, op_ratio, equi, azeo])
Here, D, F, xD, xF, q, opt_ratio are parameters and need not be worried about.
I am facing a very very weird issue:
When I am using vol mode, its working completely fine but mccabe thiele is being called twice.
When I am switching to datapts mode and entering valid equi data (5 points), its working fine but again mccabe thiele is called twice.
In case when I am intentionally using points in datapts mode where azeo is non-empty array, weirdly still mccabe_thiele function is being called (which shouldnt be the case when azeo.length>0) and stages are being drawn according to mccabe thiele method (but using equi data of vol mode). So system is using vol mode equi data for calculation when azeo is non-empty, I want the plot to not execute the mccabe thiele function in this case.
I know the problem is too long, but I want the solution. I am not using any strict mode, please help!!! (all parameter inputs are working fine)
McCabe_math.jsx
import { useEffect } from "react"
export default function McCabe_math({ D, F, xF, xD, q, vol, alpha, op_ratio, setW, setxW, addEqui, setR, setErr, equi, setSteps, setfdInter, setRm, setStages, azeo, setAzeo }) {
function round(el) {
return Math.round(el * 100) / 100
}
useEffect(() => {
setErr('')
}, [vol, D, F, xD, xF, q, op_ratio])
useEffect(() => {
if (vol === 'datapts') addEqui([{x: 0, y: 0}, {x: 1, y: 1}])
else if (vol === 'vol' && alpha > 1) equi_rel_from_alpha();
}, [vol, alpha]);
// useEffect(() => {
// if (azeo.length > 0) setErr('Azeotrope formation')
// }, [azeo])
useEffect(() => {
if (D && F && xD && xF && q && op_ratio && q && vol && alpha && equi.length > 1) {
if (D > 0 && F > 0 && F > D && xF < 1 && xD < 1 && xF > 0 && xD > 0 && alpha > 1 && F * xF > D * xD && xD > xF && op_ratio > 1) {
if (vol === 'vol') {
setErr('')
mcCabe_thiele()
}
else if (vol === 'datapts') {
if(azeo.length > 0){
setErr('Cant plot for azeotropes')
setStages([])
}
else if (equi.length >= 5) {
setErr('')
mcCabe_thiele()
}
else setErr('Atleast 5 equilibrium points must be provided')
}
}
else if (alpha <= 1) setErr('Relative volatility must be greater than 1')
else if (D <= 0) setErr('Distillate rate must be greater than 0')
else if (F <= 0) setErr('Feed rate must be greater than 0')
else if (F < D) setErr('Feed rate must be greater than distillate rate')
else if (F * xF < D * xD) setErr('You are expecting more than you are feeding')
else if (xD <= xF) setErr('Distillate purity must be more than feed purity')
else if (op_ratio <= 1) setErr('Optimum ratio must be greater than 1')
else if (xD <= 0) setErr('Distillate purity cannot be zero')
else if (xD >= 1) setErr('Distillate cannot be completely pure')
else if (xF <= 0) setErr('Feed cannot be single component')
else if (xF >= 1) setErr('Feed cannot be single component')
}
}, [alpha, D, F, xD, xF, q, op_ratio, equi, azeo])
function equi_rel_from_alpha() {
try {
let newEqui = []
let x
let y_eq
for (let i = round(0); round(i) <= 1; i += 0.1) {
x = round(i)
y_eq = (alpha * x) / (1 + (alpha - 1) * x)
newEqui.push({ x: x, y: Number(y_eq.toFixed(4)) })
}
addEqui(newEqui)
} catch (err) {
setErr('Error in finding equilibrium curve from alpha')
}
}
function line_from_2points(p1, p2) {
let x1 = p1.x
let y1 = p1.y
let x2 = p2.x
let y2 = p2.y
let m = (y2 - y1) / (x2 - x1)
return { a: m, b: -1, c: y1 - m * x1 }
}
function closestPoint(a, b, c) {
let init = Math.abs(c / (Math.pow(a * a + b * b, 0.5)))
let min = { val: init, pt: { x: 0, y: 0 } }
for (let el of equi) {
let xi = el.x
let yi = el.y
let dist = Math.abs((a * xi + b * yi + c) / (Math.pow(a * a + b * b, 0.5)))
if (dist == 0) return { x: xi, y: yi, ptr: 'exact', dist: 0 } //when the intersection is an actual data point
else if (dist < min.val) {
min.val = dist
min.pt = { x: xi, y: yi }
}
}
return { x: min.pt.x, y: min.pt.y, ptr: 'non-exact', dist: min.val }
}
function sideofPoint(xi, yi, a, b, c) {
let s_origin = a * 0 + b * 0 + c
let s_point = a * xi + b * yi + c
if (s_origin * s_point < 0) return 'right'
else if (s_origin * s_point > 0) return 'left'
}
function complementaryPoint(xi, side) {
const index = equi.findIndex(el => el.x === xi)
if (side === 'right') return equi[index - 1]
else if (side === 'left') return equi[index + 1]
}
function intersection_of_2lines(l1, l2) {
let a1 = l1.a
let b1 = l1.b
let c1 = l1.c
let a2 = l2.a
let b2 = l2.b
let c2 = l2.c
return { x: (b1 * c2 - b2 * c1) / (a1 * b2 - a2 * b1), y: (a2 * c1 - a1 * c2) / (a1 * b2 - a2 * b1) }
}
function q_line() {
try {
if (Number(q) === 1) return { a: 1, b: 0, c: Number(-xF) }
else {
let feed_slope = (-1) * (q / (1 - q))
return { a: (-1) * feed_slope, b: 1, c: xF * (feed_slope - 1) }
}
} catch (err) {
setErr('Error in finding q line')
}
}
function feed_intersection() {
try {
let feed_slope
let closestPt
let side
let compPt
if (Number(q) === 1) {
//feed line eqn: x + 0*y - xF = 0
closestPt = closestPoint(1, 0, -1 * (xF))
if (closestPt.ptr === 'exact') return { x: closestPt.x, y: closestPt.y }
else {
side = sideofPoint(closestPt.x, closestPt.y, 1, 0, -1 * (xF))
}
}
else {
//feed line eqn: (-feed_slope)x + y + xF(feed_slope - 1) = 0
feed_slope = (-1) * (q / (1 - q))
closestPt = closestPoint((-1) * feed_slope, 1, xF * (feed_slope - 1), equi)
if (closestPt.ptr === 'exact') return { x: closestPt.x, y: closestPt.y }
else {
side = sideofPoint(closestPt.x, closestPt.y, (-1) * feed_slope, 1, xF * (feed_slope - 1))
}
}
compPt = complementaryPoint(closestPt.x, side)
let comp_line = line_from_2points(closestPt, compPt)
if (Number(q) === 1) return intersection_of_2lines(comp_line, { a: 1, b: 0, c: (-1) * Number(xF) })
else return intersection_of_2lines(comp_line, { a: (-1) * feed_slope, b: 1, c: xF * (feed_slope - 1) })
} catch (err) {
setErr('Error in finding feed intersection with curve')
}
}
function step_intersection(yi) {
let snap = -1;
for (let i = 0; i < equi.length; i++) {
if (equi[i].y === yi) return { x: equi[i].x, y: equi[i].y }; // Exact match
if (equi[i].y > yi) {
snap = i;
break; // Stop at the first point where y > yi
}
}
// If `yi` is outside the range, return null
if (snap === -1 || snap === 0) return null; // No valid intersection
let p1 = equi[snap - 1];
let p2 = equi[snap];
let l1 = line_from_2points(p1, p2);
let l2 = { a: 0, b: 1, c: -yi };
return intersection_of_2lines(l1, l2);
}
function mcCabe_thiele() {
console.log('mct called')
//top_composition
let top_compo = { x: xD, y: xD }
//to find out the intersection point of feed line with equilibrium curve after finding closest and complementary eq. data points and interpolation
const feed_equi = feed_intersection()
//q-line
let q_ln = q_line()
//pinch calculations
let pinch_slope = (feed_equi.y - top_compo.y) / (feed_equi.x - top_compo.x)
let Rmin = pinch_slope / (1 - pinch_slope)
setRm(Rmin)
let Ropt = Rmin * op_ratio
setR(Ropt)
let rect_slope = Ropt / (Ropt + 1)
let rect = { a: (-1) * rect_slope, b: 1, c: xD * (rect_slope - 1) }
//intersection of feed and rectifying line
let feed_rect_intersection = intersection_of_2lines(q_ln, rect)
try {
setfdInter(feed_rect_intersection)
} catch (err) {
setErr('Error in finding feed and rectification line intersection')
}
//stripping line
let W = F - D
setW(W)
let xW = (F * xF - D * xD) / W
setxW(xW)
let bottom_compo = { x: xW, y: xW }
let strip = line_from_2points(feed_rect_intersection, bottom_compo)
//steps calculation
let step_pts = []
let x_curr = xD
let y_curr
let stage = 'rect'
let check
let next
try {
while (true) {
//rectifying area
if (stage === 'rect') {
//horizontal step
y_curr = (-1) * (rect.a * x_curr + rect.c) / (rect.b)
//check if stripping zone is reached after last vertical dip
check = sideofPoint(x_curr, y_curr, q_ln.a, q_ln.b, q_ln.c)
if (check === 'left') {
stage = 'strip'
continue
}
step_pts.push({ x: x_curr, y: y_curr })
//if stripping zone is not reached
next = step_intersection(y_curr)
x_curr = next.x
y_curr = next.y
check = sideofPoint(x_curr, y_curr, q_ln.a, q_ln.b, q_ln.c)
if (check === 'left') {
step_pts.push({ x: x_curr, y: y_curr })
stage = 'strip'
continue
}
step_pts.push({ x: x_curr, y: y_curr })
//vertical step
next = intersection_of_2lines(rect, { a: 1, b: 0, c: -1 * x_curr })
x_curr = next.x
}
if (stage === 'strip') {
//horizontal step
y_curr = (-1) * (strip.a * x_curr + strip.c) / (strip.b)
if (x_curr < xW) {
step_pts.push({ x: x_curr, y: x_curr })
break
}
step_pts.push({ x: x_curr, y: y_curr })
next = step_intersection(y_curr, equi)
x_curr = next.x
y_curr = next.y
step_pts.push({ x: x_curr, y: y_curr })
//vertical step
next = intersection_of_2lines(strip, { a: 1, b: 0, c: -1 * x_curr })
x_curr = next.x
}
}
setSteps(step_pts)
setStages(() => Math.floor(step_pts.length / 2))
}
catch (err) {
console.log(err)
setErr('Error in step calculation')
}
}
return (
<>
</>
)
}
Mccabe_plot.jsx
import { Line } from 'react-chartjs-2';
import { Chart as ChartJS, CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend } from 'chart.js';
import { useState, useEffect } from 'react';
export default function Mccabe_plot({ xW, xD, xF, fdInter, equi, steps, err, vol }) {
ChartJS.register(
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend
);
const [x_eq, addx_eq] = useState([]);
const [y_eq, addy_eq] = useState([]);
const [x_steps, addx_steps] = useState([]);
const [y_steps, addy_steps] = useState([]);
const [chartData, setChartData] = useState(null);
useEffect(() => {
if (xD < 1 && xD>0 && xW > 0 && xW<1 && xF > 0 && xF < 1 && xD>xF && xF>xW) {
if((vol==='vol' && err === '')||(vol==='datapts')){
setChartData(equi.length>=5?{
datasets: [
{
label: 'x_eq vs y_eq',
data: equi.map((point) => ({
x: Number(point.x).toFixed(4),
y: Number(point.y).toFixed(4),
})),
fill: false,
borderColor: 'rgba(75, 192, 192, 1)',
tension: 0.1,
},
{
label: 'Steps',
data: steps.map((point) => ({
x: Number(point.x).toFixed(4),
y: Number(point.y).toFixed(4),
})),
fill: false,
borderColor: 'brown',
tension: 0.1,
},
{
label: 'Enriching Line',
data: [
{ x: xD, y: xD },
{ x: fdInter.x, y: fdInter.y },
],
fill: true,
borderColor: 'red',
tension: 0.1,
},
{
label: 'Stripping Line',
data: [
{ x: xW, y: xW },
{ x: fdInter.x, y: fdInter.y },
],
fill: true,
borderColor: 'blue',
tension: 0.1,
},
{
label: 'Feed Line',
data: [
{ x: xF, y: xF },
{ x: fdInter.x, y: fdInter.y },
],
fill: true,
borderColor: 'grey',
tension: 0.1,
},
{
label: 'x=y',
data: [
{ x: 0, y: 0 },
{ x: 1, y: 1 },
],
fill: true,
borderColor: 'black',
tension: 0.1,
}
]
}:
{
datasets: [
{
label: 'x_eq vs y_eq',
data: equi.map((point) => ({
x: Number(point.x).toFixed(4),
y: Number(point.y).toFixed(4),
})),
fill: false,
borderColor: 'rgba(75, 192, 192, 1)',
tension: 0.1,
},
{
label: 'Enriching Line',
data: [
{ x: xD, y: xD },
{ x: fdInter.x, y: fdInter.y },
],
fill: true,
borderColor: 'red',
tension: 0.1,
},
{
label: 'Stripping Line',
data: [
{ x: xW, y: xW },
{ x: fdInter.x, y: fdInter.y },
],
fill: true,
borderColor: 'blue',
tension: 0.1,
},
{
label: 'Feed Line',
data: [
{ x: xF, y: xF },
{ x: fdInter.x, y: fdInter.y },
],
fill: true,
borderColor: 'grey',
tension: 0.1,
},
{
label: 'x=y',
data: [
{ x: 0, y: 0 },
{ x: 1, y: 1 },
],
fill: true,
borderColor: 'black',
tension: 0.1,
}
]
});
}
}
}, [equi, steps, err, xD, xW, xF, vol]);
const options = {
responsive: true,
scales: {
x: {
type: 'linear',
position: 'bottom',
title: {
display: true,
text: 'X',
font: {
size: 15,
weight: 'normal',
},
grid: {
borderColor: 'black',
borderWidth: 5,
},
}
},
y: {
beginAtZero: true,
title: {
display: true,
text: 'Y',
font: {
size: 15,
weight: 'normal',
},
},
},
},
};
return (
<div>
{chartData ? (
<Line data={chartData} options={options} width={600} height={570} />
) : (
<p>Invalid input values. Chart not updated.</p>
)}
</div>
);
}
I am working on a project where I need to establish a WebSocket connection between a Java backend and a JavaScript frontend. Additionally, I need to interact with a database within this WebSocket connection.
I have a project in react-native with expo, it was working correctly, when suddenly it does not recognize the index, which is the main file of my project, Expo forces me to create an index file even though it still does not recognize it, I am lost.
I’m using PowerShell to find ignored files in my Git repository that belong to a specific directory, company_logos. I’m running the following command in my project folder:
powershell
Copy
Edit
git ls-files –ignored –others –exclude-standard | Select-String “company_logos”
However, I get this error:
vbnet
Copy
Edit
Select-String : The string company_logos is not a valid regular
expression: parsing “company_logos” – Illegal at end of pattern.
At line:1 char:54
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
What I’ve tried:
Escaping the backslashes:
powershell
Copy
Edit
git ls-files –ignored –others –exclude-standard | Select-String “company_logos”
But I still get the same issue.
Using single quotes:
powershell
Copy
Edit
git ls-files –ignored –others –exclude-standard | Select-String ‘company_logos’
This also didn’t work.
Using -SimpleMatch:
powershell
Copy
Edit
git ls-files –ignored –others –exclude-standard | Select-String -SimpleMatch “company_logos”
This worked, but I want to understand why the original command failed and how to properly escape it.
Question:
Why does Select-String throw the “Illegal at end of pattern” error in my original command?
What is the correct way to search for a directory name like company_logos in this context?
Any insights would be appreciated!