teleren/devto huggingface dataset:
How to use Lodash chunk function?
Tags: node, javascript, beginners, tutorial
Published: 2022-05-14 14:04:19

Note: This tutorial also exist in my [GitHub](https://github.com/harithzainudin/how-to-lodash#how-to-lodash)

You have a problem where you need to divide an array into a new array and slice it accordingly. How you want to solve this?

Well, we can use Chunk function in Lodash. It is a function that splits an array into smaller arrays. 

It takes two arguments: the array to split and the size of each chunk. The function will returns an array of arrays. If the array cannot be split evenly, the final chunk will contain the remaining elements.

If you are not using Lodash, the solution that you can come out is 

```
const myClassmates = ["John", "Jane", "Jack", "Jill", "Joe"];
const chunkSize = 2;
const newChunk = [];
for (let i = 0; i < myClassmates.length; i += chunkSize) {
  const chunk = myClassmates.slice(i, i + chunkSize);
  newChunk.push(chunk);
}

console.log("After Chunk: ", newChunk);
```
You will be probably using slice function to slice the array where 
First argument - start index of the array to start the extraction 
Second argument - Index of the first element in the array to exclude from the returned array

`slice(start, end)`

To know more about slicing, you can click [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice)

But this solution is quite long and not very clean. Alternatively, now we will be using Lodash chunk function to solve the problem

Example: 

```
const _ = require("lodash")
const myClassmates = ["John", "Jane", "Jack", "Jill", "Joe"];

console.log("Before Chunk: ", myClassmates);
const chunkResult = _.chunk(myClassmates, 2);
console.log("After Chunk: ", chunkResult); 
```

It looks much cleaner right? Only 1 line of code. You just need to provide 2 arguments; the array and the chunk size that you want to slice it. 
Okay, that's all for this week Lodash episode!

---------------------------------------------------------
Thank you for reading :D

Psstt pstt :p
Do consider to love this article ❤️ and follow me! Why not right? It's FREE~ 
I would really appreciate it 👨🏻‍💻 
Will be posting more on things related to AWS, Javascript, Python, Serverless and more!
Go Gin&Gorm: Route Model Binding
Tags: go, programming, webdev
Published: 2022-05-14 15:02:46

Howdy guys,

From my daily work, I'm using PHP & Laravel. One of the feature that I really like & helpful is "Route Model Binding". 

Basically, you just need to define your routes and add the `Model` into the path, magic happens, you'll:
- Get the Model instance and ready-to-use in the Controllers/Middlewares/Requests.
- Receive 404 not found if the record didn't exists.

With Go, we have to build things for our needs, indeed.

Inspired by Laravel Route Model Binding, I built a Middleware for Gin which will help me to achieve that and I don't have to do `Find` then return `error` if not exists from the Controller. Extracted that to another layer.

Repo for the [Middleware - sethsandaru/go-route-model-binding](https://github.com/sethsandaru/go-route-model-binding)

Please give it a ⭐ if you actually like/going to use it 💖

## Feature

Eg: `users/:user` => Find the `User` model instance

- If exists: bind it to the Gin's context via `c.Set` so you can retrieve it 
- If not: return 404 resource not found

It definitely makes our life easier, doesn't it? I hate to do like: "find record, not exists/error => return 404" in the controller, cuz it's not fun and make my controller's methods a bit longer

- Q: Does it support multiple params eg: "users/:user/update-categories/:category"?
- A: Yes

## Mapping - Explicit Binding

Since it won't be as smart as Laravel's way. We need to define a map in order to map your route params with a gORM model.

```go
var routeModelMapping = map[string]modelMapping{
	"entity": makeModelMapping(&models.Entity{}, "uuid"),
	"user": makeModelMapping(&model.User{}, "uuid"),
	// ...
}
```

## Access from Controllers

I love the term Controller and always using MVC in all of my applications.

```go
func (controller *entityController) Show(c *gin.Context) {
	entity, _ := c.Get("entity")
	respondOk(c, entity)
}
```

```go
func (controller *userController) Show(c *gin.Context) {
	user, _ := c.Get("user")
	respondOk(c, user)
}
```

In order to get the correct type, we have to do typeAssertion - guide [here](https://golangcode.com/convert-interface-to-number/)

## Conclusions
- PROs:
  - Automatically retrieve Model instances using gORM
  - 404 not found will be returned if instance not found
  - Extracted the `find` and `check exists` out of the Controller
- CONs:
  - Have to do typeAssertion in order to get the real type

Hopefully you'll like this, just like me hehee. 

Once again, here is the repo [Middleware - sethsandaru/go-route-model-binding](https://github.com/sethsandaru/go-route-model-binding)

Please give it a ⭐ if you actually like/going to use it 💖

I'm using that Middleware from my open-source project [(WIP) Pheasant - Dynamic CRUD Management](https://github.com/sethsandaru/pheasant)

Have a nice weekend and happy go-coding!
What is YOUR theme?
Tags: programming, vscode, opensource
Published: 2022-05-14 14:34:38

What is **_YOUR_** most favorite VSCode theme that everyone should try out? What color theme/syntax highlighting is **the** most superior to you? 

 Mine is anything GruvBox Dark related. I'm currently running a theme Gruvbox ish Dark Medium. See link and picture linked underneath! 

I'd love to hear y'alls opinions and likes! ![Screenshot of the gruvbox theme I mentioned earlier](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0autzavl4jwxrxhq3hdb.png)

[Gruvbox ish by GracefulPotato](https://marketplace.visualstudio.com/items?itemName=GracefulPotato.gruvbox-ish) Thank you GracefulPotato for making the lovely edit on the original gruvbox theme.


Much Love,
Snowciel ❄️
HttpStatusDogs is published! 🐶
Tags: java, spring, showdev, webdev
Published: 2022-05-14 14:08:24

A few years back I wrote a simple Spring Boot starter that adds a header to your HTTP responses with a link to the appropriate HTTP status dog. The pet project (pun intended) was inspired by [Mike Lee's](https://twitter.com/mikeleeorg) project [httpstatusdogs.com](httpstatusdogs.com)

Today I released it on Maven Central! 🥳

### Usage

You can start using it just by adding it to your dependency list like this for Gradle:

```groovy
implementation 'dev.fomenko:httpstatusdogs:1.0.0'
```

or for Maven:

```xml
<dependency>
    <groupId>dev.fomenko</groupId>
    <artifactId>httpstatusdogs</artifactId>
    <version>1.0.0</version>
 </dependency> 
```

So now, for any endpoint, you'll have a HttpStatusDog header.

### Example

Here's an example of a Spring controller

```java
  @RestControllerclass FakeController {
         @GetMapping("/404")
         public String method404(HttpServletResponse response) {
              response.setStatus(404);
              return "Test";
         }
  }
```

and the response it provides: 
```http
HTTP/1.1 404 
StatusDog: https://httpstatusdogs.com/img/404.jpg
Content-Type: text/plain;charset=UTF-8
Content-Length: 5
Date: Fri, 13 May 2022 20:42:44 GMT

Test
```

You can find the code on my GitHub: [https://github.com/michaelfmnkhttpstatusdogs ](https://github.com/michaelfmnk/httpstatusdogs )
Maven Central: [https://search.maven.org/artifact/dev.fomenko/httpstatusdogs/1.0.0/jar](https://search.maven.org/artifact/dev.fomenko/httpstatusdogs/1.0.0/jar)

P.S: For me, this lib is an attempt at releasing my own library. I'm planning on releasing my other projects soon.
Weekly 0012
Tags: weeklyretro
Published: 2022-05-14 14:05:51

### Monday

In the morning I did an internal demo about “Network Guardian” and I received a lot of feedbacks from my colleagues.
I added them to my backlog.

Before lunch I went to the office.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mcvilp0qdk3fyjo5p96n.png) 

**Mood:** 🙂

### Tuesday

Woke up very very early for taking the train to Bern.
It’s the Azure Bootcamp day.

It was amazing to came back at an event in person and met a lot of good guys. It was one of my first time at an event just as an attendee and it was strange 😀

During one of the last sessions of the day, we had presented our product called “Red Origin” in public.

This is the official tweet: [https://twitter.com/kasuken/status/1524634118394454022?s=20&t=6ERpnxKpRdm-_Rbik-_D-A](https://twitter.com/kasuken/status/1524634118394454022?s=20&t=6ERpnxKpRdm-_Rbik-_D-A)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gpfiwklxxoohy6cj03oc.png) 

**Mood**: 🤓

### Wednesday

I worked on “Network Guardian”, nothing special.

In the late evening I started to study Azure PlayFab: a service to add a lot of stuff to the games.
I am using Notion to take notes and to create a knowledge base for the future.
This is the link of my Commonplace book section about PlayFab: [https://humble-split-b30.notion.site/Azure-PlayFab-4dd9532d5f3e49d3bea24b27bf999df5](https://www.notion.so/Azure-PlayFab-4dd9532d5f3e49d3bea24b27bf999df5)

**Mood:** 🙂

### Thursday

A busy day at work and struggled with Groups in SignalR.

I learnt a lot about them.
I think I will write some posts about SignalR and Blazor.

In the very late evening I participated to the Auth0 Ambassador onboarding program. Yes, I am an Auth0 Ambassador since a few weeks. 😊
On monday I will share some details in a blog post!

**Mood: 😐**

### Friday

I added a few features on Network Guardian. One is a page to see how is going the collection data operation. In this view you can see the changes of the json in real time.
It should be useful for the admin. On monday I will show this feature to my team.

During my break I have completed the Bootstrap 5 section in my commonplace book. This is the direct link to this section → [https://humble-split-b30.notion.site/Bootstrap-5-07aa8155d1f747fe818c4c09b20a81fd](https://www.notion.so/Bootstrap-5-07aa8155d1f747fe818c4c09b20a81fd)

In the afternoon I published a new post about Azure and Visual Studio. 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z3ecmtesuuh3aqijcnkz.png) 

[https://dev.to/kasuken/how-to-deploy-multiple-web-apps-on-the-same-azure-app-service-409e](https://dev.to/kasuken/how-to-deploy-multiple-web-apps-on-the-same-azure-app-service-409e)

With this post I achieved a super goal for my blog: 16 week streak!
It means that I wrote at least one post each week for 4 months!!!

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ga6ng0b0ejh7zeqh3gc4.png) 

**Mood:** 🙂
Free Full Stack Developer course offered by the University of Moratuwa with Certification
Tags: javascript, webdev, css, html
Published: 2022-05-14 13:54:24

[Access from Here](https://open.uom.lk/)

If are there any Difficulty to access course, watch this tutorial. 

{% embed https://www.youtube.com/watch?v=O9iA4gWWeKE %}
How to activate windows 11 for free
Tags: windows
Published: 2022-05-14 13:36:14

<img src='https://www.howtogeek.com/wp-content/uploads/2021/06/windows_11_generic_hero_1.jpg?height=200p&trim=2,2,2,2'>
----
<p>Ok so its been some time but I'm back. At least for now... LOL!
Ill show you how you can activate windows 11 for free so read till the end and follow these simple steps.</p>
----
<h1>Activate Windows 11 Using Command Prompt</h1>
<br>
- Go to the Start Menu 
- Type cmd in the search bar
- Run cmd as an administrator
- In cmd, type in the following command and hit Enter.
<br>
<br>

```
slmgr/ipk kmsclientkey
```
</pre>

<br>
<br>
- Home: TX9XD-98N7V-6WMQ6-BX7FG-H8Q99
- Home N: 3KHY7-WNT83-DGQKR-F7HPR-844BM
- Home Single Language: 7HNRX-D7KGG-3K4RQ-4WPJ4-YTDFH
- Home Country Specific: PVMJN-6DFY6-9CCP6-7BKTT-D3WVR
- Professional: W269N-WFGWX-YVC9B-4J6C9-T83GX
- Professional N: MH37W-N47XK-V7XM9-C7227-GCQG9
- Education: NW6C2-QMPVW-D7KKK-3GKT6-VCFB2
- Education N: 2WH4N-8QGBV-H22JP-CT43Q-MDWWJ
- Enterprise: NPPR9-FWDCX-D2C8J-H872K-2YT43
- Enterprise N: DPH2V-TTNVB-4X9Q3-TJR4H-KHJW4

<p>This will install the KMS license key.
Here are some tested and fully functioning Windows 11 license keys</p>

<p>Now type in the following command</p>
```
slmgr /skms s9.us.to
```
</pre>
<p>This will connect you to the KMS server.</p>
<p>Finally, to activate your Windows 11, type in the following command.</p>
<br>
```
slmgr /ato
```
</pre>
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dp6lubq5mja2qrv4lodo.png)
15+ Python Advanced Concepts You Must Know 2022- Codexashish
Published: 2022-05-14 13:32:26

Python is an object-oriented and high-level programming language and getting more popular nowadays because of its dynamic nature, versatility, and ease to learn. Python is the second most preferred programming language after JavaScript and it can be used in any field like Artificial Intelligence, Machine learning, Deep learning, and Web Development.

In this article, we are going to see 15+ advanced python concepts that you must know if you are a python developer. If you want to learn python programming or you are a python developer then you must know these python advanced concepts. So let's start this article without wasting any time:
Table Of Contents

# 1. lambda Function
A lambda is a small anonymous function that can take any number of arguments but can only have one expression. A general python function is defined using the style of def function_name(), but with the lambda function, we don't give it a name. The Lambda function is very important because the purpose of this function is to perform some kind of simple and operational expression without the need for fully defining a function.

**The Syntax of Lambda Function:**

_lambda arguments : expression_

# 2. Map Function
Python programming has a built-in function called map() which returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable(tuple, list or dict, etc.). The map function is most importantly a readable way to perform such an operation.

**The syntax for Map Function:**

_map(function, iterable)_

# 3. Filtering
The filter is also a python built-in function which is quite similar to the Map function. The main difference between map() and filter() is that the filter function only returns the filtered elements as True from a given sequence. 

**The Syntax of Filter Function:**

_filter(function, itertools)_

# 4. Generator
A generator function is used to allow you to declare a function that behaves like an iterator and it also allows programmers to make an iterator in an easy and fast way. A generator is a special type of function in python programming which does not return a single value instead it returns an iterable generator object. In the generator, the function yield statement is used rather than the return statement. 

## 
[Click Here to read more](https://www.codexashish.com/2022/05/15-python-advanced-concepts-you-must-know.html)

**Thankyou 
Codexashish**
Meu editor Neovim
Tags: vim, neovim, programming
Published: 2022-05-14 13:29:59

Tudo começou quando eu assistir esse vídeo [Vim - mais que um editor - com Magnun Leno](https://youtu.be/UUzW46SeLhg)

_Pior que deu vontade de assistir novamente e aprendi mais coisas!_

Por conta desse vídeo fiz um teste, mas acabei não continuando. Já testei o sublime text, atom, vscode dentre outros.

Mas por usar teclado + mouse acabei sentindo dores como tendinite e bursite, dentro de uma semana logo na terça-feira eu já
sentia dores. Até que assistir outro vídeo sobre vim e o cara citou novamente que não sentia mais dores e então não tive
escolha a não ser testar novamente.

Então cá estou e não tenho arrependimento algum dessa migração e agora estou divulgando por ter me ajudado muito e
aprendendo ser o que mais gosto.

Essa é a carinha da minha criança (neovim + tmux) [meu repositório](https://github.com/evertonlopesc/nvim.git)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/57kmu0n4pba75vtjzfuq.png)

Com ele eu trabalho usando Ruby on Rails, Javascript, Lua, VueJs, HTML, CSS, Tailwindcss, mas lembrando que você pode usar
outras linguagens.

Esse vai ser a minha introdução falando sobre esse super editor que pode ficar a sua cara e lhe ajudar de diversas
formas.
Using FNM with Nushell
Tags: programming, shell, linux, node
Published: 2022-05-14 13:27:45

### A new type of shell
[Nushell](https://www.nushell.sh/) is a cross-platform shell with a built-in powerful plugin system, but where the Nushell shines is in the way it displays the output.

![Output of ls command](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2vmmjiwdf0hepvai2i6s.png)

Outputs are in table format and can be filtered and sorted.

![Output of ls command, filtered to display only the directories sorted by recently modified](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r7el9ovho4wbzrwxsqsu.png)

The output of ls command, filtered to display only the directories sorted by recently modified.

***

### FNM - Fast Node Manager
[FNM](https://github.com/Schniz/fnm) describes itself as a fast and simple Node.JS version manager, built in Rust.

#### Install and configure FNM

- Open the terminal and switch to Nushell.

- Install FNM using the following command.
```
curl -fsSL https://fnm.vercel.app/install | bash
```
- Find the Nushell config by running the following command.
```
$nu.config-path
```
![$nu.config-path output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b9z8oii9qn6b20j43gtk.png)
- Open the config file in any text editor like vim and add the following lines at the end.

```
$env.PATH = ($env.PATH | prepend "/home/vaibhavdn/.fnm")
```
Here we are adding the location where the FNM was installed to the PATH environment.

```
load-env (fnm env --shell bash | lines | str replace 'export ' '' | str replace -a '"' '' | split column = | rename name value | where name != "FNM_ARCH" && name != "PATH" | reduce -f {} {|it, acc| $acc | upsert $it.name $it.value })
```
Then we load the FNM_MULTISHELL_PATH

The output of the command used to load FNM_MULTISHELL_PATH
![Loading FNM multi-shell path](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a8vcbtpbskltb2oc6sgt.png)

```
$env.PATH = ($env.PATH | prepend $"($env.FNM_MULTISHELL_PATH)/bin")
```
Finally we add the loaded FNM_MULTISHELL_PATH to the PATH environment.

Save the file and restart the terminal.
FNM is ready to be used now!!

***

Edit - Nov 2023:
Updated syntax to use $env.PATH in place of let-env PATH. Thanks to @treipatru 

***

References
1. https://www.nushell.sh/book/
2. https://github.com/Schniz/fnm
3. https://github.com/Schniz/fnm/issues/463
What is Section 230?
Tags: watercooler, news
Published: 2022-05-14 13:08:33

What to remember about section 230 of the Communications Decency Act of 1996: it impacts everyone. Section 230s objective is to promote the development of the world wide web by providing immunity to web providers and users alike. This immunity granted by section 230 covers granting online access to information created by third parties and acting in good faith to edit or restrict access to objectionable material, even if the material would be considered protected constitutionally. Its impact on big tech giants like Facebook, Twitter, and Google shows us how section 230 has shaped today’s social communities and how we begin to look at moderating content.
Why I am considering Go
Tags: go, javascript, python
Published: 2022-05-14 12:45:51

**1. Never Really Liked Javascript**
JS is a great language and I am grateful for it but its flaky at times there have been instances when it made my life hell! 
So when I heard about Go, I said to myself "Why not?!"

**2. Relatively Easy to Learn**
Its only my first week of learning Go and I already feel comfortable writing Go code. IMHO, if you have previous programming experience you should be up and running writing services in Go really quick.

**3. Performance**

Go is simply quicker and does what Python or NodeJS does but better. Higher max IO, faster arithmetic faster general operation.

But how fast?

That's exactly i wanted to know so I ran benchmarks with FastAPI(Python), ExpressJS(NodeJS) and Gin(Go). 

**Test setup:**

_8 Core CPU_
_8GB RAM_

FastAPI with Uvicorn ASGI server scaled to 4 worker nodes with Gunicorn.(idk why but, when I tried to scale it more than 4 workers the performance got worse)

ExpressJS with Cluster Module scaled to 8 cores.

Go-Gin GOMAXPROCS=8.

**My findings:**

![FastAPI with Uvicorn ASGI server scaled to 4 worker nodes with Gunicorn](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ukibel98r9t47qzli39z.png)


![ExpressJS with Cluster Module scaled to 8 cores](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/viaqmbwk53ev8952a6vr.png)

![Go-Gin with single core](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eb0mbh83ahy9vfulfdca.png)
PyScript - JavaScript's sweet cousin.
Tags: javascript, python, webdev, programming
Published: 2022-05-14 12:30:02

🐍 Python in browser movement gained some momentum nowadays. All thanks to the PyScript library. See how easy it is to bring it into a simple HTML page with no additional setup:


![PyScript in html](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5wbmcigac65ekmjvsflj.png)
![Website running PyScript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r7samz510xwq7b08xx4c.png)

Although the current version is not that mature it holds a ton of potential. 

> It's WebAssembly magic under the hood... 😉

Personally, the benefits I see are:

1. Running complex data structures in the browser. 
2. Not depending on python installation to run python.

### Do share your thoughts and use cases for it.
How to test code that works with an external API: a stub on Sinatra
Tags: ruby, testing, programming
Published: 2022-05-14 10:15:32

Imagine a situation: your application relies on an external service responsible for card charges. The service has a tiny API: get the card number (mask) by user ID, charge `X` dollars from the user. How do we test the code that works with this API?

Of course, you can actually request that external service in the tests. Maybe it even has a sandbox for such cases. But this solution is not so efficient. First of all, it slows down the tests: every request has a time cost. Secondly, it makes tests flaky: network issues will cause them to randomly fail. Thirdly, it's not always possible: the external service may have no sandbox or have strict request limits.

In such cases, it is better to use stubs for external services. I use four options of stubs, depending on the external service: is it my own or someone else's, stable or frequently changing?

One of the options is a fake service on Sinatra. Such as this one:
```ruby
let(:fake_api) do
  Class.new Sinatra::Base do
    get "/users/:user_id/card" do
      content_type :json

      { number: "4111...1111" }.to_json
    end
  end
end

before do
  stub_request(:any, /api.nanocashier.com/).to_rack(fake_api)
end
```

There are two interesting things in the above code. Firstly, `Class.new` with the `Sinatra::Base` parent in `let`, so you don't add a global constant from the test. Secondly, the `stub_request` of Webmock, which routes all requests to the rack application.

I use such rack-based stubs when I have to mock an external service which doesn't have its own stubs (e.g. stripe-ruby-mock) and making adapter-like stub is not possible.