teleren/devto huggingface dataset:
➡️👷💪 Linear Class Builder
Tags: typescript, deno, oop, javascript
Published: 2023-05-14 16:49:24

> **TLDR**: [Github @reggi/linear-builder-class](https://github.com/reggi/linear-builder-class) Code Generates Classes using the Linear Builder Class pattern

My goal is to define types and ensure that the generic values "match" from one method to the next. 

```ts
new Example()
  .stringOrNumber(1)
  .toObject((knowsItsANumber) => {
    return { yepStillKnows: knowsItsANumber }
  })
  .chainMe(({ yepStillKnows }) => {
    return yepStillKnows + 1
  })
  .done (stillANumber => {
    console.log(stillANumber) // number
  })
```

> Note: this 👆 is `example_two`

One common approach to achieve this is to maintain separate class instances that are returned for each method, instead of returning this and having a regular class where all methods are on that one class. With the latter approach, each "set" value can't be dynamically typed. By passing in a value and returning a new class instance, you can keep track of the types. This is a linear process because you can only set one property at a time in the same sequence. Due to the way that generics work, the only way to do this effectivly is to create and return new class instances which can result in a lot of boilerplate code. That's where this tool comes in. This creates the scaffolding classes required to pull this off.

What is a [builder class](https://refactoring.guru/design-patterns/builder/typescript/example)? It's a pattern of class creation where class methods generally return `this`, and you chain methods together, internal class state manages changes, an example is something like `builder.getProduct().listParts()`. With this project, I was interested in creating generating the code for a class from a small definition. 

```
request*: Request
pathname*: string
match: MatchHandler<M>
data: DataHandler<M, D>
component: ComponentHandler<M>
```

> Note: the `*` syntax means the type is a "native" type and it shouldn't be included when using the `importsFrom` option.

Builds a class with these methods:

```ts
new Leaf()
  .request(new Request('https://example.com'))  
  .pathname('/hello-world')
  .match(async (_req, ctx) => {
    const match = new URLPattern({ pathname: ctx.pathname }).exec(ctx.url.pathname)
    const age = ctx.url.searchParams.get('age')
    if (!match) return null
    if (!age) throw new Error('missing age param')
    const x = await Promise.resolve({ age })
    return x
  })
  .data(async data => {
    const x = await Promise.resolve({ ...data })
    return { age: parseInt(x.age)}
  })
  .component(props => {
    return <div>{props.age}</div>
  })
```

Where the return value is a class with these properties.

```
{
  request: Request
  pathname: string,
  match: MatchHandler<M>,
  data: DataHandler<M, D>,
  component: ComponentHandler<M>,
}
```

This example was created using Deno, you can build the code using:

```
deno run -A ./example/build.ts > example/leaf.ts
```

and run the usage using:

```
deno run example/usage.tsx
```

[Cover Attribution Creative Commons](https://pxhere.com/en/photo/1626734)
Apache AGE: Advanced Features for Efficient Graph Data Management in PostgreSQL
Tags: postgres, apacheage
Published: 2023-05-14 20:43:50

## Introduction
Apache AGE is a PostgreSQL extension that enables users to store and manage graph data in a relational database environment. It aims to provide a unified storage solution for both relational and graph model data, allowing users to use standard ANSI SQL and openCypher, a popular graph query language. This article explores some of the advanced features of Apache AGE that can enhance data management.

## Organization of Graph Labels Hierarchically
Apache AGE also offers hierarchical graph label organization, where users can define hierarchical graph label organization by creating label groups that can contain other label groups or labels. This feature can be useful in managing and analyzing large and complex data sets with multiple layers of relationships.

## Indexing Properties on Vertices and Edges
Furthermore, Apache AGE enables users to create property indexes on vertices and edges using standard SQL syntax, which can greatly improve query performance and reduce the time needed to extract insights and patterns from graph data.

## Support for Cypher Query Language
One of the major advantages of Apache AGE is its support for Cypher, a popular query language for graph databases. This feature allows users to easily query relationships and patterns within the data, leveraging this powerful tool within a PostgreSQL-based environment.

## SQL and Cypher Hybrid Querying
Apache AGE also supports hybrid querying, which means users can work with both structured and graph data in a single database environment, leading to faster development cycles, efficient data analysis, and a streamlined overall workflow.

## Multi-graph Querying
Another valuable feature of Apache AGE is its support for querying multiple graphs. By analyzing multiple graphs together, users can identify patterns and insights that may not be visible in a single graph data set. This feature is particularly useful in social network analysis scenarios, where users may need to analyze relationships between individuals or groups across multiple graphs.

## Support for Full PostgreSQL Features
Finally, AGE's full support for PostgreSQL functionality and API allows for a seamless integration into existing PostgreSQL-based workflows.

## Conclusion
Overall, Apache AGE provides an efficient and comprehensive solution for managing graph data within a PostgreSQL environment, making it a valuable tool for developers and data scientists who need to manage and analyze graph data within a relational database environment.

REF:
[age-manual](https://age.apache.org/age-manual/master/intro/overview.html)
[ApacheAGE](https://age.apache.org/)
Useful Linux commands
Tags: linux, beginners
Published: 2023-05-14 21:23:26


🔹ls - List files and directories 
🔹cd - Change the current directory 
🔹mkdir - Create a new directory 
🔹rm - Remove files or directories 
🔹cp - Copy files or directories 
🔹mv - Move or rename files or directories 
🔹chmod - Change file or directory permissions 
🔹grep - Search for a pattern in files 
🔹find - Search for files and directories 
🔹tar - manipulate tarball archive files 
🔹vi - Edit files using text editors 
🔹cat - display the content of files 
🔹top - Display processes and resource usage 
🔹ps - Display processes information 
🔹kill - Terminate a process by sending a signal 
🔹du - Estimate file space usage 
🔹ifconfig - Configure network interfaces  
🔹ping - Test network connectivity between hosts 

**PERMISSIONS IN LINUX**
Source:KodeKloud
![permissions-kodekloud](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/69k45rek67pwjmoo80hc.png)

Source:bytebytego
![permissions-byte](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oedzefm13cbk8z9rk28q.jpg)

Links:  
1.[40 Useful commands](https://www.hostinger.com/tutorials/linux-commands)

2.[Most used commands](https://kinsta.com/blog/linux-commands/)
Day 104 of #365DaysOfCode: Implementing OAuth 2.0 and Exploring Python
Tags: webdev, javascript, beginners, programming
Published: 2023-05-15 00:25:53

Hey, guys! Day 104 of #365DaysOfCode has been productive. Today, I worked on implementing OAuth 2.0 for authentication in my app. I focused on setting up separate GoogleStrategy instances and authentication routes for each user model, an important step to enhance security and user experience.

On day 4 of #100DaysOfPython, I explored control flow and logical operators, gaining a deeper understanding of their functionality in Python.

I registered the app on Google Developer Console and imported Passport.js and Express session. To accommodate different user types, I need to create separate authentication routes and corresponding GoogleStrategy instances.
MusicStar.AI - Create Music with A.I.
Tags: music
Published: 2023-05-15 02:39:02

Are you an artist looking for inspiration? Or a fan who wants to know what it feels like to be a star? MusicStar.AI is designed for anyone, regardless of musical talent, who wants to make professional-sounding music. MusicStar.AI provides the tools you need, whether you're a music professional working on your next hit or a music fan wishing to create music like your favorite artist.

[https://musicstar.ai](https://musicstar.ai)
React 基礎 Part 01 -- URL に応じて Router でコンポーネントを出し分ける
Tags: react, router
Published: 2023-05-15 15:24:08


## Router をインストール

```php
npm install react-router-dom @types/react-router-dom

added 15 packages in 2s
```

react-router-dom と その types をインストール

---

## App で Router で コンポーネントを出し分ける

App.tsx

```ts
import './App.css';
import {
  BrowserRouter,
  Route,
  Routes,
} from "react-router-dom"

 
const App = () => {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element= { <Home/>} />
        <Route path="/test" element= { <Test/>} />
      </Routes>
    </BrowserRouter>

  );
}
export const Home = () => <h2>Home</h2>
export const Test = () => <h2>Test</h2>

export default App;
```

* BrowserRouter
  * Routes
    * Route / -> Home
    * Route /test -> Test

このように Route を、Routes と BrowserRouter で挟む

---

## 画面



これによって、ブラウザでは 

1. / (root) では Home
  *  ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tig1wdwx0f48cnfmadj2.png)
2. /test では Test
  *  ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/00kgbx12zm7ja7xhq7k1.png)


が描画される。
Операторы С++.
Tags: beginners, webdev, programming, tutorial
Published: 2023-05-15 19:23:35

Ассаламу алейкум, уважаемый программист, поговорим с вами об Операторах. Операторы используются для выполнения операций над переменными и значениями.

В приведенном ниже примере мы используем оператор `+` для добавления двух значений.

```
#include <iostream>

using namespace std;

int main()
{
int a = 100 + 50;
cout << a;

return 0;
}
```

Оператор `+` часто используется для сложения двух значений вместе, как в приведенном выше примере, который также можно использовать для добавления переменной и значения или переменной и другой переменной.

```
#include <iostream>

using namespace std;

int main()
{

int n1 = 100 + 50;        // 150 (100 + 50)
int n2 = n1 + 250;       // 400 (150 + 250)
int n3 = n2 + n2;       // 800 (400 + 400)

cout << n3;

return 0;
}
```

C++ делит операторы на следующие группы:

1. Арифметические операторы
2. Операторы присваивания
3. Операторы сравнения
4. Логические операторы
5. Побитовые операторы

`Оператор - используется для выполнения операций над переменными и значениями.`

`Арифметические операторы`

`Арифметические операторы используются для выполнения общих математических операций.`


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

`Операторы присваивания`

Операторы присваивания используются для присвоения значений переменной. В следующем примере мы используем оператор присваивания ( `=` для присвоения значения` 10` переменной с именем `x` :

```
#include <iostream>

using namespace std;

int main()
{

int x = 10;
cout << x;

return 0;
}
```


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

**Операторы сравнения**

`Операторы сравнения используются для сравнения двух значений.`

Объяснение: Возвращаемое значение сравнения равно `true (1) или false (0).`

**Список всех операторов сравнения:**


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

**Логические операторы**

Логические операторы используются для определения логики между переменными или значениями:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5zrrxd0js9590q0inae5.jpeg)
Launch Alert! Wowen Modular Blockchain Network - Unleash the Power of Consensus Choice 🚀⛓️💻
Tags: ethereum, blockchain, polygon, binance
Published: 2023-05-16 15:55:07

**Welcome to Wowen, the world's first modular blockchain network tailored for developers seeking ultimate control and flexibility.** Hailing from Switzerland, Wowen revolutionizes the Web3 space by allowing developers to select their preferred consensus mechanism for each transaction.

Unleash your blockchain's potential - Choose your consensus per transaction!

Wowen empowers you to optimize your applications for speed, cost, and finality by selecting from a variety of consensus chains such as Ethereum, Binance, Avalanche, Polygon, or Hedera. This cutting-edge offering opens up new avenues for development, with the ability to operate multiple consensus chains concurrently, all within a single network.

We're excited to invite you to the Wowen Alpha release. Be among the trailblazers to test the network and experience this game-changing modular (r)evolution in blockchain technology.

Stay ahead of the curve by following us on [Twitter](https://twitter.com/wowen_network) and becoming part of our developer community on [Telegram](https://t.me/WowenNetwork). For comprehensive developer docs and the latest updates, check out our [Gitbook](https://docs.wowen.io).

Are you ready to redefine your blockchain development experience? Think modular. Join us at [Wowen](https://www.wowen.io)!

-The Wowen Team
What's Your Wildest Unfulfilled Coding Project Idea?
Tags: discuss, beginners, codenewbie
Published: 2023-05-17 07:00:00

Got any coding project ideas that are totally out of the box? Share your wildest and most unconventional project concept that you've been itching to bring to life but haven't had the chance yet. Let's inspire each other with our creative and unconventional ideas!

---
Follow the [CodeNewbie Org](https://dev.to/codenewbieteam) and [#codenewbie](https://dev.to/t/codenewbie) for more discussions and online camaraderie!

*{% embed* [https://dev.to/codenewbieteam](https://dev.to/codenewbieteam) *%}*
The Next Language Evolution
Tags: language, future, engineering, ai
Published: 2023-05-16 23:31:58

Let's talk about language and how it's linked to the future of Software Engineers and Programmers. Now, these terms—Software Engineer, Programmer, Software Developer, Coder—often get used interchangeably. But I believe we're going to see more differences between them soon.

The best way to understand this is by looking at language.

What does language do? It's a tool for moving and storing information. It could be written, spoken, or even stored on a computer hard drive. Language helps us put structure to our thoughts or instructions, be it an image in our mind or a set of steps to follow.

Now, when we talk about "programming," language is how we tell a computer to do something step by step to get a result.

Machine language, the most basic form of programming, is tough to use for complex instructions. That's why we came up with Assembly Language, a step up but still pretty hard to use. So, we created compiled languages like C for more complex tasks. But underneath C, Assembly Language was still there.

Compiled Languages still had their challenges. So, we invented even more languages, with better ways of organizing and expressing our instructions.

And then we got to a point where compiling was a limitation. So we created languages that didn't need compiling and were easier to read and change.

The big thing here is that as we changed languages, we changed the role of the "programmer." But these changes weren't random. We wanted better ways to move and store information—specifically, algorithms. Programmers didn't disappear, but their jobs changed. Software engineering didn't disappear either, but the level at which it could operate got higher. Each time, we hid away the boring and tedious stuff, improving the human experience of engineering.

Fast forward to today, we have Large-Language Models (LLMs), a big leap in how we use language to give instructions. We can now use everyday language for tedious and error-prone tasks, making our work more abstract and focused on higher-level goals. Isn't this just the next stage in how we use language to give instructions? Why would this make engineers irrelevant?

This is a new era of **empowerment**! This will allow smart engineers to give more complex instructions with ease and have a better experience than ever before. Each step in programming language advancement opened new doors and made it easier for people to enter the field, and this will too.

I don't believe AI will replace engineers. Rather, it will make them more expressive and powerful, and it will allow us to think about tackling more advanced projects. We may have fewer "coders" and "programmers", since those are jobs whose definition is bound to the languages used to perform them.

But just like nobody longs to be a “punchcard technician” today, nobody will be sad that we’ve moved on.
Rust中的“废话”
Tags: rust, python
Published: 2023-05-17 01:50:48

### 相比于Python语言的简洁，Rust中存在很多废话
---

- 1、 `let` 定义变量时会用到这个参数，而Python并没有，这个并没有存在的必要性啊；大家都懂，何必多加一个词汇呢，显得冗余
```
let x = 5;
```
- 2、 `;` 每行代码结束时有一个这个结束符；Js也是这种风格，应该是有很多语言都是这种风格，但是没有啥必要性啊；懂的都懂，显得冗余
```
let x: i32 = 42;
```
- 3、 `: <type>` 申明变量类型；这点不错，不是强制的，可写可不写；用在定义变量，变量名和赋值操作之间；如果不写，编译器会自动识别，感觉还是没有写的必要性；懂得都懂，这个让编译器自动去干就完事了嘛；尽量减少开发人员的工作量和无脑的申明

> 最为常用的规范中用‘隐式声明’，也就是不申明变量类型；代码中明确写出来的是叫‘显示声明’

- 4、 `-> ()` 指定返回值；rust main 函数一定得有一个空元祖返回值，也就是`()`；但是这不是强制这么写的，一般省略不写，编译器能自动识别；这是显式的写法，但是更为常用的是隐式的写法；
```
fn main() -> () {
    // 程序逻辑(显式)
}
```
```
fn main() {
    // 程序逻辑(隐式)
}
```
- 5、 `-> i32`；指定函数的返回类型；如下：
```
fn add_numbers(a: i32, b: i32) -> i32 {
    let sum = a + b;
    return sum;
}
```
> 除了main函数和无返回值的函数不用强制制定返回类型，其他的常规函数都必须强制指定返回类型；写惯了Python的人，真的觉得这个很多余，懂得都懂，感觉没必要
Promesas con async y await
Tags: javascript, programming, webdev, spanish
Published: 2023-05-27 20:20:55

Hay dos formas de manejar las promesas en JavaScript una es con then que ya lo explique en un articulo anterior. Y otra es la que voy a explicar a continuación que es async y await. En este ejemplo se realiza una petición a una API fake.


![Ejemplo de promesa con then](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f8biejxku9ysxmdbs4u6.png)

El detalle es que el resultado de tal petición se obtiene dentro del segundo then ahora si se quisiera detalles del primer producto de esa categoría se tendría que hacer otro fetch a la API, y así sucesivamente a estos then se les conoce como callback hell. Llega un momento en donde la lógica se vuelve anidada, si en algún momento existe un error se va producir un efecto cascada. Ahora con async y await se va refactorizar esto y quedaría de la siguiente manera.


![Ejemplo de promesa con async y await](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8dxvx246zi8a9klxzl5i.png)

Cosas diferentes que hay que notar es que ahora se realiza dentro de una función, y se le antepone la palabra reservada async, ahora dentro del cuerpo de la función se realizan las peticiones con fetch pero se le antepone la palabra reservada await. Esto quiere decir va a esperar el resultado de la promesa que devuelve fetch para continuar con las siguientes líneas, de la misma manera con la función json() que devuelve una promesa y esta trae consigo un arreglo o objeto que esta listo para manipular con el lenguaje. Con async y await se vuelve mas limpio el código y fácil de leer. En cuanto a cachar los errores que se pudieran producir a lo largo de las promesas lo encerramos dentro de un bloque try -catch.


![Ejemplo de promesa con async y await con try y cathc](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ujg6gadihom05q6ad6td.png)

Si este articulo te gusto o aprendiste algo nuevo que no sabías te agradecería mucho que lo compartieras, me ayuda bastante. Gracias.
What do you think about TDD (Test Driven Devolepment)?
Tags: testing, programming, development, discuss
Published: 2023-05-29 15:57:45

When I started my career as a developer, I was flooded with many articles about best practices, and one, in particular, caught my attention: the TDD.

In my case I used it a lot when projects were small and new, but now working on larger legacy code I can't use this concept.

My reflection here is around the real gain, and your experiences using that in different types of projects.
sync Windows local folder với aws s3
Tags: tips
Published: 2023-10-15 16:44:51

Đồng bộ Windows Local folder với aws s3 

Tiền điều kiện 

đã biết dùng S3 CLI (với Access Key) 

1. cài [aws cli ](https://aws.amazon.com/cli/)
2. tạo 1 file `sync-my-folder.bat` 
  trong nội dung file bat đấy gõ vào lệnh 
  ``` 
  aws s3 sync s3://mybucket D:\folder-can-sync
  ```
3. bật Task Scheduler (nhấn nút `Windows` , gõ "task scheduler") 
  bên Triggers thì set thời gian thực thi, 
  bên Actions thì trỏ tới cái file `sync-my-folder.bat` ở trên 

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

Enjoy 

cám ơn [bài gốc ](https://medium.com/@dangaldeependra/synchronizing-between-local-windows-drive-and-aws-s3-adfed52dba66)
Get involved: Your guide to contributing to WebCrumbs
Tags: hacktoberfest, hacktoberfest23, opensource, beginners
Published: 2023-10-15 22:15:00

Hey there, champ! So, you're itching to dive into the WebCrumbs community, eh? Fantastic! You're about to join a legion of coders hell-bent on making React development as smooth as silk. Here's how you can get your boots on the ground.

## First step: the lay of the land

Start by taking a tour of the [WebCrumbs GitHub repository](https://github.com/webcrumbs-community/webcrumbs). It's the control center of our open-source mission. Check out the `README` for a general overview and the `CONTRIBUTING` file for the nitty-gritty.

## Fork it, clone it, branch it

Alright, you know the drill. Fork the repo, clone it locally, and create a new branch. This way, you're all set to work your magic without stepping on any toes.

## Pick your battle

Whether you're a frontend maestro, a backend virtuoso, or a doc-wizard, there's room for you. Go through the open issues, pick one that resonates, and stake your claim.

## Code like a rockstar

Write clean, comment generously, and stick to the style guide. WebCrumbs is all about quality, so make every line of code count.

## The PR moment of truth

Submit a pull request, and wait for the review. Don't sweat it—feedback is how we grow. Once your PR gets the green light, you're officially part of WebCrumbs history.

## Join the conversation

Not just a coder? Fabulous! Join our Discord, engage in forums, write blog posts, or share your WebCrumbs success stories. The more the merrier!

## The icing on the cake

As you contribute, you're not just accumulating GitHub stars. You're building relationships, honing your skills, and, of course, getting those sweet, sweet open-source karma points.

### Ready to roll up your sleeves?

Jump over to the [WebCrumbs GitHub repository](https://github.com/webcrumbs-community/webcrumbs) and start your journey. Contribute code, ideas, or even a morale-boosting GIF. Let's make React a cakewalk, together.

{% embed https://github.com/webcrumbs-community/webcrumbs %}
how to fix this issue on my own
Published: 2023-10-16 04:26:45

> **_Uncaught Reference Error: Submit is not defined shown on my browser inspect_**

```
let c1 = document.getElementById('c1')
let c2 = document.getElementById('c2')
let Bd1 = document.getElementById('Bd')


let index=2;

Bd.addEventListener(Submit,(d)=>{
    d.preventDefault();
    let num1=parseInt(c1.value);
    let num2=parseInt(c2.value);
    let c3 = num1 === num2;
    alert(c3?"serial number is matched" :"number is unmatched");
    console.log(c3?"serial number is matched": "number is unmatched");
});

```