teleren/devto huggingface dataset:
File validation on the browser ✨
Published: 2024-03-03 17:13:28

Validating client-side files in a browser has always been a tedious, repetitive and boring task, at least until now.

**Zeppol** has arrived, a library that allows you to validate different types of files, from the most basic to the most complete. Here are some examples.

```js
import { type ZRules, type Validator, checkFileValidity} from 'zeppol'

// Add ZRules if you want autocompletion and type checking
const rules: ZRules<Validator> = {
    audio: {
        $params: {
            minSize: {
                value: 0,
            },
            maxSize: 1000000,
            minDuration: 10,
            maxDuration: {
                value: 60,
                // Custom error message
                message: 'The file must be shorter than 60 seconds'
            },
            mime: ['audio/mpeg', 'wav']
        },
        // Custom validators
        $validators: {
            name(file) {
                return {
                    valid: file.name.length > 10,
                    message: `File name must be longer than 10 characters`
                }
            }
        }
    }
}

const audioFile = document.getElementById('audio-file')

audioFile.addEventListener('input', async ({ target }) => {
    const file = target.files[0]
    await checkFileValidity(file, rules)  // This will throw an error if the file is not valid
})
```	

The above example defines the following rules for the file:
- The file must be an audio file
- The file must have a size between 0 and 1000000 bytes
- The file must have a duration between 10 and 60 seconds
- The file must be of type audio/mpeg or audio/wav
- The file name must be longer than 10 characters

https://www.npmjs.com/package/zeppol
reloj personalizado
Tags: beginners, programming, css, learning
Published: 2024-03-03 17:05:47

``<p class="codepen" data-height="300" data-theme-id="light" data-default-tab="html,result" data-slug-hash="LYvELde" data-user="sun-coin" style="height: 300px; box-sizing: border-box; display: flex; align-items: center; justify-content: center; border: 2px solid; margin: 1em 0; padding: 1em;">
  <span>See the Pen <a href="https://codepen.io/sun-coin/pen/LYvELde">
  Reloj con saludo customizado</a> by psicosunny (<a href="https://codepen.io/sun-coin">@sun-coin</a>)
  on <a href="https://codepen.io">CodePen</a>.</span>
</p>
<script async src="https://cpwebassets.codepen.io/assets/embed/ei.js"></script>
TypeScript (2): Handling Nullable Types (5 quick ways)
Tags: typescript, tutorial, learning, beginners
Published: 2024-03-03 16:44:30

Null-able types are all about typing a variable value that can either hold a valid value of a specific type or be NULL or UNDEFINED. 

How to handle them in typescript? so writing robust and error-free TypeScript code.

1. Declare Null-able Types: [using the union operator (`|`)]:

```typescript

   let name: string | null;
   let age: number | undefined;

```

2. Checking for Nullable Values: [use type guards]

```typescript

   if (name !== null) {
       console.log(name.toUpperCase());
   }

```

  3. Optional typing: [use Optional chaining]:

```typescript

   console.log(age?.toFixed(2));

```

4. Assigning Nullable Values: [assigned null or undefined explicitly]:

```typescript

   name = null;
   age = undefined;

```

5. Nullish Coalescing Operator (`??`):

_- It returns the right-hand operand if the left-hand operand is null or undefined._

```typescript

   let result: string;
   let nullableValue: string | null = null;

   // Using nullish coalescing operator
   result = nullableValue ?? "Default Value";
   console.log(result); // Output: "Default Value"

```

By understanding how to handle nullable types in TypeScript, you can write more robust and error-resistant code that gracefully handles nullable values.

Article on Linkedin: https://www.linkedin.com/posts/taricov_typescript-developercommunity-softwareengineering-activity-7170098531318284288-hoIj?utm_source=share&utm_medium=member_desktop
Entendendo o uso de async/await com Promises no Javascript.
Tags: javascript, node, learning, promises
Published: 2024-03-03 16:31:51

## Entendendo Promises em JavaScript

As Promises são um recurso fundamental em JavaScript para lidar com operações assíncronas, elas representam um valor que pode estar futuramente ou nunca (caso a promise retorne um erro). No contexto de desenvolvimento web, são frequentemente utilizadas para lidar com solicitações de rede, acesso a bancos de dados e outras operações que levam tempo para serem concluídas.

## O que são Promises?

Em termos simples, uma Promise é um objeto que representa o sucesso ou a falha de uma operação assíncrona. Ela possui três estados possíveis:

1. **Pendente**: Estado inicial, quando a Promise está aguardando o resultado da operação.
2. **Resolvida (Fulfilled)**: Quando a operação é concluída com sucesso.
3. **Rejeitada (Rejected)**: Quando a operação falha.

## Quando as Promises são utilizadas?

Promises são comumente utilizadas em situações em que uma operação assíncrona precisa ser realizada, como:

- Requisições HTTP para recuperar dados de APIs.
- Acesso a bancos de dados.
- Leitura e escrita de arquivos.
- Qualquer operação que envolva tempo de espera, como setTimeout.

## Uso do async/await

O `async/await` é uma sintaxe introduzida no ECMAScript 2017 (também conhecido como ES8) para facilitar o trabalho com Promises. Ele permite escrever código assíncrono de forma mais síncrona, tornando-o mais legível e fácil de entender.

> Antes do ES8 introduzir a sintaxe do async/await, as promises eram utilizadas através do método `.then()`, e os erros captados através do método `.catch()`.

## Exemplo de uso de uma Promise com async/await

```javascript
// Função que retorna uma Promise que resolve após um certo tempo
function esperar(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

// Função assíncrona que utiliza o async/await
async function exemploAsyncAwait() {
  console.log('Iniciando operação assíncrona...');
  await esperar(2000); // Espera 2 segundos
  console.log('Operação assíncrona concluída!');
}

// Chamada da função assíncrona
exemploAsyncAwait();
```

Neste exemplo, a função `esperar` retorna uma Promise que resolve após o número especificado de milissegundos. A função `exemploAsyncAwait` utiliza o `await` para aguardar a conclusão da Promise retornada por `esperar`.

## Conclusão

As Promises e o `async/await` são recursos poderosos que tornam o código assíncrono em JavaScript mais fácil de escrever e entender. Elas são essenciais em todo o desenvolvimento que envolva o JavaScript como linguagem de programação, podendo ser utilizadas em qualquer tipo de chamada assíncrona.
What is a promise
Tags: javascript, programming, webdev, beginners
Published: 2024-03-03 16:17:17

## **The syntax of Promise creation looks like below,

```
const promise = new Promise(function (resolve, reject) {
  // promise description
})
```

## The usage of a promise would be as below,

```
`const promise = new Promise(
  (resolve) => {
    setTimeout(() => {
      resolve("I'm a Promise!");
    }, 5000);
  },
  (reject) => {}
);

promise.then((value) => console.log(value));`
```

### The action flow of a promise will be as below,


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ne4f3eimp1d7pdxvexo1.png)
Manual Workflows in GitLab
Published: 2024-03-03 16:14:51



GitLab's manual workflows offers users the control to decide when the workflow should commence. The workflow is often defined in a gitlab-ci.yml file. The simplest template looks like the following.

> stages:
>   - deploy
> git_status:
>   stage: deploy
>   script:
>     - echo "hello"
>     - ls
>     - pwd
>     - git pull origin main
>     - git status
>   when: manual
>   allow_failure: true

- stages: Defines the stages in our CI/CD pipeline. In this scenario, we have a single stage named "deploy," signifying the final phase before deployment.
- git_status: The identifier for our job, customizable to suit our project's needs.
- script: Specifies the commands to be executed by GitLab upon job activation
- when: manual: mandates manual intervention before proceeding 
- allow_failure: true: Provides leniency in the event of job failure

Once the above changes have been committed, head over to the pipelines section. Build > Pipelines and click on the "Play" button adjacent to the job.

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



---

This can be used to create a release for a project or for any other manual inspecting of the project such as running a lighthouse evaluation on a reactjs project.

This article is also published in https://parkerrobert.medium.com/manual-workflows-in-gitlab-d6addb70d389
What is a higher order function
Published: 2024-03-03 16:11:46

A higher-order function is a function that accepts another function as an argument or returns a function as a return value or both.

const firstOrderFunc = () =>
  console.log("Hello, I am a First order function");
const higherOrder = (ReturnFirstOrderFunc) => ReturnFirstOrderFunc();
higherOrder(firstOrderFunc);
A Simple Light/Dark Theme Toggle - My First NPM Package
Tags: webdev, javascript, react, tailwindcss
Published: 2024-03-03 16:11:30

To dodge the debate around dark vs light theme, I always put a toggle somewhere on my websites.

The first time I did this, I couldn't find something pre-made that did exactly what I was envisioning - so I made it myself!

It's built to integrate seamlessly with Tailwind and the 'dark' tag:

`bg-white dark:bg-black`

To keep things simple, I've also used icons instead of text - the light mode toggle is a sun, the dark mode a moon.

![Light Mode](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tmrm50fsws3u8lema6po.png)

![Dark Mode](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r7tes0ilb3ui2yu8wkfz.png)

If you'd like to have a play with it, or use it in your own projects, please feel free to do so!

https://github.com/JJB9922/Tailwind-Easy-Theme-Switcher
https://www.npmjs.com/package/tailwind-easy-theme-switcher
I am a front-end developer and I was looking for a job and I just want your help
Tags: webdev, frontenddeveloper, javascript, programming
Published: 2024-03-03 16:01:05

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

I am a front-end developer and I was looking for work and I just want your help in finding work and I would be very grateful for the help. I need this work a lot and I was looking hard for work. If there is anyone who can help me I will be very grateful to him for the help.

And this is my site:-
https://www.aboeissa.online/
You will find everything about me in it, including the certificates I obtained

Here are some of my works. You will find many websites created in various languages:
https://aboeissa.online/vibrant/template/vibrant.html

If anyone can help me I will be very grateful
Discovering Your Why: Finding Your Way to Thrive Early in Your Career
Tags: webdev, beginners, programming, career
Published: 2024-03-03 16:00:28

Some of us seem to be born into their purpose, some find it very early in their lives and some of us need more time to find their drive, their reason to get up on Mondays.

Either is fine, as long as we are keen to find what makes us fulfilled and gives our life reason.

I spent decades doing things that weren’t advancing me and making me use my full potential. In my opinion this is a huge waste of time and talent. The sooner we find our why the quicker we thrive, the more we are successful, healthy and wealthy.

Let me help you accelerate your growth as an engineer and shape your career path together. With me as your mentor, you'll uncover your core motivations and learn how to build a fulfilling career centered around what truly drives you.

## Join Me

Read more about [Engineering Culture in Meta (Facebook)](https://engineeringbolt.com/contact/), [⚡Newsletter](https://engineeringbolt.substack.com/subscribe), [Twitter](https://twitter.com/alexrashkov/) and [LinkedIn](https://www.linkedin.com/in/alexrashkov) for more Career, Leadership and Growth advice.

{% embed https://twitter.com/alexrashkov/status/1764317096861663426 %}

 #startwithwhy #growth #purposedrivenlife
Slots VS Props in NUXT-3
Published: 2024-03-03 15:58:23

In Nuxt 3, "slots" and "props" serve different purposes in the context of components.

1. **Slots:**
   - Slots allow you to pass content from a parent component to a child component. They are useful when you want to create reusable components that can accept different content depending on where they are used.
   - In Nuxt 3, slots are defined in the child component using `<slot></slot>` tags. The content provided by the parent component is then inserted into these slots.
   - Slots provide flexibility and reusability by allowing the parent component to inject content into specific areas of the child component's template.

Example:
```html
<!-- ChildComponent.vue -->
<template>
  <div>
    <h2>Child Component</h2>
    <slot></slot> <!-- Content from parent component will be inserted here -->
  </div>
</template>
```

```html
<!-- ParentComponent.vue -->
<template>
  <div>
    <h1>Parent Component</h1>
    <ChildComponent>
      <!-- Content passed to ChildComponent's slot -->
      <p>This content will be placed inside the ChildComponent.</p>
    </ChildComponent>
  </div>
</template>
```

2. **Props:**
   - Props are custom attributes that you can define on a component to pass data from a parent component to a child component.
   - They allow you to make your components dynamic by passing data dynamically to them.
   - In Nuxt 3, props are defined in the child component's script section and can be used inside the component's template.
   - Props are useful when you need to pass specific data or configurations to a component.

Example:
```html
<!-- ChildComponent.vue -->
<template>
  <div>
    <h2>{{ title }}</h2>
  </div>
</template>

<script>
export default {
  props: {
    title: {
      type: String,
      required: true
    }
  }
}
</script>
```

```html
<!-- ParentComponent.vue -->
<template>
  <div>
    <h1>Parent Component</h1>
    <ChildComponent title="Dynamic Title" />
  </div>
</template>
```

In summary, while slots are used for passing content from parent to child components, props are used for passing data or configurations from parent to child components in Nuxt 3.

**> Anytime, anyday..I'd prefer to use SLOTS instead of PROPS. Slots come in very handy and you have easier control of your DOM than when you use props.**
PPH (Personal Pay Hub)
Tags: webdev, programming, python, flask
Published: 2024-03-03 15:57:15

Are you ready to dive into the excitement of a brand new project that promises to simplify your financial management in revolutionary ways?

Our innovative program, developed using Python, is designed to interpret and manage your financial data using artificial intelligence models. Imagine simplifying your financial information work, whether it's tracking your transactions, managing your payment receipts, or estimating amounts due.

We are excited to invite you to join our community on Discord via the following link: https://discord.gg/m6yzXkA7. You will discover a dynamic space where you can exchange ideas, ask questions and be at the heart of the evolution of this exciting project.

For those who like to dive into code, our project is fully accessible on GitHub: https://github.com/ocryptocode/PPH. Explore, contribute and be part of the technological adventure.

Finally, be sure to visit our website dedicated to the project: https://ocryptocode.github.io/PPH. There you will find detailed information, demonstrations and all the resources you need to stay up to date with the latest advances.

Join us on this revolutionary financial adventure and transform your data management with our intelligent program. Your financial future starts here!
Livewire CRUD Generator: Powering Efficient Laravel Development
Tags: laravel, livewire, php, webdev
Published: 2024-03-03 15:53:03

Livewire CRUD Generator: Powering Efficient Laravel Development
Introduction
Livewire CRUD Generator is a Laravel package designed to simplify and streamline the development of CRUD functionality in Laravel applications. Whether you're a seasoned Laravel developer or just starting, this package provides a fast, efficient, and user-friendly way to manage Create, Read, Update, and Delete operations.

Benefits of Livewire CRUD Generator
Streamlined Development: Quickly scaffold CRUD interfaces for your Laravel Eloquent models. Say goodbye to repetitive coding and hello to productivity.

User-Friendly Interface: An intuitive interface allows you to customize your generated components with ease. No need for complex configurations or extensive documentation.

Time-Saving: Save valuable time during the development phase. With Livewire CRUD Generator, you can focus on building the core features of your application.

Efficiency: Manage your data efficiently with CRUD operations. The package automates the process, reducing manual efforts and minimizing errors.

Versatility: The generated components are versatile and can be easily modified to suit your specific project requirements.

Compatibility: Livewire CRUD Generator is compatible with Laravel versions ^10.0 and tested on version ^8. It uses auth middleware and installs Breeze just in case you don't have any other auth mechanism.

How to Use Livewire CRUD Generator
Installation is straightforward. Simply run the following Composer command:

composer require sagor110090/livewire-crud --dev
After the installation, initiate the package with:

php artisan crud:install
This command sets up your project for generating CRUD components. To generate CRUD for a specific table, run:

php artisan crud:generate {table-name} 
This command generates the necessary files for CRUD operations, including a Livewire component, model, views, and factory.

Comprehensive Documentation
Livewire CRUD Generator provides comprehensive documentation on how to use the package effectively. You can find more detailed documentation on the official Livewire CRUD website.

Conclusion
Livewire CRUD Generator is a powerful tool for Laravel developers, offering a seamless way to build and manage CRUD interfaces. With its user-friendly interface, time-saving features, and versatility, it's a must-have for any Laravel project. Improve your development workflow and enhance your productivity with Livewire CRUD Generator.

 



https://freecoderteam.com/post/livewire-crud-generator-powering-efficient-laravel-development
Improved?
Published: 2024-03-03 15:42:52

Don't know about my love with questioning but it seems like the habit is better in its own. Coming back to my story I have tried to improve my business(selling ice creams on beach till now) well for now its going a bit better.
At least now i have confirmed myself that the day and night will not pass with an empty tummy. without food everything seems to be passing in a lot oof dizziness , i know it has been a day of not writing anything but believe it the day before was one of the best in my life.
Been first time for me to ever eat anything from my own money except of begging from strangers or parents. Well have nothing much to discuss about today , eh guess will see you guys another day not simply for tomorrow.
Improved?
Published: 2024-03-03 15:42:49

Don't know about my love with questioning but it seems like the habit is better in its own. Coming back to my story I have tried to improve my business(selling ice creams on beach till now) well for now its going a bit better.
At least now i have confirmed myself that the day and night will not pass with an empty tummy. without food everything seems to be passing in a lot oof dizziness , i know it has been a day of not writing anything but believe it the day before was one of the best in my life.
Been first time for me to ever eat anything from my own money except of begging from strangers or parents. Well have nothing much to discuss about today , eh guess will see you guys another day not simply for tomorrow.
Mastering Python: 6 Sneaky Tips Every Developer Should Know
Tags: python, programming, tutorial, softwaredevelopment
Published: 2024-03-03 15:28:29

Hey, Pythonistas! 🐍 

Whether you're a seasoned developer or just starting out in the world of programming, **Python has most likely grabbed your interest.** 
It's versatile, powerful, and very user-friendly! 💻 But let's take it up a notch, shall we? 
In this blog, I'll reveal some hidden Python tips and tricks that will elevate your experience from beginner to phenomenal.🚀 
Buckle up, because we're going to delve far into the world of Python wizardry. 🧙‍♂️

**List Comprehensions:**
Forget the clumsy loops! List comprehension is your new best buddy. They are concise, readable, and oh-so-pythonic. 
Turn this:

```
squares = []
for x in range(10):
    squares.append(x**2)
```
into this:

```
squares = [x**2 for x in range(10)]
```
**The zip() Function:**
Need to iterate over numerous lists at once? Zip() has your back. It combines two or more iterables to provide an iterator of tuples.

```
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
for name, age in zip(names, ages):
    print(name, 'is', age, 'years old.')
```
**Unpacking:**
Unpack sequences into separate variables effortlessly. This is especially handy when dealing with functions that return multiple values.

```
coordinates = (3, 5)
x, y = coordinates
print('x =', x)
print('y =', y)
```

**Virtual Environments:**
Keep your project dependencies neat and tidy with virtual environments. No more conflicts between packages!

```
$ python -m venv myenv
$ source myenv/bin/activate
```
**Generator Expressions:**
Want to generate large sequences of values without hogging memory? Generator expressions are the way to go.

```
squares = (x**2 for x in range(10))
```

**Context Managers (with Statement):**
Safely manage resources like files, locks, or database connections with context managers.

```
with open('file.txt', 'r') as f:
    data = f.read()
```

Got more Python secrets up your sleeve? Share them in the comments below and let's keep the Pythonic magic alive!🐍✨
How to document
Tags: beginners, discuss, learning, github
Published: 2024-03-03 15:37:13

I have a couple of projects in mind that I want to build. I am new to Git Hub and have heard people say that documentation is very important. It helps the people reading my code. I just wanted to hear how should I start. When should I document, how, are there any general rules when documenting? Any tips will help, thank you.