Limit the Primefaces datePicker hour, minutes and seconds to given values

I am using a datePicker Primefaces element in order to allow the user to select a value for the hours, minutes and seconds. Currently, the hour has values between 0 and 24, the minutes are between 0 and 60 and same for the seconds.

I want to limit this possibility of choice to some static values, obtained from getting the length of a video posted on the page.

So, for example, if the video has 1 minute and 30 seconds, I want the hours part not to allow the user to press the arrow up or down, the minutes to be maximum 30 and the minutes 1.
I tried the below code, but it does not work – I manage to see the max length of the video when I enter the page, but if I move the arrows from the datePicker element, I can select anything.

What can I do?

The UI datePicker element:

<p:outputPanel styleClass="input-group timestamp-input">
                                <p:datePicker id="timeDatePicker"
                                              widgetVar="widgetVarOfDatePicker"
                                              value="#{traineeDashboard.newIncidentTimestamp}"
                                              timeOnly="true"
                                              showSeconds="true"
                                              appendTo="@this">
                                    <f:converter converterId="timeConverter"/>
                                </p:datePicker>

JS Code:


function setMaxTimeForDatePicker(hours, minutes, seconds) {
    var timePicker = PF('widgetVarOfDatePicker'); 
    var hoursDropdown = $('div.ui-hour-picker span:eq(1)');
    var minutesDropdown = $('div.ui-minute-picker span:eq(1)');
    var secondsDropdown = $('div.ui-second-picker span:eq(1)');

    hoursDropdown.text(hours);
    minutesDropdown.text(minutes);
    secondsDropdown.text(seconds);

    hoursDropdown.trigger('change');
    minutesDropdown.trigger('change');
    secondsDropdown.trigger('change');
}

$(function() {
    var timePicker = PF('widgetVarOfDatePicker'); // Replace with your actual widgetVar

    // Override the behaviors for incrementing and decrementing hours, minutes, and seconds
    timePicker.cfg.onHourChange = function(newHour) {
        let maxHour = 2;
        let minHour = 0;
        if (newHour < minHour || newHour > maxHour) {
            // Set the hour back to the minimum or maximum as appropriate
            this.setTime(minHour, this.currentMinute, this.currentSecond);
        }
    };

    timePicker.cfg.onMinuteChange = function(newMinute) {
        if (newMinute < minMinute || newMinute > maxMinute) {
            // Set the minute back to the minimum or maximum as appropriate
            this.setTime(this.currentHour, minMinute, this.currentSecond);
        }
    };

    timePicker.cfg.onSecondChange = function(newSecond) {
        if (newSecond < minSecond || newSecond > maxSecond) {
            // Set the second back to the minimum or maximum as appropriate
            this.setTime(this.currentHour, this.currentMinute, minSecond);
        }
    };
});

Read Arabic text in view page [closed]

When I debugged, my controller class fetched the values including the Arabic text properly
enter image description here

but after passing this data to the View using ViewData, I m getting like this
enter image description here

So, how can I get the exact Arabic text in View page? Please help

Issue collecting data with Google Analytics

this is my first time trying to integrate google analytics for my webpage. I’ve followed a recent youtube tutorial that integrates this with a react app, although it does not seem to work.

Code I used:

const TRACKING_ID = "My Tracking Code";

ReactGA.initialize(TRACKING_ID);

const App = () => {

  useEffect(() => {
  ReactGA.send({
  hitType: "pageview",
  page: window.location.pathname + window.location.search,
  title: "Home Page",
});

  }, [])

 return (

<BrowserRouter>
  <Routes>
    <Route path='/' element={<Layout />}/>
  </Routes>
</BrowserRouter>

);
 }

Does anyone see what might be wrong?

Automatically Update React Component Based on External Class Property Changes

I have an external JavaScript class (MyClass) with a property (number) that changes automatically, but I need to update a React component whenever this property changes. I cannot modify the external class (MyClass), only the react component.

Here’s a simplified example of what I’m trying to achieve:

class MyClass {
  constructor(name, number) {
    this.name = name;
    this.number = number;
    setInterval(() => this.incrementNumber(), 1000);
  }

  incrementNumber() {
    this.number += 1;
  }
}

And the React component:

import React, { useState, useEffect } from 'react';

function App() {
  const [obj, setObj] = useState(new MyClass("omri", 0));

  useEffect(() => {
    // How can I automatically update the component when obj.number changes?
  }, [obj]);

  return (
    <div>
      {obj.name} {obj.number}
    </div>
  );
}

Constraints:
Cannot modify the MyClass external class.
Need to update the React component automatically when the number property in the external class (MyClass) changes.

What are the alternative approaches or solutions to automatically update the React component when the number property in the external class changes without altering the class?

thank you!

How to remove default html mail error message and make zod message instead with react-hook-form

this is my schema. using react-hook-form & zod for validation

const emailInputSchema = z.object({
  email: z.string().min(1, "input is required").email("email address is not valid"),
});

I want to have the message “email address is not valid” instead of the standart HTML email error message:

enter image description here

I want to have the “input is required” but I don’t get this error in the error object.

  const {
    register,
    handleSubmit,
    formState: { errors, isSubmitting },
    reset,
  } = useForm<TEmailInputSchema>({
    resolver: zodResolver(emailInputSchema, { errorMap: customErrorMap }),
  });

and here is the form inside of the TSX:

      <form onSubmit={handleSubmit(handleMailSubmit)}>
        <div className="input-container">
          <div className="input-wrapper rounded">
            <FaRegEnvelope className="input-icon" />
            <input
              type="email"
              {...register("email")}
              placeholder="email"
              className="input"
              autoComplete="email"
            />
          </div>
        </div>
        {errors.email && (
          <p className={`${errorStyle}`}>{`${errors.email.message}`}</p>
        )}
        <div className="buttons-container">
          <button
            type="submit"
            disabled={isSubmitting}
            className="form-submit-button"
          >
            Send an email
          </button>
        </div>
      </form>

Can I use http/https proxies or only socks5 for scraping wss/socket.io endpoint

Can I use http/https scraping proxies to scrape socket.io/wss endpoints from a website?

I want to hide real ip and prevent being blocked by the website.

import io from 'socket.io-client'

const socket = io.connect('https://weather.example.com', {
    rejectUnauthorized: false,
    transports: ['wss'],
    agent: //some http agent/socks5 proxy agent?
});

socket.on('connect', () => {
    console.log('connected');

    socket.emit('giveMeData');

    socket.on('someData', (data) => {
        console.log('data:', data);
    });
});

or is wss protocol suitable only to scrape via socks5?

how can I make an Ajax call instead of post printing the waybill from WordPress on my php website?

<form id="print-shipping-label-form">
    <input type="hidden" name="shipping_id" value="<?php echo $result_wpid_shipping['ID']; ?>">
    <input type="hidden" name="api_key" value="ce312203c06e8bda7157c408fbac54c4">
    <button type="submit" class="btn btn-danger">Drukuj list przewozowy</button>
</form>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        var printShippingLabelForm = document.getElementById('print-shipping-label-form');
        
        if (printShippingLabelForm) {
            printShippingLabelForm.addEventListener('submit', function(event) {
                event.preventDefault(); // Zatrzymaj domyślne zachowanie formularza
                
                var formData = new FormData(printShippingLabelForm);
                var url = 'https://torebki-fabiola.pl/?flexible_shipping_get_label=' + formData.get('shipping_id') + '&apikey=' + formData.get('api_key');
                
                // Wykonaj żądanie AJAX
                fetch(url, { method: 'POST' })
                    .then(function(response) {
                        return response.text();
                    })
                    .then(function(responseText) {
                        // Obsłuż odpowiedź z serwera, np. otwórz ją w nowym oknie.
                        window.open(responseText, '_blank');
                    })
                    .catch(function(error) {
                        console.log('Wystąpił błąd podczas wykonywania żądania AJAX: ' + error);
                    });
            });
        }
    });
</script>

I try to fix problem with this code

how do I create and save a game [closed]

Struggling on saving a game and extensions to save with

Created a game Tic-Tac-Toe and I’m trying save and open as an application but it still open with python. Seekin for help in creating applications and games and running it as on its own without python application.

autodesk-platform-services aps-iot issue: heatmap failed

I cloned the Autodesk Data Visulization service, aps-iot-extensions-demo-master; I found the Node.js in VSCode showed that “the file extension loaded into the viewer is not supported, try a different file”. After follow previous simalar question I solved this issue by set const APS_MODEL_VIEW = ”, getDefaultGeometry() to “getDefaultGeometry(true)”. Another issue exist: I just replaced APS_CLIENT_ID, APS_CLIENT_SECRET, APS_MODEL_URN and APS_MODEL_VIEW; the URN and GUID are obtained through a Model Derivative API. The source Revit file was translated to .svf file. However, the heatmap is not visualized in the Web and there is no error exist in console. The sensor location (x,y,z) are all set to be included in the Room bounds. The Model Brower in Viewer can also see “Rooms” element. Interesting, the console will not show error about” sensor do not within the Room bounds” when I put them outside the room. May be the inter-connect for sensor and room is not right? Do I need to try .svf2? If anyone can help, I will be very grateful!

Conditional utility classes using Tailwind and Astro

I am using Tailwind and Astro.

I created this menu link component:

// MenuItem.astro

---
type Props = {
  title: string;
  path: string;
};

const { title, path } = Astro.props;
const pathname = new URL(Astro.request.url).pathname;
const currentPath = pathname.slice(1);
---

<li>
  <a
    href={path}
    class=`${currentPath === path
? 'text-red'
: 'text-blue'} relative`
    >{title}</a
  >
</li>

Is there a way to make this cleaner? To use something different then a ternary, using Astro?

getPropertyValue sometimes returns empty string for CSS custom property

I am rendering the following style very early in the <head> :

<style>
:root {
    --enhanced: false;
}
@supports (selector(:not(.foo))) and
    (aspect-ratio: 1 / 1) and
    (margin-block-start: 1rem) and
    (gap: 1rem) and
    (display: grid) and
    (--css: variables) and
    (object-fit: cover) and
    (display: flex) {

    :root {
        --enhanced: true;
    }
}
</style>

Then, later, after Google Tag Manager has loaded on the page, I am then running some JavaScript to get the value of the CSS custom property that was declared:

var enhancedExperience = getComputedStyle(document.querySelector('html')).getPropertyValue('--enhanced');
if (enhancedExperience && enhancedExperience.indexOf('true') > -1) {
    return 1;
}
else if (enhancedExperience && enhancedExperience.indexOf('false') > -1) {
    return 0;
}
else {
    return enhancedExperience;
}

I have deployed this code to a website with a very high amount of traffic to run an experiment. And I have found that roughly 16% of the time it returns an empty string. And it is happening on a diverse range of browsers including the latest versions of all major browsers.

Why might this be? I thought perhaps race condition but considering the CSS custom property is declared so early on in the <head> and the JavaScript doesn’t run until GTM is loaded, is that possible?

The programming logic

I’m following an online Javascript course for beginners. One exercise is about Math.floor(), and the example given is:

get floorNum(x){
    let _x = x;
    _x = Math.floor(x);
    return _x;
}

My question is: why not just put “return Math.floor(x)” in the function body? Why let _x = x, and then return _x? Why not just return x directly? What’s the underlying logic?
I want to learn some basic programming logic.

I tried google, but didn’t find what I want. I’m an absolute beginner.

Why is it in NestJS async services, await does not work but promise .then works

In NestJS, I have this async services called fetchUsers and processUsers

async fetchUsers(type: string): Promise<UserResponse> {
  try {
    const result = await axios.get('/url')
    
    return result;
  } catch (err: any) {
    console.log(err)
  }
}

async processUsers(type: string): Promise<UserResponse> {
  const data = await this.fetchUsers(type)
  console.log('data', data)
  return data;
}

The code above does not work:

  • it prints the console log first, and then it go to the fetchUsers logic
  • it returns null because data is undefined

However, if I use fetchUsers with promise, like this:

async processUsers(type: string): Promise<UserResponse> {
  return this.fetchUsers(type).then((res) => {
    console.log('data', data)
    return data
  })
}

then it will works, it will print the log first and then returns data.

What could be the reasons behind this behavior? Also it’s worth noting that other code like this in my project works just find, only this one have this weird behavior