teleren/devto huggingface dataset:
Why blockchain
Tags: blockchain
Published: 2021-07-04 14:42:51

After graduating from Flatiron school I found myself studying algorithms, data structures and practicing for technical interviews. I spent a lot of time learning data structures and it has been helpful in understanding different ways to solve problems within a program. I also had a strong interest in blockchain development. I began to read articles and got lost in the rabbit hole.

Which brings me to now. I realized then that I am really passionate about blockchain, so I decided to focus on being a blockchain developer. I started watching [Dapp University](https://www.youtube.com/channel/UCY0xL8V6NzzFcwzHCgB8orQ), who has been a great foundation and supplies a ton of resources for building Dapps and understanding the ecosystem. [Dapp Universtiy](https://www.youtube.com/channel/UCY0xL8V6NzzFcwzHCgB8orQ) provides a lot of knowledge on becoming a blockchain developer and has plenty of videos to watch if you are interested. I have definitely been soaking up all the knowledge that has been provided.

My journey has been great. I have been learning about web3, truffle, metamask, infura, hardhat and different tooling that you can use in  this eco system. Since it is so new a lot of different things have been being created. I love that its so open. It reminds me of when the internet was first introduced and how people were trying to learn how to use it.

Be sure to check out the resource that I provided. You will be glad that you did.
Docker for Developers (Workshop Ideas)
Tags: docker
Published: 2021-07-04 14:25:11

---
title: Docker for Developers (Workshop Ideas)
published: true
description: 
tags: Docker
---

Hi,

Docker is very cool, everyone uses it bla bla bla..

In reality I rarely see that **developers** know and use Docker to automate their work, set up local environments etc.

For that reason I am planning to conduct a _Docker for Developers_ workshop (free / simbolic fee)

Question of the day is - **what could be some interesting use cases to accomplish in the workshop**?

Few ideas from my side:
- running integration tests against db / ... in Docker
- merging two different databases (MySQL & Postgres) in the Docker image and storing the output in the file locally
- running Node environment in Docker for a local development
- obfuscating `production-like` database and making it available with all the data
- running development environment locally, by using Docker Compose
Answer: How to make an tail recursive function and test it in ReasonML?
Published: 2021-07-04 14:16:31

---
title: Answer: How to make an tail recursive function and test it in ReasonML?
published: true
---

{% gist https://gist.github.com/idkjs/454418678465bebb45a3f5f1833213e1 %}

How do you test if this reasonml function is tail recursive. The simple version show you the unannottated function and `usingTailCall.re` show its annotated in reasonml.

Call in terminal with:

```sh
ocamlc -annot -o tailCall -pp "refmt -p ml" -impl tailCall.re
```

You can check where the tail calls are with:

```sh
grep call -A1 tailCall.annot 
```

Source: https://stackoverflow.com/a/40401233/2336356
Sketch: https://sketch.sh/s/eBl2Z0Wvd21azKu6SFzb9j/
Вставить запись в PostgeSQL, если таковой нет в таблице
Tags: postgres
Published: 2021-07-04 13:45:04

Необходимо сделать такую возможность: Вставить уникальную запись в таблицу бд postgresql и вернуть id этой записи (даже если такая запись есть).
Например речь идёт о таблице tags:
```sql
CREATE TABLE "tags" (
"id" uuid NOT NULL DEFAULT uuid_generate_v4(),
"name" character varying NOT NULL,
CONSTRAINT "UQ_d90243459a697eadb8ad56e9092" UNIQUE ("name"),
CONSTRAINT "PK_e7dc17249a1148a1970748eda99" PRIMARY KEY ("id")
)
```
Здесь соблюдается главное требование: записи должны быть уникальными.
Но задача состоит из двух шагов:
1. Если такого тэга нет, то вставить название тэга,
2. Вернуть id тэга по имени,- этот тэг будет или новый или старый.

Как это сделать одним запросом я не подскажу, но как сделать из двух, - пожалуйста _(мне в этом помогла [документация](https://www.postgresql.org/docs/current/sql-insert.html) )_: 
```sql
INSERT INTO tags (name) 
SELECT 'Новость'
WHERE
    NOT EXISTS (
        SELECT id FROM tags WHERE name = 'Новость'
    )
-- RETURNING id -- Если второй шаг необязателен, то можно так сделать
;
select id from tags WHERE name = 'Новость';
```
_На правах ЖЖ, для себя, чтобы не забыть._
Beginning with Vuejs
Tags: vue, html, webdev, javascript
Published: 2021-07-04 13:25:13

The easiest way to try out Vue.js is using it by importing the library from a CDN, in order to do this, we create a simple html document.

```HTML
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<!-- importing vue js dev library -->
	<!-- development version, includes helpful console warnings -->
	<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
	<title>My vue Test</title>
</head>
<body>
	<div id="app">
		{{ message }}
		<br>
		{{ sum }}
		<br>
		{{ array }}
	</div>
	<script type="text/javascript">
		var app = new Vue({ //instantiating the vue instance
		  el: '#app', //we select where vue is going to work in the DOM
		  data: {
		    message: 'Hello Vue!', //this are the data
		    sum: 2+2,
		    array: [1,5,6, "Rome", "Italy", "cookies", 10]
		  }
		})
	</script>
</body>
</html>
```

And this is the resultant page:
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3qjcsidflhnfo67gthth.png)

as we can see, at the end of the body, once all the html code has been loaded, we call our script and instantiate the vue instance. If we did it before, it wouldn't work.
slowfil.es
Tags: showdev
Published: 2021-07-04 13:20:17

| [Direct link »](https://slowfile.es) |
| ------------------------------------ |

Neat little project here made by [Harry Roberts](https://csswizardry.com/) and [Ryan Townsend](https://www.twnsnd.com/) called [slowfil.es](https://slowfil.es), which is used to – you guessed it! – load files slowly. Might be useful for testing out apps which load resources.

You only get support for `js` and `css` files for now, but that may change later.
Speed-Admin: Quickly create admin like applications with Laravel
Tags: laravel
Published: 2021-07-04 13:08:26

Hi everyone,

This post is about the introduction of a Laravel package "speed-admin". It is a rapid application development framework for Laravel 8+. It has built-in Users Management with Roles and Permissions. It speeds up the development of CRUD functionality (adding data tables and forms).

You can check its documentation and list of features at this URL: https://minaammunir.gitbook.io/speed-admin/
React Context
Tags: react
Published: 2021-07-04 12:53:58

This is effectively another way of storing data.

## The problem

Let's say you have a state hook that you define in App, it's used in Child Component 1, so you pass it down to Child Component 1. It's also used in Grandchild Component 2, so you have to pass it down to Child Component 2, which doesn't use it and just passes it down to Grandchild Component 2.

Passing props down through components that don't use it in order to get to ones that do is called prop drilling. In the same way you'd drill through the earth to get to the oil, you drill through components to get the final one.

## Context to the rescue!

Context keeps the data at a global level, so any component can access it, no matter where it is. So in our example, the data would be available globally, which Child Component 1 and Grandchild Component 2 can access. App and Child Component 2 don't have to have any idea about it at all.

### How to use it

Basically you create a context, then tell components to use it. Here's an example:

CountContext:
```javascript
import { createContext } from 'react';
export const CountContext = createContext();
``` 
This is simple - all you have to do is to create it. That's it.

App:
```javascript
import { useState } from 'react';
import CountContext from './contexts/CountContext';

const App = () => {
  const [count, setCount] = useState();

  return (
    <CountContext.Provider value={{ count, setCount }}>
      <ChildComponent />
    </ CountContext.Provider>

  )
}
```
We're still setting our hooks at the highest point we need them, as usual. The difference here is that instead of sending the hook to the ChildComponent as props, we instead wrap the ChildComponent in a context provider and include the props as value instead. And yes, you do need two sets of curly brackets.

Child Component:
```javascript
import { useContext } from 'react';
import CountContext from './contexts/CountContext';

const ChildComponent = () => {
  const { count, setCount } = useContext(CountContext);

  return (
    <button onClick={setCount((previousValue) => previousValue + 1)}></button>
    <p>Count is: {count}</p>
  )
}
``` 
The difference here is that we're not pulling the props. Instead we're defining them using the context. This is similar to how we define the state hook, but with curly brackets.

## Notes

You can create your own Provider, which means you don't have to type in all those values and hope they're right. You can also convert your Context into a custom hook. Because this is just an introduction to Context I haven't done those, but if you're interested they are something you can look up as to how and why you'd do that.
 
[As always, it's worth looking at the React docs to understand the best uses of Context.](https://reactjs.org/docs/context.html#consuming-multiple-contexts)
Housekeeping files using python modules 
Tags: python, programming
Published: 2021-07-04 11:38:43

File module in python has a lot of useful properties. It provides access to various file properties related to time which then can be plugged in use cases like housekeeping, archiving or building logic based the file modified or created time.

`os.path.getatime()` returns the access time, 

`os.path.getmtime()` returns the modification time and 

`os.path.getctime()` returns the creation time

`os.path.getsize()` returns the amount of data in the file, represented in bytes.

```
# ospath_properties.py
import os.path
import time

print('File         :', __file__)
print('Access time  :', time.ctime(os.path.getatime(__file__)))
print('Modified time:', time.ctime(os.path.getmtime(__file__)))
print('Change time  :', time.ctime(os.path.getctime(__file__)))
print('Size         :', os.path.getsize(__file__))
```

```
$ python3 ospath_properties.py

File         : ospath_properties.py
Access time  : Sun Mar 18 16:21:22 2018
Modified time: Fri Nov 11 17:18:44 2016
Change time  : Fri Nov 11 17:18:44 2016
Size         : 481
```

A simple script to archive files from given directory using getctime

```
# housekeep_files.py

import os
import time
from datetime import datetime

# get list of file names
file_names = os.listdir()
archive_days = 90
now = datetime.now()

for file in file_names:
   # get created time of file and convert to datetime
   created_time = time.ctime(os.path.getctime(files[0]))
   created_datetime = datetime.strptime(c_time, "%a %b %d %H:%M:%S %Y")
   diff_days = (now - created_datetime).days

   # find difference between archive and current day
   if days > archive_days:
      # logic here to copy or move or remove files
```
My Dev Journey: Week 9
Tags: codenewbie, beginners, javascript, bootcamp
Published: 2021-07-04 11:34:10

This week was the start of the three week long Front-End block of the Northcoders bootcamp I'm on. We started off the week by creating mini-apps by manipulating information available to us using the DOM, then moving into React in the second half of the week.

If you've enjoyed any of my blog series, then maybe consider following me on [GitHub](https://github.com/fearneyork) 😁

## What I've learnt this week

### DOM manipulation

At the start of the week, we learnt how to access and manipluate what's on a webpage using JavaScript, it was great to learn out to make something interactive and have some more visual feedback on what I was doing than what you get when doing backend tasks.

To put these new skills into practice, we built a tic-tac-toe game and were very happy with the way it turned out, we didn't get around to styling it, and instead focussed on the functionality, but the styling is something that would be good to come back to. 

### Form validation

This covered learning how to make form fields required, using RegEx to do form field validation on things like emails and URLs to make sure the user provides the correct information, and learning how to get the values from submitted forms.

We built a meme generator that took two input fields for top text, and bottom text, and then a third input field that takes an image URL. We used RegEx to validate the url and the condition that as long as there was either top or bottom text entered, the form would allow you to submit the form to generate the meme.

### React

For my first day using React, I built a pizza parlour site, that would use buttons to add and remove pizzas from a basket, clear the basket and confirm an order. I had heavy influence from Crazy Pedro's and Dough Boys Pizza in the naming and pizza types! I was really happy to get stuck into React and build something functional with it, I'm really happy with how it turned out and how much I was able to do in such a short time. Keep an eye out because I plan to finish the pizza parlour project off and show off what I can do!

But here's a demo of what it looks like so far!

{% twitter 1410293551536263169 %}

### React mini-app

For the last two days this week, we were building a working calculator using React, and taking advantage of states that React allows us to use, over methods like closure that we have been used to using. I'd really like to get this calculator full functional and styled when I have some spare time to put on my portfolio site.

## Resources that I've found useful this week

### I Hate Regex

[I hate Regex](https://ihateregex.io/) is a great site that has prebuilt regex strings, as well as details on how they work, as well as some wicked diagrams that show the flow of the logic.

### Interneting is hard

[Interneting is hard](https://www.internetingishard.com/) is another great site that has a very comprehensive beginners guide to HTML and CSS, it's a great ready through in the mornings before starting off
Style is servient to content
Tags: css, style, content, html
Published: 2021-07-04 11:31:14

An extremely short post that highlights a key consideration regarding the use of CSS to style HTML content:

> Documents that use style attributes on any of their elements ***must still be comprehensible and usable*** if those attributes were removed. (Section 3.2.6.5 The style attribute)

This is a direct quote from the [HTML Spec](https://html.spec.whatwg.org/#dom), as a reminder that content trumps style and it's a good idea to temporarily disable stylesheets (if feasible) prior to production just to make sure this holds true.
Laravel Views with React Components
Tags: react, javascript, php, laravel
Published: 2021-07-04 11:17:03

To Add React with Laravel from scratch, there are many important details you need to consider:

1. Configuring React
2. Adding State management systems like Redux and configuring store, actions and sagas for API calls
3. Configuring Routes for React Components
4. Authentication
5. Configuring ESlint for effective code

These configurations might require more time. To avoid these and focus only on developing the App functionalities, You have [laravel-react-boilerplate](https://github.com/Nilanth/laravel-react-boilerplate).

## Laravel React Boilerplate

Laravel React Boilerplate helps to fasten your development, Instead of spending more time on configuring React and SPA Authentication.

It is Pre-Configured with

* Laravel 8
* Laravel Sanctum for SPA Auth
* React 17
* Redux
* React Router
* Axios
* Ant Design
* Redux-Saga
* Sass
* ESLint
* Preconfigured redux store, actions and saga.

## Pre-Configured Modules

* User Login
* User SignUp
* Auth Routes


## How to start with it?
### Laravel Development Environment setup

You can choose either one for your development

1. Laravel Homestead
2. Laravel Sail

Basic needs
1. Composer 2.
2. Node stable version.

## Usage

1. Install using composer

```
composer create-project nilanth/laravel-react-boilerplate
```
2. `cd laravel-react-boilerplate`
3. `Run yarn install`
4. Create a Database
5. Update the Database credential to .env file
6. Run `php artisan migrate` -> To create needed tables.
7. Run `php artisan db:seed` -> To seed some fake users.
8. Run `yarn run dev`
9. Update `API HOST_URL` in resources/js/config/constant.js file


## Login

![Login](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1temn5qqyqxmx58nsui2.png)
 

## SignUp

![SignUp](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0hbh7gskervypd43p9mr.png) 

## Home Screen

![Home Screen](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1mxwdgcbfmupmfkjta6f.png) 

Use [Laravel React Boilerplate] (https://github.com/Nilanth/laravel-react-boilerplate) to fasten your development 🚀

Need to learn more? Feel free to connect on [Twitter](https://twitter.com/Nilanth) :)

**You can support me [by buying me a coffee](https://buymeacoffee.com/nilanth) ☕**
A gentle introduction to Vuejs
Tags: javascript, vue, tutorial
Published: 2021-07-04 10:41:42

VueJs is a Javascript front-end framework, it merges together some of the most interesting features of other frameworks such as ReactJs and AngularJs, the first was created by Facebook, the second by Google. Vue, on the other hand, does not have any major of the computer industry behind it, but over time it managed to carve out an important space, and is increasingly preferred to others for a variety of reasons.

<h3>Easy</h3> 
Compared to other frameworks it has roughly the same functionality, but has a much more linear learning curve for a newbie.

<h3>Rapid</h3>
VueJs has borrowed a pretty cool feature from React: the virtual DOM. 
Put simply, the DOM is a light copy of the web page, when every change is made by the user action, Vue compares the new DOM with the saved virtual one, and only makes the required changes, without having to completely redesign the page.

<h3>Light</h3>
Vue, when compared with the other frameworks, turns out to be the lightest ever, the core functions library weighs only 16 Kb!

<h3>Useful resources</h3>
<a href="https://vuejs.org/v2/guide/">The official documentation</a> should be a must read at all.
Wordpress Tutorial With Timber video
Tags: wordpress, timber, wptwig
Published: 2021-07-04 10:38:44

{% youtube 6TPpzpFt_sk %}


Playlist: 
https://www.youtube.com/embed/videoseries?list=PL3gSMjdAtx33Z_Ox9QZN1-3O-rRvr4Df0
Why I create my first NPM package
Tags: npm, typescript, react
Published: 2021-07-04 10:11:50

A useful practice when you work with a specific stack, is to create generic stuff for this stack. This is the fundamental principle of a framework, library, package, etc.

With generic and reusable code, your project will start faster. All that's left is to write the business rules part of your project.

I work with React to build front end. As languages, I use Javascript or Typescript. I prefer Typescript, but at work, sometime you have no choices.

As CSS framework, my preference goes to Bulma.

It's simple, easy to tweak or override and especially, it contains no Javascript or Jquery, only HTML and CSS rules.

All I expect from a CSS framework.

I dislike make the same thing again and again. It's useless and repetitive tasks create bugs.

Some of basic components stays the same on all projects

That's why I create a NPM package called [react-components](https://www.npmjs.com/package/@the-sleeping-dog/react-components).

It's a library of basic components made with Bulma and React Typescript.

The objectives :

- Learn how to create and publish a package.
- Learn more about open source not by participating but by being at the origin of a (very small) project.
- Learn how to manage advice and criticism about my project to progress as a developer.
- Have basics components available immediately.

Nowadays, This project is under development and contains lots of beginner mistakes.

I work on it as a side project, between all my side projects, so it's progressing very slowly.

I think to make more posts about this work and all the challenges I meet.

If you want know more about this project or how to contribute, don't be shy. Comments and DM on Twitter are open.
Bounty Program from Platon network
Tags: blockchain
Published: 2021-07-04 10:00:59

PlatON is a new generation of privacy-preserving AI network initiated and driven by the LatticeX Foundation, and is also an open-source community project. Such a huge infrastructure requires joint effort from community developers.
To encourage community developers to get more involved in the development and design of core infrastructure, the LatticeX Foundation launched Developer Bounty Program to reward those who provide basic services for PlatON and Alaya.
https://github.com/LatticeX-Foundation/dev-bounties/blob/c8513aff4a7f03cbc0f765b1a3e32a9a3716d55a/Developer%20Bounty%20Program(Phase-I).md
Send an email developer@latticex.foundation to submit more ideas and suggestions
JAVA001 Annotation and Reflection
Tags: java
Published: 2021-07-04 09:49:13

# Background

Reflection makes Java a semi-dynamic language. Hardly do we use reflection in our Java development due, it provides us with an alternative way to create object. Normally, we use `new` keyword or `clone()` method to create instances. With the help of reflection, we can have the third way.

For annotations, we often see them in frameworks like spring.  I believe most of frameworks having annotations are using reflection to get the annotation in our code.

# Annotation

An annotation is similar to a class, but it only have attributes. We can use `@interface` to declare annotations:

```java
// Self-defined annotations:

// The table name
@Target(value=ElementType.TYPE)
@Retention(value=RetentionPolicy.RUNTIME)
@interface AnnoTable {
    // 注解的参数: 参数类型 参数名()
    String value();
}

// The field information
@Target(value=ElementType.FIELD)
@Retention(value=RetentionPolicy.RUNTIME)
@interface AnnoField {
    String fieldName();
    String dataType();
    int length();
}
```

Now let's define a class and use our annotations to describe it:

```java
@AnnoTable("researchers")
class Researcher {
	
    @AnnoField(fieldName = "rid", dataType = "int", length = 11)
    private int id;
	
    @AnnoField(fieldName = "age", dataType = "int", length = 11)
    private int age;
	
    @AnnoField(fieldName = "name", dataType = "varchar", length = 30)
    private String name;
	
    public Researcher() {
    }
    public Researcher(int id, int age, String name) {
        super();
        this.id = id;
        this.age = age;
        this.name = name;
    }
	
    // ... getters and setters
}
```

# Get annotation by reflection

```java
public class TestMyAnnotation {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
		
        // 通过反射获得注解
        Class c1 = Class.forName("annotation.Researcher");
        Annotation[] as = c1.getAnnotations();
        for(Annotation a: as) {
            System.out.println(a);
        }
		
        // 获得注解中的值
        AnnoTable annotable = (AnnoTable) c1.getAnnotation(AnnoTable.class);
        String value = annotable.value();
        System.out.println(value);
		
        // only public fields can be got by getField() method
        // private fields should use getDeclaredField()
        Field f = (Field) c1.getDeclaredField("id");
        AnnoField annoField = (AnnoField) f.getAnnotation(AnnoField.class);
        System.out.println(annoField.fieldName());
        System.out.println(annoField.dataType());
        System.out.println(annoField.length());
    }
}
```