Realtime ping in flask

Is there any simple way to ping an IP from server, and display realtime console response (every response pack) in browser using flask?

The only idea I see is to ping by 1 package, store it to buffer and take by ajax. But it seems to heavy.

(May be sockets could help, but I’m scared of them, and not shure that I can inject them into, and deal with it easily.)

Set popover in gauge needles (Echarts)

I have this code, where I tried to hover over the first gauge needle to get a .popover({…}) object:

 <head>
      <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/5.3.0/echarts.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
      <title>Gauge Chart</title>
    </head>
    
    <button id='btn1'>
      Let's
    </button>
    
    <input id='slider1' type='range' value='34' min='0' max='100' step='.01'>
    <input id='slider2' type='range' value='89' min='0' max='100' step='.01'>
    
          <div id='chartid1' style='width:390px; height: 410px;'></div>
          
    <script>
      const chart1 = echarts.init(document.getElementById('chartid1'));
    
      function update1(value1, value2) {
        option = {
          series: [{
            type: 'gauge',
            min: 0,
            max: 100,
            splitNumber: 10,
            detail: {
              fontFamily: 'Lato',
              fontSize: 14,
              borderWidth: 1,
              borderColor: '#020202',
              borderRadius: 5,
              width: 32,
              height: 20
            },
            data: [{
              value: value1,
              name: 'False',
              itemStyle: {
                color: '#dd4b50'
              },
              title: {
                offsetCenter: ['-20%', '20%']
              },
              detail: {
                offsetCenter: ['-20%', '36%'],
                backgroundColor: '#dd4b50',
                color: '#f2f2f2'
              }
            },
            {
              value: value2,
              name: 'True',
              itemStyle: {
                color: '#3a9e4b'
              },
              title: {
                offsetCenter: ['20%', '20%']
              },
              detail: {
                offsetCenter: ['20%', '36%'],
                color: '#f2f2f2',
                backgroundColor: '#3a9e4b'
              }
            }
            ]
          }]
        };
    
        chart1.setOption(option);
      }
    
      function update2() {
        let value1 = Number($('#slider1').val());
        let value2 = Number($("#slider2").val());
        update1(value1, value2);
      }
    
      update2();
    
      /// clickable
      chart1.on('mouseenter', {dataIndex:0}, function(params) {
        $(this).popover({
          html: true,
          sanitize: false,
          title: 'Title ',
          content: 'This a text',
          trigger: 'hover',
          placement: 'top',
          container: 'body'
        })
      })
    
    
    </script>

I need to hover and get a .popover. I know I could use tooltip:{...}, but for a specific case, I need to configure a .popover. I tried to adjust the code above with mychart1.on(... but it didn’t work. I added the CDN of all the code requirements.

How to lift state up with this particular example

I am trying to lift state up. I have four different components Parent, Child1, Child2 and Child3.

The parent component has a default value of ‘Hi’. The default value gets updated to ‘Hi2’ in Child3 component. I want Child1 component to get this updated state of ‘Hi2’ but it doesn’t get updated and still prints out the default value of ‘Hi’ in the console.

I am not sure what I did wrong?


import React, { useState } from 'react';
    
function Parent() {
  const [value, setValue] = useState('Hi');

  return (
    <div>
      <Child1 value={value} />
      <Child2 setValue={setValue} />
    </div>
  );
}

function Child1({value}) => {

  const fetchValue = () => {
    console.log('value is: ', value);
  }

  return (
    <div>
      <Text value={value}/>
    </div>
  );
}

function Child2({setValue}) => {

  return (
    <div>
      <Child3 setValue={setValue}/>
    </div>
  );
}

function Child3({setValue}) => {

  const fetchResults = () => {
    setValue('Hi2');
  }

  return (
    <div>
      <Button click={fetchResults }/>
    </div>
  );
}

Error fetching file content: RangeError: Maximum call stack size exceeded, when trying to get files from a link

In my extension, I’m trying to fetch file content from a list of links I have from the HTML of a website, which is updated on document change using an MutationObserver object.

I’m looking for getting the file content, from the link.

In small sized files my code works perfectly, but when i tried to fetch a PowerPoint file it crashed.

Instead, I’m getting this error : Error fetching file content: RangeError: Maximum call stack size exceeded.

// content.js :

const observer = new MutationObserver((mutations) => {
        mutations.forEach(async (mutation) => {
.
.
.
            let files = [];
            const fileLinks = document.getElementsByClassName("dO");

            if (fileLinks.length !== 0) {
                for (let i = 0; i < fileLinks.length; i++) {
                    const obj = {};
            
                    let subs = fileLinks[i].querySelectorAll('*');
                    obj.filename = subs[0].textContent;
                    obj.filetype = obj.filename.slice(obj.filename.lastIndexOf('.') + 1);
                    obj.size = subs[1].textContent;
            
                    try {
                        const response = await fetch(fileLinks[i].href);
            
                        if (!response.ok) {
                            obj.file_content = '';
                        } else {
                            const fileContent = await response.arrayBuffer();
                            obj.file_content = btoa(String.fromCharCode(...new Uint8Array(fileContent)));
                        }
                    } catch (error) {
                        console.error('Error fetching file content:', error);
                        obj.file_content = '';
                    }
            
                    console.log(obj.file_content);
                    files.push(obj);
                }
            
                data.files = files;
            }

showing error [symbol.iterator()] in ts generics in knex query

const [user]: T = await db("users").select("*").returning("*");
// error:Type 'T' must have a '[Symbol.iterator]()' method that returns an iterator.

My knex query typescript giving me error when i tried brackets in knex query to return single object from array.Can someone help me understand to why it is showing me this error even when i passed specific generic type and “user” variable is storing a single object as specified by type.Is there any go through from it, I also tried with .first() instead of square brackets but it shows a different error then.

const user: T = await db("users").select("*").first().returning("*");

//error: Type 'any[]' is not assignable to type 'T'.
//  'T' could be instantiated with an arbitrary type which could be unrelated to 'any[]'.

Pie chart not rendering in React using Chart

I am facing an issue with rendering a pie chart in a React component using the react-chartjs-2 library along with Chart.js. The data for the chart is fetched from an API, and the chart is expected to render once the data is available. However, despite the data being fetched successfully, the pie chart is not rendering on the screen.

// Dashboard.js
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { useUser } from '../UserContext';
import { AppBar, Toolbar, Typography, Container, Box } from '@mui/material';
import { Chart as ChartJS, ArcElement, Tooltip, Legend } from "chart.js";
import { Pie } from 'react-chartjs-2';
ChartJS.register(ArcElement, Tooltip, Legend);
const Dashboard = () => {
  const { userData } = useUser();
  const [genderCount, setGenderCount] = useState([]);
  const [loading, setLoading] = useState(true);
  let maleCount = 0;
  let femaleCount = 0;

  useEffect(() => {
    axios
      .get('https://randomuser.me/api/?results=10')
      .then(response => {
        const users = response.data.results;
        console.log(users)
        // Iterate over the users to count genders
        users.forEach(user => {
          if (user.gender === 'male') {
            maleCount++;
          } else if (user.gender === 'female') {
            femaleCount++;
          }
        });

        // Update the state with gender count
        // setGenderCount([
        //   { gender: 'male', count: maleCount },
        //   { gender: 'female', count: femaleCount }
        // ]);
        setLoading(false);
        console.log('male',maleCount)
        console.log('female',femaleCount)

      })
      .catch(error => {
        console.error('Error fetching data:', error);
        setLoading(false);
      });
  }, []);

  // Extract data for the pie chart
 const data = {
    labels: ['Male', 'Female'],
    datasets: [
      {
        label: '# of Votes',
        data: [maleCount,femaleCount],
        backgroundColor: [
          'rgba(255, 99, 132, 0.2)',
          'rgba(54, 162, 235, 0.2)',
        ],
        borderColor: [
          'rgba(255, 99, 132, 1)',
          'rgba(54, 162, 235, 1)',

        ],
        borderWidth: 1,
      },
    ],
  };

  return (
    <Container>
      <AppBar position="fixed">
        <Toolbar>
          <Box sx={{ flexGrow: 1 }}>
            <Typography variant="h6" component="div">
              Your Logo
            </Typography>
          </Box>
          <Typography variant="h6" component="div">
            {userData && `Welcome, ${userData.username}!`}
          </Typography>
        </Toolbar>
      </AppBar>

      <Box sx={{ marginTop: '4rem', width: '80%', margin: 'auto' }}>
        <h2>Dashboard</h2>
        {  (
          <div>
            {/* Display other user information */}
            
            {/* Conditionally render pie chart when data is available */}
            {loading ? (
              <p>Loading...</p>
            ) : (
              <div>
                <h3>Gender Counts</h3>
                <Pie data={data}/>
              </div>
            )}
          </div>
        )}
      </Box>
    </Container>
  );
};

export default Dashboard;

Issue Details:

Verified that the data is being fetched correctly.
The loading state is set to false when the data is available.
Using the Pie component from the react-chartjs-2 library.
Set width and height for the chart.

Problem Details:
The pie chart doesn’t appear on the screen even after ensuring that the data is fetched and the loading state is set to false. I’ve also tried adjusting the width and height of the chart, but it doesn’t seem to resolve the issue.

Question:
I would appreciate any insights or suggestions on why the pie chart is not rendering as expected. Are there any potential issues with my code that I might have overlooked?

Thank you for your help!

Javascript add parameter if “ccm_order_by_direction=desc” is in the URL

I am trying to find a way to add &amp;#filterTop to the end of the URL if ccm_order_by_direction=desc is in the URL.

I assume JavaScript would be the easiest, but if there is a PHP way that would work too.

The catch is that it would have to update the existing page link. The links are created in the backend and I can not edit them directly. I know I did something like this before, I can not remember how or where the info would be.

I got this far. I just don’t know where to go next.

$(document).ready(function() {
  if (window.location.href.indexOf('ccm_order_by_direction=desc') !== -1) {
    let url = '<?= $actual_link ?>';
    url = url.replace('ccm_order_by_direction=desc', 'ccm_order_by_direction=desc&amp;#filterTop');
    var link = document.getElementsByClassName('.page-link');
    link.href = url;
  }
});

The links that needs updated look like this.

<li class="page-item">
  <a class="page-link" href="/switches-damper-arm-tilt-tip-over-limit?ccm_paging_p=2&amp;ccm_order_by=popular&amp;ccm_order_by_direction=desc">2</a>
</li>

I would like them to look like.

<li class="page-item">
  <a class="page-link" href="/switches-damper-arm-tilt-tip-over-limit?ccm_paging_p=2&amp;ccm_order_by=popular&amp;ccm_order_by_direction=desc&amp;#filterTop">2</a>
</li>

Mobile display differ from french to english version

i have a problem with a WordPress site. We are using the Age Gate pluggin to manage user from under a certain age to access our content because we are a Cannabis producer so, by the law, are obligated to block the content to user under 21.

where my problem happens is when i open the site on a mobile device (french version opens by default) on the french mobile age gate, the display shows as this FR mobile age gate whereas on the english mobile age gate it shows perfectly like this.EN mobile age gate

what i did is open the chrome inspector of my mobile tab from my desktop and inspected each element until i found it…offset

the damn vh-offset at -565px ? on the EN version it set at 56px. i have nowhere where i can set this and according to the chrome developper tool it is inherited from html.age-gate__restricted.age-gate__restricted.js which i have no idea where it is.

so in recap
wordpress site powered with elementor using the Age Gate pluggin

do you know where or how i can customize / edit this –vh-offset setting so it is identical on both FR and EN mobile display ?

thank you

Juice-shop Dockerfile

in https://github.com/juice-shop/juice-shop,

What is wrong with this Dockerfile , and what are the missing stuffs?
, and what are the best practices?

and is there any web site to learning and training Dockerfile writing?

FROM node:20-buster as installer
COPY . /juice-shop
WORKDIR /juice-shop
RUN npm i -g typescript ts-node
RUN npm install --omit=dev --unsafe-perm
RUN npm dedupe
RUN rm -rf frontend/node_modules
RUN rm -rf frontend/.angular
RUN rm -rf frontend/src/assets
RUN mkdir logs
RUN chown -R 65532 logs
RUN chgrp -R 0 ftp/ frontend/dist/ logs/ data/ i18n/
RUN chmod -R g=u ftp/ frontend/dist/ logs/ data/ i18n/
RUN rm data/chatbot/botDefaultTrainingData.json || true
RUN rm ftp/legal.md || true
RUN rm i18n/*.json || true

ARG CYCLONEDX_NPM_VERSION=latest
RUN npm install -g @cyclonedx/cyclonedx-npm@$CYCLONEDX_NPM_VERSION
RUN npm run sbom

# workaround for libxmljs startup error
FROM node:20-buster as libxmljs-builder
WORKDIR /juice-shop
RUN apt-get update && apt-get install -y build-essential python3
COPY --from=installer /juice-shop/node_modules ./node_modules
RUN rm -rf node_modules/libxmljs2/build && 
  cd node_modules/libxmljs2 && 
  npm run build

FROM gcr.io/distroless/nodejs20-debian11
ARG BUILD_DATE
ARG VCS_REF
LABEL maintainer="Bjoern Kimminich <[email protected]>" 
    org.opencontainers.image.title="OWASP Juice Shop" 
    org.opencontainers.image.description="Probably the most modern and sophisticated insecure web application" 
    org.opencontainers.image.authors="Bjoern Kimminich <[email protected]>" 
    org.opencontainers.image.vendor="Open Web Application Security Project" 
    org.opencontainers.image.documentation="https://help.owasp-juice.shop" 
    org.opencontainers.image.licenses="MIT" 
    org.opencontainers.image.version="16.0.0" 
    org.opencontainers.image.url="https://owasp-juice.shop" 
    org.opencontainers.image.source="https://github.com/juice-shop/juice-shop" 
    org.opencontainers.image.revision=$VCS_REF 
    org.opencontainers.image.created=$BUILD_DATE
WORKDIR /juice-shop
COPY --from=installer --chown=65532:0 /juice-shop .
COPY --chown=65532:0 --from=libxmljs-builder /juice-shop/node_modules/libxmljs2 ./node_modules/libxmljs2
USER 65532
EXPOSE 3000
CMD ["/juice-shop/build/app.js"]

How Can I add an Event that play the keys according with the keyboard in JavaScript?

I need to play a drum according to the key pressed on my keyboard. The only things that I’ve done is make it play when I click with the mouse.

I tried to add the function that plays the sounds of the drum according with to key of the keyboard, but I didn’t manage it.

function playKey(idKey) {
  const element = document.querySelector(idKey);
  if (element) {
    element.play();
  } else {
    console.error('element nof found')
  }
}

const btns = document.querySelectorAll('.btn')
for (i = 0; i < btns.length; i++) {
  const key = btns[i];
  const keyCode = key.classList[1];
  const idKey = `#btn-${keyCode}`;

  key.onclick = function() {
    playKey(idKey);
  }
}

Add a variable from array of objects and combine them

I want to add a variable from array of objects and combine them.

Example data :

    const item = [{
                "act": "Q",
                "line": 1,
                "qty": 6,
                "type": 00
},
{
                "act": "Q",
                "line": 1,
                "qty": 6,
                "type": 00
},
{
                "act": "Q",
                "line": 2,
                "qty": 6,
                "type": 00
},
{
                "act": "Q",
                "line": 2,
                "qty": 4,
                "type": 00
}]

I want to check if act is Q and type is 00 then get the output with line and sum of qty for the line.

    [{
                "line": 1,
                "qty": 12,
},
{
                "line": 2,
                "qty": 10,
}]

running node filename with typescript files gives module not found error

I have file1.js which imports file2.ts. But when I run node file1.js I get an error

Cannot find module “/path to file2” imported in “file1”

I have even tried converting file1.js to file1.ts, but then I get –

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension “.ts”

This is my tsconfig.json –

{
"compilerOptions": {
    "target": "ES2020",
    "useDefineForClassFields": true,
    "module": "ESNext",
    "lib": ["ES2020", "DOM", "DOM.Iterable"],
    "skipLibCheck": true,

    /* Bundler mode */
    "moduleResolution": "bundler",
    "allowImportingTsExtensions": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "preserve",
    "jsxImportSource": "solid-js",

    /* Linting */
    "strict": true,
    "allowJs": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noFallthroughCasesInSwitch": true,
    "baseUrl": "src"
},
"include": ["src"],
"references": [{ "path": "./tsconfig.node.json" }]
}

I have even tried adding esm:true to the tsconfig, but still no solution-

 "ts-node": {
    "esm": true
  }

Please help find a solution.

How do you set a JavaScript variable when a link is clicked (to open a specific part of a popup)

I’m trying to make a link that shows a glossary popup when you click it. It should run a script that changes the variable “WordId” to the html element id of the heading that corresponds to the definition of the word.

I tried this:

<a onclick="BrowserPopupGlossary()" onclick="WordId = "...";">...</a>

This is the BrowserPopupGlossary function:

var WordId;
function BrowserPopupGlossary() {
    window.open('glossary.html'+'#'+WordId,'popUpWindow','height=500,width=400')
}

Any advice on how to optimize / fix this?