teleren/devto huggingface dataset:
Those sneaky NullPointerExceptions!
Tags: beginners, java, junit, spring
Published: 2019-06-18 07:14:45

There is a form of driving called "defensive driving". Defensive drivers anticipate accidents and bad drivers. This lowers the chances of getting into accidents. It has saved me from several bad accidents.

Similarly, we can avoid the scary ``NullPointerException`` in Java if we know how to anticipate it.


For example, what is wrong with this ``if`` check?

```java
if (aString.equals("yes")) { /* do stuff */ }
```

It's assuming that ``aString`` has been initialized. If a string is not initialized, it will be ``null``! Calling ``.equals()`` on a ``null`` object is not going to end well.  This happens more often than you might expect.  It is better to write this:
```java
if ("yes".equals(aString)) { /* do stuff */ } 
```

I edited a POJO recently that was meant to represent a deserialized JSON object. The business requirements said I needed to remove any leading or trailing whitespace.  Thankfully, the ``String.trim()`` method can do this for me in a single line!  I placed it in the setter like this:
```java
public class Person {
  private String firstName;

  public String getFirstName() { return this.firstName; }

  public void setFirstName(String firstName) { 
    this.firstName = firstName.trim(); 
  }
}
```
Seems innocent enough. 😉

Imagine my frustration when converting a JSON to this object was throwing a ``com.fasterxml.jackson.databind.JsonMappingException`` with a not-so-helpful explanation of "N/A".  What was happening???

Apparently, if ``firstName`` is ``null`` in JSON, ``setFirstName(firstName)`` was calling ``trim()`` on a ``null`` object!

What I need to do is check to make sure that the String parameter in ``setFirstName(firstName)`` is not null. There's more than one way to check, but I chose a ternary operator:
```java
public class Person {
  private String firstName;

  public String getFirstName() { return this.firstName; }

  public void setFirstName(String firstName) { 
    this.firstName = (firstName == null) ? null : firstName.trim(); 
  }
}
```

How about you? Have you run into the dreaded ``NullPointerException`` recently? How did you fix it?
Do you use BeautifulSoup or LXML to parse your HTML markup in Python?
Tags: discuss, python, html, webdev
Published: 2019-06-18 06:19:36

`BeautifulSoup` has been my go to library for html parsing since many years, its useful for DOM parsing in the python world (just as jquery is in JavaScript world) and it supports multiple html parsers such as lxml and html5lib.

But I came across this interesting [StackOverflow answer today](https://stackoverflow.com/a/19548832/849365) which hints that BeautifulSoup may not be the best for performance, and that lxml's own module called `soupparser` is much faster.

What do you use for html parsing, have you ever come across any performance bottleneck with BeautifulSoup? Me, I haven't.
Important Abbreviations
Tags: http, html, xml, etc
Published: 2019-06-18 05:15:09


1. TCP/IP: Transmission Control Protocol/ Internet Protocol
2. MAC: Media Access Control
3. NIC: Network Interface Card
4. MODEM: Modulator Demodulator
5. FSF: Free Software Foundation
6. OSS: Open Source Software
7. FLOSS: Free Libre Open Source Software
8. GNU: GNU’s not UNIX
9. ODF: Open Document Format
10. W3C: World Wide Web Consortium
11. VoIP : Voice Over Internet Protocol.
12. FTP: File Transfer Protocol
13. HTTP: Hyper Text Transfer Protocol
14. SMTP: Simple Mail Transfer Protocol
15. WWW: World Wide Web
16. PAN: Personal Area Network
17. LAN: Local Area Network
18. MAN: Metropolitan Area Network
19. WAN: Wide Area Network
20. HTML: Hyper Text Markup Language
21. XML: eXtensible Markup Language
22. DHTML: Dynamic Hyper Text Markup Language
23. CSS: Cascading Style Sheet
24. JVM: Java Virtual Machine
25. IDE: Integrated Development Environment
26. SQL: Structured Query Language
27. Wi-Fi: Wireless Fidelity
28. RDBMS: Relational Database Management System
29. DDL: Data Definition Language
30. DML: Data Manipulation Language
31. TCL: Transaction Control Language
32. ASCII: American Standard Code for Information Interchange
33. ISCII: Indian Standard Code for Information Interchange
34. ICT: Information and Communication Technology
How to use ES6+ with Node.JS
Tags: javascript, node, ecmascript, es2015
Published: 2019-12-06 00:17:32

---
title: How to use ES6+ with Node.JS
published: true
date: 2019-06-18 05:06:53 UTC
tags: Javascript,Node.js,ecmascript,es2015
canonical_url: 
---

I have seriously come to really like the new features that come with ES6+ Javascript such as `async/await`, the new `class` syntax, `let` and `const` (screw you `hoisting`!), `arrow functions`, `destructuring`, the new `import` syntax, and many more. These features are seriously useful. I think that the `import` syntax in particular makes Node.JS feel so much more like it was made for Javascript.

Ok. Ok. I’ll get on with it—How can _I_ use ES6+ with Node.JS? It’s super simple.

1. `cd` to your project in your Terminal
  ![](https://aidanlovelace.com/wp-content/uploads/2019/06/Screen-Shot-2019-06-17-at-11.58.32-PM-1.png)

2. Run `npm install --save-dev esm`
  ![](https://aidanlovelace.com/wp-content/uploads/2019/06/Screen-Shot-2019-06-18-at-12.02.32-AM-copy.png)

3. Run your main Javascript file with `node -r esm {THE FILE}`
  ![](https://aidanlovelace.com/wp-content/uploads/2019/06/Screen-Shot-2019-06-18-at-12.02.32-AM.png)

If you are using `nodemon`, you can just run `nodemon -r esm {THE FILE}`.
Toronto Meetup June 22nd. Any DEV.to users in the GTA?
Tags: aws, webdev, meetup, ux
Published: 2019-06-18 04:37:27


---
title: Toronto Meetup June 22nd. Any DEV.to users in the GTA?
published: true
description: 
tags: aws, webdev, meetup, ux
---

I wanted to run my own tech meetup and thought of something that was broad in scope to allow for talks on things such as UX, Fullstack, DevOps, Security, BigData and ML. I figured all jobs need to start learning cloud computing to some degree and that's why I created the Solutions Architect Toronto User Group.

If you're not in Toronto, I live-stream the talks via Zoom.
If you are in Toronto that its great opportunity to network.


For more details read the [Meetup Event Page](https://www.meetup.com/Solution-Architect-Toronto-User-Group/events/262097187/)


Go Raptors? We The North.

Fun fact. When I was 7 I owned this exact Raptors Windbreaker:
![](https://thepracticaldev.s3.amazonaws.com/i/ma2bn0lhsvy27r8clxob.jpg)
Leveling Up Your Terminal/Command-Line Navigation
Tags: terminal, bash, productivity
Published: 2019-06-18 03:03:30

One motivating factor in using a terminal is the productivity gains... that is, once you can sweep the keyboard like an 80's metal guitarist. Getting a few basic keyboard shortcuts/commands down can drastically improve the usability of the terminal. Let's take a look at a few of my favorites.

*(I'll be showing off Git Bash in this article, but these commands work in most terminals)*


### Movement

**Move to the end of the input**
`ctrl + e`

![Move to the end of the input](https://thepracticaldev.s3.amazonaws.com/i/eqz7oivtmwvm2lecozxv.gif)

**Move to the beginning of the input**
`ctrl + a`

![Move to the beginning of the input](https://thepracticaldev.s3.amazonaws.com/i/pcviwamsu92rsbvv1rl6.gif)

**Move between each 'word'**
`ctrl + [arrow left/right]`

![Move between each 'word'](https://thepracticaldev.s3.amazonaws.com/i/5piz8q8un1bk2ui1fw3r.gif)


### Deleting

**Delete backwards a whole 'word'**
`ctrl + w`

![Delete backwards a whole 'word'](https://thepracticaldev.s3.amazonaws.com/i/5fhignw1fjziw7x72jjh.gif)


**Delete everything**
`ctrl + u`

![Delete everything](https://thepracticaldev.s3.amazonaws.com/i/ijiermx0qon7zuea799t.gif)


### Open File Explorer

Opening the file explorer at the current location can be super useful. The command varies based on operating system.

(Open file explorer at the current directory. Change '.' to be any location!)

**Windows:** `explorer .` 
**Unix/MacOS:** `open .`

![Open File Explorer](https://thepracticaldev.s3.amazonaws.com/i/0xcgy3c1453zwizjrhaq.gif)


### History

**Rerun the last command**
`!!`

![Rerun the last command](https://thepracticaldev.s3.amazonaws.com/i/sqofemwp8trpnsf4pwss.gif)

**Get the full history of commands**
`history`


**Rerun command from the History**
`![#number]`

![history](https://thepracticaldev.s3.amazonaws.com/i/skse39zh5t8ozz9rkkax.gif)


### End

These are shortcuts/commands I find myself going to daily that make the terminal a pleasure to deal with. Are there any I missed that you love? Let us know in the comments!



*Photo by Josiah Weiss on Unsplash*
Which dotfiles (e.g. .bashrc, .vimrc) do you actually customize/depend on for your daily dev machine setup?
Tags: discuss
Published: 2019-06-18 02:50:33

---
title: Which dotfiles (e.g. .bashrc, .vimrc) do you actually customize/depend on for your daily dev machine setup?
published: true
description: 
tags: discuss
---

As a follow-up to this [discussion](https://dev.to/lostintangent/how-do-you-manage-and-synchronize-your-dotfiles-across-multiple-machines-2n24), I’m curious to learn exactly which [dotfiles](https://wiki.archlinux.org/index.php/Dotfiles) (user-specific application config) folks actually customize, and more importantly, rely on, as part of their daily dev machine setup.

For example, if you bought a new computer tomorrow, what would you immediately notice feels inefficient? Subsequently, what would be the first config files you would create in order to enable your “flow“?

Is it primarily just setting aliases and env vars for your shell (via a .bashrc/.zshrc/etc. file)? Maybe your editor and Git settings (e.g. .vimrc, .gitconfig)? Something else?
Working in Circle City, Day 1: Many Firsts
Tags: firstday, newhire, circlecity
Published: 2019-06-18 01:42:49

---
title: Working in Circle City, Day 1: Many Firsts
published: true
description: This place is so exciting. This series is all about my new adventure.
tags: firstday, newhire, circlecity
cover_image: https://thepracticaldev.s3.amazonaws.com/i/2uuoe4i7ahw0tsfmnvd1.jpeg
series: Working in Circle City
---

My new job is downtown Indianapolis. Today was my first day for a whole list of things!

🚗 Parked in a parking garage all day
🚶🏼‍♀️ Walked 5 minutes to work
🍳 Had breakfast by myself downtown
🛍 Shopped in two stores by myself downtown
🍕 Had lunch at Giordano’s
💻 Thoroughly used a MacBook Pro

I’m sure there’ll be lots of firsts in the coming months. I finally feel like I’m in an environment and community where I can grow. Everyone was so friendly and welcoming. They care about your wellbeing. You’re encouraged to learn and educate yourself all the time.

Supporting your team matters. It makes an entire world of difference.

---

Did you know I have a newsletter? 📬

If you want to get notified when I publish new blog posts or make major project announcements, head over to [https://ashleemboyer.com/newsletter](https://ashleemboyer.com/newsletter).
Web Development Part 2E: Let's Build It!
Published: 2019-06-18 01:29:09

---
title: Web Development Part 2E: Let's Build It!
published: True
description: 
tags:
cover_image: https://gallery.mailchimp.com/fbd7db24d41cbb15fbb6a072f/images/76567adb-d5bf-4b2b-aa20-ddbbcb8ce243.png
---

##Let's Build It!
We're going to put all of our CSS knowledge to the test! Don't forget to use the hashtag #TimTeachesCode on twitter! Remember, you can all contact me whenever you have questions or feedback.

This course is completely free and will be free forever. It takes a bit of time to prepare and support, so if you'd like to contribute, you can do so at https://paypal.me/tevko. Any contribution helps!
This week: Putting it all together
In the last lesson, we learned about pseudo classes / elements and demoed as many as we could.

In this lesson, we're going to put all of our knowledge to the test by building a complete design!

![](https://thepracticaldev.s3.amazonaws.com/i/eujhp60243q9vzl0ud85.jpg)

There is a LOT to be done here, and this will not be easy! Use your best guess as to colors and fonts, and don't worry about making anything functional. Don't forget to be detail oriented! As web developers, a large part of our job is turning designs like this one into a real website. Don't be intimidated, and do reach out with questions!

You can use google fonts and placeholder images for icons and logos.

Homework: 
Reply to the email with a new codepen containing the completed design.

Extra points.
Make the FAQ functional, and include as many CSS transitions as possible!

Read: https://mxb.dev/blog/the-css-mindset/
Go Porject settings in VS Code
Published: 2019-06-18 01:26:31

---
title: Go Porject settings in VS Code
published: true
description: 
tags: 
---


# Go Porject settings in VS Code

For now VS code is a great tool for develop Go project without much efforts to config. For most simple Go project you only need to install the Go plugin to turn your VS Code into Go IDE. I have noted some problems I have encountered when I setup Go in VS Code. 

## For the project using [Go 1.11 Modules](https://github.com/golang/go/wiki/Modules) 
It's a bit tricky to setup. Because we need set environment virable
`GO111MODULE=on` and build flag: `-mod=vendor`
```javascript
// .vscode/launch.json for Go debug
{
    "version": "0.2.0",
    "configurations": [
        
        {
            "name": "Launch Package",
            "type": "go",
            "request": "launch",
            "mode": "debug",
            "program": "${workspaceFolder}",
            "env": {"GO111MODULE": "on"},
            "buildFlags": "-mod=vendor",
            "args": []
        }
    ]
}
```
Then you can run the Go project by clicking the debug button in vscode.
You can also change the `.vscode/settings.json` and add the `go.buildFlags` and `go.toolsEnvVars` . 

For the `go test`, you can set `go.testEnvVars` and `go.testFlags`. But it does not work for the test for the project which forked from the original project. For this situation please check below article.


## Disable 'format on save'

VS Code has enabled go format on save default. For most case, disable the go format on save is not recommended. But if you work on the legacy project or some project not put linter and format into workflow in the beginning. You may want to disable this feature.

It seems vscode-go or vscode have the bug with current version 
*`Version 1.35.1 (1.35.1)` go plugin version: `0.11.0`*
VS code can't disable "formatOnSave". And here is a alternative solution:

Open Shortcuts editor and change `saveWithoutFormatting` to 
`cmd+s` and change `save` to `cmd+k s`:

```json
{
  "key": "cmd+s",
  "command": "workbench.action.files.saveWithoutFormatting"
}
```

```json
{
  "key": "cmd+k s",
  "command": "workbench.action.files.save"
}
```

And we should using below solution to achive this effect. But it's not working for current vscode.

The solution is to add this property to the `.vscode/settings.json`
*May not work for `Version 1.35.1 (1.35.1)` go plugin version: `0.11.0`*
```json
    "[go]": {
        "editor.formatOnSave": false
    }
```
What are Linear and Binary search in Javascript?
Published: 2019-06-18 00:25:31

---
title: What are Linear and Binary search in Javascript?
published: true
description: 
tags: 
---
### How do Linear Search & Binary Search work?
A linear search checks each items in a collection of data one at a time in order to find the searching item. For example, when we search an item in an array, the worse case is that we have to literate through the whole array, which gives us an O(n) performance. An example of linear search would look like this in Javascript:
```
//Linear Search 
let arr = [1,4,3,9,5,2,7,8]

//this function accepts an array and an element to be searched
function linearSearchArray(arr, targetElement){

 for(let eachItemIndex in arr){
   if(arr[eachItemIndex] === targetElement){
     return eachItemIndex;
  }
 }
 return -1;
}

linearSearchArray(arr, 9) //will return 3 because 9 has an index of 3 in the array.
```
###Binary Search
A binary search is a little more complicated and only works on a sorted array. Binary search in a nutshell is that we first look at the middle element in a sorted array, then compare it with the item we are searching for, if the middle element is greater than the searching item, then we know that half of the elements in the array are greater than the item we are searching for, therefore we can drop that half of the array and search only the other half. We continue this operation until we find the element we are looking for. 

In a worse case, as we shrink the array, eventually there will be only one element left to check, if that isn't the matching element then the element we are looking for is not in the array. Because we drop half of the array each time we check, the size of the array is divided by 2 every time we conduct a comparison. Hence the time complexity of a binary search is O(log n). It is much faster than linear search on average. Here is one way to implement a binary search in Javascript:
```
//Binary Search 

let arr = [1,4,3,9,5,2,7,8]

//this function takes an array and an element we want to find arguments

function binarySearchArray(arr, target){

//define the positions we will work with
  let startPosition =0, endPosition = arr.length -1, midPosition = 0;
  
//use a while loop to keep dividing and looking for the target
 while(startPosition <= endPosition){

//define and update the middle position
       midPostion = Math.floor((startPosition + endPosition) /2);
      
//break the loop when target is equal to the middle element
//otherwise we update either the start or the end position so that half //of the array will be dropped.

       if(target == arr[midPostion]){
           console.log("target found at index:", midPostion);
           return true;
         }
        else if(arr[midPostion] < target){

            startPosition = midPostion +1;
            //console.log("target not yet found");
        }
        else{
            endPosition = midPostion -1;
            //console.log("target not yet found");
        }

    }

    return false;

}

//call the function
binarySearchArray(arr, 9)
//this returns target found at index: 3 true
```
A simple way to ensure interface won’t be implemented accidently
Tags: go
Published: 2019-06-18 03:47:38

---
title: A simple way to ensure interface won’t be implemented accidently
published: true
tags: golang
canonical_url: https://dannypsnl.github.io//golang/2019/06/18/simple-way-to-ensure-go-interface-wont-be-implement-accidently.html
---

Sample code is quite easy:

```go
type Car interface {
	impl() Car
	Move()
}

type Animal interface {
	impl() Animal
	Walk()
}
```

Now, let’s create a structure type:

```go
type Duck struct {
	Animal
}
```

Now, if you add `func (d *Duck) Move()`, you won’t be a car accident! What if you want to embed two interfaces?

```go
type Duck struct {
	Car
	Animal
}
```

The compiler would refuse the code since: `Duck.impl is ambiguous`, you can’t have two methods with the same name in Go definition. So we can use this to create something just like `impl Trait for Type` in Rust, although this is a workaround,but anyway I work with Go so I have to find out how to ensure this when we need it.

If you want to know what if we want something just take type has `Move()` method? Then just define:

```go
type Movable interface {
	Move()
}
```

The point is correctly reduce the concept in interface, and do not create interface has general name, unless you know what are you doing,but if you need a workaround, this is.

Since Go can’t write: `func foo(bar A + B + C)`, `A`, `B`, `C` are `interface`, so I suggest write:

```go
func foo(bar interface{
	A
	B
	C
})
```

> NOTE: newline is required, because Go compiler is stupid. You might want define a private interface for this function only.

Sad thing is we can’t use `A | B | C`, have to do runtime assertion for this.

One more bad thing is because you embedded the interface, Go won’t check you provide the implementation of methods or not, you have to do this manually.
Navigating with Ant Design and Reach Router
Tags: antdesign, reachrouter, react
Published: 2019-06-18 22:06:15

---
title: Navigating with Ant Design and Reach Router
published: true
tags: ant-design, reach-router, react
canonical_url: https://wheaton.dev/notes/ant-reach
---

[Ant Design](https://ant.design/docs/react/introduce) is an open-source design system built with React. It provides a collection of well-designed, functional, and accessible components to kickstart your React project.

The `Menu` component is excellent for site-wide navigation, but it wasn't immediately clear how to make this work with [Reach Router](https://reach.tech/router).

After some experimentation, I was able to get these working together:

```
<Location>
  {props => {
    return (
      <Menu selectedKeys={[props.location.pathname]}>
        <Menu.Item key="/courses">
          <Link to="/courses">Courses</Link>
        </Menu.Item>
        <Menu.Item key="/users">
          <Link to="/users">Users</Link>
        </Menu.Item>
        <Menu.Item key="/profile">
          <Link to="/profile">My Profile</Link>
        </Menu.Item>
      </Menu>
    );
  }}
</Location>
```

With Reach Router, any component that's a direct child of the router receives a `location` prop that describes the user's current location within the app.

In my case, the header navigation is a child of a page layout component. Rather than passing `location` through as a prop, I've used the `Location` component. This provides a child render prop that has access to the user's location.

Ant's `Menu` component takes any number of `Menu.Item` children. Each of these has a `key` to uniquely identify it, while the parent menu has `selectedKeys` prop which takes an array of items that should be selected.

By setting the key of each menu item to the corresponding path name, these can easily be matched up by passing the `selectedKeys` prop a single-element array containing `props.location.pathname`.

In short, Reach Router says "we're on /courses" and Ant's menu says "okay, I'll select the menu item with a key of /courses".

This would get more complex for paths with variables (e.g. /courses/abc123/edit) but for basic navigation, this does the trick.