Circular progress bar based on percentage

I’m working on a js code where circular progress bar shows based on ratings. But there’s an issue. Now total value is 10 set for progress bar. So I can enter max 10 in here. If I enter 9%, it not works as because max-value is 10. But I want something like that, if I enter any number with percent, like that 70% 85% 35%, the the value / max value will work as 100. How can I do it ?

Here’s my code:

    $(document).ready(function() {
      let val = $(".ratings").html();
      const progressBar = $('[role="progressbar"]');
      progressBar.attr('aria-valuenow', val); // Set the value to aria-valuenow attribute
      progressBar.css('--value', val); // Set the value to --value CSS custom property
      progressBar.text(val);
    });
div[role="progressbar"] {
      --size: 3rem;
      --fg: #369;
      --bg: #def;
      --pgValue: var(--value);
      --pgPercentage: calc(var(--pgValue) * 10);
      width: var(--size);
      height: var(--size);
      border-radius: 50%;
      display: grid;
      place-items: center;
      background: 
        radial-gradient(closest-side, white 80%, transparent 0 99.9%, white 0),
        conic-gradient(var(--fg) calc(var(--pgPercentage) * 1%), var(--bg) 0);
      font-size: calc(var(--size) / 3.5);
      color: var(--fg);
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="ratings" style="display: none;">9.5</div>
    <div role="progressbar" aria-valuenow="" aria-valuemin="0" aria-valuemax="10" style="--value:"></div>

Acrobat dropdown form to show hide layers with Javascript

Good morning!

Show hide layers from a dropdown in Adobe Acrobat!

I have implemented the script below that may have some errors but I have limited knowledge of JavaScript. I have adapted this script and seems to work locally however when I send it to the client it fails! is there any obvious errors in the following!

Any help much appreciated!!!


var layers = this.getOCGs();
var v = event.value; 
for (var i = 0; i < this.layers.length; i++) {
    if (layers[i].name == "Blank" && v == "BlankOption") {
        layers[i].state = true;
    }
    else if (layers[i].name == "Form1" && v == "Option1") {
        layers[i].state = true;
    }
    else if (layers[i].name == "Form2" && v == "Option2") {
        layers[i].state = true;
    }
        else if (layers[i].name == "Form3" && v == "Option3") {
        layers[i].state = true;
    }
        else if (layers[i].name == "Form4" && v == "Option4") {
        layers[i].state = true;
    }
        else if (layers[i].name == "Form5" && v == "Option5") {
        layers[i].state = true;
    }
        else if (layers[i].name == "Form6" && v == "Option6") {
        layers[i].state = true;
    }
        else if (layers[i].name == "Form7" && v == "Option7") {
        layers[i].state = true;
    }
        else if (layers[i].name == "Form8" && v == "Option8") {
        layers[i].state = true;
    }
        else if (layers[i].name == "Form9" && v == "Option9") {
        layers[i].state = true;
    }
    else if (layers[i].name != "BG-IMAGE"){
        layers[i].state = false;
    }
}

Jest is covering empty lines, comment lines and spaces in Source code

I’m using

"jest": "^29.5.0",
"jest-fetch-mock": "^3.0.3",
"jest-sonar-reporter": "^2.0.0",

Following is my jest.config.js:

module.exports = {
  automock: false,
  clearMocks: true,
  collectCoverage: true,
  coverageDirectory: "<rootDir>/Test/Reports",
  coveragePathIgnorePatterns: ["/node_modules/", "/Test/Unit/"],
  coverageReporters: ["text", ["lcovonly", { projectRoot: "." }]],
  testEnvironment: "node",
  testResultsProcessor: "<rootDir>/Test/node_modules/jest-sonar-reporter",
  testEnvironmentOptions: {
    browsers: ["chrome", "firefox", "safari"],
    url: "http://localhost",
  },
  moduleNameMapper: {
    "\.(css|less|sass|scss)$": "<rootDir>/Test/__mocks__/styleMock.js",
    "\.(gif|ttf|eot|png|svg)$": "<rootDir>/Test/__mocks__/fileMock.js",
    "^react$": "<rootDir>/Test/node_modules/react",
    "^react-dom$": "<rootDir>/Test/node_modules/react-dom",
  },
  rootDir: "../",
  roots: ["<rootDir>"],
  setupFiles: ["<rootDir>/Test/node_modules/mock-local-storage"],
  setupFilesAfterEnv: [
    "<rootDir>/Test/Unit/setupJest.js",
    "<rootDir>/Test/node_modules/mock-local-storage",
  ],
  transform: {
    "^.+\.(js|jsx|mjs)$": "<rootDir>/Test/jest-transformer.js",
  },
  verbose: true,
  watchman: true,
};

The coverage summary table and lcov.info file generated shows that new lines, comment lines, initialized variables, destructured props and non-existing lines are uncovered (example: file with 500 total lines, report says line 700-800 is uncovered).

useSWR fail to receive return response from Nextjs API route

I am using useSWR to call the internal Nextjs API route to query the database.

const fetcher = (url: string) => axios.get(url).then((r) => console.log(r.data))

export default function Model(){
    const searchParams = useSearchParams();
    const selectedMatch= searchParams.get("data"); 
    const { data } = useSWR("/api/model?data=" + selectedMatch, fetcher, {refreshInterval: 100});
    return (<p>{data}</p>)}

My /api/model:

import { connectToDB } from "@/app/utils/database";
import Events from "@/models/events";

export const GET = async (req: Object) => {
  await connectToDB();
  const matchString: String = req.nextUrl.searchParams.get("data")
  var events: any = {};

  try {
    matchString.split(",").map(async (match: string) => {
      events[match] = await Events.find({ name: match }).then((res) => res[0]);
    });
    return new Response(JSON.stringify(events), { status: 200 });
  } catch (error) {
    return new Response("Failed to fetch all events", { status: 500 });
  }
};

However, when I do the axios.get(url).then((r) => console.log(r.data)), it logs the empty object {}, if I console.log the JSON.stringify(events) in /api/model before the return, it does give me the correct data from the database, may I ask why?

Mock return a local component used

Is it possible to return a mock value for a child component?

I have been looking at getting this working and it seems that most suggest a couple of things that don’t seem to work in my case.

MainComponent.tsx

import ChildComponent from './child-component';

const MainComponent = () => (
    <ChildComponent />
);

export default MainComponent

ChildComponent.tsx

const ChildComponent = () => (
    /* Blah blah, some component stuff here that I don't care about */
)

export default ChildComponent;

From my readings I have seen that with default exports the mock should be written in this style:

jest.mock('./child-component', () => () => <h1>Some mocked child</h1>);

And if it’s a named export then it should be slightly different

jest.mock('./child-component', () => ({
    __esModule: true,
    ChildComponent: <h1>Some mocked Child</h1>
}));

There is even some talk of modifying the named one to hold an object property, default: () => <h1>blah</h1> as well. But none of this seems to work.

I have had my issues with hoisting and have placed the mocks at the top, to stop any confusion, but still no luck.

The only thing I did manage to get working was checking that the component is called. But that’s not very impressive, with

import renderer from 'react-test-renderer';
import ChildComponent from './child-component';

jest.mock('./child-component');
...
it('should hit child component', () => {
    renderer.create(<MainComponent />);
    expect(ChildComponent).toHaveBeenCalled();
});

Javascript manipulate dynamic array based on string comparision

I have an error object ‘err’ which is a consolidated list of errors from both UI and service.
I want to ultimately set them to the setError.

‘path’ represents the field id’s e.g. if there are 2 errors on field1, ‘path’ would be field1 for both

I want to

  1. Club common errors.message on same ‘path’ i.e.
    say if for field1, there are 2 “Field 1 is invalid” message, I want to only do setError with message ‘Field 1 is invalid’

  2. If there are 2 different errors.message on same ‘path’ i.e. say if for field1, one message is “Field 1 is invalid” and other message is ‘Invalid Length for Field 1’, then I want to concatenate the message and then do setError with message ‘Field 1 is invalidnInvalid Length for Field 1’

Below is my ‘err’ object looks like

err.inner.flatMap((obj) => obj.path); //['field1', 'field1', 'field2', 'field2']
err.inner.flatMap((obj) => obj.message); //['Field 1 is invalid', 'Invalid Length for Field 1', 'Field 2 is invalid', 'Invalid  Length for Field 2']
err.inner.flatMap((obj) => obj.type); //['min', 'api-error', 'min', 'api-error']

setError(path, type, message); 

Is there an ES6 way of doing the same?

I am fine with using either ‘type’ for different error messages.

How to customize svg image using JavaScript?

I want to create a custom mobile case. Where I have svg for product. So I want to upload user image on mobile case but it should not cover camera. If I drag image in camera area, It should be behind the camera.
I can have multiple layers in svg. How can I achieve this using JavaScript?

enter image description here

Securely transmitting client side logs to the server

Given that there is a client side web application which may run into errors, how can these error logs be sent to the server side for analysis in such a way that no other party can send fake logs to the server.

The main challenge here is that

  1. Message signing cannot provide any protection here as the private key is used for signing and public key for verification.
  2. Symmetric cryptography cannot provide any protection as the key must be exposed in the client side app.
  3. Asymmetric cryptography cannot be used because if the app can request for a public key, then the attacker can also do that.
  4. Custom message protocols are not useful as they can be replicated.
  5. Custom HTTP header cannot be used as the attacker can replicate them.
  6. Authentication cannot be used since if the app can authenticate itself then attacker can also do that.

In general, all the solutions that come to my mind can be replicated by an attacker. So how can you design a backend API that can somehow distinguish legit requests from fake ones?

In TypeScript how to understand which decorators are used?

Right now in TypeScript there are 2 types of decorators – the legacy and stage 3 ones.

// legacy decorator type
const legacyDecorator: PropertyDecorator;

// modern decorator type
const modernDecorator: <This, Value>(value: unknown, context: ClassFieldDecoratorContext<This, Result>) => void;

I want to create an NPM library which can used with both of decorators. But I have a problem of defining which version of decorators developer used.

I’d like to use some type like this

const myDecorator: ChooseType<
  PropertyDecorator,
  <This, Value>(value: unknown, context: ClassFieldDecoratorContext<This, Result>) => void,
>;

This way I could provide more specific types for the new decorators, but remain legacy decorators work too.

Is it possible in any way to achieve it? Maybe not with the generic type, you can tell any possible solution.

how to loop JSON object and create a HTML Table

iCreated a form to input bowling score data and i need to loop through this JSON object and put it on a html table. i want to make the table inside the if condition. how to do it?

this is the Controller class function



public ActionResult GetAllBowlingScoreData(MemberScore recObj)
        {
            
            string Result = "SUCCESS";
            string Message;

            try
            {
                List<MemberScore> mySessionData = Session["MySession"] as List<MemberScore>;
             

                ValidationResponse response = ValidateMemberScore(recObj);
                if (response.isValid)
                {
                    if(mySessionData==null)
                    {
                        mySessionData = new List<MemberScore>();
                    }
                    mySessionData.Add(recObj);
                    Session["MySession"] = mySessionData;

                    Message = "Validated Memeber";

                    //do something if its valid
                    return Json(CommonUtil.MapJSON(CommonUtil.Serialize(mySessionData), Result, Message));
                }
                else
                {
                    Session["MySession"] = null;
                    Result = "FAIL";
                    Message = response.message;

                    return Json(CommonUtil.MapJSON(null, Result, Message), JsonRequestBehavior.AllowGet);
                }



            }
            catch (Exception ex)
            {
                LogError(ex);
            }
            return Json(null, JsonRequestBehavior.AllowGet);
        }

Here is the view

 
<div class="row wrapper border-bottom white-bg page-heading marginRow">
    <div class="col-lg-11 marginRow">
        <h2>Bowling Score Management</h2>
    </div>
</div>

<div class="row wrapper wrapper-content" style="padding-bottom:0px">
    <div class="ibox float-e-margins collapsed">
        <div class="ibox-title ">
            <div class="collapse-link" style="cursor:pointer;display:inline-block;margin:0px">
                <h5>Filter</h5>
            </div>
            <div class="ibox-tools" style="display:inline-block;float:right">
                <a class="collapse-link">
                    <i class="fa fa-chevron-up"></i>
                </a>
            </div>
        </div>
        <div class="ibox-content">
            @*@Html.AntiForgeryToken()*@
            <form id="BowlingManagementFilterForm" autocomplete="on">

                <div class="row marginRow">
                    <div class="form-group col-sm-4">
                        <label>Member</label>
                        <div>
                            <input type="text" class="form-control marginRow dp" id="MEMBER_NAME" name="MEMBER">
                        </div>
                    </div>
                    <div class="form-group col-md-4">
                        <label>Games Played</label>
                        <div>
                            <input type="number" class="form-control marginRow dp MEMBER_NAME" id="GAMES_PLAYED" name="GAMES_PLAYED">
                        </div>
                    </div>
                </div>
                <div class="row marginRow">
                    <div class="form-group col-md-4">
                        <label>Max Score</label>
                        <div>
                            <input type="number" class="form-control marginRow dp" id="MAX_SCORE" name="MAX_SCORE">
                        </div>
                    </div>
                    <div class="form-group col-md-4">
                        <label>Total Score</label>
                        <div>
                            <input type="text" class="form-control marginRow dp" id="TOTAL_SCORE" name="TOTAL_SCORE">
                        </div>
                    </div>
                    <div class="form-group col-md-4">
                        <label>Average Score</label>
                        <div>
                            <input type="text" class="form-control allow-numeric" id="AVERAGE_SCORE" name="AVERAGE_SCORE">
                        </div>
                    </div>
                </div>
            </form>

            <div class="row marginRow">
                <div class="col-md-12 ">
                    <button class="btn btn-primary btn-sm" onclick="FilterGrid()">Search</button>
                    <button class="btn btn-danger btn-sm" onclick="ClearFilterandGrid()">Clear</button>
                </div>
            </div>

        </div>




    </div>


    




</div>


   <script>
        $(document).ready(function () {
            //     alert("Welcome");

        });

        function FilterGrid() {
            //alert($('#BowlingManagementFilterForm').serialize());

            $.ajax({
                url: appPath + '/Core/CommonServices/GetAllBowlingScoreData',
                method: 'post',
                type: 'json',
                data: $("#BowlingManagementFilterForm").serialize(),
                success: function (output, result, message) {
                    
                    if (output.result == "SUCCESS") {
                        
                        var AddedData = JSON.parse(output.data);

                       
                     

                        //loop json list
                        //create html tabel from javascript/jquery 
                        //apped tr from jqeuery 

                        //-----
                        //loop json list
                        //append tr from jqeuery 
                        // ID #


                        // append a html tag  to div tag/





                    }
                    else {
                        alert(output.message);
                    }
                }
            });


        }

        function ClearFilterandGrid() {
            alert("Clear Clicked");
        }

    </script>

the data is already loaded to the AddedData variable. it would be a great help if anyone can help me how to do this. thanks!!

i tried to add this to the script but it did not work.


    <script>
        $(document).ready(function () {
            //     alert("Welcome");

        });

        function FilterGrid() {
            //alert($('#BowlingManagementFilterForm').serialize());

            $.ajax({
                url: appPath + '/Core/CommonServices/GetAllBowlingScoreData',
                method: 'post',
                type: 'json',
                data: $("#BowlingManagementFilterForm").serialize(),
                success: function (output, result, message) {
                    
                    if (output.result == "SUCCESS") {
                        
                        var AddedData = JSON.parse(output.data);

                        var table = $('<table>'); // Create a new table element

                        // Create table header
                        var thead = $('<thead>').appendTo(table);
                        var headerRow = $('<tr>').appendTo(thead);

                        // Customize table headers
                        $('<th>').text('Member').appendTo(headerRow);
                        $('<th>').text('Games Played').appendTo(headerRow);
                        $('<th>').text('Max Score').appendTo(headerRow);
                        $('<th>').text('Total Score').appendTo(headerRow);
                        $('<th>').text('Average Score').appendTo(headerRow);

                        // Create table body
                        var tbody = $('<tbody>').appendTo(table);
                        AddedData.forEach(function (data) {
                            var row = $('<tr>').appendTo(tbody);

                            // Customize table cells
                            $('<td>').text(data.Member).appendTo(row);
                            $('<td>').text(data["Games Played"]).appendTo(row);
                            $('<td>').text(data["Max Score"]).appendTo(row);
                            $('<td>').text(data["Total Score"]).appendTo(row);
                            $('<td>').text(data["Average Score"]).appendTo(row);
                        });


                        // Append the table to a div tag or any other container element
                        $('#ibox-content').empty().append(table);


                     

                        //loop json list
                        //create html tabel from javascript/jquery 
                        //apped tr from jqeuery 

                        


                    





                    }
                    else {
                        alert(output.message);
                    }
                }
            });


        }

        function ClearFilterandGrid() {
            alert("Clear Clicked");
        }

    </script>

Web scraping a tourism website that contains next button with embedded java script instead of the next page id [closed]

I’m facing a problem where the website that I want to scrape is using a dropdown list, and previous and next buttons to navigate through the pages. The previous and next buttons is using Javascript to go to different pages instead of using page=1, how do I solve this?

I tried this:

for k in range(1,30):
  url = f"https://www.matta.org.my/memberspage={k}"

but since the website uses javascript instead of page=1, it only shows the first page 🙁

below are the codes for the buttons-

previous button:

<a id="body_uc_page_btn_prev" class="button input-group-button" href="javascript:__doPostBack('ctl00$body$uc_page$btn_prev','')">Prev</a>

next button:

<a id="body_uc_page_btn_next" class="button input-group-button" href="javascript:__doPostBack('ctl00$body$uc_page$btn_next','')">Next</a>

iFrame doesn’t load when booking

I’m a newbie and not totally a tech guy… wanted to ask why my iframe doesn’t work. It doesn’t load when I tried to book a flight

here’s my code below

hope you can share a fix for this code in order to work

I tried to book and doesn’t pushing trough. It’s already displaying white screen when I searched and chose my flight date.

Unable to return values from an async function running on items in an Array

I have a private async function, _getAssignment, which retrieves data for one id. I also have a public getAssignments function that accepts a list of ids, and ideally does a Promise.all to retrieve the data for all the given ids. However, when calling this function, the Promise.all statement always returns an array that is initially length 0, but is filled in later (similar to this). This is an issue because it prevents me from accessing that data, despite it showing up in the console. The functions are defined as follows:

private async _getAssignment(id: string): Promise<IData | undefined> {
  // retrieve data from firebase
  return {
    id,
    ...docData
  } as IData;
}
public async getAssignments(ids: string[]): Promise<(IData | undefined)[]> {
  // When I add a console.log inside the map's function, it displays the data correctly.
  return await Promise.all(ids.map(async (id) => await this._getAssignments(id));
}

const assignmentInfo = await getAssignments(['id1', 'id2']);

Both of these functions work perfectly fine when I modify the public getAssignment to just execute on one id rather than an array of ids. I am familiar with javascript, however I’ve never had to mess with promises deeper than using async / await so I’m curious as to what I’m missing here.

I have tried using a .then() block to capture the responses, I have tried making the public function not async, and I have tried making the list of promises separately, then using Promise.all to resolve them. Same outcome, an empty array that gets populated later (according to the browser console).
Odd state of the returned array

I have also tried replacing the Promise.all/map solution with a for…of loop that resolves each promise and adds the results to an array, however the array never ends up populated.

let test1: any = []
for (const id of administrationIds) {
  const result = await this._getAssignment(id).then((result) => {
  console.log('resolution', result) // Correct data is printed
  test1.push(result)
  console.log('test1 is now', test1) // Similar outcome to what I have seen with the map.
 })
}

Why does only one of my videos play on hover with UseRef?

I have a row of thumbnails that are supposed to play a video when I hover over them, and stop when I mouse out of the thumbnail. As of right now, only the last thumbnail plays it’s video when I hover, all the other ones are frozen. But if I hover over one of the frozen videos, then back to the working video, the working video will have moved forward as if I was hovering over it the whole time.

This is my component

import React from 'react'
import { projectlist } from '../../projectlist'
import { useRef } from 'react'
import './Projects.css'

export default function Projects() {
  const playerRef = useRef<any>()

  function onMouseOver(){
    console.log('playerRef',playerRef)
    playerRef.current.play();
  }

  function onMouseOut(){
    playerRef.current.pause();
  }

  return (
    <div className='projects-container'>

      {projectlist.map((video)=>{
        return(
          <div className='project-image' key={video.video_id} onMouseOver={onMouseOver} onMouseOut={onMouseOut}>
            <video ref={playerRef} muted loop>
              <source src={video.test} type='video/mp4' />
            </video>
            <img src={video.image}/>
          </div>
        )
      })}

    </div>
  )
}

Here is the CSS incase it is relevant

.project-image{
    position: relative;

    img{
        position: relative;
        width: 100%;
        height: 100%;
        z-index: 1;
    }
    
    video{
        position: absolute;
        opacity: 0;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        object-fit: cover;
        z-index: 0;
    }

    &:hover{
        video{
            z-index: 2;
            opacity: 1;
        }
    }
}

I used this video as a reference: https://www.youtube.com/watch?v=UIX0DSaNOjI&ab_channel=ColbyFayock around the 15:30 mark is where I followed the useRef guide.