teleren/devto huggingface dataset:
YYYY vs yyyy - The day the Java Date Formatter hurt my brain
Tags: java, json, iso, dates
Published: 2020-09-09 16:36:13

---
title: YYYY vs yyyy - The day the Java Date Formatter hurt my brain 
published: true
description: 
tags: Java, JSON, ISO, Dates
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/h5p1zz5rumotbpfnob3j.png
---

# Intro
Dates in programming are hard. The ISO-8601 Date standard made them easier but to be entirely honest I'm not ISO-8601 Certified so I'm not very good at my job. What I do know though is the very important difference between `YYYY` and `yyyy` when formatting dates.

# The Difference between y and Y
According to the DateTimeFormatter Java Docs (which implements the ISO-8601 specification)
 - y (lowercase) is year
 - Y (uppercase) is 'week-based-year'.

This difference will cause your code to work perfectly fine, except for when dealing with dates at the very end of some years. 

Here is an example that I had the absolute PLEASURE of dealing with last year. For the date 31/12/2019 (December 31st 2019), `yyyy` will output 2019 but `YYYY` will output 2020. The reason for this is the week that the 31st of December falls in technically is the first week of 2020. This issue can be a pain to notice and debug.
In my case, 31/12/2019 was being sent from the frontend, being stored correctly in the DB, but was turning into 31/12/2020 when being returned and no one had any idea why. Our default JSON date formatter was the culprit, using `YYYY` where it should have been using `yyyy` (some clumsily copied and pasted quick solution by myself ofcourse).

# Example

## Declare formatters
```java
// y (Lowercase) 
DateTimeFormatter formatteryyyy = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// Y (Uppercase)
DateTimeFormatter formatterYYYY = DateTimeFormatter.ofPattern("YYYY-MM-dd");
```
## When converting from Date to String
```java
// Contains value from Database (December 31st 2019) 
LocalDateTime dateTime;

// String value will be 2019-12-31
String yyyy = dateTime.format(formatteryyyy);

// String value will be 2020-12-31
String YYYY = dateTime.format(formatterYYYY);
```
## When convert from String to Date
```java
// Actual date value will be 2020-12-31
LocalDateTime parsedDateyyyy = LocalDateTime.parse("2020-12-31", formatteryyyy); 

// Actual date value will be 2019-12-31
LocalDateTime parsedDateYYYY= LocalDateTime.parse("2020-12-31", formatterYYYY);  
```

# Conclusion 
In 99% of use cases, the following is true:
 - yyyy good
 - YYYY bad
#CodepenChallenge 100 DIVS: Living Room
Tags: codepen, css, html, showdev
Published: 2020-09-09 16:35:21

<p>Using <code>DIV</code> HTML elements, I created this 3D living room, with functionalities using Vanilla Javascript.</p>

<p>I added touch events, so this image can be controlled using your smart phone.</p>

<p>I still retained the Pug source code, because I had so much edit with the HTML codes until I got exactly 100 <code>DIV</code> elements.</p>

<p>I created a 3D mixin for Pug, and SCSS, for me to draw 3D elements easier.</p>

{% codepen https://codepen.io/takaneichinose/pen/XWdZvPR %}
OptinMonster - Verbessere dein E-Mail-Marketing
Tags: wordpress, email, marketing, newsletter
Published: 2020-09-10 11:54:42

---
title: OptinMonster - Verbessere dein E-Mail-Marketing
published: true
date: 2020-09-09 16:29:37 UTC
tags: Wordpress,email,marketing,newsletter
canonical_url: https://j0e.org/optinmonster/
---

![OptinMonster Review](https://j0e.org/wp-content/uploads/2019/08/optinmonster-review.png)

    Mit OptinMonster hast du alle Tools für E-Mail-Marketing und Lead-Generierung an der Hand. Du möchtest …

[OptinMonster - Verbessere dein E-Mail-Marketing](https://j0e.org/optinmonster/)
How can I test Gatsby components using PageProps with Jest?
Tags: help, gatsby, typescript, jest
Published: 2020-09-09 16:21:00

I'm currently developing a Gatsby application using Typescript. There is one task that I need to use some internal props from Gatsby. These internal props come from `PageProps` interface from Gatsby.

This is my code:
```tsx
// src/pages/post.tsx
import React from "react";
import { graphql, PageProps} from "gatsby";

import { useLocalSearch } from "@hooks";
import { BlogQuery } from "@generated/graphql";

export const query = graphql`
  query BlogQuery {
    latest: allMdx {
      edges {
        node {
          fields {
            slug
          }
          frontmatter {
            title
            tags
            description
            categories
            thumbnail {
              childImageSharp {
                fluid(maxWidth: 1040, quality: 100) {
                  ...GatsbyImageSharpFluid
                }
              }
            }
            date
          }
          timeToRead
          excerpt
        }
      }
    }
  }
`;

const Post: React.FC<PageProps<BlogQuery>> = props => {
  const {
    location,
    navigate,
    data: { latest },
  } = props;
  console.log(props);

  const [localQuery, setQuery, result] = useLocalSearch(location.search);

  const onChangeValue = (e: React.ChangeEvent<HTMLInputElement>): void => {
    navigate(e.target.value ? `/post/?search=${e.target.value}` : ``);
    setQuery(e.target.value);
  };

  return (
    <OtherComponents />
    <StyledSearchContainer>
      <StyledSearchWrapper>
        <StyledSearch
          id="search"
          type="search"
          value={localQuery}
          onChange={onChangeValue}
          placeholder="Search posts"
        />
      </StyledSearchWrapper>
    </StyledSearchContainer>
  );
}
```
The `BlogQuery` is automatically generated by `graphql-codegen`.

My other page tests follow [Gatsby's testing page queries](https://www.gatsbyjs.com/docs/testing-components-with-graphql/#testing-page-queries) and they work perfectly. But they only use one prop each while this page uses more than one prop. So can I test this component? (I tried to log all props and copy them, but it didn't help at all).

Thank you.
GraphQL + TypeScript - What I've Found
Tags: graphql, typescript, javascript
Published: 2020-09-09 16:25:43

I've been working on an application recently where I have decided to use TypeScript with ApolloServer. It's a microservice architecture, so Apollo's Federation works great for me. However, despite being written in TypeScript, Apollo just absolutely struggles to use it. Now, it could be me, I've never used this combination before, but it seems to me that Apollo just doesn't have the developer experience it should, in TypeScript at least. 

I've used Apollo multiple times in my projects, it always has worked fine, until now. Now, I still really like Apollo and will continue to use it. However, let me explain just how frustrating it is to use it with TypeScript.

**beginIncrediblyFrustratingExperience():**

Hey there! I see you are using TypeScript! This is great. Go ahead and set up your project like normal. Whoops, resolvers don't work right. You need `IndexedString` that takes an `IResolver` type that you get from the `graphql-tools` library. 
Also, the `IndexedString` needs a custom definition. 

So now you need a special interface that goes into a type that allows you to pass in the `IResolvers`. Implement all that, excellent it works.

Now you want to actually implement the resolvers? Great! Let's do that like normal except that every single parameter needs a type. Well, that makes sense except, I DON'T KNOW WHAT THAT TYPE IS! Okay, so we will just mark it as `any`. Bad practice but it works so let's move on. I'm on the clock here okay?

Now you want custom directives? Nope you can't have them because they require special types as well apparently. Also they don't just go in your `federatedSchema`, you have to create two schemas and merge them. 

What's that? Your special types can't be found? Wonderful. The day just got better. Oh, and tests? Don't even bother with those. They will ruin your day. Write those in plain JavaScript or you'll have an aneurysm. 

**endStory()**

I guess this is a bit of a rant because I've been working on this for days now and I have almost nothing to show for it. It's incredibly frustrating, but I also wanted to raise a little awareness of this issue.  Now, like I said, I haven't tried this combination before. I've used both TypeScript and Apollo, but never together. I could be missing something somewhere. But from what I see, people have been opening issues and complaining about this in the repository. I'm curious if any of you have managed to find their way through this particular swamp. If you have, please direct me toward some resources I can use. Otherwise, I may just drop TypeScript all together. (I really don't want to if I don't have to). Anyway, thanks for taking the time to read this. I hope your journey is easier than mine.
What's the output?
Tags: javascript, webdev, beginners, quiz
Published: 2020-09-09 16:24:30

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

**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/)**
Coding Grace Sep Newsletter is out plus other news
Tags: codinggrace, newsletter, diversity, irishdev
Published: 2020-09-09 16:22:01

###### (Original post: https://www.codinggrace.com/news/august-newsletter-follow--2020-9-3/)

Nearly forgot to post about Coding Grace's latest newsletter, this is also a follow up on announcements that came after the newsletter. 

#### 👉 Read Coding Grace's September Newsletter: https://mailchi.mp/e909938e9e4e/cg-sep20-newsletter

---

👀 I'm also keeping a live list of virtual tech events (mostly focussed on Irish-hosted ones) on https://www.codinggrace.com/news/virtual-tech-events-live-blog-part-4-september-edition-2020-8-31/

📢 There's a call to action to nominate someone (or yourself) as part of 1 Million Women in STEM campaign, details can be found here at: https://www.1mwis.com/be-featured

🗓 Following are upcoming events (virtual and in-person) that I came across after the September newsletter was published. If I'm missing any other tech events, grants or opportunities, please share in comments below or email contact@codinggrace.com.

## 🥰 GRANTS/SCHOLARSHIP
#### (ODSC) Open Data Science Conference Diversity Scholarship
* Deadline: Fri, September 11, 2020
* Details: https://odsc.com/scholarship/

## 🌟 OPPORTUNITIES
#### Cyber Women Ireland: CYBER INSPIRE MENTOR PROGRAM
* Deadline: Monday 21 September, 9am
* Details: https://www.cyberireland.ie/cyber-women-in-ireland/

####Facebook Return To Work Programme
* Details: https://www.facebook.com/careers/facebook-life/return-to-work

#### 🆕 Diversein Mentorship Program - Applications open
* Deadline: Monday 28th Sept
* Details: https://www.diversein.com/post/application-open-for-diversein-mentorship-program

## EVENTS
### 🌈 DIVERSITY EVENTS
#### Tech For Good Dublin: Webinar Showcasing Memory Haven - * Winners of Technovation 2020
* Thu Sep 10, 18:00 – 19:00
* https://www.eventbrite.ie/e/webinar-showcasing-memory-haven-winners-of-technovation-2020-tickets-119398212267

#### AnitaB.org Dublin Meet and Greet
* Thu Sep 17, 19:00 - 20:00
* https://community.anitab.org/event/dublin-meet-and-greet/

### 🎟 EVENTS
#### Social Entrepreneurs Showcase: Ireland 2020
* Wed Sep 16, 19:30 - 21:00
* https://www.eventbrite.ie/e/social-entrepreneurs-showcase-ireland-2020-tickets-118042766091

### 🏟 CONFERENCES
#### Design Leaders Conference
* Thu Oct 22
* (Online) https://www.designleadersconference.com/
Welcome Thread - v90
Tags: welcome
Published: 2020-09-09 16:15:45

---
title: Welcome Thread - v90
published: true
description: Welcome to DEV! A thread of hellos and intros.
tags: welcome
---

![hi goat](https://media.giphy.com/media/3PAL5bChWnak0WJ32x/giphy.gif)

### Welcome to DEV!

1. Leave a comment below to introduce yourself! You can talk about what brought you here, what you're learning, or just a fun fact about yourself.

2. Reply to someone's comment, either with a question or just a hello. 👋 

**Great to have you in the community!**
Make Minecraft in React in 20 minutes
Tags: react
Published: 2020-09-09 16:15:40

---
title: Make Minecraft in React in 20 minutes
published: true
description: In this video we learn how to work with redux-thunk a library for redux to perform side effects. We'll save the data to server using a thunk.
tags: react
series: React
---

{% youtube Lc2JvBXMesY %}

I've created minecraft-like game using react, react-three-fiber, threejs and cannonjs (use-cannon)

In this video I show how to do it step by step.

Code: https://github.com/satansdeer/minecraft-react
Discord: https://discord.gg/KPh8Vvb

Subscribe to the channel: http://bit.ly/2QZ2UY3
Classes are just a fancy way of writing higher order functions
Tags: beginners
Published: 2020-09-09 16:15:08

Joe and I recently [kicked of a re-read of SICP](https://twitter.com/stopachka/status/1295411936625074178). I can say that it is *the* most interesting textbook I have gone through. Imagine, you begin with just 4 or 5 constructs, and you end up building algebraic equation solvers, circuit simulators, and even logic programming languages. Because you start off with such few constructs, the added benefit is that you begin to see the fundamentally simple, shared essence in programming. 

I wanted to give you one example that surprised me in the book. We tend to think that **classes belong in a** **fundamentally different category** **from functions.** 

But are they so different? 

For example, let’s say we have a class like this:

```javascript
class Person { 
  constructor(firstName, lastName) {
    this.fName = firstName; 
    this.lName = lastName;
  }
  getFullName() { 
    return this.fName + ' ' + this.lName;
  }
  setFirstName(firstName) {
    this.fName = firstName;
  }
}
``` 

Well, if we think about it, this is really just a higher order function. a `Person` higher order function accepts arguments (constructor), and returns a list of functions that can manipulate those arguments (methods). We could write `Person` like this: 

```javascript
 function Person(firstName, lastName) {
  let fName = firstName; 
  let lName = lastName;

  function getFullName() { 
    return fName + ' ' + lName;
  }
  
  function setFirstName(firstName) { 
    fName = firstName
  }

  return function(method) { 
    switch (method) { 
      case 'getFullName': 
        return getFullName;
      case 'setFirstName': 
        return setFirstName;  
    }
  }
}
``` 

Now, 

```javascript
const person = new Person("Ben", "Bitdiddle")
person.getFullName()
``` 

becomes

```javascript
const person = Person("Ben", "Bitdiddle")
person('getFullName')()
```

Here, instead of invoking a method, we are “passing” a message. This is why by the way, many classic OO folks talk about object orientation really being about message passing.  

Yup, really. Classes are just higher order functions, which accept arguments (constructor) and return a list of functions that can manipulate those arguments (methods). 

When you previously thought two concepts were different, but they turn out to be the same, you’re ripe to discover new ideas: you can find the deeper abstractions between them, apply ideas from across those seemingly different categories, and move between concepts more fluidly. So, not only are epiphanies like this fun, but they’re much more useful than you’d think. 

If you liked this, there are a *ton* of similar epiphanies in the textbook. To experience it best, I suggest picking a partner and working through the book together.

*Thanks to Daniel Woelfel, Alex Reichert, Jacky Wang for reviewing drafts of this essay*
Interesting Java Puzzle - Instance Initializers
Tags: java, ocaja, first, technical
Published: 2020-09-09 16:02:27

# Instance Initializer Test in Java

## Problem

Can you guess what would be the output of the below Java code? 

## Code 
```
public class InstanceInitializerTest 
{

    public static void main(String[] args) 
    {
        {
            System.out.println("Feathers");
        }
    }

    {
        System.out.println("Snowy");
    }
}
```

## Options 

The list of possible outputs are : 

```
1. Snowy
2. Snowy
   Feathers
3. Feathers
4. Feathers
   Snowy
```

## Solution

The right answer is ```(3) Feathers```

### Explanation

The instance initializers are the code blocks defined between a pair of curly braces - `{` and `}`. They dont really matter even if they are present inside a method, and they are actually counted. 

In the above program, when we run the program, the `main()` method gets executed and inside which we have an instance initializer, and it gets executed. As that was the only one executable statement inside the `main()` method, the program execution finished there. 

You may wonder why the other instance initializer - which prints `Snowy` was not executed. As you see, the 2nd instance initializer was not bound to a method, instead it was bound to the class. As we have not initiated the class, the instance initializer at the class level was not invoked. 

## Work for Brain

Try instantiating the class (inside the `main()` method - of course) and see the change in the output.

You would get the output as either `(2) Snowy , Feathers` OR the `(4) Feathers, Snowy` depending upon where you instantiate the class - before or after the instance initializer inside the `main()` method. 

> Remember, the order of the initializers matter a lot :)
Easy EC2 Tagging
Tags: aws, bash, linux, beginners
Published: 2020-09-09 15:45:30

## Problem 
I recently had the problem of inheriting an AWS account with over 1000+ EC2 resources that had an incorrect tagging strategy.
## Resolve
After the manual effort of manually sorting through all the resources, and breaking them up into the correct groups. Instead of hours going through the console and tagging each resources with 4 tags I created the below script that will prompt for the required information and then tag them correctly.

I took roughly 15 minuets to run this script a few times and tag all of my resources. 

I have a multi profile aws cli configuration, this will ask what profile to use and tag the resources there, if they don't exists it will error.

Update the profile line to match the profiles in your configuration file `~/.aws/config` if you don't remove the below lines;
```
### If you don't use AWS Profiles in the CLI this can be removed
echo "Please choose AWS Account Profile"
select profile in profile1 profile2 profile3 profile4 
do
```
```
break
done
```
You can change the tag keys and expand on them if you need to add more.

You can input as many resource ID's on the single line as you like, use a space to separate them.

```bash
#!/bin/bash

echo "Use this script to tag EC2 Resources in the desired account"
echo "Multiple can be enter at once separated by a singe space."
echo "Below resources are supported using the ID"
echo "            Instance ID"
echo "            Snapshot ID"
echo "            Volumes ID" 
echo "            Security Group ID"
echo "            Elastic IPs Allocation ID"
echo " "
echo "----------------------------------------------------------- "

### If you don't use AWS Profiles in the CLI this can be removed
echo "Please choose AWS Account Profile"
select profile in profile1 profile2 profile3 profile4 
do

echo "Please list EC2 resources (Multiple can be entered at once)"
read resources
echo "Please Enter Cost Centre"
read cost
echo "Please Enter application"
read app
echo "Please Enter environment"
read environment
echo "Please Enter owner"
read owner

aws --profile=$profile ec2 create-tags --resources $resources  \
    --tags Key="Cost Centre",Value="$cost" \
      Key="application",Value="$app" \
      Key="environment",Value="$environment" \
      Key="owner",Value="$owner" 

echo "If no error's above tagging complete"
break
done
```

On to `s3` tagging now.
Auto sign-in user using saved browser credentials
Tags: webdev, javascript, typescript, webapis
Published: 2020-09-09 15:31:31

In this post, I'll show you how you can manually prompt a user to save his credentials in the browser when a user registers, and later use it to automatically sign-in the user.

*warning: At the time of writing this post, all the browser does not support the `PasswordCredential` Web API, you can check the supported browsers and browser versions [here](https://caniuse.com/).*

## Manually storing credentials in the browser.

```ts
const PC = globalThis.PasswordCredential
export const storeCred = async (creds: {
  id: string
  password: string
}): Promise<Credential | null> => {
  // check if PasswordCredential is supported by this browser.
  if (PC) {
    const cred = new PC(creds)
    return navigator.credentials.store(cred)
  } else {
    return null
  }
}
```
You should call this function after the user `registers`, `change password`, and `reset password` to save/update the credentials in the browser. The `id` field represents the unique id that the user uses to sign-in, depending upon your application and your sign-in/sign-up process, it could be an **email, phone number, or username**.

## Auto Sign-in when a user visits your site.
To auto sign-in a user, first, we have to retrieve the stored credentials from the browser, then use the credentials to call the sign-in API on the server to sign-in the user. 

```ts
...
export const fetchCred = async (): Promise<Credential | null> => {
  // check if PasswordCredential is supported by this browser.
  if (PC) {
    return navigator.credentials.get({
      password: true,
    } as any)
  } else {
    return null
  }
}
```
# Usage
```ts
...
const cred = await fetchCred()
console.log(cred) 
// { id: 'savedUserId', password: '**********'}
// call the sign-in api, with cred.
...
```

# Prevent auto sign-in after sign-out
Once the user sign-out's itself, you don't want to auto sign-in him again, causing a lock where the user is unable to sign-out himself. This step is very important, as it allows the user to safely sign-out, sign-in with a different account, and register a new account.

```ts
export const preventSilentAccess = async (): Promise<void | null> => {
  // check if PasswordCredential is supported by this browser.
  if (PC) {
    return navigator.credentials.preventSilentAccess()
  } else {
    return null
  }
}
```
After calling the function on sign-out, when the user tries to sign-in, the browser will prompt the user to allow access to the credential, instead of silently providing credentials to the website.

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

And that's it. :)

Comment down your questions, and if you would like to see a reference implementation in React.