teleren/devto huggingface dataset:
Roman to Integer in Dart - Leetcode
Tags: dart, leetcode, programming, tutorial
Published: 2022-08-07 05:24:00

## Roman to Integer

## Approach

1. Maintain a map with roman symbol and their corresponding integer equivalent - Already given in the question

2. Scan the string from right to left. Get the corresponding value to the current character from the map and add into to result

3. The special case is where the character at the left of the current character whose value is less than the value corresponding to the current character. For e.g x represent 10, but IX represents 9. In this case we have we subtract the value of the character in the left from the result

### Code

Both Solutions are perfectly fine but first one pass with flying colors and other one end up with fatal and most annoying error I think or believe it something that while loop is broken, or maybe it does execute properly on leetCode platform

#### Simple Solution

```dart

class Solution {
  int romanToInt(String s) {
    Map<String, int> romanMap = <String, int>{
      "I": 1,
      "V": 5,
      "X": 10,
      "L": 50,
      "C": 100,
      "D": 500,
      "M": 1000,
    };
    int n = s.length;
    var nums = romanMap[s[n - 1]];
    for (var i = n - 2; i >= 0; i--) {
      if (romanMap[s[i]]! >= romanMap[s[i + 1]]!) {
        if (nums != null) {
          nums += romanMap[s[i]]!;
        }
      } else {
        if (nums != null) {
          nums -= romanMap[s[i]]!;
        }
      }
    }
    return nums!;
  }
}


```

Runtime: 841 ms, faster than 88.89% of Dart online submissions for Roman to Integer.
Memory Usage: 149.6 MB, less than 66.67% of Dart online submissions for Roman to Integer.

#### Algorithmic Solution

```dart

class Solution {
  int romanToInt(String s) {
    int getInt(String s) {
      switch (s) {
        case "I":
          return 1;
        case "V":
          return 5;
        case "X":
          return 10;
        case "L":
          return 50;
        case "C":
          return 100;
        case "D":
          return 500;
        case "M":
          return 1000;

        default:
          -1;
      }
      return 0;
    }

    int n = s.length;
    int result = 0;
    int current = 0;
    int next = 0;
    int i = 0;

    while (i < n) {
      if (i == n - 1) {
        result += getInt(s[i]);
        return result;
      }
      current = getInt(s[i]);
      next = getInt(s[i + 1]);
      if (current >= next) {
        result += current;
        i++;
      } else {
        result += next - current;
        i += 2;
      }
    }

    return result;
  }
}

```

#### Error

Submission Detail
64 / 3999 test cases passed.
Status: Time Limit Exceeded
Last executed input: "MCXXV"
1220. Leetcode Solution in Java
Tags: java
Published: 2022-08-07 05:14:17

```
class Solution {
    public int countVowelPermutation(int n) {
        final int MODULO = 1000000007;
        long[][] dp = new long[n][5];
        Arrays.fill(dp[0], 1);
        for (int i = 1; i < n; i++) {
            dp[i][0] = (dp[i - 1][1] + dp[i - 1][2] + dp[i - 1][4]) % MODULO;
            dp[i][1] = (dp[i - 1][0] + dp[i - 1][2]) % MODULO;
            dp[i][2] = (dp[i - 1][1] + dp[i - 1][3]) % MODULO;
            dp[i][3] = dp[i - 1][2];
            dp[i][4] = (dp[i - 1][2] + dp[i - 1][3]) % MODULO;
        }
        long sum = 0;
        for (int i = 0; i < 5; i++)
            sum += dp[n - 1][i];
        int count = (int) (sum % MODULO);
        return count;
    }
}
```
#leetcode
#challenge
Here is the link for the problem:
https://leetcode.com/problems/count-vowels-permutation/
Save scroll state in React when visiting an other page with a custom hook
Tags: react, javascript, webdev, tutorial
Published: 2022-08-07 05:04:00

## The problem:

Saving scroll state is very a important for a good user experience especially when the page in your React web application is really long and has a lot of content. It can be quite annoying when a user visits another page and comes back to the previous page only to find out that they have to scroll from the top of the page all over again. Well we can save them this pain by adding a little code that saves the scroll position of the page the user was at before.

### Lets create custom hook in useScrollPosition.js

```javascript
import {useEffect} from "react";

// Object in which we will save our scroll position state
const scrollPositions = {};

/* custom hook which will save the scroll state and also set 
the scroll position of our page */
const useScrollPosition = (page) => {

    useEffect(() => {

// Get the scroll state if it exists

        const pageScrollPosition = scrollPositions[page];

// If it exists then set the scroll position of our page

        if (pageScrollPosition) {

/* Using setTimeout to set the scroll position of the 
page as useEffect gets triggered before the page has 
actually rendered */

            setTimeout(() => {
                window.scrollTo(0, pageScrollPosition);
            }, 50)

        }

/* save function to save the scroll position in 
the scrollPositions object */

        const save = () => {
            scrollPositions[page] = window.scrollY;
        }

/* Attaching an event listener to listen for a scroll event 
and then fire the save function everytime a scroll event occurs */

        window.addEventListener('scroll', save)

/* Removing the event listener when the component unmounts*/

        return () => {
            window.removeEventListener('scroll', save)
        };
    }, [page]);
}

export default useScrollPosition;

```

### Now use the useScrollPosition hook in your component where you want to save the scroll state:

```javascript 
import useScrollPosition from "./useScrollPosition";

// Call the useScrollPosition hook with the page name

useScrollPosition("Home")
```

### That's it! We're all done!

<img src="https://media.giphy.com/media/l0Iyl55kTeh71nTXy/giphy.gif" alt="all done gif">
Bringing perspective to CSS
Tags: css
Published: 2022-08-07 05:00:46

The other day I started exploring [3D in CSS](https://daily-dev-tips.com/posts/creating-a-3d-dice-in-css/) and began with a dice.
The dice is excellent in 3D. However, it has no perspective, so it's still 2D in 3D.

Let's fix that and bring some perspective to 3D.

If we stop the rotation on the dice and look at it from the front, you can see the overlap, but all sides are equally big.

This is a bit weird, as the back panel should be smaller as it sits more to the back.

![3D cube in CSS](https://cdn.hashnode.com/res/hashnode/image/upload/v1658988326785/MxPrf0Zy3.png)

## CSS perspective

That's precisely where the perspective style can come into play.

Let's apply the following style to the body tag:

```css
body {
  perspective: 400px;
}
```

![3D css perspective](https://cdn.hashnode.com/res/hashnode/image/upload/v1658988600881/WYX0xpbLM.png)

A crazy difference already, right?

You can play around with the value. The lower you go, the more intense the 3D becomes.

We also get `perspective-origin`, which can define from which angle you are looking at an object.

The default value is `50% 50%`, and we can use values we know from position to set it.

```css
body {
  perspective-origin: left;
}
```

This will set the perspective to the left.

![CSS perspective origin](https://cdn.hashnode.com/res/hashnode/image/upload/v1658988858910/2qTkECSyp.png)

As you can see, this becomes a bit weird, and you can make the perspective a bit bigger to get the correct display.

Playing with perspective can give your 3D css that next-level feeling.

Feel free to play around with the adjusted dice.

{% codepen https://codepen.io/rebelchris/pen/oNqovYr %}

### Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on [Facebook](https://www.facebook.com/DailyDevTipsBlog) or [Twitter](https://twitter.com/DailyDevTips1)
Give magical powers to your DOM in Angular JS
Tags: angular, directives, javascript, webdev
Published: 2022-08-07 04:58:00

One of my mentees asked me why we use angular when the same thing can be built using html,so i explained to him about performance, maintenance and code organization but he was not convinced. So I have to explain the magical powers of angular to him. I told him that angular is a wizard who can give magical powers to any element.

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

To give new power to any element we need magic spells which we call as "Directives". Basically Directives are classes that add new behavior or modify the existing behavior to the elements in the template.

So you can add two types of magical power or behavior to an element, one is attribute directive in which you can modify attribute behavior of an element like you can modify style attribute using ngSTyle where you can put complex style in the element.There are many inbuilt attribute directives available like ngClass or ngModel.

```
<div [ngStyle]="{'background-image': 'url(' + value ? image : otherImage + ')'}"></div>
```

The other kind of magical power or behavior is Structural directive, where you can change the whole behavior of an element altogether, like you can set visibility of an element using ngIf directive or you can show list of an element using ngFor.

```
<div *ngIf="condition">Content to render when condition is true.</div>
```

These two directive i have explained practically in my [YT video](https://youtu.be/AsauWmRnERE) series as well, you can check that too.
You can also create your own spell, means you can create your own directive as well
Simplest custom directive can be:

```
import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
   constructor(private eleRef: ElementRef) {
      eleRef.nativeElement.style.background = 'red';
   }
}
```
This directive simply update the color of element to red but you can have an idea form this how to create a custom directive.

This brief blog gives you idea about what is directives in Angular, Happy Koding everyone!!!
Show devs: Cronit - The online cronjobs service
Tags: programming, ops, webdev, serverless
Published: 2022-08-07 04:41:25

Hi everyone, 

Today I decided to share one of the latest tools I made, to help the developer community. It's called Cronit ([https://cronit.app](https://cronit.app)): a code execution scheduling system, directly from your browser. 

## How does it work? 

The principle is simple: thanks to Cronit, you can create recurring jobs and schedule them very easily, directly from a web application accessible from your web browser. 

Just define a schedule, and an HTTP endpoint to call recurrently, and the application takes care of everything. 

## Why Cronit? 

For the record, Cronit was born from a simple observation: during my career as a developer, I frequently had to set up and configure recurring scripts. To do so, I had to use different tools, such as cron. Each time, I also had to waste a lot of time setting up and installing servers whose only purpose was to run these cron tasks. Realizing how much time this was wasting, I decided to abstract this step by creating the first fully serverless online cronjobs system.
Create simple speech recognition program
Tags: python, ai, beginners, programming
Published: 2022-08-07 04:09:39

if you are an ironman fan you probably know about his two AI systems called 'Jarvis' & 'friday'. tony use speech recognition to give commands to his AI systems.

how to do it in the real world, is it posibble? the answer is yes it is. in here we use python to make a program that recognizes your speech and prints it out as text. let's get to work.

requirements for this project :

1. Python 3
2. Python speech recognition module.

now let's code.

to install the python speech recognition model, type this in your terminal

    pip install SpeechRecognition

and we use the microphone as our input method. in python to use a microphone we need another module name called "Pyaudio". to install that type this in your terminal.

    pip install PyAudio

now all set. we have to write some code to make a speech recognition system.

first of all import all necessary libraries.

    import speech_recognition as sr

now initialize the recognizer.

    listener = sr.Recognizer()

now we use an error handler in case there is an error. we use to `try` and `except`

    try:
        with sr.Microphone() as source:
            print('listning...')
            voice = listener.listen(source)
            command = listener.recognize_google(voice)
            print(command)
    
    except:
        pass

&#x200B;

Now, let's break down this one by one;

    with sr.Microphone() as source:

this means with the speech recognition model (we rename speech recognition as "sr" in the beginning) gets the microphone as a source of input.

    print('listning...')

print out the text "listing"

    voice = listener.listen(source)

get the user's

voice as input through the microphone

    command = listener.recognize_google(voice)

now we pass the user's voice into the google speech recognizer, by the way, we need an internet connection for this project.

    print(command)

now print out what the user said

the output will be like this :

    PS C:\Users\User\Desktop\python practice\ai> & "C:/Program Files/Python39/python.exe" "c:/Users/User/Desktop/python practice/ai/speech-recognition.py"
    listning...
    hello
    PS C:\Users\User\Desktop\python practice\ai> 

congratulations, now you build your own voice recognition system by using python. if you face any kind of trouble or error please inform me. about that. I like to help you with that.

the complete code :

    import speech_recognition as sr
    
    listener = sr.Recognizer()
    try:
        with sr.Microphone() as source:
            print('listning...')
            voice = listener.listen(source)
            command = listener.recognize_google(voice)
            print(command)
    
    except:
        pass
Update your Git version now!
Tags: git, beginners, productivity, tooling
Published: 2022-08-07 03:54:00

Git version 2.37 is here!, update yours and get access to all the updated features and fixes listed in the [Release note](https://github.com/git/git/blob/v2.37.0/Documentation/RelNotes/2.37.0.txt)

**Update Git on Windows**
For versions from 2.14.2 to 2.16.1
```
git update
```

For versions > 2.16.1, update Git with:
```
git update-git-for-windows
```


**Update Git on Linux**

```
sudo apt-get update
```

```
sudo apt-get install git
```

**Update Git on Mac**

```
brew upgrade git
```

Leave a comment if facing any problem.
or reach me at https://adarshgoyal.com/
Thank You!
Exporting images with Containerd CLI (ctr)
Tags: docker, containerd, dns, devops
Published: 2022-08-07 03:29:55

---
title: Exporting images with Containerd CLI (ctr)
published: true
description: Using the containerd CLI to export a container image
tags: docker, containerd, dns, devops
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
---

I recently found that a Docker image I use as a part of one of my Helm charts was no longer available on DockerHub, and I hadn't mirrored it in another location. It was running in a [K3s](k3s.io) cluster, meaning I couldn't `docker tag original-maintainer/image:tag me/image:tag` it and push to the Hub myself back on my local machine, which was running the Docker CLI. 

First, logging into a node with the image on it, I ran the following:

```bash
ctr -n k8s.io images export bind9:9.11.tar docker.io/internetsystemsconsortium/bind9:9.11 --platform linux/amd64
```
which exported the image to a tarball. This is similar to [`docker image save`](https://docs.docker.com/engine/reference/commandline/image_save/). 

Then, pulling it down to my Docker CLI machines:

```bash
scp jdmarhee@192.168.0.60:bind9:9.11.tar .
```

I then [`load`](https://docs.docker.com/engine/reference/commandline/load/) the image from the tarball:

```bash
 docker image load --input bind9\:9.11.tar
```
which returns the original tag for the image (`internetsystemsconsortium/bind9:9.11`) so I can re-tag it and push:

```bash
docker image tag internetsystemsconsortium/bind9:9.11 jmarhee/bind9:9.11

docker push jmarhee/bind9:9.11
```

Now this image is available on Docker Hub for my (and your) new clusters to access.
Learn Python #6 - Let's List it...
Tags: programming, python, webdev, codenewbie
Published: 2022-08-07 01:02:00

## What are Lists?

Lists in Python are the collection of elements of data. What does that mean? Let's check the below examples.


![List](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wiowauriesm0jnta7x00.jpg)


## Let us look at an example

- Example 1:

Let's say we have a list of employees with their `name` as the list items
```
employees = ["Abc", "Bcd"]
```
In the above item, you can add a new item, remove an item, append an item, and furthermore.

### Add an item
There are two ways in which we can add a new item to the list.

- Append

```
employee.append("Cde")
// employee -> ["Abc", "Bcd", "Cde"]
```

- Insert

```
employee.insert(0, "Efg")
// employee -> ["Efg", "Abc", "Bcd", "Cde"]
```
>The difference between the `append` and `insert` methods is that the `append` add the element at the last position of the list whereas in `insert` you can specify at what position you want to add the element.

### Get the length of the list
```
employee = ["Efg", "Abc", "Bcd", "Cde"]
len(employee) -> 4
```
`len` is useful that helps in getting the length of a list.

### Reference a list item by its position
```
employee = ["Efg", "Abc", "Bcd", "Cde"]
employee[2]
```
In the `[]` you need to specify a position of an element that you need a reference to.

### Changing an item in the list
```
employee = ["Efg", "Abc", "Bcd", "Cde"]
employee[1] = "Nitin"
```
Find the element by specifying the position and then assign the value.


## Conclusion

There are more posts on the way related to the lists...So keep reading.

Thanks in advance for reading this article...🚀

*I am more than happy to connect with you on*

- [@twitter](https://twitter.com/_nitinreddy3)
- [@LinkedIn](https://www.linkedin.com/in/nitinreddy3/)

*You can also find me on*

- [@Github](https://github.com/nitinreddy3)
- [@DEV](https://dev.to/nitinreddy3)
- [@Medium](https://medium.com/@nitinreddy3)
Deploy your React.js app on AWS Amplify
Tags: react, aws, tutorial, devops
Published: 2022-08-07 00:47:44

Hi, Devs!

Deploy and CI/CD is always necessary and important for software development cycle. Let's go to learn how to deploy React.js app and its using de AWS Amplify service on cloud?

---

First you need to create an account on [AWS](
Console de Gerenciamento da AWShttps://aws.amazon.com/en/console) and access the AWS Amplify service. After you could use the search engine on AWS and looking for AWS Amplify. Click on _Get started_.

![AWS Amplify - Luiz Calaça](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/02uij6hr0i484qu6xpv8.png)

Again, click on Get started
![AWS Amplify - Luiz Calaça](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bztwp57whhr3grasssvm.png)

Connect with you remote repository, I'm using here Github to versioning my React.js app.
![AWS Amplify - Luiz Calaça](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m78ce3zdah7q5opgu1jp.png)

Add your repository.
![AWS Amplify - Luiz Calaça](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eku4au3fpp75rtbnsk2x.png)

In that step you could click on Next ou copy the code and put it on your project. It's better click on next e carry on because automatically that file will run on your project connected.
![AWS Amplify - Luiz Calaça](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hygx75tl69f0p4wusf9d.png)

If you click on Advanced Setting you could put all environment variables and use your Docker image if you desire, in that case you need to push your imagem do Docker Hub and so on inform the link in that field. And click next.
![AWS Amplify - Luiz Calaça](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t20ubmceblxiawt5w1dy.png)

Almost there and now we need to review and next to deploy.
![AWS Amplify - Luiz Calaça](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j4bmranrh78klv0axa0r.png)

The deploy has initialized and after that steps you app will available using the url below of your branch like the image here.
![AWS Amplify - Luiz Calaça](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fe3yoolynbt5yaqhhodg.png)
     
Click on your URL and see you app already deployed.
![AWS Amplify - Luiz Calaça](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/clicfgkev03jnlov48ws.png)

That' all and easy steps!

**Contacts**
Email: luizcalaca@gmail.com
Instagram: https://www.instagram.com/luizcalaca
Linkedin: https://www.linkedin.com/in/luizcalaca/
Twitter: https://twitter.com/luizcalaca
How to apply a mask into a portrait with canvas
Tags: javascript, webdev, canvas
Published: 2022-08-07 00:36:08

You see, photo contains a lot pixels, and each pixel contains 4 values: r: RED, g: GREEN, b: BLUE, a: ALPHA  or opacity. What we need is set the alpha value of original photo as the average of r g b value of mask photo.

```ts
    const maskedImageBase64 = await maskPhoto(maskPhotoUrl, originalPhotoUrl)
```

```ts
/**
 * Url to HTMLImageElement
 * @param {string} url: image url
 * @returns {Promise<HTMLImageElement>} HTMLImageElement
 */
export function urlToImageElement(url: string) {
  return new Promise<HTMLImageElement>((resolve, reject) => {
    const img = new Image()
    img.crossOrigin = "anonymous";
    img.src = url
    img.onload = () => resolve(img)
    img.onerror = reject
  })
}

/**
 * mask.jpg + original.jpg => masked.jpg
 * @param {string} maskImageUrl: mask image url
 * @param {string} originalImageUrl: original image url
 * @returns {Promise<string | undefined>} masked image url(base64)
 */
export async function maskPhoto(maskImageUrl:string, originalImageUrl:string) {
  try {
    const maskImage = await urlToImageElement(maskImageUrl)
    const originalImage = await urlToImageElement(originalImageUrl)
    const canvas = document.createElement('canvas')
    if (canvas) {
      canvas.width = originalImage.width
      canvas.height = originalImage.height
      const ctx = canvas.getContext('2d')
      if (ctx) {
        ctx.drawImage(maskImage, 0, 0, canvas.width, canvas.height)
        const maskImagedata = ctx.getImageData(0, 0, canvas.width, canvas.height)
        ctx.drawImage(originalImage, 0, 0, canvas.width, canvas.height)
        const originalImagedata = ctx.getImageData(0, 0, canvas.width, canvas.height)
        for (let i = 0; i < maskImagedata.data.length; i += 4) {
          const alpha = (maskImagedata.data[i] + maskImagedata.data[i+1] + maskImagedata.data[i+2]) / 3
          originalImagedata.data[i+3] = alpha;
        }
        ctx.putImageData(originalImagedata, 0, 0);
        return canvas.toDataURL()
      }
    }
  } catch (error) {
    console.error(error)
  }
}
```