teleren/devto huggingface dataset:
Handle CAPS-LOCK on/off event in Angular
Tags: angular, javascript, event, material
Published: 2022-05-07 20:58:06

This is an interesting, yet quite commonly expected, use-case - warn the user that the CAPS-LOCK is ON, specially while entering a password, so that the user is aware of it and can change it, if needed.

{% github anirbmuk/ng-capslock-demo no-readme %}

![Preview](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/03ij877itxenzasnndsy.gif)

There are a few scenarios handled in this demonstration:
1. Change the message when the user toggles the caps-lock while on the password field.
2. Also change the message when the user changes the caps-lock state elsewhere (maybe in another application or browser tab, etc) and then comes back to this application.
3. Remove the events when component is destroyed, to prevent memory leaks.
4. Run change-detection when `ChangeDetectionStrategy` is `OnPush`.

---

Let's see about 1 & 2.

> By the way, I am on @angular/cli 13.3.0 and @angular/material 13.3.6. For the message, I have used `mat-hint` on `mat-form-field`.

To achieve this, we grab the reference of the password field (using `@ViewChild`) and then add a couple of event handlers to the underlying `HTMLInputElement` - `keyup` and `mousedown`.

The `keyup` event handler will toggle the message when the user toggles the CAPS-LOCK button while being on the password field. This generates a `KeyboardEvent`.

The `mousedown` event handler will toggle the message when the user changes the state elsewhere and the navigates back to the application and clicks on the password field. This will be beneficial for the user since the information is now provided even before something is typed. This is done through a `MouseEvent`.


![ngAfterViewInit](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vmagyotxyzpbm56vuf24.png)

---
### Some improvements:

To prevent memory leaks, we need to remove these event handlers once the component is destroyed.
![ngOnDestroy](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7a1mdf49f3qo06ojom2z.png)

If the `ChangeDetectionStrategy` is set to `OnPush`, we need to mark the component for a change detection whenever either of the above events are fired. So, at the end of the event handler, use
```
this.cdRef.markForCheck();
```

The browser's password manager may auto-fill the password data for you. This will also fire a `keyup` event, but this will not be an instance of `KeyboardEvent` and will thus not have the `getModifierState` method. So we will ignore this!
```
if (event?.type === 'keyup' && !(event instanceof KeyboardEvent)) {
  return;
}
```

Cheers!
[Anirban Mukherjee](https://anirbmuk.appspot.com/en)
Interface Consumer en Java bDarija
Tags: darija, java, consumer, interface
Published: 2022-05-07 20:36:32

L'interface Consumer kaykon f java.util.function.
 
Syntax dialha:

```
@FunctionalInterface
public interface Consumer<T> {
  void accept(T t);
}
```

  * T type de l'argument
  * t l'argument  
  * void type de retourne implique que la fonction makatrejee walo

**Exemple dial program:**

```
Consumer<Integer> consumer= new Consumer<Integer>() {
            @Override
            public void accept(Integer integer) {
                System.out.println(integer);
            }

        };
```
nefs lcode walakin had lmera b lambda

```
Consumer<Integer> consumer1=(integer)-> System.out.println(integer);

```
JavaScript Calculator - The DOM way
Tags: javascript, webdev, watercooler, showdev
Published: 2022-05-07 20:24:14

So I was bored this morning and did said to me "let's do a calculator with JS". 
I planned to do it in React but then "Why do I need react or any other library to do it?" so I ended up with this calculator with JS relying on the information showed on the DOM.


{%codepen https://codepen.io/joelbonetr/pen/vYdLKXG %}


I know it's not 100% perfect but those were 4 well spent hours.
 
That's all folks! 

<img src="https://c.tenor.com/MK3U9VAdNq4AAAAC/talk-soon-talk-to-you-soon.gif" />

PD: If you want more JS-related stuff check out <a href="https://dev.to/joelbonetr/structs-in-javascript-1p9l">this dope thingy</a>.

<hr />
<p align="center">Do you like my content?</p>
<a href="https://www.buymeacoffee.com/joelbonetr" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-blue.png" alt="Buy Me A Coffee" style="height: 60px !important;width: 217px !important;" ></a>
Day 22-25 of 100 Days of Code: Thinking Responsively
Tags: webdev, html, css
Published: 2022-05-07 20:10:08

I developed a 3-page responsive website using. The theme of the site is living a simple life. The site is mobile friendly using media queries and flexbox. This was a build-along project with Scrimba. You can view it [here](https://simplelicity.netlify.app/).
5 Surprising ways to use Rails console
Tags: ruby, rails, codenewbie, webdev
Published: 2022-05-07 20:06:18

While running on Rails, there's been hardly a day when you don't pull up rails console. Having basic mode and usage is fine but to spice up things a little bit I would like to share some tricks in this regard.


## View Tables
Just run this command and get a glimpse of tables

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/900maaq4yvo76lie5fnk.png)


## Sandbox Mode
You can enable sandbox mode, so that commands are rolled back once you exit

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xktujzs6kb28qvonmk7o.png)


## Make HTTP Requests
Being lazy to hit a route through chrome or any other browser, just play with **app** object's methods!

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/upiw32a2xca5ohnhrdhi.png)


## Locate Method Source
Its a kindof search feature that a code editor also offers, but helpful one for the rubyists

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v8c7e2r3e3d66lq46p6g.png)


## Block Returned Output
If you're annoyed from the return value by iterators and other structures, this will let you cool down!

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ij1768yev9de4stb91yi.png)

Does it worth time saving?. Let me know inside comments. 
Make sure to Love and follow @moiz1524
Build Dynamic Dependent Dropdown using React JS
Tags: react, mui, javascript, webdev
Published: 2022-05-07 20:06:07

A cascading dropdown is a group of dropdowns where the value of one dropdown depends upon another dropdown value. Child dropdown values are populated based on the item selected in the parent dropdown.

Tools and Packages :

- [React](https://reactjs.org/)

- [Material UI (M-UI)](https://mui.com/)

- [Axios](https://www.npmjs.com/package/axios)

_API Link:_ [API](https://pkgstore.datahub.io/core/world-cities/world-cities_json/data/5b3dd46ad10990bca47b04b4739a02ba/world-cities_json.json
)

App.js

```
import { Autocomplete, Container, TextField, Typography } from "@mui/material";
import { Box } from "@mui/system";
import axios from "axios";
import { useEffect, useState } from "react";

function App() {
  const [data, setData] = useState([]);
  const [getCounty, setCounty] = useState([]);
  const [getState, setState] = useState([]);
  useEffect(() => {
    axios
      .get(
        "https://pkgstore.datahub.io/core/world-cities/world-cities_json/data/5b3dd46ad10990bca47b04b4739a02ba/world-cities_json.json"
      )
      .then((response) => {
        // console.log(response);
        setData(response.data);
      })
      .catch((err) => {
        console.log(err);
      });
  }, []);

  const country = [...new Set(data.map((item) => item.country))];
  // console.log(country);

  // console.log(data);

  const handleCountry = (event, value) => {
    let states = data.filter((state) => state.country === value);
    states = [...new Set(states.map((item) => item.name))];
    states.sort();

    setState(states);
  };

  return (
    <Container>
      <Typography>Dependent Select Field</Typography>
      <Autocomplete
        onChange={(event, value) => handleCountry(event, value)}
        id="country"
        getOptionLabel={(country) => `${country}`}
        options={country}
        isOptionEqualToValue={(option, value) => option.name === value.name}
        noOptionsText={"No Available Data"}
        renderOption={(props, country) => (
          <Box component="li" {...props} key={country} value={getCounty}>
            {country}
          </Box>
        )}
        renderInput={(params) => <TextField {...params} label="Search" />}
      />
      <Autocomplete
        id="city"
        getOptionLabel={(getState) => `${getState}`}
        options={getState}
        isOptionEqualToValue={(option, value) => option.name === value.name}
        noOptionsText={"No Available User"}
        renderOption={(props, getState) => (
          <Box component="li" {...props} key={getState}>
            {getState}
          </Box>
        )}
        renderInput={(params) => <TextField {...params} label="City" />}
      />
      {/* <Autocomplete /> */}
    </Container>
  );
}

export default App;
```

**Github Repository Link:** [GitHub](https://github.com/jps27CSE/Dependent_Input_API_React)
RARE ALERT: Monkeypox Case Confirmed In The UK
Tags: mentalhealth, news, uk, webdev
Published: 2022-05-07 19:43:30

The first human case of monkeypox was recorded in 1970 within the Democratic Republic of Congo during a period of intensified effort to eliminate smallpox. From that point on monkeypox has been reported in humans from other central and western African countries.

If you get infected with monkeypox, it usually takes between 5 and 21 days for the first symptoms to appear.

The first symptoms of monkeypox include:

- a high temperature
- a headache
- muscle aches
- backache
- swollen glands
- shivering (chills)
- exhaustion

A rash usually appears 1 to 5 days after the first symptoms. The rash often begins on the face, then spreads to other parts of the body.

The rash is typically confused with chickenpox. It starts as raised spots, which changes into small blisters stuffed with fluid. These blisters eventually form scabs which later fall off.

The symptoms usually clear up in 2 to 4 weeks.

If you plan on travelling to West and Central Africa then here are a couple of things you can do to cut back the danger of getting it.

**To Do:**

- Wash your hands with soap and water regularly or use an alcohol-based hand sanitiser

- Only eat meat that has been cooked thoroughly

**Don't Do:**

- Don't go near wild or stray animals, including dead animals
- Don't go near any animals that appear unwell
- Don't eat or touch meat from wild animals (bush meat)
- Don't share bedding or towels with people who are unwell and may have monkeypox
- Don't have close contact with people who are unwell and may have monkeypox

## Monkeypox In The UK

Only a few people have been diagnosed with monkeypox in the UK. These people had all traveled to west Africa or were close contacts of someone who had traveled to west Africa.

The UK Health Security Agency (UKHSA) confirmed a case has been found in Britain in a statement today.

The patient travelled from Nigeria and is now being treated at St Thomas's Hospital in London.

UKHSA is now working with the NHS to contact anyone who may have been in close contact to the infected person.

The disease is extremely rare and therefore the risk of catching it within the UK is extremely low. 

See Full Report [Here](https://www.cdc.gov/poxvirus/monkeypox/index.html).
Laravel 9 Multi Update or Insert with this 'Magic'
Tags: laravel, php
Published: 2022-05-07 19:40:08


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yqr5eddmmq8tz2nxm8ze.png)
Laravel includes Eloquent, an object-relational mapper (ORM) that makes it enjoyable to interact with your database. When using Eloquent, each database table has a corresponding "Model" that is used to interact with that table. In addition to retrieving records from the database table, Eloquent models allow you to insert, update, and delete records from the table as well.

If you would like to perform multiple "_upserts_" in a single query, then you should use the upsert method instead. The method's first argument consists of the values to insert or update, while the second argument lists the column(s) that uniquely identify records within the associated table. The method's third and final argument is an array of the columns that should be updated if a matching record already exists in the database. The upsert method will automatically set the created_at and updated_at timestamps if timestamps are enabled on the model:

```
if(count($data) > 0) {
   $error = '';
}
PostNilai::upsert($data,['id','user_id','nilai_id','score_s1','score_s2','score_s3','score_s4','score_s5']);
return redirect(route('nilai'))->with('error', $error);

```

{% details watch full tutorial %} 
https://youtu.be/eMBS80A2SzI
{% enddetails %}
CREATING CRUD PAGES WITH SQL SERVER, ASP NET WEB API, ANGULAR AND RADZEN
Tags: webapi, angular, radzen, sqlserver
Published: 2022-05-07 19:35:40

Source code and database script can be found at https://github.com/benjaminsqlserver/BookStoreAngularWithWebAPI
{% embed https://www.youtube.com/watch?v=8U1TzZihvSI %}
Pass by Value
Tags: go, tutorial
Published: 2022-05-07 19:19:45


In this section We Will Discuss What Does Mean "Pass by Value"
  We have 2 Type of Values
  
  Pointer Wrapper Values
 - Map
 - Slices
 - Functions

Non-Pointer Values

- Strings
- Int
- Floats
- Booleans
- Arrays
- Stuctures

For **non-pointers**, we need to redefine separately, for example

Whenever we try to change it with a function parameter, a variable copy of a new parameter is created in the computer memory for that function, so it does not change even if we try to change the value of the variable in our next codes. due to scope range
 
 ```go
package main

import "fmt"

func changevalue(i int) {
	i = 20
}

func main() {
	i := 5
	changevalue(i)

	fmt.Println("Value:", i) // Value: 5
}
```
If you ask how this is for the **pointer wrapper value**, they update the memory address directly instead of creating a copy for the variable.

```go
package main

import "fmt"

func changevalue(y map[string]float64) {
	y["baklava"] = 15.5
}

func main() {

	menu := map[string]float64{
		"pie":       35.6,
		"ice cream": 20.4,
	}

	fmt.Println(menu) // map[ice cream:20.4 pie:35.6]
	changevalue(menu)
	fmt.Println(menu) // map[baklava:15.5 ice cream:20.4 pie:35.6]
}

```
Thanks for Reading 
*WinneRose*
How to spot poor implementations of 2FA
Tags: security, cybersecurity, passwords
Published: 2022-05-07 19:06:36

I enable 2FA every time it's possible, and I encourage you to do the same.

2FA means two-factor authentication. It's an extra layer of security that forces you to enter one-time passwords (OTP) in addition to your classic credentials (login/passwords). 

Most of the time, it's a series of 6-8 numbers that are sent by SMS or generated with a dedicated mobile app. This way, it's another device, for example, a smartphone, that holds the authentication factor.

Besides, even if your credentials are stolen or leaked, hackers won't be able to use them **theoretically**. The problem is that some implementations are flawed or prone to attacks.

## Disclaimer

It's not an exhaustive list but a collection of simple observations.

## 7 signs of bad 2FA implementation

* the generated OTP does not seem to expire, even hours after
* you can access the URL directly, for example, your admin panel, so the 2FA can be totally bypassed
* the 2FA process depends on a header or a status code that can be modified from the client side
* there's no limit for login attempts with OTP, so hackers can Brute-Force the code easily*
* 2FA is automatically disabled during passwords recovery
* re-sending the code resets the limit of login attempts
* the 2FA procedures discloses sensitive information, like "we've sent an authentication code to +12277777777"

_*6-8 numbers is the equivalent of a very weak password during a Brute-Force attack_

## How to fix the situation

Again, enabling 2FA is a valid choice, regardless of the implementation, but if you see something strange, like one of the 7 signs we've just saw, do not hesitate to report it to the apps/websites/services.

Fortunately, not all implementations are that bad. While even the most robust ones can be bypassed under specific conditions, 2FA hardens your security significantly.
Drop Shadow Service | Reflection Shadow- touch editing fast Best quality
Tags: carphotoeditor
Published: 2022-05-07 18:59:45

Pictures of beautiful cars are enough to attract the attention of your customers. [Car photo editing services](https://toucheditingfast.com/best-car-shadow-service-reflection-shadow-creation-car-images-edit/) can give you the perfect image for your ad. Visit our website if you need car photo editing services.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yj850n0hsza8jnzb98sk.jpg)
Command Line Minesweeper (written in Python)
Published: 2022-05-07 18:46:10

I have been working to finish the Codecademy Computer Science Career Path, and am about to wrap up CS 101, the first course therein. The final project was to create a terminal-based game. Because it's a game I have enjoyed in the past, and because I could easily imagine how to implement this game using object oriented programming and modular design, I chose to create my own version of Minesweeper.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qu1ceoy1eo1b8e2ofihc.png)

This program is mainly built around the "Cell" class. A "Cell" has boolean properties that track whether each cell has been stepped on, has a bomb, or has been flagged by the user. Other "Cell" properties include the number of bomb cells surrounding each cell, and the "mask" which labels a Cell at any particular moment (as a bomb, a flag, or the number of surrounding bombs). Most of the work is done by helpful functions such as "print_board", "check_surrounding_cells", and "step". This allowed the "main" section of the program to be designed as a single while-loop. 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uzyrytc90fntrhjsksaz.png)

This version of Minesweeper is licensed under the GNU GPL Version 3, and as such, it is free software. It is hosted on GitHub here:
https://github.com/spekkio1/minesweeper

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fb2g34rgajbmk0wp54im.png)

I hope that this implementation of Minesweeper will serve as a way for a gamer to have a little fun, as well as a way for a novice programmer to be able to study some freely licensed code, in order to see how a simple game like this can be implemented in Python. I also created this program as a way to finish CS 101 at Codecademy and demonstrate my burgeoning Python skills.
Chords in HTML
Tags: html, music
Published: 2022-05-07 18:30:34

As an amateur guitarist, I use chord websites, and sometimes I think about how to implement it with HTML and CSS. I mean, the tricky part of keeping the chords in the right position relative to the letter it points on.

![image](https://i.ytimg.com/vi/jl32u4LEX00/hqdefault.jpg)

One day came across a cool HTML element, [`<ruby/>`]("https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ruby") that can solve this problem.

>The `<ruby>` HTML element represents small annotations that are rendered above, below, or next to base text, usually used for showing the pronunciation of East Asian characters. It can also be used for annotating other kinds of text, but this usage is less common.

A [codepen]("https://codepen.io/oryamne/pen/OJxgEJe") to play with

By the way, by inspecting chords website you can see that they are using different methods.
How does the clear in CSS work?
Tags: css, webdev, productivity, beginners
Published: 2022-05-07 18:17:03

The **clear** property works with respect to **float** property. It sets whether an element must be moved below the floating elements that precede it.

##Let's understand this with the help of an example.

We will consider four blocks red, yellow, blue and green which will be added one after the other and they all will be placed at same level.

![Adding blocks](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bmt4nt2u7bholu2ftl6m.gif)

Then we will make each element float to left one by one which means they will be moved one level above their initial position. This will allow other non floating elements to wrap around the floating element.

![floating blocks](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n1vfskzrugejuj3o59tt.gif)

**Note - The next block will occupy the position of the floating block that is why it is not visible. When we change the dimension of next block we observe that it is covered with floating block which is present one layer above it.**

After this we will apply `clear:left` to blue block which means that no element will be floating to the left of blue block.

![Clear blocks](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/66zzcozp15zlu4kjvjwk.gif)

With the help of clear property we can specify that which side of floating elements are not allowed to float. It sets or return the position with respect to the floating objects.

##Values accepted in clear property.
```css
clear: none;
clear: left;
clear: right;
clear: both;
clear: inline-start;
clear: inline-end;

clear: inherit;
clear: initial;
clear: revert;
clear: revert-layer;
clear: unset;
```

You can find the code [here](https://jsfiddle.net/Jasmincvv/hm89skrx/)

I tried to cover the working of CSS clear property using a basic example for better understanding. Please share your examples and feel to add up to this post 😊

Happy Learning!👩🏻‍💻
Pyscript! Finally!
Tags: webdev, python, productivity, html
Published: 2022-05-06 06:32:35

For all of us who have had it with server side/client side programming languages separation and have had it with having to learn at least one language from both sides of the fence, our day has come!
If Java could have JavaScript as its web client programming language offspring (both languages actually not being related and naming the clientside scripting language after Java as a marketing gig aside), why can't the all-mighty Python have its own client side scripting language offspring called (aptly) Pyscript?
Despite the Pyscript project being in its very alpha stage of development, things look very, very promising. The two most exciting parts in its current stage of development (for Python developers at least) are the abilities to inject output of Python functions into HTML elements (provided you already tagged them with `id=`) and to enclose actual Python code at its full power within <py-script> tags. Provided, any additional packages needed for that code to work are imported within the HTML's `<head>` tags, within `<py-env>`. Oh what could be imported? Well, how about matplotlib? Or NumPy?
What a great Cinco De Mayo this is! Head over to [PyScript's project home on GitHub](https://github.com/pyscript/pyscript/blob/main/GETTING-STARTED.md) and get as excited about this project as I am now.