I am trying to run a SQL query inside a Javascript Snowflake Stored Procedure but it isn’t working and it keeps failing to initialise

I am trying to create a Javascript Stored Procedure in Snowflake where the javascript executes a sql query. I am new to javascript and I stole all of it from an existing one that already exists (and works). The problem is that the stored procedure never initializes when I call it, and when I cancel the query, it returns an error:

SQL compilation error: error line 4 at position 28
invalid identifier 'TABLE_NAME'
At Statement.execute, line 20 position 23 (line 37)

My Stored Procedure is this:

 CREATE OR REPLACE procedure TRIAL
    (
    DATABASE_NAME VARCHAR,
    SCHEMA_NAME VARCHAR,
    TABLE_NME VARCHAR,
    COLUMN_NME VARCHAR
    )
    RETURNS varchar(100)
    language javascript
    as '   

    var return_value = "";

    var sql_command= `INSERT INTO XXX.YYY.END_TABLE (table_name, column_name, issue_code,parameters,value,row_hash, exception_ts)
                    WITH CTE AS (
                            SELECT 
                            ${TABLE_NME},
                            ${COLUMN_NME},
                            ''DQ_IS_NULL'',
                            ''NULLs not permitted'',
                            HASH(*) AS ROW_HASH,
                            CURRENT_TIMESTAMP()
                            FROM ${DATABASE_NAME}.${SCHEMA_NAME}.${TABLE_NME}
                            )
                    SELECT CTE.* FROM CTE
                    LEFT JOIN XXX.YYY.END_TABLE dql
                    ON CTE.ROW_HASH = dql.ROW_HASH WHERE dql.ROW_HASH IS NULL;`
    var stmt1 = snowflake.createStatement({sqlText: sql_command});
    var result_scan=stmt1.execute();
 
       return "Records Inserted";        
    ';

CALL TRIAL('DATABASE_NAME','SCHEMA_NAME','TABLE_NME','COLUMN_NME');

When calling the stored procedure, I have purposefully left in the variable names as an example.

Is anybody able to help?

Extract data from iframe pdf file

i have simple website with pdf viewer by pdf.js and what i want to do is draw rectangle via mouse and get text from iframe pdf file to text field. None of my code work properly

I did almost every options from web but still no result, only drawing rectangle in js work

KafkaJS Discard connection to consumer

currently I am stuck trying to disconnect my consumer properly.

My frontend lets me send a request to backend, which then starts a Consumer, to consume all messages of that topic , and then return them.

The first request works just fine, but when I send the 2nd, another consumer joins the group (cause i start a node for every request), and Kafka rebalances the >100 000 messages topic and this takes a few seconds.

So this led me to the issue, that my consumer does not get disconnected properly.

I checked in my code, that consumer.disconnect() get executed and it does. However if I check with this command:

kafka-consumer-groups –bootstrap-server localhost:9092 –describe –group test-group

I can see it is still connected, so how do I manage to discard this connection. If I wait for ~20 sec and I check again with this command. He is being disconnected (must be kafka connection timeout).

If I sent a request now, I get the result almost instantly which means he started a new connection, instead of joining a group and having to rebalance. How do I solve this ? XD

TypeError: n.indexOf is not a function error for firebase/firestore v9

I am receiving a TypeError: n.indexOf is not a function error when trying to access the customers collection in my database. However, I can access the products collection fine.

This is the code I’m trying:

   const taskQuery = doc(collection(db, "customers"), where("uid", "==", user.uid))
    const loadCheckout = async (priceId) => {
        try {
            const taskDocs = await getDocs(taskQuery)

        } catch (error) {
            console.log(error.message)
        }
    }

user.uid is defined and because I can access the ‘products’ collections, the app initialisation is hooked up correctly. If I remove the ‘where(“uid”…)’ I get a ‘Missing or insufficient permissions’ error which lead me to believe there is something wrong in the rules.

Rules:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /customers/{uid} {
      allow read: if request.auth.uid == uid;

      match /checkout_sessions/{id} {
        allow read, write: if request.auth.uid == uid;
      }
      match /subscriptions/{id} {
        allow read: if request.auth.uid == uid;
      }
    match /products/{id} {
      allow read: if true;

      match /prices/{id} {
        allow read: if true;
      }

      match /tax_rates/{id} {
        allow read: if true;
      }
    }
  }
}

firestore database](https://i.stack.imgur.com/g4UcV.png)

Update HTML page with new content upon POST Request

I want HTML page been updated after POST request in NODE app with new content,
without using:
additional modules like express etc
forms
new routes

new content is:

<!DOCTYPE html>
  <html>
    <head>
      <title>Updated Page</title>
    </head>
    <body>
      <h1>Clicked</h1>
      <p>Clicked</p>
    
    </body>
  </html>

full code is here:

const http = require('http');

// create a server to handle requests
const server = http.createServer((req, res) => {
  // handle POST requests
  if (req.method === 'POST') {
    let body = '';

    req.on('data', (chunk) => {
      console.log('Received data:', chunk);
      body += chunk;
    });

    req.on('end', () => {
      console.log('Received complete data:', body);


          // send an updated HTML response to the client
  const responseHtml = `<!DOCTYPE html>
  <html>
    <head>
      <title>Updated Page</title>
    </head>
    <body>
      <h1>Clicked</h1>
      <p>Clicked</p>
    
    </body>
  </html>`;

        // send a success response to the client
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.end(responseHtml);
      });
    } else {
    // send an HTML page to the client that allows them to paste images and videos
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end(`<!DOCTYPE html>
    <html>
    <head>
      <title>Blue Div</title>
      <style>
        #blue-div {
          width: 200px;
          height: 200px;
          background-color: blue;
        }
      </style>
    </head>
    <body>
      <div id="blue-div" onclick="sendPostRequest()"></div>
    
      <script>
        function sendPostRequest() {
          const data = {};
          fetch('/', {
            method: 'POST',
                    headers: {
        'Content-Type': 'application/json'
      },
            body: JSON.stringify(data)
          })
          .then(response => {
            if (response.ok) {
              console.log('POST request successful');

            } else {
              console.error('POST request failed');
            }
          })
          .catch(error => {
            console.error('Error sending POST request:', error);
          });
        }
      </script>
    </body>
    </html>
    
    `);
  }
});

// start the server
server.listen(8080);
console.log('Server running at http://localhost:8080/');

In DevTools on network tab I’m getting Correct responseresponse

But HTML page stays the same.

I’ve tried to use
location.reload(); if response is ok, but it just Reloaded page to initial state while vanishing ‘request’ itself, i could see appearence for milliseconds

How to make a jquery messaging accepts a user validation from the web-form?

I need some help, i have message.min.js file that must diplay messaging before a user puts an input from the form. Currently the form does not display any message and i only get this error message when inspecting the element from the browser. ” messages.min.js:1 Uncaught SyntaxError: Cannot use import statement outside a module (at messages.min.js:1:437)” .

// javascript libraries

// I get an exception again when i try to use this type module ” Uncaught TypeError: Failed to resolve module specifier “@angular/core”. Relative references must start with either “/”, “./”, or “../”.

// signup-form messaging

$().ready(function() {
    
$('#signup-form').validate({
rules:{
    name: {
        required:true,
        minlength:12
    },
    surname:{
        required:true,
        minlength:15
    },
    email:{
        required:true,
        email:true
    },
    confirmed_email:{
        required:true,
        confirmed_email:true
        
    },
    phone_number: {
        required:true,
        phone_number:true,
        minlength:10
    },
    service_number:{
        required:true,
        service_number:true,
        minlength:10
    },
    agree: {
        required:true,
        agree:true
    }
},
messages: {
    name: {
        required:"Please enter your name",
        minlength:"Your name must have at least 12 characters"
    },
    surname: {
        required:"Please enter your surname",
        minlength:"Your surname must have at least 15 characters"
    },
    email: {
        required:"Please enter your email address",
        equalTo:"Please enter the same email address as above"
    },
    agree: "Please accept our policy"
}

})
});

How to destructure all of the objects from the nested arrays?

An array containing objects with attributes that have nested arrays containing more objects with attributes in it.
const courses = [
{
name1: ‘Half Stack application developm
id: 1,
parts: [
{
name: ‘Fundamentals of React’,
exercises: 10,
id: 1
},
{
name: ‘Using props to pass data’,
exercises: 7,
id: 2
},
{
name: ‘State of a component’,
exercises: 14,
id: 3
},
{
name: ‘Redux’,
exercises: 11,
id: 4
}
]
},
{
name1: ‘Node.js’,
id: 2,
parts: [
{
name: ‘Routing’,
exercises: 3,
id: 1
},
{
name: ‘Middlewares’,
exercises: 7,
id: 2
}
]
},

]

How to destructure all of the objects from the nested arrays?

So far I can only get the attributes of the first object from the nested arrays. But I would need all of the others objects. It works well for the parent array even when updating the array, but not for the children arrays containing the objects.

for (const {
    name1: n,
    parts: [{ name: n2, exercises: ex }],
  } of courses) {
console.log(`${n}:
${n2} ${ex}`);
}

ACTUAL RESULT:
Half Stack application development:
Fundamentals of React 10
Node.js:
Routing 3

EXPECTED RESULT:

Half Stack application development:
Fundamentals of React 10
Using props to pass data 7
State of a component 14
Redux 11

Node.js:
Routing 3
Middlewares 7

MongoDB “atomic” find entity and if not found update a different one

I am trying to solve a race condition issue through MongoDB operations so I can avoid the implementation of locks.

My goal is to be able to check if there is any document with a certain status in the collection and if not, to set that status to an existing document of the collection of my choice. That goal comes from the need that due to concurrency any implementation I tried makes that with a race condition I get more than one document updated.

Let me put a parallel example. In a scenario of concurrent calls, my goal is that the logic checks if there is not any existing Card that has status ACTIVE, a Card of my choice is set to ACTIVE, and if there is already an ACTIVE Card, to leave that as it is. All in just one MongoDB operation. This operation is triggered by a different flow so I can’t change the flow to set as ACTIVE a Card before executing that logic.

I tried through the use of the findOneAndUpdate (and even findOneAndReplace) operation:

const query = {
  userId: 'user-id-1',
  status: 'ACTIVE',
};

Card.findOneAndUpdate(
    query,
    {
        $set: {
            _id: 'chosen-id', // A certain chosen ID to update if not found.
            userId: 'user-id-1', 
            status: 'ACTIVE',
        },
    },
    {
        upsert: true,
        returnNewDocument: true,
    }
);

But I find myself unable to achieve my goal with any of the options available, therefore I only achieve to update a found Card. If not found, anything remains the same and my chosen Card is not set as ACTIVE. The only case is when adding like in the example upsert: true I can create a new document, but I do not want as I want to update a different existing document.

Has MongoDB any implementation that can achieve this behaviour in one single operation? Regardless of the version. I have no limitations in upgrading if needed.

how to show each image when clicked and show them in a modal

What I am looking for is that the user, when clicking on any image, opens a modal with that same image in a large size.

What I have achieved so far is that only the first image is displayed, because clicking on the others does not interact with anything.

image gallery
only image that is activated

this image is from image gallery code in django
gallery code

This image is of the modal code that is displayed when clicking on an image
modal image zoom

and this image is of the js code
modal image zoom js

From now on, sorry for my bad English.
I hope you can understand me and help if you can, thank you!

Calculate increase or decrease percentage between two number

I have two numbers of yesterday’s price and today’s price in the table. I want to display the price increase or decrease as a percentage next to today’s price number.

This is my table:

<table>
  <thead>
    <tr>
      <th>yesterday's price</th>
      <th>today's price</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>50</td>
      <td>75</td>
   </tr>
   <tr>
     <td>100</td>
     <td>50</td>
   </tr>
   <tr>
     <td>82</td>
     <td>82</td>
   </tr>
  </tbody>
</table>

I’m going to change it like this:

By adding what JavaScript codes can I make these changes in the table? Thanks for your help

<table>
  <thead>
    <tr>
      <th>yesterday's price</th>
      <th>today's price</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>50</td>
      <td class="increase">75 (+50% increase)</td>
   </tr>
   <tr>
     <td>100</td>
     <td class="decrease">50 (-50% decrease)</td>
   </tr>
   <tr>
     <td>82</td>
     <td class="nochange">82 (no change)</td>
   </tr>
  </tbody>
</table>

using mergeMap to return a Observable void – good practice questions

I am reading some existing code, and i find it interesting the way the same data is simultaneously used as argument and return value (prepareData() method) – I wonder how much of a bad practice this is.

And how we are using mergeMap and returning Observable void in loadMyData method.

Headsup that I copied code I didn’t write, and renamed variables and types, just trying to understand how correct this code is, and if you would improve it in any obvious way.

My knowledge of RxJs is very basic and I am just trying to learn.

 public prepareData(values: myTypeArr[]): Observable<myTypeArr[]> {
   return this.loadMyData().pipe(take(1),
   map(() => {
     values.forEach((value) => {
       // add value to data in store
       this.assignValueToStore(value);
     });
     return values;
   }))
 }

loadMyData() looks like this.

public loadMyData(): Observable<void> {
  this.logger.info('Loading data.');

  return this.myService.apiDataGet().pipe(
    map((responseArr: responseType[]) => {
      //Reset an internal state
      this.resetState({});
      this.logger.info(`Got ${responseArr.length} items from API.`);
      return responseArr;
    }),
    mergeMap(responseArr=> {
      return this.addItemsToStore(responseArr); //this will return Observable<void>
    })
  );
}

Frame size of ‘X’ bytes exceeds maximum accepted frame size

I’m attempting to calculate slippage of the past X number of blocks to determine if a potential trade is likely to slip beyond the threshold 1% level. If it does I will cancel the trade.

To do this, I have used web3.eth.getPastLogs() and have started to receive this error:

Error: CONNECTION ERROR: Couldn't connect to node on WS.
    at Object.ConnectionError (/Users/TrentKennelly/trading_bot_V2/node_modules/web3-core-helpers/lib/errors.js:66:23)
    at Object.InvalidConnection (/Users/TrentKennelly/trading_bot_V2/node_modules/web3-core-helpers/lib/errors.js:36:21)
    at /Users/TrentKennelly/trading_bot_V2/node_modules/web3-providers-ws/lib/index.js:161:37
    at Map.forEach (<anonymous>)
    at WebsocketProvider._onClose (/Users/TrentKennelly/trading_bot_V2/node_modules/web3-providers-ws/lib/index.js:160:28)
    at W3CWebSocket._dispatchEvent [as dispatchEvent] (/Users/TrentKennelly/trading_bot_V2/node_modules/yaeti/lib/EventTarget.js:115:12)
    at W3CWebSocket.onClose (/Users/TrentKennelly/trading_bot_V2/node_modules/websocket/lib/W3CWebSocket.js:228:10)
    at WebSocketConnection.<anonymous> (/Users/TrentKennelly/trading_bot_V2/node_modules/websocket/lib/W3CWebSocket.js:201:17)
    at WebSocketConnection.emit (node:events:513:28)
    at WebSocketConnection.drop (/Users/TrentKennelly/trading_bot_V2/node_modules/websocket/lib/WebSocketConnection.js:475:14)
    at /Users/TrentKennelly/trading_bot_V2/node_modules/websocket/lib/WebSocketConnection.js:303:18
    at process.processTicksAndRejections (node:internal/process/task_queues:77:11) {
  code: 1009,
  reason: 'Frame size of 5607436 bytes exceeds maximum accepted frame size'
}

I have attempted to increase the maxReceivedFrameSize in my truffle-config, which is a solution offered here like so:

networks: {
    mainnet: {
      provider: () => new HDWalletProvider(mnemonic, `wss://mainnet.infura.io/ws/v3/${process.env.INFURA_API_KEY}`,
        {
            clientConfig: {
                maxReceivedFrameSize: 100000000,
                maxReceivedMessageSize: 100000000
            }
        }),
      network_id: '*', 
      gasPrice: 100000000000
    }
}

Here is the function that is producing the error. :

const determineSlippage = async (_token0, _token1, _pairContract) => {

  console.log(`Calculating Slippage...n`)

  const endpoint = 'https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2'

  // Set the token pair to analyze
  const token0 = _token0 
  const token1 = _token1 

  // Set the time interval to analyze (in blocks)
  const blocks = 500

async function getTradesForPair(token0, token1, blocks, uPairValue) {
  // Get the latest block number
  const latestBlockNumber = await web3.eth.getBlockNumber();

  // Determine the block range to search for trades
  const startBlockNumber = Math.max(latestBlockNumber - blocks, 0);
  const endBlockNumber = latestBlockNumber;
              
  const pair = _pairContract;

  const filter = {
    fromBlock: startBlockNumber,
    toBlock: endBlockNumber,
    topics: [web3.utils.sha3('Swap(address,uint256,uint256,uint256,uint256,address)')]
  };

  // Get the past Swap events from the Uniswap pair contract
  const events = await web3.eth.getPastLogs(filter);

  // Create an array of trades from the Swap events
  const trades = events.map(event => {
  const { amount0In, amount1In, amount0Out, amount1Out } = event.returnValues;
  const { token0, token1 } = pair.options;
  const trade = { 
    inputToken: token0.options.address === token0Address ? token0 : token1,
    outputToken: token0.options.address === token0Address ? token1 : token0,
    inputAmount: web3.utils.toBN(token0.options.address === token0Address ? amount0In : amount1In),
    outputAmount: web3.utils.toBN(token0.options.address === token0Address ? amount1Out : amount0Out)
  };

  return trade;

});

return trades;
}

As a final note, this error occurs whether blocks is 500 or 100. Doesn’t seem to matter. Any thoughts?

AG grid react focus issue

In AG grid react.. press tab to move next cell that time focus and editing enable on each cell I moved using tab but if I sorted grid ascending and decending after that if i click one cell editing and focusing enable on someother row.what is the solution for that?

I wrote function for oncellfocused and tired

Need to Dynamically Change Headings in Fiori List report Developed Using Fiori Elements

I do have a Fiori list report developed using Fiori Elements. I need to dynamically change the column headings.
I have a filter called Period which can be selected as Monthly or Weekly.
When the user has selected the Monthly option, the columns should have headings for next four months ,
like
03/2023 04/2023 05/2023 06/2023
When the user has selected the Weekly option, the columns should have headings for next four periods ,
like

Calender 09 Calender 10 Calender 11 Calender 12 .
How can i achieve the same using javascript code in the front end ? especially for the one which developed with fiori elements.

@Fiori Elements @Fiori @UI5 @Javascript

Dynamic Column in List report developed using Fiori Elements