How to persist resultset in Snowflake Stored Procedure written in Javascript?

I have a stored procedure that runs a sql command then it is run multiple times to call it multiple times. Is there a way to persist the resultSet so as not to run the snowflake query multiple times?

Currently

var my_sql_query = ` select * from table`;
var results = snowflake.execute({sqlText: my_sql_query});


while (results.next())
{
     script += results.getColumnValue(1);
}

... other script additions ...

// Second Run of the same script
var results = snowflake.execute({sqlText: my_sql_query});
while (results.next())
{
     script += results.getColumnValue(1);
}

Desired Output (as best as I can describe)

var my_sql_query = ` select * from table`;
var results = snowflake.execute({sqlText: my_sql_query});


while (results.next())
{
     script += results.getColumnValue(1);
}


// Second Run of the same script
while (results.next())
{
     script += results.getColumnValue(1);
}

How to speed up clock of browser

I want to speed up time in the browser without interfering local clock.

I’ve found an userscript that does exactly this (https://github.com/canguser/hooker-js/blob/master/src/plugins/timer-hooker/timeHooker.js)
But, I’m having trouble understanding it (I have a moderate understanding of js).

It’d be nice if anyone could explain the specific code responsible for speeding up the browser clock (The user script is large and most of it responsible for UI, which I’m not interested in).

I’d appreciate code snippets to run on the browser console to test the effects.

Test site: https://www.timeanddate.com/timer/

Chart.JS Display 5 largest values in the legend

I was wondering how to go about using Chart.JS to limit the amount of items displayed in the legend. I’d like to set essentially a max amount of 5, and it’ll display the 5 largest values in the legend. I’m assuming this would be done with a filter function in the options.plugins.labels, but I’m not sure how to go about checking the datasets against each other and then only displaying the 5 largest.

Thanks so much for the help

Remove all the white space between letters in a string but ignore space tab or enter at the end

I have searched and found ways to check for ALL whitespace existence between letters in a string but what about if the string contains a space, tab or enter at the end?

For example:

let str="John ";
console.log(str.includes(' '));

The above console.log will return true because there is a space at the end, however that is not relevant for me. I only wanted to check for:

let str="J o h n";

How to achieve this with Javascript ( and ignore space check at the end)?

response.json() throws “TypeError: Failed to fetch”

I use fetch for getting some resources from the server. I can see from logs that from time to time conversion to JSON fails on "TypeError: Failed to fetch" which is very interesting because should only happen when the request fails.

The simplified code I use:

const response = await fetch('https:/something.com/api')
await response.json() // -> throws TypeError: Failed to fetch

I cannot really find the case when it might happen. I tested possible cases and all failed on the first line of code, i.e. fetch('https:/something.com/api'). I have no idea when this might happen. I also should mention that it happens in modern browsers like chrome 99. So it is not definitely something like internet explorer thing.

Cases tested:

  1. Network error – user disconnected from the internet
  2. CORS – missing CORS headers

Unable to debug Opensource repos download from githup such as ramda or lodash

Unable to debug Opensource repos download from githup such as ramda or lodash.

Using those libraries are easy but cannot find a way to debug/edit it even if its adding console.log(“hello”) into a simple add function.

If I run add.js in either ramda or lodash I get a similar error.

”’
Uncaught SyntaxError c:Usersaspiesourcereposlodashadd.js:1
import createMathOperation from ‘./.internal/createMathOperation.js’
^^^^^^

SyntaxError: Cannot use import statement outside a module
at compileFunction (node:vm:352:18)
”’

Using multiple modals linked to th:href

I am trying to generate modals from hrefs:

<ul class="unordered-list" th:each="barOrder : ${OrdersByUser}">
                <li>
                    <a th:href="@{/users/details/{userId}/orderHistory/{orderId}(orderId=${barOrder.orderId}, userId=${billyUserId})}">
                        <div class="grid-orderHistory-parent">
                            <div class="grid-user-child-left"  th:text="${#temporals.format(barOrder.getDateTime(), 'dd-MM-yyyy HH:mm')}"></div>
                            <div class="grid-user-child-left"  th:text="${barOrder.getTotalPriceDisplayString(barOrder.getTotalPrice())}"></div>
                            <div class="grid-user-child-left" th:text="${barOrder.getBartenderName()}"></div>
                        </div>
                    </a>
                </li>
            </ul>

It is for an overview with orderhistory. For every order I want to details to pop up in a modal. So far I tried using JS but with no luck.

TIA

Regex for test strings with only letters

I have a form input which is where I only need to take speakable text phrase ( i.e no numbers, symbols etc )

I’m using following Regex pattern to test the user inputs.

const friendlyPhraseReg = new RegExp(/^[aA-zZs]+$/);

friendlyPhraseReg.test('@@') // false

friendlyPhraseReg.test('11') // false

friendlyPhraseReg.test('%%') // false

friendlyPhraseReg.test('&&') // false

friendlyPhraseReg.test(')')  //false

friendlyPhraseReg.test('"')  //false

friendlyPhraseReg.test('/')  //false

It all make sense until I try to test following two strings

friendlyPhraseReg.test('\') // true
friendlyPhraseReg.test('^^') // true

Why does it only return true for ‘^’ and ” ? I’m not very good with regex so pardon me if im asking a stupid question. Can someone clear me why its return true only for those two symbols ?

How to css animate per pixel distance, or consistent speed

var field = document.getElementById('field');
var player = document.getElementById('player');
field.oncontextmenu = (e) => {
    var xposition = (e.clientX - player.offsetLeft - player.offsetWidth/2);
    var yposition = (e.clientY - player.offsetTop - player.offsetHeight/2);
    player.style.transform = "translate("+ xposition + "px," + yposition + "px)";
    e.preventDefault();
}
#field{
    width: 500px;
    height: 500px;
    background-color: #999;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
  #player{
    background-color: #f30f4f;
    width: 50px;
    height: 50px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    border-radius: 50%;
    transform-origin: 25px 25px; 
    transition: all 0.3s linear;
  }
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="layout.css">
    <title>TESTING</title>
</head>
<body>
    <p> Click on the gray box anywhere and the dot will move to the click location</p>
    <div id="field"></div>
    <div id="player"></div>
    <script src="layout.js"></script> 

</body>
</html>

Instead of transition: all 0.3s linear; is there a way to make it move f.e. 2px per 0.3s?
Right now if the player moves a longer distance it moves faster than moving a short distance (since it has to move further in 0.3s): I would want that to be the same consistent speed.

Ho can i make an array of only those values, that are non-unique in initial array in js? [closed]

i have this array:

var arr = ["apple","potato","carrot","tomato","grape","banana","potato","carrot","carrot"];

As you can see, we have “potato” 2 times in this array, and also “carrot” 3 times in this array. How can i create a new array, that will content only “potato” and “carrot” values, so only values that are not single/unique in initial array?

Like this:

["potato","carrot"];

How it can be done in js?

Dividing an Input field value in React

I have been trying to calculate an input field value, It is a blockchain project. I want the users to input a certain value or worth of a coin they want to purchase and the system to automatically calculate the amount in Ethereum. For Example when a user input 50000, the system should divide the amount by 10000 and the user will pay 5 Eth.

const handleSubmit = (e) => {
  const { addressTo, amount, message } = formData;

  e.preventDefault();

  if ( !amount || !message) return;   

  sendTransaction();
};


<Input placeholder="Address To" name="addressTo" type="hidden" handleChange={handleChange} />
<Input placeholder="Amount (Coin)" name="amount"  type="number" handleChange={handleChange} />
<Input placeholder="Enter Description" name="message" type="text" handleChange={handleChange} />


await ethereum.request({
  method: "eth_sendTransaction",
  params: [{
    from: currentAccount,
    to: addressTo,
    gas: "0x5208",
    value: parsedAmount._hex,
  }],
});

D3.js – ForceBoundary when Zooming

I’m using the d3-force-boundary library in order to keep my nodes within the visualisation. My problem is that I also want to use the zoom functionality for the graph which is already implemented and working, but the boundary is not updating once I zoom in or out.

Is there a way to keep the nodes within the boundary after zooming in? Or when zooming out, the nodes should spread again across the the board.

<html>
<meta charset="utf-8">
<script src="https://d3js.org/d3-force.v1.min.js"></script>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/d3-force-boundary.min.js"></script>
<style>
.edge{
  stroke: green;
  stroke-width: 1;
}
.graphSVG{
  background-color: black;
}

div.container {
  width: 100%;
  border: 1px solid gray;
}
div.tooltip {
  position: absolute;
  text-align: center;
  width: 180px;
  padding: 2px;
  font: 12px sans-serif;
  background: lightsteelblue;
  border: 0px;
  border-radius: 8px;
  pointer-events: none;
}
</style>

<body>
  <div id="graphDiv"></div>

<script>

var radius = 5;

var defaultNodeCol = "white",
    highlightCol = "yellow";

var height = window.innerHeight;
var graphWidth =  window.innerWidth;

var graphCanvas = d3.select('#graphDiv').append('canvas')
.attr('width', graphWidth + 'px')
.attr('height', height + 'px')
.node();

var context = graphCanvas.getContext('2d');

var div = d3.select("body").append("div")
    .attr("class", "tooltip")
    .style("opacity", 0);


var simulation = d3.forceSimulation()
              .force("boundary", forceBoundary(0,0,graphWidth,height))        <--- this is the d3-force-boundary library command
              .force("center", d3.forceCenter(graphWidth / 2, height / 2))
              .force("x", d3.forceX(graphWidth / 2).strength(0.1))
              .force("y", d3.forceY(height / 2).strength(0.1))
              .force("charge", d3.forceManyBody().strength(-50))
              .force("link", d3.forceLink().strength(1).id(function(d) { return d.id; }))
              .alphaTarget(0)
              .alphaDecay(0.05)

var transform = d3.zoomIdentity;

d3.json("data.json",function(error,data){
  console.log(data)

  initGraph(data)

  function initGraph(tempData){
    function zoomed() {
      console.log("zooming")
      transform = d3.event.transform;
      simulationUpdate();
    }

    d3.select(graphCanvas)
        .call(d3.drag().subject(dragsubject).on("start", dragstarted).on("drag", dragged).on("end",dragended))
        .call(d3.zoom().scaleExtent([1 / 10, 8]).on("zoom", zoomed))

  function dragsubject() {
    var i,
    x = transform.invertX(d3.event.x),
    y = transform.invertY(d3.event.y),
    dx,
    dy;
    for (i = tempData.nodes.length - 1; i >= 0; --i) {
      node = tempData.nodes[i];
      dx = x - node.x;
      dy = y - node.y;

      if (dx * dx + dy * dy < radius * radius) {

        node.x =  transform.applyX(node.x);
        node.y = transform.applyY(node.y);

        return node;
      }
    }
  }

  function dragstarted() {
    if (!d3.event.active) simulation.alphaTarget(0.3).restart();
    d3.event.subject.fx = transform.invertX(d3.event.x);
    d3.event.subject.fy = transform.invertY(d3.event.y);
  }

  function dragged() {
    d3.event.subject.fx = transform.invertX(d3.event.x);
    d3.event.subject.fy = transform.invertY(d3.event.y);

  }

  function dragended() {
    if (!d3.event.active) simulation.alphaTarget(0);
    d3.event.subject.fx = null;
    d3.event.subject.fy = null;
  }

    simulation.nodes(tempData.nodes)
              .on("tick",simulationUpdate);

    simulation.force("link")
              .links(tempData.edges);

    function render(){

    }

    function simulationUpdate(){
      context.save();

      context.clearRect(0, 0, graphWidth, height);
      context.translate(transform.x, transform.y);
      context.scale(transform.k, transform.k);

      tempData.edges.forEach(function(d) {
            context.beginPath();
            context.moveTo(d.source.x, d.source.y);
            context.lineTo(d.target.x, d.target.y);
            context.stroke();
        });

        // Draw the nodes
        tempData.nodes.forEach(function(d, i) {

            context.beginPath();
            context.arc(d.x, d.y, radius, 0, 2 * Math.PI, true);
            context.fillStyle = d.col ? "red":"black"
            context.fill();
        });

        context.restore();
    }
  }
})


</script>
</body>

How to give a new REDUIX item a unique ID?

I am mapping an array of data with props into a component. Then onClick I pull some of that data into redux/reducer from the rendered items, trying to render the same data – but in a different spot on the page.

My problem is (I assume?) that the ID’s are the same – I render data with keys’s/id’s that were already taken – while React wants unique ones.

I am not sure, if that’s what’s causing the problem – but I keep getting a warning that react wants unique key props.

(it’s a shop app – on click, i want to add the chosen item to a cart with redux… )

Thoughts?

Adding google map in my website | javascript does not work in my website

When i’m adding JS API of google map

   <script src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&libraries=places">

This error appear

Source map error: Error: request failed with status 404
Resource URL: http://127.0.0.1:8000/assets/admin/vendors/js/vendors.min.js
Source Map URL: bootstrap.min.js.map

And this

> jQuery.Deferred exception: $(...).dateDropper is not a function @http://127.0.0.1:8000/assets/admin/js/scripts/extensions/date-time-dropper.js:20:19
j@http://127.0.0.1:8000/assets/admin/vendors/js/vendors.min.js:2:29999
Deferred/then/g/</k<@http://127.0.0.1:8000/assets/admin/vendors/js/vendors.min.js:2:30313
setTimeout handler*Deferred/then/g/<@http://127.0.0.1:8000/assets/admin/vendors/js/vendors.min.js:2:30522
i@http://127.0.0.1:8000/assets/admin/vendors/js/vendors.min.js:2:28017
fireWith@http://127.0.0.1:8000/assets/admin/vendors/js/vendors.min.js:2:28783
fire@http://127.0.0.1:8000/assets/admin/vendors/js/vendors.min.js:2:28819
i@http://127.0.0.1:8000/assets/admin/vendors/js/vendors.min.js:2:28017
fireWith@http://127.0.0.1:8000/assets/admin/vendors/js/vendors.min.js:2:28783
ready@http://127.0.0.1:8000/assets/admin/vendors/js/vendors.min.js:2:31934
S@http://127.0.0.1:8000/assets/admin/vendors/js/vendors.min.js:3:35
EventListener.handleEvent*@http://127.0.0.1:8000/assets/admin/vendors/js/vendors.min.js:3:149
@http://127.0.0.1:8000/assets/admin/vendors/js/vendors.min.js:2:220
@http://127.0.0.1:8000/assets/admin/vendors/js/vendors.min.js:2:225
 undefined

Loading failed for the <script> with source “http://127.0.0.1:8000/admin/js/scripts/pages/chat-application.js”.

Sequelize [Op.and] not working with M:N association

I have two models

Units and Filters which are related with M:N association through unit_filter table

 this.belongsToMany(Unit, {
        through: "unit_filter",
        as: "units",
      });

  this.belongsToMany(Filter, {
        through: 'unit_filter',
        as: 'filters',
      });

The goal is to fetch units which have more than 1 filter associated with and condition.

let result = await Unit.findAll({
          include: [
            {
              model: Filter,
              where: {
                id: {
                  [Op.and] : [2,252,4,80]
                }
              },
              as: 'filters',
            },
          ],
        });

The above is only working if there is only one id in the array which does not make any sense.

Seqeulize documenation states

  Post.findAll({
      where: {
       [Op.and]: [{ a: 5 }, { b: 6 }],            // (a = 5) AND (b = 6)
      }
    })

So the code I have should work theoritically. I also tried with

where: {
   [Op.and] : [{id:2},{id:252},{id:4},{id:80}]
}

which results in getting all the items from the db. It does not even care about the where condition in this case.

Would be of great help if any one points me in right direction.