Rating system follow by mouse php

Hi I am trying to create rating system and now I am working on to change color of the star while user move the mouse I had this code but I dont know why this is not working. I have form with star container

<form>
  <div class="form-group">
  <div class="modal-body">
        <h4 class="text-center mt-2 mb-4">
            <i class="fas fa-star star-light submit_star mr-1" id="submit_star_1" data-index="1"></i>
            <i class="fas fa-star star-light submit_star mr-1" id="submit_star_2" data-index="2"></i>
            <i class="fas fa-star star-light submit_star mr-1" id="submit_star_3" data-index="3"></i>
            <i class="fas fa-star star-light submit_star mr-1" id="submit_star_4" data-index="4"></i>
            <i class="fas fa-star star-light submit_star mr-1" id="submit_star_5" data-index="5"></i>
        </h4>
    <label for="reviewer-name" class="col-form-label">Your name:</label>
    <input type="text" class="form-control" id="reviewer-name">
  </div>
  <div class="form-group">
    <label for="message-text" class="col-form-label">Review:</label>
    <textarea class="form-control" id="message-text"></textarea>
  </div>
</form>

and this function mouseenter

$('.submit_star').on('mouseenter', function(){

    var rating = $(this).data('rating');

    reset_background();

    for(var count = 1; count <= rating; count++)
    {

        $('#submit_star_'+count).addClass('text-warning');

    }

});

Any idea what could be wrong will be great, thanks

Typescript: type guard for whether an object property is defined, when the key is a wide type?

I have a function that returns whether an object property is undefined. I need this function instead of just doing obj[key] === undefined because otherwise I’d sometimes get Property 'foo' does not exist on type 'Bar'.. It’s straightforward to write the type when the property key is a literal. I.e.:

function hasDefinedProp<
  Obj extends Partial<Record<string, any>>,
  Prop extends string,
>(
  obj: Obj,
  prop: Prop,
): obj is Obj & Record<Prop, Prop extends keyof Obj ? Exclude<Obj[Prop], undefined> : unknown> {
  return obj[prop] !== undefined;
}

const obj: Partial<Record<string, number>> = {};
if (hasDefinedProp(obj, 'foo')) {
    obj.foo + 1; // No error.
    obj.bar + 1; // "Object is possibly 'undefined'."
}

However, this doesn’t work when the key’s type is a wide type, i.e.:

const obj: Partial<Record<string, number>> = {};
const key: string = '';
if (hasDefinedProp(obj, key)) {
    obj[key] + 1; // No error.
    obj.bar + 1; // No error. Should be "Object is possibly 'undefined'."
}

Is it possible to make the type guard work for wide types?

dynamic user list consumer in Django channels

I’m using Django(3.2.11) with the Postgres database. I’m creating a chat app with Django channels. so I created a message consumer and save it into the database. and also created a message history consumer by room. now I want to create a user list consumer which has dynamic messages with the user name. for that I made a consumer who returns infinite data.
like:-

class ChatListConsumer(AsyncJsonWebsocketConsumer):
    async def connect(self):
        self.room_group_name = 'chat_list_%s' % self.scope['user'].user_id
        self.connection = True
        await self.channel_layer.group_add(
            self.room_group_name,
            self.channel_name
        )
        await self.accept()

    async def disconnect(self, close_code):
        self.connection = False
        await self.channel_layer.group_discard(
            self.room_group_name,
            self.channel_name
        )

    def get_serializer(self, obj):
        return {'data': ProductQueryUsersSerializer(
            instance=obj.order_by('-updated_at'), many=True
        ).data, 'type': "chat_list"}

    async def receive(self, text_data):
        while self.connection:
            try:
                self.query = await database_sync_to_async(
                    ProductQueryUsers.objects.filter
                )(Q(seller__user=self.scope['user']) | Q(user=self.scope['user'])
                  )
                data = await database_sync_to_async(self.get_serializer)(self.query)
            except EmptyPage:
                data = {'data': [], 'type': "chat_list"}
            await self.send(text_data=json.dumps(data))

and call this in javascript like:-

<div id="message"></div>
    <script>
        const chatSocket = new WebSocket('ws://192.168.29.72:8000/ws/chat-list/?user=VXNlcjo4Mg==');
        chatSocket.onopen = function(e){
            chatSocket.send(JSON.stringify({}));
            console.log("open", e);
        };
        chatSocket.onmessage = function(e) {
            const data = JSON.parse(e.data);
            console.log(data)
            data.data.forEach(function (item, index, arr) {
                var element = document.getElementById(item.room_id);
                if (typeof(element) != 'undefined' && element != null){
                    document.getElementById(item.room_id).innerHTML = item.last_message.message
                } else {
                     document.getElementById('message').innerHTML += `<h1 id="${item.room_id}">${item.last_message.message}</h1>`
                }
            });
        };
        chatSocket.onerror = function(e){
            console.log("error", e)
        };
        chatSocket.onclose = function(e){
            console.log("close", e)
        };

    </script>

it infinite time return users’ list with their last message. but when it run another socket does not connect. so how can I create a user list consumer with the last message received? and call the three sockets on the same page.

How to upload image with base64 and validate it with formik

I want to handle it with formik and base64

const [postImage, setPostImage]: any = React.useState({
myFile: ”,
})

  const convertToBase64 = (file: any) => {
    return new Promise((resolve, reject) => {
      const fileReader = new FileReader()
      fileReader.readAsDataURL(file)
      fileReader.onload = () => {
        resolve(fileReader.result)
      }
      fileReader.onerror = (error) => {
        reject(error)
      }
    })
  }

  const handleFileUpload = async (e: any) => {
    const file = e.target.files[0]
    const base64 = await convertToBase64(file)
    setPostImage({...postImage, myFile: base64})
  }           

<input
type=’file’
multiple
className=’form-control’
name=’images’
accept=’.jpeg, .png, .jpg’
// value={props.postImage.myFile}
onChange={uploadImage}
/>

How to add array inside an array in Joi validator?

When I’m trying to add this to the Joi validation schema.

joi.array().items(joi.array().items(joi.number().integer())).default([]),

I’m getting this error.

Invalid schema configuration: `undefined` is not a valid type within the array `location`.

I have tried other iterations to figure out what causes the error.

joi.array().items().default([]) // No error
joi.array().items(joi.number().integer()) // No error
joi.array().items(joi.array().items()) // This caused error 

I think adding an array inside an array is causing the error.

How can I refresh the ProtonMail web inbox page once with Tampermonkey?

I have multiple ProtonMail accounts, and am trying to add an avatar to replace the default first letter of my name in the upper right hand corner of the ProtonMail web interface so I can more easily differentiate which inbox I’m in, like this:

enter image description here

I’ve worked out the Tampermonkey script below that loads images from my localhost server (on OS X; this could easily load images from imgur, etc.) according to the email address in the browser location bar, and that works.

The issue is that the images only show after I force reload the page once.

Is it possible to force a reload of the page once via Tampermonkey using jQuery or Javascript?

I can’t simply use location.reload(); in the script, as that will refresh over and over; I only need to refresh the page once after the inbox loads.

Or is there another way to get the avatars to show on first page load?

// ==UserScript==
// @name         ProtonMail Avatars
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  ProtonMail Avatars
// @author       Me
// @match        https://mail.protonmail.com/*
// @icon         
// @require      https://code.jquery.com/jquery-3.4.1.min.js
// @grant        GM_addStyle
// ==/UserScript==

/* globals jQuery, $, waitForKeyElements */

jQuery(document).ready(function() {
 $(window).bind("load", function() {

  var term = document.title;
  var email1 = "[email protected]";
  var email2 = "[email protected]";

  if (term.indexOf(email1)!= -1) {
   $(".user-initials span").css("display","none");
    $(".user-initials").css('background-image','url(http://localhost/email1.png)');
}

 if (term.indexOf(email2)!= -1) {
  $(".user-initials span").css("display","none");
   $(".user-initials").css('background-image','url(http://localhost/email2.png)');
}

 });
});

HTML5 Video — limiting buffer for an MP4

Is it possible to use an HTML5 Video tag to load an MP4, but control how much of the file is downloaded/buffered from the server (assume it supports byte ranges).

Essentially, I’d like to be able to say “only download 60 seconds ahead” so I can avoid the browser downloading an entire 2 GB file when the user is going to end up bouncing anyway.

Problem with opening HTML, CSS and JavaScript files (elements moved)

When I created my html, css and javascript files for the first time, they was located on desktop. Then decided to move all three files to another folder which located on disk D: and to rename the html file. Then, I opened my html file and noticed that my work is no longer in the same condition as it was before. Some elements are moved(see screenshot) and there one of the images is removes(there is an alternative text instead of the image). What should I do to return my work to the original status? Thanks, a lot for your help IMAGE

How to display discord.js greeting message?

I got some problem when tried my discord.js bot to send a greeting when somebody come in the server. I followed all of the instruction from documentation, but it doesn’t change anything. My terminal didn’t send an error and any commands is useable. My discord.js version is 12.5.3

client.on('guildMemberAdd', member => {
    const lobbyChannel = member.guild.channels.find(ch => ch.name === 'lobby');
    if (!lobbyChannel) return;
    lobbyChannel.send(`Welcome to the server, ${member}`).catch(console.error);
});

How to pass the variable password to the other functions in typescript?

I have implemented a login API and I want to use the password variable in other functions where I need to log that password. Like that status Service I have other 7 similar functions that should be logged. I tried by initializing the variable globally and try to use it later but not worked. Can anyone give any ideas on how to pass the variable to other functions in typescript or in javascript please.

@injectable()
export class IngestionService {
  @inject(TYPES.IngestionRepository)
  private ingestionRepository: IngestionRepository;

public async loginService(request, response) {
    try {
      let userDetails: any = await this.ingestionRepository.loginCheck(request.body);
      var email=request.body.emailid;
      var password=request.body.password;
      if (userDetails.rows.length === 0) {
        let wrongEmailResponse ={
          status: "Error",
          message: "The email "+email+" is not found in our database. So please enter the correct email address"
        }
        response.status(500).send(wrongEmailResponse);
      } else {
        let crypted = await this.authenticateUser.getEncryptedpassword(request.body.password);
        request.body.password = crypted;
        console.log(crypted);
        console.log(typeof userDetails.rows[0].userpassword)
        if(userDetails.rows[0].userpassword.match(crypted)){
          
          let responseData={
            status: "Success",
            message: "You have logged in successfully"
          }
          response.status(200).send(responseData);
        }
        else{
          let wrongPassResp={
            status: "Error",
            message: "You have entered wrong password"
          }
          response.status(500).send(wrongPassResp);
        }
      }
    //  return password;
    }
    catch (err) {
      let message = { message: err.message };
      response.status(500).send(message);
    }
  }



  public async statusService(request, response) {
    try {
      let ids = getid(request);
      var [msg]: any = await this.checkId.id(request, response);
      if (msg === true) {
        await this.ingestionRepository
          .getAssetStatusRepository({
            assetid: assetids,
            columns: request.query.columns,
          })
          .then((data: any) => {
            data.forEach((element) => {
              this.dateConversion(element);
            });
            let responseData = {
              status: "Success",
              message: "Below are the asset details",
              data: data
            };
            response.status(200).send(responseData);

          });
      }
    } catch (err) {
      let message = { message: err.message };
      response.status(500).send(message);
      //mongoResponse.error_message = message;
    }
  }

How to show the result of an onclick in another div? [duplicate]

I tried every lines of code I could think of but it didn’t work. I’m stuck on these for like a week now.

    let button = document.querySelector("convert");
let celsius = document.querySelector("temp_celsius");
let fahrenheit = document.querySelector("temp_fahr");

button.onclick = function celsiusToFahrenheit(celsius){
    var fahrenheit = (9 * celsius / 5) + 32;
    return fahrenheit;
};

document.getElementById("temp_celsius").innerHTML = celsius;
document.getElementById("convert").onclick = button;
document.getElementById("temp_fahr").value;


// "temp_celsius" - id of celsius div
// "convert" - id of calculate div
// "temp_fahr" - id of fahrenheit div

/* function celsiusToFahrenheit(celsius){
    var fahrenheit = (9 * celsius / 5) + 32;
    return fahrenheit;
};  - function to convert Celsius to Fahrenheit made on exercise #2 */ 

How can I put the conversion of celsius to fahrenheit?