Change Display gamma on Linux Mint

To change the display gamma on Linux Mint, you can use the xgamma utility. Follow these steps:

Step 1: Install xgamma (if not already installed)

Open a terminal and install xgamma if it is not already installed:

sudo apt update
sudo apt install x11-xserver-utils

Step 2: Adjust the Gamma Value

You can adjust the gamma value using the xgamma command. The gamma value can be set for red, green, and blue channels individually or together. The default gamma value is usually 1.0. Adjusting this value will change the brightness of the display.

To set gamma for all channels equally:

xgamma -gamma 2.2

Step 3: Make the Changes Permanent

The changes made with xgamma will be reset after a reboot. To make them permanent, you can add the xgamma command to your startup applications or add it to your ~/.xprofile file.

Adding to Startup Applications:

  1. Open the Menu and search for “Startup Applications”.
  2. Click “Add” to create a new startup program.
  3. Enter a name (e.g., “Set Gamma”), and in the command field, enter the xgamma command you used (e.g., xgamma -gamma 1.2).
  4. Click “Add” to save the entry.

Adding to ~/.xprofile:

  1. Open a terminal.
  2. Edit the ~/.xprofile file (create it if it does not exist):
    nano ~/.xprofile
    
  3. Add the xgamma command you used (e.g., xgamma -gamma 1.2).
  4. Save the file and exit the editor (in nano, you can do this by pressing Ctrl+X, then Y, and Enter).

Now, the gamma settings should be applied every time you log in.

Step 4: Verify the Changes

To verify the current gamma settings, simply run xgamma without any arguments:

xgamma

This will display the current gamma settings for red, green, and blue channels.

By following these steps, you should be able to adjust and maintain your desired display gamma settings on Linux Mint.

Disable CPU mitigations on Linux Mint

To disable mitigations on Linux Mint, you need to edit the GRUB configuration file and add a kernel parameter. Here are the steps to do that:

  1. Open Terminal: You can open the terminal by searching for it in the application menu or by pressing Ctrl + Alt + T.
  2. Edit GRUB Configuration:
    sudo nano /etc/default/grub
    
  3. Modify the GRUB_CMDLINE_LINUX_DEFAULT Line: Find the line that starts with GRUB_CMDLINE_LINUX_DEFAULT. It usually looks something like this:
    GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"
    

    Add mitigations=off to this line. After editing, it should look like this:

    GRUB_CMDLINE_LINUX_DEFAULT="quiet splash mitigations=off"
    
  4. Update GRUB: Save the file and exit the editor (in nano, you can do this by pressing Ctrl + X, then Y, and Enter). Then update GRUB with the following command:
    sudo update-grub
    
  5. Reboot: Reboot your system for the changes to take effect:
    sudo reboot
    

After rebooting, the mitigations should be disabled. You can verify this by checking the kernel command line:

cat /proc/cmdline

You should see mitigations=off in the output.

Transform SVGs into React components using svgr as vite plugin

npm install --save-dev vite-plugin-svgr
// vite.config.js
import svgr from "vite-plugin-svgr";

export default {
  // ...
  plugins: [svgr()],
};

Then SVG files can be imported as React components:

import Logo from "./logo.svg?react";

If you are using TypeScript, there is also a declaration helper for better type inference:

/// <reference types="vite-plugin-svgr/client" />

 

References
https://www.npmjs.com/package/vite-plugin-svgr

Save userId using React Redux Toolkit

To save userId using React Redux Toolkit in TypeScript, you can follow these steps:

  1. Set up your Redux store with Redux Toolkit:

    First, you’ll need to install the required dependencies if you haven’t already:

    npm install @reduxjs/toolkit react-redux
    
  2. Create a slice for the user state:

    Create a new file userSlice.ts for the user state slice.

    // src/features/user/userSlice.ts
    import { createSlice, PayloadAction } from '@reduxjs/toolkit';
    
    interface UserState {
      userId: string | null;
    }
    
    const initialState: UserState = {
      userId: null,
    };
    
    const userSlice = createSlice({
      name: 'user',
      initialState,
      reducers: {
        setUserId(state, action: PayloadAction<string>) {
          state.userId = action.payload;
        },
        clearUserId(state) {
          state.userId = null;
        },
      },
    });
    
    export const { setUserId, clearUserId } = userSlice.actions;
    export default userSlice.reducer;
    
  3. Configure the Redux store:

    Configure your Redux store by combining the user slice reducer.

    // src/app/store.ts
    import { configureStore } from '@reduxjs/toolkit';
    import userReducer from '../features/user/userSlice';
    
    const store = configureStore({
      reducer: {
        user: userReducer,
      },
    });
    
    export type RootState = ReturnType<typeof store.getState>;
    export type AppDispatch = typeof store.dispatch;
    export default store;
    
  4. Set up the provider in your main application file:

    Wrap your application with the Redux provider.

    // src/index.tsx
    import React from 'react';
    import ReactDOM from 'react-dom';
    import { Provider } from 'react-redux';
    import store from './app/store';
    import App from './App';
    
    ReactDOM.render(
      <Provider store={store}>
        <App />
      </Provider>,
      document.getElementById('root')
    );
    
  5. Create a component to use the user state and dispatch actions:

    Here’s an example component that uses the user state and dispatches actions to set and clear the userId.

    // src/components/UserComponent.tsx
    import React, { useState } from 'react';
    import { useDispatch, useSelector } from 'react-redux';
    import { RootState } from '../app/store';
    import { setUserId, clearUserId } from '../features/user/userSlice';
    
    const UserComponent: React.FC = () => {
      const dispatch = useDispatch();
      const userId = useSelector((state: RootState) => state.user.userId);
      const [inputUserId, setInputUserId] = useState('');
    
      const handleSetUserId = () => {
        dispatch(setUserId(inputUserId));
      };
    
      const handleClearUserId = () => {
        dispatch(clearUserId());
      };
    
      return (
        <div>
          <h1>User ID: {userId}</h1>
          <input
            type="text"
            value={inputUserId}
            onChange={(e) => setInputUserId(e.target.value)}
          />
          <button onClick={handleSetUserId}>Set User ID</button>
          <button onClick={handleClearUserId}>Clear User ID</button>
        </div>
      );
    };
    
    export default UserComponent;
    
  6. Use the component in your application:

    Finally, use the UserComponent in your application.

    // src/App.tsx
    import React from 'react';
    import UserComponent from './components/UserComponent';
    
    const App: React.FC = () => {
      return (
        <div>
          <UserComponent />
        </div>
      );
    };
    
    export default App;
    

This setup allows you to manage the userId state using Redux Toolkit in a TypeScript React application.

Change Expiration Dates for access and refresh tokens in Django JWT

To change the expiration dates for access and refresh tokens when using Django Simple JWT, you can configure the settings in your Django project’s settings file (settings.py). Here’s how you can do it:

  1. Install Simple JWT (if not already installed):
    pip install djangorestframework-simplejwt
    
  2. Update settings.py to include Simple JWT settings:
    from datetime import timedelta
    
    SIMPLE_JWT = {
        'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5),  # Change this to your desired lifetime
        'REFRESH_TOKEN_LIFETIME': timedelta(days=1),  # Change this to your desired lifetime
        'ROTATE_REFRESH_TOKENS': False,
        'BLACKLIST_AFTER_ROTATION': True,
        'UPDATE_LAST_LOGIN': False,
    
        'ALGORITHM': 'HS256',
        'SIGNING_KEY': SECRET_KEY,
        'VERIFYING_KEY': None,
        'AUDIENCE': None,
        'ISSUER': None,
    
        'AUTH_HEADER_TYPES': ('Bearer',),
        'USER_ID_FIELD': 'id',
        'USER_ID_CLAIM': 'user_id',
        'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
        'TOKEN_TYPE_CLAIM': 'token_type',
    
        'JTI_CLAIM': 'jti',
    
        'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp',
        'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5),
        'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),
    }
    
  3. Update the REST_FRAMEWORK settings to use Simple JWT as the authentication class:
    REST_FRAMEWORK = {
        'DEFAULT_AUTHENTICATION_CLASSES': (
            'rest_framework_simplejwt.authentication.JWTAuthentication',
        ),
    }
    

Example

If you want to set the access token to expire in 15 minutes and the refresh token to expire in 7 days, you would update your settings.py as follows:

from datetime import timedelta

SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(minutes=15),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=7),
    'ROTATE_REFRESH_TOKENS': False,
    'BLACKLIST_AFTER_ROTATION': True,
    'UPDATE_LAST_LOGIN': False,

    'ALGORITHM': 'HS256',
    'SIGNING_KEY': SECRET_KEY,
    'VERIFYING_KEY': None,
    'AUDIENCE': None,
    'ISSUER': None,

    'AUTH_HEADER_TYPES': ('Bearer',),
    'USER_ID_FIELD': 'id',
    'USER_ID_CLAIM': 'user_id',
    'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
    'TOKEN_TYPE_CLAIM': 'token_type',

    'JTI_CLAIM': 'jti',

    'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp',
    'SLIDING_TOKEN_LIFETIME': timedelta(minutes=15),
    'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=7),
}

These settings will ensure that your access tokens expire after 15 minutes and refresh tokens expire after 7 days. Adjust the timedelta values as needed for your application’s requirements.

Add a custom claim to the JWT in Django

Adding a custom claim to the JSON Web Tokens (JWT) in Django using the django-simple-jwt library involves extending the token creation process to include additional information. Here’s how you can achieve this:

  1. Install the necessary libraries: Make sure you have djangorestframework and djangorestframework-simplejwt installed.
    pip install djangorestframework djangorestframework-simplejwt
    
  2. Update your Django settings: Configure django-simple-jwt in your settings.py file.
    INSTALLED_APPS = [
        ...
        'rest_framework',
        'rest_framework_simplejwt',
    ]
    
    REST_FRAMEWORK = {
        'DEFAULT_AUTHENTICATION_CLASSES': (
            'rest_framework_simplejwt.authentication.JWTAuthentication',
        ),
    }
    
  3. Create a custom claims serializer: Extend the TokenObtainPairSerializer to include your custom claim.
    from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
    
    class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
    
        def get_token(self, user):
            token = super().get_token(user)
    
            # Add custom claims
            token['custom_claim'] = 'custom_value'
            
            # Example: Add user's email to the token
            token['email'] = user.email
    
            return token
    
  4. Create a custom view: Use the custom serializer in your view.
    from rest_framework_simplejwt.views import TokenObtainPairView
    from .serializers import MyTokenObtainPairSerializer
    
    class MyTokenObtainPairView(TokenObtainPairView):
        serializer_class = MyTokenObtainPairSerializer
    
  5. Update your URLs: Include the custom view in your URL configuration.
    from django.urls import path
    from .views import MyTokenObtainPairView
    from rest_framework_simplejwt.views import TokenRefreshView
    
    urlpatterns = [
        path('api/token/', MyTokenObtainPairView.as_view(), name='token_obtain_pair'),
        path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
    ]
    
  6. Test your custom claim: Now when you obtain a token, it should include your custom claim.

Create a Management Command to add User in Django

If you want to create a user in Django who does not have access to the admin panel, you can use the create_user method instead of createsuperuser. The create_user method creates a regular user account without admin privileges.

You can create a custom management command to add users. Create a new file management/commands/create_user.py in one of your apps (e.g., myapp):

# myapp/management/commands/create_user.py

from django.core.management.base import BaseCommand
from django.contrib.auth import get_user_model

class Command(BaseCommand):
    help = 'Create a regular user'

    def add_arguments(self, parser):
        parser.add_argument('username', type=str)
        parser.add_argument('email', type=str)
        parser.add_argument('password', type=str)

    def handle(self, *args, **kwargs):
        username = kwargs['username']
        email = kwargs['email']
        password = kwargs['password']

        User = get_user_model()
        user = User.objects.create_user(username=username, email=email, password=password)
        user.save()

        self.stdout.write(self.style.SUCCESS(f'User {username} created successfully'))

After creating this file, you can run the management command:

python manage.py create_user username [email protected] password

Implementing JWT (JSON Web Token) authentication in Django

Step 1: Install Necessary Packages

First, you need to install the required packages. For JWT authentication in Django, you can use the djangorestframework-simplejwt package.

pip install djangorestframework djangorestframework-simplejwt

Step 2: Configure Django Settings

Add rest_framework and rest_framework_simplejwt to your INSTALLED_APPS in settings.py.

INSTALLED_APPS = [
    ...
    'rest_framework',
    'rest_framework_simplejwt',
    ...
]

Next, configure the REST framework to use JWT for authentication:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ),
}

Step 3: Set Up URLs

In your urls.py, include the views for obtaining and refreshing tokens.

from django.urls import path
from rest_framework_simplejwt.views import (
    TokenObtainPairView,
    TokenRefreshView,
)

urlpatterns = [
    ...
    path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
    ...
]

Step 4: Create Views and Protect Endpoints

Create views and protect your endpoints using the @api_view decorator and the permission_classes attribute.

from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def protected_view(request):
    return Response({'message': 'This is a protected view'})

Step 5: Testing

To test your JWT implementation, you can use tools like Postman or CURL to interact with your API. First, obtain a token by making a POST request to /api/token/ with your username and password.

curl -X POST http://localhost:8000/api/token/ -d "username=yourusername&password=yourpassword"

This will return a response containing the access and refresh tokens. Use the access token to access protected endpoints by including it in the Authorization header.

curl -H "Authorization: Bearer <your_access_token>" http://localhost:8000/protected-endpoint/

Example Project Structure

Here is a basic project structure for reference:

myproject/
    manage.py
    myproject/
        __init__.py
        settings.py
        urls.py
        wsgi.py
    myapp/
        __init__.py
        views.py
        models.py
        urls.py

Example settings.py

# settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'rest_framework_simplejwt',
    'myapp',
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ),
}

# Additional settings...

Example urls.py

# urls.py

from django.contrib import admin
from django.urls import path
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
from myapp.views import protected_view

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
    path('protected/', protected_view, name='protected_view'),
]

How It Works

The TokenObtainPairView and TokenRefreshView views provided by djangorestframework-simplejwt are already implemented and ready to use. You do not need to create additional views for these endpoints. They are automatically generated when you include them in your urls.py.

  • TokenObtainPairView: This view is used to obtain a pair of access and refresh tokens. You POST to this endpoint with user credentials (username and password) to get the tokens.
  • TokenRefreshView: This view is used to refresh the access token. You POST to this endpoint with a valid refresh token to get a new access token.

Example Requests

  1. Obtain Token Pair:
    curl -X POST http://127.0.0.1:8000/api/token/ -d "username=myusername&password=mypassword"
    

    This will return a JSON response with access and refresh tokens.

  2. Refresh Token:
    curl -X POST http://127.0.0.1:8000/api/token/refresh/ -d "refresh=your_refresh_token"
    

    This will return a new access token.

Example Response

  • TokenObtainPairView Response:
    {
        "refresh": "your_refresh_token",
        "access": "your_access_token"
    }
    
  • TokenRefreshView Response:
    {
        "access": "your_new_access_token"
    }
    

With these steps, you can seamlessly integrate JWT authentication into your Django application using djangorestframework-simplejwt. There is no need to create additional views for these token endpoints as they are provided out of the box by the package.

Optimize Intel WiFi Driver Settings in Linux

# Disable 802.11n to potentially improve stability
options iwlwifi 11n_disable=1

# Disable hardware encryption to offload encryption to the CPU
options iwlwifi swcrypto=0

# Disable Bluetooth coexistence to potentially improve WiFi performance
options iwlwifi bt_coex_active=0

# Disable power saving features to improve performance at the cost of higher power consumption
options iwlwifi power_save=0

# Disable Unscheduled Automatic Power Save Delivery (U-APSD)
options iwlwifi uapsd_disable=1

# Set power scheme to maximum performance
options iwlmvm power_scheme=1

# Enable antenna aggregation to potentially improve WiFi performance
options iwlwifi 11n_disable=8

To apply these settings, you would typically place them in a configuration file under /etc/modprobe.d/. For example, you could create a file called iwlwifi.conf:

sudo nano /etc/modprobe.d/iwlwifi.conf

Then, paste the configuration options into this file and save it.

Finally, to apply these changes, you will need to reload the iwlwifi module:

sudo modprobe -r iwlwifi
sudo modprobe iwlwifi

Or, you can simply reboot your system for the changes to take effect.

Django REST framework with function based view

Setup

  1. Install Django and Django REST framework:
    pip install django djangorestframework
    
  2. Create a new Django project:
    django-admin startproject myproject
    cd myproject
    
  3. Create a new Django app:
    python manage.py startapp myapp
    
  4. Add the app and DRF to INSTALLED_APPS in myproject/settings.py:
    INSTALLED_APPS = [
        ...
        'rest_framework',
        'myapp',
    ]
    

Models

Let’s define a simple model in myapp/models.py:

from django.db import models

class Item(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField()

    def __str__(self):
        return self.name

Run migrations to create the database table:

python manage.py makemigrations
python manage.py migrate

Serializers

Create a serializer for the Item model in myapp/serializers.py:

from rest_framework import serializers
from .models import Item

class ItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = Item
        fields = '__all__'

Views

Create function-based views in myapp/views.py:

from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from .models import Item
from .serializers import ItemSerializer

@api_view(['GET', 'POST'])
def item_list(request):
    if request.method == 'GET':
        items = Item.objects.all()
        serializer = ItemSerializer(items, many=True)
        return Response(serializer.data)
    elif request.method == 'POST':
        serializer = ItemSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

@api_view(['GET', 'PUT', 'DELETE'])
def item_detail(request, pk):
    try:
        item = Item.objects.get(pk=pk)
    except Item.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = ItemSerializer(item)
        return Response(serializer.data)
    elif request.method == 'PUT':
        serializer = ItemSerializer(item, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    elif request.method == 'DELETE':
        item.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

URLs

Define the API endpoints in myapp/urls.py:

from django.urls import path
from . import views

urlpatterns = [
    path('items/', views.item_list),
    path('items/<int:pk>/', views.item_detail),
]

Include the app’s URLs in the project’s urls.py:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('myapp.urls')),
]

Testing the API

Run the development server:

python manage.py runserver

You can now test your API using tools like curl, Postman, or a web browser:

  • GET all items: http://127.0.0.1:8000/api/items/
  • POST a new item: http://127.0.0.1:8000/api/items/ (with JSON data)
  • GET a single item: http://127.0.0.1:8000/api/items/<id>/
  • PUT to update an item: http://127.0.0.1:8000/api/items/<id>/ (with JSON data)
  • DELETE an item: http://127.0.0.1:8000/api/items/<id>/