How to Detect user if stopped at some unknown location base or a place from gps history data

I want to create a feature that contains the location history of the user itself every time it stops at a place.

For example, if the user stops at a location that I previously marked, it will display the name of the location, but if it stops at an unknown place, it will display the words “Unknown Stop”. Like the example below.

The following is an example of the location history of the user I have.

[{
"location": {
  "timestamp": 1640226572000,
  "fromMockProvider": false,
  "speedAccuracy": 3.0999999046325684,
  "speed": 2.126629114151001,
  "courseAccuracy": 60.29999923706055,
  "course": 335.00262451171875,
  "accuracy": 4.800000190734863,
  "altitudeAccuracy": 1.71183432826049805,
  "altitude": 6.099546432568,
  "longitude": 91.72313144,
  "latitude": 3.9974028
},
"device_information": "angelica ANGELICA Redmi",
"battery": 1},{
"location": {
  "timestamp": 1640226575000,
  "fromMockProvider": false,
  "speedAccuracy": 2.9000000953674316,
  "speed": 1.7470654249191284,
  "courseAccuracy": 67.80000305175781,
  "course": 318.0428161621094,
  "accuracy": 4.724999904632568,
  "altitudeAccuracy": 1.741869330406189,
  "altitude": 6.09213144568,
  "longitude": 91.7316444,
  "latitude": 3.9974605
},
"device_information": "angelica ANGELICA Redmi",
"battery": 1}]


//and more history in array

and the test code done, looks like it works with geolib library but has bugs in time

for (let i = 0; i < unknownArr.length; i++) {
    var dataPertama = unknownArr[i]
    var dataKedua = unknownArr[i + 1]
    if (dataKedua != undefined) {
        var selisihTotalKeduanya = hitungSelisihAngka(dataPertama.lama_unknown, dataKedua.lama_unknown)
        if (selisihTotalKeduanya > 10) {
            var jikaDekatToko = visitTimeArr.some(data => {
                var customerData = data.customer_data
                if (customerData.customer_latitude != null || customerData.customer_latitude != undefined) {
                    return isPointWithinRadius(
                        {
                            latitude: customerData.customer_latitude,
                            longitude: customerData.customer_longitude
                        },
                        {
                            latitude: dataPertama.start_unknown.location.latitude,
                            longitude: dataPertama.start_unknown.location.longitude
                        }, 100)
                } else {
                    return false
                }
            })
            var jikadiIntika = isPointWithinRadius(Strings.kordinatIntika, {
                latitude: dataPertama.start_unknown.location.latitude,
                longitude: dataPertama.start_unknown.location.longitude
            }, 100)

            if (!jikaDekatToko) {
                if (!jikadiIntika) {
                    response.push(unknownArr[i])
                } else {
                    var dataIntikaPertama = unknownArr.find(el => {
                        el.name = 'Intika'
                        return el !== undefined
                    })
                    response.push(dataIntikaPertama)
                }
            }
        }
    } else {
        var jikadiIntika = isPointWithinRadius(Strings.kordinatIntika, {
            latitude: dataPertama.start_unknown.location.latitude,
            longitude: dataPertama.start_unknown.location.longitude
        }, 100)
        if (!jikadiIntika) {
            response.push(unknownArr[i])
        } else {
            if (findFirstIntika) {
                var dataIntikaTerakhir = unknownArr[unknownArr.length - 1]
                if (dataIntikaTerakhir.name == 'Intika') {
                    response.push(dataIntikaPertama)
                }
            } else {
                var dataIntikaPertama = unknownArr.find(el => {
                    el.name = 'Intika'
                    return el !== undefined
                })
                response.push(dataIntikaPertama)
            }
        }
    }
}

The result but bug in time

getting sql error unknown column in where clause when trying to filter data

In the SQL query where city clause when I put string ‘delhi’ I get results but when I put a variable like below I get error unknown column delhi in where clause. how to solve the issue?

router.get('/filter/:city', (req, res) => {
  const location = req.params.city;
  const singleQuoteLocation = location.replace(/"/g, "'");
  connection.query(
    `select * from weather_data where city=${singleQuoteLocation}`,
    (err, results, field) => {
      if (err) {
        console.log(err);
      } else {
        res.status(200).send(results);
        console.log(results);
      }
    }
  );
});

When should I use functions as classes in Javascript?

I wish to create two sets of information that I’m going to re-use, one for a beer and one for a dispenser of beer, in Javascript.

The information is retrieved from an API, and all the beers are objects with an ID, name etc.

I’m wondering if I should bother with making each beer into a function like this:

function Beer() {
   this.Id = 0;
   this.Name = "";
   
   etc.
}

and then instantiate by setting a variable to a new Beer() through a forEach loop on the parsed JSON string. Is it worth it? Or should I just take the information directly from the API every time I reference different information about each beer? In other words, if this is not the time to use functions as pseudo-classes, when is?

If it helps, I’m writing in MVC, so I’m planning on having the information about the beer and the dispenser in my model, so I can use it with the controller and display it in my view very easily.

Function call from js script in ejs file tags

Suppose an ejs file for upvoting system:

<% if(clicked(post_id)==1) %>
    // load green button 
<%} else {%>
     // load red button

 <script>
 function clicked(id){
   if(currentUser.upvotes_downvotes===undefined)
       return -1;
   PreClicked = arr.find(clicked => {
        return clicked.postId.equals(id);})
   if(PreClicked === undefined)
    return 0;
   else if(PreClicked.type === "upvote")
     return 1;
   else if(PreClicked.type === "downvote")
     return 2;
     }
   </script>

But I am getting clicked is not defined

Passing array from tickboxes to a button- Jquery

So, I am trying to make id of each row into array and when the checked boxes are ticked, a button will show. From this button, we can have all the selected checkboxes id.
Notes: the checkboxes id actually likes this :

<input type="checkbox" id="chkT{$rows.id}" value="{$rows.id}" style="width: 15px; height: 15px;" class="js-checkbox single-row-checkbox" onchange="toggleTick_Change()" />

This is because, each row is getting it’s data from database, hence the {$rows.id}.
In the snippet, i delete the {$rows.id} just for example.

  1. the console.log is used for me to check whether the id is in array or not.
  2. I have tried the following codes regarding arrays, but the id’s are not in array.
let ids=[]
$(document).ready(function(){
    $('.js-checkbox').change (function() {
        if ($(this).attr('id') === 'chkAll'){
            if ($(this).prop('checked') === true){
                $('.single-row-checkbox').prop('checked', true);
                //ids.push($(this).attr("id")); 
                ids.push('.single-row-checkbox'.id);
                $('#conditional-part').show();
            }else if ($(this).prop('checked') === false){
                $('.single-row-checkbox').prop('checked', false);
                ids.pop($(this).attr("id"));
                //ids.pop(this.id);
                $('#conditional-part').hide();
            }
        } else if ($(this).attr('id') === 'chkT'){
            const checked = $('.single-row-checkbox');
                if (checked.length >= 2) {
                    $('#conditional-part').show();
                    //ids.push(this.id);
                    ids.push($(this).attr("id"));   
                } else {
                    $('#conditional-part').hide();
                    ids.pop($(this).attr("id"));
                }

        }
    });
});


I have achieve to make the selected checkbox into array using this code :

    let arr= [];
    function toggleTick_Change(){   
        var arr = $.map($('.single-row-checkbox:checkbox:checked'),     function(e, i) {
            return +e.value;
        });
        console.log('the checked values are: ' + arr.join(','));
        $('#conditional-part').show();
      
      //bind the event handler to it
          $arr.on('click', function(){
            btnPrintCNT_Click();
        });
    }

    function btnPrintCNT_Click(id){
        console.log('the checked values are: ' + id);   
    }
 #conditional-part{
    display:none;
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script>
<span id="conditional-part" >
      <div class="input-group "  role="group" aria-label="..." style="width: 85px; margin-top: 2px; " >
                <span class="input-group-btn">
                        <button id="btnPrintCNT" type="button" class="btn btn-sm btn-primary" style="margin: 2px; width: 100px; margin-left: 20px; float: left;"                        onclick="javascript:btnPrintCNT_Click()">CNT</button>
                </span>
            </div>
    </span>
                
    <input type="checkbox" id="chkT" value="{$rows.id}" style="width: 15px; height: 15px;" class="single-row-checkbox" onchange="toggleTick_Change()" />
    <input type="checkbox" id="chkT" value="{$rows.id}" style="width: 15px; height: 15px;" class="js-checkbox single-row-checkbox" onchange="toggleTick_Change()" />

But now, problem I faced are:

  1. How to call the id in array from ticked checkboxes to the button?
  2. How do I ticked all checkboxes without ticking it one by one?

Any help is highly appreciated. Thank you.

Angular – Apply decimal pipe to an input

I want to apply decimal pipe on an input so the user can see comma separated numbers as he/she types. I have tried the ngx-mask but that only works if you type in the input. When you patch a value to the input it doesn’t transform the value into decimal format.

Como puedo agregar objetos a un mismo item de LocalStorage?

Estoy empezando en JavaScript, tengo en mente crear una pagina de ventas, primero lo haré con local storage antes de meterme con bases de datos. creo que si puedo resolver esto podré hacer lo demás sin problema. Este script es solo para cuando haga el registro de los usuarios en la pagina, pero se guarda la misma información. Ya he intentado de muchas maneras, mi ultima opción ha sido preguntar.

CODIGO-JAVASCRIPT

const users = [], allUsers = []; // CREO LAS LISTAS DE LOS USUARIOS

// CLASE PARA GUARDAR LA INFORMACION DE LOS USUARIOS
class Users {
    constructor(id, nombre, edad, peso) {
        this.id = id;
        this.nombre = nombre;
        this.edad = edad;
        this.peso = peso;
    }
}

// SE PIDEN LOS DATOS DE CADA USUARIO
const id = getRandom();
const nombre = prompt('Nombre del nuevo usuario');
const edad = parseInt(prompt('Edad del nuevo usuario'));
const peso = prompt('Peso del nuevo usuario');
users.push(new Users(id, nombre, edad, peso));

// PREGUNTA SI EXISTE EL ITEM CON LA CLAVE EN EL LOCAL STORAGE
let existingUsers = JSON.parse(localStorage.getItem('allUsers'));
if (existingUsers == null) {
    localStorage.setItem('allUsers', allUsers);
}

// INTENTA ALMACENAR CADA USUARIO EN EL ITEM ALLUSERS DEL LOCAL STORAGE
localStorage.setItem('users', JSON.stringify(users));
allUsers.push(users[0]);
localStorage.setItem('allUsers', JSON.stringify(allUsers))

// ESCRIBE EN EL DOCUMENTO LA INFO DEL USUARIO REGISTRADO
console.log(`ID: ${id}<br>
Nombre: ${nombre}<br>
Edad: ${edad}<br>
Peso: ${peso}<br>`);

// FUNCION QUE DEVUELVE UN NUMERO ALEATORIO GRANDE PARA EL ID
function getRandom() {
    const max = 100000000000, min = 999999999999;
    const id_aleatorio = Math.round(Math.random() * (max - min ) + min);
    return id_aleatorio;
}

How to remove duplicates from array of objects and combine values of that duplicates?

I have array like this, my id and name will be same for multiple objects but organizations values can be different

array= [
  {id: 1, name: "Test1", organizations: 1},
  {id: 1, name: "Test1", organizations: 2},
  {id: 1, name: "Test1", organizations: 3},
  {id: 2, name: "Test2", organizations: 4},
  {id: 2, name: "Test2", organizations: 5},
  {id: 2, name: "Test2", organizations: 6} 
];

I want to convert this to be like this:

expectedArray =  [
  {id: 1, name: "Test1", organizations: [1,2,3]},
  {id: 2, name: "Test2", organizations: [4,5,6]} 
];

Can someone please help

How to drag and drop before or after element using java

I am building a drag and drop website. But I’m facing a problem to drop the element before or after, above or below the other element. I have watched a tutorial about it that’s working but I cannot attach the code to my code as I’m totally new to java. Here is my drag and drop code:

function allowDrop(ev) {
  ev.preventDefault();
}

function drag(ev) {
  ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
  ev.preventDefault();
  var data = ev.dataTransfer.getData("text");
  ev.target.appendChild(document.getElementById(data));
}
#div1, #div2 {
  float: left;
  width: 200px;
  height: 300px;
  margin: 10px;
  padding: 10px;
  border: 1px solid black;
}
<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)">

<button  draggable="true" ondragstart="drag(event)" id="drag1">btn1</button>
<button  draggable="true" ondragstart="drag(event)" id="drag2">btn2</button>
<button  draggable="true" ondragstart="drag(event)" id="drag3">btn3</button>
 
</div>

<div id="div2" ondrop="drop(event)" ondragover="allowDrop(event)"></div>

Answer in javascript please

Remove space in chart.js

I am making line chart using chart js and here I would like to have a line alone without grid lines, axes lines and labels.

I have removed everything using the configurations but I am getting more space at the bottom of the chart.

Also the left side and top of points has been cut (only half circle is visible) and not displayed correctly.

var ctx = document.getElementById('myChart').getContext('2d');

var gradientStroke = ctx.createLinearGradient(500, 0, 100, 0);
gradientStroke.addColorStop(0, '#80b6f4');
gradientStroke.addColorStop(1, '#f49080');

var gradientFill = ctx.createLinearGradient(500, 0, 100, 0);
gradientFill.addColorStop(0, 'rgba(128, 182, 244, 0.6)');
gradientFill.addColorStop(1, 'rgba(244, 144, 128, 0.6)');

var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL'],
    datasets: [
      {
        label: 'Data',
        borderColor: gradientStroke,
        pointBorderColor: gradientStroke,
        pointBackgroundColor: gradientStroke,
        pointHoverBackgroundColor: gradientStroke,
        pointHoverBorderColor: gradientStroke,
        pointBorderWidth: 10,
        pointHoverRadius: 10,
        pointHoverBorderWidth: 1,
        pointRadius: 3,
        fill: false,
        backgroundColor: gradientFill,
        borderWidth: 4,
        data: [100, 120, 150],
      },
    ],
  },
  options: {
    legend: {
      display: false,
    },
    plugins: {
      datalabels: {
        display: false,
      },
    },
    layout: {
      padding: {
        bottom: -20,
      },
    },
    scales: {
      yAxes: [
        {
          ticks: {
            fontColor: 'rgba(0,0,0,0.5)',
            fontStyle: 'bold',
            beginAtZero: true,
            maxTicksLimit: 5,
            display: false,
          },
          gridLines: {
            drawTicks: false,
            display: false,
            tickMarkLength: 0,
          },
          display: false,
        },
      ],
      xAxes: [
        {
          gridLines: {
            zeroLineColor: 'transparent',
            display: false,
            tickMarkLength: 0,
          },
          ticks: {
            fontColor: 'rgba(0,0,0,0.5)',
            fontStyle: 'bold',
            display: false,
          },
          display: false,
        },
      ],
    },
  },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.js"></script>


<div class="chart-container">
 <canvas id="myChart"></canvas>
</div>

Could you please help me to resolve,

-> Removing of space at the bottom

-> Make the graph to fit in a size so that the left , top edges are visible in proper.

Thanks in advance.

how to add script code for thumb slide in slider for mobile

<script>
var slideIndex = 0;
showSlides();
var slides,dots;

function showSlides() {
    var i;
    slides = document.getElementsByClassName("mySlides");
    dots = document.getElementsByClassName("dot");
    for (i = 0; i < slides.length; i++) {
       slides[i].style.display = "none";  
    }
    slideIndex++;
    if (slideIndex> slides.length) {slideIndex = 1}    
    for (i = 0; i < dots.length; i++) {
        dots[i].className = dots[i].className.replace(" active", "");
    }
    slides[slideIndex-1].style.display = "block";  
    dots[slideIndex-1].className += " active";
    setTimeout(showSlides, 6000); // Change image every 6 seconds
}

function plusSlides(position) {
    slideIndex +=position;
    if (slideIndex> slides.length) {slideIndex = 1}
    else if(slideIndex<1){slideIndex = slides.length}
    for (i = 0; i < slides.length; i++) {
       slides[i].style.display = "none";  
    }
    for (i = 0; i < dots.length; i++) {
        dots[i].className = dots[i].className.replace(" active", "");
    }
    slides[slideIndex-1].style.display = "block";  
    dots[slideIndex-1].className += " active";
}

function currentSlide(index) {
    if (index> slides.length) {index = 1}
    else if(index<1){index = slides.length}
    for (i = 0; i < slides.length; i++) {
       slides[i].style.display = "none";  
    }
    for (i = 0; i < dots.length; i++) {
        dots[i].className = dots[i].className.replace(" active", "");
    }
    slides[index-1].style.display = "block";  
    dots[index-1].className += " active";
}
</script>

I have a slider which is scroll with right and left arrow that is working fine for desktop but I need arrow as well as thumb slider in mobile view when someone can slide with thumb in mobile left and right I have added script. thanks in advance.

Does Kendo Grid support cell merge or not?

My Grid has the following structure

 $("#grid").kendoGrid({
   dataSource: {
       data: data,
       type: 'json'
       },
       pageable: true,
       columns: [
           { field: "SubServiceTypeName", title: "Sub Type" },
           { field: "PrepaidMonthName", title: "Gói dịch vụ" },
           { field: "DeviceName", title: "Tên thiết bị" },
           { field: "DeviceStatusName", title: "Tình rạng" },
           { field: "IsDeployName", title: "Triển khai" },
           { field: "PriceStatementName", title: "CL giá" }
       ]             
 });

Result: enter image description here

I want to merge rows with same value of column [PrepaidMonthName] (call as “Gói dịch vụ”). I don’t know if kendo supports merge cells or not yet?
What I expect:

enter image description here

Or is there another solution for me to do this?

Can npm devDependencies be used in production?

One of our products at work is a JS SDK that our clients can install and use with npm install .... I was going through the package.json file and found that a package, socket.io-client was installed as a devDependency. But the SDK is using socket.io for an integral part of its working, and it obviously it’s working for our clients. So, why is it working? Since, going by the documentation, devDependencies should not be installed when using npm install.

Error when attempting to call smart contract with javascript

I am trying to write a piece of javascript that calls a smart contract. The smart contract has been deployed to a local test net with truffle and ganache and the javascript is producing the following error:

Promise { <pending> }
/Users/user/node_modules/web3-core-helpers/lib/errors.js:43
        return new Error(message);
               ^

Error: Invalid JSON RPC response: ""
    at Object.InvalidResponse (/Users/user/node_modules/web3-core-helpers/lib/errors.js:43:16)
    at XMLHttpRequest.request.onreadystatechange (/Users/user/node_modules/web3-providers-http/lib/index.js:95:32)
    at XMLHttpRequestEventTarget.dispatchEvent (/Users/user/node_modules/xhr2-cookies/dist/xml-http-request-event-target.js:34:22)
    at XMLHttpRequest._setReadyState (/Users/user/node_modules/xhr2-cookies/dist/xml-http-request.js:208:14)
    at XMLHttpRequest._onHttpRequestError (/Users/user/node_modules/xhr2-cookies/dist/xml-http-request.js:349:14)
    at ClientRequest.<anonymous> (/Users/user/node_modules/xhr2-cookies/dist/xml-http-request.js:252:61)
    at ClientRequest.emit (node:events:390:28)
    at Socket.socketErrorListener (node:_http_client:442:9)
    at Socket.emit (node:events:390:28)
    at emitErrorNT (node:internal/streams/destroy:164:8)
    at emitErrorCloseNT (node:internal/streams/destroy:129:3)
    at processTicksAndRejections (node:internal/process/task_queues:83:21)

Node.js v17.3.0

Javascript code:

onst Web3 = require('web3');

const web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));

const contract_abi = [
   {
      "inputs":[

      ],
      "name":"getName",
      "outputs":[
         {
            "internalType":"string",
            "name":"",
            "type":"string"
         }
      ],
      "stateMutability":"view",
      "type":"function"
   },
   {
      "inputs":[
         {
            "internalType":"string",
            "name":"newName",
            "type":"string"
         }
      ],
      "name":"setName",
      "outputs":[

      ],
      "stateMutability":"nonpayable",
      "type":"function"
   }
]


const contract_address = "0x6C1750bfDD9D1327AE8c5dBD1Af75dc73C138Fd7";
var Contract = new web3.eth.Contract(contract_abi, contract_address);

console.log(Contract.methods.getName().call());

Solidity code:

pragma solidity >=0.4.24;

contract NameContract {

    string private name = "This is working!";

    function getName() public view returns (string memory)
    {
        return name;
    }

    function setName(string memory newName) public
    {
        name = newName;
    }
}

I am not sure if the issue is coming from me not handling the async request properly, the JSON abi being malformed or the smart contract response not being handled correctly.

Any help would be greatly appreciated.