NodeJS regex returns 0 on string.search()

I’m working on a NodeJS script (launched from the CMD with the node command) getting me some HTML content in a string, in which I need to extract some data between a specific <div> element. I’m having a hard time firguring why this portion of code doesn’t give me the desired output.

const input = '<div class="some_class">Some data</div><div class="some_other_class">< class="some_other_other_class">...</div></div>'
const regex = new RegExp(/<div class="some_class">(.*?)</div>/g)
let obj = {
    'tmp': input.search(regex),
}
console.log(obj) // outputs { tmp: 0}
console.log(input.search(/<div class="some_class">(.*?)</div>/g)) // outputs 0
 
const x = input.search(/<div class="some_class">(.*?)</div>/g)
console.log(x) // outputs 0

I know this seems a bit of a regular issue here, but I tried passing the Regex with string format (between single quotes ‘), passing it as a Regex (between delimiter /) and finally by defining a new RegExp element, but without success. I always happen to get 0 as an output.

However, when I test it on an online tool, it does match and capture the desired data in the group #1 : https://www.regextester.com/?fam=131034

I don’t know if I’m missing something or if I’m doing something wrong, but after some hours spent on this issue, I’m quite struggling to get my ideas straight.

Image comparison slider with diagonal handle

I need to make an image comparison slider, the usual slider where you have two images and a handle that allows you to show/hide the images.
Like this one for example https://codyhouse.co/demo/image-comparison-slider/index.html

The twist is that the handle must be vertical, but not perfectly vertical, it must have an angle, like in the image below. Then it’s dragged horizontally. How would you achieve this?
enter image description here

Need to run a function with parameter, getting TypeError

I am following POM model in cypress where I have a use case to tick checkboxes in page from json file. My files are as below:
homePageTest.cy.js

it("some test", () => {
        cy.fixture("jsonValues").then((data) => {
        homePage.populateDataBasedOnJsonValues(data)
        });
    });

homepage.js

class HomePage{

_getcheckBox(question) {
        this.get("div[class$='checkbox-component-" + question + "'] > label > input");
    }

 populateDataBasedOnJsonValues(answers) {
        for (let key in answers) {
            const question = _getcheckBox(answers[key]);
            question.click()
        }
    }
}
export default HomePage;

On running the code I am getting following error:
TypeError
_homePage.default.populateDataBasedOnJsonValues is not a function

All other methods without parameter (e.g answers) are working fine. But this one with parameter is not working well.
I have tried to move the method in commands file and it is working, but I can’t move it in commands file as that is not where it belongs to.
I am not sure mistake I am making, have tried adding this. before _getcheckBox(answers[key]);
but that also doesnt work.
Can someone please help, new to cypress and JS. TIA
`

CSS, JS in Python Streamlit (.loader issue)

I have an issue with CSS and JS code in my streamlit project.

I tried to add an animation of the spinner which would be executed when the page is loading. I add my own spinner with st.markdown() function, the animation works but doesn’t hide when the page is fully loaded.

Here is an example of the code:

css_code = """
@import url('https://fonts.googleapis.com/css2?family=Readex+Pro:wght@300;400;500;600;700&display=swap');


* {font-family: 'Readex Pro';}

a {
    text-decoration: none;
    color: white !important;
    font-weight: 500;
}

a:hover {
    color: #d33682 !important;
    text-decoration: none;
}

ul {list-style-type: none;}

hr {
    margin-top: 0px;
    margin-bottom: 5%;
}

#MainMenu {visibility: hidden;}
footer {visibility: hidden;}
header {visibility: hidden;}

.loader {
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: transparent;
    transition: opacity 0.75s, visibility 0.75s;
}

.loader-hidden {
    opacity: 0;
    visibility: hidden;
}
    
.loader::after {
    content: "";
    width: 75px;
    height: 75px;
    border: 15px solid #dddddd;
    border-top-color: #7449f5;
    border-radius: 50%;
    animation: loading 0.75s ease infinite;
}

@keyframes loading {
    from {
        transform: rotate(0turn);
    }
    to {
        transform: rotate(1turn);
    }
}
"""


javascript_code = """
    window.addEventListener("load", () => {
        const loader = document.querySelector(".loader");

        loader.classList.add("loader-hidden");

        loader.addEventListener("transitionend", () => {
            document.body.removeChild("loader");
        })

    })
"""


st.set_page_config(page_title=PAGE_TITLE, page_icon=PAGE_ICON)

st.markdown("<style>{}</style>".format(css_code), unsafe_allow_html=True)

st.markdown("<script>" + javascript_code + "</script>", unsafe_allow_html=True)

st.markdown("""
<div class="loader"></div>
""", unsafe_allow_html=True)

time.sleep(5)
#Here is the rest of the code (website content)

I also tried the st.spinner() function but this animation always is displayed at the very top of the page which is not what I’m expecting (the animation should follow the user’s screen).

If you have any ideas how to make this animation hide after the page is fully loaded please share your ideas.

Rest of the code you can find here in this repo: https://github.com/KRSN5/app

There is also a one more thing a really small detail that I’d like to change. If there is any method to make st.text_area() empty/cleared after a successful message send please tell me how to do it.

Here is an example of the code:

st.header("Leave a message")

email = st.text_input("E-mail")
message = st.text_area("Message")
submit = st.button("Send")


if submit:
    if email and message:
        try:
            subject = "Subject"
            body = f"From: {email}nn{message}"
            data = {
                "email": email,
                "message": message
            }
            response = requests.post(f"xxxxxxxxxxxxxxxxxx",
                                    data=data,
                                    headers={"Referer": "http://xxxxxxxxxxxxx"})
            
            if response.status_code == 200:
                st.success("Sent successfully")
            else:
                st.error("Error occured")
        except Exception as e:
            st.error(f"Error occured: {e}")
    else:
        st.warning("Please complete all fields")

The throbber won’t go away

I would like the message to disappear from the field after the message has been successfully sent

Like/unlike works good on an individual post page , but cant figure how to do the same on a list of posts

Yesterday was stuck on liking/unliking post on an individual post page, but made it work eventually.

Now im stuck on liking/unliking post on a list of posts. Tried to do the same i did yesterday with separate post, but realized that Post component is getting mapped and doesnt render anything on its own.

Here are the components

const Feed = () => {

  const posts = useSelector(state => state.post.posts);
  console.log('posts', posts);
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(getAllPosts());
  }, [posts.length])

  return (
    <div className='feed'>
      <header className='feed__header'>
        <h2>Home</h2>
      </header>
      <PostBox />
      <ul className='posts__list'>
        {posts.map((el) => (
          <li key={el.id}>
            <Post
              id={el.id}
              text={el.text}
              likedBy={el.likedBy}
              createdAt={el.createdAt}
              userId={el.User?.id}
              userName={el.User?.name}
              userEmail={el.User?.email}
              userInfo={el.User?.info}
              userAvatar={el.User?.avatar}
            />
          </li>
        ))}
      </ul>
    </div>
  )
}
const Post = ({ id, text, likedBy, createdAt, userId, userName, userAvatar }) => {

  const dispatch = useDispatch();

  const openPostHandler = () => {
    dispatch(getOnePost(id))
  }

  const openUserPageHandler = () => {
    dispatch(getOneUser(userId))
  }

  const user = useSelector(state => state.auth.user);
  const postLikes = likedBy.length;
  const alreadyLiked = likedBy.map(el => el.Likes.user_id).includes(user.id)
  const [likes, setLikes] = useState(postLikes);

  console.log('id', id, 'likes', likes, 'already liked?', alreadyLiked);

  useEffect(() => {
    setLikes(postLikes)
  }, [postLikes])

  const likePostHandler = () => {
    if (alreadyLiked) {
      setLikes(prev => prev - 1)
      dispatch(upvotePost(id))
    } else {
      setLikes(prev => prev + 1)
      dispatch(upvotePost(id))
    }
  }

  const avatar = `http://localhost:3001${userAvatar}`
  const postedAt = new Date(createdAt).toLocaleString(undefined, { day: 'numeric', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' });

  return (
    <div className='post' >
      <Link to={`/user/${userId}`} className='post__link'>
        <div onClick={openUserPageHandler}>
          <img src={userAvatar ? avatar : default_avatar} alt='' className='post__avatar' />
        </div>
      </Link>
      <div className='post__content'>
        <div className='post__header'>
          <Link to={`/user/${userId}`} className='post__link'>
            <div className='post__titles' onClick={openUserPageHandler}>
              <h3>{userName}</h3>
              <h4>{postedAt}</h4>
            </div>
          </Link>
          <MoreHoriz className='post__options' />
        </div>
        <Link to={`/posts/${id}`} className='post__link'>
          <div className='post__body' onClick={openPostHandler}>
            {text}
          </div>
        </Link>
        <div className='post__media'>
          {/* <img src='https://images.ctfassets.net/pwv49hug9jad/4TFlhL2UJq6QgwOy2msA2G/551ecbaf540cd98dc523afb9cff82240/picture_books_in_sec_shools_664_02_18_2.jpg?fm=webp' alt='' /> */}
        </div>
        <div className='post__footer'>
          <div className='post__footer__options'>
            <ChatBubbleOutline fontSize='small' />
          </div>
          <div className='post__footer__options'>
            <FavoriteBorderOutlined fontSize='small' onClick={likePostHandler} />
            {likes > 0 ? likes : null}
          </div>
        </div>
      </div>
    </div>
  )
}

Tried putting the code from Post to Feed but was overwhelmed by everything being arrays and not sure how to proceed. Dont know if it even is a good idea to do this logic in Feed, because in theory there could be really big arrays to loop through so Post components seems like it is the right way, but again, it renders nothing so UseEffect cant track it.

here is how the posts array look like in console

enter image description here

and here is the code from yesterday’s individual post page for reference

const OnePost = () => {

  const post = useSelector(state => state.post.post_id);
  const user = useSelector(state => state.auth.user);

  const postLikes = post.likedBy?.length;
  const alreadyLiked = post.likedBy?.map(el => el.Likes.user_id).includes(user.id);
  const [likes, setLikes] = useState(postLikes);
  const [isLiked, setIsLiked] = useState(alreadyLiked);
  
  useEffect(() => {
    setLikes(postLikes)
    setIsLiked(alreadyLiked)
  }, [postLikes, alreadyLiked])
  
  useEffect(() => {
    dispatch(getOnePost(id))
  }, [likes])
  
  const { id } = useParams();
  const dispatch = useDispatch();
  const navigate = useNavigate();

  const openUserPageHandler = () => {
    dispatch(getOneUser(post.user_id))
  }

  const likePostHandler = () => {
    if (alreadyLiked) {
      setLikes(prev => prev - 1);
      setIsLiked(false)
      dispatch(upvotePost(id));
    } else {
      setLikes(prev => prev + 1);
      setIsLiked(true)
      dispatch(upvotePost(id))
    }
  }

  const avatar = `http://localhost:3001${post.userAvatar}`
  const createdAt = new Date(post.createdAt).toLocaleString(undefined, { day: 'numeric', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' });
  const comments = useSelector(state => state.comment.comments);

  useEffect(() => {
    dispatch(getPostComments(id));
  }, [])

  return (
    <>
      <div className='one-post__container'>
        <div className='one-post'>
          <div className='one-post__info'>
            <div className='one-post__info__head'>
              <div onClick={() => navigate(-1)}>
                <ArrowBackIcon className='one-post__back__arrow' />
              </div>
              <span className='profile__name'>
                <h3>Tweet</h3>
              </span>
            </div>
            <div className='one-post__info__mid'>
              <Link to={`/user/${post.userId}`} className='one-post__link'>
                <div className='one-post__name' onClick={openUserPageHandler}>
                  <img src={post.userAvatar ? avatar : default_avatar} alt='' className='one-post__profile__avatar' />
                  <h4 className='one-post__user__name'>{post.userName}</h4>
                </div>
              </Link>
              <div className='one-post__options'>
                <MoreHoriz />
              </div>
            </div>
            <div className='one-post__body'>{post.text}</div>
            <div className='one-post__footer'>
              <div className='one-post__time'>{createdAt}</div>
              <div className='one-post__icons'>
                <div className='one-post__icons__options'>
                  <ChatBubbleOutline fontSize='small' />
                </div>
                <div className={isLiked ? 'heart active' : 'heart'}>
                  <FavoriteBorderOutlined className='heart-icon' fontSize='small' onClick={likePostHandler} />
                  {likes > 0 ? likes : null}
                </div>
              </div>
            </div>
          </div>
        </div>
        <CommentForm />
        <ul className='comments__list'>
          {comments.map((el) => (
            <li key={el.id}>
              <Comment
                id={el.id}
                text={el.text}
                createdAt={el.createdAt}
                userId={el.User?.id}
                userName={el.User?.name}
                userAvatar={el.User?.avatar}
              />
            </li>
          ))}
        </ul>
      </div >
    </>
  )
}

Bottom tab menu in React Native not working

In my react native application I am trying to develop a bottom tab menu for android. When I press an icon of the menu to navigate to the page that it represents. I tried creating the menu and using the options property to create a button to use react navigation but without any luck. For more details I am using stack navigator in my App component for navigation. What can I do ?
Here is the code for the component where I am trying to show the menu:

const Discover = () => {
  const navigation = useNavigation();
  const Tab = createMaterialBottomTabNavigator();
return (
<SafeAreaView className="flex-1 bg-white relative">
<Tab.Navigator>
        <Tab.Screen
          name="Favorites"
          component={FavoritesScreen}
          options={{
            tabBarIcon: () => (
              <TouchableOpacity
                onPress={() => navigation.navigate("FavoritesScreen")}
                style={{
                  flex: 1,
                  justifyContent: "center",
                  alignItems: "center",
                }}
              >
                <Text>Favorites</Text>
              </TouchableOpacity>
            ),
          }}
        />
      </Tab.Navigator>
    </SafeAreaView>
  );
};

And here is the code for my App:

export default function App() {
  const Stack = createNativeStackNavigator();

  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Home" component={HomeScreen} />
        <Stack.Screen name="Discover" component={Discover} />
        <Stack.Screen name="ItemScreen" component={ItemScreen} />
        <Stack.Screen name="FavoritesScreen" component={FavoritesScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );

I am also leaving a picture of how my menu looks right now. For any advice I am gratefulPicture

Can’t filter an array in reference hook

I’m trying to filter out found objects in a array in a hidden object game I’m working on. When a player clicks at the right coordinate and selects the right object, that object is taken away from an array. To do that, I’m storing the array in a ref value as let items = useRef([]) since I’m not actually rendering the objects.

Finding player’s selection inside the array doesn’t have any issue at all.

const item = items.current.find(item => item.name === toy)

if(!item){
  setFound('Not quite, try again!')
  return;
}

However filtering player’s selection simply does nothing

item.current.filter((item)=>item.name!==toy);

My first option was actually to store items in a state but items never reach zero. I suspect that happens immediately since states work asynchronously, which means I can actually see the deletion one render ahead. On the other hand, a plain variable isn’t recommended because I’m setting it inside useEffect, items in reality stores data from a data base.

React documentation states that references are mutable values but I’ve not been able to changing with Array.splice() either.

Can anyone point out what I’m doing wrong please?

This is my code:

import {useNavigate} from 'react-router-dom';
import { useState, useEffect, useRef} from "react";
import supabase from "../config/supabaseClient";
import Image from "./image"
import Timer from "./timer";

const Game = ()=>{
  let items = useRef([]);
  const [fetchError, setFetchError] = useState(null);
  const [found, setFound] = useState("");
  const [time, setTime] = useState(0);
  const navigate = useNavigate();

  useEffect(()=>{

    const fetchOptions = async()=>{
      const{data,error} = await supabase
        .from('items')
        .select();

      if(error){
        setFetchError('Could not fetch items');
        items.current = [];
      }

      if(data){
        items.current = data;
        setFetchError(null);
      }
    }
    fetchOptions();
  },[])

  function handleAction(click, toy){
    
    const item = items.current.find(item => item.name === toy )

    if(!item){
      setFound(`Not quite, try again!`);
      return;
    }

    if(click.x>item.left&&click.x<item.right){
      if(click.y<item.bottom&&click.y>item.top){
        setFound(`Well done! You've found Sarah's ${toy}`);
        items.current.filter((item)=>item.name!==toy);
        console.log(items.current)
        if(items.length === 0){
          console.log('Winner');
          navigate("/leaderboard", {state:time});
        }
      }
    }else{
      setFound(`Not quite, try again!`);
      return;
    }
  }

  return(
    <>
      {fetchError&&(<p>{fetchError}</p>)}
      <Timer time={time} setTime={setTime}/>
      <Image handleAction={handleAction}/>
      <p>{found}</p>
    </>
  );

}

export default Game;

Can`t receive calls with SIPJS

I’m trying to use SIPJS to create a sip client, and I can call another phones on the server just fine, but I cannot receive calls, that are dropped immediately like the phone is not connected.

The test code that I used is below:

<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" type="module" src="sip-0.21.2.js"></script>
  </head>
  <body>
    uri sip <input type=text id="uri" value="sip:[email protected]"><br>
    usuario sip <input type=text id="user" value="4002"><br>
    senha<input type=text id="password" value="US4002"><br>
    numero a chamar<input type=text id="remote" value="4001"><br>
    <video id="remoteAudio" hidden></video>
    <video id="localAudio" hidden></video><br>
    <button id="registerButton">REGISTER</button>
    <button id="unregisterButton" disabled>UNREGISTER</button><br>
    <button id="callButton" disabled>CALL</button>
    <button id="hangupButton" disabled>HANGUP</button>
    <script>
      const server = "172.17.4.216"
      const aor = "sip:4002@" + server;
      const server_url = "wss://" + server +":8089/ws";
      const registerButton = document.getElementById("registerButton")
      const unregisterButton = document.getElementById("unregisterButton")
      const callButton = document.getElementById("callButton")
      const hangupButton = document.getElementById("hangupButton")
      var UA;
      var session;
      var callNumber = document.getElementById("remote").value

      const transportOptions = {
         server: server_url
      };

      const uri = SIP.UserAgent.makeURI(document.getElementById("uri").value);

      const userAgentOptions = {
         authorizationPassword: document.getElementById("password").value,
         authorizationUsername: document.getElementById("user").value,
         transportOptions: transportOptions,
         uri: uri,
         contactName: document.getElementById("user").value,
         viaHost: server,
      }
      const options = {
            aor: aor,
            media:{
                constraints: {
                    audio: true,
                    video: false,
                    },
                remote: {
                    video: document.getElementById('remoteAudio')
                },
                local: {
                    video: document.getElementById('localAudio')
                }
            },
                userAgentOptions: userAgentOptions
            }
      UA = new SIP.Web.SimpleUser(server_url, options);
      //UA = new SIP.Web.SessionManager(server_url, options);
      UA.delegate = {
        onCallReceived: async (session_) => {
                console.log("INCOMING CALL!");
                await UA.answer(session_);
            },
        onCallCreated: (session_) => {
                console.log("=========================Calling "+callNumber+"========================");
                session = session_;
            },
        onCallHangup: (session_) => {
                console.log("=========================Hangup on "+callNumber+"========================");
                callButton.disabled = false;
                hangupButton.disabled = true;

            }
      }
    async function receive(invitationOptions){
      console.log("INCOMING CALL!");
      UA.answer();
    }

    function register(){
      UA.connect().then(()=>{
        UA.register().then(()=>{
            registerButton.disabled = true;
            unregisterButton.disabled = false;
            callButton.disabled = false;
            hangupButton.disabled = true;
        })
      })
    }

    function unregister(){
       console.log("Unregister")
       UA.unregister().then(()=>{
            callButton.disabled = true;
            unregisterButton.disabled = true;
            registerButton.disabled = false;
       });
    }

    function call(){
        console.log(callNumber);
        callNumber = document.getElementById("remote").value
        UA.call("sip:" + callNumber + "@" + server).then(()=>{
            callButton.disabled = true;
            hangupButton.disabled = false;
        });
    }

    async function hangup(){
        UA.hangup(session);
    }

    registerButton.addEventListener("click",register);
    callButton.addEventListener("click",call);
    registerButton.addEventListener("click",register);
    hangupButton.addEventListener("click",() => hangup());
    unregisterButton.addEventListener("click",unregister);

    </script>
  </body>
</html>

The extension works fine in another softphones, and can call and receive.
Does anybody know what I am doing wrong?

How can I return correct value from function with multiple ajax requests?

I have a function and its have nested two ajax call. I want to return a value inside from second ajax call when ajax call is successed. i think because function ending but the ajaxs call still not end. But i didn’t solve it.

I prepared a example code below:

        
    var patato = function(){
            $.ajax({
                type: 'POST',
                url: 'https://jsonplaceholder.typicode.com/posts',
                dataType: 'json',
                data: {
                    title: 'foo',
                    body: 'bar',
                    userId: 1,
                },
                success:function(res){
                    console.log("Work 1")
                    $.ajax({
                        type: 'POST',
                        url: 'https://jsonplaceholder.typicode.com/posts',
                        dataType: 'json',
                        data: {
                            title: 'foo',
                            body: 'bar',
                            userId: 1,
                        },
                        success:function(res){
                            console.log("Work 2")
                            return true;
                        }
                    })
                }
            })
            console.log("Çalıştı 3")
        }
        var patatos = patato();
        if(patatos) {
            console.log("Patato true")
        }else{
            console.log("Patato false")
        }
<script src="https://code.jquery.com/jquery-3.7.0.min.js" integrity="sha256-2Pmvv0kuTBOenSvLm6bvfBSSHrUJ+3A7x6P5Ebd07/g=" crossorigin="anonymous"></script>

VanillaJS drag & drop dashboard with HTML panels

I have dashboard that has multiple HTML panels with different sizes (determined with w, h) and positions (determined with x, y). These panels are found in a CSS grid with columns and rows. I cannot use any libraries or plugins for this dashboard.

Currently, the panels have drag and drop functionality but I have a few problems with it:

  1. When a panel is dropped on a cell that doesn’t have a panel adjacent to it,the dropped panel does not populate the target cell, and defaults to a cell closest to another panel in the grid.

  2. Due to the fact that panels have different width and height properties, they overlap often after being dropped, which needs to be fixed by moving other panels around dynamically as the drop occurs.

I tried various ways to check for overlaps and adjust accordingly, including adding/removing rows and columns dynamically, and shifting the overlapped panels right or down until the overlap is fixed. I may have done it incorrectly though.

Here is some code detail:

part of the html:

<!-- DASHBOARD PANELS -->
            <div class="dashboard-page-panels" data-bind="
                style: {
                    gridTemplateColumns: `repeat(${$data.grid.columns()}, 1fr)`,
                    gridTemplateRows: `repeat (${$data.grid.rows()}, 1fr)`
                },
                event: {
                    drop: (...p) => $data.onDrop(...p),
                    dragover: (...p) => $data.onDragOver(...p)
                }">
                    <!-- ko foreach: panels() -->
                    <div
                        class="dashboard-page-panel"
                        data-bind="
                            style: {
                                gridColumn: `${$data.position.x()} / span ${$data.position.w()}`,
                                gridRow: `${$data.position.y()} / span ${$data.position.h()}`
                            },
                            event: {
                                dragstart: (...p) => $data.onDragStart(...p)
                            },
                            attr: {
                                'data-panel-element-id': $data.elementId(),
                                draggable: $root.editMode()
                            }"
                        draggable="true"
                    >
                    <div data-bind="visible: $root.editMode()">
                        <div class="dashboard-page-panel-edit-btn" data-bind="click: (...p) => $data.panel_resize_btn(...p)">
                            <a title="Edit" class="fa fa-edit"></a>
                        </div>
                        <div class="dashboard-page-panel-edit-btn" data-bind="click: (...p) => $parent.removePanel($data)">
                            <a title="Delete" class="fa fa-trash"></a>
                        </div>
                    </div>
                    <div data-bind="attr: {id: $data.elementId()}, stopBinding: true"></div>
                    </div>

part of the javascript code:

    constructor(DashboardVM, page)
    {
        this.DashboardVM = DashboardVM;
        this.DashboardAPI = DashboardVM.DashboardAPI;
        this.page = page;
        this.title = ko.observable(page.title || 'Missing title!');
        this.grid = {
            columns: ko.observable(page.grid?.columns || '1'),
            rows: ko.observable(page.grid?.rows || '1')
        };
        let panels = [];
        for (let panel of page.panels || [])
            panels.push(new DashboardPagePanelVM(this, panel));
        this.panels = ko.observableArray(panels);
        this.actions = ko.observableArray(page.actions || []);
        let panelTypeNames = [];
        for (let [typeName,panelType] of Grape.registry.getRegister('DashboardPanelType'))
            panelTypeNames.push(typeName);
        this.panelTypes = ko.observableArray(panelTypeNames);
        this.draggedPanelType = ko.observable('');
        this.loadPanels();
    }
    async loadPanels()
    {
        // This is necessary to ensure the knockout element attributes id has been set :(
        await Promise.resolve();
        for (let panel of this.panels())
        {
            const element = document.getElementById(panel.elementId());
            if (!element)
            {
                // something probably went wrong in setting the panel element IDs
                console.warn(`Couldnt find element with ID ${panel.elementId()}`);
                continue;
            }
            try {
                await panel.load(element);
            } catch (err) {
                //console.error(err);
                element.innerHTML = 'Error rendering this panel: ' + err.message;
            }
        }
    }
    getPanelByElementId(elementId)
    {
        return this.panels().find((x) => x.elementId() === elementId);
    }
    getPanelByPoint(x, y)
    {
        let element = document.elementFromPoint(x, y);
        if (!element)
            return null;
        while (
            !element.classList.contains('dashboard-page-panel') &&
            element.parentElement
        )
            element = element.parentElement;
        if (!element)
            return null;
        return this.getPanelByElementId(element.dataset.panelElementId) || null;
    }
    async onDrop(data, event)
    {
        console.debug('onDrop data=',data, 'event=',event);
        // Allow drop
        event.originalEvent.preventDefault();
        let payload;
        try {
            payload = event.originalEvent.dataTransfer.getData('text/json');
            payload = JSON.parse(payload);
        } catch (err) { 
            return;
        }
        let draggedPanel = this.getPanelByElementId(payload.elementId);
        console.debug('draggedPanel:',draggedPanel);
        let targetPanel = this.getPanelByPoint(event.originalEvent.clientX, event.originalEvent.clientY);
        if (targetPanel)
        {
            // Dropped on another panel. Swap the 2 panels around
            console.debug('targetPanel:',targetPanel);
            let originalPos = {x: draggedPanel.position.x(), y: draggedPanel.position.y()};
            draggedPanel.position.x(targetPanel.position.x());
            draggedPanel.position.y(targetPanel.position.y());
            targetPanel.position.x(originalPos.x);
            targetPanel.position.y(originalPos.y);
        }
        else
        {
            // Dropped on empty space
            let left = null;
            let right = null;
            let below = null;
            let above = null;
            let x = event.originalEvent.clientX;
            while (left == null && (x=x-10) > 0)
                left = this.getPanelByPoint(x, event.originalEvent.clientY);
            x = event.originalEvent.clientX;
            while (right == null && (x=x+10) < window.innerWidth)
                right = this.getPanelByPoint(x, event.originalEvent.clientY);
            let y = event.originalEvent.clientY;
            while (above == null && (y=y-10) > 0)
                above = this.getPanelByPoint(event.originalEvent.clientX, y);
            y = event.originalEvent.clientY;
            while (below == null && (y=y+10) < window.innerHeight)
                below = this.getPanelByPoint(event.originalEvent.clientX, y);
            console.debug('left=',left);
            console.debug('right=',right);
            console.debug('above=',above);
            console.debug('below=',below);
            if (left && !right)
            {
                draggedPanel.position.x(left.position.x()+1);
                draggedPanel.position.y(left.position.y());
            }
            else if (!left && right)
            {
                draggedPanel.position.x(right.position.x()-1);
                draggedPanel.position.y(right.position.y());
            }
            else if (left && right)
            {
                draggedPanel.position.x(right.position.x()-1);
                draggedPanel.position.y(right.position.y());
            }
            else if (!left && !right)
            {
                if (above)
                {
                    draggedPanel.position.y(above.position.y()+1);
                    draggedPanel.position.x(above.position.x());
                }
                else if (below)
                {
                    draggedPanel.position.y(below.position.y()-1);
                    draggedPanel.position.x(below.position.x());
                }
            }
            else
            {
                console.debug('Not implemented');
            }
        }
    }
    onDragStart(data, event)
    {
        console.debug('onDragStart data=',data, 'event=', event);
        event.originalEvent.dataTransfer.effectAllowed = 'move';
        this.draggedPanelType(data)
        return true;
    }
    // Allow drop
    onDragOver(data, event)
    {
        event.originalEvent.dataTransfer.dropEffect = 'move';
        event.originalEvent.preventDefault();
    }

JS input sum output as currency format?

I use the following code to add 2 values of an input and then i display it as the result.

                    $(document).ready(function(){
    var val1 = +$(".value1").val();
    var val2 = +$(".value2").val();
    $("#result").val(val1*val2);
});
$('.input').blur(function(){
    var val1 = +$(".value1").val();
    var val2 = +$(".value2").val();
    $("#result").val(val1*val2);
});

This works fine, but just outputs a standard number format i.e 9000 i want to make it display $9,000 or just 9,000.

I am using the below code which allows me to have an input box with data-type=”currency” and that displays fine i.e $9,000.

But when i try to add it to my “result” input box it is just displaying as standard numbers is there anyway of merging my val1*val2 function with the input output?

$("input[data-type='currency']").on({
    keyup: function() {
      formatCurrency($(this));
    },
    blur: function() { 
      formatCurrency($(this), "blur");
    }
});


function formatNumber(n) {
  // format number 1000000 to 1,234,567
  return n.replace(/D/g, "").replace(/B(?=(d{3})+(?!d))/g, ",")
}


function formatCurrency(input, blur) {
  // appends $ to value, validates decimal side
  // and puts cursor back in right position.
  
  // get input value
  var input_val = input.val();
  
  // don't validate empty input
  if (input_val === "") { return; }
  
  // original length
  var original_len = input_val.length;

  // initial caret position 
  var caret_pos = input.prop("selectionStart");
    
  // check for decimal
  if (input_val.indexOf(".") >= 0) {

    // get position of first decimal
    // this prevents multiple decimals from
    // being entered
    var decimal_pos = input_val.indexOf(".");

    // split number by decimal point
    var left_side = input_val.substring(0, decimal_pos);
    var right_side = input_val.substring(decimal_pos);

    // add commas to left side of number
    left_side = formatNumber(left_side);

    // validate right side
    right_side = formatNumber(right_side);
    
    // On blur make sure 2 numbers after decimal
    if (blur === "blur") {
      right_side += "00";
    }
    
    // Limit decimal to only 2 digits
    right_side = right_side.substring(0, 2);

    // join number by .
    input_val = "$" + left_side + "." + right_side;

  } else {
    // no decimal entered
    // add commas to number
    // remove all non-digits
    input_val = formatNumber(input_val);
    input_val = "$" + input_val;
    
    // final formatting
    if (blur === "blur") {
      input_val += ".00";
    }
  }
  
  // send updated string to input
  input.val(input_val);

  // put caret back in the right position
  var updated_len = input_val.length;
  caret_pos = updated_len - original_len + caret_pos;
  input[0].setSelectionRange(caret_pos, caret_pos);
}

Vus Js – How to show javascript code with opening and closing script tag as v-html or in textarea input box

In my vus js application, I have this html code:

<b-row>
    <b-col md="12">
        <h5>Add the following code in the header of every page</h5>
        <b-form-textarea readonly name="header_code" id="textarea" v-model="header_code" rows="10" max-rows="6"></b-form-textarea>
    </b-col>
    <b-col md="12" class="mt-1">
        <h5>Add the following code on the thank you page, replace the demo data with live data</h5>
        <b-form-textarea readonly name="thank_you" id="textarea" v-model="thank_you" rows="10" max-rows="6"></b-form-textarea>
    </b-col>
</b-row>

Here, on this thank_you v-model I want set the javascript code along with opening and closing script tag so that user can copy the code.

What I am doing this :

created() {
    callThankYouCode
},
methods: {
    callThankYouCode() {
        const jsToken = this.jsToken;
        const code = `tsTracker(
'track',
'purchase',
{
    token:  '${this.jsToken}',
    items: [

            {item_id: "id1", quantity: X1 (numeric), price_per_item_without_vat: Y1 (numeric)},
            {item_id: "id2", quantity: X2 (numeric), price_per_item_without_vat: Y2 (numeric)},
            {item_id: "id3", quantity: X3 (numeric), price_per_item_without_vat: Y3 (numeric)}
    ],
    // Price without VAT = Price with VAT / (1 + VAT rate)
    order_total_without_vat: TOTAL_CART (numeric), // without shipping costs or applied discounts, must be numeric
    order_shipping_total_without_vat: TOTAL_SHIPPING (numeric), // shipping costs without VAT
    user_data: {
        // this is optional, but the data is usefull it you are planning to use Facebook Conversion API for a better matchig, it is recommended if you want to you POAS in Facebook, for GDPR you must add it in TOS
        email: "",
        phone: "",
        last_name: '',
        first_name: ''
    },
    currency: 'RON',
    transaction_id: 'ORDER_ID_OR_REFERENCE',
    other_costs: 0, // if there are any other costs, for example packing price etc, without VAT
    order_date: 'ORDER Placement date', // it should be exactly how its inserted in the database, not autogenerated with javascript, using the format Y-m-d H:i:s
}
);
        `;

        this.thank_you = code;
    },
}

On created hook I called this method callThankYouCode. On this method, I have set the thank_you data property value. It’s working fine.

but

I want to add the opening and closing script tag on this code variable. If I do so then the application is not working. I see this type of error on the console log:

[vue-router] Failed to resolve async component default: Error: Module
build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError:
/Applications/MAMP/htdocs/FeedParserProject/resources/js/src/views/apps/poas/settings.vue:
Unterminated template. (456:32)

454 | ‘purchase’, 455 | {

456 | token: ‘${this.jsToken}’,
| ^ 457 | items: [ 458 | 459 | {item_id: “id1”, quantity: X1 (numeric),
price_per_item_without_vat: Y1 (numeric)},

So, can you tell me how can I use a this javascript code with opening and closing script tag to the thank_you data propery and use it in the html area?

How JavaScript language is been executed under the hood in Google V8 engine

Hello Guys I have a question, so i study computer science at university , we have built a simple language called NewJava , its syntax is similar to Java, we built the interpreter with c++ , we have done everything lexical thing , grammar , we create token , parse it to create The abstract syntax tree , then for example when we see variable declaration in NewJava such as : ‘’ dec number = 10’’ we store the variable with its value in a hashMap using c++ to keep track with the value, and same thing with other functionalities such as creating obj, array, linkedList , everything we create in NewJava is just converted into c++ w pushed into a hash-table. Our teacher said that this is how programming languages are created, it looked weird to me , because when i read the V8 engine for example i saw that the AST compiled and machine code generated , and not like i study, i want to know if javaScript for example works the same way we created NewJava or not? , thank you!

I have searched on google about that and i saw that the code of AST is compiled into bytecode!

How to show a data from two different database (mongodb) in separate html card in site?

I try to create web site which will contain ads that users place on the site. I create a database with mongodb, one database contain a images and others database contain text, I create a “seacrets” page when a users login they can add images from computer and text and that will bi store in database. I managed to do it but i dont now how to present images and text from database in html card for each input individually.

This is my app.js

const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require("mongoose");
const bcrypt = require("bcrypt");
const saltRounds = 10;
const multer = require("multer");

const app = express();



app.set('view engine', 'ejs');
app.use(express.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));


mongoose.set('strictQuery', true);
const db1 = mongoose.createConnection("mongodb://127.0.0.1:27017/SiteofAds",);
const db2 = mongoose.createConnection("mongodb://127.0.0.1:27017/Images",{
    useNewUrlParser: true,
    useUnifiedTopology: true
});
const db3 = mongoose.createConnection("mongodb://127.0.0.1:27017/Content",);

const UsersSchema = new mongoose.Schema ({
  email: String,
  password: String,

});

const User = db1.model("User", UsersSchema);

const ImageSchema = new mongoose.Schema({
    
    image: {
        data:Buffer,
        contentType:String
    }
});

const Image = db2.model("Image", ImageSchema);

const storage = multer.memoryStorage()
const upload = multer({storage:storage})

const ContentSchema = new mongoose.Schema({
    text: String

});

const Content = db3.model("Content", ContentSchema);


images= []
contents= []
app.get("/", async (req, res) =>{
    const images = await Image.find().sort({_id:-1})
    const contents = await Content.find().sort({_id:-1})
    res.render("home", {images: images, contents: contents});
});

app.get("/login", function(req, res){
    res.render("login");
});

app.get("/register", function(req, res){
    res.render("register");
});



app.post("/register", function(req, res){


    bcrypt.hash(req.body.password, saltRounds, function(err, hash) {
        const newUser = new User({
        email: req.body.username,
        password: hash
    });

    newUser.save().then(function(){
        res.render("secrets");
    }).catch(function(error){
        console.log(error);
    });
        
        
    });


  
});


app.post("/login", function(req, res){
    const username = req.body.username;
    const password = req.body.password;


    User.findOne({email:username}).then(user => {
        if (user) {
            bcrypt.compare(password, user.password, function(err, result) {
        if (result === true) {
            res.render("secrets");
        }
    });
        }
    })

})

myTextArea = "";
img = "";


app.post("/secrets", upload.single("image"), async(req, res) =>{
    

    const image = new Image({
        image:{
            data: req.file.buffer,
            contentType: req.file.mimetype
        }
    })

    const content = new Content({
        text: req.body.myTextArea
    })

    await image.save();
    await content.save();

    res.render('home');  

})

app.get("/contact", function(req, res){
    res.render("contact");
});

app.get("/about", function(req, res){
    res.render("about");
});

app.get("/proba", function(req, res){
    res.render("proba");
});


app.listen(3000, function() {
  console.log("Server started on port 3000");
});

this is my home.ejs

<%- include("partials/header") %>



<div class="grid">
    <div class="grid-item">
        <div class="card">
            <img class="card-img" src="images/NoImage.jpg" alt="">
            <div class="card-content">
                <h1 class="card-header">No.1</h1>
                <p slass="card-text">
                    Text
                </p>
                <button class="button2"> About</button>

            </div>
        </div>

    </div>
</div>

I found how to pull out data from database with foreach, but i dont now how to data present in individually card.

I try this, but all data from database display on same space in one card. I try put this for loop outside car but i didn’t succed.
Can anyone help me or have any ideas, thanks

<div class="grid">
    <div class="grid-item">
        <div class="card">

            <% if (images.length> 0) { %>
                <% images.forEach((image)=> { %>
                    <div class="card">
                        <img
                            src="data:<%= image.image.contentType %>;base64,<%= image.image.data.toString('base64') %>" />
                    </div>
                    <% }); %>
            <% } else { %>
                    <p>No images uploaded yet.</p>
             <% } %>

                        <div class="card-content">
                                <h1 class="card-header">Oglas br.1</h1>
                                <p slass="card-text">
            <% if (contents.length> 0) { %>
                <% contents.forEach((content)=> { %>
                                <div>
                                    <h2>
                                        <%= content.text %>
                                    </h2>
                                </div>
                <% }); %>
            <% } else { %>
                                <p>No content yet.</p>
             <% } %>
                                    
                                <button class="button2"> Detalji</button>
                        </div>
        </div>
    </div>
</div>

To find a solution for problem.