teleren/devto huggingface dataset:
Binary Search 
Tags: algorithms, computerscience
Published: 2020-09-01 15:40:52

Binary Search is an algorithm that finds an item in a list by continuously comparing the middle list item with the item you are looking for. It then splits the list to the left if the middle is greater or to the right if the middle is smaller. 
I have seen a lot of programs that implement this with arrays and numbers which is very useful but I wanted to create a version with an array of objects, which encase strings and numbers, that finds a certain entry based on the number.

##Implementation
So to start making this, get an object, any will do but in case you are having a hard time thinking of one here is an example:
```
let names = [
  {"Adeline Garrett": 11},
  {"Carlene Stevenson": 24},
  {"Glen Moyer": 36},
  {"Tamara Vega": 47},
  {"Cecile Dixon": 54},
  {"Sebastian Burton": 69},
  {"Natasha Sloan": 75},
  {"Roger Crawford": 83},
  {"Damien Hensley": 93},
  {"Josie Frost": 103},
];
```
Now for the binary search, create a function that splits the array in half and gets the value from the midpoint. Since the array is already sorted this is pretty easy. Then implement recursion until the entry is found:
```

let binSearchObj = ( arr, numb) => {
    let midPoint = Math.floor(arr.length / 2); //get mid index
    let mid = Object.values(arr[midPoint])[0]; //get mid value
    if (mid > numb) {
        let newArr = arr.slice(0, midPoint); 
        //slice the array from the beginning to the midPoint 
        return binSearchObj(newArr, numb); 
        //recursively call the function again with the sliced 
        //array
    }
    if (mid < numb) {
        let newArr = arr.slice(midPoint, arr.length); 
        //slice the array from the midpoint to the end
        return binSearchObj(newArr, numb);
        //recursively call the function again with the sliced 
        //array
    return arr[midPoint];
    //if the function gets to this point then the only thing left 
    //is what you are looking for
}

console.log(binSearchObj(names, 103))
```
Try this out with some different arrays. The example above did not implement a check for non-existent search items yet, so I leave that to you to figure out how to do it. This is just a good start for a more robust binary search algorithm
BFE.dev challenge #64 auto-retry Promise on rejection
Tags: javascript, challenge
Published: 2020-09-01 15:33:18

> https://bfe.dev is like a LeetCode for FrontEnd developers. I’m using it to practice my skills.

This article is about the coding problem [BFE.dev#64. auto-retry Promise on rejection](https://bigfrontend.dev/problem/retry-promise-on-rejection)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/mibt97o1c2upy7tdrbub.png)

## Look at the interface

```js
/**
 * @param { () => Promise<any> } fetcher
 * @param { number } maximumRetryCount
 * @returns { Promise<any> }
 */
function fetchWithAutoRetry(fetcher, maximumRetryCount) {
  // your code here
}
```

1. we need to return a Promise, which calls fetcher
2. it resolves when fetcher's Promise resolves
3. goes to 1 when rejection is met

## Start coding

First, the fulfilled case is easy.

```js
function fetchWithAutoRetry(fetcher, maximumRetryCount) {
  return new Promise((resolve, reject) => {
    () => fetcher().then((data) => {
      resolve(data)
    }, (error) => {
      // to do
    })
  })
}
```

The triggering of fetcher is a logic that should be run for multiple times, so we wrap it into a named function.

```js
function fetchWithAutoRetry(fetcher, maximumRetryCount) {
  return new Promise((resolve, reject) => {
    const callFetcher = () => fetcher().then((data) => {
      resolve(data)
    }, (error) => {
      callFetcher() // when rejected, call it again
    })
    
    callFetcher()
  })
}
```

Last, we need to limit the recalling, by comparing with the `maximumRetryCount`. We could just declare a `count` variable outside of `callFetcher()`

```js
function fetchWithAutoRetry(fetcher, maximumRetryCount) {
  return new Promise((resolve, reject) => {
    let retryCount = 0
    const callFetcher = () => fetcher().then((data) => {
      resolve(data)
    }, (error) => {
      if (retryCount < maximumRetryCount) {
        callFetcher()
        retryCount += 1
      } else {
        reject(error)
      }
    })
    
    callFetcher()
  })
}
```

That's it!

## Passed!

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/a7ok3gy2kjwl3zi6d6ka.gif)

This is pretty interesting problem, maybe you can also have a try at https://bfe.dev

Hope it helps, see you next time.
Lint & Validate Github Actions Workflow in VSCode
Tags: webdev, vscode, productivity, github
Published: 2020-09-01 15:32:56

Finding out that your Github Action workflow is invalid only *after* you push to Github is a slow and painful process 😕

Wouldn't it be awesome to get instant linting & validation in VSCode as you're typing your workflow? 🤩

Well, you can! In this (very) short video I show you how.

🔗 Links from video
YAML extension for VSCode - https://marketplace.visualstudio.com/items?itemName=redhat.vscode-yaml
JSON Schema Store - https://www.schemastore.org/json/

👉🏼 Watch more videos like this one on my [YouTube channel 🎥](https://www.youtube.com/maximization)

## Become a skilled Node.js developer

Every other Tuesday I send an email with tips on building solid Node.js applications. If you want to grow as a web developer and move your career forward with me, [drop your email here 💌](https://maximorlov.ck.page/0076aaf499).
Floyd Warshall algorithm
Tags: algorithms, cpp, dynamic, datascience
Published: 2020-09-01 15:31:22

The floyd warshall algorithm is for solving the All Pairs Shortest Path problem. The problem is to find shortest distances between every pair of vertices in a given edge weighted directed Graph. 
Here is the Link to the code : https://codegd96.blogspot.com/2020/08/floyd-warshall-algorithm-and-its.html
3 Reasons why Gmail SMTP is not working with PHPMailer()
Tags: gmail, smtp, phpmailer, email
Published: 2020-09-01 15:03:38

If you are using Gmail as an SMTP Server, most chances are it won't work on the first try. And it would definitely won't work if you have enabled 2-factor authentication. 

So here are the 3 steps you would need to complete before be able to send emails using Gmail SMTP Server. 

### 1. Enable IMAP

This is simple, Just go to Gmail Settings and click the Enable IMAP option.

![Step 1](https://dev-to-uploads.s3.amazonaws.com/i/lf2s1rlf03ulv39dns2j.jpg)


### 2. Allow Less Secure Apps

Now, go to the following link to Allow Less Secure Apps to Access your Gmail Account.  https://myaccount.google.com/lesssecureapps

### 3. Unlock Other Apps
If you are using 2-Step Verification, the above step won't work. Instead you would need to visit the following link and Unlock Other Apps: https://accounts.google.com/DisplayUnlockCaptcha

![Step 2](https://dev-to-uploads.s3.amazonaws.com/i/ot9dw4k5oy2n6i91tugn.jpg)

Hooraay!! SMTP Form should work fine now. 

Still not working? Comment below or ask the [Gmail Community](https://support.google.com/mail/community?hl=en)
TypeDraft: Use Pattern Match DSL
Tags: javascript, typescript, dsl, patternmatch
Published: 2020-09-01 14:54:32



In [typedraft](https://github.com/mistlog/typedraft) `0.2.5`(use [draft-dsl-match](https://github.com/mistlog/draft-dsl-match/tree/develop)  0.2.0), we have full support of pattern match as DSL:

```ts
import { MatchDSL } from "draft-dsl-match";

type Vector1 = { x: number };
type Vector2 = { x: number; y: number };
type Vector3 = {
  x: number;
  y: number;
  z: number;
};
type Vector = Vector1 | Vector2 | Vector3;

const vector: Vector = { x: 1 };
const result = Λ<string>("match")` ${vector as Vector} 
  ${{ x: 1, y: 1, z: 1 }} -> ${"vector3"}
  ${{ x: 2, y: 1 }} -> ${"vector2"}
  ${{ x: 1 }} -> ${"vector1"}
`;

console.log(result); // "vector1"
```

`Λ<string>("match")...` will be translated to `MatchDSL...`, behind the scene, [ts-pattern](https://github.com/gvergnaud/ts-pattern) provides runtime support for pattern match.

Document for typedraft can be found in [typedraft-docs](https://mistlog.github.io/typedraft-docs/docs/), examples of pattern match: [draft-dsl-match](https://github.com/mistlog/draft-dsl-match/tree/develop), and it's well tested: [Test cases as examples](https://github.com/mistlog/draft-dsl-match/blob/develop/src/ts-pattern.test.tsx).

Have a try in [dsl-match-demo](https://github.com/mistlog/dsl-match-demo)! Any feedback is welcome.
Let's add a code Quality Check (tutorial)
Tags: tutorial, github, testing
Published: 2020-09-01 14:42:54

Hey everyone! In this video, I show you how to add a code quality check to your Pull Requests with the help of bit.ly/embold-platform.

When working for a company,  checking the quality of your pull requests can be an automated task. I show you how to automate this in order for you to never submit buggy code to your master branches and colleagues.

Useful links to this video:
- Embold Platform: https://www.bit.ly/embold-platform

Twitter: https://www.twitter.com/ania_kubow
YouTube: https://www.youtube.com/aniakubow
Instagram: https://www.instagram.com/aniakubow

BONUS: For implementing an Embold GitHub Action:
https://www.youtube.com/watch?v=COPS4VMfaUc
If you would like to implement the Embold GitHub Action, please follow my tutorial on it above.

If you enjoyed watching this video, please do Like and Subscribe so I now to continue making more :)

{% youtube 6k_eFhnsUYU %}
Process `string | string[]` item with `flat()` and `map()`
Tags: typescript, todayilearned, javascript
Published: 2020-09-01 14:41:38

In some case, we meet `string|string[]` type (I meet this on next.js)

I found this can process simply with `flat()` and `map()` (Not `flatMap()`)

```ts
function appendC(strOrArr : string | string[]) : string[] {
  return [strOrArr].flat().map( item => item + "c" )
}

appendC("a")  // ["ac"]
appendC(["aa", "bb")  // ["aac", "bbc"]
```

If you need generate array in map, you can use `flatMap`

```ts
function splitItems(strOrArr : string | string[]): string[]{
  return [strOrArr].flat().flatMap( item => item.split(",") )
}

splitItems("a,b")  // ["ac"]
splitItems(["aa,bb", "bb,cc")  // ["aac", "bbc"]
```

In addition, if you need process deep array (like `[1,[1,2,[1,2,3],2],[3,2]]`), you can use `flat(Infinity)`

```ts
[deepArray].flat(Infinity).map(...
```
Replacing an Array item by Index with Refactoring Example
Tags: typescript, javascript
Published: 2020-09-01 14:32:54

<sub>Photo courtesy of [DreamsTime](https://www.dreamstime.com/)</sub>

Original Code

```typescript 
let items = ["one","two","three"];
let newValue = "four";
let found = items.find(item=>item==="two");
let index = items.indexOf(found);
items.splice(index,1,newValue);
```
First Mutable Refactor
```typescript
// mutable example
function replace(items, currentValue, newValue){
  let found = items.find(item=>item===currentValue);
  let index = items.indexOf(found);
  items.splice(index,1,newValue);
}
```
Second Immutable Refactor
```typescript
// immutable example
function replace(items,currentValue, newValue):[]{
  let list = [...items];
  let found = list.find(item=>item===currentValue);
  let index = list.indexOf(found);
  list.splice(index,1,newValue);
  return list;
}
```

What would the last refactor look like? Let us know in comments below.

JWP2020 Replacing Items in an Array
The F*ck - A Great Little Productivity App
Tags: productivity, thisweekilearned
Published: 2020-09-01 14:21:52

Welp, things have been a bit slow on the project. The last few weeks have been a lot of rinse and repeat kind of stuff, but alas, that's how it goes sometimes. All that to say that there wasn't much in the way of _This Week I Learned_.

However, I do want to share what is probably my favorite productivity-related app: [The Fuck](https://github.com/nvbn/thefuck). Now is probably a good time to mention that the 'F Bomb' will be dropped a few more times in this post, but it's all in good fun, so I hope it's not too offensive. Now, what is _The Fuck_, and why do I like it so much? From the docs:

> The Fuck is a magnificent app, inspired by a [@liamosaur](https://twitter.com/liamosaur/) [tweet](https://twitter.com/liamosaur/status/506975850596536320), that corrects errors in previous console commands

So, basically, if you drop a typo in a command, say, like:

`git chekout develop`

You would get a a nice error message from `git`, even suggesting the correction. But instead of having to type it out again, you can simply type:

`fuck`

And you are presented with what _The Fuck_ assumes you meant to type initially:

`git checkout develop [enter/↑/↓/ctrl+c]`

From there you can either hit `enter` to use that suggested command, use the up/down arrows to cycle through the options, or `ctrl c` to abort.

But that is just one of the fairly large list of commands that _The Fuck_ recognizes and can fix, a comprehensive list can be found on the incredibly well documented [README](https://github.com/nvbn/thefuck#the-fuck-----).

Because the README is so detailed, I'm not going to retype all the intricacies here. I will say that the install is very simple:

`brew install thefuck`

And it is highly customizable. There is even an [experimental instant mode](https://github.com/nvbn/thefuck#experimental-instant-mode), if that's your cup of tea.

This little app gets me to chuckle out loud just about every time I use it. It's kind of perfect, since I have been known to swear under my breath when frustrated, now I can take that energy and actually fix the problem! And, if you are someone who isn't a fan of typing out the 'F word' on the regular, you could always utilize this powerful tool from an alias, like, I dunno, `duck`?
The World famous javascript interview question
Tags: javascript, beginners, codenewbie, interview
Published: 2020-09-01 14:19:57

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/r7qr42qqa6n2p1bmyrbe.png)

__Write your answers below.__

> Knowing the output is not that important, understanding why the output is important!


**Thanks for reading 💙**  
Follow **@codedrops.tech** for daily posts.  
[Instagram](https://www.instagram.com/codedrops.tech/) ● [Facebook](https://www.facebook.com/codedrops.tech/)

Micro Learning ● Web Development ● Javascript ● MERN stack  
**[codedrops.tech](https://www.codedrops.tech/)**
Set up a Blog with Notion and Vercel in 10 min
Tags: notion, blog
Published: 2020-09-01 14:04:35

This post will show you how to set up a blog with [Notion](https://www.notion.so/) and [Vercel](https://vercel.com/) in 10 minutes. For doing that, we need to use the following repo, `notion-blog`. Of course, you can do this without paying 😜

{% github ijjk/notion-blog %}


## Step 1 Create accounts
Need to create a notion account and a vercel account. Both of them don't need to pay or register your credit card. This step won't take so much time. Also if you don't have a GitHub account, please create it.
If you don't want to use `GitHub`, you can use `GitLab` or `Bitbucket`

[Notion](https://www.notion.so/)   
[Vercel](https://vercel.com/)  
[GitHub](https://github.com/)

## Step 2 Import a Git Repository
This step sounds a little bit complicated, but actually it's very easy since this step only needs to click a button.


## Step 3 Set up 
You just need to follow the images.

### 3-1 Click `Continue`
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/0rpy6axw6xlivl2j02mo.png)

### 3-2 Select your GitHub account
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/km55qjauyg0wbkmsutkc.png)

### 3-3 Name your repo
In this case, I named `koji-notion-blog`. Of course, you can change the name later.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/nti2v1cfjhrmv00m5six.png)

## Step 4 Set Env variables
We are almost there.
Probably, this step is a little bit tricky, but if you know `Developer Tools`, it shouldn't be difficult.

We need to fill out two things.
The one is `BLOG_INDEX_ID` and the other is notion's `token_v2`
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/liq8z700eehw45ycclym.png)

### HOW TO GET BLOG_INDEX_ID
https://github.com/ijjk/notion-blog#getting-blog-index-and-token

### HOW TO FIND YOUR NOTION V2 TOKEN
https://www.redgregory.com/notion/2020/6/15/9zuzav95gwzwewdu1dspweqbv481s5

Then click `Deploy`. 


Now you can access to vercel's dashboard like below.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/c1t4eg4hpykx4racjv9u.png)


Click `Visit` button to check your blog.
If everything goes well, you will see this.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/9s2aspe0w0hb8sf4m0ha.png)


The setup process is done 😁


You can use notion desktop app or notion website to write an article. Once you edit an item on the table and check `published`, your article will be published in a couple of minutes. 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/v3ibfmxy17wfhovmqi15.png)


## Customize your blog
notion-blog is made by `next.js` that is the react framework for `SSR`(server-side rendering). So if you are familiar with reactjs, customizing your blog isn't very hard.
You can use a custom domain for your blog.

Hopefully, this will be useful to you!

My notion-blog is here
https://koji-notion.vercel.app/

<a href="https://www.buymeacoffee.com/koji"><img src="https://res.cloudinary.com/practicaldev/image/fetch/s--kA3wM6t6--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.buymeacoffee.com/buttons/default-red.png" alt="Buy Me A Coffee" height="41" width="174" loading="lazy"></a>
🤦‍♂️ Weekly fail (36/2020)
Tags: fail, lessonlearned, youtube, recording
Published: 2020-09-01 13:54:18

If there's one thing I've learned in my 13 years of being a software developer, it's that nothing is easy! Even the tasks that seem the most trivial. 

A little over a year ago, I was given the amazing opportunity to become a developer evangelist for one of the leading content management providers out there, [Kentico](https://kentico.com). One of the things I love most about being a developer evangelist, and the primary reason I changed roles, is I get to create content about my passion, software development. 

One of the mediums for my content is video uploaded to my [YouTube channel](https://rebrand.ly/developersgarage). You would think sitting down in front of a camera, recording yourself talking would be a no brainer. Well remember in the beginning I said "nothing is easy"... yeah, that includes sitting down in front of camera and recording yourself talking. 

In my latest [video](https://www.youtube.com/watch?v=4TIDvb-Xo08), I recorded a 20 minute portion without audio 🤦‍♂️. At some point I muted the microphone because it was providing background noise as I was trying to edit a video. To make matters worse, I didn't actually find this out until I started to editing this video. Needless to say I had to go back and re-record that section.

_Lesson learned:_ __No matter how many times you've done it, ALWAYS perform a video and audio test before you begin your production recording! That's right, testing isn't just for software development anymore. 😜__

_Bonus_: __Own your fails and be proud of them! Your failures and how you handle them, say so much more about you, than your successes.__

What's been one of your latest fails?
A guide to through async/await with Babel and Webpack
Tags: javascript, babel, webpack, es6
Published: 2020-09-01 13:43:10

At first, the JavaScript projects with [Webpack](https://webpack.js.org/) ran well. Then I realized that our project should be able to run on an outdated browser, so I chose [Babel](https://babeljs.io/). I subsequently [installed](https://medium.com/@imranhsayed/install-and-set-up-babel-for-your-project-a6ce1fc37633) and ran it.

The projects include [a beautiful restaurant page](https://bertil291utn.github.io/restaurant-page/#) and [a cool design to-do list app](https://rawcdn.githack.com/NewIncome/mv_todo-list/360b90c602894736e0f744429a057caff0ed5042/index.html). Then APIs came into the scenario. Inevitably I had to deal with [promises](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise). I can handle them with `.then` or `async/await` functions.

I decided to go with `async/await`, to write the API function 


```javascript

const getDataByIpCheck = async () => {
    const response = await fetch(
      `http://api.ipstack.com/check?access_key=${process.env.API_KEY_IPSTACK}&format=1`
    );
    return response.json();
  };
  };
``` 

I ran the application `npm run start` and 😮, but what's going on, I got an error

![image](https://flaviocopes.com/parcel-regeneratorruntime-not-defined/Screenshot%202020-04-05%20at%2017.45.59.png)

What are we going to do?. I could've cried over our keyboard but I  chose to find a solution.

This was the solution 💡

***

## What @babel/polyfill is?

>It's just the import of stable core-js features and regenerator-runtime for generators and async functions, so if you load @babel/polyfill - you load the global version of core-js without ES proposals.

 
### Install babel-polyfill
>I'm assuming that you've already installed all webpack dependencies, along with babel config inside webpack [config file](https://webpack.js.org/loaders/babel-loader/)

Through npm add this dependency ` npm install --save @babel/polyfill ` to your project

### Update webpack file

At the beginning in the module.export object, entry key add 
` entry: ["@babel/polyfill", "<your enter js file>"] `

Your file should look like the below

```js
module.exports = {
  mode: 'development',
  entry: ['@babel/polyfill', './src/index.js'],
```
Run again `npm run start`

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1597788201748/3ISCw8FlP.png)

And voilà the project now works.

## Conclusion 
`@babel/polyfill` allows us to emulate a full ES2015+ environment, in this case, to work with **async/await** promise functions. Polyfill adds a global scope to accomplish this 


***

> I'd be grateful if you could leave a comment if you found this post helpful or liked it.

Please follow [@btandayamo](https://twitter.com/btandayamo) on Twitter
Introduction To Discord.py
Tags: python, discord, bot, discordpy
Published: 2020-09-01 13:38:44

{% youtube S3afP8yqjW0 %}

Hello, Guys Today We are gonna see what is discord.py and where is it used and also we are gonna code a simple bot out of Discord.py 



## What is Discord.py
Discord.py is a Python library for making cool and unique Discord Bots Which You Can use on your Discord Channels. We prefer it as a developer because it makes our works a lot easier.

## Where is Discord.py Used
To make it simple it's like Discord.js which is a discord Bot API library for Node.js Likewise you can use it to code a lot of cool Discord Bots.

## A simple Discord.py Bot
Before We Code I Think you guys have install discord.py by running `python3 -m pip install -U discord.py` 

{% gist https://gist.github.com/raghavmri/472912cd47fdafa012dbb0a8010271bb
%}

## Conclusion
Thanks For Reading My post 

Do Support me on Patreon - https://www.patreon.com/gogamic
Need suggestion about React+Material UI component directory structure
Tags: react, help, discuss, watercooler
Published: 2020-09-01 13:31:15

Hello Guys,

I need a quick suggestion regarding the React component directory structure. I am using Material UI in my React app and using CSS in JS feature to style my components (using `makeStyles`). 

At the moment my JS and CSS code resides in a single JS file. Like this

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/166v0d44shisri7gvdnr.png)

As I keep adding more CSS classes my JS code keeps moving down (duh...). And it is pretty annoying to keep scrolling up and down to check things or to add new code. 

The question is, will it be considered good practice to move CSS classes into a separate file like traditional CSS? If there is any other way to do it please let me know.

Thanks!
What are some great and inspiring developers to follow on Twitter and Instagram?
Tags: dev, devs, instagram, twitter
Published: 2020-09-01 13:30:27

---
title: What are some great and inspiring developers to follow on Twitter and Instagram?
published: true
description: I really liked thecodeness' posts on Instagram but she hasn't posted for a few years
tags: #dev #devs #instagram #twitter
//cover_image:
---