Problems running assync python file inside electron framework

guys,

Please, I need some help.

My Electron desktop app runs a python script and I’m having a problem because when it runs, the app stays in ‘not responding’ and this is a huge problem for the users, because with one click while it’s not responding the process will stop and the app will close.

How can I do it works properly?

in renderer.py:

saveAndExecuteButton.addEventListener('mouseup', () => {
      const inputData = textInput.value;
      output.textContent = 'Executing';
      console.log('Save and execute button pressed.');
      
      electronAPI.sendToMain('saveAndExecute', inputData);

      alert('Data saved.');
    });

in main.js:

inside createWindow:

// Handle the event to save to SQLite and execute the Python script

ipcMain.on('saveAndExecute', (event, data) => {
    console.log('Received data to save to SQLite and execute the Python script:', data);
    saveToSQLiteAndExecuteScript(data);
  });

functions of the main process:

function saveToSQLiteAndExecuteScript(data) {
  console.log('Initiating the operation to save to SQLite...');
  // Connect to the SQLite database
  const db = new Database(path.join(__dirname, 'anansi.db'));

  // Create a table if it doesn't exist
  db.run('CREATE TABLE IF NOT EXISTS anansi (rowid INTEGER PRIMARY KEY, link TEXT)');

  // Insert or update data in the table
  const stmt = db.prepare('INSERT OR REPLACE INTO anansi (rowid, link) VALUES (1, ?)');
  stmt.run(data, function (err) {
    if (err) {
      console.error('Error inserting/updating data in SQLite:', err.message);
    } else {
      console.log('Data inserted/updated into SQLite successfully!');
    }

    // Finalize the statement before closing the connection
    stmt.finalize();

    // Close the database connection
    db.close();
  });
  executePythonScript();
}
async function executePythonScript() {
  console.log('Executing the Python script...');

  const pythonExecutable = 'C:\Users\Gustavo\AppData\Local\Programs\Python\Python312\python.exe';
  const pythonScriptPath = path.join(__dirname, 'anansi.py');

  try {
    console.log('começou');
    const processResult = spawnSync(pythonExecutable, [pythonScriptPath], { encoding: 'utf8' });
    console.log('aqui é o then');
    
    if (processResult.error) {
      console.error('Error from the Python script:', processResult.error);
    } else {
      console.log('Output from the Python script:', processResult.stdout);
      console.log('main.js finalizado com sucesso');
    }
  } catch (error) {
    console.error('Error in executePythonScript:', error);
  }
}

I’ve tried to implement assync functions to make the code waits for the python file to run, but without success.

Also, my idea is to pack the python scripts into an EXE later and redo the python script execution as an EXE, but, for a while, make this python script runs well will help.

I’ve tried to run the functions as async functions, and it didn’t work.

What design patter to choose for javascript. Event driven, Pub/Sub, what else? [closed]

I need help choosing (and implementing) a desing pattern using javascript.
I have a webpage that hold many charts. This charts are filled with data gather by several asynchronous fetch functions. Some charts need data from only one endpoint and others need data from two or more.
I have a chart class that holds chart related data, div id, chart title, etc. Each chart has its own object.

What i want to accomplish is to filled the charts with data as soon as the fetch promises are fulfilled. Some charts might fill faster than others, and some might not fill at all if the endpoint has an error.

Relationships woud be as follows:
Fetch endpoint(A) —> [Chart A, Chart B]
Fetch endpoint(B) —> [Chart B]

In this example, chart A need data only from endpoint A. On the other hand, chart B needs data from endpoint A and B.

I am not sure if a event driven desing patter would be the correct aproach to accomplish this. Maybe the fetch function could raise an event to which the charts objects are listening and when all the data needed is fetched, fill the chart.

The other design patter I though off is a pub/sub in which every fetch function publishes a specific topic related to the data gathered and the chart objects subscribe to those topic and get the data associated to it.

I hope I have made myself clear.
Please let me know if I can provide more information to make this easier.
Thanks!

Unable to Transfer BLOB content from Oracle APEX to another DB using ORDS REST API

There is requirement that when user select image/document using ‘File Browse’ item in Oracle APEX, this image/document needs to be transferred to remote DB via ORDS REST API. ORDS POST API is created on remove DB which takes parameter like content, type etc. and insert details to DB. It is working find but somehow BLOB (image/document) is getting corrupted in remote DB.
Below is item details created in Oracle APEX Page –

enter image description here

Image/document uploaded using this item goes to APEX temp table (apex_application_temp_files). Now when user click on ‘Upload’ following JavaScript gets executed –

//alert('here');
var base64Image = "";
var fileName = $v('P28_NEW');

var getImageDetails = async function() {
    //alert('inside get image details func');
    return apex.server.process(
        "GET_IMAGE_DETAILS", {
            x01: fileName
        }, {
            async: false,
            dataType: "json",
            success: function(pData) {
                console.log('success');
                console.log('requestBody:'+JSON.stringify(pData));
            },
            error: function(request, status, error) {
                alert("Error1:" + error);
            },
        }
    );
};


async function mainFunction() {
    try {
        var callFunction1 = await getImageDetails();

        var apiUrl = '...../ords/..../..../image/api?TITLE=test&FILENAME=test&SUBMITTED_BY=ssss&MIMETYPE=application/pdf';
        var imageContent = callFunction1.image;
        var imageType = callFunction1.mimetype; 
        //console.log('requestBody:'+JSON.stringify(callFunction1));
       
        fetch(apiUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: imageContent
            })
            .then(function(response) {
                if (response.ok) {
                    console.log('successful');
                } else {
                    console.error('failed');
                }
            })
            .catch(function(error) {
                console.error('Error:', error);
            });

    } catch (e) {
        console.error(e);
    }
}

mainFunction();

This JavaScript function calls one AJAX process to get content of uploaded image/document –

DECLARE
  l_image       CLOB;
  l_mime_type   VARCHAR2 (255);
  l_imag1e varchar2(500):=  APEX_APPLICATION.g_x01;
BEGIN
  SELECT blob_content, mime_type
                  INTO l_image, l_mime_type
                  FROM apex_application_temp_files
                 WHERE name = l_imag1e; 
    
   -- Return the values using apex_json package
    apex_json.open_object;
    apex_json.write('image', l_image);
    apex_json.write('mimetype', l_mime_type);
    apex_json.close_object; 
    exception   
     when others then
        apex_json.open_object; 
        apex_json.write('message', sqlerrm);
        apex_json.close_object; 
        --htp.p(sqlerrm);
END;

ORDS REST API which is created on remote DB. It extracts content using ‘:body’ parameters.

enter image description here

How does replit execute code in isolation?

I have always been curious. platforms like https://codedamn.com/, https://replit.com/ execute user code on demand and orchestrate resources in such a genius way.

Do they spin up a container per execution submitted?Is there any other options to achieve full isolation like theirs?How do they achieve very small and effective containers/images if they do so?

If they are using containers, or a similar concept, how would things like availability of those containers to the outside world be handled? are those containers on the same host as their backend service?

I am spinning up a new container per execution, but the size is very large and gets to 2gb after installing nodejs inside the container. which proves to be unefficient in case of many users.

How to make Text element not wrap in React Native? [duplicate]

I want to create a simple textarea component that will be markdown aware and change the color and font weight of the headers. I don’t want to use a library for this since this should be pretty simple.

According to the documentation this should work:

<TextInput>
  <Text>
    {/* The following will render a bold text in this format: **aa**aa */}
    <Text style={{ fontWeight: 900 }}>aa</Text>aa
  </Text>
</TextInput>

I’ve create this component:

const Textarea = ({initValue, style, onChange = () => {}}) => {
  const [value, setValue] = useState(initValue);

  const changeHandler = ({nativeEvent: {text}}) => {
    setValue(text);
    onChange(text);
  };
  return (
    <TextInput
      style={[styles.texarea, style]}
      multiline
      onChange={changeHandler}>
      <Text>
        {value.split('n').map((line, index) => {
          return <Text key={`${index}-${line}`}>{ line }</Text>;
        })}
      </Text>
    </TextInput>
  );
};

This is just first step next would be to parse the line and add style.

But this makes all the text in one line. When using View React Native gives an error.

I’ve tried:

<Text style={{flex: 1, flexDirection: 'column'}}>

But this doesn’t work. How can I make each string into its own line?

add response data from a post request to state

I’m working on an inventory management system and when I click the save button to add a new item, I want to take that response data and set state with all of the previous items, plus the newly added one so I don’t have to refresh the page to see changes.

Here is the code that handles the post request:

import React, { Component } from 'react'

const RESET_VALUES = {id: '', category: '', price: '', name: ''}

class ProductForm extends Component {
    constructor(props) {
        super(props)
        this.handleChange = this.handleChange.bind(this)
        this.handleSave = this.handleSave.bind(this)
        this.state = {
            product: Object.assign({}, RESET_VALUES),
            errors: {}
        }
    }
        
    handleChange(e) {
        const target = e.target
        const value = target.value
        const name = target.name
    
        this.setState((prevState) => {
            prevState.product[name] = value
            return { product: prevState.product }
        })
    }
    
 
    handleSave = async (e) => {
      //this.props.onSave();
      e.preventDefault();
        
        const backendURL = 'http://localhost:5000/product/create'; 
        const { product } = this.state;
      
        try {
          const response = await fetch(backendURL, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(product)
          });
      
          if (response.ok) {
            const data = await response.json(); // Extract response data
            console.log(data)

            this.setState(prevState => ({
              products: { ...prevState.products, [data._id]: data},
              product: { ...RESET_VALUES },
              errors: {} // Reset errors if needed
            }));
             
            // Handle success - e.g., show a success message
            console.log('Product saved successfully!',product);
            
          } else {
            // Handle error - e.g., show an error message
            console.error('Error saving product:', response.statusText);
          }
        } catch (error) {
          console.error('Error:', error.message);
          // Handle network errors or other exceptions
        }
         
      };
      
    render () {
        return (
            <form>
                <h4>Add a new product</h4>
                <p>
                    <label>Name <br /> 
                    <input type="text" class="form-control" name="name" onChange={this.handleChange} value={this.state.product.name} /></label>
                </p>
                <p>
                    <label>Category <br /> 
                    <input type="text" class="form-control" name="category" onChange={this.handleChange} value={this.state.product.category} /></label>
                </p>
                <p>
                    <label>Price <br /> 
                    <input type="text" class="form-control" name="price" onChange={this.handleChange} value={this.state.product.price} /></label>
                </p>
                <input type="submit" class="btn btn-info" value="Save" onClick={this.handleSave}></input>
            </form>
        )
    }
}

export default ProductForm

here is what the response data looks like: { "id": null, "product": { "productid": null, "category": "7", "price": 7, "name": "mario", "instock": true }, "_id": "65720598b1e57eb76e2f5658", "__v": 0 }

the state is just an array of the same object I am trying to add to state

I tried to look at other examples of how to set new state while keeping the previous state

Is there any reliable JSON visualizer that could handle visualization of big JSON dumps from Google Chrome Dev Tools Performance tab profiler?

I did three different JSON dumps using Google Chrome’s Developer Tools Performance logging tool, regarding code execution of website’s I’m working on.

The dumped code involves all of the code calls happening during logout process from the app.
Dumps are three, because they concern three different tabs of same application but different views, communicating with each other through WebSockets, Window.PostMessage, .etc.

I’ve tried using DataGraph, JSON Visualizer and JSON Crack plugins for IntelliJ IDEA Ultimate, but none of them could handle the amount of code that need to be visualized.

All of the plugins freeze the IDE while parsing the JSON code.

Is there any reliable JSON parser that can visualize JSON into diagrams (like PUML) that can handle bigger amounts of data?

Remove button wont remove last created card

I have a function that adds event listeners to all the buttons on created cards, but they only remove up to the last created card?


DOMSelectors ={
    form: document.querySelector("#form"),
    itemname: document.querySelector("#item-name"),
    parent: document.querySelector(".container"),
}
async function getData(){
    let thing = DOMSelectors.itemname.value.toLowerCase();
    thing = thing.replaceAll(' ','-')
    let URL = `https://www.dnd5eapi.co/api/spells/${thing}`; 
    console.log(URL)
    try {
        const response = await fetch(URL);
        console.log(response);
    if (response.status !=200){
        throw new Error(response.statusText);
    }
    const data = await response.json(); 
    let id = ""
    if(data.hasOwnProperty("damage")){
        id = data.damage.damage_type.index
    }else if(data.hasOwnProperty("heal_at_slot_level")){
        id= "heal"
    }else{
        id=data.school.index
    }
    console.log(data.name, id);
   DOMSelectors.parent.insertAdjacentHTML(
        "beforeend",
        `<div class='card' id=${id}>
        <h2 id="name" class="name">${data.name}</h2>
        <h3 id="price" class="name">${data.desc}</h3>
        <button class="btn">REMOVE</button>
        </div>`
    )
    } catch (error){
       alert("Enter a valid spell")
    }
}
function clearfields(){
    DOMSelectors.itemname.value = ''
}
DOMSelectors.form.addEventListener("submit", function(event) {
    event.preventDefault();
    getData();
    clearfields();
    byebye()
});
function byebye(){
    let buttons = document.querySelectorAll(".btn")
    buttons.forEach((btn)=> btn.addEventListener('click', function(event){
        btn.parentElement.remove();
    }))
}

this is the code so far its the byebye function that should remove the cards

ive used an identical function with the same purpose on a different project and it worked so i tried to just replicate the conditions and nothing happened

Mastering TypeScript: Overcoming REST API Challenges and Solutions

In the TypeScript project, there are configuration and import errors that need to be addressed. These errors are related to the use of TypeScript, a statically-typed superset of JavaScript, and the integration of a REST API within the project.

Configuration Errors: TypeScript requires a configuration file called tsconfig.json to specify how the code should be compiled. The errors may be due to incorrect configuration options or missing settings in this file. It’s crucial to ensure that the TypeScript compiler is correctly configured to understand the project’s structure and dependencies.

Import Errors: TypeScript enforces strong typing and module systems. Import errors can occur when there are issues with importing modules or libraries. These errors might include incorrect import statements or issues with type definitions.

The combination of these configuration and import errors can result in compilation failures and runtime issues when running the project. To resolve these problems, it’s essential to review and correct the TypeScript configuration, as well as ensure that module imports are properly structured and typed.

Addressing these issues will enable the TypeScript project, which includes a REST API, to compile and run successfully, ensuring that the codebase is free from errors and runs smoothly.

Thease are the errors:
`

**PS C:UsersjangiDesktopaudio-feature-extraction-main> npx tsc server.ts
server.ts:3:10 - error TS1005: 'as' expected.

           ~~~~

server.ts:3:15 - error TS1005: 'from' expected.

3 import * from "fs";
                ~~~~


Found 2 errors in the same file, starting at: server.ts:3

PS C:UsersjangiDesktopaudio-feature-extraction-main> npx tsc server.ts
server.ts:1:8 - error TS1259: Module '"C:/Users/jangi/Desktop/audio-feature-extraction-main/node_modules/@types/express/index"' can only be default-imported using the 'esModuleInterop' flag

1 import express, { NextFunction } from "express";
         ~~~~~~~

  node_modules/@types/express/index.d.ts:128:1
    128 export = e;
        ~~~~~~~~~~~
    This module is declared with 'export =', and can only be used with a default import when using the 
'esModuleInterop' flag.

server.ts:2:8 - error TS1259: Module '"C:/Users/jangi/Desktop/audio-feature-extraction-main/node_modules/@types/formidable/index"' can only be default-imported using the 'esModuleInterop' flag

2 import formidable from "formidable";
         ~~~~~~~~~~

  node_modules/@types/formidable/index.d.ts:328:1
    328 export = formidable;
        ~~~~~~~~~~~~~~~~~~~~
    This module is declared with 'export =', and can only be used with a default import when using the 
'esModuleInterop' flag.

server.ts:3:8 - error TS1192: Module '"fs"' has no default export.

3 import fs from "fs";
         ~~

server.ts:7:8 - error TS1259: Module '"C:/Users/jangi/Desktop/audio-feature-extraction-main/node_modules/@types/formidable/Formidable"' can only be default-imported using the 'esModuleInterop' flag

7 import IncomingForm from "formidable/Formidable";

  node_modules/@types/formidable/Formidable.d.ts:52:1
    52 export = IncomingForm;
       ~~~~~~~~~~~~~~~~~~~~~~
    This module is declared with 'export =', and can only be used with a default import when using the 
'esModuleInterop' flag.


Found 4 errors in the same file, starting at: server.ts:1

PS C:UsersjangiDesktopaudio-feature-extraction-main> npx tsc server.ts
server.ts:22:11 - error TS2749: 'IncomingForm' refers to a value, but is being used as a type here. Did you mean 'typeof IncomingForm'?

22     form: IncomingForm,
             ~~~~~~~~~~~~


Found 1 error in server.ts:2`


This is the code from https://cs310.hashnode.dev/?source=top_nav_blog_home:

`import express, { NextFunction } from "express";

import formidable from "formidable";

import fs from "fs";
import { IncomingMessage } from "http";
import { Essentia, EssentiaWASM } from "essentia.js";
import decode from "audio-decode";
import IncomingForm from "formidable/Formidable";


const app = express();
const port = 3000;

const essentia = new Essentia(EssentiaWASM);

const KEYS = ["C", "D", "E", "F", "G", "A", "B"];

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

const parseForm = async (
    form: IncomingForm,
    req: IncomingMessage,
    next: NextFunction
): Promise<{ fields: formidable.Fields; files: formidable.Files }> => {
    return await new Promise((resolve) => {
        form.parse(
            req,
            function (
                err: Error,
                fields: formidable.Fields,
                files: formidable.Files
            ) {
                if (err) return next(err);
                resolve({ fields, files });
            }
        );
    });
};

const decodeAudio = async (filepath: string) => {
    const buffer = fs.readFileSync(filepath);
    const audio = await decode(buffer);
    const audioVector = essentia.arrayToVector(audio._channelData[0]);
    return audioVector;
};

app.post("/upload", async (req, res, next) => {
    const form = formidable();

    const { files } = await parseForm(form, req, next);

    // The file uploaded must have the field name "file"
    const file = files.file as any;

    const data = await decodeAudio(file.filepath);

    const danceability = essentia.Danceability(data).danceability;
    const duration = essentia.Duration(data).duration;
    const energy = essentia.Energy(data).energy;

    const computedKey = essentia.KeyExtractor(data);
    const key = KEYS.indexOf(computedKey.key);
    const mode = computedKey.scale === "major" ? 1 : 0;

    const loudness = essentia.DynamicComplexity(data).loudness;
    const tempo = essentia.PercivalBpmEstimator(data).bpm;

    res.status(200).json({
        danceability,
        duration,
        energy,
        key,
        mode,
        loudness,
        tempo,
    });
});

app.listen(port, () => {
    return console.log(Express server listening at http://localhost:${port});
});

I just tried to test the code but it gives errors

Unable To Add ‘Line_item’ Property From ‘Checkout’ Object To DataLayer On The Order Status Page

I’m trying to get the value of a checkout object property to get pushed to the dataLayer on the Order Status page after a purchase. But for some reason I can’t seem to access it.

The image attached shows that the ‘selling_plan_name’ property exists in checkout.line_items[0].selling_plan_name.

But when calling that directly in Order Status Page>Additional scripts I can’t get it to show in the dataLayer.

Ideally, I’ll be able to iterate through the purchased items and push to the DL in an array, but first just trying to figure out why this can’t be picked up.

Also, here’s the dataLayer script I’m using.

subscriptionStatus is this new property I’m trying to call by following the same format as the others in the line_items loop:

{% comment %} Purchase data layer v2.1 - part of "Shopify GA4 Kit" by Analyzify
Visit https://analyzify.app/shopify-google-analytics/ga4 for complete tutorial 
{% endcomment %}

{% assign template_name = template.name %}

<script type="text/javascript">
window.dataLayer = window.dataLayer || [];

window.appStart = function(){
  window.allPageHandle = function(){
    window.dataLayer.push({
      event: "ga4kit_info",
      contentGroup: "{{ template_name }}",
      {% if customer %}
      userType: "member",
      customer: {
        id: "{{- checkout.customer.id | json -}}",
        lastOrder: "{{- customer.last_order.created_at | date: '%B %d, %Y %I:%M%p' -}}",
        orderCount: "{{- checkout.customer.orders_count | json -}}",
        totalSpent: "{{- checkout.customer.total_spent | times: 0.01 | json -}}",
        tags: {{- checkout.customer.tags | json -}}
      }
      {% else %}
        userType: "visitor",
      {% endif %}
    });
  };
  allPageHandle();

{% if first_time_accessed %}

  var shippingPrice = "{{shipping_price | money_without_currency }}".replace(",", ".");
  var totalPrice = "{{checkout.total_price | money_without_currency }}".replace(",", ".");
  var subTotal = "{{checkout.subtotal_price | money_without_currency }}".replace(",", ".");
  var taxPrice = "{{tax_price | money_without_currency }}".replace(",", ".");
  var orderItemsName = [];
  var orderItemsId = [];
  var orderItemsCategory = [];
  var orderItemsBrand = [];
  var orderItemsType = [];
  var orderItemsPrice = [];
  var orderItemsSku = [];
  var subscriptionStatus = [];
  var orderItemsvariantId = [];
  var orderItemsQuantity = [];
  var orderItemsvariantTitle = [];
  var totalQuantity = 0;
    var customerEmail = "{{customer.email}}";
    var customerPhone = {{- checkout.shipping_address.phone | json -}};
    var customerFirstname = {{- checkout.shipping_address.first_name | json -}};
    var customerLastname = {{- checkout.shipping_address.last_name | json -}};
    var customerCity = {{- checkout.shipping_address.city | json -}};
    var customerCountry = {{- checkout.shipping_address.country | json -}};
    var customerState = {{- checkout.shipping_address.province | json -}};
    var customerZip = {{- checkout.shipping_address.zip | json -}};

  {% for line_item in checkout.line_items %}  
      orderItemsName.push("{{ line_item.product.title | remove: "'" | remove: '"'}}");
      orderItemsId.push("{{ line_item.product_id }}");
      subscriptionStatus.push("{{ line_item.selling_plan_name | remove: "'" | remove: '"' }}");
      orderItemsPrice.push("{{ line_item.price | times: 0.01 }}");
      orderItemsSku.push("{{ line_item.sku | remove: "'" | remove: '"' }}");
      orderItemsQuantity.push("{{ line_item.quantity }}");
      orderItemsvariantId.push("{{ line_item.variant_id }}");
      orderItemsvariantTitle.push("{{ line_item.variant.title }}");
      orderItemsCategory.push("{{ line_item.product.collections.last.title | remove: "'" | remove: '"' }}");
      orderItemsBrand.push("{{ line_item.vendor | remove: "'" | remove: '"' }}");
      orderItemsType.push("{{ line_item.product.type | remove: "'" | remove: '"' }}");
      totalQuantity += {{ line_item.quantity }};
  {% endfor %}

  window.dataLayer.push({  
      page_type: "purchase",
      event: "analyzify_purchase",
      currency: "{{ shop.currency }}",
      totalValue: totalPrice,
      totalValueStatic: totalPrice,
      subTotal: subTotal,
      currencyRate: window.Shopify.currency.rate,
      shipping: shippingPrice,
      tax: taxPrice,
      payment_type: "{{order.transactions[0].gateway}}",
      {% if order.name %}
      transaction_id: "{{order.name | remove: "'" | remove: '"'}}",
      {% else %}
      transaction_id: "{{checkout.id | remove: "'" | remove: '"'}}",
      {% endif %}
      productName: orderItemsName,
      productId: orderItemsId,
      productBrand: orderItemsBrand,
      productCategory: orderItemsCategory,
      productVariantId: orderItemsvariantId,
      productVariantTitle: orderItemsvariantTitle,
      productSku: orderItemsSku,
      productType: orderItemsSku,
      productPrice: orderItemsPrice,
      productQuantity: orderItemsQuantity,
            email: customerEmail,
            phone: customerPhone,
            CustomerFirstName: customerFirstname,
            CustomerLastName: customerLastname,
            CustomerCity: customerCity,
            CustomerCountry: customerCountry,
            CustomerState: customerState,
            CustomerZip: customerZip,
            SubscriptionStatus: subscriptionStatus

  });

{% endif %}

}
appStart();
</script>

No matter what I try the array comes back blank in the dataLayer.

If it’s available via the console, what’s stopping me from being able to pull that value?

Any help would be much appreciated!

Code from Console

I would expect the dataLayer variable I’ve setup in GTM to now show the values for selling_plan_name but instead it comes back blank.

JavaScript bundles load without errors but functionality for file attachment and form submission not working

I have the task at my project to rewrite logic of using static files: use dynamic names or dynamic URLs for your static files. Example of dynamic name: /static/main.abcdef0123.js. I am using ASP NET Core MVC and Webpack for bundling. Before this task, the project have been using just .js and .css files without webpack so I have working logic in ‘.js’ files.

The issue at hand is that while the JavaScript and CSS bundle files are being successfully loaded into the browser—as confirmed by their 200 statuses in the Network tab, and the respective <script> and <link> elements visible in the DOM—the expected functionality is not working.

The functionality with the JS file that isn’t working is related to file handling and form submission on the webpage, specifically:

  1. The function that should be triggered when users drop or attach files isn’t executing as expected.

  2. The submit button on the form is non-responsive. It’s not initiating any action or event when clicked.

The CSS bundle is working.

It’s important to note that the bundling process appears to be working – the files are being bundled properly and the server is making these files available to the browser. The problem is not with serving the files to the client, but instead with the actual functionality coded within the JavaScript file, which for some reason isn’t working as expected when it’s served as a part of the bundled file.

In summarizing, the problem is that despite no errors in the loading of bundled JavaScript and CSS files, the expected user-interaction functionality programmed in the JavaScript isn’t activating or executing as expected on the webpage.
My webpack.config.js:

/* eslint-disable no-unused-vars */
const path = require('path');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const { WebpackManifestPlugin } = require('webpack-manifest-plugin');

module.exports = {
    mode: process.env.NODE_ENV === 'production' ? 'production' : 'development', // change to 'production' when building for production
    entry:'./wwwroot/js/index.js',
    output: {
        path: path.resolve(__dirname, 'wwwroot/dist'),
        filename: 'bundle.[contenthash].js',
        publicPath: '/dist/'
    },
    module: {
        rules: [
            {
                test: /.m?js$/,
                
                loader: 'babel-loader'
            },
            {
                test: /.svg$/,
                use: {
                    loader: 'url-loader',
                    options: {
                        limit: 10000   // Use data urls for <=10kb images, uses file-loader for other
                    }
                } 
            },
            {
                test: /.css$/,
                use: [MiniCssExtractPlugin.loader, 'css-loader'] 
            }
        ]
    },
    plugins: [
        new MiniCssExtractPlugin({
            filename: 'styles.[contenthash].css'
        }),
        new BundleAnalyzerPlugin(),
        new WebpackManifestPlugin()
    ]
};

My index.js where I store imports for all my .js files and use entry in webpack.config.js :

import './pagination.js';
import './site.js';
import './form/edit_form_init.js';
import './form/form.js';
import './form/new_form_init.js';
import './form/npApiCalls.js';
import './surveyForm/commonLogic.js';

function requireAll(r) {
    r.keys().forEach(r);
}

// Import all css files within the css directory and its subdirectories
requireAll(require.context('../css/', true, /.css$/));

// Import all svg files within the images directory
requireAll(require.context('../images/', false, /.svg$/));

My package.json for project description and names for npm scripts:

{
  "name": "***",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "precompile": "webpack",
    "build": "webpack",
    "start": "webpack-dev-server",
    "test": "echo "Error: no test specified" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.23.5",
    "@babel/preset-env": "^7.23.5",
    "babel-loader": "^9.1.3",
    "css-loader": "^6.8.1",
    "eslint": "^8.54.0",
    "file-loader": "^6.2.0",
    "mini-css-extract-plugin": "^2.7.6",
    "style-loader": "^3.3.3",
    "svg-inline-loader": "^0.8.2",
    "url-loader": "^4.1.1",
    "webpack": "^5.89.0",
    "webpack-bundle-analyzer": "^4.10.1",
    "webpack-cli": "^5.1.4",
    "webpack-dev-middleware": "^6.1.1",
    "webpack-dev-server": "^4.15.1",
    "webpack-manifest-plugin": "^5.0.0"
  },
  "babel": {
    "plugins": [
      "@babel/syntax-dynamic-import"
    ],
    "presets": [
      [
        "@babel/preset-env",
        {
          "modules": false
        }
      ]
    ]
  }
}

I have manifest.json:

{
  "main.css": "/dist/styles.7b1bf0ef4c5af1795361.css",
  "main.js": "/dist/bundle.0363bed44d8d0b3f64ff.js",

  "unauthorized-access-page.svg": "/dist/df81d60cc31dfc502a4f19196a3457b2.svg",
  // other .svg files...
}

How I import bundled files to _Layout.cshtml:

@using System.IO
@using Newtonsoft.Json
@inject Microsoft.AspNetCore.Hosting.IWebHostEnvironment env
@{
    var manifestPath = System.IO.Path.Combine(env.WebRootPath, "dist", "manifest.json");
    var manifest = System.IO.File.Exists(manifestPath)
        ? JsonConvert.DeserializeObject<Dictionary<string, string>>(System.IO.File.ReadAllText(manifestPath))
        : new Dictionary<string, string>();
}

    <link rel="stylesheet" href="@manifest.GetValueOrDefault("main.css")" />

    <script src="@manifest.GetValueOrDefault("main.js")"></script>

The line <script src="@manifest.GetValueOrDefault("main.js")"></script> is after </footer>.

Headers of bundle.js

I’ve tried to use in the webpack.config.json but expected behavior did not occur:

 module: {
     rules: [
         {
             test: /.m?js$/,
             // exclude: /(node_modules|bower_components)/,
             loader: 'babel-loader'
             /*use: {
                 options: {
                     presets: ['@babel/preset-env']
                 }
             }*/
         },

My pipeline of running the project:

  1. Run npm run build with the output:
npm run build

> [email protected] build
> webpack

Webpack Bundle Analyzer is started at http://127.0.0.1:xxxx
Use Ctrl+C to close it
assets by path *.svg 322 KiB
  assets by info 1.58 KiB [immutable]
    asset 17936c45f1f5e57990d7.svg 667 bytes [emitted] [immutable] [from: wwwroot/images/search-icon.svg] (auxiliary name: main)
    asset 74e13e43c2967dfb9cfd.svg 539 bytes [emitted] [immutable] [from: wwwroot/images/excel-icon.svg] (auxiliary name: main)
    asset fe3c8b386d2d6f26ea5a.svg 411 bytes [emitted] [immutable] [from: wwwroot/images/close_image.svg] (auxiliary name: main)
  + 10 assets
assets by chunk 245 KiB (name: main)
  asset bundle.0363bed44d8d0b3f64ff.js 153 KiB [emitted] [immutable] (name: main)
  asset styles.7b1bf0ef4c5af1795361.css 92 KiB [emitted] [immutable] (name: main)
asset manifest.json 1.02 KiB [emitted]
Entrypoint main 245 KiB (322 KiB) = styles.7b1bf0ef4c5af1795361.css 92 KiB bundle.0363bed44d8d0b3f64ff.js 153 KiB 13 auxiliary assets
runtime modules 39.2 KiB 183 modules
orphan modules 97.1 KiB (javascript) 1.58 KiB (asset) [orphan] 48 modules
built modules 93.7 KiB (javascript) 79.2 KiB (css/mini-extract) [built]
  javascript modules 93.7 KiB
    optional modules 30.4 KiB [optional]
      modules by path ./wwwroot/images/ 28.4 KiB 42 modules
      modules by path ./wwwroot/css/ 2 KiB 41 modules
    modules by path ./wwwroot/js/ 60.7 KiB 8 modules
    ./wwwroot/css/ sync .css$ 1.25 KiB [built] [code generated]
    ./wwwroot/images/ sync nonrecursive .svg$ 1.27 KiB [built] [code generated]
  css modules 79.2 KiB 48 modules
webpack 5.89.0 compiled successfully in 2386 ms
  1. dotnet run
  2. The app is running at https://localhost:xxxx

Global store: state conflicts

I use Pinia store where I have 4 actions: loadRecipesByKeyword, loadPopularRecipes, loadPaginatedRecipes, loadRecipesCount. I’ve noticed I have data conflicts when I put all of the data in the same state property data.

const data = await res.json();
this.data = data;

For example, let’s say I’m at /home right now where I load popular recipes. If I go to /recipes where I have a pagination and I load limited amount of recipes per page, instead of seeing the limited amount, I see all of the popular recipes loaded for some reason, even though I have a separate query for this task on the server and the store action called loadPaginatedRecipes. Something’s wrong with the data persistance and there’s definitely a conflict.

Should I add all the data into one state like I do right now, but manage it somehow more correctly, or should I separate it into different properties to avoid issues, for example:

export const state = () => {
     return {
         popularRecipes: [],
         recipeByKeyword: [],
         paginatedRecipes: [],
         reсipesCount: 0,
         selectedRecipe: null,
     };
};

Please, give a solution.

Display pdf on expo react native

“I’m working on a React Native application where I need to display the content of a PDF that I retrieve through an API. I’ve tried various methods, including using WebView, but I can’t get it to work properly. Unfortunately, I can’t use native dependencies due to the restrictions of Expo Go. Does anyone have suggestions on how I can achieve rendering a PDF in my React Native application using Expo?

`import React, { useEffect, useState } from "react";
import { View, Text, StyleSheet } from "react-native";
import { WebView } from "react-native-webview";
import { IPV4_ADDRESS } from "../views/SiteHome";

export const NodeContent = ({ route }) => {
  const { id, ticket } = route.params;
  const [pdfUrl, setPdfUrl] = useState("");

  const fetchContentNode = async (id, ticket) => {
    const myheaders = {
      method: "GET",
      headers: {
        Authorization: "Basic " + ticket,
      },
    };

    const response = await fetch(
      `http://${IPV4_ADDRESS}:8080/alfresco/api/-default-/public/alfresco/versions/1/nodes/${id}/content`,
      myheaders
    );

    const pdfUrl = response.url;
    console.log(pdfUrl)
    return pdfUrl;
  };

  useEffect(() => {
    const getPdfUrl = async () => {
      const url = await fetchContentNode(id, ticket);
      setPdfUrl(url);
    };
    getPdfUrl();
  }, [id, ticket]);

  return (
    <View style={styles.container}>
      {pdfUrl ? (
        <WebView source={{ uri: pdfUrl }} />
      ) : (
        <Text>Loading PDF...</Text>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
});`

Are there any alternatives or approaches I can consider to solve this problem?

Sorry for my english

Why can’t I fetch data from firebase realtime database?

I’m trying to fetch data from firebase’s realtime database but I keep getting this error:
GET http://localhost:4000/events net::ERR_CONNECTION_REFUSED

here is my react component(I removed the config from this code):

import firebase from 'firebase/compat/app';
import 'firebase/compat/database';

const firebaseConfig = {

};

if (!firebase.apps.length) {
  firebase.initializeApp(firebaseConfig);
}


export default function EventDetails() {
 const { id } = useParams()
 console.log('Event ID:', id);

 const event = useLoaderData()
 console.log('Event Data:', event);


 return (
   <div className="event-details">
     <h2>{event.title}</h2>
     <p>{event.description}</p>
     <div className="details">
       <p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Dicta sed sunt ipsam quam assumenda quasi ipsa facilis laborum rerum voluptatem!</p>
     </div>
   </div>
 )
}

// data loader
export const eventDetailsLoader = async ({ params }) => {
 const { id } = params

 const ref = firebase.database().ref('/events/' + id);
 const snapshot = await ref.once('value');

 if (!snapshot.exists()) {
   throw Error('Could not find that event.')
 }

 return snapshot.val();
}

I was at first trying to import the config from an external component but that didn’t work I checked the realtime databes and I couldn’t find any issues then I asked GPT and it was only able to suggest adding this line when initializing the app: if (!firebase.apps.length) { firebase.initializeApp(firebaseConfig);

Alpine Expression Error: variable is not defined

I’m encountering this error after moving my Tile class to Tile.js and moving the game data from app.js to game.js. When all the JS is in the same file everything works fine, but once I break it up into different files I get the error in the title. There’s a lot of posts with similar questions, but almost everyone I looked at was broken due to a syntax error or something simple. I don’t think that is the case here.

Reproduction on Stackblitz

<!-- index.html -->
<html>
  <head>
    <base href="/" target="_blank" />
    <link rel="stylesheet" href="./styles.scss" />
    <script src="//unpkg.com/alpinejs" defer></script>
    <script type="module" src="./app.js"></script>
  </head>
  <body>
    <div id="game" x-data="game" @keyup.window="onKeyPress($event.key)">
      <template x-for="row in board">
        <div class="row">
          <template x-for="tile in row">
            <div class="tile" x-text="tile.letter"></div>
          </template>
        </div>
      </template>
    </div>
  </body>
</html>
// app.js
import game from './game';

document.addEventListener('alpine:init', () => {
  Alpine.data('game', () => game);
});
// game.js
import Tile from './Tile';

export default {
  guessesAllowed: 5,
  wordLength: 5,
  currentRowIndex: 0,

  init() {
    this.board = Array.from({ length: this.guessesAllowed }, () => {
      return Array.from({ length: this.wordLength }, () => new Tile());
    });
  },

  onKeyPress(key) {
    if (/^[A-z]$/.test(key)) {
      this.fillTile(key);
    }
  },

  fillTile(key) {
    for (let tile of this.currentRow()) {
      if (!tile.letter) {
        tile.fill(key);
        break;
      }
    }

    if (this.currentTileIndex === this.wordLength - 1) {
      this.currentRowIndex++;
      this.currentTileIndex = 0;
    } else {
      this.currentTileIndex++;
    }
  },

  currentRow() {
    return this.board[this.currentRowIndex];
  },
};
// Tile.js
export default class Tile {
  letter = '';
  status = ''; // 'correct', 'incorrect', 'empty'
  
  fill(key) {
      this.letter = key.toUpperCase();
      this.status = 'filled';
  }
  
  empty() {
      this.letter = '';
      this.status = 'empty';
  }
}