how can reload a chart automatically in every fixed time in vaadin 14

I am using a column range chart to make a Gantt chart. As I am using the horizontal axis to show the time line and maintaining a red plot line to show the current time. To Show the red vertical line always in the middle .I need to refresh the chart. I am able to refresh the whole page but not able to refresh the chart alone.

I am able to start the timer at chart load event. I want to load the chart only. Not able to call the functions written in java code to call inside JavaScript function.

The Web Share API in JavaScript does not support sharing text along with files and URLs

I am using the Web Share API in JavaScript. When I set all four properties – title, text, URL, and files, it only shares the URL and files, excluding the text. I attempted sharing on WhatsApp, Twitter, Telegram, and Facebook. In all cases, it sends the URL and files except on Facebook, where it only sends the files. I tested this on Android Chrome. How can I fix this issue?


const shareButton = document.getElementById('shareButton');
shareButton.addEventListener('click', async () => {
    try {
        const blob = await fetch(base64Image).then(response => response.blob());
        const file = new File([blob], 'image.png', { type: 'image/png' });
        // Check if the Web Share API is supported by the browser
        if (navigator.canShare && navigator.canShare(file)){
                await navigator.share({
                    title: 'Share Image',
                    text: 'Check out this generated image! http://www.google.com',
                    url: 'http://www.google.com',
                    files: [file],
                });
          } else {
             // Web Share API not supported, provide fallback
             alert('Sorry, your browser does not support the Share API or Your system does not support sharing these files.');
          }
    } catch (error) {
        console.error('Error sharing image:', error);
    }
});

I expect that this API shares at least text, URL, and one file.

how to install Install shadcn/ui using yarn or npm

IAM NEW TO WEB DEVELOPMENT, CAN SOMEONE PLEASE GUIDE ME ON HOW TO INSTALL THIS?

Iam currently trying to build notion clone using nextjs using shadcn ui.
[ https://ui.shadcn.com/ ]

C:UsersjananOneDriveDesktopnotion>npx create-shadcn-ui-app@latest init
npm ERR! code E404
npm ERR! 404 Not Found - GET https://registry.npmjs.org/create-shadcn-ui-app - Not found
npm ERR! 404
npm ERR! 404  'create-shadcn-ui-app@latest' is not in this registry.
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, http url, or git url.

npm ERR! A complete log of this run can be found in: C:UsersjananAppDataLocalnpm-cache_logs2024-02-03T15_21_44_957Z-debug-0.log

C:UsersjananOneDriveDesktopnotion>yarn create shadcn-ui-app@latest init
yarn create v1.22.21
warning package.json: No license field
[1/4] Resolving packages...
error Error: https://registry.yarnpkg.com/create-shadcn-ui-app: Not found
    at params.callback [as _callback] (C:UsersjananAppDataRoamingnpmnode_modulesyarnlibcli.js:66148:18)
    at self.callback (C:UsersjananAppDataRoamingnpmnode_modulesyarnlibcli.js:140874:22)
    at Request.emit (node:events:518:28)
    at Request.<anonymous> (C:UsersjananAppDataRoamingnpmnode_modulesyarnlibcli.js:141846:10)
    at Request.emit (node:events:518:28)
    at IncomingMessage.<anonymous> (C:UsersjananAppDataRoamingnpmnode_modulesyarnlibcli.js:141768:12)
    at Object.onceWrapper (node:events:632:28)
    at IncomingMessage.emit (node:events:530:35)
    at endReadableNT (node:internal/streams/readable:1696:12)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21)
info Visit https://yarnpkg.com/en/docs/cli/create for documentation about this command.

How can I get live data from an API using HTTP.Get

Using
ANGULAR

I would like http.get to frequently pull data from an API, and can’t find a viable solution. The API is providing minute by minute traffic data, and I would like Angular to reflect the updates.

At the moment i am using interval from rxjs to refresh the Get request, but that’s crashing the browser. This turns out, is not a suitable way do get this done. It is memory intensive.

interval(3000).subscribe(x => { http.get('api.link')});

What solution is there that I could get this done conservatively ?

Rotating a line to look at the mouse with linear interpolation causes jumping

Earlier, I was trying to find out how to rotate a line around a pivot using p5.js, and I played with the code a little bit to make the line point towards the mouse using the atan2 function. It worked fine, and I decided to see what it would look like if I used linear interpolation (lerp) to make the animation look smoother. What was weird is that it seemed once the line passed a certain point, it jumped to the other side instead of just moving to that point.
example image of issue

Here’s the code I’m having the issue with:

let angle = 0;

let rot = 0;

function setup() {
  createCanvas(600, 300);
}

function draw() {
  let v1 = createVector(width / 2 - 50, height / 2);
  let v2 = createVector(width / 2 + 50, height / 2);

  background(255);
  stroke(0);
  strokeWeight(4);

  rot = lerp(rot, atan2(mouseY - v1.y, mouseX - v1.x), 0.1);

  push();
  translate(v1.x, v1.y);
  rotate(rot);
  translate(-v1.x, -v1.y);
  let r0 = line(v1.x, v1.y, v2.x, v2.y);
  strokeWeight(10);
  let p1 = point(v1.x, v1.y);
  let p2 = point(v2.x, v2.y);
  pop();
}

How can I make this animation look smooth, without the weird jumping?

How to get alert to display properly based on number of inputs?

i’m in a very beginner javascript course and we were tasked with making a simple loop “program”. I settled on asking users for names of colors and based on how many answers they come up with, it would display some kind of result message.

I got the initial question prompt to work asking for color names but no matter what i do or where I try to put my alert code, it doesn’t seem to work, any guidance on where to go from here? tried changing i in the alert pop up statements to colorNames and cName but still nothing

// variable for while loop
var colorNames = [];
var keepRunning = true;

// keep naming colors until done
while (keepRunning) {

    var newColor = prompt('Name as many colors as you can!' + "n" + 'If you can't think of any more, leave empty and hit OK.');

    //test if prompt box has something in it or not
    if (newColor.length > 0) {
        colorNames.push(newColor);
    } else {
        keepRunning = false;
    }
}

// display color names entered 
for (var i = 0; i < colorNames.length; i++) {

    var cName = colorNames[i];
    document.write(cName + "  ");

}

//alert pop up based on number of inputs
if (keepRunning = false) {
    if (i <= 4) {
        alert('That's all you could think of? Refresh and try again!')
    } else if (i <= 8) {
        alert('Not bad, but you can probably do better. Refresh to play again.')
    } else if (i <= 12) {
        alert('Wow! You really know your colors! You can refresh to challenge yourself again!')
    } else if (i >= 15) {
        alert('I don't think anyone could do better than this, nice job!')
    }
}

React – State items flickering when data is the same

I allow users to search for other users within my component using a query state variable to track this. Whenever this query changes, after a timeout, the query is performed and the new users are mapped on screen. Here is the code for this:

const [query, setQuery] = useState("")
const [users, setUsers] = useState([])
const [isLoading, setIsLoading] = useState(false)
const [noResultsFound, setNoResultsFound] = useState(false)


useEffect(() => {
    if (query === "" || !query) return

    let timer = setTimeout(async () => {
        setIsLoading(true)
        const res = await axiosPrivate.get(`${BASE_URL}/api/users/get_users/${query}`, { headers: { "x-auth-token": token } })
        if (res?.data?.length === 0) {
            setUsers([])
            setNoResultsFound(true)
        } else {
            setUsers(res.data)
            setNoResultsFound(false)
            console.log(users)
        }

        setIsLoading(false)
    }, 500)

    return () => {
        clearTimeout(timer)
    }
}, [query])

Then I map the users array on the screen if they are available, otherwise I display a loading indicator. If no results were found for the query, then some text indicating this is displayed instead.

            {isLoading && (
                <Spinner
                    noDelay={true}
                    withStyles={false}
                />
            )}

            {!isLoading && noResultsFound === false && users.length > 0 && (
                <>
                    {users.map((user) => (
                        <p key={uuidv4()}{ user.username}</p>
                    ))}
                </>
            )}

            {!isLoading && noResultsFound === true && users.length === 0 && <p>No users</p>}

The problem I have is that if the query changes, and the exact same results are returned from the API, a flicker occurs for each of the users list items. I have ensured all my keys for the mapped items are unique. How can I ensure that if the exact same results are returned from the API, then don’t re-render the list items to avoid the flicker on screen. If this is not a solution, is there any potential methods I could use in order to avoid this flickering? Thanks.

Looking for a javascript cryptography library on NPM

For a project I participate in I need a javascript library that allows you to encrypt/decrypt a text string with AES encryption, preferably abstracting on the crypto library. There are many libraries on npm that do these things, but I’m not an expert on this topic and I don’t know how to choose. I would have used crypto-js but it is no longer maintained.

  1. Could you recommend a good library on npm?

  2. More generally, what features should I look at in order to choose a professional level library on npm?

Smooth transition between Tailwind and React page switching

I want to make a smooth transition between page changes using react, with tailwind, the transitions are very abrupt.

page sitch

I will give the code example of the Home.jsx page

Home.JSX:


// Hooks
import{ useNavigate, Link, Navigate } from "react-router-dom"
import { useState } from "react"
import { useFetchDocuments } from "../../hooks/useFetchDocuments"

// Components
import PostDetail from "../../components/PostDetail"

const Home = () => {
  const [query, setQuery] = useState("")
  const { documents: posts, loading, error } = useFetchDocuments("posts")
  const navigate = useNavigate()
  // const [posts] = useState([])
  // const [loading, setLoading] = useState(true)

  const handleSubmit = (e) => {
    e.preventDefault()
    if(query){
      return navigate(`/search?q=${query}`)
    }
  }

  return (
    <main className="transition-all duration-300 ease-in-out">
      <div className="w-full bg-slate-900 h-72 md:h-48 
      md:mb-20
      lg:w-full">
        <h1 className="pt-10 text-2xl font-bold uppercase text-slate-400 text-center">Veja os nossos posts mais recentes</h1>
        <form onSubmit={handleSubmit} className="my-10 flex-col md:flex-row flex justify-center">
          <input type="text" placeholder="Ou busque por tags..." className="w-60 mx-auto  px-4 py-2 outline-none mb-4 rounded-lg
          md:mx-0 md:w-80"  onChange={(e) => setQuery(e.target.value)}/>
          <button className="bg-slate-400 w-40 mx-auto py-2 rounded-lg text-slate-800
          md:mx-0 md:ml-5 md:h-10">Pesquisar</button>
        </form>
      </div>
      <div className="mt-10">
        {loading && <p>Carregando...</p>}
        {error && <p>Erro ao carregar os posts: {error}</p>}
        {posts && posts.map((post) => (
          <PostDetail key={post.id} post={post}/>
        ))}
        {posts && posts.length === 0 && (
          <div className="flex flex-col text-center my-20">
            <p className="text-center text-2xl font-bold uppercase mb-10">Não foram encontrados posts</p>
            <Link to='/posts/create' className="w-40vw mx-auto my-2 bg-slate-600 py-2 rounded-md hover:text-slate-900 transition-all duration-500 text-slate-200 text-center
            md:w-20vw">Criar primeiro post</Link>
          </div>
        )}

      </div>
      
    </main>
    
  )
}

export default Home

What can I do to have a smooth transition? any tailwind classes, any external libraries?? Can someone help me?

I’m trying to use the && operator but it’s not working for me

My goal was to create a form where someone would insert both their username and password but if either value was less than five digits, an alert would show up to tell them that either or both of their value were less than five digits and I tried using the && logical operator to go about this but it I need to it the alert to only show up after both values have been inserted instead it only checks one and runs immediately. I am also using a traditional DOM event handler to go about this as well. What could I be doing wrong?

<form style= "margin-top: 2rem;" id="form">
  <label for="username">Create A Username</label>
  <input type="text" id="username" onblur="Blur1()"/>
  <input type="password" id="password"/>
  <div id="feedback1"></div>
  <input type="submit" value="send"/>
</form>
function Blur1() {
  var msg = document.getElementById("username");
  var pswrd = document.getElementById("password");
  var feedbck = document.getElementById("feedback1");

  if (msg.value.length < 5 && pswrd.value.length < 5) {
    feedbck.textContent = "Please insert a username and/or password with at least 5 digits";
  } else {
    feedbck.textContent = "";
  }
}
document.getElementById("password").onblur = Blur1;

Javascript. How to put number in the inputs td of dynamic table without tbody (there is a table id tableD) [closed]

I have a old Sudoku game in a dynamic table (id: tableD) without tbody.
I’m using it together with a new table (id: tableB) with images instead of numbers.
It works nice.
But I found innerHTML in the TD, not in the input.

I just need the functions (jquery?) to add the value in the input.

Here is the original snippet:

https://codepen.io/Mobius1/pen/EmJEoJ

Here is the experiment website:

https://www.pctraverse.nl/Project/Verkleind/Documents2/020224A.html

click on a image on the right site.
At all td’s is the number. That’s wrong.
It has to be in the chosen td only.
Put the mouse on the upper table.
click in a free input.
The image is after that in the second table.

Someone can help?


function help(bgp){
var column_num = parseInt( $(this).index() );
var row_num = parseInt( $(this).parent().index() );
var firstRow = document.getElementById('tableD').rows[row_num];
//var xp= firstRow.cells[column_num].innerHTML;

// working on all inputs together atonce not on the chosen input.

$(':input', '#tableD td').each(function () {

    this.value= bgp;
});
}

Setting Geometry in ee.Image: Facing Challenges in Google Earth Engine JavaScript API

I’m currently working on a project using the Google Earth Engine JavaScript API, and I’m encountering difficulties in setting the geometry for an ee.Image. I’ve tried using the setGeometry function, but it seems to be unavailable for ee.Image. I’ve explored the documentation and attempted alternative approaches, but I haven’t found a solution yet.

Here’s a simplified version of the code I’m working on:

var image = ee.Image(null, {
  'bands': bands,
  'geometry': geometry,
  'target': feature.getNumber('target')
});

// Attempted setGeometry
// image = image.setGeometry(geometry); // Results in an error

// Other attempts...
// image = image.set('system:footprint', geometry);
// image = image.set('system:geometry', geometry);

I would greatly appreciate any insights, alternative methods, or corrections to my approach. Has anyone else faced similar challenges when setting geometry for ee.Image in the Google Earth Engine JavaScript API? Your assistance would be invaluable.

Thank you in advance for your help!

Refresh child component

I have a problem to solve this case.

how to refresh child component 1, when the data changes in child component 2. Child 1 and Child 2 are in the same parent.

enter image description here

Real cases I have:

enter image description here

In this case, if there is an addition to the PO item, then I want the payment component to also refresh to get the results from the API. How does it do it?

And in the implementation, I want the payment data to also be refreshed (like calling the API) when I add items:

enter image description here

Sorry if my English is not good.

ASP.NET Core: Pulling data to Choices library with Ajax

In my ASP.NET Core project, I am pulling data to the second select element according to the ID value of the data I selected in the first select element with Ajax.

Ajax codes,

<script>
    $(document).ready(function () {
        $("#choices-single-brand").change(function () {
            var id = $(this).val();

            $.ajax({
                url: "/Inventory/ListModel?id=" + id,
                type: "GET",
                success: function (data) {
                    var modelSelect = $("#choices-single-model");
                    modelSelect.empty();

                    $.each(data, function (index, model) {
                        modelSelect.append($("<option>", {
                            value: model.modelID,
                            text: model.modelName
                        }));
                    });
                },
                error: function (xhr, status, error) {
                    console.log(xhr, status, error);
                }
            });

        });
    });
</script>

It is added to the normal select element as , there is no problem here. But I’m also using the choices library, so I can’t see the data. I restarted the library in the success function with Ajax, but it doesn’t work.

How can I solve this problem? I kindly ask for your support.