Javscript proxy not transparent in Chrome

A common trick sites use to protect against reverse engineering is to prevent Javascript from executing correctly when the developer tools are open. Usually, this relies on an object logged to the console with a getter or custom toString function that only gets called when the console is visible. A simple workaround is to proxy console.* functions and discard offending objects.

I recently stumbled across a site that is a bit more difficult – it detects if you’ve proxied or otherwise messed around with native functions. Unfortunately, the site’s scripts are heavily obfuscated, so I haven’t been able to determine the exact method they use. However, the following seems to be a reliable way to determine if a native function is proxied in Chrome:

function isProxied(func) {
  return func.toString().length === 29;
}

console.log(isProxied(eval));

eval = new Proxy(eval, {});

console.log(isProxied(eval));

How can I make a proxied object appear identical to its target?

Loading module from “http://URL/main.js” was blocked because of a disallowed MIME type (“text/html”)

I configured redirect on nginx in location block in server block. When i open URL page (javascript) i receive error:

Loading module from “http://URL/main.js” was blocked because of a disallowed MIME type (“text/html”).

In my server block and nginx.conf I have lines:

include       /etc/nginx/mime.types;

In mime.types file I have line:

application/javascript   js;

How to solve this issue?

Safari download csv file is not working properly, windows.open(url,_blank)

In Safari browser, when try to download file with windwo.open() or just creating a link (a tag) then click on it doesn’t download to file rather than open file in new tab.

1.

window.open(url, '_blank')

2

let a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
a.href = <your_url>;
a.download = <your_fileName>;
a.click();
document.body.removeChild(a);```

3. setTimeout

Expected should be like chrome open new tab and download it

how get BackHandler event while keyboard is open in react native

I am working on a chat app, in which I want that, when user click on android default back button it should close the keyboard and also Goback in navigation.

I know I can capture the keyboard close event but I am using that event for opening the emoji picker, so I can not use keyboard dissmiss event

and the main issue is when keyboard is open and Back button pressed it only closes the keyboard and does not fire event in BackHandler. if keyboard is close then it works fine..

const backHandler = BackHandler.addEventListener(
      'hardwareBackPress',
      backAction,
    );

How do I convert the local date and time (e.g. EST) to UTC?

I’m experimenting with Javascript, and wanted to try out converting a date and time that is indicating when the post was posted (such as a social media site), which is the local time zone (so if my system is EST, the page will show it as EST). I would like to have JS to also know what time zone my PC is at, then take the shown post date (assume its post date is the same as my PC), and convert it to UTC. I understand toISOString, the milliseconds since the epoch work. But how do I convert a local date and time displayed on a webpage to UTC?

Here’s an example: https://bsky.app/profile/kimscaravelli.bsky.social/post/3klaue65stp2x

The post date from my PC at my time zone says in EST – “Feb 12, 2024 at 5:12 PM”. However it may be different when you guys view the post date. I’m also aware of the daylight savings time does effect several time zones, but UTC and the milliseconds since the epoch are unaffected. I do not want to manually have to set my PC or website settings to make the site display the UTC time, instead I wanted JS code that regardless of what time zone you are in, a post that displays a date locally, it will always display the same UTC time.

React Chartjs not showing with dynamic values

I am using chartjs library to show charts in my application. I am using chart in a separate component. The component is showing the chart when the values are hard coded. I want to pass the values from other components and use the same chart in different other components. The chart is not showing with dynamic values.

const DoughnutChart = (props) => {
  const chartRef = useRef(null);

  const [wrong] = useState(props.wrong);
  const [right] = useState(props.right);

  useEffect(() => {
    const data = {
      datasets: [{
        label: 'Result',
        data: [wrong,right],
        backgroundColor: [
          'rgb(255, 0, 0)',
          'rgb(0, 255, 0)',
        ],
      }]
    };

    // Options for the chart
    const options = {
      plugins: {
        title: {
          display: true,
          text: 'Exam Result'
        }
      }
    };

    // Create the chart instance
    const myChart = new Chart(chartRef.current, {
      type: 'doughnut',
      data: data,
      options: options
    });

    // Clean up function to destroy the chart when component unmounts
    return () => myChart.destroy();
  }, []);

  return (
    <div style={{width:300}}>
      <canvas ref={chartRef}></canvas>
    </div>
  );
};

export default DoughnutChart;

How to unit test azure durable function in javascript for v4?

how to write unit test case of this durable function. it is calling through app and df, so it does not have any function. how can i call the trigger and orchestrator? Here is my code

const { app } = require('@azure/functions');
const df = require('durable-functions');

const { autoDeleteBackUpActivity, autoDeleteBackUpDeterminer } = require('../activity/autoDeleteBackUpActivity');

df.app.orchestration('AutoDeleteBackupOrchestrator', function* (context) {
  const backupDatabasesToBeRemoved = yield context.df.callActivity('AutoDeleteBackUpDeterminer');

  const parallelTasks = [];
  for (const backupDatabase of backupDatabasesToBeRemoved) {
    parallelTasks.push(
      context.df.callActivity(
        'AutoDeleteBackUpActivity',
        backupDatabase
      )
    );
  }
  if (parallelTasks.length > 0) {
    yield context.df.Task.all(parallelTasks);
  }
});

df.app.activity('AutoDeleteBackUpDeterminer', {
  handler: autoDeleteBackUpDeterminer
});

df.app.activity('AutoDeleteBackUpActivity', {
  handler: autoDeleteBackUpActivity
});

app.timer('AutoDeleteBackupTimerTrigger', {
  schedule: '0 0 2 * * *',
  extraInputs: [df.input.durableClient()],
  handler: async (myTimer, context) => {
    const client = df.getClient(context);
    const instanceId = await client.startNew('AutoDeleteBackupOrchestrator');
    context.log('[Auto-Delete-Backup]: Started orchestration with ID: ', instanceId);
  }
});

is there any testing util is available for v4 javascript durable function? how we can write unit test case of these code.

How can I convert a DOCX file into a PDF file using any programming language? [closed]

I would like to add the “Save as PDF” and “Print” features to my desktop Electron-based application. That’s why I am looking for a solution that will allow me to convert DOCX files to PDF. A solution written in any language would work for me, as I plan to package this solution into an executable file and include it in my application.

However, there are some restrictions:

  1. The solution should only use open-source libraries.
  2. The solution should be able to work offline, as sending requests to external services is not an option.
  3. The solution should work on multiple platforms, including Windows, Mac, and Linux.
  4. Converting to HTML (or other formats) is not an option. The PDF file should be very similar to the original.
  5. The solution should not rely on LibreOffice (or any other similar software), as it is heavy, making it impossible to install it on users’ computers.

I have tried many different libraries and solutions for different programming languages, but none of them meet my needs. If anyone has any suggestions or advice, I would greatly appreciate it.

Disable ASP.NET Core hot reload script from frontend

Sometimes I make changes in my IDE and don’t want the page to be reloaded in the browser after I save. A typical scenario is that I make changes to the page via the devtools, and if the page is reloaded then those changes would be lost; or perhaps I’m interacting with some remote API and don’t want to lose such state.

There are ways to disable hot reload, but that’s not what I want – I want to keep using it, but to disable it per page, on demand, from the frontend itself (by somehow overriding the script). For example, I want to inject a floating button into the page with a script that disables hot reload.

The _framework/aspnetcore-browser-refresh.js script is here.

The obvious solution is to clear the script’s timeout, but it uses setTimeout without saving the id.

I tried this without success:

window['_dotnet_watch_ws_injected'] = 1;

What else could I try?

Can someone help me an tell me how to approach the problem

Description

Let’s call a sequence of brackets balanced if :

Starts with an opening bracket

Ends with a closing bracket

At any point the number of closing brackets does not exceed the number of opening brackets.

The number of opening bracket is same as the number of closing bracket.

We call a balanced sequence of brackets n-balanced if there are n consecutive opening brackets followed by n closing brackets.

From the string n-balanced substrings are removed and the substring to the left and right of the deleted substring is concatenated.

You need to repeatedly remove n-balanced substrings until no more n-balanced substrings exist.

Input
Input Format
The input consists of multiple testcases.

The first line contains an integer t – the number of testcases.

The next 2*t lines contains the description of the t testcases.

The first line of each testcase contains a string s – the sequence of brackets.

The second line of each testcase contains the integer n.

Constraints
1 ≤ t ≤ 10^3

1 ≤ |s| ≤ 10^4

1 ≤ n ≤ 10^2

Output
Output Format
For each testcase print the remaining string after performing all the removals, or -1 if the string becomes empty.

Sample Input
3
((())())()
2
((()))
3
))((
2
Sample Output
()

))((

function main(str, n){
let stk = [], s1 = 0, res = [], i = 0;

for(i=0;i<str.length;i++){
    if(str[i] == "("){
        stk.push(str[i]);
        res.push(str[i])
    }else if(str[i] == ")"){
        if(stk.length > 0 && stk[stk.length-1] == "("){
            res.push(str[i])
            stk.pop();
            s1++;
        }else{
            stk.push(str[i]);
            res.push(str[i])
        }
    }
    
    if(s1 == n){
        let temp = [];

        for(let j=0;j<res.length;j++){
            if(j >= (res.length-(s1*n)) && j <= res.length){
                continue;
            }else{
                temp.push(res[j])
            }
        }
        res = temp;

        s1 = 0;
    }
}

if(s1 == n){
    let temp = [];
    
    for(let j=0;j<res.length;j++){
        if(j >= (res.length-(s1*n)) && j <= res.length){
            continue;
        }else{
            temp.push(res[j])
        }
    }
    res = temp;
    
}

if(stk.length == 0){
    if(res.length == 0){
        console.log(-1)
    }else{
        console.log(res.join(""));
    }
}else{
    console.log(stk.join(""));
}

}

Trouble achieving spacing between stacked bar charts in React with Recharts

I am able to develop the stacked bar chart but I am not sure how to leave a 10px space between two vertical stacked bar charts.
I gave the barGap={8880} and barCategoryGap={100} but still no luck.
Providing the code and stackblitz below. Can you let me know how to fix it.

https://stackblitz.com/edit/react-zta9v9?file=src%2FApp.js,src%2Fstyle.css

import './style.css';
import React from 'react';
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
} from 'recharts';

const data = [
  {
    name: 'Page A',
    uv: 4000,
    pv: 400,
    amt: 2400,
  },
  {
    name: 'Page B',
    uv: 3000,
    pv: 1398,
    amt: 2210,
  },
  {
    name: 'Page C',
    uv: 2000,
    pv: 9800,
    amt: 2290,
  },
  {
    name: 'Page D',
    uv: 2780,
    pv: 3908,
    amt: 2000,
  },
  {
    name: 'Page E',
    uv: 1890,
    pv: 4800,
    amt: 2181,
  },
  {
    name: 'Page F',
    uv: 2390,
    pv: 3800,
    amt: 2500,
  },
  {
    name: 'Page G',
    uv: 3490,
    pv: 4300,
    amt: 2100,
  },
];

export default function App() {
  return (
    <BarChart
      width={500}
      height={300}
      data={data}
      margin={{ top: 5, right: 50, bottom: 5, left: 50 }}
    >
      <CartesianGrid strokeDasharray="3 3" />
      <XAxis dataKey="name" />
      <YAxis />
      <Tooltip />
      <Legend />
      <Bar
        dataKey="pv"
        stackId="a"
        fill="#8884d8"
        radius={[100, 100, 100, 100]}
        barGap={8880}
        barCategoryGap={100}
      />
      <Bar
        dataKey="uv"
        stackId="a"
        fill="#82ca9d"
        radius={[100, 100, 100, 100]}
        barGap={8880}
        barCategoryGap={100}
      />
    </BarChart>
  );
}

what does these characters mean inside the replace method – elDocument.className = elDocument.className.replace(/(^|s)no-js(s|$)/, ‘$1’);

im sorry for this newbie question. I tried to google but couldn’t an answer on what are the characters inside the .replace method.

here’s the HTML

then in javascript I saw these characters in the replace method.

elDocument.className = elDocument.className.replace(/(^|s)no-js(s|$)/, ‘$1’);

would you be able to share what does this mean /(^|s) and (s|$)/ ?

Thanks in advance!

would you be able to share what does this mean /(^|s) and (s|$)/ ?

I got this error in my .get request using Angular

This is the error i got

HttpErrorResponse {headers: _HttpHeaders, status: 200, statusText: 'OK', url: 'http://localhost:4200/dc-batman', ok: false, …}
error
: 
{error: SyntaxError: Unexpected token '<', "<!doctype "... is not valid JSON at JSON.parse (<anonymous>…, text: '<!doctype html>rn<html lang="en">rn<head>n  <scrip…ain.js" type="module">x3C/script></body>rn</html>rn'}
headers
: 
_HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message
: 
"Http failure during parsing for http://localhost:4200/dc-batman"
name
: 
"HttpErrorResponse"
ok
: 
false
status
: 
200
statusText
: 
"OK"
url
: 
"http://localhost:4200/dc-batman"
[[Prototype]]
: 
HttpResponseBase

I have my service where I make my .get

@Injectable()
export class HeroesService{

    urlHeroes: string = "http://localhost:3000/heroes";


    getInfoId(id:string): Observable<SearchHeroesResponse>{
        return this.http.get<SearchHeroesResponse>(id)
    }

    constructor(private http:HttpClient){}
}

and in my component where I subscribe the response

@Component({
  selector: 'app-heroe',
  templateUrl: './heroe.component.html',
})
export class HeroeComponent {

    ngOnInit(){
        this.activatedRoute.params.pipe(switchMap(({id})=>this.http.getInfoId(id)))
        .subscribe(info => console.log(info));
    }

  constructor(private http: HeroesService, private activatedRoute:ActivatedRoute){}

}

I’m using a JSON Server, where I have a localhost with this info (clipped information)

{
  "usuarios": [
    {
      "id": 1,
      "usuario": "John Doe",
      "email": "[email protected]"
    }
  ],
  "heroes": [
    {
      "id": "dc-batman",
      "superhero": "Batman",
      "publisher": "DC Comics",
      "alter_ego": "Bruce Wayne",
      "first_appearance": "Detective Comics #27",
      "characters": "Bruce Wayne"
    },
    {
      "id": "dc-flash",
      "superhero": "Flash",
      "publisher": "DC Comics",
      "alter_ego": "Jay Garrick",
      "first_appearance": "Flash Comics #1",
      "characters": "Jay Garrick, Barry Allen, Wally West, Bart Allen"
    }
  ]
}

I don’t know what to do, I have searched on internet and they say something about HTML and JSON compatibility, but I’m new at Angular and I’m following a course of it, so please be understandable.

If you want more information about what I wanna do, I click a button from each heroe that sends the id to the url with a routerLink:

<button mat-button color="warn" [routerLink]="['/heroes', heroe.id]">Read more</button>

I do get the id in url, indeed it shows the heroe name in console when executing this code:

ngOnInit(){
    this.activatedRoute.params.subscribe( ({id}) => console.log(id));
  }

Uncaught SqlError when saving in the DB (MariaDB)

MariaDB reports this error when that comes from edit/user/X HTML page

NodeJS: 21.6.2
MariaDB: 10.4
OS: Windows 11

"dependencies": {
        "body-parser": "^1.20.2",
        "ejs": "^3.1.9",
        "express": "^4.18.2",
        "mariadb": "^3.2.3",
        "path": "^0.12.7"
}

Error Code

Uncaught SqlError SqlError: (conn=114, no: 1064, SQLState: 42000) You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''{"first_name":"test","last_name":"test","email_address":"test",...' at line 1
sql: UPDATE user SET ? WHERE user_id = ? - parameters:[{"first_name":"test","last_name":"test","email_address":"test","telephone_number":"test","role_id":"1","house_number":"test","zip_code":"5000","town":"test","country":"test"},'2']

Formatted message of the error:

Uncaught SqlError SqlError: (conn=114, no: 1064, SQLState: 42000) You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 
sql: UPDATE user SET ? WHERE user_id = ? - parameters:
[
  {
    "first_name":"test",
    "last_name":"test",
    "email_address":"test",
    "telephone_number":"test",
    "role_id":"1",
    "house_number":"test",
    "zip_code":"5000",
    "town":"test",
    "country":"test"
  },
  '2'
]

JS Code

app.post('/edit/:user_id', (req, res) => {
    const userId = req.params.user_id;
    
    // Flatten the object before updating
    const updatedUser = {
      first_name: req.body.first_name,
      last_name: req.body.last_name,
      email_address: req.body.email_address,
      telephone_number: req.body.telephone_number,
      role_id: req.body.role_id,
      house_number: req.body.house_number,
      zip_code: req.body.zip_code,
      town: req.body.town,
      country: req.body.country,
      // Add other fields as needed
    };
  
    db.pool.query('UPDATE user SET ? WHERE user_id = ?', [updatedUser, userId], (error) => {
      if (error) throw error;
  
      // After updating, fetch the updated user data and render the edit page again
      db.pool.query('SELECT * FROM user WHERE user_id = ?', [userId], (err, result) => {
        if (err) throw err;
        res.render('edit', { user: result[0] });
      });
    });
  });

What is causing this error, I cannot find a fix or proper information that explains what I am doing wrong.

Cant get the state with useSelector but sometimes it appears and disappears without modifying anything how can i get the state (redux toolkit)

cartSlice.js

(https://i.stack.imgur.com/YG3JL.png)

store.js
(https://i.stack.imgur.com/b89BE.png)

Trying to select the cart state and cant get the cartItems
and i try other form to get the state like state.cart but the same result

(https://i.stack.imgur.com/jD8ae.png)

The result of the console.log

(https://i.stack.imgur.com/h9Nqh.png)

Can someone help me .

I try to get the state but can’t get any