Can’t pass a function as parameter from a NextJS component

I have this type of code in a NextJS component:

const [currentGPS, setCurrentGPS] =
        useState({coords:{latitude:0.0,longitude:0.0}})

useEffect(() => {
  utl.getGPSLocation(
    (v:{coords: {latitude:number; longitude:number;};})=>
    setCurrentGPS(v))
}, [])

When using the function below:

function getGPSLocation({callBackFn}:
  {callBackFn:
    (v:{coords: {latitude:number; longitude:number;};}) => void
  }) {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
      (position: {coords: {latitude:number; longitude:number;};}) => {
        callBackFn(position)
        console.log('(U)position.coords.latitude='+JSON.stringify(position.coords.latitude))
        console.log('(U)position.coords.longitude='+JSON.stringify(position.coords.longitude))
      });
  } else {
    console.log("Geolocation is not supported by this browser.");
  }
} /* End of getGPSLocation */

I get this error in the Web Developer Tools console of my web browser:

Uncaught TypeError: t is not a function
    NextJS 10
page-1aeb39b39d44f814.js:1:332

The message above is due to the line of code:

callBackFn(position)

If I comment out the line, I see what I expect:

(U)position.coords.latitude=25.515932844138406 page-2bc533c4f68ab71b.js:1:339
(U)position.coords.longitude=67.32855152591916 page-2bc533c4f68ab71b.js:1:417

​Why am I getting the error? And what is the way to solve it?

I need to have the right syntax to use to pass my function (setCurrentGPS) to getGPSLocation() when calling it.

Astro – Using client:load directive to include JavaScript for components not working as expected

I’m using React in Astro, and when including a TSX component and applying the client:load directive, it doesn’t work, i.e., the JavaScript is not included.

I’m new to Astro.

This is how the code looks:

<Navbar client:load path="blog" />

I need interactivity for the Navbar because I have dropdowns and dropdown togglers. The onClick handlers on them are not working.

I don’t get data of sectionId in ThemeModal component

I am currently working on the Shopify remix app. I made one route app.sections. I write a query to get data from the database in the loader function and export it to my component now in my component I pass this data to another component named ProductCard through props and again pass this data from ProductCard to ThemeModel component. In my Product card components there is one button named Install section and onClick of the button I show the ThemeModel component. ThemeModal is a one Modal which shows a list of themes of Shopify online store. there is one submit button at the end of themeModal where I use the Form API of Remix and give an action path to the app/section route. so when I click the button this functionality works but every time I get the section-id 1. So how can I get a different section-id when I click on different sections?

1 – map on totalSection and give to the ProductCard component
2 – Give totalTheme and section_id from ProductCard to ThemeModal component
3 – use the ThemeModal component and give section_id and selectedThemeId at the Submit button.

[1 image]:(https://i.stack.imgur.com/GPKHu.png)
[2 image]:(https://i.stack.imgur.com/iT4OB.png)
[3 image]:(https://i.stack.imgur.com/BtU6z.png)

So, I want that when click on the submit button of ThemeModal, I don’t get a different section-id.
I only get every time section-id = 1.

How to creat family tree?

I am making a family tree website, I am using php, mysql and orgChat.js, I have to show the children of a person in this website, then the data of the children of those children and we have to keep doing like this till further. We find out the name of a person’s father from the parent_id, for example, if Jon’s ID is 1, then the parent_id of his children will be 1. Below I am giving the structure of my table as well as my code.

I have a problem, currently I am seeing only one branch whereas I have to display all the branches as is happening in the first branch.

Table Structure

id | name | parent_id |

1 | Jone | null |

2 | Max | 1 |

3 | Kane | 1 |

4 | Gale | 2 |

Jone is father, Max is son of Jone and Gale is Grand Child of Jone.

index.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Family Tree</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/orgchart/2.1.9/js/jquery.orgchart.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/orgchart/2.1.9/css/jquery.orgchart.min.css">
    <style>
        #chart-container {
            width: 100%;
            height: 500px;
        }
    </style>
</head>
<body>
    <h2>Family Tree</h2>
    <div id="chart-container"></div>

    <script>
        $(function() {
            // Fetch family tree data from PHP script
            $.ajax({
                url: 'fetch_family_tree.php',
                type: 'GET',
                dataType: 'json',
                success: function(data) {
                    // Initialize OrgChart
                    $('#chart-container').orgchart({
                        'data': data,
                        'depth': 5, // Set the depth level for better visualization
                        'nodeContent': 'name'
                    });
                }
            });
        });
    </script>
</body>
</html>

fetch_family_tree.php

<?php
// Include the database connection file
include 'db.php';

// Fetch family tree data from the database
$sql = "SELECT id, name, parent_id FROM family_tree";
$result = mysqli_query($connection, $sql);

// Organize the data into a hierarchical structure
$family_tree = array();
while ($row = mysqli_fetch_assoc($result)) {
    $id = $row['id'];
    $name = $row['name'];
    $parent_id = $row['parent_id'];

    if ($parent_id === NULL) {
        // Root node
        $family_tree[$id] = array(
            'id' => $id,
            'name' => $name,
            'children' => array()
        );
    } else {
        // Non-root node
        if (!isset($family_tree[$parent_id]['children'])) {
            $family_tree[$parent_id]['children'] = array();
        }
        $family_tree[$parent_id]['children'][] = array(
            'id' => $id,
            'name' => $name,
            'children' => array() // Initialize children array
        );
    }
}

// Function to recursively add descendants to each node
function addDescendants(&$node, $family_tree) {
    if (isset($node['children'])) {
        foreach ($node['children'] as &$child) {
            if (isset($family_tree[$child['id']]['children'])) {
                addDescendants($family_tree[$child['id']], $family_tree);
            }
        }
    }
}

// Recursively add descendants to each node
foreach ($family_tree as &$node) {
    addDescendants($node, $family_tree);
}

// Close the database connection
mysqli_close($connection);

// Get the root node
$root_node = reset($family_tree);

// Output the root node to start traversal
echo json_encode($root_node);
?>

Upgrading Hapi and Joi validation issues

I’m currently upgrading an API server that uses Hapi for handling requests. When upgrading from Joi 13.7.0 to 17.12.2 and Hapi 18.1.0 to 21.3.3 I’m having an issue with POST requests returning a 400 error with the message "payload" must be of type object and using the content type text/plain;charset=UTF-8 (due to the way applications are calling the route).

The route configuration currently looks like this:

const postRouteA = {
  method: 'POST',
  path: '/post-route-a/{id}/item',
  options: {
    handler: async (request, h) => {
      // ....
      // Handler Code
      // ....
      return h.response(result).code(201);
    },
    description: 'Api description',
    validate: {
      params: Joi.object({
        id: Joi.string()
          .required()
          .description('Unique identified')
          .example('1a'),
      }),
      payload: Joi.object({
        date: Joi.string()
          .required()
          .description('Date/time')
          .example('2018-06-27T01:35:21.595Z'),
        description: Joi.string()
          .required()
          .description('Description')
          .example('Example Description'),
      }).label('payload'),
    },
    response: {
      status: {
        201: Joi.object({
          id: Joi.number().integer()
            .example(1234)
            .description('Unique identified'),
        }).label('Result'),
      },
    },
  },
};

Prior to upgrading the route making a POST request worked with the content-type header set to text/plain;charset=UTF-8. But after upgrading, this route only works when content-type header is set to application/json. In addition to upgrading packages, I have also moved from NodeJS 8 to 18.

Is there any way to get this working without having to update the application that uses this and maintain the current functionality?

Is there a way to know the style is declutter?

When my feature requires a combination of text and line styles at the same time, the text is decluttered using overflow, but the lines still exist. I don’t have a way to judge and hide the lines. Do you know of any other ways I can use this combination?
it looks like this now.

enter image description here

I want to know if it is possible to get the declutter of the style, or if there is another way to achieve this effect.

ServiceNow Flow Designer – Invalid property id error

The error: invalid property id (Process Automation.65fea5d993050210f7db35918bba1034.InlineScript_assignment_groupa1fea5d9f5050210d8e77cda73f14762; line 10)

The Code:
// Get the incident category
var category = current.category;

// Define a map to store category-to-group
var assignmentMap = {
  "Hardware": "Hardware",
  "Software": "Software",
  "Network": "Network",
  "Inquiry/Help": "Help Desk",
  null: "Incident Management",
};

// Does the category exists in the map
var assignedGroup = assignmentMap[category];

// Assign the group to the incident if found
if (assignedGroup) {
  current.assignment_group = assignedGroup;
} else {

  gs.info ("no assignment for " +category);
}

// Update the incident record
current.update();

I am expecting that assignment groups get associated with categories at creation or update of records.

How to allow focus on two components, TextField and Popover, at the same time

I have a popover component that is rendered below a textfield component. The use case is to toggle a menu when a user types a special key such as : in to the textfield. The user can then click one of these menu items “autocomplete” the textfield.

A good example of this is GitHubs Hidden text expander feature.

github feature gif

I have two implementations. One implementation, which mui implements by default, creates a focus trap on the menu when it is opened, preventing the user from freely typing in to the textedit component. The menu component is then accessible with the keyboard controls such as ESC, ENTER, TAB as well as closes on blur.

To allow the user to continue typing in to the textfield while the menu is still open, I have disabled the autofocus on the popover menu component using some of the apis mui offers.

How can I accomplish something likes GitHubs feature that allows the component to have some accessibility while continuing to allow the user to freely type in to the textfield?

Here is the implementation that disables the focusing feature for the popover menu.

  return (
    <>
      <div className="card">
        <TextField
          fullWidth
          inputRef={inputRef}
          value={text}
          id="filled-basic"
          label="Filled"
          variant="filled"
          onChange={(e) => handleChange(e)}
        />
        <Menu
          id="demo-positioned-menu"
          aria-labelledby="demo-positioned-button"
          open={activeToken?.word === "#"}
          onClose={handleClick}
          anchorReference="anchorPosition"
          autoFocus={false}
          disableAutoFocus={true}
          disableEnforceFocus={true}
          anchorPosition={{
            top: t + 20,
            left: l
          }}
          anchorOrigin={{
            vertical: 'bottom',
            horizontal: 'right',
          }}
          transformOrigin={{
            vertical: 'top',
            horizontal: 'left',
          }}
        >
          <MenuItem onClick={() => handleClose('JavaScript')}>#JavaScript</MenuItem>
          <MenuItem onClick={() => handleClose('Clojure')}>#Clojure</MenuItem>
          <MenuItem onClick={() => handleClose('Python')}>#Python</MenuItem>
        </Menu>
      </div>
    </>
  )

Fixing my error: closing the tutorial popup

Not sure how to.
If you want my code, here

// Tutorial Popup

  const slides = document.querySelectorAll('.tutorial-slides');

        const dots = document.querySelectorAll('.tutorial-dot');

                const nextBtn = document.querySelector('.tutorial-next');

        let currentSlide = 0;



        // Show the slide based on current slide index

        function showSlide(slideIndex) {

            slides.forEach((slide, index) => {

                slide.style.display = index === slideIndex ? 'block' : 'none';

            });



            dots.forEach((dot, index) => {

                dot.classList.remove('active');

            });

            dots[currentSlide].classList.add('active');

        }



        // Next button click handler

        nextBtn.addEventListener('click', function() {

            currentSlide++;

            if (currentSlide === slides.length) {

                // Hide the popup if it's the last slide

               

                document.getElementById('tutorial-popup').style.display = 'none;'

            } else {

                showSlide(currentSlide);

            }

        });



        // Dot click handler (optional)

        dots.forEach((dot, index) => {

            dot.addEventListener('click', function() {

                currentSlide = index;

                showSlide(currentSlide);

            });

        });



        // Show the first slide initially

        showSlide(currentSlide);     

Was excpecting it to close the tutorial popup when it reached slides.length but didn’t, instead, it kept showing empty tutorial templates.
For some reason, it kept creating empty templates and then couldn’t read the classlist, i trii tried msny ways to make the tutorial popup close at the last slide which is ‘4’ but it was considered ‘3’ in terms of this javascript.

Importing a js library into Phoenix app.js file stop LiveView

I have imported a javascript library to connect a digital wallet to my Phoenix/Liveview dApp, however that causes Liveview to stop working and all live routes became regular http routes

import {PeraWalletConnect} from "@perawallet/connect"
// or
import "@perawallet/connect"

Once I comment the import Liveview returns to function normally, I wonder where is the issue here, I have tried another library for another wallet and I had the same thing, any help please ?

apexchart javascript grouped stacked bars sometimes not working

Here’s the scenario, I have multiple tabs containing multiple reports using apexcharts javascript.

For some reason, I can’t get the grouped stack bar to work just like from the demo in https://apexcharts.com/javascript-chart-demos/bar-charts/grouped-stacked-bars/. In the demo it was grouped into two per categories. Mine is just stacked in a single line.

I already tried incognito and still the same it is only in a single line. tried clearing cache using laravel’s optimize still not working.

It must be in my application since the sample given from the demo works just fine when I pasted it in codepen. any ideas?

Here’s my html code

<div class="tab-content mt-4" id="chart-tab-category-content">
    <div class="bg-white tab-pane fade active show" id="effect-rating" role="tabpanel" arialabelledby="effect-rating">
        <div id="effect-rating-test">

        </div>
        <div id="effect-rating-process">

        </div>
    </div>

    <div class="bg-white tab-pane fade" id="rate-distribution-summary" role="tabpanel" arialabelledby="chart-tabs-rating-distribution">
        <div class="mt-4" id="rate-distribution">

        </div>
        <div class="mt-4" id="rating-distribution-process">

        </div>
    </div>
</div>

Here’s from the sample given by apexcharts

var options = {
      series: [
      {
        name: 'Q1 Budget',
        group: 'budget',
        data: [44000, 55000, 41000, 67000, 22000]
      },
      {
        name: 'Q1 Actual',
        group: 'actual',
        data: [48000, 50000, 40000, 65000, 25000]
      },
      {
        name: 'Q2 Budget',
        group: 'budget',
        data: [13000, 36000, 20000, 8000, 13000]
      },
      {
        name: 'Q2 Actual',
        group: 'actual',
        data: [20000, 40000, 25000, 10000, 12000]
      }
    ],
      chart: {
      type: 'bar',
      height: 350,
      stacked: true,
    },
    stroke: {
      width: 1,
      colors: ['#fff']
    },
    dataLabels: {
      formatter: (val) => {
        return val / 1000 + 'K'
      }
    },
    plotOptions: {
      bar: {
        horizontal: true
      }
    },
    xaxis: {
      categories: [
        'Online advertising',
        'Sales Training',
        'Print advertising',
        'Catalogs',
        'Meetings'
      ],
      labels: {
        formatter: (val) => {
          return val / 1000 + 'K'
        }
      }
    },
    fill: {
      opacity: 1,
    },
    colors: ['#80c7fd', '#008FFB', '#80f1cb', '#00E396'],
    legend: {
      position: 'top',
      horizontalAlign: 'left'
    }
    };

    var chart = new ApexCharts(document.querySelector("#effect-rating-test"), options);
    chart.render();

Content inside ScrollView React Native can’t be scrolled

I have a screen, there he is:

// Home.jsx

import {View, Text, StatusBar} from 'react-native';
import Head from '../components/header/Head';
import {useSafeAreaInsets} from 'react-native-safe-area-context';
import Greeting from '../components/block/Greeting';
import MiniMenu from '../components/block/MiniMenu';
import ArticleMiniList from '../components/block/ArticleMiniList';
import InternetCheck from '../components/utils/InternetCheck';
import {createContext, useEffect, useState} from 'react';
import {
  GestureHandlerRootView,
  RefreshControl,
  ScrollView,
} from 'react-native-gesture-handler';
import PointPelanggaran from '../components/block/PointPelanggaran';
import {
  widthPercentageToDP as wp,
  heightPercentageToDP as hp,
} from 'react-native-responsive-screen';

export const RefreshContext = createContext();

function HomeScreen() {
  const insets = useSafeAreaInsets();

  const [refresh, setRefresh] = useState(false);

  useEffect(() => {
    if (refresh) {
      setTimeout(() => {
        setRefresh(false);
      }, 3000);
    }
  }, [refresh]);

  return (
    <View>
      <GestureHandlerRootView>
        <RefreshContext.Provider value={{refresh, setRefresh}}>
          <View
            className="justify-center items-center space-y-10"
            style={{
              paddingTop: insets.top,
              paddingBottom: insets.bottom,
              paddingLeft: insets.left,
              paddingRight: insets.right,
            }}>
            <StatusBar
              backgroundColor="transparent"
              barStyle={'dark-content'}
              translucent={true}
            />
          </View>

          <Head name={'StudentHub'} button />

          {/* <View style={{flex: 1}}> */}
          <ScrollView
            // contentContainerStyle={{flexGrow: 1}}
            contentInsetAdjustmentBehavior="always"
            refreshControl={
              <RefreshControl
                refreshing={refresh}
                onRefresh={() => setRefresh(true)}
              />
            }>
            <View
              style={{
                flex: 1,
              }}>
              <Greeting />
              <MiniMenu />
              <ArticleMiniList />
              <PointPelanggaran />
            </View>
          </ScrollView>
          {/* </View> */}

          <InternetCheck />
        </RefreshContext.Provider>
      </GestureHandlerRootView>
    </View>
  );
}

export default HomeScreen;

I can’t scroll in ScrollView even though the content is already more than the screen height.

I saw some suggestions on the internet to provide a container with the flex-1 style to wrap the ScrollView, but with that I can’t see my content at all.

Without flex container :
Can’t scrolling, but the content is still visible

With flex container :
Content is not visible and absolutely can’t be scrolled

Desafio do Array dos Minerais

Descrição
Você é um mestre construtor em um mundo de blocos e tem a tarefa de gerar biomas em diferentes regiões do

//Desafios JavaScript na DIO têm funções “gets” e “print” acessíveis globalmente:
//- “gets” : lê UMA linha com dado(s) de entrada (inputs) do usuário;
//- “print”: imprime um texto de saída (output), pulando linha.

// Lê a quantidade de golpes informada pelo usuário.
// O parseInt(()) vai converter os valores de entrada(string) para um valor numérico(Int).
const quantidadeGolpes = parseInt(gets());

// TODO: Defina aqui os tipos de minerais Carvao, Ferro, Diamante e Pedra
let minerais = [” Carvao “, ” Ferro “, ” Diamante “, ” Pedra “];

// Loop para cada golpe, de 1 até a quantidade informada
for (let i = 1; i <= quantidadeGolpes; i++) {
// Calcula o índice do mineral usando o operador de módulo (%) para garantir que o índice esteja dentro do tamanho do array
let minaIndex = i % minerais.length;

// TODO: Agora exiba o índice i, concatene com o caractere “:”, após, concatene com tipo de minerais[minaIndex]:
print(i + “:” + minerais[minaIndex]);
}

que desce certo esse código mas não está dando

Node JS – Recieve UDP String Used for Live Timing – Issues with Parsing Data

I have a simulator game that outputs Live Timing results via a UDP String. In Node JS I spun up a UDP client to receive data from the game. I’m getting what I need from the game but I’m having a hard time parsing the data so that I can use to update a webpage in real time. The string comes in as a big string with smaller strings separated by n.

This race had one racer in it, me. This is what is received by the Node JS Client.

MSG
0
EVENT
RACE
LiveResults Test
Forest Raceway
1256.0
OPEN

ENTRY
123
Racer Name
KTM 250 SX-F 2023
OEM 250 SX-F '23
MX2 OEM
FF011000010134CF9F


SESSION
RACE2
INPROGRESS
L 2

WEATHER
CLEAR
0.0

BESTLAP
906
82443
82443
1
36201
60607
15.2

LASTLAP
906
82443
82443
1
36201
60607
15.2

I’ve tried using RegEx and using split to try and extract the data I need. I just can’t seem to go get it to work. What would be the most efficient way to do this? There will be about 30 racers per server so I’m assuming there will be 30 racers under the ENTRY section each racer contains 6 lines. (Race #, Racer Name, Bike, Bike Model, Class and GUID)

I want to be able to extract all details about the racer and their LASTLAP time.

React – Using useState to push object of arrays to an array

I’m new to react and I want to keep track of array, as it changes. I’m using useState and I want to add array of objects into another array. I can accomplish this with push() but based on react documentation, this is mutating the array, which is not the right way. How could I accomplish this using array spread ..., slice() and etc?

Code

const [images, setImages] = useState(data.images)
const [object, setObject] = useState([])

const removeImage = (image) => {
    object.push(images)
    setImages(images.filter(i => i.id != image.id))
  }

Result

Array [ (5) […] ]
Array [ (5) […], (4) […] ]
Array(3) [ (5) […], (4) […], (3) […] ]
Array(4) [ (5) […], (4) […], (3) […], (2) […] ]
Array(5) [ (5) […], (4) […], (3) […], (2) […], (1) […] ]
Array(5) [ (5) […], (4) […], (3) […], (2) […], (1) […] ]
Array(5) [ (5) […], (4) […], (3) […], (2) […], (1) […] ]
Array(5) [ (5) […], (4) […], (3) […], (2) […], (1) […] ]
Array(5) [ (5) […], (4) […], (3) […], (2) […], (1) […] ]