teleren/devto huggingface dataset:
How to Use Laravel Rules
Tags: laravel, php
Published: 2023-07-27 14:23:00

Managing field logic in a separate file through rules can greatly enhance the organization and reusability of your codebase. By employing this approach, you can utilize your logic for various validations throughout your project. Let's demonstrate this with an example:

Suppose we have a Permission enum in our Laravel project, and when an admin assigns a permission to a user, we need to verify if the permission is valid. To accomplish this, we'll create the Permission enum using [BenSampo/laravel-enum](https://github.com/BenSampo/laravel-enum) package:

```bash
php artisan make:enum Permission
```

Next, we'll define some sample permissions in the Permission enum:

```php
const ManagePermissions = 'manage-permissions';

const ManageUsers = 'manage-users';

const ManagePosts = 'manage-posts';
```

Now, let's proceed to create the ValidPermissionRule to handle permission validation:
```bash
php artisan make:rule ValidPermissionRule
```

The validate method in the ValidPermissionRule class will accept three parameters:
- `$attribute`: name of the field
- `$value`: value of the attribute
- `$fail`: a callback to use if the validation is not valid


Our logic for this rule is quite straightforward: we need to check if the `$value` exists in the `Permission` enum; if it does, the validation passes; otherwise, it fails, and we'll use the `$fail` callback to display an error message:
 
```php
public function validate(string $attribute, mixed $value, Closure $fail): void
{
    if (! in_array($value, Permission::getValues())) {
        $fail($attribute.' is invalid.');
    }
}
```

By using this ValidPermissionRule, you can now easily apply permission validation in various parts of your application, ensuring that only valid permissions are assigned to users.


Now that we have created the ValidPermissionRule, we can use it in our Laravel project to validate permissions. Let's explore two methods of using this rule.

You can use the rule directly in your controller or wherever you need to validate the permission:
```php
$request->validate([
    'permission' => new ValidPermissionRule,
]);
```

Alternatively, you can extend the rule and give it a name for easier usage across your application:

First, extend the rule in a service provider or directly in the boot method of the AppServiceProvider:
```php
use Illuminate\Support\Facades\Validator;

Validator::extend(
    'valid_permission',
    '\\App\\Rules\\ValidPermissionRule@validate'
);
```

Now you can use the extended rule with the name valid_permission in your validations:
```php
$request->validate([
    'permission' => 'valid_permission',
]);
```

By using this structured approach and custom validation rule, you can easily maintain and reuse your permission validation logic throughout your Laravel application.
Oque estudar {rust}
Tags: rust, webdev, programming, tutorial
Published: 2023-07-27 13:42:31



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



Para aprender Rust, você pode seguir uma abordagem passo a passo para adquirir os conhecimentos necessários. Aqui estão as principais áreas que você pode estudar para se tornar proficiente em Rust:

1. **Sintaxe e estrutura da linguagem:** Comece com o básico, aprendendo a sintaxe e a estrutura da linguagem Rust. Entenda como declarar variáveis, usar tipos de dados, estruturas de controle (como loops e condicionais) e funções.

2. **Propriedades da linguagem:** Aprenda os principais conceitos que tornam Rust único, como propriedade de propriedade, empréstimos, mutabilidade e o sistema de tipos de Rust. Esses conceitos são fundamentais para escrever código seguro e livre de erros.

3. **Gerenciamento de memória:** Estude como o Rust gerencia a memória de forma segura, evitando problemas comuns, como vazamentos de memória e referências inválidas. Entenda os conceitos de empréstimos e regras de propriedade.

4. **Tipos de dados avançados:** Aprofunde-se nos tipos de dados mais avançados, como enums, structs, tuplas e arrays. Aprenda a usar esses tipos para criar estruturas de dados complexas e eficientes.

5. **Programação concorrente e assíncrona:** Rust possui um poderoso suporte para programação concorrente e assíncrona. Estude os conceitos de threads, paralelismo e programação assíncrona usando as primitivas fornecidas pelo Rust.

6. **Gerenciamento de pacotes e projeto com Cargo:** Familiarize-se com o gerenciador de pacotes do Rust, chamado Cargo. Aprenda a criar, gerenciar e compartilhar projetos em Rust usando o Cargo.

7. **Bibliotecas e frameworks:** Explore as bibliotecas e frameworks disponíveis para Rust que podem facilitar o desenvolvimento de diferentes tipos de aplicativos, como web, jogos, sistemas, entre outros.

8. **Exemplos práticos:** Escreva projetos pequenos e exemplos práticos para aplicar os conceitos aprendidos. Isso ajudará a solidificar seu conhecimento e a ganhar experiência na escrita de código em Rust.

9. **Leitura e documentação oficial:** Consulte a documentação oficial do Rust (https://doc.rust-lang.org/) e outros recursos recomendados pela comunidade. Isso lhe dará informações detalhadas e precisas sobre a linguagem.

10. **Participação na comunidade:** Participe de fóruns, grupos e comunidades de desenvolvedores em Rust. Compartilhe seu aprendizado, faça perguntas e aprenda com outras pessoas. A comunidade Rust é amigável e colaborativa.

Lembre-se de que o aprendizado de uma nova linguagem de programação requer prática e dedicação. À medida que você adquire mais experiência em Rust, continue explorando projetos e desafios mais complexos para aprimorar suas habilidades. Aproveite a jornada de aprendizado e divirta-se programando em Rust!
Fun with UTF-8: Printing sound
Tags: unicode, utf, raku
Published: 2023-07-27 13:37:22

"Fun with UTF" are digressions from main posts in this series. They are purely optional and not needed to understand basics of UTF, but showing some cool tricks. Let's start with first one.  

I already explained that UTF-8 is ASCII compatible. And ASCII had many control characters, that were literally controlling physical devices like this teletype on the other end:

![Teletype](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rl60mwx6a2lzy05644xw.jpg)

Many of those control characters are obsolete today. Some are still in use, like for example `CRLF` line ending, made from two control characters Carriage Return (literally moving printing head to the beginning of line) and Line Feed (literally scrolling paper to the next line).

Now try this:

```
$ raku -e 'Buf.new( 0x07 ).decode.say'
```

It prints `BEL` character. Which surprisingly is still supported by many terminals today and will do system alert ping. Back in DOS era (when computers without sound cards were common) it caused a PC speaker beep. And even further back in time it was ringing physical bell (hence the name) to notify that something in incoming transmission required attention.
UTF-8 internal design
Tags: unicode, utf, raku
Published: 2023-07-27 13:37:04

We already know from previous posts of this series that UTF-8 is variable, multi byte encoding. But how does this exactly work? How does any program know where each character starts and how many bytes it has?

**`0`**`xxxxxxx` - This is 1 byte character. You may notice that it uses the same bits as 7 bit ASCII and that is correct - UTF-8 is compatible with ASCII. However this `0` is important, because it was repurposed to serve as a byte length terminator.
**`110`**`xxxxx` **`10`**`xxxxxx` - This is 2 bytes character.
**`1110`**`xxxx` **`10`**`xxxxxx` **`10`**`xxxxxx` - This is 3 bytes character.
**`11110`**`xxx` **`10`**`xxxxxx` **`10`**`xxxxxx` **`10`**`xxxxxx` - This is 4 bytes character.

So:
- Amount of `1`s before `0` tells how many bytes <u>multi byte</u> character has.
- Following bytes must start with `10`, which means they are <u>multi byte</u> character continuation.
- If there are no leading `1`s it is ASCII.

Here are some real characters analyzed:

```
raku -e '"a".encode>>.fmt( "%08b" ).say'
(01100001)
```

```
$ raku -e '"ź".encode>>.fmt( "%08b" ).say'
(11000101 10111010)
```

```
$ raku -e '"😊".encode>>.fmt( "%08b" ).say'
(11110000 10011111 10011000 10001010)
```

**Note on Raku:** I will illustrate many UTF examples using [Raku](https://www.raku.org/) language. It has excellent built-in UTF support and compact syntax with no boilerplate. I also will explain syntax briefly, which may be outside of the scope of this series, but will help to understand what is going on in these one-liners.
In this case character is encoded into byte buffer. Each byte is passed to formatting function (`>>` is just a lazy way to avoid `for` or `map`) which prints them as eight zero-padded bits.

Let's stop for a moment to admire **genius UTF-8 design**:

- It is 7 bit ASCII compatible. Which also means it is space efficient, most commonly used letters use single byte.

- Has natural protection against ASCII extensions described previously, which used **`1`**`xxxxxxx` space. If byte representation of a text encounters byte starting with `1` which does not match "_amount of `1`s followed by `0` must be followed by the same amount of bytes starting with `10`_" pattern, then parser can detect that some crooked encoding is being loaded as UTF-8.

```
$ raku -e 'Buf.new( 0b10000000 ).decode'
Malformed UTF-8 at line 1 col 1
```

- Software does not have to know list of Unicode characters to find their boundaries. It is very easy to add basic UTF-8 support and multi byte character concept to very old programs by doing simple byte math.

![Cobol](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dvat6vsnhfqaamilpffs.png)

- Programs does not have to support latest Unicode version. They can find start/end of an unknown character and display some replacement glyph without messing up the rest of text.

**Coming up next:** [Fun with printing sound](https://dev.to/bbkr/fun-with-utf-printing-sound-ccl) (optional). [Codepoints](https://dev.to/bbkr/utf-8-code-points-u1234-meaning-e1i), what does U+0105 mean?
UTF variable length to the rescue
Tags: unicode, utf
Published: 2023-07-27 13:36:27

In previous post of this series I explained how extending base 7 bit ASCII led to encodings chaos of biblical proportions. The issue was in the method used - everyone were trying to jam non-ASCII characters into free space of a single byte, causing conflicts and compatibility issues.

UTF people took a different approach - to store all characters\* in a <u>single</u> encoding and dynamically extend its available space by using multiple bytes to store some less common characters.
_[\*] They are actually codepoints, but that will be explained later, let's call them characters for now._

**Note:** They were not the first to have this idea. CJK for Chinese and Shift-JIS for Japanese were hacking around single byte limitation of necessity, because even whole single byte could not fit those alphabets. If you like clever algorithms read about [Shift-JIS](https://en.wikipedia.org/wiki/Shift_JIS), it is mind blowing. Also [UCS](https://en.wikipedia.org/wiki/Universal_Coded_Character_Set) can be considered the real technical predecessor of UTF.

Back to **UTF - it comes in 3 variants**:
- **UTF-8** stores character using 1, 2, 3 or 4 bytes.
- **UTF-16** stores character using 2 or 4 bytes (this is common misconception that "16" means 16 bits / 2 bytes only).
- **UTF-32** stores character using 4 bytes.

So theoretical maximum capacity for characters is `2^32=4_294_967_296`. Real capacity is way lower because many bytes are used for namespace organization purposes. For example for UTF-8 it is `1_112_064`, but it still can be considered "unlimited" when compared to `128` capacity of 7 bit ASCII or `256` capacity of various encodings mentioned in previous post.

**UTF-16 and UTF-32**

Before I focus on UTF-8 I'd like to briefly talk about those two. UTF-16 was an abomination and never got popular. Main issue was weird characters organization, lack of backward compatibility with 7 bit ASCII and `0x00` (null bytes) used. Null bytes terminate strings in C language and it required extra care with memory management when reading this encoding. Here is rare picture of an unaware C programmer who read his first UTF-16 string ;)

![C 0x00](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m0ingc9ed4l7jbh7yqls.png)

UTF-32 has the same flaws and on top of that it seems like a huge waste of space - you need 4 times more bytes to store simple `a` than in ASCII. However sometimes having predictable, fixed characters-to-bytes ratio is so beneficial that it outweighs additional space cost. For example if you need to access 128th character in a string it starts at `127*4+1`th byte in memory (assuming using composed form, which will be explained later).

**Coming up next:** Genius [design of UTF-8](https://dev.to/bbkr/utf-8-internal-design-5c8b).
Building Next-Gen Apps: Best Frameworks for 2023
Tags: mobileappdevelopment, frameworks, mobileappframeworks, appdevelopment
Published: 2023-07-27 13:32:43

Selecting the right mobile app framework sets the foundation for a successful development process. Factors to consider include platform compatibility, development language, community support, and scalability.

Features and Benefits of the Top 10 Mobile App Frameworks

React Native: A popular framework for building cross-platform mobile apps using JavaScript and 

React. Instagram utilized React Native to build the IGTV app

Flutter: Developed by Google, Flutter allows you to create high-performance, visually appealing apps for both Android and iOS using a single codebase. Google developed its Ads app using Flutter

Xamarin: Xamarin enables the development of native apps for iOS, Android, and Windows platforms, utilizing the power of .NET and C#. Storyo, a popular social media app for creating collaborative photo albums, used Xamarin to develop its app.

Ionic: A framework that leverages web technologies like HTML, CSS, and JavaScript to build hybrid mobile apps compatible with multiple platforms. Ionic has over 5 million apps built using its framework.

NativeScript: With NativeScript, you can build native mobile apps using JavaScript, TypeScript, or Angular, offering direct access to native APIs and UI components. NativeScript has been used to build Strudel.

PhoneGap: PhoneGap (also known as Apache Cordova) allows developers to build mobile apps using web technologies and wrap them in a native container for deployment. PhoneGap has been used to develop Wikipedia.

Kotlin Multiplatform Mobile (KMM): Developed by JetBrains, KMM allows you to share code between Android and iOS platforms, making cross-platform development more efficient. Slack has been built using KMM.

jQuery Mobile: Ideal for creating mobile-friendly web applications, jQuery Mobile provides a touch-optimized framework that works across various platforms. Hulu, the streaming app has been built using this.

Swift: Although primarily associated with iOS app development, Swift can also be used to create robust, native apps for macOS, watchOS, and tvOS. Swift has been used to build Airbnb.

Unity: While commonly used for game development, Unity can also be utilized to build interactive and visually stunning mobile apps with 2D or 3D graphics. Unity is commonly used for game development, but it has also been used to build interactive apps like Pokémon GO.

As mobile app development continues to soar in 2023, selecting the right mobile app framework becomes paramount. These frameworks are among the top choices, each offering unique features and benefits. Businesses can empower their development efforts and deliver exceptional mobile applications in this competitive landscape by considering performance, backend integration, UI/UX design, and partnering with a reputable [mobile app development company](https://www.rootquotient.com/).

Get More Insight at [Top Mobile App Frameworks of 2023](https://www.rootquotient.com/blog/top-mobile-app-frameworks-2023/)
Dominate Online Research: Game-Changing Queries!
Tags: beginners, productivity, ai, learning
Published: 2023-07-27 13:30:00

**[CensysGPT](https://www.aiforme.wiki/ai/tools/CensysGPT) Beta is an advanced tool that simplifies the process of building queries and enhances users' capabilities in conducting efficient and effective reconnaissance operations. **

With CensysGPT, users gain valuable insights into hosts on the internet, streamlining the entire process and enabling more proactive threat hunting and exposure management. The tool is continuously evolving, and user feedback is actively encouraged to improve its functionality further.

## Key Features of CensysGPT Beta:

**Efficient Query Building:**
CensysGPT Beta makes query building a breeze, empowering users with powerful queries that provide valuable information about hosts on the internet. Its user-friendly interface streamlines the process for more productive reconnaissance.

**Proactive Threat Hunting:**
By providing quick and easy insights into internet hosts, CensysGPT Beta enables users to proactively hunt for potential threats and vulnerabilities. This proactive approach strengthens security measures and helps prevent potential cyberattacks.

**Exposure Management:**
CensysGPT Beta facilitates exposure management by allowing users to identify and assess potential points of vulnerability. With this information, organizations can take proactive steps to mitigate risks and enhance their overall security posture.

**Continuous Improvement:**
The CensysGPT team is dedicated to improving the tool continually. User feedback is highly valued, and suggestions for enhancement are actively welcomed to refine and expand the tool's capabilities.

**Conclusion:**
CensysGPT Beta is a cutting-edge tool that simplifies and enhances internet reconnaissance operations. By offering efficient query building and empowering users with valuable insights, the tool enables proactive threat hunting and exposure management.

Embrace [CensysGPT](https://www.aiforme.wiki/ai/tools/CensysGPT) Beta to bolster your cybersecurity efforts, stay ahead of potential threats, and strengthen your organization's overall resilience. Your feedback is crucial in shaping the future of CensysGPT, as it strives to become an indispensable asset for cybersecurity professionals and organizations worldwide.
Day 13: Guess it
Tags: 100daysofcode, javascript, day13
Published: 2023-07-27 13:30:00

Today we will see the output based question 

## 1. Closure 

```javascript
function outer() {
  var x = 10;

  function inner() {
    console.log(x);
  }

  x = 20;
  return inner;
}

var closureFunc = outer();
closureFunc(); // output ?
```

## 2. This

```javascript
const obj = {
  count: 0,
  increment() {
    this.count++;
  },
};

const increment = obj.increment;
increment();
console.log(obj.count); // output ?

```

## 3. Arrow Function and this

```javascript
const obj = {
  name: 'Alice',
  age: 30,
  sayHello: function() {
    setTimeout(() => {
      console.log(`Hello, I'm ${this.name} and I'm ${this.age} years old.`);
    }, 1000);
  },
};

obj.sayHello(); // output ?
```

## 4. Fn Borrow
```javascript
const obj = {
  count: 0,
  increment() {
    this.count++;
  },
};

const increment = obj.increment.bind(obj);
increment();
console.log(obj.count);
```

Write the answer in the comments
Filter() method in JavaScript ?
Tags: filter, javascript, tutorial, opensource
Published: 2023-07-27 13:29:47

Filter() is a method in JavaScript that can effortlessly provide filtered output data(in the form of array) by processing an array

Here's the syntax of the `filter()` method:
```js
array.filter(function(currentValue, index, arr), thisArg)
```

In this syntax:

Parameters:

**function(currentValue, index, arr):** Required. A function to test each item in the array. The function should return `true` for the items that meet the specified condition, and `false` otherwise.
- **currentValue:** The current element being processed in the array.
- **index: Optional.** The index of the current element being processed in the array.
- **arr: Optional.** The array on which `filter()` was called.
- **thisArg:** Optional. An object to which the `this` keyword can refer in the `callback` function. If `this` parameter is empty, the this keyword is undefined in the `callback` function.

Here is a basic usage example:

```javascript

const array = [1, 2, 3, 4, 5, 6];

const filteredArray = array.filter(element => element > 3);

console.log(filteredArray); // Output: [4, 5, 6]
```
In this case, the test function checks whether each element in array is greater than 3. The filter() method returns a new array `filteredArray` containing only the elements that passed this test.

Thank you for reading. I encourage you to follow me on Twitter where I regularly share content about JavaScript and React, as well as contribute to open-source projects. I am currently seeking a remote job or internship.

Twitter: https://twitter.com/Diwakar_766

GitHub: https://github.com/DIWAKARKASHYAP

Portfolio: https://diwakar-portfolio.vercel.app/
How Quantum Computing Will Save Our Planet from Climate Change: Quantum Superpowers to the Rescue
Tags: news, motivation, ai
Published: 2023-07-27 13:29:39

Buckle up, because today we’re delving into the thrilling world of quantum computing and how it may just save our beautiful planet from the clutches of climate change. As a newcomer in this realm, I feel a tremendous burst of excitement and determination to make a positive impact on Earth’s future. Our future.

### A Critical Revelation

Have you ever looked at our world and thought, “Blimey, we really messed up!” The human species, with all our brilliance and bungles, played a significant role in putting our planet on the edge of an environmental cliff. Now it’s time for us to take responsibility for the mess we’ve made.

Cue the dramatic entrance of quantum computing, wearing its superhero cape. This cutting-edge technology may just be the ray of hope we need to tackle the looming climate crisis.

### A Quantum-Powered Tomorrow

With quantum computing’s immense processing power, we can unleash its potential to simulate climate models with unprecedented precision. By understanding the intricacies of nature’s systems, we can forecast extreme weather events, rising sea levels, and the effects of climate change.

But wait, there’s more! Quantum computing is not content with just simulations. It’s a game changer. Quantum algorithms can help us make better use of solar, wind, and other clean energy sources, making them more efficient and affordable for everyone. Picture a world where fossil fuels take a backseat, and renewable energy zooms ahead.

> "The greatest threat to our planet is the belief that someone else will save it." - Robert Swam. 

Imagine a future where quantum-powered climate simulations not only help us predict extreme weather events but also guide us in making well-informed decisions to protect ecosystems. Envision a world where clean, renewable energy is not a distant dream but a vibrant reality, accessible to all, and nurturing a greener, more sustainable Earth.

### The Future is in Our Hands

As we bid farewell to the notion of “someone else will fix it,” we embrace a new narrative of hope and action. Each one of us has the capacity to contribute to this critical mission. Whether you’re a quantum expert or an environmental activist, you have a role to play in shaping a greener, brighter future.

The future is in our hands, and together, we can make it a greener, safer, and more promising place for all.