teleren/devto huggingface dataset:
I'm headed to the Rockies... Virtually, that is
Tags: bootcamps, teaching, javascript, learning
Published: 2020-04-02 06:17:30

---
title: I'm headed to the Rockies... Virtually, that is
published: true
date: 2019-09-24 07:00:00 UTC
tags: bootcamps, teaching, javascript, learning
canonical_url: https://www.jaysonjphillips.com/blog/2019/09/i-m-headed-to-the-rockies-virtually-that-is/
---

I recent begun teaching my 4th full cohort of Full Stack Web Development, this time at the University of Denver’s Coding Bootcamp.

I was and still am excited to get back into the classroom. Especially now that I’m working full-time on building the best [learning platform](https://2u.com/) [delivered online](https://trilogyed.com/), I get to get back into the practice of really understanding my future learning user base.

I’ll be taking nearly 30 students, once again, on a ride of Javascript, HTML5, CSS, NodeJS, MySQL, MongoDB and more over the next 6 or so months.

As someone who "broke" into engineering with a very non-traditional background, being an instructor gives me a very tangible way to not only help others transition into the practice of being software engineers, but to also mentor them on the sometimes unique challenges that come with getting out there in the market post-graducation.
New CompileSwift Podcast iOS, iPadOS 13.1
Tags: swift, ios, podcast
Published: 2019-09-24 04:14:42

I managed to get this episode out just before the release of iPadOS 13.1.

[Listen on Anchor.fm](https://anchor.fm/compileswift/episodes/iOS-13-and-iPadOS-13-1-Releases--Backing-Up-iPad-Correctly--SwiftUI-Plans-e5hdeh)


**Show Notes**
- iOS 13.0 has now been out a few days and iPadOS 13 and the .1 releases are due out on Tuesday 24th September.
- My recommended way to totally backup the iPad before upgrading
- My plans for learning SwiftUI and a few things more

My CodeNotes for iOS source-code:
https://github.com/GrfxGuru/CodeNotesForiOS
.dev Domains Not Resolving
Tags: webdev, networking, tech, dns
Published: 2019-09-17 23:18:44

---
title: .dev Domains Not Resolving
published: true
description: It took me an entire year to figure out what was wrong.
tags: webdev, networking, tech, dns
canonical_url: https://anti-pattern.com/dev-domains-not-resolving
---

For the last year I’ve been unable to view any `.dev` domains on my computer. The problem was simple, but it took me a _long_ time to figure out what it was.

As soon as Google started selling domains on the `.dev` <abbr title="Top-level domain">TLD</abbr> developers started snapping them up and using them for their websites, blogs, and other projects.

Strangely though, I found I couldn’t see any of them.

Whenever I would click through to a website on a `.dev` domain it wouldn’t resolve and I’d get a blank white screen in my browser.

At first I chalked it up to the website being down or an issue with my <abbr title="Internet service provider">ISP</abbr> and ignored it, but after being unable to follow a dozen links to `.dev` domains over the span of a month, eventually it became clear the issue was something on my end.

I did the usual incantantions I could think of. I tried [`dig`][dig], but nothing seemed to be wrong. I tried [`ping`][ping] and [`traceroute`][traceroute], which both hung, indicating something was wrong, but also returned no information I could use to narrow down the issue.

I searched around online but couldn’t find anyone with a similar problem and gave up. Every time I’d get linked to a `.dev` domain I’d repeat this process, spending a few minutes trying different searches. Finally, nearly a year later I found an unrelated problem that tipped me off as to what mine might be.

The problem was [Pow][pow]. That’s right, the swanky development server from about six years ago.

You might still be using Pow, but more likely you haven’t used it in years and completely forgot about it. I certainly had.

Unfortunately, I didn’t uninstall Pow properly and its resolvers were still hanging around, routing all requests for `.dev` and `.test` into a black hole.

```
❯ ls /etc/resolver/
dev  test
```

🤦🏼‍♂️

```
❯ sudo rm /etc/resolver/dev
❯ sudo rm /etc/resolver/test
```

Delete the resolver files and you should be good to go ✌🏼

[dig]: https://en.wikipedia.org/wiki/Dig_(command)
[ping]: https://en.wikipedia.org/wiki/Ping_(networking_utility)
[traceroute]: https://en.wikipedia.org/wiki/Traceroute
[pow]: http://pow.cx
Inconsistent json unmarshal 
Tags: go, json, unmarshal
Published: 2019-09-24 03:23:14

# Common daily task
Go provides has a json package in the standard library. However a common case we face everyday at work is that our input is not consistent, that means a json entry could have different data types. 

Consider the following input jsons 

```
# good input
{
    "name": "Sam smith",
    "age" : 34
}
# lazy input 
{
    "name": "Sam smith stringer",
    "age" : "41"
}

```

as one can see the "age" field has two different types string and number.
Go provides a trick to handle this case; So the recipe is

- Write your go struct with the right types
- Create an Alias for your struct to avoid recursively unmarshal 
- Unmarshal to your intermediate struct with your embbeded alias
- Select the attributes of your struct and parse them to the intended type 
 

### Full code snippet 
```
package main

import (
	"fmt"
	"encoding/json"
	"strconv"
)

type InputJSON struct {
	Name string `json:"name,omitempty"`
	Age  int    `json:"age,omitempty"`
}

/* Alias to avoid calling implicit UnmarshalJSON of your original 
   struct 
*/
type Alias InputJSON

/* write your Unmarshal function using an intermediate struct to use interface to handle any type */
func (i *InputJSON) UnmarshalJSON(input []byte) error {
	// intermediate step
	middle := struct {
		Alias 
		Age interface{} `json:"age,omitempty"`
	}{}

	if err := json.Unmarshal(input, &middle); err != nil {
		return err
	}

	*i = InputJSON(middle.Alias)

	if middle.Age != nil {
		switch realValue := (middle.Age).(type) {
		case string:
			intValue, err := strconv.Atoi(realValue)
			if err != nil {
				return err
			}
			i.Age = intValue
		case float64:
			// by default uses a float64 for number representation
			i.Age = int(realValue)
		}
	}
	return nil
}

func main() {
	// use cases 
	expectedCase := []byte(`
		{
			"name": "Sam smith",
			"age" : 34
		}
	`)
	
	awfulCase := []byte(`
		{
			"name": "Sam smith stringer",
			"age" : "41"
		}
	`)

	goodInput := InputJSON{}
	
	if err := json.Unmarshal(expectedCase, &goodInput); err != nil {
		fmt.Println(err)
	}
	fmt.Printf("%+v\n", goodInput)
	
	badInput := InputJSON{}
	
	if err := json.Unmarshal(awfulCase, &badInput); err != nil {
		fmt.Println(err)
	}
	fmt.Printf("%+v\n", badInput)
	
}

```

Not the most elegant way to do it, but it works :) 

https://play.golang.org/p/dwAPmGtHzZi
Worst thing I ever named anything
Tags: watercooler, discuss, dotnet
Published: 2019-09-24 03:12:10

I once called a set of UI controls The MegaBlocks.  Still not sure if it was all that bad.  

It was in WebForms in dotnet 1.1 though.  That part was bad. 

Also arbitrarily added “_30” to all my database names for a reason I could never remember nor explain.  They still exist with that name.

How about you?  What’s your worst?
So, new computer up and running finally. BUT
Tags: devops, computerscience, discuss
Published: 2019-09-24 02:52:34

New computer it awesome. Just upgraded the HDD to a PCIe m.2. Crazy fast. BUT I have spent 3 days now transferring projects and code snippets. There much be a better way. Should I start working off a external hard drive or what? Since I still use my laptop a lot I feel cloud storage might work good for me but I want to know what others devs do. How so you work from multiple machines or save your files for a full hard drive swap?
Refactoring Conditionals for More Readable Code
Tags: webdev, ruby, rails, refactoring
Published: 2019-09-24 02:19:49

---
title: Refactoring Conditionals for More Readable Code
published: true
description: 
tags: webdev, Ruby, rubyonrails, refactoring
---

The today I was writing some code and it just felt weird when I started to write this long conditional. I asked a coworker of mine did he have any ideas to what we could do to make this more readable. We did the following

Before

```
  class GetStuff

    def fetch(current_url)
      response = handle_response(query).try(:first)
      return nil if !enabled?(response) && !postable?(response) && current_url == response.global_banner.first.button_url
      
      response
    end

    private

    def enabled?(value)
      return false if value.nil?
      value.enabled
    end

    def postable?(value)
      Time.at(value.post_date) < Time.now && value.enabled
    end
  end

```

After
```

  class GetStuff

    def fetch(current_url)
      @current_url = current_url
      @response = handle_response(query).try(:first)

      return nil unless show?
      
      @response
    end

    private

    def show?
      return false if @response.nil?
      enabled? && postable? && is_current_page?
    end

    def is_current_page?
      false if @current_url == @response.global_banner.first.button_url
    end

    def enabled?
      @response.enabled
    end

    def postable?
      Time.at(@response.post_date) < Time.now && @response.enabled
    end
  end

```
We did a couple of things here we removed some reverse logic here.

```
!enabled?(response) && !postable?(response) && current_url == response.global_banner.first.button_url
```
We don't need the ! anymore. I don't know about you but the less I have to think about if this thing is true reverse it the better.

We also simplified the variables being passed through to methods by making some instance variables.

Before

```
def fetch(current_url)
 response = handle_response(query).try(:first)
 return nil if !enabled?(response) && !postable?(response) && current_url == 
  response.global_banner.first.button_url
      
 response
end

```


After
```
def fetch(current_url)
 @current_url = current_url
 @response = handle_response(query).try(:first)

 return nil unless show?
      
 @response
end

```

We have a gaurd clause that is protecting us against a empty response from a server. We already had this but it wasn't really clear what it was doing and that it was protecting everything.

Before

```
return nil if !enabled?(response) && !postable?(response) && current_url == response.global_banner.first.button_url

def enabled?(value)
  return false if value.nil?
  value.enabled
end

```
After
```
def show?
  return false if @response.nil?
  enabled? && postable? && is_current_page?
end
```

Things are more readable and the methods explain why we have the checks in place and what is this condional doing. I feel like this is self documenting code.
Find in Capybara
Tags: rails
Published: 2019-09-24 02:02:17

---
title: Find in Capybara
tags: rails
published: true
---

## 🔗 Parent Note
{% link https://dev.to/n350071/my-capybara-note-2gp3 %}


## basic
### 👍 find by attributes (find by name)
```ruby
find('input[type="checkbox"]').click
find('a[href="/dashboard"]').click
find('[name="user_form[age]"]')
```

### 👍 find by name
```ruby
find('a', name: 'click here').click
```

### 👍 find by element and class
```ruby
# <div class='my-class'>hello</div>
find('div.my-class').text

# <div id='book-body'>
#    <div class='book-contents vertical'>にほんご</div>
# </div>
find('#book-body > book-contents.vertical').text
```

### 👍 find invisible element
```ruby
find('p.message', visible: false).text
```


## advanced
### 👍 find the parent of the node
```ruby
# just one parent node
find('#target_node').find(:xpath, '..')

# recursively parent
el.find(:xpath, '../../../dt')
el.find(:xpath, 'ancestor::dl')
```

📚 [Recursively go up or down | XPath tutorial](https://docs.scrapy.org/en/xpath-tutorial/topics/xpath-tutorial.html#recursively-go-up-or-down)

### 🤔 find from several same selector
#### 👻Bad code
You'll see Ambiguous match error if you use just a find method.

```html
<div class='base'>
  <span class='greeting'>hello</span>
  <span class='greeting'>goodbye</span>

  <a href="#">link_1</a>
  <a href="#">link_2</a>
</div>
```

```ruby
find('span.greeting')
#=> Capybara::Ambiguous: Ambiguous match, found 2 elements matching visible css ('span.greeting')
```

#### 👍good code
```ruby
first('div.hello')
all('div.hello')
```

- Cons
  - Easy
- Pros
  - they don't wait for the selector is rendered.
  - you have to maintain if selector order is modified in the future.

📚 [Stack Overflow](https://stackoverflow.com/questions/13132506/capybara-ambiguity-resolution)

#### 🦄 good code
```ruby
find('div.base > span:nth-child(1)').text #=> hello
find('div.base > span:nth-child(2)').text #=> goodbye

find('div.base > span:nth-of-type(1)').text #=> hello
find('div.base > span:nth-of-type(2)').text #=> goodbye

find_link('link_1', match: :first).cilck
```

nth-of-type is better.

📚 [nth-child](https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child)
JS Bites: React hook is called in a function which is neither a React function or [sic] a custom React Hook
Tags: react, javascript, tutorial
Published: 2019-09-24 01:41:48

---
title: JS Bites: React hook is called in a function which is neither a React function or [sic] a custom React Hook
published: true
description: What does it mean when you get an error telling you you've used a React hook in a function that isn't a React function when you're pretty sure it is?
tags: React, Javascript, tutorial
cover_image: https://thepracticaldev.s3.amazonaws.com/i/vo959x4xc2cqelt2xudd.png
---

So, you've decided to dive into React Hooks. Things have been going well (hopefully) until you get a mysterious error similar to the one below.

```javascript
import React, { useState } from 'react';

const landingPage = ({ user }) => {
  const [user, setUser] = useState(user);

  return (
    <div>
      <span> Your users is </span> { user.name }
    </div>
  );
}

export default landingPage;
```
`Error: React Hook "useState" is called in a function "landingPage" which is neither a React function or a custom React Hook function.`

Oh no! What happened? Setting aside the awful grammar in that error message, what else went wrong? It certainly looks like a React component. You've imported `React`. You've imported `useState`. You are exporting your function. Everything should be working, but it's not.

Here's the gotcha, when you are using React Hooks, your functional component's name *MUST* start with a capital letter. In this case, the function name is `landingPage`. If you change it to `LandingPage` it will work as expected.

Likewise, if you are going to use a hook inside of a hook custom hook, the name of the custom hook *MUST* start with "use" (lowercase).

If you are wondering why, check out the [React documentation](https://reactjs.org/docs/hooks-rules.html) on the subject.


----------- ------------------------------------------------------------------
     JS Bites

     Have you ever need a quick solution to a problem, but when you search 
     Google you are met with pages of tutorials and detailed instructions that 
     bury the information you need? That's what JS Bites attempts to solve. 
     Each post is a small, bite-sized primer on a very specific JS topic. The 
     aim is to provide enough detail to boost understanding, but not so much that 
     you become overwhelmed or lost.
I’m creating a deep dive into Pure Functional Components, FlatLists, and really cool stuff you can do with hooks! Here's video 1
Tags: reactnative, tutorial, javascript
Published: 2019-09-24 01:32:13

 [https://www.youtube.com/watch?v=vNq1P06KkoU&feature=youtu.be](https://www.youtube.com/watch?v=vNq1P06KkoU&feature=youtu.be) 

```javascript
import React, {useState, useRef, useMemo} from 'react';
import {
  SafeAreaView,
  TouchableOpacity,
  FlatList,
  StyleSheet,
  Text,
} from 'react-native';

const DATA = [
  {
    id: 'bd7acbea-c1b1-46c2-aed5-3ad53abb28ba',
    title: 'First Item',
    selected: false,
  },
  {
    id: '3ac68afc-c605-48d3-a4f8-fbd91aa97f63',
    title: 'Second Item',
    selected: false,
  },
  {
    id: '58694a0f-3da1-471f-bd96-145571e29d72',
    title: 'Third Item',
    selected: false,
  },
];

function Item({item: {id, title, selected}, onSelect}) {
  console.log('L29 "item is rendering" ===', id);

  return (
    <TouchableOpacity
      onPress={() => onSelect(id)}
      style={[
        styles.item,
        {backgroundColor: selected ? '#6e3b6e' : '#f9c2ff'},
      ]}>
      <Text style={styles.title}>{title}</Text>
    </TouchableOpacity>
  );
}

function ItemPureFunctional({item: {id, title, selected}, onSelect}) {
  return useMemo(() => {
    console.log('L44 "item is rendering" ===', id);
    return (
      <TouchableOpacity
        onPress={() => onSelect(id)}
        style={[
          styles.item,
          {backgroundColor: selected ? '#6e3b6e' : '#f9c2ff'},
        ]}>
        <Text style={styles.title}>{title}</Text>
      </TouchableOpacity>
    );
  }, [selected]);
}

class ItemPureComponent extends React.PureComponent {
  render() {
    return (
      <TouchableOpacity
        onPress={() => this.props.onSelect(this.props.id)}
        style={[
          styles.item,
          {backgroundColor: this.props.selected ? '#6e3b6e' : '#f9c2ff'},
        ]}>
        <Text style={styles.title}>{this.props.title}</Text>
      </TouchableOpacity>
    );
  }
}

export default function App() {
  const [data, setData] = useState(DATA);

  const onSelect = useRef(id => {
    setData(oldData => {
      return [
        ...oldData.map(item => {
          if (id === item.id) {
            return {
              ...item,
              selected: !item.selected,
            };
          }
          return item;
        }),
      ];
    });
  });

  return (
    <SafeAreaView style={styles.container}>
      <FlatList
        data={data}
        renderItem={({item}) => (
          <ItemPureFunctional item={item} onSelect={onSelect.current} />
        )}
        keyExtractor={item => item.id}
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: 24,
  },
  item: {
    backgroundColor: '#f9c2ff',
    padding: 20,
    marginVertical: 8,
    marginHorizontal: 16,
  },
  title: {
    fontSize: 32,
  },
});
```
Poll: Do you read the question or answers first on Stackoverflow? 
Tags: stackoverflow, discuss, watercooler
Published: 2019-09-24 00:10:27

---
title: Poll: Do you read the question or answers first on Stackoverflow? 
published: true
description: The question of the ages. Q or A's first? 🤔
tags: stackoverflow, discuss, watercooler
---

Just curious, when you're searching for an answer on Stackoverflow, do you take the time to read the original question at the top of the page thoroughly or go straight to the answers at the bottom? 

I will usually quickly scan over the question just to see if it's vaguely related to what I'm looking for, then look at the answers, and then usually have to go back to the question at the top. 😂
JAMstack Roundup for September 23rd 2019
Tags: jamstack, react, graphql, webdev
Published: 2019-09-24 00:04:47

###Here are 5 great articles and videos we're bringing to you this week!

1. [Auto-publish future posts with JAMstack on Netlify and CircleCI 2.0 scheduled jobs](https://codewithhugo.com/scheduled-posts-circleci/)

    One of the earliest and possibly most painful issues you may come across is “How do I schedule content to publish for later?” 🧐. Enter the JAMstack. 💪

2. [Reconciling GraphQL and Thrift at Airbnb](https://medium.com/airbnb-engineering/reconciling-graphql-and-thrift-at-airbnb-a97e8d290712)

    Airbnb’s frontend engineers wanted rapid iteration ♽ and flexibility from GraphQL, while their backend engineers wanted stability and specificity from Thrift. This is the story of how they got the two groups talking and built something that works for everyone. 🤝

3. [Jekyll Tutorial: Static Site Generator & JAMstack Intro](https://www.youtube.com/watch?v=hhwAVZz3CWo)

    Here's an in-depth introduction to static websites and static site generators with Jekyll. 🧠

4. [Crafting a Webpack-Powered Static Site with Spike](https://snipcart.com/blog/webpack-static-site-tutorial-spike)

    In Snipcart’s research for a new static site generator, they stumbled upon Spike. The fact that Spike is powered by webpack caught their attention. 😯

5. [Why Mobile Performance Is Crucial](https://www.gatsbyjs.org/blog/2018-10-16-why-mobile-performance-is-crucial/)

    Mobile traffic 📲 now makes up over half of all site visits, and more than half of mobile site visits are abandoned if a page takes over 3 seconds to load.
Pushing Left, Like a Boss - Part 8: Testing
Tags: application, tutorial, beginners, security
Published: 2019-09-23 23:21:02

---
title: Pushing Left, Like a Boss - Part 8: Testing
published: true
description: This article explains various types of security testing and when in the system development lifecycle it makes sense to do them.
series: Pushing Left Like a Boss
tags: application, tutorial, beginners, security
---
###This series, and my blog, have moved! [Check it out](https://wehackpurple.com/g8tg)!
---

![Testing can happen as soon as you have something to test.](https://thepracticaldev.s3.amazonaws.com/i/uabwvxzt7yb31wwh52y2.png "Testing can happen as soon as you have something to test.")

It is my belief that testing should be done throughout the development lifecycle, and not only during the testing phase. We want feedback as soon as possible, to ensure we make a high-quality product that customers actually want. Below I will lay out some strategies for security testing.
Provide Developers with security scanning software (such as OWASP Zap), teach them to use it, and ask them to fix everything it finds before sending it to QA.

Add automated security testing into your pipeline, specifically:
* VA scanning of infrastructure (missing patches/bad config - this is for containers or VMs, but you use different tools to scan them)
* 3rdparty components and libraries for known vulnerabilities
* Dynamic Application Security Testing (DAST) - only do a passive scan so that you don't make the pipeline too slow




![Q&A at #DevSecCon Seattle, 2019](https://thepracticaldev.s3.amazonaws.com/i/9polg0dvag5vwzlbgcbz.jpg "Q&A at #DevSecCon Seattle, 2019")

During the testing phase I suggest doing a proper Vulnerability/Security Assessment(VA) or PenTest (if you need management's attention), but early enough that if you find something you can fix it before it's published. 

###[Read the rest on my NEW blog!](https://wehackpurple.com/xuro)!