Get values from 2 database statements with radio buttons

I am trying to connect two database statements via two radio buttons. As soon as I change the radio button value, these have to be retrieved again directly via the database.

I am currently trying to do this via HTML, JavaScript and Python. However, only one of the two statements is currently displayed.

js:

$("#id_base-0-show_null").change(function () {
        var show_null_value = document.querySelector('input[name=base-0-show_null]:checked').value;
        var checked_0 = document.getElementById('id_base-0-show_null_0').checked;
        var checked_1 = document.getElementById('id_base-0-show_null_1').checked;

        console.log(show_null_value, checked_0, checked_1);
       **currently doesn't do anything**

    });

exporter.py:

def get_last_values_of_target(self, target_type, target_name):
...

def get_zero_values_of_target(self, target_type, target_name):
...

manual_input.py:

def get_last_values_of_target(request):
    if is_ajax(request):
        target_type = int(request.POST['target_type'])
        target_name = request.POST['target_name']
        exporter = Exporter()
        exporter.station = target_type
        values = exporter.get_last_values_of_target(target_type, target_name) **here is the current single exporter where i'm trying to add a second one (get_zero_values_of_target)**
        return HttpResponse(simplejson.dumps({'values': values}), 'application/javascript')
    else:
        return HttpResponseBadRequest("Not allowed")

template:

{% block content %}
    <form action="" method="post" id="manual_input_form" name="manual_input_form">
        {% csrf_token %}
        <div class="timeDiffer">
            {% for base_form in base_formset %}
                ***
                <div class="{% if base_form.non_field_errors %}error {% else %}showDiff{% endif %}">
                    <div>{{ base_form.show_differences.label_tag }}{{ base_form.show_differences }}</div>
                </div>
                {% if base_form.show_differences %}
                    <div class="{% if base_form.non_field_errors %}error {% else %}showNull{% endif %}">
                        <div class="flex">{% trans base_form.show_null.label_tag %}{{ base_form.show_null }}</div>
                    </div>
                {% endif %}
            {% endfor %}
            <input type='hidden' id='source' name='source' value='Manual'>
        </div>
        {% for epoch_form in epochs_formset %}
            <table id="epoch_forms_table"
                   class="{% if counter >= 9 %}epoch_forms_table_long
                {% elif counter > 5 and counter < 9 %}epoch_forms_table_medium
                {% else %}epoch_forms_table{% endif %}">
            {% if forloop.first %}
                <tr class="title_row">
                    <th>{% autoescape off %}{% trans "Target name" %}{% endautoescape %}</th>
                    {% for k,v,i,z,b in sorted_title_list %}
                        {% if k == selected_item %}
                            <th>{{ z|capfirst }}</th>
                            {% if b|length == 1 %}
                                {% for key, value in b.items %}
                                    <th style="width: 50px;">
                                        <label for="unit_selector">
                                            <select class="master_select" id="unit_selector" name="unit_selector"
                                                    {% if b|length == 1 %}disabled{% endif %}>
                                                <option value="{{ value }}" id="{{ key }}">{{ value }}</option>
                                            </select>
                                        </label>
                                    </th>
                                {% endfor %}
                            {% else %}
                                <th style="width: 40px"><label for="unit_selector">
                                    <select class="master_select" id="unit_selector" name="unit_selector">
                                        {% for key, value in b.items %}
                                            <option value="{{ value }}" id="{{ key }}">{{ value }}</option>
                                        {% endfor %}
                                    </select>
                                </label></th>
                            {% endif %}
                        {% endif %}
                    {% endfor %}
                    <th class="last"></th>
                </tr>
            {% endif %}
            <tr class="value_row{% if epoch_form.errors %} error{% endif %}">
                <td><input id="id_epochs-0-target_name" name="epochs-0-target_name" class="group_left" type="text"
                           maxlength="100" size="16"></td>
                {% for k,v,i,z,b in sorted_title_list %}
                    {% if k == selected_item %}
                        <td><label><input id="id_epochs-0-{{ i }}" type="number" size="13" step="0.001"
                                          name="epochs-0-{{ i }}"></label></td>
                        {% if b|length == 1 %}
                            {% for key, value in b.items %}
                                <td class="{{ key }}_unit unit" id="{{ key }}"><label>{{ value }}</label></td>
                            {% endfor %}
                        {% else %}
                            {% for key, value in b.items %}
                                {% if forloop.first %}
                                    <td class="{{ key }}_unit unit" id="{{ key }}"><label>{{ value }}</label></td>
                                {% endif %}
                            {% endfor %}
                        {% endif %}
                    {% endif %}
                {% endfor %}
                <td><a href="#" class="button icon remove remove_row_button danger"></a></td>
            </tr>
            <tr id="last_value_row" class="last_value_row target_background_color">
                <td></td>
                {% for k,v,i,z,b in sorted_title_list %}
                    {% if k == selected_item %}
                        <td></td>
                        {% if b|length == 1 %}
                            {% for key, value in b.items %}
                                <td class="{{ key }}_unit unit" id="{{ key }}"><label>{{ value }}</label></td>
                            {% endfor %}
                        {% else %}
                            {% for key, value in b.items %}
                                {% if forloop.first %}
                                    <td class="{{ key }}_unit unit" id="{{ key }}"><label>{{ value }}</label></td>
                                {% endif %}
                            {% endfor %}
                        {% endif %}
                    {% endif %}
                {% endfor %}
                <td></td>
            </tr>
            <tr class="error_row">
                {% for field in epoch_form %}
                    <td>{{ field.errors }}</td>
                {% endfor %}
                <td></td>
            </tr>
        {% endfor %}
        </table>
...
    </form>
{% endblock %}

current Radio Buttons(Nullwert & Letzter Wert) with table

Maximum Update Depth Exceeded on a search modal

I have a dynamic search modal that queries the backend as users type. When a user selects one of the options it saves that option in state and is rendered as a Chip component. However, after updating our dependencies, the modal will not launch and the console is displaying this message

“Warning: Maximum update depth exceeded. This can happen when a
component calls setState inside useEffect, but useEffect either
doesn’t have a dependency array, or one of the dependencies changes on
every render.”

I logged the dependencies of my useEffect and none of them appear to be changing from render to render, however they are logged more times than I’d expect. Here is the component:

const SearchModalReturnField = ({
  open,
  fetchService,
  fetchQueryFieldName,
  handleClose,
  value,
  setValue,
  ...props
}) => {
  const [modalValue, setModalValue] = useState([]);
  const [inputValue, setInputValue] = useState('');
  const [options, setOptions] = useState([]);
  const [error, setError] = useState();

  const handleChangeInput = (event) => {
    setInputValue(event.target.value);
  };

  const handleChange = (event, newValue) => {
    setModalValue(uniqWith(newValue, isEqual));
  };

  const handleSelectIngredient = (event, newValue) => {
    setInputValue('');
    if (options.length > 0) {
      setModalValue(uniqWith([...modalValue, newValue], isEqual));
    }
  };

  const fetch = useMemo(
    () =>
      debounce((params, callback) => {
        fetchService(params)
          .then(callback)
          .catch((error) => {
            console.error(error);
            if (error && error.message) {
              return setError('Error: ' + error.message);
            }
            if (typeof error === 'string') {
              return setError('Error: ' + error);
            }
            return setError('Error encountered');
          });
      }, 500),
    [fetchService],
  );

  useEffect(() => {
    let active = true;

    if (inputValue === '') {
      setOptions([]);
      return undefined;
    }

    if (fetchService) {
      const params = {
        query: inputValue,
        limit: 200,
      };
      fetch(params, (results) => {
        if (active) {
          setOptions(map(results, fetchQueryFieldName) || []);
        }
      });
    }

    return () => {
      active = false;
    };
  }, [inputValue, fetchQueryFieldName]);

  const handleDelete = (item) => {
    setModalValue(filter(modalValue, (v) => v !== item));
  };

  const handleAccept = () => {
    setValue(uniqWith(concat(value, modalValue), isEqual));
    setModalValue([]);
    handleClose();
  };

  const handleCloseModal = () => {
    setModalValue([]);
    handleClose();
  };

  const optionsList = options.map((option, index) => {
    return (
      <OptionLabel
        key={index}
        onClick={(e) => handleSelectIngredient(e, option)}
        data-test="searchModal-foodOption"
      >
        {getHighlightedText(capitalize(option), inputValue)}
      </OptionLabel>
    );
  });

  if (isMobile()) {
    // Mobile view
    return (
      <MobileDialog
        open={open}
        handleClose={handleClose}
        height="fit-content"
        maxheight="85%"
        small="small"
        data-test="mobile-modal"
      >
        <DialogContainer flexDirection="column" alignItems="center">
          <Puller />
          <TopContainer flexDirection="column" alignItems="center">
            <MobileHeading>{props.heading}</MobileHeading>
            <MobileSubheading marginTop={'8px'}>
              {props.subheading}
            </MobileSubheading>
          </TopContainer>
          <SearchContainer flexDirection="column" alignSelf="flex-start">
            <MobileInputLabel>Search for food</MobileInputLabel>
            <DynamicSearchBar
              searchTerm={inputValue}
              handleChange={handleChangeInput}
              data-test="searchModal-ingSearch"
            />
          </SearchContainer>
          <MobileChipContainer wrap="wrap" alignItems="center">
            {modalValue.map((option, index) => (
              <ChipStyled
                key={index}
                label={props.getOptionLabel(option)}
                handleDelete={() => handleDelete(option)}
                bgcolor={props.chipBgColor}
                iconcolor="#FFFBFB"
                selected
                data-test="searchModal-ingChip"
              />
            ))}
          </MobileChipContainer>
          <OptionsContainer flexDirection="column">
            {optionsList}
          </OptionsContainer>
          {error && (
            <AlertStack
              messages={error}
              type="error"
              variant="filled"
              open={!!error}
              handleClose={() => setError(null)}
              autoHideDuration={10000}
            />
          )}

          <MobileAddButton
            alignItems="center"
            justify="center"
            backgroundcolor={props.chipBgColor}
            onClick={handleAccept}
            data-test="submit-items"
          >
            <MobileSubheading color="#fff">
              Add {props.heading}
            </MobileSubheading>
          </MobileAddButton>
          <div style={{ height: 8 }} />
          <MobileAddButton
            alignItems="center"
            justify="center"
            backgroundcolor="#fff"
            borderColor={colors.primary800}
            onClick={handleCloseModal}
          >
            <MobileSubheading color={colors.primary800}>
              Cancel
            </MobileSubheading>
          </MobileAddButton>
        </DialogContainer>
      </MobileDialog>
    );
  } else {
    // Web View
    return (
      <Dialog onClose={handleClose} open={open}>
        <DialogTitle>
          {handleClose ? (
            <TitleButton aria-label="close" onClick={handleCloseModal}>
              <CloseIcon />
            </TitleButton>
          ) : null}
        </DialogTitle>
        <DialogContent>
          <Title>Search Foods</Title>
          <AutocompleteStyled
            multiple
            autoComplete
            freeSolo
            includeInputInList
            filterOptions={(x) => x}
            options={options}
            getOptionLabel={props.getOptionLabel || ((option) => option.name)}
            value={modalValue}
            onChange={handleChange}
            renderInput={(params) => (
              <InputBase
                ref={params.InputProps.ref}
                inputProps={{
                  ...params.inputProps,
                  onChange(event) {
                    handleChangeInput(event);
                    return params.inputProps.onChange(event);
                  },
                }}
                placeholder={props.placeholder || ''}
                fullWidth
                endAdornment={
                  <InputAdornment position="end">
                    <IconButton aria-label="search" edge="end">
                      <SearchIcon />
                    </IconButton>
                  </InputAdornment>
                }
                data-test="searchModal-ingSearch"
              />
            )}
          />
          {error && (
            <AlertStack
              messages={error}
              type="error"
              variant="filled"
              open={!!error}
              handleClose={() => setError(null)}
              autoHideDuration={10000}
            />
          )}
          {modalValue.map((option, index) => (
            <ChipStyled
              key={index}
              label={props.getOptionLabel(option)}
              handleDelete={() => handleDelete(option)}
              bgcolor={props.chipBgColor}
              hovercolor={props.hoverColor}
              iconcolor="#FFFBFB"
              data-test="searchModal-ingChip"
              selected
            />
          ))}
        </DialogContent>
        <DialogActions>
          <AddButton
            buttonText="ADD"
            onClick={handleAccept}
            backgroundcolor={props.chipBgColor}
            hovercolor={props.hoverColor}
            data-test="searchModal-add"
          />
        </DialogActions>
      </Dialog>
    );
  }
};

No .on event firing. Asp.NET Core 6, JQuery

I am building an ASP.NET Core 6, JQuery application.

I have the following JQuery on my page

@section Scripts {
    @{
        await Html.RenderPartialAsync("_ValidationScriptsPartial");
    }
    <script>

        $(function () {
           $('#postcodeKnown').on('click', function () {
             alert("Changed")
           });
        });

    </script>
 }

I was wanting the on click event to fire on the following check box control –

<div class="row">
   <label class="control-label col-md-4">(02) Known</label>
   <div class="col-md-3 mb-1">
      <input id="postcodeKnown" type="checkbox" title="Please check if postcode is known." class="chkBox d-inline-flex mr-4 col-md-1" />
   </div>
</div>

The HTML rendered by the browser is –

<input id="postcodeKnown" type="checkbox" title="Please check if postcode is known." class="chkBox d-inline-flex mr-4 col-md-1">

Nothing happens when I click on the checkbox.

I have tried –

@section Scripts {
    @{
        await Html.RenderPartialAsync("_ValidationScriptsPartial");
    }
    <script>

        $(function () {
            $('#<%=postcodeKnown.ClientID%>').on('click', function () {
            alert("Changed");
        });
        
    </script>
 }

Still doesn’t work

I have tried it without the $(function () { around it, nothing.

At the bottom of my _layout.cshtml I have –

<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
@await RenderSectionAsync("Scripts", required: false)

Any help would be greatly appreciated.

Some laptop devices doesn’t trigger Javascript blur event functions while the window is on the full screen

I have written a code to detect whether the user is going out of the browser window. (like a lockdown browser)
window.addEventListener('blur', onBlur);

Most laptop devices I have tried successfully triggers the onBlur function if the window lost focus.
But some laptops doesn’t trigger the onBlur function while it’s on full screen. So far I found this issue only on HP laptops which are using Intel Iris GPU.

I have tried adding the blur event to the document.body as well. Didn’t work.

What is the correct way of declaring a prototype function in Javascript [duplicate]

We have code reviews at work and I saw some code from another colleague where he declared a javascript function like below

newdev.prototype.render = function render(){ ///Codes }

instead of

newdev.prototype.render = function(){ ///Codes }
I’m not sure if it’s the same or if there’s a problem with his approach. I never seen this from the different examples online.

I’ve searched google and found some question here but it’s not what I am looking for.

I found this but it’s not what I was looking for
Javascript Prototype What is Correct?
Two ways of declaring methods in Javascript

Exporting Highchart using JS PDF but its not supporting for Other Language Text translation

Exporting Highchart using JS PDF. its working for English Language and when we change other language it shows invalid character in JS PDF.

pdf.svg(svgImage, {
                    x: chartOffset.x,
                    y: chartOffset.y,
                    width: chartWidth,
                    height: chartHeight,
                }).then(() => {
                    pdf.save(fileName);
                    
                });

https://jsfiddle.net/ranjithkumarsv/La89x4n7/4/

Other language translation also need to support in JS PDF.

Note: We can see translated text inside svgImage.

in React remove element from list with callback function

I wanna make a project like “Google Keep” project but when remove element from Note list ,I faced a problem. I wrote a callback (remoteElement)and pass as probs(removeCallback) every Note Component.
and When I clicked button , element was removing from list with MoveTrashhandle() function

but I have a problem

example list have two elements. [“A”,”B”]

if first I remove “B” not be a problem. but

if first I remove “A” , I can’t remove “B”
and Trying to delete “A” from the list

Why Does this do ? , is callback function wrong ?

Note.js

    function Note({ children, removeCalback }, key) {
    const [note, setNote] = useState(children);
    const [fav, setfav] = useState(false);
    const dispatch = useDispatch();

    useEffect(() => {});

    const AddFavhandle = () => {
      dispatch(addFavorie(note));
      setfav(true);
    };
    const removeFavhandle = () => {
      setfav(false);
      dispatch(removeFavorite(note));
    };
    const MoveTrashhandle = () => {
      dispatch(addTrash(note));
      removeCalback(note);
    };

    return (
      <div className="d flex">
        <button
          onClick={() => {
            !fav ? AddFavhandle() : removeFavhandle();
          }}
          style={{ height: 20, width: 20, background: !fav ? "grey" : "yellow" }}
        ></button>
        <li>{children}</li>
        <button
          onClick={() => {
            MoveTrashhandle();
          }}
          className="bg-green-200"
        >
          MoveTrash
        </button>
      </div>
    );
  }
  export default Note;

ListComp.js

        function ListComp({ NoteStr }) {
      const [noteList, setnoteList] = useState([NoteStr]); //reducer a taşı
      const [continueBool, setContinueBool] = useState(false);

      useEffect(() => {
        !continueBool ? setContinueBool(true) : setnoteList([...noteList, NoteStr]);
      }, [NoteStr]);

      const removeElement = (item) => {
        console.log(item);
        const updatedList = noteList.filter((note) => note !== item);
        setnoteList(updatedList);
        console.log(noteList);
      };
      useEffect(() => {}, [noteList]);

      return (
        <div>
          {console.log("ListComp rendered")}
          {noteList && noteList.length > 0 ? (
            noteList.map((note, index) => (
              <>
                {console.log(note, "note")}
                <Note key={index} removeCalback={removeElement}>
                  {note}
                </Note>
              </>
            ))
          ) : (
            <li>Not bulunamadı</li>
          )}
        </div>
      );
    }

    export default ListComp

I would be glad if you help .Thanks.

Vite build stuck on ‘modules transform’

While building a svelte application with vite, the build process gets stuck on ‘modules transform’. No error is reported on the building logs.

I’ve tried several things, including but not limited to:

  • removing and reinstalling node modules
  • removing unused libs from package.json
  • disabling the minification process.
  • using a plugin to let vite accept top level awaits
  • building using a different js runtime (bun)
  • building in another machine

npm run dev works perfectly fine, so i don’t think it is a problem related to the application itself.

How to effectively mock @kesha-antonov/react-native-action-cable for Jest tests in a React Native project?

I’m currently working on a React Native project that utilizes @kesha-antonov/react-native-action-cable for WebSocket connections. As part of my testing strategy, I’m using Jest for unit testing. However, I’m facing challenges in properly mocking @kesha-antonov/react-native-action-cable within my Jest tests.

Here’s the mock implementation I’ve attempted:

    jest.mock('@kesha-antonov/react-native-action-cable', () => ({
      ActionCable: jest.fn().mockImplementation(() => ({
        createConsumer: jest.fn().mockImplementation(() => ({})),
      })),
      Cable: jest.fn().mockImplementation(() => {}),
    }));

Despite this mock setup, I’m having difficulty mocking the functionality of ActionCable and createConsumer effectively within my tests. It seems that the mock is not behaving as expected.

Could someone provide guidance on how to properly mock @kesha-antonov/react-native-action-cable for Jest tests in a React Native environment?

Mongoose Error – Can’t call openUri() on an active connection

I hope you are okay. I am trying to write some tests for my application and I am fairly new to node.js, mongoose, and js in general.
I have this dbconnection file:

const mongoose = require("mongoose");
const logger = require("../utility/logger");
const config = require("config");
const { MongoMemoryServer } = require("mongodb-memory-server");

let mongoServer;

async function connectDB() {
   if (mongoose.connection.readyState !== 0) {
      await mongoose.connection.close();
   }

   if (process.env.NODE_ENV === "test") {
      if (!mongoServer) {
         mongoServer = await MongoMemoryServer.create();
         const mongoUri = mongoServer.getUri();
         await mongoose.connect(mongoUri);
      }
   } else {
      const url = config.get("db");
      await mongoose
         .connect(url)
         .then(() => logger.info(`Connected to DB: ${url}`))
         .catch((err) => logger.error("Could not connect to DB.", err));
   }
}

async function disconnectDB() {
   if (mongoose.connection.readyState !== 0) {
      await mongoose.disconnect();
      if (mongoServer) {
         await mongoServer.stop();
      }
   }
}

module.exports = { mongoose, connectDB, disconnectDB };

And the test that I am trying to make it work:

const request = require("supertest");
const app = require("../../../app"); 
const { User } = require("../../models/userModel"); 
const {
   connectDB,
   disconnectDB,
} = require("../../../src/startup/dbconnection");

describe("User Authentication", () => {
   let userPayload;

   beforeAll(async () => {
      await connectDB();
   });

   afterAll(async () => {
      await disconnectDB();
   });

   beforeEach(() => {
      userPayload = {
         firstName: "John",
         lastName: "Doe",
         email: "[email protected]",
         password: "password123",
         phoneNumber: "1234567890",
      };
   });

   it("should register a user and authenticate the user", async () => {
      
      let res = await request(app).post("/api/auth/register").send(userPayload);

      expect(res.status).toBe(200);
      expect(res.body).toHaveProperty("email", userPayload.email);

      res = await request(app).post("/api/auth/login").send({
         email: userPayload.email,
         password: userPayload.password,
      });

      expect(res.status).toBe(200);
      expect(res.body).toHaveProperty("token");
   });

   it("should fail authentication with incorrect credentials", async () => {
     
      await request(app).post("/api/auth/register").send(userPayload);

      const res = await request(app).post("/api/auth/login").send({
         email: userPayload.email,
         password: "wrongPassword",
      });

      expect(res.status).toBe(400);
      expect(res.text).toContain("Invalid email or password");
   });
});

I always get this error:

 MongooseError: Can't call `openUri()` on an active connection with different connection strings. Make sure you aren't calling `mongoose.connect()` multiple times. See: https://mongoosejs.com/docs/connections.html#multiple_connections

I have rewritten dbconnection file several times. I have the env set to test, I check if there is an existing connection and if there is to force close it. I am not sure what can I do. I’ve tried debugging with gpt as well but gpt(gpt4) seems to either have old stuff in it or just doesn’t comprehend the problem at hand.
Please help, thank you!

Export grouped ag-grid row data to excel using native excel row groups

I have an ag-grid with row grouping and am exporting to excel. The client wants the data in the resulting excel file to be grouped using Excel’s native row groups.

I see in the ag-grid documentation that they provide a way to style row group names using processRowGroupCallback, but I don’t see any way to map row groups to Excel row groups.

Am I missing something? Is this possible? Or would you essentially have to write your own excel export functions from scratch, and know the inner working of excel file format and the implementation of row grouping there?

‘Axios’ doesn’t request again after token refresh – react native

I’m using axios with React Native

Now I’m sending request with accessToken to create profile and fix it.

So I made axiosInstace and baseURL.

And in axiosInstance header, I put ‘Authorization’ (accessToken).

The problem is, axios request works when it is before accessToken is expired.
So I can fix the profile several times before expired.

And if the accessToken is expired, the error comes with status code 401.
And my code reissue an accessToken.
Still, reissuing accessToken works!!

However, after reissuing accessToken, sending a new request doesn’t work.

I’m not sure why it doesn’t work.

Can you please help me?



import axios from 'axios';
import EncryptedStorage from 'react-native-encrypted-storage';

const baseURL = '-';
const axiosInstance = axios.create({ baseURL });

let _refreshingPromise = null;

const reissueToken = async () => {
    try {
        const refreshToken = await EncryptedStorage.getItem('refreshToken');

        if (!refreshToken) {
            throw new Error('refreshToken doesnt exist');
        }

        const response = await axios.post(`${baseURL}/auth/renew`, { refreshToken });

        const newAccessToken = response.data.accessToken;
        await EncryptedStorage.setItem('accessToken', newAccessToken);

        return newAccessToken;
    } catch (error) {
        console.error('reissue failed,', error);
        throw error;
    }
};

axiosInstance.interceptors.request.use(
    async (config) => {
        try {
            const accessToken = await EncryptedStorage.getItem('accessToken');
            config.headers['Content-Type'] = 'application/json';
            config.headers['Authorization'] = accessToken;

            console.log('original request's config:', config);
            return config;
        } catch (error) {
            console.error('request interceptor failed:', error);
            return Promise.reject(error);
        }
    },
    (error) => {
        console.error('request interceptor error :', error);
        return Promise.reject(error);
    }
);


axiosInstance.interceptors.response.use(
    (response) => {
        console.log('request succeed!');
        return response;
    },
    async (error) => {
        const { config,response } = error;
        const status = response? response.status : null;

    
        console.log("response status code : ", status);
        if(status === 502) {
            console.log("502 error");
            
        }
        if (status === 401) {
            console.log("start!");
            if (!_refreshingPromise) {
                console.log(_refreshingPromise);
                _refreshingPromise = new Promise((resolve, reject) => {
                    reissueToken()
                        .then((newAccessToken) => {
                            console.log("newToken : ", newAccessToken);
                            config.headers['Authorization'] = newAccessToken;
                            console.log(config.headers.Authorization);

                            axios(config)
                            .then((response) => {
                                
                                console.log('response after request:', response.data);
                                resolve(response); // 요청 성공 시 Promise를 성공 처리
                            })
                            .catch((error) => {
                                console.log("request failed!");
                                reject(error); // 요청 실패 시 Promise를 실패 처리
                            })
                            .finally(() => {
                                _refreshingPromise = null;
                            });
                        })
                        .catch((reissueError) => {
                            reject(new Error('error', reissueError));
                        })
                        .finally(() => {
                            _refreshingPromise = null;
                        });
                });
            }

            return _refreshingPromise;
        }

        return Promise.reject(error);
    }
);

export default axiosInstance;

  1. I tried change axios version. – now it is v1.6.8

  2. made new Promise to have only 1 request.

How do I get rid of this error, whenever the function is called is gives an error?

I am creating a project to query youtube videos, where you paste a link of yt video and then you can ask questions based on the video. So, first I get a audio stream of video using ytdl-core api and I wrote a speech to text function which sends a req to openai api and wait for the response and then return the text data. But when creating a configuration object it says “configuration is not a constructor”
here is the reference code:

const PineconeClient = require("@pinecone-database/pinecone").PineconeClient;
const PineconeStore = require("langchain/vectorstores/pinecone").PineconeStore;
const RecursiveCharacterTextSplitter = require("langchain/text_splitter").RecursiveCharacterTextSplitter;
const Document = require("langchain/document").Document;
const OpenAIEmbeddings = require("langchain/embeddings/openai").OpenAIEmbeddings;
require("dotenv").config();
const { OpenAIApi } = require("openai");
const { Configuration } = require("openai");
const fs = require("fs");
const axios = require("axios");
const props = {
  openai_api_key: process.env.OPENAI_API_KEY,
  pinecone_api_key: process.env.PINECONE_API_KEY,
  pinecone_env: process.env.PINECONE_ENV,
  pinecone_index: process.env.PINECONE_INDEX,
  pinecone_delete: process.env.PINECONE_DELETE,
};
async function speechToText(key) {
  console.log("speech to Text function called");
  const configuration = new Configuration({
    apiKey: key,
  });
  const openai = new OpenAIApi(configuration);
  console.log("sending api request to openai");
  const resp = await openai.createTranscription(
    fs.createReadStream("compressedAudio.mp3"),
    "whisper-1"
  );
  console.log("Api response recieved");
  return resp.data.text;
}

pls tell a fix

I tried removing the new keyword, but it didn’t worked. Also tried import the module differently that also did’nt work.

Query string accent encoding issue between JS and vb.net

The problem

When I try to retrieve the query string parameter the accent decoding doesn’t work correctly.


Environment & info

  • Website html/js and server side .net Framework 4.0 (written in vb)
  • I don’t have access to the server, and therefore not even to IIS
  • In the web.config I set the encoding to UTF-8: <globalization uiCulture="it" culture="it-IT" requestEncoding="utf-8" responseEncoding="utf-8"/>
  • I’m quite convinced that this problem wasn’t there until a few days (months?) ago.
  • I can’t provide the site to check the problem on.

Code & test

$txtSearchSimple.val() is an input/textbox that contains: “perchè questo”

//JS
console.log(encodeURIComponent($txtSearchSimple.val()));
window.location = '/page.aspx?t=' + encodeURIComponent($txtSearchSimple.val());

In console the browser write correctly: perch%C3%A8%20questo

But on VB:

Session("TEST_Acc") = Request.QueryString("t") & " --> "
Session("TEST_Acc") &= Uri.UnescapeDataString(Request.QueryString("t")) & " -> " 
Session("TEST_Acc") &= HttpUtility.UrlDecode(Request.QueryString("t")) & " -> " 
Session("TEST_Acc") &= HttpUtility.UrlDecode(Request.QueryString("t")) & " -> " 
Session("TEST_Acc") &= HttpUtility.UrlDecode(Request.QueryString("t"), Encoding.UTF8) & " -> " 
Session("TEST_Acc") &= HttpUtility.UrlDecode(Uri.UnescapeDataString(Request.QueryString("t")), Encoding.UTF8)

Session("TEST_Acc2") = HttpUtility.UrlDecode(Uri.UnescapeDataString("perch%C3%A8%20questo"), Encoding.UTF8) & " -> " 
Session("TEST_Acc2") &= HttpUtility.UrlDecode(Uri.UnescapeDataString("perchè questo"), Encoding.UTF8) 

The results:

'TEST_Acc:
perchè questo --> perchè questo -> perchè questo -> perchè questo -> perchè questo

'TEST_Acc2:
perchè questo -> perchè questo

I also attach the result of the chrome request/response

enter image description here

I don’t understand how it is possible that between the request (which seems correct) and the server-side fetch it is decoded incorrectly even before I can query the value with the Request.QueryString.

Thank you very much for the help you want to give me.