Azure Function with Javascript as http trigger language – missing function.json when generated via VS Code

I had created Azure Function with Javascript as the platform language. It works and deploys just fine. However, it’s missing function.json. Is it expected to generated as I seen other posts having it. The reason I am asking this is because I need to add other dependencies (import modules) to write the code to connect to Azure Cosmo DB as an example.

Please let me point me the right path as I tried searching around but no luck for Azure Function with Javascript and if I do found them, they are older posts with function.json created automatically.

Thanks in advance.

I created a boilerplate using VS Code but missing function.json. Is this expected to be generated? It was shown on other tutorials and posts.

Nextjs Google Oauth2 invalid_grant error Gaxios

Trying to authenticate with googleapis oauth client.

Getting the following error:

 ⨯ node_modules/.pnpm/[email protected]/node_modules/gaxios/build/src/gaxios.js (141:22) @ Gaxios._request
 ⨯ Error: invalid_grant
    at setCredentials

The weird part is this only happens when I call the set credentials method on the client

I am able to get a valid token response. Here’s my code:

export const generateUrl = async (): Promise<string> => {
  const url = sheets.generateAuthUrl({
    access_type: "offline",
    scope: googleSheetsScopes,
  })
  console.log("url", url)
  return url
}

export const setCredentials = async (code: string): Promise<void> => {
  const user = await currentUser()
  if (!user) {
    throw new Error("Not logged in")
  }
  const { tokens } = await sheets.getToken(code)

  try {
    console.log("tokens", tokens)
    sheets.setCredentials(tokens) ==> error here
  } catch (e) {
    console.log("e", e)
  }
}

I get a valid token when I log tokens to the console:

tokens {
  access_token: '****',
  refresh_token: '****',
  scope: 'https://www.googleapis.com/auth/spreadsheets',
  token_type: 'Bearer',
  expiry_date: 1704909622185
}

cant write on my EXCEL file using Javascript

i have been trying to write on a constant (fixed path) excel file where i want to add a new row every time the save button is clicked but feeling lost and have no clue how to get it done

my JS code

document.getElementById('save').addEventListener('click', async function saveStudent() {
    // Note: You don't need to use require for XLSX in a browser environment
    // Include SheetJS library in your HTML file using a script tag
    // <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.16.9/xlsx.full.min.js"></script>

    // You can directly use the global XLSX object
    const XLSX = window.XLSX;

    const workbook = XLSX.readFile("students.xlsx");
    const worksheet = workbook.Sheets["Sheet1"];

    // Retrieve values from the form
    var fullname = document.getElementById('fullname').value.trim();
    var grade = document.getElementById('grade').value.trim();
    var birthdate = document.getElementById('birthdate').value.trim();
    var address = document.getElementById('address').value.trim();
    var phonenumber = document.getElementById('phonenumber').value.trim();

    // Check if any field is empty
    if (!fullname || !grade || !birthdate || !address || !phonenumber) {
        alert('Please fill in all information.');
        return;
    }

    // Add data to the worksheet
    worksheet.addRow({ fullname: fullname, grade: grade, birthdate: new Date(birthdate), address: address, phonenumber: phonenumber });

    console.log('added');

    // Write the workbook back to the file (save changes)
    XLSX.writeFile(workbook, "students.xlsx");

    // Clear the form inputs
    clearInputs();
});

// Your clearInputs function remains the same
function clearInputs() {
    // Clear all input fields
    document.getElementById('fullname').value = '';
    document.getElementById('grade').value = '';
    document.getElementById('birthdate').value = '';
    document.getElementById('address').value = '';
    document.getElementById('phonenumber').value = '';
}

an error that keeps coming up is :

xlsx.full.min.js:12  Uncaught (in promise) Error: Cannot access file students.xlsx
    at j (xlsx.full.min.js:12:15462)
    at Wg (xlsx.full.min.js:23:13327)
    at Object.Vg (xlsx.full.min.js:23:14506)
    at HTMLButtonElement.saveStudent (addstudentscript.js:9:27)  

and whenever i try to import-> require(“xlsx”); it gives the following error

addstudentscript.js:2  Uncaught (in promise) ReferenceError: require is not defined
    at HTMLButtonElement.saveStudent (addstudentscript.js:2:18)

i tried a lot of tutorials but i cant figure out on how to write or edit the original sheet with no new copies

busqueda en input con javascript resulta en objet Objet

intento que un input del menu busque en tiempo real en mi bd nombres de articulos que coincidan con lo escrito, me muestra los resultados, sin embargo al dejar de tipear, musestra objet objet

`document.getElementById('searchItem').addEventListener('click', function() {
document.getElementById('searchInput').style.display = 'block';
});

document.getElementById('searchInput').addEventListener('input', function() {
    var query = this.value;
    var xhr = new XMLHttpRequest();
   xhr.open("GET", "fetch.php?q=" + query, true);
   xhr.onreadystatechange = function() {
     if (this.readyState == 4 && this.status == 200) {
        var results = JSON.parse(this.responseText);
        var resultsContainer = document.getElementById('results');
        resultsContainer.innerHTML = '';
        if (results.length > 0) {
          resultsContainer.style.display = 'block';
          for (var i = 0; i < results.length; i++) {
             var li = document.createElement('li');
             li.textContent = results[i].nomitem;
             resultsContainer.appendChild(li);
          }
        } else {
     resultsContainer.style.display = 'none';
     }
  }
};
xhr.send();

});`

intente cambiando el evento de input a change, pero empeora y solo muestra los resultados con objet Objet

`document.getElementById(‘searchItem’).addEventListener(‘click’, function() {
document.getElementById(‘searchInput’).style.display = ‘block’;
});

document.getElementById('searchInput').addEventListener('change', function() {
  var query = this.value;
  var xhr = new XMLHttpRequest();
  xhr.open("GET", "fetch.php?q=" + query, true);
  xhr.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var results = JSON.parse(this.responseText);
      var resultsContainer = document.getElementById('results');
      resultsContainer.innerHTML = '';
      if (results.length > 0) {
        resultsContainer.style.display = 'block';
        for (var i = 0; i < results.length; i++) {
          var li = document.createElement('li');
          li.textContent = results[i].nomitem;
          resultsContainer.appendChild(li);
        }
      } else {
        resultsContainer.style.display = 'none';
      }
    }
  };
  xhr.send();
});`

Highlighting a different word in a list every few second using jquery [duplicate]

I’ve a list of words in the format “xxx – yyy – zzz”, so ” – ” being the separator. What I’m hoping to do is simply increase the size of one of the words at random every few seconds so as to highlight that word.

My approach is wrap the list in a div:

<div id="highlight-list">XXX - YYY - ZZZ</a>

and then use something like this (not tested yet!):

var fullList = document.querySelector("#highlight-list");
var regex = // *- *//;
var eachItem = fullList.innerHTML.split(regex);
fullList.innerHTML = "";
for(var word in eachItem){
  fullList.innerHTML += "<span>" + eachItem[word] + "</span>";
}

to wrap individual words within the Div with a span. My grand plan is to then apply a CSS class to each span at random for a few seconds, then remove the class, and repeat… but I’m struggling with the first step!

Any help would be hugely appreciate, thank you.

Im stuck at this weather app javaScript project because of 2 bugs

I’m stuck at my new weather app javaScript project because of 2 bugs. I don’t understand what I did wrong since I followed everything just like in the tutorial.

I receive undefined back once I try to search up a city name and the numbers don’t even change

yt tutorial I followed: https://www.youtube.com/watch?v=MIYQR-Ybrn4
I watched the video multiple times and I don’t find any typing mistakes.

This is what the Browser tells me but I don’t understand why the lines are wrong

This is what the console says

codepen.io/num_/pen/eYXdzpN

Google app script for user mail based filter

Sir
I have datas range A1:D1000 in Master sheet with dropdown
I need my users to filter their datas to edit by their email id.

I need google script

When user login based on email id filter specific datas for that user to edit. At same time many user to edit their specific datas alloted for them.
Thank you

I need script code for google sheet

REACT Comment trouver l’erreur et comment ka corriger?

ERROR
Cannot read properties of undefined (reading ‘map’)
TypeError: Cannot read properties of undefined (reading ‘map’)
at http://localhost:3000/static/js/bundle.js:214:191

when i try to search a city it gives me this error and it gives me this line of code can you help me thank you so much

Send value via bluetooth writeValueWithResponse return undefined

I send hex value with writeValueWithResponse function from chrome and i get undefined
when i try with with the app serial bluetooth terminal in android i succeed to get hex value in return from cellocator device

let characteristic;// other function make sure instance here
let request = '4D324300000000000000000000';
let request2 = '4D3243000000000000000000000D0A';

function sendValue() {

       // const encoder = new TextEncoder();
      //  const data = encoder.encode(request);

    //let buffer = new Uint8Array(request.match(/../g).map(h=>parseInt(h,16))).buffer

let array = new Uint8Array(request.match(/[da-f]{2}/gi).map(function (h) {
  return parseInt(h, 16)
}))

       characteristic.writeValueWithResponse(array)
        .then(res => {
            console.log('writeValue res ' + res);
        })
        .catch(error => {
            console.error('writeValue error ' + error);
        });
     
    } else {
        console.log('Characteristic not available');
    }
}

What to use in place of datasetStrokeWidth for the lastest chart.js?

This demo is attempting to convert this demo to the latest version of chart.js.

What should we use in place of datasetStrokeWidth? It controls the width of the line.

  options: {
    responsive: true,
    datasetStrokeWidth: 10,
    pointDotStrokeWidth: 14,
...

I tried borderWidth which is in the documentation, however the ChartConfiguration type produces a lint error … and it also does not have any effect …

using Built-in Json object,uncaught syntax error:missing initializer in const declaration

I am trying to learn about built-in JSON object in Javascript. I am trying to convert a Javascript object into a JSON string. I am getting an uncaught syntax error: missing initializer in the const declaration.

    <html>

        <body>

            <h1>Objects</h1>

            <script>

            const product2{

                name:'shirt',
                'delivery-time':'1-day',

                rating:{
                    stars:4.5,
                    count:87
                }

            };
            console.log(product2);


           console.log(JSON.stringify(product2));
            </script>
        </body>
    </html>

I tried looking it up on google, but it was more about dot notation. I also read that in Java script objects are references. the code doesn’t make a copy of the object, it just makes a copy of the reference that points to the object and we will be able to change the const object where whereas the const variable prevents us from doing so. what should I do to not get that error?

Error 400: “The field is required” when I tried to consume a put method in React

I don’t see what’s failing in the code; I want to consume a Put method, but when I do, the response returned by the API is:

"errors": {
    "$": [
        "The JSON value could not be converted to MTE.API.Request.Supplier.PutSupplierRequest. Path: $ | LineNumber: 0 | BytePositionInLine: 2."
    ],
    "request": [
        "The request field is required."
    ]
}

What I’m trying to achieve is that, visualizing a series of data in a table, I can edit the information from a modal. I think the problem is precisely there, but I have no idea why. The other methods works well (get, post and delete).

I structured the request like this:
For more context: I have a const to define the url: http://api.com/api/suplier

 actualizarProveedor: async (proveedorData) => {
    try {
      const response = await axios.put(`${API_BASE_URL}`, proveedorData, {
        headers: {
          'Content-Type': 'application/json',
        },
      });
  
      console.log('Actualizar Proveedor:', response.data);
      return response.data;
    } catch (error) {
      console.error('Error en actualizarProveedor:', error);
      throw error;
    }
  },

And this is how the data is sent to the request:

const handleGuardarEdicion = async (editedProveedor) => {
    try {
      await apiCompras.actualizarProveedor(editedProveedor.id, {
        id: editedProveedor.id,
        name: editedProveedor.nombre,
        ruccode: editedProveedor.numeroRUC,
      });
  
      console.log('Proveedor actualizado exitosamente:', editedProveedor);
  
      cargarProveedores();
    } catch (error) {
      console.error('Error al actualizar proveedor:', error);
    }
  };

Finally, this is how the modal is constructed:

<Dialog open={modalOpen} onClose={handleCloseModal}>
  <DialogTitle>Editar Proveedor</DialogTitle>
  <DialogContent>
    <form>
      <TextField
        label="Nombre"
        variant="outlined"
        margin="normal"
        fullWidth
        required
        value={selectedProveedor ? selectedProveedor.name : ''}
        onChange={(e) => handleEditFieldChange('name', e.target.value)}
      />
      <TextField
        label="Código RUC"
        variant="outlined"
        margin="normal"
        fullWidth
        required
        value={selectedProveedor ? selectedProveedor.ruccode : ''}
        onChange={(e) => handleEditFieldChange('ruccode', e.target.value)}
      />
    </form>
  </DialogContent>
  <DialogActions>
    <Button onClick={() => { handleGuardarEdicion(selectedProveedor); handleCloseModal(); }} color="primary">
      Cerrar
    </Button>
  </DialogActions>
</Dialog>

I’ve made changes that have altered the error message to this:

"errors": {
    "Id": [
        "The field Id must be between 1 and 2147483647."
    ],
    "Name": [
        "The Name field is required."
    ],
    "RUCCODE": [
        "The RUCCODE field is required."
    ]
}

Adding this to the request:

try {
  const requestData = {
    request: {
      id: supplierData.id,
      name: supplierData.name,
      ruccode: supplierData.ruccode,
    }
  };

How to add dynamic validators to an angular reactive form control

I was using angular’s reactive forms. The use-case is that the form is being created dynamically with the field’s value and types coming from BE. Also the validators for the fields are coming from BE too.
I am able to create the form dynamically but adding validators dynamically is giving me error.

control.addValidators(Validators[validator]()

where validator is a dynamic string which could be ‘pattern’, ‘required’, ‘minLength’ etc.

The error I am getting for this are

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof Validators'.
No index signature with a parameter of type 'string' was found on type 'typeof Validators'.

VideoJS restarts video at the beginning after 10s playback

I do have a page which I can’t really change the source code of, but it’s played in an environment where I can inject JS (like you’d do with GreaseMonkey).

In this page, there’s a video player which causes me some issues, so I replace it with VideoJS. I want the video to play in full screen. Here’s the code that does that:

var player = null;

function loadCss(url, callback)
{
  var head = document.getElementsByTagName('head')[0];
  var style = document.createElement('link');
  style.href = url;
  style.type = 'text/css';
  style.rel = 'stylesheet';

  style.onreadystatechange = callback;
  style.onload = callback;

  head.append(style);
}

function loadScript(url, callback)
{
  var head = document.getElementsByTagName('head')[0];
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = url;

  script.onreadystatechange = callback;
  script.onload = callback;

  head.appendChild(script);
}

function replacePlayer()
{
  var videos = document.getElementsByTagName('video');
  var source = document.querySelector('video source').getAttribute('src');

  var newVideo = document.createElement('video');

  newVideo.width = 1920;
  newVideo.height = 1080;
  newVideo.classList.add("video-js");
  newVideo.classList.add("vjs-default-skin");

  newVideo.id = 'videojs';

  var newVideoSource = document.createElement('source');
  newVideoSource.src = source;
  newVideo.appendChild(newVideoSource);



  while (document.body.children.length > 0)
  {
    document.body.children[0].remove();
  }
  document.body.appendChild(newVideo);

  player = window.player = videojs('videojs');

  var fsb = document.createElement('button');
  fsb.id = 'btn_patch_fullscreen';
  fsb.style.position = "absolute";
  fsb.style.top = 0;
  fsb.style.left = 0;
  fsb.style.width = "100%";
  fsb.style.height = "100%";
  fsb.style.backgroundColor = "rgba(0,0,0,0)";

  var body = document.getElementsByTagName('body')[0];

  fsb.addEventListener('click', (e) => {
    player.requestFullscreen();
    fsb.remove()
  });

  body.appendChild(fsb);
  return true;
}

loadCss("https://unpkg.com/[email protected]/dist/video-js.css", () => {

  loadScript("https://unpkg.com/[email protected]/dist/video.js", function () {
    var timer = setInterval(() => {
      if (!replacePlayer())
      {
        return;
      }
      clearInterval(timer);
      player.ready(function () {
        player.play();
      });
    }, 100);
  });
});

Now when I execute that code, my video starts playing in full screen, and after 10s, it starts playing again from the beginning (only 1 time, it does not loop). On top of it, if I execute “player.currentTime()” right after it goes to the beginning, it will indicate the current time is about 10s, so it does not exactly seems like it did seek back.

Digging, I found that not loading the CSS “fixes” the issue. So I dug in the CSS. I made a copy of it, played with it. It turns out that if I comment out lines 546 and 547, my video won’t be full screen, BUT it doesn’t loop.

I’m very puzzled as to why setting width & height to 100% causes some kind of loop…
And I need my video to not restart, and be full screen…

In React, in a nested component, can I render a sibling component which properties are calculated by the previous sibling component’s rendering?

I need to render a component child that depends on data that is constructed when rendering previous sibling component.

I want to use the fact that React follows a strict order when rendering nested components. The code explains itself:

const DQCustomLayout = ({ document, questionIDs, }) => {

  const layoutIDtoQuestionDict = useSelector((state) => state.dqN.LayoutIDtoQuestionDict);

  const questionsPendingToBeRendered = [...questionIDs];
  const handleQuestionRendered = (questionID) => {
    const i = questionsPendingToBeRendered.indexOf(questionID);
    if (i == -1) { return; }
    questionsPendingToBeRendered.splice(i, 1);
  };

  if (!document) {  // ...or error in parsing
    console.log("DQCustomLayout no document");
    return null;
  }
  else {
    return (
      <View>
        { document.children.map((node, i) => { 
          return (
            <Node 
              key={i} 
              node={node} 
              index={i} 
              layoutIDtoQuestionDict={layoutIDtoQuestionDict}
              onQuestionRendered={handleQuestionRendered}
            />
          );
        })}
        <DQNoLayout questionIDs={questionsPendingToBeRendered} />
      </View>
    );
  }

};

export default DQCustomLayout;

The View renders a tree-like structure that updates a list of the elements being rendered.
The list is not stored as state because it is being used in the same rendering.
DQNoLayout needs the View rendering to finish to have the full list of pending-to-render elements before start to render itself.

This apparently works. But I want to be sure it is a valid React usage.
Summarizing, my questions are:

Is this a valid React usage scenario, based on the rendering order React uses?

Is it correct to use the variable questionsPendingToBeRendered the way it is being used, not as a state but as a local variable being modified by “state-set-alike” function?