react-image-annotate – How to save an image along with the annotations?

The npm package react-image-annotate gives a decent react component to annotate images.

This component uses a tag called <ReactImageAnnotate /> for the annotate window. It has a prop called onExit which will give the details of all the data of that image we are working on.

My question is:
Suppose I did mark some things using a box in the image, and now I want to save/export/download that image along with that box. How can we do that?

OIDC client silent refresh multiple times

Here is my client config:

const settings = {
      userStore: new WebStorageStateStore({ store: window.localStorage }),
      client_id: 'authtest',
      automaticSilentRenew: true,
      accessTokenExpiringNotificationTime: 10,
      response_type: 'code',
      scope: 'openid profile email offline_access',
    };

Silent refresh page is a static html page

<!DOCTYPE html>
<html>
  <head>
    <title>Silent Renew Token</title>
  </head>
  <body>
    <script
      src="https://cdnjs.cloudflare.com/ajax/libs/oidc-client/1.11.5/oidc-client.min.js"
      integrity="sha512-pGtU1n/6GJ8fu6bjYVGIOT9Dphaw5IWPwVlqkpvVgqBxFkvdNbytUh0H8AP15NYF777P4D3XEeA/uDWFCpSQ1g=="
      crossorigin="anonymous"
      referrerpolicy="no-referrer"
    ></script>
    <script>
      console.log('renewing tokens');
      new Oidc.UserManager({
        userStore: new Oidc.WebStorageStateStore({ store: window.localStorage }),
      }).signinSilentCallback();
    </script>
  </body>
</html>

I wanted to check how exactly it works and there is something strange:
token request is being sent multiple times (6x)

Is this supposed to work like that? My [PersistedGrant] table is growing very fast during this test (6 records every 50 seconds). What is the problem and how to solve it?

removing an element in array within map in react

On the click of the span, i want to remove that element from the array and run the map again so that the spans also gets removed. I don’t know if the syntax is wrong or what. This is the link to sandbox where I wrote my code. https://codesandbox.io/s/angry-wu-4dd11?file=/src/App.js

import "./styles.css";

export default function App() {
  const data = [{
      name: "Alex",
    },
    {
      name: "John",
    },
    {
      name: "Leo",
    },
    {
      name: "Murphy",
    },
    {
      name: "Alex",
    },
    {
      name: "John",
    },
    {
      name: "Leo",
    },
    {
      name: "Murphy",
    },
  ];

  return ( <
    div className = "App" > {
      data.map(function(val, id) {
        return ( <
          span key = {
            id
          }
          className = "select__item"
          onClick = {
            (e) => {
              data.splice(data.indexOf(val), id + 1);
              console.log(data);
            }
          } >
          {
            val.name
          } < br / > < br / >
          <
          /span>
        );
      })
    } <
    /div>
  );
}

How do you add toggle functionality to a wishlist button to add and remove items from a wishlist?

I have made a wishlist where I add items to a wishlist by a button and remove the items from within the wishlist itself by pressing a cross next to the item. However, I need the button to add AND remove items too by having a toggle functionality on the button itself. Can anybody help?

$(document).ready(function() {
      $(".wishlist").on("click", function() {
        $data = "";
        $item_id = $(this).attr("item_id");
        $item_name = $(this).attr("item_name");
        $item_str = "<tr class='wishlist-item' id='list_id_" + $item_id + "'><td class='w-pname'>" + $item_name + "</td><td class='w-premove' wpid='" + $item_id + "'>x</td></tr>";
        //check if the element is in the array
        if ($.inArray($item_id, wish_list) == -1) {


          $("#wish_list_item").append($item_str);

          wish_list.push($item_str);
          localStorage.setItem(wishlistkey, JSON.stringify(wish_list))
          show_message($item_name + " Item Added");
        }
        count_items_in_wishlist_update();
      });

Objects are not valid as a React child (found: object with keys {_id, name}) if i use populate in server side code

if i put populate in server side code i am getting error like this Uncaught Error: Objects are not valid as a React child (found: object with keys {_id, name}). If you meant to render a collection of children, use an array instead.
if i remove the populate then code is working fine.
How can i solve this issue ?
My code is
ProductPage.js

import React, { useState } from "react";
import Layout from "../components/Layout/Layout";
import { Container, Row, Col, Table } from "react-bootstrap";
import { useDispatch, useSelector } from "react-redux";
import Input from "../components/UI/Input";
import { addProduct } from "../redux/actions";
import Modal from "../components/UI/Modal";
import "./Home.css";
import { generatePublicurl } from "../urlConfig";

function ProductsPage(props) {
  const category = useSelector((state) => state.category);
  const product = useSelector((state) => state.product);
  const dispatch = useDispatch();
  const [show, setShow] = useState(false);
  const [productDetailModail, setProductDetailModal] = useState(false);
  const [productDetails, setProductDetails] = useState(null);
  const [name, setName] = useState("");
  const [productPicture, setProductPicture] = useState([]);
  const [description, setDescription] = useState("");
  const [price, setPrice] = useState("");
  const [quantity, setQuantity] = useState("");
  const [categoryId, setCategoryId] = useState("");
  const handleClose = () => {
    const form = new FormData();
    form.append("name", name);
    form.append("description", description);
    form.append("price", price);
    form.append("quantity", quantity);
    form.append("category", categoryId);
    for (let pic of productPicture) {
      form.append("productPicture", pic);
    }

    dispatch(addProduct(form));

    setShow(false);
  };
  const handleShow = () => setShow(true);

  const createCategoryList = (categories, options = []) => {
    for (let category of categories) {
      options.push({ value: category._id, name: category.name });
      if (category.children.length > 0) {
        createCategoryList(category.children, options);
      }
    }
    console.log(options);
    return options;
  };

  const handleProductPicture = (e) => {
    setProductPicture([...productPicture, e.target.files[0]]);
  };

  const renderProducts = () => {
    return (
      <Table style={{ fontSize: 12 }} responsive="sm" className="mt-5">
        <thead>
          <tr>
            <th>#</th>
            <th>Product Name</th>
            <th>Price</th>
            <th>Quantity</th>
            <th>Category</th>
            <th>Created By</th>
          </tr>
        </thead>
        <tbody>
          {product.products.length > 0
            ? product.products.map((product) => (
                <tr
                  key={product._id}
                  onClick={() => showProductDetailsModal(product)}
                >
                  <td>1</td>
                  <td>{product.name}</td>
                  <td>{product.price}</td>
                  <td>{product.quantity}</td>
                  <td>{product.category}</td>
                  <td>{product.createdBy}</td>
                </tr>
              ))
            : null}
        </tbody>
      </Table>
    );
  };

  const renderAddProductModal = () => {
    return (
      <Modal
        show={show}
        handleClose={handleClose}
        modalTitle={"Add New Product"}
        actionName={"Add Product"}
      >
        <Input
          label="Product Name"
          vale={name}
          placeholder="Product Name"
          onChange={(e) => setName(e.target.value)}
        />
        <Input
          label="Product Price"
          vale={price}
          placeholder="Product Price"
          onChange={(e) => setPrice(e.target.value)}
        />
        <Input
          label="Product Stock"
          vale={quantity}
          placeholder="Product Stock"
          onChange={(e) => setQuantity(e.target.value)}
        />
        <Input
          label="Product Description"
          vale={description}
          placeholder="Product Description"
          onChange={(e) => setDescription(e.target.value)}
        />
        <select
          value={categoryId}
          className="form-control"
          onChange={(e) => setCategoryId(e.target.value)}
        >
          <option>Select Category</option>
          {createCategoryList(category.categories).map((option) => (
            <option value={option.value} key={option.value}>
              {option.name}
            </option>
          ))}
        </select>
        {productPicture.length > 0 &&
          productPicture.map((pic, index) => <div key={index}>{pic.name}</div>)}
        <input
          className="mt-3"
          type={"file"}
          name="productPicture"
          onChange={handleProductPicture}
        />
      </Modal>
    );
  };
  const handleCloseProductDetailModal = () => {
    setProductDetailModal(false);
  };

  const showProductDetailsModal = (product) => {
    setProductDetails(product);
    setProductDetailModal(true);
  };
  const renderProductDetailsModal = () => {
    if (!productDetails) {
      return null;
    }
    return (
      <Modal
        size="lg"
        show={productDetailModail}
        handleClose={handleCloseProductDetailModal}
        modalTitle={"Product Details"}
        actionName={"Save Changes"}
      >
        <Row>
          <Col md="6">
            <label className="key">Product Name</label>
            <p className="value">{productDetails.name}</p>
          </Col>
          <Col md="6">
            <label className="key">Product Price</label>
            <p className="value">{productDetails.price}</p>
          </Col>
        </Row>
        <Row>
          <Col md="6">
            <label className="key">Product Quantity</label>
            <p className="value">{productDetails.quantity}</p>
          </Col>
          <Col md="6">
            <label className="key">Product Category</label>
            <p className="value">{productDetails.category}</p>
          </Col>
        </Row>
        <Row>
          <Col>
            <label className="key">Product Description</label>
            <p className="value">{productDetails.description}</p>
          </Col>
        </Row>
        <Row>
          <Col>
            <label className="key mb-3">Product Images</label>
            <div style={{ display: "flex" }}>
              {productDetails.productPictures.map((picture) => (
                <div className="productImageContainer ">
                  <img src={generatePublicurl(picture.img)} />
                </div>
              ))}
            </div>
          </Col>
        </Row>
      </Modal>
    );
  };
  return (
    <Layout sidebar>
      <Container>
        <Row>
          <Col md={12}>
            <div style={{ display: "flex", justifyContent: "space-between" }}>
              <h3>Products</h3>
              <button onClick={handleShow}>Add Product</button>
            </div>
          </Col>
        </Row>
        <Row>
          <Col>{renderProducts()}</Col>
        </Row>
        {renderAddProductModal()}
        {renderProductDetailsModal()}
      </Container>
    </Layout>
  );
}

export default ProductsPage;

initialData.js

const Product = require("../../models/product");
const Category = require("../../models/category");

function createCategories(categories, parentId = null) {
  const categoryList = [];
  let category;
  if (parentId == null) {
    category = categories.filter((cat) => cat.parentId == undefined);
  } else {
    category = categories.filter((cat) => cat.parentId == parentId);
  }

  for (let cate of category) {
    categoryList.push({
      _id: cate._id,
      name: cate.name,
      slug: cate.slug,
      parentId: cate.parentId,
      children: createCategories(categories, cate._id),
    });
  }
  return categoryList;
}

exports.initialData = async (req, res) => {
  const categories = await Category.find({}).exec();
  const products = await Product.find({})
    .select(
      "_id name slug price quantity category createdBy description productPictures"
    )
    .populate({ path: "category", select: "_id name" })
    .exec();
  res.status(200).json({
    categories: createCategories(categories),
    products,
  });
};

For ref please find the attached image also.

enter image description here

Flask, How to refresh an ajax url with a generated id

I am new in javascript, I have created a flask site and I would like to follow ansible tower job.
I have create a specific route :

@app.route("/tower/<int:id>", methods=['POST','GET'])
def status(id):
    launch = True
    job_info = {}
    status = refreshstatus(id)
    return render_template(
        'tower.html',
        job_info = job_info,
        status = status,
        launch = launch,
        id = id)

@app.route("/tower", methods=['POST','GET'])
def tower():
    launch = False
    if request.method == 'POST':
        keyword = request.form['launchjob']
        logger.info("Test | Keyword var => " + keyword)
        template_id = request.form['template_id']
        job_info = launch_job(template_id, keyword)
        launch = True
        return render_template('tower.html', job_info = job_info, launch = launch)
    else:
        return render_template('tower.html')

my js script:

function refresh() {
    $.ajax({
        url: '/tower/' + id,
        dataType: 'json',
        id: { id : job_info.job_id },
        success: function(data) {
        $('#statustable').html(data);
        }
      });
      setTimeout(refresh, 10000);
      console.log('refresh')
    };
$(function(){
      refresh();
});

and my html file

<th scope="row"></th>
<td> {{ job_info.job_id }}</td>
<td><p class="text-warning" id="statustable">{{ job_info.job_status }}</p></td>
<td><a href="{{ job_info.url }}" target="_blank">Lien vers le stdout</a></td>

When I refresh manually it works the job status changes, but no auto refresh.
Could you help ?

Thanks

David

access a property of an object

How do we access a certain property value from an object ? , I wanted to access the area value from territoryAreaDto. I tried element.territoryAreaDto[0].area but it does not work

#Sample Object (items) – items is an array of objects.

   {
    "id": 19,
    "region": "37",
    "repmid": 630,
    "territoryAreaDto": [
        {
            "id": 3,
            "regionId": 32,
            "territoryAssignmentsId": 19,
            "area": "121"
        }
    ]
}

#code

public static modifyTerritoryAssignmentsObject(items: any) {
    items.forEach(element => {
      if(element.territoryAreaDto) {
        
        console.log('element.territoryAreaDto.area;' , element.territoryAreaDto[0].area)
        element.area = element.territoryAreaDto.area;
      }
    })
    return items;
  }

WebView2 ExecuteScriptAsync with XML input

I want to run a C# function using ExecuteScriptAsync() with XML text as input.

Something like that:

var xml = "<?xml version="1.0" encoding="UTF - 16" standalone="no" ?><values>42</values>";
webView2Control.CoreWebView2.Navigate("file:///C:/Users/erezf/AppData/Local/Temp/index.html");
var input = "func(" + xml + ")";
await webView2Control.CoreWebView2.ExecuteScriptAsync(input);

The html file include the function func:

<script id="test" type="text/javascript">
    function func(xml) { alert(xml); }
</script>

This code doesn’t work, why?

Thanks,
Erez

DataTable Refresh with Two Methods

I have two trigger function that used for two functions. end point is once the objective is completed DataTable would be reloading. as per this case, One function is working when the other is not. The not working one’s process is a simple add function with a modal popup. once it is added it will be displayed on the datatable real-time. below is the function.

    //DOESN'T REFRESH TABLE

    $(document).on('click','#add',function(event){
        event.preventDefault();
        $('#add-cat').html('');
        var id = $(this).data('id');
        $.ajax({
            type:'POST',
            url:'../cat/modal/add.php',
            data:{id:id},
            success : function(data)
            {
                $('#add-cat').html(data);

                //TO REFRESH TABLE
                $('#example').DataTable().ajax.reload();
            }
        });
    });

The refreshing one real-time as per requirement is below

     //REFRESHES TABLE
     $(document).on('click','#con',function(event){
        if(confirm("Are you sure?")){
            event.preventDefault();
            var id = $(this).attr('data-id');
            $.ajax({
                url     : '../ord/stat.php',
                method  : 'POST',
                data    : {id : id},
                success : function(data)
                {
                    $('#example').DataTable().ajax.reload();
                }
            });
        }
        else{
            return false;
        }
    });

Why the first one is not updating the table and the second one is?

Regards.

My JavaScript file isn’t linking to my HTML file

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap" rel="stylesheet">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="css/main.css">
    <script src="./main.js"></script>
    <title>Florida Plan - Financing and Planning</title>
</head>
</html>

Internal JS works fine and I wouldn’t mind using it, but I want to start getting into the habit of using external JS files. I’ve tried linking it, and it doesn’t seem to work. I gave it a small test with just one line of code… Also, it didn’t correct itself after adding a semi-colon.

document.getElementById("rent").innerHTML = "56" // external

Internal worked

 <script>
    document.getElementById("rent").innerHTML = "56" // internal
 </script>

It only seemed to work in the script tag inside the HTML document. I’ve also tried specifying full paths to the file, which is in the same directory, it doesn’t seem to work. Screenshot of directory. If anyone could help, it’d be great!

data comes to controller but not to view

 public ActionResult Index()
        {
         
        GetEmployee();

        return View();
    }

    private void GetEmployee()
    {
       
        SocialMedia item = new SocialMedia();
        var employee = _employeeRepository.GetById(Session.GetEmployeeNo());           
           //employee.No, employee.ManagerNo
            item.FirstName = employee.FirstName;
            item.LastName = employee.LastName;
            item.Departmen = employee.PositionCode;
        item.FullName = item.FirstName + " " + item.LastName;
        
    }

And my HTML

@using Models.Model

@model Models.Model.SocialMedia
                            <div>
                                @Html.LabelFor(model => model.FullName)
                            </div>
                            <div>
                                @Html.LabelFor(model=>model.Departmen)
                            </div>

And My result is

FullName
Departmen

Name,surname and departmen were supposed to come but didn’t.
Can you help me

Using async() functions in eval() – discord.js

  • Recently, I tried the eval command in my bot using ‘await’ but since await is valid in async functions, I made the following aeval command.
  • The problem here is, it only returns undefined for everything I eval.
const { Base } = require("../../../lib/base");
const { inspect } = require("util");

module.exports = new Base({
    name: "aeval",
    description: "Owner only command to evaluate an asynchronous javascript code",
    async execute({ client, message, args }) {
        let script = args.join(" ");
        let evaled;
        let hrDiff;
        try {
            const hrTime = process.hrtime();
            evaled = await eval(`(async() => {${script}})()`);
            hrDiff = process.hrtime(hrTime);
            evaled = inspect(evaled);
            await message.reply(
                `Executed in `${hrDiff[1] / 1000000}` ms.n```jsn${inspect(
                    evaled
                )}n````
            );
        } catch (error) {
            console.log(error);
            message.reply(`Error Occurred:n```jsn${error}n````);
        }
    },
});

Why does outerWith give different values for some websites?

I wonder why window.outerWith gives me a bigger value at Stackoverflow.com than at other websites in my browser. I have just noticed this behaviour only on Firefox and Stackoverflow. Shouldn’t it be the same on all websites?

In MDN Web Docs it says:

Window.outerWidth read-only property returns the width of the outside
of the browser window. It represents the width of the whole browser
window including sidebar (if expanded), window chrome and window
resizing borders/handles.

Example outerWidth at fullscreen:

  • Stackoverflow: 2070
  • Discord.com and the others in my tabs: 1863

So far I haven’t found any website that has a similar behaviour.

console.log( window.outerWidth )

steps to to reproduce it

  1. visit stackoverflow.com
  2. open Developer Tool / Console
  3. write window.outerWitdh
  4. visit google.com or other side
  5. write window.outerWitdh in the console

In Firefox these two values are different. Stackoverflow has a larger value.

Function does not return value when use promise, JavaScript

I have a very few knowledge in JavaScript, so sorry in advance for this question.

I have a method:

function userAgent() {
            var result = "";

            navigator.userAgentData.getHighEntropyValues(["platformVersion"])
                .then(ua => {
                    if (navigator.userAgentData.platform === "Windows") {
                        const majorPlatformVersion = parseInt(ua.platformVersion.split('.')[0]);
                        if (majorPlatformVersion >= 13) {
                            console.log("Windows 11 or later");
                            result = "Windows 11 or later";
                        }
                        else if (majorPlatformVersion > 0) {
                            console.log("Windows 10");
                            result = "Windows 10";
                        }
                        else {
                            console.log("Before Windows 10");
                            result = "Before Windows 10";
                        }
                    }
                    else {
                        console.log("Not running on Windows");
                        result = "Not running on Windows";
                    }

                    
                });

            return result;
        }

And it returns empty string, but prints to console the correct value.

Please, tell me what is my mistake and how to return value here, I want to use it after.

Thank you!