teleren/devto huggingface dataset:
SLAP: Single Level of Abstraction Principle
Tags: cleancode, designprinciples, slap
Published: 2020-12-26 16:35:54

---
title: SLAP: Single Level of Abstraction Principle
published: true
date: 2020-12-26 16:30:00 UTC
tags: CleanCode,DesignPrinciples,SLAP
canonical_url: https://le0nidas.gr/2020/12/26/slap-single-level-of-abstraction-principle/
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/9j5iwqzgjl29v7uh7qd1.png
---

Even thought this acronym is quite catchy, `SLAP` is the one principle that you don’t find many people talking about.

#### Single Level of Abstraction

In essence, the principle proposes that each block of code should not mix **what** the code does with **how** it does it. Another way of thinking about it is, whenever possible, the code should describe in steps the actions that will take and then each step can elaborate on that.

For example:

{% gist https://gist.github.com/le0nidas/c29ea33494488dc9c1345f579b9c5af6 %}

this class has one method that showcases both what it does and how it does it.

If we want to `SLAP` it we need to delegate the _how_ of each step to its own method:

{% gist https://gist.github.com/le0nidas/48171affa15f34734da33bddb1188b42 %}

here the `invoke` method simply describes what will happen upon its invocation. A new task will be created, then saved and finally passed to any observers.   
For knowing how each step gets implemented we need to drill down one level. For example, creating a new task requires us to normalize the provided description and then create the task. For knowing how the normalization gets implemented we yet again move one level deeper!

#### Conclusion

Keep hiding how something gets implemented in new methods until you can no longer avoid it!
**kwargs, you got me!
Tags: python, programming, todayilearned, gotcha
Published: 2020-12-26 16:17:43

Hello, world! 👋🏼

Being a Python developer since quite a few years now, this language still doesn't stop to teach me!

The other day I was refactoring a function that took just `kwargs` as a parameter. We wanted to make functions more readable, so we thought of having few important entries from `kwargs` as positional arguments.

So this:
```python
def foo(**kwargs):
    print(kwargs)
```
turned into this:
```python
def foo(status, **kwargs):
    print(kwargs)
```
Of course this requires that `kwargs` should have the `status` key, otherwise it would throw an error
```python
TypeError: foo() missing 1 required positional argument: 'status'
```

After making this sure, things looked pretty readable; until a test case failed:
```python
KeyError: 'status'
```

_Wait. What? How?? I just changed the arguments, not a single line of code change inside the function..?_
And yet, I got `KeyError` for `kwargs['status']`

At first, this seemed as if it should not have had happened. But then, it did! Going back to the REPL and trying out few things quickly shed light onto a thing that I didn't know about `kwargs` till that day.

Consider the below code:
```python
>>> d = {'a': 'A', 'b': 'B'}
>>> 
>>> def foo(x, **kwargs):
...     print(x, kwargs)
... 
>>> def bar(x, c, **kwargs):
...     print(x, c, kwargs)
... 
>>> 
```
Now let's see what happens when we call these functions:
```python
>>> foo(1, **d)
1 {'a': 'A', 'b': 'B'}
>>> 
```
```python
>>> bar(1, **d)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: bar() missing 1 required positional argument: 'c'
>>> 
```
This error is the same as mentioned above. We solve this by making sure the key is present in the `dict`:
```python
>>> d['c'] = 'C'
>>> 
```
And call the function again:
```python
>>> bar(1, **d)
1 C {'a': 'A', 'b': 'B'}
>>> 
```
Notice what happens when we print `kwargs` - the key that we accepted as a positional argument (`c`) got popped out of `kwargs`! It was no more part of `kwargs`, which explains why we got the `KeyError` above - because before refactoring, the key `status` was a part of `kwargs`, which, after refactoring, was coming in as an individual argument **and** was no more a part of `kwargs`.

It's a small thing, but can go unnoticed. Thanks to test cases, we were saved from creating another incident report..
Collect and Store Streaming TimeSeries data into Amazon TimeStream DB
Tags: aws, serverless, database, architecture
Published: 2020-12-26 15:48:30

# Introduction
This post discusses serverless architectural consideration and configuration steps for deploying the Streaming TimeSeries Data Solution for Amazon TimeStream DB in the Amazon Web Services (AWS) Cloud.It includes links to a code repository that can be used as a base to deploy this solution by following AWS best practices for security and availability.

# Components Basics
**AWS Lambda**
Lambda is a serverless compute service that lets you run code without provisioning or managing servers.
**Amazon Timestream**
Amazon Timestream is a fast, scalable, and serverless time series database service for IoT and other operational applications.
**AWS Kinesis**
Amazon Kinesis Data Streams ingests a large amount of data in real-time, durably stores the data, and makes the data available for consumption.

#DataFLow
The streaming data pipeline will look alike as given below after the deployment.

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

#Getting Started
**AWS Kinesis Setup**
Create timeseries-stream DataStream with a Shard.

**Amazon TimeStream Setup**
Create a database named ecomm in the same region as kinesis datastream and table named inventory in database ecomm using the gists shared in github.

**AWS Lambda Setup**
Create a Kinesis producer to create and ingest time series data into the kinesis data stream which has to be read in the same order. To do so, create a kinesis consumer. The python SDK examples used for this article has been kept at github repository [TimeStream](https://github.com/prasanth-m/AWS/tree/master/TimeStream).

#Deployment
Serverless framework makes deployment and development faster. Deploy Lambda Producers and Consumers into AWS and schedule them to run based on time-series event triggers or any schedule. In a typical production scenario, the producers might be outside of the cloud region and events might arrive through the API gateway.
Producer and Consumer Logs will be available in cloud watch.

The written results can be quired using the query editor of Amazon TimeStream.
   `select * from “ecomm”.”inventory”
    limit 10`

#Conclusion
In most organizations, Timeseries data points are written once and read multiple times. It is clear that time-series data can be collected and stored using serverless services. Though Timestream can be integrated with various AWS services, kinesis is chosen since it has data retention and replay features. The next article about time-series data will have a use case using kappa data processing architecture.
Create and connect a Siteground PostgreSQL Database
Tags: siteground, postgres
Published: 2020-12-26 15:41:27

Siteground is one of the top WordPress hosting providers, and you could use it for some **database hosting** too! Sadly there hasn't been much documentation around for setting up PostgreSQL with Siteground (especially for newbies like myself), and Siteground's documentation on PostgreSQL isn't very updated for the new Site Tools.

This article is a straightforward step-by-step guide on setting a PostgreSQL database in Siteground, and finding the needed information to remote connecting it.  

### Creating Postgresql Database in Siteground 

1. Create a **new site** in Siteground if haven&#39;t done so
2. Head over to _Site Tools_, find &quot;PostgreSQL&quot; under &quot;SITE&quot; section
3. Since Siteground blocked access to your site's server, you have to whitelist IP addresses first. Go to the _REMOTE_ tab, add your ip address to the Remote Access Host. To make it more convenient, add `0.0.0.0/0` into the list of the whitelisted host. **Notice adding `0.0.0.0/0` will allow all IPs to connect to your database if your database credentials are leaked**.

    ![] (https://static.slab.com/prod/uploads/8eyamqri/posts/images/riimyCkkY1iyI9SXjlzY5LKP.png)

4. Switch to _USERS_ tab, click &quot;CREATE USER&quot; and a user will be automatically created. If you don't like the default password, click the three dots under action and **change the password** for this user (and save it somewhere else, you will need it later).

    ![](https://static.slab.com/prod/uploads/8eyamqri/posts/images/k9UXnvqAqVHNyZIuAupILVij.png)

5. Switch to the _DATABASES_ tab, click &quot;CREATE DATABASE&quot; and an empty postgresql database will be created. Click the Person icon under Actions to **grant access** to the created user to this database.

    ![](https://static.slab.com/prod/uploads/8eyamqri/posts/images/DpiUO1Ol7FAsC5hGCegO-xad.png)

That&#39;s it for the Siteground part! Consider adding **Labels** to both the database and user to make things easier to refer to in the future.



### Setup remote connection to the postgresql database 

For connecting a postgresql database, you will need to locate the below 5 information:

1. Hostname/Address
1. Port
1. Database Name
1. Username
1. Password

#### Database Name, Username &amp; Password 

_Database Name_, _Username_ &amp; _Password_ for this Siteground postgresql database are information you have just created if you have followed along, and these information are always accessible under the &quot;SITE&quot; → &quot;PostgreSQL&quot; section in _Site Tools_.

#### Port 

According to Siteground&#39;s [help center](https://www.siteground.com/kb/which_ports_are_open_on_siteground_shared_servers/), 5432 is the default PostgreSql port.

#### Hostname/Address 

To locate the hostname of your server/database, head over to your site&#39;s &quot;DASHBOARD&quot;  via Site Tools. Find &quot;Site IP&quot; under &quot;Site Information&quot; → &quot;IP and Name Servers&quot; section, this IP address is all you need.



You should now be able to connect to your Siteground PostgreSQL database!
Discussion on how to find the perfect domain for our side project
Tags: discuss, domain, sideprojects
Published: 2020-12-26 15:41:26

---
title: Discussion on how to find the perfect domain for our side project
published: true
description: Discussion on tips and tricks on how to find and buy the domain of your dreams
tags: 
- "discuss"
- "domain"
- "sideprojects"

cover_image: https://user-images.githubusercontent.com/630705/103154442-3204c180-478f-11eb-8ab5-2f5322a66ca5.jpg
---
Cover image by <a href="https://unsplash.com/@markuswinkler?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Markus Winkler</a>

Coming up with an idea for a side project that we want to promote to the world can be difficult enough. What comes next is finding a good name for it... aaand Success! We found the perfect name that we love, we made a nice concept in our head about how to promote it and the excitement has begun.

Now it's time to buy a domain name for that and guess what... `.com` is not available. What shall we do? No non developer will take `.io` seriously. Buy a `.co` or `.me` domain? How about adding separating the each word in the name with a dash? Yes `my-project.com` is now available. But idk, this dash makes me not want to look at the name.

What shall we do in that case? Any other ideas?
The Sylar Project V 0.0.5
Tags: dohackathon, webdev, mentalhealth
Published: 2020-12-26 15:33:36

New update! I've successfully used Next JS API routes to create a serverless function that handles getting state resources from an Airtable Database instead of serving some local JSON. I left the option to use the local JSON however in case others wish to contribute to other parts of the app and don't need access to Airtable. It was also super nice to see tests pass and build not fail from the GitHub actions checks which are also officially added and updated. An awesome new thing I learned while working on this. 

Here is my next major goal: Allow for user-submitted resources. Setting up Airtable was a part of this but here is what I plan to do in the next couple versions of this leading up to my v1 for submission to the hackathon:

- Make an API route for creating resources - by default they will be in an unapproved state
- Use Tailwind UI to make things look nicer and build a pleasant-looking form
- Integrate Zapier so I can get an email notification whenever someone submits on the form and my Airtable database gets updated
- Create a workflow for myself that lets me quickly look at the email notifications with the resource and approve them if they are appropriate. 

Something I've noticed so far with this that I wish I had done with earlier projects: even unfinished it is useable. The first update I put out only had resources for two states and was a very small and simple UI. It still worked and helped people in those states. Now it holds much more and I've already gotten feedback that someone was able to use it to find a resource in their local state. This alone makes this entire project worth it. 

To see current progress check it out below! Hoping to have a domain name as well once I do submit. 

https://github.com/Rahat-ch/The_Sylar_Project

https://the-sylar-project-6avzk.ondigitalocean.app/
Help Me, a mental health crisis app
Tags: codenewbie, dohackathon, mentalhealth, digitalocean
Published: 2020-12-26 15:32:21

Throughout my life I only saw mental health issues on the TV. I considered mental health issues as other people problems until I saw it manifest within my family and friends. Now I'm scared of the thought that someone I love, cherish, and respect could experience something dramatic and terrifying alone. Even worse, being hurt/kill while reaching out for help.

A sad by-product of going through a mental health crisis and using social media as a “call for help” is that person's reputation is shredded and people who aren't dedicated to that person safety. I have found that this adds to the drama and fuel the fire of paranoia.

The app is called “Help Me” and is designed primarily as an “SOS” (distress signal) to a selected circle of trusted people.
* One push of a button will send a “I am having a mental crisis” message and a location to the trusted people.
* Create a trusted community around the user with private conversations and a system to show their emotions. This will help the trusted people to be aware of the user range of emotions. 

Miguel Hernandez and I have entered the DigitalOcean App Platform Hackathon as a avenue to build this app. The category is **Program for the People and specifically mental health.**

This is an opportunity to learn, build, deploy, and scale an application with DigitalOcean.

This is the initial wireframe. 
![JC's wireframe](https://dev-to-uploads.s3.amazonaws.com/i/6e4jsj4ugchw7anzdzyy.png)

This is the final wireframe. 
![Miguel's wireframe](https://dev-to-uploads.s3.amazonaws.com/i/v4rq75c77tk6q15pd9zo.PNG)

#### Day 1 Activities
* An GitHub repository was quickly spun up to a basic Angular application. We used GitHub's projects to break the app into tasks.

* We talked about what parts of the application that we know how to complete and what parts will be a challenge. We discussed what would be to consider an MVP version, version 2, and version 3.

* We decided to use Angular 11 for front-end and NodeJS for the backend. TailwindCSS will be used for styling. The app will be hosted on the DigitalOcean platform. Finally, GitHub will be used for version control and GitHub projects for task management.

# What's Next
* Tomorrow goal is to start learning TailwindCSS and building the Log-in screen.   

###Stay on the lookout for a Day 2 breakdown blog post!!!
Storing theme state in localStorage
Published: 2020-12-26 15:18:12

Creating Dark-Light mode for website and storing user preferred theme state to local storage. 

So, Earlier I wrote a post about creating Dark-Light mode theme for website. Explaining how it work, way to create it.
But, Problem with that code is when you refresh or if site have multiple pages and you go to another page, theme revert back to it's default theme. *We don't want that* .

# Let's Solve this problem

**********************
I tweak original code. 
### Our HTML
Simple tiny HTML code.
`<a type="button" class="nav-item theme" id="theme-toggle">🌚</a>`

# Now the CSS
```
// Default Light theme color pallet
:root {
    --bg-color: #ffffff; 
    --bg-light: #e3fdfd;

    --font-color:#1f2933;   
    --font-light: #000000;
}
// Dark theme color pallet
body.dark-theme {
    --bg-color: #111216; 
    --bg-light: #24252c;

    --font-color: #9999b3;   
    --font-light: #fff;
}
```

#The JavaScript part

```
const themeToggle = document.querySelector("#theme-toggle");

const currentTheme = localStorage.getItem("theme");
const pageTheme = document.body;

let isDark = true

if (currentTheme == "dark") {
  pageTheme.classList.add("dark-theme");
  themeToggle.innerText="🌞";
} else {
    themeToggle.innerText = "🌚"
}

function themeMode() {
    isDark = !isDark;
    isDark ? themeToggle.innerText = "🌚" : themeToggle.innerText = "🌞";
    pageTheme.classList.toggle("dark-theme");

    let theme = "light";
    if (pageTheme.classList.contains("dark-theme")) {
      theme = "dark";
    }
    localStorage.setItem("theme", theme);
}

themeToggle.addEventListener("click", themeMode)

```
### What is localStorage?

The localStorage properties allow to save key/value pairs in a web browser. The localStorage property is read-only.

+ ##### For storing data to localStorage.
`localStorage.setItem("key", "value");`

+ ##### For reading data from localStorage.
`var lastname = localStorage.getItem("key");`
Learn more about [localStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage)

### What is toggle?

toggle is method of DOMTokenList() interface.
It remove token from token list and return false.
If token doesn't exist, then it add token and return true.

### What's happening here?
+ By default our theme is Light.

+ This part of code check if user already changed theme or has seleted theme, by getting theme data from localStorage.
```
const currentTheme = localStorage.getItem("theme");
if (currentTheme == "dark") {
  pageTheme.classList.add("dark-theme");
  themeToggle.innerText="🌞";
} else {
    themeToggle.innerText = "🌚"
}
```
`themeToggle.innerText` is our button. We are changing emoji if it's Light Mode then emoji is Moon🌚. and if it's Dark Mode then emoji is Sun🌞.

+ When we click our button to change theme, it add `dark-theme` class to `body` tag. Dark theme color pallet is applied to site.

+ It set's current theme to localStorage, using `localStorage.setItem("theme", theme);`

**************************
Here's pen

{% codepen https://codepen.io/vaishnav21/pen/JjROZYZ default-tab=js,result %}
Are you on Github?
Tags: opensource
Published: 2020-12-26 15:12:48

Are you on Github? What is your favorite project? Did you build an open-source project? The one that I have contributed to and I am most proud of is a Bootstrap 5 powered dashboard template, which actually was trending on GH for a couple of days.

Share your profile with us and a project that you like or you have built. Let's connect!

Here's my profile: https://github.com/zoltanszogyenyi
And the project: https://github.com/themesberg/volt-bootstrap-5-dashboard
React + GraphQL Full Stack Tutorial needed.
Tags: react, graphql, tutorial, discuss
Published: 2020-12-26 15:00:26

Guys,
Can anyone list down the references to hands-on free tutorials of building a full-stack application which are built primarily in React and GraphQL.
Thanks

Here are some which I’ve seen already -
1. https://fsgql.com
2. https://youtu.be/n1mdAPFq2Os
Hello, World
Tags: startup, cybersecurity
Published: 2020-12-26 14:57:02

กลับมารื้อฟื้น การเขียนโปรแกรมอีกรอบ เพื่อปั้น startup ทางด้าน Cybersecurity, AI and Robotics 

เป้าหมายเพื่ออยากจะพัฒนาประเทศไทยให้มีความเจริญเทียบเท่ากับนานาประเทศ

มาร่วมด้วยช่วยกันสร้าง Tech Startup ในไทย ให้เหมือนกับซิลิคอนแวเล่ย์ ของฝั่งอเมริกากันเถอะครับ :)
King Snow Fall Animation Effects
Tags: html, css, codenewbie, codepen
Published: 2020-12-26 14:53:08

Pure CSS King Snow Fall Animation Effects | King Snow Fall | Html5 
CSS3

Demo ==> https://codepen.io/Bilal1909/full/yLaPKGW

King Snow Fall

<img src="https://i.postimg.cc/rpvhX8xt/screenshot-codepen-io-2020-12-26-19-43-06-210.png">
Day 3 of 100DaysOfCode: Python Program To Calculate Electric Bill
Tags: 100daysofcode, python, beginners, codenewbie
Published: 2020-12-26 14:37:08

This is my 3rd day of #100daysofcode. I learned alots of thing about python basis with the help of Goggle, youtube and Coursera.
Today I learned specially about looping, List, file handling, function etc. I also did some course of coursera in the topic python data structure. Here is a code  of mine which I used to calculate the amount of money purchasing for electric bill. In this code I used multiple if else statements for multiple conditions. There are different amount according to units consumed criteria. 
```python
# python program to calculate electric bill
units = int(input('Please enter the number of unit you consumed: '))
if(units < 50):
    amount = units * 2.60
    surcharge = 25
elif(units <= 100):
    amount = 130 + ((units - 50)*3.25)
    surcharge = 35
elif(units <= 200):
    amount = 130 + 162.50 + ((units - 100)* 5.26)
    surcharge = 45
else:
    amount = 130 + 162.50 + 526 + ((units - 200)*8.45)
    surcharge = 75
total = amount + surcharge 
print('\n Electricity Bill = %.2f' % total)
```
 <blockquote class="twitter-tweet"><p lang="en" dir="ltr"><a href="https://twitter.com/hashtag/100DaysOfCode?src=hash&amp;ref_src=twsrc%5Etfw">#100DaysOfCode</a> , day 3<br>* Learn about the python basis.<br>* Python code about the electric bill.<br>* Use of if and elif. <a href="https://t.co/VTIGj4XPzX">pic.twitter.com/VTIGj4XPzX</a></p>&mdash; Durga Pokharel (@mathdurga) <a href="https://twitter.com/mathdurga/status/1342832515082416131?ref_src=twsrc%5Etfw">December 26, 2020</a></blockquote> <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>