TypeScript, Type ‘(status: string) => { text: string; onClick: () => void; }[]’ is not assignable to type ‘{ text: string; onClick: () => void; }[]’

I am trying to understand what this TypeScript error is telling me and how to resolve it.

Type '(status: string) => { text: string; onClick: () => void; }[] | undefined' is not assignable to type '{ text: string; onClick: () => void; }[]'

I have a header component which accepts an array of objects.

I can pass the array in as follows with no issues.

        menuItems={[
          { text: 'Save', onClick: () => console.log('test1') },
          {
            text: 'Submit Referral Request',
            onClick: () => console.log('test2'),
          },
        ]}
      />

Now what I want to do is extract the array and replace it with a function call that will build an array.

  function renderActionMenuItems(status: string) {
    if (status === 'new') {
      return new Array(
        { text: 'Save', onClick: () => console.log('test1') },
        {
          text: 'Submit Referral Request',
          onClick: () => console.log('test2'),
        }
      )
    }
  }


      <ActionBar
        menuItems={renderActionMenuItems}
      />

However the above code gives me an error when running the app.
ActionBar.tsx:83 Uncaught TypeError: t2.map is not a function

and the following error in my IDE

Type '(status: string) => { text: string; onClick: () => void; }[] | undefined' is not assignable to type '{ text: string; onClick: () => void; }[]'.ts(2322)
index.d.ts(93, 5): The expected type comes from property 'menuItems' which is declared here on type 'IntrinsicAttributes & HeaderProps'

Validation For Empty Input Function Not Working

In the code presented, I thought it should only refresh or it should only alert, but it does both?

function answerQ() {
    if (document.forms['empty'].name.value === "") {
    alert("Submit Your Question");
    }
    else if (document.forms['empty'].name.value !== "") {
    window.location.reload();
    }
}

I want the code to alert the user when the input is blank when it is submitted, and refresh the page when it is not blank when submitted, but for me it just isn’t doing that.

So I then expiremented.
I tried throwing a return like this:

function answerQ() {
    if (document.forms['empty'].name.value === "") {
    alert("Submit Your Question");
        return;
    }
    else if (document.forms['empty'].name.value !== "") {
    window.location.reload();
    }
}

but that also didnt work, then I tried this:

function answerQ() {
    if (document.forms['empty'].name.value === "") {
    alert("Submit Your Question");
        throw;
    }
    else if (document.forms['empty'].name.value !== "") {
    window.location.reload();
    }
}

but that also didn’t work, so I don’t know what to do.
And that is why I am here

Why bootstrap js not loaded in my laravel’s vite config?

In my laravel 10 vite.config.js I try to load the bootstrap js:

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import inject from "@rollup/plugin-inject";

import { readdirSync,lstatSync } from 'fs';
import { resolve } from 'path';


function getFilesFromDir(dir, fileTypes) {
    const filesToReturn = [];

    function walkDir(currentPath) {

        if(lstatSync(currentPath).isFile()){
            filesToReturn.push(currentPath);
            return;
        }

        const files = readdirSync(currentPath);
        for (let i in files) {
            console.log(files[i]);
            const curFile = resolve(currentPath, files[i]);
            if(lstatSync(curFile).isDirectory()){
                walkDir(curFile);
                continue;
            }
            const file = resolve(dir, files[i]);
            filesToReturn.push(file);
        }
    }

    walkDir(resolve(__dirname, dir));
    return filesToReturn;
}


// Get all .css and .scss files in the directory
const pageStyles = getFilesFromDir('./resources/css', ['css', 'scss']);
const js = getFilesFromDir('./resources/js',['js']);

const paths = [

    ...pageStyles,
    ...js,

    'node_modules/jquery/dist/jquery.js',
    'node_modules/bootstrap/dist/css/bootstrap.css',
    'node_modules/bootstrap/dist/js/bootstrap.bundle.js',
    'node_modules/@fortawesome/fontawesome-free/css/all.css'
]

console.log(paths);

export default defineConfig({
    plugins: [
        laravel({
            input:paths,
            refresh: true,
        }),
        inject({
            $: 'jquery',
            jQuery: 'jquery',
            'common_functions':'resources/js/common_functions.js',
        }),
    ],
    build: {
        rollupOptions: {
            external: [
                "js/modules/*",
            ]
        }
    }
});

And I have installed bootstrap in my package.json:

{
    "private": true,
    "scripts": {
        "dev": "vite",
        "build": "vite build",
        "build_dev": "vite build --watch"
    },
    "devDependencies": {
        "@rollup/plugin-inject": "^5.0.5",
        "axios": "^1.1.2",
        "laravel-vite-plugin": "^0.7.2",
        "vite": "^4.0.0"
    },
    "dependencies": {
        "@fortawesome/fontawesome-free": "^6.5.1",
        "bootstrap": "^5.3.2",
        "emodal": "^1.2.69",
        "jquery": "^3.7.1",
        "nodejs": "^0.0.0",
        "scss": "^0.2.4"
    }
}

But Once I do:

    @vite(['node_modules/bootstrap/dist/js/bootstrap.bundle.js'])

I get the error:

Unable to locate file in Vite manifest: node_modules/bootstrap/dist/js/bootstrap.bundle.js.

Despite that file does exist and be in vite.config.js:

$ ls -l  node_modules/bootstrap/dist/js/bootstrap.bundle.js
-rw-r--r-- 1 www-data www-data 207731 Jan  5 08:30 node_modules/bootstrap/dist/js/bootstrap.bundle.js

l$ grep "node_modules/bootstrap/dist/js/bootstrap.bundle.js" vite.config.js
    'node_modules/bootstrap/dist/js/bootstrap.bundle.js',

May I have some help?

The server is not updating JS and SCSS files on the domain, but PHP files are being updated

I’m facing an issue where I’ve updated my code files on the server. The PHP files and SQL database reflect the changes, but the JavaScript (JS) and SCSS files seem to persist with the old versions. I’ve checked the Apache log, and there are no reported errors. The server team mentioned that updates should occur automatically, and no additional steps are required.

I’ve tried clearing the local storage cache in multiple browsers, and I also identified something resembling local storage on the server side, which I cleared. Despite these efforts, the client-side version of the website still shows the old JS and SCSS files.

Any insights or suggestions on resolving this issue would be greatly appreciated.

Thank you!

get current cursor position in TinyMCE Oracle Apex 23.1

I need to have current cursor position in TinyMCE Oracle Apex.
I use this js code for another type of page items and it work correctly.

“var curPos = document.getElementById(“P7_TEXT”).selectionStart; “

but when “P7_TEXT” is a Rich Text Editor (TinyMCE) , **return “undefined” **
what can I do?

get current cursor position in TinyMCE Oracle Apex 23.1

Blank page on vercel deploy [Larvel vue vite]

I deployed to vercel my laravel vue vite app, but its just a blank page

This is the code that i have in app.blade.php

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
    @inertiaHead

    <link rel="icon" type="image/x-icon" href="https://www.pup.edu.ph/about/images/PUPLogo.png">

    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.4/css/all.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.css" />
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-4bw+/aepP/YC94hEpVNVgiZdgIC5+VKNBQNGCHeKRQN+PtmoHDEXuppvnDJzQIu9" crossorigin="anonymous">
  </head>
  <body>
    @inertia

    <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-I7E8VVD/ismYTF4hNIPjVp/Zjvgyol6VFvRkX/vR+Vc4jQkC+hVqc2pM8ODewa9r" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-Rx+T1VzGupg4BHQYs2gCW9It+akI2MM/mndMCy36UVfodzcJcF0GGLxZIzObiEfa" crossorigin="anonymous"></script>
  </body>
</html>

vite.config.js file

    import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import vue from '@vitejs/plugin-vue'

export default defineConfig({
    plugins: [
        vue(),
        laravel({
            input: [
                'resources/css/app.css', 
                'resources/js/app.js'],
            refresh: true,
        }),
    ],
    build: {
        manifest: true,
        outDir: 'build',
    },
    base: './',
});

Im really wondering what is the problem, build was successful but its just plain blank white page and sometimes its manifest error

menu option install app missing for vue3 pwa

I setup a Vue 3 project with command npm create vue@latest. Then to add PWA I installed vite-plugin-pwa, updated vite.config.js and made some changes to other files, see below.

Now I get error about manifest.json, which is an empty file:
image

The icons in the icons array in vite.config.js are correctly cached as far as I can see.

Now:

  1. Menu item to install the app on the mobile device doesn’t work (now only possible to add to startscreen (browser icon instead of app icon). How can I fix that?
  2. Under ‘Service workers’ I can see that serviceworker sw.js is started, but the message in sw.js is not displayed in the console. Is there something I must do to make that message in sw.js appear?

image

vite.config.js:

import { fileURLToPath, URL } from 'node:url'
import { VitePWA } from 'vite-plugin-pwa';
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    VitePWA({
      registerType: 'auto',
      includeAssets: ['favicon.ico', 'robots.txt', 'apple-touch-icon.png'],
      manifest: {
        name: 'WKB PWA',
        short_name: 'WKB P',
        theme_color: '#01bd7e',
        start_url: '/',
        display: 'standalone',
        background_color: "#fff",
        icons: [
          {
            "src": "/img/icons/maskable_icon.png",
            "sizes": "1024x1024",
            "type": "image/png",
            "purpose": "maskable"
          },
          {
            "src": "/img/icons/maskable_icon_x512.png",
            "sizes": "512x512",
            "type": "image/png",
            "purpose": "maskable"
          },
          {
            "src": "/img/icons/maskable_icon_x192.png",
            "sizes": "192x192",
            "type": "image/png",
            "purpose": "maskable"
          },
          {
            "src": "/img/icons/windows11/SmallTile.scale-100.png",
            "sizes": "71x71"
          },
         
          {
            "src": "/img/icons/windows11/Square44x44Logo.altform-lightunplated_targetsize-80.png",
            "sizes": "80x80"
          },
          {
            "src": "/img/icons/windows11/Square44x44Logo.altform-lightunplated_targetsize-96.png",
            "sizes": "96x96"
          },
          {
            "src": "/img/icons/windows11/Square44x44Logo.altform-lightunplated_targetsize-256.png",
            "sizes": "256x256"
          },
          {
            "src": "/img/icons/android/android-launchericon-512-512.png",
            "sizes": "512x512"
          },
          {
            "src": "/img/icons/android/android-launchericon-192-192.png",
            "sizes": "192x192"
          },
          {
            "src": "/img/icons/android/android-launchericon-144-144.png",
            "sizes": "144x144"
          },
etc 
        ],
      },
    }),          


  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  },
  build: {
    manifest: true,
  }
})

main.js look like this:

import './assets/main.css'

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import './registerServiceWorker'

// main.js

const app = createApp(App)

app.use(router)

app.mount('#app')

No registerServiceWorker.js file since as I understand it Vite should take care of that.

Package.json:

{
  "name": "wkb-app",
  "version": "1.0.6",
  "type": "module",
  "private": true,
  "author": "",
  "scripts": {
    "build": "vite build",
    "test:unit": "vitest",
    "test:e2e": "start-server-and-test preview http://localhost:4173 'cypress run --e2e'",
    "dev": "vite",
    "preview": "vite preview",
    "test:e2e:dev": "start-server-and-test 'vite dev --port 4173' http://localhost:4173 'cypress open --e2e'"
  },
  "dependencies": {
    "express": "^4.18.2",
    "register-service-worker": "^1.7.2",
    "vue": "^3.4.15",
    "vue-router": "^4.2.5"
  },
  "devDependencies": {
    "@vitejs/plugin-vue": "^4.6.2",
    "@vue/test-utils": "^2.4.3",
    "cypress": "^13.6.3",
    "jsdom": "^23.0.1",
    "start-server-and-test": "^2.0.3",
    "vite": "^5.0.10",
    "vite-plugin-pwa": "^0.17.4",
    "vitest": "^1.0.4"
  }
}

service-worker.js , for now:

console.log("Message from SW")

Don’t know what to do to fix this.

I am not able to play an audio file (which is supposed to play after clicking a button) in React Native

This is a part of my React Native code:-

import React, { useState, useEffect } from 'react';
import { View, Image, StyleSheet, Animated, Easing, TouchableOpacity, Text, ScrollView, ImageBackground, Dimensions } from 'react-native';
import Sound from 'react-native-sound';

const {height, width} = Dimensions.get('window');

const styles = StyleSheet.create({
  //styles
});

const DisplayLogo = () => {
  const [showSeparatePage, setShowSeparatePage] = useState(false);
  const [showWeatherPage, setShowWeatherPage] = useState(false);
  const [showBuyImplementsPage, setShowBuyImplementsPage] = useState(false);
  const [showSellHarvestPage, setShowSellHarvestPage] = useState(false);
  const [showAudioPodcastsPage, setShowAudioPodcastsPage] = useState(false);
  const [showBackButton, setShowBackButton] = useState(false);
  const translateY = new Animated.Value(700);
  const logoOpacity = new Animated.Value(1);
  const buttonOpacity = new Animated.Value(0);
  const backgroundColor = new Animated.Value(0);
  const rowData = [
    { sn: '1', step: 'Ploughing', implement: 'Wooden or iron ploughs' },
    { sn: '2', step: 'Levelling', implement: 'Wooden or iron levellers' },
    { sn: '3', step: 'Manuring', implement: 'Manually or with drills' },
    { sn: '4', step: 'Sowing', implement: 'Ploughs, hand sowing, seed drills' },
    { sn: '5', step: 'Irrigation', implement: 'Tubewells, sprinklers' },
    { sn: '6', step: 'Weeding', implement: 'Trowel (khurpa)' },
    { sn: '7', step: 'Crop protection', implement: 'Sprayers' },
    { sn: '8', step: 'Harvesting', implement: 'Sickle, harvesting machine' },
    { sn: '9', step: 'Threshing', implement: 'Animals, threshers, combines' },
    { sn: '10', step: 'Crop storage', implement: 'Jute bags, wooden, clay or metal containers' },
  ];

  useEffect(() => {
    const logoAnimation = Animated.sequence([
      Animated.timing(translateY, {
        toValue: 250,
        duration: 1000,
        useNativeDriver: true,
        easing: Easing.inOut(Easing.ease),
      }),
      Animated.delay(2000),
      Animated.parallel([
        Animated.timing(translateY, {
          toValue: -50,
          duration: 1000,
          useNativeDriver: true,
          easing: Easing.inOut(Easing.ease),
        }),
        Animated.timing(logoOpacity, {
          toValue: 0,
          duration: 1000,
          useNativeDriver: true,
        }),
      ]),
    ]);

    const podcast1 = new Sound('./assets/Podcast 1.mp3', Sound.MAIN_BUNDLE, (error) => {
      if (error) {
        console.log('Failed to load the podcast', error);
        return;
      }
      // loaded successfully
      console.log('Duration in seconds: ' + podcast1.getDuration() +
          'number of channels: ' + podcast1.getNumberOfChannels());
    });
  
    // Remember to release the resource when it's not needed
    return () => podcast1.release();
  }, []);

    const buttonsAnimation = Animated.timing(buttonOpacity, {
      toValue: 1,
      duration: 500,
      delay: 500,
      useNativeDriver: true,
    });

    Animated.sequence([logoAnimation, buttonsAnimation]).start();

    setTimeout(() => {
      Animated.timing(backgroundColor, {
        toValue: 1,
        duration: 500,
        useNativeDriver: false,
      }).start();
    }, 3000);

    return () => {
      translateY.setValue(500);
      logoOpacity.setValue(1);
      buttonOpacity.setValue(0);
      backgroundColor.setValue(0);
    };
  }, [showSeparatePage, showWeatherPage, showBuyImplementsPage, showSellHarvestPage, showAudioPodcastsPage]);

  const handleTipsForFarmingPress = () => {
    setShowSeparatePage(true);
    setShowBackButton(true);
    Animated.timing(buttonOpacity, {
      toValue: 0,
      duration: 500,
      useNativeDriver: true,
    }).start();
    Animated.timing(backgroundColor, {
      toValue: 2,
      duration: 500,
      useNativeDriver: false,
    }).start();
  };
  const handleWeatherReportPress = () => {
    setShowWeatherPage(true);
    setShowBackButton(true);
    Animated.timing(buttonOpacity, {
      toValue: 0,
      duration: 500,
      useNativeDriver: true,
    }).start();
    Animated.timing(backgroundColor, {
      toValue: 2,
      duration: 500,
      useNativeDriver: false,
    }).start();
  };
  const handleBuyImplementsPress = () => {
    setShowBuyImplementsPage(true);
    setShowBackButton(true);
    Animated.timing(buttonOpacity, {
      toValue: 0,
      duration: 500,
      useNativeDriver: true,
    }).start();
    Animated.timing(backgroundColor, {
      toValue: 2,
      duration: 500,
      useNativeDriver: false,
    }).start();
  };
  const handleSellHarvestPress = () => {
    setShowSellHarvestPage(true);
    setShowBackButton(true);
    Animated.timing(buttonOpacity, {
      toValue: 0,
      duration: 500,
      useNativeDriver: true,
    }).start();
    Animated.timing(backgroundColor, {
      toValue: 2,
      duration: 500,
      useNativeDriver: false,
    }).start();
  };
  const handleAudioPodcastsPress = () => {
    setShowAudioPodcastsPage(true);
    setShowBackButton(true);
    Animated.timing(buttonOpacity, {
      toValue: 0,
      duration: 500,
      useNativeDriver: true,
    }).start();
    Animated.timing(backgroundColor, {
      toValue: 2,
      duration: 500,
      useNativeDriver: false,
    }).start();
  };
  const handleBackButtonPress = () => {
    setShowSeparatePage(false);
    setShowWeatherPage(false);
    setShowBuyImplementsPage(false);
    setShowSellHarvestPage(false);
    setShowAudioPodcastsPage(false);
    setShowBackButton(false);
    Animated.timing(buttonOpacity, {
      toValue: 1,
      duration: 500,
      useNativeDriver: true,
    }).start();
    Animated.timing(backgroundColor, {
      toValue: 1,
      duration: 500,
      useNativeDriver: false,
    }).start();
  };

  if (showSeparatePage) {
    return (
      <ScrollView contentContainerStyle={{ flexGrow: 1 }}>
        <View style={{ ...styles.separatePageContainer }}>
          <Text style={styles.separatePageText}>
            Farming or agriculture is very important for survival, and some proper techniques have to be used. The following are the basic steps for farming.
          </Text>

          {/* Table */}
          <View style={styles.table}>
            <Text style={{ ...styles.tableHeader }}>S. No.</Text>
            <Text style={{ ...styles.tableHeader }}>Steps</Text>
            <Text style={{ ...styles.tableHeader }}>Implements</Text>
          </View>

          {/* Rows */}
          {rowData.map((row, index) => (
            <View key={index} style={styles.tableRow}>
              <Text style={{ ...styles.tableCell }}>{row.sn}</Text>
              <Text style={{ ...styles.tableCell }}>{row.step}</Text>
              <Text style={{ ...styles.tableCell }}>{row.implement}</Text>
            </View>
          ))}

          <Text style={styles.Heading}>
            Ploughing
          </Text>
          <Text style={styles.separatePageText}>
            The process of loosening and turning the soil is called tilling or ploughing. It helps in adding air to the soil, allowing the roots to penetrate deeper, bringing nutrient-rich soil to the top, helping in the growth of earthworms, etc.
          </Text>
          <Text style={styles.separatePageText}>
            The implements used for ploughing are plough, hoe, and cultivator.
          </Text>
          <Image source={require('./assets/Plough.jpg')} style={styles.Image}></Image>
          <Image source={require('./assets/Hoe.jpg')} style={styles.Image}></Image>
          <Image source={require('./assets/Cultivator.png')} style={styles.Image}></Image>
          <Text style={styles.separatePageText}>
            Generally, cultivator is the best one to use in order to save time and labour. It can break up soil, remove seeds, and penetrate large depths in order to sufficiently break up the soil for soil-bed preparation.
          </Text>
          <Text style={styles.Heading}>
            Levelling
          </Text>
          <Text style={styles.separatePageText}>
            The soil has to be levelled after ploughing. It helps in uniform distribution of water in the field during irrigation and reduces irrigation time, prevents the loss of moisture from ploughed soil, and increases yield and quality.
          </Text>
          <Text style={styles.Heading}>
            Manuring
          </Text>
          <Text style={styles.separatePageText}>
            The process of applying organic minerals and adding nutrients to the soil is called manuring. This is done for proper mixing of manure with soil to increase soil fertility before seeds are sown in the field.
          </Text>
          <Text style={styles.Heading}>Sowing</Text>
          <Text style={styles.separatePageText}>
            Once the soil is prepared, seeds are sown in it. While sowing seeds the following points need to be kept in mind.
          </Text>
          <Text style={styles.separatePageText}>
          Seeds should be of good quality, healthy and free from diseases.
          </Text>
          <Text style={styles.separatePageText}>
          They must be planted at the proper depth in the soil. If planted too deep in the soil, they cannot respire and their shoots may not be able to push through the soil. If planted on the surface, they will be eaten by birds.
          </Text>
          <Text style={styles.separatePageText}>
          Seeds require water for germination. The soil should, therefore, have water in it. However, if there is too much water, seeds will not germinate properly.
          </Text>
          <Text style={styles.separatePageText}>
          Seeds should be sown at proper distances. If they are too close, they will compete and hence will not get enough water, sunlight and nutrients for their normal growth and development. If they are too far apart, there is wastage of field space.
          </Text>
          <Text style={styles.separatePageText}>
          A seed drill should be used for sowing seeds as it sows seeds at equal distances and at proper depths.
          </Text>
          <Image source={require('./assets/Seed_Drill.jpg')} style={styles.Image}></Image>
          <Text style={styles.Heading}>
            Irrigation
          </Text>
          <Text style={styles.separatePageText}>
          Irrigation means supplying water to crops in the field. It provides water to the plants for their various physiological activities like photosynthesis, transpiration, ascent of sap, etc. Water helps in the absorption of minerals from the soil. Water is essential for germination of seeds and elongation of roots. Water protects crops from frost or from dry hot air currents. Moreover, farmers should not depend on rainfalls for their crops and instead have their own irrigation system.
          </Text>
          <Text style={styles.separatePageText}>
          The modern ways of irrigation are pumps, canals, sprinkler system and drip irrigation.
          </Text>
          <Image source={require('./assets/Pump.jpg')} style={styles.Image}></Image>
          <Image source={require('./assets/Canal.jpg')} style={styles.Image}></Image>
          <Image source={require('./assets/Sprinkler_System.jpg')} style={styles.Image}></Image>
          <Image source={require('./assets/Drip_Irrigation.jpg')} style={styles.Image}></Image>
          <Text style={styles.Heading}>
            Weeding
          </Text>
          <Text style={styles.separatePageText}>
          Weeds are unwanted plants that grow along with the main crops. They compete with the main crops for water, minerals and sunlight and, therefore, reduce crop yield.
          </Text>
          <Text style={styles.separatePageText}>
          The best time to remove weeds is when the soil is damp and moist as damp soils are loose and make it easier to remove weeds with their roots. Weeding can be done in the following ways.
          </Text>
          <Text style={styles.SubHeading}>
            Mechanical Methods
          </Text>
          <Text style={styles.separatePageText}>
            Weeds are removed manually by pulling them out with hands or by using a khurpa (trowel), hoe or a rake. In small fields, hand pulling or by means of a khurpa or hoe is the appropriate method. But in large fields, mechanical weeding is done by methods like ploughing, harrowing, intercultivation, flooding or burning. This method is time consuming and involves a lot of labour.
          </Text>
          <Image source={require('./assets/Weeding1.jpg')} style={styles.Image}></Image>
          <Text style={styles.SubHeading}>
            Chemical Methods
          </Text>
          <Text style={styles.separatePageText}>
            Weeding is also done by spraying special chemicals called herbicides or weedicides, with the help of a sprayer. Some common weedicides are dalapon, metachlor, siniazine, 2, 4-D (2, 4-dichlorophenoxy acetic acid), MCPA (2-methyl-4-chloro-1-phenoxy acetic acid) and Butachlor.
          </Text>
          <Text style={styles.separatePageText}>
            However, weedicides are poisonous and the grains must be properly washed before being consumed. Since weedicides are poisonous, spraying may affect the health of farmers. Therefore, farmers should be careful while using weedicides. It is advised that the farmer should cover his mouth and nose with cloth while spraying.
          </Text>
          <Image source={require('./assets/Weeding2.jpg')} style={styles.Image}></Image>
          <Text style={styles.SubHeading}>
            Biological Methods
          </Text>
          <Text style={styles.separatePageText}>
            Research for evolving safer methods to kill weeds is going on. For example, insects that attack only specific weeds have been used to control those weeds. However, it is necessary to check the reproduction of these insects. For example, cochineal insect in Tamil Nadu is used to eliminate prickly pear (Opuntia) from the crop fields. Experiments have been conducted to attract and trap the male population of the insects, in order to check their reproduction.
          </Text>
          <Image source={require('./assets/Weeding3.jpg')} style={styles.Image}></Image>
          <Image source={require('./assets/Weeding4.jpg')} style={styles.Image}></Image>
          <Text style={styles.Heading}>
            Crop Protection
          </Text>
          <Text style={styles.separatePageText}>
            Crops can be protected from stray animals like cows and buffaloes by putting wire fence all around the field. Birds can be scared away from fields by placing scarecrows or by beating drums.
          </Text>
          <Text style={styles.separatePageText}>
            Pests can be controlled by pesticides which are poisonous chemicals. Pesticides kill pests as well as their eggs and larvae but do not affect the plant.
          </Text>
          <Image source={require('./assets/Scarecrow.jpg')} style={styles.Image}></Image>
          <Text style={styles.Heading}>
            Harvesting
          </Text>
          <Text style={styles.separatePageText}>
            Once the crop matures it is harvested, i.e., cut and gathered. This may be done manually by using a sickle, or by using a machine called a harvester.
          </Text>
          <Image source={require('./assets/Harvester.jpg')} style={styles.Image}></Image>
          <Text style={styles.separatePageText}>
            Next, the grain is separated from the cut or harvested crop through threshing. It can be done manually or by using a thresher. A combine is used for both harvesting and threshing.
          </Text>
          <Image source={require('./assets/Threshing.jpg')} style={styles.Image}></Image>
          <Text style={styles.separatePageText}>
            After threshing, the grain is separated from the chaff by winnowing.
          </Text>
          <Image source={require('./assets/Winnowing.jpg')} style={styles.Image}></Image>
          <Text style={styles.Heading}>
            Crop Storage
          </Text>
          <Text style={styles.separatePageText}>
            Crops are stored after harvesting. Generally, a buffer stock is maintained to compensate if the monsoons fail anytime.
          </Text>
          <Text style={styles.SubHeading}>
            Gunny Bags
          </Text>
          <Text style={styles.separatePageText}>
            Gunny bags are jute bags. They are filled with food grains and are stacked in large godowns on wooden platforms. They are stored at about 10-15 cm above the ground and above 70 cm away from the wall. The godowns are made free of microbes, insects and rodents by spraying pesticides and insecticides.
          </Text>
          <Image source={require('./assets/Gunny_Bag.jpg')} style={styles.Image}></Image>
          <Text style={styles.SubHeading}>
            Silos And Granaries
          </Text>
          <Text style={styles.separatePageText}>
            Silos are tall cylindrical containers used for bulk storage of grains. These are used specially by government agencies like Food Corporation of India (FCI). Grain silos facilitate easy inspection, fumigation, protection from pests and temperature control. Granaries are large buildings where grains are stored inside gunny bags, etc.
          </Text>
          <Image source={require('./assets/Silos.jpg')} style={styles.Image}></Image>
          <Image source={require('./assets/Granary.jpg')} style={styles.Image}></Image>
          {showBackButton && (
            <TouchableOpacity
              style={{ ...styles.button, ...styles.backButton, marginTop: 60 }}
              onPress={handleBackButtonPress}
            >
              <Text style={styles.buttonText}>Back</Text>
            </TouchableOpacity>
          )}
        </View>
      </ScrollView>
    );
  }
  if (showWeatherPage) {
    return (
      <ScrollView contentContainerStyle={{ flexGrow: 1 }}>
        <View style={{ ...styles.weatherReportPageContainer }}>
        <Image source={require('./assets/Weather_Report.png')} style={styles.Image}></Image>
        <Text style={{ ...styles.Heading, color: 'cyan' }}>
            Hyderabad Weather
          </Text>
          <Text style={styles.Date}>
            10 February 2024
          </Text>
          <Image source={require('./assets/SunnyCloudy.png')} style={styles.Weather}></Image>
          <Text style={styles.Date}>
            11 February 2024
          </Text>
          <Image source={require('./assets/Sunny.png')} style={styles.Weather}></Image>
          <Text style={styles.Date}>
            12 February 2024
          </Text>
          <Image source={require('./assets/SunnyCloudy.png')} style={styles.Weather}></Image>
          <Text style={styles.Date}>
            13 February 2024
          </Text>
          <Image source={require('./assets/Sunny.png')} style={styles.Weather}></Image>
          <Text style={styles.Date}>
            14 February 2024
          </Text>
          <Image source={require('./assets/Sunny.png')} style={styles.Weather}></Image>
          <Text style={styles.Date}>
            15 February 2024
          </Text>
          <Image source={require('./assets/Sunny.png')} style={styles.Weather}></Image>
          <Text style={styles.Date}>
            16 February 2024
          </Text>
          <Image source={require('./assets/SunnyCloudy.png')} style={styles.Weather}></Image>
          <Text style={styles.Date}>
            17 February 2024
          </Text>
          <Image source={require('./assets/SunnyCloudy.png')} style={styles.Weather}></Image>
          <Text style={styles.Date}>
            18 February 2024
          </Text>
          <Image source={require('./assets/SunnyCloudy.png')} style={styles.Weather}></Image>
          <Text style={styles.Date}>
            19 February 2024
          </Text>
          <Image source={require('./assets/Sunny.png')} style={styles.Weather}></Image>
          <Text style={styles.Date}>
            20 February 2024
          </Text>
          <Image source={require('./assets/SunnyCloudy.png')} style={styles.Weather}></Image>
          <Text style={styles.Date}>
            21 February 2024
          </Text>
          <Image source={require('./assets/SunnyCloudy.png')} style={styles.Weather}></Image>
          <Text style={styles.Date}>
            22 February 2024
          </Text>
          <Image source={require('./assets/Sunny.png')} style={styles.Weather}></Image><Text style={styles.Date}>
            23 February 2024
          </Text>
          <Image source={require('./assets/Sunny.png')} style={styles.Weather}></Image>
          <Text style={styles.Date}>
            24 February 2024
          </Text>
          <Image source={require('./assets/SunnyCloudy.png')} style={styles.Weather}></Image>
          <Text style={styles.Date}>
            25 February 2024
          </Text>
          <Image source={require('./assets/Sunny.png')} style={styles.Weather}></Image>
          <Text style={styles.Date}>
            26 February 2024
          </Text>
          <Image source={require('./assets/Sunny.png')} style={styles.Weather}></Image>
          <Text style={styles.Date}>
            27 February 2024
          </Text>
          <Image source={require('./assets/Sunny.png')} style={styles.Weather}></Image>
          <Text style={styles.Date}>
            28 February 2024
          </Text>
          <Image source={require('./assets/Sunny.png')} style={styles.Weather}></Image>
          <Text style={styles.Date}>
            29 February 2024
          </Text>
          <Image source={require('./assets/Rainy.png')} style={styles.Weather}></Image>
          {showBackButton && (
            <TouchableOpacity
              style={{ ...styles.button, ...styles.backButton, marginTop: 60 }}
              onPress={handleBackButtonPress}
            >
              <Text style={styles.buttonText}>Back</Text>
            </TouchableOpacity>
          )}
        </View>
      </ScrollView>
    );
  }
  if (showBuyImplementsPage) {
    return (
        <View style={{ ...styles.buyImplementsPageContainer}}>
        <Image source={require('./assets/Shop_Image.png')} style={styles.Shop}></Image>
          {showBackButton && (
            <TouchableOpacity
              style={{ ...styles.button, ...styles.backButton, marginTop: 60 }}
              onPress={handleBackButtonPress}
            >
              <Text style={styles.buttonText}>Back</Text>
            </TouchableOpacity>
          )}
        </View>
    );
  }
  if (showSellHarvestPage) {
    return (
        <View style={{ ...styles.sellHarvestPageContainer}}>
        <ImageBackground source={require('./assets/Sell_Harvest.jpg')} style={styles.SellHarvestImage} resizeMode="stretch">
        <Text></Text><Text></Text><Text></Text><Text></Text><Text></Text><Text></Text><Text></Text><Text></Text><Text></Text><Text></Text><Text></Text><Text></Text><Text></Text><Text></Text><Text></Text><Text></Text><Text></Text><Text></Text><Text></Text><Text></Text><Text></Text><Text></Text><Text></Text><Text></Text><Text></Text><Text></Text><Text></Text><Text></Text><Text></Text><Text></Text><Text></Text><Text></Text><Text></Text><Text></Text><Text></Text><Text></Text>
          {showBackButton && (
            <TouchableOpacity
              style={{ ...styles.button, ...styles.backButton, marginTop: 60 }}
              onPress={handleBackButtonPress}
            >
              <Text style={styles.buttonText}>Back</Text>
            </TouchableOpacity>
          )}
          </ImageBackground>
        </View>
    );
  }
  if (showAudioPodcastsPage) {
    return (
        <View style={{ ...styles.audioPodcastsPageContainer}}>
          <Text style={styles.Heading}>
            Podcast 1: Basic Farming
          </Text>
          <Image source={require('./assets/Audio.png')} style={styles.Audio}></Image>
          <Text style={styles.Heading}>
            Podcast 2: Farming Implements
          </Text>
          <Image source={require('./assets/Audio.png')} style={styles.Audio}></Image>
          <Text style={styles.Heading}>
            Podcast 3: Crop Storage
          </Text>
          <Image source={require('./assets/Audio.png')} style={styles.Audio}></Image>
          {showBackButton && (
            <TouchableOpacity
              style={{ ...styles.button, ...styles.backButton, marginTop: 60 }}
              onPress={handleBackButtonPress}
            >
              <Text style={styles.buttonText}>Back</Text>
            </TouchableOpacity>
          )}
        </View>
    );
  }

  return (
    <ScrollView contentContainerStyle={{ flexGrow: 1 }}>
      <Animated.View style={{ ...styles.container, backgroundColor: backgroundColor.interpolate({
        inputRange: [0, 1, 2],
        outputRange: ['white', 'skyblue', 'orange'],
      }) }}>
        <Animated.Image
          style={{
            ...styles.logo,
            transform: [{ translateY }],
            opacity: logoOpacity,
          }}
          source={require('./assets/Logo.png')}
        />

        <Animated.View style={{ ...styles.buttonContainer, opacity: buttonOpacity }}>
          {/* Yellow buttons */}
          {['Tips For Farming', 'Weather Updates', 'Buy Implements', 'Sell Harvest', 'Audio Podcasts', 'Donate'].map(
            (buttonName, index) => (
              <TouchableOpacity
                key={index}
                style={{ ...styles.button, ...styles.yellowButton }}
                onPress={() => {
                  if (buttonName==='Tips For Farming') {
                    handleTipsForFarmingPress()}
                  if (buttonName==='Weather Updates') {
                    handleWeatherReportPress()}
                  if (buttonName==='Buy Implements') {
                    handleBuyImplementsPress()}
                  if (buttonName==='Sell Harvest') {
                    handleSellHarvestPress()}
                  if (buttonName==='Audio Podcasts') {
                    handleAudioPodcastsPress()}
                  }
                }
              >
                <Text style={styles.buttonText}>{buttonName}</Text>
              </TouchableOpacity>
            )
          )}

          {/* Gray buttons */}
          <View style={{ flexDirection: 'row' }}>
            {['Help', 'Settings'].map((buttonName, index) => (
              <TouchableOpacity
                key={index}
                style={{ ...styles.button, ...styles.grayButton, marginLeft: 10 }}
                onPress={() => console.log(`Button pressed: ${buttonName}`)}
              >
                <Text style={styles.buttonText}>{buttonName}</Text>
              </TouchableOpacity>
            ))}
          </View>

          {/* Orange button */}
          <TouchableOpacity
            style={{ ...styles.button, ...styles.orangeButton }}
            onPress={() => console.log(`Button pressed: Return Feedback`)}
          >
            <Text style={styles.buttonText}>Return Feedback</Text>
          </TouchableOpacity>

          {/* Green button */}
          <TouchableOpacity
            style={{ ...styles.button, ...styles.greenButton }}
            onPress={() => console.log(`Button pressed: Contact`)}
          >
            <Text style={styles.buttonText}>Contact</Text>
          </TouchableOpacity>
        </Animated.View>
      </Animated.View>
    </ScrollView>
  );
};

export default DisplayLogo;


My first audio file is ‘.assets/Podcast 1.mp3’. I want it to play when the play button is clicked in the Podcasts page. The podcasts page is accessible by clicking the Audio Podcasts button in the main page.

I have not been able to get help from ChatGPT. What I want is as follows.

  1. Click on the Audio Podcasts button.
  2. Click on the play button for the first podcast.
  3. Play the audio file ‘./assets/Podcast 1.mp3’.

Please help.

How to restrict URLs/links to be access directly from the browser

Unprivileged Access of Privilege URLs (i.e. URLs/links accessible only after login) is possible. If hacker simply
knows the URL she/he can enter the URL manually in the browser and hit enter, after which the content or data of
that URL is accessible to any user without any validation or authorization.

User role should be bound to the URL is being accessed and each time Request is made to access ths URL
presence of session should be validated. This should be done on server side by intercepting the GET or POST
request and validating if the target URL is allowed to be accessed by the role of logged in user.

How to find the x axis value based on mouse position in svg produced with d3?

As an exercise I am tryint to replicate this visualization. I have almost everything figured out now but I am stuck on the vertical line with tooltip based on the mouse position.

I have tried to use the xScale to find out the year but it doesn’t provide the correct value and I don’t know why. The result is different for different time ranges (as chosen by the slider), it is not consistently erroneous by some amount. I know that once I’ve got the correct year based on the mouse position I’ll be able to sort everything else out. Here is my code:

import {LinearAxisLeft} from "../../shared/LinearAxisLeft";
import {AxisBottom} from "../../shared/AxisBottom";
import {useState} from "react";
import * as d3 from "d3";
import {CircleMarks} from "../../shared/CircleMarks";

export const MultilineChart = ({
                                   data,
                                   xScale,
                                   xValue,
                                   yScale,
                                   yValue,
                                   innerWidth,
                                   innerHeight,
                                   xTickFormat,
                                   yTickFormat,
                                   colorScale,
                                   colorValue,
                                   marksRadius,
                                   fadeOpacity,
                                   hoveredValue
                               }) => {

    const [hovered, setHovered] = useState(false);
    const colors = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf"]

    const disorders = new Set(data.map(d => d.disorder));

    const data_by_disorder = [...disorders].map(d => {
        return data.filter(x => x.disorder === d);
    });

    const line = d3.line()
        .x(d => xScale(new Date(d.year, 0)))
        .y(d => yScale(d.cases));

    const handleMouseMove = (e) => {
        if (hovered) {
            let x = e.clientX;
            let year = xScale.invert(x).getFullYear()
            console.log(year)
        }
    }

    const filteredData = data_by_disorder.flat().filter(d=> (d.disorder === hoveredValue))


    return (
        <>
            <rect width={innerWidth} height={innerHeight} fill="white" opacity={0} onMouseOver={(e) => setHovered(true)}
                  onMouseMove={(e) => handleMouseMove(e)}
                  onMouseLeave={() => setHovered(false)}/>
            <LinearAxisLeft
                yScale={yScale}
                innerWidth={innerWidth}
                tickFormat={yTickFormat}
            />
            <AxisBottom
                xScale={xScale}
                innerHeight={innerHeight}
                tickFormat={xTickFormat}
            />
            <g opacity={hoveredValue ? fadeOpacity : 1}>
                {data_by_disorder.map((d, i) =>
                    <path key={i} fill="none" stroke={colorScale(colorValue(d[0]))} strokeWidth={3} d={line(d)}/>
                )}
                <CircleMarks data={data_by_disorder.flat()}
                             xScale={xScale}
                             xValue={xValue}
                             yScale={yScale}
                             yValue={yValue}
                             radius={marksRadius}
                             colorScale={colorScale}
                             colorValue={colorValue}
                             tooltip={false}
                />
            </g>
            <g opacity={hoveredValue ? fadeOpacity : 1}>
                {data_by_disorder.map((d, i) =>
                    <path key={i} fill="none" stroke={colorScale(colorValue(d[0]))} strokeWidth={1.5} d={line(d)}/>
                )}
                <CircleMarks data={data_by_disorder.flat()}
                             xScale={xScale}
                             xValue={xValue}
                             yScale={yScale}
                             yValue={yValue}
                             radius={marksRadius}
                             colorScale={colorScale}
                             colorValue={colorValue}
                             tooltip={false}
                />
            </g>
            {filteredData.length > 0 &&
                <>
                    <path fill="none" stroke={colorScale(colorValue(filteredData[0]))} strokeWidth={1.5} d={line(filteredData)}/>
                    <CircleMarks data={filteredData}
                                 xScale={xScale}
                                 xValue={xValue}
                                 yScale={yScale}
                                 yValue={yValue}
                                 radius={marksRadius}
                                 colorScale={colorScale}
                                 colorValue={colorValue}
                                 tooltip={false}
                    />
                </>
            }

            ));

        </>
    )
}

Here is the screenshot of what is produced when I hover over the 1994 point.

enter image description here

Could you help me to figure out what is wrong with my onMouseMove function?

How to use forEach method in javascript? [closed]

The forEach method in JavaScript is an iterative method that executes a provided function once for each element in an array in ascending-index order. However, it has some limitations. For instance, it is not possible to stop or break a forEach() loop other than by throwing an exception.

Comma separated mobile number Regex validation

I’m trying validation for mobile number(With country code) which is not working. Posting the validation criteria below:

Valid Numbers:

  • +18790912345 (Valid)
  • +18790112345,+18790123409 (Valid)
  • +1-2569890912345 (Valid)
  • +1-2569890912345,+939890912098 (Valid)
  • -19890123909 (Valid)

Invalid Numbers:

  • +1909890 (Invalid)
  • 9800112345 (Invalid – without country code)
  • +1 9092345690 (Invalid-Containing spaces in between)

I’ve tried with the below regex code’s but it’s not passing the criteria.

/^[+-][1-9]{0,1}[0-9-]{0,16}[,]$/

and

^[+-][0-9-]{0,16}+(,[+-][0-9-]{0,16}+)*$

Please give some suggestions on this. Thanks.

Abnormal Zoom in on Iphone

I am developing a webpage, The page contains only a division containing images in it. I have added event Listeners to the images. I am changing the ‘viewport’ meta tag dynamically if clicked on a portion of image before displaying another division on the same page, so that the content on division fits the whole screen. When closing the division, I am changing the viewport back to normal. But It is abnormally zooming-in when closed the division. And I can Zoom-out to normal position without any problem. It is working perfectly fine on Android.

Here is the initial meta tag:

<meta name="viewport" content="width=device-width, initial-scale=0.25, minimum-scale=fit-content, maximum-scale=fit-content"/>

//which is working fine.

On clicking a button, I am Changing the meta tag in JavaScript like this :

//before opening the division on page

let meta = document. querySelector ("meta[name=viewport]");
if (meta) {
    meta.setAttribute ('content', "width=device-width, initial-scale=0.1 minimum-scale=1.0");
}

After closing the division, I am changing the meta tag back to the initial values like this:

let meta = document.querySelector ("meta[name=viewport]");
if (meta) {
    meta.setAttribute ('content', "width=device-width, initial-scale=0.25,minimum-scale=fit-content");
}

What might be the problem, I have tried this on iPhone 14, IOS version – 17.2.1.
All I am expecting is the scale of the page to be normal after closing the division. Is this a glitch in the software or can it be resolved?? Mentioning again This is working fine on Android.

how to vanish the border, like in google user login

please help, or what is it called?
email is a placeholder, but when we click on the box, it goes to border and the line betwn vanish
google uses it in their login form.
i am trying.
do we have to use jqury?
sorry i am new to front end react.

import React, { useState } from "react";

const Textbox = (props) => {
  const [isFocused, setIsFocused] = useState(false);

  const handleFocus = () => setIsFocused(true);

  const handleBlur = () => setIsFocused(false);

  return (
    <>
      <div style={{ margin: "5px", padding: "10px" }}>
        <fieldset
          className={isFocused ? "focused" : ""}
          style={{
            border: `1px solid ${isFocused ? "transparent" : "#000"}`,
            position: "relative",
          }}
        >
          <legend
            style={{
              position: "absolute",
              top: isFocused ? "-0.7rem" : "50%",
              left: isFocused ? "0" : "50%",
              transform: isFocused
                ? "translateY(0) translateX(0)"
                : "translateY(-50%) translateX(-50%)",
              transition: "top 0.3s, left 0.3s, transform 0.3s",
              pointerEvents: "none",
              fontSize: isFocused ? "0.75rem" : "1rem", // Adjust the font size
              zIndex: isFocused ? 1 : 0,
              outline: "none",
            }}
          >
            {props.legendText || "baka"}
          </legend>
          <input
            type="text"
            onFocus={handleFocus}
            onBlur={handleBlur}
            className="textbox-input"
          />
        </fieldset>
      </div>
    </>
  );
};

export default Textbox;