teleren/devto huggingface dataset:
Why doesn't useState has a dependency array?
Tags: discuss, react
Published: 2022-06-25 11:20:18

---
title: Why doesn't useState has a dependency array?
published: true
tags: discuss, react
---

This is how I'm updating a custom hook's state based on the prop passed to it:
```js
const useCustomHook = (prop: number) => {
   const [state, setState] = useState(prop);
   
   // this is how I'm currently updating state
   // when the props change.
   useEffect(() => {
      setState(prop);
   }, [prop]);

   return state;
};

// it's usage
const [localState, setLocalState] = useState(0);
const hookState = useCustomHook(localState);
```
But the problem with above approach is that the `return state` of the custom hook is going to run first, returning the old value before running the `useEffect` callback and updating the hook's state and then returning the new state. This will cause the main component to render twice.

Now you may ask, what's the big deal if it renders twice? It can lead to bugs. For example, the custom hook could be a count-down, implementing setInterval, that comes down to 0, but when I reset it with setLocalState(5), the useCustomHook will immediately return 0 and not 5.

Why doesn't useState return updated value based on if the value passed to it is changed? or why doesn't it have a dependency array like useEffect if we don't want to change its behaviour.

Thanks for your time.
Database Reindexing (MSSQL)
Tags: sql, database
Published: 2022-06-25 11:01:06

There are a number of ways to reindex a database.  This is my preferred method.

First, execute the below to check the fragmentation level of the active database:

```
declare @fragmentation float

set @fragmentation = 20

SELECT 
	S.name as [Schema],
	T.name as [Table],
	I.name as [Index],
	DDIPS.avg_fragmentation_in_percent
FROM 
	sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL, NULL) AS DDIPS
INNER JOIN 
	sys.tables T with (nolock) 
on 
(
	T.object_id = DDIPS.object_id
)
INNER JOIN 
	sys.schemas S with (nolock) 
on 
(
	T.schema_id = S.schema_id
)
INNER JOIN 
	sys.indexes I with (nolock) 
ON 
(
	I.object_id = DDIPS.object_id AND 
	DDIPS.index_id = I.index_id
)
WHERE 
	DDIPS.database_id = DB_ID() and 
	I.name is not null AND 
	DDIPS.avg_fragmentation_in_percent > @fragmentation
ORDER BY 
	DDIPS.avg_fragmentation_in_percent desc
```

Run the database reindex by executing the following:

```
declare @fragmentation float

set @fragmentation = 20

declare @schema_name sysname,
		@table_name sysname,
		@index_name sysname
 
DECLARE cursor_tables 
	CURSOR FOR 
		SELECT 
			S.name as 'Schema',
			T.name as 'Table',
			I.name as 'Index'
		FROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL, NULL) AS DDIPS
		INNER JOIN sys.tables T with (nolock) on (T.object_id = DDIPS.object_id)
		INNER JOIN sys.schemas S with (nolock) on (T.schema_id = S.schema_id)
		INNER JOIN sys.indexes I with (nolock) ON (I.object_id = DDIPS.object_id AND DDIPS.index_id = I.index_id)
		WHERE 
			DDIPS.database_id = DB_ID() and 
			I.name is not null AND 
			DDIPS.avg_fragmentation_in_percent > @fragmentation
		ORDER BY 
			DDIPS.avg_fragmentation_in_percent desc

open cursor_tables
		
fetch next from cursor_tables
into @schema_name, @table_name, @index_name
 
while @@fetch_status = 0
begin
	exec
	(
		'
			ALTER INDEX [' + @index_name + '] ON [' + @schema_name + '].[' + @table_name + ']
			REBUILD WITH(FILLFACTOR = 80, SORT_IN_TEMPDB = ON, STATISTICS_NORECOMPUTE = ON)
		'
	)

	exec
	(
		'
			ALTER INDEX [' + @index_name + '] ON [' + @schema_name + '].[' + @table_name + ']
			REORGANIZE
		'
	)
 
	fetch next from cursor_tables
	into @schema_name, @table_name, @index_name
end
 
close cursor_tables
deallocate cursor_tables
```

And finally, update statistics by running this

```
EXEC sp_updatestats
```

_Article created mostly for personal reference; there are of course a few different ways in which these scripts could be improved, but when providing them to clients the simplest solution is often the best._
Uniraj.org
Published: 2022-06-25 11:00:14

Uniraj.org
[Uniraj.org](https://www.uniraj.org.in/) - Rajasthan University (Univraj) Results 2022 Uniraj Results, Admit Card, Exam Form, Time Table for BA, B.Com, B.Sc part 1,2,3 and MA, M.Com, M.Sc.

Get the latest news about Rajasthan University (Uniraj) Results, Admit Card, Exam Date, Fees, and Admissions. All information about the University of Rajasthan latest notifications. Uniraj.org.in gives you the latest updates about admit card, results, and exam timetables from Rajasthan University's official website. Also, Get notification about the latest Government Jobs and vacancies at Uniraj.org.in.
How to disable text selection with CSS
Tags: css, codenewbie, webdev
Published: 2022-06-25 10:43:31

On a web page, we typically should **not** disable text selection, but there are a few cases where having it enabled can take away from the user experience. Normally, we do not want to take away a user's ability to select text, as that will lead to a bad user experience. There was a time when a small number of websites would stop users copying article text as a method of stopping plagiarism, but thankfully that is far less common today.

Having said that, there are a notable number of examples where disabling text selection can actually improve user experience. For example:
- On HTML elements that trigger events, especially on mobile - where tapping or double tapping might lead to text selection
- On drag and drop interfaces, where a user has to drag an element - we don't want that drag to trigger text selection too.
- On many other custom web-built user applications where text selection needs to be limited to certain elements or situations. For example, on a text editor, we usually don't want the button that makes text **bold** to be selectable, since it is a button.

**Fortunately** there is an easy way in CSS to disable text selection on certain elements if you need to.

## How to disable text selection in CSS

All modern browsers (with the exception of some versions of Safari) support the `user-select` property, which makes any HTML element unselectable. For example, if you wanted all buttons not be selectable, you could write the following:
```css
button {
    -webkit-user-select: none;
    user-select: none;
}
```
We have to use `-webkit-user-select` since Safari still requires it. If you want to support Internet Explorer (which is becoming less and less common), you can also use `-ms-user-select`:
```css
button {
    -ms-user-select: none;
    -webkit-user-select: none;
    user-select: none;
}
```

This single property will stop user selection. `user-select` also has other properties, in theory, but the support for these vary.
- `user-select: none` - no user select on the element.
- `user-select: text` - you can only select the text within the element
- `user-select: all` - tapping once will select the entire elements content.
- `user-select: auto` - the default, lets you select everything like normal.

The support for each of these varies, but you can find a full, up to date [list of support for user-select on caniuse](https://caniuse.com/?search=user-select).

To see some demos on this, [check out the original article here](https://fjolt.com/article/css-disable-text-selection).
My first experience in buying an NFT (as a blockchain lover)
Tags: web3, blockchain, nft
Published: 2022-06-25 10:28:41

Look at my article on 

- Buy Me A Coffe : [article](https://www.buymeacoffee.com/giuliopie/my-first-experience-buying-nft-blockchain-lover)
- Medium: [article](https://medium.com/@giuliopiepoli.dev/my-first-experience-in-buying-an-nft-as-a-blockchain-lover-12a86ff286be)

and please, let me know what do you think.

Enjoy.
Why does HTML recognize Ninja Turtle as a Background Colour
Published: 2022-06-25 10:27:16

Why do certain random strings produce colours when entered as background colours in HTML
For example, Look at the following code snippet and its output

```
<html lang="en">
    

<head>
  <title>Hello, world!</title>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1" />
  <meta name="description" content="" />
</head>
<body bgcolor="ninjaturtle">
  <h1 >What should you do when you see a green alien</h1>
  <h1>Wait until it's ripe</h1>
</body>
</html>

```

And now let's look at the output

![green alien](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dcxl70bg74j35ob8odqk.png) 

![green alien 2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fik1xq6n1s6t2wtapuxc.gif)


The real reason behind this is that the browser can not understand it and tries to  somehow translate it to what it can understand and in this case turns it into a hexadecimal value

ninja turtles start with n which is an unrecognized character in hexadecimal, also it's converting all unrecognized characters into 0

However, it recognizes all the hexadecimal characters and keeps it as it is

So ninja turtles in hexadecimal format becomes:0000a00000e0 and all other characters become 0 other than a and e remain where they are...

Now they get divided by 3 for RGB(red, green, blue)... R: 0000, G: a000, B:00e0...

But we know valid hexadecimal for RGB is just 2 characters, which means R: 00, G: a0, B:00
.


So the real result is:
`<body bgcolor="#00a000">`

There are other anomalies as well 


```
<body bgcolor="cabs">
<h1>
  Fun fact - According to this logic  bgcolor="cabs" test 
  would give you the color of a California Taxi Cab
  </h1>
</body>
```

produces 

![cab](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/571v1so3yfjadyz0nxwr.png)

Also Netscape(RIP) was located in Mountain View,California 

 
and one final one for all my pokemon lovers 

```
<table>
  <td bgcolor="squirtle">squirtle</td>
  <td bgcolor="ivysaur">ivysaur</td>
  <td bgcolor="charmeleon">charmeleon</td>
</table>
```

![pokemon](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hj2vxunmxyzk3druivb1.png)
you can read about more HTML anomalies at:[ A little rant about Microsoft Internet Explorer's color parsing](http://scrappy-do.blogspot.com/2004/08/little-rant-about-microsoft-internet.html)


Thanks for Reading
Help with trigonometry in Python needed!
Tags: trigonometry, pythonhelp, python
Published: 2022-06-25 10:23:18

Hey, guys! So, right to the problem - I have a formula that has sines and I want to make a python version of it (to relieve me from counting it by hand - it's really complex).

So you know that sine of 30 degrees is 0.5, sine of 45 degrees is sqrt of 2 divided by 2 etc.
And I need a function that would do the opposite - get a number (like 0.5) and turn it into a degree (like 30).

Disclaimer: I don't know trigonometry that well, so I'm quite probably missing something.

Thanks! :)
This week’s newsletter is out! (25-06-2022) - Sentient AI
Tags: javascript, tech, webdev, discuss
Published: 2022-06-25 10:18:31

---
title: This week’s newsletter is out! (25-06-2022) - Sentient AI
published: true
description: Another week of great javascript, tech and web development links.
tags: javascript, tech, webdev, discuss
---

Sentient AI

https://markjgsmith.substack.com/p/mark-smiths-newsletter-25-06-2022

Would love to hear any comments and feedback you have.

[@markjgsmith](https://twitter.com/markjgsmith)
4 Ways to Run Python Commands From Command Prompt (or the Terminal)
Tags: python, beginners, tutorial, linux
Published: 2022-06-25 10:17:58

You'd have to run many shell commands daily if you're a programmer.  

Python is a helpful language for doing a lot of work without leaving the command prompt (or the terminal.)

Languages such as Python don't need compilation before they run. Thus you can run Python commands directly from the shell. 

But as the complexity of your query grows, you could do slight tweaks to your Python commands. They'll allow the reusability of complex logic and a lot more. 

This post discusses four ways you could run a Python command in a terminal. 

[**_4 Ways to Run Python Commands from Terminal_**](https://www.the-analytics.club/python-run-command-in-terminal)
Wu Dong Qian Kun Season 3
Tags: nontondonghua, donghuasubtitle
Published: 2022-06-25 09:45:32

Musim Ketiga Wu Dong Qian Kun – Untuk menjadi lebih kuat dan mengalahkan Lin Langtian dalam kompetisi klan berikutnya, Lin Dong, Xiao Diao, dan Xiao Yan memulai jalan kultivasi bersama, dan ada banyak petualangan di sepanjang jalan. Di bawah bimbingan Xiao Yan, Lin Dong akhirnya datang ke monumen kuno Great Wilderness, dan berhasil memperoleh petunjuk untuk menelan jimat leluhur, dan berhasil memperoleh seni bela diri keberuntungan di bawah persaingan Lin Langtian dan banyak orang kuat. , dan Jari Surga yang Terpenjara di Gurun Besar!
Sumber lengkap : [https://www.hibstreamsub.my.id/2022/05/wu-dong-qian-kun-season-3.html](url)
Python Exercise 16: find the highest index alphabet
Tags: beginners, python, challenge
Published: 2022-06-25 09:29:20

## Question
- Given a name, return the letter with the highest `index` in alphabetical order, 
	- with its corresponding index, 
	- in the form of a string. 
- You are prohibited to use `max()` nor is reassigning a value to the alphabet list allowed.

### Example

```python
alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]


alphabet_index(alphabet, "Flavio") ➞ "22v"

alphabet_index(alphabet, "Andrey") ➞ "25y"

alphabet_index(alphabet, "Oscar") ➞ "19s"
```
## My attempt
- algorithm

```
>find the letter with the highest index in alphabetical order
 initialise highest_index to 0
 initialise highest_index_character to empty string
>>Find the highest index of the character and the relevant character in the name
  initialise highest_index to 0
  initialise highest_index_character to empty string
  for each character in the name:
	  if character's index in alphabet is higher than in highest_index
	  set highest_index to character's index
	  set highest_index_character to character
  return string of highest_index and highest_index_character
```
- code

```python
alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u",  
            "v", "w", "x", "y", "z"]  
  
  
def alphabet_index(alphabet: list, name: str):
	# The name are in upper case, but alphabet is in lower case
    name = name.lower()  
    # initialise highest_index to 0  
    highest_index = 0  
    # initialise highest_index_character to empty string  
    highest_index_character = str()  
    # for each character in the name:  
    for character in name:  
        #  if character's index in alphabet is higher than in highest_index  
        if alphabet.index(character) + 1 > highest_index:  
            # set highest_index to character's index  
            highest_index = alphabet.index(character) + 1  
            #   set highest_index_character to character  
            highest_index_character = character  
    # return string of highest_index and highest_index_character  
    return str(str(highest_index) + highest_index_character)  
  

```
## Other solution
- don't find any particular impressive code. If there is shorter way to do this, please let me know.

## My reflection
- This takes me long time to write out the algorithm in appropriate formate, need to practice more

## Credit
- challenge find on [edabit](https://edabit.com/challenge/wcdS7MEL5gvr5SGsh)
What's the difference between an inline and inline-block element in CSS?
Tags: css, html, webdev, beginners
Published: 2022-06-25 08:50:03

In CSS, `inline` and `inline-block` are two values assignable to an element's `display` property.

**Inline Elements**
An element's display with `inline` sets both its **outer** and **inner** display types to `inline`.

In the **normal flow** of the document set by the **Initial Block Formatting Context**, inline items create an **Inline Formatting Context**. Items with an **outer** value of `inline` are arranged one after the other in a line. They are moved to the next line if there is not enough horizontal space. The `width` of an inline element is defined by the width of its content. **Vertical** `padding` and `margin`s are **ignored**, as they disrupt line spacing of the inline nodes.

The **inner** type of `inline` (set by the same `inline` keyword, used once) creates an Inline Formatting Context (IFC) for its children (e.g. text nodes inside a `<span>`), which tells them to follow the layout rules of IFC themselves.

This is very trivial, so we'll come to an example when comparing `inline` to `inline-block`.

**Inline-block Elements**
For inline-block elements, we have to assign their `display` properties to `inline-block`. This sets the **outer** display type to `inline` and the **inner** type to `block`.

The outer display value of `inline` essentially tells the item to behave as an inline item when it's interacting with its neighbors. The inner type, `block`, creates a Block Formatting Context and imposes block level rules on its children.

Creating a BFC for its children allows them to have vertical padding and margins. In the example below:

```
<div>
  Some very important text here. This should be a long one so that we can have multiple lines to see what is going on with vertical padding and margin. Then a
 <span class="with-vertical-pm">span with a dummy text. This span is an inline-block element.
  <div class="floated">
    A section with floated content. But this is contained oddly within a span.
  </div>
 </span>
</div>
```

```
.with-vertical-pm {
  display: inline-block;
  margin: 20px;
  padding: 20px;
  color: orange;
  border: 1px solid blue;
}

.floated {
  float: left;
  width: 200px;
  height: 100px;
  background-color: skyblue;
}
```
the `<span>` is no longer an `inline` element, rather an `inline-block` element. This gives it the flexibility of having a vertical padding and margin.

We can see the behavior this [this codepen pen](https://codepen.io/anewman15/pen/eYVqxpW).

Note how the floated div with class `.floated` is contained within the borders of the `<span>` element because `display: inline-block;` creates a BFC which contains a float by default.

Notice also, thanks to the outer `inline` display, how the `<span>` element acts as an `inline` element with respect to the text nodes in the parent div.

---
References
1. [The display Property
](https://www.w3schools.com/cssref/tryit.asp?filename=trycss_display)
2. [Display](https://developer.mozilla.org/en-US/docs/Web/CSS/display#precomposed)
Converting JSX to downloadable pdf in react
Tags: react, pdf, jsx, reacttopdf
Published: 2022-06-25 08:45:00


### A simple demonstration to convert JSX to PDF in react with the help of `Html2pdf.js` library.<br><br>

Create React Project and install packages

```
npx create-react-app jsx-to-pdf-example
cd jsx-to-pdf-example
npm install html2pdf.js 
```

`App.js`

```javascript
import html2pdf from 'html2pdf.js/dist/html2pdf.min';
import './App.css';

function App() {
  const pdfJSX = () => {
    return (
      <>
        <h1>JSX to PDF Convert Example</h1>
        <h2>Hello React</h2> 
      </>
    )
  }

  const printHandler = () => {
    const printElement = pdfJSX();
    console.log(printElement);

    html2pdf().from(printElement).save();
  }

  return (
    <div className="App">
      <button onClick={printHandler}>Print</button>
    </div>
  );
}

export default App;

```
After clicking on `print` button here, you will notice that nothing is happening. Here is what console log would show you in dev tools of the browser.

![DevTools output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nfb9jkdopum83fv2wkn2.png)

So basically `html2pdf.js` package is expecting simple HTML and nothing is happening.

Lets convert JSX to HTML first using `ReactDOMServer` and then pass that to html2pdf function.

`App.js`

```javascript
import ReactDOMServer from 'react-dom/server';
import html2pdf from 'html2pdf.js/dist/html2pdf.min';
import './App.css';

function App() {
  const pdfJSX = () => {
    return (
      <>
        <h1>JSX to PDF Convert Example</h1>
        <h2>Hello React</h2> 
      </>
    )
  }

  const printHandler = () => {
    const printElement = ReactDOMServer.renderToString(pdfJSX());
    // const printElement = pdfJSX();

    html2pdf().from(printElement).save();
  }

  return (
    <div className="App">
      <button onClick={printHandler}>Print</button>
    </div>
  );
}

export default App;

```

Final Demo
![demo](https://media.giphy.com/media/jxUFGFkFFGik0L1rA1/giphy.gif)

**<br>Bonus (Fix Warnings)**
If you notice that there are some warnings on the terminal regarding the package and to fix them, I only found this solution.

- Create `.env.development` file inside root directory (_outside /src_)
- Add this line to the file:
`GENERATE_SOURCEMAP=false` and warnings would be gone.


<br>Library Reference:
[https://www.npmjs.com/package/html2pdf.js/v/0.9.0](https://www.npmjs.com/package/html2pdf.js/v/0.9.0)
Peace ✌️
HTTP: An Introduction
Tags: javascript, webdev, beginners
Published: 2022-06-25 08:24:06

**Hypertext Transfer Protocol (HTTP)** is a client-server protocol for fetching resources allowing communication between the server and the client.

The client initiates the process by sending a request and the server returns the requested document as a response.

The document is constructed from  different sub-documents fetched including, text, layout description, images, videos, and scripts.

The client combines these resources to render a web page that can be updated using the scripts.

**Characteristics of HTTP**

1. HTTP is simple allowing for readability and ease of use
2. HTTP is extensible and adaptable to various functionalities between the server and the client.
3. HTTP is stateless and the server does not keep any data about the request. Each request is independent.

### **HTTP Messages**

Two types of HTTP messages; Request and Response. 
The request consists of the 
- **HTTP method**

This represents the operation the client wants to perform.

The most commonly used HTTP methods are GET, POST,PUT and UPDATE.

- GET is used to retrieve resources from the server.
- POST is used to send resources such as form data to the server.
- DELETE is used to remove resources from the server 
- PUT is used to make changes to existing information in the server.
- HEAD is used to get the headers of a get request without the body.
- PATCH is used to make partial updates to resources.
 
Learn more HTTP methods [here](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods).

- **Path** 
This is the path of the resources to be used. The URL of the resource.

- **Body**
Data sent to the server. POST,PUT and PATCH requests have request bodies. 
- **optional headers**
The headers give the server more information about the request.

The response consists of the 

- **HTTP response status codes**

HTTP response status codes indicate whether a specific HTTP request has been successfully completed. 
The status code fall under five categories:

- Informational responses (100–199)
These responses are used to give more information to the client on how to proceed while waiting for a response.

- Successful responses (200–299)
These indicate that the request was executed successfully and a response sent to the client successfully.

- Redirection messages (300–399)
These responses inform the client on where to find a resource if it has been moved or redirected elsewhere.

- Client error responses (400–499)
The response alert the client of an error on their side causing the server to be unable to process the request.

- Server error responses (500–599)
Inform the client that their request was not processed because of an error on the server side.
Find specific status codes [here](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status)

- **Headers**
The headers provide more information about the response.

- **Body**
This is the data returned in a response from the fetched resource.

Details on HTTPs will be covered in a future post.

Happy learning!!!