teleren/devto huggingface dataset:
Laravel JsonResource class and toArray method.
Published: 2024-04-10 17:06:46

In Laravel, a JsonResource is part of Laravel's Eloquent API Resources that allows you to transform your Eloquent models (and model collections) into JSON format easily and consistently across your application. It provides a convenient way to control the exact structure of the JSON data you want to return for an API response. 

###toArray method

In Laravel's JsonResource, the toArray method plays a critical role by defining how the resource should be converted to an array, which is then automatically converted to JSON when the resource is returned from a route or controller. 

**Check this code**

```
public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            "images" => json_decode($this->images),
        ];
    }
```

Here this is the response of a model called Post. "posts" table has "images" column which stores json data


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

But PHP does not aware about json. It is just a string for PHP. So if we do like this,

```
return [
            'id' => $this->id,
            'name' => $this->name,
            "images" => $this->images,
        ];
```
 
What they return in response will be a string.


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

But if we do like this, And **json_decode ** the field


```
return [
            'id' => $this->id,
            'name' => $this->name,
            "images" => json_decode($this->images),
        ];
```

**json_decode will convert "$this->images" to a PHP array**. And toArray method is all about converting PHP arrays to JSON arrays, and this will convert into an array,


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

See now it is already JSON array. Not a string. So you can use it straightaway inside loop from frontend without parsing.

##Additional things

###Json objects an arrays

In JSON (JavaScript Object Notation), {} and [] represent two fundamental data structures

`{}` denotes an object


```
{
  "name": "John Doe",
  "age": 30,
  "isStudent": false
}
```

`[]` denotes an array


```
["apple", "banana", "cherry"]
```

Arrays can also contain objects


```
[
  {"name": "John Doe", "age": 30},
  {"name": "Jane Doe", "age": 25}
]
```

###Convert string to json

```
"images": "["https://via.placeholder.com/640x480.png/0011bb?text=doloribus", "https://via.placeholder.com/640x480.png/00aa55?text=ab"]",
```

This is a string that represents a JSON array of image URLs.

```
let imagesArray = JSON.parse(imagesString);
```

This will convert it to json array and you can loop through that array.
Learning AWS Day by Day — Day 33 — CloudWatch Part 2
Tags: aws, cloud, cloudcomputing, beginners
Published: 2024-04-10 17:01:26

Exploring AWS !!

Day 33:

Amazon CloudWatch — Part 2


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


CloudWatch: monitors service for AWS cloud resources and applications you run on AWS, we can collect and track metrics.

Two types of monitoring: Basic and Detailed

Basic: free, polls every 5 minutes, 10 metrics, 5 GB of data ingestion, 5 GB of data storage.
Detailed: chargeable, charged per instance per month, polls every minute.
Allows you to record metrics for EC2, EBS, ELB and S3. We can add these metrics to dashboard.

Events: can create events based on CloudWatch monitoring, example trigger lambda function.
Example: Amazon CloudWatch → Lambda → Archive
If EBS fills up then lambda should be triggered and data must be archived.

Logs: install agents on EC2 instances to send monitoring data about instances to Cloudwatch.

Alarms: set alarms to warn based on resource usage, for example, CPU Utilization is too high, we can also autoscale and shut down idle instances.
GTK4 `dotnet new` Project Template
Tags: dotnet, gtk4
Published: 2024-04-10 17:00:00

I have been writing some samples using GTK4 using `GirCore` so its time to reduce the manual project setup steps and turn it into a `dotnet new` project template.  

# Project Template
Time to follow the excellent [article](https://devblogs.microsoft.com/dotnet/how-to-create-your-own-templates-for-dotnet-new/) by Syed Ibrahim.

I have taken out the project setup section from my GTK 4 tutorials and turned it into the template. I have created a console application, added `GirCore.Gtk-4.0` nuget package to the project and updated the `Program.cs` to create a main Gtk window with `Hello World` label.  

Next tutorial for GTK4 hopefully I will use this template to bootstrap the project. And I will keep it updated with new releases of `GirCore`.  

## Usage
1. Clone repository locally  
2. Build nuget package  
`dotnet pack -o .`  
3. Install template for `dotnet new` using following command  
`dotnet new install Gtk4.Templates.1.0.0.nupkg`  
4. Create new project using template  
`dotnet new gtk4-app --param:name [ProjectName]`  
OR  
`dotnet new gtk4-app -p:n [ProjectName]`  
5. Uninstall template using following command  
`dotnet new uninstall Gtk4.Templates`  

## Source
Source code for the template is available on GitHub in [gtk4-dotnet-template](https://github.com/kashif-code-samples/gtk4-dotnet-template) repository.  

## References & Resources
* [dotnet new](https://docs.microsoft.com/en-us/dotnet/core/tools/dotnet-new)  
* [dotnet-template-samples](https://github.com/dotnet/dotnet-template-samples)  
* [How to create your own templates for dotnet new](https://devblogs.microsoft.com/dotnet/how-to-create-your-own-templates-for-dotnet-new/)  
* [templating](https://github.com/dotnet/templating)  
* [Gir.Core](https://github.com/gircore/gir.core)
Free AI Chat and AI Art
Tags: ai, gpt3, claude, realistic
Published: 2024-04-10 16:48:40

RsnChat offers US free ai chat. gpt, openchat, gemini, llama, claude3, mixtral, codellama And image generation is also provided

[RsnChat npm package](https://npmjs.com/rsnchat)

![Realistic Model](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g3zq4d11v65voymw2jni.png)


![Photography model](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9wvs6v97pbbr1kjmdmzn.png)


![Disney Model](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wpw1hfrpbdzpv0lhinig.png)


![Anime Model](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r2muw7a44dazwosyddrn.png)
Turso + PHP - The LibSQL Client for PHP
Tags: devjournal, php, libsql, turso
Published: 2024-04-10 16:47:49

Hello, Punk! Here I am again. I'm not exactly sure what's happening to me this year. Sometimes, I feel strange and happy at the same time.

I've dedicated my life to building something that seemed useless until people understood what I was doing, starting in 2014. My activities, which include hiking, coding, dancing, and hacking, make me happy. I live as a seemingly foolish yet attractive person in a world that shone in the past and was born into a modern, mature world of overwhelming information, until it becomes misinformation.

By the way, this holiday (Eid Al-Fitr in Indonesia), I received a DM from **[Glauber Costa](https://twitter.com/glcst)**, Founder/CEO at [**Turso**](https://turso.tech/). He asked me to add more features and maintain my **[TursoHTTP](https://github.com/darkterminal/turso-http)** and **[TursoSyncd](https://github.com/darkterminal/turso-syncd)**, which I created just for fun amidst the chaotic election in Indonesia 3 months ago.

But I decided to create another one from scratch (not entirely), at least following the SDK Specs, and here is [libsql-client-php](https://github.com/darkterminal/libsql-client-php) it's still work in progress.

I've made 35% progress in my development environment, but I'm still conducting research and trying to identify some issues regarding synchronization and embedded replicas in the general usage of Turso by Discord users.

If anyone here is using Turso, please let me know in the comments and share your experience, including what you feel is missing from the SDK.
Variables,Nomlash qoidalari
Published: 2024-04-10 16:38:03

Kompilyatsiya vaqtida vaqtinchalik ma'lumotlarni saqlab turuvchi xotira **Variables(o'zgaruvchilar)** deb ataladi.Bular qanday ma'lumot saqlashiga qarab,har xil **data type**larda saqlanadi.Masalan butun sonlarni saqlash uchun `int`tipidan foydalaniladi.
O'zgaruvchini shunchaki e'lon qilish- **variable declaration** deyiladi:`int son;`
Qiymat o'zlashtirish - **assignment**:`son=10;`
Ham e'lon qilib ham qiymat berish jarayoni - **initialization**:`int son=10;`
Bir xil tipdagi bir necha o'zgaruvchini bir vaqtda e'lon qilish mumkin --> `int a,b,c;`

## Nomlash qoidalari

1. Nomda alifbo harflari,raqamlar va underscore(_)ishlatish mumkin
2.Nomning birinchi belgisi raqam bo'la olmaydi
3.Nomda maxsus belgilar bo'lishi mumkin emas
4.Maxsus kalit so'zlardan nom sifatida foydalanish mumkin emas

##Casing rules
1.Local o'zgaruvchilar **camelCase** orqali yoziladi:`int kattaSon=123;`
2.Propertylar,class nomlari,method nomlari **PascalCase** orqali yoziladi:

```
public class Student
{
   public string FullName {}

}
```
3.Constant qiymatga ega o'zgaruvchilar **UPPERCASE** orqali yoziladi:`const PI=3.14;`
Create a MacOS desktop application with pure Ruby (Tutorial)
Tags: ruby, application, macos, native
Published: 2024-04-10 16:25:07

This is (for now) a modest step-by-step tutorial about creating a MacOS desktop application with Ruby.
I used [Traveling Ruby](https://github.com/YOU54F/traveling-ruby) and [Platypus](https://github.com/sveinbjornt/Platypus/releases), so it doesn't need any system dependencies to run because it downloads Ruby executables and installs gems in the application bundle.
(I'll try to make it more detailed and add more features in the future).

`Tested on Apple M3`

## 1
You have your Ruby application inside a `example` folder
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cpjkj7fiidurrhhqhi23.png)

## 2
Create a `ruby2pack.rb` file outside `example`
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ve71b8n9ram9adm27vs9.png)
and fill it with this gist https://gist.github.com/josephschito/96c0e385cb803f3778fb4c40226e64f5

## 3
From IRB require that file with `require ./ruby2pack` and run `Ruby2Pack.new(source_path: 'example', ruby_version: '3.3.0', platform: 'osx-arm64', rel: '20240215').run`.
Test your application execution by running `./dist/osx-arm64-3.3.0-20240215/run`

## 4
Download Platypus from https://github.com/sveinbjornt/Platypus/releases
and run it

## 5

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


Follow the image instructions and then press [Create App]

## THE END
That's it! 🎉

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d6tcfuhhtq810ks6etzs.gif)
Add to Cart Feature in React with Redux Toolkit
Published: 2024-04-10 16:14:24

Redux, a key part of managing state in React apps, can seem daunting at first. But there's a simpler way to approach it. In this blog, I'll share my journey of understanding Redux and using it in a straightforward manner. I'll show you how to easily add features like a shopping cart to your React app with Redux. Let's explore Redux together and make state management in React simpler.

## Setting Up Your Environment
Before diving into the code, make sure you have Node.js and npm (or yarn) installed on your machine. Create a new React application using Vite:

```
npm create vite@latest
```

## Next, install Redux Toolkit:

```
npm install @reduxjs/toolkit react-redux
```

## Creating the Redux Store
First, let's create a Redux store to manage our application state. Inside the src directory, create a new folder called "store" and inside it, create a file named "store.js":

```
import { configureStore } from "@reduxjs/toolkit";
import cartReducer from "./cartSlice";

export const store = configureStore({
  reducer: {
    reducer: cartReducer,
  },
});

export default store;

```

## Defining the Cart Slice
Now, let's define our cart slice, which includes the reducer and action creators. Create a new file named "cartSlice.js" in the "redux" folder:

```
import { createSlice } from "@reduxjs/toolkit";

const initialState = { itemList: [], totalQuantity: 0, showCart: false };

const cartSlice = createSlice({
  name: "cart",
  initialState,
  reducers: {
    addToCart(state, action) {
      const newItem = action.payload;
      const existingItem = state.itemList.find(
        (item) => item.id === newItem.id
      );
      if (existingItem) {
        existingItem.quantity++;
        existingItem.totalPrice = existingItem.price * existingItem.quantity;
      } else {
        state.itemList.push({
          name: action.payload.name,
          price: action.payload.price,
          totalPrice: action.payload.totalPrice,
          id: action.payload.id,
          quantity: 1,
        });
      }
    },
    removeFromCart(state, action) {
      const findItem = state.itemList.find(
        (item) => item.id === action.payload.id
      );
      if (findItem.quantity === 1) {
        state.itemList = state.itemList.filter(
          (item) => item.id != action.payload.id
        );
      } else {
        findItem.quantity--;
        findItem.totalPrice -= findItem.price;
      }
    },
    setShowCart(state) {
      state.showCart = !state.showCart;
    },
  },
});

export const { addToCart, removeFromCart, setShowCart } = cartSlice.actions;
export default cartSlice.reducer;

```
This completes the redux setup now data insertion and fetch can be done using useDispatch and useSelector respectively. 
Complete implementation of this is available in my Github:
https://github.com/Krishnan-Avinash/add-to-cart
Status Update: 2019-09-15
Tags: phalcon4, status, update
Published: 2019-11-01 21:13:32

---
title: Status Update: 2019-09-15
published: true
date: 2019-09-15 16:40:33 UTC
tags: phalcon4,status,update
canonical_url: 
---

Another update regarding Phalcon and v4, brought to you by the Phalcon Team :)

We are pushing hard to get v4 out as stable. Huge thank you to the community that have identified bugs with v4.beta.2. Most of those issues have been already resolved.

### Bitchute

We now have a channel on Bitchute. Feel free to go to our channel ([https://phalcon.link/bitchute](https://phalcon.link/bitchute)) and subscribe, if that is where you wish to follow us. We have set the channel to synchronize with YouTube so you can enjoy our content there too. Please note that our community hangouts (for now) will only occur in YouTube, since Bitchute does not offer this functionality yet.

### RC

This week coming we are going to release a Release Candidate version, so stay tuned!

### Sample Apps

[Vokuro](https://github.com/phalcon/vokuro), is nearly complete. We have ported the application fully to v4 but also enhanced it by adding migrations. sample environments (docker, nanobox), Travis CI and more. There are some minor things to address but we are done. Thanks goes to [@Jeckerson](https://github.com/jeckerson) for the effort.

Work has already started on migrating the [phalcon-api](https://github.com/phalcon/phalcon-api) to v4, our REST sample implementation.

### Documentation

We are continuing to review and revise all of our documents. The status of this effort can be seen [here](https://github.com/phalcon/docs/issues/2322). As you can see we have around 30 documents to review and revise.

We mentioned this before in blog posts as well as our community hangouts, some documents had to be completely rewritten because they have been missing functionality, clarifications or were simply wrong. Some documents had not been revised since version 2.

Well, we are addressing this right now and admittedly it is the only thing that is slowing us down from releasing v4 stable. However we do need to get all the documents up to speed so as to ensure that all developers have the most accurate information possible regarding Phalcon.

If you are interested in helping with this effort, reply to the issue above with the document you are going to work on and then issue a pull request to our [docs](https://github.com/phalcon/docs) repository for the English language (`en` folder).

If you have found any typos from the documents already revised, again feel free to issue a pull request with your corrections.

\<3 Phalcon Team
Streamline Your TypeScript Imports with TSImportRefiner
Published: 2024-04-10 16:02:25

Greetings fellow TypeScript enthusiasts! I'm excited to introduce TSImportRefiner, a tool designed to simplify and optimize TypeScript import statements.

TSImportRefiner is a script that automates the refactoring of TypeScript import statements. It efficiently organizes imports based on path aliases from tsconfig.json, enhancing code readability and maintenance.
<table>
  <tr>
    <td>
      <p align="center">Before Refactoring</p>
      <img src="https://github.com/AliRezaBeigy/TSImportRefiner/blob/master/assets/before.png?raw=true" alt="Before Refactoring" width="300"/>
    </td>
    <td>
      <p align="center">After Refactoring</p>
      <img src="https://github.com/AliRezaBeigy/TSImportRefiner/blob/master/assets/after.png?raw=true" alt="After Refactoring" width="300"/>
    </td>
  </tr>
</table>

**Key Features:**
- Alias Conversion: Automatically converts module paths to defined aliases.
- Sort Imports: Neatly organizes imports by line length.
- Easy Integration: Easily integrates with existing TypeScript projects with minimal setup required.

**Getting Started:**
Install via npm:
```sh
npm install -g tsimportrefiner
```
Usage is straightforward:
```sh
tsimportrefiner <path> [options]
```
where <path> can be a single file or a directory.

**Example Usage:**
An example command:
```sh
tsimportrefiner ./src --extensions=ts,tsx
```
which processes all .ts and .tsx files in the src directory.

**Contributing:**
Contributions are welcomed and appreciated. Whether it's feature development, bug fixes, or suggestions, your input helps improve TSImportRefiner.

TSImportRefiner is here to make your TypeScript experience smoother and more efficient. I'm looking forward to your feedback and contributions. Let's make TypeScript coding cleaner and more enjoyable together!

GitHub Repository: [TSImportRefiner](https://github.com/AliRezaBeigy/TSImportRefiner)
standard deviation
Published: 2024-04-10 16:01:11

Standart sapma, bir veri setindeki değerlerin ortalama etrafındaki dağılımın ölçüsüdür. Yani, bir veri setindeki değerlerin ortalama değere ne kadar yakın veya uzak olduğunu gösteren bir ölçüdür. Standart sapma, veri setinin varyansının karekökü olarak hesaplanır.

Standart sapmanın formülü şu şekildedir:


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


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






Standart sapma, veri setindeki değerlerin ne kadar homojen veya heterojen olduğunu belirlemek için kullanılır. Düşük bir standart sapma, veri setindeki değerlerin ortalama etrafında yoğunlaştığını ve homojen olduğunu gösterirken, yüksek bir standart sapma, veri setindeki değerlerin ortalama etrafında daha fazla yayıldığını ve heterojen olduğunu gösterir.

Özetle, standart sapma, veri setindeki değerlerin ortalama etrafındaki dağılımı hakkında bilgi sağlar ve veri setinin yayılma veya dağılımının ölçülmesinde önemli bir rol oynar.
Project structure
Published: 2024-04-10 15:57:42

Siz .NET loyiha yaratganingizda loyiha bir necha qismdan tashkil topganiga guvoh bo'lasiz.Shulardan biri .**csproj** fayldir.Bu faylni ichida .**NET SDK version,output type,ImplicityUsings** kabi ma'lumotlar bo'ladi.Agarda project fayl mavjud bo'lmasa,`dotnet run` komandasini tersak dasturimiz ishlamaydi.
Projectni ichida bizga kerakli yana bir fayl **Solution ya'ni .sln** fayl ham mavjud.Qachonki biz katta loyihada ishlayotganimizda,har bir loyiha o'zining alohida ._csproj_ fayliga ega bo'ladi.Solution faylni vazifasi o'sha fayllarni bir joyda saqlab,bir vaqtda run qilishdir.Agarda bu fayl bo'lmasa,loyihalar individual ravishda ishlaydi.`dotnet new sln`komandasi orqali yangi solution fayl yaratib olishimiz mumkin.Loyihani solution faylga qo'shish uchun `dotnet sln add` komandasini teramiz.
`dotnet build`komandasi solution fayl ichidagi barcha loyihalarni kompilatsiya qiladi
Day 10/366
Tags: 1percentplusplus, 100daysofcode
Published: 2024-04-10 15:36:05

🚀 **Today's Learning:**

🌟 DSA

- Insertion Sort
- Quick Sort

🌟 Dev

- Virtual DOM

🔍 **Some Key Highlights:**

DSA

**Insertion Sort**:
In insertion sort, we divide the array into two parts: sorted and unsorted. We start with the second element and compare it with the elements in the sorted part, moving elements to make space for the current element in the correct position. This process continues until the entire array is sorted. The outer loop 'i' runs from the second element to the last, and the inner loop 'j' helps in shifting elements. Average and worst-case time complexity: O(n^2), Best case: O(n) when the array is already sorted.

**Quicksort**:
Quicksort works by selecting a 'pivot' element from the array and partitioning the other elements into two sub-arrays according to whether they are less than or greater than the pivot. The process is then applied recursively to the sub-arrays. The pivot helps in dividing the array efficiently. The average and worst-case time complexity of quicksort is O(n log n), though in rare cases it can degrade to O(n^2) if the pivot selection is poor. However, it's generally very efficient for large datasets due to its divide-and-conquer approach.

DEV

DOM stands for Document Object Model. The DOM represents an HTML document with a logical tree structure. Each branch of the tree ends in a node, and each node contains objects.

React keeps a lightweight representation of the real DOM in the memory, and that is known as the virtual DOM. When the state of an object changes, virtual DOM changes only that object in the real DOM, rather than updating all the objects. 
React updates only those components that have changed, rather than updating all the components at once. This results in much faster web applications.

 #100daysofcode #1percentplusplus #coding #dsa