teleren/devto huggingface dataset:
LeetCode 111. Minimum Depth of Binary Tree
Tags: java, tree
Published: 2019-04-16 01:53:14

---
title: LeetCode 111. Minimum Depth of Binary Tree
published: true
description: Solution + explanation for problem 111
tags: java, tree
series: LeetCode in Java
---

```java
public class Solution {
    public int minDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }

        Queue<TreeNode> q = new LinkedList<>();
        TreeNode rightMost = root;
        q.add(root);
        int depth = 1;
        while (!q.isEmpty()) {
            TreeNode node = q.poll();
            if (node.left == null && node.right == null) {
                break;
            }
            if (node.left != null) {
                q.add(node.left);
            }
            if (node.right != null) {
                q.add(node.right);
            }
            if (node == rightMost) {
                depth++;
                rightMost = (node.right != null) ? node.right : node.left;
            }
        }

        return depth;
    }
}
```

We use BFS to solve this problem. We add nodes at the same level to a queue `q`. We iterate through each of the nodes. When we encounter a leaf node, we stop and return `depth` (the minimum depth). After iterating all the nodes at the same level, we still cannot find a leaf node, we increment `depth` by 1 then repeat the above process for the nodes at the next level. We can use DFS as well. However, BFS  outperforms DFS on highly unbalanced trees since it terminates once it reaches the first leaf node.

_Time Complexity_: `O(n)`

_Extra Space_: `O(1)`
LeetCode 98. Validate Binary Search Tree
Tags: java, tree
Published: 2019-04-16 01:38:54

---
title: LeetCode 98. Validate Binary Search Tree
published: true
description: Solution + explanation for problem 98
tags: java, tree
series: LeetCode in Java
---

# Recursion

```java
public class Solution {
    public boolean isValidBST(TreeNode root) {
        return isValid(root, null, null);
    }

    private boolean isValid(TreeNode p, Integer low, Integer high) {
        if (p == null) {
            return true;
        }

        return (low == null || p.val > low) && (high == null || p.val < high) && isValid(p.left, low, p.val) && isValid(p.right, p.val, high);
    }
}
```

In a BST, a left child node is smaller than its parent and a right child node is always greater than its parent. The solution is based on this property. In the `isValid` function, we recursively check if a node has a value between `low` and `high`. There is an edge case where a node may have a value equal to `Integer.MIN_VALUE` or `Integer.MAX_VALUE`. So we use `null` to represent the infinity.

_Time Complexity_: `O(n)`

_Extra Space_: `O(1)`

# In-Order Traversal

```java
public class Solution {
    private TreeNode prev;

    public boolean isValidBST(TreeNode root) {
        prev = null;
        return isMonotonicIncreasing(root);
    }

    private boolean isMonotonicIncreasing(TreeNode p) {
        if (p == null) {
            return true;
        }

        if (isMonotonicIncreasing(p.left)) {
            if (prev != null && p.val <= prev.val) {
                return false;
            }
            prev = p;
            return isMonotonicIncreasing(p.right);
        }

        return false;
    }
}
```

If the tree is a valid BST, its elements should strictly follow an increasing order within an in-order traversal. We can use this property to solve the problem. To learn more about in-order traversal, please check out this [link](https://en.wikipedia.org/wiki/Tree_traversal#In-order_(LNR)). We define `prev` to keep a track of the previous element in the in-order traversal. Whenever we detect that there exists a TreeNode `p` that is smaller than `prev`, we know the tree is not a valid BST.

_Time Complexity_: `O(n)`

_Extra Space_: `O(1)`
Critique My Resume!
Tags: career, beginners, discuss, help
Published: 2019-04-16 01:14:47

I know there have been some posts in the past where people critique resumes, but I haven't seen one for a while. Are there any long-time devs out there willing to check out my resume and give some tips? Thanks!

[Check it out here as a pdf](https://drive.google.com/file/d/1XQ4yDjyd8qPwI9x0LTEAHWT-3Fd5aGDv/view?usp=sharing)

![Resume](https://thepracticaldev.s3.amazonaws.com/i/wf4zywidpw3e6dbn923p.png)
1 podcast episode delivered weekly right to your inbox!
Tags: showdev
Published: 2019-04-16 00:26:45

---
title: 1 podcast episode delivered weekly right to your inbox!
published: true
description: 
tags: showdev
---

Hi! 

I launched a site called [onePodcast](https://onepodcast.xyz) that will send out 1 thrilling and insightful podcast episode, once per week! It gets a little crazy finding new podcasts sometimes, by signing up to the newsletter you'll get a new episode delivered weekly right to your inbox. 

onePodcast will allow folks to discover podcasts on a weekly basis from small to large creators. We encourage listeners to support podcast creators by leaving reviews for them on iTunes, if they enjoy our newsletter feature and the episodes content. 

Feel free to check onePodcast out and subscribe to be part of the podcast mailing list! 

_p.s. we keep your email private and you're free to unsubscribe at anytime if the newsletter does not bring you value._
How to solve Git issues on renaming files and folder
Tags: showdev, webdev, git, devtips
Published: 2019-06-17 12:55:11

---
title: How to solve Git issues on renaming files and folder
published: true
tags: ['showdev', 'webdev', 'git', 'devtips']
canonical_url: https://learnwithparam.com/blog/solve-git-rename-issues/
---

Many of you might got nightmares due to file rename issues in git. Recently I encountered one issue, everything works locally but repeatedly my circle CI throwing error as file not found while transpilling JSX.

the filename was `NavBar` and I renamed it to `Navbar` everywhere in recent git commits. I didn’t noticed the mismatch in name, it takes a while for me to get to the root of the issue.

This is how I solved it, there might be other better solutions but this worked for me.

```
# Rename the file once again from Navbar to NavBar (basically revert back to original file name)
git mv NavBar.jsx Navbar.jsx
```

This solution can be applied to folder name change as well. For folders,

```
git mv ./NavBar ./Navbar
```

Hope this helps you to learn the trick about git move command 🤗
PHP Dependency Injection The Easy Way
Tags: php, showdev, discuss
Published: 2019-04-15 20:18:38

---
title: PHP Dependency Injection The Easy Way
published: true
description: 
tags: php, showdev, discuss
---

Hey guys,

About 6 or 7 years ago I wrote a little PHP library that ended up becoming the a core part of a framework I built out for a project I was working on. I wanted to have a good dependency injection engine for my project but was not happy with the DI's that were available at the time. So I decided to make a very simple DI engine that is easy to understand.

https://github.com/joshualjohnson/ulfberht

I just wanted to share it because it's been a while since I've shared it. If you're looking for a good DI engine for your next PHP project, this is a good solution.

I was thinking about moving it over to my Org (https://github.com/ua1-labs) and officially supporting it again. This will depend on if anyone else sees a need for it.

Future feature updates:

* Add a put($className, $object) method that will allow you to put and override instances within the DI container.
* Update the project to become part of the Fire family. Rename it to FireDI.
* Add Unit Testing with FireTest.

What features do you need in a DI?
Reduce Redux's action-creator boilerplates without library support in TypeScript
Tags: typescript, redux, javascript
Published: 2019-04-15 23:40:08

---
title: Reduce Redux's action-creator boilerplates without library support in TypeScript
published: true
description: 
tags: TypeScript, Redux, JavaScript
---

```typescript
// Define action-creators
export const fetchPostsRequest = () => ({
  type: "FETCH_POSTS" as const
});
export const fetchPostsSuccess = (posts: any) => ({
  type: "FETCH_POSTS_SUCCESS" as const,
  payload: { posts }
});
export const fetchPostsFailure = (error: Error) => ({
  type: "FETCH_POSTS_FAILURE" as const,
  error
});

// Define Action and ActionTypes
export type FetchPostAction = ReturnType<
  | typeof fetchPostsRequest
  | typeof fetchPostsSuccess
  | typeof fetchPostsFailure
>
export type FetchPostsActionTypes = FetchPostAction["type"];

// Let's use
const action: FetchPostAction = {
  type: "FETCH_POSTS_FAILURE"
}; // -> Property 'error' is missing
```
Mapbox - Interactive Maps in React (Video)
Tags: react, mapbox
Published: 2019-04-15 22:41:59

In this video we'll see how to use Mapbox to display markers for all the skateparks from Ottawa, our great capital of Canada.

Source code can be found here: https://github.com/leighhalliday/mapbox-react-demo

Data can be found here: http://data.ottawa.ca/dataset/skateboard-parks/resource/8c26bbf7-51d9-4b54-997a-c472c5b6d355

{% youtube JJatzkPcmoI %}

Seriously, props to Ottawa for making so much open data available in an easily digestible format.
pretty-quick git trick
Tags: javascript, tools, discuss, opensource
Published: 2019-04-15 22:20:15

---
title: pretty-quick git trick
published: true
description: 
tags: javascript, tools, discuss, opensource
---

A cool thing about using [`pretty-quick`](https://github.com/azz/pretty-quick) in a [`husky`](https://github.com/typicode/husky) pre-commit hook is that it catches unresolved merge conflicts when you run:
```
git cherry-pick --continue
```
How to manage the configuration of a dev env?
Tags: linux, help, python
Published: 2019-04-15 20:53:35

I keep thinking about the best way to manage a robust infrastructure of a custom dev enviorment.

My best idea is to use ansible for every modification that needs to be done and keep everything in git, but I would like something else, don't know what, a more cleaner way.

So how do you manage your dev enviorment, when we are talking about multiple build servers with CI and a lot of testing going on?
The Dark Mode of usability and accessibility
Tags: usability, ux, access, a11y
Published: 2019-04-15 21:32:35

---
title: The Dark Mode of usability and accessibility
published: true
tags: usability,ux,access,accessibility
canonical_url: https://craignicol.wordpress.com/2019/04/15/the-dark-mode-of-usability-and-accessibility/
---

I saw an interesting thread by Laurie Voss where he takes issue with the universal shift to Dark Mode across apps and platforms as an option. I’m sure it’s mainly a weary jest about all the effort to make something not for him. (After all, I’ve heard similar takes from white men about why bother spending time and money catering for women or people of colour).

This tweet stood out though and me think about how I conceptualise usability and accessibility :

> I have extremely poor night vision (halos and starbursts around anything bright) so dark mode makes any interface that is primarily white on black unusable to me. So Dark Mode is "totally useless mode" for me.
> 
> — Laurie Voss (@seldo) [April 15, 2019](https://twitter.com/seldo/status/1117876005039771649?ref_src=twsrc%5Etfw)

<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>

<figcaption>‘Dark Mode is “totally useless mode” for me.’</figcaption>

I like dark mode for many reasons, there’s a small nostalgia element, but I do get big problems with eye strain. I started programming when we didn’t hook computers up to monitors, we used TVs, and sitting arms length from a bright flickering CRT is no good for anyone’s eyes. Modern LCD and OLED screens are much better (and I particularly like how well my Sony phone handles direct sunlight), but even then, I can get sore eyes and headaches looking at something too bright for too long. Dark mode allows me to use a screen longer without losing contrast. Although I am now more wary of wrist strain.

That’s how I often think of interfaces, as something which makes things easier. Something that reduces strain. And I sometimes forget that the point of accessibility cues is to make things possible. It’s not so I can stare at the screen for longer, it’s so that Laurie Voss has a screen where he can see the words.

So yes, I tag my images in Twitter. I use colour schemes with high contrast. I use structured HTML that ties inputs to their labels so that the accessibility tools have the best possible chance of doing their job.

So today, take a step back and think about what would make it impossible for a potential user to access what you’re building. Be that user. What do you need to add for them? If you’re not sure, enable the screen reader on your device and turn the screen over or off. Grab a screenshot and [add a color-blindness filter](https://www.color-blindness.com/coblis-color-blindness-simulator/). [Fill out a form by voice, or use your onscreen keyboard to simulate a switch input.](https://www.boia.org/blog/why-developers-must-consider-alternate-input-devices-for-web-accessibility)

How are you going to walk your software in someone else’s shoes today?
autoapp: A quick dive into containerized CI/CD
Tags: go, docker, devops, productivity
Published: 2019-04-15 19:45:53

---
title: autoapp: A quick dive into containerized CI/CD
published: true
description: A simple intermediate guide into CI/CD with: Github, Drone, Quay, Spinnaker, k8s.
tags: go, docker, devops, productivity
cover_image: https://thepracticaldev.s3.amazonaws.com/i/zatdtqgk48j4g5uy4sw8.jpeg
---


I've been deep diving and vetting a lot of new technologies lately to improve productivity for myself and team(s). Some of the things I've been getting into:
- [k8s](https://kubernetes.io/docs/concepts/)
- [Spinnaker](https://spinnaker.io)
- [Drone](https://drone.io)
- Docker registries:
    - [Quay](https://quay.io)
    - [GCR](https://cloud.google.com/container-registry/)
    - [Private docker-registry](https://docs.docker.com/registry/deploying/)

So I figure I might as well create an experiment project and document the steps along the way for others to learn and partake. Let me preface and forewarn that this is mostly for educational purposes and is not recommended for production usage. Also to note that it does require some comfort at the command line `$`.

Pull-requests are welcomed 😍

{% github derekahn/autoapp %}

Opinions:
- I personally really 💚 [Drone](https://drone.io); It's ease of use, documentation, and containerization is Amazing! Well at least compared to [travis](https://travis-ci.org/), [circle-ci](https://circleci.com/), or [jenkins](https://jenkins.io/). Fun fact... it can pretty much be deployed on anything. Also it looks to be a perfect match for ephemeral pods on k8s.
- I definitely prefer [Quay's](https://quay.io) UI/UX, it's also `"supposedly"` the most battle-tested/preferred at the moment 🤷🏽‍♂️. But it's also the most expensive, so I guess you get what you pay for.
- [Spinnaker](https://spinnaker.io) is a 🐻. But needless to say it's super powerful and flexible. You can unlock that power once you've figured out how to navigate the esoteric documentation. They do have a [slack](https://join.spinnaker.io/) and [forum](https://community.spinnaker.io/), but I still found it a tad bit difficult getting help/advice on configurations, etc. But once it's up and running everything is ✅.
[C++ CODE] Valid Parenthesis
Tags: thetealpickle, algorithms, coding, challenge
Published: 2019-04-15 18:51:58

---
title: [C++ CODE] Valid Parenthesis
published: true
description: Determine whether the input string is valid
tags: #thetealpickle #algorithms #coding #challenge
cover_image: https://thepracticaldev.s3.amazonaws.com/i/wh08dqbyg7oau6qxyobc.png
---

THE TEAL PICKLE CODING CHALLENGE!! Determine whether the input string is valid. I solved this problem with bae (C++). TRY IT 👀

<img src="https://thepracticaldev.s3.amazonaws.com/i/4s6p6mg2jvspg2g6o4yv.png" />


Check out my solution and share yours!! ~ 💻 💻 

<img src="https://thepracticaldev.s3.amazonaws.com/i/1rb4vx73utid3dvt47uk.png" />
Multiple stow directories
Tags: stow, dotfiles
Published: 2019-04-15 18:25:07

---
title: Multiple stow directories
published: true
description: 
tags: stow, dotfiles
---


# Hi again 👋

Today I want to write about the problem that I recently had that I solved after a few
hours of searching google. It may help others so I write a post about it.

## Problem

For managing my [dotfiles](https://github.com/krzysztofzuraw/dotfiles) I'm using
[stow](https://www.gnu.org/software/stow/). It works great for my use case - symlinking
folders from my dotfiles to actual place that they are needed. Yet recently I decided
to split my dotfiles into two: public and private.

The problem was that after a split I cannot easily use `stow fish` from my private dotfiles because
I got an error that this directory is already used by stow.

## Stow folding problem

It turns out that stow is doing something called `folding`. It means that it is
symlinking whole folder instead of individual files. So `stow fish` will create
folder symlink and that is why I cannot symlink other files to the same location.

## Solution

Yet stow has an interesting flag `--no-folding` which called while stowing folder:
`stow fish --no-folding`. Because of this stow won't symlink folders but files
inside folders. Thanks to that I can have two dotfiles with the same fish folder
but with different files.

## Summary & TL;DR

If you want to symlink the same two directories from different stow folders you can
use `--no-folding` flag.
What an Admin can do?
Tags: noob, help, sorry
Published: 2019-04-15 18:24:16

---
title: What an Admin can do?
published: true
description: Can you help to this noob "developer"
tags: noob, help, sorry
---

Hello, first of all, this is my first post, sorry for my bad english.
I'm developing a little App to management a G.Y.M/Sport center, this application has roles, i don't know what an Admin can do, i mean, he can has a list of employees, the admin can add class or create a new schedule, but that's it?
If somebody can tell me what an admin can do, because i dont have any idea.
Thanks.
How do you support detailed validation error messages?
Tags: html, javascript, discuss
Published: 2019-04-15 18:17:04

I was irked by [this Tweet](https://twitter.com/sebmck/status/1116868234324496384) from Sebastian McKenzie:

 > If you’re writing validation code, please never make it output “Incorrect foo” or “Invaid bar”. Pleeeaaase just tell me what I need to fix, and why it’s invalid.

It irked me not because Sebastian is wrong... on the contrary, it hits too close to home. I need to implement more detailed validation messages for some of Crutchfield's inputs, but it's not clear how I should do it.

For example, take this email validation regex:

```regex
^[-a-zA-Z0-9+.*!#$\/=_]+@((([a-zA-Z0-9][-a-zA-Z0-9]{0,61}[a-zA-Z0-9])|([a-zA-Z0-9]))\.)+(([a-zA-Z0-9][-a-zA-Z0-9]{0,61}[a-zA-Z0-9])|([a-zA-Z0-9]))$
```

(I know it's [not great](https://stackoverflow.com/a/1903368/684776) to validate email with regex - but it works for 99.999% of real-world email addresses, and it helps users catch common typos.)

A number of things can cause an address to fail validation, but the regex only communicates two states: _valid_ or _invalid_.

So how do I communicate to the user what invalidated the input? I could imagine designing a series of validations using parts of the above pattern:

```javascript
    [
        {
            "pattern": "^[-a-zA-Z0-9+.*!#$\/=_]",
            "message": "Your email must start with a letter, number, or one of these symbols: - + . * ! # $ \/ = _"
        },
        {
            "pattern": "@",
            "message": "Your email address must contain @"
        }
    ]
```

But there are a couple problems:

 1. There's code duplication, complicating maintenance.
 2. Applying the validation requires JavaScript (the `pattern` attribute won't suffice).
 3. It becomes less clear for developers what is the "true" validation (which should also be used server-side) and what is just used for helpful messaging.

Here is a potential solution:

 1. Call the additional patterns "typo checks" instead of "validation," making clear they're only used to help resolve simple typos, not provide a complete validity check.
 2. Don't treat input as invalid if _only_ the typo check fails. If the main validation pattern matches, treat the input as valid; if it doesn't match, check the other patterns to find a "friendly message."

At least that's my current plan of attack.

Does that make sense? How does your site/app handle this?
Invoke a child function from the parent one to get computed data
Tags: react, hooks, computeddata
Published: 2019-04-15 18:05:22

---
title: Invoke a child function from the parent one to get computed data
published: true
description: How to invoke a child function from the parent one to get computed data?
tags: React, hooks, computed-data
---

Ok, let's say we have the most basic component, a `<div>` element with two inputs:

![enter image description here](https://thepracticaldev.s3.amazonaws.com/i/gh03s4fs6i3i7qmvfag0.png?w=50)

And let's call this component `Card`; There is also a 2nd component called `CardHolder` which consists of a `div` element containing `Card` components(a list of names and scores).

Let's say we want the `CardHolder` component to print at the button the average of all the scores in its list, like in the image below:

![enter image description here](https://thepracticaldev.s3.amazonaws.com/i/5ozbovnceyxrylixhi1c.png?w=50)

How can this be implemented considering the following constraints?:

1) Use of functions(No Classes)
2) Card Element is independent(does not require any external information to work) and reusable(any component can import it and use it without any knowledge of its internals and there is no need to the caller to send props/states to the `Card` child)
3) Keep it simple, ie: do not recommend global state handlers(ie: `Redux`), that'd be like to use a building to kill an ant, let's remember the goal here is to keep a simple component with a very basic functionality.

My background is java, and there the easiest way to achieve this is creating a public function in `card`(ie: `getScore()`) so the parent(no matter who is it) just need to invoke it without knowledge of how does it work on the inside; Is this feasible in any similar way in react or what is the right approach/pattern in here?

Thanks to anyone in advance...
I'm a new dev blogger - I can has your tools?
Tags: discuss, beginners, writing, tips
Published: 2019-04-15 17:19:49

---
title: I'm a new dev blogger - I can has your tools?
published: true
description: Everybody *else* has fancy blog tools for creating images, referencing source code, and generally making it look like they have an editorial team helping them churn out the awesome.
tags: #discuss #beginners #writing #tips
---

As a new dev blogger, my tool box is a little, er, *sparse*.  I've been learning markdown, which is nice for formatting, but then I see other people's beautiful looking posts and I think - I want their tools, their methods, their flare.  As part of my ascent into blogging nirvana, I thought I'd spark a discussion and see what others think.

* **Screenshots** - I've seen images that blur all but the important stuff, others that highlight/number the relevant clicks and inputs, etc.  In my StackOverflow posts, I've used... Paint...  Probably time to upgrade, what would you suggest?
* **Code examples** - There's the gist thing from github which I haven't explored, things like codepen and jsfiddle for web stuff.  Of course I can \`\`\`\<language\> in markdown - what else?  Any pro tips?
* **Productivity boosters** - are you composing your markdown in the dev.to editor or is there a better way? Live previews? Templates?
* **Other 'nice to haves'** - Any other wizzbang I should consider to make my posts POP?