retrieving information from a previous chat

Programmers, Engineers!
I am having this issue trying to retrieve data in the same session during chatting with this chat bot

@app.route("/chat", methods=["POST"])
def chat():
    try:
        user_input = request.json.get("message", "")
        session_id = request.json.get("session_id", str(uuid.uuid4()))  # Generate a new session ID if not provided
        user_name = request.json.get("name", "User")  # Extract user name if provided

        # Store or update the user's name in the conversation model
        conversation = Conversation.query.filter_by(session_id=session_id).first()
        if conversation:
            conversation.user_name = user_name
            conversation.user_message = user_input
        else:
          conversation = Conversation(session_id=session_id, user_name=user_name, user_message=user_input, bot_reply="")
            db.session.add(conversation)
        db.session.commit()

        # Retrieve conversation history
        conversations = Conversation.query.filter_by(session_id=session_id).all()
        conversation_history = [c.user_message for c in conversations]

        # Retrieve user name from session
        user_name = session.get("name", "User")

        # Generate response using OpenAI's API with a system message
        app.logger.info("Generating response with ChatGPT...")
        try:
            response = openai.ChatCompletion.create(
                model="gpt-3.5-turbo",
                messages=[
                    {"role": "system", "content": f"You are a medical assistant. Your name is {user_name}. Provide accurate medical information and advice. If you are unsure about a medical issue, advise the user to consult a healthcare professional."},
                    {"role": "system", "content": "Conversation history: " + ", ".join(conversation_history)},
                    {"role": "user", "content": user_input}
                ],
                max_tokens=300,
                temperature=0.7
            )
            bot_reply = response['choices'][0]['message']['content'].strip()
            app.logger.info(f"ChatGPT reply: {bot_reply}")
        except Exception as e:
            app.logger.error(f"Error generating response with ChatGPT: {e}")
            bot_reply = "Error: Unable to generate response."

        # Update and store the conversation in the database
        app.logger.info("Updating conversation in database...")
        conversation.bot_reply = bot_reply
        db.session.commit()
        app.logger.info("Conversation updated successfully.")

        return jsonify({"response": bot_reply, "session_id": session_id, "name": user_name})

    except Exception as e:
        app.logger.error(f"Error processing request: {e}")
        return jsonify({"response": "Sorry, there was an error processing your request."})

This is the chat i had with the AI:
Hi there my name is Osama

Hello, Osama! How can I assist you with your medical questions or concerns today?

what is my name

I’m sorry, I don’t have access to your personal information such as your name. How can I assist you today?

Me: Hi there my name is osamah

ChatBot: Hello, Osamah! How can I assist you today?

Me: what is my name

ChatBot: I’m sorry, but I don’t have access to that information. How can I assist you today?

this is my app.js that i spent hours trying to find if id does not run the session correctly:

function App() {
  const [chatHistory, setChatHistory] = useState([]);
  const [message, setMessage] = useState('');
  const [loading, setLoading] = useState(false);
  const [sessionId, setSessionId] = useState('');
  const [userName, setUserName] = useState('');

  // Initialize a new session ID when the component mounts
  useEffect(() => {
    const initSession = async () => {
      try {
        const response = await axios.post('http://localhost:5000/chat', { message: '' });
        setSessionId(response.data.session_id);
        console.log('Session initialized:', response.data);
      } catch (error) {
        console.error('Error initializing session:', error);
      }
    };
    initSession();
  }, []);

  const handleSendMessage = async () => {
    if (message.trim() === '' || !sessionId) return;

    setChatHistory([...chatHistory, { role: 'user', content: message }]);

    try {
      setLoading(true);
      const response = await axios.post('http://localhost:5000/chat', {
        message: message,
        session_id: sessionId,
        name: userName
      });
      console.log('Response from server:', response.data);
      setChatHistory(prev => [
        ...prev,
        { role: 'assistant', content: response.data.response }
      ]);
    } catch (error) {
      console.error('Error fetching data:', error);
      setChatHistory(prev => [
        ...prev,
        { role: 'assistant', content: 'Error: Unable to get a response.' }
      ]);
    } finally {
      setLoading(false);
      setMessage('');
    }
  };

  const handleUserNameChange = (event) => {
    setUserName(event.target.value);
  };

Configuring the Highcharts Library slider (stocks)

I have a stock chart of the Highcharts library. How to adjust the position of the right and left slider in the picture. I need that when I click on the “now” button, the left slider moves to today’s date, and the right one is at a distance from it, for example, 3 hours enter image description here

As I understood in this library, the position of the left slider is dancing from the position of the right one. I implemented moving the left slider for the number of seconds I needed. But it’s dancing from the same right-hand runner…

log in and sign up linked together

I tried to implement a login and signup system where both forms are linked together, allowing users to switch between them easily. I also set up a mock API to simulate backend interactions, but I’m facing several challenges:

  1. Form Switching: I’m having trouble toggling between the login and signup forms smoothly. The UI doesn’t update as expected, and sometimes it loses the user’s input or causes unexpected behavior.
  2. Mock API Handling: I set up a mock API to handle login and signup requests, but I’m not sure if I’m simulating the API responses correctly. I’m facing issues with returning success or error responses, and I’m unsure how to handle these responses properly on the frontend.
  3. Authentication State: Managing the user’s authentication state is proving difficult. I need to ensure that once a user successfully logs in or signs up, they are redirected appropriately, but my current implementation doesn’t handle this well.
  4. Validation and Error Handling: Implementing form validation for both login and signup forms has been challenging. I also need to show relevant error messages when something goes wrong, like invalid input or failed login attempts, but my current error handling is either incomplete or not working as expected.

I’m looking for detailed examples or guidance on how to address these issues effectively.

Execution contexts of exporting modules in call stack

Consider following code:

moduleA.js:

// moduleA.js
export const moduleVarA = "I am from moduleA";
export function greetA() {
    console.log("Hello from moduleA");
}

moduleB.js:

// moduleB.js
import { moduleVarA, greetA } from './moduleA.js';

console.log(moduleVarA); // "I am from moduleA"
greetA(); //"Hello from moduleA"

I want to ask what will be the order of execution contexts of above modules in call stack? I mean will after loading and executing module A its execution context be popped off from call stack OR it will remain there until execution contexts of all importing modules(like moduleB) get finished?

Incorrect Jest Module Name Mapper: Could not locate module

I am using Jest v29.7.0 as well as babel-jest v29.7.0.

This is my jest.config.js file

module.exports = {
    transform: {
        '\.[jt]sx?$': 'babel-jest'
    },
    rootDir: './',
    verbose: true,
    setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
    moduleDirectories: ['node_modules', '<rootDir>/public/js'],
    moduleFileExtensions: ['js', 'jsx', 'ts', 'tsx', 'json', 'node'],
    moduleNameMapper: {
        '^components/(.*)$': '<rootDir>/public/js/components/$1',
    },
    extensionsToTreatAsEsm: ['.jsx'],
    transformIgnorePatterns: ['/node_modules/'],
    testEnvironment: 'jsdom',
    collectCoverage: true,
    coverageDirectory: '<rootDir>/test/output/coverage',
    coverageReporters: ['html', 'text-summary'],
    testTimeout: 10000,
    roots: ['./public/js/components', './test/spec'],
    collectCoverageFrom: ['./public/js/**/*.{js,jsx}']
};

When trying to run one particular test: npm run test-jest -- test/spec/components/UserProfile/Account/Payments.spec.js

Error from Jest

Test suite failed to run

    Configuration error:
    
    Could not locate module components/UserProfile/Account/Payments mapped as:
    /Users/XXXXXXX/repo/public/js/components/$1.
    
    Please check your configuration for these entries:
    {
      "moduleNameMapper": {
        "/^components/(.*)$/": "/Users/XXXXXXX/repo/public/js/components/$1"
      },
      "resolver": undefined
    }

      2 | import { render, screen, fireEvent } from '@testing-library/react';
      3 | import '@testing-library/jest-dom';
    > 4 | import Payments from 'components/UserProfile/Account/Payments';
        | ^
      5 |
      6 | // Mock implementations
      7 | const mockGetState = jest.fn();

      at createNoMappedModuleFoundError (node_modules/jest-resolve/build/resolver.js:759:17)
      at Object.require (test/spec/components/UserProfile/Account/Payments.spec.js:4:1)
          at runMicrotasks (<anonymous>)

In my project I don’t use extensions when importing, for example I use import Payments from 'components/UserProfile/Account/Payments'; without having to use .jsx and my Webpack config understands this.

But I am new to Jest and don’t know how to get it to understand the imports without extensions when using them in tests.

My Simple failing test

import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import '@testing-library/jest-dom';
import Payments from 'components/UserProfile/Account/Payments';

describe('Payments Component', () => {
    beforeEach(() => {
        jest.clearAllMocks();
    });

    it('renders without crashing', () => {
        render(<Payments />);
    });
});

babel.config.js

module.exports = {
    presets: ['@babel/preset-env', '@babel/preset-react']
};

jest.setup.js

import '@testing-library/jest-dom';

What am I missing?

Loading form data in modal window

I have a webpage, I’m building in vb.net. The page lists worship locations for parishes. At the bottom of the list is a link to add a new location. When the link is clicked, a modal window appears containing a form. The form is completed and submitted to a separate page for processing. Upon return, the new location is on the list.

Next to each location is a link, “Edit”. I want to load the location information into the modal window so the user can make changes and submit them to a processing page.

In order to get the modal window to open I use:

<a href="#AddWS"" class="texttrigger" data-toggle="modal">Add Worship Site</a>

I want to have the edit link call a piece of javascript in order to place the location info into a hidden form at the bottom of the page and submit with action=”thispage.aspx#editWS”. The URL in the address bar upon submission is correct but the modal window does not display.

<a href=""javascript:editWS(185)"" >Edit</a>

function editWS(LID) {
    
    if (LID == 185) {
       
        document.editLocation.ID.value = 185;
        document.editLocation.address.value = "123 Anywhere St.";
        document.editLocation.city.value = "clairmont";
        document.editLocation.state.value = "NY";
        document.editLocation.zip.value = "11111";
        document.editLocation.phone.value = "(012) 888-1682";
        document.editLocation.county.value = "8";
        document.editLocation.vicariate_ID.value = "4";
        document.editLocation.SeatingCapacity.value = "200";
        document.editLocation.submit();
    }
    
    
    if (LID == 220) {
       
        document.editLocation.ID.value = 220;
        document.editLocation.address.value = "6 Main St.";
        document.editLocation.city.value = "cloverfield";
        document.editLocation.state.value = "NY";
        document.editLocation.zip.value = "22222";
        document.editLocation.phone.value = "(333) 622-3191";
        document.editLocation.county.value = "6";
        document.editLocation.vicariate_ID.value = "4";
        document.editLocation.SeatingCapacity.value = "";
        document.editLocation.submit();
    }     
}  

<form name="editLocation" action="thispage.aspx#editWS" method="post">
<input type="hidden" name="ID" value="" />
<input type="hidden" name="address" value="" />
<input type="hidden" name="city" value="" />
<input type="hidden" name="state" value="" />
<input type="hidden" name="zip" value="" />
<input type="hidden" name="phone" value="" />
<input type="hidden" name="county" value="" />
<input type="hidden" name="vicariate_ID" value="" />
<input type="hidden" name="SeatingCapacity" value="" />
</form>

In the modal window, I plan to load the data from the form object.The user can then update the info and submit it to a processing page.

How can I listen to inputs from cross-domain iframe?

I am working on a chrome extension where users will often times go to a webpage where there will be a cross-domain iframe embedded in the web page. What I am wanting to do is to listen for when inputs inside of an iframe are clicked or focused, and then do something based off of that.

A good example of what we are wanting to do is 1Password. Their extension is able to display suggestions when an input is clicked, even when that input is in a cross-domain iframe.

I am wanting to know how I can do something similar?

Getting We had some trouble connecting. Try again? when trying to update modals

Need some urgent help on slack bolt JS.
I am developing a slack application where user can approve/reject tasks.

I am trying to open a new modal (After one API call) which will confirm if the task is completed or not and this is giving me the error.

Please note I will need this aprovalresponse to compare the status received from api so I cannot make this api async.

**Below is the code I am using to open a modal to provide comment for the action.
**


// Handle selection of a pending task in the static select
app.action(
  { type: "block_actions", action_id: /^pending_task_action_(d+)$/ },
  async ({ ack, body, client }) => {
    await ack();

    const selectedOption = body.actions[0].selected_option.value;
    const selectedApplicationId = body.actions[0].block_id;
    const userEmail = body.user.name + "@mdsol.com";

    try { 
      const selectedCategory = body.view.private_metadata;

      // Open a modal with a text input for reasonm
      await client.views.open({
        trigger_id: body.trigger_id,
        view: {
          type: "modal",
          callback_id: "reason_modal",
          private_metadata: JSON.stringify({
            selectedOption,
            selectedApplicationId,
            selectedCategory,
            userEmail,
          }),
          title: {
            type: "plain_text",
            text: ":wave: Please comment",
          },
          blocks: [
            {
              type: "input",
              block_id: "reason_input",
              element: {
                type: "plain_text_input",
                action_id: "reason",
                multiline: true,
              },
              label: {
                type: "plain_text",
                text: "Please provide comment for your action:",
              },
            },
          ],
          submit: {
            type: "plain_text",
            text: "Submit",
          },
        },
      });
    } catch (error) {
      console.error("Error handling pending task action:", error);
    }
  }
);

And to handle this comment I wrote below code and here i am receiving the error.

// Handle submission of the reason modal
app.view('reason_modal', async ({ ack, body, view, client }) => {

  await ack()
  const viewId = view.id;
   // Open a quick loading modal
   await client.views.update({
    view_id: viewId,
    "response_action": "update",
    view: {
      type: "modal",
      title: {
        type: "plain_text",
        text: ":man-biking:Processing..",
      },
      blocks: [
        {
          type: "section",
          text: {
            type: "plain_text",
            text: ":hourglass_flowing_sand: Processing your request... ",
          },
        },
      ], 
    },
  });
  
  **//Making One api call here**
  
    const approvalResponse = await axios.post(approvalUrl, payload, {
      headers: {
        "Content-Type": "application/json",
        "x-api-key": process.env.X_API_KEY,
      },
    });
    
    **//Below Modal is returning same error.**
    
    if (approvalResponse.status == 200) {
    // Update the modal with the final content
    await client.views.update({
      view_id: viewId,
      "response_action": "update",
      view: {
        type: "modal",
        callback_id: "modal-1",
        title: {
          type: "plain_text",
          text: "Action Update!",
        },
        blocks: [
          {
            type: "section",
            block_id: "section-1",
            text: {
              type: "mrkdwn",
              text:"task is completed",
            },
          },
        ],
      },
    });
    }

error

Tried various approaches like opening a view pushing a view but still getting same error.

Is there a way to verify AWS Cognito password reset confirmation code without providing a new password?

I’m working on a React Native app that uses AWS Cognito for authentication with aws-amplify library. I am currently implementing the “Forgot Password” feature.

In the process of resetting a user’s password, I can call:

await confirmResetPassword({
  username: "[email protected]",
  confirmationCode: "123456",
  newPassword: "hunter3",
});

This function expects both the confirmation code and the new password in a single call.

However, I’d like to first verify the confirmation code (to check if it’s valid), and then, once the code is verified, prompt the user to set a new password.

Is there any way in AWS Cognito (using aws-amplify or any other method) to verify the confirmation code separately, without providing the new password right away? Ideally, I’d like to pass just the username and confirmationCode, and get a response on whether the code is valid.

Any suggestions or alternative approaches are appreciated!

Issue with CORS when hitting API using LangChain.js with MERN stack

Issue with CORS when hitting API using LangChain.js with MERN stack

I am using LangChain.js in my MERN stack project and I am importing the following:

import { ChatGoogleGenerativeAI } from "@langchain/google-genai";

Scenario:

  • In my frontend, I am hitting an API endpoint /llm/response which is supposed to interact with Google AI via LangChain.
  • The issue I am facing is that from the frontend I get a CORS error, something like:
    Access to XMLHttpRequest at 'http://localhost:3000/api/llm/response' from origin 'http://localhost:5173' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. .
  • However, when I test the same API endpoint separately using Postman, it works fine and gives me a response.

Additional Observations:

  • When I directly interact with Google AI via LangChain.js from the frontend, it works without any CORS issue, but my API key gets exposed, which is a security risk.

Question:

  • I need to use a free AI API to perform some computations. If there is any better way to handle this, I would appreciate a good explanation along with code examples.

How can I resolve this CORS issue, or what am I missing here? And if there’s a better way to securely use AI APIs (like free ones), please provide a solution with code.

What I tried and what I was expecting:

  • I tried hitting the /llm/response endpoint from my frontend expecting it to work just like it does in Postman without CORS issues, but instead, I got a CORS error.
  • I also tried setting up a backend proxy to resolve the issue, but it didn’t work. I expected that hitting the API from the frontend would securely interact with the API without exposing my API key.

How to change body background dynamically based on the active slide in Elementor loop carousel?

Body:

I’m using Elementor and I have a loop carousel element with multiple slides. I want to dynamically change the body background image to match the image of the central slide (the one currently in focus). The carousel is created with Elementor’s loop carousel widget.

This is the page: https://riccardocurin.com/new-homepage-02/

I tried using jQuery to detect the active slide and change the body background, but I’m not sure how to properly target the central slide and get its image URL. The carousel seems to use Slick Slider underneath.

I’m using the latest version of Elementor with a custom loop carousel.
Any suggestions on how to implement this properly? Thank you!

Here’s what I’ve tried so far:

jQuery(document).ready(function($) {
    function updateBodyBackground() {
        // Find the current active slide's image (swiper-slide-active)
        let activeSlideImage = $('.swiper-slide-next img').attr('src');
        
        if (activeSlideImage) {
            // Change the body's background to the active slide's image
            $('body').css({
                'background-image': 'url(' + activeSlideImage + ')',
                'background-size': 'cover',
                'background-position': 'center',
                'background-repeat': 'no-repeat'
            });
        }
    }

    // Initialize Swiper and update background every time slide changes
    const swiper = new Swiper('.swiper-container', {
        loop: true, // Enable loop
        on: {
            slideChangeTransitionEnd: function() {
                updateBodyBackground(); // Update background at the end of every slide change
            }
        }
    });

    // Initial background setting when the page loads
    updateBodyBackground();
});

The carousel works fine, but I can’t seem to get the correct class or method to target the central slide properly.

Cannot find package ‘@aws-sdk/client-cognito-identity-provider

Getting a very strange error with AWS Cognito provider.
I stepped away from our back-end Node JS repo for a few weeks, and suddenly our sign-in endpoint is no longer working.

{
"message": {
    "errorType": "Error",
    "errorMessage": "Cannot find package '@aws-sdk/client-cognito-identity-provider' imported from /var/task/index.mjs",
    "trace": [
        "Error [ERR_MODULE_NOT_FOUND]: Cannot find package '@aws-sdk/client-cognito-identity-provider' imported from /var/task/index.mjs",
        "    at new NodeError (internal/errors.js:322:7)",
        "    at packageResolve (internal/modules/esm/resolve.js:732:9)",
        "    at moduleResolve (internal/modules/esm/resolve.js:773:18)",
        "    at Loader.defaultResolve [as _resolve] (internal/modules/esm/resolve.js:887:11)",
        "    at Loader.resolve (internal/modules/esm/loader.js:89:40)",
        "    at Loader.getModuleJob (internal/modules/esm/loader.js:242:28)",
        "    at ModuleWrap.<anonymous> (internal/modules/esm/module_job.js:76:40)",
        "    at link (internal/modules/esm/module_job.js:75:36)",
        "    at process.runNextTicks [as _tickCallback] (internal/process/task_queues.js:60:5)",
        "    at /var/runtime/deasync.js:23:15"
    ]
},
"error": null

Situation

  • no other team mates using the same repo, are getting this
  • no code changes were made on my end
  • going back to a branch made weeks ago that was working fine, is also throwing this error.

What I’ve tried

  • tried with Node versions 22, 20, and 14.

  • tried updating that particular package, and all the other AWS packages we use.

  • deleted and reinstalled the node_modules

  • Completely deleted and re-cloned the repo

Extra Notes

This error only shows in Postman when I hit the sign-in endpoint. There are no errors when starting the server. This error does not show in my console, only in Postman.

Why would points render in a Highcharts Stock chart when changing range selection?

Question: why would points appear on a Stock chart in Highcharts instead of just plot lines?

I’m playing with the Stock chart module in Highcharts in a Dashboard and I noticed that when I expand or contract the range selection in certain ways then points appear where there were none:

Highcharts Dashboard with Stock chart has points artifact (animation)

You can try this here: https://jsfiddle.net/zroq19nc/1/

I think I must be missing something when configuring the chart; here’s its component entry in the dashboard:

{
  "renderTo": "stock-cell",
  "type": "Highcharts",
  "chartConstructor": "stockChart",
  "connector": {
    "id": "example-budget-data",
    "columnAssignment": [
      {
        "seriesId": "Total Spend",
        "data": ["d", "Total"]
      }
    ]
  },
  "sync": {
    "highlight": true
  },
  "tooltip": {
    "useHTML": true
  },
  "chartOptions": {
    "chart": {
      "className": "highcharts-stock-chart"
    },
    "title": {
      "text": "Total Spend"
    },
    "series": [
      {
        "name": "Total Spend",
        "id": "total-spend"
      }
    ]
  }
}

how to send text to control with focus on new browser window opened using js.window.open(“https://www.bing.com/chat”)

how to send text to control with focus on new browser window opened using js.window.open(“https://www.bing.com/chat”)

I have a web app in python that has a button I can click to open a browser window to bing chat. I can see the new bing chat window with the cursor blinking on the copilot question textbox but how can I send text to the control to ask the question via code

VS Code Terminal Slow to Start and Respond When Using Code Runner Extension

I have been using vs code for a while now ,but recently I am facing the issue of a laggy and a very slow terminal response while executing .js files ,even a single line js program like console.log(“hello world); takes hell lot of time to get displayed in the terminal ,tried every possible solution found in youtube videos still not fixed,can anyone help me fix this issue?
I am having a asus tuf gaming f15 11th gen 16gb Ram laptop.

Tried every set of solution from yt videos and even Uninstalled the vs code couple of times.