teleren/devto huggingface dataset:
Implement Stack using Queues
Tags: leetcode, dsa, theabbie
Published: 2022-06-16 14:30:37

Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (`push`, `top`, `pop`, and `empty`).

Implement the `MyStack` class:

*   `void push(int x)` Pushes element x to the top of the stack.
*   `int pop()` Removes the element on the top of the stack and returns it.
*   `int top()` Returns the element on the top of the stack.
*   `boolean empty()` Returns `true` if the stack is empty, `false` otherwise.

**Notes:**

*   You must use **only** standard operations of a queue, which means that only `push to back`, `peek/pop from front`, `size` and `is empty` operations are valid.
*   Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue's standard operations.

**Example 1:**

**Input**
\["MyStack", "push", "push", "top", "pop", "empty"\]
\[\[\], \[1\], \[2\], \[\], \[\], \[\]\]
**Output**
\[null, null, null, 2, 2, false\]

**Explanation**
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // return 2
myStack.pop(); // return 2
myStack.empty(); // return False

**Constraints:**

*   `1 <= x <= 9`
*   At most `100` calls will be made to `push`, `pop`, `top`, and `empty`.
*   All the calls to `pop` and `top` are valid.

**Follow-up:** Can you implement the stack using only one queue?

**SOLUTION:**

    class MyStack:
    
        def __init__(self):
            self.stack = []
    
        def push(self, x: int) -> None:
            self.stack.append(x)
    
        def pop(self) -> int:
            if not self.empty():
                return self.stack.pop()
    
        def top(self) -> int:
            if not self.empty():
                return self.stack[-1]
    
        def empty(self) -> bool:
            return len(self.stack) == 0
    
    
    # Your MyStack object will be instantiated and called as such:
    # obj = MyStack()
    # obj.push(x)
    # param_2 = obj.pop()
    # param_3 = obj.top()
    # param_4 = obj.empty()
How not to write clean code in React? 🧹
Published: 2022-06-16 14:15:04

## Introduction
Wassup everyone, long time no see. Today we will see a few ways to not clean code in React, let's jump right into it!

![Jump right into it](https://media1.giphy.com/media/iMBEgyXkFBtdCFS93i/200.gif)

## 10 ways to not write clean code

### Not use a linter
Who needs a linter to keep good code styles, and keep the code clean when you can define the rules as you go.  🚨

### Add everything in one file
Just put everything in one file, so you don't need to create many different files and components and can have 1000s of lines in one file. The compilation build time will also be very small if you use just a single file! 🙈

### Write duplicate code
Why reuse variables, and components when you can copy-paste the same code over and over again and if you need to change one small thing then spend a ton of time adjusting it everywhere. So productivity++ 😌

### Have unused imports/variables everywhere
Why care to delete the unused variables and import them when they can stay where they are and increase your app bundle size. 📈

### Prop drilling
Just keep passing props 10 components deep because who wants to use a tool to manage state properly 🥱.

### Not destructure objects
Who cares about destructuring objects, keep doing `{object.a}`, `{object.b}` everywhere. 🧐

### Not using typescript
Who needs to use typescript when you can pass a number for `name` somewhere and string for the same variable somewhere 🤷‍♂️

### Not using enums
Who doesn't love typos!? Why use enums when you can make a typo and mess up your entire code base and pull your hair for 2 days to find the error after breaking production 🤡

### Use random names for functions, variables, components
Why waste time thinking about a great function/variable/component name, use a random name and save time. 🕰

## Conclusion
I hope you were able to understand how not to write clean code, now it is up to you to choose if you wanna write good code or bad code! That's it for this one ✌️

### Useful links

[How to not become a better developer](https://blog.avneesh.tech/how-to-not-become-a-better-developer)

[Connect with me](https://links.avneesh.tech/)
Sum of Digits in Base K
Tags: leetcode, dsa, theabbie
Published: 2022-06-16 14:00:45

Given an integer `n` (in base `10`) and a base `k`, return _the **sum** of the digits of_ `n` _**after** converting_ `n` _from base_ `10` _to base_ `k`.

After converting, each digit should be interpreted as a base `10` number, and the sum should be returned in base `10`.

**Example 1:**

**Input:** n = 34, k = 6
**Output:** 9
**Explanation:** 34 (base 10) expressed in base 6 is 54. 5 + 4 = 9.

**Example 2:**

**Input:** n = 10, k = 10
**Output:** 1
**Explanation:** n is already in base 10. 1 + 0 = 1.

**Constraints:**

*   `1 <= n <= 100`
*   `2 <= k <= 10`

**SOLUTION:**

    class Solution:
        def sumBase(self, n: int, k: int) -> int:
            total = 0
            while n > 0:
                total += n % k
                n = n // k
            return total
Decentralized economy VS classic banking: what are the advantages of digital assets?
Tags: cryptoprocessing, cryptocurrency, payment, banking
Published: 2022-06-16 13:58:38

In times of global change, companies are faced with changing internal processes: finding more ways to deliver goods and buy materials, new payment options. Each step helps to keep existing customers and often to find new audiences.

The shutdown of financial services corporations has forced freelancers, entrepreneurs, and large business owners to think about using cryptocurrency. Today, we'll find out what the difference is between classic banking services and digital assets.

**1 Anonymity**
When you pay by card or transfer, you can see who is making the transaction. Many would prefer to get rid of it — because of shyness, a desire to keep personal information private, or other reasons.

Despite the fact that banks do not distribute personal data for nothing, it is cryptocurrency transactions that can provide complete anonymity due to the established mechanisms of exchanges and wallets.

**2 Spending on Commissions**
It is impossible to say the exact amount of commissions in cryptocurrency transactions, but they are much less than bank ones. Banks provide about 10-15% (high-risk business gets a higher percentage).

**3 Checks**
Many people do not like frequent inspections by the bank, combined with the possible complete blocking of accounts or denial of service. In these unpleasant situations, you can always get to the bottom of it and probably regain access to assets — but how much time will be lost? How much energy?

In cryptocurrency transactions, the parties to the transaction take full responsibility. There will be no checks, but you always have to be careful and check the data you enter and the wallet addresses.

**4 Transaction speed**
Here cryptocurrencies win with a large margin — transactions are almost instantaneous. Bank transfers often take 3 days or more.

**5 Income reports**
Anonymity extends to income reports to the governing bodies of the state: in the cryptocurrency world, it is not necessary to do them, while in traditional banks it is a necessity.

And, of course, cryptocurrencies solve problems with fraudulent chargebacks.

Periods of crises are scary, but it is thanks to them that you can decide to change. Digital assets will become a part of everyday life very soon, and connecting a system to pay for goods or services with cryptocurrencies today means making a contribution to a good, quality future.
Progressive web apps with Material UI (MUI), Next.js and Workbox
Tags: nextjs, materiaui, mui, pwa
Published: 2022-06-16 13:53:05

Setting up PWA's involves a lot of moving parts, so I've decided to create a template repository, that I would always keep up to date, and it will enable me to get started quickly.

demo: https://material-pwa.vercel.app/

repository: https://github.com/ivandotv/nextjs-material-pwa


## Layout

The application supports both desktop and mobile layouts.

The desktop layout has a sidebar on the left side that can open and close.

![desktop layout](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dnrxov1innw6wbe9ieyx.gif)

The mobile layout has two options.

- Traditional layout with a sidebar that can be swiped to open/close


![mobile sidebar layout](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1laz4l8uev3eswo8z847.gif)

- Modern layout where menu items are at the bottom


![mobile bottom menu layout](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gl7ib0pvlrkmc4wy3g1m.gif)

## Theming

- There are two themes dark and light, and they can easily be customized.

## Onboarding slideshow

I've also included an onboarding slideshow which is usually present in native apps. This is optional and it can easily be removed.

![onboarding slideshow](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tnnsxmxfbc3a0zauv8ch.gif)

## Service worker

The real hard part of creating PWA's is service worker integration, both in the build process and in production.
Service worker functionality is implemented with the excellent [Workbox library](https://developer.chrome.com/docs/workbox/)

### service worker setup

- Service worker is written in Typescript and it will be compiled together with the rest of the code. The service worker will precache all the routes, images, CSS, and google fonts. Every time the app is built new cache manifest is created.

When the service worker is installed, the application will show a prompt to reload the application so the new service worker can take over.

### offline fallback

Offline fallback is provided, if `navigation` happens when there is no network, the fallback page will be shown. Please note that the fallback files must be pure html,css, and js (no react, or css-in-js libraries). Fallback files need to be placed in the `public` directory.

Also, there is `network offline` detection, if the browser loses network connection, there will be a notification inside the app that the application is offline. You can test this via the Chrome dev tools network tab.

### installation prompt

The application also has a custom prompt for the installation of the app. Please note that the installation prompt only works on the desktop OS'es and Android, no IOS.

### app shortcuts

The application also has set some demo shortcuts which show up if the application is installed. 

![PWA shortcuts](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/urn8si7aijaxcfh1y66h.gif)


Make sure to check out the demo:

demo: https://material-pwa.vercel.app/

repository: https://github.com/ivandotv/nextjs-material-pwa
SSH Tutorial [Crash Course]
Tags: ssh, tutorial, git, aws
Published: 2022-06-16 13:41:39

Ever looked for a practical crash course on SSH that is fun and entertaining at the same time? Then have a look at this brand-new episode of [Marco Codes: SSH Tutorial - Nice & Easy](https://youtu.be/UnM4QAumuCQ).

In this video, you'll learn how to use SSH on the command line, which includes: 
* creating keypairs with various algorithms
* using SCP to copy/download files
* using SSH-agents to improve keyfile handling
* using SSH config files to properly manage your SSH target hosts * using SSH keys to checkout repositories from GitHub 
* as well as more advanced topics like SSH agent forwarding, SSH tunneling and using password managers for maximum comfort. 

By the end of the tutorial, there won't be many questions left when it comes to using SSH and friends. Enjoy and let me know what you think!

If you prefer text, have a look at this instead: https://www.marcobehler.com/guides/ssh-cheat-sheet

{% embed https://youtu.be/UnM4QAumuCQ %}
How To Implement Bitbucket Login In Laravel
Tags: webdev, laravel, bitbucket, beginners
Published: 2022-06-16 13:37:04


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

According to a research report, users' session is shorter on every website nowadays. In this case, you can simplify the registration and login process for your application. The socialite package is the best and primarily used package for social login. It is used to reduce the process. In this article, we implement a Bitbucket login to your application.

##Step by step guide on Bitbucket login in the laravel application

- Install Socialite Package
Install Socialite package on laravel application. Run the following command.
```
composer require laravel/socialite
```
You need to add the below line of code inside the app.php file.
```
$providers= [
	
	......
	Laravel\Socialite\SocialiteServiceProvider::class,
	......
]; 

$alias = [

	......
	'Socialite' => Laravel\Socialite\Facades\Socialite::class,
	......
]
```
[Read More](https://www.devrohit.com/bitbucket-login-in-laravel-8/)
Permutation Sequence
Tags: leetcode, dsa, theabbie
Published: 2022-06-16 13:30:39

The set `[1, 2, 3, ..., n]` contains a total of `n!` unique permutations.

By listing and labeling all of the permutations in order, we get the following sequence for `n = 3`:

1.  `"123"`
2.  `"132"`
3.  `"213"`
4.  `"231"`
5.  `"312"`
6.  `"321"`

Given `n` and `k`, return the `kth` permutation sequence.

**Example 1:**

**Input:** n = 3, k = 3
**Output:** "213"

**Example 2:**

**Input:** n = 4, k = 9
**Output:** "2314"

**Example 3:**

**Input:** n = 3, k = 1
**Output:** "123"

**Constraints:**

*   `1 <= n <= 9`
*   `1 <= k <= n!`

**SOLUTION:**

    class Solution:
        def nextPermutation(self, nums: List[int]) -> None:
            n = len(nums)
            i = n - 1
            while i > 0:
                if nums[i - 1] < nums[i]:
                    break
                i -= 1
            if i == 0:
                nums.reverse()
                return
            mdiff = float('inf')
            closest = None
            for j in range(i, n):
                if nums[j] > nums[i - 1] and nums[j] - nums[i - 1] <= mdiff:
                    mdiff = nums[j] - nums[i - 1]
                    closest = j
            if closest:
                nums[i - 1], nums[closest] = nums[closest], nums[i - 1]
            for j in range(i, (i + n) // 2):
                nums[j], nums[n - j + i - 1] = nums[n - j + i - 1], nums[j]
        
        def getPermutation(self, n: int, k: int) -> str:
            nums = list(range(1, n + 1))
            for _ in range(k - 1):
                self.nextPermutation(nums)
            return "".join(map(str, nums))
7 Powerful hacks for skyrocketing your career in 2022.
Tags: webdev, javascript, beginners, career
Published: 2022-06-16 13:25:40

> Spoiler: you don't need to be a high performer when applying these strategies.

## 1. Stop Doing What You’re Told

> "Nobody will believe in you if you don't."

Instead of doubting yourself, think positively. 

Not only will you be happier and more successful, but you will spread it to everyone around you.

"If you don't act, growth will stay away from you."


## 2. Stop filling your mind with garbage

> “Garbage in garbage out,” they say.

The quality of your mind is determined by what you think about. Your thoughts become the color of your soul.

- You must feed your brain a nutritious diet.

- You have control over what influences you.

## 3. Stop trying to do it all alone

> "Doing everything yourself causes burnout."

Join the community.

It makes no difference how you win as long as you do.

By seeking assistance, you can balance your weaknesses with the strengths of others.

## 4. Never fake, always be genuinely You:

> “Fake it until you make it.” === Bullshit advice

Faking makes everyone uncomfortable.

“You should know what you know  & what you need to know.”


## 5. Create a game plan for career growth

> "When you have a plan, your chance of achieving success is 80% higher."

- Start with what you want
- Seek feedback from people about what you're naturally good at
- Time to build SMART goals
- Resources needed to achieve it
- Set timeline


## 6. Say “NO.”

Most powerful two words if you want to see growth.

- "No” is understanding your priorities & living by them.
- Be crystal clear while saying NO

> Saying no is hard for many people.

It’s just two letters, and yet saying no can feel really hard even complicated.


## 7. Stop deciding what will happen:

> Only from within — from our own perceptions — does disturbance arise.

- Forget about fear
- Set a time limit on your research & take action
- Start making little progress every day
- More thinking is not always good thinking
- Trust gut feel.

That concludes this blog.

Today I hope you learned something new. Please like/share if you did so that it reaches others.


[Twitter](https://twitter.com/TheAnkurTyagi) is a great place to follow my journey.

If you enjoyed this, sign up for my [newsletter](https://www.getrevue.co/profile/AnkurTyagi). 

It's completely free.
create go application with Docker
Published: 2022-06-16 13:23:08

**Question**: I have a question related to learning, when we use the Dockerfile for running our go application, and for instance I use the base image like golang:1.15-alpine in practice work and in my machine environment setup I have installed the golang:1.17 version, so my question is when we use the Dockerfile for our go application and use any Golang version base image, so is there any effect on our machine environment setup, or just effect in our go application?
wkhtmltoimage-binary and wkhtmltopdf-binary gems for ARM
Tags: rails, arm, m1
Published: 2022-06-16 13:13:58

## Issue

Error below might occur when you have [wkhtmltoimage-binary](https://github.com/nicholasklick/wkhtmltoimage-binary) or [wkhtmltopdf-binary](https://github.com/zakird/wkhtmltopdf_binary_gem) gems while running ARM when Gemfile

```
qemu-x86_64: Could not open '/lib64/ld-linux-x86-64.so.2': No such file or directory
```

## Workaround

- Install OS dependencies
- Download and install package from https://wkhtmltopdf.org/downloads.html
- Remove above gem(s) from Gemfile

```
# ubuntu:20.04
export PLATFORM=$(dpkg --print-architecture)\
  && apt-get update\
  && apt-get install -y libfontenc1 xfonts-75dpi xfonts-base xfonts-encodings xfonts-utils\
  && wget --quiet https://github.com/wkhtmltopdf/packaging/releases/download/0.12.6-1/wkhtmltox_0.12.6-1.focal_${PLATFORM}.deb\
  && dpkg -i wkhtmltox_0.12.6-1.focal_${PLATFORM}.deb\
  && rm wkhtmltox_0.12.6-1.focal_${PLATFORM}.deb
  && rm -rf /var/lib/apt/lists/*\
  && apt-get purge --auto-remove\
  && apt-get clean
```
Blind 75 - 1. Two Sum Javascript
Tags: algorithms, javascript, beginners, programming
Published: 2022-06-16 13:04:11


   One Of the most popular problem of leetcode is [2 sum](https://leetcode.com/problems/two-sum/). This problem can be solved through many ways like 2 pointers, hashing... out of them if Input array is not sorted then the hashing approach is better in terms of Time Complexity. If input array is sorted then the two pointer approach will be better in that case Space Complexity will be reduced down to O(1). 
The Hashing approach is:

```
var twoSum = function(nums, target) {
    const mp = new Map();
    for (let i = 0;i < nums.length;i++) {
        let rem = target - nums[i];
        if (mp.has(rem)) {
            return [i, mp.get(rem)];
        }
        mp.set(nums[i], i);
    }
    return [-1,-1];
};
```
The time complexity of this approach is O(N), space complexity is O(N)
--------------------------------------------------------

If the input array is sorted then we can farther optimise this solution by using 2 pointers
we can place 2 pointers in the both ends

```
var twoSum = function(nums, target) {
    let i = 0, j = nums.length-1;
    while (i < j) {
        const sum = nums[i]+nums[j];
        if (sum == target) {
            return [i, j];
        } else if (sum < target) {
          i++;  
        } else {
            j--;
        } 
    }
    return [-1, -1];
};
``` 

> NOTE: This solution will not work in leetcode because we have to return the indexes so if we sort the input array then it will messed up the indexes.
[](url)
The Time Complexity of this approach is O(N) and Space Complexity is O(1).
How to avoid making mistakes in your Ansible Playbooks?
Tags: ansible, automation, ansibleplaybooks, ansiblecollections
Published: 2022-06-16 12:57:35

When we write an Ansible playbook or role, we usually do so because we want to automate error-prone manual tasks. But if the Ansible playbook we wrote is unreliable, all we did is replace one source of problems with another. Fortunately, with a little bit of knowledge, discipline, and help from appropriate tools, everyone can write a high quality Ansible playbook that will help you achieve reliable automation, saving you time and worry.  

**Here are the steps for shaping up your playbooks:**
1. Detect errors early and fix them right away. 
2. Enforce the desired state instead of executing actions.  
3. Detect deviations from the desired state (configuration drift).  
4. Test multiple ephemeral hosts with ease.  
5. Follow best practices.  
6. Detect potential issues based on the Collection analysis.  

Learn how to build a robust development workflow to make your playbooks reliable and make you trust in your automation in [this free webinar](https://steampunk.si/webinars-training/avoiding-common-mistakes-ansible-playbooks/?utm_source=dev&utm_medium=social).
What is the best age to start learning programming?
Tags: beginners, career, discuss, codenewbie
Published: 2022-06-16 12:53:47

Many people are complaining about their age, asking themself — if it is too late or too early to start programming? In this article, I will explain a matter of age to the developer. Also, I will provide some learning resources to start learning. As an example, I will take the front-end developer beginner path.

## When to start learning programming?
The earliest time to start, from school. At the beginning of Your journey, it is crucial to keep yourself motivated. For absolute beginners, I would recommend starting with HTML and CSS. One of the most user-friendly platforms for absolute beginners to start is W3Schools. The platform will not explain, what CSS and HTML are and explain the main concepts to learn. After You will feel confident with HTML and CSS start learning JS. All these 3 technologies are must-haves for any front-end developer. If You are planning to find work in the future as a front-end developer this article can help to find your first work/internship. In the article, I provided the importance of soft and technical skills. Moreover, added useful resources for beginners and experienced programmers.

## When it is too late?
There is never too late to start learning programming. I am talking not only about the front-end developer path. There are developers who made their first steps in programming from being at 30+ years old and after there were able to find work. It is important to put time and effort, improve yourself as a developer and person.

## Conclusion
It is never too late. Most depend on You, if there is a family it will be harder to find time to learn. By making step after step, You will reach the goal. For someone, it will take more time, someone less. Most important to put effort and be consistent in Your path.

I am available on social media:

Twitter

LinkedIn

Instagram

If You want to support me:

buymeacoffee.com/oscarWeb