Why my bubble sort dosnt work when i add Drag and Drop?

When I added Drag and Drop, sorting by dates and letters stopped working for me. I understand that this is due to the fact that I do sorting when I do “map”. And I add a new sorting method for dragged objects there. How can this be fixed?

This is my Drag and Drop function:

    function dragStartHandler(e, item) {
    console.log(item)
    setCurrentItem(item)
}

function dragEndHandler(e) {

}

function dragOVerHandler(e) {
    e.preventDefault()
}

function dragHandler(e, item) {
    e.preventDefault()
    setTable([...table].map(c => {
        if (c.id === item.id) {
            return { ...c, order: currentItem.order }
        }
        if (c.id === currentItem.id) {
            return { ...c, order: item.order }
        }
        return c;
    }))
}

 const SortItems = (a, b) => {
     if (a.order > b.order) {
         return 1
     } else {
         return -1
     }
 }

Then i sort my array and use sort.

  table.sort(SortItems).map((item, id) => {
                return (
                    <tr
                        onDragStart={(e) => dragStartHandler(e, item)}
                        onDragLeave={(e) => dragEndHandler(e)}
                        onDragEnd={(e) => dragEndHandler(e)}
                        onDragOver={(e) => dragOVerHandler(e)}
                        onDrop={(e) => dragHandler(e, item)}
                        draggable={true}
                        key={item.id}>

But now my other sort function doesn’t work: enter image description here

  useEffect(() => {
setTable((table) => ([...table].sort((a, b) => !arrays ? a.data.year - b.data.year || a.month - b.month : b.data.year - a.data.year || b.month - 
   a.month)))
    }, [arrays])


const sortByText = () => {
setTable((table) => ([...table].sort((a, b) => a.text.toLocaleLowerCase > b.text.toLocaleLowerCase ? 1 : -1)))
  }

How can i fix this?

Counting from object Javascript [closed]

So I have a object like this:

const update = [
    {
        id: "1.0x",                         //
        version: [                          //
            {                               //
                id:"100",                   //
                version:"1.0.0",            //
                description:"Null"          // Result = 1
            },                              //
            {                               //
                id: "101",                  //
                version: "1.0.1",           //
                description: "Null"         //
            }                               //
        ],                                  

        id: "1.1x",                         //
        version: [                          //
            {                               //
                id: "110",                  //
                version: "1.1.0",           //
                description: "Null"         // Result = 2
            },                              //
            {                               //
                id: "111",                  //
                version: "1.1.1",           //
                description: "Null"         //
            }                               //
        ],                                  //
    }
]

Now I want to counting to get Result = 2 and get something like this:

// Result = get count from update
if(Result %2 === 0) {
    //map for each object inside version and do some css stuff
}
else {
    //map for each object inside version and do some css stuff
}

What should I can do to counting from my object like that.

using node.js and found this error > ‘server’ is declared but its value is never read.ts(6133) > from “var server = app.listen(3000, listening);”

been doing the 8.6 in api2 folder but got this error/bug then I look at my server.js and found the error/bug then I go back to api1 folder which is the 8.5 lesson, I have finish the 8.5 lesson and it doing correctly by save to json file and read json file just fine, but for some reason this happen when I go back to my api1??

The Coding Train

8.5: Saving Data to JSON File with Node.js – Programming with Text

https://www.youtube.com/watch?v=4zr8j-jeU_M&list=PLRqwX-V7Uu6Yyn-fBtGHfN0_xCtBwUkBp&index=6

The Coding Train

8.6: API Front End Client – Programming with Text

https://www.youtube.com/watch?v=4zr8j-jeU_M&list=PLRqwX-V7Uu6Yyn-fBtGHfN0_xCtBwUkBp&index=6

//

This is my error/bug

var server = app.listen(3000, listening);

var server: Server

‘server’ is declared but its value is never read.ts(6133)

//

this is my file and folder

api1 //folder

node_modules //folder

package-lock.json //file

server.js //file

var fs = require('fs');
var data = fs.readFileSync('words.json');
var words = JSON.parse(data);
console.log(words);

//console.log('server is starting');

var express = require('express');

var app = express();

var server = app.listen(3000, listening);

function listening () {
    console.log("listening...");
}

app.use(express.static('website'));

app.get('/add/:word/:score?', addWord);

function addWord(request, response) {
    var data = request.params;
    var word = data.word;
    var score = Number(data.score);
    var reply;
    if (!score) {
       var reply = {
            msg: "Score is required."
        }
        response.send(reply);
    } else{
        words[word] = score;
        var data = JSON.stringify(words, null, 2);
        fs.writeFile('words.json', data, finished);

        function finished(err) {
            console.log('all set.');
            reply = {
                word: word,
                score: score,
                status: "success"
            }

            response.send(reply);
        }
        
    }

}

app.get('/all', sendAll);

function sendAll(request, response) {
    response.send(words);
}

app.get('/search/:word/', searchWord);

function searchWord(request, response) {
    var word = request.params.word;
    var reply;
    if (words[word]) {
        reply = {
            status: "found",
            word: word,
            score: words[word]
        }
    } else {
        reply = {
            status: "not found",
            word: word
      }
    }
response.send(reply);
}

website //folder

index.html //file

words.json //file

{
  "rainbow": 5,
  "unicorn": 3,
  "doom": -3,
  "gloom": -2,
  "purple": 3,
  "pink": 6,
  "flower": 7
}

Convert Age to date of birthday [closed]

I have this example 46 years old i want to convert 46 to a date of birth with JS any solution please?
I just want to get the Year of birth
I found a solution for a date to age but what I want is to enter a number like 46 and give me date of birthday 01/01/Year

How can I update the quantity property of a cart item product in this Angular 13 e-commerce app?

I am working on an e-commerce app who’s front-end is made in Angular 13.

The below code is intended to sum the prices of the items in the cart:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: '.app-top-cart',
  templateUrl: './top-cart.component.html',
  styleUrls: ['./top-cart.component.css']
})
export class TopCartComponent implements OnInit {
  cartItems: any = [
    {
      id: 1,
      title: "iPhone 9",
      description: "An apple mobile which is nothing like apple",
      price: 549,
      discountPercentage: 12.96,
      rating: 4.69,
      stock: 94,
      brand: "Apple",
      category: "smartphones",
      thumbnail: "https://dummyjson.com/image/i/products/1/thumbnail.jpg",
      images: [
        "https://dummyjson.com/image/i/products/1/1.jpg",
        "https://dummyjson.com/image/i/products/1/2.jpg",
      ]
    },
    {
      id: 2,
      title: "iPhone X",
      description: "SIM-Free, Model A19211 6.5-inch Super Retina HD display with OLED technology A12 Bionic chip with ...",
      price: 899,
      discountPercentage: 17.94,
      rating: 4.44,
      stock: 34,
      brand: "Apple",
      category: "smartphones",
      thumbnail: "https://dummyjson.com/image/i/products/2/thumbnail.jpg",
      images: [
        "https://dummyjson.com/image/i/products/2/1.jpg",
        "https://dummyjson.com/image/i/products/2/2.jpg",
      ]
    },
    {
      id: 3,
      title: "Samsung Universe 9",
      description: "Samsung's new variant which goes beyond Galaxy to the Universe",
      price: 1248,
      discountPercentage: 15.46,
      rating: 4.09,
      stock: 36,
      brand: "Samsung",
      category: "smartphones",
      thumbnail: "https://dummyjson.com/image/i/products/3/thumbnail.jpg",
      images: [
        "https://dummyjson.com/image/i/products/3/1.jpg"
      ]
    },
  ];

  constructor() { }

  totalPrice: number = 0;

  doTotalPrice(){
    let total = 0;
    this.cartItems.forEach((item: { price: number, quantity: number }) => {
      item.quantity = 1;
      total += item.price * item.quantity
    });
    this.totalPrice = total;
  }

  ngOnInit(): void {
    this.doTotalPrice();
  }

}

The problem

I have not been able to find a way to update item.quantity whenever one more piece of a product is added to the cart.

How can I update the quantity count?

LG WebOS doesn’t clear localStorage when app is reinstalled

The application fails LG QA processing because the “token” is stored in localStorage when uninstalling the application and re-installing is there a way to remove localStorage when uninstalling? They send this text in the QA process response.

Condition : Start App > Login > Main page > Delete App > Reinstall App > Restart App > Check page.

Error Type : Login (or Logout) error/ Payment error

Problem : When restart the App after deleting, it login automatically.

Opinion : –

Expected : When restart the App after deleting, it should not login automatically and login page should appear.

Issue Device : webOS5.0( K6Lp, K6Hp, O20, E60 ), webOS6.0( LM21U, O20N, K7Lp, E60+F20, LM21A, LM21U FHD )

How to contain ‘mousemove’ effect INSIDE a

When I add mousemove event I am getting it all over my page. I want it inside my div only. when my cursor leaves the div it should not show the effect I have added. please help me to solve this. thankyou

Screenshot for clarification

Here is my code (HTML, CSS, and JS included)

index.html

<body>
    
    <div class="container">
        <div class="hex"></div>
        <div class="bg"></div>
    </div>

    <script src="index.js"></script>
</body>

style.css

.container {
    height: 800px;
    width: 100%;
    background-color: #000;
    position: relative;
}

.hex {
    background: url("images/Hexagon.svg") repeat;
    height: 800px;
    width: 100%;
    position: absolute;
    background-size: 500px;
    z-index: 1;
}

.bg {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    height: 300px;
    width: 300px;
    background: linear-gradient(90deg, #335bfa 0%, #2ae9c9 100%);
    filter: blur(20px);
    z-index: 0;
    overflow: none;
}

index.js

 const BG = document.querySelector(".bg");

 document.querySelector(".container").addEventListener("mousemove", function(e) {
     BG.style.left = e.clientX + "px";
     BG.style.top = e.clientY + "px";
 });

Making a dynamically resizable Canvas according to the image drawn in it

I am trying to make a dynamically resizable canvas whose width and height can be changed depending on the Image I am trying to load in it and also scaling it down.
I have been able to achieve resizable Canvas according to the image width and height, but The Image loads first and then the canvas width and height changes thus Image becomes stretched.

How can I make it so that the canvas resizes first and then the image loads?

    let newLowerImgWidth, newLowerImgHeight;
    var lower_canvas = document.getElementById('lower-canvas');

    function loadImg(){
    
    var ctx = lower_canvas.getContext('2d')
    , lower_img = new Image()
    , f = document.getElementById("lower_image").files[0]
    , url = window.URL || window.webkitURL
    , src = url.createObjectURL(f);
    
    lower_img.src = src;
    lower_img.onload = () => {
        ctx.clearRect(0, 0, lower_canvas.width, lower_canvas.height);

        // Scalling down the image
        newLowerImgWidth = Math.round(lower_img.width * 0.2);
        newLowerImgHeight = Math.round(lower_img.height * 0.2);
        
        // trying to apply width and height to canvas width and height
        lower_canvas.style.width = newLowerImgWidth+"px";
        lower_canvas.style.height = newLowerImgHeight+"px";

        ctx.drawImage(lower_img, 0, 0, newLowerImgWidth, newLowerImgHeight);
        url.revokeObjectURL(src);
        }
    }

My Depth First Search function seems not to return list of visited nodes i need to Visualize on front-end

I am writing my own visualizer based on this tutorial here https://github.com/clementmihailescu/Pathfinding-Visualizer-Tutorial,
I created a depth-first algorithm based on the javascript example in the Oreilly Book, data structures, and algorithms, example below here

    function dfs(v) {
        this.marked[v] = true;
        // if statement for print is not required
        if (this.adj[v] != undefined)
            print("Visited vertex: " + v);
        for each(var w in this.adj[v]) {
            if (!this.marked[w]) {
                this.dfs(w);
            }
        }
    }

Below is my implementation of the algorithm in my own react app is below here, the grid parameter is simply a 2-dimensional array of nodes, the closestNode being the start node to begin from, and the finishNode is the node to cancel the operation once reached, visitedNodesInOrder is an array to kept track of nodes being visited

export function startDfs(grid, closestNode, finishNode, visitedNodesInOrder) {
  // console.log(closestNode);
  closestNode.isVisited = true;
  if (closestNode !== undefined) {
    visitedNodesInOrder.push(closestNode);
  }

  var unvisitedNeighbors = getUnvisitedNeighbors(closestNode, grid);

  for (var x = 0; x < unvisitedNeighbors.length; x++) {
    if (!unvisitedNeighbors[x].isVisited) {
      if (unvisitedNeighbors[x].isWall) {
        continue;
      }
      if (unvisitedNeighbors[x] === finishNode) {
        return visitedNodesInOrder;
      }
      startDfs(grid, unvisitedNeighbors[x], finishNode, visitedNodesInOrder);
    }
  }
}



function getUnvisitedNeighbors(node, grid) {
  const neighbors = [];
  const {col, row} = node;
  if (row > 0) neighbors.push(grid[row - 1][col]);
  if (row < grid.length - 1) neighbors.push(grid[row + 1][col]);
  if (col > 0) neighbors.push(grid[row][col - 1]);
  if (col < grid[0].length - 1) neighbors.push(grid[row][col + 1]);
  return neighbors.filter(neighbor => !neighbor.isVisited);
}

My final intention is to collect the visitedNodesInOrder array and animate the list of nodes on the grid i created on the front end, the 2D array is an exact reflection of the grid i made on the front end using a map function to map the original 2D List with nodes to an HTML, CSS DOM layout, my final implementation that’s giving me an error is below

 visualizeDijkstra() {
    var nodesInShortestPathOrder = [];
    var visitedNodesInOrder = [];
    const {grid} = this.state;
    const startNode = grid[START_NODE_ROW][START_NODE_COL];
    const finishNode = grid[FINISH_NODE_ROW][FINISH_NODE_COL];
    var start = new Date().getTime();
    visitedNodesInOrder = startDfs(
      grid,
      startNode,
      finishNode,
      visitedNodesInOrder,
    );
    console.log(visitedNodesInOrder);
    boardToClear = visitedNodesInOrder;
    //nodesInShortestPathOrder = getNodesInShulortestPathOrder(finishNode);
    var stop = new Date().getTime();
    elasped = stop - start;

    this.animateDijkstra2(visitedNodesInOrder);
  }

this is the error i am getting below, i don’t understand what happened to the array

PathfindingVisualizer.jsx:113 Uncaught TypeError: Cannot read properties of undefined (reading 'length')
    at PathfindingVisualizer.animateDijkstra2

AJAX dynamic dropdown error only show first row data from db relationship

so i have error when i want to do dynamic dropdown by using AJAX and Jquerry.
the problem is when i choose a Province A, it’s retrieving City that belongs to Province A, but when i Choose Province B, it’s still retrieveing City from Province A too , the same thing happened when i choose Province B,C,D etc.. its still retrieving City from Province A which is in this DB, province A was the first row from province table

here my Screenshot

enter image description here


enter image description here

here’s my code html :

                                            <div class="form-group">
                                            <label class="font-weight-bold">PROVINSI ASAL</label>
                                            <select class="form-control provinsi-asal" name="province_origin">
                                                <option value="0">-- pilih provinsi asal --</option>
                                                @foreach ($provinces as $province => $value)
                                                    <option value="{{ $province }}">{{ $value }}</option>
                                                @endforeach
                                            </select>
                                        </div>
                                        <div class="form-group">
                                            <label class="font-weight-bold">KOTA / KABUPATEN ASAL</label>
                                            <select class="form-control kota-asal" name="city_origin">
                                                <option value="">-- pilih kota asal --</option>
                                            </select>
                                        </div>

here my ajax :

$('select[name="province_origin"]').on('change', function() {
            let provinceId = $(this).val();
            if (provinceId) {
                jQuery.ajax({
                    url: 'transaction/cities/'+ rovinceId,
                    type: "GET",
                    dataType: "json",
                    success: function(response) {
                        $('select[name="city_origin"]').empty();
                        $('select[name="city_origin"]').append(
                            '<option value="">-- pilih kota asal --</option>');
                        $.each(response, function(key, value) {
                            $('select[name="city_origin"]').append(
                                '<option value="'+ key +'">' + value +
                                '</option>');
                        });
                    },
                });
            } else {
                $('select[name="city_origin"]').append(
                    '<option value="">-- pilih kota asal --</option>');
            }

FUnction in controller to get the province,cities

 public function getCities($id)
{
    $city = City::where('province_id', $id)->pluck('name', 'city_id');
    return response()->json($city);
}

Document scroll height in Vue not working

I’m aiming to retrieve the full scrollable height of my page using:

document.body.scrollHeight

but all I get back is the height of the viewport and not the full height of the scrollable page.

I’m running this in a method that is called after mounted. It’s even in a nexttick function. I need this to randomly place images over the full height of the page. It could be something to do with Vue’s reactivity(?) and the DOM not updating quick enough for my method to get the full document height?

What is a different way I can get the scroll height of a document in Vue that will actually work?


<script>
export default {
data() {
 return {
   images: [
     require("@/assets/img/icons/1.png"),
     require("@/assets/img/icons/2.png"),
   ],
   addedImage: [],
   imgTop: 150,
   imgLeft: 900,
   imgHeight: 64,
   imgWidth: 64,
   selectedImage: "",
   nextId: 100,
 };
},
mounted() {
 this.randomImage();
 this.$nextTick(() => {
   for (let i = 0; i < 40; i++) {
     this.randomImage();
     this.addImage();
     this.randomPosition();
   }
 });
},

methods: {
 randomImage() {
   const idx = Math.floor(Math.random() * this.images.length);
   this.selectedImage = this.images[idx];
 },
 randomPosition() {
   const randomPos = (twoSizes) => Math.round(Math.random() * twoSizes);
   this.imgTop = randomPos(document.body.scrollHeight - this.imgHeight);
   this.imgLeft = randomPos(window.innerWidth - this.imgWidth);
 },
 addImage() {
   this.addedImage.push({
     style: {
       top: `${this.imgTop}px`,
       left: `${this.imgLeft}px`,
       height: `${this.imgHeight}px`,
       width: `${this.imgWidth}px`,
     },
     src: this.selectedImage,
     id: this.nextId++,
   });

 },

},
};
</script>

Hacky way to make VueJS save the state of input values changed by Javascript

Hacky way to make VueJS save the state of input values changed by Javascript

resetFieldValue: function ($event) {
                $event.target.value = null;
                $event.currentTarget.dispatchEvent(new Event('input'));
            }

Will come in useful when doing validation in VueJS.
Example: Setting an input field to NULL when input value fails validation.

Sorry, typing this on stackoverflow cause I spent hours finding this answer. Am hoping it’ll benefit others too.

Copy image to clipboard chrome 70

I’m developing a feature of copying image. and It doesn’t work for me on Chrome 70,
Is this possible?
I think it might be a security limitation.

The clipboard API allows only copying text, the write function is undefined

await navigator.clipboard.write([
      new ClipboardItem({
        [blob.type]: blob
      })
    ])

also tried this implementation

function copyElementToClipboard(element) {
  window.getSelection().removeAllRanges();
  let range = document.createRange();
  range.selectNode(typeof element === 'string' ? document.getElementById(elementName) : element);
  window.getSelection().addRange(range);
  document.execCommand('copy');
  window.getSelection().removeAllRanges();
 }

but it doesnt work.

How should I enable and implement this feature?

Onchange Action Switch btn

I am struggling trying to make my switch btn work.

<div class="custom-control custom-switch" id="off">
  <%= form_for @review, url: "#", method: :put, remote: true do |f| %>
<%= f.check_box :switch, value: :true, class:"custom-control-input toggles", id: "customSwitch1" %>
<label class="custom-control-label" for="customSwitch1"> </label>
<p>Activate instructions</p>
  <% end %>
</div>

<div class="custom-control custom-switch" id="on">
  <%= form_for @review, url: "/reviews/#{@review.id}", method: :put, remote: true do |f| %>
<%= f.check_box :switch, value: :false, class:"custom-control-input toggles", id: "customSwitch2" %>
<label class="custom-control-label disabled" for="customSwitch2"> </label>
<p>Desactivate instructions</p>
  <% end %>
</div>

My idea was to add an “onchange=” “” into the two f.check_box
But I can’t seem to get the behavior right. Which is when I click on the radio btn, a text appears, then when I click on it again, it disappears

Do you have a clue for me?

Thanks