How to get information from Google sheet using API

I’m trying to send data from google sheet using POST.

Actually it works, if I write data in code. But I wand to get it from google sheet

My code

function sendDataToRoistatAPI() {
  var url = "https:XXX";
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = spreadsheet.getSheetByName("Users"); 

  var data = sheet.getDataRange().getValues();

  for (var i = 0; i < data.length; i++) {
    var rowData = data[i];
    var payload = {
      manual_custom_metric_id: rowData[1], 
      source: rowData[2], 
      value: rowData[3], 
      period: rowData[4], 
    };

    var options = {
      method: "post",
      contentType: "application/json",
      payload: JSON.stringify(data),
    };

    var response = UrlFetchApp.fetch(url, options);
    Logger.log(response.getContentText()); 
  }
}

The mistake is
{“status”:”error”,”error”:”incorrect_request”,”description”:”Argument value is not a positive valuenRequired argument period is missingnArgument manual_custom_metric_id is not a positive integer number”}

In google sheet named Users I have colums: manual_custom_metric_id,source,value,period

The background image ends at some point React.js

First of all, sorry for my bad English. On the site I have made, when I press the send button by taking information such as name and surname from the user with the form, it is added to the table you see in the picture, but after a point, the background image does not continue, a white field appears. how can I fix it? (I’m using react)

My css codes:

.bolum1{
    background-image: url(Assets/bg1.png);
    background-repeat: no-repeat;
    background-size: cover;
    background-position: 50% 0;
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
}
.katman{
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.6 );
    position: absolute;
    top: 0;
    left: 0;

}

pic

bolum1: editing the background image.
katman: giving the background a dark color (briefly layer)

How to sanitize JavaScript objects using the Zod (or any other) library

I want to define an object schema with Zod.js and use it to ensure that whatever input value I send to the parse method, the output object will be filled with default values when

  1. the value is missing in the input,
  2. the value is of wrong type.

For example let’s have a schema for a Person:

const PersonSchema = z.object({
  address: z.object({
    street: z.string().default('Trafalgar Square'),
    city: z.string().default('London'),
  }).default({}),
});

const person = PersonSchema.parse({});

This works nicely when address is missing. But when it is of wrong type, the parsing fails. I tried to use the catch method, but then I have to duplicate the default values in adress:

const PersonSchema = z.object({
  address: z.object({
    street: z.string().default('Trafalgar Square'),
    city: z.string().default('London'),
  }).default({}).catch({ street: 'Trafalgar Square', city: 'London' }),
});

This is totally impractical for larger data structures. Is there a way to do this with Zod? Or maybe some of the other input validation libraries can do this?

Not able to fetch data from mongodb server

I am connected to mongodb database using npm. And I am trying to print all data stored in table company.

Here is my code :

    var mongoose = require("mongoose");
    var empSchema =  new mongoose.Schema({empId:Number, empName:String, Salary:Number });
    var empModel = mongoose.model("company",empSchema);
    mongoose.connect("mongodb://localhost/company");
    
    async function myItems() {
    const itemFound = await empModel.find({});
    if(itemFound.length != 0)
        console.log(itemFound);
    else
        console.log("No data found");
}

myItems();

Output :

    No data found

After creating table, I have inserted data in it like this :

company> db.company.insertOne({"empId":1, "empName": "John", "Salary": 10000});
{
  acknowledged: true,
  insertedId: ObjectId("655b231b7ec16f57c1b72326")
}
company>

I tried to check whether it is inserted in the table or not like this :

company> db.company.find()
[
  {
    _id: ObjectId("655b231b7ec16f57c1b72326"),
    empId: 1,
    empName: 'John',
    Salary: 10000
  }
]
company>

If there is a data in the table, why I can not fetch it ?
What is wrong in my code ?

apply syntax highlighting to a piece of text which may contain codeblocks

I have a string of text, this string is multiline and it may contain a code block enclosed within triple backticks. It may also have an inline code string. The location of these code blocks is not known (it may be at the end of string or in the middle of string), the language of these code blocks is known. For example:

This is normal text
``
if __name__ == __main__:
    print('hello')
``

(I used double backticks instead of triple, couldn’t figure out how to render triple backticks inside triple backticks on stackoverflow, but in my string it is always triple backticks)

How can I apply syntax highlighting to the code block while keeping the normal text outside of syntax highlighting. Essentially I want it to look like, how this question looks like on the stackoverflow, with code block in a separate block. I would also like to add a copy button to the code block and show the language of code block.

(I am using svelte and tailwindcss for the front end)

What I have already tried:

  1. I have tried markdown-it package with highlight.js. This does most of the part, somehow the code comes out without syntax highlighting (my guess is there is some clash between highligh.js css classes and tailwiind css classes). Also this generates the whole thing in single component, which makes it difficult to separate out the code block to further customise it.
  2. I also looked into CodeBlocks from skeletonui but it expects the only the code string and not the normal text. And I couldn’t figure how to separate normal text from code text without knowing the location of latter in advance.

Join two arrays in php and send via json_encode

I have two arrays in PHP and I intend to combine them to send via json_encode. To do this I am using the following code:

php:

$query = $conn->prepare("SELECT AQuenteSan, AFriaSan, dioxcloro, TemCaldeira, TemAQuente, TemAFria, TemBQuente, TemBFria, PH, Realizacao 

FROM raddb.Reg_legInt WHERE Realizacao BETWEEN ? AND ?");

$query->execute([$inicio, $fim]);

$json = [];
while($row=$query->fetch(PDO::FETCH_ASSOC)){
    extract($row);

    $json[]= [(string)$AQuenteSan, (string)$AFriaSan, (string)$dioxcloro, (string)$TemCaldeira, (string)$TemAQuente, (string)$TemAFria, (string)$TemBQuente, (string)$TemBFria, (string)$PH, (string)$Realizacao];
}

$query1 = $conn->prepare("SELECT AQuenteSan, AFriaSan, AQuenteSann, AFriaSann, AQuenteSannn, AFriaSannn, Ferro, Realizacao 

FROM raddb.Reg_legExt WHERE Realizacao BETWEEN ? AND ?");

$query1->execute([$inicio, $fim]);

$json1 = [];
while($row1=$query1->fetch(PDO::FETCH_ASSOC)){
    extract($row1);

    $json1[]= [(string)$AQuenteSan, (string)$AFriaSan, (string)$dioxcloro, (string)$TemCaldeira, (string)$TemAQuente, (string)$TemAFria, (string)$TemBQuente, (string)$TemBFria, (string)$PH, (string)$Realizacao];
}

echo json_encode(array_merge($json, $json1));

This way it returns the following data:

(2) [Array(10), Array(10)] 
0: (10) ['0.40', '0.20', '0.10', '61.00', '50.00', '19.00', '49.00', '20.00', '6.50', '2023-11-20'] 
1: (10) ['0.60', '0.45', '0.10', '61.00', '50.00', '19.00', '49.00', '20.00', '6.50', '2023-11-20']

Then when I do for in js it returns the data as follows:

for (var i = 0; i < data.length; i++) {
  console.log(data[i][0]);
}

0.40
0.60

The problem I have is that it returns the value of position zero of line zero and line 1 and it shouldn’t.
When I do console.log(data[i][0]); it should only return the value 0.40.

And when you do console.log(data[i][10]) it should only return 0.60, but that’s not what happens. Can you help?

URL encoding issue: Spaces encoded as plus signs instead of %20 in OData query

I’m facing an issue with URL encoding in an OData query. When I encode spaces in the query, the software seems to be representing them as plus signs (+) instead of the standard %20.

Encoded URL (from user input):

$select=ID&$expand=Apps($select=ID,Type;$filter=Target/any(d:(d%20eq%20'PC'))))))))

Parsed URL (result):

$select=ID&$expand=Apps($select=ID,Type;$filter=Target/any(d:(d+eq+'PC'))))))))

Has anyone encountered a similar issue, and if so, how did you address it? Is there a specific setting or configuration that controls the URL encoding behavior in Pact?

I’ve considered aligning the encoding with the standard URL encoding convention (%20) for compatibility. Any insights or suggestions on resolving this issue would be greatly appreciated!

How can I run a psql command when a button is pressed using typescript?

I am new to all of this, so there is bound to be a lot of mistakes.

I have a button in a file called DeviceControlsView.tsx with the following code:

//export button
buttons.push(
    <HTTPTriggerButton variant="outlined"
        key={"Export"}
        method="post"
        path={"/devices/" + props.deviceID + "/export"}
        onComplete={props.triggerReload}
        body={()=>{
            console.log('click') //what should go here?
        }}
    >EXPORT</HTTPTriggerButton>
)

I need the following psql command to be executed when the button is clicked:
docker exec -t 0379d63a5e8c pg_dumpall -c -U postgres > dump_date +%d-%m-%Y"_"%H_%M_%S.sql

For context I have a sql database that needs to be downloaded when the button is clicked.

I tried using the child process module, I had a file with called exports.js with the following code:

const { exec } = require("child_process");

export function executeExport() {
    exec("docker exec -t 0379d63a5e8c pg_dumpall -c -U postgres > dump_`date +%d-%m-%Y'_'%H_%M_%S`.sql", (error, stdout, stderr) => {
        if (error) {
            console.log(`error: ${error.message}`);
            return;
        }
        if (stderr) {
            console.log(`stderr: ${stderr}`);
            return;
        }
        console.log(`stdout: ${stdout}`);
    });
}

but I keep getting the following error:

ERROR in ./src/components/Devices/deviceViewPannels/exports.js 5:4-28

Module not found: Error: Can’t resolve ‘child_process’ in ‘/opt/repos/dashboard/dashboard-api/ui/src/components/Devices/deviceViewPannels’

I was hoping there would be an easier solution, or does anyone know how I can fix my current solutoin?

Thank you 🙂

Uploaded image disappears after button click JavaScript

I am new to JavaScript and uploading an image on browser. I am selecting the image from computer and shows it on browser window. However, that image disappears when I click on any other button on screen. I do not know, why it is happening. Any help?

HTML code:

 <div class="card">
      <h1> Upload Image</h1>
      <canvas class="removed"></canvas>
      <img src="images/default.png" id="pic">
      <label for="input-file"> Update image</label>
      <input type="file" accept="image/jpeg, image/png, image/jpg" id="input-file">
 </div>

JavaScript code:

let picture = document.getElementById("pic");
let inputFile = document.getElementById("input-file");

inputFile.onchange = async function () {
  picture.src = URL.createObjectURL(inputFile.files[0]);
}

How to solve styling breaking on refresh

I have created a simple website using Next. It has a Navbar, and a few pages with nothing yet.
In my page.jsx, I import the landing page which I use as the Home page.
The navbar has links to the other pages.

When on the homepage, the styling is not breaking. Once I navigate to other pages, the styling is good but once I refresh any of those pages the styling breaks. When I navigate to home, everything comes on well.

Layout file
 <html lang="en">
      <head> 
        ...
      </head>
      <WagmiConfig config={config}>
        <ConnectKitProvider mode="dark">
          <body>
            <div className="flex flex-col min-h-screen">
              <Navbar />
              <div className="flex-grow">{children}</div>
              <Footer />
            </div>
          </body>
        </ConnectKitProvider>
      </WagmiConfig>
    </html>

Normal site Behaviour

When the site breaks

My Repo

I have tried searching for this from last weekend but can’t find anything related. Your help is appreciated. The ones I have seen are using material UI but I’m not using it. I even changed the styling from normal css to tailwind css but the issue persists.

code: ‘ERR_DLOPEN_FAILED’ issue or node_modulesrollupdistnative.js:60:48) issue

When I want to create a project with vite. After typing npm run dev, I get the following error. Can anyone help? I can’t run the project.

Error: The specified module was not found
\?C:UserspensoOneDriveMasaüstüuytnode_modules@rolluprollup-win32-x64-msvcrollup.win32-x64-msvc.node
    at Module._extensions..node (node:internal/modules/cjs/loader:1327:18)
    at Module.load (node:internal/modules/cjs/loader:1091:32)
    at Module._load (node:internal/modules/cjs/loader:938:12)
    at Module.require (node:internal/modules/cjs/loader:1115:19)
    at require (node:internal/modules/helpers:130:18)
    at Object.<anonymous> (C:UserspensoOneDriveMasaüstüuytnode_modulesrollupdistnative.js:60:48) //makes this place obvious
    at Module._compile (node:internal/modules/cjs/loader:1241:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1295:10)
    at Module.load (node:internal/modules/cjs/loader:1091:32)
    at Module._load (node:internal/modules/cjs/loader:938:12) {
  code: 'ERR_DLOPEN_FAILED'
}

I tried to run the project with vite but it didn’t work

codeingiter 3 infinite scrolling issue

I’m using codeigniter 3 for my project, to display products i’m using infinite scrolling functionality.
when i scroll little bit also, then also scripts run multiple time to fetch data from ajax,
Im trying to get data once i reach bottom of the page.

I have tried below ajax functionality to get data

`var load_flag = 0;
var seo = ‘uri->segment(2)?>’;

LoadMoreData(load_flag);
function LoadMoreData(start){
  // alert(start)
  $.ajax({
    url: '<?php echo base_url()?>Vendor/Load_more_data/' + seo,
    data: 'start=' + start,
    type: 'post',
    success: function(result){
      
      if (result.trim() !== "") {
      // Check for duplicate data
        var existingData = $('#ven_pagination').html();

        if (existingData.indexOf(result) === -1) {
            $('#ven_pagination').append(result);
            load_flag += 24;

        } else {
            // Data already exists, handle accordingly
            console.log('Duplicate data');
        }
      } else {
          // No more data, you may want to disable further scrolling or show a message
          console.log('No more data');
      }
  }

})

}
$(document).ready(function () {

  $(window).scroll(function () {
      if($(window).scrollTop() +  $(window).height() > $('#ven_pagination').height()) {
          LoadMoreData(load_flag);
      }
  });
});`