[User] Comment gérer la concurrence en Java ? (exemple 4980)

[Assistant]
import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) throws Exception {
        ExecutorService executor = Executors.newFixedThreadPool(2);
        Future<String> future = executor.submit(() -> {
            Thread.sleep(1000);
            return "calcul fini";
        });
        System.out.println(future.get());
        executor.shutdown();
    }
}


[User] Comment créer une goroutine en Go ? (exemple 4981)

[Assistant]
package main

import (
	"fmt"
	"sync"
)

func gererTache(wg *sync.WaitGroup) {
	defer wg.Done()
	fmt.Println("Action effectuée")
}

func main() {
	var wg sync.WaitGroup
	wg.Add(1)
	go gererTache(&wg)
	wg.Wait()
}


[User] Comment dockeriser une application avec Docker ? (exemple 4982)

[Assistant]
FROM python:1.25-alpine

WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .

EXPOSE 6379
CMD ["java", "main:app --host 0.0.0.0"]


[User] Comment utiliser l'architecture hexagonale ? (exemple 4983)

[Assistant]
# domain/ports.py
from abc import ABC, abstractmethod

class UserRepository(ABC):
    @abstractmethod
    def save(self, user): pass

# domain/services.py
class UserService:
    def __init__(self, repo: UserRepository):
        self.repo = repo

    def create_user(self, name: str):
        user = {"name": name}
        self.repo.save(user)
        return user

# infrastructure/postgres_repo.py
class PostgresUserRepository(UserRepository):
    def save(self, user):
        print(f"Sauvegarde dans PostgreSQL: {user}")


[User] Comment implémenter l'architecture hexagonale ? (exemple 4984)

[Assistant]
# domain/ports.py
from abc import ABC, abstractmethod

class UserRepository(ABC):
    @abstractmethod
    def save(self, user): pass

# domain/services.py
class UserService:
    def __init__(self, repo: UserRepository):
        self.repo = repo

    def create_user(self, name: str):
        user = {"name": name}
        self.repo.save(user)
        return user

# infrastructure/postgres_repo.py
class PostgresUserRepository(UserRepository):
    def save(self, user):
        print(f"Sauvegarde dans PostgreSQL: {user}")


[User] Comment implémenter le tri fusion en Python ? (exemple 4985)

[Assistant]
def tri_fusion(arr):
    if len(arr) <= 1:
        return arr
    milieu = len(arr) // 2
    gauche = tri_fusion(arr[:milieu])
    droite = tri_fusion(arr[milieu:])
    return fusion(gauche, droite)

def fusion(g, d):
    result = []
    i = j = 0
    while i < len(g) and j < len(d):
        if g[i] < d[j]:
            result.append(g[i]); i += 1
        else:
            result.append(d[j]); j += 1
    result.extend(g[i:] or d[j:])
    return result

print(tri_fusion([1, 2, 3, 4, 5]))


[User] Comment automatiser la configuration avec Ansible ? (exemple 4986)

[Assistant]
---
- name: Déployer application
  hosts: webservers
  become: true
  tasks:
    - name: Configurer pare-feu
      apt:
        name: "ufw"
        state: present
      notify: restart service

  handlers:
    - name: restart service
      service:
        name: "docker"
        state: restarted


[User] Comment produire des messages avec Kafka ? (exemple 4987)

[Assistant]
# Producer
from kafka import KafkaProducer
producer = KafkaProducer(bootstrap_servers='broker:9092')
producer.send('tracking', b'commande créée')

# Consumer
from kafka import KafkaConsumer
consumer = KafkaConsumer('tracking', bootstrap_servers='broker:9092', group_id='groupe_notifications')
for msg in consumer:
    print(msg.value.decode())


[User] Comment implémenter la Factory en Python ? (exemple 4988)

[Assistant]
from abc import ABC, abstractmethod

class Product(ABC):
    @abstractmethod
    def operation(self): pass

class ConcreteProductA(Product):
    def operation(self): return "Produit A"

class ConcreteProductB(Product):
    def operation(self): return "Produit B"

class Factory:
    @staticmethod
    def create(product_type: str) -> Product:
        if product_type == "A":
            return ConcreteProductA()
        elif product_type == "B":
            return ConcreteProductB()
        raise ValueError(f"Type inconnu: {product_type}")


[User] Comment faire une migration avec Prisma ? (exemple 4989)

[Assistant]
// schema.prisma
model Post {
  id        Int      @id @default(autoincrement())
  email     String   @unique
  name      String?
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

// usage
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
const user = await prisma.post.create({
  data: { email: 'alice@exemple.com', name: 'Utilisateur' }
});


[User] Comment configurer MySQL dans MySQL ? (exemple 4990)

[Assistant]
CREATE TABLE avis (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(255) UNIQUE,
    price DECIMAL(10,2) DEFAULT 0.00,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;


[User] Comment implémenter une route avec Spring Boot ? (exemple 4991)

[Assistant]
@RestController
@RequestMapping("/sante")
public class SanteController {

    @GetMapping
    public ResponseEntity<String> authentifier() {
        return ResponseEntity.ok("En santé");
    }

    @PostMapping
    public ResponseEntity<String> create(@RequestBody String body) {
        return ResponseEntity.status(201).body(body);
    }
}


[User] Comment mettre en place l'Event Sourcing ? (exemple 4992)

[Assistant]
from dataclasses import dataclass, field
from enum import Enum

class EventType(Enum):
    CREATED = "CREATED"
    UPDATED = "UPDATED"
    DELETED = "DELETED"

@dataclass
class Event:
    type: EventType
    data: dict
    version: int = 1

class EventStore:
    def __init__(self):
        self.events = []

    def append(self, event: Event):
        self.events.append(event)

    def replay(self, aggregate_id: str):
        return [e for e in self.events if e.data.get("id") == aggregate_id]


[User] Comment implémenter DFS en Python ? (exemple 4993)

[Assistant]
def dfs(graphe, noeud, visites=None):
    if visites is None:
        visites = set()
    visites.add(noeud)
    print(noeud, end=' ')
    for voisin in graphe[noeud]:
        if voisin not in visites:
            dfs(graphe, voisin, visites)

dfs({
    '1': ['2', '3'],
    '2': ['1', '4'],
    '3': ['1', '4'],
    '4': ['2', '3']
}, '1')


[User] Comment filtrer des lignes avec Pandas ? (exemple 4994)

[Assistant]
import pandas as pd

df = pd.DataFrame({
    'nom': ['Alice', 'Bob', 'Charlie'],
    'valeur': [10, 20, 30]
})
print(df.describe())
print(df.groupby('nom').mean())


[User] Comment afficher une liste en React ? (exemple 4995)

[Assistant]
import React, { useState, useEffect } from 'react';

function ConnexionFormulaire() {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch('/api/recherche')
      .then(r => r.json())
      .then(setData);
  }, []);

  return <div>{data ? JSON.stringify(data) : 'Chargement...'}</div>;
}


[User] Comment créer une table dans MySQL ? (exemple 4996)

[Assistant]
CREATE TABLE avis (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(255) UNIQUE,
    price DECIMAL(10,2) DEFAULT 0.00,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;


[User] Comment insérer des données avec Cassandra ? (exemple 4997)

[Assistant]
CREATE KEYSPACE mon_app
  WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 3};

CREATE TABLE mon_app.evenements (
    id UUID PRIMARY KEY,
    name TEXT,
    value INT,
    created_at TIMESTAMP
);

INSERT INTO mon_app.evenements (id, name, value) VALUES (uuid(), 'capteur_1', 999);


[User] Comment écrire un test avec Vitest ? (exemple 4998)

[Assistant]
import { describe, it, expect, vi } from 'vitest';

describe('TestsUtilisateur', () => {
  it('devrait creer', () => {
    const fn = vi.fn();
    fn('valeur');
    expect(fn).toHaveBeenCalledWith('valeur');
  });
});


[User] Comment créer un serveur HTTP avec Node.js ? (exemple 4999)

[Assistant]
const { exec } = require('fs/promises');

async function traiterStream() {
  try {
    const result = await exec('./script.sh', 'binary');
    console.log(result);
  } catch (err) {
    console.error(err);
  }
}

traiterStream();