teleren/devto huggingface dataset:
Basic Intro to NextJS
Tags: nextjs, react, nuxt, sveltekit
Published: 2021-06-08 03:37:37

Some people will call NextJS a Static Site Generator like GatsbyJS but it's so much more. Essentially NextJS allows you to create an Isomorphic Application, meaning:

- Some parts are statically rendered
- Some parts are client side rendered
- Some parts are server side rendered

Meaning, you can optimize for speed and security static rendering while not giving up all the benefits of rendering on the client and the server for dynamic content. NextJS is built on React but the other frameworks have their equivalents.

| Frontend Framework | Static Site Gen | Isomorphic App |
|--------------------|-----------------|----------------|
| React | Gatsby | NextJS |
| Vue | Gridsome | NuxtJS |
| Svelte | ElderJS | SvelteKit |
| Angular | Scully | Angular Universal |
| SolidJS | NOT YET | NOT YET |

There are lot more features that frameworks for Isomorphic apps bring to the table but how about we just take NextJS for a Spin.

# Pre-Requisites

- NodeJS Installed

# Setup

- Create a new app `npx create-next-app`
- choose an application name
- cd into the new folder for your project

# Features

NextJS has file based routing, these are the essential rules:

- If a file that export defaults a react component in the pages folder, it automatically becomes a page with a route named after the file.
    * If you have a file pages/cheese.js it would turn into a page at /cheese
    * If you have a file pages/news/june.js it would turn into a page at /news/june
    * If you have a file pages/news/index.js it would turn into a page at /news (index.js files take on their folder name)

- If you export a express style function from a file in the API folder, it becomes a backend route
    * If you have a file pages/api/hey.js it would be available at /api/hey

- If a file has square brackets then it is treated as a URL param
    * If you have a file called `pages/eat/[food].js` it is treated at `/eat/:food`

- To link between different pages, Link components are used

- To get the url param you bring in the useRouter hook

```jsx
// for pages/eat/[food].js
import useRouter from "next/router"

export default function Food() => {
    // Pull out router
    const router = useRouter()
    // Get the param
    const food = router.query.food

    return <h1>{food}</h1>
}
```

- Files can be served statically outside of public folder

- If you export a function getStaticProps and/or getStaticPaths that page will be rendered statically

- KILLER FEATURE: Incremental Static Regeneration, you can set a timer on how often Next should try to regenerate that static page on a user request. Let's say you set it for 20 minutes. No matter how many requests comes it will only regenerate the page on the first request within the 20 minutes allowing dynamic content to dynamic, and speeds to be FAST.

- If you export a function called getServerSideProps that page will be server side rendered and rendered on the server for each request.

## Bottom Line

That's a pretty sweet feature set, no wonder everyone is so excited by frameworks like Next, Nuxt and SvelteKit!
34. Find First and Last Position of Element in Sorted Array
(javascript solution)
Tags: algorithms, javascript
Published: 2021-06-08 03:26:23

###Description:
You are given a string s and an integer k. You can Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.

If target is not found in the array, return [-1, -1].

You must write an algorithm with O(log n) runtime complexity.

###Solution:
Time Complexity : O(nlog(n))
Space Complexity: O(1)

```javascript
var searchRange = function(nums, target) {
    const output = []
    
    // find lower bounds
     let l1 = 0, r1 = nums.length;
    while(l1 < r1) {
        const mid = l1 + Math.floor((r1-l1)/2)
        if(nums[mid] >= target) r1 = mid
        else l1 = mid+1
    }
    // if we can't find target in the array then return [-1,-1]
    if(nums[l1]!==target) return [-1,-1]
    
    // if we did find target, push the lower bound into the output array and search for the upper bound index
    output.push(l1)
    
    // find upper bounds
    let l2 = l1, r2 = nums.length;
    while(l2 < r2) {
        const mid = l2 + Math.floor((r2-l2)/2)
        if(nums[mid] <= target) l2 = mid+1
        else r2 = mid
    }
    // pointers will meet at the index above the upper bound index, push in the index 1 less than where they meet
    output.push(l2-1)
    
    return output
};
```
Fre Offscreen rendering: The fastest vdom algorithm
Tags: react, vue, fre, preact
Published: 2021-06-08 03:24:53

In the past, I wrote a front-end framework named fre in school, which uses the data structure of fiber linked list. 

In fre v1, the biggest breakthrough is `Time slicing`. It can greatly improve the response performance.

Now that fre2 is released, I've made a breakthrough again. 

It is called `Offscreen rendering`. It operates DOM in memory and draws them to the screen once at the last time.

In the actual benchmark test, Fre is the fastest, it broke the rules of the game.

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

In the past, we always thought that frameworks with vdom could not be faster than vanilla JS, while svelte's idea could be close to the performance of vanilla JS.

https://github.com/yisar/fre/blob/master/demo/src/benchmark.tsx

Fre with off-screen rendering breaks this fact. I'm proud to say that fre is the fastest vdom-based framework, and it's only 400 lines, the smallest size.

It is worth mentioning that this is a highly optimized data structure and core algorithm. 

And it does not conflict with time slicing and does not depend on the 'DocumentFragment' API.

In fact, similar optimizations always exist in IOS or OpenGL. It's not easy for web to do this, so fre is the first framework to implement it.

I don't want to introduce too many implementation details of off-screen rendering. If you are interested in this, you can reply to it or read the source code of fre.

https://github.com/yisar/fre

I really hope to get your feedback, because I am a Chinese, usually in school or company, no one can discuss these with me, I can only study alone.

Thank you very much!
Best Free Resources (documentation) for learning Web Development
Tags: webdev, html, css, beginners
Published: 2021-06-08 03:16:03

If you are looking to learn web development online, there are more than enough resources out there to teach you everything you need to know, which sometimes might overwhelm you but get into it. Here are some of my best picks:

‣ Mozilla Web Docs (MDN)

MDN Web Docs, previously Mozilla Developer Network and formerly Mozilla Developer Center, is a documentation repository and learning resource for web developers used by Mozilla, Microsoft, Google, and Samsung. The project was started by Mozilla as a unified place for documentation about open web standards, Mozilla's own projects, and developer guides. MDN Web Docs content is maintained by Mozilla and Google employees and volunteers (community of developers and technical writers). Topics include HTML5, JavaScript, CSS, Web APIs, Django, Node.js, WebExtensions, MathML, and others.

These are some really well curated documents and you should definitely refer to them while learning web development. 

You can find them [here](https://developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web)


‣ The Odin Project

The Odin Project is a great place to jumpstart your career in web development with a full stack curriculum approach that is backed up by an open-source community. The curriculum is made up of a collection of online tutorials, blogs, and courses. For example, there is a web development 101 course made up of lessons that start and the basics and end with you building a practical web application. So you will have opportunities to build portfolio-worthy projects alongside a community of developers.
You can find it [here](https://www.theodinproject.com/paths/foundations/courses/foundations).


‣ Shay Howe's Book for Learning HTML and CSS

It is a really well written book and I personally refer to it whenever I need any help related to HTML and CSS. It makes use of [codepen.io](https://codepen.io/).
You can find it [here](https://learn.shayhowe.com/html-css/).


‣ w3schools

It is also one of the best resource to learn web development and master the concepts.
You can find it [here](https://www.w3schools.com/).

My best tip for all the newbies would be that don't get stuck in tutorial hell and if you don't know what that is, you can read my previous article which you can find [here](https://dev.to/tannudaral/if-you-re-a-beginner-in-coding-read-this-458m). 

Hopefully, these web developer resources can help you along the way. Feel free to share some of your favorite online resources in the comments below.

Keep Learning! Keep Coding!
Reverse A String - 5 Methods
Tags: java, programming, webdev, oop
Published: 2021-06-08 02:51:30

- Method 1 - String Builder / String Buffer

```java
// Using String builder and String buffer

public class Method1 {
	public static void main(String[] args) {
		
		// pass the string to reverse
		StringBuilder sb = new StringBuilder("Amritanshu");
		StringBuffer sbf = new StringBuffer("Rawat");
		
		// printing
		System.out.println("String Builder: "+ sb.reverse().toString());
		System.out.println("String Buffer: " + sbf.reverse().toString());
	}
}
```

- Method 2 - String Concatenation

```java
// String Concatenation

public class Method2 {
public static void main(String[] args) {

// String to reverse
String name = "Amritanshu Dev Rawat";

// empty string to store reverse string
String rev = "";

// reverse loop logic and appending to rev
for(int i = name.length()-1;i>=0;i--) {
rev += name.charAt(i);
	}

// printing
System.out.println(rev);

	}
}
```

- Method 3 - Character Array

```java
// Char array

public class Method3 {
public static void main(String[] args) {

// String to reverse
String name = "Amritanshu";

// converting to char array
char[] charName = name.toCharArray();

// reverse loop logic and printing
for(int i = charName.length -1; i>=0;i--) {
System.out.print(name.charAt(i));
		}
	}
}
```

- Method 4 - Stack 

```java
// Stack

import java.util.Stack;

public class Method4 {
public static void main(String[] args) {
	
	// string to reverse
	String name = "Amritanshu";

	// empty character stack
	Stack<Character> charStack = new Stack<Character>();

	// push every character to stack
	char[] ch = name.toCharArray();
	for (int i = 0; i < name.length(); i++) {
        charStack.push(ch[i]);
    }

	// pop element and store
	int k =0;
	while(!charStack.isEmpty()) {
		ch[k++] = charStack.pop();
	}

	// convert char to string and print
	System.out.println(String.copyValueOf(ch));

	}
}
```

- Method 5 - Swap

```java
// Two Pointer swap

public class Method5 {
public static void main(String[] args) {
	// String to reverse
	String name = "Amritanshu Dev Rawat";

	// converting to char array
	char[] c = name.toCharArray();

	// one pointer at begin
	int begin=0;

	// one at end
    int end=c.length-1;

    // one to store value and swap
    char temp;

    // looping and swapping
    while(end>begin){
        temp = c[begin];
        c[begin]=c[end];
        c[end] = temp;
        end--;
        begin++;
    }

    //printing
    System.out.println(String.valueOf(c));
	}
}
```
ใช้ Dev.to API ถึงข้อมูลของบทความที่เขียนออกมา
Tags: devto, api
Published: 2021-06-08 02:34:35

เว็บ Dev.to ที่เขียนอยู่นี้มี API ให้ใช้ด้วย ตัวอย่างเช่นถ้าเราอยากลิสต์บทความของ user คนไหนออกมาดูก็เรียก http GET ที่ endpoint นี้ แล้วใส่ query string `username` กับกำหนดชื่อ username ที่ต้องการลิสต์บทความ

```
https://dev.to/api/articles?username=iporsut
```

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

ซึ่งปกติจะได้ 30 บทความล่าสุด แต่ตัว API support pagination ด้วยก็ใส่ option ดึง page ต่อไปมาได้

ทีนี้ถ้าอยากดูข้อมูลเฉพาะของบทความใดๆ ก็เรียก GET ไปที่ endpoint เดิม แต่ใส่ path param เป็น ID ของบทความที่ต้องการ แบบนี้

```
https://dev.to/api/articles/719722
```

ซึ่งก็จะมีข้อมูลของบทความหมายเลข 719722 ออกมาซึ่งรวมทั้ง HTML ของหน้าบทความนี้ด้วย

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

นอกจากนั้นยังมี API อื่นๆอีกลองเราไปดูได้ที่นี่ครับ https://docs.forem.com/api/

มีประโยชน์มากๆเพราะเราสามารถเขียนบทความที่ dev.to แล้วไปสร้าง page ของเราเองที่ดึงข้อมูลจาก dev.to ไปแสดงเพื่อ custom การแสดงผลเองได้ด้วย

## ขอฝาก Buy Me a Coffee
สำหรับท่านใดที่อ่านแล้วชอบโพสต์ต่างๆของผมที่นี่ ต้องการสนับสนุนค่ากาแฟเล็กๆน้อยๆ สามารถสนับสนุนผมได้ผ่านทาง Buy Me a Coffee คลิ๊กที่รูปด้านล่างนี้ได้เลยครับ

<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>
Laravel URL Presenters
Published: 2021-06-08 02:05:01

Usually, we always find new ways to make our backend code cleaner, readable and flexible by applying design patters, software principles, refactoring strategies, etc.

This time, the strategy we are going to apply is about communication of backend and frontend and how the backend code can provide much more information to our views.

Most of us render the application routes directly in the view, and sometimes we find that we are repeating these same routes along the view.

![Index view](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xavn7oslq887lcpoc90d.png)

We can see that we are repeating the same url in lines #19 and #28. This is the good way, some people use (see line #2):

![Index view 2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y0etz3vz6pui3386n7oz.png)

So, how can we make this a little bit cleaner and reusable along the application? Well, we can apply a Url Presenter.

There are many ways to do it, so I'm going to show you one of them. 

Some people like to do it inside the model, which I think is not the best way because we are giving a responsibility to the model that should not have, I mean, why the model should know about urls?

Let's begin with the first step.
&nbsp;
&nbsp;

### Creating an interface

When I talk about interface I mean that it could be an abstract class or interface, that depends on your need. This time we are going to make a simple interface for a url resource (index, show, edit, ...).

![Interface](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t16pn1rngnwpw0r0hd9g.png)
&nbsp;

### Creating concrete url presenter

Now, we just create a concrete url presenter, in this case we are going to create a ``UserUrlPresenter``

![Concrete](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ld078vxbnc1nyeja46lb.png)
&nbsp;

### Using the presenter

Let's suppose we have our UserController, we just have to pass the url presenter to the view.


![Controller](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b2ktmhftzi4l9gmhcgmt.png)
&nbsp;

### Final view

Now, we can use the url presenter inside the view.

![Final View](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/weo9t3lgvo3kwmqn6lua.png)

&nbsp;
&nbsp;
&nbsp;
## Bonus

I know I said that I am not a fan of url presenters inside the model, but I will give you an example of how to do it.
&nbsp;

### Creating the interface


![Interface](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uu81x51nib8jmii26gi7.png)
&nbsp;

### Creating concrete url presenter

![Concrete presenter url 2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cpp0kn78ggrlxujd47sc.png)
&nbsp;

### The presenter in the model

![Model](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m7os4ssznfcggzybc7nr.png)
&nbsp;

### Using the presenter


![Controller 2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q7enmoox8wvavjja39xf.png)
&nbsp;


### Final View

![Index 3](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/brck81eyfix3fmy19fzr.png)
Weekly Check-In #1: Onboarding Period
Tags: opensource, python, gsoc
Published: 2021-06-08 01:15:17

The last three weeks were an onboarding time for all interns in the GSoC, and today 7th June is starting the coding phase. Although I don't have experience in writing blogs, sometimes all that we need is to take a leap of faith 😊 so, I will be recording my experience and status on a series of blog posts. Follow me on this journey and I hope that you enjoy it.

## What did you do these weeks?

During these weeks I was working on getting familiarized with the [Runestone](https://runestoneinteractive.org/) library, and the [Playwright](https://playwright.dev/python/docs/intro/) library. The first one is a tool to create interactive books in different languages, Python in this case 👍, and the last one is a tool to create automated end-to-end tests on web apps.

In addition, during the onboarding period I had two meetings with the mentors and the entire team, in the first one we met each other and talked about the status of the project, and the mentor merged all [PR's](https://github.com/PyAr/PyZombis/pulls?q=is%3Apr+is%3Amerged++author%3Ay-martinez) that we had created during the application period.

The second meeting with the mentors was more technical and it helped to coordinate how we are going to work on our tasks and schedule bi-weekly meetings following the Scrum methodology. For this, I split my initial proposal into [issues](https://github.com/y-martinez/PyZombis/issues) and [milestones](https://github.com/y-martinez/PyZombis/milestones) using Github, and for making all organized I put them in a [Github project board](https://docs.github.com/en/issues/organizing-your-work-with-project-boards) as well.

## What is coming up next?

In the first month of the coding period, I am going to work on my first milestone. More specifically in the next week, I am going to work to fix the current bugs on quizzes, adding an end-to-end test to ensure that everything is ok.

![Testing Code meme](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gnchm8d35rl38kniov3z.jpg)

## Did you get stuck anywhere?

Not yet, but if this happens I am going to find on the internet solutions and talk with my mentors 😅 and find solutions on the Internet.
S3 101
Tags: aws, cloudpractitioner
Published: 2021-06-08 01:12:49

# Q: Why S3? 

A: Simple Storage Service

## Notes

1. S3 is object based, allows you to upload files.
2. Files could be 0bytes to 5TB
3. Unlimited storage
4. Files are stored in buckets — not folders
5. S3 is a universal namespace — names should be unique. It’s like a one big C drive
6. Not suitable to install an operating system 
7. Successful uploads will return a HTTP 200 status code

## Basics

* Key/Value pair
* Key name of the object
* Value data of the object
* Upload - read immediately
* Modify / Delete - not guaranteed to take effect at once.

## Types

S3 Standard | S3 Infrequently Accessed | S3 One zone | S3 Intelligent Tiering | S3 Glacier | S3 Deep Archive
Extend Constructors to Receive Arguments
Tags: javascript, devops, tutorial, beginners
Published: 2021-06-08 00:34:31

* Continued
* The `Dog` constructor from the last post worked well. However, notice that all `Dogs` that are created with the `Dog` constructor are automatically named Anakin, are brown in color, and have four legs. What if you want dogs with different values for name and color? It's possible to change the properties of each dog manually but that would be a lot of work:
```
let husky = new Dog();
husky.name = "Rex";
husky.color = "blue";
```
* Suppose you were writing a program to keep track of hundreds or even thousands of different dogs in an aviary. It would take a lot of time to create all the dogs, then change the properties to different values for every one. To more easily create different `Dog` objects, you can design your Dog constructor to accept parameters:
```
function Dog(name, color) {
  this.name = name;
  this.color = color;
  this.numLegs = 4;
}

let terrier = new Dog("Ewok", "tan");
```
* Then pass in the values as arguments to define each unique dog into the `Dog` constructor: `let terrier = new Dog("Ewok", "tan");` This gives a new instance of Dog with `name` and `color` properties set to `Ewok` and `tan`, respectively. The `numLegs` property is still set to 4. The `terrier` has these properties:
```
console.log(terrier.name); // will print out Ewok
console.log(terrier.color); // will print out tan
console.log(terrier.numLegs); // will print out 4
```
* The constructor is more flexible. It's now possible to define the properties for each Dog at the time it is created, which is one way that JavaScript constructors are so useful. They group objects together based on shared characteristics and behavior and define a blueprint that automates their creation.
Using a Constructor to Create Objects
Tags: javascript, devops, tutorial, beginners
Published: 2021-06-08 00:20:42

* Continued.
* Here's the Dog constructor from the previous post:
```
function Dog() {
  this.name = "Anakin";
  this.color = "brown";
  this.numLegs = 4;
}

let hound = new Dog();
```
NOTE: `this` inside the constructor always refers to the object being created.

* Notice that the `new` operator is used when calling a constructor. This tells JavaScript to create a new instance of `Dog` called `hound`. Without the `new` operator, this inside the constructor would not point to the newly created object, giving unexpected results. Now `hound` has all the properties defined inside the `Dog` constructor:
```
hound.name; // when console.log it will print out Anakin
hound.color; // when console.log it will print out brown
hound.numLegs; // whem console.log it will print out 4
```
* Just like any other object, its properties can be accessed and modified:
```
hound.name = 'Obi-Wan Kenobi';
console.log(hound.name); // will print out Obi-Wan Kenobi
```
Cron job on a server
Tags: cronjob, server
Published: 2021-06-08 00:19:17

What is a cron job?
A cron job is use to execute a particular script (code) on a scheduled time repeatedly.

What is cron job is use for?
 Email marketing
 Delete file 
 to send newsletter

<h3>How to setup cron job on a server</h3>

Login to the dashboard
Locate cron job and click on it
Then fill the for under add cron job
<img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vxm8994ogefu16vo6bua.png">
Select your command settings
This where you select may be the script will be execute once per day, once per week ,etc
Then select the minute,hour,day, monthly and weekend in which the cron job will be execute.





<table>
  <tr>
    <td>minute</td>
    <td>0-59</td>
<td>The exact minute that the command sequence executes</td>
  </tr>
  <tr>
    <td>hour</td>
    <td>0-23</td>
    <td>The hour of the day that the command sequence executes</td>
  </tr>
<tr>
    <td>day</td>
    <td>1-31</td>
<td>The day of the month that the command sequence executes</td>
  </tr>

<tr>
    <td>month</td>
    <td>1-12</td>
<td>The day of the month that the command sequence executes</td>
  </tr>
<tr>
    <td>weekday</td>
    <td>0-6</td>
<td>The day of the week that the command sequence executes (Sunday = 0, Monday = 1, Tuesday = 2, and so forth)</td>
  </tr>
<tr>
    <td>command</td>
    <td>special</td>
<td>The complete sequence of commands to execute. The command string must conform to Bourne shell syntax. Commands, executables (such as scripts), or combinations are acceptable.</td>
  </tr>

</table>

command
<code>
cd/home/user /public_html/admin; php -q auto.php
This command will open the folder admin on n the server,
Then php represent the format of the script 
Follow by -q and then the file you want to execute
</code>