teleren/devto huggingface dataset:
Writing Go with Github Copilot
Tags: github, go, programming, webdev
Published: 2021-08-03 17:19:06

## Intro 

I've been using Github Copilot a lot recently. In fact, my latest project, [redisql](https://github.com/DGKSK8LIFE/redisql), was written partially with suggested code snippets. In this post, I'll illustrate its power with various examples.

## Examples

We'll start with simple arithmetic, then advance to web servers and SQL transactions.

### Math

```go
// Write a function that returns the square of the number.
func square(a int) int {
	return a * a
}
```

Now for something more advanced:
```go
// Write a function that multiples two two-dimensional arrays together and returns the result.
func multiply(a [][]int, b [][]int) [][]int {
	result := make([][]int, len(a))
	for i := range result {
		result[i] = make([]int, len(a[i]))
		for j := range result[i] {
			result[i][j] = a[i][j] * b[i][j]
		}
	}
	return result
}
```

### Web

```go
// Write an http server which returns 'hello world' for any request.
package main

import (
	"fmt"
	"net/http"
)

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintln(w, "hello world")
	})
	http.ListenAndServe(":8080", nil)
}
```

At this point I attempted requesting html rendering with user data. Needless to say, copilot crushed it, even commenting in instructions on how to run the program:
```go
// Write an http web server that returns an html header that shows the user's IP address and the time.
// Usage:
// go run examples/web/httpserverwithhtml.go
package main

import (
	"fmt"
	"net/http"
	"time"
)

func main() {
	http.HandleFunc("/", handler)
	http.ListenAndServe(":8080", nil)
}

func handler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	fmt.Fprintf(w, "<html><body><h1>Your IP is %s. The time is %s</h1></body></html>",
		r.RemoteAddr, time.Now().Format(time.RFC1123))
}
```

I attempted requesting something even more advanced: a WebSocket server that echoes whatever is sent to it with HTML input. Sadly, copilot couldn't handle this task, and suggested incomplete code. Over time, with more training, this may be possible.

### SQL 

```go
// Write a program that opens a MySQL server connection and executes a query on a user table and prints the results.
package main

import (
	"database/sql"
	"fmt"
	"log"

	_ "github.com/go-sql-driver/mysql"
)

func main() {
	// Open a connection to the MySQL server
	db, err := sql.Open("mysql", "user:password@tcp(127.0.0.1:3306)/test")
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	// Execute a query
	rows, err := db.Query("SELECT * FROM user")
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()

	// Loop through the rows and print the results
	for rows.Next() {
		var id int
		var name string
		if err := rows.Scan(&id, &name); err != nil {
			log.Fatal(err)
		}
		fmt.Println(id, name)
	}
}
```

## Conclusion

Copilot is extremely helpful. The snippets are only basic examples of its capacity, I am actively posting more in [go-copilot](https://github.com/DGKSK8LIFE/go-copilot).
Redirecting GitHub Pages
Tags: github, markdown, jekyll, redirection
Published: 2021-08-03 17:14:50

---
title: Redirecting GitHub Pages
published: true
description: A simple way to redirect GitHub markdown pages to another document is a simple HTML template
tags: GitHub, markdown, jekyll, redirection
canonical_url: https://christianheilmann.com/2021/08/03/redirecting-github-pages/
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gwo67oed7tjuhyeok49u.jpeg
---
 
Today I finished moving the [Edge Tools for VS Code extension](https://aka.ms/devtools-for-code) documentation to its [official space in the Microsoft docs](https://docs.microsoft.com/en-us/microsoft-edge/visual-studio-code/microsoft-edge-devtools-extension). That meant I needed to redirect the documentation I hosted with GitHub pages in a docs folder/branch of the [repository](https://github.com/microsoft/vscode-edge-devtools).

There are plugins available for that, but I didn't want to install any extra features on the repository, so I chose a simpler approach. 

You can define HTML templates for your GitHub pages in a folder called `_layouts` and connect them using the Markdown frontmatter. So if you create a file called `test.md` you can define a template called `forward`. You can also add a `target` to redirect to, in this case `https://example.com`

test.md:

```markdown
---
layout: forward
target: https://example.com
---
... rest of your markdown ... 
```

Your `forward.html` template in the `_layouts` folder can use a meta redirect to the target. In its most basic form this can be:

forward.html: 

```html
<html lang="en">
<head>
    <meta charset="utf-8"/>
    <meta http-equiv="refresh" content="0;url={{ page.target }}"/>
    <link rel="canonical" href="{{ page.target }}"/>
    <title>Redirecting</title>
</head>
<body>
    <p>Document has moved, if you aren't automatically redirected 
    <a href="{{ page.target }}">go here</a>.</p>
</body>
</html>
```

That means that if someone goes to the test document in your GitHub pages, they will get redirected to example.com

You can see this in action [in this GitHub demo repo](https://github.com/codepo8/github-redirection-demo/) I quickly put together. I've added quite a few more options to redirect, such as definition of the time and displaying different titles and text. You can read it all and [try out the demos in the README](https://codepo8.github.io/github-redirection-demo/).
My very first post to test React Blog
Published: 2021-08-03 17:09:17

I followed this youtube playlist to build my very first post to have React blog: 

#Issue 1: 
The first issue happened at Live #2. I am supposed to obtain id of the post, but I don't see the link of id anywhere. It is resolve by adding colon before id because the syntax mattered.
`<Route exact path="/posts/:id">` is correct.
JVM Testing Newsletter | July 2021
Tags: java, kotlin, android, testing
Published: 2021-08-03 17:09:00


> What's new in JVM testing? Check July 2021 issue.

## Articles & blogposts

### Hidden Perks of Unit Tests

https://www.egorand.dev/hidden-perks-of-unit-tests/

### Where to write Android UI Tests (two articles)

https://proandroiddev.com/where-to-write-android-ui-tests-part-1-92cc9bf98c03
https://proandroiddev.com/where-to-write-android-ui-tests-part-2-cb45033f3ddf


### Hibernate Traps: @Transactional Integration Tests
https://www.kode-krunch.com/2021/07/hibernate-traps-transactional.html?m=1

### JUnit Coroutines Runner
https://krossovochkin.com/posts/2021_07_10_junit_coroutines_runner/

### Why I'm switching from Mockito to MockK
https://www.ericthecoder.com/2021/07/20/why-im-switching-from-mockito-to-mockk/

### Don't mock static: test SLF4J Logger with appenders

https://kotlintesting.com/mock-slf4j/

## Podcasts & videos
### Android Developers Backstage Podcast | Episode 169
In this episode, Romain and Tor are joined by Adarsh Fernando, Arif Sukoco and Yahan Zhou from the Android Studio team, covering the recent improvements to support for testing. This includes automated test snapshots, where the emulator captures a snapshot for a failing test you can then load and analyze later, it includes the Test Matrix tool where the IDE shows a matrix of tests and the devices they're running on, as well as a unified Gradle test runner, and Gradle managed virtual devices, and more.

https://adbackstage.libsyn.com/episode-169-testing

### TDD Conference - talk recordings
https://www.youtube.com/watch?v=-_noEVCR__I


## Libraries & releases
- [junit-pioneer](https://github.com/junit-pioneer/junit-pioneer)
- [turbine release 0.6.0](https://github.com/cashapp/turbine/releases/tag/0.6.0)


> Originally published at [KotlinTesting.com](https://kotlintesting.com/tag/newsletter/)
Kubernetes Hardening Guidance
Tags: kubernetes, security, devops, cloudnative
Published: 2021-08-03 17:00:22

### NSA, CISA release Kubernetes Hardening Guidance

The National Security Agency (NSA) and the Cybersecurity and Infrastructure Security Agency (CISA) released a Cybersecurity Technical Report, “Kubernetes Hardening Guidance,” today. This report details threats to Kubernetes environments and provides configuration guidance to minimize risk. 

For more guidance you can [continue reading here...](https://www.google.com)
Ordenar un arreglo de objetos en Javascript.
Tags: javascript, sort, array, object
Published: 2021-08-03 16:58:29

Lo que vamos a realizar es ordenar un arreglo de objetos por sus propiedades **nombre** (string) y **edad** (number).
El arreglo es el siguiente:

```javascript
let users = [
  {
    nombre: "Rakan",
    edad: "24",
    correo: "algo@gmail.com"
  },
  {
    nombre: "Ashe",
    edad: "47",
    correo: "algo@zoho.com"
  },
  {
    nombre: "Ziggs",
    edad: "30",
    correo: "algo@yahoo.com"
  },
  {
    nombre: "Akali",
    edad: "30",
    correo: "algo@yahoo.com"
  },
  {
    nombre: "Veigar",
    edad: "30",
    correo: "algo@yahoo.com"
  }
];
```
- En el siguiente codigo lo que hacemos es ordenar los elementos de menor a mayor por **edad(number)** con el metodo **sort(callback)** el cual recibe una callback, que es la funcion de comparacion.

ordenar de mayor a menor ------> **<**

ordenar de menor a mayor ------> **>**

```javascript
let edad = users.sort((a, b) => {
  return a.edad > b.edad;
});
console.log(edad);

```
El resultado es el siguiente:
![Imagen 1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/38hgmq927yc65ourkpv1.png)

- y para ordenar por **nombre(string)** es practicamente igual solo que cambiamos el valor

```javascript
let edad = users.sort((a, b) => {
  return a.nombre > b.nombre;
});
console.log(edad);
```

![img-2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/amst1fxr0iqwi182oumr.png)
Testers needed for self developed account analyzer
Tags: python, datascience, analytics
Published: 2021-08-03 16:49:48

I have written a program, which reads-in csv-bank data and categorizes the account transactions according to your needs. The results are shown in several charts (png-files) and in a locally hosted dashboard. I've used a GTK-GUI to enable interaction. Help me to fix the last bugs through testing the software. See my codeberg-profile (https://codeberg.org/codade/KYSA) for more info.
I appreciate every feedback!
Thanks in advance!
The Developer Journey Map
Tags: devrel
Published: 2021-08-03 16:42:39

Perhaps no other tool or framework went through as many revisions as The Developer Journey Map during the development of the book. It’s our most ambitious framework, as it seeks to document the end-to-end life cycle of a developer interacting with your DevRel program. Consequently, in the book, there are six chapters totaling over 15,000 words dedicated to exploring The Developer Journey Map. This post can only scratch the surface of this topic, but will hopefully serve as a useful introduction to the concept.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e6vnv6602z7ejvsxhn1x.png)
Like a customer journey, The Developer Journey Map is a visualization that identifies the path a developer follows and experiences. As they move left to right across the stages, their level of interaction increases with your brand, team, and product. It’s one of the most valuable tools in DevRel in that it helps you to think holistically about the experience from the developers’ perspective while providing a very practical guide for you.

Your goal with the map is to progress your developer from left to right as quickly as possible to increase product adoption and revenue potential.

The fives stages of the map (Discover, Evaluate, Learn, Build, Scale) indicate significant changes in the developer’s intent and actions. They do not imply elapsed time. 

See more about the Developer Journey: https://lnkd.in/dfNmFrC


As always - all comments appreciated!
Back to Basics: SOLID Principles (Part 1)
Tags: python, beginners
Published: 2021-08-03 16:41:02

SOLID is an acronym for the 5 programming principles which stands for:

- **S**ingle Responsibility Principle
- **O**pen Closed Principle 
- **L**iskov Substitution Principle
- **I**nterface Segregation Principle
- **D**ependency Inversion Principle

Why should you care about these principles you ask?

These principles help you in changing one area of the software without impacting others. Basically, they’re intended to make the code easier to understand, maintain, and extend.

This post is just Part 1 of the series, Back to Basics, each covering one SOLID principle.

--------------------------------------------

## Single Responsibility Principle

A class should have one and only one reason to change which means it should only have one job.


If a class has more than one responsibility then changing one responsibility results in modifications in other responsibilities.

Let's take an example:

```python

class Animal:
	def __init__(self, name):
		self.name = name

	def get_name(self):
		return self.name

	def save(self, animal):
		"""Saves the animal details to DB"""
		pass

```

Now the Animal class has two responsibilities:
1. Maintain the properties of the animal
2. Save the animal details in a database

If the application changes in a way that it affects the database management functions, for example: save() function, then the classes that use the properties of the Animal class will have to be updated and recompiled.

Solution?

We create another class which will handle all the database management responsibilities.

```python

class AnimalDB:
	def save(self, animal):
		"""Saves the animal details to DB"""
		pass
	
	def get_animal(self, _id):
		"""Gets the animal details by _id from the DB"""
		pass

class Animal:
	def __init__(self, name):
		self.name = name
		self._db = AnimalDB()

	def get_name(self):
		"""Get animal name"""
		return self.name

	def save(self):
		"""Saves the animal to DB"""
		self._db.save(animal=self)


```

At the time of designing our classes, we should always put related features together so whenever they tend to change they change for the same reason and try to separate the features that will change for different reasons.
What is Git ?
Published: 2021-08-03 16:38:55

Git is the most commonly used version control system. 
It is used for coordinating work among programmers collaboratively developing source code during software or 
website development.
It was developed by  Linus Torvalds in 2005 for development of the Linux kernel.
Git is free and open-source software distributed under GNU General Public License Version 2.
-----------------------------------------------------------
# We can create account on git free
# Create repository as public or private
# Host our project
# Backup Our project
save username and password in Git?
Published: 2021-08-03 16:37:53

This method saves the credentials in plaintext on your PC's disk. Everyone on your computer can access it, e.g. malicious NPM modules.
1- run in terminal
`git config --global credential.helper store`
2- then
`get pull`

provide a username and password and those details will then be remembered later. The credentials are stored in a file on the disk, with the disk permissions of "just user readable/writable" but still in plaintext.

If you want to change the password later

`git pull`

Will fail, because the password is incorrect, git then removes the offending user+password from the `~/.git-credentials` file, so now re-run:

`git pull`

to provide a new password so it works as earlier.

**Happy Coding**
The sight seeing gift of a trader 
Tags: machinelearning, deeplearning, algorithms, python
Published: 2021-08-03 16:37:12

The philosopher's stone, the holy grail , in stock market predictioners is to find the mathematical formulae that can predict the future. That said, no trader or business ever in history was able to achieve that with only historic data . To achieve sight seeing of future market valuations is needed something completely different . Is needed a dataset with  expected production outputs for the near future . ...
....that said,
The non linear regression below is not that good. One can achieve better results with a simple deep neural network architecture rather than the one employed here. The only obstacle is for one to find the optimal number of hidden layers and optimal number of neurons on the network. One that is able to output a regression result of near 100% accuracy .
Enjoy !

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sbiyx2ltmmi1vy4d3bkl.jpg)
Python Syntax
Published: 2021-08-03 16:28:15

**1 .When writing functions**
- Just as other programming languages python uses parenthesis (),when declaring functions.
However instead of using curly brackets{ }to to embed its code,it uses **indentation**
below is an example:
```def greeting():
      return hello World!```

**2. Commenting Out code**
-use # for single line comments
-Use triple quotes for multiple line comments
Install matplotlib In A Docker Container
Tags: python, docker, linux
Published: 2021-08-03 16:26:09

---
title: Install matplotlib In A Docker Container
published: true
description: 
tags: python, docker, linux
canonical_url: https://earthly.dev/blog/python-matplotlib-docker/
---

`matplotlib` is an excellent library for creating graphs and visualizations in Python. For example, I used it to generate the performance graphs in [my merging article](/blog/python-timsort-merge), and internally, we use it now and again for visualizing any metrics we produce. It is a bit hard to install inside a docker container, though.

## Installing Matplotlib in Alpine Linux

On Alpine, or an Alpine-based docker image, it's _possible_ to install `matplotlib`; however it will involve compiling it from source as pip does not provide any pre-compiled binaries -- this will take quite a bit of time. If you don't mind compiling from source, you will need to have its dependencies in place to make this work:

``` Docker
 FROM python:3.6-alpine
 RUN apk add g++ jpeg-dev zlib-dev libjpeg make
 RUN pip3 install matplotlib
```

## Installing Matplotlib in Ubuntu

On Ubuntu, or a Ubuntu-based docker image, the process is much simpler:

``` Docker
 FROM ubuntu:20.10
 RUN apt-get update && apt-get install -y python3 python3-pip
 RUN pip3 install matplotlib
```

In either case, after you've installed it, you can quickly generate great graphs and visualizations:

``` Python
import numpy as np
from scipy.interpolate import splprep, splev

import matplotlib.pyplot as plt
from matplotlib.path import Path
from matplotlib.patches import PathPatch

N = 400
t = np.linspace(0, 3 * np.pi, N)
r = 0.5 + np.cos(t)
x, y = r * np.cos(t), r * np.sin(t)
fig, ax = plt.subplots()
ax.plot(x, y)
plt.xlabel("X value")
plt.ylabel("Y value")
plt.savefig('1.png')
```

![Simple Graph](https://earthly.dev/blog/assets/images/python-matplotlib-docker/1.png)

## Appendix: Alpine vs Ubuntu Pip Install

Why is the Ubuntu process fast and simple and the Alpine process slow? The reason is `glibc`. The pip wheels for `matplotlib` are compiled c/c++ programs that dynamically link to `glibc` and Alpine does not have `glibc`.  

Alpine tries to stay small and so uses `musl-libc` instead. Unfortunately, this means compiling from source on Alpine, which can be a lengthy process.  

[ThisGuyCantEven](https://stackoverflow.com/questions/49037742/why-does-it-take-ages-to-install-pandas-on-alpine-linux/58210701#58210701) on Stack Overflow has more details:

> Pip looks first for a wheel with the correct binaries, if it can't find one, it tries to compile the binaries from the c/c++ source and links them against `musl`. In many cases, this won't even work unless you have the python headers from python3-dev or build tools like make.
>
> Now the silver lining, as others have mentioned, there are `apk` packages with the proper binaries provided by the community, using these will save you the (sometimes lengthy) process of building the binaries.
Video Player Interface for Bootstrap 5
Tags: bootstrap, videoplayer, frontend, html
Published: 2021-08-03 16:05:19

Since I'm currently working on a project that requires a custom video player for Bootstrap, I decided to share the code with everyone.

Yeah, it's Open Source:
https://koehlersimon.github.io/bootstrap-videoplayer/

If you want to participate on GitHub, let's go:
https://github.com/koehlersimon/bootstrap-videoplayer

It's an experimental interface to implement a video player using the Bootstrap 5 framework. The HTML structure was deliberately created so that you can customize the player to your own design using Bootstrap's built-in CSS classes.

- Bootstrap Version 5.0.2
- Uses Bootstrap Icons

### UPDATE 2021-08-09
The video player now has the main functions needed to play videos, such as play/pause, jump to a specific point in the timeline, adjust volume and enable/disable full screen.

### Example HTML Markup for Video Player
```
<div class="videoplayer" id="myCustomPlayer">
   <div class="ratio ratio-16x9 bg-dark">
      <video class="video" src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4"></video>
   <div>
   <div class="controls">
      <button class="btn btn-lg btn-video-playpause" type="button" title="Play Video">
          <i class="bi bi-play-fill"></i>
          <i class="bi bi-pause-fill d-none"></i>
      </button>
      <div class="px-1 w-100">
          <div class="progress w-100">
              <div class="progress-bar"></div>
          </div>
      </div>
      <button class="btn btn-lg btn-video-pip" title="Play picture in picture">
          <i class="bi bi-pip"></i>
      </button>
      <button class="btn btn-lg btn-video-fullscreen">
          <i class="bi bi-arrows-fullscreen"></i>
      </button>
      <div class="dropup">
          <button class="btn btn-lg btn-video-volume" data-bs-toggle="dropdown" title="Volume">
              <i class="bi bi-volume-mute-fill"></i>
          </button>
          <div class="dropdown-menu dropdown-menu-end dropup-volume">
              <input type="range" class="form-range form-range-volume">
          </div>
      </div>
      <div class="dropup">
          <button class="btn btn-lg" data-bs-toggle="dropdown" title="More...">
              <i class="bi bi-three-dots-vertical"></i>
          </button>
          <div class="dropdown-menu dropdown-menu-end">
              <a class="dropdown-item" href="#">
                  <i class="bi bi-info-circle-fill"></i> About
              </a>
          </div>
      </div>
   </div>
</div>
```
### Note
This article will be updated, as well as the GitHub Page and Repository. Check back soon and please leave a comment! Thanks!

### Support my work: 
► https://www.paypal.com/paypalme/typo3freelancer
► https://www.patreon.com/koehlersimon

### Follow me:
► https://github.com/koehlersimon
► https://www.linkedin.com/in/typo3-freelancer/
► https://bitbucket.org/typo3freelancer/
► https://twitter.com/koehlersimon
► https://www.instagram.com/fullstackfreelancer/
Learn HTML Using Notepad (Pc) or TextEdit (Mac) #1
Tags: webdev, html, tutorial, beginners
Published: 2021-08-03 15:56:18

Step 1: Open Notepad (PC)
Windows 8 or later:

Open the Start Screen (the window symbol at the bottom left on your screen). Type Notepad.

Windows 7 or earlier:

Open Start > Programs > Accessories > Notepad

Step 2: Write Some HTML

Write or copy the following HTML code into Notepad:

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

Step 3: Save the HTML Page

Save the file on your computer. Select File > Save as in the Notepad menu.

Name the file "index.html" and set the encoding to UTF-8 (which is the preferred encoding for HTML files).

Tip: You can use either .htm or .html as file extension. There is no difference, it is up to you.***

Step 4: View the HTML Page in Your Browser

Open the saved HTML file in your favorite browser (double click on the file, or right-click - and choose "Open with").

The result will look much like this:
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/543sja59aq2odzw8qblf.png)