teleren/devto huggingface dataset:
What Did You Learn This Week --May 8?
Tags: todayilearned, discuss
Published: 2020-05-11 02:29:54

---
title: What Did You Learn This Week --May 8?
tags: todayilearned, discuss
cover_image: https://res.cloudinary.com/practicaldev/image/fetch/s--TpOOUw4B--/c_imagga_scale,f_auto,fl_progressive,h_420,q_auto,w_1000/https://dev-to-uploads.s3.amazonaws.com/i/67bb72156h4y13zl5cio.png
series: this-week-i-learned
---
Why PureVPN?
Published: 2020-05-11 02:07:26

Because PureVPN operates a self-managed VPN constellation of 2000+ servers in 140+ countries. Because we provide instant access to your favorite content. Because we empower you to access everything on the internet, download securely, and remain protected all the while. But mostly because, we value your trust!

Iron-Clad Security of Your Online Avatar  

With your traffic routed through our secure VPN servers, you will be able to browse safely and with complete peace of mind.

To make your data appear completely gibberish to anyone who manages to intercept your communications or hijack your data.

Public Wi-Fi hotspots are breeding grounds for hackers and identity thieves. PureVPN secures your Wi-Fi connection to protect your data transmissions.

To Keep Your Online Privacy Intact 

Privacy is being invisible. Privacy is not leaving any digital breadcrumbs behind. Privacy is another name for PureVPN.

Cookies, device IDs, IP mapping and geolocation, app permissions, etc., are all used to keep tabs on your activities.

Data security means keeping your data secure during transmission and not allowing authorized access to it.

To Get Complete Internet Freedom

You have unlimited bandwidth, crazy speed, and a global network of servers spread across the globe to do just that.

We have dedicated P2P servers in countries where P2P file-sharing is legal by law, so you can download files securely.

Absolutely! We have optimized servers for streaming to make sure you get a buffer-free streaming experience every time.

More PureVPN Reviews: https://www.topvpnguides.com/purevpn-review/
⚡️Tools and products we use at Spike - part 2
Tags: productivity, customersupport
Published: 2020-05-11 01:45:28

We believe in outsourcing complex jobs to specific products. This a small list of other tools and products we use.

👈 [First part](https://dev.to/spike/tools-and-products-we-use-at-spike-part-1-37mm) on all the tools and products used by engineering.

###1. [Intercom](https://intercom.com)
We got into Intercom's [early stage program](https://www.intercom.com/early-stage) to access the entire platform. We mainly use this for customer support using Live chat and user onboarding.

###2. [GitBook](https://www.gitbook.com)
After having tried multiple products to host our documentation, we finalised GitBook. It's intuitive, has a great UI and super flexible. Our customers love [our docs](https://docs.spike.sh). 

###3. [1Password](https://1password.com)
We didn't think we would use this as much as we do. This is by far the product we use the most other than Gmail. We recommend orgs and individuals to use 1Password to stay safe and secure. 

###4. [Notion](https://notion.so)
Roadmap, sprints, extensive documentation for features and team collaboration all on Notion. It's literally capable of everything our teams needs in one place.

###5. [Headway](https://headwayapp.co)
We display our changelog on the website and on the dashboard. There are mixed opinions about public changelog on the internet but for us, it's easy to keep our customers up to date about the latest changes on our platform.

###6. [Figma](https://figma.com)
Frankly, the only reason we started with this was because it was free. (_not kidding_). However, Figma has played a HUGE role in how we work. At [Spike](https://spike.sh), we take design very seriously and Figma has been an ultimate solution.

###7. [SendX](https://www.sendx.io)
We use SendX for our promotional emails. Easy, affordable and perhaps the best support of all the other products we have used. Super SME friendly.
Using Beautiful Soup For Web Scraping
Tags: python, webdev
Published: 2020-05-11 01:29:00

Beautiful Soup is a python module which can inspect HTML and XML content. It does not fetch any HTTP pages (use `requests` or `urllib3` for that), and you need to load the HTML into Beautiful Soup in order to process it.

If you ever used lxml or html5lib to parse HTML, BeautifulSoup uses these modules internally and this library makes it easier to parse HTML, similar to how requests is built on urllib3.

You import it with `import bs4`, and therein is a class called `BeautifulSoup` that represents an HTML structure. It takes the string representing an HTML file as an argument.

```python
# html_doc is a string of HTML
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc, 'html.parser')
```

To print the HTML on the screen it would be beneficial to format it with whitespace using `BeautifulSoup.prettify()` first.

```python
>>> print(soup.prettify())
<html>
 <head>
  <title>
# ...
```

Check out the sample HTML file listed at https://www.crummy.com/software/BeautifulSoup/bs4/doc/. It is simple enough to demonstrate extracting elements in an easy-to-understand way.

The BeautifulSoup object contains members for each HTML tag, such as `<title>`, `<p>`, `<a>` and `<b>`, and even `<head>` and `<body>`. In fact, if you use the `find_all()` method and pass the tag name as a string without angle brackets, it will collect all tags across the HTML with that name and return them in a list. You can instruct `find_all()` to search by CSS class by passing the `class_` keyword argument. (The word "class" is a reserved keyword in Python so it had to be named `class_`.)

The `contents` member contains the element's children.

```python
soup = BeautifulSoup(...)
head_tag = soup.head
head_tag
# <head><title>The Dormouse's story</title></head>

head_tag.contents  # For an iterator, try .children
[<title>The Dormouse's story</title>]
```

You also get familiar `parent`, `next_sibling` and `previous_sibling` elements to get the element's parent, next sibling node and previous sibling node respectively. Do note that instead of getting next/previous sibling elements repeatedly you can just get `next_siblings` and `previous_siblings` which return them all as an iterator.

## And we're done

If you see anything incorrect in this post, let me know so I can fix them.

Image by <a href="https://pixabay.com/users/Goumbik-3752482/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=2047314">Goumbik</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=2047314">Pixabay</a>
Python Zero to Hero - Ep.6 - Python Classes and Instances
Tags: python, beginners, tutorial, livecoding
Published: 2020-05-11 01:25:30

---
title: Python Zero to Hero - Ep.6 - Python Classes and Instances
published: true
description: Python classes provide functionalities for Object-Oriented Programming. Today we explore how to write classes in Python, clear some concepts of scopes. We learn by purposely breaking some code.
tags: python, beginner, tutorial, live coding
---
Python classes provide functionalities for Object-Oriented Programming. Today we explore how to write classes in Python, clear some concepts of scopes. We learn by purposely breaking some code.

You can get the slide deck [here](https://slides.com/cheukting_ho/python-classes#/) and the example code and homework form [GitHub here](https://github.com/Cheukting/python02hero). Ask questions at my [Twitch channel](https://t.co/7sqvTilzF1?amp=1)

Also, check out Naomi Ceder's [Twitch channel](https://t.co/hXhTu0ZIG8?amp=1) for more beginner's (slightly more advance) tutorial.
#3 Building a simple GraphQL API with Actix and Juniper (Rust)
Tags: rust, graphql, tutorial, webdev
Published: 2020-05-11 00:48:03

{% youtube 7v7ERnrC4fo %}

⏱️TIMESTAMPS⏱️
0:00 Simple GraphQL API with Actix and Juniper - part 3
0:07 Start of the video
0:28 Refactoring of User queries into a repository
4:06 Get a single user
6:45 Code to create and list Posts
11:15 Query the posts on GraphiQL
13:10 Posts as a field of User
15:59 N+1 Problem
16:45 Solution? Dataloaders
17:11 Using a Dataloader to get the posts of an user
26:05 Did it work?
27:39 Thank you!

[Part 1](https://dev.to/nemesiscodex/building-a-simple-graphql-api-with-actix-and-juniper-rust-26f6)
[Part 2](https://dev.to/nemesiscodex/2-building-a-simple-graphql-api-with-actix-and-juniper-rust-51h9)
Context vs Hooks ({experiment})
Tags: react, context, hooks
Published: 2020-05-11 00:19:34

Recently I came with an idea to change the app flow I am working on, It is not a big application, so I'm using context to wrap my components routes in other to share some data and states across components.

But last night, I thought. What if I replace the context for hooks and pass down those hooks from the routes? That should be faster right? In that way, I can use my hooks as HOF holding the states I need to use across the application, no more providers, no more context.

Well, I did a little experiment to confirm that the change I was going to do could be beneficial, so I created a simple condesandbox with and application holding two routes, that passes simple state value and a method that modifies that state, to both components, in one of them I called the method on a button click to change the state up in the tree, and the profiler results were this:

App with Context API

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

App with Hooks as HOF (passed down from the routes)

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

It's not a big difference but to my surprise, the context was faster that the hook! According to React docs:

*“Context provides a way to pass data through the component tree without having to pass props down manually at every level.”*

Final thoughts:
Context beats Hooks as a single source of truth or HOF to manage your app state.

*I'll need to test this out with more children components in other to check if the performance remains on the context side.*

*Photo by [Gratisography, at Pexels](https://www.pexels.com/es-es/@gratisography)*
Create multiple files for your routes in Laravel
Published: 2020-05-11 00:17:06

While adding functionalities to my website, the need arose to better organize my routes in separate files, and for this reason I began to investigate how it is done and what I come to share with you today.

It is a very simple task since you will only have to make the modifications to the file
app / Providers / RouteServiceProvider.php in the mapWebRoutes function by adding require base_path ('routes / filename.php');

Example:
We create a file called user.php that will contain the routes related to the users, now we simply register it in the mapWebRoutes function as follows require base_path ('routes / user.php'); finally leaving the function like this

  protected function mapWebRoutes()
    {
        Route::middleware('web')
            ->namespace($this->namespace)
            ->group(function ($router) {
                require base_path('routes/usuario.php');
                require base_path('routes/web.php');
            });
    }}

Any problem you can contact me in the comment box or directly on my social networks.
You can find more content like this on my Globalizations website
Using a stack to manage my workflow
Published: 2020-05-11 00:08:06

Just thought I'd share a self organization tool I've found helpful and thought others might too. 

I often will go layers deep into my project to reach a development goal; to get one thing right means getting another right, but the second has multiple things that need to be right, and so on.

To help with this, i created a physical stack with post it notes. The first note is a primary goal and if applicable, the pieces of that problem. When i decide what part i need to work on first, i write that on the next note and put it on the top of the stack. Then the specific part of that needs to be developed goes on a note and on the top of the stack. I keep doing this until I'm at a point of solving a specific problem.

When I'm finished with that problem i toss the note from the top of the stack and get right back to work on the previous problem until it's done (which may require building up the stack again).

With this i always know what my current problem is and what led me there. This is very helpful when interruptions are unavoidable, and for not losing track of what should be worked on in order keep moving forward. 

I also keep a backlog stack of notes that i think of or discover along the way but don't want/need to add to the current stack. These may start a new stack someday, become necessary and added to the current stack, or even just thrown out eventually for whatever reason. Having this as a dumping ground for things that come up helps to let it go and keep focused on the current problem.
Fetch API Results from the Browser and send them to Shiny
Tags: rstats, javascript, shiny
Published: 2020-05-13 16:27:01

---
title: Fetch API Results from the Browser and send them to Shiny
published: true
date: 2020-05-11 00:00:00 UTC
tags: rstats, javascript, shiny
canonical_url: https://colinfay.me/api-from-client-shiny/
---

How to fetch API results from client-side in a Shiny app and send them to R.

## Why on earth?

Good question! Why on earth would you want your Shiny application to make API requests from the User Interface (i.e. from the browser)? Right now, if your application makes API calls, chances are that you have been doing them straight from R, and that it works pretty well. But in some cases it might not be the correct implementation, notably if the API limits requests based on an IP and your application gets a lot of traffic. For example, Brewdog’s [PUNK API](https://punkapi.com/) limits to one call per IP per second. In that scenario, if the calls are made from the server, you will only be able to serve one call per second, and if your users do a lot of API call at the same time, they will be slowed down, as the server’s IP is limited to 1 call per second. On the other hand, if the API call is made from the users’ browsers, the server IP isno longer limited: each user has its own limitation.

## How to

You can write API calls using the `fetch()` JavaScript function. It can then be used inside a Shiny JavaScript handler, or as a response to a DOM event (for example, with `tags$button("Get Me One!", onclick =
"get_rand_beer()")`, as we will see below).

Here is the general skeleton, that would work when the API does not need authentication and returns JSON.

- Inside JavaScript (here, we create a function that will be available on an `onclick` event)
<!-- end list -->

```
// JAVASCRIPT FUNCTION DEFINITION
const get_rand_beer = () => {
    // FETCHING THE API DATA
    fetch("https://api.punkapi.com/v2/beers/random")
      // DEFINE WHAT HAPPENS WHEN JAVASCRIPT RECEIVES THE DATA
      .then((data) =>{
        // CONVERT THE DATA TO JSON
        data.json().then((res) => {
          // SEND THE JSON TO R
          Shiny.setInputValue("beer", res, {priority: 'event'})
        })
        // DEFINE WHAT HAPPENS WHEN THERE IS AN ERROR TURNING DATA TO JSON
        .catch((error) => {
          alert("Error catchin result from API")
        })
      })
      // DEFINE WHAT HAPPENS WHEN THERE IS AN ERROR FETCHING THE API
      .catch((error) => {
        alert("Error catchin result from API")
      })
  };

```

- Observe the event in your server:
<!-- end list -->

```
observeEvent( input$beer , {
  # Do things with input$beer
})

```

And here it is, when the users click on the button, the API calls willbe made from their browser, and then sent back to the server.

Note that the data shared between R and JavaScript is serialized toJSON, so you will have to manipulate that format once you receive it in R.

See an example at[ColinFay/punkapi](https://github.com/ColinFay/punkapi)
Coffee Companion App LS:002
Tags: swift, swiftui
Published: 2020-05-13 04:24:19

---
title: Coffee Companion App LS:002
published: true
tags: Swift, SwiftUI 
canonical_url: https://www.buymeacoffee.com/p/62523
series: Coffee Companion App
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/t5qp1m3b3a3ci523p0dl.png
---

Missed what this is about? Read the initial [post on my blog](https://appsbymw.com/blog/2020/05/05/coffee-timer-app).

# What did I do on May 11th?

Here's a list of what I did

- Allow user to input a new coffee amount by pressing on "Coffee Grounds"
- Made water amount change when coffee amount is changed
- Made blooming amount change when coffee amount is changed

Watch a replay of the live stream

{% youtube TcIsl2xHi8Q %}

# What am I planning on May 18th?

Here's some things I'm going to work on

- Format doubles to only have 2 digits to the right of the decimal
- Add the button to dismiss the new amount sheet
- Get the timer function working

# Looking for something related to the project?

- Wanting to know what tasks need to be done? [Check out the Trello board](https://trello.com/b/KgqJHA8o/coffee-app)
- Wanting to see the code? [Look at the GitHub repo](https://github.com/appsbymw/coffee-app)
- Wanting to show support? Buy me a coffee or two here!


---

If you enjoy my posts, streams, and apps, consider encouraging my efforts.
- <a href="https://www.patreon.com/appsbymw" target="_blank"><button type="button" class="crayons-btn">Become a Patron</button></a>
- <a href="https://www.buymeacoffee.com/appsbymw" target="_blank"><button type="button" class="crayons-btn">Buy Me a Coffee</button></a>
- <a href="https://buttondown.email/appsByMW"><button type="button" class="crayons-btn">Subscribe to my Newsletter!</button></a>
Database deadlocks
Published: 2020-05-15 14:33:15

---
title: Database deadlocks
published: true
date: 2020-05-11 00:00:00 UTC
tags: 
canonical_url: https://www.geekytidbits.com/database-deadlocks/
cover_image: https://www.geekytidbits.com/database-deadlocks/deadlock.png
---

In a database system, a deadlock happens when two or more transactions wait for one another to release a lock. When this happens, the only course of action for the database engine is to kill one of the transaction to unblock the others.

Here is a simple visualization of a deadlock:

![Deadlock Example](https://www.geekytidbits.com/database-deadlocks/deadlock.png)

### Mitigations

Here are some mitigation steps to avoid deadlocks:

1. Take locks in a consistent order. Deadlocks happen when competing transactions take locks in opposite order. In the [PostgreSQL Explicit Locking documentation](https://www.postgresql.org/docs/current/explicit-locking.html#LOCKING-DEADLOCKS), the following deadlock example is given:

      Session 1:

      ```
      UPDATE accounts SET balance = balance + 100.00 WHERE acctnum = 11111;
      ```

      Session 2:

      ```
      UPDATE accounts SET balance = balance + 100.00 WHERE acctnum = 22222;​
      UPDATE accounts SET balance = balance - 100.00 WHERE acctnum = 11111;
      ```

      Session 1:

      ```
      -- DEADLOCK WILL HAPPEN!​
      UPDATE accounts SET balance = balance - 100.00 WHERE acctnum = 22222;​
      -- DEADLOCK HAPPENED!
      ```

    If Session 2 had updated the accounts record `WHERE account = 11111` first and then `WHERE account = 22222`, which is the same order as Session 1, a deadlock would be avoided.

2. Find long running transactions and make them faster by optimizing or breaking them up into smaller transactions. The longer transactions run, the greater the chance of a deadlock.

3.  Move statements that obtain a lock as far down in a transation as possible, so that the locks are obtained for a shorter duration of time.

4. Use explicit locking to take less aggressive locks where possible. For example, in SQL Server, evaluate using `READ UNCOMMITTED` isolation level where possible.

5. Depending upon the database system, adding an index may help prevent deadlocks. For example, in SQL Server, a clustered index scan could be blocked by a row lock from another transaction. Adding another index could prevent this.

As a last resort, you could add retry logic to the application. The application could catch a deadlock exception and then let the application gracefully retry until it succeeds. This option should be a last resort since it is working around the root cause of the problem.
Do you ever go back and clean up your Github repos?
Tags: watercooler, discuss, help, healthydebate
Published: 2020-05-10 23:50:03

I recently shared my GitHub profile with someone and realized I have 330 repos. Most of them are from my time at Flatiron, working on class assignments. But some are code challenges, leetcode problems, forked repos, and random things I've tried over the past few months. 

Since Github doesn't allow you to group repos, organizing would be a time-consuming exercise. 

Is it worth the time investment? Do recruiters expect your GitHub to be easy to navigate? Do you regularly review and purge your  inactive repos?
Add Sentry to Vercel Next.js API Routes
Tags: javascript, typescript, tutorial
Published: 2020-05-10 23:45:59

To add Sentry to Next.js, you can wrap your entire route in a `try` block and have the Sentry reporting done in the `catch` block:

```typescript
// /pages/api/someRoute.ts
import * as Sentry from '@sentry/node';
import { NextApiRequest, NextApiResponse } from 'next';

Sentry.init({ dsn: process.env.SENTRY_DSN });

export default async (req: NextApiRequest, res: NextApiResponse) => {
  try {
    // ...your main business logic here
  } catch (error) {
    Sentry.captureException(error);
    await Sentry.flush(2000);
    throw error;
  }
};
```

Of course, writing that `catch` block over and over is bad programming practice. We can wrap the `try/catch` in a [higher order function](https://eloquentjavascript.net/05_higher_order.html):

```typescript
import * as Sentry from '@sentry/node';
import { NextApiRequest, NextApiResponse, NextApiHandler } from 'next';

Sentry.init({ dsn: process.env.SENTRY_DSN });

const sentryHandler = (apiHandler: NextApiHandler) => {
  return async (req: NextApiRequest, res: NextApiResponse) => {
    try {
      return await apiHandler(req, res);
    } catch (error) {
      console.error(error);
      Sentry.captureException(error);
      await Sentry.flush(2000);
      throw error;
    }
  };
};

export default sentryHandler(async (req: NextApiRequest, res: NextApiResponse) => {
  // ...your main business logic here
});
```
You can extract the `sentryHandler` to its own file and wrap it around all the Next.js API routes you need Sentry to handle.