Why does new Date(); work in the title tag but new Date().toLocaleTimeString() doesn’t?

Google chrome set timer for 5 minutes makes a timer countdown in the title tag. It made me want to try to put javascript in the title tag. I was able to put in new Date() and get it working but not for just the time. Why does that not work?

document.getElementById("button_title").onclick = changeIt;
      function changeIt() {
        /*Attempt 1 - works - document.title = "Hi you!";*/

        
        
        /* Attempt 2 - works */
        document.title = new Date();
      }

        /*Attempt 3  - doesn't work*/
        /* document.title = new Date().toLocaleTimeString; */
        

Is there a way to plot change of day on an hourly timescale on the x axis? ReactJS – Recharts

I’m using Recharts (A ReactJS library for charts).

On the x-axis, I want to show the date whenever the time crosses midnight.
Something like this:

22:00   22:20   23:00   23:30  2010-11-17   00:15   01:30   02:00

Here is the example code:
https://codepen.io/nahushf/pen/PgrgLX?editors=1010

const {BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend} = Recharts;
const data = [
      {name: '22:00', uv: 4000, pv: 2400, amt: 2400},
      {name: '22:30', uv: 3000, pv: 1398, amt: 2210},
      {name: '23:00', uv: 2000, pv: 9800, amt: 2290},
      {name: '23:30', uv: 2780, pv: 3908, amt: 2000},
      {name: '00:15', uv: 1890, pv: 4800, amt: 2181},
      {name: '00:30', uv: 2390, pv: 3800, amt: 2500},
      {name: '01:30', uv: 3490, pv: 4300, amt: 2100},
];
const SimpleBarChart = React.createClass({
    render () {
    return (
        <BarChart width={600} height={300} data={data}
            margin={{top: 5, right: 30, left: 20, bottom: 5}}>
       <XAxis dataKey="name" xAxisId={0} />
       <XAxis dataKey="name" xAxisId={1} hide/>
       <YAxis/>
       <CartesianGrid strokeDasharray="3 3"/>
       <Tooltip/>
       <Legend />
       <Bar barSize={20}dataKey="uv" xAxisId={1} fill="#ccc" />
       <Bar dataKey="pv" barSize={20} xAxisId={0} fill="#8884d8" />
      </BarChart>
    );
  }
})

ReactDOM.render(
  <SimpleBarChart />,
  document.getElementById('container')
);

TypeError [ERR_INVALID_ARG_VALUE]: The property ‘options.family’ must be one of: 0, 4, 6. Received false

When using the node-binance-api, namely the order book, this error appears. I don’t know how to solve it. Experience is not enough…

TypeError [ERR_INVALID_ARG_VALUE]: The property 'options.family' must be one of: 0, 4, 6. Received false
        at lookup (node:dns:143:7)
        at node:net:1082:5
        at defaultTriggerAsyncIdScope (node:internal/async_hooks:463:18)
        at lookupAndConnect (node:net:1081:3)
        at Socket.connect (node:net:1019:5)
        at Object.connect (node:_tls_wrap:1660:13)
        at Agent.createConnection (node:https:142:22)
        at Agent.createSocket (node:_http_agent:343:26)
        at Agent.addRequest (node:_http_agent:294:10)
        at new ClientRequest (node:_http_client:311:16) {
      code: 'ERR_INVALID_ARG_VALUE'
    }
    
    Node.js v18.0.0

code that doesn’t work

On the previous version, node js was running, but also with an error. However, it worked.

(node:6424) [DEP0153] DeprecationWarning: Type coercion of dns.lookup options is deprecated
(Use `node --trace-deprecation ...` to show where the warning was created)

How can a JS Client pass POST parameters to a JS Server?

I’d like to have a pair of Javascript client and server that communicate
using JSON without involving a Web Browser. I can get it going as long as
the client does not try to send anything to the server. When it does, I get
the error message (% node poster.js):

.../node_modules/xhr2/lib/xhr2.js:281
            throw new NetworkError(`Unsupported protocol ${this._url.protocol}`);

Can somebody help me with this protocol issue please. What I have so far:
a server that I can start with “pm2 start jsonServer.js” –

var port = 62022
var http = require('http')
var srvr = http.createServer (function (req, res) {
        console.log ('Request type: ' + typeof(req))
        console.log (req)
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.write('Hello World!n');
        res.write(req);
        res.end();
})
var scriptName = __filename.split(__dirname+"/").pop();
console.log ('Script: ' + scriptName +'. Listening to port ' + port)
srvr.listen(port)

… and a client that is

var XMLHttpRequest = require('xhr2')

var serialize = function(object) {
  return JSON.stringify(object, null, 2)
}

let xhr = new XMLHttpRequest();
xhr.open("POST", "localhost:62022");

xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");

xhr.onload = () => console.log(xhr.responseText);

let data = `{
  "Id": 912,
  "First Name": "Archibald",
  "Last Name": "Haddock"
}`;
//console.log (serialize(data));
//xhr.send(serialize(data));
console.log (data);
xhr.send(data);

How to return body in REQUEST nodejs

I just want to return a body but I get only {} instead real data.

const Ocr = (file,req,response) => {

    const options = {
        method: "POST",
        url: "https://api.aiforthai.in.th/ocr",
        headers: {
            "Apikey": "LgArg8PNY2BiY1cmtFsE1XXN6bP6O903",
            "Content-Type": "multipart/form-data"
        },
        formData: {
            "uploadfile": fs.createReadStream(file)
        }
    };

    request(options, function (err, res, body) {
        if (err) {
            console.log(err)
            return 
        }
        return body //here I want to return
    });

};

And this is my main function that call the top code.

exports.testOcr = async (req, res, next) => {
    try {
        const file = "docs/uploadsNotice/65/กรุงเทพ.jpg"
        const result = await requestOcr.Ocr(file)
        return res.status(200).json({
            data: result,
        });
    } catch (error) {
        next(error);
    }
};

My function is not returning body

Can someone please help me with this?

JQuery AJAX not working when filtering data by price

I use AJAX for limited data scrolling. But use it together with a data filter, it doesn’t filter and always creates case else in function. AJAX scrolling data works fine but when using data filtering it doesn’t work the filtering. Thanks a lot

PHP Index

<body>
        <form action="" method="GET">
                <div class="filter-row">
                    <div class="filter">
                            <label for="">Start Price</label>
                                <input type="text" name="start_price" value="<?php if(isset($_GET['start_price'])){echo $_GET['start_price']; }else{echo "";} ?>" class="form-control">
                    </div>
                        <div class="filter">
                            <label for="">End Price</label>
                                <input type="text" name="end_price" value="<?php if(isset($_GET['end_price'])){echo $_GET['end_price']; }else{echo "";} ?>" class="form-control">
                        </div>
                        <div class="filter">
                                <button type="submit" class="btn-filter">Filter</button>
                        </div>
                </div>
        </form>
        <div id="load_data"></div>
        <div id="load_data_message"></div>

<script>
    $(document).ready(function() {
        var limit = 3;
        var start = 0;
        var action = 'inactive';
 function load_data(limit, start)
        {
            $.ajax({
            url:"fetch.php",
            method:"GET",
            data:{limit:limit, start:start},
            cache:false,
            success:function(data)
        {
            $('#load_data').append(data);
            if(data == '')
                {
                    $('#load_data_message').html("<button type='button' class='btn btn-info'>No Data Found</button>");
                    action = 'active';
                }
            else
                {
                    $('#load_data_message').html("<button type='button' class='btn btn-warning'>Please Wait....</button>");
                    action = 'inactive';
                }
            
        }
        });
 }
    if(action == 'inactive')
    {
        action = 'active';
        load_data(limit, start);
    }
        $(window).scroll(function(){
            if($(window).scrollTop() + $(window).height() > $("#load_data").height() && action == 'inactive')
                {
                    action = 'active';
                    start = start + limit;
                    setTimeout(function(){ load_data(limit, start);}, 1000);
                }
        });
 });
</script>
</body>
</html>

And file fetch.php of me, I don’t know if I broke any rules but I think it looks right

<?php
if(isset($_GET["limit"], $_GET["start"]))
    {
        require 'connection.php';
        if(!empty($_GET['start_price']) && !empty($_GET['end_price']))
                {
                     $startprice = $_GET['start_price'];
                     $endprice = $_GET['end_price'];
                     $query = "SELECT * FROM car c JOIN carType ct WHERE c.typeid=ct.typeid AND ct.price BETWEEN $startprice AND $endprice ORDER BY c.typeid DESC LIMIT ".$_GET["start"].", ".$_GET["limit"]."";        
            } else {           
                $query = "SELECT * FROM car c JOIN carType ct WHERE c.typeid=ct.typeid ORDER BY c.typeid DESC LIMIT ".$_GET["start"].", ".$_GET["limit"]."";
            }    
                $result = $conn->query($query) or die("Query failed: ".$conn->error);
                while ($row = $result->fetch_assoc()){
                echo "<div class="car-info">
                                <img class="carImg" src='imgLoad.php?name=$row[carID]'>
                                <b>Type : </b>$row[typeName]<br>
                                <b>Price    : </b>$row[price] VNĐ/ngày<br>
                            </div>";
            }
        }
?>

Js change parent of an element with transform translate animation

check the image

I want to move an element from one parent to another parent. Here I wanna apply CSS transform animation.

function abc() {
let child = document.querySelector("#child");
let parent = document.querySelector("#div_b");

parent.appendChild(child);
}
<div id="div_a" style="height:30px; width:30px; background-color:yellow;">
    <div id="child" class="new-box">
        <div style="width: 20px; height: 20px; background-color: green;"></div>
    </div>
  </div>

  <div id="div_b" style="height:30px; width:30px; background-color:red;">
  </div>
  
<button onclick="abc()">move</button>

jQuery DataTables – Search Using a Select List Value

I need to search my jQuery server side DataTable using a select list “Drawing Category” value.

Index view:

    <div style="background-color:#f5f5f5; padding:5px">
        <h2>Search Panel</h2>
        <table>
            <tbody>
                <tr>
                    <td>Drawing Number</td>
                    <td><input type="text" id="txtDrawingNumber" /></td>
                    <td>Drawing Category</td>
                    @*<td><input type="text" id="txtDrawingCategory" /></td>*@
                    <td>
                        <select id="txtDrawingCategory" style="width:200px">
                            <option value="">
                            </option>
                            @{
                                foreach (var value in Model.DrawingCategoryList)
                                {
                                    <option value="">
                                        @value.Text
                                    </option>
                                }
                            }
                        </select>
                    </td>
                </tr>
                <tr>
                    <td>
                        <input type="button" value="Search" id="btnSearch" />
                    </td>
                    <td>
                        <input type="button" value="Clear" id="btnClear" />
                    </td>
                </tr>
            </tbody>
        </table>
    </div>

JavaScript:

        table = $('#DrawingDataTable').DataTable();
        $('#btnSearch').click(function () {
            table.columns(0).search($('#txtDrawingNumber').val().trim());
            table.columns(1).search($('#txtDrawingCategory').val().trim());
            table.draw();
        });

        $('#btnClear').click(function () {
            table.columns(0).search($('#txtDrawingNumber').val(""));
            table.columns(1).search($('#txtDrawingCategory').val(""));
            table.draw();
        });

The values are displayed correctly in the “Drawing Category” select list. The Clear button does clear the selected “Drawing Category” value. The issue is that the selected “Drawing Category” value does not produce any results when I click the “Search” button. If I just use the commented out @*<td><input type="text" id="txtDrawingCategory" /></td>*@ line, it does search for the entered “Drawing Category” value. I want to provide a select list instead of just a text field.

Browser extensions to cache all the http requests to a domain

As a frontend engineer, I’m wondering if there is a way to speed up my development by using a tool at the browser level to cache all the requests to a server.
Through hot restart, I have to wait to fetch a lot of requests to refresh the page and return to the desired state of the application.
A lot of times I don’t need to have these pieces of information live. A cached version is fine (also that would avoid useless server workload).

In short, to put it simple, is there a way to cache a request with all the parameters like “http://myserver/endpoint/?params” and make the browser return the cached result?

Problems with RegEx not replacing with the first captures and instead just returning $1

So I have been trying to replace this value and capture that same value with the same typing (for example, if the query is bOb, replace with bOb) but it has not been working correctly. I am not sure what is wrong but the output is

Substitution result: /$1/ Thorton

Which is not what I want (I want the actual word bOb instead of $1. I do not know what could be wrong in this case

var query = "bob"

const regex = new RegExp((query), 'gmi')

// Alternative syntax using RegExp constructor
// const regex = new RegExp('(bob)', 'gmi')

const str = `boB Thorton`;
var subst = `/<i>$1</i>/`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log('Substitution result: ', result);

What is the lifetime of the variables declared inside component file in React?

Consider the React code declared inside LoremComponent.tsx below:

const foo = "bar";

export default (props) => {
  return (
    <h1>{foo}</h1>
  )
}

What is the lifetime of variable foo –

  1. If the LoremComponent.tsx is not imported anywhere, then this variable wont be declared inside memory?
  2. If the component is imported in other component, then what will be the lifetime of the variable foo?
  3. Or till the React application is running?

React JSON object is not parsing

I have field description which contains a JSON object and I want to parse it.

When I console.log(description) it displays the object content and also displays the object on the page.

{"blocks":[{"key":"1i9ik","text":"Issue Title","type":"header-three","depth":0,"inlineStyleRanges":[],"entityRanges":[],"data":{}},{"key":"4nluf","text":"Hi,","type":"unstyled","depth":0,"inlineStyleRanges":[],"entityRanges":[],"data":{}},{"key":"evi0t","text":"","type":"unstyled","depth":0,"inlineStyleRanges":[],"entityRanges":[],"data":{}},{"key":"5s8vp","text":"Lorem Ipsum is simply dummy text of the printing and typesetting industry.","type":"unstyled","depth":0,"inlineStyleRanges":[{"offset":0,"length":11,"style":"BOLD"}],"entityRanges":[],"data":{}},{"key":"fkbca","text":"Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, ","type":"unstyled","depth":0,"inlineStyleRanges":[],"entityRanges":[],"data":{}},{"key":"3dc6a","text":"when an unknown printer took a galley of type and scrambled it to make a type specimen book.","type":"unstyled","depth":0,"inlineStyleRanges":[],"entityRanges":[],"data":{}},{"key":"8rfom","text":"","type":"unstyled","depth":0,"inlineStyleRanges":[],"entityRanges":[],"data":{}},{"key":"es2ha","text":"one","type":"ordered-list-item","depth":0,"inlineStyleRanges":[],"entityRanges":[],"data":{}},{"key":"aeon1","text":"Two","type":"ordered-list-item","depth":0,"inlineStyleRanges":[],"entityRanges":[],"data":{}},{"key":"ei5sb","text":"Three","type":"ordered-list-item","depth":0,"inlineStyleRanges":[],"entityRanges":[],"data":{}},{"key":"bo9vp","text":"Urgent","type":"unstyled","depth":0,"inlineStyleRanges":[{"offset":0,"length":6,"style":"BOLD"},{"offset":0,"length":6,"style":"UNDERLINE"}],"entityRanges":[],"data":{}}],"entityMap":{}}

But I want to parse this object using the JSON.parse() method and when I console.log the parsed object or try to display the parsed object it gives the following error.

Uncaught SyntaxError: Unexpected token u in JSON at position 0

code:-

import { useEffect, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { useSelector, useDispatch } from "react-redux";

import { Editor, EditorState, convertFromRaw } from "draft-js";

const PostPage = () => {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const { postId } = useParams();

  const [description, setDescription] = useState();

  const { post, isSuccess } = useSelector((state) => state.posts);

  useEffect(() => {
    dispatch(getpost(postId));
  }, [dispatch, post]);
   
  console.log(post.description);


  const contentState = convertFromRaw(post?.description);
  const editorState = EditorState.createWithContent(contentState);

  return (
    <>
      <div className="wrapper">
        <div className="post-details-container">
          <div className="post-details">
            <div className="post-header">
              <div className="post-header-subject-created-at">
                <div className="post-header-subject">{post.subject}</div>
              </div>
            </div>
            <div className="post-content-container">
              <div className="post-content-header-container">
                <div className="post-content-header">
                  <div className="post-content-username">
                    <div className="post-username">{post.name}</div>
                  </div>
                </div>
              </div>
              <div className="post-content-description">
                <Editor editorState={editorState} readOnly={true} />
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

export default PostPage;

What am I doing wrong?

Array is randomized before randomizing function is called [duplicate]

I am trying to implement a shuffled deck of cards in Javascript, but I am running into behavior I am having a hard time understanding.

Here is my code. For conciseness, this deck contains only cards with faces 1-5 and only two suits:

function shuffleArray(array) {
    for (var i = array.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}

function getDeck() {
  let values = Array(5).fill().map((element, index) => index + 1);
  let suits = ['H', 'D'];
  let deck = new Array();

  values.forEach(function(value) {
    suits.forEach(function(suit) {
      let card = {
        'value': value,
        'suit': suit
      }
      deck.push(card);
    })
  })
  return deck
}

var deck = getDeck();
console.log(deck);
shuffleArray(deck);
console.log(deck);

I took the shuffle in place code from this answer

I would expect for the first log statement to show an unshuffled deck and the second log statement to show a shuffled deck. Instead, they both show identically shuffled decks! It’s as if the randomization is reaching backwards in time!

enter image description here

To make matters worse, when I was first trying to code a minimal example, I didn’t bother with values and suits and tried only to shuffle a small array, but in that case, it worked exactly as expected, only deepening my confusion…

function shuffleArray(array) {
    for (var i = array.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}

function getDeck() {
    let deck = [1, 2, 3, 4, 5];
    return deck;
}


var deck = getDeck();
console.log(deck);
shuffleArray(deck);
console.log(deck);

In that case, the output is

enter image description here

What’s going on? Why does the simple case work but the more complex case not seem to? What about timing or scoping am I misunderstanding?