Saturday, 7 September 2024

Using Elastic Search In Laravel

1. Composer install Elasticsearch

"elasticsearch/elasticsearch": "^8.15",

* Note: Elasticsearch clients have the same version as Elasticsearch (in this case version 8)

1. Add observer for model

#[ObservedBy([ViolationObserver::class])]
class Violation extends Model

observer code

<?php

namespace App\Observers;

use App\Models\Violation;

class ViolationObserver
{
    public const VIOLATION_INDEX_NAME = 'violations_index';
    protected $client;

    public function __construct()
    {
        $this->client = app('elasticsearch');
    }

    /**
     * Handle the Violation "created" event.
     */
    public function created(Violation $model): void
    {
        $this->indexDocument($model);
    }

    /**
     * Handle the Violation "updated" event.
     */
    public function updated(Violation $model): void
    {
        $this->indexDocument($model);
    }

    /**
     * Handle the Violation "deleted" event.
     */
    public function deleted(Violation $model): void
    {
        $this->deleteDocument($model);
    }

    /**
     * Handle the Violation "restored" event.
     */
    public function restored(Violation $violation): void
    {
        //
    }

    /**
     * Handle the Violation "force deleted" event.
     */
    public function forceDeleted(Violation $violation): void
    {
        //
    }

    protected function indexDocument(Violation $model)
    {
        $params = [
            'index' => self::VIOLATION_INDEX_NAME,
            'id'    => $model->id,
            'body'  => [
                'id'     => $model->id,
                'control_plate'   => $model->control_plate,
                'status' => $model->status,
            ],
        ];

        $this->client->index($params);
    }

    protected function deleteDocument(Violation $model)
    {
        $params = [
            'index' => self::VIOLATION_INDEX_NAME,
            'id'    => $model->id,
        ];

        $this->client->delete($params);
    }
}

3. Register service

  $this->app->singleton('elasticsearch', function ($app) {
            return ClientBuilder::create()
                ->setHosts(config('elasticsearch.hosts'))
                ->build();
        });

4. Create a command demo

<?php

namespace App\Console\Commands;

use App\Models\Violation;
use App\Observers\ViolationObserver;
use Illuminate\Console\Command;

class CreateAndSyncElasticsearchIndexForViolation extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:create-and-sync-elasticsearch-index-for-violation';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $indexName = ViolationObserver::VIOLATION_INDEX_NAME;
        $client = app('elasticsearch');

        try {
            // $this->createIndex($client, $indexName);
            // $this->syncData($client, $indexName);
            $this->searchData($client, $indexName);
        } catch (\Exception $e) {
            dump("Error: " . $e->getMessage());
        }

        $this->info('Index created and data synchronized successfully');
    }

    /*
    * searchData
    */
    protected function searchData($client, $indexName)
    {
        // Violation::create([
        //     'control_plate' => '21'
        // ]);

        // Violation::destroy(9);

        $params = [
            'index' => $indexName, // Replace with your index name
            'body'  => [
                'query' => [
                    // 'match_all' => new \stdClass() // Match all documents
                    // 'match' => [
                    //     'control_plate' => '11111111' // Replace with your field and search value
                    // ],
                    'wildcard' => [
                        'control_plate' => '*2*'
                    ]
                ]
            ]
        ];
       
        try {
            $response = $client->search($params);
            if (isset($response['hits']['hits'])) {
                foreach ($response['hits']['hits'] as $hit) {
                    echo 'ID: ' . $hit['_id'] . '<br>';
                    echo 'Source: ' . print_r($hit['_source'], true) . '<br><br>';
                }
            } else {
                echo 'No results found';
            }
       
        } catch (\Exception $e) {
            echo 'Error: ', $e->getMessage();
        }
    }

    /*
    * createIndex
    */
    protected function createIndex($client, $indexName)
    {
        $params = [
            'index' => $indexName,
            'body'  => [
                'mappings' => [
                    'properties' => [
                        'id' => [
                            'type' => 'integer'
                        ],
                        'control_plate' => [
                            'type' => 'text'
                        ],
                        'status' => [
                            'type' => 'keyword'
                        ]
                    ]
                ]
            ]
        ];

        try {
            $response = $client->indices()->create($params);
            $this->info('Index created: ' . $indexName);
        } catch (\Exception $e) {
            $this->error('Error creating index: ' . $e->getMessage());
        }
    }

    /*
    * syncData
    */
    protected function syncData($client, $indexName)
    {
        $models = Violation::all(); // Fetch all records from the table

        $params = ['body' => []];

        foreach ($models as $model) {
            // Add index operation for each record
            $params['body'][] = [
                'index' => [
                    '_index' => $indexName,
                    '_id'    => $model->id,
                ]
            ];

            $params['body'][] = [
                'id'     => $model->id,
                'control_plate'   => $model->control_plate,
                'status' => $model->status,
            ];
        }

        try {
            // Bulk index the records
            $response = $client->bulk($params);
            $this->info('Data synchronized successfully');
        } catch (\Exception $e) {
            $this->error('Error synchronizing data: ' . $e->getMessage());
        }
    }
}


run command: php artisan app:create-and-sync-elasticsearch-index-for-violation

5. Docker-composer for Elasticsearch 8.15.1

### kibana815 ########################################
    kibana815:
        image: kibana:8.15.1
        container_name: kibana
        environment:
          - ELASTICSEARCH_URL=http://elasticsearch815:9200
        ports:
          - "5601:5601"
        networks:
          - frontend
          - backend

### ElasticSearch ########################################
    elasticsearch815:
      image: elasticsearch:8.15.1
      container_name: elasticsearch
      environment:
        - discovery.type=single-node
        - ES_JAVA_OPTS=-Xmx2g -Xms2g  # Adjust JVM heap size as needed
        - xpack.security.enabled=false  # Disable security features
      ports:
        - "9200:9200"  # HTTP port
        - "9300:9300"  # Transport port
      volumes:
        - elasticsearch815:/usr/share/elasticsearch/data
      healthcheck:
        test: ["CMD", "curl", "-f", "http://localhost:9200"]
        interval: 30s
        retries: 3
        start_period: 30s
        timeout: 10s
      networks:
        - frontend
        - backend

Thank you

Friday, 6 September 2024

Service, service Container, service Providers in laravel

1. Service is a class to perform some feature, or logic in the Laravel app
2. Service Container is a place containing registered services in the Larravel app
3. The Service Provider serves as a bridge to register services to the service container
- To register a service for Service Container you can register it in the service provider, you can use the bind() or singleton() method
$this->app->bind('App\Services\PaymentGateway', function ($app) {
    return new \App\Services\PaymentGateway(config('services.payment.api_key'));
});

$this->app->singleton('App\Services\PaymentGateway', function ($app) {
    return new \App\Services\PaymentGateway(config('services.payment.api_key'));
});

- To register a service provider to Laravel, there are 2 ways:
(1) Config Service provider in config/app.php
'providers' => [
    // Other Service Providers

    App\Providers\MyCustomServiceProvider::class,
],

(2) Config service provider in composer.json

"extra": {
    "laravel": {
        "providers": [
            "Vendor\\Package\\ServiceProvider"
        ],
        "aliases": {
            "SomeAlias": "Vendor\\Package\\Facade"
        }
    }
}

Thank you

Thursday, 5 September 2024

Tools for developer

1. Vs Code

- https://200lab.io/blog/vs-code-extension-cho-react/#12-auto-import 

- Prettier - Code formatter: https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode

- ES7+ React/Redux/React-Native snippets: ES7+ React/Redux/React-Native snippets

- glean: https://marketplace.visualstudio.com/items?itemName=wix.glean

2. Chorm extension

* Cut template

- CSS Used: https://chromewebstore.google.com/detail/css-used/cdopjfddjlonogibjahpnmjpoangjfff

-  Resources Saver: https://chromewebstore.google.com/detail/resources-saver/nlfcijlhljpenllloeheihmhoobeefpc

- Save All Resources: https://chromewebstore.google.com/detail/save-all-resources/abpdnfjocnmdomablahdcfnoggeeiedb

* Image to text

- Fast OCR: https://chromewebstore.google.com/detail/fast-ocr/oefooeopdahbeimdgamlblnpegijmdem

- Docsumo Free OCR Software: https://chromewebstore.google.com/detail/docsumo-free-ocr-software/ihmmlfacoffajllfpdfkdikgmoogbnph

- OCR - Image Reader: https://chromewebstore.google.com/detail/ocr-image-reader/bhbhjjkcoghibhibegcmbomkbakkpdbo

* Dictionary

- Ddict Translate: Translator - Dictionary: https://chromewebstore.google.com/detail/ddict-translate-translato/bpggmmljdiliancllaapiggllnkbjocb

* Edit Cookie

- EditThisCookie: https://chromewebstore.google.com/detail/editthiscookie/fngmhnnpilhplaeedifhccceomclgfbg

3. Local server

- Laragon

- Laradock

4. Window apps

- Mobaxterm: https://mobaxterm.mobatek.net/download.html

- Pixie: https://download.com.vn/download/pixie-22616

5. Data base GUI

- phpMyAdmin => for mysql

- pgAdmin => for postgres

- orthers: HeidiSQL, DBeaver, MySQL Workbench, dbForge Studio for MySQL, Navicat, DataGrip, Beekeeper Studio, DbVisualizer

Thank you

Saturday, 31 August 2024

Install & Uninstall Ubuntu on Windows with WSL2

To install Ubuntu on Windows 10 using WSL2 (Windows Subsystem for Linux version 2), follow these steps:

Step-by-Step Guide to Install Ubuntu on Windows 10 with WSL2

  1. Enable WSL and Virtual Machine Platform:

    • Open PowerShell as Administrator. You can do this by right-clicking on the Start button and selecting “Windows PowerShell (Admin)”.

    • Run the following commands to enable WSL and the Virtual Machine Platform:

      powershell
      dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart
  2. Set WSL2 as the Default Version:

    • To set WSL2 as the default version, run:

      powershell
      wsl --set-default-version 2
  3. Restart Your Computer:

    • Restart your computer to apply the changes.
  4. Install Ubuntu from Microsoft Store:

    • Open the Microsoft Store app.
    • Search for “Ubuntu” and select your preferred version (e.g., Ubuntu 20.04 LTS).
    • Click on the “Get” button to download and install Ubuntu.
  5. Initialize Ubuntu:

    • After installation, open the Ubuntu app from the Start menu.
    • A console window will open, and Ubuntu will initialize. This may take a few moments.
    • You’ll be prompted to create a new UNIX username and password. This username and password are for your Ubuntu environment.
  6. Check WSL Version:

    • To ensure that your Ubuntu installation is using WSL2, run the following command in PowerShell:

      powershell
      wsl --list --verbose
    • You should see Ubuntu listed with version 2 next to it. If it shows version 1, you can change it to WSL2 by running:

      powershell
      wsl --set-version Ubuntu-20.04 2

    (Replace Ubuntu-20.04 with the exact name of your Ubuntu installation if it's different.)

  7. Start Using Ubuntu on WSL2:

    • You can now start using Ubuntu by launching it from the Start menu or by typing wsl in PowerShell or Command Prompt.

Additional Tips

  • Update and Upgrade Ubuntu: Run sudo apt update && sudo apt upgrade in your Ubuntu terminal to keep your packages up to date.
  • Access Windows Files: You can access your Windows files from Ubuntu via the /mnt/c directory (for the C: drive).

That's it! You now have Ubuntu running on Windows 10 using WSL2, allowing you to use Linux commands and software directly within Windows.

 

* folder data: C:\Users\{user_name}\AppData\Local\Packages\CanonicalGroupLimited.Ubuntu_..

Thank you

Learn English

1. Vocabularies

- conscioutly

- deliberately



Thursday, 1 August 2024

Free up space docker

Docker resources to free up space. Here are some steps to do that:

  1. Remove Unused Volumes:

    docker volume prune
  2. Remove Unused Networks:

    docker network prune
  3. Remove Stopped Containers:

    docker container prune
  4. Remove Unused Images:

    docker image prune
  5. Remove All Unused Resources:

    docker system prune
  6. Remove All Unused Resources Including Volumes:

    docker system prune -a --volumes
  7. Check Docker Disk Usage:

    docker system df
  8. Identify and Remove Specific Unused Images: List images:

    docker images

    Remove specific image:

    docker rmi <image_id>
  9. Remove Unused Containers: List containers:

    docker ps -a

    Remove specific container:

    docker rm <container_id>
  10. Clean Docker Build Cache:

    docker builder prune

Thank you

Publish npm package

  Để publish   pav-kit  lên NPM, bạn hãy làm theo các bước dưới đây. Tôi đã tạo thêm file  index.js  để đảm bảo gói tin hợp lệ. Bước 1: Tạo ...