how to customize tsx syntax using babel?

I’m a newer to babel,I want to transform the code:

const posts = []

export const PostList = () => {
    const [fetchSignal, setFetchSignal] = useReducer(signal => !signal, false)
    const withRefresh = useWithRefreshScope()
    useEffect(() => {
        getArticles().then((res) => {
            withRefresh(
                () => {
                    posts.push(...res.data.articles)
                 
                }
            )
        })
    }, [fetchSignal])
    return (
        <>
     
        </>
    )
}

to this:

const posts = []
@useWithRefreshScope
export const PostList = () => {
    const [fetchSignal, setFetchSignal] = useReducer(signal => !signal, false)
    useEffect(() => {
        getArticles().then((res) => {
            withRefresh{
                    posts.push(...res.data.articles)
                }
        })
    }, [fetchSignal])
    return (
        <>
 
        </>
    )
}

I just want to create a scope syntax to reduce some boilerplate code,so that i need to write a babel plugin(maybe not?)
how can i do that?(inspired by kotlin)

How to dynamically set an Image object src in javascript and Vue

I’m trying to teach myself javascript and Vue.js. I was following the documentation on Vue’s site and modifying their demonstrations as an exercise. I wanted to change their looping directive example to dynamically add images to the list from a specified url. I can’t seem to get the image to show despite setting the image properties src field. I have verified that everything runs and the field is in fact getting set. I assume I must be misunderstanding something related to the DOM or ordering of events.

Thanks in advance.

HTML

<script src="https://unpkg.com/vue@next"></script>

<div id="list-rendering" class="demo">
  <input v-model="imgsrc"></input>
  <button v-on:click="setImage">  Set</button>
  <ol>
    <li v-for="todo in todos">
      {{ todo.text }} {{todo.image}}
    </li>
  </ol>
</div>

CSS

.demo {
  font-family: sans-serif;
  border: 1px solid #eee;
  border-radius: 2px;
  padding: 20px 30px;
  margin-top: 1em;
  margin-bottom: 40px;
  user-select: none;
  overflow-x: auto;
}

Javascript

const ListRenderingApp = {
  data() {
    return {
      todos: [
        { text: 'Learn JavaScript',
          image: new Image(16,16)},
        { text: 'Learn Vue',
          image: new Image(16, 16)},
        { text: 'Build something awesome',
          image: new Image(16, 16)}
      ],
      imgsrc: ""
    }
  },
  methods:{
    setImage(){
       this.todos.map(todo => todo.image.src = this.imgsrc)
    }
  }
}

Vue.createApp(ListRenderingApp).mount('#list-rendering')

Vue problem why it will not work in Windows 11 [closed]

Vue.js won’t work.

I’m trying code that used to work before, so the code isn’t the issue. None of the Vue.js seems to work either in Brave browser, or in Firefox.

I can’t seem to figure out what is the main problem here. I’ve tried several CDNs, I’ve tried several code examples.
I am using Windows 11.

Are there any settings I should take into account in the browser?

Or, maybe is the Anti-Virus scanner the problem? I’m using Norton for lack of a better one right now.

Are there any settings in Windows 11 I need to check?

What is a simple checklist I could follow to ensure that Vue.js works? Any installation steps I can repeat to have it function?

Thanks a bunch in advance… I really want to continue w/ my course.

async await axios post data with vue js, the data send is different between vue and postmant

i try to create data with vue js, but backend can not read the data and just send “undefined” to database, i try create data with postman, backend can read the data,

i see the data captured on backend, it turns out that there is a difference between the data sent by vue js end the data sent by postman

here is the data sent by postman

[Object: null prototype] { name: '6', email: '5', password: '3' }

and here is the data sent by vue js

[Object: null prototype] {
  '{"name":"2","email":"2","password":"2"}': ''
}

here is the script in vue js

<script>
  import axios from "axios";
  export default {
    name: 'AddUser',
    data(){
      return {
        model: {
          name: '',
          email: '',
          id_status: '',
          password: '',
        }
      };
    },
    methods: {
      async saveUser(){
        try{
          const response = await axios.post('http://localhost:8000/users',this.model);
          res.data.headers['Content-Type'];
          console.log(response);
        } catch (err){
          console.log(err);
        }
      }
    },
  };
</script>

and here is script in node js as backend

if(q.pathname == "/users" && req.method == "POST"){
        var body = '';
        req.on('data', function(data){
            body += data;
            if(body.length > 1e6)
                req.connection.destroy();
        });

        req.on('end', function(){
            var postData    = qs.parse(body);
            let name        = postData.name;
            let email       = postData.email;
            let id_status   = postData.id_status;
            let password    = postData.password;            
            let sql = `insert into users (name,email,id_status,password) values ('${name}','${email}','${id_status}','${password}')`
            console.log(postData)
            db.query(sql,(err, result) => {
                if (err) throw err;

                if(result.affectedRows == 1){
                    res.end(JSON.stringify({message: 'success'}));
                }else{
                    res.end(JSON.stringify({message: 'failed'}));
                }   
            });
        });

Why am I still getting an error with a DELETE request in Postman?

I’m kinda new to programming and I am trying to send a delete request to Postman but I keep getting this error in postman. Would anyone know how to fix this?

ERROR:

{
    "code": 79,
    "codeName": "UnknownReplWriteConcern",
    "errInfo": {
        "writeConcern": {
            "w": "majority;",
            "wtimeout": 0,
            "provenance": "clientSupplied"
        }
    },
    "result": {
        "n": 1,
        "opTime": {
            "ts": {
                "$timestamp": "7022899934215012355"
            },
            "t": 99
        },
        "electionId": "7fffffff0000000000000063",
        "ok": 1,
        "writeConcernError": {
            "code": 79,
            "codeName": "UnknownReplWriteConcern",
            "errmsg": "No write concern mode named 'majority;' found in replica set configuration",
            "errInfo": {
                "writeConcern": {
                    "w": "majority;",
                    "wtimeout": 0,
                    "provenance": "clientSupplied"
                }
            }
        },
        "$clusterTime": {
            "clusterTime": {
                "$timestamp": "7022899934215012355"
            },
            "signature": {
                "hash": "/gnrM/bYkyRYi4XXXmEnkaLJJpg=",
                "keyId": {
                    "low": 1,
                    "high": 1620408145,
                    "unsigned": false
                }
            }
        },
        "operationTime": {
            "$timestamp": "7022899934215012355"
        }
    }
}

NOW, the delete request is working properly as I can see the query selection being deleted when I send the delete request but I am still getting that error in postman. I tried using this solution https://stackoverflow.com/a/69779799/16216414 which was working fine when I used any other request in Postman. I tried checking my code for

posts.js:

const router = require("express").Router();
const User = require("../models/User");
const Post = require("../models/Post");

//CREATE POST
router.post("/", async (req, res) => {
  const newPost = new Post(req.body);
  try {
    const savedPost = await newPost.save();
    res.status(200).json(savedPost);
  } catch (err) {
    res.status(500).json(err);
  }
});

//UPDATE POST
router.put("/:id", async (req, res) => {
  try {
    const post = await Post.findById(req.params.id);
    if (post.username === req.body.username) {
      try {
        const updatedPost = await Post.findByIdAndUpdate(
          req.params.id,
          {
            $set: req.body,
          },
          { new: true }
        );
        res.status(200).json(updatedPost);
      } catch(err) {
      res.status(500).json(err);
      }
    } else {
      res.status(401).json("You can only update your post.")
    }
  } catch(err) {
      res.status(500).json(err)
  }
});

//DELETE POST
router.delete("/:id", async (req, res) => {
  try {
    const post = await Post.findById(req.params.id);
    if (post.username === req.body.username) {
      try {
        await post.delete();
        res.status(200).json("Post has been deleted...");
      } catch (err) {
        res.status(500).json(err);
      }
    } else {
      res.status(401).json("You can delete only your post!");
    }
  } catch (err) {
    res.status(500).json(err);
  }
});

//GET USER
router.get("/:id", async (req, res) => {
  try {
    const post = await Post.findById(req.params.id);
    res.status(200).json(post);
  } catch (err) {
    res.status(500).json(err);
  }
});

module.exports = router;

How to detect (when trying to append a created element) if that element has been created once before with JavaScript

So I’m trying to build a gif/webm/png etc viewer, right now I’m creating elements to then set the file selected to that img (or if it is a webm file, then we’ll set it’s src to a video element)

Now I’m also building a hide button (the element I want to see if it’s already appended) to hide the image or video when it is clicked, so I want to create it… then append it when an image like a gif or png is chosen, but I have made a listener to detect if the file is a webm.

I also want to detect if the document already has the hide button, so therefore I can assign a hide button to either the img element or video separately element because as on my codepen
the hide button won’t work to hide the video when the img is created first then the video and so forth.

Basically I want to detect if the hide button has been appended before for the img element and/or video element (to prevent duplicates on the page) then delete it and create a new one that will read for the new video or img element.

mapping from another component Reactjs

I have created an array data for (title,desc,images,etc…) from one component and want to mapping in another component:

    return (
        <div className={styles.container}>
          {data.map((pizza, i) => ( 
            <>
               <Image src={pizza.imgSrc} key={i} alt="" width="500" height="500" />
            <h1 className={styles.title}>{pizza.title}</h1>
            <span className={styles.price}>{pizza.price}</span>
            <p className={styles.desc}>
          {pizza.desc}
        </p>
        </>
          ))}
      </div>
    );

my container CSS:

.container {
    width: 22%;
    padding: 20px 40px;
    display: flex;
    align-items: center;
    justify-content: center;
}

It is rendering only flex-direction: column, I want to render ‘row’ but nothing happen.

Can someone help me?

use object key as key for another object

I want to create a type in type script and use values of another object for it keys

const routes = {
home: "HOME",
profile: "PROFILE"
}

export type NavigatorParamList = {
  [routes.home]: undefined;
  [routes.profile]: undefined;
};

I knew that this code is not working!
any idea how to do it?

JavaScript function call inside another call allow you to access arguments that the “arguments[num]” can’t access

i was learning in free code camp and i fell into a problem arguments[1] result into undefined when the function gets called like this functionName(arg1) (arg2) so for example arguments[1] would result in undefined but using this solved it return (second) => addTogether(first, second); and i don’t know how a function call in the function itself could have accessed something that even the arguments[1] couldn’t access, can anyone explain
here is the full code if anyone is interested:

function addTogether() {
  const [first, second] = arguments;
  if (typeof(first) !== "number")
    return undefined;
  if (second === undefined)
    return (second) => addTogether(first, second);
  if (typeof(second) !== "number")
    return undefined;
  return first + second;
}

How can I do to insert a script using React and Tailwind CSS?

I am working on a project using React and Tailwind CSS and I would like to implement a modal but I have some problems to do that. Here is my code for the Modal using tailwind and react :

import React from "react";
import "./styles.css";
import "./styles/tailwind-pre-build.css";
import Navbar from "./components/Navbar";
import LivePortal from "./components/LivePortal";
import WorkContainer from "./components/WorkContainer";
import HomePage from "./components/Homepage";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";

const App = () => {
  return(
    <>
<div class="p-3">
    <button onclick="openModal(true)" class="bg-green-500 hover:bg-green-600 px-4 py-2 rounded text-white focus:outline-none">
        Open Modal
    </button>
</div>

<div id="modal_overlay" class="hidden absolute inset-0 bg-black bg-opacity-30 h-screen w-full flex justify-center items-start md:items-center pt-10 md:pt-0">

<div id="modal" class="pacity-0 transform -translate-y-full scale-150  relative w-10/12 md:w-1/2 h-1/2 md:h-3/4 bg-white rounded shadow-lg transition-opacity transition-transform duration-300">

    <button 
    onclick="openModal(false)"
    class="absolute -top-3 -right-3 bg-red-500 hover:bg-red-600 text-2xl w-10 h-10 rounded-full focus:outline-none text-white">
    &cross;
    </button>

    <div class="px-4 py-3 border-b border-gray-200">
    <h2 class="text-xl font-semibold text-gray-600">Title</h2>
    </div>

    <div class="w-full p-3">
    Lorem ipsum, dolor sit amet consectetur adipisicing elit. Asperiores, quis tempora! Similique, explicabo quaerat maxime corrupti tenetur blanditiis voluptas molestias totam? Quaerat laboriosam suscipit repellat aliquam blanditiis eum quos nihil.
    </div>

    <div class="absolute bottom-0 left-0 px-4 py-3 border-t border-gray-200 w-full flex justify-end items-center gap-3">
    <button class="bg-green-500 hover:bg-green-600 px-4 py-2 rounded text-white focus:outline-none">Save</button>
    <button 
        onclick="openModal(false)"
        class="bg-red-500 hover:bg-red-600 px-4 py-2 rounded text-white focus:outline-none"
    >Close</button>
    </div>
</div>

</div>


</>
  );
}

export default App;

I would like to use that script below to open the modal and close it but I don’t know how can I do that. Could you help me please ? Thank you very much

<script>
const modal_overlay = document.querySelector('#modal_overlay');
const modal = document.querySelector('#modal');

function openModal (value){
    const modalCl = modal.classList
    const overlayCl = modal_overlay

    if(value){
    overlayCl.classList.remove('hidden')
    setTimeout(() => {
        modalCl.remove('opacity-0')
        modalCl.remove('-translate-y-full')
        modalCl.remove('scale-150')
    }, 100);
    } else {
    modalCl.add('-translate-y-full')
    setTimeout(() => {
        modalCl.add('opacity-0')
        modalCl.add('scale-150')
    }, 100);
    setTimeout(() => overlayCl.classList.add('hidden'), 300);
    }
}
openModal(true)
</script>

You can get my code without the script tag here : https://codesandbox.io/s/tailwind-css-and-react-forked-6funy?file=/src/App.js

Apply perspective transformation to react element and propagate to children

I am applying perspective transformation to a react element, so the css property may look like this at one point:

transform: "perspective(48vh) rotateX(2deg) rotateY(3deg)"

I’m following the example here: https://armandocanals.com/posts/CSS-transform-rotating-a-3D-object-perspective-based-on-mouse-position.html, which is written in vanilla js:

let constrain = 20;
let mouseOverContainer = document.getElementById("ex1");
let ex1Layer = document.getElementById("ex1-layer");

function transforms(x, y, el) {
  let box = el.getBoundingClientRect();
  let calcX = -(y - box.y - (box.height / 2)) / constrain;
  let calcY = (x - box.x - (box.width / 2)) / constrain;
  
  return "perspective(100px) "
    + "   rotateX("+ calcX +"deg) "
    + "   rotateY("+ calcY +"deg) ";
};

 function transformElement(el, xyEl) {
  el.style.transform  = transforms.apply(null, xyEl);
}

mouseOverContainer.onmousemove = function(e) {
  let xy = [e.clientX, e.clientY];
  let position = xy.concat([ex1Layer]);

  window.requestAnimationFrame(function(){
    transformElement(ex1Layer, position);
  });
};

The logic itself is trivial, but when re-writing it into react using hooks, I’m having some issue referencing the proper view, this answer nonewithstanding: react: element.getBoundingClientRect is not a function, and I’m having some issue in applying the animation. This is what I have so far:



const useStyles => makeStyles((theme: Theme) => createStyles({

    container: {
        height: `calc(100vh - 230px)`,
        width: `calc(100vh-230px)`,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        border: `3.0px solid red`,
    },

    box : {
        height: '48vh',
        width: '48vh',
        background: 'red',
        borderRadius: '30px',
        textAlign: 'center',
        alignItems: 'center',
        
        // eample: all perspective logic
        transform: `perspective(48vh) rotateX(2deg) rotateY(3deg)`

    }

}));


const useMousePosition = () => {

    const [position, setPosition] = useState({ x: 0, y: 0 });

    useEffect(() => {
        const setFromEvent = (e) => setPosition({ x: e.clientX, y: e.clientY });
        window.addEventListener("mousemove", setFromEvent);

        return () => {
            window.removeEventListener("mousemove", setFromEvent);
        };
    }, []);

    return position;
};


function goTransform({ pose, ref }){
    // @TODO: implement this function
    // based on `pose.x` `pose.y`, compute
    // transform wrt. div's size
}


export default function PerspectiveContainer(props) {

    const isOnMobile = useCheckMobileScreen(1000);
    const classes = useStyles(isOnMobile)();    

    // persepctive shift
    const pose = useMousePosition();
    const inputRef = useRef();

    // @TODO: impl. this function, then apply transformation
    const transform = goTransform({ pose: pose, ref: inputRef })

    return (
        <Box className={classes.container}>
            <Box ref={inputRef} className={classes.box}>
                <h4 style={{color:'white'}}> { transform.x }, {transform.y } </h4>
            </Box>
        </Box>
    )

}

I’m running into an issue where when I call ref.current, the entire screen goes white, presumably because ref.current is not a valid reference.

ELK: Kibana graph chart & elastic-search mapping

I’d like to ask for advice about Kibana’s graph visualization & ElasticSearch mapping with join types.

I am having different entities, let say pets (let’s call them major entities) and their owners (minor entity).

I am inserting pets in PETS index and put owners in separate index of OWNERS. So some pets have a property that can be connected/join with the following (only one) owner.

Like this:

pets

{ 
  id: 1,
  name: 'Pikacho',
  ownerId: 1
}

owner

{ 
  id: 1,
  name: 'Rachel',
  petId: 1
}

Actually I am free to use every structure I want, even nested owner documents inside every pet. The real question is how to achieve the best case for graph data

Owners are really a separate entity and I don’t need them in the business logic of my app, but sometimes, as a user I’d like to check in Kibana’s UI via graph chart how many pets have one owner and so on.

enter image description here

So my question is: Are there any restrictions on data inserting (with.index method) via ElasticSearch driver for node.js, if I’d like to build a graph chart?

  • Should I create index via .create index and mark every field with correct mapping or I can just write them as usual and connect necessary field inside Kibana?
  • How to use join relation correctly in this case if I have to use it for graph chart?
  • ..and any other useful examples

My Elastic & Kibana versions are 7.16+ (current)

Reloading JS scripts on page (transition) change when using Barba JS

I’m trying to implement barba.js on a HubSpot site.

Consider the following two pages:

  1. Resources
  2. Customers

With my current barba.js implementation, this is the current flow I’m experiencing:

  1. I access the resources page (not by transitioning to it, by directly accessing it via /resources).
  2. At this point, all my js is working (slick-sliders, scroll functions etc)
  3. I then use the nave to try and access the customers page. The page loads, but all of the js specific to modules for that page are not working.

In short, js for pages that I transition to do not work.

To resolve this, what I’m trying to do is to reload all scripts within the container beforeEnter().

See below:

$(function() {

  function delay(n){
    n = n || 2000;
    return new Promise((done) => {
      setTimeout(() => {
        done();
      }, n);
    });
  }

  barba.init({
    sync: true,
    prefetchIgnore: true,
    debug: true,
    transitions: [{

      async leave(data){
        const done = this.async();
        await delay(200);
        done();
      },

      async beforeEnter({ next, container }) {

        $(container).find('script').each(function (i, script) {
          var $script = $(script);
          $.ajax({
            url: $script.attr('src'),
            cache: true,
            dataType: 'script',
            success: function () {
              $script.trigger('load');
            }
          });
        });
      },

      async enter(data){
        let scrollX = 0
        let scrollY = 0

        barba.hooks.leave(() => {
          scrollX = barba.history.current.scroll.x;
          scrollY = barba.history.current.scroll.y;
        });

        window.scrollTo(scrollX, scrollY);
      },

      async once(data){
        console.log("done");
      },

    }]
  });

});

However, my current beforeEnter() still yields the same results. Any way around this?