Developer Blog

Tipps und Tricks für Entwickler und IT-Interessierte

Laravel | Erstellen einer Starter-App

Inhaltsverzeichnis

TL;DR

Der Code für die in diesem Post erstelle Anwendung liegt hier.

Installation

Erstellen der Starter App

laravel new Laravel-Starter-App --jet --stack=livewire --api --teams --dark --pest --verification --database sqlite --git --quiet

Konfiguration der Datenbank

Die Konfiguration der Datenbank erfolgt in der bereits vorhandenen Datei .env.

Nach der Installation finden Sie dort die folgenden Einträge für eine MySQL Datenbankanbindung:

Datenbank SQLite verwenden

Bei Einrichten der Starter App wurde bereits SQLite vorselektiert:

DB_CONNECTION=sqlite

Leere Datenbankdatei erstellen

Die Starter App hat bereits eine leeren Datenbank im Ordner database mit dem Namen database.sqlite

Tabellen erstellen

Die für Laravel notwendigen Tabellen wurden ebenfalls eingerichtet:

php artisan migrate
Migration der Tabellen durchführen

Hinweis: Die vorhandenen Tabellen können Sie sie über die Kommandozeile anzeigen:

sqlite3.exe .\database\database.sqlite ".tables"
Vorhandene Tabellen in der Datenbank

Installation und Konfiguration des Frontend

Um mit dem Frontend arbeiten zu können, müssen zu ersten die notwendigen Komponenten installiert und das Frontend erstellt werden:

npm install
npm run dev

Anzeigen der Anwendung

Die grundlegende Installation und Konfiguration ist abgeschlossen. Starten Sie die Anwendung durch das nachfolgende Kommando:

php artisan serve
Lokalen Webserver starten

Öffnen Sie die Anwendung im Browser über den Link http://127.0.0.1:8000

Anmeldung und Authentifizierung

Die erstelle Laravel-Anwendung enthält bereits die Funktionalität, das sich Benutzer Registrieren und Anmelden können. Hierzu finden Sie auf der Startseite rechts oben entsprechende Links.

Mit den verwendeten Standardeinstellungen sin Ausreichend für das Einrichten neuen Benutzer.

Um eine höhere Sicherheit zu erreichen, werden diese Einstellungen so geändert, das einen Bestätigungsmail an den Benutzer gesendet wird. Erst durch den Klick auf den darin enthaltenen Bestätigungslink wird die Einrichtung des Benutzers abgeschlossen.

E-Mail Verification einrichten

Das Einrichten dieser E-Mail Verification erfolgt in mehreren Schritten.

Hinweis: Diese wurden ebenfalls durch die Starter App durchführt.

Aktivieren des Features emailVerification in der Datei config/fortify.php

Einrichtern der E-Mail-Verifizierung bei der Registrierung

Passen sie die Datei app/User.php an:

use Illuminate\Contracts\Auth\MustVerifyEmail;
class User extends Authenticatable implements MustVerifyEmail
Einrichten der emailVerification

Festlegen der E-Mail Konfiguration

Damit Laravel eine E-Mail versenden kann wird der Zugang zu einem E-Mail Server verwendet. Hier benötigen wir die Zugangsdaten für den SMTP-Versand.

Für das Empfangen der Verifizierungsmail gibt es zwei Möglichkeiten:

  • die Verifizierungsmail wird im Laravel-Log gespeichert
  • die Verifizierungsmail wird an einen SMPT-Server gesenden
    • sie können hier ihren eigenen SMTP-Server verwenden
    • oder sie verwenden mailpit (Lokaler SMTP-Server für Tests)

Festgelegt werden diese Parameter wieder in der Datei .env:

Die entsprechenden Werte hängen vom verwendeten Mailserver ab.

Laravel Log verwenden

Der Eintrag in der Datei .env lautet dann:

MAIL_MAILER=log

Die Verifizierungsmail finden sie dann in der Datei storage/logs/laravel.log:

Eigener SMTP-Server

Der Eintrag in der Datei .env lautet dann:

MAIL_MAILER=smtp

Zuerst müssen Sie bei ihrem Provider ein Mailkonto einrichten (Benutzer und Passwort). Testen Sie am besten diese Daten über den von ihrem Provider bereitgestellten Webmailer.

Die weiteren Werte (Port, Protokoll) entnehmen Sie der Dokumentation ihres Providers.

Nachfolgend zwei Beispiele:

ProviderStratoUnited Domains
MAIL_MAILERsmtpsmtp
MAIL_HOSTsmtp.strato.desmtps.udag.de
MAIL_PORT587587
MAIL_ENCRYPTIONtlstls
Beispiele für die E-Mail-Konfiguration

Lokaler SMTP-Server für Testzwecke: mailpit

Für Testzwecke können sie die E-Mail-Konfiguration auch vereinfachen, indem ein lokaler Mailserver verwendet wird: mailpit (https://mailpit.axllent.org/docs/install/)

Installieren sie diesen und starten sie ihn dann mit den Parametern aus der Laravel-Konfiguration: dem SMTP-Port aus der Datei .env. Passen sie zusätzlich den Parameter MAIL_MAILER an:

MAIL_MAILER=smtp
❯ mailpit -s 0.0.0.0:2525
INFO[2024/04/09 18:42:33] [smtpd] starting on 0.0.0.0:2525 (no encryption)
INFO[2024/04/09 18:42:33] [http] starting on [::]:8025
INFO[2024/04/09 18:42:33] [http] accessible via http://localhost:8025/

mailpit Frontend öffnen

Klicken sie auf den angegeben Link der Ausgabe von mailpit, um das Frontend zu starten:

http://localhost:8025/

Benutzer einrichten

Starten Sie die Anwendung neu und richten Sie einen weiteren Benutzer ein

php artisan serve
Lokalen Webserver starten

Registrierung durchführen

Starten Sie die Registrierung über den Link Register auf der Startseite.

Geben Sie die notwendigen Benutzerdaten ein. Bestätigen Sie ebenfalls die Terms of Services, falls diese aktiviert sind. Wie sie diese aktivieren können sie hier nachlese.

Bei erfolgreichen Versand der Bestätigungsmail erscheint diese Anzeige. Sie erhalten ebenfalls eine Bestätigungsmail an die verwendete E-Mail-Adresse.

Öffnen Sie die E-Mail und klicken Sie auf den Bestätigungslink. Achten Sie darauf, das der Link im gleichen Browser geöffnet wird, mit dem Sie die Registrierung durchgeführt haben.

Alternativ kopieren Sie einfach den Link, wechseln wieder zurück in das Registrierungsfenster und fügen den kopierten Link ein.

Wenn sie mit mailpit arbeiten, so sehen sie im Frontend, das eine neue E-Mail eingegangen ist:

Danach befinden Sie sich auf dem Dashboard der Anwendung. Die Registrierung hat somit funktioniert.

Mögliche Konfigurationsfehler

E-Mail Server ist falsch

Fehlermeldung: Der angegebene Host ist unbekannt

Port ist falsch

Fehlermeldung: Es konnte keine Verbindung hergestellt werden, da der Zielcomputer die Verbindung verweigerte

Benutzername oder Passwort sind falsch

Fehlermeldung: Authentication failed: wrong user/password

Weitere Anpassungen

Terms of Services aktivieren

Aktivieren Sie dazu das Feature termsAndPrivacyPolicy in der Datei config/jetstream.php

Dadurch sehen sie im Registrierungsdialog ein zusätzliches Optionsfeld

Ändern der Sprache

Bearbeiten Sie in der Datei config/app.php die Einstellung locale. Ändern Sie den Wert auf 'de'.

Nach einem Neustart der Anwendung werden aber weiterhin die englischen Texte angezeigt.

Die Ursache liegt an der nicht vorhandenen deutschen Übersetzung der verwendeten Texte. Prüfen Sie einfach den Ordner mit den vorhandenen Übersetzungen: resources/lang

Es gibt nur einen Unterordner en für die englischen Texte:

Zusätzlich zu den Übersetzungen muss noch ein weiterer Schritt erfolgen. Um ihre Anwendung komplett auf Mehrsprachlichkeit umzustellen dürfen keine Texte direkt angegeben werden.

Betrachten wir hierzu die Startseite, speziell die Links in der rechten oberen Ecke:

Der View für die Startseite wird in der Datei resources/views/welcome.blade.php definiert:

Wir sehen, das hier der Text direkt in englischer Sprache angegeben wird.

<a href="{{ route('register') }}" class="...">Register</a>

Es ist sehr schwierig, eine automatische Übersetzung für alle Texte durchzuführen, wenn nicht angegeben wird, ob ein bestimmter Text übersetzt werden soll. Einfach alle Texte zu übersetzen kann zu Problemen führen.

Daher wird bei Laravel der Weg gewählt, explizit anzugeben, ob ein Text übersetzt werden soll.

Diese Angabe der nachfolgende Text soll übersetzt werden erfolgt mit Hilfe der Funktion __ (Der Name der Funktion lautet tatsächlich __, als zwei Unterstriche)

Anstatt

Register

schreiben wir nun

{{ __('Register') }}

Dadurch erkennt Laravel (speziell die Blade Template Engine), das hier eine Übersetzung durchgeführt werden soll und sucht eine passenden Übersetzungstext.

Hier kommt nun der bereits angesprochen Ordner resources/lang ins Spiel. Erstellen Sie in diesem Ordner eine Datei de,json und verwenden Sie als Inhalt den nachfolgenden Text:

Nach einen Neustart der Anwendung sehen wir gewünschte Ergebnis:

Den gewünschten Übersetzungstext findet Blades anhand des angegebenen Textes innerhalb der Funktion __:

welcome.blade.phpde.json

Die Übersetzung der Anwendung erfordert somit für alle Texte die gleichen Schritte

  • Ermitteln des Views mit dem zu übersetzenden Text, z. B. Sample Text
  • Einbinden des Textes in die Funktion , z. B. {{ ('Sample text') }}
  • Hinzufügen der Übersetzung in der Datei de.json, z. B. "Sample text“: Beispieltext

Erstellen einer neue Startseite

Die Startseite entspricht immer noch der Standardanwendung. Der entsprechende View ist welcome.blade.php.

Zur Startseite wird dieser View aber nicht durch den Namen, sondern durch eine Einstellung in der Datei routes/web.php

Mit Hilfe des von Laravel verwendeten Routing, wird festgelegt, welcher View angezeigt wird, wenn eine bestimmte URI aufgerufen wird.

In der vorhandenen Einstellung legt fest, das bei der Uri '/' der View 'welcome' angezeigt wird.

Einfache Startseite erstellen

Wir verwenden hier das in der Laravel Dokumentation beschrieben einfache Beispiel.

Erstellen Sie die Datei Datei resources/views/home.blade.php. Verwenden Sie als Inhalt den nachfolgenden Text

<html>
    <body>
        <h1>Hello, {{ $name }}</h1>
    </body>
</html>

Routing anpassen

Passen Sie dann die Datei routes/web.php an.

Route::get('/welcome', function () {
    return view('welcome');
})->name('welcome');

Route::get('/', function () {
    return view('home', ['name' => 'Laravel']);
});

Wir ändern die neue Startseite mit der Uri / und stellen die alte Startseite unter einer neuen Uri /welcome bereit.

Neue Startseite anzeigen

Öffnen Sie nun wieder die Seite http://localhost:8000 oder aktualisieren Sie ein bereits geöffnetes Browserfenster:

Die vorherige Startseite können wir über die Uri /welcome erreichen

Neue Seite zur Navigation hinzufügen

Erweitern Sie die Daten resources/views/navigation-menu.blade.php um einen Eintrag:

<!-- Navigation Links -->
<div class="hidden space-x-8 sm:-my-px sm:ml-10 sm:flex">
    <x-jet-nav-link href="{{ route('dashboard') }}" 
                    :active="request()->routeIs('dashboard')">
         {{ __('Dashboard') }}
    </x-jet-nav-link>
</div>

<div class="hidden space-x-8 sm:-my-px sm:ml-10 sm:flex">
    <x-jet-nav-link href="{{ route('welcome') }}" 
                    :active="request()->routeIs('welcome')">
         {{ __('Welcome') }}
    </x-jet-nav-link>
</div>

Komponenten

Komponente erstellen

php artisan make:component MyComponent

Blade-Komponenten registrieren

You can register your jetstream blade components in App\Providers\JetstreamServiceProvider.php located in app\Providers folder.

Fügen sie die nachfolgende Funktion hinzu:

protected function registerComponent(string $component) {
    \Illuminate\Support\Facades\Blade::component('jetstream::components.'.$component, 'jet-'.$component);
}

Der nachfolgende Programmcode registriert ihre Komponente:

public function register() {
    $this->registerComponent('subform');
}

Sie können diese nun wie folgt nutzen:

<x-jet-subform>

Laravel | Einstieg in </> htmx

Inhaltsverzeichnis

TL;DR

Der Code für die in diesem Post erstelle Anwendung liegt hier.

Einrichten der Starter-App

Erstellen der Starter App. In diesem Post beschreibe ich, wie sie eine Starter-App erstellen und die grundlegenden Anpassungen durchführen können.

Sie können auch direkt mit dem dazugehörigen Repository starten:

❯ git clone https://github.com/r14r/Laravel_Tutorial_Erstellen-einer-Starter-App Laravel_Tutorial_Arbeiten-mit-htmx
❯ composer install
❯ npm install
❯ npm run build
❯ php artisan
❯ cp .env.example  .env
❯ php artisan migrate
❯ php artisan key:generate
❯ php artisan serve

htmx einrichten

Installation

❯ npm install htmx.org

Hinweis: Verwenden sie nicht das NPM Paket htmx, dies hat einen anderen Inhalt

Seite für unsere Beipiele erstellen (htmx Playground)

Routing erstellen

Seite erstellen: resources/views/playground.blade.php

cp resources/views/dashboard.blade.php resources/views/playground.blade.php

Inhalt anpassen:

<x-app-layout>
    <x-slot name="header">
        <h2 class="font-semibold text-xl text-gray-800 dark:text-gray-200 leading-tight">
            {{ __('Playground') }} for Laravel and <<span style="color:#3d72d7">/</span>> htm<span
                    style="color:#3d72d7">x</span>
        </h2>
    </x-slot>

    <div class="py-12">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
            <div class="bg-white dark:bg-gray-800 overflow-hidden shadow-xl sm:rounded-lg">
                #
            </div>
        </div>
    </div>
</x-app-layout>

Navigationslinks anpassen

Ergebnis

Ersten htmx Aufruf hinzufügen

API Aufruf einrichten

Die Datei routes/api.php erweitern:

Route::get('/htmx/message', function () {
    return response('Dies ist eine Nachricht', 200)->header('Content-Type', 'application/json');
});

Playground Seite anpassen

<div hx-get="/api/htmx/message">
    Mitteilungen laden...
</div>

Ergebnis

htmx Beispiele

Auf der htmx – Projekteseite finden sie viele Beispiele. Wir wollen nun einige davon in Laravel umsetzen.

Astro Tutorial – Working with Preact

Inhaltsverzeichnis

TL;DR

Code for this tutorial is on Github

Starter Project

Create Starter

❯ npm create astro@latest "Tutorial - Working with Preact"
.../21.6.2/pnpm/store/v3/tmp/dlx-99714   |  +39 ++++
.../21.6.2/pnpm/store/v3/tmp/dlx-99714   | Progress: resolved 39, reused 39, downloaded 0, added 39, done

 astro   Launch sequence initiated.

      ◼  dir Using Tutorial - Working with Preact as project directory

  tmpl   How would you like to start your new project?
         Empty

    ts   Do you plan to write TypeScript?
         Yes

   use   How strict should TypeScript be?
         Strict

  deps   Install dependencies?
         Yes

   git   Initialize a new git repository?
         Yes

      ✔  Project initialized!
         ■ Template copied
         ■ TypeScript customized
         ■ Dependencies installed
         ■ Git initialized

  next   Liftoff confirmed. Explore your project!

         Enter your project directory using cd "./Tutorial - Working with Preact"
         Run pnpm dev to start the dev server. CTRL+C to stop.
         Add frameworks like react or tailwind using astro add.

         Stuck? Join us at https://astro.build/chat

╭─────╮  Houston:
│ ◠ ◡ ◠  Good luck out there, astronaut! 🚀
╰─────╯

Run Starter

❯ cd "Tutorial - Working with Preact"
❯ npm run dev

> tutorial---working-with-preact@0.0.1 dev /Users/Shared/CLOUD/Programmier-Workshops/Kurse/Astro/Einsteiger/Tutorial - Working with Preact
> astro dev


 astro  v4.5.13 ready in 156 ms

┃ Local    http://localhost:4321/
┃ Network  use --host to expose

14:34:39 watching for file changes...

Modify Project Structur and add helper code

tsconfig.json

{
  "extends": "astro/tsconfigs/strict",
  "compilerOptions": {
    "allowJs": true,
    "strictNullChecks": true,
    "baseUrl": ".",
    "lib": ["es2022", "dom", "dom.iterable"],
    "paths": {
      "@/*": ["src/*"]
    }
  },
  "exclude": ["node_modules", "**/node_modules/*", ".vscode", "dist"]
}

Replace relative path with reference to path alias in every page

import Layout from '../../layouts/BlogPost.astro';

becomes to

import Layout from '@/layouts/BlogPost.astro';
import Layout from '../styles/global.css';

becomes to

import Layout from '@/styles/global.css';

Install Preact Integration

Add integration for preact

❯ npx astro add preact
✔ Resolving packages...

  Astro will run the following command:
  If you skip this step, you can always run it yourself later

 ╭──────────────────────────────────────────────────╮
 │ pnpm add @astrojs/preact@^3.1.2 preact@^10.20.1  │
 ╰──────────────────────────────────────────────────╯

✔ Continue? … yes
✔ Installing dependencies...

  Astro will make the following changes to your config file:

 ╭ astro.config.mjs ─────────────────────────────╮
 │ import { defineConfig } from 'astro/config';  │
 │                                               │
 │ import preact from "@astrojs/preact";         │
 │                                               │
 │ // https://astro.build/config                 │
 │ export default defineConfig({                 │
 │   integrations: [preact()]                    │
 │ });                                           │
 ╰───────────────────────────────────────────────╯

✔ Continue? … yes

   success  Added the following integration to your project:
  - @astrojs/preact

  Astro will make the following changes to your tsconfig.json:

 ╭ tsconfig.json ───────────────────────────────────────────────────────╮
 │ {                                                                    │
 │   "extends": "astro/tsconfigs/strict",                               │
 │   "compilerOptions": {                                               │
 │     "allowJs": true,                                                 │
 │     "strictNullChecks": true,                                        │
 │     "baseUrl": ".",                                                  │
 │     "lib": [                                                         │
 │       "es2022",                                                      │
 │       "dom",                                                         │
 │       "dom.iterable"                                                 │
 │     ],                                                               │
 │     "paths": {                                                       │
 │       "@/*": [                                                       │
 │         "src/*"                                                      │
 │       ]                                                              │
 │     },                                                               │
 │     "jsx": "react-jsx",                                              │
 │     "jsxImportSource": "preact"                                      │
 │   },                                                                 │
 │   "exclude": [                                                       │
 │     "node_modules",                                                  │
 │     "**/node_modules/*",                                             │
 │     ".vscode",                                                       │
 │     "dist"                                                           │
 │   ]                                                                  │
 │ }                                                                    │
 ╰──────────────────────────────────────────────────────────────────────╯

✔ Continue? … yes

   success  Successfully updated TypeScript settings

Install preact/signale

npm install preact/signal

Modify src/pages/index.astro

---
import Counter from "@/components/Counter";
import { signal } from "@preact/signals";

const count = signal(0);
---

<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <meta name="generator" content={Astro.generator} />
    <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
    <style>
      html,
      body {
        font-family: system-ui;
        margin: 0;
      }
      body { padding: 2rem; }
      h1 { text-align: center; }
    </style>
  </head>
  <body>
    <main>
      <h1 style="halign:center">Working with Astro and Preact</h1>
      <Counter count={count} client:visible><h3>Hello, Preact 1!</h3></Counter>
      <Counter count={count} client:visible><h3>Hello, Preact 2!</h3></Counter>
    </main>
  </body>
</html>

Create Component Counter

Create folder src/components

mkdir src/components

Create file Counter.tsx

import type { ComponentChildren } from "preact";
import type { Signal } from "@preact/signals";
import { lazy, Suspense } from "preact/compat";

import "./Counter.css";

const Message = lazy(async () => import("./Message"));
const Fallback = () => <p>Loading...</p>;

type Props = {
  children: ComponentChildren;
  count: Signal<number>;
};

export default function Counter({ children, count }: Props) {
  const add = () => count.value++;
  const subtract = () => count.value--;

  return (
    <>
      <div class="counter">
        <button onClick={subtract}>-</button>
        <pre>{count}</pre>
        <button onClick={add}>+</button>
      </div>
      <Suspense fallback={Fallback}>
        <Message>{children}</Message>
      </Suspense>
    </>
  );
}

Create file Counter.css

.counter {
	display: grid;
	font-size: 2em;
	grid-template-columns: repeat(3, minmax(0, 1fr));
	margin-top: 2em;
	place-items: center;
}

Create Message.tsx

import type { ComponentChildren } from 'preact';
import './Message.css';

export default function Message({ children }: { children: ComponentChildren }) {
	return <div class="message">{children}</div>;
}

Create Message.css

.message {
	text-align: center;
}

Run App

npm run dev

Astro Tutorial – Add Table of Content (TOC) to the Post Layout

Inhaltsverzeichnis

TL;DR

Code for this tutorial is on Github

Starter Project

Create Starter

❯ npm create astro@latest
.../21.6.2/pnpm/store/v3/tmp/dlx-5990    |  +39 ++++
.../21.6.2/pnpm/store/v3/tmp/dlx-5990    | Progress: resolved 39, reused 39, downloaded 0, added 39, done

 astro   Launch sequence initiated.

   dir   Where should we create your new project?
         ./Tutorial - Add TOC to PostLayout

  tmpl   How would you like to start your new project?
         Use blog template

    ts   Do you plan to write TypeScript?
         Yes

   use   How strict should TypeScript be?
         Strict

  deps   Install dependencies?
         Yes

   git   Initialize a new git repository?
         Yes

      ✔  Project initialized!
         ■ Template copied
         ■ TypeScript customized
         ■ Dependencies installed
         ■ Git initialized

  next   Liftoff confirmed. Explore your project!

         Enter your project directory using cd "./Tutorial - Add TOC to PostLayout"
         Run pnpm dev to start the dev server. CTRL+C to stop.
         Add frameworks like react or tailwind using astro add.

         Stuck? Join us at https://astro.build/chat

╭─────╮  Houston:
│ ◠ ◡ ◠  Good luck out there, astronaut! 🚀
╰─────╯

Run Starter

❯ cd Tutorial\ -\ Add\ TOC\ to\ PostLayout/

Tutorial - Add TOC to PostLayout on  master [+] is 📦 v0.0.1 via  v21.6.2 via 🐍 v3.12.2 (3.12)
❯ npm run dev

> tutorial---add-toc-to-postlayout@0.0.1 dev /Users/Shared/CLOUD/Programmier-Workshops/Kurse/Astro/Einsteiger/Tutorial - Add TOC to PostLayout
> astro dev


 astro  v4.5.12 ready in 300 ms

┃ Local    http://localhost:4321/
┃ Network  use --host to expose

12:18:45 watching for file changes...

Modify Project Structur and add helper code

tsconfig.json

{
  "extends": "astro/tsconfigs/strict",
  "compilerOptions": {
    "allowJs": true,
    "strictNullChecks": true,
    "baseUrl": ".",
    "lib": ["es2022", "dom", "dom.iterable"],
    "paths": {
      "@/*": ["src/*"]
    }
  },
  "exclude": ["node_modules", "**/node_modules/*", ".vscode", "dist"]
}

Replace relative path with reference to path alias in every page

import Layout from '../../layouts/BlogPost.astro';

becomes to

import Layout from '@/layouts/BlogPost.astro';
import Layout from '../styles/global.css';

becomes to

import Layout from '@/styles/global.css';

Create separate Layouts for Project and Posts

Rename src/layouts/BlogPost.astro to src/layouts/BaseLayout.astro

Change every import of BlogPost to

import Layout from '@/layouts/BaseLayout.astro';

Astro – Cookbook

Animation

Animate Image by MouseOver / Hover

CSS

      .book {
        width: 300px;
        height: 480px;
        position: relative;
        transform-style: preserve-3d;
        transform: rotateY(-30deg);
        transition: 1s ease;
        animation: 1s ease 0s 1 initAnimation;
      }

      .book:hover {
        transform: rotateY(0deg);
      }

page.astro

        ><div class="book">
          <Image
            src={"/cover-2.jpeg"}
            width={300}
            height={600}
            alt={book.title}
            format={"avif"}
          />
        </div>

Daily: VS Code Error NSOSStatusErrorDomain

If you got an NSOSStatusErrorDomain Error, when you start VS Code from the command line

❯ code
[0309/155203.303710:ERROR:codesign_util.cc(108)] SecCodeCheckValidity: Error Domain=NSOSStatusErrorDomain Code=-67062 "(null)" (-67062)

You should do this: codesign --force --deep --sign -

❯ which code
/Users/Shared/VSCode/Default/Visual Studio Code - Insiders.app/Contents/Resources/app/bin/code

❯ codesign --force --deep --sign - "/Users/Shared/VSCode/Default/Visual Studio Code - Insiders.app"
/Users/Shared/VSCode/ralphg/Visual Studio Code - Insiders.app: replacing existing signature

❯ code -v
1.88.0-insider
19ecb4b8337d0871f0a204853003a609d716b04e
x64

The Art of AI: Create / Recreating Images

Today, i want to find out, how to create / recreating images with ChatGPT.

Challenge: I found an image and want to recreate the image:

Write a Prompt that creates this Image
Create an image of a woman with long, sleek black hair and striking features. She should have a strong, confident posture with her arms crossed. She's wearing a simple, elegant black dress with a round neckline. The background is a modern, minimalist office with a hint of sophistication. The color palette should be neutral, with emphasis on shades of grey and black to match her attire. The lighting is soft and diffused, highlighting her from the front and casting a gentle shadow behind her. The overall aesthetic is chic and polished with a touch of corporate professionalism.
Write a Prompt that creates this Image
Create an image of a poised and professional woman with long, sleek black hair and prominent, striking features. She stands with a sense of authority, her arms confidently crossed in front of her. She is dressed in a simple yet sophisticated black dress with a modest round neckline. The setting is a contemporary, minimalist office space that exudes a refined elegance. The color scheme is a harmonious blend of neutral tones, dominated by greys and blacks that complement her attire. Soft, ambient lighting bathes the scene, casting a gentle illumination that accentuates her silhouette against the muted sophistication of the office backdrop. The composition should convey an atmosphere of chic professionalism and understated luxury.
Write a Prompt that creates this Image
Create an image of an elegant and professional woman with long, black hair and defined, striking features. She exhibits a posture of confidence and composure with her arms crossed. Her attire is a chic, form-fitting black dress with a modest neckline. The environment is a stylish, minimalist office setting with sophisticated furnishings and a neutral color scheme emphasizing grays and blacks. The scene is illuminated with soft, ambient lighting that casts a gentle glow on the woman, highlighting her assertive stance against the contemporary backdrop, evoking a sense of refined grace and corporate elegance.

Notes:

Mostly, after running the same prompt the second time, ChatGPT responded with something like that:

So, i ask ChatGPT nicely to do it again:

Create the image again, because each time the image looks different

Next Step: find the precise prompt

As we see, using the same prompt results in different images. So i asked ChatGPT how to create a prompt that produces the same image each time:

MeUsing one prompt multiple times, each image is different from another. How can a state the prompt more clearly so that the prompt creates each time exactly the same imageChatGPT
ChatGPTCreating exactly the same image multiple times using a text-to-image AI model like DALL-E is challenging due to the inherent variability in how these models interpret and render prompts. Each time a prompt is processed, the model generates a unique interpretation based on its training and algorithms, which can lead to variations in the resulting images. However, there are some strategies you can use to minimize these differences:
Be Highly Specific: Provide as many details as possible in your prompt, including specifics about posture, facial expression, clothing, and background elements. The more detailed your description, the less room there is for the AI to interpret differently.
Use Precise Descriptors: Instead of using general terms, use precise descriptors. For example, instead of saying “long, black hair,” specify the style, such as “long, straight, black hair that falls to mid-back.”
Define the Scene Layout: Be explicit about the composition of the image, like where the subject is positioned in the frame, how much of the background is visible, and the perspective or angle of the view.
Describe Colors and Lighting: Clearly state the colors you want to be used, including shades and tones, and describe the lighting (e.g., “soft, diffused lighting from the front left”).
Include Comparable Examples: If possible, reference a similar existing image or style to guide the AI’s interpretation.
Consistency in Format: If you’re looking for a portrait, landscape, or specific aspect ratio, mention this explicitly.
Even with these strategies, it’s important to remember that AI models like DALL-E are probabilistic and may still produce variations with each rendering. The nature of these models means they interpret prompts creatively, so exact replication of images is not always possible.

Ok, lets try:

Me
Using your suggestions, create a precise prompt that create this image. Use all 6 strategies in your prompt
ChatGPTCreate a digital portrait of a woman who embodies elegance and professionalism. She should have long, straight, jet-black hair with a glossy sheen, cascading down to mid-back. Her facial features are sharply defined, with high cheekbones, almond-shaped hazel eyes, meticulously groomed eyebrows, and full, neutral-colored lips. Her skin has a matte finish with a porcelain-like quality.
Her stance is assertive; she stands straight with her shoulders back and arms crossed at the waist, showcasing a silver bracelet on her right wrist and a matching ring on her left middle finger. She wears a tailored, form-fitting black sheath dress with three-quarter sleeves and a boat neckline, ending just above the knees.
The setting is an upscale, minimalist office: to her right is a steel-gray filing cabinet with a potted green succulent on top; to her left, a sleek, black office chair behind a dark walnut desk, on which rests a closed silver laptop and a white ceramic mug. The background comprises floor-to-ceiling windows with thin, vertical blinds casting soft shadows, and the walls are a light gray.
The lighting is soft and directional, coming from the top left, creating a subtle highlight on her left cheek and a soft shadow to her right, enhancing her features without harshness. The overall color palette is monochrome, with a focus on blacks, whites, and grays, providing contrast against her black dress and the lighter office environment.
The composition is centered and balanced, with the woman placed in the middle of the frame, allowing for an equal amount of office space on either side of her. The camera angle is at eye level, ensuring a direct and engaging connection with the viewer. The image should convey a narrative of confidence, sophistication, and modern professional elegance.

Wow, impresiv. Ok, here are the image created by this prompt:

The results looks more the same, but still lacking these “unique” factor.

So i asked ChatGPT again:

MeThe images still looks different. Is there a deterministic way to uniquely generate an imageChatGPT
ChatGPTAI image generation models like DALL-E are designed to introduce variation and creativity into their outputs. Even with highly detailed prompts, they are not deterministic in the traditional sense — you won’t get the exact same image with each generation because the model incorporates an element of randomness or “seed” into each creation process. This randomness is a core feature, as it enables the generation of unique images from the same prompt.
However, in some advanced implementations of these models, you can specify a “seed” value, which can help in producing the same image across multiple runs if the seed is kept constant. The “seed” is essentially a starting point for the random number generator used in the generation process. By using the same seed, you tell the AI to start from the same random point, leading to the same sequence of “random” numbers, which can result in the same output.
At the moment, the system you are interacting with does not provide an option to control the seed value manually for each request. Each new image generation is treated as a fresh instance, without a way to replicate the exact randomness of a previous run.
Therefore, while you can guide the AI with very specific and detailed prompts to achieve close approximations, there is currently no way to ensure that a publicly available AI image generation model like DALL-E will produce the exact same image twice.

Ok, so we wont get 100% equal images. But being more precise, hopefully we will reach someting around 90 – 95%.

Me

Could you suggest the general structure of an image creating prompt, so that this prompt will create nearly the same images, each time i run the pr

To achieve the most consistent results with an AI image generation model like DALL-E, you should craft a prompt that is detailed and specific, reducing the room for interpretation as much as possible. Here’s a general structure you can follow:

  1. Subject Description: Start with a detailed description of the main subject, including physical characteristics, expressions, and attire.
    • Example: “Create an image of a woman in her 30s with shoulder-length curly brown hair, green eyes, wearing a navy blue blazer and white shirt.”
  2. Posture and Expression: Clearly describe the subject’s posture, facial expression, and any gestures.
    • Example: “She has a friendly smile, direct eye contact with the viewer, and her hands are folded in her lap.”
  3. Setting and Background: Detail the setting, including specific objects, colors, and the overall atmosphere.
    • Example: “She is seated on a red armchair in a well-lit room with bookshelves filled with colorful books in the background.”
  4. Lighting and Shadows: Describe the lighting direction and intensity, as well as the resulting shadows.
    • Example: “There is soft lighting coming from the left, creating a gentle shadow on the right side of her face.”
  5. Color Palette: Specify the colors you want to be dominant in the image.
    • Example: “The color palette is warm, with rich browns and creams, accentuating the wooden elements of the furniture and books.”
  6. Camera Angle and Composition: Mention the perspective of the image, such as the angle and framing.
    • Example: “The viewpoint is at eye level, capturing the upper body of the woman, centered in the frame with equal space on both sides.”
  7. Additional Details: Add any other specific details that you want to include.
    • Example: “She wears a silver pendant necklace and has a small mole on her right cheek.”

Here’s how it would look put together:

“Create an image of a woman in her 30s with shoulder-length curly brown hair and green eyes, smiling friendly at the viewer, seated on a red armchair with hands folded in her lap. She is wearing a navy blue blazer and white shirt. The room is well-lit, with soft lighting coming from the left creating a gentle shadow on the right side of her face. The background is filled with bookshelves with colorful books. The color palette is warm, with rich browns and creams. The viewpoint is eye level, framing the woman in the center with equal space on both sides. She wears a silver pendant necklace and has a small mole on her right cheek.”

Even with this structure, slight variations can occur due to the stochastic nature of AI image generation. However, providing a highly structured and detailed prompt like the one above can significantly increase the consistency of the images produced.

Ok, let’s try i out

Me

Create an image of a woman in her 30s with shoulder-length curly brown hair and green eyes, smiling friendly at the viewer, seated on a red armchair with hands folded in her lap. She is wearing a navy blue blazer and white shirt. The room is well-lit, with soft lighting coming from the left creating a gentle shadow on the right side of her face. The background is filled with bookshelves with colorful books. The color palette is warm, with rich browns and creams. The viewpoint is eye level, framing the woman in the center with equal space on both sides. She wears a silver pendant necklace and has a small mole on her right cheek.

Azure Open AI – The Roadmap to become an expert

Inhaltsverzeichnis

Roadmap

  • Basics of Programming: Python is a great starting point due to its simplicity and extensive support in the AI field. Familiarize yourself with variables, data types, loops, conditionals, functions, and object-oriented programming. Resources: Codecademy, LeetCode, HackerRank.
  • Understanding of AI and Machine Learning: Learn about foundational concepts like supervised learning, unsupervised learning, reinforcement learning, regression, classification, clustering, neural networks. Resources: Andrew Ng’s course on Coursera, “Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow” by Aurélien Géron.
  • Study Deep Learning: Deep learning is a special kind of machine learning involving artificial neural networks with several layers (“deep” structures). Study convolutional networks (used in image recognition), recurrent networks (used in sequence data), and the concept of deep reinforcement learning. Resources: Deep Learning Specialization by Andrew Ng on Coursera, “Deep Learning” by Ian Goodfellow, Yoshua Bengio and Aaron Courville.
  • Learn about Microsoft Azure: Azure is a cloud platform offering services like compute power, storage options, and AI models. Learn how to navigate the Azure portal, create/manage resources, and understand core services (Azure Compute, Azure Storage, Azure Data Services). Resources: Microsoft Learn, Azure documentation.
  • Microsoft’s AI Services: Azure AI services include Azure Machine Learning for building, training, and deploying machine learning models, and Azure Cognitive Services for pre-trained AI services like vision, speech, and language processing. Resources: Microsoft Learn’s path for AI Engineer, Azure AI documentation.
  • Azure OpenAI: Azure OpenAI offers access to powerful models like GPT-3 for tasks like text generation, translation, summarization, etc. Learn how to call these APIs from your application and how to use the results effectively. Resources: Azure OpenAI documentation, OpenAI’s GPT-3 playground.
  • Projects: Practical projects could include building a chatbot using Azure Bot Service and QnA Maker, creating a text summarizer using GPT-3, or developing a computer vision application using Azure Cognitive Services.
  • Stay Updated: AI is an ever-evolving field. Blogs like Towards Data Science, Medium, the Microsoft Azure blog, and arXiv for research papers can keep you updated. Webinars and online forums like AI Saturdays, AI Fest, and Stack Overflow also help.
  • Certifications: Certifications like the Microsoft Certified: Azure AI Engineer Associate or Microsoft Certified: Azure Data Scientist Associate validate your skills and knowledge. They require a solid understanding of Azure services and machine learning concepts.
  • Contribute to the Community: Sharing your knowledge and experience helps solidify your understanding and establishes your expertise. Write blogs or make YouTube videos explaining concepts, give talks at local meetups or conferences, contribute to open-source projects on GitHub, or answer questions on forums like Stack Overflow.

Understanding of AI and Machine Learning

  • Mathematical Foundations: Brush up on your knowledge of Linear Algebra, Calculus, Probability, and Statistics. These are essential for understanding machine learning algorithms.
  • Programming Skills: Python is the most used language in the field of machine learning. Familiarize yourself with Python, its libraries like NumPy, Pandas, and Matplotlib, and an IDE such as Jupyter Notebook.
  • Data Preprocessing: Learn how to clean and preprocess data, handle missing data, and perform feature scaling. Understand the importance of data visualization for exploring your dataset.
  • Supervised Learning: Start with simple linear regression and then move on to multiple linear regression, logistic regression, k-nearest neighbors, support vector machines, and decision trees. Understand the concept of overfitting and underfitting, and techniques to combat them like regularization.
  • Unsupervised Learning: Learn about clustering techniques like K-means and hierarchical clustering. Understand dimensionality reduction techniques like Principal Component Analysis (PCA).
  • Advanced Topics: Once you’re comfortable with the basics, move onto more advanced topics like ensemble methods, neural networks, and deep learning. Learn about different types of neural networks like Convolutional Neural Networks (CNNs), Recurrent Neural Networks (RNNs), and transformers.
  • Tools and Libraries for Machine Learning: Get hands-on experience with Scikit-Learn, TensorFlow, and Keras. Learn how to build, train, and evaluate models with these libraries.
  • Validation and Evaluation Metrics: Understand validation techniques like k-fold cross-validation. Learn about different evaluation metrics like accuracy, precision, recall, F1 score, ROC AUC, mean squared error, etc.
  • Special Topics: Study special topics like natural language processing, reinforcement learning, generative adversarial networks, transfer learning, etc.
  • Projects: Apply your knowledge to real-world projects. This could be anything from predicting house prices to building a chatbot.
  • Stay Updated and Keep Learning: Machine learning is a rapidly evolving field. Read research papers, follow relevant blogs, participate in Kaggle competitions, and take online courses to keep your knowledge up-to-date.

Deep Learning

  • Mathematical Foundations: Make sure you have a good understanding of Linear Algebra, Calculus, Probability, and Statistics. These are crucial for understanding how deep learning algorithms work.
  • Programming Skills: Python is the most common language in the field of deep learning. Make sure you’re comfortable with it. Libraries like NumPy and Matplotlib will also be useful.
  • Understanding of Machine Learning: Before delving into deep learning, you should have a solid understanding of basic machine learning concepts and algorithms. This includes concepts like overfitting, underfitting, bias-variance tradeoff, and understanding of algorithms like linear regression, logistic regression, and more.
  • Introduction to Neural Networks: Start with understanding what neural networks are and how they work. Learn about the architecture of neural networks, activation functions, and the backpropagation algorithm for training neural networks.
  • Frameworks for Deep Learning: Get hands-on experience with deep learning frameworks like TensorFlow and PyTorch. Learn how to define, train, and evaluate neural networks with these libraries.
  • Convolutional Neural Networks (CNNs): These are used primarily for image processing, object detection, and recognition tasks. Understand the architecture of CNNs and concepts like convolutional layers, pooling layers, and filters.
  • Recurrent Neural Networks (RNNs): Used for sequence data like time series and natural language. Learn about the structure of RNNs, the problem of long-term dependencies, and solutions like LSTM (Long Short-Term Memory) and GRU (Gated Recurrent Units).
  • Advanced Topics in Deep Learning: Explore advanced topics like autoencoders, generative adversarial networks (GANs), transfer learning, reinforcement learning, etc.
  • Deep Learning for Natural Language Processing: Understand how deep learning is used in NLP. Learn about Word2Vec, GloVe, RNNs, LSTMs, GRUs, and Transformer models like BERT.
  • Projects: Apply your knowledge to real-world projects. This could be anything from image recognition tasks, text generation, sentiment analysis, etc.
  • Stay Updated and Keep Learning: Deep learning is a rapidly evolving field. Follow the latest research papers, participate in online courses and challenges like those on Kaggle.

Book on Machine Learning

Introduction to Machine Learning

  • Definition and Importance
  • Applications of Machine Learning
  • Types of Machine Learning: Supervised, Unsupervised, Reinforcement Learning

Mathematical Foundations

  • Linear Algebra
  • Calculus
  • Probability and Statistics
  • Exercises and Sample Problems

Python for Machine Learning

  • Python Basics
  • Python Libraries: NumPy, Pandas, Matplotlib
  • Exercises: Python Coding Problems

Data Preprocessing

  • Importing Data
  • Cleaning Data
  • Feature Engineering
  • Data Visualization
  • Exercises: Data Cleaning and Visualization

Supervised Learning

  • Regression Analysis
    • Simple Linear Regression
    • Multiple Linear Regression
    • Logistic Regression
  • Classification Algorithms
    • Decision Trees
    • K-Nearest Neighbors
    • Support Vector Machines
  • Exercises: Implementing Supervised Learning Algorithms

Unsupervised Learning

  • Clustering
    • K-Means Clustering
    • Hierarchical Clustering
  • Dimensionality Reduction
    • Principal Component Analysis
  • Exercises: Implementing Unsupervised Learning Algorithms

Evaluating Machine Learning Models

  • Overfitting and Underfitting
  • Bias-Variance Tradeoff
  • Cross-Validation
  • Performance Metrics
  • Exercises: Evaluating Models

Neural Networks and Deep Learning

  • Introduction to Neural Networks
  • Backpropagation
  • Convolutional Neural Networks
  • Recurrent Neural Networks
  • Exercises: Implementing Neural Networks

Advanced Topics

  • Ensemble Methods
  • Reinforcement Learning
  • Natural Language Processing
  • Transfer Learning
  • Generative Adversarial Networks
  • Exercises: Advanced Topics Projects

Case Studies in Machine Learning

  • Case Study 1: Predictive Analytics
  • Case Study 2: Image Recognition
  • Case Study 3: Natural Language Processing

Future Trends in Machine Learning

Appendix

References and Further Reading

Glossary of Machine Learning Terms