teleren/devto huggingface dataset:
Not Another Next.js Post (Part II)
Tags: nextjs
Published: 2020-12-19 20:59:31

---
title: Not Another Next.js Post (Part II)
published: true 
series: Not Another Next.js Post
description: Part II - Handling External Data in Next.js
tags: nextjs
cover_image: https://images.unsplash.com/photo-1531187884142-65254c0f2609
---

In the first installment of this series we brushed on the differences between Static Site Generation and Server Site Rendering in Next.js. Both have their use cases, but it is recommended by the creators of Next to use Static Site Generation, since it is more optimal to initially build a page’s HTML and reuse the layout with subsequent requests, as opposed to rendering HTML with every request made. I also mentioned how a page component doesn’t contain any render logic. However, if necessary, we can implement some logic that fetches any external data that a component may require to pre-render, like a list of a user’s blog posts from a CMS, or a newsfeed.

##Fetching External Data##
Next.js contains a few built-in methods used for fetching data by calling to external API routes. One of these methods, `getStaticProps()`, fetches the data at the received context at build time. Of course, this means that we must use our better judgment to determine if it is feasible to do so, based on the type of data needed. `getStaticProps()` is ideal for data that is publicly accessible; 'data that would not require an authorization token to access. 

```
export async function getStaticProps(context) {
//dynamic route to call
  const res = await fetch(‘http://example.com/api/posts’);
  const data = await res.json();
//error handling + return props object with serializable data
  if (!data) {
     { notFound: true } 
   }
  return {
    props: {}
  }
}
```
The `getStaticProps` function asynchronously receives our context. After fetching our data from an API, it returns our data as a serializable `props` object.

Static Site generation is optimal for pages such as landing sites that don’t require any handling of data that gets updated regularly. By rendering our HTML at build time we also improve our SEO. 

Another option for data fetching is the `getServerSideProps` function. This function runs at build time as well, with the major difference being that `getServerSideProps` renders pages with every request. Like `getStaticProps`, this function fetches data from the API and returns the data as props in an object. 

```
async getServerSideProps(context) {
const res = await fetch(‘http://example.com/api/posts’);
  const data = await res.json();
//error handling + return props object with serializable data
  if (!data) {
     { notFound: true } 
   }
  return {
    props: {}
  }
}

```
To reiterate, it's more optimal to pre-render a web-application's pages at build time, than to render them every time a request is made. After the initial build, all markup and all logic is now rendered on the client side, and is now reusable, making re-rendering not necessary.

That's it for part 2! Until next time!
---
Application Insights for Worker Service using Serilog
Tags: dotnet, serilog, applicationinsights, csharp
Published: 2020-12-19 20:48:50

This post is a contribution for [C# Advent Calendar 2020](https://www.csadvent.christmas/). This is a simple guide for implementing [Azure Application Insights](https://docs.microsoft.com/en-us/azure/azure-monitor/app/app-insights-overview) using Serilog in a dotnet core worker service.

.Net Core worker services are best suited for long-running background tasks. These services can be run as a windows service or linux daemons. Worker services comes with DI, logging and configuration features out-of the box. 

First create a new Worker Service project via your favorite terminal using the following simple command
```
dotnet new worker -o WorkerService
```

Install the following Serilog Packages in your project directory.
1. Serilog
2. Serilog.Extensions.Hosting
3. Serilog.Settings.Configuration
4. Serilog.Sinks.Console
5. Serilog.Sinks.ApplicationInsights

```
dotnet add package Serilog
dotnet add package Serilog.Extensions.Hosting
dotnet add package Serilog.Settings.Configuration
dotnet add package Serilog.Settings.Configuration
dotnet add package Serilog.Settings.Configuration
```

Copy your Application Insights Instrumentation Key from Azure Portal and update your appsettings.json with the following json
```
{
  "Serilog": {
    "MinimumLevel": "Debug",
    "WriteTo": [
      "Console",
      {
        "Name": "ApplicationInsights",
        "Args": {
          "instrumentationKey": "__ApplicationInsightsInstrumentationKey__",
          "restrictedToMinimumLevel": "Information",
          "telemetryConverter": "Serilog.Sinks.ApplicationInsights.Sinks.ApplicationInsights.TelemetryConverters.TraceTelemetryConverter, Serilog.Sinks.ApplicationInsights"
        }
      }
    ]
  }
}

```

In **Program.cs** file import Serilog namespace
` using Serilog;` and update your **CreateHostBuilder** to instansiate Serilog logger and chain with **UseSerilog()** method to replace the default logging provider with Serilog.
```
public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureServices((hostContext, services) =>
                {
                    services.AddHostedService<Worker>();
                     Log.Logger = new LoggerConfiguration()
                    .ReadFrom.Configuration(hostContext.Configuration)
                    .CreateLogger();
                }).UseSerilog();
```
Use the following command in your project directory to run the worker service.
```
dotnet run
```
You should start seeing your console messages in your Azure portal Application Insights logs

![Console messages log](https://dev-to-uploads.s3.amazonaws.com/i/0to3n0nuqj1zrbti757h.PNG)


![Application Insights Log](https://dev-to-uploads.s3.amazonaws.com/i/dxz3izp4g3fgemz0yyoe.PNG)
Let your window speak your text
Published: 2020-12-19 20:41:46

Here are the basics you will need for text to speech.
It should work on all browsers but if not you can put if or else statement checking if 'speechSynthesis' in window exists or is supported.
var msg = new SpeechSynthesisUtterance();
msg.text = "Hello, my name is Peter";
window.speechSynthesis.speak(msg);
Havel–Hakimi Algorithm in Java
Tags: java
Published: 2020-12-19 20:19:14

The Havel–Hakimi algorithm is an algorithm in graph theory solving the graph realization problem. That is, it answers the following question: Given a finite list of nonnegative integers, is there a simple graph such that its degree sequence is exactly this list? The degree sequence is a list of numbers that for each vertex of the graph states how many neighbors it has. For a positive answer, the list of integers is called graphic. The algorithm constructs a special solution if one exists or proves that one cannot find a positive answer. This construction is based on a recursive algorithm. The algorithm was published by Havel (1955), and later by Hakimi (1962).

```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
public class HavelHakimi { //Delete all zeros from the list 
  public static void deleteZeros(ArrayList < Integer > list) {
        for (int i = 0; i < list.size(); i++) {
            int num
                = list.get(i);
            if (num == 0) {
                list.remove(i);
                i = 0;
            }
        }
    } //Put thelist in descending order 
    public static void descendingSort(ArrayList list) {
        Collections.sort(list, Collections.reverseOrder());
    }
    //Check the length of the list against a given number       
    public static boolean lengthCheck(int length, ArrayList list) {
        if (length > list.size()) {
            return true;
        } else {
            return false;
        }
    } //Subtract 1 from the first N numbers in the list
    public static void frontElim(int numElim, ArrayList list) {
        System.out.println(numElim);
        System.out.println(list.size());
        if (numElim >= list.size()) {
            System.out.println("Shits fucked.");
        }
        for (int i = 0; i <= numElim; i++) {
            list.set(i, (Integer) list.get(i) -
                1);
        }
    } //Recursively perform the Havel-Hakimi algorithm on a given list 
    public static boolean HavelHakimi(ArrayList list) {
        int N = 0;
        deleteZeros(list);
        if (list.size() == 0) return
        true;
        descendingSort(list);
        N = (int) list.remove(0);
        if (N > list.size()) return false;
        frontElim(N, list);
        return HavelHakimi(list);
    }
    public static void main(String[] args) {
        int numWitness = 10; //create a random list
        Random random = new Random();
        ArrayList < Integer > randList = new ArrayList < Integer > ();
        for (int i = 0; i <= numWitness - 1; i++) {
            randList.add(random.nextInt(15));
        } //Make a pre defined list for testing
        ArrayList < Integer > testList = new ArrayList < Integer > ();
        testList.add(4);
        testList.add(2);
        testList.add(0);
        testList.add(1);
        testList.add(5);
        testList.add(0);
        //Test the algorithm and print the result           
        System.out.println(HavelHakimi(testList));
    }
}
```
f-Strings print in Python 3.6+
Tags: python
Published: 2020-12-19 19:47:18

This is an easy way to print messages in Python. This kind of string needs an "f" to activate the curly brackets in the string for the print function. Let's begin with a simple example like this:

```python
user_name = input("Hello!\nWhat is your name?\n:")

In[1]: Oscar

print(f"OK {user_name}!\nI'm a computer :)")

Out[1]: OK Oscar!
        I'm a computer :)
```

We can use other ways to declare a string with the same result:

```python
value = 3.14159
print(f'{value}')
print(f"pi = {value}")
print(f"""The Pi constant:
this is an approximation: {value}""")
```

We must be careful with the variable inside of the curly brackets because if doesn't exist a SyntaxError will pop up from python, ok that's all also you can use multiples values in a single f-string.

```python
def plus_one(value: int) -> int:
    """sum 1 to input
       input: a number
       output: number + 1"""
    return value + 1


user_name = input("Hello!\nWhat is your name?\n:")
try:
    number = '2'
    ans = plus_one(number)

except Exception as err:
    print(f""">>> Message:
plus_one function doesn't work with {number} like input.
Here is the error honey:
{err}""")

else:
    print(f"Ok {user_name}, {number} plus_one is {ans}.")

finally:
    print("Bye!")
```

Thanks for reading!
How to reverse a string in C++?
Tags: cpp, oop, programming, computerscience
Published: 2020-12-19 18:05:31

How reversing the string works in C++? Assume we have a string as “exam” the reverse form of this string will be “maxe”. There are some methods to reverse a string in c++ and we will be learning them in this article. 

---
title: originally posted here 👇
canonical_url: https://kodlogs.com/blog/455/how-to-reverse-a-string-in-c
--- 

#Methods
 

1. By creating a function
2. Using the inbuilt function
3. Printing reverse

 

For understanding all of the methods, let's take an example of a string. Assume we have a string
`
string str = “abcd”;
`

##Creating a function

We can create our own function to reverse the string in c++. This method is pretty simple, in this method we are creating a function which will swap the characters of the string.
```
#include <iostream>
#include <bits/stdc++.h> 
using namespace std; 
  
void reverseStr(string& str) 
{ 
    int n = str.length(); 
  
  for (int i = 0; i < n / 2; i++) 
        swap(str[i], str[n - i - 1]); 
} 
  

int main() 
{ 
    string str = "abcd"; 
    reverseStr(str); 
    cout << str; 
    return 0; 
}
```
##Inbuilt function

C++ provides inbuilt function reverse() for reversing the characters. The function did all the work by itself, we only need to define it.
```
#include <iostream>
#include <bits/stdc++.h> 
using namespace std; 
 

int main() 
{ 
    string str = "abcd"; 
    reverse(str.begin(), str.end()); 
    cout << str; 
    return 0; 
}
```
##Printing reverse

This method is a little similar to the first one. The only difference is in the first method we are swapping the characters of the string but in this method, we are going to print the characters of the string in the reverse order.
```
#include <iostream>
#include <bits/stdc++.h> 
using namespace std; 
  
void reverse(string str) 
{ 
    
  for (int i = str.length()-1; i >=0; i--) 
        cout << str[i];
} 
  

int main() 
{ 
    string s = "abcd"; 
    reverse(s);  
    return 0; 
}
```
###Output
The output of all three programs will be the same. it will be “dcba”
**Header files**
I used the visual code for testing the programs and it just needed two header files.

#include<iostream> and #include<bits/stdc++.h>

If you are still getting error after adding these header files then try adding #include<algorithm.h>

 

If you have any doubt ask freely.
Font weight reference
Tags: css, beginners
Published: 2020-12-19 19:24:16

Notes from one of my CSS files.


    /**
     * Fonts
     *
     * 100    Extra Light or Ultra Light
     * 200    Light or Thin
     * 300    Book or Demi
     * 400    Normal or Regular
     * 500    Medium
     * 600    Semibold, Demibold
     * 700    Bold
     * 800    Black, Extra Bold or Heavy
     * 900    Extra Black, Fat, Poster or Ultra Black
     *
     * Fonts are prioritized in a list of preference.
     * WOFF2, WOFF, OTF, SVG, EOT, TTF
     *
     * We should only need WOFF2 because of modern browser support,
     * but Apple (obviously) has some issues which requires us to
     * support WOFF asw well.
     */
Memories #03
Tags: webdev, beginners, gamedev, codenewbie
Published: 2020-12-19 19:20:40

## What the hell are you doing

One more old project,
This one done with a lot of HTML, CSS, and Javascript developed in 2017 as a hobby to not be stoped. It has one quest, a few dialogues and a few more things.

It was a funny experience to try new things!


## Do you want to check out?

If you want to check out the video or the code about the project here on the links below:

Links:
[Youtube](https://youtu.be/TdcC63ItCzk)
[Twitter](https://twitter.com/DavidCRicardo/status/1340609322275852293)
Created Music For Dev Community
Tags: showdev
Published: 2020-12-19 19:15:11

I created the soundtrack for the dev community and posted over SoundCloud. 
**Soundtrack**: [Ievan Polkka](https://en.wikipedia.org/wiki/Ievan_polkka) Ft. [Bilal Göregen](https://youtube.fandom.com/wiki/Bilal_G%C3%B6regen) Club Mix.
**SoundCloud Link**: https://soundcloud.com/user-353727136/sanmak-ievan-polkka-ft-bilal-goregen-club-remix

The song is in Finnish language and is trending.

Enjoy this mix and welcome 2021.

{% soundcloud https://soundcloud.com/user-353727136/sanmak-ievan-polkka-ft-bilal-goregen-club-remix %}

To read interesting topics, follow and read <a href="https://boxpiper.com/">BoxPiper blog</a>.

Support my work and [buy me a Coffee](https://ko-fi.com/E1E72C2MM). It'll mean the world to me. 😇

<a href="https://ko-fi.com/E1E72C2MM"><img src="https://cdn.ko-fi.com/cdn/kofi1.png?v=2"/></a>
YouTube Loading animation  Dark Mode 
Tags: html, css, codenewbie, codepen
Published: 2020-12-19 18:58:53

YouTube Loading animation using HTML and CSS with Dark Mode

Source Code=> https://codepen.io/Bilal1909/pen/bGwRJRp?editors=1100


Legend
This is a story which removes the negative stereotype that is associated with Islam in current society, and shows the history of it's proud Ghazi and Beys. A story based on the father of the man who founded the Ottoman empire, created to give insight in the culturally diverse past often ignored. A tale which can be used to inspire many of all beliefs and learn the meaning of what it means to live.
The Sylar Project V 0.0.1
Tags: dohackathon, webdev, mentalhealth
Published: 2020-12-19 13:47:10

I saw the announcement about the digital ocean hackathon and decided to just execute and iterate on an idea I had. I wanted some type of API that allows folks to quickly find mental health resources in their local area. What I've noticed is that while mental health resources do exist in a lot of different places they may be hard to find or buried in some hard to navigate government website. I want to help do the work in making these resources more accessible for folks who are looking to get help for their mental health. 

As of writing this post, I have up an initial version of the site. I am working on adding different mental health resources state by state in the US. Right now I have a couple resources for Alabama and Alaska, I'm working through in Alphabetic order. My hope is others will fork this project and create a Sylar Project specifically for their community/city/country wherever. I can't cover the whole world but if others can help do this work I would love to make sure that all versions of The Sylar Project are linked on the repository as well as the website. 

Check out The Sylar Project here:
https://the-sylar-project-6avzk.ondigitalocean.app/

Contribute to or fork the repository for your community:
https://github.com/Rahat-ch/The_Sylar_Project

I would appreciate stars on the repo as well thank you!
The Simplest Button Counter on Earth!
Tags: ruby
Published: 2020-12-19 18:44:16

[Glimmer DSL for SWT](https://github.com/AndyObtiva/glimmer-dsl-swt) (Ruby Desktop GUI) and [Glimmer DSL for Opal](https://github.com/AndyObtiva/glimmer-dsl-opal) (Ruby Web GUI) had a new release with support for a new sample: Hello, Button!

Desktop GUI:
![Desktop GUI](https://raw.githubusercontent.com/AndyObtiva/glimmer-dsl-swt/master/images/glimmer-hello-button-incremented.png)

Web GUI:

![Web GUI](https://raw.githubusercontent.com/AndyObtiva/glimmer-dsl-opal/master/images/glimmer-dsl-opal-hello-button-incremented.png)

```ruby
class HelloButton
  include Glimmer
  
  attr_accessor :count
  
  def initialize
    @count = 0
  end
  
  def launch
    shell {
      text 'Hello, Button!'
      
      button {
        text bind(self, :count) {|value| "Click To Increment: #{value}  "}
        
        on_widget_selected {
          self.count += 1
        }
      }
    }.open
  end
end

HelloButton.new.launch
```

Notice how utterly simple and intuitive the code is. 

It is simply leveraging a standard Ruby attribute on a class (`:count`), data-binding to it in the GUI (`text bind(self, :count)`), and then using a block to dynamically customize the data-bound property on read from the attribute before displaying in the button text (`{|value| "Click To Increment: #{value}  "}`). 

Otherwise, the `on_widget_selected` event, which gets triggered on click of the button simply calls the `+=` operator in Ruby to do the increment work in the model (`self.count += 1`), and that automatically updates the text in the GUI. 

None of the web template mixing nonsense you see in web examples of it since it is written fully in pure Ruby, thanks to the [Glimmer GUI DSL](https://github.com/AndyObtiva/glimmer-dsl-swt#glimmer-gui-dsl-syntax). 

As such, it is the most concise, understandable, and maintainable code for a button counter. Beautiful, isn't it?!

Originally posted at the Code Master blog:
https://andymaleh.blogspot.com/2020/12/glimmer-hello-button-sample-swt-opal.html

Glimmer DSL for SWT (Ruby Desktop GUI):
https://github.com/AndyObtiva/glimmer-dsl-swt

Glimmer DSL for Opal (Ruby Web GUI):
https://github.com/AndyObtiva/glimmer-dsl-opal
I developed a free Nuxtjs tailwindcss landing page template
Tags: tailwindcss, nuxt, vue
Published: 2020-12-19 18:16:00

---
title: I developed a free Nuxtjs tailwindcss landing page template
published: true

description: free Nuxtjs tailwindcss landing page template

tags: #tailwindcss #nuxtjs #vuejs
//cover_image: ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ybagd0ufn982a7mzeynz.png)
---

I developed this nuxtjs tailwindcss landing page. Also I will start releasing a free one every 1 - 2 weeks
 
Demo: https://bit.ly/3p9ySyE
Download: https://bit.ly/2J8HG8C
ERROR Double Free or Corruption (out).
Tags: programming, computerscience
Published: 2020-12-19 18:08:18

In this article, we are going to discuss another error named “Double Free or Corruption Error”. This is an error related to memory operations. All descriptions and solutions to this error are given ahead of time.

---
title: originally posted here 👇
canonical_url: https://kodlogs.com/blog/332/error-double-free-or-corruption-out
---

#Double Free or Corruption Error
The error Double Free or Corruption Error in the program means that our program has a C runtime function free(). The C runtime function, free(), can be called by mistake or somehow with an invalid pointer. All of this fuss can happen due to the use of dynamic memory allocation or by invoking free() directly.

##Cause
This error is commonly caused if your code has overwritten memory due to an out of bounds array index. For further explanation, you can observe this example.
```
!! Generates a "double free or corruption" error.
program free
  integer, dimension(:), allocatable :: data
  integer :: i

  allocate(data(5))
  do i = 1, 5
     data(i-1) = i
  end do
  deallocate(data)
end program free
```
When we compile this piece of code we will get this error. 
`
./free: double free or corruption (out): 0x0000000000607590
`
##Solution
To resolve this problem we have to track the issue as to where it should be. The way to achieve this is: to check invalid array indexing, compile the program with -fbounds-check. Then when we run it again and if there is any array indexing that is out of bounds then we will get an error message like this.
`
% gfortran -fbounds-check -o free free.f90
% ./free 
At line 8 of file free.f90
Fortran runtime error: Array reference out of bounds for array 'data', lower bound of dimension 1 exceeded (0 < 1)
`
This redirects us to a line of code. Here we can rewrite it and can change it to solve our issues.
useEffect (How Cool is It?)
Tags: react, webdev, useeffect, hooks
Published: 2020-12-19 18:06:01

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ajnbq038rs8t8el7rw01.JPG)

**Learning useEffect vs Enjoying Coffee?**

(*I would prefer useEffect! What about you?*)

**useEffect** Hook lets us to perform **side effects** in react functional components.

It is a replacement of **componentDidMount** , **componentDidUpdate** and **componentWillUnmount** (these are used along-side class-based components to perform side effects). 

Mutations, subscriptions, timers, logging, and other side effects are not allowed inside the main body of a function component. We use **useEffect** hook to overcome these problems. The function passed to useEffect will run after the render is committed to the screen.

*Stay connected for the series of blogs on React hooks with detailed examples!*

What do you think which one is better - **useEffect**  or **componentDidUpdate/Mount**?? 

*Type it down in the comments section below*

**Happy Coding!!**

Cheers!
*-Jayant Khandelwal*

*P.S: If you share it, it will make my day!*

<a href="https://www.buymeacoffee.com/jackent2b" 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>