Generate CreateForm/EditForm dynamically for “args/options” from many CLI programs

I write code in node.js and typescript.

I have a REST backoffice front-end (build with react-admin but it doesn’t matter) on which I need to develop a CRUD for CliOptionsEntity, which have this shape :

{ 
  configName: string // unique identifier
  name: string // the CLI package name
  options: string  // a json object with all args saved for this clie
}

I want to generate the FormCreate and FormEdit views dynamically (as opposite to create a new one each time I had a CLI), as I have many CLIs programs.

My CLI usually use yargs to have a generic interface for it’s args. (I am OK to change if it helps.)

Usually, the CLI program is a function, which is just wrapped in my CLI interface.

What technical strategies can fit this use case so I can dynamically generate my form ?

Multi tag replace between values

I have some script which makes replacements. It works fine, but because of replaced values standing close to each other i’ve got more than one
between values.

It looks like:

<br />
Value

<br />
Value

<br />


<br />
Value

<br />
Value

<br />


<br />
Value

<br />


<br />

<br />

My task is to get only one <br> between values:

<br />
Value

<br />
Value

<br />
Value

Because of not so many variations in my list I know one decision for all available variants but it is bad hardcode something like:

var mystring=`<br />


<br />`

for (i=0; i<mystring.length; i++){
          var regex = new RegExp(mystring[i],"g");
           mystring = mystring.replace(regex, "");
       }    

Is there any elegant way to solve my case? Thinking of regexp but it’s too hard for me to write it. Or may be there is another way?

whats wrong with my timer code? im making this website for my gf but im not sure whats wrong this is code? t [closed]

document.addEventListener('DOMContentLoaded', function() {
    // Timer code
    function updateTimer() {
        const startDate = new Date("2024-06-05T17:00:00").getTime();
        const now = new Date().getTime();
        const distance = now - startDate;

        const years = Math.floor(distance / (1000 * 60 * 60 * 24 * 365));
        const days = Math.floor((distance % (1000 * 60 * 60 * 24 * 365)) / (1000 * 60 * 60 * 24));
        const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        const seconds = Math.floor((distance % (1000 * 60)) / 1000);

        document.getElementById("timer").innerHTML = years + " years " + days + " days " + hours + " hours " + minutes + " minutes " + seconds;
    }
    setInterval(updateTimer, 1000);


please help

i made this code to get like as a timer for my relationship with my girlfriend. but nothing appeared on the website.

How can I animate sidebar items sliding up when an item is deleted?

I am trying to create a sidebar with a list of items. When an item is deleted, I want the remaining items to slide up smoothly to fill the space left by the deleted item. How can I achieve this?

This is my code:

document.addEventListener("DOMContentLoaded", function () {
   const deleteButtons = document.querySelectorAll(".del");

   deleteButtons.forEach((button) => {
      button.addEventListener("click", function () {
         const item = this.parentElement;
         item.classList.add("deleting");
         item.addEventListener("transitionend", function () {
            item.remove();
         });
      });
   });
});
.sidebar {
   width: 250px;
   background-color: #f0f0f0;
   padding: 10px;
   border-right: 1px solid #ccc;
   border-radius: 10px;
}

.item-list {
   list-style-type: none;
   padding: 0;
   margin: 0;
}

.item {
   background-color: #fff;
   margin: 5px 0;
   padding: 10px;
   border: 1px solid #ccc;
   display: flex;
   justify-content: space-between;
   align-items: center;
   border-radius: 10px;
   transition: transform 0.3s ease, opacity 0.3s ease;
}

.item.deleting {
   transform: translateY(-100%);
   opacity: 0;
   border: none;
}

.del {
   background-color: #ff6666;
   border: none;
   color: white;
   padding: 5px 10px;
   cursor: pointer;
   border-radius: 9999px;
   transition: background-color 0.3s;
}

.del:hover {
   background-color: #ff3333;
}
<div class="sidebar">
   <ul class="item-list">
      <li class="item">item 1 <button class="del">Delete</button></li>
      <li class="item">item 2 <button class="del">Delete</button></li>
      <li class="item">item 3 <button class="del">Delete</button></li>
      <li class="item">item 4 <button class="del">Delete</button></li>
      <li class="item">item 5 <button class="del">Delete</button></li>
      <li class="item">item 6 <button class="del">Delete</button></li>
      <li class="item">item 7 <button class="del">Delete</button></li>
      <li class="item">item 8 <button class="del">Delete</button></li>
      <li class="item">item 9 <button class="del">Delete</button></li>
      <li class="item">item 10 <button class="del">Delete</button></li>
   </ul>
</div>

While the deleting item moves up, the other items don’t immediately move to fill its space until the item is deleted. How can I make sure that the other items move up to fill its space while the item is moving up?

Shopify Theme Customizer: How to Make Custom Section Content Editable?

I have a custom section on my Shopify website where I display a title, text, and images. The HTML structure includes specific styles and a JavaScript function that renders text in a circular pattern. Here’s my Liquid code of my custom component:


<style>
  body {
    margin: 0;
  }
  
  .custom-section {
    background: linear-gradient(180deg, #D6F1FA 0%, #C5EAF7 100%);
    position: relative;
    width: 1440px;
    height: 650px;
  }
  
  .custom-section .container-wrapper {
    position: relative;
    width: 1510px;
    height: 430px;
    border: 2px dashed red;
    overflow: hidden;
    left: 75px;
    top:110px;
  }
  
  .custom-section .text-section {
    width: 520px;
    height: 100%;
    position: absolute;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    border: 2px dashed blue;
  }
  
  .custom-section .title-container h2 {
    font-family: 'ITC Garamond Std';
    font-size: 64px;
    font-weight: 300;
    line-height: 70px;
    letter-spacing: -2px;
    text-align: left;
    margin: 0;
    padding: 0;
  }
  
  .custom-section .text-container {
    font-family: 'iCiel Internacional', sans-serif;
    font-size: 16px;
    font-weight: 400;
    line-height: 26px;
    text-align: left;
    width: 60%;
    margin-bottom: 0;
    padding-bottom: 0;
  }
  
  .custom-section .spacer {
    flex: 1;
    border: 2px dashed green;
  }
  
  .custom-section .images-wrapper {
    width: 960px;
    height: 430px;
    position: absolute;
    left: 550px;
    display: flex;
    gap: 30px;
    border: 2px dashed purple;
  }
  
  .custom-section .images-wrapper img {
    width: 300px;
    height: 430px;
  }
  
  .circular span {
    font: 13px Monaco, MonoSpace;
    height: 80px;
    position: absolute;
    left: 75px;
    transform-origin: bottom center;
  }
  
  .circular {
    width: 160px;
    height: 160px;
    border: 2px dashed yellow;
    position: relative;
  }
  
</style>

<script src="{{ 'custom-section.js' | asset_url }}" defer="defer"></script>


<section class="custom-section">
  <div class="container-wrapper">
    <div class="text-section">
      
      <div class="title-container">
        <h2>Our jewelry</h2>
      </div>
      
      <div class="text-container">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut tempor tincidunt posuere. Nam tempus, leo ac tempus hendrerit.</p>
      </div>
      
      <div class="spacer"></div>
      
      <h1 class="circular">
        
      </h1>
    </div>
    
    <div class="images-wrapper">
      <img src="{{ 'image1.jpg' | asset_url }}" alt="Image 1">
      <img src="{{ 'image2.jpg' | asset_url }}" alt="Image 2">
      <img src="{{ 'image3.jpg' | asset_url }}" alt="Image 3">
    </div>
  </div>

 
</section>

<!--
{% schema %}
{
  "name": "Custom section",
  "settings": [
    {
      "type": "text",
      "id": "text",
      "label": "Text"
    }
  ],
  "presets": [
    {
      "name": "Default custom section"
    }
  ],
  "tag": "section",
  "class": "custom-section",
  "limit": 1
}
{% endschema %}
-->

And this is my “custom-section.js”:


document.addEventListener('DOMContentLoaded', () => {

  const text = document.querySelector('.circular');

  const message = "We’re the bestie that you can be yourself with. ";

  text.innerHTML = '';

  for (let i = 0; i < message.length; i++) {
    let circularTextSpan = document.createElement('span');
    circularTextSpan.textContent = message[i];
    text.appendChild(circularTextSpan);
    circularTextSpan.style.transform = `rotate(${360 * i / message.length}deg)`;
  }
});

The JavaScript (custom-section.js) creates circular text inside <h1 class="circular">.

However, this section isn’t customizable from Shopify’s Theme Customizer. I want users to be able to edit the title, text content, and possibly change images through the customizer without needing to modify the theme files directly.

What I’ve Tried:

Schema Definition: I’ve defined a schema for the custom section in the Shopify theme settings, but I’m not sure how to integrate it properly.


{% schema %}
{
  "name": "Custom section",
  "settings": [
    {
      "type": "text",
      "id": "text",
      "label": "Text"
    }
    // Other settings for images, etc.
  ],
  "presets": [
    {
      "name": "Default custom section"
    }
  ],
  "tag": "section",
  "class": "custom-section",
  "limit": 1
}
{% endschema %}


Question:

  • How can I modify the HTML structure and JavaScript (custom-section.js) to ensure that the content inside .custom-section is fully customizable using Shopify’s Theme Customizer?

  • Specifically, how do I ensure that changes made through the Theme Customizer (like modifying the title, text content, or images) reflect correctly in the frontend without breaking the circular text functionality implemented in JavaScript?

Any guidance or examples on integrating the custom section with Shopify’s Theme Customizer would be greatly appreciated. Thank you!

I need tp help of REact js [closed]

ps
Summarize your problem in a one-line title.
Describe your problem in more detail.
Describe what you tried and what you expected to happen.
Add “tags” which help surface your question to members of the community.
Review your question and post it to the site.

ps
Summarize your problem in a one-line title.
Describe your problem in more detail.

ReferenceError: print_text is not defined [WASM]

Just a beginner writing a very simple rust program to build a lib


pub use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub struct SomeStruct {
}

#[wasm_bindgen]
impl SomeStruct {
    
    #[wasm_bindgen(constructor)]
    pub fn new() -> SomeStruct {
        SomeStruct { }
    }

    pub fn print_text() {
        println!("Text to Print");
    }
}

index.js

import { SomeStruct } from './pkg';
document.write(print_text());

when running

npm run serve

getting

Uncaught runtime errors:

ERROR
print_text is not defined
ReferenceError: print_text is not defined
    at eval (webpack:///./index.js?:7:10)

I’m new to both Rust and JS, and can’t understand exactly where I am missing

In pkg folder, I have files with following names

index.d
index.js
index_bg.js
index_bg.wasm
index_bg.wasm.d
package

how do sort and raiting in my flutter food app?

First of all im just trying do that plan bcse i whatch YouTube channel Mithc Koko and try add something new thats my plan:

IN PRODUCT PAGE :

  1. 5 stars (collecting if each user want to rate product)
  2. if user rate product 0-5 (the product position is sorted by rating in HomePage)
  3. when user search, do same thing but there user can chose how to sort search.(raiting, location, price)

for now i dont realisate ratingBar for rate food im stuck there how to calculate and saveload rating and sort in Page;

This my Food class :

import 'package:combi/models/rating_manager.dart';

class Food {
  final String name;
  final String restaurantName;
  final String restaurantUid; // Add restaurantUid property
  final String description;
  final String imagePath;

  final FoodCategory category;
  final int price;
  int popularity;
  final bool favorites;

  List<Addon> availableAddons;

  Food({
    required this.name,
    required this.description,
    required this.imagePath,
    required this.price,
    required this.availableAddons,
    required this.restaurantName,
    required this.restaurantUid, // Initialize restaurantUid when creating Food objects
    this.popularity = 0,
    this.favorites = false,
    required this.category,
  });

  // Method to update popularity based on user rating
  void updatePopularity(
      int rating, int foodWeight, int restaurantWeight, int positionIndex) {
    // Calculate the new popularity score
    popularity = RatingManager.calculatePopularity(
      popularity,
      rating,
      foodWeight,
      restaurantWeight,
      positionIndex,
    );
  }

  // Method to toggle favorites
  Food toggleFavorite() {
    return Food(
      name: name,
      restaurantName: restaurantName,
      restaurantUid:
          restaurantUid, // Handle null value by providing a default value
      description: description,
      imagePath: imagePath,
      category: category,
      price: price,
      popularity: popularity,
      availableAddons: availableAddons,
      favorites: !favorites, // Toggle the value
    );
  }
}

enum FoodCategory {
  combo,
  doner,
  pizza,
  chicken,
}

class Addon {
  String name;
  int price;

  Addon({
    required this.name,
    required this.price,
  });
}

new class RatingManager:

class RatingManager {
  static int calculatePopularity(int currentPopularity, int rating,
      int foodWeight, int restaurantWeight, int positionIndex) {
    int newPopularity = (currentPopularity +
            (rating * (foodWeight + restaurantWeight) * positionIndex))
        .toInt();
    return newPopularity;
  }
}

and this how Menu load from firebase for HomePage:


class Restaurant extends ChangeNotifier {
  final FirebaseFirestore _firestore = FirebaseFirestore.instance;

  final FirebaseAuth _auth;

  final List<Food> _menu = [];
  final String name;
  int popularity;
  final List<Food> _favoriteItems = []; // Add list of favorite foods

  Restaurant({
    required this.name,
    this.popularity = 0,
    required FirebaseAuth auth, // Pass FirebaseAuth instance as a parameter
  }) : _auth = auth {
    _loadMenu();
  }

  // Load menu from Firestore
  Future<void> _loadMenu() async {
    try {
      QuerySnapshot querySnapshot = await _firestore.collection('foods').get();
      List<Food> loadedMenu =
          querySnapshot.docs.map((doc) => _foodFromSnapshot(doc)).toList();
      _menu.addAll(loadedMenu);
      notifyListeners();

      // Check if the user is authenticated
      if (_auth.currentUser != null) {
        DocumentSnapshot userDoc = await _firestore
            .collection("Users")
            .doc(_auth.currentUser!.uid)
            .get();
        Map<String, dynamic> userData =
            userDoc.data() as Map<String, dynamic>? ?? {};
        String? userName = userData['name'];
        String? userPhoneNumber = userData['phoneNumber'];
        String? restaurantUid = userData['restaurantUid'];
        // Update SharedPreferences with user's name and phone number if available
        if (userName != null &&
            userPhoneNumber != null &&
            restaurantUid != null) {
          SharedPreferences prefs = await SharedPreferences.getInstance();
          await prefs.setString('name', userName);
          await prefs.setString('phoneNumber', userPhoneNumber);
          await prefs.setString('restaurantUid', restaurantUid);
        }
      }
    } catch (e) {
      print('Error loading menu: $e');
    }
  }

// Getter for favorite items
  List<FavoriteItem> get favoriteItems {
    // Convert favorite foods to FavoriteItem objects with selected addons
    return _favoriteItems
        .map((food) => FavoriteItem(food: food, selectedAddons: []))
        .toList();
  }

  void updatePopularity(int rating, int restaurantWeight) {
    // Calculate the new popularity score
    popularity = RatingManager.calculatePopularity(
      popularity,
      rating,
      0, // Placeholder for food weight, as it's not provided in this method
      restaurantWeight,
      0, // Placeholder for position index, as it's not provided in this method
    );
  }

  Food _foodFromSnapshot(DocumentSnapshot snapshot) {
    Map<String, dynamic> data = snapshot.data() as Map<String, dynamic>;
    String categoryString = data['category'] ?? '';
    FoodCategory category =
        _getFoodCategory(categoryString); // Convert string to enum
    return Food(
      name: data['name'] ?? '',
      description: data['description'] ?? '',
      imagePath: data['imagePath'] ?? '',
      price: (data['price'] ?? 0).toInt(), // Convert double to int
      category: category,
      availableAddons: _addonsFromMapList(data['availableAddons'] ?? []),
      restaurantName: data['restaurantName'] ?? '',
      restaurantUid: data['restaurantUid'] ?? '', // Initialize restaurantUid
      popularity: (data['popularity'] ?? 0).toInt(), // Convert double to int
      favorites: data['favorites'] ?? false,
    );
  }

// Helper method to convert string to FoodCategory enum
  FoodCategory _getFoodCategory(String categoryString) {
    switch (categoryString.toLowerCase()) {
      case 'combo':
        return FoodCategory.combo;
      case 'doner':
        return FoodCategory.doner;
      case 'pizza':
        return FoodCategory.pizza;
      case 'chicken':
        return FoodCategory.chicken;
      default:
        return FoodCategory.combo; // Default to combo if category is unknown
    }
  }

  // Helper method to convert list of maps to list of Addon objects
  List<Addon> _addonsFromMapList(List<dynamic> mapList) {
    return mapList
        .map((addon) => Addon(
              name: addon['name'] ?? '',
              price: addon['price'] ?? 0,
            ))
        .toList();
  }

  // user cart - real quic))
  final List<CartItem> _cart = [];

  // delivery address (can update/change)
  String _deliveryAddress = 'город: Актобе';

  // G E T T E R S
  List<Food> get menu => _menu;
  List<CartItem> get cart => _cart;
  String get deliveryAddress => _deliveryAddress;

  // O P E R A T I O N S
  // add to cart
  void addToCart(Food food, List<Addon> selectedAddons) {
    // see if there is a cart item already with the same food and selected addons
    CartItem? cartItem = _cart.firstWhereOrNull((item) {
      // check if the food items are the same
      bool isSameFood = item.food == food;

      // check if the List of selected addons are the same
      bool isSameAddons =
          const ListEquality().equals(item.selectedAddons, selectedAddons);

      return isSameFood && isSameAddons;
    });
    // if item already exist, increase it`s quantity
    if (cartItem != null) {
      cartItem.quantity++;
    }
    // otherwise, add a new cart item to the cart
    else {
      _cart.add(
        CartItem(
          food: food,
          selectedAddons: selectedAddons,
        ),
      );
    }
    notifyListeners();
  }

// add to favorites
  void addToFavorites(Food food, List<Addon> selectedAddons) {
    // Check if the food with the same addons already exists in favorites
    FavoriteItem? existingFavorite = _favoriteItems
        .map((food) => FavoriteItem(food: food, selectedAddons: []))
        .firstWhereOrNull((favoriteItem) {
      // Check if the food items are the same
      bool isSameFood = favoriteItem.food == food;

      // Check if the list of selected addons are the same
      bool isSameAddons = const ListEquality()
          .equals(favoriteItem.selectedAddons, selectedAddons);

      return isSameFood && isSameAddons;
    });

    // If the item already exists, do nothing
    if (existingFavorite != null) {
      return;
    }

    // Otherwise, add a new favorite item to the favorites list
    _favoriteItems.add(food);

    // Toggle favorite status
    food.toggleFavorite();

    // Notify listeners
    notifyListeners();
  }

  // remove from cart
  void removeFromCart(CartItem cartItem) {
    int cartIndex = _cart.indexOf(cartItem);

    if (cartIndex != -1) {
      if (_cart[cartIndex].quantity > 1) {
        _cart[cartIndex].quantity--;
      } else {
        _cart.removeAt(cartIndex);
      }
    }
    notifyListeners();
  }

// Remove from favorites
  void removeFromFavorites(Food food) {
    int favoriteIndex = _favoriteItems.indexOf(food);

    if (favoriteIndex != -1) {
      _favoriteItems.removeAt(favoriteIndex);
    }

    // Toggle favorite status
    food.toggleFavorite();

    notifyListeners();
  }

  // get total price
  int getTotalPrice() {
    int total = 0;

    for (CartItem cartItem in _cart) {
      int itemTotal = cartItem.food.price;

      for (Addon addon in cartItem.selectedAddons) {
        itemTotal += addon.price;
      }
      total += itemTotal * cartItem.quantity;
    }
    return total;
  }

  // get total number of items in cart
  int getTotalItemCount() {
    int totalItemCount = 0;

    for (CartItem cartItem in _cart) {
      totalItemCount += cartItem.quantity;
    }
    return totalItemCount;
  }

  // clear cart
  void clearCart() {
    _cart.clear();
    notifyListeners();
  }

  // clear favorites
  void clearFavorites() {
    _cart.clear();
    notifyListeners();
  }

  // update delivery address
  void updateDeliveryAddress(String newAddress) {
    _deliveryAddress = newAddress;
    notifyListeners();
  }

  // H E L P E R S
  // Update displayCartReceipt method
  Future<String> displayCartReceipt() async {
    try {
      final SharedPreferences prefs = await SharedPreferences.getInstance();
      final receipt = StringBuffer();
      receipt.writeln("Статус оплаты: "); //$paymentStatus
      // Format the date to include up to seconds only
      String formattedDate =
          DateFormat('yyyy-MM-dd HH:mm:ss').format(DateTime.now());

      // Append the formatted date to the receipt
      receipt.writeln("Дата: $formattedDate");
      receipt.writeln();
      receipt.writeln(
          "Restaurant Name: ${_menu.isNotEmpty ? _menu.first.restaurantName : 'Unknown'}"); // Fetch restaurantName from any item in the menu
      // receipt.writeln(
      //     "Restaurant Uid: ${_menu.isNotEmpty ? _menu.first.restaurantUid : 'Unknown'}"); // Fetch restaurantUid from any item in the menu
      receipt.writeln(
          "<<-------------------------------------------------------------------------------->>");

      // Add cart items details
      for (final cartItem in _cart) {
        receipt.writeln(
            "${cartItem.quantity} x ${cartItem.food.name} - ${_formatPrice(cartItem.food.price)}");

        if (cartItem.selectedAddons.isNotEmpty) {
          receipt.writeln(
              "      Дополнения: ${_formatAddons(cartItem.selectedAddons)}");
        }
        receipt.writeln();
      }

      // Add total items and total price
      receipt.writeln(
          "<<-------------------------------------------------------------------------------->>");
      receipt.writeln();
      receipt.writeln("Общее количество: ${getTotalItemCount()}");
      receipt.writeln("Общая сумма: ${_formatPrice(getTotalPrice())}");
      receipt.writeln(
          "<<-------------------------------------------------------------------------------->>");
      receipt.writeln("Доставка по адресу: $deliveryAddress");

      // Add saved name and phone number to the receipt
      receipt.writeln();
      receipt.writeln("Имя: ${prefs.getString('name') ?? 'Unknown'}");
      receipt.writeln(
          "Номер телефона: ${prefs.getString('phoneNumber') ?? 'Unknown'}");

      return receipt.toString();
    } catch (e) {
      print('Error displaying cart receipt: $e');
      return "Ошибка при отображении квитанции.";
    }
  }

  // format double/int value into money
  String _formatPrice(int price) {
    return '${price.toStringAsFixed(2)}₸';
  }

// format list of addons into a string summary
  String _formatAddons(List<Addon> addons) {
    return addons
        .map((addon) => "${addon.name} (${_formatPrice(addon.price)})")
        .join(", ");
  }

  Restaurant copyWith({
    String? name,
    int? popularity,
  }) {
    return Restaurant(
      name: name ?? this.name,
      popularity: popularity ?? this.popularity,
      auth: FirebaseAuth.instance,
    );
  }

  Map<String, dynamic> toMap() {
    return <String, dynamic>{
      'name': name,
      'popularity': popularity,
    };
  }

  factory Restaurant.fromMap(Map<String, dynamic> map) {
    return Restaurant(
      name: map['name'] as String,
      popularity: map['popularity'] as int,
      auth: FirebaseAuth.instance,
    );
  }

  String toJson() => json.encode(toMap());

  factory Restaurant.fromJson(String source) =>
      Restaurant.fromMap(json.decode(source) as Map<String, dynamic>);

  @override
  String toString() => 'Restaurant(name: $name, popularity: $popularity)';

  @override
  bool operator ==(covariant Restaurant other) {
    if (identical(this, other)) return true;

    return other.name == name && other.popularity == popularity;
  }

  @override
  int get hashCode => name.hashCode ^ popularity.hashCode;
}

i do something wrong, i know. Maybe someone tell me easy way or example please? Thanks!

i was try do rate and just save number with product information (it works) but after days i think i can do better and sort this rated products (and now im here) hope some body help me bcse im bored after weeks drop this project and created new one, but still wanna try that idea

can’t fetch from local host as it violates CSP policy

I’m a new developer, was following this tutorial, but got stuck at 21:06 when I was trying to fetch from local host after implementing the CORS. According to the video, it is supposed to work but I got this error instead.

fetch('http://localhost:3000');
VM262:1 Refused to connect to 'http://localhost:3000/' because it violates the following Content Security Policy directive: "connect-src chrome://resources chrome://theme 'self'".

(anonymous) @ VM262:1Understand this error
VM262:1 Refused to connect to 'http://localhost:3000/' because it violates the document's Content Security Policy.
(anonymous) @ VM262:1Understand this error
Promise {<rejected>: TypeError: Failed to fetch
    at <anonymous>:1:1}
VM262:1 Uncaught (in promise) TypeError: Failed to fetch
    at <anonymous>:1:1

Here is a summary of my code from the tutorial so far. I added the http headers to modify the CSP but still to no avail.

const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
const path = require('path');
const {logger} = require('./middleware/logger');
const errorHandler = require('./middleware/errorHandler');
const cookieParser = require('cookie-parser');
const cors = require('cors');

// Middleware to set CSP headers
app.use((req, res, next) => {
    res.setHeader('Content-Security-Policy', "default-src 'self'; connect-src 'self' http://localhost:3000");
    next();
});



app.use(cors());

app.use(logger);


app.use(express.json());

app.use(cookieParser());

app.use('/', express.static(path.join(__dirname, '/public')));

app.use('/', require('./routes/root'))

app.all('*', (req, res) => {
    res.status(404);
    if (req.accepts('html')){
        res.sendFile(path.join(__dirname, '/views/404.html'));
    } else if (req.accepts('json')){
        res.send({error: 'Not found'});
    } else {
        res.type('txt').send('Not found');
    }
})

app.use(errorHandler);

app.listen(PORT, ()=>{
    console.log(`Server is running on port ${PORT}`);
})

Does anyone know why is this occuring and how can I fix this problem? I tried searching for solutions online but the problems don’t seem to match mine as they are more advanced. Thanks.

How can i add fetchpriority dom attribute in nextjs using a js file

enter image description here
Getting this error in nextjs

I have tried fetchpriority=’high’ attribute to Image of next but its still showing the warning. Also tried with data prefix with fetchpriority but still the warning is same. Also i tried to create a declare module file but that file is only supported for typescript.
Please provide a solution so that this warning should be removed from my console.This warning is effecting my performance.

Is my understanding of Node.js architecture (single-threaded event loop with libuv) correct

I have started working on concurrency in Node.js, but I am unsure if my understanding of Node.js event loop architecture is correct because everybody on the internet has a different view of how Node.js runs code under the hood. After hours of researching, I have come up with this diagram, which represents how I think Node.js executes JavaScript on the server side.
enter image description here

According to me, Node.js comes bundled with Google’s V8 and libuv. V8 converts and executes JavaScript. All tasks that can’t initially be executed by V8 are offloaded to libuv for processing, such as the setTimeout async task.

**
The flow according to me is:**

  1. Write JS in english
  2. V8 interprets source code to machine bytecode line by line
  3. Bytecode is pushed to stack where V8 executes it
  4. Bytecode which cannot be processed initally such as settimeout async tasks are offloaded to libuv which returns a callback after async process is completed
  5. callback is added to taskqueue which should be called a callback queue
  6. event loop check if stack is empty and adds the callback to the stack
  7. V8 executes the callback

Is my diagram and flow correct? I’m certain there are significant gaps in my explanation. Please help me in understanding them.

sap.ui.comp.filterbar – Clear of filters works in BAS but not in hosted BSP application

I have a strange behaviour in my UI5-freestyle application.
It is being developed in BAS, with JS, freestyle UI5, and the backend is CDS ala RAP via Eclipse.

If i want to clear all filters inside the filterbar of my orders-table, it works only inside the bas webide.

It does not work, if I navigate using the url of the index.html of the bsp app.
The browser debugging tools do NOT show any exception / error.
The filters are simply not cleared.
Any clue what might cause this ?

enter image description here

Why The Output is 4 Explain? [closed]

<html>
    <script>
        let user1=[342,4344,43];
        let user2=("424","100");
        let join=user1.concat(user2);
        document.writeln(join.length);
        </script>
 </html>

I M Trying to get length expected 5 but not get as i expect can you explain in deep why not happening and reason of coming 4

An uncaught Exception was encountered Type: TypeError Message: Master_Matakuliah::update():

i’ve got an error says :
An uncaught Exception was encountered
Type: TypeError

Message: Master_Matakuliah::update(): Argument #1 ($id) must be of type id, string given, called in C:xampphtdocssisfo_akademiksystemoreCodeIgniter.php on line 532

this is my controller :
‘public function update($id)
{
$where = array(‘id’=> $id);
$data[‘master_matakuliah’] = $this->master_matakuliah_model->edit_data($where, ‘master_matakuliah’)->result();
$this->load->view(‘templates_administrator/header’);
$this->load->view(‘templates_administrator/sidebar’);
$this->load->view(‘administrator/master_matakuliah_update’, $data);
$this->load->view(‘templates_administrator/footer’);

    }'

line graph is not displaying in React Native

I Am using react-native-gifted-charts for displaying line chart and creating the data object for given array. and below is my code where i have done for linechart but lines are not displaying

import React, { useEffect, useState } from 'react';
import { Image, Text, TouchableOpacity, View } from 'react-native';
import arrow_dropdown from '../../../../assets/images/arrow_dropdown.png';
import styles from './Styles';
import { SCREEN_HEIGHT, SCREEN_WIDTH } from '../../../../components/dimensions/Index';
import { LineChart } from 'react-native-gifted-charts';
import { Dropdown } from 'react-native-element-dropdown';
import { symptomTracker } from '../../../../services/residentServices/HealthTrackerService';
import moment from 'moment';
import { getAuthData } from '../../../../services/PaymentService';

const SymptomsTrack = ({
  navigation,
  symptom_lookupId,
  onUpdateTitles,
  patient_lookup_id,
}) => {
  const [active, setActive] = useState(false);
  const [active1, setActive1] = useState(false);
  const [filter, setFilter] = useState('month');
  const [placeholder, setPlaceholder] = useState('Monthly');
  const [symptomsTitles, setSymptomsTitles] = useState([]);
  const [lineData, setLineData] = useState([]);
  const d = new Date();
  const colors = [
    '#2980b9',
    '#27ae60',
    '#f39c12',
    '#e74c3c',
    '#8e44ad',
    '#2ecc71',
    '#d35400',
    '#34495e',
  ];
  const filterData = [
    { label: 'Daily', value: 'day' },
    { label: 'Monthly', value: 'month' },
    { label: 'Weekly', value: 'week' },
  ];

  useEffect(() => {
    fetchGraphData();
  }, [symptom_lookupId, filter]);

  const fetchGraphData = async () => {
    const { lookupId, type } = await getAuthData();
    let data = {};
    if (type === 'nurse') {
      data = {
        from_date: moment(d).subtract(1, 'months').format('YYYY-MM-DD'),
        lookup_id: patient_lookup_id,
        symto_lookup_id: symptom_lookupId,
        to_date: moment(d).format('YYYY-MM-DD'),
        type: filter,
      };
    } else {
      data = {
        from_date: moment(d).subtract(1, 'months').format('YYYY-MM-DD'),
        lookup_id: lookupId,
        symto_lookup_id: symptom_lookupId,
        to_date: moment(d).format('YYYY-MM-DD'),
        type: filter,
      };
    }

    try {
      const res = await symptomTracker(data);

      const symptomsArray = res?.symptoms?.map(item => ({
        symptomTitle: item.title,
        lookup_id: item.lookup_id,
      }));
      onUpdateTitles(symptomsArray);

      const groupedSymptomData = {};
      res.data.forEach(item => {
        if (item.symptoms) {
          item.symptoms.forEach(symptom => {
            if (!groupedSymptomData[symptom.lookup_id]) {
              groupedSymptomData[symptom.lookup_id] = {
                data: [],
                color: colors[Object.keys(groupedSymptomData).length % colors.length],
              };
            }
            groupedSymptomData[symptom.lookup_id].data.push({
              value: symptom.value,
              label: new Date(item.modified).toLocaleDateString(),
            });
          });
        }
      });

      const lineDataUpdated = Object.keys(groupedSymptomData).map(key => ({
        data: groupedSymptomData[key].data,
        color: groupedSymptomData[key].color,
      }));

      console.log(JSON.stringify(lineDataUpdated, null, 2)); // Debugging line to check the formatted data

      setLineData(lineDataUpdated);
    } catch (error) {
      console.error('Error:', error);
    }
  };

  return (
    <>
      <View style={styles.contentContainer}>
        <View
          style={{
            flexDirection: 'column',
            justifyContent: 'space-between',
            paddingBottom: SCREEN_HEIGHT * 0.01,
          }}>
          <Dropdown
            style={styles.container}
            placeholderStyle={styles.container_text}
            selectedTextStyle={styles.container_text}
            iconStyle={styles.iconStyle}
            iconColor={'#1492E6'}
            data={filterData}
            maxHeight={SCREEN_HEIGHT * 0.5}
            labelField="label"
            valueField="value"
            placeholder={placeholder}
            value={filter}
            renderRightIcon={() => (
              <Image source={arrow_dropdown} style={styles.iconStyle} />
            )}
            onChange={item => {
              setFilter(item.value);
            }}
          />
          <Text
            style={[styles.container_text, { marginLeft: SCREEN_WIDTH * 0.01 }]}>
            {moment(d).format('DD MMM YYYY')}
          </Text>
        </View>
        <TouchableOpacity
          style={
            active
              ? [styles.container1, { borderColor: '#4191DF' }]
              : styles.container1
          }
          onPress={() => {
            setActive(true), setActive1(false);
          }}>
          <View style={{ alignItems: 'center' }}>
            <Text style={styles.container_text}>Compare to</Text>
            <Text style={styles.container_text}>Baseline</Text>
          </View>
          <Text style={styles.count_text}>- -</Text>
        </TouchableOpacity>
        <TouchableOpacity
          style={
            active1
              ? [styles.container1, { borderColor: '#4191DF' }]
              : styles.container1
          }
          onPress={() => {
            setActive(false), setActive1(true);
          }}>
          <View style={{ alignItems: 'center' }}>
            <Text style={styles.container_text}>Average</Text>
            <Text style={styles.container_text}>Rating</Text>
          </View>
          <Text style={styles.count_text}>- -</Text>
        </TouchableOpacity>
      </View>

      <View style={{ marginTop: 10, alignSelf: 'center' }}>
        {lineData.length > 0 ? (
          <LineChart
            data={lineData}
            height={300}
            width={SCREEN_WIDTH * 0.9}
            thickness={2}
            yAxisTextStyle={{ color: 'black' }}
            xAxisTextStyle={{ color: 'black' }}
            hideAxesAndRules={false}
            showVerticalLines
            yAxisTextNumberOfLines={11} 
            maxValue={10}
            minValue={0}
            spacing={44}
            initialSpacing={0}
            textColor1="green"
            textShiftY={-2}
            textShiftX={-5}
            textFontSize={13}
            showDataPoints
            dataPointsHeight={6}
            dataPointsWidth={6}
            dataPointsRadius={3}
            isAnimated
          />
        ) : (
          <LineChart
            data={[{ value: 0, label: '' }]} // Empty data to show axes
            height={300}
            width={SCREEN_WIDTH * 0.9}
            thickness={2}
            yAxisTextStyle={{ color: 'black' }}
            xAxisTextStyle={{ color: 'black' }}
            hideAxesAndRules={false}
            showVerticalLines
            yAxisTextNumberOfLines={11}
            maxValue={10}
            minValue={0}
            spacing={44}
            initialSpacing={0}
            textColor1="green"
            textShiftY={-2}
            textShiftX={-5}
            textFontSize={13}
          />
        )}
      </View>
    </>
  );
};

export default SymptomsTrack;

Below is the linedata i am genarting from the api respons eiget but lines are not displaying for this below array.

[
  {
    "data": [
      {
        "value": 0,
        "label": "6/3/2024"
      },
      {
        "value": 5,
        "label": "6/19/2024"
      },
      {
        "value": 6,
        "label": "6/19/2024"
      }
    ],
    "color": "#2980b9"
  },
  {
    "data": [
      {
        "value": 0,
        "label": "6/3/2024"
      },
      {
        "value": 7,
        "label": "6/19/2024"
      },
      {
        "value": 3,
        "label": "6/19/2024"
      }
    ],
    "color": "#27ae60"
  },
]