teleren/devto huggingface dataset:
126. Leetcode solution in Java
Tags: java
Published: 2022-08-14 06:07:08

```
class Solution {
    public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {
        Set<String> words = new HashSet<>(wordList);
        List<List<String>> ans = new ArrayList<>();
        if (!words.contains(endWord)) {
            return ans;
        }
        
        Map<String, List<String>> adjWords = new HashMap<>();
        Map<String, Integer> dist = new HashMap<>();
        bfs(beginWord, adjWords, dist, words);
        dfs(endWord, beginWord, adjWords, dist, new ArrayList<>(), ans);
        
        return ans;
    }
    
    public void bfs(String beginWord, Map<String, List<String>> adjWords, Map<String, Integer> dist, Set<String> words) {
        Queue<String> queue = new LinkedList<>();
        queue.offer(beginWord);
        dist.put(beginWord, 0);
        for (String word : words) {
            adjWords.put(word, new ArrayList<>());
        }
        
        while (!queue.isEmpty()) {
            String cur = queue.poll();
            List<String> neighbors = neighbors(cur, words);
            for (String next : neighbors) {
                adjWords.get(next).add(cur);
                if (!dist.containsKey(next)) {
                    dist.put(next, dist.get(cur) + 1);
                    queue.offer(next);
                }
            }
        }
    } 
    
    public void dfs(String curWord, String beginWord,Map<String, List<String>> adjWords, Map<String, Integer> dist, List<String> path, List<List<String>> ans) {
        path.add(curWord);
        if (curWord.equals(beginWord)) {
            Collections.reverse(path);
            ans.add(new ArrayList<>(path));
            Collections.reverse(path);
        } else {
            for (String next : adjWords.get(curWord)) {
                if (dist.containsKey(next) && dist.get(curWord) == dist.get(next) + 1) {
                    dfs(next, beginWord, adjWords, dist, path, ans);
                }
            }
        }
        
        path.remove(path.size() - 1);
    }
    
    public List<String> neighbors(String word, Set<String> words) {
        List<String> ans = new ArrayList<>();
        char[] sc = word.toCharArray();
        for (int i = 0; i < sc.length; i++) {
            char cur = sc[i];
            for (char c = 'a'; c <= 'z'; c++) {
                sc[i] = c;
                String temp = new String(sc);
                if (words.contains(temp)) {
                    ans.add(temp);
                }
            }
            sc[i] = cur;
        }
        
        return ans;
    }
}
```

#leetcode
#challenge
here is the link for the problem: 
https://leetcode.com/problems/word-ladder-ii/
Check - isSubsequence
Tags: javascript, leetcode
Published: 2022-08-14 05:54:00

```js
var isSubsequence = function (s, t) {
  let i = 0; // T
  let j = 0; // S
  let isMatchFound = false;
  while (i < t.length) {
    if (t[i] === s[j]) {
      i++;
      j++;
    } else {
      i++;
    }
    if (j === s.length) {
      isMatchFound = true;
    } 
  }
  return isMatchFound;
};

console.log(isSubsequence("abc", "ahbgdc"));
```
Dark and Light Theme Toggler + YT Channel 🚀🔥
Tags: javascript, webdev, css, html
Published: 2022-08-14 05:31:00

### In this Article, I'll tell you how to create a DARK and LIGHT THEME TOGGLER with Pure HTML, CSS and JavaScript.
-----------------------------------------------

First create three files: index.html, style.css and script.js

Now paste this HTML code in your _index.html_
```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dark & Light Theme Toggler</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div>
        <input type="checkbox" class="checkbox" id="inp">
        <label class="label" for="inp">
            <div class="ball"></div>
        </label>
    </div>
</body>
<script src="script.js"></script>
</html>
```

Now its time for the styling and all, so lets write the CSS now paste this code in your style.css
```css
* {
    box-sizing: border-box;
}

body {
    background-color: #fafafa;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100vh;
    margin: 0;
    transition: background 0.2s linear;
}

body.dark {
    background-color: #292C35;
}

.checkbox {
    opacity: 0;
    position: absolute;
}

.label {
    background-color: #111;
    border-radius: 50px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: space-around;
    padding: 5px;
    position: relative;
    height: 26px;
    width: 50px;
    transform: scale(1.5);
}

.label .ball {
    background-color: #fff;
    border-radius: 50%;
    position: absolute;
    top: 2px;
    left: 2px;
    height: 22px;
    width: 22px;
    transform: translateX(0px);
    transition: transform 0.2s linear;
}

.checkbox:checked + .label .ball {
    transform: translateX(24px);
}
```

Now lets program the logic for the Toggler button, paste this javascript code in your script.js
```js
const inp = document.getElementById('inp');

inp.addEventListener('change', () => {
    document.body.classList.toggle('dark')
})
```

And this is it, click on the ball to see the magic
![Image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ss4shb8lrwanrqkytk4y.png)

This tutorial video is already on my channel - https://www.youtube.com/shorts/Lfetzzs6Bqo (Fantastic Frontend)
Subscribe the channel and like the video for more awesome content.
Also don't forget to follow me on dev.to

Made with 💗 by Arjun
Angular: Star rating with no external libraries
Tags: typescript, angular, html, css
Published: 2022-08-14 04:11:00

It is a very simple and very much needed small component required in every other blog to rate the services provided.

Mostly, developers want to use some external start-rating libraries to show much styled and very interactive stars. Though, We can also create such stylistic stars using native JS and CSS support. 

I always prefer to write things natively hence here is my implementation for the star rating without using any libraries. 

Please let me know any improvements. I am always happy to update the article.

```ts

// app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  title = 'Star Rating';

  arr: any[] = [];
  index: number = 0;

  constructor() {
    this.arr = [
      { value: 1, color: 'black' },
      { value: 2, color: 'black' },
      { value: 3, color: 'black' },
      { value: 4, color: 'black' },
      { value: 5, color: 'black' }
    ];
  }

  onClickItem(index: number) {
    this.index = index;
    this.manipulateArr(index);
  }

  onMouseHover(index: number) {
    this.manipulateArr(index);
  }

  onMouseLeave() {
    this.manipulateArr(this.index);
  }

  manipulateArr(index) {
    this.arr.forEach((item, i) => {
      if (i <= index - 1) {
        item.color = 'green';
      } else {
        item.color = 'black';
      }
    });
  }
}
```
```html
<!--app.component.html-->
<div>
  <ul>
    <li *ngFor="let item of arr" (click)="onClickItem(item.value)" (mouseover)="onMouseHover(item.value)"
      (mouseleave)="onMouseLeave()" [style.color]="item.color">*
    </li>
  </ul>
</div>

<p>User Rated: {{ index }}/5</p>
```
```scss
// app.component.scss
ul li {
  width: 60px;
  cursor: pointer;
  display: inline-block;
  font-size: 80px;

  &:hover {
    color: green;
  }
}
```

Mostly, everything written is self explanatory. But, explanation always help to the newbies.

In HTML, I populated stars using `arr` of items with symbol `*` (available on keyboard) using `ul`. This `arr` initialized with `5` elements hence `5-stars` displayed. You can see the `ts` file for the initialized array.

If user hovers on it then its color will change to `green` otherwise `black` and it has been handled using two events `mouseover` and `mouseleave` and the corresponding methods have been executed each time. 

Also, when user clicks on any star then `count` has been updated below as `User Rated: 4/5` and color will be `green` till selected. 

You can follow me: https://twitter.com/urstrulyvishwak

Here you can see how it works:

{% embed https://angular-ivy-bat5xd.stackblitz.io/ %}

Thanks
How I applied Leetcode lessons to work
Tags: career, leetcode
Published: 2022-08-14 02:19:00

Leetcode in itself isn't very useful. Yes, take 30 minutes to solve a Data Structures & Algorithm (DSA) question in an interview, but over the past 6 months in actual work, I've hardly had the need for DSA.

However, the mathematical thinking behind it may be very useful! Recently my feature's lead was ill, and I stepped up to fill that role. Swimming around in complexity and edge cases, and suddenly all those months of Leetcode practice just clicked!

## 1. Problem-Solving Skills
This is a process of a typical Leetcode interview

1. R - Repeat the question to make sure you understood problem.
2. E - give Examples to make even more sure.
3. A - suggest Algorithm(s) that might work.
4. C - Code it up, after permission from interviewer.
5. T - Test your code, run a few test cases.
6. O - Optimize the time / space complexity.

Credits: https://www.youtube.com/watch?v=DIR_rxusO8Q (omg, I viewed this prior to my first coding interview in May 2021)

And this is how I solved the problem at work
1. R - Revise problem information and constraints
2. E - think of Example test cases
3. A - find Areas in the codebase where I could implement new feature effectively, consider maintainability etc.
5. C - Code it up
6. T - Test it (with an XCode Simulator)
7. O - Optimize (in terms of writing Clean Code for maintainability. Time complexity is less important here in Frontend)

It is pretty much the same process!

## 2. It's OK to Simplify the Problem
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3h21q8jztoj90t09shno.gif)
Some days your mind is just sleeping, and in Leetcode you just can't solve. But you can solve a simpler sub-problem, rest, then come up with a better solution another time! (Though the interviewer might be like the GIF above)

Same goes for work, sometimes you can only deliver a partial feature (but your users won't know that) and that's OK! It can be built up slowly.

Just make sure to communicate the challenges and get everyone onboard.

## 3. Copy-Paste
Don't need to re-invent the wheel. If a problem you're trying to solve has been solved before, just copy-paste (but take care to check that code works / is safe).

## 4. DETERMINATION
Challenging problems are tough to crack, but with determination and focus, we will eventually get through it :)
(though Curiosity really helped me see it through also hmm)
Vue 3 Tip / Detect outside click
Tags: javascript, vue
Published: 2022-08-14 02:14:00

You need three things for this

**NOTE**: Options Api gist [here](https://gist.github.com/Erefor/1aa0c587bd0a9fc3e5c27683967df413)

1- A compontent ref like this:

```javascript

<template>
  <div
    ref="componentRef"
    class="general-style"
  >
  </div>
</template>

<script setup>
import { ref } from 'vue'

const componentRef = ref()
</script>
```

2- The next composable:

```javascript
import {onBeforeUnmount, onMounted} from 'vue'

export default function useDetectOutsideClick(component, callback) {
    if (!component) return
    const listener = (event) => {
        if (event.target !== component.value && event.composedPath().includes(component.value)) {
            return
        }
        if (typeof callback === 'function') {
            callback()
        }
    }
    onMounted(() => { window.addEventListener('click', listener) })
    onBeforeUnmount(() => {window.removeEventListener('click', listener)})

    return {listener}
}
```
3- Use within your component and send the ref as composable param:

```javascript

<template>
  <div
    ref="componentRef"
    class="general-style"
  >
  </div>
</template>

<script setup>
import { ref } from 'vue'
import useDetectOutsideClick from '/useDetectOutsideClick'

const componentRef = ref()
const exampleComposableText = ref('hello')

useDetectOutsideClick(componentRef, () => { 
exampleComposableText.value = 'edit hello'
})
</script>
```

Summary: Just declare a ref, point the ref to the template element and send it to the composable as first parameter. The second parameter of the composable is the callback what do you want to execute when clicked out.

Happy Code!
Use Absolute path in importing components - React || Next
Tags: react, nextjs, javascript, programming
Published: 2022-08-14 01:38:27

Simply create a jsconfig.json file in your base directory, then copy this code into it, then save.

```
{
  "compilerOptions": {
    // make all imports without a dot '.' prefix relative to the base url
    "baseUrl": ".",
    "paths": {
      "@/component/*": ["compomponents/*"]
    }
  }
}
```

Programming class enrollment for August: https://paystack.com/pay/ovuc-xymw6
Adding search to static sites with pagefind
Tags: pagefind, astro
Published: 2022-08-14 00:57:18


In this article I will cover how add pagefind to an astro site. This code is accessible in this github repo for those interested.

For pagefind, you can install it with the following command:

```bash
npm install pagefind
```

Then in your package.json file make sure you generate the search after your static site is built

```json
  {
  "scripts": {
    ...
    "build": "astro build",
    "postbuild": "pagefind --source dist",
  },
  }

```

Then you can run the following command to search for content in your site:

```html
<link href="/_pagefind/pagefind-ui.css" rel="stylesheet" />
<script src="/_pagefind/pagefind-ui.js" type="text/javascript">

</script>
<div id="search" class="ml-3 p-4"></div>
<script>
  window.addEventListener('DOMContentLoaded', (event) => {
    new PagefindUI({ element: '#search' });
  });
</script>
```

As described by the pagefind documentation, you can use the search bar to search for content in your site.

Another thing to keep in mind is that you can choose to not index certain pages.

```html
<body>
  <main>
    Content goes here
  </main>
<div class="bg-slate-900 text-gray-100" data-pagefind-body >
</div>
</body>
```

To index page content, use data-pagefind-body attribute on the page.

```html
<body class="bg-slate-900 text-gray-100" data-pagefind-body >
    <main>
    Content goes here
  </main>
</body>
```

To see this in action, you can look at my personal website repository.

https://github.com/FriendlyUser/astro-tech-blog

### References

* https://pagefind.app/
* https://friendlyuser.github.io
#46 - Sum of a sequence - Codewars Kata (7 kyu)
Tags: javascript, programming, 100daysofcode, computerscience
Published: 2022-08-14 00:43:13

**How can you help?**
[You can support by buying a coffee ☕️](https://www.buymeacoffee.com/cesardlr)
[Follow me on Github ](https://github.com/Cesardlr)
[Follow me on Twitter ](https://twitter.com/cesar__dlr)

##Instructions
**Task:**
our task is to make function, which returns the sum of a sequence of integers.

The sequence is defined by 3 non-negative values: begin, end, step (inclusive).

If begin value is greater than the end, function should returns 0

**Examples**

2,2,2 --> 2
2,6,2 --> 12 (2 + 4 + 6)
1,5,1 --> 15 (1 + 2 + 3 + 4 + 5)
1,5,3  --> 5 (1 + 4)

---

##My solution:


```javascript
const sequenceSum = (begin, end, step) => {
  var count = 0;
  for (let i = begin; i <= end; i += step) {
    count += i;
  }
  return count;
};
```


---

##Explanation
First I made the variable count, in which I'll save the results of the sums in the loop

```javascript
var count = 0;
```

---

Then I used a for loop, in which I started with the value of the begin param, it will iterate until the "i" value is equal to the end value, and in each iteration the "i" value will be summed the "step" param value.
And in each iteration I summed the "i" value to count

```javascript
  for (let i = begin; i <= end; i += step) {
    count += i;
  }
```

---

At the end I just returned count

```javascript
return count;
```

---


**What do you think about this solution? 👇🤔**

[Solve this Kata 👨🏽‍💻]
(https://www.codewars.com/kata/586f6741c66d18c22800010a)
Javascript Tagalog - Strings
Tags: javascript, tagalog, filipino, strings
Published: 2022-08-14 00:36:51


**Ano ngaba ang strings sa Javascript**
Ang string ay data structure lang para mag store and mag manipulate ng mga text.

---
**Strings Example**
Gumamit ng mga quotes para madefine mga strings either single or double quotes.
![Javascript Tagalog Filipino Strings](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3gwkg4gy8iigd967krol.png)
 
**May mga built in methods and properties ang javascript sa mga string**
![Javascript Tagalog Filipino Strings](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kr7lcly7s4fy4h2jhegz.png)
 
--- 
**Comparing Strings**
![Javascript Tagalog Filipino Strings](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ij96jh0pruoe0f1vwsnd.png)

---

**More tagalog Javascript Learning Resources:**
https://javascript-methods-in-tagalog.vercel.app/
Javascript Tagalog - Boolean
Tags: javascript, tagalog, filipino, boolean
Published: 2022-08-14 00:23:21


**Ano ngaba ang Boolean sa Javascript?**
Dalawa lang ang boolean values **true** and **false** and ginagamit often sa mga conditional statements... boom done pwede kana umalis alam mona yung Boolean values. joke lang may mga values na considered falsy and truthy boolean values.

**Truty Values Examples...**

![Javascript Tagalog - Boolean Values](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fehzby5e0648nc3wn653.png)

isNaN means "is Not a Number" in Javascript

**Falsy Values Examples...**
![Javascript Tagalog - Boolean Values](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1fbgj1z51usqnspe4tbm.png)
 
---
 
**Boolean expressions sa conditional statements**
![Javascript Tagalog - Boolean Values](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/azl2om8iy68mv75u2cyt.png)
 

---


**More tagalog Javascript Learning Resources:**
https://javascript-methods-in-tagalog.vercel.app/
Javascript Tagalog - Null
Tags: javascript, filipino, tagalg, null
Published: 2022-08-13 23:45:32

**Ano ngaba ang Null sa Javascript?**
Null meaning niya is walang reference or absent yung kinukuhang value, considered falsy value sa mga conditions statements.
Basta ang null ibig sabihin lang is empty or unknown na value

like undefined yung best way para matutunan ang mga ganitong values is code kalang ng code kasi siguradong ma e-encounter mo sila

---

**Example...**

![Null in Javascript Tagalog Filipino](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n8543rutbgxkoorn18ok.png)

**Console output**
![Null in Javascript Tagalog Filipino](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5le9jqxeg5sal5qeomu4.png)

since alam natin naturally may body element yung isang html success na naselect natin yung body element and since wala akong linagay na form element sa html, null yung binigay na value satin ng javascript

---

**Falsy value ang Null**

![Null in Javascript Tagalog Filipino](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b8z5z89j6805v3tiwbdv.png)


**Yung type ng Null is an object sa javascript**

![Null in Javascript Tagalog Filipino](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g01owtw2qhwhntgeh20o.png)

---

**More tagalog Javascript Learning Resources:**
https://javascript-methods-in-tagalog.vercel.app/
Soyhipst.cv
Tags: codepen, css, html, writing
Published: 2022-08-13 23:28:23

Hello! since you're here, check out my professional portfolio #developerjobs 👉
Proximamente subire mis proyecto con su URL. Si te agrada y apoyas mi talento, dejame tu like👍 y buena energy🤠 Th'k!

🌐 MyPortfolio => https://soyhipst.github.io/Soyhipst.cv-2022/

📲 CodePen => https://codepen.io/SoyHipst

{% codepen https://codepen.io/SoyHipst/pen/eYMLMWJ %}
About to finish and Launch my first public product.
Tags: programming, tutorial, career, dart
Published: 2022-08-13 23:13:00

Building in Public has been one my Go to Do's now. I just started doing this not long ago on my Youtube channel https://www.youtube.com/channel/UCHhoRieE3bNlEIXoUXhBtmQ, where I am currently building different startup products on live stream to be launched within my current location.

It's fun but it takes a lot to do it. The one I am about to finish and Launch is a Mental Heath care app. Guys do check it out and let me know what you think.

What do you guys think about building in public?
How to change SVG colors.
Tags: css, vscode, python, tutorial
Published: 2022-08-13 23:03:19

## ℹ️ Disclaimer
_This will only worrk for svg icons that are solid colors, if you have 2 layers that or have spaces between the image, like a settings.svg icon that has a gear as an icon that has more than 1 gap between the image.. It wont work._

## Do me a solid; 
**❤️ 🦄, save & comment!  **
Much ❤️❤️❤️❤️❤️

## ℹ️ Back Story
I recently found myself struggling with changing SVG colors when trying to do it within PyQt5 Editor. I struggled for 10mins when I realized that there HAS to be a better way. I asked Google, with the "stackoverflow" attached at the end, and It lead me to a thread that looked like 8Mile from movie.

As per the thread found from 8yrs ago found. I wasn't going to "endulge" myself in reading that massive thread of word-vomit. So to make it super easier for the next programmer/coder looking for faster answers, here it is!

You can change any SVG color. Now how to get it to hover a different color change inside a python application, is beyond me at this conjuction in life, but I am positive I will find what I am looking for when the time comes.

[FeatherIcons](https://feathericons.com/) also has some really nice icons, ready to go! What I used, but also **JUST** found out I could do, is change the color I needed **HERE** before I download the icons, **PLUS** I can also adjust the size & stroke width before downloading lol (HUGE FAIL) 

You live and you learn!

## Other ways
My other way I did it before discoverying what I did in the previous sentence.

- DUPLICATE THE FOLDER OF SVG's YOU WANT TO EDIT (Assuming the color is Black), so another folder you can have can be white or red. I remade a folder for all white logos. 

- Use any code editor, I used VSCode for this. Open the SVG inside your code editor. And it will show something like this.. 


![svg example of a black icon](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8wna18iulx8i50z10lm1.jpg)

## Note
- You will want to make the changes to the attributes, **fill="none"** **stroke="currentColor"**

- Flip the attributes of fill & stroke; You will want it looking like the picture below. after vscode edit


![vscode svg edit, black to white](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u8anr0vn5rx3cdnrhjg7.jpg)

## Example
**Before**
```
fill="none" stroke="currentColor"
```

![example of a black svg icon](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9quwhjtr9g0wskgxb38o.jpg)
before edit

**After**
```
fill="currentColor" stroke="white"
```

![changed svg color, black to white](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gdoi2gbf92982z1ip8mj.jpg)
after edit

I hope this was super helpful to you as it was to me..