teleren/devto huggingface dataset:
How to Handle touchstart Events with Stacked Elements
Tags: beginners, webdev, mobile
Published: 2019-05-31 03:03:15

---
title: How to Handle touchstart Events with Stacked Elements
published: true
description: The touchstart event in mobile web apps is a little different than the click event. Here's how I solved an issue I've run into frequently.
tags: beginner, webdev, mobile
---

I came across some issues on touch screens where I have a navigation menu expanded and the common "shadow" showing on the non-menu portion of the screen. When I tried tapping on the "shadow" to close the menu, way too many things were happening! Here's a quick illustration of what sort of screen I'm talking about:

![Mobile screenshot of a menu and its shadow](https://thepracticaldev.s3.amazonaws.com/i/ql9hc8t6rgeghdx1ikgw.png)

When a user taps on the "shadow" portion of the screen, they expect the menu to close. Nothing else should happen. You can handle this by adding a `touchstart` event listener to the element used for the shadow, but there are a couple of things to watch out for. It won't behave the same as a `click` event listener you use for the desktop version of your app.

It's all about when events are fired. A `click` event doesn't go until after a click is over and a mouse button is released. So, when a user clicks on the "shadow" with their mouse, there aren't any side effects. It's a different story for touchscreens, however.

If the items "behind" the "shadow" are clickable, a user touching the "shadow" to close the menu will also cause fire off the click events on those items. It's a pretty simple fix. In your `touchstart` listener, all you have to do is call `preventDefault` on the event passed into the listener. It might go something like this:

![Screenshot of touchstart event listener code showing call to preventDefault and some example lines of code for hiding the shadow and menu](https://thepracticaldev.s3.amazonaws.com/i/llil1vy7msaoswf3dbtf.png)

It's really that easy&mdash;a one-line fix. It wasn't super obvious to me at first, so I hope this helps clear things up for anyone else in the same boat as me. Have you ever run into similar issues? If so, enlighten us in the comments and save us some pain! :)

---

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).
AWS CloudWatch Log Group Retention
Tags: aws, python, devops
Published: 2019-05-31 02:54:39

Amazon CloudWatch Logs is used as centralized place to monitor, store, and access all our log files from different AWS services 

CloudWatch organises logs in a log group and when a new log group is created, it’s retention period is set to Never expire by default, which means logs will be retained forever.


Here is a sample python script that helps with changing the retention days to 60.

```
import boto3
# set the number of retention days 
retention_days = 60
# list the regions you are interested to run this script on
regions=['us-east-1']

for region in regions:
    client = boto3.client('logs',region)
    response = client.describe_log_groups(
    )
    nextToken=response.get('nextToken',None)
    retention = response['logGroups']
    while (nextToken is not None):
        response = client.describe_log_groups(
            nextToken=nextToken
        )
        nextToken = response.get('nextToken', None)
        retention = retention + response['logGroups']
    for group in retention:
        if 'retentionInDays' in group.keys():
            print(group['logGroupName'], group['retentionInDays'],region)
        else:
            print("Retention Not found for ",group['logGroupName'],region)
            setretention = client.put_retention_policy(
                logGroupName=group['logGroupName'],
                retentionInDays=retention_days
                )
            print(setretention)
```

Once this script is run problem is solved for existing log groups but it would be nice to automate it using cloud watch events to run a python code using lambda in that way all the log groups created going forward will have retention value set.
Do You Cuss In Your Commit Messages?
Tags: discuss, showdev, github
Published: 2019-05-31 02:32:17

# Do You Cuss In Your Commit Messages?
### 🔲 Never
### 🔲 Sometimes
### ✅ All The Fucking Time

## Let 'Er Rip

Most of my commit messages don't see the light of day, so I'm like a sailor in those fuckers.

```
git commit -m "What The Fuck!?! Why wont this god damn piece of shit fucking work"

...

git commit -m "Holy fucking shit it actually fucking works"
```

## Gotta Keep It Professional
I get that in your enterprise and business level Repos you probably need to keep it professional. 

* Does your company have rules about this? or is it more of a general guideline? 
* Anybody have stories of companies with a culture that emphasizes cussing?
* Any issues arise from leaving an F-Bomb somewhere you shouldn't?

# [Git Shit](https://twitter.com/git_shit) - Shit Developers Say

I'd like to introduce you to [Git Shit](https://twitter.com/git_shit)! It's a Twitter Bot that pulls Angry Commit Message from GittHub. It's a pretty simple Node Script using Octokit and the Twitter API. It strips out Emails, Repos, & URLs in order to keep everything anonymous. It only runs a few times a day, so it won't clog up your feed.

### [Give It A Follow!](https://twitter.com/git_shit)
_^^or ^^don't. ^^I ^^don't ^^give ^^a ^^shit._
Underrated Articles on Dev.to Last Week
Tags: top7, webdev, meta, bestofdev
Published: 2019-05-31 00:59:27

---
title: Underrated Articles on Dev.to Last Week
published: true
description: 
tags: icymi, webdev, meta, bestofdev
cover_image: https://thepracticaldev.s3.amazonaws.com/i/t4xvuqdidhv2m7nm4aqf.png
series: Underrated Articles
---
Hey folks! I'm back with another installment of underrated posts of last week! Let's check them out and see what the community has been up to.
 
## 1. Set up MongoDB

In this article, Akhila writes a brief description to show how to set up a MongoDB database for Node application.
{% link https://dev.to/akhilaariyachandra/setup-mongodb-in-node-js-with-mongoose-4gik %}

## 2. Perspective on Criticism

Criticism is hard to deal with. This post brings the ideal perspective on criticism that we all should know to make leaps forward in your career.
{% link https://dev.to/skill_pathway/is-your-perspective-on-criticism-damaging-your-career-progression-nkm %}

## 3. Learning Machine Learning

In this article, Muhammad gives you a better understanding of what Machine Learning really is. He also shared helpful resources to learn machine learning.  
{% link https://dev.to/tabz_98/machine-learning-from-zero-to-slightly-less-confused-2bal %}

## 4. Manageable To-DO List

In this article, Matylda shares tips to manage the to-do list. She tells about the strategies and frameworks that you should use while tackling your Wip (work in progress). 
{% link https://dev.to/matylda_wro/how-to-make-your-to-do-list-more-manageable-4ked %}

## 5. Developer-client Communication Mistakes

Client-Developer relationship might be degraded over time because of small mistakes. In this article, Phillip writes about these subtle mistakes that we made even in day-to-day communication. 
{% link https://dev.to/phillipmalboeuf/subtle-developer-client-communication-mistakes-1hca %}
---
*That's all for now. These were my personal favorite underrated posts from last week. I hope you liked this post. Tell me in the comments about your favorite posts of last week that you think went underrated!* ❤️
What are some good tutorials/tips for building your own computer
Tags: discuss, linux, help
Published: 2019-05-31 00:56:48

---
title: What are some good tutorials/tips for building your own computer
published: true
tags: discuss, linux, help
---

I'm a complete newb when it comes to linux, operating systems and all the rest. Basically I'm dumb as to how computers actually work. 

I thought it'd be fun to build my own computer from the ground up. But I have no idea where to start! I thought some of you in the community would have some good tips and tutorials to share. Look forward to hearing from you in the comments 🙂
The Squavenger Hunt
Tags: bash, terminal, api
Published: 2019-05-31 00:21:36

---
title: The Squavenger Hunt
published: true
description: help find out dev please
tags: bash,terminal,api
cover_image: https://thepracticaldev.s3.amazonaws.com/i/9l8fwi0j36ikgzq7ckyl.png
canonical_url: https://twitter.com/SquareDev/status/1134083181324296194
---

https://twitter.com/SquareDev/status/1134083181324296194
The best way to make a web API
Tags: discuss, webdev, api
Published: 2019-05-31 00:03:07

What’s your favorite way to make a web API? Give us an outline:
- Programming Language
- Framework
- Scheme/spec/standard
- Documentation
- Authentication
- Authorization
- Client libraries?

Here’s my example:
- Python
- Flask
- OpenAPI REST (I use Flask-RESTPlus)
- Swagger UI
- JWT (Bearer token) with Flask-Login
- Resource-based policies with Flask-Pundit
- Swagger codegen

There are a lot of decisions to make when creating an API, and a lot of problems that don’t seem to have a standard solution. So what’s yours?
A Bot Protection Overview
Tags: engineering, captcha, spam, secure
Published: 2020-09-21 07:17:40

---
title: A Bot Protection Overview
published: true
date: 2019-05-31 00:00:00 UTC
tags: Engineering,Captcha,Spam,Secure
canonical_url: https://www.loginradius.com/engineering/blog/a-bot-protection-overview/
---

Bots are tools that are created to automate tedious processes and reduce work. For example, chatbots automate replies to users for customer support, and search bots are used to populate search results on a Google search. However, there are many bots that are crafted for the…

   
[Read On](https://www.loginradius.com/engineering/blog/a-bot-protection-overview/)
OAuth 1.0 VS OAuth 2.0
Tags: oauth, engineering
Published: 2020-09-21 07:17:59

---
title: OAuth 1.0 VS OAuth 2.0
published: true
date: 2019-05-31 00:00:00 UTC
tags: OAuth, Engineering
canonical_url: https://www.loginradius.com/engineering/blog/what-is-the-difference-between-oauth1-and-oauth2/
---

Learn about the differences between OAuth 1.0 and OAuth 2.0 and how OAuth 2.0 is superior to OAuth 1.0

   
[Read On](https://www.loginradius.com/engineering/blog/what-is-the-difference-between-oauth1-and-oauth2/)
Working With Decorators In Python
Tags: python, decorators
Published: 2019-05-30 23:58:33

---
title: Working With Decorators In Python
published: true
description: 
tags: python, decorators
---


In my last [post](https://dev.to/abe21412/understanding-functional-closures-4la8), I wrote about functional closures in Python and I mentioned that the most interesting thing about them is that they can be used to create decorators. And they do just that, they decorate existing functions with additional functionality, and they're also reusable so they can be applied to multiple different functions at once.

## **Decorators Defined**

A decorator is essentially a higher order function that both accepts a function as an argument and also returns a function. The result is a function that has the same functionality as the one you passed into the decorator along with whatever extra functionality you defined within the decorator body. This is best explained through a code example:

```python
def example_func():
    print("I'm a function!")
    
def decorator(func):
    def inner():
        func()
        print("I've been decorated!")
    return inner
```
Now we can say: 
```python
decorated_func = decorator(example_func)
decorated_func()
```
Now if we run the program, the output will be:
```
I'm a function!
I've been decorated!
```
Decorators actually have a cool bit of syntactic sugar where instead of typing this:
```python
decorated_func = decorator(example_func)
decorated_func()
```
We can just add ``@decorator`` above the decorated function's definition like so:
```python
@decorator
def example_func():
    print("I'm a function!")
```
Now if you call ``example_func()``, the output will be the same as it was previously.

## Decorating A Function That Takes Arguments

Decorators can also be applied to a function that takes in parameters, and the decorator will actually have access to any parameters passed into the decorated function.

Take this function: 
```python
def capitalize_first_name(func):
    def wrapper(first_name,last_name):
        capitalized = first_name.upper()
        func(capitalized,last_name)
    return wrapper
    
@capitalize_first_name
def print_name(first_name,last_name):
    print(f"Hi, my name is {first_name} {last_name}")
```
Now, for example, if we say ``print_name("John", "Doe")``,
the output will be ``Hi, my name is JOHN Doe!`` without us ever having to alter the original function.

And you don't always need to have the same number of arguments for a decorator to work; you can pass the ``*args`` operator into the wrapper and be able to work with any function with any number of arguments!

## Conclusion

Decorators are, in my opinion, one of the coolest features that Python has to offer. You don't always have a good reason to use them, and you probably shouldn't unless you actually have to, but they can be incredibly useful when the situation calls for them. Decorators are highly used in web frameworks like Flask and Django to add HTTP routing functionality, authentication, and more.
Instalando Deno, um runtime para Typescript e Javascript
Tags: javascript, typescript, deno, scoop
Published: 2019-05-30 23:13:15

## O que é Deno?
Deno é o mais novo runtime de typescript e javascript, desenvolvido por Ryan Dahl , o mesmo desenvolvedor do NodeJS. Deno promete ser mais rápido e seguro que o Node, pois ele não irá usufruir de grandes dependências e pacotes, como por exemplo o tão famoso 'node_modules', tendo uma estrutura um pouco diferente do convencional.   

### Instalando Deno no Windows 10

Para facilitar nossa vida, iremos instalar um command-line installer do Windows chamado Scoop. Para instalar execute os seguintes passos.

Abra seu prompt de comando e digite o seguinte comando para abrir o seu powershell:


``` bash
> powershell
```
(Verifique se o PowerShell 5 (ou posterior, inclui o PowerShell Core ) e o .NET Framework 4.5 (ou posterior) estão instalados)

Ao habilitar o powershell rode o seguinte comando:

``` bash
> iex (new-object net.webclient).downloadstring('https://get.scoop.sh')
```
Scoop instalado!

#### Agora finalmente vamos instalar o Deno

Abra um novo terminal e digite: 

```bash
> scoop install deno
```
Após terminar de fazer o download digite no cmd:
(Se necessário abra um novo terminal)

```bash
> deno
```
E deverá aparecer logo embaixo um terminal da seguinte forma:

```bash
> _
```

Neste terminal digite:

```bash
> console.log('Hello World!')
```
Se ele retornar: 

```bash
> console.log('Hello World!')
Hello World!
undefined
```
O Deno está instalado corretamente!

Agora o próximo passo é se aventurar com essa nova tecnologia, até a próxima!
Interactive JS Date Cheat Sheet
Tags: javascript, vue, beginners
Published: 2019-05-30 22:36:42

This is the story of my process building [JSDates.dev](https://jsdates.dev), my first published project and what I learned along the way.

#Why Dates?

Remembering all of the various Javascript Date and Time methods has always been a struggle for me. Various methods have a partner with a slightly similar name, causing confusion:

+ toISOString & toJSON
+ toUTCString & toGMTString

Some have similar names but provide different results:

+ getFullYear
+ getUTCFullYear
+ getYear

Some have different names and provide almost the exact same value:
+ valueOf
+ getTime

# Cheat Sheet

With all of that in mind, I set out to create a tool that would allow me to input multiple dates, see all of the values of all of the methods and compare. Thus [JSDates.dev](https://jsdates.dev) was born!

# Tools & Methodology

I've been a big proponent of Vue for some time now, so I knew that it would be my JS framework of choice. The CSS framework Bulma has some very helpful classes that allowed for quick styling. Although I am normally a VS Code user, i decided to try out CodeSandbox for this project. I hadn't used it for any previous projects, but its integration with Netlify was unbelievably easy to use in order to build on commit.

# Learnings

+ CSS Grid is truly amazing, and is only going to get better. Setting up a responsive grid takes mere seconds.
+ Vue's reactivity system continues to impress in terms of rendering speed
+ Dates & Times are confusing, but understanding the options can be more valuable than adding a specific library

# Next Steps

I tried quite hard to find a way to add function arguments without hard-coding the various options. Looping through prototype methods was fairly simple, but trying to determine what arguments went with those methods doesn't appear to be possible.


Please feel free to give me your thoughts or open an issue on the [Github Repo](https://github.com/aprouja1/DateCheatSheet)
Easy Way To Find Weekday From a Given Date String
Tags: tutorial, javascript, beginners, i18n
Published: 2019-05-30 22:17:33

---
title: Easy Way To Find Weekday From a Given Date String
published: true
description: Use the Intl.DateTimeFormat constructor, to find the weekday of a given date string.
tags: tutorial, javascript, beginners, i18n
cover_image: https://thepracticaldev.s3.amazonaws.com/i/xrnkvy42s5n1snu7htgb.jpeg
---

I've recently been introduced to the `Intl` object, which is used as the namespace for the [ECMAScript Internationalization API](https://norbertlindenberg.com/2012/12/ecmascript-internationalization-api/index.html).  It has a neat object called `DateTimeFormat` which can be used to format a date value into locale specific strings. 

I'll show you a typical use case for using `Intl.DateTimeFormat` to generate the weekday of a given date string (e.g. `07/16/1945`).

## Problem

Given a `dateString` in the format `MM/DD/YYYY`, find and return the weekday for that date.  

## Solution

```js
/**
 * Given a date string in the format MM/DD/YYY, find and return the 
 * weekday for that date in English.
 *
 * @param {string} dateString
 * @returns {string} - weekday for the given date [e.g: Wednesday]
 */
const getWeekDay = (dateString) => {
  const date = new Date(dateString);
  const dateTimeFormatOptions = { weekday: 'long' };
  const dateTimeFormat = new Intl.DateTimeFormat('en-US', dateTimeFormatOptions); 
  return dateTimeFormat.format(date);
}
```

## Explanation

1. Create a function expression called `getWeekDay` which takes a string (`dateString`).
2. Create a `Date` object with the given `dateString`, so that we can pass it as a parameter into the `format` method of `DateTimeFormat`.
3. Create an object to hold the [`options`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat#Parameters) parameter for `Intl.DateTimeFormat`. Setting the `weekday` property equals to `long`, so that we get the localized weekday when calling `format`.
4. Create a an instance of [`Intl.DateTimeFormat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat) setting `locales` to `en-US`, and passing in the previously created `dateTimeFormatOptions` object.
5. Return the result of calling [`format`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/format) method on `Intl.DateTimeFormat` to find the weekday for the given `date`. 

## Output

```js
console.log(getWeekDay("07/16/1945"));
// expected output: "Monday"

```

In closing, we used the `Intl.DateTimeFormat` object to quickly find the weekday of a given date string. Best of all [`Intl`](https://caniuse.com/#feat=internationalization) has great support across modern browser. 

Thank you for reading.
ES7 Async/Await with React Native
Tags: reactnative, javascript
Published: 2019-05-30 21:47:40

Async/Await is a new syntax for writing asynchronous code in JavaScript. Support was added in React Native 0.10 and it’s now reached TC39 stage 3 (candidate).

<!--more-->

## Example

In this example using the promise returning fetch polyfill. We will display the React Native GitHub star count.

```jsx
const URL = "https://api.github.com/repos/facebook/react-native";

class StarCount extends Component {
  constructor() {
    super();

    this.state = {stars: "?"};
  }

  componentDidMount() {
    this.fetchData().done();
  }

  async fetchData() {
    const response = await fetch(URL);
    const json = await response.json();
    const stars = json.stargazers_count;

    this.setState({stars});
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.text}>
          React Native has {this.state.stars} stars
        </Text>
      </View>
    );
  }
}
```

Async / await works with any Promise based API or one of your creation.

```js
const getStars = () =>
  new Promise(resolve => {
    const FIVE_SECONDS = 5000;
    // Simulate async operation
    setTimeout(() => resolve(1234), FIVE_SECONDS);
  });
const fetchData = async () => {
  const stars = await getStars();
  // Do something with stars
};
```
Robots, now + in the future
Tags: machinelearning, robots
Published: 2019-05-30 21:45:01

Q:  Robots are the physical manifestation of AI – how will robots transform businesses/ our daily lives in the future?

A:  When most people think of robots, what I’ve heard most often comes to mind is something vaguely humanoid or animal-shaped with mobility challenges and usually a sci-fi angle.

  When I think of robots, I think of asking my phone “How do I get home?”

  If we use this framework with robots as a physical manifestation of AI, it includes the phone you give your grandmother for Christmas.  This is what we see now, her using her phone to interact with her bank, ask for directions to the doctor, trading travel pictures with her friends.  We are building highly sophisticated technology enabling people to be part of automated decision processes into people’s lives every day.

  In the future, and the future is now, we have to continue to make decisions about *how* and *where* to integrate technology into our lives. 
 These algorithms are data-intensive and we have to consider what that means in the applications we build for people.  Most promising is the work that I see emphasizing pushing model training and data collection out to devices, to give users the same features they want from advanced products without having to give up your personal local data.  There is an area of research known as [federated learning](https://www.tensorflow.org/federated/federated_learning) which allows developers to give people the benefits that they want from this technology without having to give up their personal patterns.  As data protection becomes increasingly important, the architectures for building the applications they want to use will change and platforms will have to adjust to support that.