PHP Week Days Secific Language

I’m Trying to make Conditional Delivery Notice based on Time and Date in Woocommerce
and want to display week days specific language.

   //Next Day Delivery Calculator
    add_action( 'woocommerce_before_checkout_form', 'next_day_delivery' );
    add_action( 'woocommerce_before_cart', 'next_day_delivery' );
    
    function next_day_delivery() {
        if( WC()->cart->is_empty() )
            return; // Exit
    
        // Set the time zone
        date_default_timezone_set('Asia/Tbilisi');
        
    
        // From Monday to Friday
        $is_week_days  = in_array( date('w'), array( 1, 2, 3, 4, 5 ) ) ? true : false;
        $end_time      = mktime('14', '00', '00', date('m'), date('d'), date('Y'));
        $now_time      = time();
        $after_tomorow = date('l', strtotime('+2 days'));
    
        $dateDiff      = intval(($end_time - $now_time)/60);
        $diff_hours    = intval($dateDiff/60);
        $diff_minutes  = $dateDiff%60;
        $hours_label   = _n( 'საათი', 'საათი', $diff_hours, 'wooocommerce' );
        $minutes_label = _n( 'წუთი', 'წუთი', $diff_minutes, 'wooocommerce' );
    
        
    
        if ( $end_time > $now_time && $is_week_days ) {
            
            // print text 
            $message = sprintf( __( '%s დარჩა შეკვეთის გასაფორმებლად თუ გსურთ ჩაგბარდეთ ხვალ!', 'woocommerce' ),
            $diff_hours.' '.$hours_label.' და '.$diff_minutes.' '.$minutes_label);
        }
        elseif ( $end_time <= $now_time && $is_week_days ) {
            
            $message = sprintf( __( 'თქვენ მიიღებთ შეკვეთას %s.', 'woocommerce' ), $after_tomorow );
        } else {
            $message = __( 'თქვენი შეკვეთა ფორმირდება ორშაბათს და ჩაგბარდებათ სამშაბათს.', 'woocommerce' );
        }
        wc_print_notice( $message, 'success' );
    }

also want to make conditional checkbox based shipping class. (if shipping class is express its same day delivery must hide notice about shipping date)

//Hide Delivery Message Express Shipping Checked

    add_action( 'woocommerce_after_checkout_form', 'show_notice_billing' );
    function show_notice_billing(){
        ?>
            <script>
            jQuery(function($){
               $(document).ready(function() {
        $(document).on("click", "#shipping_method_0_flat_rate-12", function(e) {
           var checked = $(this).find("input:checkbox").is(":checked");
           if (checked) {
               $('.woocommerce-message').hide(300);
           } else {
               $('.woocommerce-message').show(300);
           }
        });
    });
            });
        </script>
        <?php
    }

Last Name output problem in student application management system

I am building a student application management system using PHP, JavaScript. Each student has a unique ID. There will be a system for students to submit applications. If you select the ID of any student, the First name, last name of the student will come down automatically. I was able to get the first name of the student using JavaScript. But I could not bring the last name of students. When I select last name it is vanished automatically. My Code is:

                    <div class="form-group">
                        <label class="col-sm-3 control-label right"><strong>Student Id</strong></label>
                        <div class="col-sm-9">
                            
                            <?php

                                $username = '';
                                $query = "SELECT username FROM users where ref ='".$uid."'";
                                $result = mysqli_query($conms, $query);
                                while($row = mysqli_fetch_array($result))
                                {
                                    $username .= '<option value="'.$row["username"].'">'.$row["username"].'</option>';
                                }
                            ?>
                            
                            <select name="startdate" id="username" class="form-control action">
                                <option value="">Select Student</option>
                                    <?php echo $username; ?>
                            </select>

                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label class="col-sm-3 control-label right"><strong>First Name</strong></label>
                        <div class="col-sm-9">
                            <select name="enddate" id="firstname" class="form-control action">
                                <option value=""></option>
                            </select>
                            
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label class="col-sm-3 control-label right"><strong>Last Name</strong></label>
                        <div class="col-sm-9">
                                <select name="leavetype" id="lastname" class="form-control action">
                                <option value=""></option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label class="col-sm-3 control-label right"><strong>Mobile No</strong></label>
                        <div class="col-sm-9">
                            <select name="reason" id="mobileno" class="form-control action">
                                <option value=""></option>
                            </select>
                        </div>
                    </div>
                
                    <div class="form-group">
                        <label class="col-sm-3 control-label right"><strong>Nationality</strong></label>
                        <div class="col-sm-9">
                            <input class="form-control" name="totaldays" type="text" id="nationality" value="" >
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label class="col-sm-3 control-label right"><strong>University Name</strong></label>
                        <div class="col-sm-9">
                            <input class="form-control" name="tm" type="text" value="" >
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label class="col-sm-3 control-label right"><strong>Programe</strong></label>
                        <div class="col-sm-9">
                            <input class="form-control" name="dtm" type="text" value="" >
                        </div>
                    </div>
                    

                    
                    <div class="col-sm-9 col-sm-offset-3">
                        <button class="btn btn-primary btn-block" type="submit">SEND</button>
                    </div>
                </div>
                
                
                <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>        
                <script>
                    $(document).ready(function(){
                     $('.action').change(function(){
                      if($(this).val() != '')
                      {
                       var action = $(this).attr("id");
                       var query = $(this).val();
                       var result = '';
                       if(action == "username")
                       {
                        result = 'firstname'; 
                       }
                       else
                       {
                        result = 'lastname';
                       }
                    
                       $.ajax({
                        url:"fetch.php",
                        method:"POST",
                        data:{action:action, query:query},
                        success:function(data){
                         $('#'+result).html(data);
                        }
                       })
                      }
                     });
                    });
                </script>

fetch.php

         <?php
       include ('include/header.php');
      if(isset($_POST["action"]))
      {

     $output = '';
    if($_POST["action"] == "username")
     {
    $query = "SELECT fullname FROM users WHERE username = '".$_POST["query"]."'";
    $result = mysqli_query($conms, $query);
    $output .= '<option value="">Select First Name</option>';
   while($row = mysqli_fetch_array($result))
   {
   $output .= '<option value="'.$row["fullname"].'">'.$row["fullname"].'</option>';
   }
   }
  if($_POST["action"] == "firstname")
  {
  $query = "SELECT fathersname FROM users WHERE fullname = '".$_POST["query"]."'";
  $result = mysqli_query($conms, $query);
  $output .= '<option value="">Select Last Name</option>';
   while($row = mysqli_fetch_array($result))
   {
   $output .= '<option value="'.$row["fathersname"].'">'.$row["fathersname"].'</option>';
   }
   }


  echo $output;
  }
  ?>

1

2

checkbox changing a controlled input of type checkbox to be uncontrolled

Warning: A component is changing an uncontrolled input of type text to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component.*

Following is my code:

import React from 'react';
import { useEffect } from 'react';
import { useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { detailsUser } from '../actions/userActions';
import LoadingBox from '../components/LoadingBox';
import MessageBox from '../components/MessageBox';

export default function UserEditScreen(props) {
  const userId = props.match.params.id;
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [isSeller, setIsSeller] = useState(false);
  const [isAdmin, setIsAdmin] = useState(false);

  const userDetails = useSelector((state) => state.userDetails);
  const { loading, error, user } = userDetails;

  const dispatch = useDispatch();
  useEffect(()=>{
      if(!user){
          dispatch(detailsUser(userId));
      }
      else{
          setName(user.name);
          setEmail(user.email);
          setIsSeller(user.isSeller);
          setIsAdmin(user.isAdmin);
      }
  },[dispatch, user, userId])

  const submitHandler = (e) => {
    e.preventDefault();
  };
  return (
    <div>
      <form className="form" onSubmit={submitHandler}>
        <div>
          <h1>Edit User {name}</h1>
          {loading && <LoadingBox></LoadingBox>}
          {error && (
            <MessageBox variant="danger">{error}</MessageBox>
          )}
        </div>
        {loading ? (
          <LoadingBox />
        ) : error ? (
          <MessageBox variant="danger">{error}</MessageBox>
        ) : (
          <>
            <div>
              <label htmlFor="name">Name</label>
              <input
                id="name"
                type="text"
                placeholder="Enter name"
                value={name}
                onChange={(e) => setName(e.target.value)}
              ></input>
            </div>
            <div>
              <label htmlFor="email">Email</label>
              <input
                id="email"
                type="email"
                placeholder="Enter email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
              ></input>
            </div>
            <div>
              <label htmlFor="isSeller">Is Seller</label>
              <input
                id="isSeller"
                type="checkbox"
                checked={isSeller}
                onChange={(e) => setIsSeller(e.target.checked)}
              ></input>
            </div>
            <div>
              <label htmlFor="isAdmin">Is Admin</label>
              <input
                id="isAdmin"
                type="checkbox"
                checked={isAdmin}
                onChange={(e) => setIsAdmin(e.target.checked)}
              ></input>
            </div>
            <div>
              <button type="submit" className="primary">
                Update
              </button>
            </div>
          </>
        )}
      </form>
    </div>
  );
}

I am getting this error while updating the isSeller option it is working for admin but not for seller. please provide the answer…
Thanks 🙂

jquery to Vanila javascript [closed]

if ($(".nvabarTogglerButtonProduct").hasClass("collapsed"))

how can we replace this with vanila javascript I have try this that way

if (document.querySelector('.nvabarTogglerButtonProduct").classList.contains("collapsed"))

but this code is not working please suggest me some good replacement for this

HTML JS Open new window with console in google chrome

This is client-side HTML. I’m just using HTML for automation.

My initial goal was to open a new window https://live.ipms247.com/login/ and then paste the values in the three login fields. All three fields have ID tags. And I can write to them from the console. For example.

document.getElementById("username").value="sample"; 
document.getElementById("hotelcode").value="12345"; 
document.getElementById("password").value="Password";

I wrote a code to copy text from parent window to child window at the click of a button.
My code is on a local file.

<html>
<head>
<script type="text/javascript">
function init()
{
    popupWin = window.open('https://live.ipms247.com/login/','popupWin','');
}
function transferText()
{
    popupText = popupWin.document.getElementById("username");
    parentText = document.getElementById("parentTextBox");
    popupText.value = parentText.value
}
</script>
</head>
<body>
<input type="text" id="parentTextBox" onkeyup="transferText();" value="Hello World">
<input type="button" onclick="init();" value="popup window">
<input type="button" onclick="transferText();" value="Transfer Text">
</body>
</html>

However, this does not work, apparently because my code is on a local file and the website is on another domain.

So my only solution to this problem, so far, is to launch the site with onlick and then focus to it. Press Ctrl+Shift+J to open the console and then paste the commands (I have code which copies them to clipboard) and hit enter.

Is there any possibility to launch the new window with the console open and focus on the console?

How to create a embed for a API response for a Discord Bot

I have added a API response to my Discord Bot and want to know how to format this API response into a embed to make it look nice when it gets sent in Discord

Here is my code:

const ifliveService = require("../utils/InfiniteFlightLive")
const ifl = new ifliveService()

module.exports = {
    category: "Userstats",
    description: "Fetches the users states from Discourse.",
    expectedArgs: '<ifc username>',
    minArgs: 1,
    maxArgs: 1,
    callback: async ({channel, args}) => {
        const username = args[0]
        
        const userstats = await ifl.getUserStats(username)
        if(!userstats || userstats.result == []) return "Invalid user"
        return JSON.stringify(userstats.result[0], null, 't')
         }
     }

I want to return that base reply into a embed how would that be possible? Please note I am a bit of a beginner with all of this so I apologize if it is a quick and easy solution.

Function is declared but its value is never read

The function is working on the HTML page but not working from the external JS file and showing this error (‘checkSelection’ is declared but its value is never read). Is there any solution for this?

   function checkSelection(that) {
    if (that.value == "web-dev") {
      document.getElementById("web-section").style.display = "block";
    } else {
      document.getElementById("web-section").style.display = "none";
    }
    if (that.value == "grp-dsg") {
      document.getElementById("graphic-section").style.display = "block";
    } else {
      document.getElementById("graphic-section").style.display = "none";
    }
    if (that.value == "dgt-mkt") {
      document.getElementById("marketing-section").style.display = "block";
    } else {
      document.getElementById("marketing-section").style.display = "none";
    }
  }
<input onchange="checkSelection(this);">

how to change another text according to dropdown in react native

API PART:

{
    "response": "success",
    "fuel_type": [
        {
            "m_type_id": "1",
            "m_fuel_name": "Diesel",
            "m_fuel_price": "98.25"
        },
        {
            "m_type_id": "3",
            "m_fuel_name": "Extra Premium",
            "m_fuel_price": "116.50"
        },
        {
            "m_type_id": "2",
            "m_fuel_name": "Petrol",
            "m_fuel_price": "101.98"
        }
    ]
}

this is drop down and chnage the data according to dropdown

How to change दर according to dropdown

TypeError: Class extends value undefined is not a constructor or null while using stream-browserify

While using stream-browserify to import Transform class and extend it in the code causing the following exception in the browser console

AudioUtils.ts:52 Uncaught TypeError: Class extends value undefined is not a constructor or null
    at Module../src/components/AudioUtils.ts (AudioUtils.ts:52:1)
    at Module.options.factory (react refresh:6:1)
    at __webpack_require__ (bootstrap:24:1)
    at fn (hot module replacement:61:1)
    at Module../src/components/TController.ts (TConfig.ts:10:1)
    at Module.options.factory (react refresh:6:1)
    at __webpack_require__ (bootstrap:24:1)
    at fn (hot module replacement:61:1)
    at Module../src/components/STT.tsx (AudioUtils.ts:67:1)
    at Module.options.factory (react refresh:6:1)

Here is the snippet of AudioUtils.ts

import { Transform } from 'stream'

export class EncodePcmStream extends Transform {
    _transform(chunk: any, encoding: string, callback: TransformCallback) {
        const buffer = encodePcm(chunk); // encodePcm is a local function
        this.push(buffer);
        callback();
    }
}

Here is the snippet of package.json

{
  "name": "app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@types/jest": "^27.4.1",
    "@types/node": "^16.11.26",
    "@types/react-dom": "^17.0.2",
    "buffer": "^6.0.3",
    "microphone-stream": "^6.0.1",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "5.0.0",
    "stream-browserify": "^3.0.0",
    "typescript": "^4.6.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "devDependencies": {
    "@types/readable-stream": "2.3.13"
  },
  "type": "module"
}
  • I checked most of the questions with similar error here but none of the solutions worked.
  • I used dpdm to check circular dependency and there are no circular dependency that it reported.

How to open the ‘brush preset manager’ using javascript in Photoshop 2017?

I’ve loaded a .tpl preset file into Photoshop CC 2017, the .tpl file is pretty big and after loading it into the Preset manager, most of the brushes were duplicated for some reason. But it works fine in Photoshop CS 6, so I’m pretty sure the file itself is OK. Now I’m trying to delete all the duplicated brushes through Preset Manager, but there’re just too many of them I could not do it manually.

I’m thinking about writing a .jsx script to do that for me. It will go through the Preset Manager with a for loop and remove every duplicated ones. But I’m not familiar with Photoshop scripting. Pls send help!

Make p5js project run faster

I made a project called “pixel paint” by javascript with p5js library, but when I run it, that project ran too slow. I don’t know why and how to make it run faster. And here is my code:

let h = 40, w = 64;
let checkbox;
let scl = 10;
let painting = new Array(h);
let brush = [0, 0, 0];
for(let i = 0; i < h; i++) {
  painting[i] = new Array(w);
  for(let j = 0; j < w; j++) {
    painting[i][j] = [255, 255, 255];
  }
}

function setup() {
  createCanvas(w * scl, h * scl);
  checkbox = createCheckbox('Show gird line', true);
  checkbox.changed(onChange);
}

function draw() {
  background(220);

  for(let y = 0; y < h; y++) {
    for(let x = 0; x < w; x++) {
      fill(painting[y][x]);
      rect(x * scl, y * scl, scl, scl);
    }
  }

  if(mouseIsPressed) {
    paint();
  }
}

function onChange() {
  if (checkbox.checked()) {
    stroke(0);
  } else {
    noStroke();
  }
}

function paint() {
  if(mouseX < w * scl && mouseY < h * scl) {
    let x = floor(mouseX / scl);
    let y = floor(mouseY / scl);
    painting[y][x] = brush;
  }
}
<!--Include-->
<script  src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.min.js"></script>

Is there a solution to make my project run faster?

React router v5 to v6 Migration

I’m learning to react and trying to migrate an app from the react-router v5 to v6. I have an issue with the routing and need to fix that. The UI looks like below:

enter image description here

If I click the title say Airplane or the New Movie button, the code should hit the route <Route path="/movies/:id" element={<MovieForm/>}/> and take me to the MovieForm page.

The code for the App.js is below:

function App() {
    return (
        <React.Fragment>
            <NavBar/>
            <main className="container">
                <Routes>
                    <Route path="/register" element={<RegisterForm/>}/>
                    <Route path="/login" element={<LoginForm/>}/>
                    <Route path="/movies/:id" element={<MovieForm/>}/>
                    <Route path="/movies" element={<Movies/>}/>
                    <Route path="/customers" component={<Customers/>}/>
                    <Route path="/rentals" component={<Rentals/>}/>
                    <Route path="/not-found" component={<NotFound/>}/>

                    <Route path="/" element={<Navigate replace to="/movies" />} />
                    <Route path="/*" element={<Navigate replace to="/not-found" />} />
                </Routes>
            </main>
        </React.Fragment>
    );
}

The MovieForm code is below:

class MovieForm extends Form {

    state = {
        data: {
            title: "",
            genreId: "",
            numberInStock: "",
            dailyRentalRate: ""
        },
        genres: [],
        errors: {}
    };

    schema = {
        _id: Joi.string(),
        title: Joi.string()
            .required()
            .label("Title"),
        genreId: Joi.string()
            .required()
            .label("Genre"),
        numberInStock: Joi.number()
            .required()
            .min(0)
            .max(100)
            .label("Number in Stock"),
        dailyRentalRate: Joi.number()
            .required()
            .min(0)
            .max(10)
            .label("Daily Rental Rate")
    };




    componentDidMount() {
        const genres = getGenres();
        this.setState({ genres });

        const movieId = this.props.match.params.id;
        if (movieId === "new") return;

        const movie = getMovie(movieId);
        if (!movie) return this.props.history.replace("/not-found");

        this.setState({ data: this.mapToViewModel(movie) });
    }

    mapToViewModel(movie) {
        return {
            _id: movie._id,
            title: movie.title,
            genreId: movie.genre._id,
            numberInStock: movie.numberInStock,
            dailyRentalRate: movie.dailyRentalRate
        };
    }


    doSubmit = () => {
        saveMovie(this.state.data);

        this.props.history.push("/movies");
    };



    render() {
        return (
            <div>
                <h1>Movie Form</h1>
                <form onSubmit={this.handleSubmit}>
                    {this.renderInput("title", "Title")}
                    {this.renderSelect("genreId", "Genre", this.state.genres)}
                    {this.renderInput("numberInStock", "Number in Stock", "number")}
                    {this.renderInput("dailyRentalRate", "Rate")}
                    {this.renderButton("Save")}
                </form>
            </div>
        );
    }
}

export default MovieForm;

The UI page (the image provided above) is movies.js and the code is below:

class Movies extends Component {
    state = {
        movies: [],
        genres: [],
        pageSize: 4,
        currentPage: 1,
        sortColumn: { path: 'title', order: 'asc' },
    };

    componentDidMount() {
        const genres = [{ name: 'All Genres', _id: '' }, ...getGenres()];
        this.setState({ movies: getMovies(), genres: genres });
    }

    handleDelete = (movie) => {
        console.log('Deleting the movie named => ' + movie.title);

        const moviesAfterDelete = this.state.movies.filter(
            (m) => m._id !== movie._id
        );
        this.setState({ movies: moviesAfterDelete });
    };

    handleLike = (movie) => {
        const movies = [...this.state.movies];
        const index = movies.indexOf(movie);

        movies[index] = { ...movies[index] };
        movies[index].liked = !movies[index].liked;

        this.setState({ movies });
    };

    handlePageChange = (page) => {
        this.setState({ currentPage: page });
    };

    handleGenreSelect = (genre) => {
        this.setState({ selectedGenre: genre, currentPage: 1 });
    };

    handleSort = (sortColumn) => {

        this.setState({ sortColumn});
    };

    handleSearch = (query) =>{
        this.setState({
            searchQuery: query,
            selectedGenre: null,
            currentPage: 1,
        });
    };

    getPageData = ()=>{
        const {
            pageSize,
            currentPage,
            sortColumn,
            selectedGenre,
            searchQuery,
            movies: allMovies,
        } = this.state;


        let filtered = allMovies;
        if (searchQuery)
            filtered = allMovies.filter((m) =>
                m.title.toLowerCase().startsWith(searchQuery.toLowerCase())
            );
        else if (selectedGenre && selectedGenre._id)
            filtered = allMovies.filter(
                (m) => m.genre._id === selectedGenre._id
            );


        const sorted = _.orderBy(
            filtered,
            [sortColumn.path],
            [sortColumn.order]
        );

        const movies = paginate(sorted, currentPage, pageSize);

        return {totalCount: filtered.length, data: movies};

    };

    render() {
        const { length: count } = this.state.movies;
        const {
            pageSize,
            currentPage,
            sortColumn,
            searchQuery
        } = this.state;

        if (count === 0) return <p>There are no movies in the database!</p>;

        const {totalCount, data: movies} = this.getPageData();

        return (
            <div className="row">
                <div className="col-3">
                    <ListGroup
                        items={this.state.genres}
                        selectedItem={this.state.selectedGenre}
                        onItemSelect={this.handleGenreSelect}
                    />
                </div>

                <div className="col">

                    <Link
                        to="/movies/new"
                        className="btn btn-primary"
                        style={{ marginBottom: 20 }}
                    >
                        New Movie
                    </Link>
                    <p>Showing {totalCount} movies in the database.</p>

                    <SearchBox
                        value={searchQuery}
                        onChange={this.handleSearch}
                    />

                    <MoviesTable
                        movies={movies}
                        onLike={this.handleLike}
                        sortColumn={sortColumn}
                        onDelete={this.handleDelete}
                        onSort={this.handleSort}
                    />
                    <Pagination
                        itemsCount={totalCount}
                        pageSize={pageSize}
                        currentPage={currentPage}
                        onPageChange={this.handlePageChange}
                    />
                </div>
            </div>
        );
    }
}

export default Movies;

If you look closely in the class above, the New Movie button is there –

                    <Link
                        to="/movies/new"
                        className="btn btn-primary"
                        style={{ marginBottom: 20 }}
                    >
                        New Movie
                    </Link>

Now, how do I make sure that the route <Route path="/movies/:id" element={<MovieForm/>}/> is working correctly in the react-router v6?

Thanks.