teleren/devto huggingface dataset:
Gnarly Learnings from July 2023
Tags: rails, react, typescript, javascript
Published: 2023-07-31 19:52:52

## [`ComparisonValidator`](https://github.com/rails/rails/pull/40095)


Gone are the days when we need to write custom validators in Rails to determine if a start date begins before an end date! Back in 2021, the `ComparisonValidator` was added to Rails 7. While useful for solving the date comparison example above, that’s not all it can do! It can also compare strings, and it allows for the flexibility of custom comparisons. 


## [Active Storage Can Pre-Process Variants](https://github.com/rails/rails/pull/47473) 

Earlier this month Rails added a feature allowing Active Storage variants to be pre-processed _up front_ by adding `preprocessed: true` to the variant definition. This makes the attachment ready to serve from the outset, rather than requiring the variant to be prepared/transformed on the fly. 


## [JavaScript’s `findLast()` and `findLastIndex()` ](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findLastIndex)

There are a few new `Array` functions included in ES2023, `findLast()` and `findLastIndex()`. The exciting piece is less about what these functions _do_ (you can probably figure it out from the names) and more about the convenience that they provide. As a Rubyist by trade, I am used to a super developer-friendly experience when it comes to the readability, and accessibility of functions so it’s great to see these being added to JavaScript - even if it took until 2023. 😉


## [Partial Renders in Rails](https://guides.rubyonrails.org/layouts_and_rendering.html#using-the-content-for-method)

Partial rendering allows you to create a consistent template with different sections, for example “title”, “body”, and “footer.”  Then the templates can define content for each of those sections without having to know anything about the layout of the root template.


##[`React.FC` Removed From create-react-app Base TypeScript Template](https://github.com/facebook/create-react-app/pull/8177)

If you build React apps with TypeScript, you're certainly used to seeing and using the `React.FC` (or `React.FunctionalComponent`) type at the declaration of your functional components. The folks maintaining create-react-app have decided to remove this type from their template as they believe it is more harmful than helpful. I tend to agree, particularly around the implicit definition of `children`. 


## Contributors:


* [Ethan Fertsch](https://github.com/efertsch)
* Steve Zelaznik
* Taylor Kearns

_Learn more about how The Gnar [builds software](https://www.thegnar.com/software-development)._
Create a MongoDB database from Excel table
Tags: excel, mongodb
Published: 2023-07-31 19:49:34

It's always a trick to convert flexible Excel tables to databases, like this one.

But, it's good practice to just aim for SQL format of the Excel table conversion.

Like this header

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

Note this is just applicable for internal threads, I can convert it to a one-line header as 

MinorDiaMin
MinorDiaMax
PitchDiaMin
PitchDiaMax
MajorDiaMin
MajorDiaMax
TapDrillBasic
ThreadRunouts

and I can save this page to csv files.

After it's saved as csv files, I can simply import that csv file into the MongoDB compass app or use MongoDB VScode extension to import.

Now you have a MongoDB database, take your connection string out and we can continue.
move zeros to the end while keeping the order of the rest
Tags: programming, javascript, beginners, interview
Published: 2023-07-31 19:44:57


Given an array of integers, move zeros to the end while keeping the order of the rest.

You should make the in-place change.

```
Example
const list = [1,0,0,2,3]
moveZeros(list) 
console.log(list) // [1,2,3,0,0]
```
**Notes**: What is the time & space complexity of your approach?

**Solution 1**

```
function moveZeros(arr) {
  let i = 0,
    j = arr.length - 1;
  while (i < j) {
    while (arr[j] === 0 && i < j) j--;
    if (arr[i] === 0) {
      let temp = arr[i];
      arr[i] = arr[j];
      arr[j] = temp;
    }
    i++;
  }
}
```

**Explanation**

It uses two pointers, i and j, to track the current element and the next non-zero element. The loop iterates until i and j meet. Inside the loop, the code first checks if the element at index j is equal to 0. If it is, then the code decrements j. Otherwise, the code checks if the element at index i is equal to 0. If it is, then the code swaps the elements at indices i and j. Finally, the code increments i.


**Solution 2**

```
function moveZeros(arr) {
  let i = 0,
    j = 0;
  while (i < arr.length) {
    if (arr[i] !== 0) {
      arr[j] = arr[i];
      j++;
    }
    i++;
  }
  while (j < arr.length) {
    arr[j] = 0;
    j++;
  }
}

```

**Explanation**

- The moveZeros() function takes an array as input and returns the modified array.
- The function first initializes two variables, i and j. i is used to iterate through the array, and j is used to track the index of the next non-zero element.
- The function then iterates through the array, starting at index i. If the current element is not equal to 0, then the element is swapped with the element at index j. The value of j is then incremented.
- After the loop has finished, the remaining elements in the array are all zeros.
- The function then returns the modified array.


| Approach | Advantages | Disadvantages |
|---|---|---|
| First approach | Only traverses the array once.<br/> Easy to understand and maintain.| Not as space-efficient as the second approach.
| Second approach | Space-efficient. <br/>Easy to understand and maintain.| * Traverses the array twice.
📢 New Additions to DEV's Code of Conduct!
Tags: meta, community, moderation
Published: 2023-07-31 19:14:39

At DEV, we prioritize an inclusive and welcoming environment, and today, we are excited to announce some additional guidelines that further emphasize our commitment to these principles. Our updated [Code of Conduct](https://dev.to/code-of-conduct) now highlights these key points:

**Positive Behavior:**
- Citing sources if used to create content (for guidance see [DEV Community: How to Avoid Plagiarism](https://dev.to/devteam/dev-community-how-to-avoid-plagiarism-4kia))
- Following our [AI Guidelines](https://dev.to/guidelines-for-ai-assisted-articles-on-dev) and disclosing AI assistance if used to create content

**Unacceptable Behavior:**
- No hate speech or communication that is racist, homophobic, transphobic, ableist, sexist, or prejudiced/discriminatory (including pronoun misuse or disrespect)
- Plagiarizing content or misappropriating works

Please keep in mind that the aforementioned points are only the newest additions. Please review the full [DEV Code of Conduct](https://dev.to/code-of-conduct) for complete details, and let's continue building a diverse, respectful, and friendly community together. ✨


---


🤝 Join Us as a DEV Moderator! 🌟

If you share our values and want to help enforce the Code of Conduct, consider becoming a DEV moderator. Visit the [DEV Community Moderation page](https://dev.to/community-moderation) for more information on roles and how to get involved.
Build a drag and drop Kanban Board: React, Typescript, Tailwind, Dnd-Kit
Tags: webdev, typescript, tutorial, react
Published: 2023-07-31 18:14:15

---
title: Build a drag and drop Kanban Board: React, Typescript, Tailwind, Dnd-Kit
published: true
description: 
tags: #webdev #typescript #tutorial #react
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
# published_at: 2023-07-31 17:40 +0000
---
# Build a drag and drop Kanban Board: React, Typescript, Tailwind, Dnd-Kit

Hi everyone,

Are you looking for a fun and practical project to improve your React skills? Do you want to learn how to create a kanban board that lets you organize your tasks and projects in a visual way?

I’ve just uploaded a new video where I show you how to build a kanban board from scratch using React, TypeScript, TailwindCSS and dnd-kit.

[Demo](https://react-kanban-board-dnd-kit-tutorial-yt.vercel.app/)

{% youtube RG-3R6Pu_Ik %}

In this video, you will learn how to:

Create columns and tasks with React components
Enable drag and drop functionality for both columns and tasks using dnd-kit
Edit the content and title of tasks and columns with inline editing
Style the UI with TailwindCSS utility classes
This project is a great way to practice your React skills and learn some new techniques and libraries. You will also end up with a useful tool that you can use for your own projects or customize further.

So what are you waiting for? Check out the video below and let me know what you think in the comments.

I hope you enjoy it as much as I did 😃
Pinghome - Leading uptime monitoring & incident management stack
Tags: monitoring, saas, tech
Published: 2023-07-31 18:02:59

Pinghome is the leading provider of premium cloud-based uptime monitoring services. Our mission is simple: to empower you with the tools and insights you need to ensure your websites and APIs are always up and running flawlessly.

At Pinghome, we believe in delivering the highest quality service, and that starts with our exceptional team of experienced and passionate developers. With their expertise and dedication, we are ready to cater to all your website monitoring needs, providing you with unparalleled support and guidance every step of the way.

[https://www.pinghome.io](https://www.pinghome.io)
Classes
Published: 2023-07-31 18:02:03

Classes serve as a blueprint for instances of objects in programming. Today I learned about creating classes in Ruby. A few notes:

-We only use capital letters in Ruby when referring to classes.
-A multi-word class name should be in CamelCase.
-The keyword `attr_accessor` is used to declare the attributes of a class.
-We can define our own methods within a class using the keyword `def`.

Here is an example of a class with a class method.

```
class Cat
  attr_accessor :name
  attr_accessor :age
  attr_accessor :fur_color

  def meow
    return self.name + " says 'Meow!' :3"
  end
end
```

Another important keyword in classes is `self`. According to the learn materials, this keyword "refers to the class it is inside of and can be used to refer to all the attributes of that class".

Additionally, this module discusses inheritance, which is one of the four pillars of object-oriented programming, or OOP, the most commonly used modern programming paradigm. Inheritance basically means that you can create subclasses of any class that inherit the attributes and methods of the parent class (but also have their own!).

The syntax to a subclass is:

```class SubClass < ParentClass```
Python 🐍 challenge_31⚔️
Tags: python, challenge, beginners
Published: 2023-07-31 17:56:58

## Simple Encryption - Alternating Split 💥

- Implement a pseudo-encryption algorithm which given a string S and an integer N
- Concatenates all the odd-indexed characters of S with all the even-indexed characters of S.
- This process should be repeated N times.


#### Examples:

```
encrypt("012345", 1)  =>  "135024" 
encrypt("012345", 2)  =>  "135024"  ->  "304152"
encrypt("012345", 3)  =>  "135024"  ->  "304152"  ->  "012345"
```

- Together with the encryption function, you should also implement A decryption function which reverses the process.
- If the string S is an empty value or the integer N is not positive, return the first argument without changes.


###### Task URL: [Link](https://www.codewars.com/kata/simple-encryption-number-1-alternating-split)


## My Solution:

```
def encrypt(text: str, n: int) -> str:

    if not text or n < 0:
        return text

    for _ in range(n):

        odd_chars = []
        even_chars = []

        for i, char in enumerate(text):

            if i % 2:
                odd_chars.append(char)
            else:
                even_chars.append(char)

        text = ''.join(odd_chars + even_chars)

    return text


def decrypt(encrypted_text: str, n: int) -> str:

    if not encrypted_text or n < 0:
        return encrypted_text

    length = len(encrypted_text)
    half_length = length // 2

    for _ in range(n):

        odd_chars = encrypted_text[:half_length]
        even_chars = encrypted_text[half_length:]

        decrypted_chars = []

        for i, j in zip(even_chars, odd_chars):

            decrypted_chars.append(i)
            decrypted_chars.append(j)

        if length % 2 == 1:

            decrypted_chars.append(even_chars[-1])

        encrypted_text = ''.join(decrypted_chars)

    return encrypted_text
```


### Code Snapshot:


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


### Learn Python

######  Python top free courses from Coursera🐍💯🚀

🎥 {% youtube 2VRXU2H4q0c%}


### Connect with Me 😊

#### 🔗 Links

[![linkedin](https://img.shields.io/badge/linkedin-0A66C2?style=for-the-badge&logo=linkedin&logoColor=white)](https://www.linkedin.com/in/mahmoud-el-kariouny-822719149/)

[![twitter](https://img.shields.io/badge/twitter-1DA1F2?style=for-the-badge&logo=twitter&logoColor=white)](https://twitter.com/Mahmoud42275)
Enhance Your Productivity with Code-Snippets in VSCode
Tags: vscode, python, javascript, coding
Published: 2023-07-31 17:56:13

I've been using a lot of Python27 recently and since there's no f-strings in it, I have to write a lot of code like this for debugging:
```
logging.info("This variable: {}".format(variable))
```
which I really hate.

Using Code Snippets has really been helpful in this regard since I can just type any letter combination that I have configured and get a boilerplate of what I want to code.

E.g. on typing `plog` I get:

```
logging.info('${1:placeholder}: {}'.format(${1:placeholder}))
```

and if I start typing after pressing enter, the placeholder `1:placeholder` gets replaced with whatever I typed. Since in this example there are two placeholders, pressing enter will replace them both simulataneously.

If you have set a placeholder like `2:placeholder` then you can just hit tab after you're done replacing `1:placeholder` so that you can edit `2:placeholder`.

Here's how you can do it in VSCode.
Open VSCode and press ctrl + shift + P. Type "Snippet: Configure Code Snippets" and hit enter.

![Code Snippet Option VSCode](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wp7w3job3ta8x32d36ow.png)

Select a language (I'll select Python).

![Language Selection in Code Snippet](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r9y12c6h4k3fakdjtcup.png)

Then add snippets like so. Notice that each new line is a new entry in the body array.

![Code Snippets Configuration](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tltp2dpzdznch3m0yo4w.png)

Save the file.

Now let's say I type `imndb` 

![Typing imndb](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fid4lfx04p6w2vdajw6a.png)

and press enter, it gets replaced with my saved code snippet.

![imndb Code Snippet](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n761fs41zt78qkbfpuno.png)

Hope this was helpful in improving your workflow. Feel free to drop a comment and share with your friends.
JS Challenge: Fold a long line of text into lines of 80ish characters without breaking words
Tags: javascript, javascripttips, jschallenge, oneliners
Published: 2023-07-31 17:40:34

---
title: JS Challenge: Fold a long line of text into lines of 80ish characters without breaking words
published: true
description: JavaScript one-liner to fold a long line of text
tags: javascript, javascripttips, js, jschallenge, oneliners
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
# published_at: 2023-07-31 16:37 +0000
---
The challenge is to wrap text after every 80th character. If the 80th character is within a word, wrap after the word ends.

Solution:
```js
const longLine = `This is a long line of text that needs to be \
folded after 80ish characters. If the 80th character \
happens to be within a word, wrap the line after the word`;

console.log(longLine.replace(/([^\n\r]{80})\s+/g, "$1\n"));
```

Basically the above code scans the long line of text for stretches of 80 characters without a line break followed by space(s) and inserts line breaks at those offsets.

If the 80th character falls within a word, the above code will forward to the end of that word and break there. But what if you don't want the lines to exceed 80 characters under no circumstances? In that case you need to go back to the end of the previous word and insert a line break there. The code below does exactly that:

```js
const longLine = `This is a long line that needs to be folded \ 
into lines not more than 80 characters long without breaking \
words.`;

console.log(longLine.replace(/([^\n\r]{80}\s+)/g, 
  (m,g) => g.replace(/\s+([^\s]+\s*)$/, "\n$1")
));
```
Reliability in PostgreSQL
Tags: postgressql, apacheage, database, sql
Published: 2023-07-31 16:29:44

Reliability holds immense importance in a robust database system, and PostgreSQL is fully dedicated to ensuring a dependable operation. In this blog post, I will explore the significance of reliability in database systems, which plays a crucial role in preserving data integrity and safeguarding against potential failures.

In the context of a database system, reliability implies that all data from a committed transaction must be securely stored in a nonvolatile location, protected from power outages, operating system glitches, and hardware malfunctions. PostgreSQL achieves this by writing data to the computer's permanent storage, typically using disk drives. The remarkable aspect is that even in the event of a catastrophic computer failure, as long as the disk drives remain intact, they can be moved to another computer with similar hardware, and all committed transactions will be preserved.

However, ensuring data is written to disk is not as simple as it sounds. Disk drives are much slower than main memory and CPUs, which leads to several layers of caching between the main memory and disk platters. To tackle this, PostgreSQL employs operating system buffer cache features to force writes from the cache to disk. Yet, there are additional caches in disk drive controllers and the disk drives themselves that can pose reliability hazards, especially those with volatile write-back caches.

To mitigate these risks, administrators must take measures like disabling write-back caching when necessary and choosing disk controllers with battery-backup units (BBUs) that preserve cache contents during power failures.

In any serious database system, reliability is of paramount importance, and PostgreSQL leaves no stone unturned in its pursuit of dependable operation. This makes it a powerful and robust solution for mission-critical applications where data reliability is crucial.

[Reference](https://www.postgresql.org/docs/current/wal-reliability.html)
Baby coders. Git add/commit/push and create files using terminal.
Tags: terminal, vscode, javascript, beginners
Published: 2023-07-31 17:07:06

Here we are going to focus on git add/commit/push as well as a simple action to create a file with the terminal.

when changing files on a cloned repository we want to always follow through with adding the changes through git with `$git add .`  , then committing them with `$git commit -m` "description of changes", and finally push the changes right to your forked repository on github with $git push

example:

```
$git add .
$git commit -m "add README.md"
$git push
```
If the steps are followed correctly you should see the changes reflected on your forked over repository on github.


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

Now lets move on to another simple but important to remember action. 
Lets create a file in your repository using $touch.
When creating a file it could be simplest to just use Vscode to right click and create file. Yet its super important to know the roots and basics so if you are put in a situation where you cant use vscode you will still be able to make a file in seconds using our lovely terminal.
Lets get straight to it!

Example:


```
$touch README.md
```

Boom its as simple as that!!! 
Now lets break this down.
First we use the command touch "touch is used to create files", next we name the file being ``"README"``. We next need to define that file type so this type will be ``".md"``
Now we have our new file created! woooo!!! GJ!


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/123myi33z1lqezthab7j.jpg)
updating g++ compiler
Tags: programming, opensource, discuss, development
Published: 2023-07-31 17:04:35

I updated my MinGW compiler to the latest version and now when I look at g++ --version I get 201703 which I believe is version C++17!  Unfortunately I'm looking at a tutorial that requires C++20!  So does anyone know where to go to download version 20?  I thought that the MinGW website had the latest and greatest version, but it seems that I am wrong in this assumption. Not the end of the world, but I would like to explore threads, so I need to update to version 20. Advice welcome on this one.
sydney / wt1v
Narrow profile LLM
Tags: narrow, profile, llm, chatbot
Published: 2023-07-31 17:00:49

Hi, everyone,
my name is Aya, short for Aigerim. My team is called Aestima project. We are deeply involved in complex multidisciplinary research. To address the challenges of research we propose to design a specialized LLM-driven chatbot. The model will be focusing on areas of autism, technology, and regulation, to synthesize knowledge relevant to these topics.
If you are interested in this idea project, please reach out. We will be happy to discuss any form of co-operations, from consultation to partnership. We have a great team of experts and we need someone to consult us about tech side. Best regards.