Violating Content Secuirty Policy in Electron app using React and Webpack

I am currently making a small application that is trying to fetch data from an API. To begin, I used electron-forge’s webpack and react template to get started.

Without any CSP configuration in the meta tag of the HTML file, I get this error:

enter image description here

Added the following CSP to my main HTML file:

<meta
      charset="UTF-8"
      http-equiv="Content-Security-Policy"
      content="default-src 'self' 'unsafe-inline' data: https://api.flybywire.com/;"
    />

This results in this error with a blank page in the renderer (before, it displayed the rest of the page correctly).

enter image description here

If I add ‘unsafe-eval’ to the CSP, I get this.

enter image description here

The strange thing is it appears that there are two CSP policies going on here. I have made an electron app without WebPack before that fetched data online with no issue, and I am unfamiliar with it. I have a feeling the issue lies in there.

I’ve tried editing my webpack.renderer.config.js by adding devtool: "eval-source-map" under module.exports to no avail.

The source code is available under this github repository , however I haven’t pushed the version that calls the data fetching function which is located in metar.jsx.

Any help would be greatly appreciated as I have been scouring around for a fix for days now.

How do I return firestore result in svelte?

How do you get the result from this in svelte into the page:

async function getCities(db) {
  const citiesCol = collection(db, 'cities');
  const citySnapshot = await getDocs(citiesCol);
  const cityList = citySnapshot.docs.map(doc => doc.data());
  return cityList;
}

Simplest ways of getting CSV headers from URL

I’ve built a web-app that allows users to upload contacts using CSV files, and I’d like them to be able to map the CSV header fields to the app’s fields.

The issue I’m facing is that I’m trying to figure out an efficient and simple way to return a list of CSV headers from a CSV link, ideally as an HTTP request or using JavaScript.

For example, this is a CSV of hurricane counts:
https://people.sc.fsu.edu/~jburkardt/data/csv/hurricanes.csv

The headers are:

Month, "Average", "2005", "2006", "2007", "2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015"

I’ve had the idea to write a Python script that does this, then run it as an API using AWS Lambda.

Is there another way to get this done faster or without the setup?

Issue with equired with Page Object model design with Playwright test

Below is the code for the test file

const { test, expect } = require('@playwright/test')
const HomePage = require('./pageobejcts/HomePage')

test.beforeEach(async ({ page }) => {
    await page.goto("https://automationexercise.com/");
})

test('Navigate to Login', async ({ page }) => {

    let homepage = new HomePage(page);
    homepage.navigateToLoginSignUp();
    await expect(page.locator('//div[@class="signup-form"]/h2')).toBeVisible();
    await page.screenshot({ path: 'screenshot.png' });

    //await expect(page.locator('//img[@alt="Website for automation practice"]')).toBeVisible;

})

And below is code for one of the Screen class

class HomePage {
    constructor(page) {
        this.page = page;
        this.signupLnk = '//a[@href="/login"]';
    }

    async clickSignupLink() {

        await this.page.click(this.signupLnk);

    }

}
module.exports = HomePage;

Now the above code works fine. But in the Screen Class as there is not Page object defined, there is no auto complete/documentation available when using the Page methods.

eg On writing page.click(), the IDE does not recognise the click function and does not suggest the correct parameters

Is there a way to resolve this.

Drop down when select the option from ajax another input field appear

Hi i needed some help where if i select a drop down and select from ajax option and a hidden input field appear how can i do it ?

<div class="form-row">
  <div class="col">
    <label for="select-price-mode" class="col-form-label">Price Mode</label>
    <select class="select-price-mode custom-select-sm col-10" id="select-price-mode" required>
      <option selected disabled value="">Select ....</option>
    </select>

  </div>

  <div class="col" hidden>
    <label for="select-payment-frequency" class="col-form-label">Payment Frequency</label>
    <select class="select-payment-frequency custom-select-sm col-10" id="select-payment-frequency" required>
      <option selected disabled value="">Select ....</option>
    </select>
   
  </div>

This is my ajax

// Here the calling Ajax for the drop down menu below
    $.ajax({
    // The url that you're going to post
    /*

    This is the url that you're going to put to call the
    backend api,
    in this case, it's
    https://ecoexchange.dscloud.me:8080/api/get (production env)

    */
    url:"https://ecoexchange.dscloud.me:8090/api/get",
    // The HTTP method that you're planning to use
    // i.e. GET, POST, PUT, DELETE
    // In this case it's a get method, so we'll use GET
    method:"GET",
    // In this case, we are going to use headers as
    headers:{
        // The query you're planning to call
        // i.e. <query> can be UserGet(0), RecyclableGet(0), etc.
        query:"PriceModeGet()",
        // Gets the apikey from the sessionStorage
        apikey:sessionStorage.getItem("apikey")
    },
    success:function(data,textStatus,xhr) {
        console.log(data);
        for (let option of data) {
            $('#select-price-mode').append($('<option>', {
                value: option.PriceMode,
                text: option.PriceMode
            }));
        }
                                                    },
    error:function(xhr,textStatus,err) {
        console.log(err);
    }
});

and this is my ajax response

[
    {
        "PriceMode": "Price By Recyclables"
    },
    {
        "PriceMode": "Service Charger"
    }
]

Where say if i select Price By Recyclables the hidden drop down list appear how can i do it ?

How to properly load build folder in WordPress

I am trying to convert my html to WordPress.

I have two folders, one is build folder which consist of:

-index.css
-index.js
-index-style.css

Then on my other folder which called src:

-index.js
-modules folder
--HeroSlider.js
--GoogleMap.js

I tried to load the HeroSlider.js on my function.js file on my WordPress theme folder like this:

<?php 

function school_files(){
    wp_enqueue_script('main-school-js', get_theme_file_uri('/src/index.js'), NULL, '1.0', true);
    wp_enqueue_style('custom-google-font', '//fonts.googleapis.com/css?family=Roboto+Condensed:300,300i,400,400i,700,700i|Roboto:100,300,400,400i,700,700i"');
    wp_enqueue_style('font-awesome', '//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"');
    wp_enqueue_style('school_main_styles', get_stylesheet_uri());
}


add_action('wp_enqueue_scripts', 'school_files');

But this one did not load my Hero Slider file on my WordPress file. How do I load it so i can make sure the template works?

How do i make my music bot send embed from a function when song is played?

So I made music bot and I’m making it work on Discord js v13 and Distube v3(I have been using v12 before). Sadly there are many changes and some of them made me search for solution for hours. If you can help me with this one i may be able to fix the whole bot :D. So here’s the code:https://sourceb.in/BI41NrxFPH. When song is played i want my bot to send embed but it doesn’t send anything. I made lots of changes and got many results like

DiscordAPIError: Cannot send an empty message

but embed was never sent. If you need some information let me know.

Most optimal way to keep last N values

Currently i preparing for the algorithm interviews in IT companies. During problem solving I have met very common problem: I need to store last N elements as cache to be possible to use it by the constant address. It must take constant memory.

Example how it should work.

const arr = [] 
//limit must be 2
arr.push(1)
//[1]
arr.push(2)
//[1,2]
arr.push(3)
//[2,3]

Of course it’s possible to create dedicated function to implement this. But I’m trying to find the most elegant way to do it.

P.S. It’s not important which data structure will be used.

Cloning an image to avoid many HTTP requests. Best scenario for a chat widget/tab?

I’ve been trying to get an idea on how to go about my problem below. I couldn’t find much in the way already on stack so thought I’d ask. So here it goes!

I currently have a chat I am working on that has a slight issue each message acquires a new source for avatar leading to additional HTTP Requests. This is poor use in my eyes and the goals were to avoid this practice completely! No caching, just one fetch and re-use.

The chat messages are jammed into an array with inserted objects containing the avatar link and details of each message so the chat can be re-built when switching from public/private messages.


This is not overly an issue my code till there’s a 100 different avatars loaded in a chat and someone switches to private chat and back to public (for instance). Oddly 100 avatars will load if 1,000 or 100,000 messages instead of the message count.

If these are directly coming in as new messages the re-sourcing makes a new request. Making 1,000 of the messages 1,000 requests for avatar regardless. Not overly an issue but yikes won’t scale well… I need a better approach!


With all that said, I’d love for ideas on how to combat this and it not be overly stressing on client’s CPU or server’s.

Perhaps not possible but can a user XHR request the file and Base64 Encode it to keep forever as the new src file and avoid this?

Not sure of my options here but thanks again for any suggestions.

Modal scroll body don’t work after second calling ajax content

I have a modal in Boostrap 4. I put <div class="modal-dialog modal-lg modal-dialog-scrollable">

I don’t know why when I choose from dropdown second time, body from modal is not scrolling, in console I don’t have any error!

I made an gif with how it works Gif movie with action

I call via ajax and display content in to modal. This is js code that I use:

$(document).ready(function(e) {
    $('.select2bs4').select2({
        theme: 'bootstrap4'
    })
    $('#map_cat').on('change', function() {
        var cat = $("#map_cat option:selected").val();
        $.ajax({
            url: "products/categories/get_char_category",
            type: "POST",
            data: {
                cat_id: cat,
                [csrf_name]: csrf_value
            },
            dataType: "json",
            beforeSend: function() {
                $("#loaderDiv").show();
                $('#characteristics').empty();
                $('#text-inf').empty();
            },
            success: function(data) {

                $("#loaderDiv").hide();
                $('#characteristics').empty();
                $('#text-inf').empty();

                var textInf = '<div class="mb-4 text-center"><?php echo $this->lang->line('match_char '); ?></div>';
                $('#text-inf').append(textInf);
                var mandatory = '';

                $.each(data, function(key, value) {
                    var mandatory = '';

                    if (value.name !== null) {

                        if (value.required !== null) {

                            var mandatory = 'mandatory';
                        }

                        var dataHtml = '<div class="col-md-12 form-group"><div class="row d-flex justify-content-between align-items-center"><div class="col-sm-6"><label class="' + mandatory + '"> ' + value.name + ' </label></div><div class="col-sm-6"><div><select name="char_id[]" class="form-control select2bs4"><option value="0"><?php echo $this->lang->line("char_select"); ?></option><?php foreach($chars as $cha){ ?><option value="<?php echo $cha->id; ?>"><?php echo $cha->char; ?></option><?php } ?></select></div></div></div></div>';
                        $('#characteristics').append(dataHtml);

                        $('.select2bs4').select2({
                            theme: 'bootstrap4'
                        })
                    }
                });
            },
            error: function(xhr, textStatus, errorThrown) {
                return false;
            }
        });
    });
});

How to get Id using razor pages jquery in asp.net entity framework project?

I have a cshtml file with a form:

<div class="widget-content widget-content-area">
                            <form id="ticketdata" action="/Ticket/[email protected]" method="post">
                                <input type="hidden" asp-for="@Model.TicketId" />
...
...
...
<button id="btnticket" type="submit" class="btn btn-primary" onclick="CreateTicket(">Create Ticket</button>
                            </form>

In the first field I am selecting a Name from a drop down menu who has a unique userId. Based on the UserId I am fetching other details as well(and that’s working).
Here is the script for that:


$("#CustomerName").change(function () {
            var CustomerName = $("#CustomerName").val();
            $.ajax({
                    url: "../Ticket/FetchCustomerAddress",
                    data: { userId: CustomerName },
                    type: "Get",
                    success: function (data) {
                        $('#Address').val(data.address);
                        $('#City').val(data.city);
                        $('#ZipCode').val(data.zipCode);
                        $('#CustomerName').val(data.customerId)
                    }

After filling the form, at the time of submission. I want that userId for further operations. But I am not getting those details. I am only getting other details in the form and not the selected userId.

In the Ticket model, I have a parameter userId.

How to get that userId in the controller? using jquery or javascript?

Display values on chartjs

I am making a simple chart with react and typescript.

Requirement: Need to make all the values to display by default

Sample:

enter image description here

Things tried:

onAnimationComplete: function () {
    datasets.forEach(function (dataset) {
        dataset.points.forEach(function (points) {
            ctx.fillText(points.value, points.x, points.y - 10);
        });
    })
}

But it looks like this is for version 1.0 but I am using version 3+ .

Working Example:

Edit Chart.js React Typescript (forked)

Could you please help to make the values on each node by default on load of the chart? Thanks in advance.

How to find the count of particular object in array using javascript?

i have an array of objects like below,

const arr_obj = [
    {
        id: '1',
        children: [],
        type: 'TYPE1',
    },
    {
         id: '2',
         children: [
             {
                  id: '1',
                  children: [
                      {
                          //some attributes
                       }
                  ],
                  type: 'MAIN',
             },
             {
                  id: '2',
                  children: [
                      {
                          //some attributes
                       }
                  ],
                  type: 'MAIN',
             },
             {
                  id: '3',
                  children: [
                      {
                          //some attributes
                       }
                  ],
                  type: 'MAIN',
             },
         ]
         type: 'TYPE2',
     },
     {
         id: '3',
         children: [
             {
                  id: '4',
                  children: [
                      {
                          //some attributes
                       }
                  ],
                  type: 'MAIN',
             },
             {
                  id: '5',
                  children: [
                      {
                          //some attributes
                       }
                  ],
                  type: 'MAIN',
             },
             {
                  id: '6',
                  children: [
                      {
                          //some attributes
                       }
                  ],
                  type: 'MAIN',
             },
         ]
         type: 'TYPE2',
     }
 ]

Now i have to find out the count of type: ‘MAIN’. these ‘MAIN’ will be within type: “type2”

so the expected count is 6. the outer children array can be empty and sometimes inner children array with type: “type2” is not there at all examples like below,

children: [] //empty array


children: [
    {
        id: '1',
        children: [],
        type: 'TYPE1',
    },
] //no children with type: 'TYPE2'

could someone help me with this. i am new to programming. thanks.

Angular: update to version 12 and problems with running the application on the current branch (with Angular 8)

I’m in the process of upgrading Angular in my application from version 8 to 12. Meanwhile there was a bug that needed a hotfix so I wanted to go back to the current branch which still has Angular 8 on it – I deleted the node_modules and dist folders, deleted the yarn.lock file, ran the yarn clean cache -all command and yarn install. Still it gives me errors like on the attached picture. I have no idea what else I can do, maybe someone encountered something similar?

enter image description here