teleren/devto huggingface dataset:
Create a Simple Vue.js Login Form — an Example
Tags: vue, programming, webdev, beginners
Published: 2021-01-20 03:05:01

**Check out my books on Amazon at https://www.amazon.com/John-Au-Yeung/e/B08FT5NT62**

**Subscribe to my email list now at http://jauyeung.net/subscribe/**


Login forms are a part of most web apps.

We can create one easily.

In this article, we’ll look at how to create a login form with Vue and Express.

### Back End

We can create a simple login form that takes some data in the back end.

To do that, we create an Express app by installing some packages:

```
npm i express cors body-parser
```

Then we can use them by writing:

```
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors')
const app = express();
app.use(cors())
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.post('/login', (req, res) => {
  res.json(req.body);
});

app.listen(3000, () => console.log('server started'));
```

The `cors` package lets us do cross-domain communication.

We used it with `app.use(cors())` .

`bodyParser` parses the JSON request body that we’ll submit from the front end.

`bodyParser.json()` lets us parse JSON.

We also have a `login` route to get the request data.

`req.body` has the parsed JSON data.

We should add logic for user validation when we create a production app.

### Login Form Front End

We add the login form in our Vue app.

To do that, we can write:

```
<template>
  <div id="app">
    <form @submit.prevent="login">
      <input v-model="username" placeholder="username">
      <input v-model="password" placeholder="password" type="password">
      <input type="submit" value="log in">
    </form>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      username: "",
      password: ""
    };
  },
  methods: {
    async login() {
      const { username, password } = this;
      const res = await fetch(
        "https://SomberHandsomePhysics--five-nine.repl.co/login",
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json"
          },
          body: JSON.stringify({ username, password })
        }
      );
      const data = await res.json();
      console.log(data);
    }
  }
};
</script>
```

We created the login form in the template.

`v-model` binds the data to the reactive properties we initialized in the `data` method.

The input with type `submit` will trigger the submit event.

We listen to the `submit` event with `submit.prevent` to call `preventDefault` automatically.

This way, we can submit our login credentials with JavaScript.

Then in the `login` method, we called `fetch` to make a request to the `login` route we created.

The `method` property has the request method.

`headers` has the request headers. We need to set `Content-Type` to `application/json` so that we can submit JSON.

The `body` has the requests body.

Then we get back the response with `res.json()` .

When we type in something and click ‘log in’, we should get a response logged.

### Conclusion

We can create a simple login form with Vue and Express easily.
Code Smell 57 - Versioned Functions
Tags: codenewbie, codesmell, webdev, tutorial
Published: 2021-01-20 03:03:08

*sort, sortOld, sort20210117, workingSort, It is great to have them all. Just in case*

# Problems

- Readability

- Maintainability

# Solutions

1. Keep just one working version of your artefact (class, method, attribute).

2. Leave time control to your version control system.

# Sample Code

## Wrong

[Gist Url]: # (https://gist.github.com/mcsee/3b63bc3a76faf6e98c3770171f8e1c10)
```javascript
findMatch()
findMatch_new()
findMatch_newer()
findMatch_newest()
findMatch_version2()
findMatch_old()
findMatch_working()
findMatch_for_real()
findMatch_20200229()
findMatch_thisoneisnewer()
findMatch_themostnewestone()
findMatch_thisisit()
findMatch_thisisit_for_real()
```

## Right

[Gist Url]: # (https://gist.github.com/mcsee/1e3df98869010c8b9f37f1a76ff80c8b)
```javascript
findMatch()
```

# Detection

We can add automatic rules to find versioned methods with patterns.

Like many other patters we might create an internal policy and communicate.

# Tags

- Versioning
 
# Conclusion

Time and code evolution management is always present in software development. Luckily nowadays we have mature tools to address this problem.
 
# Relations

{% post https://dev.to/mcsee/code-smell-05-comment-abusers-2ba5 %}
 
# Credits

<span>Photo by <a href="https://unsplash.com/@k8_iv">K8</a> on <a href="https://unsplash.com/s/photos/onion">Unsplash</a></span>

Original idea

{% twitter 1341808635115151360 %}

* * *

> That's why I write, because life never works except in retrospect. You can't control life, at least you can control your version.

_Chuck Palahniuk_

{% post https://dev.to/mcsee/software-engineering-great-quotes-26ci %}

* * *

This article is part of the CodeSmell Series.

{% post https://dev.to/mcsee/how-to-find-the-stinky-parts-of-your-code-1dbc %}
tmux config
Published: 2021-01-20 02:41:29

```
tee -a ~/.tmux.conf <<EOF

setw -g mode-keys vi
set -g prefix C-a                                                                                                                 
unbind-key C-b
bind-key C-a send-prefix
EOF
```

in case of 'server version is too old for client' (after upgrade)

```
sudo kill -9 $(pgrep -f tmux)
```
Sass Intro
Tags: sass, css
Published: 2021-01-20 02:28:09

I recently came upon Sass ('Syntactically Awesome Style Sheets') which is CSS preprocessor that enables you to use things like variables, nested rules, and inline imports in addition to regular CSS. It is an organizational tool used for creating style sheets quicker. 

##Installation

With npm:

`$ npm install -g sass`

#Usage

There are two types of Syntax for Sass:

- SCSS (Sassy CSS): Uses the .scss file extension and is fully compliant with CSS syntax
- Indented (simply called 'Sass'): Uses .sass file extension and indentation rather than brackets; it is not fully compliant with CSS syntax, but it's quicker to write

**Variables**

For storing things like colors, font stacks, or any CSS value for reuse, Sass uses the $ symbol for declaring variables. For example, you can store a colour value variable at the top, and then use this variable when setting the colour of your elements for quick and easy colour changes:

**Sass**

```
$font-stack:    Helvetica, sans-serif
$primary-color: #333

body
  font: 100% $font-stack
  color: $primary-color
```

**CSS**
```
body {
  font: 100% Helvetica, sans-serif;
  color: #333;
}
```
 
**Nesting**

Sass allows nesting CSS selectors in a way that follows the same visual hierarchy of HTML. Here's an example of some typical navigation styles:

**Sass**
```
nav
  ul
    margin: 0
    padding: 0
    list-style: none

  li
    display: inline-block

  a
    display: block
    padding: 6px 12px
    text-decoration: none
```

**CSS**
```
nav ul {
  margin: 0;
  padding: 0;
  list-style: none;
}
nav li {
  display: inline-block;
}
nav a {
  display: block;
  padding: 6px 12px;
  text-decoration: none;
}
```

**Mixins**

Mixins simplify tedious CSS code. Group declarations for reusability and vendor prefixes, for example, are possible with mixins. An example of transform:

**Sass**
```
=transform($property)
  -webkit-transform: $property
  -ms-transform: $property
  transform: $property
.box
  +transform(rotate(30deg))
```

**CSS**
```
.box {
  -webkit-transform: rotate(30deg);
  -ms-transform: rotate(30deg);
  transform: rotate(30deg);
}
```

This is just a brief overview of Sass and its features. On the official [site](https://sass-lang.com/), you can read more documentation on things like partials and operators.

**References**

- https://sass-lang.com/
- https://www.creativebloq.com/web-design/what-is-sass-111517618
- https://github.com/sass/sass
Deploying a Rails App with React Frontend to Heroku
Tags: react, rails, heroku, deploy
Published: 2021-01-20 02:03:32

This is not an overview of deploying a Rails API/React application, built in two separate pieces, two separate repos, to Heroku. (Although I did write a series on the [topic](https://dev.to/lizlaffitte/series/10869).)

This is an overview of taking Rails application that uses Webpack to configure the frontend to use React and deploying it to Heroku.  (Which is how I'm building my [social media marketing app](https://dev.to/lizlaffitte/series/10870).) One repo, one app deployed, all the awesomeness.

If you've started your project by running:
```
rails new rails_react_app -d=postgresql --webpack=react
```
This overview is for you!

First you'll need to create a new app in your Heroku account, either via the CLI or the web app. Creating an app in the CLI will automatically create a git remote. You can push changes to this remote or set up automatic deploys via GitHub.

```
$ heroku create rails-react-app
``` 

From within the web app:
1. Login
2. New > Create New App: rails-react-app

To set up automatic deploys from GitHub:
1. Deployment Method > Connect to GitHub
2. Find your project GitHub repo
3. Pick the appropriate branch 
4. Enable Automatic deploys

So far, so good. At this point, we come to the main difference in deployment of separate Rails & React project repos: buildpacks!

You did not use `create-react-app` to build this project, so **do not need the create-react-app buildpack.**

You need to add the Heroku NodeJS and Ruby buildpacks. You can do so via the web app or the CLI.

Web App:
1. Select your project
2. Navigate to Settings
3. Scroll down to Buildpacks
4. Add buildpack: nodejs
5. Add buildpack: ruby

CLI: 
```
$ heroku buildpacks:set heroku/nodejs
$ heroku buildpacks:add --index 2 heroku/ruby
```

To make sure you've added them both successfully:
```
$ heroku buildpacks
```
*Note*, if you get the following errors when running heroku commands:
```
 ›   Error: Missing required flag:
 ›     -a, --app APP  app to run command against
 ›   See more help with --help
```

Make sure you're running the commands with the -a flag, followed by the name of your app on Heroku.

```
$ heroku buildpacks -a rails-react-app
```

Don't forget to migrate and seed your database!

```
$ heroku run rake db:migrate
$ heroku run rake db:seed
```
What's next?

<img width="100%" style="width:100%" src="https://media.giphy.com/media/l41Ykpd9588EBqZzi/giphy.gif"/>

You should be good to go! If you run into any errors, check your logs:
```
$ heroku logs -t
```

For me, I needed to upgrade my Ruby version to 2.6.6 to work with Heroku-18.
Supply vs Demand
Tags: serverless
Published: 2021-01-20 01:38:36

When running public service as a free-time effort, it is  critical to consider supply & demand as early on in the process as feasible.

For most folks:

* 'supply' is the resources you can sink into the service
* 'demand' is what the public wants out of this service

If you structure your service in such a way that demand immediately outstrips supply, you may have to quickly pivot in a manner that is disruptive to your users.

On the contrary, building a service that no one wants is a waste of your time entirely.

## Addressing demand

For the kernel café, I'll focus initially on solving the use cases where I've seen demonstrable demand by open-source developers:

* Access to mixed-architecture Kubernetes clusters
* Interactive access to arm64 (Linux, macOS)

To reduce demand, I am considering the following limitations:

* IPv6-only
* Public data only
* 1-hour CPU limit*
** Unprivileged access*

* Subject to contribution of time or money

## Addressing supply

Maintaining open infrastructure is incredibly time consuming, and potentially expensive.

### Time

CNCF Projects, such as [https://tinkerbell.org](Tinkerbell), make it substantially cheaper to work with physical infrastructure, by allowing it to be managed as cattle rather than pets. Treating the hosts as ephemeral, where they are reinstalled each reboot, goes a long way to addressing long-term maintainability of nodes. In situations where downtime is acceptable or encouraged, requiring that each node is rebooted on a schedule (weekly) also helps.

=== Money

Setting up a janky datacenter is not expensive, but does require capital outlay.

With my limited experience, the more worrying expense is that of power and cooling. Thankfully, both issues can be addressed by speccing out equipment that consumes no more power than necessary.

I intend to build the backbone of cluster with Raspberry Pi 4's, which seems to be unusually cost-effective, even if there are I/O performance limitations. They only consume ~4w at idle.

I have 4x RockPro64's that I can throw into the mix, but they are a bit more exotic for a build-out, and are limited to 8GB. Similar power consumption properties. Interactive users will likely use a Honeycomb LX2 for now.

For x86 support (a necessary evil for platforms like Fuschia), it is difficult to get similar power consumption numbers. Intel NUC's seem to enjoy the best balance of support and power consumption, even if AMD-based solutions trounce them in performance. Before I begin to acquire NUC's, I'll first need to collect data on consumption vs performance.

To be continued ...
Create a Bottom Drawer in Xamarin.Forms
Tags: xamarinforms
Published: 2021-01-20 01:30:33

A common pattern in mobile apps is to show a list of actions and contextual UI within a modal panel that slides up from the bottom of the screen, aka a bottom drawer. This video walks through creating a bottom drawer, a backdrop, and the gestures and animation code to create that UX.

{% youtube kd0fuWT2Xyg %}

### Resources:
* [Docs: Pan gesture](https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/gestures/pan)
* [Docs: Animations](https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/animation/)
* [Docs: Grid layout](https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/layouts/grid)

{% github davidortinau/xappy no-readme %}
JavaScript Fetch API
Published: 2021-01-20 00:48:13

The foundational languages of websites are HTML, CSS, and Javascript. 

If we were to compare a website to a house, then
HTML (Hypertext Markup Language) would be the concrete blocks making up the house and providing it with a stable structure.
CSS (Cascading Style Sheets) would be the color and molding of the house, enriching its space through eye-catching design.
And finally JAVASCRIPT would be the electrical wires of the house that bring it to life.

This post will focus on Javascript, and more specifically, the Javascript “FETCH API”

Before we begin, let’s take a slightly deeper look at Javascript.

Javascript is a programming language initially designed to interact with elements of web pages. When a web page is loaded, once the HTML and CSS have been downloaded, the Javascript in the web browser executes the JavaScript code. The JavaScript code then modifies the HTML and CSS to dynamically update the user interface. 

Ok so why is the FETCH API important? What does it do?

The fetch API is important because it allows us to make HTTP requests to servers from web browsers.

*How does it work?*

**WE START BY SENDING A REQUEST**
The fetch() method requires one parameter to work, which is the URL of the resource that you want to fetch.

**WE GET BACK A PROMISE**
The fetch method returns a Promise containing the response.

**WE HANDLE THE PROMISE**
You can use the then() and catch() methods to handle the promise

**THE RESOURCE IS AVAILABLE**
When the request completes, the resource is available and the Promise resolves into a Response object.

here is an example of a fetch request:
``` getTopics = () => fetch(this.root+"/topics").then(res => res.json())```
ลองเล่น Go Fiber web framework
Tags: go, programming
Published: 2021-01-20 00:40:38

[Fiber](https://gofiber.io/) เป็น Go web framework ที่บอกว่าได้แนวคิดแบบเดียวกันกับ Express framework ของทางฝั่ง Node.js และ ใช้ Fasthttp ซึ่งเป็น library จัดการ HTTP server ที่ไม่ใช่ standard `net/http` โดยเคลมว่าเป็น HTTP engine ที่เร็วที่สุดสำหรับ Go

เดี๋ยวจะลองเล่นดูสักเล็กน้อยแล้วทำความเข้าใจสไตล์การเขียนของมันดู

เริ่มจากสร้าง module ใหม่สำหรับ program เราก่อนเลย

```
$ mkdir try-go-fiber && cd try-go-fiber
$ go mod init "try-go-fiber"
```

ลองง่ายๆสมมติเป็น list posts API สำหรับ list ข้อมูลของ blog post ออกมา เราสามารถสร้าง router เพื่อ map path กับใส่ handler function เพื่อเขียนโค้ดให้ส่ง response กลับออกไปได้แบบนี้

```go
package main

import "github.com/gofiber/fiber/v2"

type PostID int

type Post struct {
	ID    PostID `json:"id"`
	Title string `json:"title"`
	Body  string `json:"body"`
}

var posts = map[PostID]Post{
	1: {
		ID:    1,
		Title: "ลองเล่น Fiber",
		Body:  "Fiber ใช่ง่ายๆเลยสำหรับคนเคยเล่น Express มา",
	},
	2: {
		ID:    2,
		Title: "สิ่งที่อยากทำในปี 2021",
		Body:  "อยากลดน้ำหนักให้น้อยกว่านี้",
	},
}

func main() {
	app := fiber.New()

	app.Get("/posts", func(c *fiber.Ctx) error {
		var result []Post
		for _, post := range posts {
			result = append(result, post)
		}
		return c.JSON(result)
	})

	app.Listen(":3000")
}
```

จะเห็นว่าวิธีใช้ก็คือเรียก function `fiber.New()` เพื่อสร้าง app ที่เป็นค่าที่เก็บ context ต่างๆของ application เรา

และเราจะเอามันไปเรียก method ในการกำหนด route ต่างๆเพื่อ map กับ handler จากตัวอย่างเราเรียก `app.Get("/posts", ...handler_function...)` คือกำหนดถ้าเรียกมาด้วย HTTP GET ที่ path `/posts` จะทำงานตาม handler function ที่เรากำหนด

ในตัวอย่าง handler function เราเขียนเป็น anonymous function โดยฟังก์ชันต้องรับค่า `c *fiber.Ctx` กับ return `error`
ตัว `*fiber.Ctx` คือค่าที่ Fiber จะส่งมาให้ handler เป็นค่าที่เราใช้ทั้งถึงข้อมูลที่มากับ request และส่งข้อมูล response กับไป

จากตัวอย่างผมเอาข้อมูลของ posts ตอบกลับไปเป็น JSON format ด้วย method `c.JSON` นั่นเอง

สุดท้ายเราต้องเรียก `app.Listen(":3000")` เพื่อให้ fiber เปิด HTTP server รอรับ request ที่ port 3000 นั่นเอง

ลองเรียก API endpoint นี้ของเราด้วย curl (แล้ว format ด้วย jq) จะเห็นผลลัพธ์แบบนี้

```
$ curl -s http://127.0.0.1:3000/posts | jq
[
  {
    "id": 1,
    "title": "ลองเล่น Fiber",
    "body": "Fiber ใช่ง่ายๆเลยสำหรับคนเคยเล่น Express มา"
  },
  {
    "id": 2,
    "title": "สิ่งที่อยากทำในปี 2021",
    "body": "อยากลดน้ำหนักให้น้อยกว่านี้"
  }
]
```

ซึ่งถ้าเราดูจากสไตล์การเขียน ก็ไม่ยากเท่าไหร่ ถ้าใครเคยใช้ Gin หรือ Echo framework มาก่อนก็แบบไม่ต่างกันเท่าไหร่เลย ที่เหลือก็คงเป็นเรื่องความเร็วที่เคลมว่าเร็วกว่าใครอยากลองเอาไปวัดดูจริงๆกับระบบตัวเองก็ลองย้ายมาเขียนแล้วเทียบกันดูได้เลย

<a href="https://www.buymeacoffee.com/weerasak" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 60px !important;width: 217px !important;" ></a>
Dreaming of a Kernel Cafe
Tags: kubernetes, unix
Published: 2021-01-20 00:35:36

Remember the 1990's? 

When folks blessed with bandwidth setup shell servers, and invited their friends to share in the bounty?

I just moved into a new house, and discovered that I was in this scenario again, for the first time in 20 years.

Today, open-source developers need bandwidth less than access to dev & test environments that differ from their own. What if I combined the two ideas together to create something new?

Thus was born the idea of the Kernel Cafe: Public Cloud Native Infrastructure, run by volunteers.

It's not yet clear to me whether this idea has legs, but you can follow along here to watch.
Pop-Up UI Design
Tags: codepen
Published: 2021-01-20 00:07:26

<p>Inspired by Ildiko Gaspar <a href="https://dribbble.com/shots/14963500-UI-Components-Design" target="_blank">https://dribbble.com/shots/14963500-UI-Components-Design</a></p>

{% codepen https://codepen.io/osmancandulger/pen/OJRqxKL %}
Media query for dark mode in css
Tags: css, darkmode, mediaquery
Published: 2021-01-20 12:28:46

---
title: Media query for dark mode in css
published: true
date: 2021-01-20 00:00:00 UTC
tags: css,darkmode,mediaquery
canonical_url: https://yogeshwaran.in/media-query-for-dark-mode-in-css/
---
![Dark mode css](https://dev-to-uploads.s3.amazonaws.com/i/og8cet9uqdbxanz0v1vy.png)

Its 2021 almost every android,ios and windows devices have the option to choose light/dark mode as their preferable mode. its nice to have dark/light mode in your websites. Fancy isn't it ?

### Media query for Dark mode

```
@media (prefers-color-scheme: dark) {
}
```

if your website theme is already have dark backrounds and light text. you can do it in reverse by adding light mode media query.

### Media query for Light mode

```
@media (prefers-color-scheme: light) {
}
```

If you are not using css variables or any preprocessors in your website. you need to overwrite most of the color for having it in dark/light mode.

### CSS Variables are handy

Using css variables it is easy to setup colors for dark/light mode in a simple way by replacing color variables in media query

```
:root {
  --background: #fff;
  --text-color: #323232;
}

// Dark mode
@media (prefers-color-scheme: dark) {
  :root {
    --background: #323232;
    --text-color: #fff;
  }
}
```

### Live example

Try switching dark and light mode in your device and see how the below page renders

<iframe height="361" style="width: 100%;" scrolling="no" title="Media query for dark mode" src="https://codepen.io/yoyo/embed/wvzOXzN?height=361&amp;theme-id=35149&amp;default-tab=html,result" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true">
  See the Pen <a href="https://codepen.io/yoyo/pen/wvzOXzN">Media query for dark mode</a> by yogeshwaran
  (<a href="https://codepen.io/yoyo">@yoyo</a>) on <a href="https://codepen.io">CodePen</a>.
</iframe>

Feel free to ask me in case of doubts. i am very much happy to help you.
How to Visualize Your SQLite Database with One Command (and Nothing to Install)
Tags: database
Published: 2021-01-19 23:15:25

---
title: How to Visualize Your SQLite Database with One Command (and Nothing to Install)
series: Document Your Database
published: true
description: Generate a diagram of your SQLite database with one command.
tags: database
//cover_image: https://direct_url_to_image.jpg
---

Ever wondered what the tables in your SQLite database look like, and how they are related to each other? Generate a diagram of your SQLite database with one command. You can run this on any system that has Docker installed. 

On a Linux system, run a command like:

```sh
docker run \
--mount type=bind,source="$(pwd)",target=/home/schcrwlr \
--rm -it \
schemacrawler/schemacrawler \
/opt/schemacrawler/bin/schemacrawler.sh \
--server=sqlite \
--database=chinook-database-2.0.1.sqlite \
--info-level=standard \
--command=schema \
--output-file=output.png
```

The command assumes that a SQLite database called ["chinook-database-2.0.1.sqlite"](https://github.com/schemacrawler/chinook-database/releases/download/v16.11.7/chinook-database-2.0.1.sqlite) is in your current directory. A file called ["output.png"](https://github.com/schemacrawler/chinook-database/blob/master/chinook_schema_diagram.png) will be generated with the database schema, including columns, data-types, and foreign key relationships. 

If you are using PowerShell on Windows, replace the trailing backslash on each line with a back-tick, and map the current directory differently. Run this command:

```powershell
docker run `
--mount type=bind,source="${PWD}",target=/home/schcrwlr `
--rm -it `
schemacrawler/schemacrawler `
/opt/schemacrawler/bin/schemacrawler.sh `
--server=sqlite `
--database=chinook-database-2.0.1.sqlite `
--info-level=standard `
--command=schema `
--output-file=output.png
```

You can generate PDF files, and other types of output too. Go through the [SchemaCrawler tutorials on Katacoda](https://www.katacoda.com/schemacrawler) to learn more SchemaCrawler commands.