how to fix my route error on godaddy using node express

I’m making a node application using express on godaddy and when I start the server and open the page the html appears normally with the css and js but the route to the server always gets error 500 and I’m not able to get out of it, can anyone help?

I’m doing a basic login site using node express and trying to host it on godaddy but my route to validation with the database is giving error 500 and I can’t get out of it

Discord Bot does not show activity status

My Discord bot does not show the activity status I have tried several methods but none worked my current code looks like this.

client.once('ready', () => {
  try {
    client.user.setActivity('Test', { type: 'PLAYING' });
    console.log(`Bot's Status: successfully updated`);
  } catch (error) {
    console.error(`Bot's Status: error while updating status`, error);
  }
});

I am using node.js v18.18.1
and discord.js the latest version

I have already tried with .setPresence see below but it did not work either.

client.once('ready', async () => {
  try {
    client.user.setPresence({
      status: 'online',
      activity: {
        name: 'Test',
        type: 'PLAYING'
      }
    });
    console.log(`Bot's Status: successfully updated`)
  } catch (error) {
    console.error(`Bot's Status: error while updating status`)
  }
});

So either I’m not awake enough or it just doesn’t work the bot has got adminesstrator rights has already been kicked and reloaded and the token has been reset but it still doesn’t work.

Parsing response from OpenAI containing markdown to html

I’m facing the problem of parsing answers (and covering all cases I can encounter) from the OpenAI API that contain markdown to html, specifically in React, without breaking one of the following; tables, multiple line breaks from the response (e.g. “HellonnWorld”), indentations in nested lists.

I’ve tried a bunch of solutions and libs including marked, react-markdown, markdown-it, various plugins (gfm, breaks), whitespace: pre-wrap, hacky &nbsp n fixes etc. What always ends up happening is that either tables, multiple line breaks or tables end up breaking with any variation of the solutions being applied.

The furthest I’ve gotten with this sample response is when using react-markdown with remark-gfm and whitespace: pre-wrap. Everything seems to be working fine besides nested ordered / unordered list indentation. It’s starting to seem like writing a lot of RegEx to adapt the output from OpenAI to something more suitable for react-markdown (or simply changing the format of response from OpenAI, which is the less desirable option) is inevitable, but perhaps someone had the same troubles as I’ve encountered and can provide some much needed input!

I cannot be able to make two dropdowns on yii2 php website pull interdependent data

I am getting ths error
Object of class yiiwidgetsActiveForm could not be converted to string
below is the snipet of the controller where the issue might be

  $campusList = ArrayHelper::map(TblCollege::find()->all(), 'name', 'name');
        return $this->render('view_probation', [
        'model' => new yiibaseDynamicModel(['campus', 'program']),
//            'model' => $model,
        'collegeList' => $campusList,
    ]);

and here is the view

 $form = ActiveForm::begin();
                    echo $form->field($model, 'college_id')->widget(Select2::classname(), [
                        'data' => $collegeList,
                        'options' => ['placeholder' => 'Select a college', 'id' => 'college_id'],
                        'pluginOptions' => [
                            'allowClear' => true,
                        ],
                    ]);

                    // Second Select2 for Programs
                    echo $form->field($model, 'program_id')->widget(Select2::classname(), [
                        'options' => ['placeholder' => 'Select a program', 'id' => 'program_id'],
                        'pluginOptions' => [
                            'allowClear' => true,
                            'depends' => ['college_id'],
                            'url' => Url::to(['common/list_program_curry_bycampuss']),
                        ],
                    ]);

and here is the javascript

$this->registerJs('
    // JavaScript to hide the loader initially
    $("div#loader").hide();

    $("#college_id").on("change", function() {
        var collegeId = $(this).val();
        if (collegeId) {
            $.ajax({
                url: "' . Url::to(['common/list_program_curry_bycampuss']) . '",
                type: "GET",
                data: {collegeId: collegeId},
                success: function(data) {
                    // Parse the received JSON data
                    var programsData = JSON.parse(data);

                    // Convert data to the format expected by Select2
                    var options = programsData.map(function(item) {
                        return {id: item.id, text: item.text};
                    });

                    // Populate the program dropdown
                    $("#program_id").html("").select2({data: options});
                }
            });
        } else {
            // Reset program dropdown if college is not selected
            $("#program_id").html("").select2({data: {}});
        }
    });

I want when i select campus, the second dropdown populates with programs for the campus selected

What are the best ways to pass IIS Site Name to the JavaScript file?

I’m developing now ASP.NET Core MVC application with Razor pages, where one of the requirements is to keep all JavaScript functions in a separate file.

In the JS function I’m sending a POST request to some endpoint, after receiving successful response I want to redirect the application to another page.

function onRowClick(e) {
    var dbkey = e.data === undefined ? 0 : e.data.DBKey;

    if (dbkey != null) {
        $.ajax({
            url: "/test/ValidateDataInEndpointY",
            type: "POST",
            data: { selectedProjectDBkey: dbkey },
            dataType: "json",
            crossDomain: true,
            cache: false,
            success: function (response) {
                window.location.href =  "/test2/GoToPageX";
            }
        });
    }
}

When I’m using Visual Studio or custom IIS WebSite everything works.The application url in VS/IIS is build like https://localhost:1234/ and the AJAX requests are using proper endpoint/page address – https://localhost:1234/test/...

But when I deployed the application to IIS and added it to the Default Web Site as a new application (using Convert to Application function) and created new application address -> http://localhost/myApplicationName, the AJAX request stopped working.

enter image description here

It do not take the myApplicationName into consideration, and builds the url of the endpoint like https://localhost/test/... instead of https://localhost/myApplicationName/test/....

What is the best way to handle the Site name and base URL here? I’ve tried to use different solutions in the JS file – windows.location, document.location, passing the parameter from the Razor page like below, and nothing worked. Everytime I’m just getting the localhost without the site name.

<script>
   var baseUrl = somefunctionhere;
</script>

Data returned by document.location:

enter image description here

At this moment I have a workaround – I define the base URL in the JavaScript file, but I assume it’s not the best solution. Also, if not needed I do not want to get the Site information from backend on the server.

Why am I getting “ReferenceError: Property ‘axios’ doesn’t exist, js engine: hermes” when I try to register a new user?

The part of the code that is causing the problem has the following syntax:

import axios from "axios";

const handleLogin = () => {
        const user = {
            email:email,
            password:password,
        };

        axios.post("http://localhost:8082/login", user).then((response) =>{
            const token = response.data.token;
            AsyncStorage.setItem("authToken",token);
            router.replace("/(tabs)/home")
        }) 

    }

Here are the errors presented both in cmd and in the application:

enter image description here
enter image description here

After researching what could be due to the syntax, but even after changing it, there was no solution to the problem. Any idea how I resolve this?

Trouble Implementing ISBN Reader in Laravel Project Using Packages like Guagua and ZXing

Hello Stack Overflow community,

I am currently working on a Laravel project and need assistance with implementing an ISBN reader. My objective is to enable the application to scan an ISBN number using a mobile phone’s camera and retrieve the ISBN for further processing.

I have explored existing packages such as Guagua and ZXing for this purpose, but I am encountering difficulties in getting them to work effectively within my Laravel environment. As a relatively new user to these packages, I would appreciate guidance and suggestions on how to successfully integrate an ISBN reader into my Laravel project.

Here are the specific challenges I’m facing:

Package Integration: I have attempted to integrate Guagua and ZXing into my Laravel project following their respective documentation, but the functionality does not seem to work as expected. I am unsure if there are any Laravel-specific configurations or nuances that I might be overlooking.

Camera Scanning: I am particularly interested in implementing the ISBN scanning functionality using a mobile phone’s camera. If anyone has successfully achieved this within a Laravel project using the mentioned packages or alternative solutions, your insights would be valuable.

Simplified Implementation: As a beginner in this domain, I am looking for a straightforward and well-explained approach to implementing an ISBN reader in Laravel. If there are any alternative packages or step-by-step guides that provide a simpler implementation, I would greatly appreciate recommendations.

In summary, I am seeking guidance on successfully implementing an ISBN reader in my Laravel project, specifically focusing on scanning ISBN numbers using a mobile phone’s camera. Any assistance, code snippets, or recommendations for alternative packages would be highly beneficial.

Thank you in advance for your time and expertise.

How do I highlight text on a webpage in my Edge extension?

I’m trying to learn how to make extensions in Edge (and eventually implement my dream upgrade for the Control-F Find function). This is a small extension so far, and it doesn’t work: when I click the “Find” button, nothing happens, but I want every occurrence of the search string on the webpage to be highlighted. Could you please help me to highlight all the search string matches on the web page? Thank you.

I checked for errors in the browser console and didn’t see any. Also, the print statement “find function reached” is not even printed to the console. So it’s like the find function is not getting called at all.

manifest.json

{
  "manifest_version": 2,
  "name": "Find and Follow",
  "version": "1.0",
  "description": "A browser extension that allows you to search for text and follow hyperlinks with ease.",
  "browser_action": {
    "default_popup": "popup.html"
  },
  "permissions": ["activeTab"]
}

popup.html

<!DOCTYPE html>
<html>
  <head>
    <title>Find and Follow</title>
  </head>
  <body>
    <input type="text" id="search" placeholder="Search...">
    <button id="find">Find</button>
    <script src="popup.js"></script>
  </body>
</html>

popup.js

function find() {
  let searchText = document.getElementById("search").value;

  let regex = new RegExp(searchText, "ig");
  let matches = document.documentElement.innerHTML.match(regex);
  if (matches) {
    document.documentElement.innerHTML = document.documentElement.innerHTML.replace(
      regex,
      '<span style="background-color: yellow;">$&</span>'
    );
  }
  console.log("find function reached.");

}

document.getElementById("find").addEventListener("click", find);

How to use RxJs with Require.JS

I try to use RxJs with Require.JS on Html page (without Angular or WebPack), this is my test

    <script src="http://requirejs.org/docs/release/2.3.6/comments/require.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/7.8.1/rxjs.umd.min.js"></script>
    <script type="text/javascript">
    require.config({
      paths: {
          "rxjs": "https://cdnjs.cloudflare.com/ajax/libs/rxjs/7.8.1/rxjs.umd.min.js"
      }
    });
    require (['rxjs'], (x) => x.of(1,2,3,4,5).subscribe(console.log));
    //-- before this line all working fine

    var rxjs_1 = require (['rxjs'], (x) => x);
    rxjs_1.of(6,7,8,9,10).subscribe(console.log);
    ....
    </script>

First way working fine, I see on console 1,2,3,4,5, but I don’t want rewrite something my huge code and want to receive reference to RxJs in variable rxjs_1 and than simple working with variable rxjs_1.
Something lacks in my code, maybe await or other functions from rxjs_1 obj, current code get me in rxjs_1 variable only ref to ‘function localRequire(deps, callback, errback)’ instead reference to RxJs and Observable. And, of course, OF() in rxjs_1 is undefined.
What lack in this code?

Uploading Image and saving it in table with other fields using react and spring boot

I have SpringBoot backend API that handle user registration, it looks like this:

@PostMapping("/signin")
public ResponseEntity < ? > authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {

    Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getEmail(), loginRequest.getPassword()));

    SecurityContextHolder.getContext().setAuthentication(authentication);
    String jwt = jwtUtils.generateJwtToken(authentication);

    UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
    List < String > roles = userDetails.getAuthorities().stream().map(item -> item.getAuthority()).collect(Collectors.toList());

    return ResponseEntity.ok(new JwtResponse(jwt, userDetails.getId(), userDetails.getEmail(), roles));
}

@PostMapping(value = "/signup", consumes = "multipart/form-data")
public ResponseEntity<?> registerUser(@RequestPart(value = "profilePicture", required = false) MultipartFile profilePicture,
                                      @RequestPart("signUpRequest") SignupRequest signUpRequest) {
    try {

        if (userRepository.existsByEmail(signUpRequest.getEmail())) {
            return ResponseEntity.badRequest().body(new MessageResponse("Error: Email is already in use!"));
        }

        User user = new User(signUpRequest.getEmail(), encoder.encode(signUpRequest.getPassword()));

        Set < String > strRoles = signUpRequest.getRole();
        Set < Role > roles = new HashSet < > ();

        if (strRoles == null) {
            Role userRole = roleRepository.findByName(ERole.ROLE_CLIENT).orElseThrow(() -> new RuntimeException("Error: Role is not found."));
            roles.add(userRole);
        } else {
            strRoles.forEach(role -> {
                switch (role) {
                    case "admin":
                        Role adminRole = roleRepository.findByName(ERole.ROLE_ADMIN).orElseThrow(() -> new RuntimeException("Error: Role is not found."));
                        roles.add(adminRole);
                        break;
                    case "mod":
                        Role modRole = roleRepository.findByName(ERole.ROLE_MODERATOR).orElseThrow(() -> new RuntimeException("Error: Role is not found."));
                        roles.add(modRole);
                        break;
                    case "freelancer":
                        Role freelancerRole = roleRepository.findByName(ERole.ROLE_FREELANCER).orElseThrow(() -> new RuntimeException("Error: Role is not found."));
                        roles.add(freelancerRole);
                        break;
                    default:
                        Role clientRole = roleRepository.findByName(ERole.ROLE_CLIENT).orElseThrow(() -> new RuntimeException("Error: Role is not found."));
                        roles.add(clientRole);
                }
            });
        }

        user.setRoles(roles);

        if (strRoles != null && strRoles.contains("freelancer")) {
            FreelancerProfile freelancerProfile = FreelancerProfile.createFromSignupRequestFreelancer(signUpRequest, user);

            Set < String > selectedSkills = signUpRequest.getSkills();
            if (selectedSkills != null && !selectedSkills.isEmpty()) {
                for (String selectedSkillName: selectedSkills) {
                    Skill skill = skillRepository.findBySkillName(selectedSkillName).orElseGet(() -> {
                        Skill newSkill = new Skill();
                        newSkill.setSkillName(selectedSkillName);
                        return skillRepository.save(newSkill);
                    });

                    freelancerProfile.getSkills().add(skill);
                }
            }
            user.setFreelancerProfile(freelancerProfile);
        } else {
            ClientProfile clientProfile = ClientProfile.createFromSignupRequestClient(signUpRequest, user);
            user.setClientProfile(clientProfile);
        }

        if (profilePicture != null) {
            logger.info("Received profile picture: {}", profilePicture.getOriginalFilename());
        } else {
            logger.info("No profile picture received");
        }

        if (profilePicture != null && !profilePicture.isEmpty()) {
            Photo photo = new Photo();
            photo.setData(profilePicture.getBytes());
            photo.setUser(user);
            user.setPhoto(photo);
        }

        userRepository.save(user);

        return ResponseEntity.ok(new MessageResponse("User registered successfully!"));
    } catch (Exception e) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new MessageResponse("Internal Server Error"));
    }
}`

And when I test it in postman like this:

key profilePicture as file and select file
key signUpRequest and value as:

{ "email": "[email protected]", "password": "asdfasdfsaf", "role": [ "client" ], "firstName": "asdfasdf", "lastName": "asdsad", "contactPhone": "asdasdasd", "location": "NY", "skills": [ null ], "portfolio": "", "yearsOfExperience": 0 }

user is saved success, but on my react part I can not save him, Guess I need to handle image process more better in frontend

import React, { useState, useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Formik, Field, Form, ErrorMessage } from "formik";
import { register } from "../slices/auth";
import validationSchema from "../services/utils/validationSchemas";
import Select from "react-select";
import useApiData from "../services/utils/useApiData";

const Register = () => {
  const [successful, setSuccessful] = useState(false);
  const [selectedRole, setSelectedRole] = useState("");
  const locations = useApiData("http://localhost:8080/api/utils/getAllLocations");
  const skills = useApiData("http://localhost:8080/api/utils/getAllSkills");

  const { message } = useSelector((state) => state.message);
  const dispatch = useDispatch();

  const initialValues = {
    email: "",
    password: "",
    role: "",
    firstName: "",
    lastName: "",
    contactPhone: "",
    location: "",
    portfolio: "",
    yearsOfExperience: 0,
  };

  const handleRegister = (formValue, { resetForm }) => {
    const {
      email,
      password,
      role,
      firstName,
      lastName,
      contactPhone,
      location,
      portfolio,
      yearsOfExperience,
      skills,
    } = formValue;
    setSuccessful(false);

    const rolesArray = Array.isArray(role) ? role : [role];

    const skillsArray = Array.isArray(skills) ? skills : [skills];

    const additionalFields = {
      firstName,
      lastName,
      contactPhone,
      location,
      portfolio,
      yearsOfExperience,
    };

    dispatch(
      register({
        email,
        password,
        role: rolesArray,
        skills: skillsArray,
        ...additionalFields,
      })
    )
      .unwrap()
      .then(() => {
        setSuccessful(true);
        resetForm();
      })
      .catch(() => {
        setSuccessful(false);
      });
  };


  const handleRoleChange = (event, setFieldValue) => {
    const role = event.target.value;
    setSelectedRole(role);
    setFieldValue("role", role);
  };

  const locationOptions = locations.map((location) => ({
    value: location,
    label: formatLocationName(location),
  }));

  function formatLocationName(location) {
    const words = location.split("_");
    const formattedWords = words.map(
      (word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()
    );
    return formattedWords.join(" ");
  }

  return (
    <div className="col-md-12 signup-form">
      <div className="card card-container">
        <Formik
          initialValues={initialValues}
          onSubmit={handleRegister}
          validationSchema={validationSchema}
        >
          {({ setFieldValue }) => (
            <Form>
              <div className="form-group">
                <label htmlFor="role">Select Role:</label>
                <div>
                  <button
                    type="button"
                    onClick={(e) => handleRoleChange(e, setFieldValue)}
                    value="client"
                    className="btn btn-secondary"
                  >
                    Client
                  </button>
                  <button
                    type="button"
                    onClick={(e) => handleRoleChange(e, setFieldValue)}
                    value="freelancer"
                    className="btn btn-secondary ml-2"
                  >
                    Freelancer
                  </button>
                </div>
              </div>

              {selectedRole === "freelancer" && (
                <>
                  <div className="form-group">
                    <label htmlFor="email">Email</label>
                    <Field name="email" type="email" className="form-control" />
                    <ErrorMessage
                      name="email"
                      component="div"
                      className="alert alert-danger"
                    />
                  </div>

                  <div className="form-group">
                    <label htmlFor="password">Password</label>
                    <Field
                      name="password"
                      type="password"
                      className="form-control"
                    />
                    <ErrorMessage
                      name="password"
                      component="div"
                      className="alert alert-danger"
                    />
                  </div>

                  <div className="form-group">
                    <label htmlFor="firstName">First Name</label>
                    <Field
                      name="firstName"
                      type="text"
                      className="form-control"
                    />
                    <ErrorMessage
                      name="firstName"
                      component="div"
                      className="alert alert-danger"
                    />
                  </div>

                  <div className="form-group">
                    <label htmlFor="lastName">Last Name</label>
                    <Field
                      name="lastName"
                      type="text"
                      className="form-control"
                    />
                    <ErrorMessage
                      name="lastName"
                      component="div"
                      className="alert alert-danger"
                    />
                  </div>

                  <div className="form-group">
                    <label htmlFor="contactPhone">Contact Phone</label>
                    <Field
                      name="contactPhone"
                      type="text"
                      className="form-control"
                    />
                    <ErrorMessage
                      name="contactPhone"
                      component="div"
                      className="alert alert-danger"
                    />
                  </div>
                  <div className="form-group">
                    <label htmlFor="location">Location:</label>
                    <Field name="location">
                      {({ field, form }) => (
                        <Select
                          {...field}
                          options={locationOptions}
                          isSearchable
                          placeholder="Search or select a location"
                          value={locationOptions.find(
                            (option) => option.value === field.value
                          )}
                          onChange={(selectedOption) =>
                            form.setFieldValue(
                              "location",
                              selectedOption ? selectedOption.value : ""
                            )
                          }
                        />
                      )}
                    </Field>
                    <ErrorMessage
                      name="location"
                      component="div"
                      className="alert alert-danger"
                    />
                  </div>

                  <div className="form-group">
                    <label htmlFor="skills">Select Skills:</label>
                    <Field
                      name="skills"
                      as="select"
                      multiple
                      className="form-control"
                    >
                      {skills.map((skill) => (
                        <option
                          key={skill.id || skill.skillName}
                          value={skill.skillName}
                        >
                          {skill.skillName}
                        </option>
                      ))}
                    </Field>
                  </div>

                  <div className="form-group">
                    <label htmlFor="portfolio">Portfolio</label>
                    <Field
                      name="portfolio"
                      type="text"
                      className="form-control"
                    />
                  </div>

                  <div className="form-group">
                    <label htmlFor="yearsOfExperience">
                      Years of Experience
                    </label>
                    <Field
                      name="yearsOfExperience"
                      type="number"
                      className="form-control"
                    />
                  </div>
                </>
              )}

              {selectedRole === "client" && (
                <>
                  <div className="form-group">
                    <label htmlFor="email">Email</label>
                    <Field name="email" type="email" className="form-control" />
                    <ErrorMessage
                      name="email"
                      component="div"
                      className="alert alert-danger"
                    />
                  </div>

                  <div className="form-group">
                    <label htmlFor="password">Password</label>
                    <Field
                      name="password"
                      type="password"
                      className="form-control"
                    />
                    <ErrorMessage
                      name="password"
                      component="div"
                      className="alert alert-danger"
                    />
                  </div>

                  <div className="form-group">
                    <label htmlFor="firstName">First Name</label>
                    <Field
                      name="firstName"
                      type="text"
                      className="form-control"
                    />
                    <ErrorMessage
                      name="firstName"
                      component="div"
                      className="alert alert-danger"
                    />
                  </div>

                  <div className="form-group">
                    <label htmlFor="lastName">Last Name</label>
                    <Field
                      name="lastName"
                      type="text"
                      className="form-control"
                    />
                    <ErrorMessage
                      name="lastName"
                      component="div"
                      className="alert alert-danger"
                    />
                  </div>

                  <div className="form-group">
                    <label htmlFor="contactPhone">Contact Phone</label>
                    <Field
                      name="contactPhone"
                      type="text"
                      className="form-control"
                    />
                    <ErrorMessage
                      name="contactPhone"
                      component="div"
                      className="alert alert-danger"
                    />
                  </div>

                  <div className="form-group">
                    <label htmlFor="location">Location:</label>
                    <Field name="location">
                      {({ field, form }) => (
                        <Select
                          {...field}
                          options={locationOptions}
                          isSearchable
                          placeholder="Search or select a location"
                          value={locationOptions.find(
                            (option) => option.value === field.value
                          )}
                          onChange={(selectedOption) =>
                            form.setFieldValue(
                              "location",
                              selectedOption ? selectedOption.value : ""
                            )
                          }
                        />
                      )}
                    </Field>
                    <ErrorMessage
                      name="location"
                      component="div"
                      className="alert alert-danger"
                    />
                  </div>
                </>
              )}

              {selectedRole && (
                <div className="form-group">
                  <button type="submit" className="btn btn-primary btn-block">
                    Sign Up
                  </button>
                </div>
              )}
            </Form>
          )}
        </Formik>
      </div>

      {message && (
        <div className="form-group">
          <div
            className={
              successful ? "alert alert-success" : "alert alert-danger"
            }
            role="alert"
          >
            {message}
          </div>
        </div>
      )}
    </div>
  );
};

export default Register;

import axios from "axios";

const API_URL = "http://localhost:8080/api/auth/";

const register = (
  email,
  password,
  role,
  firstName,
  lastName,
  contactPhone,
  location,
  skills,
  portfolio,
  yearsOfExperience
) => {
  return axios.post(API_URL + "signup", {
    email,
    password,
    role,
    firstName,
    lastName,
    contactPhone,
    location,
    skills,
    portfolio,
    yearsOfExperience,
  });
};

const login = (email, password) => {
  return axios
    .post(API_URL + "signin", {
      email,
      password,
    })
    .then((response) => {
      if (response.data.accessToken) {
        localStorage.setItem("user", JSON.stringify(response.data));
      }

      return response.data;
    });
};

const logout = () => {
  localStorage.removeItem("user");
};

const authService = {
  register,
  login,
  logout,
};

export default authService;

How I can now include profile picture upload and save it successfully on fronted part?

Printing nested items of array with known depth

I have a array which represents something like AST.

const ast = [
  { type: 'KEYWORD', value: 'let' },
  { type: 'IDENTIFIER', value: 'variable' },
  { type: 'OPERATOR', value: '=' },
  { type: 'NUMBER', value: 5 },
  { type: 'OPERATOR', value: '+' },
  {
    type: 'EXPRESSION',
    value: [
      { type: 'SOME_TYPE', value: 'some_value' },
      { type: 'ANOTHER_TYPE', value: 'another_value' },
      // ... more nested items
    ],
  },
];

function printNestedItems(array, depth) {
  function logItem(item, currentDepth) {
    if (currentDepth === depth) {
      console.log(`Type: ${item.type}, Value: ${item.value}`);
      return;
    }

    if (Array.isArray(item.value)) {
      item.value.forEach((nestedItem) => {
        logItem(nestedItem, currentDepth + 1);
      });
    }
  }

  array.forEach((item) => {
    logItem(item, 0);
  });
}

printNestedItems(ast, calculateDepth(ast) - 1) // calculateDepth function getting depth of array.

And lastly problem, it not printing anything.. Nor error. In Node.js version v20.10.0

Python requests issue [closed]

I have been stuck on this issue for the past 2 months and maybe stack overflow will help me, there is this website I am trying to web scrape which I cannot provide the code cause I am not near my PC but all it does is to scrape from a website using the python requests library, the problem is that it says that the browser needs to enable JavaScript and I don’t wanna use selenium, puppeteer or any other automated browser, the weird thing is it works with C# HttpRequest but not with python requests or Rust requests, in python and rust it says that thing with JavaScript, I’ll be infinitly thankful if somebody would give me a fine code example of how to properly enable JavaScript without browser automation.

Tried requests-html, didn’t work, I also need the program to work on rust as well

How to make the navbar stay fixed when a link is clicked?

I’m developing a navbar that disappears when the user scrolls down, and reappears when they scroll up (the navbar is always visible at the top of the page). However, when a link in the navbar (responsible for redirecting the user to a certain section of the page) is clicked, I would like the navbar to remain visible while the scroll navigates to that section and, only after that, return to its behavior of appearing and disappearing as the scroll.

Code:

// Navbar.jsx

import { useEffect, useState } from 'react';

import NavbarLink from './NavbarLink';

const Navbar = ({ isOpen, toggleMenu, navLinks }) => {
  const [sticky, setSticky] = useState(false);
  const [scrolling, setScrolling] = useState(0);

  const transitionClasses = sticky
    ? `transition-all duration-300 opacity-0 -translate-y-full`
    : `transition-all duration-300 translate-y-0`;

  useEffect(() => {
    window.addEventListener('scroll', () => {
      scrolling > window.scrollY ? setSticky(false) : setSticky(true);
      setScrolling(window.scrollY);
    });

  }, [scrolling]);

  return (
    <nav className={`${sticky && 'bg-opacity-95'} fixed top-0 bg-white w-full z-50 ${transitionClasses}`}>
      {/* Rest of the code (Not relevant to the question) */}

          {/* Links de Navegação */}
          <div className="hidden w-full md:block md:w-auto">
            <ul className="flex flex-row items-center gap-3.5 ml-3 font-medium lg:gap-5">
          <div className='hidden w-full md:block md:w-auto'>
            <ul className='flex flex-row items-center gap-3.5 ml-3 font-medium lg:gap-5'>
              {navLinks.map((link, index) => (
                <NavbarLink key={index} href={link.href} text={link.text} />
              ))}
            </ul>
          </div>
        </div>

       {/* Rest of the code (Not relevant to the question) */}
    </nav>
  );
};
// NavbarLink.jsx 

import { Link } from 'react-router-dom';
import { HashLink } from 'react-router-hash-link';

const NavbarLink = ({ href, text }) => {
  if (href.startsWith('/')) {
    return (
      <Link to={href} className={`text-xs lg:text-sm transition duration-300 group`}>
        <li>{text}</li>
        <span className='block max-w-0 group-hover:max-w-full transition-all duration-300 h-0.5 bg-gradient-to-br from-green-500 to-blue-400'></span>
      </Link>
    );
  };

  if (href.startsWith('#')) {
    return (
      <HashLink smooth to={href} className={`text-xs lg:text-sm transition duration-300 group`}>
        <li>{text}</li>
        <span className='block max-w-0 group-hover:max-w-full transition-all duration-300 h-0.5 bg-gradient-to-br from-green-500 to-blue-400'></span>
      </HashLink>
    );
  };
};

export default NavbarLink;

The only solution I’ve been able to come up with is to use setTimeout, but I wouldn’t want to use that solution because its behavior isn’t completely what I want.

NOTE: my code already produces the effect of appearing and disappearing as you scroll, but it still doesn’t support keeping the navbar visible when a link is clicked.

How to make this element only open on click of a button?

I have this js code:

(function (d, s, id, h) { var ftjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; var js = d.createElement(s); js.id = id; js.src = “https://cdn.formitable.com/sdk/v1/ft.sdk.min.js”; h && (js.onload = h); ftjs.parentNode.insertBefore(js, ftjs); }(document, ‘script’, ‘formitable-sdk’, function () { FT.load(‘Analytics’); }));

I also have a button with the class of “Nvigation / Primary”.

The code above is a popup wuth data-open=”1500″

Now i want the data to open only when the user clicks on the mentioned button.
How do i make this happen?

Tanks in advance !

How do I connect js files to Gulp?

I’m trying to figure out Gulp and I ran into this problem: .The js file is uploaded to dist, but the file script does not run, and HTML and CSS are displayed normally. Tell me, please, what is the error?

.js

console.log('Hello');

gulpfile.js

const webpack = require('webpack-stream');
gulp.task('js', function(){
    return gulp.src('./src/js/*.js')
        .pipe(webpack(require('./webpack.config.js')))
        .pipe(gulp.dest('./dist/js'));
});

gulp.task('default', gulp.series(
    'clean',
    gulp.parallel('html', 'sass', 'images', 'js'),
    gulp.parallel('server', 'watch')
));

webpack.config.js

const config = {

mode: 'production',

entry: {
    index: './src/js/index.js',
},

output: {
    filename: '[name].bundle.js',
},

module: {
    rules: [
        {
            test: /.css$/,
            use: ['style-loader', 'css-loader'],
        },
    ],
},

}

module.exports = config;

And in index.html I’m connecting the script

<scrip src="./js/index.bundle.js"></scrip>

Everything starts, but the string ‘Hello’ is not output in the console. Here is the result

enter image description here