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.

Firestore fetching data twice

This is the code I currently have

async function getOrders() {
  const querySnapshot = await getDocs(collection(db, "orders"));
  querySnapshot.forEach((doc) => {
    // doc.data() is never undefined for query doc snapshots
    console.log(doc.id, " => ", doc.data());

  });
}

When I call this function, firestore fetches twice. I put another console.log to check if I called the function twice and I didn’t. I currently have only 1 item in firestore, and it shows two (they are duplicates). Please check the code above and the pics downbelow.

Console Img

Firebase Firestore Img

Axios post method is sending a object with my data as the key and empty value rather than the whole data object itself

Alright so I’m guessing this should have a simple solution, but I can’t seem to figure it out. I made the frontend first and now I’m want to make the backend so I can connect to a database.

const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));

app.get("/", function (req, res) {
  res.send("hello");
});
app.post("/", function (req, res) {
  console.log(req.body);
});
app.listen(3001, function () {
  console.log("listening on 3001");
});

And this is the post request I’m making on my react frontend.

axios.post("http://localhost:3001/", JSON.stringify(note));

note is an object like such
{title: "",content: ""} the empty string gets filled out with submission data.

when I make the post request this is what gets logged in the console
{ '{"title":"test","content":"one"}': '' }
I had to use JSON.stringify() to show whats being passed through but without it, my output is {}

So the problem is when my object is posted it becomes the key of an object with empty values

What I want to do is simply send the whole object like so
axios.post("http://localhost:3001/", note);
so that in the backend I can tap into the values by doing req.body.title and req.body.content

npm ERR! 404 happened when I want to install jest

Whan, I want to install Jest this error has happened, I have the latest version of Node,

npm ERR! code E404
npm ERR! 404 Not Found – GET https://registry.npmjs.org/Jest – Not found
npm ERR! 404
npm ERR! 404 ‘Jest@*’ is not in this registry.
npm ERR! 404 This package name is not valid, because
npm ERR! 404 1. name can no longer contain capital letters
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, http url, or git url.

“Swap” using interact.js, when dragging item A from area A to area B, and area B is already populated

Is it possible the “Swap out” draggable items using InteractJS, when dragging a draggable item from a “origin” to a “target” zone?

I cannot find any reference in their Documentation https://interactjs.io/docs about this specific use case

To explain better the situation and goal I made this rough fiddle:
https://jsfiddle.net/09afor6w/

It has 2 draggable “boxes” each in a “parent box”. When dragging the first box to the second, the second should automatically swap locations with the first, instead of staying put, or at least not allow the dragged element to be superposed to the element already there.

I assumed they would have a specific “swap” feature but it does not seem so.
With the “restrict” method, I can only restrict size and area of (size and drag), but not control that no items should overlap and thus maybe use this as a workaround to create a “swap” experience.

The goal behind this is creating a UI where the user can drag and drop single form elements into different places in a restricted, “gridded” area and resize the form elements.
When dragging elements from A to B, the element from the target area should change location to the “origin” area of the dragged item, that’s all.
So if there is an easier, lighter way to do this, I am also happy to hear about.

This is the code I use.
HTML:

<div class="contain-all">
    <div class="contain-some">
        <div class="grid-snap">
          Move this box to the white target area below
        </div>
    </div>
    <div class="contain-some">
        <div class="grid-snap">
          This box should automatically swap place with the moved box
        </div>
    </div>
</div>

JS:

var elements = document.getElementsByClassName('grid-snap');
$(elements).each(function(){
var x = 0; var y = 0
    interact(this)
  .resizable({
    // resize from all edges and corners
    edges: { left: true, right: true, bottom: true, top: true },

    listeners: {
      move (event) {
        var target = event.target
        var x = (parseFloat(target.getAttribute('data-x')) || 0)
        var y = (parseFloat(target.getAttribute('data-y')) || 0)

        // update the element's style
        target.style.width = event.rect.width + 'px'
        target.style.height = event.rect.height + 'px'

        // translate when resizing from top or left edges
        x += event.deltaRect.left
        y += event.deltaRect.top

        target.style.transform = 'translate(' + x + 'px,' + y + 'px)'

        target.setAttribute('data-x', x)
        target.setAttribute('data-y', y)
      }
    },
    modifiers: [
      // keep the edges inside the parent
      interact.modifiers.restrictEdges({
        outer: 'parent'
      }),

      // minimum size
      interact.modifiers.restrictSize({
        min: { width: 100, height: 50 }
      })
    ],

    inertia: true
  })
  .draggable({
    listeners: { move: window.dragMoveListener },
    inertia: true,
    modifiers: [
      interact.modifiers.restrictRect({
        restriction: '#formthing',
      }),
      interact.modifiers.snap({
        targets: [
          interact.snappers.grid({ x: 30, y: 30 })
        ],
        range: Infinity,
        relativePoints: [ { x: 0, y: 0 } ]
      }),
    ]
  })
  .on('dragmove', function (event) {
    x += event.dx
    y += event.dy

    event.target.style.transform = 'translate(' + x + 'px, ' + y + 'px)'
  })
});

Vue.js can’t v-bind:multiple in

<script>
export default {
  props: { multiple: { type: Boolean, default: false } }
}
</script>

<template>
  <input type="file" :multiple="multiple" />
</template>

does not work. Maybe because Vue sets the attribute after the DOM is build. And HTML does not recheck for attributes.

How do I fix this? I already tried v-once and duplicating the input element with a v-if, both failed. I need to set the multiple Attribute dynamically on component creation.

thank you.

trigger windows key + period with jquery or js [duplicate]

Since Windows 10 there is an integrated emoji collection that can be accessed with a combination (Windows logo key + . (period))

What I am trying to figure out is if there is a way to trigger that combination on an element click with either jQuery or pure JS.

I have tried searching to see if someone already has a solution for that, but can’t seem to find anything apart from that thread Is it possible to simulate key press events programmatically? but not sure how to do it.

So, for example, let say that with have this element <span id="emoji">Open Emoji</span>, how do we trigger (Windows logo key + . (period)) on click?

How to insert big HTML block in Javascript? Django JS

I have custom.js file in my django website. I need to create django – div in .js

catalog.html

                <div class="row px-3" id="products-section">

                       #-----------------
                       # This block should be placed from js
                       #-----------------
                        <div class="col-sm-4">
                            <article class="post post-medium border-0 pb-0 mb-5">
                                <div class="post-image">
                                    <a href="{% url 'product' product.url %}">
                                        <img src="media/{{product.img}}" class="img-fluid img-thumbnail img-thumbnail-no-borders rounded-0" alt="" />
                                    </a>
                                </div>

                                <div class="post-content">
                                    <h2 class="font-weight-semibold text-5 line-height-6 mt-3 mb-2"><a href="{% url 'product' product.url_dop %}">{{product.name}}</a></h2>

                                    <p>{{product.description}}</p>

                                    <div class="post-meta">
                                        <span><i class="far fa-user"></i> by <a href="{% url 'brandpage' product.manufacturer_url %}">{{product.manufacturer_name}}</a> </span>
                                        <span class="d-block mt-2"><a href="{% url 'product' product.url %}" class="btn btn-xs btn-light text-1 text-uppercase">Подробнее</a></span>
                                    </div>

                                </div>
                            </article>
                        </div>
                       #-----------------
                       # End block
                       #-----------------

                </div>

custom.js

var parent_div = document.getElementById("products-section");
var product_node = document.createElement("div");
product_node.className = "col-sm-4";
product_node.innerHTML = "Big html block here";
parent_div.append(product_node);

How i can add so big block? And also i need to replace django variables by js variables in this block.