How do you connect 2 diferent languages or more

It may sound silly but Im a beginner and still trying to learn more. Many websites now days use many languages in their backend and frontend, such as python, C# for database and others. How do you connect 1 and another programming languages, like for an example if a user click the login button, it will trigger the javascript function and do lookup in the database with python or C# for an example, How do you guys connect that 2 different languages?

I’ve read and watch several things but still curious

Using React-router-dom gives 404 error on github pages

I have been attempting to put my react js router project onto github pages but for some reason it keeps giving me a 404 error. It works locally hosted on my machine, I am also using a custom domain for github sites, im not sure if this makes a difference. Can anyone help? I am new to this and some help would be much appreciated!

Index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.****
reportWebVitals();

App.js

import React from 'react';
import { BrowserRouter as Router, Routes, Route} from 'react-router-dom';
import Login from './pages/Login';
import Success from './pages/Success';
import Home from './pages/Home';
import Other from './pages/Other';
import Error from './pages/Error';
import NavBar from './componenets/NavBar';

function App() {
  return (
    <>
      <Router>
      <NavBar/>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/other" element={<Other />} />
        <Route path="/auth/success" element={<Success />} />
        <Route path="*" element={<Error />} />
        <Route path="/login" element={<Login />} />
      </Routes>
      </Router>
    </>
  );
}

export default App;

package.json

{
  "name": "client",
  "homepage": ".",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@supabase/auth-ui-react": "^0.4.6",
    "@supabase/auth-ui-shared": "^0.1.8",
    "@supabase/supabase-js": "^2.38.4",
    "@testing-library/jest-dom": "^5.17.0",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "react-dom": "^18.2.0",
    "react-router-dom": "6.4",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "predeploy": "npm run build",
    "deploy": "gh-pages -d build",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "gh-pages": "^6.0.0"
  }
}

I have looked at many different posts and tutorials but I cant seem to fix it.

React dot notation component passing between components

How to pass Parent props boolean in to child component when using dot notation with functional component.

Component structure is

<Dropdown className="float-right">
  <Dropdown.Title>Open menu</Dropdown.Title>
  <Dropdown.Menu align="end">
    <Dropdown.Item className="hello mate" href="/dashboard">
      Dashboard
    </Dropdown.Item>
    <Dropdown.Item className="hello mate" href="/settings">
      Settings
    </Dropdown.Item>
    <Dropdown.Divider />
    <Dropdown.Item className="hello mate" onClick={signOut}>
      Sign out
    </Dropdown.Item>
  </Dropdown.Menu>
</Dropdown>

Child component <Dropdown.Title> has OnClick to open `<Dropdown.Menu>

const DropdownTitle = (props) => {
  const { children, className } = props;
  const [openDropdown, setOpenDropdown] = useState(false);
  const toggleDropdown = () => setOpenDropdown(!openDropdown);
  return (
    <button type="button" onClick={toggleDropdown}>{children}</button>
  );
};

How to pass the openDropdown prop to <Dropdown.Menu> from <Dropdown.Title>

Edit young-smoke-c9glwr

Display file and number from electron-log

I would like to display the file and line number where I call an electron-log function from in the developer tools console. Currently it just displays console.js:77 to the right of each log, which is where electron-log internally logs to the developer tools console from.

I could just call the two functions like I have below to determine where the log is coming from and continue to log to file at the same time, but a single line solution would be preferable. Any suggestions would be appreciated.

console.log(message)
log.info(message)

Limit spaces in input HTML field

I’m writing a website using React and I’ve encountered an interesting problem.

I have a simple component in which the user can enter text. This component is implemented using an HTML input field.

 const Title = () => {
  return (
      <span>
        Name title
      </span>
      <input
        id="name_title"
        onChange={(event) => setNameTitle(event.target.value)}
        value={NameTitle}
      />
  );
};

export default Title;

My problem is handling spaces. By default, spaces are not processed in any way and, accordingly, the user can enter any number of them. But as you understand, this is not correct. I would like to :

  1. Prohibit starting input in a field with spaces. That is, so that the user cannot enter a space as the first character in the field;
  2. Limit the number of spaces between words. No more than one. That is, a space cannot be followed by a space.

I think this is a very useful thing, but unfortunately I found absolutely no information on this issue. Tell me how to solve this problem

FCM Token on iOS Safari Changing Frequently

I’m working on adding Firebase Cloud Messaging to my web app, and I’m a bit confused about when to get the device token. Right now, I’m getting it every time someone opens a page in my app, but I’m not sure if that’s the right way.

Especially on iOS Safari, I’m facing issues. I’ve noticed that the token changes often, even though information online suggests it shouldn’t (https://github.com/firebase/firebase-js-sdk/issues/4132). Unfortunately, I can’t pinpoint when or why these changes happen. In my view, I find it necessary to check the token every time the app is called to address this challenge. However, I’m still a bit puzzled about the frequent changes and their reasons.

Also, I’m wondering if there’s a way to determine whether the token returned by getToken is freshly generated or an old one. This information would be valuable in deciding whether I should send it back to my server for storage. Currently, I’m sending it back every time, causing a significant amount of unnecessary overhead. Any insights or suggestions on optimizing this process would be greatly appreciated.

Thanks!

setting cookies between two different domains

before asking this question I’ve searched a lot of related questions without any answer to what I want, I have a NextJS client app running on http://localhost, and a NestJS backend app running on a islamabdelhakiim.xyz domain in which I’ve built an api endpoint to handle the /login as follows “note the session & login creating”


    public async login(emp: CreateAuthDto, res?: Response, req?: Request): Promise<Employee> {
        const { email, password, rememberMe } = emp;
        const hashedPassword = EmployeesService.hash(password);

        const user = await this.employeesModel.findOne({ email, password: hashedPassword });
        if (!user) throw new NotFoundException("user not exists!");

        const userId = user._id;

        // set expiry
        let expiry: Date = rememberMe ? new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 30 : new Date().getTime() + 1000 * 60 * 60 * 24 * 7;

        //create the session(
        const session = new this.sessinoModel<Session>({ expiry, userId });
        const saved = await session.save()
        const sessionId = saved._id.toString();
        
        //create the cookie
        res.cookie('session', sessionId, {
            expires: expiry,
            sameSite: "none",
            secure: true,
        });
        res.cookie('user', userId.toString(), {
            sameSite: "none",
            secure: true,
        });
        res.status(200);
        return user;

    } 

the thing is after many different attempts to set the cookies using my client app : **http**://localhost with the secure flag as false, the browser refused to create the cookies because of the same origin policy.

so, I’ve transformed my Nextjs app into **https**://localhost and the secure flag into true, and then the server successfully created the cookies, but with islamabdelhakiim.xyz for its domain, and despite having the cookies into the browser, the Next app couldn’t read them because of the domain, and I noticed that if I manually changed the cookie’s domain into localhost it can be read by my Next app,

so I’ve turned to my server-side and added domain attribute into the setCookie function as follows

//create the cookie
        res.cookie('session', sessionId, {
            expires: expiry,
            sameSite: "none",
            secure: true,
            domain: "localhost"
        });
        res.cookie('user', userId.toString(), {
            sameSite: "none",
            secure: true,
            **domain: "localhost"**
        });
        res.status(200);
        return user;

but also the browser refused to set the cookies and threw an error next to the response’s cookie header
enter image description here

I don’t know what else to do, of course, there is a way for communication between two different domain websites, I’m trying to implement the session-cookie authentication pattern and I don’t want to use any third-party package.

Sorry for the long post

unable to dynamically set a value in react-hook-form

I am using react-hook-form to build a form. there is a section of the form where the user can enter item name, item price, and the quantity of items. i also want an input where the user cannot interact with, but rather calculates the total amount of the item based on the price and quantity the user entererd.
but it seems i have been doing only the wrong things.

import React from "react";
import { useFieldArray, useForm } from "react-hook-form";
import { DevTool } from "@hookform/devtools";
const FormInput = () => {
  const {
    register,
    control,
    handleSubmit,
    formState,
    getValues,
    setValue,
    watch,
  } = useForm({
    defaultValues: {
      clientName: "Jensen Huang",
      clientEmail: "[email protected]",
      status: "paid",
      createdAt: new Date(),
      paymentDue: new Date(),
      description: "Re-branding",
      senderAddress: {
        street: "",
        city: "London",
        postCode: "E1 3EZ",
        country: "United Kingdom",
      },
      clientAddress: {
        street: "106 Kendell Street",
        city: "Sharrington",
        postCode: "NR24 5WQ",
        country: "United Kingdom",
      },
      items: [
        {
          name: "",
          quantity: "",
          price: "",
          // totalAmount: 0,
        },
      ],
    },
  });
  const onSubmit = (data) => {
    console.log(data);
  };
  const { errors, isValid, isDirty } = formState;
  const { append, remove, fields, insert } = useFieldArray({
    name: "items",
    control,
  });
  // Function to update total amount when quantity or price changes
  const calculateTotalAmount = (index) => {
    const quantity = getValues(`items.${index}.quantity`);
    const price = getValues(`items.${index}.price`);
    if (quantity && price) {
      const totalAmount = parseFloat(quantity) * parseFloat(price);
      setValue(`items.${index}.totalAmount`, totalAmount.toFixed(2));
    } else {
      setValue(`items.${index}.totalAmount`, "");
    }
  };

  return (
    <>
      <form onSubmit={handleSubmit(onSubmit)} noValidate>
        <div className="form-control">
          <h4>Bill From</h4>
          <div className="invoice-input">
            <label htmlFor="senderStreet">
              <span>Sender Address</span>
              <span className="error">
                {errors?.senderAddress?.street?.message}
              </span>
            </label>
            <input
              type="text"
              id="senderStreet"
              {...register("senderAddress.street", {
                required: {
                  value: true,
                  message: "can't be empty",
                },
              })}
            />
          </div>
          <div className="form-3-col">
            <div className="invoice-input">
              <label htmlFor="senderCity">
                <span>Sender City</span>
                <span className="error">
                  {errors?.senderAddress?.city?.message}
                </span>
              </label>
              <input
                type="text"
                id="senderCity"
                {...register("senderAddress.city", {
                  required: {
                    value: true,
                    message: "can't be empty",
                  },
                })}
              />
            </div>
            <div className="invoice-input">
              <label htmlFor="senderPostcode">
                <span>Post code</span>
                <span className="error">
                  {errors?.senderAddress?.postCode?.message}
                </span>
              </label>
              <input
                type="text"
                id="senderPostcode"
                {...register("senderAddress.postCode", {
                  // valueAsNumber: true,
                  required: {
                    value: true,
                    message: "can't be empty",
                  },

                  pattern: {
                    value: /^d{1,5}$/,
                    message: "Please enter a number",
                  },
                  maxLength: {
                    value: 5,
                    message: "Postal code must be 5 characters or less",
                  },
                })}
              />
            </div>
            <div className="invoice-input">
              <label htmlFor="senderCountry">
                <span>Country</span>
                <span className="error">
                  {errors?.senderAddress?.country?.message}
                </span>
              </label>
              <input
                type="text"
                id="senderCountry"
                {...register("senderAddress.country", {
                  required: {
                    value: true,
                    message: "can't be empty",
                  },
                })}
              />
            </div>
          </div>
        </div>
        <div className="form-control">
          <h4>Bill to</h4>
          <div className="invoice-input">
            <label htmlFor="clientStreet">
              <span>Address</span>
              <span className="error">
                {errors?.clientAddress?.street?.message}
              </span>
            </label>
            <input
              type="text"
              id="clientStreet"
              {...register("clientAddress.street", {
                required: {
                  value: true,
                  message: "can't be empty",
                },
              })}
            />
          </div>
          <div className="form-3-col">
            <div className="invoice-input">
              <label htmlFor="clientCity">
                <span>city</span>
                <span className="error">
                  {errors?.clientAddress?.city?.message}
                </span>
              </label>
              <input
                type="text"
                id="clientCity"
                {...register("clientAddress.city", {
                  required: {
                    value: true,
                    message: "can't be empty",
                  },
                })}
              />
            </div>
            <div className="invoice-input">
              <label htmlFor="clientPostCode">
                <span>Post code</span>
                <span className="error">
                  {errors?.clientAddress?.postCode?.message}
                </span>
              </label>
              <input
                type="text"
                id="clientPostCode"
                {...register("clientAddress.postCode", {
                  required: {
                    value: true,
                    message: "can't be empty",
                  },

                  pattern: {
                    value: /^d{1,5}$/,
                    message: "Please enter a number",
                  },
                  maxLength: {
                    value: 5,
                    message: "Postal code must be 5 characters or less",
                  },
                })}
              />
            </div>
            <div className="invoice-input">
              <label htmlFor="clientCountry">
                <span>country</span>
                <span className="error">
                  {errors?.clientAddress?.country?.message}
                </span>
              </label>
              <input
                type="text"
                id="clientCountry"
                {...register("clientAddress.country", {
                  required: {
                    value: true,
                    message: "can't be empty",
                  },
                })}
              />
            </div>
          </div>
        </div>
        <div className="form-control">
          <h4>Items</h4>
          {fields.map((field, index) => (
            <div key={field.id} className="form-4-col">
              <div className="invoice-input">
                <label htmlFor={`items.${index}.name`}>
                  <span>Item Name</span>
                </label>
                <input
                  type="text"
                  id={`items.${index}.name`}
                  {...register(`items.${index}.name`)}
                />
              </div>
              <div className="invoice-input">
                <label htmlFor={`items.${index}.quantity`}>
                  <span>Quantity</span>
                </label>
                <input
                  type="number"
                  id={`items.${index}.quantity`}
                  {...register(`items.${index}.quantity`)}
                  onChange={() => calculateTotalAmount(index)}
                />
              </div>
              <div className="invoice-input">
                <label htmlFor={`items.${index}.price`}>
                  <span>Price</span>
                </label>
                <input
                  type="text"
                  id={`items.${index}.price`}
                  {...register(`items.${index}.price`)}
                  onChange={() => calculateTotalAmount(index)}
                />
              </div>
              <div className="invoice-input">
                <label htmlFor={`items.${index}.totalAmount`}>
                  <span>Total Amount</span>
                </label>
                <input
                  type="text"
                  id={`items.${index}.totalAmount`}
                  {...register(`items.${index}.totalAmount`)}
                  readOnly
                />
              </div>

              <svg
                className="remove-item"
                onClick={() => remove(index)}
                width="13"
                height="16"
                xmlns="http://www.w3.org/2000/svg"
              >
                <path
                  d="M11.583 3.556v10.666c0 .982-.795 1.778-1.777 1.778H2.694a1.777 1.777 0 01-1.777-1.778V3.556h10.666zM8.473 0l.888.889h3.111v1.778H.028V.889h3.11L4.029 0h4.444z"
                  fill="#888EB0"
                  fill-rule="nonzero"
                />
              </svg>
            </div>
          ))}
          <div>
            <button
              className="btn"
              type="button"
              onClick={() =>
                insert(0, {
                  name: "",
                  quantity: "",
                  price: "",
                  totalAmount: "",
                })
              }
            >
              Add Item
            </button>
          </div>
        </div>

        <div className="btn-container">
          <div className="btn-discard">
            <button type="button" className="btn btn-discard">
              Discard
            </button>
          </div>
          <div className="btn-others">
            <button type="button" className="btn btn-draft">
              Save as Draft
            </button>
            <button type="submit" className="btn btn-send">
              Save & send
            </button>
          </div>
        </div>
      </form>
      <DevTool control={control} />
    </>
  );
};

export default FormInput;

i’ve tried multiple resources online but i’m only getting more confused!

Mongo DB Error: Error: The `uri` parameter to `openUri()` must be a string, got “undefined”

I got a common error and tried multiple threads to fix it with no success.

I think there is something else involved that I’m just not seeing. This site used to be deployed through Heroku. The plan was supposed to be free, but it looks like they charge now so I’m in the process of moving this over to vercel since its a student project with limited users. I removed the heroku build language, but I’m having trouble connecting with my Mongo DB and am getting this error:

Error: The uri parameter to openUri() must be a string, got "undefined".     Make sure the first parameter to mongoose.connect() or mongoose.createConnection() is a string.

I have tried:

  • making sure .env folder is in root directory
  • i have useNewUrlParser: true, in db.js file
  • that the mongoDB password is correct and matches .env file

This worked fine when it was on Heroku. Need to get up and running to deploy elsewhere. Thanks for your help!

How to submit by by pressing enter button in addition to clicking Bootstrap button

I have the following HTML code for inputting prompts to a chatbot:

<div class="input-group mb-3">
      <input type="text" class="form-control" id="chat-input">
      <div class="input-group-append">
        <button id="gpt-button" class="btn btn-primary" >Ask ChatGPT</button>
      </div>
    </div>

And this is the Javascript code that executes upon clicking the button:

$("#gpt-button").click(function(){

.......

}

However, this only submits upon clicking the button, not upon pressing the enter button.

I have tried the following modifictions to the above Javascript code. However, none of them succeed in submitting the prompt by using the Enter button.

$("#gpt-button").keyup(function(event){
.........
}
$("#gpt-button").on('click', function(event){
...........
}

Prevent layout shift then disabling scrolling on a website

I have a rather classic CSS problem. I have a website with a header and a navigation menu. When menu is opened I need to disable the scroll on the website beneath. Simple enough – just add overflowY: hidden. But it is causing problem with the width of the website – when scrollbar appears or disappears it causes stuff on the website to shift left and right due to change in website width (I’m mostly concerned about the header as it is most visible).

I made a simple dummy website to demonstrate the problem:

https://jsfiddle.net/2yqr7hon/1/ – when you open the menu it hides the scrollbar and everything in the header moves.


I tried couple of approaches:

  1. First I looked into scrollbar-gutter as it seemed perfect for the job. But it does not do what I’m looking for. I added scrollbar-gutter: stable; straight on the body and overflow: auto; on the html to make it work. But instead of extending padding on the right it just creates a blank spot. Maybe I was hoping for a magic solution or I’m using it wrong: https://jsfiddle.net/7L9u45ap/6/

  2. Then I tried some solutions with disabling the scrollbar, without actually hiding it. So I tried using position: fixed in combination with overflowY: scroll. It makes it so that the scrollbar is always visible, but scrolling is not possible. This is what I was looking for. But this has a downside of assuming that website always has a scroll. And while it is true on almost all pages, there are some examples (like for example login page) that are not tall enough to have scroll.

  3. To fix this I came up with another iteration that checks if website requires a scroll, and applies it only when necessary. It is kinda junky but it works:
    https://jsfiddle.net/7L9u45ap/3/

I wonder if there is a better solution to this problem? All evidence points to scrollbar-gutter, but it doesn’t seem to work as expected. And the rest are just some javascript hacks. I was hoping for a native CSS solution since I saw many improvements in recent years. Like for example new units or mentioned scrollbar gutter. But I couldn’t figure out what to do, and all resources/question that I’ve found were mostly ancient or didn’t help.

It could be either the solution of not completely hiding the scrollbar, or somehow adjusting the width of the website to not move when scrollbar is absent.

I am trying to code a searchbar using react native with API calls. I’m getting an Axios error

I am new to react native and am I trying to code a search bar with API calls. Every time I run the code I get a fetching data error. Could anyone help me please?

Here is my code:

When running the code it gives me the following error:

Error Fetching Data: AxiosError: error failed with status code 404.
Could anyone please help me? Thanks!

import React, { useState, useEffect } from 'react';
import { View, StyleSheet, Text, ScrollView, TextInput } from 'react-native';
import Ionicons from 'react-native-vector-icons/Ionicons';
import axios from 'axios';

function Menu(props) {
    const [searchText, setSearchText] = useState('');
    const [searchResults, setSearchResults] = useState([]);

    const rapidApiKey = "****************p1dfd12jsnf2823d3248e8"; // Replace with your actual RapidAPI key

    const handleSearch = async () => {
        try {
            const response = await axios.get('https://worldwide-restaurants.p.rapidapi.com/search', {
                headers: {
                    'X-RapidAPI-Host': 'worldwide-restaurants.p.rapidapi.com',
                    'X-RapidAPI-Key': rapidApiKey,
                },
                params: {
                    q: searchText,
                },
            });

            setSearchResults(response.data.results);
        } catch (error) {
            console.error('Error fetching data:', error);
            console.log('Error response:', error.response); // Log the detailed error response
        }
    };

    useEffect(() => {
        handleSearch(); // Fetch initial data when the component mounts
    }, []);

    return (
        <ScrollView vertical showsVerticalScrollIndicator={false}>
            <View style={styles.container}>
                <View style={styles.search}>
                    <TextInput
                        placeholder='Search'
                        placeholderTextColor="#fff"
                        clearButtonMode='always'
                        autoCapitalize='none'
                        autoCorrect={false}
                        style={styles.searchBar}
                        value={searchText}
                        onChangeText={(text) => setSearchText(text)}
                        onSubmitEditing={handleSearch}
                    />
                    <Ionicons name='search' size={25} color={'#8E43ED'} />
                </View>
                <View style={styles.suggestion}>
                    {searchResults.map((result) => (
                        <View key={result.id} style={styles.suggestionBox}>
                            <Text style={{ color: '#fff' }}>{result.name}</Text>
                            {/* Add other relevant data fields */}
                        </View>
                    ))}
                </View>
            </View>
        </ScrollView>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#333',
        padding: 10,
        paddingTop: 50,
    },
    search: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        marginBottom: 20, // Added margin to separate the search bar from suggestions
    },
    searchBar: {
        paddingHorizontal: 10,
        paddingVertical: 5,
        borderBottomColor: '#8E43ED',
        borderBottomWidth: 2,
        color: '#fff',
        width: '80%', // Adjusted width for better alignment
    },
    suggestion: {
        flex: 1,
        flexDirection: 'row',
        flexWrap: 'wrap',
        alignItems: 'center',
        justifyContent: 'center',
        padding: 10,
        gap: 50,
    },
    suggestionBox: {
        backgroundColor: '#8E43ED',
        width: 150,
        height: 200,
        margin: 10,
        padding: 10,
        borderRadius: 8,
    },
});

export default Menu;

Improve performance of p5.js simulation of gravity grid

I made a cool simulation in p5.js for a grid of dots, but it’s not super performant. It seems like most of the performance problem lies in the ellipse calls.

I’ve seen people talking about shaders, so do I have to make a shader to optimize the performance of this??

const settings = {
  fps: 60,
  dotColor: '#bab6ab',
  dotSize: 2,
  maxGravForce: 12,
  maxEllasticForce: 20,
  columns: 120,
  columnGap: 2,
  rows: 60,
  rowGap: 1,
};

let running = false;

const clamp = (num, min, max) => {
  return Math.min(Math.max(num, min), max);
};

/**
 * force = G*m1*m2 / (distance * distance)
 */
const calculateGravity = (point1, point2) => {
  const G = 1000; // grav constant
  const m1 = 1;
  const m2 = 1;

  // calculate distance
  const dx = point2.x - point1.x;
  const dy = point2.y - point1.y;
  const distance = Math.sqrt(dx * dx + dy * dy);

  // calculate force magnitude
  const forceMagnitude = G * m1 * m2 / Math.pow(distance, 1.05);

  // calculate force direction (unit vector)
  const ux = dx / distance;
  const uy = dy / distance;

  // calculate vector components
  const fx = clamp(forceMagnitude * ux, -settings.maxGravForce, settings.maxGravForce);
  const fy = clamp(forceMagnitude * uy, -settings.maxGravForce, settings.maxGravForce);

  // create and return the force vector
  return createVector(fx, fy);
};

const calculateElasticity = (point1, point2) => {
  // calculate distance
  const dx = point2.x - point1.x;
  const dy = point2.y - point1.y;
  const distance = Math.sqrt(dx * dx + dy * dy);

  // calculate force magnitude
  let forceMagnitude = 0;
  if (distance <= 2.62) { // 2.62 is where these two functions intersect
    // y = x
    forceMagnitude = Math.abs(distance);
  } else {
    // exponential
    forceMagnitude = (Math.pow(2, (0.5 * distance) - 2)) + 2;
  }

  // calculate force direction (unit vector)
  const ux = distance !== 0 ? (dx / distance) : 0;
  const uy = distance !== 0 ? (dy / distance) : 0;

  // calculate vector components
  const fx = clamp(forceMagnitude * ux, -settings.maxEllasticForce, settings.maxEllasticForce);
  const fy = clamp(forceMagnitude * uy, -settings.maxEllasticForce, settings.maxEllasticForce);

  // create and return the force vector
  return createVector(fx, fy);
};

class Entity {
  constructor(position, debug) {
    this.position = createVector(position.x, position.y);
    this.velocity = createVector(0, 0);
    this.anchor = createVector(position.x, position.y);
    this.debug = debug || false;
  }

  getPosition() {
    return this.position;
  }

  getAnchor() {
    return this.anchor;
  }

  applyForce(force) {
    this.velocity.add(force);
  }

  applyAnchorDamping() {
    // the closer we are to the anchor, the more we reduce the speed
    const point1 = this.position;
    const point2 = this.anchor;

    // Define a minimum distance to avoid extreme damping close to the anchor
    const minDistance = 8; // You can adjust this value
    const safeDistance = Math.max(point1.dist(point2), minDistance);

    // Define the damping strength
    const dampingStrength = 0.95; // You can adjust this value (closer to 1 means less damping)

    // Calculate the damping factor
    // As the entity gets closer to the anchor, the damping factor decreases
    const dampingFactor = Math.pow(dampingStrength, safeDistance);

    //     if (this.debug) {
    //       console.log('anchor damping', point1.dist(point2).toFixed(2), dampingFactor)
    //     }

    // Apply damping to velocity
    this.velocity.mult(dampingFactor);
  }

  applyMouseDamping(mousePoint, debug) {
    const point1 = this.position;
    const point2 = mousePoint;

    const distance = point1.dist(point2);

    if (distance > 30) {
      return;
    }

    const dampingFactor = clamp(0.05 * distance + 0.0, 0, 1);

    // if (this.debug) {
    //   console.log('mouse damping', point1.dist(point2).toFixed(2), dampingFactor)
    // }

    this.velocity.mult(dampingFactor);
  }

  applyVelocity() {
    this.position.add(this.velocity);
  }

  show() {
    noStroke();
    fill(settings.dotColor);
    ellipse(this.position.x, this.position.y, settings.dotSize, settings.dotSize, 6);
  }
}

function throttle(cb, delay) {
  let flag = null;
  return (...args) => {
    if (flag === null) {
      cb(...args);
      flag = setTimeout(() => {
        flag = null;
      }, delay);
    }
  };
}

let entities = [];
function createEntities() {
  entities = [];

  const gridWidth = (settings.columns * settings.dotSize) + ((settings.columns - 1) * settings.columnGap);
  const gridHeight = (settings.rows * settings.dotSize) + ((settings.rows - 1) * settings.rowGap);

  for (let i = 0; i < settings.columns; i++) {
    for (let j = 0; j < settings.rows; j++) {
      let x = i * (settings.dotSize + settings.columnGap);
      let y = j * (settings.dotSize + settings.rowGap);

      // normalize to center
      x = x - (gridWidth / 2);
      y = y - (gridHeight / 2);

      entities.push(
        new Entity(
          { x, y },
          i === 0 && j === 0,
        ),
      );
    }
  }
}

const createEntitiesThrottled = throttle(createEntities, 250);

function setup() {
  frameRate(settings.fps);
  createCanvas(windowWidth, windowHeight, WEBGL);

  createEntities();

  // noLoop();
}

function draw() {
  // console.log(frameRate())
  clear();
  // background('#DCDAD4')

  for (let i = 0; i < entities.length; i++) {
    const entity = entities[i];

    const mousePosition = mouseX !== 0 && mouseY !== 0 ? createVector(mouseX - (windowWidth / 2), mouseY - (windowHeight / 2)) : null;

    if (mousePosition) {
      const mouseForce = calculateGravity(
        entity.getPosition(),
        mousePosition,
      );
      // if (entity.debug) {
      //   console.log(mouseForce.toString())
      // }
      entity.applyForce(mouseForce);
    }

    const anchorForce = calculateElasticity(
      entity.getPosition(),
      entity.getAnchor(),
    );
    entity.applyForce(anchorForce);

    entity.applyAnchorDamping();

    if (mousePosition) {
      entity.applyMouseDamping(mousePosition);
    }

    entity.applyVelocity();

    entity.show();
  }
}

function windowResized() {
  resizeCanvas(windowWidth, windowHeight);
  createEntitiesThrottled();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.6.0/p5.js"></script>

How to upload a word document using WCF service while maintaining the styling?

I am writing a Chrome extension with the feature of uploading a Word document and using a WCF service to get the job done. While the file is getting saved on the server the content of the Word document is getting all messed up. I think it’s a problem with the encoding, but I am unsure how to solve it. Any suggestions on how I can get this done?

WCF Service

[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/UploadFile", ResponseFormat = WebMessageFormat.Json,
            BodyStyle = WebMessageBodyStyle.WrappedRequest,
            RequestFormat = WebMessageFormat.Json)]
string UploadFile( Stream fileStream);

public string UploadFile(Stream fileStream)
{

    try
    {
        string FilePath = Path.Combine(HostingEnvironment.MapPath("~/Uploads"), "Test.docx");


        int length = 0;
        using (FileStream writer = new FileStream(FilePath, FileMode.Create))
        {
            int readCount;
            var buffer = new byte[8192];
            while ((readCount = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                writer.Write(buffer, 0, readCount);
                length += readCount;
            }
        }
        return "true";
    }
    catch (Exception ex)
    {
        System.IO.File.WriteAllText(HttpContext.Current.Server.MapPath("~/error.txt"), ex.StackTrace);
        System.IO.File.AppendAllText(HttpContext.Current.Server.MapPath("~/error.txt"), "n" + ex.Message);
        return "false";
    }


}

Chrome Extension Upload Function

document.getElementById('uploadResume').addEventListener('click', function () {
    const fileInput = document.getElementById('fileInput');
    const file = fileInput.files[0];
    
    if (file) {
        // Create a FormData object to send the file
        console.log("FIleDatan");
        console.log(file);
        const formData = new FormData();
        formData.append('fileName', file.name);
        formData.append('fileStream', file);
        // Create an XMLHttpRequest object
        const xhr = new XMLHttpRequest();

        // Define the WCF service URL
        const wcfServiceUrl = '';

        // Open a POST request to the WCF service
        xhr.open('POST', wcfServiceUrl, true);

        // Set a callback function to handle the response
        xhr.onload = function () {
            if (xhr.status === 200) {
                // Request was successful, handle the response here
                console.log('File upload successful');
                console.log(xhr.responseText);
            } else {
                // Request failed, handle errors here
                console.error('File upload failed');
            }
        };
        console.log(formData);
        xhr.send(formData);
    } else {
        console.error('No file selected');
    }
    console.log("Button CLicked");
});

React – announce that fact that a component is displayed

I have to make screen readers announce the fact that a section is displayed. This section is displayed based on a boolean value that is changed when the user clicks on a link.

This is how it is implemented so far:

 import { Row } from 'react-bootstrap';
    ...
    const [shouldDisplay, setShouldDisplay] = useState<boolean>(false);
    ...
    return(
     {!shouldDisplay && (
        <a href="somepage.com" onClick={setShouldDisplay(true)} />
      )}

      {shouldDisplay && (
        <Row>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. </p>
        </Row>)}
    );

I have tried to add aria-live=”polite” to the Row but the screen readers still don’t announce the fact that the new part with the lorem ipsum is displayed. It should announce “Lorem ipsum part is displayed” or at least “expanded” like the case when Collapse from react-bootstrap, with aria-expanded=”true” is used. Is there a way to achieve this?