Real-time Clock showing incorrect date html/css/javascript

I’m trying to make a real time clock with this format (DD/MM/YYYY – HOUR:MIN:SEC) but it displays the wrong date.

PHOTO:

Clock

It should display the current date.


MY CODE

function display_c() {
  var refresh = 1000; // Refresh rate in milli seconds
  mytime = setTimeout('display_ct()', refresh)
}

function display_ct() {
  var x = new Date()
  var day = x.getDay()
  var month = x.getMonth()
  var year = x.getFullYear()
  var hour = x.getHours()
  var min = x.getMinutes()
  var sec = x.getSeconds()
  if (day < 10) day = "0" + day;
  if (month < 10) month = "0" + month;
  if (hour < 10) hour = "0" + hour;
  if (min < 10) min = "0" + min;
  if (sec < 10) sec = "0" + sec;
  var x1 = day + "/" + month + "/" + year + " - " + hour + ":" + min + ":" + sec;
  document.getElementById('ct').innerHTML = x1;
  display_c();
}
<html>

<head>
  <title>Lancelot</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="projetoNew.css">
  <script type="text/javascript" src="projetoNew.js"></script>
</head>

<body onload=display_ct();>
  <header>
    <div class="headerContainer header-theme">
      <a href="" class="header-logo button-theme1 header-item">Lancelot</a>
      <span id="ct"></span>
    </div>
  </header>

Second Line of Else Block Not Running [closed]

In my else block, the second line does not appear to be running. It runs setHelperText but seems to ignore setAlertValue.

  const [alertValue, setAlertValue] = useState("error");
  const [errValue, setErrorValue] = useState("Error State");
  const [helperText, setHelperText] = useState('Input "success" to remove error');

  const handleChange = (e) => {
    setErrorValue(e.target.value);

    if (e.target.value === "success") {
      setAlertValue(null);
      setHelperText("Update input to re-enable error");
    } else 
      setHelperText('Input "success" to remove error');
      setAlertValue("error"); // this line does not run
  };

  <TextField
       label="Error State"
       message="this is an ERROR message"
       alert={alertValue}
       value={errValue}
       onChange={handleChange}
       helperText={helperText}
   />

my projects functionality works with live server extension only

I just created my first calculator and it works perfectly on live server, but not directly if opening via HTML file. After placing js, css, img and audio file in separate folder and changing the path in HTML it started working, but the arrow function that serves to delete symbols still not working if opening directly. Any ideas?

  <section>
    <p>Olena's <br> calculator</p>
    <div class="container">
        <div class="pic"><img src="files/pic.png" alt="pic"></div>
        <div class="display" id="dis"></div>
            <div class="buttons">
                <div class="button" id="c">C</div>
                <div class="button" id="pro">.</div>
                <div class="button" id="larr">&larr;</div>
                <div class="button" id="sub">/</div>
                <div class="button" id="seven">7</div>
                <div class="button" id="eight">8</div>
                <div class="button" id="nine">9</div>
                <div class="button" id="mul">*</div>
                <div class="button" id="four">4</div>
                <div class="button" id="five">5</div>
                <div class="button" id="six">6</div>
                <div class="button" id="di">-</div>
                <div class="button" id="one">1</div>
                <div class="button" id="two">2</div>
                <div class="button" id="three">3</div>
                <div class="button" id="plus">+</div>
                <div class="button" id="zero">(</div>
                <div class="button" id="dblzero">0</div>
                <div class="button" id="point">)</div>
                <div class="button" id="equal">=</div>
            </div>
    </div>
</section>


<audio src="files/mixkit-plastic-bubble-click-1124.wav" id="audio"></audio>

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

buttons.map(but => {
but.addEventListener('click', (key) => {
    console.log(key.target.innerText)
    switch (key.target.innerText) {
        case 'C':  
            display.innerText = ' '
        break
        case '←':
            if (display.innerText) {
            display.innerText = display.innerText.slice(0, -1)
            break
            }
        case '=':
            try{
            display.innerText = eval(display.innerText)
            break
            } catch {
                display.innerText = 'Помилка'
                break
            }
        default:
            display.innerText += key.target.innerText 
    }
})
})

const audio = document.getElementById('audio')

document.onclick = () => audio.play();

ES6 module constructor’s scope

I’ve stumbled upon a behavior I cannot understand. Could someone, more proficient with JS, have a quick glance at it.

I apologize for posting screenshots instead of setting up a working example here, but I hope it should be enough for an expert to quickly recognize what’s reason is.

  • I have a JS class in an ES6 module
  • I pass a function to the class’ constructor
  • I attach an event handler to an HTMLElement and in this handler I expect to have this function to be accessible.

It’s accessible if I don’t use ES6 modules, I’ve checked. So the reason must be related to the ES6 modules’ scope also I suspect the shadow DOM may be related.

So at this point, line 8 the notifyController function is definedpicture of a browser's console window, function is defined.

But when the event handler is run, it’s undefined.picture of a browser's console window, function is not defined

How come?

Thank you in advance.

Iterative implementation of Binary Search

please i have a question about the Iterative implementation of Binary Search

This is the function i create in c:

int BinarySearch(int arr[], int l, int r, int x)
{
  while(l <=  r) {
      int mid = l + (r - l) / 2;
      if(arr[mid] == x)
          return mid;
      if(arr[mid] > x)
          r = mid - 1;
      else
          l = mid + 1;
  }
  return -1;
}

This is my main function :

int main()
{
    int arr[] = {1,2,3,5,16,15,20};
    int n = sizeof(arr) / sizeof(arr[0]);
    int x = 16;
    int result = BinarySearch(arr, 0, n-1, x);
    (result == -1)
        // WE CALL THIS ternary operator.
        ? printf("Element is not present in array")
        : printf("Element is present at index %d", result);
    return 0;
}

The question is: when i search 16 the function return -1.
If you see the number 16 is on the list any help please ??

JS is Concatenating instead of Adding Variables [duplicate]

I’m trying to figure out why this block of code isn’t behaving the way I’d expect. This is for a simple online financing calculator with trade in. Everything worked until I added the ‘accessories’ section to the code. Instead of returning product + accessories (e.g. $100 + $50 = $150) it’s concatenating the results (e.g. $100 + $50 = $10050). The trade in and month calculation seem to work correctly if I don’t enter any value into the accessories field.

function Calculate() {
        var months = document.querySelector("#months").value;

        var product = document.querySelector("#product").value;

        var accessories = document.querySelector("#accessories").value;

        var trade = document.querySelector("#trade").value;

        var basket = product + accessories;

        var total =  ((basket - trade) / months).toFixed(2);

        document.querySelector("#total")
                .innerHTML = "Estimated Monthly Payment: $" + total;
}

Google Apps Script to obtain the index if any of the words on a string match another string?

I have a long list of roles obtained from a sheet range stored as strings in an array, to give an example the array looks something like this:

arr1 = ["football manager","hockey coach", "fb player","fb coach","footballer"];

and I have another array in which I have a list of words and a classification code
it represents something like the following table.

Table # 2
| Profession | Class |
| ——————–| ————– |
| football | FB01 |
| fb | FB01 |
| hockey | HK01 |
| footballer | FB01 |

I am trying to match the roles of the first array to the professions on the second one and assign a class to each of the roles.

I have been trying to do this by obtaining the index of the matched row:

for(let i in arr1){
arr2.findIndex(s => s.indexOf(arr1[i]) >= 0);
}

But this only works for “footballer” as it is an exact match, I need for all of the partial matches to be classified as well.

How can I loop through a Map which contains a hashmap in angularjs?

I have a Map<String(religion), Map<String(name), Person>> where Person contains Name, Age and Date – yes name is stored twice.

I return this map and store into a [] in my controller.

I’m trying to do a repeater for every entry in people and then another repeater within that for every entry in the map inside but cant access the values. I need to create a table that creates a showing the religion, person.name, person.date for every single entry

Lerna bootstrap doesn’t install symlink

I have a project and updated from node v14 (npm 6) to node LTS (npm 8.3)

Lerna bootstrap doesn’t install my dependencies as symlink.

Structure:

.X
├── lerna.json
├── package.json (My node_modules contains A and B packages)
├── packages
│   ├── A
│   │   └── package.json (install two as symlink (taking from root node_modules)- but 
│   │                     it's not working)
│   └── B
│       └── package.json
.Y
├── lerna.json
├── package.json (My node_modules contains A and B packages)
├── packages
│   ├── C
│   │   └── package.json (it should installs A and B as symlink)
│   │
│   └── D
│       └── package.json (it should installs A as symlink)

When I use node v14, lerna bootstrap install correctly but when I use v16 it’s not..

Cypress: Use leaflet in cypress test?

I am trying to utilize the setView method in leaflet in a cypress test but having a web-pack error. I’m not sure how to import this correctly to be able to use it. In the main app everything is working correctly but I don’t understand how to utilize it in cypress. I am trying something simple just to start off and see if it works. Here it is.

import L from 'react-leaflet';

const map = L.map('mapid')
            map.setView([4881264.780784771,-9929607.312884448], 2)

but it will not even load the cypress test and fails at

Error: Webpack Compilation Error
./cypress/integration/explorer/test.spec.js
Module not found: Error: Can't resolve 'react-leaflet' in '/Users/Documents/github/dashboards/cypress/tests'

Has anyone done this before?

Allow only alphabet in input Html – Angular

I want to know how to only allow alphabet in an input, if a number or special character is entered in the input, ignore it, i work with Angular.

I work with reactive form but if I use pattern this just validates the field when submit is done, what I need is that for example if I press the number “1” in keyboard it simply does not show, when the key is pressed ignore everything that is not alphabet letter

React firebase database rendering data

I am using react-firebase-hooks useList which wraps around onX(..) listening to data in real time.

This is my insert method:

export const insertItem = () => {
  let key = createUniqueId();
  return set(ref(db, `chat/${key}`), {
    chat_id: key,
  })
    .then((data) => {
       push(ref(db, `chat/${data.key}/messages`),{
          sender: "foo",
          text: "hello"
       })
    })
    .catch((error) => {
      return error;
    });
};

This is my component:

export const Chat = () => {
  const [snapshots, loading, error] = useList(ref(db, 'chats'));
  
  let chats = snapshots.map(data => {
      let chat = data.val()
      let checkNewMessage = Object.keys(chat["messages"]);
      let newest = checkNewMessage[checkNewMessage.length - 1];
      let item = chat["messages"][newest]
      return (
          <div>{item.text}</div>
      )
  })

  return (
      <div>{chats}</div>
  )
};

Databse:

enter image description here

When it comes to rendering the chat along with the message I run into two issues.

Cannot convert undefined or null to object

Can’t perform a React state update on an unmounted component. This is
a no-op, but it indicates a memory leak in your application. To fix,
cancel all subscriptions and asynchronous tasks in a useEffect cleanup
function.

From my understanding, I think the reason why it is still null/undefined is due to the message item has not yet been created due to async/promise actions. How can I correctly wait for all db changes to be inserted?

Once I refresh my page it renders it as expected. without any errors.

java script to react js [closed]

can someone pls write a react js way for this javascript code pls

const menuBtn = document.querySelector('.menu-btn');
let menuOpen = false;
menuBtn.addEventListener('click', () => {
  if(!menuOpen) {
    menuBtn.classList.add('open');
    menuOpen = true;
  } else {
    menuBtn.classList.remove('open');
    menuOpen = false;
  }
});

Why does some of my columns in my HTML table display cells as undefined while other columns display correctly?

Table output picture
I couldn’t figure out why some of the cells are undefined even though they have similar data types to some of the cells that are displaying values correctly? What can I try to make them display properly? The code should take the list of dictionaries and populate the tables with them. I am fairly new to javascript and web development. I usually work in backend with SQL and python. thank you.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

<style>
    th{ 
        cursor: pointer;
        color:#fff;
            }
</style>


<table class="table table-striped">
    <tr  class="bg-info">
        <th  data-colname="date" data-order="desc">date &#9650</th>
        <th  data-colname="exposed" data-order="desc">exposed (mn) &#9650</th>
        <th  data-colname="displaced (k)" data-order="desc">displaced (k) &#9650</th>
        <th  data-colname="killed" data-order="desc">killed &#9650</th>
        <th  data-colname="duration(days)" data-order="desc">duration(days) &#9650</th>
        <th  data-colname="cause" data-order="desc">cause &#9650</th>
        <th  data-colname="Country Name" data-order="desc">Country Name &#9650</th>
        <th  data-colname="ISO code" data-order="desc">ISO code &#9650</th>
    </tr>
    <tbody id="myTable">
        
    </tbody>
</table>


<script>
var myArray =[{'date': '7/21/2007', 'exposed': 27712991, 'displaced (k)': 5000000, 'killed': 1071, 'duration(days)': 86, 'cause': 'Heavy rain', 'Country Name': 'Nepal', 'ISO code': 'NPL'}, {'date': '9/9/2010', 'exposed': 23137894, 'displaced (k)': 140000, 'killed': 0, 'duration(days)': 21, 'cause': 'Heavy rain', 'Country Name': 'Nepal', 'ISO code': 'NPL'}, {'date': '8/30/2008', 'exposed': 21631628, 'displaced (k)': 600000, 'killed': 0, 'duration(days)': 9, 'cause': 'Heavy rain', 'Country Name': 'Nepal', 'ISO code': 'NPL'}, {'date': '8/18/2008', 'exposed': 21529060, 'displaced (k)': 10000000, 'killed': 400, 'duration(days)': 37, 'cause': 'Heavy rain', 'Country Name': 'Nepal', 'ISO code': 'NPL'}, {'date': '7/12/2007', 'exposed': 21488636, 'displaced (k)': 11100000, 'killed': 96, 'duration(days)': 90, 'cause': 'Heavy rain', 'Country Name': 'Nepal', 'ISO code': 'NPL'}, {'date': '6/20/2004', 'exposed': 19855086, 'displaced (k)': 40000000, 'killed': 3000, 'duration(days)': 109, 'cause': 'Heavy rain', 'Country Name': 'Nepal', 'ISO code': 'NPL'}, {'date': '10/1/2010', 'exposed': 19362985, 'displaced (k)': 500000, 'killed': 15, 'duration(days)': 11, 'cause': 'Tropical StormSurge', 'Country Name': 'Nepal', 'ISO code': 'NPL'}, {'date': '7/25/2016', 'exposed': 18456496, 'displaced (k)': 25000, 'killed': 42, 'duration(days)': 32, 'cause': 'Heavy rain', 'Country Name': 'Nepal', 'ISO code': 'NPL'}, {'date': '9/1/2018', 'exposed': 17213562, 'displaced (k)': 1000, 'killed': 20, 'duration(days)': 6, 'cause': 'Heavy rain', 'Country Name': 'Nepal', 'ISO code': 'NPL'}, {'date': '6/11/2003', 'exposed': 16822143, 'displaced (k)': 9500000, 'killed': 600, 'duration(days)': 121, 'cause': 'Heavy rain', 'Country Name': 'Nepal', 'ISO code': 'NPL'}, {'date': '7/21/2002', 'exposed': 16541422, 'displaced (k)': 250000, 'killed': 380, 'duration(days)': 25, 'cause': 'Heavy rain', 'Country Name': 'Nepal', 'ISO code': 'NPL'}, {'date': '7/3/2007', 'exposed': 16486188, 'displaced (k)': 3000000, 'killed': 958, 'duration(days)': 81, 'cause': 'Heavy rain', 'Country Name': 'Nepal', 'ISO code': 'NPL'}, {'date': '9/16/2012', 'exposed': 15526445, 'displaced (k)': 200, 'killed': 45, 'duration(days)': 2, 'cause': 'Heavy rain', 'Country Name': 'Nepal', 'ISO code': 'NPL'}, {'date': '8/15/2011', 'exposed': 14830495, 'displaced (k)': 70000, 'killed': 158, 'duration(days)': 48, 'cause': 'Heavy rain', 'Country Name': 'Nepal', 'ISO code': 'NPL'}, {'date': '8/10/2017', 'exposed': 13271467, 'displaced (k)': 300000, 'killed': 117, 'duration(days)': 16, 'cause': 'Heavy rain', 'Country Name': 'Nepal', 'ISO code': 'NPL'}, {'date': '9/18/2010', 'exposed': 12414310, 'displaced (k)': 15000, 'killed': 88, 'duration(days)': 12, 'cause': 'Heavy rain', 'Country Name': 'Nepal', 'ISO code': 'NPL'}, {'date': '9/22/2008', 'exposed': 12372235, 'displaced (k)': 0, 'killed': 2400, 'duration(days)': 7, 'cause': 'Dam', 'Country Name': 'Nepal', 'ISO code': 'NPL'}, {'date': '10/7/2004', 'exposed': 11965543, 'displaced (k)': 100000, 'killed': 210, 'duration(days)': 11, 'cause': 'Heavy rain', 'Country Name': 'Nepal', 'ISO code': 'NPL'}, {'date': '8/20/2014', 'exposed': 11058729, 'displaced (k)': 500000, 'killed': 17, 'duration(days)': 19, 'cause': 'Heavy rain', 'Country Name': 'Nepal', 'ISO code': 'NPL'}, {'date': '9/22/2008', 'exposed': 8627859, 'displaced (k)': 13000, 'killed': 49, 'duration(days)': 7, 'cause': 'Heavy rain', 'Country Name': 'Nepal', 'ISO code': 'NPL'}]

buildTable(myArray)



 $('th').on('click', function(){
     var column = $(this).data('colname')
     var order = $(this).data('order')
     var text = $(this).html()
     text = text.substring(0, text.length - 1);
     
     
     
     if (order == 'desc'){
        myArray = myArray.sort((a, b) => a[column] > b[column] ? 1 : -1)
        $(this).data("order","asc");
        text += '&#9660'
     }else{
        myArray = myArray.sort((a, b) => a[column] < b[column] ? 1 : -1)
        $(this).data("order","desc");
        text += '&#9650'
     }

    $(this).html(text)
    buildTable(myArray)
    })


   
 
    
function buildTable(data){
    var table = document.getElementById('myTable')
    table.innerHTML = ''
    for (var i = 0; i < data.length; i++){
        var colname = `date-${i}`
        var colname = `exposed-${i}`
        var colname = `displaced (k)-${i}`
        var colname = `killed-${i}`
        var colname = `duration(days)-${i}`
        var colname = `cause-${i}`
        var colname = `Country Name-${i}`
        var colname = `ISO code-${i}`

        var row = `<tr>
                        <td>${data[i].date}</td>
                        <td>${data[i].exposed}</td>
                        <td>${data[i].displaced}</td>
                        <td>${data[i].killed}</td>
                        <td>${data[i].duration}</td>
                        <td>${data[i].cause}</td>
                        <td>${data[i].CountryName}</td>
                        <td>${data[i].ISOcode}</td>
                   </tr>`
        table.innerHTML += row
    }
}

</script>
<div id="time-range">
    <p>Time Range: <span class="slider-time"></span> - <span class="slider-time2"></span>
    </p> 
    
    <div class="sliders_step1">
        <div id="slider-range"></div>
    </div>
</div>

]2