mediapipe selfi-segmentation in javascript

I need to extract the background from the real-time video and replace it with an image.
The code you created has completed the background and person extraction, but the background is not deleted.
It’s a basic function, but I can’t solve it alone, so I’d appreciate it if you could help me.

This is my code

<body>
   <div class="container">
     <video class="input_video" width="640px" height="480px"></video>
     <canvas class="output_canvas" width="640px" height="480px"></canvas>
   </div>

   <script type="module">

   const videoElement = document.getElementsByClassName('input_video')[0];
   const canvasElement = document.getElementsByClassName('output_canvas')[0];
   const canvasCtx = canvasElement.getContext('2d');

   function onResults(results) {

       canvasCtx.save();
       canvasCtx.clearRect(0, 0, canvasElement.width, canvasElement.height);
       canvasCtx.drawImage(results.segmentationMask, 0, 0,
                           canvasElement.width, canvasElement.height);
       // Only overwrite existing pixels.
       canvasCtx.globalCompositeOperation = 'source-in';
       canvasCtx.fillRect(0, 0, canvasElement.width, canvasElement.height);
       canvasCtx.segmentationMask = 'source-out';
       // Only overwrite missing pixels.
       canvasCtx.globalCompositeOperation = 'destination-atop';
       canvasCtx.drawImage(
           results.image, 0, 0, canvasElement.width, canvasElement.height);

       canvasCtx.restore();
   }

   const selfieSegmentation = new SelfieSegmentation({locateFile: (file) => {
       return `https://cdn.jsdelivr.net/npm/@mediapipe/selfie_segmentation/${file}`;
   }});
   selfieSegmentation.setOptions({
       modelSelection: 1,
       selfieMode: true,
       effect: 'mask',
   });
   selfieSegmentation.onResults(onResults);

   const camera = new Camera(videoElement, {
       onFrame: async () => {
         await selfieSegmentation.send({image: videoElement});
       },
       width: 640,
       height: 480
   });

   camera.start();

   </script>

</body>

React Native: passing data back to parent from child component

I’m trying to pass data I got from the child component to the parent component.

I keep on getting an error saying “Attempted to assign to readyonly property.”

TypeError: Attempted to assign to readonly property.
at node_modulesreact-nativeLibrariesLogBoxLogBox.js:149:8 in registerError
at node_modulesreact-nativeLibrariesLogBoxLogBox.js:60:8 in errorImpl
at node_modulesreact-nativeLibrariesLogBoxLogBox.js:34:4 in console.error
at node_modulesexpobuildenvironmentreact-native-logs.fx.js:27:4 in error
at node_modulesreact-nativeLibrariesCoreExceptionsManager.js:104:6 in reportException       
at node_modulesreact-nativeLibrariesCoreExceptionsManager.js:172:19 in handleException      
at node_modulesreact-nativeLibrariesCoresetUpErrorHandling.js:24:6 in handleError
at node_modulesexpo-error-recoverybuildErrorRecovery.fx.js:12:21 in ErrorUtils.setGlobalHandler$argument_0
at node_modulesregenerator-runtimeruntime.js:63:36 in tryCatch
at node_modulesregenerator-runtimeruntime.js:294:29 in invoke
at node_modulesregenerator-runtimeruntime.js:63:36 in tryCatch
at node_modulesregenerator-runtimeruntime.js:155:27 in invoke
at node_modulesregenerator-runtimeruntime.js:165:18 in PromiseImpl.resolve.then$argument_0    
at node_modulesreact-nativenode_modulespromisesetimmediatecore.js:37:13 in tryCallOne      
at node_modulesreact-nativenode_modulespromisesetimmediatecore.js:123:24 in setImmediate$argument_0
at node_modulesreact-nativeLibrariesCoreTimersJSTimers.js:123:14 in _callTimer
at node_modulesreact-nativeLibrariesCoreTimersJSTimers.js:177:14 in _callImmediatesPass    
at node_modulesreact-nativeLibrariesCoreTimersJSTimers.js:437:30 in callImmediates
at node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:388:6 in __callImmediates  
at node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:132:6 in __guard$argument_0at node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:365:10 in __guard
at node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:131:4 in flushedQueue

  

I have a radio button on my child component, and I want it’s value to go back to the parent component since that data will be used in the parent component.

child radio handle (OrderCard.js):

const handleRadio = (value) => {
    console.log(value)
    setRadioValue(value)
    if(value === true) {
        props.onChange = true
    } else if (value === false) {
        props.onChange = false
    }
}

on the parent I mapped the component since it is like a card with buttons,

                        {orders.map((order, index) => {
                        return (
                            <OrderCard 
                                orderNum={order.order_name} 
                                items={order.order_items} 
                                key={index} 
                                count={index}
                                onChange={(value) => accepted(value)}
                            />
                        )
                    })}

and the accepted function, tried to make it appear in console:

    const accepted = (data) => {
    console.log('data: ', data)
    }

How to await state change in React Native?

I have spent the whole day searching through similar questions etc. but to no avail and I am losing my mind.

I am building a “translate app” using an API. In my Home functional component which is one of three in my bottom tab navigator, I have these states:

const [from, setFrom] = useState({language:'German', code:'ge_GE'});
const [to, setTo] = useState({language: 'English', code: 'en_GB'});
let [input, setInput] = useState("");
const [output, setOutput] = useState("");
const [favorites, setFavorites] = useState([])

So I have a textinput with onChange handler binded to setInput.
That input then becomes a part of a API request by axios which is either called on a button press or useEffect with input as its dependency which turned out to be more effective, gets translated and I set it to output state like this:

const fetch = () =>  {
    axios.request(options).then(function (response) {
    console.log(response.data)
    if(response.data.result == "I'm waiting for entry"){
      setOutput("");
    }
    else{
      setOutput(response.data.result);
    }
    }).catch(function (error) {
      console.error(error);
      setOutput("");
    });
  } 

The output then updates in my UI and the wanted result in UI is achieved.

THE PROBLEM IS: I then use a button with saveHandler like this:

function saveHandler(){
  const newFaves = [...favorites,{phrase: input, translation: output, source: from.code, target: to.code, key: favorites.length + 1 }];
    setFavorites(newFaves);
  }

The aim is to take the current translation along with its language codes and save it in an object and add it to the full list of favorites that can be persisted with AsyncStorage etc.

When I then do a setFavorites and console.log(favorites) inside a favorite dependent useEffect, the values returned by state are not the latest. I have seen similar issues on SO, people using second callback arguments, but I keep getting told by expo console that useState does not support it. I am not really trying to turn to class components as I am absolutely lost after trying it. I believe there must be a way to do this. I ask you kind souls of SO, for your helping hand 🙁

How can I change the width of the slides in swiperjs using slidesPerview?

I’m trying to get my swiper to look like this, with the active slide centered and the previous and next slide showing a little bit on the side.

enter image description here

However, I don’t know how can I change the width of the slides and keep the slides centered

https://codesandbox.io/s/empty-wind-yxj67v?file=/index.html

.box {
  max-width: 1440px;
  display: flex;
  height: 500px;
  margin: 0 auto;
  overflow: hidden;
}
.box .banner-swiper {
  width: 100%;
  height: 100%;
  display: flex;
  position: relative;
}
.box .swiper-wrapper {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
}
.box .swiper-wrapper .prev-slide,
.box .swiper-wrapper .next-slide {
  opacity: 0.4;
}
.box .swiper-slide {
  display: flex;
  justify-content: center;
  align-items: center;
}
.box .swiper-slide {
  width: 1000px;
}
.box .swiper-slide img {
  display: block;
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.box .navigation {
  display: block;
  position: absolute;
  width: 120px;
  height: 56px;
  z-index: 50;
  bottom: 16px;
  right: 236px;
}
.box .navigation .previous {
  margin-right: 8px;
}
.box .navigation .previous,
.box .navigation .next {
  width: 56px;
  height: 56px;
  background-color: #424142;
}
.box .navigation .previous i,
.box .navigation .next i {
  color: white;
}

Getting Tooltipster: one or more tooltips are already attached to the element below. Ignoring. in console when hover or click the tooltip element

jQuery("body").delegate('[title][title!=]', 'mouseover',function (event){
    $('[title][title!=]').tooltipster({
        animation: 'grow',
        theme: 'tooltipster-punk'
    });
    jQuery(event.target).mouseover();
 })

refer the attached image error

The problem is when I generate HTML with JavaScript. First time I put the cursor over the element I don’t get any error in the browser console, but the second time I repeat it i get this errors:

If anybody knows what I’m doing wrong it would be of help. Thank you very much in advanced!!

Discord HTTPError [AbortError]: The user aborted a request


Hello, my bot changes the prices of cryptocurrencies with the name of discord. and it does it randomly between 3, 4, 5 minutes. but I am getting an error like this. I think the bot is blocking the discord when it sends name change requests on too many servers.

If you have a solution/idea, I would be very happy if you could help me.


C:UsersAdministratorDesktopcrypto-v2BOTS-1BTCnode_modulesdiscord.jssrcrestRequestHandler.js:93
        throw new HTTPError(error.message, error.constructor.name, error.status, request.method, request.path);
              ^

HTTPError [AbortError]: The user aborted a request.
    at RequestHandler.execute (C:UsersAdministratorDesktopcrypto-v2BOTS-1BTCnode_modulesdiscord.jssrcrestRequestHandler.js:93:15)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async RequestHandler.push (C:UsersAdministratorDesktopcrypto-v2BOTS-1BTCnode_modulesdiscord.jssrcrestRequestHandler.js:39:14)
    at async GuildMember.edit (C:UsersAdministratorDesktopcrypto-v2BOTS-1BTCnode_modulesdiscord.jssrcstructuresGuildMember.js:312:5) {
  code: 500,
  method: 'patch',
  path: '/guilds/962762744648585286/members/@me/nick'
}

Python & Selenium: How to get values generated by JavaScript

I use Selenium in Python for scraping.
I can’t get values though these values are displayed on the browser.

So I checked the HTML source code, then I found that there are no values in HTML as below.

HTML

<div id="pos-list-body" class="list-body">

</div>

But there are values when I checked developer tool in chrome.

DevTools

<div id="pos-list-body" class="list-body">
    <div class="list-body-row" id="pos-row-1">
        <div class="pos-list-col-1">
            <input class="list-checkbox" type="checkbox" value="1">
        </div>
        <div class="detail-data pos-list-col-2">
            1
        </div>
        <div class="detail-data pos-list-col-3">
            a
        </div>
        ...
    </div>
    <div class="list-body-row" id="pos-row-2">
        <div class="pos-list-col-1">
            <input class="list-checkbox" type="checkbox" value="2">
        </div>
        <div class="detail-data pos-list-col-2">
            2
        </div>
        <div class="detail-data pos-list-col-3">
            b
        </div>
        ...
    </div>
    ...
</div>

It seems that these values generated by JavaScript or something.

There is no iframe in sorce code.

How can I get these values with python?

It would be appreciated if you could give me some hint.

discompose javascript react state with three dots, but why we are specifying state and state’s attribute separately

I am a beginner in react, and javascript in general. And rencently I been following a Youtube tutorial. In the tutorial, I saw the folling code:

const reducer = (state, action) => {
    console.log(action)
    switch (action.type) {
        case 'ADD_TO_BASKET':
            // keep the state to be whatever it is, 
            // and the basket is whatever it currently is plus the item passed inside.
            return {
                ...state,
                basket: [...state.basket, action.item],
            };

        case 'REMOVE_FROM_BASKET':
            const index = state.basket.findIndex(
                (basketItem) => basketItem.id === action.id
            );
            let newBasket = [...state.basket];

            if (index >= 0) {
                newBasket.splice(index, 1);
            } else {
                console.warn(
                    `Cant remove product (id: ${action.id}) as its not in the basket!`
                )
            }

            return {
                ...state,
                basket: newBasket
            }

        default:
            return state;
    }

I think I understand what the code is doing at a high level, such that this specifies how the reducer function is handling different requests based on the action’s type.

The part that I am confusing is, from what I understand, the basket is one attribute of the state,
then why in the line

return {
                ...state,
                basket: newBasket
            }

it’s returning the basket alongside with the state, why couldn’t it be something like

return {
state.basket : newBasket }

Thanks for reading my question this far, much appreciate.

firebase data not being updated with use effect

hi i have to refresh my page to see the effect of the person adding an event to the calendar:

my code is

 const handleDateClick = async (DateClickArg) => {

        if(DateClickArg){
            
            const title = prompt("Enter title",DateClickArg.dateStr); // allows user to put a title in
            
            // making object
            const event = {
                title: title ? title : DateClickArg.dateStr,
                start: DateClickArg.date,
                allDay: true,
                
            }

            allEvents.push(event)

            const db = fire.firestore();
            let currentUserUID = fire.auth().currentUser.uid
            const doc = await fire
                        .firestore()
                        .collection("userCalendar")
                        .doc(currentUserUID)
                        .get()
                    
                        db.collection("userCal/"+currentUserUID+"/activities").add({event})       
        }

and my getuserinfo is:

    const getUserInfo = async () => {
        
        let currentUserUID = fire.auth().currentUser.uid
    
        const qSnap = await fire
        .firestore()
        .collection('userCal')
        .doc(currentUserUID)
        .collection("activities")
        .get()
        
        const data = []
        data = (qSnap.docs.map(d => ({ id: d.id, title: d.data().event.title, start: d.data().event.start.toDate(), allDay: d.data().event.allDay,...d.data() })));
        
        //setData(data)
        console.log(data);
        setData([...data])
       

}
        useEffect(() => {
            let mounted = false

            if(!mounted){
                getUserInfo()
            }
            
            return () => {
                mounted = true
                
            }
    
        }, [])

where am i going wrong with my use effect? is there a way for the data to update in the browser once its added to firebase? i am using react full calendar

How can I query and get data from an endpoint through the a search bar input in javascript?

This endpoint http://vk-data:8003/v1/entity/ returns this:

[
    {
        "id": "country",
        "url": "http://vk-data:8003/v1/entity/country",
        "name": "Countries",
        "description": "All the countries in the world"
    },
    {
        "id": "data-site",
        "url": "http://vl-data:8003/v1/entity/data-site",
        "name": "World data storage",
        "description": "A catalog of health data"
    }
]

I want to write a function that allows user to access either data-site or country data through a search bar input.

How can I get my code to do that? Here’s what I have so far.

<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="css/styles.css">

</head>
<body>
<button id="catalog" onclick="RetrieveCatalog()">Get Catalog</button>

<input type="text" placeholder="Search for User" onChange={(e) => RetrieveEntities(e.target.value)} className="input_search" />
<button onClick={fetchData} className="search_button">Search Github</button>
<script>

//fetch catalog function
function RetrieveCatalog(){
    //http request
    fetch("http://vk-data:8003/v1/entity/")
    .then(function(data){
        console.log(data)
        return data.json()
    })
    .then(function(data){})
    .catch(error => console.error(error))
    }
    
    //fetch catalog function
function RetrieveEntities(){
    //http request
    fetch("http://vk-data:8003/v1/entity/${entities}")
    .then(function(data){
        console.log(data)
        return data.json()
    })
    .then(function(data){})
    .catch(error => console.error(error))
    }

</script>

</body>

</html> 

expected a identifier instead saw ‘(‘. expected a identifier instead saw ‘)’

I am using bubble sort to sort a array but when I write swap function , I’m getting error when writing the line function swap(arr,j,j+1) I am getting the err” expected ‘)’ to match from ‘(‘

function solve(N,arr){
   
        
 for(var i = 0; i <N; i++){
     
    
   for(var j = 0; j < ( N - i -1 ); j++){

     if(arr[j] > arr[j+1]){
         
      
      swap(arr,j,j+1)
     }
   }
 }
 
 console.log(arr.join(" "));
function swap(arr,j,j+1) //getting error here "expected a identifier instead saw '('.  expected a identifier instead saw ')'. "[look at the screenshot ][1]
{
     var temp = arr[j];
       arr[j] = arr[j + 1];
       arr[j+1] = temp;
}
  
}

How to make iframe work in outer parent area?

How to close a popup opened in an iframe with ESC in the parent document area?

This is the currently applied JS source.

$(document).on('keyup', function(e) {
  if (e.key == "Escape") {
    $('.window:last-child .close').click();
    $('.window:last-child, .modal_bg:last-child').detach();
  }
});

I can’t close the popup opened in the iframe with a shortcut when I click the outer parent area.

Is it possible to close a popup opened in an iframe with ESC even within the parent area?

Merge two objects but not all properties

I am struggling to merge two objects the way I need them using Node.js express and mongoDB. Below you will see both initial objects.

Obj1: {
       "name":"max",
       "age":26,
       "hometown": "NY"
}
Obj2: {
       "id": "123",
       "favoriteteams" : ["Yankees, "Knicks"],
       "home" : "NY"
    }

I am currently trying:

const merged = {...obj1, ...obj2.favoriteteams};

But that gives me

merged: {
       0: "Yankees"
       1: "Knicks"
       "name":"max",
        "age":26,
        "hometown": "NY"
    }

But what I need is:

merged: {
       "name":"max",
        "age":26,
        "hometown": "NY"
        "favoriteteams": ["Yankees", "Knicks"];
    }

I also have tried const merged = {...obj1, ...obj2}; and using Object.assign() but both obviously then mesh in the fields I don’t need from obj2 (ID and home). Effectively I only need to get the favoriteteams from the second object, but I need that to be a new key in the first object and also to maintain the array response with the list of strings.

Thank you for any help.

Trying to position searchbar in nav

I made a nav bar, and I’m trying to add a search bar to it, but I can’t seem to position it.
I’d like to have the search bar show on the right side of the nav bar without overlapping any of the other elements. I tried relative and absolute position but nothing so far.

Any help is very much appreciated, thank you! 🙂

@import url('https://fonts.googleapis.com/css2?family=Open+Sans&display=swap');
html,
body {
  margin: 0;
  padding: 0;
  height: auto;
  font-family: 'Poppins';
  box-sizing: border-box;
  background-color: rgb(236, 241, 236);
}

body {
  margin-bottom: 0;
  padding: 0;
}

.search-bar {
  float: right;
  width: 200px;
  height: 40px;
}

.search-bar .search-icon {
  position: absolute;
  right: 0px;
  /*adjust this*/
  top: 0px;
  /*adjust this*/
  background-color: red;
}

nav {
  width: 100%;
  height: 140px;
  background-color: #333;
  color: #fff;
  text-align: center;
}

nav p {
  font-family: 'poppins';
  color: white;
  font-size: 40px;
  line-height: 40px;
  padding-top: 2%;
  text-align: center;
}

nav ul {
  margin: 0px auto;
  display: inline-block;
}

nav ul li {
  float: left;
  list-style: none;
  position: relative;
}

nav ul li a {
  display: block;
  font-family: 'poppins';
  text-transform: uppercase;
  color: white;
  font-size: 20px;
  text-decoration: none;
  padding: 0px 30px;
}

nav ul li a:hover {
  color: black;
}

nav ul li ul {
  display: none;
  position: absolute;
  padding: 10px;
  background-color: rgb(215, 209, 209);
  border-radius: 1%;
  z-index: 1;
}

nav ul li:hover ul {
  display: block;
}

nav ul li ul li {
  width: 180px;
}

nav ul li ul li a {
  padding: 8px 10px;
  color: black;
}

nav ul li ul li a:hover {
  background-color: rgb(120, 118, 118);
  transition: ease-in-out 0.2s;
}
<nav>
  <p>Book PRESS</p>
  <ul>
    <li><a href="#">Home</a></li>
    <li><a href="#">Books <i class="fa-solid fa-caret-down"></i></a>
      <ul>
        <li><a href="">Young Adult</a></li>
        <li><a href="">Adult</a></li>
        <li><a href="">Non-Fiction</a></li>
      </ul>
    </li>
    <li><a href="#">Authors <i class="fa-solid fa-caret-down"></i></a>

      <ul>
        <li><a href="">Our Authors</a></li>
        <li><a href="">Book Tours</a></li>
        <li><a href="">Events</a></li>
      </ul>
    </li>
    <li><a href="#">About Us <i class="fa-solid fa-caret-down"></i></a>
      <ul>
        <li><a href="">Our Team</a></li>
      </ul>
      <li><a href="#">News</a></li>
    </li>
    <li><a href="#">Contact Us <i class="fa-solid fa-caret-down"></i></a>
      <ul>
        <li><a href="">Submissions</a></li>
        <li><a href="">Permissions</a></li>
        <li><a href="">Translation</a></li>
        <li><a href="">Press</a></li>
        <li><a href="">Hiring</a></li>
        <li><a href="">Contact</a></li>
      </ul>
      <li class="search-bar">
        <form class="form"> <input type="text" name="Search" placeholder="Search"> <button type="submit"> </button> </form>
      </li>
    </li>


</nav>