teleren/devto huggingface dataset:
My first NPM library — pronouns.js
Tags: typescript, devpride, npm, javascript
Published: 2023-06-04 23:19:57

Hey all! This is my first post on DEV... Let's see how it goes.

## My story

I started writing a library a while ago — back in January — for a way to CRUD pronouns in JavaScript. (Don't worry, it's not as bad as I made it sound.) I originally needed this for my Discord bot, but after many searches on NPM, I realized I was going to have to write this myself. I, being my unimaginative self, decided to call it **pronouns.js**.

So I followed countless tutorials on NPM packaging with no results for a while, eventually giving up. After a week or so, I went back to NPM's docs and looked through them again. And finally, some success! I left it and came back to it a lot, bringing it to its current state.

It's been through a _lot_ of changes since its first release. v1.0.0 only worked with TypeScript, and the docs I wrote were horrid. I was publishing up to 5 different minor versions on some days. (Now I know better.) Eventually, I realized that JavaScript users would not be able to use it at all, setting me on the journey of learning to use declaration files.

Then came the final stretch: this past month, I've been frantically editing JSDoc comments to generate some readable documentation. I stumbled upon [Docma](https://onury.io/docma) a while ago, and its beautiful layout immediately convinced me to use it. After spending hours messing around with my `docma.config.jsonc` file, I got frustrated once again. The docs simply would not render images and HTML in Markdown properly, and it was also completely ignoring a type definition. I couldn't find any other packages using Docma, so I had no example to follow. I stopped working on this project and started writing a CLI file trashing system. When I looked for a simple JSON key-value database system, I was shocked — its docs were built using Docma. Quickly picking up the semantics of the config file, I built the docs properly, and this time it all fell together.

That brings this story to the present time, at which I have published some docs [here](https://pronouns-js.vercel.app/). I am waiting on DNS verification, but if all goes well, the same site will be hosted on [this fancy subdomain](https://pronouns.js.org). The NPM package can be viewed [here](https://npmjs.com/package/pronouns.js), and the GitHub repository is [akpi816218/pronouns.js](https://github.com/akpi816218/pronouns.js).

I, as a result of learning how to do this, now have 5 packages on NPM.

Thanks for reading, and have a great pride month!

🏳️‍🌈🏳️‍🌈🏳️‍🌈

## Extras:


![pretty docs!!!](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w6k5jg9bl0kly2y9wc3p.png)
Javascript Memoized Functions
Published: 2023-06-04 23:16:11

Memoization is an optimization technique that makes applications more efficient and hence faster. It does this by storing computation results in cache, and retrieving that same information from the cache the next time it's needed instead of computing it again.

```
function memoize(fn) {
  const cache = new Map();
  return (...args) => {
    const key = JSON.stringify(args);
    if (cache.has(key)) {
      console.log(`fetching from cahce for args ${key}`);
      return cache.get(key);
    }
    const data = fn.apply(this, args);
    cache.set(key, data);
    return data;
  };
}

```

```
const addThreeNums = (a, b, c) => a + b + c;
const add = memoize(addThreeNums);
console.log(add(1, 2, 3));
console.log(add(1, 2, 3));

const factorial = memoize((x) => {
  if (x === 0) return 1;
  else return x * factorial(x - 1);
});

console.log(factorial(5));
console.log(factorial(6));
```
Integration testing concept
Tags: testing
Published: 2023-06-04 23:15:01

Integration testing là một loại test nhằm đảm bảo rằng các thành phần, module của phần mềm hoạt động đúng cách khi được tích hợp với nhau.

Trong khi unit test tập trung vào từng đơn vị code riêng lẻ, integration test tập trung vào việc tích hợp nhiều đơn vị lại với nhau.

Cụ thể:

Integration test kiểm tra sự tương tác giữa các module/component khác nhau.

Nó liên quan đến tích hợp các phần phần mềm với nhau, ví dụ API với ứng dụng, ứng dụng với cơ sở dữ liệu,...

Việc integration test được thực hiện sau khi unit test các thành phần riêng lẻ.

Nó giúp phát hiện các vấn đề tương tác giữa các thành phần khi được tích hợp với nhau.

Test việc tích hợp API với ứng dụng để kiểm tra liệu ứng dụng có gọi đúng API và xử lý dữ liệu từ API một cách chính xác.

Test ứng dụng với cơ sở dữ liệu để đảm bảo việc truy vấn, cập nhật dữ liệu được thực hiện đúng.

Nói tóm lại, integration test là kiểm tra sự tương tác giữa các thành phần đã được unit test để đảm bảo chúng hoạt động đúng khi tích hợp với nhau.

Ví dụ:

```
[TestClass]
public class ApiIntegrationTest 
{
    [TestMethod]   
    public void GetData_CheckResult()
    {
        // Gọi API
        var apiResult = Api.GetData();
        
        // Gọi ứng dụng xử lý dữ liệu từ API         
        var result = App.ProcessData(apiResult);  
        
        // Kiểm tra kết quả
        Assert.AreEqual(expectedResult, result);    
    }
}
```
Ở đây tương tự:

Chúng ta gọi API bằng Api.GetData()

Gọi ứng dụng xử lý dữ liệu từ API bằng App.ProcessData(apiResult)

Cuối cùng assert kết quả trả về với kết quả mong đợi.

Đây là một đoạn integration test đơn giản để kiểm tra sự tương tác giữa API và ứng dụng bằng C# .NET.

Những điểm chính khi viết integration test:

Khởi tạo dữ liệu mock nếu cần để test

Gọi các component cần test tương tác với nhau

Kiểm tra kết quả trả về

Ưu tiên dùng database in-memory để test nhanh hơn.

Các loại test này rất quan trọng để đảm bảo mọi thứ hoạt động đúng đắn khi được tích hợp.
Full-stack Blockchain with Andrew
Tags: webdev, blockchain, developer, javascript
Published: 2023-06-04 23:08:47

Whenever I am asked to think about my mentoring experiences, it is an automatic habit to think of times I have been mentored. But the truth is, I have mentored as well.

## My Mentor

Recently, I met a great mentor named Andrew James Okpainmo, who is a blockchain expert and put together his wealth of mentorship experience to bring out the best in all the specially privileged mentees that will be participating.

The mentorship encompasses full-stack blockchain with the proper understanding of MongoDB, Web Sockets, AWS S3, Solidity, Remix IDE, Hardhat, Ethereum, and the Polygon (L2) blockchain.
As a mentor, your job is to encourage your protégé to reach for the stars. Reassuring your mentees and helping them gain confidence in their abilities is important. This is the ultimate job as a mentor, and you will likely find it an equally rewarding experience for all.

## What have I learned from mentorship?

Through these mentorship experiences, I have discovered many different things about myself and new technologies. During every mentorship call, there is an agenda for the meeting and a focus for our deliberations among the mentees.

My full-stack blockchain experience with Andrew as my mentor has been transformative. I have not only had the privilege of being mentored by an expert in the field, but I have also grown as a mentee and learned invaluable lessons along the way.

## Conclusion

I am excited to apply the knowledge and insights gained from this mentorship to my future endeavors, knowing that I have a strong foundation to succeed.

**Thanks for reading.**
Unit testing concept
Tags: testing
Published: 2023-06-04 23:07:48

Unit test là một loại test cụ thể được sử dụng trong TDD.

Unit test là test mỗi đơn vị/module riêng biệt của code như một class, function hoặc method.

Nó được dùng để:

Kiểm tra hàm/phương thức đó hoạt động đúng như mong đợi.

Tìm ra các lỗi ngay từ ban đầu trong quá trình phát triển code.

Giúp bảo trì và mở rộng code dễ dàng hơn bằng cách chạy các unit test khi có sự thay đổi xảy ra.

Ví dụ đoạn code dưới đây: 

```
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTestProject1
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            // Arrange
            var calculator = new Calculator();
            
            // Act
            var result = calculator.Add(2, 3); 

            // Assert 
            Assert.AreEqual(5, result);
        }
    }
}
```
Giải thích:

TestClass: Đánh dấu lớp chứa các unit test.

TestMethod: Đánh dấu phương thức là một unit test.

Arrange: Chuẩn bị dữ liệu cần thiết.

Act: Thực hiện hành động cần test.

Assert: Kiểm tra kết quả có đúng như mong đợi hay không.
Polyfill Array.flat
Tags: javascript, programming, beginners, tutorial
Published: 2023-06-04 22:54:56

A polyfill is a piece of code that provides functionality that's not natively supported by a web browser.

If you're working with a browser that doesn't support the flat() method, you can use a polyfill to provide the same functionality. Here's an example of how you can create a polyfill for the flat() method:

```
if (!Array.prototype.flat) {
  Array.prototype.flat = function(depth) {
    var flattened = [];

    function flatten(arr, currentDepth) {
      for (var i = 0; i < arr.length; i++) {
        if (Array.isArray(arr[i]) && currentDepth < depth) {
          flatten(arr[i], currentDepth + 1);
        } else {
          flattened.push(arr[i]);
        }
      }
    }

    flatten(this, 0);

    return flattened;
  };
}
```

The implementation of the flat() method is done recursively. The flatten() function takes an array arr and a current depth currentDepth. If the arr is an array and the currentDepth is less than depth, then the flatten() function is called recursively with the nested array and the currentDepth incremented by 1. Otherwise, the elements of the array are pushed onto the flattened array.

Usage

```
var nestedArray = [
  [1, 2, 3],
  [4, 5, [6, 7, [8, 9, [10]]]],
  [7, 8, 9],
];

nestedArray.customFlat(2) 

// [ 1, 2, 3, 4, 5, 6, 7, [ 8, 9, [ 10 ] ], 7, 8, 9 ]
```
How to use file templates in vim
Tags: vim, templates, neovim, programming
Published: 2023-06-04 21:54:39

In the modern world boilerplate is something that we as developers just got used to as part of the job and part of all mainstream frameworks used today, but it's a pain to manage all that by hand specially when you don't want to keep running `generators` commands (some frameworks don't even have those generators commands 😥)

It would be awesome to let our editor deal with this part while allowing us to focus on what pay the bills, right? Well, vim got you cover!

In the help page for `:help skeleton` you can find pretty much all the basics you want for templates, basically you write the template you want in a file like `~/.vim/templates/c_main.c`:

```c
int main () {
 return 0;
}
```

After that, you declare a simple autocmd to insert it when a new file is made:

```vim
autocmd BufNewFile *.c 0r ~/.vim/templates/c_main.c
```

And voilà! When you create a new file with `:e main.c` the content will be inserted automatically

> WARNING: This doesn't work from the command like, just with the :e command

But let's add a little caviar to this receipt by applying the goodness of vim script! We'll define a template for a simple react component that follows the pattern `ComponentName/index.tsx`, the idea is to insert a new component with the right name based on the folder. Cool right?

First, we'll define the template in `~/.vim/templates/react_component.tsx`

```tsx
export const %component_name% = () => {
  return <h1>%component_name%</h1>;
};
```

Notice the `%component_name%`, this will be used to replace with the folder name.

Now we add our autocmd:

```vim
autocmd BufNewFile */**/index.tsx 0r ~/.vim/templates/react_component.tsx | %s/%component_name%/\=expand('%:h:t')
```

Notice that our pattern is much more narrow this time, we want to match only `index.tsx` files that have a folder as its parent. Another important part to keep track is the `\=` in the substitution command, this is an expansion for vim script, so we can use the function `expand('%:h:t')` as part of the substitution

> Tip: you can read more about the substitution pattern with :help \\=

The result is as we expect:

<https://asciinema.org/a/w30ozGvQIVGsoa8WGik66NxOC>

![New react component](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nj349zurj7yvjam2wwkp.png)
Animal Search App
Tags: githubhack23, actionshackathon, react
Published: 2023-05-20 17:58:18

## What I built 

A Simple React App With Express Server to Search for randomly generated animal names.

---
### Category Submission: Wacky Wildcards

---
### App Link
https://animalfarm-8u9v.onrender.com

---
### Screenshots 

![Home Page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ahz7opq0ziaf5bnecovn.jpg)

![Search View](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l2dma0mtmfovznc8471v.jpg)

---
### Description 
A Simple React App With Express Server to Search for randomly generated animal names. It uses Chance library to generate random animal names and other data and also uses Material UI for UI. 

---
### Link to Source Code 
https://github.com/rony0000013/animalfarm

---
### Permissive License 
MIT License
https://github.com/rony0000013/animalfarm/blob/master/LICENSE

---
## Background (What made you decide to build this particular app? What inspired you?) 
I had learned react and various other things. So to prototype and increase my knowledge base I learned and used Material UI, Github Actions, Express, etc and used them to build a simple app.

---
### How I built it (How did you utilize GitHub Actions or GitHub Codespaces? Did you learn something new along the way? Pick up a new skill?) 
- I build the app in a Github Codespace.
- The React App was simple and I used Express for backend server to send data. I also implemented search with query parameter in express backend.
- I learned and used Material UI, Github Actions, Express, etc and used them in the app. 
- I created basic Guithub Action CI test for errors before deploying after commit and another action for code analysis after commit.

---
### Additional Resources/Info
https://docs.github.com/en/actions
https://react.dev/learn
https://expressjs.com/en/starter/hello-world.html
https://mui.com/material-ui/getting-started/overview/
Speed Up Your Woocommerce Store With These 9 Tips
Published: 2023-06-04 21:45:43

With the right optimizations, you can speed up your woocommerce store by up to 50%. In this post, we will cover the 5 most common woocommerce issues and how to fix them.

What is the Woocommerce Issue?
The woocommerce issue is the main reason that your woocommerce store is not loading as fast as it should. There are 5 common woocommerce issues and we will cover each one in detail.

How to Fix the Woocommerce Issue?

Check If Your Website Is Optimized for Mobile Viewing:
Make sure that your website is optimized for mobile viewing. This will speed up your woocommerce store overall.

Remove Unnecessary CSS and JavaScript Files:
Remove any unnecessary CSS and JavaScript files from your website. This will reduce the load time of your woocommerce store.

Clear Your Cache:
Clear your cache on your website to speed up your woocommerce store.

Use Amazon S3 for Storage:
Using Amazon S3 for storage can speed up your woocommerce store by offloading storing bulk data to the cloud.

Enable GZip Compression:
Enable GZip compression on your website to speed up the loading of your woocommerce store pages.

Optimize Your Images:
Make sure that your images are optimized and are loading quickly. This will also [speed up your woocommerce store](https://www.cloudways.com/blog/speed-up-woocommerce/).

Optimize Your Code:
Make sure that your code is optimized and is loading quickly. This will also speed up your woocommerce store.

Remove Unnecessary Files:
Remove any unnecessary files from your woocommerce store. This will also speed up your woocommerce store.

Check for Broken Links:
Check for any broken links and fix them if necessary. This will also speed up your woocommerce store.

Conclusion
By following these 9 simple steps, you can speed up your woocommerce store.
Thymeleaf
Tags: webdev, spring
Published: 2023-04-11 22:26:43

## What is Thymeleaf
Thymeleaf는 server-side JAVA 기반의 template engine 이다.
Spring boot 가 권장하는 템플릿 엔진 중 하나이다.(Groovy, Thymeleaf, FreeMarker..) 그동안 사용해왔던 jsp보다 더 간단한 설정과 표준 문법으로 HTML을 작성할 수 있다. Thymeleaf는 웹 표준, 특히 HTML5 에 맞춰 설계되었기에 완전히 검증된 템플릿을 만들 수 있다.
JSP의 경우, tag libraries를 사용하는 경우, HTML 표준 태그가 아니기에 브라우저가 해석할 수 없는 코드가 된다.

```
<form:inputText name="userName" value="${user.name}" />
```
Thymeleaf를 이용하여 작성한 경우, 브라우저가 해석할 수 있는 코드가 된다. 문법 역시 깔끔하게 보인다.
```
<input type="text" name="userName" value="James Carrot" th:value="${user.name}" />
```
이로 인해 퍼블리셔, 디자인과 개발팀의 격차를 해소하며 커뮤니케이션을 개선할 수 있는 것을 어필한다.(공식 doc에서..)

## Standard Expression Syntax
[Simple expressions]
Variable Expressions: ${...}
Selection Variable Expressions: *{...}
Message Expressions: #{...}
Link URL Expressions: @{...}
Fragment Expressions: ~{...}
 
[Text operations]
String concatenation: +
Literal substitutions: |The name is ${name}|
 
## Thymeleaf Doc
[Tutorial: Using Thymeleaf](https://www.thymeleaf.org/doc/tutorials/3.1/usingthymeleaf.html)

## Conclusion
사용해보니 개발할 때도 Thymeleaf 가 훨씬 편하다. jsp의 경우 view 템플릿 레더링을 Servlet Container가 하기 때문에 결과를 보는데 딜레이가 있다. 반면 Thymeleaf의 경우는 Servlet Container 개입없이 최종 View를 완성하므로, 바로 확인이 수월하다. 테스트 시에도 Servlet Container를 띄울 필요가 없으므로 mockMVC으로도 테스트 코드 작성이 가능하다.
만약 frond-end 개발자가 Thymeleaf없이 view를 랜더링해서 만들고 있다는 경우라면, 이를 고려하여 attribute 도 추가해줘야 한다..
UPDATE RETURNING OLD | NEW in YugabyteDB and PostgreSQL
Tags: distributed, postgres, yugabytedb, database
Published: 2023-06-04 20:36:42

It is a good idea to prefer UPDATE ... RETURNING instead of a two-statement transaction with an UPDATE and a SELECT. By default, the new value is returned. Oracle 23c has added the possibility to [return the old values](https://oracle-base.com/articles/23c/dml-returning-clause-enhancements-23c). 

Here is how to do the same in YugabyteDB and PostgreSQL.

```sql
yugabyte=# create table demo (id bigint primary key, value text);
CREATE TABLE

yugabyte=# insert into demo 
           select generate_series(1,50), '...old...';
INSERT 0 50

yugabyte=# update demo set value='...new...' where id=42
           returning id, value;

 id |   value
----+-----------
 42 | ...new...
(1 row)

UPDATE 1

```

Here is how I run the same to return the old and new values:
```sql
yugabyte=# with old as (select * from demo where id=42)
           update demo new set value='...new...'
           from old where old.id=new.id
           returning new.id, old.value, new.value ;

 id | old_value | new_value
----+-----------+-----------
 42 | ...old... | ...new...

(1 row)

UPDATE 1
```

The WITH clause (also called CTE for Common Table Expression) is very helpful to do multiple reads and write operations within one statement. The advantage of declaring the logic in a single SQL statement makes it more efficient and scalable by reducing the roundtrips, increasing the possibilities of transparent retries (on clock skew for example) and avoiding anomalies even in read committed isolation level.
Fleet un editor de texto minimalista
Tags: javascript, beginners, tooling
Published: 2023-06-04 20:23:29

En este video muestro una de las herramientas que he estado ocupando las ultimas semanas y creo que Fleet es un buen contendiente a sustituir a VS Code.

{% embed https://www.youtube.com/embed/YVS_h_6dVJI %}
Building Modern Data Streaming Apps with Open Source - Timothy Spann, St...
Published: 2023-06-05 14:19:05

---
title: Building Modern Data Streaming Apps with Open Source - Timothy Spann, St...
published: true
date: 2023-06-04 20:12:00 UTC
tags: 
canonical_url: 
---

<iframe frameborder="0" height="270" src="https://youtube.com/embed/WvPqE8J3ZOE" style="background-image: url(https://i.ytimg.com/vi/WvPqE8J3ZOE/hqdefault.jpg);" width="480"></iframe>
Why Aren't There A Lot of Transgender CS Students?
Tags: devpride, transgenderfirst, discuss
Published: 2023-06-04 18:52:04

### Lack of Scholarships
We all know that college is scary and expensive. To pay for college we have to apply to scholarships and sometimes take out student loans. As a non-binary person, I looked specifically for scholarships for LGBTQ+ students, but I didn't find a lot of them. Even after applying to other scholarships, I still am in need of a student loan and that's a terrifying thought. The lack of scholarships for transgender and genderqueer students makes it hard for them to pay for college, which results in many of them not entering the field.

### Lack of Inclusive Options
Colleges have male dorms and female dorms. Where does a trans person fit in? A trans woman would like to sleep in the female dorm, but there are always the people who will make an issue about that. The dorms at most, if not all colleges, are split into only two genders and that leaves out room for trans and non-binary people. 

### Computer Science Is Still Male-Dominated
Women have struggled to break into the computer science industry for decades, despite having been the earliest computer programmers. The male-dominated computer science field has a hard time accepting women, and an even harder time accept genderqueer people. This causes many trans and non-binary people from leaving the field due to the rejection they face as computer science students.

Luckily I came across the Transgender First scholarship. This is a scholarship for trans and non-binary people to help them get through college. You can find them at their [website here](https://www.onlinedegree.com/transgender-first-scholarship/).
Hacker News API & fechting data with React js
Tags: api, webdev, react, javascript
Published: 2023-06-04 20:02:57


To `fetch `data from the Hacker News API using React.js, you can utilize the fetch function or the `axios `library. Here's an example using the `fetch `function:

**1. Install the `axios `library (if not already installed):**

```
npm install axios
```

**2. In your React component file, import the necessary dependencies:**

```
import React, { useEffect, useState } from 'react';
import axios from 'axios';
```

**3. Create a component and define a state variable to store the fetched data:**

```
const HackerNews = () => {
  const [newsData, setNewsData] = useState([]);

  useEffect(() => {
    fetchNewsData();
  }, []);

  const fetchNewsData = async () => {
    try {
      const response = await axios.get('https://hacker-news.firebaseio.com/v0/topstories.json');
      const data = response.data.slice(0, 5); // Fetching top 5 stories
      setNewsData(data);
    } catch (error) {
      console.error('Error fetching Hacker News data:', error);
    }
  };

  return (
    <div>
      <h1>Hacker News Top Stories</h1>
      <ul>
        {newsData.map((storyId) => (
          <li key={storyId}>{storyId}</li>
        ))}
      </ul>
    </div>
  );
};

export default HackerNews;
```

**4. Render the component wherever desired in your application:**

```
import React from 'react';
import HackerNews from './HackerNews';

const App = () => {
  return (
    <div>
      <h1>My App</h1>
      <HackerNews />
    </div>
  );
};

export default App;
```
In this example, we fetch the top story IDs from the Hacker News API and store them in the `newsData `state variable. We then render the top story IDs as list items in the component. You can customize the fetching logic and the way you display the data according to your requirements.

Remember to handle any errors that may occur during the API request and adjust the API endpoint or parameters as needed for different data types (e.g., comments, user data),
you can also see [how to fetch data in Next.js 14](https://www.medcode.dev/blogs/nextjs-ways-fetch-data-api)