How can I fix my SvelteKit script when using Google Translate?

SvelteKit Script Doesn’t work with Google Translate

I don’t know what happen to my code when use google translate it doesn’t work. I have function that show a timer.

when I choose another language (english default) the timer stop working.

I trying to console what in the element does, the log :

  • English
    00:32:15

  • Another Language
    <font style="vertical-align: inherit;"><font style="vertical-align: inherit;">00:32:15</font></font>

How to resolve “Could not resolve com.android.tools.build:gradle:8.1.1”

Could not resolve com.android.tools.build:gradle:8.1.1.

I’m new to react native and am trying to run an existing project but I keep getting this error. I use VSCode. Could I get a reason on why this happens and what I could do to fix this?
Thanks,
Jerrin

The supplied phased action failed with an exception.
A problem occurred configuring root project ‘veinapp’.
Could not determine the dependencies of null.
Could not resolve all task dependencies for configuration ‘:classpath’.
Could not resolve com.android.tools.build:gradle:8.1.1.
Required by:
project :
Could not resolve com.android.tools.build:gradle:8.1.1.
Could not get resource ‘https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/8.1.1/gradle-8.1.1.pom’.
Could not GET ‘https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/8.1.1/gradle-8.1.1.pom’.
No such host is known (dl.google.com)

How to format Chart.js dates in the axes and tooltip

I have the following code that uses chart.js to generate a line graph.
The Y axis represents price values, while the X axis represents date values.
I want the dates on the X axis to display only the year, but I still want the full date to appear in the tooltip when hovering over a data point.

  const datesArray = ["1 May 2023", "2 May 2023", "3 May 2023", "4 May 2023", "5 May 2023"];
  const valuesArray = [107.71, 105.98, 106.12, 105.21, 106.215];

  const Chart = ({ width }) =>  (
    <ChartDiv style={{ width }} className='cursor-auto'>
      <PriceGraph 
         chartData={{ data: valuesArray, labels: datesArray }} 
         chartColour={'#218B82'} 
         chartFillColour={'#F2FFFF'} 
      />
    </ChartDiv>
  );
import React from 'react';
import { Line } from 'react-chartjs-2';
import { Chart, registerables } from 'chart.js';
import 'chartjs-adapter-date-fns';
Chart.register(...registerables);

const PriceGraph = ({ chartData, chartColour, chartFillColour }) => {
  const options = {
    scales: {
      x: {
        ticks: {
          display: true,
          callback: (value, index, values) => {
            const tickDate = new Date(value);
            return tickDate.getFullYear().toString();
          }
        }
      },
      y: {
        beginAtZero: true,
        ticks: {
          display: true,
        }
      }
    }
  }

  const data = {
    labels: chartData.labels,
    datasets: [
      {
        data: chartData.data,
        backgroundColor: chartFillColour,
        borderColor: chartColour,
        fill: true,
      }
    ]
  }

  return <Line data={chartData.labels ? data : null} options={options}/>;  
}

export default PriceGraph

When I run my code the tool tip reflects the correct date, however each tick on the X Axis displays “1970”. I expect this is an issue with the data being input input in my callback function or the inappropriate use of a callback function.

Reviewing the chart.js documentation, there is an indication that I should use the type: time, and apply formatting. When I modify my code as follows I get a blank chart.

scales: {
      x: {
        type: 'time',
        time: {
          unit: 'year',
          tooltipFormat: 'dd MMM yyyy'
        },
        ticks: {
          display: true,
        }
      },

Any suggestions on how I should go about formatting my X axis?

How to declare type `spread` in Mongoose?

I’m looking to use spread in Mongoose but I can’t find a way to do it. I have tried many different ways but nothing works. Below is an example of what I am trying to do:
The schema that I want is as follows:

    const mongoose = require("mongoose");
    const ImageSchema = mongoose.model("Image",
        new mongoose.Schema({
            img_name: String,
            img_path: String,
            labels: [{
                labelId:{type: mongoose.Schema.ObjectId, ref: 'Label'},
               
                x1: Number,
                x2: Number,
                ....
                xn: Number,

                y1: Number,
                y2: Number, 
                ...
                yn: Number,
            }],
            is_deleted : {type: Boolean, default: false}
        }, {
            timestamps: true,
            collection: 'Image'
        })
    );

    module.exports = ImageSchema;

With labels is an array of objects with properties: labelId is an object that references to the collection name Label and x1, x2, ..., xn, y1, y2, ..., yn.
How do I declare the spread type in this case for x1… xn, y1… yn? Because x1, x2, …, xn, y1, y2, …, yn are different depending on each labeling case

React Native Maps Rendering current location breaks when I restart App

currently with my app I have it so that it asks the user for location perms and if they accept it then fetches their location. Currently however when I render the map with a set region it works and when the change the code to their location that the code fetches it changes to their location. When i reset the app or Expo the app crashes because the state is undefined. How can I get passed this? Here is the code:

const Map = () => {

  // Get permissons for using user location
  const [location, setLocation] = useState();
  
  useEffect(() => {
    const getPermissions = async () => {
      let { status } = await Location.requestForegroundPermissionsAsync();
      if (status !== 'granted') {
        console.log("Please grant location permissions");
        return;
      }

      let currentLocation = await Location.getCurrentPositionAsync({});
      setLocation(currentLocation.coords);

      console.log("Location:");
      console.log(currentLocation);
    };
    
    getPermissions();

  }, []);

    return(
//Will change this Mapview to users current location
//Will display about 0 - 30 miles away from used depending on user settings.
    <MapView 
    initialRegion={
      { 
          //I when I restart the app with latitude and longitude as latitude: latitude: location.coords.latitude longitude: location.coords.longitude app crashes cause the state is cleared. 
          latitude: 24.8607,
          longitude: 67.0011,
          latitudeDelta: 0.0922,
          longitudeDelta: 0.0421,
        }}
     style ={styles.map}/>
  );
}

I want the app to constantly be set to the users location even if the app is restarted

react.js formic and yup multiple error display

I am trying to validate using formic and yup on react.js. In the schema I created for yup, there is an email and password section, I just want to show all the errors in the password section at the same time, the errors in the email section should be displayed in order, but I couldn’t do it, but I would be very grateful if you could help me.

Here is how I created the yup object

 const validationPageTwo = Yup.object({
   email: Yup.string().required("Required field"),
   password: Yup.string()
  .required("Required field password")
  .matches(/^(?=.{8,})/, "Must Contain 8 Characters")
  .matches(/^(?=.*[!@#$%^&*])/, " One Special Case Character")
  .matches(/^(?=.*[0-9])/, " One Number")
  .matches(/^(?=.*[a-z])/, " One Lowercase")
  .matches(/^(?=.*[A-Z])/, " One Uppercase"),
 });

javascript alert not working when handling exception in Laravel

I tried to handle duplicate exception, where if it catch the duplicate exception it should pop up some javascript alert with message

Below is the code I’m using :

 public function storeNeraca(Request $request)
    {
        try {
            $neraca = new Neraca;
            $neraca->outlet = $request->outlet;
            $neraca->bulan = $request->bulan;
            $neraca->tahun = $request->tahun;
            $neraca->kode = $request->outlet.$request->bulan.$request->tahun;
            $neraca->save();
        } catch (Exception $e) { 
            if ($e->getCode() == 23000) {
                echo '<script language="javascript">';
                echo 'alert("Data yang diminta sudah tersedia")';
                echo '</script>';
            }
        }
        
        
        return redirect()->back();
    }

the result is, it doesn’t create a new Neraca (because it’s a duplicate), it also doesn’t show error stack trace (it’s a good thing), but it also doesn’t show pop alert, which I hope it should show it, can anynone help where i get things wrong?

Is there a way to update only the values of the modified cells in the tabulator grid without redrawing the whole thing?

I’m using a tabulator to create a grid,
When the cell is completely modified, I would like to modify the cell’s addsts with “update.
So when I finished modifying a cell using the ‘cellEdited’ function, I got the information of that cell and entered update in addsts,
Using console.log changes the value to addsts to update, but does not change the value to addsts on the grid on the screen.

To solve this problem, I checked the official documents and they told me the table.redraw() method, but if the data is more than 10000, I think it’s an inefficient way to redraw the whole thing every time I modify multiple rows.

I want to update only the row of the cell I modified, is there a way?

The columns I defined.

var table = new Tabulator("#dataList", {
        height:300,
        virtualDom: true, // 스크롤 추가
        virtualDomBuffer: 50,
        virtualDomBufferedRenderTimeout: 20,
        layout: "fitColumns",
        ajaxURL: "<c:url value='findList'/>",
        ajaxConfig: "POST",
        ajaxContentType:"json",
        ajaxParams: function(params) {
            return {
                searchValue1: $("[name=searchValue1]").val(),
                searchValue2: $("[name=searchValue2]").val()
            };
        },
        columns:[
            {formatter:"addsts", hozAlign:"center",  width:150},
            {formatter:"rownum", hozAlign:"center" , width:50},
            {formatter:"rowSelection",titleFormatter:"rowSelection",align:"center",headerSort:false, hozAlign:"center" , width:50},
            {title:"1", field:"codecategorykey", editor:"input", editable:editCheck, "cellClick":cellClick},
            {title:"2", field:"categoryname", editor:"input", cellEdited:function(cell){
                var rowData = cell.getRow().getData();
                if (rowData.addsts != "insert"){
                    var rowData = cell.getRow().getData();
                    rowData.addsts = "update";
                    
                }
            }}
        ],
        movableColumns:true,
        resizableRows:true,
        initialSort:[
            {column:"codecategorykey", dir:"desc"}
        ],
        rowSelection:true,
        ajaxResponse: function(ajaxUrl, params, response){
            return response;
        }
    });

Thank you.

If you change the value of addsts to update, it is expected that both the data value taken on the console and the grid on the screen will be changed to update.
However, the data on the console has been changed to update, but the values do not change dynamically on the grid on the screen.
I don’t want to refresh the entire grid, I want to change the value of the row I updated, leaving the other data intact.
table.updateData didn’t work

What could be causing data not to show up on the front-end of a Next.js and React.js app using Firebase’s Firestore?

I’m literally on the verge of pulling all my hair out. Not sure why but my data isn’t being pulled from Firestore.

export const getStaticPaths = async () => {
const carRef = collection(dbs, "cars");
const carSnap = await getDocs(carRef);
const carList = carSnap.docs.map(doc => doc.data());
const paths = carList.map(car => {
return {
  params: { id: car.blob?.toString() || '' }
 }
})

return {
 paths,
 fallback: false
 }
}

export const getStaticProps = async (context: any) => {
const id = context.params.id;
const carRef = collection(dbs, "cars");
const carSnap = await getDocs(carRef);
const carList = carSnap.docs.map(doc => doc.data());
const car = carList.find(car => car.blob?.toString() === id);
return {
 props: { car }
 }
}

type Props = {
car: any
}

https://i.stack.imgur.com/2hTPN.png

https://i.stack.imgur.com/PhMsa.png

https://i.stack.imgur.com/SPaar.png

https://i.stack.imgur.com/Zo12J.png

I’ve tried playing with the rules on Firebase but didn’t fix anything, according to them I have been reading data but nothing seems to show up on the front end.

How to use Chartist in React Typescript Component

I’m struggling to use Chartist in my React Typescript component. I’m using Chartist v1.3.0 and am getting these errors:

enter image description here
enter image description here

This is my code:

import styled from "styled-components";
import 'chartist/dist/index.css';
import { LineChart } from 'chartist';


export const ChartPage = () => {

    new LineChart(
        '#chart',
        {
            labels: [1, 2, 3, 4, 5, 6, 7, 8],
            series: [[5, 9, 7, 8, 5, 3, 5, 4]]
        },
        {
            low: 0,
            showArea: true
        }
    );
      

    return (
        <div>
            <div id="chart"></div>
        </div>
    )
}

Can someone help me use chartist in my app. I’ve tried a bunch of stuff like making sure DOM element exists but I can’t seem to get it to work.

Javascript if function only checks for one variable despite &&

I am using php, javascript and html to create a website where logged in users can comment in a chatbox. I am trying validate the input email during account creation by checking if it includes ‘@’ and ‘.’. The call to the function is within an html file. The form (wrapper and body excluded looks like this:

<form id="form" onsubmit="HandleSubmit(event)" action="accountcreation.php" method="POST">
                 
    <label for="email">Email:</label>
    <br>
    <input type="text" id="email" name="email" required>
    <br>
    <label for="password">Password:</label>
    <input type="password" name="password" required>
    <br>
    <br>
    <button type="submit">Create account</button>
            
    </form>

The function is being called below:

<script src="validate.js"></script>
<script>
    function HandleSubmit(e) {
        console.log("OnSubmit");

        // Validation
        if (!ValidateEmail("email")) {
            e.preventDefault();
            alert("Invalid input of email");
            return false;
        }

    }
</script>

In the validate.js file the function is contructed like this:

function ValidateEmail(emailinputId) {

    const elem = document.getElementById(emailinputId);
    if ( !elem.value.includes(".") && !elem.value.includes("@")) {
        return false;
    }
    
    return true;

}

The webpage only sends and alert when the ‘@’ sign is missing but is fine with ‘.’ missing.
I need to solve this within a day so I’m praying for a saviour.

I have tried with both && and || which didn’t work.
I tried separating the ‘.’ and ‘@’ checks into separate if statements within the same function which didn’t work.

I changed it to an alternate version:

function ValidateEmail(emailinputId) {

    const elem = document.getElementById(emailinputId);
    
    if ( ("." in elem ) && ("@" in elem)) {
        return true;
    }
    
    return false;

}

And called to it in the same way.

Same thing happens. What is the issue?

How to use fuzzysearch with Shiny in R?

I am trying to use this JS script (from this website: https://datatables.net/blog/2021-09-17) in a DT datatable:

var fsrco = $('#fuzzy-ranking').DataTable({
    fuzzySearch: {
        rankColumn: 3
    },
    sort: [[3, 'desc']]
});
 
fsrco.on('draw', function(){
    fsrco.order([3, 'desc']);
});

Using this script tag:

“//cdn.datatables.net/plug-ins/1.11.3/features/fuzzySearch/dataTables.fuzzySearch.js”

I want to incorporate it in a DT datable function within a Shiny app where the fuzzy search is applied using the rank order (with higher similarity on top), however, I do not want the rank column to be shown.

Something like this, but without showing the Rank column.
enter image description here

Some base regular example:

    library(shiny)
    library(DT)
    js <- c(
      "  var fsrco = $('#fuzzy-ranking').DataTable({",
      "    fuzzySearch: {",
      "        rankColumn: 3",
      "    },",
      "    sort: [[3, 'desc']]",
      "});",
      "fsrco.on('draw', function(){",
      "    fsrco.order([3, 'desc']);",
      "});"
)
    ui <- fluidPage(
      DTOutput("table")
    )
    server <- function(input, output, session){
      output[["table"]] <- renderDT({
        datatable(
          iris,
          selection = "none",
          editable = TRUE, 
          callback = JS(js),
          extensions = "KeyTable",
          options = list(
            keys = TRUE,
            url = "//cdn.datatables.net/plug-ins/1.11.3/features/fuzzySearch/dataTables.fuzzySearch.js"
          )
        )
      })
    }
    shinyApp(ui, server)

Can you explain how to make the javascript alert appear after radio button has been shown where the user clicked?

I have tried doing this, but it would display alert before showing what the user clicked for the radio button…
Should I remove the switch statement from the function?

"use strict";
window.onload = pageLoad;

function pageLoad(){
    var redButton = document.getElementById("red").onclick=colorChoice;
    var blueButton = document.getElementById("blue").onclick=colorChoice;
    var greenButton = document.getElementById("green").onclick=colorChoice;
    var yellowButton = document.getElementById("yellow").onclick=colorChoice;
    var orangeButton = document.getElementById("orange").onclick=colorChoice;
}

function colorChoice(){
    var userName = document.getElementById("nameBox").value;
    var color;
    var all_colors = document.getElementsByName("colorButton");
    for(var i = 0; i < all_colors.length; i++){
        if(all_colors[i].checked){
            color = all_colors[i].value;
        }
    }
    switch (color){
        case "red":
        alert("Hi " + userName + ", your favorite color is red");
        break;
        case "blue":
        alert("Hi " + userName + ", your favorite color is blue");
        break;
        case "green":
        alert("Hi " + userName + ", your favorite color is green");
        break;
        case "yellow":
        alert("Hi " + userName + ", your favorite color is yellow");
        break;
        case "orange":
        alert("Hi " + userName + ", your favorite color is orange");
        break;
        default:
        alert("There is an error");
        break;
    }
}

The result is this…
result

Why do the buttons on this JavaScript trivia game keep displaying an incorrect answer when the correct answer button was clicked?

I am building a trivia game using vanilla JavaScript and Bootstrap, the app gets questions from the https://opentdb.com API, displays the question and then four multiple choice answers on a separate button using Bootstrap. A simple random loop to generate numbers between 1 and 4 (without repeating) to an array is created to ensure the buttons are shuffled for the next question.

Ever since introducing the nextQuestion function to go to the next question, if I click on the correct answer, that button will not change to “Correct!” and a random “Incorrect” button will show. Before I was just refreshing the page every time to generate another question.

I have tried declaring the rand array globally and under the nextQuestion function to reset it and outputting these numbers to the console to check that are changing. I’ve noticed that more than often the last correct answer position for the previous question is where the “Incorrect” button is shown.

Please let me know if you need anymore information.

Here is the code:

Main.js

const api_url = 'https://opentdb.com/api.php?amount=1&category=9&type=multiple&encode=url3986';
let score = 0;
let buttonClicked = false; // Variable to track button click state
const delay = 2000; // Delay in milliseconds

// Get questions and answers from API
async function getQuestion() {
    try {
        // Fetch questions from the API
        const response = await fetch(api_url);
        const data = await response.json();
        const { results } = data;

        displayQuestion(results);

    } catch (error) {
        console.log(error);
    }
}

function displayQuestion(results) {
    const question = decodeURIComponent(results[0].question);
    const answer = decodeURIComponent(results[0].correct_answer);
    const incorrect1 = decodeURIComponent(results[0].incorrect_answers[0]);
    const incorrect2 = decodeURIComponent(results[0].incorrect_answers[1]);
    const incorrect3 = decodeURIComponent(results[0].incorrect_answers[2]);

    // Generate random number without duplicates to shuffle position of answer buttons
    randomArray = [];
    let n = [1, 2, 3, 4];
    i = n.length;
    j = 0;

    while (i--) {
        j = Math.floor(Math.random() * (i + 1));
        randomArray.push(n[j]);
        n.splice(j, 1);
    }

    // Display question and answers on separate buttons for user input
    document.getElementById('question').textContent = question;
    document.getElementById(`answer${randomArray[0]}`).textContent = answer;
    document.getElementById(`answer${randomArray[1]}`).textContent = incorrect1;
    document.getElementById(`answer${randomArray[2]}`).textContent = incorrect2;
    document.getElementById(`answer${randomArray[3]}`).textContent = incorrect3;

    // User input for button click
    document.getElementById(`answer${randomArray[0]}`).addEventListener("click", correctAnswer);
    document.getElementById(`answer${randomArray[1]}`).addEventListener("click", incorrectAnswer1);
    document.getElementById(`answer${randomArray[2]}`).addEventListener("click", incorrectAnswer2);
    document.getElementById(`answer${randomArray[3]}`).addEventListener("click", incorrectAnswer3);
}

function correctAnswer() {
    if (buttonClicked) return; // Prevent multiple clicks within the delay period
    buttonClicked = true; // Set button click state to true
    document.getElementById(`answer${randomArray[0]}`).innerHTML = "Correct!";
    document.getElementById(`answer${randomArray[0]}`).className = 'btn btn-success btn-sm';
    // Increment the score
    score++;
    // Update the score display
    updateScore();
    setTimeout(() => {
        nextQuestion();
        buttonClicked = false; // Reset button click state after the delay
      }, delay);
}

function incorrectAnswer1() {
    if (buttonClicked) return; // Prevent multiple clicks within the delay period
    buttonClicked = true; // Set button click state to true
    document.getElementById(`answer${randomArray[1]}`).innerHTML = "Incorrect!";
    document.getElementById(`answer${randomArray[1]}`).className = 'btn btn-danger btn-sm';
    setTimeout(() => {
        nextQuestion();
        buttonClicked = false; // Reset button click state after the delay
      }, delay);
}

function incorrectAnswer2() {
    if (buttonClicked) return; // Prevent multiple clicks within the delay period
    buttonClicked = true; // Set button click state to true
    document.getElementById(`answer${randomArray[2]}`).innerHTML = "Incorrect!";
    document.getElementById(`answer${randomArray[2]}`).className = 'btn btn-danger btn-sm';
    setTimeout(() => {
        nextQuestion();
        buttonClicked = false; // Reset button click state after the delay
      }, delay);
}

function incorrectAnswer3() {
    if (buttonClicked) return; // Prevent multiple clicks within the delay period
    buttonClicked = true; // Set button click state to true
    document.getElementById(`answer${randomArray[3]}`).innerHTML = "Incorrect!";
    document.getElementById(`answer${randomArray[3]}`).className = 'btn btn-danger btn-sm';
    setTimeout(() => {
        nextQuestion();
        buttonClicked = false; // Reset button click state after the delay
      }, delay);
}

// Function to update the score
function updateScore() {
    const scoreElement = document.getElementById('score');
    scoreElement.textContent = `Score: ${score}`;
}

function nextQuestion() {
    // Clear the previous question and answer buttons
    document.getElementById('question').textContent = '';

    // Clear answer buttons' styles and text content
    for (let i = 0; i < randomArray.length; i++) {
      const answerButton = document.getElementById(`answer${randomArray[i]}`);
      answerButton.classList.remove('btn-success', 'btn-danger');
      answerButton.classList.add('btn-primary');
      answerButton.textContent = '';
    }
    getQuestion();
  }

getQuestion();

game.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Trivia Game</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
    <link href="/css/style.css" rel="stylesheet">
</head>
<body>
    <div id="container">
    <div class="text-center font-weight-bold col-8 mx-auto">
        <span id="question"></span>
    </div>
    <div class="d-grid gap-2 col-4 mx-auto">
        <button type="button" class="btn btn-primary btn-sm p-1" id="answer1"></button>
        <button type="button" class="btn btn-primary btn-sm" id="answer2"></button>
        <button type="button" class="btn btn-primary btn-sm" id="answer3"></button>
        <button type="button" class="btn btn-primary btn-sm" id="answer4"></button>
        <div class="text-center" id="score">Score: 0</div>
    </div>
    </div>
    <script src="main.js"></script>
</body>
</html>

Can I create an Expo app without accessing device permissions while using sensors?

Expo – Is it possible to make an app without permissions?

It’s been 4 days since I started developing the app, so I don’t know much about permission. I’m developing an app for personal project purposes, so it’s better not to have permission. Is it essential using permissions when using sensors or storage of the device? I am thinking of using expo LightSensor in Android OS to compare ambient light and device’s brightness for checking whether the user is using the device in dark environment or using it with low brightness.(I’d appreciate it if you let me know if it is possible to implement this feature using expo sensors)