Merge branch 'main' into jquery

This commit is contained in:
FireIsGood committed 2024-12-04 05:28:55 -08:00
commit 155f549b4d
7 files changed
+1262 -152

No files matched your search

+2 -1
View File
@@ -11,4 +11,5 @@ RUN apk add --no-cache nginx && mkdir -p /run/nginx
COPY --from=build /usr/share/nginx/html/ /usr/share/nginx/html/
COPY --from=build /etc/nginx/nginx.conf /etc/nginx/nginx.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
HEALTHCHECK --interval=1s --timeout=3s CMD wget -q -O - http://localhost:80 || exit 1
CMD ["nginx", "-g", "daemon off;"]
+41 -41
View File
@@ -78,7 +78,7 @@ const int BIRTHYEAR = 1980;
```c
// this is a comment
printf("Hello World!"); // Can comment anywhere in file
printf("Hello World!\n"); // Can comment anywhere in file
/*Multi-line comment, print Hello World!
to the screen, it's awesome */
@@ -87,12 +87,12 @@ to the screen, it's awesome */
### Print text
```c
printf("I am learning C.");
printf("I am learning C.\n");
int testInteger = 5;
printf("Number = %d", testInteger);
printf("Number = %d\n", testInteger);
float f = 5.99; // floating point number
printf("Value = %f", f);
printf("Value = %f\n", f);
short a = 0b1010110; // binary number
int b = 02713; // octal number
@@ -183,7 +183,7 @@ printf("%s", greetings);
```
**NOTE**: String literals might be stored in read-only section of memory. Modifying a string literal invokes undefined
behavior. You can't modify it.!
behavior. You can't modify it!
`C` **does not** have a String type, use `char` type and create an `array` of characters
@@ -192,18 +192,18 @@ behavior. You can't modify it.!
```c
int time = 20;
if (time < 18) {
printf("Goodbye!");
printf("Goodbye!\n");
} else {
printf("Good evening!");
printf("Good evening!\n");
}
// Output -> "Good evening!"
int time = 22;
if (time < 10) {
printf("Good morning!");
printf("Good morning!\n");
} else if (time < 20) {
printf("Goodbye!");
printf("Goodbye!\n");
} else {
printf("Good evening!");
printf("Good evening!\n");
}
// Output -> "Good evening!"
```
@@ -212,7 +212,7 @@ if (time < 10) {
```c
int age = 20;
(age > 19) ? printf("Adult") : printf("Teenager");
(age > 19) ? printf("Adult\n") : printf("Teenager\n");
```
### Switch
@@ -221,10 +221,10 @@ int age = 20;
int day = 4;
switch (day) {
case 3: printf("Wednesday"); break;
case 4: printf("Thursday"); break;
case 3: printf("Wednesday\n"); break;
case 4: printf("Thursday\n"); break;
default:
printf("Weekend!");
printf("Weekend!\n");
}
// output -> "Thursday" (day 4)
```
@@ -403,13 +403,13 @@ switch(day) {
int myNum;
// Ask the user to enter a number
printf("Please enter a number: \n");
printf("Enter a number: ");
// Get and save the number entered by the user
scanf("%d", &myNum);
// Output the number entered by the user
printf("The number you entered: %d", myNum);
printf("The number you entered: %d\n", myNum);
```
### User input string
@@ -418,11 +418,11 @@ printf("The number you entered: %d", myNum);
// create a string
char firstName[30];
// Ask the user to enter some text
printf("Enter your name: \n");
printf("Enter your name: ");
// get and save the text
scanf("%s", &firstName);
// output text
printf("Hello %s.", firstName);
printf("Hello %s.\n", firstName);
```
### memory address
@@ -442,10 +442,10 @@ To access it, use the reference operator (`&`)
```c
int myAge = 43; // an int variable
printf("%d", myAge); // output the value of myAge(43)
printf("%d\n", myAge); // output the value of myAge(43)
// Output the memory address of myAge (0x7ffe5367e044)
printf("%p", &myAge);
printf("%p\n", &myAge);
```
### pointer variable {.col-span-2}
@@ -716,12 +716,12 @@ printf("%c\n", myLetter);
```c
#include <stdio.h>
int main() {
printf("File :%s\n", __FILE__);
printf("Date :%s\n", __DATE__);
printf("Time :%s\n", __TIME__);
printf("Line :%d\n", __LINE__);
printf("ANSI :%d\n", __STDC__);
int main(void) {
printf("File: %s\n", __FILE__);
printf("Date: %s\n", __DATE__);
printf("Time: %s\n", __TIME__);
printf("Line: %d\n", __LINE__);
printf("ANSI: %d\n", __STDC__);
}
```
@@ -764,7 +764,7 @@ When you need to convert a macro parameter to a string constant, use the string
```c
#include <stdio.h>
#define tokenpaster(n) printf ("token" #n " = %d", token##n)
#define tokenpaster(n) printf ("Token " #n " = %d\n", token##n)
int main(void) {
int token34 = 40;
@@ -823,7 +823,7 @@ int main(void) {
```c
int main(void) {
printf("Hello World!");
printf("Hello World!\n");
return 0;
}
@@ -855,7 +855,7 @@ int main() {
}
void myFunction() {// Function definition
printf("Good evening!");
printf("Good evening!\n");
}
```
@@ -864,7 +864,7 @@ void myFunction() {// Function definition
```c
// create function
void myFunction() {
printf("Good evening!");
printf("Good evening!\n");
}
int main() {
@@ -918,7 +918,7 @@ int myFunction(int x) {
}
int main() {
printf("Result: %d", myFunction(3));
printf("Result: %d\n", myFunction(3));
return 0;
}
// output 8 (5 + 3)
@@ -932,10 +932,10 @@ int myFunction(int x, int y) {
}
int main() {
printf("Result: %d", myFunction(5, 3));
printf("Result: %d\n", myFunction(5, 3));
// store the result in a variable
int result = myFunction(5, 3);
printf("Result = %d", result);
printf("Result = %d\n", result);
return 0;
}
@@ -950,7 +950,7 @@ int sum(int k);
int main() {
int result = sum(10);
printf("%d", result);
printf("%d\n", result);
return 0;
}
@@ -970,10 +970,10 @@ int sum(int k) {
#include <math.h>
void main(void) {
printf("%f", sqrt(16)); // square root
printf("%f", ceil(1.4)); // round up (round)
printf("%f", floor(1.4)); // round down (round)
printf("%f", pow(4, 3)); // x(4) to the power of y(3)
printf("%f\n", sqrt(16)); // square root
printf("%f\n", ceil(1.4)); // round up (round)
printf("%f\n", floor(1.4)); // round down (round)
printf("%f\n", pow(4, 3)); // x(4) to the power of y(3)
}
```
@@ -1028,13 +1028,13 @@ int main() {
struct myStructure s1;
strcpy(s1. myString, "Some text");
// print value
printf("my string: %s", s1.myString);
printf("My string: %s\n", s1.myString);
return 0;
}
```
Assigning values ​​to strings using the `strcpy` function
Assigning values to strings using the `strcpy` function
### Accessing structure members {.row-span-2}
@@ -1100,7 +1100,7 @@ struct myStructure s1 = {
s1.myNum = 30;
s1.myLetter = 'C';
// print value
printf("%d %c %s",
printf("%d %c",
s1.myNum,
s1.myLetter);
```
+559 -107
View File
@@ -111,7 +111,15 @@ Migrate: Will read the migrations files and create the actual database and table
### Configuration settings
<!-- TODO: split this section up (I am not a Django dev) -->
##### Project base templates directory and Apps templates directory:
- create folder project/templates
- create folder appfolder/templates/appname
##### Create Static folder in base root and separate for apps:
- project_name\static\root
- app_name\static\app_name
```python
# Add app to settings.py
@@ -120,27 +128,18 @@ INSTALLED_APPS = [
'app_name.apps.App_nameConfig',
]
# App templates folder
create folder appfolder/templates/appname
# Project templates folder:
create folder projectname/templates
# settings.py template config
# template directory config
Project templates settings.py:
TEMPLATES = [
{ …
'DIRS': [BASE_DIR / 'templates'],
… }
# Create Static folder:
project_name\static\
# Static folder (settings.py):
# Static folder:
STATIC_URL = '/static/'
STATICFILES_DIRS = [ BASE_DIR / 'static' ]
STATIC_ROOT = 'static_root'
# Media folder (settings.py):
# Media folder:
MEDIA_URL = '/media/'
STATICFILES_DIRS = (
(BASE_DIR / 'static'),
@@ -205,7 +204,7 @@ CSRF_COOKIE_SECURE = True
```python
# models.py
# The id fields is automatically created by Django
# The id fields is automaticly created by Django
# for each model that why it's not show below
from django.db import models
@@ -221,9 +220,9 @@ class Customer(models.Model)
img = models.ImageField(upload_to ='uploads/')
# Select Field (return value, display value)
TYPE_CHOICES = (
('Customer', 'Customer'),
('Supplier', 'Supplier'),
('Student', 'Student'),
('Customer', _('Customer')),
('Supplier', _('Supplier')),
('Student', _('Student')),
)
type = models.CharField(choices=TYPE_CHOICES)
@@ -231,7 +230,8 @@ class Customer(models.Model)
verbose_name = "Customer"
verbose_name_plural = "Customers"
def __str__(self): # Model string representation
# Model string representation
def __str__(self):
return self.name
# the URL that points to a resource or page on your website
@@ -239,7 +239,34 @@ class Customer(models.Model)
return reverse("customer_detail", kwargs={"pk": self.pk})
```
### Relationship between models
#### We can also use this method to define the ChoiceField value.
```python
class Customer(models.Model)
class TypeList(models.IntegerChoices):
customer = 1, _('Customer'))
supplier = 2, _('Supplier'))
student = 3, _('Student'))
.
.
.
type = models.CharField(choices=TypeList.choices, default=1)
```
#### To access the ChoiceField value in the template, we need to do the following in the template:
- In Django templates you can use the "`get_FOO_display()`" method, that will return the readable alias for the field, where `'FOO'` is the name of the field.
- If the choices are stored in the variable `CHOICES` and the model field storing the selected choice is `'type'` then you can directly use
```html
<!-- Here, X is the model instance -->
{{ X.get_type_display }}
<!-- You can even use this method to display its translation. -->
{% trans X.get_type_display %}
```
#### Relationship between models
```python
# One-to-Many: (use double quotes if the entity is not yet declare) ex. "Supplier"
@@ -424,7 +451,8 @@ def show(request, id):
return render(request, 'appfolder/show.html', {'post': post})
def create(request):
form = PostForm(request.POST or None)
form = PostForm(request.POST or None, request.FILES or None)
# When the form contains an image or file field, we should use request.FILES
if form.is_valid():
# optionally we can access form data with form.cleaned_data['first_name']
post = form.save(commit=False)
@@ -436,7 +464,7 @@ def create(request):
def edit(request, id):
post = Post.objects.get(id=id)
form = PostForm(request.POST or None, instance=post)
form = PostForm(request.POST or None, request.FILES or None, instance=post)
if form.is_valid():
form.save()
return redirect('/posts')
@@ -526,57 +554,107 @@ path('<int:pk>/update/', PostsUpdateView.as_view(), name='post-update')
Templates are store in `project_folder/templates` or in your <code>app_folder/templates/app_name/\*.html</code>
<!-- TODO: Fix this, as it is not correctly escaped -->
```python
```html
<!-- Extend from another template -->
<!-- can use the same parts of your HTML for different template -->
{% extends 'base.html' %}
{% block content %}
{% endblock %}
<!-- A part of the parent template that is defined and is replaced by a part in the child template -->
{% block contents %} {% endblock contents %}
<!-- include template-->
{% include 'partials/header.html' %}
# include template with One or More Parameters
<!-- include template with One or More Parameters -->
{% include 'body.html' with key1=value1 key2=value2 %}
<!-- If statement in template -->
{% if user.username = 'Mike' %}
<p>Hello Admin</p>
<p>Hello Admin</p>
{% elif user.username = 'john' %}
<p>Hello John Doe</p>
<p>Hello John Doe</p>
{% else %}
<p>Hello User</p>
<p>Hello User</p>
{% endif %}
<!-- for loop in template -->
{% for product in products %}
<p>product number: {{ forloop.counter0 }}<p>
<p>The product name is {{ product }}<p>
{% endfor %}
<p>row: {{ forloop.counter }} # starting index 1 {{ forloop.counter0 }} # starting index 0</p>
<p>The product name is {{ product.name }}</p>
<p></p>
<p>The product name is {{ product.price }}</p>
<p>
{% endfor %}
# Access to the variable in the template
{{ var_name }}
<!-- Access to the variable in the template -->
{{ var_name }}
# Template variables formatting
{{ title | lower }}
{{ blog.post | truncatwords:50 }}
{{ order.date | date:"D M Y" }}
{{ list_items | slice:":3" }}
{{ total | default:"nil" }}
<!-- Template variables formating -->
{{ title | lower }} {{ blog.post | truncatwords:50 }} {{ order.date | date:"D M Y" }} {{ list_items | slice:":3" }} {{
total | default:"nil" }}
# Current path (ex. posts/1/show)
{{ request.path }}
<!-- Current path (ex. posts/1/show) -->
{{ request.path }}
# URL by name with param
{% url 'posts.delete' id=post.id %}
<!-- URL by name with param -->
{% url 'posts.delete' id=post.id %}
# Use static in template:
{% load static %}
{% static 'css/main.css' %}
<!-- Use static in template: -->
{% load static %} {% static 'css/main.css' %}
# Define the variable in the template
{% with name="World" %}
<html>
<div>Hello {{ name }}!</div>
</html>
{% endwith %}
<!-- Define the variable in the template -->
{% with name="World" %}
<html>
<div>Hello {{ name }}!</div>
</html>
{% endwith %}
<!-- Template translate text -->
{% load i18n %}
<title>{% trans "This is the title." %}</title>
<!-- Use variable translate in the template -->
<title>{% trans object.title %}</title>
<!-- Define the list in the template -->
<input type="number" {% if product.unit in 'kg,milligram,milliliter' %} step="0.01" {% else %} step="1" {% endif %}>
<!-- Safely Pass Data to JavaScript in a Django Template: -->
<!--+ Use data attributes for simple values -->
<script data-username="{{ username }}">
const data = document.currentScript.dataset;
const username = data.username;
</script>
<!-- + Separate script files: can use document.currentScript for separate script files -->
<script src="{% static 'index.js' %}" data-username="{{ username }}"></script>
<!-- + Case conversion -->
<script src="{% static 'index.js' %}" data-full-name="{{ full_name }}"></script>
<!-- Read it in JavaScript as fullName: -->
<script>
const data = document.currentScript.dataset;
const fullName = data.fullName;
</script>
<!-- + Non-string types -->
<script src="{% static 'index.js' %}" data-follower-count="{{ follower_count }}"></script>
<!-- parseInt() to convert this value from a string: -->
<script>
const data = document.currentScript.dataset;
const followerCount = parseInt(data.followerCount, 10);
</script>
<!-- + There’s no limit: A <script> can have as many data attributes as you like: -->
<script
src="{% static 'index.js' %}"
defer
data-settings-url="{% url 'settings' %}"
data-configuration-url="{% url 'configuration' %}"
data-options-url="{% url 'options' %}"
data-preferences-url="{% url 'preferences' %}"
data-setup-url="{% url 'setup' %}"
></script>
</p>
```
### Custom Template Tags and Filters
@@ -594,7 +672,7 @@ app_name/
- And in your template you would use the following:
```python
```html
{% load basetags %}
```
@@ -673,7 +751,8 @@ def site_email(request):
'OPTIONS': {
'context_processors': [
…
'app_name.context_processors.site_email', # <- New context processor here
'app_name.context_processors.site_email',
# New context processor here
…
],
… },
@@ -798,30 +877,47 @@ class ArticleForm(ModelForm):
help_texts = {
'name': 'Enter Your First Name',
}
```
# Render form in template
<form method=“post” action=“” novalidate>
{% csrf_token %}
{{ form }}
<button type="submit">Submit</button>
```html
<!-- Render form in template -->
<form method="“post”" action="“”" novalidate>
{% csrf_token %} {{ form }}
<button type="submit">Submit</button>
</form>
```
# Bootstrap (pip install django-crispy-forms + installed_apps: 'crispy_forms')
{% load crispy_forms_tags %}
{{ form|crispy }}
{{ form.email|as_crispy_field }}
- NOTE: If the form contains a file field, your form MUST contain `enctype="multipart/form-data"`, eg:
# crispy-tailwind
```html
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">{% trans 'Submit' %}</button>
</form>
```
##### A Tailwind CSS template pack for the wonderful django-crispy-forms.
```bash
pip install crispy-tailwind
```
```python
# settings.py
INSTALLED_APPS = (
...
"crispy_forms",
"crispy_tailwind",
...
)
CRISPY_ALLOWED_TEMPLATE_PACKS = 'tailwind'
CRISPY_TEMPLATE_PACK = 'tailwind'
```
# template usage
{% load tailwind_filters %}
{{ form|crispy}}
```html
<!-- template usage -->
{% load tailwind_filters %} {{ form|crispy }}
```
### Form Validation
@@ -849,20 +945,17 @@ def clean(self):
### Displaying messages
<!-- TODO: Fix this, as it is not correctly escaped -->
```python
messages.success(request, 'Login successful')
messages.error(request, 'Login error')
# Message tags
# debug, info, success, warning and error
# Display flash in template
{% if messages %}
{% for message in messages %}
{% message %}
{% message.tags %}
messages.success(request, 'Login successful')
messages.error(request, 'Login error')
```
```html
<!-- Display flash messages in template -->
{% if messages %} {% for message in messages %} {% message %} {% message.tags %} {% endfor %} {% endif %}
```
## User Model
@@ -898,20 +991,20 @@ from django.contrib.auth.views import LoginView
path('login/', LoginView.as_view(), name='login')
# By default the LoginView will try to open a template name 'registration/login.html' and send a login form with it.
```
# Create a template under registration/login.html
{% extends "base.html" %}
{% block content %}
<form method="post">
{% csrf_token %}
{{ form }}
<button type="submit">Login</button>
</form>
```html
<!-- Create a template under registration/login.html -->
{% extends "base.html" %} {% block content %}
<form method="post">
{% csrf_token %} {{ form }}
<button type="submit">Login</button>
</form>
{% endblock content %}
# When user click the Login button, the LoginView will try to authenticate the user with the form username ans password.
<!-- When user click the Login button, the LoginView will try to authenticate the user with the form username ans password -->
# If successful il will then login the user and redirect to LOGIN_REDIRECT_URL specified in your settings.py
<!-- If successful il will then login the user and redirect to LOGIN_REDIRECT_URL specified in your settings.py -->
```
#### Authentication : LogoutView
@@ -943,23 +1036,26 @@ class SignupView(CreateView):
def get_success_url(self):
return reverse("login")
```
# Create template: registration/signup.html
{% extends "base.html" %}
{% block content %}
<form method="post">
{% csrf_token %}
{{ form }}
<button type="submit">Signup</button>
</form>
```html
<!-- Create template: registration/signup.html -->
{% extends "base.html" %} {% block content %}
<form method="post">
{% csrf_token %} {{ form }}
<button type="submit">Signup</button>
</form>
{% endblock content %}
```
```python
# Add a url to reach that view
from posts.views import SignupView
path('signup/', SignupView.as_view(), name='signup')
```
```python
# Optional: Customize the UserCreationForm
# (forms.py)
from django.contrib.auth import get_user_model
@@ -983,16 +1079,14 @@ urlpatterns += path('', include('django.contrib.auth.urls'))
#### Template Authentication helpers
```python
# Authentication links
```html
<!-- Authentication links -->
<a href="{% url 'login' %}">Login</a>
<a href="{% url 'signup' %}">Signup</a>
<a href="{% url 'logout' %}">Logout</a>
# Check if user login
{% if request.user.is_authenticated %}
Logged in as: {{ request.user.username }}
{% endif %}
<!-- Check if user login -->
{% if request.user.is_authenticated %} Logged in as: {{ request.user.username }} {% endif %}
```
#### Authorization: LoginRequiredMixin and login_required
@@ -1052,7 +1146,8 @@ user.set_password('raw password')
```python
# Add accounts app to settings.py
INSTALLED_APPS = [ … ,
'accounts.apps.AccountsConfi', ]
'accounts.apps.AccountsConfig',
]
.
.
.
@@ -1751,3 +1846,360 @@ command. We can also take a look at the program output with the `tail` command.
```bash
~$ supervisor> quit
```
## Deployment Django in Server
### Set Up Django with Postgres, Nginx, and Gunicorn on Ubuntu server
#### Step 1 — Installing the Packages from the Ubuntu Repositories
```bash
sudo apt update
sudo apt install python3-venv python3-dev libpq-dev postgresql postgresql-contrib nginx curl
```
#### Step 2 — Creating the PostgreSQL Database and User
```bash
sudo -u postgres psql
```
- First, create a database for your project:
```bash
postgres=# CREATE DATABASE myproject;
```
- Next, create a database user for our project. Make sure to select a secure password:
```bash
postgres=# CREATE USER myprojectuser WITH PASSWORD 'password';
```
- Afterwards, you’ll modify a few of the connection parameters for the user that you just created
```bash
postgres=# ALTER ROLE myprojectuser SET client_encoding TO 'utf8';
postgres=# ALTER ROLE myprojectuser SET default_transaction_isolation TO 'read committed';
postgres=# ALTER ROLE myprojectuser SET timezone TO 'UTC';
```
- Now, you can give the new user access to administer the new database:
```bash
postgres=# GRANT ALL PRIVILEGES ON DATABASE myproject TO myprojectuser;
```
- When you are finished, exit out of the PostgreSQL prompt by typing:
```bash
postgres=# \q
```
#### Step 3 — Creating a Python Virtual Environment for your Project
- thin the project directory, create a Python virtual environment by typing:
```bash
mkdir ~/myprojectdir
cd ~/myprojectdir
```
- Within the project directory, create a Python virtual environment by typing:
```bash
python3 -m venv myprojectenv
```
- Before installing your project’s Python requirements, you will need to activate the virtual environment. You can do
that by typing:
```bash
source myprojectenv/bin/activate
```
- With your virtual environment active, install Django, Gunicorn, and the psycopg2 PostgreSQL adaptor with the local
instance of pip
```bash
(myprojectenv)$ pip install django gunicorn psycopg2-binary
```
#### Step 4 — Creating and Configuring a New Django Project
- With your Python components installed, you can now create the actual Django project files.
```bash
(myprojectenv)$ django-admin startproject myproject ~/myprojectdir
```
- The first thing you should do with your newly created project files is adjust the settings. Open the settings file in
your text editor:
```bash
(myprojectenv)$ nano ~/myprojectdir/myproject/settings.py
```
- Start by locating the ALLOWED_HOSTS directive.
```python
# ~/myprojectdir/myproject/settings.py
ALLOWED_HOSTS = ['your_server_domain_or_IP', 'second_domain_or_IP', . . ., 'localhost']
```
- Next, find the section that configures database access. It will start with DATABASES. The configuration in the file is
for a SQLite database.
```python
. . .
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'myproject',
'USER': 'myprojectuser',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': '',
}
}
. . .
```
- Next, move down to the bottom of the file and add a setting indicating where the static files should be placed.
```python
. . .
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
import os
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
```
#### Step 5 — Completing Initial Project Setup
- Now, you can migrate the initial database schema to our PostgreSQL database using the management script:
```bash
(myprojectenv)$ ~/myprojectdir/manage.py makemigrations
(myprojectenv)$ ~/myprojectdir/manage.py migrate
```
- Create an administrative user for the project by typing:
```bash
(myprojectenv)$ ~/myprojectdir/manage.py createsuperuser
```
- You can collect all of the static content into the directory location that you configured by typing:
```bash
(myprojectenv)$ ~/myprojectdir/manage.py collectstatic
```
#### Step 6 — Testing Gunicorn’s Ability to Serve the Project
```bash
(myprojectenv)$ cd ~/myprojectdir
(myprojectenv)$ gunicorn --bind 0.0.0.0:8000 myproject.wsgi
```
- You’re now finished configuring your Django application. You can back out of our virtual environment by typing:
```bash
(myprojectenv)$ deactivate
```
#### Step 7 — Creating systemd Socket and Service Files for Gunicorn You have tested tha
```bash
sudo nano /etc/systemd/system/gunicorn.socket
```
- Inside, you will create a `[Unit]` section to describe the socket, a `[Socket]` section to define the socket location,
and an `[Install]` section to make sure the socket is created at the right time:
```bash /etc/systemd/system/gunicorn.socket
[Unit]
Description=gunicorn socket
[Socket]
ListenStream=/run/gunicorn.sock
[Install]
WantedBy=sockets.target
```
- Save and close the file when you are finished.
- Next, create and open a systemd service file for Gunicorn with sudo privileges in your text editor. The service
filename should match the socket filename with the exception of the extension:
```bash
sudo nano /etc/systemd/system/gunicorn.service
```
```bash
[Unit]
Description=gunicorn daemon
Requires=gunicorn.socket
After=network.target
[Service]
User=sammy
Group=www-data
WorkingDirectory=/home/sammy/myprojectdir
ExecStart=/home/sammy/myprojectdir/myprojectenv/bin/gunicorn \
--access-logfile - \
--workers 3 \
--bind unix:/run/gunicorn.sock \
myproject.wsgi:application
[Install]
WantedBy=multi-user.target
```
- You can now start and enable the Gunicorn socket. This will create the socket file at /run/gunicorn.sock now and at
boot. When a connection is made to that socket, systemd will automatically start the gunicorn.service to handle it
```bash
sudo systemctl start gunicorn.socket
sudo systemctl enable gunicorn.socket
```
#### Step 8 — Checking for the Gunicorn Socket File
- Check the status of the process to find out whether it was able to start:
```bash
sudo systemctl status gunicorn.socket
```
- Next, check for the existence of the gunicorn.sock file within the /run directory:
```bash
file /run/gunicorn.sock
```
#### Step 9 — Testing Socket Activation
```bash
sudo systemctl status gunicorn
```
- To test the socket activation mechanism, you can send a connection to the socket through curl by typing:
```bash
curl --unix-socket /run/gunicorn.sock localhost
```
- You should receive the HTML output from your application in the terminal. This indicates that Gunicorn was started and
was able to serve your Django application. You can verify that the Gunicorn service is running by typing:
```bash
sudo systemctl status gunicorn
```
- Check your /etc/systemd/system/gunicorn.service file for problems. If you make changes to the
/etc/systemd/system/gunicorn.service file, reload the daemon to reread the service definition and restart the Gunicorn
process by typing
```bash
sudo systemctl daemon-reload
sudo systemctl restart gunicorn
```
#### Step 10 — Configure Nginx to Proxy Pass to Gunicorn
- Start by creating and opening a new server block in Nginx’s sites-available directory:
```bash
sudo nano /etc/nginx/sites-available/myproject
```
```bash
server {
listen 80;
server_name server_domain_or_IP;
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
alias /home/sammy/myprojectdir/staticfiles/;
}
location /media {
autoindex on;
alias /home/sammy/myprojectdir/media/;
}
location / {
include proxy_params;
proxy_pass http://unix:/run/gunicorn.sock;
}
}
```
- Save and close the file when you are finished. Now, you can enable the file by linking it to the sites-enabled
directory:
```bash
sudo ln -s /etc/nginx/sites-available/myproject /etc/nginx/sites-enabled
```
- Test your Nginx configuration for syntax errors by typing:
```bash
sudo nginx -t
```
- If no errors are reported, go ahead and restart Nginx by typing:
```bash
sudo systemctl restart nginx
```
- you need to open up your firewall to normal traffic on port 80
```bash
sudo ufw allow 'Nginx Full'
```
You should now be able to go to your server’s domain or IP address to view your application.
#### Step 11 — Troubleshooting Nginx and Gunicorn
- Nginx Is Showing the Default Page Instead of the Django Application
```bash
sudo tail -F /var/log/nginx/error.log
```
- Django Is Displaying: “could not connect to server: Connection refused”
```bash
sudo systemctl status postgresql
```
- If it is not, you can start it and enable it to start automatically at boot (if it is not already configured to do so)
by typing:
```bash
sudo systemctl start postgresql
sudo systemctl enable postgresql
```
If you change Gunicorn socket or service files, reload the daemon and restart the process by typing:
```bash
sudo systemctl daemon-reload
sudo systemctl restart gunicorn.socket gunicorn.service
```
If you change the Nginx server block configuration, test the configuration and then Nginx by typing:
```bash
sudo nginx -t && sudo systemctl restart nginx
```
+2 -2
View File
@@ -89,8 +89,8 @@ intro: |
| `Ctrl` `Shift` `W` | Close Window |
| `Ctrl` `Tab` | Cycle through Tabs in Recently Used Order |
| `Ctrl` `Q` | Quit |
| `Ctrl` `Alt` `Left` | Go one Tab to the Left |
| `Ctrl` `Alt` `Right` | Go one Tab to the Right |
| `Ctrl` `PgUp` | Go one Tab to the Left |
| `Ctrl` `PgDown` | Go one Tab to the Right |
| `Ctrl` `Shift` `PgUp` | Move Tab Left |
| `Ctrl` `Shift` `PgDown` | Move Tab Right |
| `Ctrl` `Shift` `Home` | Move Tab in focus to start |
+192
View File
@@ -0,0 +1,192 @@
---
title: Unreal Engine
date: 2024-10-24 21:12:26
tags:
- unreal
- engine
categories:
- Keyboard Shortcuts
intro:
A visual cheat-sheet for many keyboard shortcuts found in Unreal Engine 5
---
## Level Editor
### Viewport Transformation
| Shortcut | Action |
| --------------------- | --------------------------- |
| `W` | Translate |
| `E` | Rotate |
| `R` | Scale |
| `Space Bar` | Toggle Transform Mode |
| `[` | Decrease Position Grid Size |
| `]` | Increase Position Grid Size |
| `Shift` `[` | Decrease Rotation Grid Size |
| `Shift` `]` | Increase Rotation Grid Size |
{.shortcuts}
### View Modes
| Shortcut | Action |
| --------------------- | --------------------- |
| `Alt` `2` | Wireframe |
| `Alt` `3` | Unlit |
| `Alt` `4` | Lit |
| `Alt` `5` | Detail Lighting |
| `Alt` `6` | Lighting Only |
| `Alt` `7` | Light Complexity |
| `Alt` `8` | Shader Complexity |
| `Alt` `0` | Lightmap Density |
{.shortcuts}
### Level Editor General {.row-span-2}
| Shortcut | Action |
| --------------------- | ---------------------------- |
| `Esc` | Deselect All |
| `H` | Hide Selected |
| `Ctrl` `H` | Unhide All |
| `F` | Focus on Actor |
| `F9` | Screenshot |
| `F11` | Immersive Mode |
| `G` | Game View |
| `T` | Toggle Translucent Selection |
| `(right click)` | Asset Menu |
| `Ctrl` `E` | Edit Selected Asset |
| `Ctrl` `P` | Open Asset |
| `P` | Toggle Navmesh |
| `Ctrl` `Shift` `,` | Profile GPU |
| `Ctrl` `Shift` `H` | Toggle FPS |
| `~` | Command Console |
{.shortcuts}
### Camera Navigation
| Shortcut | Action |
| --------------------- | --------------------- |
| `Alt` `G` | Perspective View |
| `Alt` `H` | Front View |
| `Alt` `J` | Top View |
| `Alt` `K` | Side View |
| `Ctrl` `0-9` | Set Bookmark |
| `0-9` | Jump to Bookmark |
{.shortcuts}
### Editing Modes
| Shortcut | Action |
| --------------------- | --------------------- |
| `Shift` `1` | Selection Mode |
| `Shift` `2` | Landscape Mode |
| `Shift` `3` | Foliage Mode |
| `Shift` `4` | Modeling Mode |
| `Shift` `5` | Brush Editing Mode |
| `Shift` `6` | Animation Mode |
{.shortcuts}
### Snapping
| Shortcut | Action |
| --------------------- | --------------------- |
| `End` | Snap to Floor |
| `Alt` `End` | Snap Pivot to Floor |
| `Shift` `End` | Snap Bounds to Floor |
| `Ctrl` `End` | Snap to World Grid |
{.shortcuts}
### Play in Editor (PIE)
| Shortcut | Action |
| --------------------- | --------------------- |
| `Alt` `P` | Start PIE Session |
| `Pause` | Pause |
| `F8 ` | Eject from Player |
| `Esc` | Stop PIE Session |
{.shortcuts}
### Content Browser
Note: You need to select assets first for these shortcuts to work
| Shortcut | Action |
| --------------------- | --------------------- |
| `Alt` `Shift` `A` | Audit Assets |
| `Alt` `Shift` `R` | Reference Viewer |
| `Alt` `Shift` `M` | Size Map |
{.shortcuts}
## Asset Editors
### Blueprints {.row-span-2}
| Shortcut | Action |
| --------------------- | ------------------------------- |
| `B` | Add Branch |
| `S` | Add Sequence |
| `D` | Add Delay |
| `F` | Add For Each Loop |
| `G` | Add Gate |
| `M` | Add Multi Gate |
| `O` | Add Do Once |
| `N` | Add Do N |
| `C` | Add Comment |
| `F7` | Compile Blueprint |
| `F9` | Add Breakpoint to selected node |
| `Ctrl` `Shift` `F9` | Remove all Breakpoints |
| `Home` | Zoom to selected node |
{.shortcuts}
### Asset Editor Viewports
Used in the viewport for the Mesh Editor, Material Editor, Blueprint Editor, etc.
| Shortcut | Action |
| --------------------- | ---------------------- |
| `I` | Toggle Environment |
| `O` | Toggle Floor |
| `P` | Toggle Post Processing |
{.shortcuts}
### Static Meshes
| Shortcut | Action |
| --------------------- | ------------------------- |
| `Ctrl` `N` | Show Nanite Fallback Mesh |
| `Alt` `N` | Toggle Normals |
| `Alt` `S` | Toggle Sockets |
{.shortcuts}
## Your own Shortcuts
### Shortcut Settings
- Click on the `Edit` Menu
- Open `Editor Preferences`
- Under "General" (the first section), find `Editor Shortcuts`
- Here you can modify all of the above shortcuts, as well as many more!
## Also see
- [Unreal Engine Blog: Designer's Guide to Shortcuts](https://www.unrealengine.com/en-US/tech-blog/designer-s-guide-to-unreal-engine-keyboard-shortcuts)
_(www.unrealengine.com)_
- [Unreal Developer Community: Unexplored Shortcuts](https://dev.epicgames.com/community/learning/tutorials/yp8j/the-unexplored-unreal-engine-keyboard-shortucts)
_(dev.epicgames.com)_
- [Unreal Engine Editor Hotkey Cheat Sheet](https://uecasts.com/resources/unreal-engine-5-editor-hotkeys-cheat-sheet)
_(uecasts.com)_
- [Unreal Engine Actor Snapping Shortcuts](https://unrealdirective.com/tips/actor-snapping-shortcuts)
_(unrealdirective.com)_
+465
View File
@@ -0,0 +1,465 @@
# Best Windows Shortcuts on Your Keyboard
Copy selected content (Ctrl + C can also abort commands):
```
Ctrl + C
```
Paste copied content:
```
Ctrl + V
```
Paste unformatted content:
```
Ctrl + Shift + V
```
Delete and copy selected content (good for moving text, files, etc.):
```
Ctrl + X
```
Select all available content in focus:
```
Ctrl + A
```
Undo the previous action:
```
Ctrl + Z
```
Redo the previous action:
```
Ctrl + Y
```
Save what you're working on:
```
Ctrl + S
```
Open a new file:
```
Ctrl + O
```
Open the print dialog box:
```
Ctrl + P
```
Open the search tool to find something on the page:
```
Ctrl + F
```
Refresh the contents on the screen (only F5 works in some cases):
```
Ctrl + R
```
Close the active program:
```
Alt + F4
```
Enter full-screen mode:
```
F11
```
Stop or close a prompt or process:
```
Esc
```
# Keyboard Shortcuts for Navigating Windows
Lock your user account:
```
Win + L
```
Open File Explorer:
```
Win + E
```
Open Windows Settings:
```
Win + i
```
Move focus to the navigation bar to edit or copy the folder path:
```
Alt + D
```
Go to the folder the current folder is stored in:
```
Alt + Up
```
Show your password on the sign-in screen:
```
Alt + F8
```
Open Task Manager (Ctrl + Alt + Del works, too):
```
Ctrl + Shift + Esc
```
Open the Run dialog box to run commands:
```
Win + R
```
Quickly switch to the desktop:
```
Win + D
```
Open the selected item's Properties window:
```
Alt + [Enter or double-click]
```
Add a Virtual Desktop:
```
Win + Ctrl + D
```
Switch to the virtual desktop on the left or right:
```
Win + Ctrl + [Left or Right]
```
Show All Open Desktops:
```
WIN + Tab
```
Close Current Virtual Desktop:
```
WIN + Ctrl + F4
```
Select noncontiguous items (like files or folders):
```
Ctrl + Click
```
A possible fix for when your screen is black:
```
Win + Ctrl + Shift + B
```
Select every item between the first and last select items:
```
Shift + Click
```
Permanently delete a file or folder (it skips the Recycle Bin):
```
Shift + Del
```
Switch to the last used window:
```
Alt + Tab
```
Snap the active window to one side of the screen:
```
Win + [Arrow]
```
Rename the selected file or folder:
```
F2
```
Open the Power User Menu:
```
Win + X
```
Open a new instance of that app:
```
Shift + Click Taskbar Icon
```
Launch that item from the taskbar:
```
Win + [number]
```
Make a new folder:
```
Ctrl + Shift + N
```
Open the Windows About page:
```
Win + Pause
```
# Keyboard Shortcuts for Screenshots
Screenshot just the active window:
```
Alt + PrtScn
```
Auto-save full-screen screenshot to Pictures > Screenshots:
```
Win + PrtScn
```
Choose a part of the screen to make a screenshot:
```
Win + Shift + S
```
# Keyboard Shortcuts for Text Manipulation
Bold the selected text:
```
Ctrl + B
```
Italicize the selected text:
```
Ctrl + i
```
Underline the selected text:
```
Ctrl + U
```
Insert a hyperlink into the selected text:
```
Ctrl + K
```
Open the Find and Replace tool (confirmed in MS Word and Google Docs):
```
Ctrl + H
```
Pick an arrow key with this shortcut to quickly highlight a whole word or paragraph:
```
Shift + Ctrl + [Arrow]
```
Highlight everything from the cursor to the beginning or end of the line:
```
Shift + [Home or End]
```
Delete the word to the right of the cursor:
```
Ctrl + Del
```
# Keyboard Shortcuts for Web Browsers
Open a new tab:
```
Ctrl + T
```
Reopen the most recently closed tab:
```
Ctrl + Shift + T
```
Close the active tab:
```
Ctrl + W
```
Open the link in a new tab:
```
Ctrl + [Link]
```
View your web browsing history:
```
Ctrl + H
```
View recent or active downloads:
```
Ctrl + J
```
Start a search using the default search engine:
```
Ctrl + E
```
Jump to the tab in that position from the left (e.g., Ctrl + 4):
```
Ctrl + [number]
```
Open the options to delete browsing data:
```
Ctrl + Shift + Del
```
Go back or forward a page:
```
Alt + [Left or Right]
```
Adjust the size of the text (scroll up with the mouse to increase the size):
```
Ctrl + [Zoom]
```
Add .com to the end of the text in the address bar, and then visit the page:
```
Ctrl + Enter
```
Refresh the page, but skip the cache:
```
Ctrl + F5
```
Open LinkedIn (or Teams, Word Online):
```
Ctrl + Shift + Alt + Win + L
```
# Windows Shortcuts in Run Command
- The quickest way to access the Run command window is to use the keyboard shortcut `Windows + R`
| Command | Description |
| --------------------- | -------------------------------------------------------------------------------- |
| `sysdm.cpl` | Windows Propertes |
| `compmgmt.msc` | Component Managment |
| `winver` | Windows Version |
| `appwiz.cpl` | Programs And Fuatchers |
| `resmon` | The Resource Monitor window will open, displaying real-time performance d`ata |
| `taskmgr` | Task Manager |
| `explorer` | Windows Explorer |
| `ncpa.cpl` | Network Connection |
| `Firewall.cpl` | Firewall |
| `wf.msc` | Windows Firewall Advanced |
| `intl.cpl` | Time And Date Options |
| `timedate.cpl` | Time And Date Settings |
| `mstsc` | Remote Desktop |
| `osk` | Keybord Virtual |
| `charmap` | Character Map |
| `devmgmt.msc` | Device Managment |
| `desk.cpl` | Desktop Resuliation |
| `dfrgui` | program for configuring the scheduled task for disk defragmentation |
| `diskmgmt.msc` | Disk Managare |
| `fsmgmt.msc` | Show Folders Share |
| `inetcpl.cpl` | Internet Explorer options |
| `logoff` | Log Off |
| `magnify` | Show Magnifier |
| `mmsys.cpl` | Sound settings |
| `msconfig` | System settings |
| `msinfo32` | Show system all info |
| `systeminfo` | Show system info |
| `netplwiz` | System Users info |
| `perfmon.msc` | Start Windows Reliability and Performance Monitor in a specific s`tandalone mode |
| `powercfg.cpl` | Power options |
| `services.msc` | Services |
| `shrpubw` | Shared Folder Wizard |
| `write` | WordPad |
| `control` | Control Panel |
| `Control Printers` | Device And Printers |
| `dxdiag` | Show System Information Hardware |
| `tracert` | Trace Route |
| `printui /s /t2` | Print Server Properties |
| `printui /s` | Show Printer Drivers |
| `PrintManagement.msc` | Printers Management , show all printers with drivers |
| `shell:appsfolder` | Show App Folder |
| `shutdown /r /t 5` | Restart the system after 5 seconds |
| `shutdown /s /t 5` | System shutdown after 5 seconds |
| `shutdown -a` | This command will cancel the scheduled shutdown for one time |
| `shutdown /r /fw` | Bios Login from windows |
# Create God Mode Folder
create a new folder on your desktop with this exact name (copy and paste it):
`GodMode.{ED7BA470-8E54-465E-825C-99712043E01C}`
- The folder icon will change to a Control Panel-style icon, and you will be able to jump in and change all kinds of
settings
+1 -1
View File
@@ -9,7 +9,7 @@
<div class="w-24 h-full bg-emerald-500 dark:bg-slate-800"></div>
</div>
<div class="w-full grid grid-cols-2 md:grid-cols-4 gap-6 md:gap-8 mb-6 text-slate-800">
<% site.categories.findOne({name: category}).posts.sort('-date').map(function(post){ %>
<% site.categories.findOne({name: category}).posts.sort('date').map(function(post){ %>
<%- partial('_partial/index/card', {
url: url_for(post.path),
title: post.title,