teleren/devto huggingface dataset:
Structure project directories
Tags: go, gin
Published: 2021-06-24 16:57:44

It's always good practice to separate your code based on what every part is doing, so it's easier to find relevant part later on, so we will do just that before going further. In root project directory we will create new directories `cmd/rgb/` and we will move our `main.go` file there. That will be entry point for our app.
Also, we will create directories `internal/server/` and there add new file `server.go` where Gin server will be started. Function for starting server will be called from `main.go`. We will also move router setup to its own file `internal/server/router.go`. Let's look at our files now.

Content of `cmd/rgb/main.go`:

```go
package main

import "rgb/internal/server"

func main() {
  server.Start()
}
```

Content of `inernal/server/server.go`:

```go
package server

func Start() {
  router := setRouter()

  // Start listening and serving requests
  router.Run(":8080")
}
```

Content of `internal/server/router.go`:

```go
package server

import (
  "github.com/gin-gonic/gin"
)

func setRouter() *gin.Engine {
  // Creates default gin router with Logger and Recovery middleware already attached
  router := gin.Default()

  // Create API route group
  api := router.Group("/api")
  {
    // Add /hello GET route to router and define route handler function
    api.GET("/hello", func(ctx *gin.Context) {
      ctx.JSON(200, gin.H{"msg": "world"})
    })
  }

  router.NoRoute(func(ctx *gin.Context) { ctx.JSON(http.StatusNotFound, gin.H{}) })

  return router
}
```

Now our project directories looks like on picture below.

![Structured project directories](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hdimxcn9fl88qbv93ra2.png)
Starting Gin server
Tags: go, gin
Published: 2021-06-24 16:44:06

First we need to give our Web App a name. We will be making a simple blog, so let's call it RGB (React Gin Blog).

We will start by making project root directory inside of `~/go/src` and making it our current working directory.

```bash
cd ~/go/src
mkdir rgb
cd rgb
```

Our first dependency is Gin framework. You can download it by running `go get github.com/gin-gonic/gin` if you don't have it already.
Before writing our first backend source file, we need to crate `go.mod` file in project root directory needed by Golang to find and import required dependencies. Content of that file will for now be:

```mod
module rgb

go 1.16

require github.com/gin-gonic/gin v1.6.3
```

Now let's make our app entry point, `main.go` file:

```go
package main

import (
  "github.com/gin-gonic/gin"
)

func main() {
  // Creates default gin router with Logger and Recovery middleware already attached
  router := gin.Default()

  // Create API route group
  api := router.Group("/api")
  {
    // Add /hello GET route to router and define route handler function
    api.GET("/hello", func(ctx *gin.Context) {
      ctx.JSON(200, gin.H{"msg": "world"})
    })
  }

  router.NoRoute(func(ctx *gin.Context) { ctx.JSON(http.StatusNotFound, gin.H{}) })

  // Start listening and serving requests
  router.Run(":8080")
}
```

And that's it. We can now start our server by running:

```bash
go run main.go
```

Verify that server is running by opening `localhost:8080/api/hello` in your favorite web browser. If server is working you will see `{"msg":"world"}`.
CSS-фреймворк, о котором вы даже не подозревали Tachyons.io
Tags: css, tachyons
Published: 2021-06-24 16:43:57

#tachyons.io Функциональный CSS для людей.

Быстро создавайте и разрабатывайте новый интерфейс без написания CSS.
##Принципы

*Все должно быть на 100% отзывчивым*
*Все должно быть доступно для чтения на любом устройстве*
Все должно быть максимально быстро*
Создание дизайна в браузере должно быть простым*
Должно быть легко изменить любой интерфейс или часть интерфейса, не нарушая никаких существующих интерфейсов.
Очень хорошее выполнение одной задачи способствует повторному использованию и сокращает повторение
Документация способствует повторному использованию и обмену знаниями
CSS не должен препятствовать доступности или функциональности HTML по умолчанию.
Вы должны отправить пользователю минимально возможное количество кода.
##Функции
Архитектура CSS, ориентированная на мобильные устройства
490 доступных цветовых комбинаций
Базовая сетка 8 пикселей
Несколько утилит отладки для уменьшения проблем с компоновкой
Целевая структура класса
Оптимизирован для максимального сжатия gzip
Легкий (~ 14 КБ)
Может использоваться в разных проектах
Растущая библиотека компонентов с открытым исходным кодом
Хорошо работает с обычным HTML, React, Ember, Angular, Rails и другими.
Бесконечно вложенная адаптивная сеточная система
Построен с PostCSS

Документы можно найти на: [TACHYONS.IO](http://tachyons.io/docs) . Модули, как правило, довольно маленькие, поэтому их легко и быстро читать.
###Используйте CDN
Самый быстрый и простой способ начать использовать тахионы - это включить ссылку на минифицированный файл в заголовок вашего HTML-файла.

###< link  rel = " stylesheet " href = " https://unpkg.com/tachyons@4/css/tachyons.min.css " >
Web app development guide using Golang, Gin and React
Tags: go, gin, react, docker
Published: 2021-06-24 16:43:25

This guide will show you how to build full stack Web App from scratch using Go programming language, with Gin and React frameworks.

**Go** (or sometimes called **GoLang**) is an open source programming language developed by Google. More info, as well as download link can be found on [official web page](https://golang.org/).

**Gin** is lightweight but high-performance web framework with support for most essential features and functionalities required for modern web applications. Check [Gin GitHub](https://github.com/gin-gonic/gin) for more information, documentation and installation guide.

**React** is JavaScript framework developed by Facebook. It's one of the most commonly used solutions today for writing frontend part of Web Apps. Additional information can be found [here](https://reactjs.org/).

**Bootstrap** is the most popular CSS framework and we will use it to add styles to our React components. You can learn more about Bootstrap on their [official webpage](https://getbootstrap.com/).

**PostgreSQL** is a database we will be using for storage. You can check their [home page](https://www.postgresql.org/) to find out more.

So now that we listed all we need, let's start with building our Web App.
Data Structures in TypeScript - Queue
Tags: datastructures, typescript, queue
Published: 2021-06-24 16:23:51

---
title: Data Structures in TypeScript - Queue
published: true
description: Queues can be used whenever is necessary to process things in a first-in-first-out order, also helps in algorithms of other data structures.
tags: dataStructures,typescript,queue
series: Data Structures in TypeScript
canonical_url: https://ricardoborges.dev/data-structures-in-typescript-queue
cover_image: https://res.cloudinary.com/dje4crtui/image/upload/v1626974055/articles%20covers/cover_wnn3mp.png
---

A queue uses FIFO (first-in-first-out) ordering, that is, items are removed from the queue in the same order that they are added, like a line.
Queues can be used whenever is necessary to process things in that order (FIFO), like requests to a single shared resource, CPU scheduling, also helps in algorithms of other data structures, such as breadth-first search in graphs.

![queue](https://res.cloudinary.com/dje4crtui/image/upload/v1622906544/data%20structures/queue_dw6rf8.png)

### Representation

A queue can be implemented using an array or a linked list, can be either fixed or dynamic size.

### Basic operations

- **Add** - Add an item to the end of the queue, also called enqueue.
- **Remove** - Remove the first item from the queue, also called dequeue.
- **Peek** - Return the top of the queue, without removing it.
- **isEmpty** - Return true if the queue is empty.
- **isFull** - Return true if the stack is full, used when the queue is fixed size.

Here's an implementation of a queue using an array, in TypeScript an array doesn't have a fixed length, so the operation **isFull** is not required, however, you can implement a queue with a fixed length and use that operation.

```typescript
class Queue<T> {
  private array: T[] = [];

  add(data: T): void {
    this.array.push(data);
  }

  remove(): T | undefined {
    if (this.isEmpty()) throw new EmptyQueueException();

    return this.array.shift();
  }

  peek(): T {
    if (this.isEmpty()) throw new EmptyQueueException();

    return this.array[0];
  }

  isEmpty(): boolean {
    return this.array.length === 0;
  }
}
```
Sudoku in React
Tags: react, sudoku, algorithms
Published: 2021-06-24 16:21:25

Developed a Sudoku implementation in Javascript. 

[Launch App](https://sudoku.ioblitz.com)

##Anatomy
Front end - Reactjs on bootstrap
Back end - None
Hosted - Firebase
Open Source - [Github Repo](https://github.com/blackarck/sudokujs)


The application generates a random sudoku app in easy, medium & hard mode. The app has an about page which showcase the thought behind algorithm. 
Its a non recursive algorithm using back tracking. UI took the most time in generating the app.
How to count html tags in a web page by using web url
Tags: ruby, webdev, showdev, rails
Published: 2021-06-24 16:18:57

* Create new rails app

* Install following Gems
```ruby
gem 'nokogiri'
gem 'open-uri'
```

* Script
```ruby
begin
  @doc = Nokogiri::HTML(URI.open(params[:page][:url]).read)
  @summary = @doc.xpath("//*").map(&:name).each_with_object({}) {|n, r| r[n] = (r[n] || 0) + 1 }
rescue Exception => e
  puts "Couldn't read \"#{ params[:page][:url] }\": #{ e }"
end
```

* View
```ruby
<% @summary.each do |tag, count| %>
  <div>
    <%= tag %>: <%= count %>
  </div>
<% end %>
```

Github Repo: [rails-UrltoHtml](https://github.com/MA-Ahmad/rails-urltohtml)
Demo Link: [rails-UrltoHtml](https://urltohtmlapp.herokuapp.com/)
Web Scraping Online | Instantly Scrap Multiple Pages With Scraping
Published: 2021-06-24 16:14:40

Web scraping refers to the process of crawling or spidering a website or multiple websites systematically and then extracting relevant data usually not intended for consumption by software programs. The difficulty comes in the fact that the web is haphazard, designed originally for humans, varied in implementation, and then the relevant data is not defined semantically.

https://youtu.be/Ga87B3HA19E
Learn Elixir the language behind Whatsapp,Telegram, Discord and Pinterest
Tags: elixir, erlang, distributedsystems, javascript
Published: 2021-06-24 16:07:56

**Elixir** is a dynamic, functional language for building scalable and maintainable applications.
> Elixir leverages the Erlang VM, known for running low-latency, distributed, and fault-tolerant systems. Elixir is successfully used in web development, embedded software, data ingestion, and multimedia processing, across a wide range of industries. Here is a peek:

### Performance feature's of elixir:

#### Scalability
  * All Elixir code runs inside lightweight threads of execution 
(called processes) that are isolated and exchange information 
via messages

#### Erlang compatible
  * Elixir runs on the Erlang VM giving developers complete access to Erlang's ecosystem, used by companies like Heroku, WhatsApp, Klarna and many more to build distributed, fault-tolerant applications

#### Fault-tolerance
 * To cope with failures, Elixir provides supervisors which describe how to restart parts of your system when things go awry, going back to a known initial state that is guaranteed to work

> If you haven’t yet installed Elixir, visit [installation page](https://elixir-lang.org/install.html). Once you are done, you can run `elixir --version` to get the current Elixir version.

let’s start by running `iex`  means interactive elixir
###### some basic code
``` 
iex(1)> 40 + 2
42

iex(2)> "hello" <> " world"
"hello world"

iex> String.length("The quick brown fox jumps over the lazy dog")
43
```
###### Support for binary, octal, and hexadecimal numbers comes built in:

```
iex> 0b0110
6
iex> 0o644
420
iex> 0x1F
31
```
###### ATOMS
```
iex> :apple
:apple
iex> :orange
:orange
iex> :apple == :apple
true
iex> :apple == :orange
false
iex> true == :true
true
```
######You can print a string using the `IO.puts/1` function from the IO module

```
iex> IO.puts("hello\nworld")
hello
world
:ok
```
> `IO.puts/1` function returns the atom :ok after printing.

#### In next Article we will go more deep into Elixir Laguage.
Using Canvas in vanilla JavaScript
Tags: javascript
Published: 2021-06-24 16:04:41

##What is Canvas?
Canvas is HTML element which you could draw graphic or use it to create some fancy animations.

##Setup Canvas
In order to setup a canvas in vanilla JavaScript, you need to add <code>canvas</code> element on HTML file. 
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2g46iok5xr6897y4osh5.png)
and then using <code>querySelector</code> to select the element, and setup the size of your canvas and chose the dimensional of context you are going to use, below I using two-dimensional drawing context
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9odjdqo54365a6mnevmh.png)

##Basic Shape 
#####1. Line
We need <code>beginPath()</code> to set a new path and using <code>MoveTo()</code> to create a sub-path of beginning of line and <code>LineTo()</code> to create a sub-path of ending of line. The <code>strokeStyle() </code> is color of line, the <code>stroke() </code> to drawing the line 
 
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a5tekxjf41e3om3bgt5a.png) 
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nnjkwoerbo3ni9pdt5n0.png)
 
#####2. Circle
Similarly, in order to drawing a circle on Canvas, we need <code>beginPath()</code> to set a new path, then using the <code>arc()</code> to create circular arc which require 6 parameters, 1st parameters is x-axis of arc's center, 2nd parameters is y-axis of arc's center, 3rd parameters is radius, 4th parameters is start angle, 5th parameters is end angle (below Math.PI *2 = 360°), the last parameters is determining if drawing the arc counter-clockwise between the start and end angles. The The <code>strokeStyle()</code> is outline color of circle , the <code>stroke() </code> to drawing outline of circle

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kabs9jhp0pwhrmnoejec.png)
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/atc027qqhral8n14d4w5.png)
 
#####3. Rectangle
The <code>fillStyle()</code> to set to set the color of rectangle and The <code>fillRect()</code> to create a rectangle 

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/riy84i9pvc7lc2z8szrs.png)
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0iq94le3f94w4tvnwz79.png)
 
***Reference:*** 
[Line](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineTo) [Circle](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/arc) [Rectangle](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/arc) [More](https://www.w3schools.com/html/html5_canvas.asp)
UI, UX Guide
Tags: ux, webdev
Published: 2021-06-24 15:31:43

##User Interface (UI) Key Points-     
Colors
Typography
Visual Design Elements

>3 C's of Interface Design- 

Color - Contrast - Content

##User Experience (UX) Key Points-
Task Flows
Scenarios

Example- 
**Car (UX) & Color (UI) of Car**

Popular UI Design Language-

>Minimalist - Less is More

[Material](https://material.io/design)- Google's Design Language.

#Guide-
##Accessibility - 
Accessibility in design allows users of diverse abilities to navigate, understand and use your UI.

Tips-
* Clear Layouts.
* Suitable for variety of users (doesn't mean different devices).
* Assistive tech support like YouTube Voice Search is very popular, Screen Reader used on Govt. Websites.
* Common action center like Button in Google apps to perform multiple actions, in Facebook Search apart from People, Pages you can search Settings and other functionalities as well.  

>Focus on the user and all else will follow.

##Design - 
> What is beautiful is usable.
>Consistency is the key  -- Zak Frazer

For making a product look more consistent the developer should master **Principle of least surprise**

##Device Compatibility and Optimization -
The product must be cross-platform available and optimized for different devices as well.
*Responsive Web Design with proper media queries.
*Responsive frameworks like Tailwind, Bootstrap.

##User Flow -
Some minor tweaks might get the user a better experience like Search Box, Navigation Menu, Proper Categorization.
>Initial/ Default Item.

Most frequently selected or Last item selected by user can be set as an initial/default item.

>Recognize instead of Recall.

Instead of writing or searching something user can quickly select from the options.

* Reconfirmation and Undo Options will help users take better acknowledged actions.


##Performance - 
The product developed should be fast and efficient. It should not take much time and resources. If the page loads up slowly the user might lose interest, so good performance is an important aspect.
ASP.NET Core Identity User Locked out
Tags: dotnet, identity, auth
Published: 2021-06-24 15:20:39



The user lockout feature is the way to improve application security by locking out a user that enters a password incorrectly several times. This technique can help us in protecting against brute force attacks, where an attacker repeatedly tries to guess a password. ⛳ 

Quite a basic feature for an authentication service, but adding it in my Web API app was quite a head scratcher.

#### 1. Adding to configuration service

In your startup.cs or container configuration file,   the config for locking out can be  set.


```
services.AddIdentity<User, IdentityRole>(opt =>
{
    // previous code removed for clarity reasons
    opt.Lockout.AllowedForNewUsers = true;
    opt.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(2);
    opt.Lockout.MaxFailedAccessAttempts = 3;
})
```
The property names are self explanatory here.

The  above code will  by default setup locking out feature and if a person is trying to login with wrong `password` for a given `username` the user account will be locked out for 5 minutes updated accordingly in `LockoutEnd` column 

#### 2. How to check if this user is Locked Out?

```
//  AuthService.cs
..
    var result = await signInManager.CheckPasswordSignInAsync(user, model.Password, lockoutOnFailure: true);
..
```
The properties  of `result : SignInResult` we are concerned here are `Succeeded`, `IsLockedOut`.

✅ `Succeeded ==  true` if the username and password **match**

❌ `Succeeded == false` if the username and password **do not match**

✅ `IsLockedOut == true` if this user has been locked out after x number of trials

#### 3. 🤔 What is here to scratch your hear for

I was expecting `LockOutEnabled` will become `true (1)` in the identity user table. It took me few hours to get to the documentation but it was stated clearly in the Library class.

```
// Microsoft.AspNetCore.Identity.IdentityUser
      
// Gets or sets a flag indicating if the user could be locked out.

public virtual bool LockoutEnabled { get; set; }
```

I missed the **could be**  and  it costed me some hours.😪

Updating this column to `true` for necessary users then locks out the user for particular a time limit set in the `config`

The proper logging and an error can be thrown with 
`result.IsLockedOut` flag from the service layer 😅

📚 References
1. Using  [UserManager.CheckPasswordAsync versus SignInManager.PasswordSignInAsync](https://stackoverflow.com/questions/53854051/usermanager-checkpasswordasync-vs-signinmanager-passwordsigninasync
)

2. [User Lockout with ASP.NET Core Identity](https://code-maze.com/user-lockout-aspnet-core-identity/)
Loading dotENV files with Deno
Tags: javascript, tools, deno
Published: 2021-09-09 20:38:43

---
title: Loading dotENV files with Deno
published: true
date: 2021-06-24 15:19:52 UTC
tags: javascript,tools,deno
canonical_url: https://hyper-io.medium.com/loading-dotenv-files-with-deno-d53594c99395
---

Deno is a server runtime for javascript and typescript, it serves the same function as NodeJS, but different implementation. Deno strives to closely model the implementation of the browser version of javascript for better compatibility.

#### dotenv

One of the handiest modules in the NodeJS ecosystem is the dotenv module. With this module you can create a .env file and place your environment variables for your application, then you can load them into your application using a require('dotenv').config() function. In Deno, we do not have require, and Deno handles the loading of environment variables differently.

#### Deno.env

With Deno, you call, instead of the NodeJS way of process.env being a simple object. The Deno.env is not a plain object. You can access the values using the get method.

#### dotenv for Deno

There is a dotenv for Deno, that is even easier to use than dotenv of NodeJS.

create your .env

```
GREETING=Hello
```

import the load.ts module from the dotenv package

```
import "https://deno.land/x/dotenv/load.ts";

console.log(Deno.env.get('GREETING'));
```

And now you can access your config information from a .env just like you would access environment variables in Deno.

#### Summary

Deno has some different updated technology that still takes getting used to, but many libraries that we use in NodeJS have alternate libraries in Deno now and can serve the same purposes. Check out the Deno Third Party ecosystem for these implementations.

[Deno — A secure runtime for JavaScript and TypeScript](https://deno.land/x)

[Deno is a simple, modern and secure runtime for JavaScript and TypeScript that uses V8 and is built in Rust.](https://deno.land/x)

![](https://cdn-images-1.medium.com/max/180/0*DeClwCx2x94Q5WJo.png)

[DenoLand](https://deno.land/x)

![](https://cdn-images-1.medium.com/max/512/0*R5m0fA4HnlVErwob.png)

#### About hyper

hyper is a service framework built using Deno, check hyper out at [https://hyper.io](https://hyper.io) learn how you can build scalable applications using hyper.
I built a Hugo template with WindiCSS
Tags: hugo, windicss, showdev
Published: 2021-06-24 15:00:26

Link: https://github.com/pontakornth/hugo-with-windicss

## How did I build it?

Hugo actually has some assets processing features such as SCSS and PostCSS. WindiCSS is also available as PostCSS module but the author said that it should be the [last resort](https://github.com/windicss/postcss-windicss).

NPM script can actually run other command as well. I can use it to run `hugo` command. The problem is CSS need to be generated along with Hugo dev server for good developer experience (DX).

## npm-run-all comes to rescue

I don't really remember where I know `npm-run-all` in the first place. It is a package that allow you to run command in parallel or sequence. It is possible to run multiple command using && in Unix-based system. However, it is not supported on Windows CMD.

## WindiCSS config

If you read the config files, you will see `extract` field. It is a field that allow WindiCSS to include and exclude files from building. This feature allow WindiCSS to generate enough CSS to display things correctly but no additional unused CSS.


I don't include anything besides basic template so you can build on your own without having to modify the theme or rebuild from scratch. I hope you enjoy building your site.