teleren/devto huggingface dataset:
Code Smell 219 - Looping from index 0
Tags: webdev, javascript, beginners, programming
Published: 2023-07-24 01:05:15

*Counting from zero seems natural. Doesn't it?*

> TL;DR: Start counting from one instead of zero. Like humans do.

# Problems

- [Bijection](https://dev.to/mcsee/the-one-and-only-software-design-principle-3086) from real-world broken

- Cognitive load

- Overly implementation-oriented code

# Solutions

1. Favor high-level declarative languages

# Context

Low-level languages force you to think at a machine level.

Hardware turning machines were designed to use binary gates and start indexing at 0.

A few programming languages use one-based indexing, where indexing starts from 1. 

These languages are known for being higher level and more declarative:

- Basic / Visual Basic
- Pascal
- Smalltalk
- Fortran
- Lua
- MATLAB
- R
- Julia 

# Sample Code

## Wrong

[Gist Url]: # (https://gist.github.com/mcsee/79140cca1b6b1d1459ae73801ef26845)
```go
package main

import "fmt"

func main() {    
    numbers := []int{10, 20, 30, 40, 50}
    
    for i := 0; i < len(numbers); i++ {
        // Iteration goes from zero to len-1
        fmt.Println(numbers[i])
    }
}

```

## Right

[Gist Url]: # (https://gist.github.com/mcsee/3ccf0ebb605c95b96a185999290bd52f)
```matlab
numbers = [10, 20, 30, 40, 50];

% Looping through the array using one-based indexing
% from 1 to length
for currentIndex = 1:length(numbers)
    disp(numbers(currentIndex));
end

```

# Detection

[X] Automatic 

This is a language smell. 

# Exceptions

- Low-level optimized code

# Tags

- Declarative Code

# Conclusion

We need to think as humans when we code and not as machines.

Humans count from one.

[Zero number](https://en.wikipedia.org/wiki/0) was a brilliant discovery in math and science but it does not apply to everyday counting.

# Relations

{% post https://dev.to/mcsee/code-smell-53-explicit-iteration-40hl %}

{% post https://dev.to/mcsee/code-smell-123-mixed-what-and-how-4bak %}

# More Info

[Wikipedia](https://en.wikipedia.org/wiki/Zero-based_numbering)

# Disclaimer

Code Smells are my [opinion](https://dev.to/mcsee/i-wrote-more-than-90-articles-on-2021-here-is-what-i-learned-1n3a).

# Credits

Photo by [Andy Kelly](https://unsplash.com/@askkell) on [Unsplash](https://unsplash.com/photos/0E_vhMVqL9g)  
  
* * *

> Pay attention to zeros. If there is a zero, someone will divide by it.

_Cem Kaner_ 
 
{% post https://dev.to/mcsee/software-engineering-great-quotes-26ci %}

* * *

This article is part of the CodeSmell Series.

{% post https://dev.to/mcsee/how-to-find-the-stinky-parts-of-your-code-1dbc %}

* * *

My new book about clean code is available for pre-order.

You will find several recipes like this one with a higher level of detail

[![Book](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w8b5b0sj75jkgkoxfhmh.jpg)](https://amzn.to/44s1XdO)
High Order Functions Benefits
Published: 2023-07-24 00:48:18

High order functions allow functions to be parameters as well as return functions (Codeacademy, 2023). Benefits of higher order functions is that it makes code shorter and easier to read. It also helps with organization of code into smaller units which helps with the maintenance of the code (Prasad, 2023). You can use higher order functions to manipulate or transform data in array, create new arrays from objects, and create complex functions from simpler ones (Prasad, 2023). Some high order functions that are commonly used are map(), reduce(),filter(),and sort() (Prasad 2023). 
One example of the use an higher order function is the use of map()
const arr = [2, 4, 6, 8, 10];
const output = arr.map((num) => num += 5)
console.log(arr); // [2, 4, 6, 8, 10]
console.log(output); // [7, 9, 11, 13, 15]
(Prasad, 2023)
In this example, the map function adds 5 to each item in the array.


References:
Prasad, S. (2023). Higher Order Functions in JavaScript – Explained with Practical Examples. freeCodeCamp.org. https://www.freecodecamp.org/news/higher-order-functions-in-javascript-explained/#:~:text=Using%20higher%20order%20functions%20has,it%20easier%20to%20debug%20code.
Learn JavaScript: Higher Order Functions and iterators: Learn JavaScript: Iterators cheatsheet | Codecademy. (n.d.). Codecademy (2023). https://www.codecademy.com/learn/game-dev-learn-javascript-higher-order-functions-and-iterators/modules/game-dev-learn-javascript-iterators/cheatsheet.
Sending File Data in JavaScript: Comparing File Streaming with Multipart Form Data
Published: 2023-07-24 00:25:07

In modern web applications, the ability to handle file uploads efficiently is essential for providing a seamless user experience. JavaScript, being a widely used client-side scripting language, offers several methods to send file data from the browser to the server. In this article, we will explore two popular approaches: File Streaming with the fetch API and Multipart Form Data. Understanding the differences between these methods can help you make informed decisions when implementing file upload functionality in your projects.

1. File Streaming with the fetch API:

The fetch API is a powerful tool for making asynchronous network requests in modern JavaScript applications. One of its lesser-known features is the ability to handle file uploads in a streaming fashion. When you want to upload large files or stream data continuously, the file.stream() method comes to the rescue. This method reads the file data in chunks and sends them as individual packets to the server. The browser handles the chunking process automatically, and you don't need to worry about managing it manually.

Advantages of File Streaming with fetch API:

Efficient handling of large files: Streaming allows you to start uploading the file even before the entire file is read, reducing memory consumption.
Improved performance with HTTP/2: If the server supports HTTP/2, multiple requests can be multiplexed over a single connection, reducing latency and enhancing performance.
Simplified code: The fetch API provides a clean and straightforward interface to work with file streaming.
2. Multipart Form Data:

Multipart form data is a standard format used for submitting form data, including file uploads, to a server. When you submit a form with file inputs in HTML, the data is automatically encoded as multipart form data. However, you can also construct and send multipart form data programmatically in JavaScript using libraries or native APIs.

Advantages of Multipart Form Data:

Handling form submissions: Multipart form data is the preferred way to handle traditional HTML form submissions that include file uploads and other form fields.
Compatibility with server expectations: If your server expects file uploads in a specific multipart format, using this method is essential for seamless integration.
Conclusion:

Both File Streaming with the fetch API and Multipart Form Data are powerful techniques for sending file data from the browser to the server. Your choice between the two methods should be based on your specific use case and server-side requirements.

Use File Streaming with fetch API for handling large files and when you need to leverage HTTP/2 benefits for concurrent requests.
Use Multipart Form Data when you are dealing with form submissions that include file uploads and other form fields, or when your server expects file uploads in this specific format.
Understanding the strengths and limitations of each method will empower you to build efficient and seamless file upload functionality in your web applications. Happy coding!
Never Lose Your Work Again: Autosave Has Your Back
Published: 2023-07-25 15:55:38

---
title: Never Lose Your Work Again: Autosave Has Your Back
published: true
date: 2023-07-24 00:00:00 UTC
tags: 
canonical_url: https://blog.brainstory.ai/autosave/
---

We are excited to introduce a new feature within the Contenda editor- autosave! Now when you make changes, Contenda’s editor will save them as you work. With this new autosave feature, our users have a more seamless and stress-free writing experience.

## No More Worries About Losing Your Work:

Say goodbye to that sinking feeling when the power goes out or when you accidentally close the tab without saving your hard work. Autosave will continuously save your changes in real-time, securing every modification you make to your document. You can focus solely on the creative process without worrying about losing your progress.

<video controls width="500" height="400">
  <source src="https://contenda.co/blogimages/Autosave.mp4" type="video/mp4">

Autosave is live in our editor and ready to try now. Login or sign up to use!
用 LangChain 構建基於資料庫的問答機器人（三）：ReAct
Published: 2023-07-24 00:00:00

大家好，我是 Jambo。我們已經學習瞭如何使用 LangChain 的一些基本功能，解下我們就應該要結合這些功能來做一些複雜的東西了。但在這之前，為了讓同學們更好的理解 LangChain 在這其中做了什麼，我想先介紹一下關於 GPT 使用方面的一些知識。

在 ChatGPT 開放之初，除了各大公司在 AI 算法方面競爭，還有許多人在研究如何僅通過修改 prompt 就能讓 GPT-3 做出更好的回答，這種方法被稱為“提示工程（Prompt Engineering）”。如果把 LLM 比喻成一個擁有一般常識的大腦，那麼提示工程就是在教它如何思考，從而更有效的結合知識得出答案。像 AutoGPT 就是這樣，他通過精心設計的 prompt，就能讓 GPT-4 自行完成各種任務。為了讓同學們了解這其中的思想，我們先從“思維鏈”開始介紹。

# 思維鏈（Chain of Thought）

思維鏈（Chain of Thought）在 ChatGPT 推出後不久就被提出，具體來說就是通過手動編寫示例的方式讓 GPT-3 將問題的思考過程也生成出來，通過這種方式 GPT-3 回答的效果會有大幅提升。就像我們在寫比較複雜的計算題，將過程一步一步寫出來的正確率會比直接寫出答案要高。

![Alt text](https://raw.githubusercontent.com/JamboChen/Jambo-blog/master/img/langchain/react/cot.png)

後來有人發現，只需要加上 “Let's think step by step.” 這一魔法提示，就能達到一樣的效果，還不需要寫示例。並且他還在這基礎上，額外讓 GPT 根據它前面附帶思考過程的回答，再總結出一個更簡潔的答案，相當於把思考過程隱藏起來。

![Alt text](https://raw.githubusercontent.com/JamboChen/Jambo-blog/master/img/langchain/react/zore_shot_cot.png)

我這裡想強調的是，我們用 LLM 構建應用時，完全可以在輸出最終答案前多次用 LLM 分析、拆解、解決問題。就像深度學習網絡中的介於輸入和輸出之間的隱藏層，我們可以在這裡加入更多的邏輯，讓 LLM 能夠更好的理解問題，從而得出更好的答案。

# ReAct

無論我們如何調整 prompt，但 LLM 仍然存在一個重大缺陷：它始終基於訓練時的數據集和 prompt 中提供的信息生成回答。如果提問有關天氣、新聞或內部文件等問題，LLM 將無法回答或會產生虛假回答（"幻覺"）。

當然，我們可以在用戶提出問題後，先使用搜索引擎或內部資料庫來搜索問題，然後將搜索結果作為 prompt 的一部分。但在實際應用中，這種方法的效果並不總是好的，甚至在某些情況下會產生誤導。例如，如果我們想讓 LLM 幫助我們修改一篇文章，在這種流程下，程序會首先使用搜索引擎搜索文章，但很可能搜索不到相關結果。這樣一來，LLM 就會直接罷工，因為我們通常要求 LLM 僅根據 prompt 提供的信息生成內容，以確保准確性。

為了解決這個問題，我們可以讓 LLM 自己決定是否要進行搜索，要搜索什麼內容，就和上一篇教程中提到的用 LLM 優化搜索語句一樣。於是 ReAct 系統就被提出來了，通過 prompt 中的示例告訴 LLM 可以使用哪些工具，然後讓 LLM 自己決定是否要使用這些工具，以及如何使用這些工具。 ReAct 總共有三個部分：
1. 思考：根據當前的信息思考需要做什麼動作。
2. 行動：根據思考結果做出相應的行動，如調用工具。程序可以分析這一步生成的字符串，來調用相應的工具，類似 Python 的 `eval` 函數。
3. 觀察：存放行動的結果，如搜索的內容，以便下一次思考時使用。

這三個步驟會不斷循環，直到思考步驟判斷已經找到答案，並在下面的行動中給出最終答案。

![Alt text](https://raw.githubusercontent.com/JamboChen/Jambo-blog/master/img/langchain/react/react.png)

其實你仔細回想一下，這個過程和我們人類思考的過程是類似的。我們在思考時，會根據當前的信息判斷是否需要做出某些行動，然後根據行動的結果來判斷是否已經找到答案，如果沒有就繼續思考，直到找到答案為止。

AutoGPT 的行為模式實際上和 ReAct 一樣，只是相比提出 ReAct 的論文中的步驟，AutoGPT 的 prompt 更加詳細，並且提供了更多的工具給 LLM 使用。但不管哪種方式，都需要編寫大量的示例來告訴 LLM 如何思考、行動，並且根據提供工具的不同，效果也會有所不同，並且 ReAct 的思考流程會有很多步驟。而 LangChain 幫我們把這些步驟都隱藏起來了，將這一系列動作都封裝成 “代理”，而這就是我們下一章要介紹的內容了。
react-infinite-scroll-component
Tags: webdev, javascript, react, programming
Published: 2023-07-23 23:58:27

"react-infinite-scroll-component" is a popular React library used to implement infinite scrolling behavior in web applications. Infinite scrolling is a technique where new content is loaded dynamically as the user scrolls down the page, providing a seamless and continuous user experience.

The "react-infinite-scroll-component" library simplifies the process of implementing infinite scrolling by abstracting away much of the complexity. It provides a straightforward and customizable API for developers to add infinite scrolling to their React applications.

Some key features of "react-infinite-scroll-component" typically include:

1. Infinite scrolling: Automatically triggers a callback function when the user reaches the bottom of the scrollable content, indicating the need to load more data.

2. Custom loader: Allows you to display a loading indicator or spinner while new data is being fetched.

3. Control over behavior: You can customize aspects such as the scroll threshold (how far from the bottom the user has to scroll to trigger loading) and whether the loading function should be called just once or repeatedly.

4. Support for various scrollable elements: The library can be used with different types of scrollable elements, including the window, a specific container, or a scrollable component.

 Here's a basic example of how you might use "react-infinite-scroll-component" in a React functional component:

```
import React, { useState, useEffect } from 'react';
import InfiniteScroll from 'react-infinite-scroll-component';

const MyComponent = () => {
  const [data, setData] = useState([]);
  const [page, setPage] = useState(1);

  const fetchData = async () => {
    // Simulate an API call to fetch new data
    const response = await fetch(`https://api.example.com/data?page=${page}`);
    const newData = await response.json();

    setData((prevData) => [...prevData, ...newData]);
    setPage((prevPage) => prevPage + 1);
  };

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

  return (
    <InfiniteScroll
      dataLength={data.length}
      next={fetchData}
      hasMore={true} // Set to 'false' when you have reached the end of your data.
      loader={<h4>Loading...</h4>} // Custom loader element
    >
      {data.map((item, index) => (
        <div key={index}>{item.name}</div>
      ))}
    </InfiniteScroll>
  );
};

export default MyComponent;

```

In this example, the "MyComponent" fetches data from an API when it mounts, and then, as the user scrolls down, the "fetchData" function is called to load more data dynamically.

Remember to install the "react-infinite-scroll-component" package using npm or yarn before using it in your project:

```
npm install react-infinite-scroll-component
# or
yarn add react-infinite-scroll-component
```
The Shocking Revelation: Inline CSS is the Future of Web Development!
Tags: css, frontend, webdev
Published: 2023-07-23 23:36:41

Hold onto your hats, web development community, because we're about to unleash a controversial opinion that will flip the tables of conventional wisdom! Brace yourselves as we make the audacious claim that "Inline CSS is the Future of Web Development!" Yes, you read that right, folks. Forget external stylesheets, preprocessors, and all those fancy class names – we're going back to the good ol' days of inline styles. Prepare to have your minds blown!

## Back to Simplicity
In this fast-paced world, we need to embrace simplicity. What could be simpler than just sticking the CSS right in the HTML? No more worrying about linking stylesheets or managing multiple files. With inline CSS, your styles live where they belong – right next to the elements they style! It's like a beautiful marriage of content and style, hand in hand, without any extra baggage.

## Superior Specificity
Let's be honest, CSS specificity can be a headache. The cascading nature of stylesheets means that you sometimes have to write ridiculously long selectors to target your elements precisely. But fear not! Inline CSS comes to the rescue with unparalleled specificity. No more battling with those pesky selector wars; inline styles take precedence over everything else, saving you hours of frustration!

## The Ultimate Mix-and-Match
Flexibility is the name of the game, and what's more flexible than inline CSS? Imagine effortlessly mixing styles directly within your HTML tags. No need to manage different classes for minor variations; simply change the style attribute whenever you want! The power of inline CSS puts you in full control, like a maestro conducting a beautiful symphony of design.

## Blazing Fast Rendering
Performance is a key concern for any web developer. Inline CSS provides a performance boost that is second to none. Since the styles are right there in the HTML, the browser doesn't need to make additional requests, resulting in lightning-fast rendering. Users will thank you for the snappy experience, and search engines will reward you with better rankings!

## Revolutionary Debugging
Debugging CSS can be a wild goose chase. But with inline CSS, debugging becomes a walk in the park. Just inspect the element, and voila! There's your style, clear as day, without having to trace it through multiple files. This time-saving technique will free up your schedule for more important things, like sipping coffee or pondering the mysteries of the universe.

## The end 
In conclusion, while the idea of inline CSS being the future of web development may sound goofy, it does offer some unique advantages worth considering. Simplifying development, improving specificity, and boosting rendering speed are potential benefits. However, trade-offs like code redundancy and reduced maintainability should be taken seriously. As responsible developers, let's strike a balance between innovation and adhering to best practices to create exceptional web experiences. Happy coding and stay curious! 🚀🌐
Debounce in JavaScript
Tags: typescript, javascript, react
Published: 2023-07-23 23:03:56

Debouncing is a technique used in JavaScript to control the frequency of executing a function that is triggered by an event, such as a button click or key press. It ensures that the function is called only once after a specific period of inactivity, regardless of how many times the event is actually fired during that period.

Here's a simple implementation of debouncing in JavaScript:

```
function debounce(func, delay) {
  let timerId;
  
  return function() {
    const context = this;
    const args = arguments;
    
    clearTimeout(timerId);
    timerId = setTimeout(function() {
      func.apply(context, args);
    }, delay);
  };
}

// Example usage
function handleButtonClick() {
  console.log("Button clicked!");
}

const debouncedButtonClick = debounce(handleButtonClick, 300);

// Attach debounced function to button click event
document.getElementById("myButton").addEventListener("click", debouncedButtonClick);

```
In the code above, the debounce function takes two parameters: func (the function to be debounced) and delay (the amount of time to wait before invoking the debounced function).

Within the returned function, a timer is used to clear any previously set timeouts. After clearing the timeout, a new one is created using setTimeout with the specified delay. This ensures that the debounced function will be called only after the specified delay has elapsed without any new invocations.

In the example usage, the handleButtonClick function is wrapped with debounce, creating a new function debouncedButtonClick. This debounced function can then be attached to the button click event, ensuring that handleButtonClick will be called only once after a 300ms inactivity period.
I built this language learning app
Tags: vue, javascript, career
Published: 2023-07-23 22:44:32

Hi,
I built [this web application](https://inspiring-puppy-6410cb.netlify.app/) in Vue.js that is meant to help you learn a language. The repo to check out the code : [https://github.com/tofl/revocab](https://github.com/tofl/revocab).

The idea is simple, you just add a language and from there you can add as many words as you want with their translation in your language. You can create categories to manage your words. Then you can either display them in a table or use the "Practice" page to review them in a flash card style. All the data is stored in the local storage, so the user can export his vocabulary just to have a backup.

**Why did I build this project?**

I finished my studies over a year ago and took a gap year, haven't written any code since. I really need to get my career started now. This project was simply meant to brush up my skills.

It's quite demoralising because I really feel like I have to relearn everything. I think doing this helped me a lot but I need to keep practicing.

I would really love it if you could check out my source code and tell me what you think about it. What would you have done differently regarding :
* My file structure   
* Code reuse -> would you break down the app into components the same way I did it or would you have created different components?   
* What do you think of my usage of Pinia? I used the options API for Pinia instead of setup. Was it a mistake ?   
* What do you think about the way I named my components? Especially those in the views folder...   
* The time needed to build the app. 2-3 days for me. How fast do you think you would've done it ?   

Also feel free to tell me what you think of the website in general, its design and what you think I should build next!

Thanks !
A Beginner's Guide to HTML, CSS, and JavaScript
Tags: beginners, javascript, css, html
Published: 2023-07-23 22:26:33

Hello everyone! Myself Ekta, I am sharing basics of HTML, CSS and JavaScript.

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

**<u>Introduction:</u>**
Welcome to the world of web development! In this blog, we will explore the fundamental building blocks of the web: HTML, CSS, and JavaScript. These three technologies work together to create the dynamic and visually appealing websites you see every day. Whether you're a complete beginner or looking to brush up on your skills, this guide will introduce you to the basics of HTML, CSS, and JavaScript.

**<u>1. HTML - The Structure of the Web:</u>**
HTML (Hypertext Markup Language) forms the backbone of any web page. It provides the structure and content of a webpage. HTML uses tags to define elements, such as headings, paragraphs, images, links, and more. Let's look at a simple example:


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



**<u>2. CSS - Adding Style and Design:</u>**
CSS (Cascading Style Sheets) is responsible for the visual presentation of a webpage. It allows you to style HTML elements, change colors, adjust layouts, and create visually appealing designs. Here's a simple CSS example:


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




**<u>3. JavaScript - Adding Interactivity:</u>**
JavaScript brings life to web pages by adding interactivity and dynamic behavior. It enables you to respond to user actions, manipulate HTML/CSS, and fetch data from servers. Let's see a basic JavaScript example:


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



**<u>Conclusion:</u>**
HTML, CSS, and JavaScript are the foundational languages of the web. With HTML, you structure the content; with CSS, you add style and design; and with JavaScript, you create interactive and dynamic experiences. This is just the beginning of your web development journey. There's so much more to explore, including responsive design, frameworks, libraries, and server-side technologies. So keep learning and building, and soon you'll be crafting impressive websites and web applications! Happy coding!
GitHub Copilot Custom AutoComplete
Tags: vscode, githubcopilot, autocomplete
Published: 2023-07-23 22:15:11

การใช้ Github Copilot ช่วยทุ่นแรงในการเขียนโค้ดที่เป็นรูปแบบซ้ำ ๆ เช่นการเตรียมข้อมูล Seed สำหรับ migrate database แค่เราเอาข้อมูลที่แบ่งเป็น fields มาแปะไว้ให้ Copilot เรียนรู้มันก็จะจัดการให้เราแบบรวดเร็ว

## Demo จาก YouTube

{% embed https://youtu.be/-ZXQWgd_bTQ %}

จากตัวอย่างจำลองการ insert ข้อมูลลง table แบบหลาย ๆ row ซึ่งจะมีรูปแบบที่ซ้ำ ๆ กัน โดยได้นำข้อมูลมาแปะขั่วคราวไว้ใน comment ของ code แล้วก็ให้ Copilot ทำการเติมเต็มให้เท่าที่ลองมาจะทำงานค่อนข้างแม่นมาก และ รวดเร็ว คือแปะปุ๊บมันก็เติมให้เลยแทบไม่มีการให้รอเลย ก็ลองเอาไปเล่นกันดูครับ