teleren/devto huggingface dataset:
Understanding Apollo Client Cache: How to Manage and Update Nested Data Structures Effectively
Tags: apollo, react, graphql
Published: 2024-05-22 05:39:34

Apollo Client’s cache is designed to handle normalized data, where each entity is stored separately and identified by unique keys. Understanding this normalization process and how identifiers work is key to managing and updating the cache effectively.

### **How Apollo Cache Works**

1. **Normalization**: Apollo Client normalizes the data by splitting the result into individual entities, each identified by a unique key. This key is usually a combination of the entity’s type (**`__typename`**) and its unique identifier (**`id`**).
2. **Entity Storage**: Each entity is stored in the cache separately. Relationships between entities are maintained using references. For example, in your case, **`cma_report`** would be stored with references to its **`lead`**, which in turn references **`property`**.

### **Example Query**

Consider your query:

```graphql
{
  cma_report {
    id
    lead {
      property {
        id
      }
    }
  }
}
```

When this query is executed, Apollo Client might normalize the data like this:

- **`cma_report:{id}`** -> {id, lead: **`lead:{id}`**}
- **`lead:{id}`** -> {property: **`property:{id}`**}
- **`property:{id}`** -> {id}

### **Updating the Cache**

When you perform a mutation, Apollo Client tries to update the cache based on the data returned from the mutation. If the mutation payload doesn't include enough information to match the normalized entities in the cache, it may fail to find the relevant entity.

For example, if your mutation looks like this:

```graphql
mutation {
  updateCmaReport(id: 1, lead: {property: {id: 2}}) {
    cma_report {
      id
      lead {
        property {
          id
        }
      }
    }
  }
}
```

### **Issue with Missing IDs**

If the mutation payload does not include the **`id`** for **`lead`**, Apollo Client cannot find the corresponding entity in the cache. In your case, the structure Apollo Client expects might look like this:

- **`cma_report:{id}`** -> {id, lead: **`lead:{id}`**}

If the mutation payload is missing the **`lead.id`**, it cannot match **`lead:{id}`**. Therefore, the cache update fails, and Apollo might fall back to refetching the entire parent query to ensure the cache is up-to-date.

### **Fixing the Issue**

By including the **`id`** for **`lead`** in the mutation response, you provide Apollo Client with the necessary information to find and update the correct entity in the cache. This aligns the mutation payload with the structure in the cache, allowing for a successful update.

### **Summary**

To ensure Apollo Client’s cache is updated correctly:

- Always include **`id`** fields for all nested entities in both queries and mutation responses.
- Understand the normalized structure and how entities are referenced in the cache.
- Ensure your mutation payloads match the expected structure in the cache.

By following these practices, you can leverage Apollo Client’s cache effectively and avoid unnecessary refetches.
What is Science, Computer Science, and Engineering?
Published: 2024-05-22 05:38:22

There's such a great conflict that people sometimes say that computer science is not even a science. Is that true? Then what's actually the difference between science and computer science?

Also, what actually is engineering?


Read more here: https://www.queryhub.info/thread/what-is-science-computer-science-and-engineering-63
KIU's Online Learning Platforms
Published: 2024-05-22 05:26:40

Are you considering furthering your education and looking for a reputable institution to study at? Look no further than KIU! With a focus on providing quality education and a conducive learning environment, KIU is the perfect place to pursue your academic dreams. Let's delve into what makes studying at KIU such a rewarding experience.

Why Choose KIU?
Academic Excellence: At KIU, we pride ourselves on our commitment to academic excellence. Our faculty members are experts in their respective fields, providing students with top-notch education and training.
State-of-the-Art Facilities: When you study at KIU, you have access to state-of-the-art facilities that enhance your learning experience. From modern classrooms to fully equipped laboratories, we have everything you need to succeed.
Diverse Course Offerings: Whether you're interested in business, science, technology, or healthcare, KIU offers a wide range of courses to choose from. You can tailor your education to fit your career goals and aspirations.
The KIU Experience
Studying at KIU is more than just attending classes; it's about immersing yourself in a vibrant community of learners and educators. Our campus is a melting pot of cultures, ideas, and perspectives, creating a dynamic and enriching environment for personal and academic growth.

What Sets KIU Apart?
Career Readiness: At KIU, we are dedicated to preparing our students for successful careers. Our career services team provides support with resume building, interview preparation, and job placement assistance.
Hands-On Learning: We believe in hands-on learning experiences that go beyond the classroom. Our students have the opportunity to participate in internships, research projects, and community service initiatives that complement their academic studies.
Global Perspectives: With a diverse student body and faculty from around the world, KIU offers a truly global education experience. You'll have the chance to interact with individuals from different backgrounds and cultures, broadening your perspective and fostering cross-cultural understanding.
How to Apply to KIU
Ready to take the next step in your academic journey? Applying to KIU is easy and straightforward. Simply visit our website and fill out the online application form. Our admissions team will guide you through the process and assist you with any questions you may have.

In Conclusion
Studying at KIU is a transformative experience that will set you on the path to success. With a focus on academic excellence, state-of-the-art facilities, and a vibrant learning community, KIU provides everything you need to achieve your educational and career goals. So why wait? Apply to KIU today and embark on your journey to a brighter future.
Dot Matrix Printer
Published: 2024-05-22 04:46:42

Dot Matrix Printer
Print with high security and accuracy with our dot matrix printers which are designed to print not just text but also creative project and much more. Save your time and money by switching to our dot matrix printers.
#dotmatrixprinters #printers #tvs #printing #easy-to-use #smartprinters
https://www.tvs-e.in/dot-matrix-printers/
Incremental progress feels futile...
Published: 2024-05-22 04:42:20

I spent a lot of my career building a git client - I was laser focused on enabling and accelerating incremental progress. But in the age of LLMs that approach feels inadequate. In this piece I tried to figure out why "business-as-usual" feels so broken right now, and also tried to work through my hangups getting fully on board with the new stuff.

https://dev.to/thecontextwindow/the-new-stuff-is-always-simple-5epk
rust trait
Published: 2024-05-22 04:10:54

you can regard trait as interface as ts.but it is more flexiable.

```
pub struct Animal {
   name:String
}
pub trait Action {
    fn say() ;
    fn getName -> String；
}
impl  Action for Animal {
     fn say(){

      },
    fn getName() ->String{

    } 
}
```
and you can set default implement for tait
such as 

```
pub trait Action {
   fn say(){

      },
    fn getName -> String；
}

impl  Action for Animal {
  
    fn getName() ->String{

    } 
}

```
seond powerful function 

```
pub trait Action<T,U> {
   fn say(){

      },
    fn getName -> String；
}

pub trait2 Action<T,U> {
   fn say(){

      },
    fn getName -> String；
}

fn main(ff:impl trait<String,String> + trait2<String,String> ) {

}

fn main<T:trait<String,String> + trait2<String,String>>(ff:T){

}

fn main<T,U>(ff:T)
where
   T:trait<String,String> + trait2<String,String>
{

}
```
the three methods are equal
React: Effective UI Practices
Tags: reactjsdevelopment, webdev, javascript
Published: 2024-05-22 03:25:34

As web development evolves, it is important to choose the right practices that help us create a scalable, readable, maintainable, and testable codebase. In this blog series, we will look at different practices that help us create such a codebase.

This blog series is divided into three topics:

1. Application Design
2. State Management
3. Testing Practices

## Application Design
Understanding how to convert business requirements into a React codebase with minimal effort is crucial. In today's blog, we will be exploring the following practices under Application Design:

- Extracting Design Components
- Building Application Logic as Custom Hooks
- Embracing Component Architecture

### Extracting Design Components
UI applications are nothing but a composition of design components such as buttons, tables, and accordions. These design components can be as granular as a button, icon, or form row, or as large as a table, accordion, or form. It is important to decouple these design components from business logic so that:

- We can reuse them across all places without redesigning them every time.
- Design changes can be applied in a single place and reflect everywhere.
- We can test the behaviour of these design components in an isolated environment since they are decoupled from business logic.

### Building Application Logic as Custom Hooks
React Hooks are not just another feature; they represent a paradigm shift in the React development journey. By embracing React Hooks, developers can focus more on building the application logic rather than grappling with React’s complexities. This shift orchestrates:

- Efficient code organisation, which helps improve the reusability and maintainability of behaviours.
- Easier testing.
- Improved overall application performance by avoiding unnecessary re-renders.

**Reference:** [Reusing Logic with Custom Hooks](https://react.dev/learn/reusing-logic-with-custom-hooks)

### Embracing Component Architecture
Component architecture is a fundamental concept in React development. Breaking our application into smaller components instead of having one bulk component is as important as extracting design components and behaviours. As the complexity of a component increases, it is a good idea to split it into separate components to make your code:

- More readable and maintainable.
- Easier to test.
- Loosely coupled with other behaviours and components.

**Reference:** [Break the UI into a component hierarchy](https://react.dev/learn/thinking-in-react#step-1-break-the-ui-into-a-component-hierarchy)

That is all for today. In our next blog, we will look at some of the best practices for managing and designing state in React.
rust Generics
Published: 2024-05-22 03:01:35

what is Generics？
the essence of Generics is assuming it to be certain type。
the true type is not know until excution

1. how to use generics in function？

```
fn <T,U>name(st:T):U{

}
```

2. how to use generics in stuct？

```
stuct A <T,U> {
  string:T
  age:U
}

impl <T,U> A <T,U> {
     fn say<T2>(&self,param:T2) -> T2 {

        return  param;
    }
} 


`3. how to use generics in enum？``

enum Result <T,U>{
   Ok(T),
   Err(U)
 
}
１３章25
Published: 2024-05-22 02:49:03

いいえ、`Main`クラスでは`Sample`クラスのインスタンスを作成して、その際にコンストラクタを呼び出して`value`フィールドを初期化しています。つまり、`Main`クラスで特別に`value`フィールドを初期化する必要はありません。すべてがコンストラクタで行われます。

以下がその例です：

```java
package ex25.a;

public class Sample {
    public String value; // フィールドの宣言
    public Sample(String value) { // コンストラクタで初期化
        this.value = value;
    }
}
```

```java
package ex25.b;
import ex25.a.Sample;

public class Main {
    public static void main(String[] args) {
        Sample s = new Sample("Hello Java"); // コンストラクタ呼び出し
        System.out.println(s.value); // 初期化されたvalueを出力
    }
}
```

`Main`クラスでは、次のステップを実行しています：

1. `Sample`クラスのインスタンスを作成する際に、コンストラクタ`Sample(String value)`を呼び出し、`"Hello Java"`という値を渡しています。
2. `Sample`クラスのコンストラクタは、この値を`value`フィールドに割り当てます。
3. `System.out.println(s.value);`で、初期化された`value`フィールドの値を出力します。

したがって、`Main`クラスで追加の初期化を行う必要はありません。このままで正しく動作し、`"Hello Java"`が出力されます。
Rust type Result
Published: 2024-05-22 02:48:16

1. 
type Result is enum

```
pub enum Result<T, E> {
    /// Contains the success value
    #[lang = "Ok"]
    #[stable(feature = "rust1", since = "1.0.0")]
    Ok(#[stable(feature = "rust1", since = "1.0.0")] T),

    /// Contains the error value
    #[lang = "Err"]
    #[stable(feature = "rust1", since = "1.0.0")]
    Err(#[stable(feature = "rust1", since = "1.0.0")] E),
};
```
let me create a function that returntype is Result

```
fn test(path:String)->Result<&str,&str> {
      if path == "d" {
            Ok("我是成功了")
       }else{
           Error("我失败了")
       }

}

match test {
    Ok(s) =>{

    },
    Error(x)=>{

    }
}
```
BATA4D : Bandar Togel Online & Toto Online paling Resmi dan Terpercaya Se-Asia
Tags: bata4d, slotgacor, bandartogel, situsslotgacor
Published: 2024-05-22 02:45:35

KLIK DI SINI UNTUK DAFTAR BATA4D


Judi slot online telah menjadi hiburan populer bagi banyak orang di Indonesia. Namun, dengan banyaknya agen judi slot online yang tersedia, memilih yang terbaik dapat menjadi tugas yang menantang. Salah satu agen terkemuka di pasar adalah Bata4d. Dalam artikel ini, kita akan membahas cara memilih Bata4d terbaik untuk pengalaman bermain yang lebih baik.

Keamanan dan Lisensi

Langkah pertama dalam memilih Bata4d adalah memastikan keamanan dan kepercayaan situs tersebut. Pastikan agen tersebut memiliki lisensi resmi dari badan pengatur perjudian yang diakui. Lisensi menunjukkan bahwa situs tersebut diatur dan dilindungi oleh otoritas yang relevan, sehingga memberikan jaminan keamanan bagi pemain.

Koleksi Permainan

Bata4d yang baik harus menawarkan berbagai pilihan permainan slot online. Pemain harus dapat menemukan game-game populer dari penyedia terkemuka seperti Pragmatic Play, Playtech, Microgaming, dan banyak lagi. Selain itu, variasi tema dan fitur bonus juga penting untuk meningkatkan pengalaman bermain.

Promosi dan Bonus

Promosi dan bonus adalah salah satu faktor yang membedakan antara bata4d yang baik dan yang tidak. Pilihlah agen yang menawarkan promosi menarik, seperti bonus deposit, cashback, dan putaran gratis. Namun, pastikan untuk membaca syarat dan ketentuan yang terkait dengan promosi tersebut untuk menghindari kekecewaan di kemudian hari.

Pelayanan Pelanggan

Pelayanan pelanggan yang responsif dan ramah juga merupakan hal yang penting dalam memilih Bata4d. Pastikan agen tersebut memiliki layanan pelanggan yang dapat diakses melalui berbagai saluran komunikasi, seperti percakapan langsung, email, atau telepon. Kemudahan dalam menghubungi dukungan pelanggan akan membantu memecahkan masalah dengan cepat jika diperlukan.




Ulasan dan Reputasi

Terakhir, jangan lupa untuk membaca ulasan dan melihat reputasi Bata4d sebelum mendaftar. Tinjauan dari pemain sebelumnya dapat memberikan wawasan berharga tentang kualitas layanan dan pengalaman bermain di agen tersebut.
How to Improve Team Development Efficiency with Effective Use of Pull Requests and Code Comments
Tags: github, webdev
Published: 2024-05-22 02:37:41

## Introduction
In programming, while it is ideal to convey information solely through source code, there are limitations. This is especially true in team development, where pull requests (PRs) and source code comments become essential. This article explains the appropriate use and differentiation of these tools.

## Importance of Pull Requests
PRs are a means to show code changes to the team and receive reviews. The main goal is to improve code quality.

### Readers of Pull Requests
There are primarily two types of readers for PRs:
- **Code Reviewers**: Those who review the PR
- **Code Modifiers**: Those who investigate the PR to understand the history of code changes

### Information to Include in a Pull Request
1. **Purpose of the Change**: Why the change was made
2. **Main Changes**: Overview of the modifications
3. **Scope**: Range of the modifications
4. **Testing**: Items tested and verification points
5. **Design/Implementation Considerations**: Background of technical decisions
6. **Related Issues**: Information on related tickets

Basically, include explanations that span multiple files or modifications, rather than what can be explained in code. If code explanations are necessary, it is preferable to write source code comments as mentioned later. However, if not suitable, supplement with inline review comments on the PR for easier understanding.

## Importance of Source Code Comments
Source code comments are written to explain the behavior and intent of the code. The goal is to enable the reader to efficiently use and modify the code.

### Readers of Source Code
There are also two types of readers for source code:
- **Code Users**: Those who want to know how to correctly use the code
- **Code Modifiers**: Those who modify the code to avoid bugs

### Information to Include in Source Code Comments
1. **Purpose of Functions and Classes**: What the function or class is for
2. **Usage of Functions and Classes**: Typical usage examples of classes or functions
3. **Explanation of Complex Processes**: Explanation of difficult-to-understand logic or algorithms
4. **Notes and TODOs**: Points to improve or be aware of in the future
5. **External Reference Resources**: URLs of referenced pages, etc.

Source code comments should pertain to specific files. Again, there is no need to rewrite what can be expressed in the code.

## Conclusion
PRs and source code comments play an important role in team development. By understanding and appropriately using each, we can achieve improved code quality and efficient communication.
Named export를 동적 import() 호출하기
Tags: webdev, javascript, react
Published: 2024-05-22 02:30:02

필자는 프로젝트를 진행하면서 page 컴포넌트를 `default export` 방식으로 컴포넌트를 내보내어 코드를 작성하였다.

```tsx
// Component default export
function MyPage () => { ... }
export default MyPage;

// Component import
import MyPage from './pages/MyPage';
```

페이지 컴포넌트에 `default export`로 굳어진 습관도 무시할 수 없지만, 페이지는 단 한개의 페이지 컴포넌트 뷰의 기능을 담당해야 하기 때문에 default로 작성하였다.

그러나 `default export` 의 단점으로 import 하는 과정에서 휴먼 에러가 발생할 수 있다는 단점과 import 코드 라인이 늘어나는 단점이 존재하기 때문에 이번에는 `named export`를 통해 컴포넌트를 export 하였다.

```tsx
// Component named export
export const MyPage= () => { ... }

// Component import
import { MyPage } from './pages';
```

`named export`로 변경 후 import 하는 과정에서 자동으로 컴포넌트 name을 선언해 주며, 여러 export된 컴포넌트 및 함수를 name으로 import 할 수 있는 장점이 생겼다.

&nbsp;

## React.lazy로 import

각 페이지 컴포넌트를 최적화 하기 위해 React.lazy 를 사용하여 동적으로 컴포넌트를 import 하였다.

> React v16.6.0의 외부 라이브러리 없이 코드 로드(load)를 연기할 수 있는 React.lazy를 도입하였다.
> [react.dev-lazy](https://react.dev/reference/react/lazy)

즉, React.lazy 함수는 동적 import를 통해 컴포넌트를 지연 로드하여 렌더링할 수 있게 해준다.

Before:
```tsx
import { MyPage } from './pages';

function AppComponent() {
  return (
    <div>
      <MyPage />
    </div>
  )
}
```
After:
```tsx
const MyPage = React.lazy(() => import('./pages/MyPage'));

function AppComponent() {
  return (
    <div>
      <MyPage />
    </div>
  )
}
```
그리고 바로 다음에서 문제가 발생, 아래에 다음과 같은 메시지가 있다.

```
React.lazy takes a function that must call a dynamic import(). 
This must return a Promise which resolves to a module with a default export containing a React component.
```
번역하면 이렇다.

> React.lazy는 동적 import()를 호출하는 함수를 받습니다. 이 함수는 React 컴포넌트를 포함하는 `default export` 모듈로 해석되는 Promise를 반환해야 합니다.

그래서 아래와 같이 변경하라고 한다.

```tsx
function MyPage () => { ... }
export default MyPage;
```

&nbsp;

## 해결방법

하지만 `default export`로 export 하지 않는다면 어떻게 해야 할까 고민 중에 ChatGPT를 통해 그 답을 얻을 수 있었으며 이 경우, 컴포넌트를 가져올 때 import() 코드를 약간 변경해야 한다.

```tsx
const MyPage = React.lazy(
  () => import('./pages/MyPage/index.tsx').then((module) => ({ default: module.MyPage }))
);
```

> 필자는 MyPage라는 폴더를 두고 그 안에 **index.tsx** 파일로 컴포넌트를 생성해 주었다. 그리고 중요한 점은 **확장자 명**을 반드시 붙여 주어야 한다.

정리하자면 import()가 반환하는 Promise에 체이닝을 추가하여 `default export`를 추가하는 작업을 하고 있는 것이다.

이렇게 React.lazy로 가져온 `named export`된 컴포넌트의 경우 위와 같은 형식으로 lazy 함수를 작성해 주어야 한다. 

그리고 기억해야 할 것으로 **React.lazy**로 가져온 컴포넌트는 반드시 **React.Suspense** 안에서 렌더링 되어야 한다는 점을 기억해야 한다.

최종적으로 변경된 전체 코드는 아래와 같다.

```tsx
const MyPage = React.lazy(
  () => import('./pages/MyPage/index.tsx').then((module) => ({ default: module.MyPage }))

function AppComponent() {
  return (
    <div>
      <Suspense fallback="loading..." />
        <MyPage />
      <Suspense/>
    </div>
  )
}
```
WordPress Error Log Not Showing with Laravel Herd
Tags: wordpress, laravel, development, debugging
Published: 2024-05-22 02:24:09

---
title: WordPress Error Log Not Showing with Laravel Herd
published: true
description: Learn how to resolve the issue of WordPress error logs not appearing when using Laravel Herd for local development.
tags: wordpress, laravel, development, debugging
# cover_image: 
# Use a ratio of 100:42 for best results.
# published_at: 2024-05-22 01:56 +0000
---

As a developer working with both WordPress and Laravel, I prefer to use the same development environment for efficiency. For local development, I always use Laravel Herd. However, I encountered an issue where the WordPress error log was not showing up in my development setup.

> After extensive debugging, I discovered that **Laravel Herd** logs errors to `/Users/{username}/Library/Application Support/Herd/Log/php-fpm.log`.

I attempted to set the path explicitly using `ini_set('error_log', WP_CONTENT_DIR . '/debug.log')`, but `ini_get('error_log')` consistently returned the Laravel Herd default path: `/Users/{username}/Library/Application Support/Herd/Log/php-fpm.log`. Interestingly, the error logging worked perfectly from the WP CLI shell but not through the browser.

To resolve this issue, I decided to create a symlink in `wp-config.php` as follows:

```
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', false);
define('SCRIPT_DEBUG', true);

// Target file or directory
$target = ini_get('error_log');

// Symlink path
$link =  __DIR__ .'/wp-content/debug.log';

if ( ! is_link( $link ) && file_exists( $link ) ) {
    unlink( $link );
}

// Check if the symlink already exists
if (! ( file_exists( $link ) || is_link( $link ) ) ) {
    symlink($target, $link);
}
```

**Alternative solution** https://stackoverflow.com/a/77102145.
Rust release
Published: 2024-05-22 02:23:20

setup cargo.toml

```
[profile.dev]
panic = 'abort'
```
as you called cargo run 
if your code happen panic!(); rust excutor dose not expand stack，Just exit main thread. let OS solve the error.
```
[profile.release]
panic = 'abort'
```
as you called cargo run  --release
if your code happen panic!(); rust excutor dose not expand stack，Just exit main thread. let OS solve the error.

--release mean product environment；the build time would be slow, but packaged file will small.
cmd and powershell
Published: 2024-05-22 01:50:36

in windows os
how to set cmd environment variable？

```
set fff = 1
```
how to set  environment variable in powershell?

```
$env:RUST_BACKTRACE = "1"
```
how to output all  environment variable into console in powershell?
```
gci Env:
```

how to output all  environment variable into console in cmd?
```
set
```

the mothods bellow just make environment variable live in one powershell or cmd ？ when you close it. they will be destroied。
Html, 숫자만 입력 가능하게 하기
Tags: html
Published: 2024-05-22 01:42:39

```
<input type='number'></input>
```

```
<input type='number' min='10' max='30' step='3'>
```

```
<input type="text" pattern="[0-9]+">
```
_참조: https://hianna.tistory.com/413_