teleren/devto huggingface dataset:
Release 1.0 - Text to Html Converter
Tags: webdev, programming, opensource
Published: 2023-09-19 03:03:54

Have you ever wanted to turn your plain text files into beautiful web pages? That's exactly what I set out to do with my latest coding project. While the end result was great, getting there was quite an adventure filled with some puzzling problems.

The main idea was simple: I wanted to create a tool that could take a plain text file, like something you'd write in Notepad, and turn it into a proper web page with all the HTML bells and whistles. Sounds easy, right? Well, not quite.

One of the first challenges was dealing with paragraphs. You see, web pages need these things called <p> tags around paragraphs. But figuring out where each paragraph started and ended in the text was trickier than I thought. I had to use some special code to find those blank lines and turn them into <p> tags.

Then came the issue of titles. If the first line of the text was a title (with two blank lines below it), I wanted to use it as the page title and as a big heading at the top of the page. Making this work required some fancy file reading and text extraction.

But the biggest challenge? Dealing with what people wanted. I wanted to give users the freedom to choose where their new web pages would go and whether they wanted to use a special design (a stylesheet). Allowing users to customize things like this meant I had to write extra code to handle their choices and avoid mistakes.

Another tricky part was managing directories. You know, folders where you store your files? My tool was supposed to create a new folder for the web pages, but it had to make sure that folder was empty first. Getting this right involved using a special tool to delete the old stuff and create a fresh space.

Despite all these challenges, I finally made it work. Now my tool can take plain text and turn it into web pages with titles, custom styles, and it puts them where you want them.

This project taught me that coding isn't just about typing code. It's about solving puzzles, paying attention to details, and never giving up. Even though I faced some tough problems, I'm proud of what I created. As the programmer says that every problem is a chance to learn and get better.
Fontima: Optimize Your Google Fonts Requests
Tags: webdev, css, showdev, fonts
Published: 2023-09-19 03:00:00

**[Fontima](https://fontima.com/) delivers fine-grained font CSS**.

It is based on the `text` URL parameter from Google Fonts, the one we use to *subset a font* by specifying which characters (actually glyphs) we need from it. Fontima lets you do that with just a couple of clicks while optimizing the CSS on the fly, producing *better, measurable results* to **get the characters you need from the families you want when they are required**.

---

## Why Fontima?

**Fonts need to be optimized**.

We often say "images weight too much," so we use a battery of tools to optimize them. The problem is that **fonts are as large or even larger than images**. Fontima exists to address that issue, it can *save you up to +95% on font files* (CSS + WOFF2) and *prevent undesired, automatic downloads* by including the appropriate `unicode-range` value on each `@font-face` rule.

## How to Use Fontima?

1. Bring the code given by Google Fonts,
1. Choose the characters you need,
1. Click Optimize to get your CSS.

That's it!

## Do I Need Fontima?

Prerequisite: **have a clear idea of what the characters wearing a given font family will be**.

It could be used for a web logo; a set of math symbols; a set of languages for any web/app that is not intended to be worldwide used (e.g.: a local web or a private business app); a single character, etc.

## Pros and Cons of Using Fontima

✔️ Pros:

- **Download lighter files**;
- **Download fewer files** (for most cases);
- **Download fonts only when required**.

❌ Cons:

- **Some fonts can not be optimized by GF**\*;
- **Fonts may have missing glyphs** they are supposed to include;
- **Static CSS** (instead of using a static URL to get the CSS dynamically).

\*Specially the ones with *non-standard/unregistered [variable axes](https://fonts.google.com/knowledge/glossary/axis_in_variable_fonts "Axis (in variable fonts)")* and an *[optical size](https://fonts.google.com/knowledge/glossary/optical_size_axis "Optical Size axis (opsz)")* value different than `none`, cases in which Google Fonts returns the default CSS.

---

Your feedback will be appreciated.

Thanks for reading!
Código
Published: 2023-07-31 15:56:05

**Parte 1. Archivo main**

```
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

async function main() {
  const nuevoestudiante = await prisma.estudiante.create({
    data: {
      email: "adonis@gmail.com",
      nombre: "adonis",
      pais: "Costa Rica",
    },
  });
  console.log("Nuevo profesor creado: ", nuevoestudiante);
  const todosEstudiantes = await prisma.estudiante.findMany();
  console.log("Todos los todosEstudiantes: ");
  console.dir(todosEstudiantes, { depth: null });
}

main()
  .catch((e) => {
    console.error(e);
    process.exit(1);
  })
  .finally(async () => {
    await prisma.$disconnect();
  });
```
Parte 2
Este es e apartado del Index

```
import { PrismaClient } from "@prisma/client";
import express from "express";

const prisma = new PrismaClient();

const app = express();

app.use(express.json());

app.get("/", async (req, res) => {
  // console.log("Hola a todos");
  res.send("¡Hola a todos! Bienvenidos a mi aplicación.");
});

app.use((req, res, next) => {
  res.status(404);
  return res.json({
    success: false,
    payload: null,
    message: `APY SAYS: Endpoint not not found for path: ${req.path}`,
  });
});

app.listen(process.env.PORT || 8001, () =>
  console.log(`🚀 Server ready at: http://localhost:8001`)
);
```
CRUD empezamos con el get este nos ayuda a obtener la información con la que se cuenta en las tablas de pgAdmin4

```
app.get("/estudiantes", async (req, res) => {
  const estudiante = await prisma.estudiante.findMany();
  res.json({
    success: true,
    payload: estudiante,
    message: "Operation Successful",
  });
});
```
----------------------------------------------------------
Post agrega datos pgAdmin4
```
app.post("/crear_estudiante", async (req, res) => {
  const result = await prisma.estudiante.create({
    data: req.body,
  });
  res.json(result);
});
```
----------------------------------------------------------
Delete agrega datos pgAdmin4

```
app.delete(`/estudiante/:id`, async (req, res) => {
  const { id } = req.params;
  const estudiante = await prisma.estudiante.delete({
    where: {
      id: Number(id),
    },
  });
  res.json(`La estudiante con el id ${id} fue eliminada exitosamente`);
});
```
----------------------------------------------------------
Put agrega datos pgAdmin4

```
app.put("/estudiante/:id", async (req, res) => {
  const { id } = req.params;
  try {
    const datosActualizados = await prisma.estudiante.update({
      where: { id: Number(id) },
      // req.body es la info que manda el usuario para actualizar
      data: req.body,
    });
    res.json({
      datos: datosActualizados,
      mensaje: `La estudainte con el id ${id} fue actulizado exitosamente`,
    });
  } catch (e) {
    res.json({ error: `La estudiante con el id ${id} no existe` });
  }
});
```
rust构建openwrt armv7l 程序（跨平台实现的最简单方式）
Published: 2023-09-19 02:43:29

早期写过一个[版本](如何用rust构建openwrt armv7l CPU架构的可执行程序)，但是有点繁琐，操作起来容易不成功，而且跨平台性不好

### 下面是更为简单的实现方式
---

- 1、安装rust跨平台使用的交叉编译第三方工具`cross` [github地址](https://github.com/cross-rs/cross)

> 该工具是基于Docker的，所以你的编译环境得有Docker,原理上该工具是对于不同的target有不同的匹配docker镜像，镜像内配置了所需要的一切环境；通过--target 参数来自动匹配拉取镜像，在镜像内完成构建，并将构建结果输出到镜像外部
```
cargo install cross --git https://github.com/cross-rs/cross
```

- 2、使用。安装完直接使用，不需要配置任何其他的东西

> 使用上和cargo一样，几乎没有区别，直接将cargo换成cross就行
```
# (ONCE PER BOOT, on Linux)
# Start the Docker daemon, if it's not already running using systemd
# on WSL2 and other systems using SysVinit, use `sudo service docker start`.
$ sudo systemctl start docker

# MAGIC! This Just Works
$ cross build --target aarch64-unknown-linux-gnu

# EVEN MORE MAGICAL! This also Just Works
$ cross test --target mips64-unknown-linux-gnuabi64

# Obviously, this also Just Works
$ cross rustc --target powerpc-unknown-linux-gnu --release -- -C lto
```

- 3、编译适配 `openwrt armv7l` 的程序

> 编译相当耗时，macos M2 芯片花了8分多钟，是真的慢啊
```
cross build --target=armv7-unknown-linux-musleabihf --release
```

- 4、发布程序

> 比如代码项目的目录名为`subscribe_update`

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

> 编译目标程序名称为`subscribe`

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

> 那么编译好的文件在目录：
` /subcribe_update/target/armv7-unknown-linux-musleabihf/release/subscribe `


- 5、部署问题。部署执行程序的时候发现，程序需要读取某个文本文件来加载配置，但是该文件并没有被编译到可执行文件内，就导致了程序报错（找不到可读取的文件）

- 6、为解决第5点问题，将文本文件改为.rs文件，将配置内容定义为rust的常量

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hr2bdibm2g9ho9whq36v.png)
Design-First vs Develop-First: Navigating the Choices in REST API Development
Tags: api, restapi
Published: 2023-09-19 02:39:04

Building a REST API involves a crucial choice between the Design-First and Develop-First approaches. Both have unique merits and challenges, and your project's needs will dictate the best fit. This article explores these paradigms and highlights how OpenAPI/Swagger can benefit either strategy.

## Design-First Approach

### Characteristics

- **Design-Centric**: Starts with an API contract, detailing endpoints, responses, and data types.
- **Structured Workflow**: Begins with design, followed by development and testing.
  
### Advantages and Disadvantages

- **Pros**: Facilitates team collaboration, enables automated testing, produces a stable API.
- **Cons**: Requires upfront time, less flexibility to change.

## Develop-First Approach

### Characteristics

- **Code-Centric**: Development starts with code, evolving the API iteratively.
- **Flexible Workflow**: Testing and documentation happen alongside development.

### Advantages and Disadvantages

- **Pros**: Faster initial development, flexibility for change.
- **Cons**: Potential inconsistencies, risk of inadequate documentation.

## Comparison Chart

| Category                | Design-First       | Develop-First    |
|-------------------------|--------------------|------------------|
| Initial Focus           | API Contract       | Code             |
| Workflow                | Structured         | Flexible         |
| Collaboration           | Early, cross-team  | Often developer-centric |
| Testing                 | Facilitated        | On-the-fly       |
| Documentation           | Prioritized        | Can be secondary |
| Flexibility for Changes | Limited            | High             |

## How OpenAPI/Swagger Adds Value

### For Design-First

- **Standardized Contract**: Enables creation of a detailed, standard API contract.
- **Code Generation**: Automates code stub and SDK creation.
- **Automated Testing**: Facilitates creation of mock servers and automated tests based on the API specification.

### For Develop-First

- **Documentation from Code**: Generates robust API documentation directly from code annotations.
- **Built-in Validation**: Compares the developed API against the OpenAPI spec for compliance.
- **Interactive Testing**: Provides an interactive user interface for easy endpoint testing.

### Universal Benefits

- **Better Integration**: Eases compatibility issues with third-party services.
- **Rich Ecosystem**: Benefits from extensive community support and tooling.

## Conclusion

Whether you choose Design-First or Develop-First, incorporating OpenAPI/Swagger can provide significant advantages, making your API more robust, easier to test, and simpler to maintain. Both approaches have their pros and cons, but with OpenAPI/Swagger, you’re better equipped to develop a high-quality API.
My first TIL for Text to HTML converter
Published: 2023-09-19 02:35:44

Hi there! I'm excited to introduce my latest project, **TIL-Netlify** 🚀. This is my very own open-source command-line interface (CLI) tool that allows you to effortlessly convert plain text files into beautifully formatted HTML files. But first, a little background:

### Node-TILify

Node-TILify stands for "Today I Learned" and "Node.js," which are at the core of this project. It's an open-source tool I developed to make it easier for everyone to share and present their learnings, insights, or any kind of textual content in a more visually appealing way.

🔗 **[Link to the Repository] https://github.com/Jilesh980/Text-To-HTML

**Installation:** 
 
1) Make sure to install the proper dependencies for the project before executing: npm install
2) Clone the repository in your local machine: git clone https://github.com/Jilesh980/till-tool.git

**FEATURES:**

1. Convert a single .txt file into an HTML file effortlessly.
2. Process entire directories of .txt files to generate corresponding HTML files.
3. Wrap each paragraph in <p> tags for clear formatting.
4. Passing -h or --help command prints help menu.
5. Passing -v or --version command prints version and name of the tool.
6. Optional Feature #2: When you include the -o or --output command followed by a path to an output directory, it saves all the HTML files generated to that specified directory. In case the directory doesn't already exist, the tool will create it automatically.

**How to produce the output**
The command which takes .txt file and convert it to .html file and store it in ./til directory.

```
node src/index.js document.txt 
```

The command which take .txt file, convert it into .html file and store in the custom directory


```
node src/index.js document.txt -o custom
```


**Conclusion:** Node-TILify is not just a tool; it's a bridge between the world of text and the web, designed to make sharing knowledge more accessible and visually appealing. With its user-friendly features and versatility, it's an open-source gem waiting to amplify your wisdom. So, take it for a spin, contribute to its growth, and let's collectively enhance the way we share and learn from one another.
Llama 2 in Apple Silicon Macbook (2/3)
Published: 2023-09-19 02:32:00

To program Llama 2 easily, it is highly recommended to encode quantized model.

There is llama C++ port repository.

# Download llama.cpp

```
git clone https://github.com/ggerganov/llama.cpp.git
cd llama.cpp
make
```

# Convert model to GGLM format

```
cd llama.cpp
python3 -m venv llama2
source llama2/bin/activate
python3 -m pip install -r requirements.txt
```

Converting process consists of two step.
1. convert model to f16 format
2. convert f16 model to ggml

## convert to f16 format

```
mkdir -p models/7B
python3 convert.py --outfile models/7B/ggml-model-f16.bin \
--outtype f16 \
../llama2/llama/llama-2-7b-chat \
--vocab-dir ../llama2/llama
```

Before run the convert, create output directory (ex. models/7B)

--outfile is for specifying the output file name
--outtype is for specifying the output type which is f16
--vocab-dir is for specifying the directory containing _tokenizer.model_ file

If you are hard to find tokenzier.model file, see [tokenizer.model](https://github.com/choonho/llama_server/blob/main/tokens/tokenizer.model)

## convert f16 model to ggml

This step is called as _quantize the model_

```
./quantize ./models/7B/ggml-model-f16.bin \
./models/7B/ggml-model-q4_0.bin q4_0
```

After quantize model, the file size became very small.

```
mzc01-choonhoson@MZC01-CHOONHOSON 7B % ls -alh
total 33831448
drwxr-xr-x@ 4 mzc01-choonhoson  staff   128B  9 12 17:23 .
drwxr-xr-x@ 5 mzc01-choonhoson  staff   160B  9 12 16:50 ..
-rw-r--r--@ 1 mzc01-choonhoson  staff    13G  9 12 17:23 ggml-model-f16.bin
-rw-r--r--@ 1 mzc01-choonhoson  staff   3.6G  9 12 17:23 ggml-model-q4_0.bin
```

# Example

All done. run example binary!!!

```
./main -m ./models/7B/ggml-model-q4_0.bin -n 1024 --repeat_penalty 1.0 --color -i -r "User:" -f ./prompts/chat-with-bob.txt
```


# References

GGML - Large Language Models for Everyone
https://github.com/rustformers/llm/blob/main/crates/ggml/README.md

# Series
Llama 2 in Apple Silicon Bacbook (1/3)
https://dev.to/choonho/llama-2-in-apple-silicon-macbook-13-54h

Llama 2 in Apple Silicon Bacbook (2/3)
https://dev.to/choonho/llama-2-in-apple-silicon-macbook-23-2j51

Llama 2 in Apple Silicon Bacbook (3/3)
https://dev.to/choonho/llama-2-in-apple-silicon-macbook-33-3hb7
How Association Rule Mining Algorithms Improve the Efficiency of Computer Screen Monitoring Software
Published: 2023-09-19 01:55:23

In today’s workplace, computer screen monitoring software has become a standard tool for many businesses, used to monitor employee work behaviors to enhance productivity and security. However, to maximize the utility of monitoring software, Association Rule Mining algorithms are emerging as a valuable resource. Let’s explore how Association Rule Mining algorithms can enhance the monitoring efficiency of computer screen monitoring software through the following aspects:

Introduction to Association Rule Mining Algorithms

Association Rule Mining algorithms are a data mining technique that analyzes relationships among items in a dataset. In the context of computer screen monitoring software, this means it can help us understand employee behavior patterns and work habits, enabling the development of more precise monitoring strategies.

Optimizing Monitoring Strategies

Through Association Rule Mining algorithms, monitoring software can gain a better understanding of employee activities on their computers. It can uncover patterns, such as certain tasks being more prevalent during specific time periods or the frequency of using particular applications. These insights can assist managers in optimizing monitoring strategies, making them more precise and efficient.

For example, if it is discovered that employees are most productive between 10:00 AM and 11:00 AM each day, the monitoring software can increase surveillance during that time while reducing monitoring frequency during other hours to reduce employee anxiety.

Automated Anomaly Detection

Association Rule Mining algorithms can also automatically detect abnormal employee behavior. If an employee suddenly opens a specific application frequently during non-working hours, the monitoring software can promptly issue an alert. This can help preempt potential data leaks or security risks.

Behavior Prediction

By analyzing historical behavior data, Association Rule Mining algorithms can help managers predict future behavior trends. For instance, if an employee typically works late at the end of each month, the monitoring software can allocate additional tasks in advance to cope with increased workload and stress.

Protecting Employee Privacy

While the purpose of computer screen monitoring software is to enhance productivity and security, employee privacy must still be respected. Association Rule Mining algorithms can assist managers in finding a balance, ensuring that monitoring software improves efficiency without violating employee privacy rights.

Although computer screen monitoring software is an integral part of the modern work environment, Association Rule Mining algorithms can help optimize monitoring strategies, automatically detect unusual behavior. However, it is essential to remember that the use of this technology must be legal and compliant, and employees should be treated fairly and transparently to create a healthy work environment!
why you should use IIfe (immediately invoked function expression ) in your javascript code
Tags: webdev, javascript, beginners, programming
Published: 2023-09-19 00:24:57

Programmers use Immediately Invoked Function Expressions (IIFE) in JavaScript for several reasons:

1. **Encapsulation**: An IIFE creates a new scope for your code, preventing variable and function name clashes with other code. This helps avoid unintentional variable pollution and conflicts in global scope.

   ```javascript
   (function() {
       // Your code here
   })();
   ```

2. **Isolation**: IIFEs allow you to isolate a block of code and execute it immediately without affecting other parts of the program. This can be particularly useful when you want to create temporary variables or execute code that doesn't need to be reused elsewhere.

3. **Module Pattern**: IIFEs are often used to create modules in JavaScript, allowing you to define private variables and functions within the scope of the IIFE while exposing only the necessary parts to the outer world.

   ```javascript
   var module = (function() {
       var privateVar = 0;

       function privateFunction() {
           // Do something privately
       }

       return {
           publicVar: 1,
           publicFunction: function() {
               // Access privateVar and privateFunction here
           }
       };
   })();
   ```

4. **Pollution Prevention**: By using an IIFE, you can prevent the pollution of the global namespace with your variables and functions. This helps maintain a clean and organized codebase, reducing the risk of naming conflicts with other scripts.

5. **Dependency Injection**: IIFEs can be used to inject dependencies into a module or function, ensuring that specific values or objects are available for use without polluting the global scope.

6. **Compatibility**: In older versions of JavaScript, before the introduction of block-scoped variables with `let` and `const`, IIFEs were a common technique to create local scope for variables within loops or conditionals, preventing unintended variable hoisting.

Here's an example of an IIFE used to create a simple module that counts button clicks:

```javascript
var clickCounter = (function() {
    var count = 0;

    function incrementCount() {
        count++;
    }

    function getCount() {
        return count;
    }

    return {
        increment: incrementCount,
        getCount: getCount
    };
})();

clickCounter.increment(); // Increases the count
console.log(clickCounter.getCount()); // Retrieves the count
```

In modern JavaScript, the use of IIFEs has become less common thanks to the introduction of block-scoped variables (`let` and `const`) and the availability of ES6 modules, which provide better ways to encapsulate and modularize code. However, IIFEs are still relevant in certain scenarios, especially when working with legacy code or in specific situations where encapsulation and isolation are required.