Finished importing notes
BIN
content/notes/ready/algorithms-and-data/bigO.png
Normal file
|
After Width: | Height: | Size: 243 KiB |
499
content/notes/ready/algorithms-and-data/index.md
Normal file
@@ -0,0 +1,499 @@
|
||||
---
|
||||
title: Algorithms & Data Structures
|
||||
description:
|
||||
date: 2025-02-17T08:52:10+00:00
|
||||
draft: false
|
||||
tags:
|
||||
- c
|
||||
- programming
|
||||
author: TrudeEH
|
||||
showToc: true
|
||||
---
|
||||
|
||||
## Time Complexity
|
||||
|
||||
The amount of steps required for an algorithm to execute.
|
||||
|
||||
### Big O Notation
|
||||
|
||||
Maximum time for `n` input size. (Upper bound - worst case)
|
||||

|
||||
|
||||
### Omega Notation
|
||||
|
||||
Minimum time for `n` input size. (Lower bound)
|
||||
- `Ω(n²)`
|
||||
- `Ω(n log n)`
|
||||
- `Ω(n)`
|
||||
- `Ω(log n)`
|
||||
- `Ω(1)`
|
||||
|
||||
> If both are the same, use `θ`
|
||||
|
||||
## Searching Algorithms
|
||||
|
||||
|Algorithm|Average Time Complexity|RAM|
|
||||
|---|---|---|
|
||||
|Linear Search|O(n) \| Ω(1)|0|
|
||||
|Binary Search|O(log n) \| Ω(1)|0|
|
||||
|
||||
### Linear Search
|
||||
|
||||
Check every element until `n` is found.
|
||||
|
||||
```C
|
||||
#include <stdio.h>
|
||||
int main(void) {
|
||||
int n = 1; // number to find
|
||||
int numbers[] = {20, 500, 10, 5, 100, 1, 50};
|
||||
const int numbersLength = 7;
|
||||
for (int i = 0; i < numbersLength; i++) {
|
||||
if (numbers[i] == n) {
|
||||
printf("Found n\n");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
printf("Not found\n");
|
||||
return 1;
|
||||
}
|
||||
```
|
||||
|
||||
### Binary Search
|
||||
|
||||
```C
|
||||
#include <stdio.h>
|
||||
int main()
|
||||
{
|
||||
int c;
|
||||
int n = 10 // Number of elements in array
|
||||
int array[] = {0, 1, 2, 3, 4, 5, 6, 7, 8 ,9}
|
||||
int search = 2; // Number to find
|
||||
int first = 0;
|
||||
int last = n - 1;
|
||||
int middle = (first+last)/2; // Average
|
||||
while (first <= last) {
|
||||
if (array[middle] < search)
|
||||
first = middle + 1;
|
||||
else if (array[middle] == search) {
|
||||
printf("%d found at location %d.\n", search, middle+1);
|
||||
break;
|
||||
}
|
||||
else
|
||||
last = middle - 1;
|
||||
middle = (first + last)/2;
|
||||
}
|
||||
if (first > last)
|
||||
printf("Not found! %d isn't present in the list.\n", search);
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
## Sorting Algorithms
|
||||
|
||||
|Algorithm|Average Time Complexity|RAM|Use If|
|
||||
|---|---|---|---|
|
||||
|Selection Sort|O(n²) \| Ω(n²)|1 var|Never|
|
||||
|Bubble Sort|O(n²) \| Ω(n)|0||
|
||||
|Insertion Sort|O(n²) (Faster if the data is kind of sorted)|0||
|
||||
|Merge Sort|O(n log n) \| Ω(n log n)|More RAM|Large Arrays|
|
||||
|Quick Sort|O(n log n)|Less RAM|Small arrays|
|
||||
|
||||
## Data Structures
|
||||
|
||||
### Queue (Concept)
|
||||
|
||||
First In, First Out
|
||||
- enqueue - Add an item to the end of the line.
|
||||
- dequeue - Remove an item from the beginning of the line.
|
||||
|
||||
### Stack (Concept)
|
||||
|
||||
Last In, First Out
|
||||
The last item added will be used first, so the first ones added might never be used.
|
||||
- push - Add an item to the top of the stack
|
||||
- pop - Remove an item from the top of the stack
|
||||
|
||||
### Arrays
|
||||
|
||||
|Search|O(log n)|
|
||||
|---|---|
|
||||
|Multiple data types|No|
|
||||
|Resizable|No|
|
||||
|RAM Usage|Low|
|
||||
|
||||
```C
|
||||
double prices[] = {5.0, 3.2, 13.0};
|
||||
double values[5]; //Initialize an empty array, that can hold 5 items.
|
||||
printf("%lf€", prices[0]);
|
||||
printf("%d", sizeof(prices)); //3
|
||||
```
|
||||
|
||||
#### 2D Arrays
|
||||
|
||||
```C
|
||||
int numbers[2][3] = {
|
||||
{1, 2, 3},
|
||||
{4, 5, 6}
|
||||
};
|
||||
numbers[0][1]; //2
|
||||
numbers[1][2]; //6
|
||||
numbers[0][1] = 10; //Set [0][1] to 10.
|
||||
// Note: Calculate the rows and columns automatically.
|
||||
int rows = sizeof(numbers)/sizeof(numbers[0]);
|
||||
int columns = sizeof(numbers[0])/sizeof(numbers[0][0]);
|
||||
```
|
||||
|
||||
#### Array of Strings
|
||||
|
||||
```C
|
||||
char cars[][10] = {"Mustang", "Corvette", "Camaro"};
|
||||
//cars[0] = "Tesla"; ERROR! String arrays don't support item assignment.
|
||||
strcpy(cars[0], "Tesla"); //Does the same, but <string.h> must be included.
|
||||
```
|
||||
|
||||
### Resize Array
|
||||
|
||||
#### Manually
|
||||
|
||||
```C
|
||||
#include <stdlib.h>
|
||||
int *list = malloc(3 * sizeof(int));
|
||||
// Works like an array
|
||||
list[0] = 1;
|
||||
list[1] = 2;
|
||||
list[2] = 3;
|
||||
//Same as
|
||||
*list = 1;
|
||||
*(list + 1) = 2;
|
||||
*(list + 2) = 3;
|
||||
// ...
|
||||
// Add 1 extra byte to the array
|
||||
int *tmp = malloc(4 * sizeof(int));
|
||||
if (tmp == NULL) {
|
||||
free(list);
|
||||
return 1;
|
||||
}
|
||||
for (int i = 0; i < 3; i++){
|
||||
tmp[i] = list[i];
|
||||
}
|
||||
tmp[3] = 4;
|
||||
free(list);
|
||||
list = tmp;
|
||||
// ...
|
||||
free(list);
|
||||
return 0;
|
||||
```
|
||||
|
||||
#### Realloc
|
||||
|
||||
```C
|
||||
int *list = malloc(3 * sizeof(int));
|
||||
list[0] = 1;
|
||||
list[1] = 2;
|
||||
list[2] = 3;
|
||||
// ...
|
||||
int *tmp = realloc(list, 4 * sizeof(int)); //tmp is only needed to verify if realloc was successful, if realloc was assigned to int and failed, the 3 bytes from the list would be lost as list = NULL.
|
||||
if (tmp == NULL) {
|
||||
free(list);
|
||||
return 1;
|
||||
}
|
||||
list = tmp;
|
||||
list[3] = 4;
|
||||
// ...
|
||||
free(list);
|
||||
return 0;
|
||||
```
|
||||
|
||||
### Linked Lists
|
||||
|
||||
| Linked List | TC |
|
||||
| --------------------- | ------ |
|
||||
| Add element unordered | O(1) |
|
||||
| Add element ordered | O(n) |
|
||||
| Search | O(n) |
|
||||
| Insert | O(n) |
|
||||
| Multiple data types | Yes |
|
||||
| Resizable | Yes |
|
||||
| RAM Usage | Medium |
|
||||
|
||||
Each element has its value, and a pointer to the next element. The last element's pointer is `NULL`. (NULL == 0x0)
|
||||
|
||||
```Plain
|
||||
[N] -> [N] -> [N] -> [N] ...
|
||||
```
|
||||
|
||||
```C
|
||||
typedef struct node {
|
||||
int number; // Value
|
||||
struct node *next; // Pointer to the next node
|
||||
} node;
|
||||
```
|
||||
|
||||
#### Unordered Linked List Example
|
||||
|
||||
Both code blocks are unsafe (if there's no memory, the program won't free)
|
||||
|
||||
```C
|
||||
typedef struct node {
|
||||
int number;
|
||||
struct node *next;
|
||||
} node;
|
||||
int main(void) {
|
||||
node *list = NULL;
|
||||
node *n = malloc(sizeof(node)); // n points at the first node of the linked list.
|
||||
(*n).number = 1; // First element = 1.
|
||||
//Or
|
||||
n->number = 1; // Same.
|
||||
n->next = NULL; // Point to NULL so it won't point to a garbage value.
|
||||
list = n;
|
||||
node *n = malloc(sizeof(node)); // n points at the first node of the linked list.
|
||||
n->number = 2;
|
||||
n->next = list;
|
||||
list = n;
|
||||
}
|
||||
```
|
||||
|
||||
```C
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
typedef struct node {
|
||||
int number;
|
||||
struct node *next;
|
||||
} node;
|
||||
int main(void) {
|
||||
node *list = NULL;
|
||||
int numbers[] = {1, 2, 3};
|
||||
// Create linked list with the elements in the array.
|
||||
for (int i = 0; i < 3; i++) {
|
||||
node *n = malloc(sizeof(node));
|
||||
if (n == NULL) return 1;
|
||||
n->number = number;
|
||||
n->next = NULL;
|
||||
n->next = list;
|
||||
list = n;
|
||||
}
|
||||
// Print all elements from linked list.
|
||||
node *ptr = list;
|
||||
while (ptr != NULL) {
|
||||
printf("%i\\n", ptr->number);
|
||||
ptr = ptr->next; // Borrow the value in the list->n, which has the next node address.
|
||||
}
|
||||
// Free the list's memory.
|
||||
ptr = list;
|
||||
while (ptr != NULL) {
|
||||
node *next = ptr->next;
|
||||
free(ptr);
|
||||
ptr = next;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Trees
|
||||
|
||||
| Balanced | Unbalanced | TC |
|
||||
| ------------------- | ---------- | ---- |
|
||||
| Add element | O(n) | O(n) |
|
||||
| Search | O(log n) | O(n) |
|
||||
| Insert | O(log n) | O(n) |
|
||||
| Multiple data types | Yes | Yes |
|
||||
| Resizable | Yes | Yes |
|
||||
| RAM Usage | High | High |
|
||||
|
||||
If organized correctly, allows for binary search.
|
||||
Each node has 2 pointers.
|
||||
|
||||
```Plain
|
||||
[N] - root / parent
|
||||
/ \\
|
||||
[N] [N] - parent and children
|
||||
/ \\ / \\
|
||||
[N] [N] [N] [N] - leaf / child
|
||||
```
|
||||
|
||||
```C
|
||||
typedef struct treenode {
|
||||
int value;
|
||||
struct treenode *left;
|
||||
struct treenode *right;
|
||||
} treenode;
|
||||
treenode *createnode(int value) {
|
||||
treenode* result = malloc(sizeof(treenode));
|
||||
if (result != NULL) {
|
||||
result->left = NULL;
|
||||
result->right = NULL;
|
||||
result->value = value;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
void printtabs(int numtabs){
|
||||
for (int i=0; i < numtabs; i++){
|
||||
printf("\\t");
|
||||
}
|
||||
}
|
||||
void printtree_rec(treenode *root, int level){
|
||||
if (root == NULL) {
|
||||
printtabs(level);
|
||||
printf("----<empty>-----\\n");
|
||||
return;
|
||||
}
|
||||
// Preordered
|
||||
printtabs(level);
|
||||
printf("value = %d\\n", root->value);
|
||||
printtabs(level);
|
||||
printf("left\\n");
|
||||
printtree_rec(root->left, level + 1);
|
||||
printtabs(level);
|
||||
printf("right\\n");
|
||||
printtree_rec(root->right, level + 1);
|
||||
printtabs(level);
|
||||
printf("done\\n");
|
||||
}
|
||||
void printtree(treenode *root) {
|
||||
printtree_rec(root, 0);
|
||||
}
|
||||
int main(void){
|
||||
treenode *n1 = createnode(10);
|
||||
treenode *n2 = createnode(11);
|
||||
treenode *n3 = createnode(12);
|
||||
treenode *n4 = createnode(13);
|
||||
treenode *n5 = createnode(14);
|
||||
// n1 will be the root
|
||||
n1->left = n2;
|
||||
n1->right = n3;
|
||||
n3->left = n4;
|
||||
n4->right = n5;
|
||||
printtree(n1);
|
||||
free(n1);
|
||||
free(n2);
|
||||
free(n3);
|
||||
free(n4);
|
||||
free(n5);
|
||||
}
|
||||
```
|
||||
|
||||
### Hash Tables
|
||||
|
||||
| Average | Worst | Best |
|
||||
| ------------------- | --------- | --------- |
|
||||
| Add element | O(1) | O(n) |
|
||||
| Search | O(1) | O(n) |
|
||||
| Insert | O(1) | O(n) |
|
||||
| Multiple data types | Yes | Yes |
|
||||
| Resizable | Yes | Yes |
|
||||
| RAM Usage | Very High | Very High |
|
||||
|
||||
An array, in which every element is a linked list.
|
||||
The array is used to 'choose' a linked list, and the linked list stores a dynamic number of elements.
|
||||
|
||||
```C
|
||||
[0] -> [N] -> [N] -> [N]
|
||||
[1] -> [N] -> [N]
|
||||
[2] -> [N]
|
||||
[3] -> [N] -> [N]
|
||||
[4] -> [N] -> [N] -> [N]
|
||||
[5] -> [N] -> [N]
|
||||
0-5 - Array element
|
||||
N - Linked list node
|
||||
```
|
||||
|
||||
### Trie
|
||||
|
||||
| Trie | Average | Worst |
|
||||
| ------------------- | -------------- | -------------- |
|
||||
| Add element | O(1) | O(1) |
|
||||
| Search | O(1) | O(1) |
|
||||
| Insert | O(1) | O(1) |
|
||||
| Multiple data types | Yes | Yes |
|
||||
| Resizable | Yes | Yes |
|
||||
| RAM Usage | Extremely High | Extremely High |
|
||||
|
||||
Tree, but every node is an array.
|
||||
Useful to store words. Every element in an array is linked to the next letter.
|
||||

|
||||
|
||||
```C
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdbool.h>
|
||||
#include <string.h>
|
||||
#define ALPHABET_SIZE 26
|
||||
struct TrieNode {
|
||||
struct TrieNode *children[ALPHABET_SIZE];
|
||||
bool isendofword;
|
||||
};
|
||||
typedef struct TrieNode TrieNode;
|
||||
TrieNode *createNode() {
|
||||
TrieNode *node = (TrieNode *)malloc(sizeof(TrieNode));
|
||||
node->isendofword = false;
|
||||
for (int i = 0; i < ALPHABET_SIZE; i++) {
|
||||
node->children[i] = NULL;
|
||||
}
|
||||
return node;
|
||||
}
|
||||
void insert(TrieNode *root, const char *key) {
|
||||
TrieNode *current = root;
|
||||
for (int i = 0; i < strlen(key); i++) {
|
||||
int index = key[i] - 'a';
|
||||
if (current->children[index] == NULL) {
|
||||
current->children[index] = createNode();
|
||||
}
|
||||
current = current->children[index];
|
||||
}
|
||||
current->isendofword = true;
|
||||
}
|
||||
bool search(TrieNode *root, const char *key) {
|
||||
TrieNode *current = root;
|
||||
for (int i = 0; i < strlen(key); i++) {
|
||||
int index = key[i] - 'a';
|
||||
if (current->children[index] == NULL) {
|
||||
return false;
|
||||
}
|
||||
current = current->children[index];
|
||||
}
|
||||
return (current != NULL && current->isendofword);
|
||||
}
|
||||
bool isempty(TrieNode *root) {
|
||||
for (int i = 0; i < ALPHABET_SIZE; i++) {
|
||||
if (root->children[i] != NULL) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
TrieNode *deleteHelper(TrieNode *root, const char *key, int depth) {
|
||||
if (root == NULL) {
|
||||
return NULL;
|
||||
}
|
||||
if (depth == strlen(key)) {
|
||||
if (root->isendofword) {
|
||||
root->isendofword = false;
|
||||
}
|
||||
if (isempty(root)) {
|
||||
free(root);
|
||||
root = NULL;
|
||||
}
|
||||
return root;
|
||||
}
|
||||
int index = key[depth] - 'a';
|
||||
root->children[index] = deleteHelper(root->children[index], key, depth + 1);
|
||||
if (isempty(root) && !root->isendofword) {
|
||||
free(root);
|
||||
root = NULL;
|
||||
}
|
||||
return root;
|
||||
}
|
||||
void deletekey(TrieNode *root, const char *key) {
|
||||
deleteHelper(root, key, 0);
|
||||
}
|
||||
int main() {
|
||||
TrieNode *root = createNode();
|
||||
insert(root, "example");
|
||||
insert(root, "word");
|
||||
printf("%s\n", search(root, "word") ? "Found" : "Not Found");
|
||||
printf("%s\n", search(root, "example") ? "Found" : "Not Found");
|
||||
printf("%s\n", search(root, "trude") ? "Found" : "Not Found");
|
||||
deletekey(root, "word");
|
||||
printf("%s\n", search(root, "word") ? "Found" : "Not Found");
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
BIN
content/notes/ready/algorithms-and-data/trie.png
Normal file
|
After Width: | Height: | Size: 143 KiB |
BIN
content/notes/ready/binary-operations/addition.png
Normal file
|
After Width: | Height: | Size: 8.2 KiB |
BIN
content/notes/ready/binary-operations/binarycalc.png
Normal file
|
After Width: | Height: | Size: 14 KiB |
BIN
content/notes/ready/binary-operations/hand_addition1.png
Normal file
|
After Width: | Height: | Size: 10 KiB |
BIN
content/notes/ready/binary-operations/hand_addition2.png
Normal file
|
After Width: | Height: | Size: 10 KiB |
BIN
content/notes/ready/binary-operations/image68.png
Normal file
|
After Width: | Height: | Size: 22 KiB |
BIN
content/notes/ready/binary-operations/image69.png
Normal file
|
After Width: | Height: | Size: 13 KiB |
BIN
content/notes/ready/binary-operations/image70.png
Normal file
|
After Width: | Height: | Size: 19 KiB |
BIN
content/notes/ready/binary-operations/image71.png
Normal file
|
After Width: | Height: | Size: 89 KiB |
BIN
content/notes/ready/binary-operations/image72.png
Normal file
|
After Width: | Height: | Size: 33 KiB |
BIN
content/notes/ready/binary-operations/image73.png
Normal file
|
After Width: | Height: | Size: 19 KiB |
BIN
content/notes/ready/binary-operations/image74.png
Normal file
|
After Width: | Height: | Size: 17 KiB |
BIN
content/notes/ready/binary-operations/image75.png
Normal file
|
After Width: | Height: | Size: 17 KiB |
390
content/notes/ready/binary-operations/index.md
Normal file
@@ -0,0 +1,390 @@
|
||||
---
|
||||
title: Binary Operations
|
||||
description:
|
||||
date: 2025-02-17T08:37:24+00:00
|
||||
draft: false
|
||||
tags:
|
||||
- computer-science
|
||||
author: TrudeEH
|
||||
showToc: true
|
||||
---
|
||||
|
||||
## Binary
|
||||
|
||||
Binary is a base-2 numeral system: A simple way to represent numbers using only two states.
|
||||
|
||||
|Binary|Decimal|Hexadecimal|
|
||||
|---|---|---|
|
||||
|0000|00|00|
|
||||
|0001|01|01|
|
||||
|0010|02|02|
|
||||
|0011|03|03|
|
||||
|0100|04|04|
|
||||
|0101|05|05|
|
||||
|0110|06|06|
|
||||
|0111|07|07|
|
||||
|1000|08|08|
|
||||
|1001|09|09|
|
||||
|1010|10|0A|
|
||||
|1011|11|0B|
|
||||
|1100|12|0C|
|
||||
|1101|13|0D|
|
||||
|1110|14|0E|
|
||||
|1111|15|0F|
|
||||
|
||||

|
||||
|
||||
### Speaking Binary
|
||||
|
||||
> The information in this section is non-standard, and mostly a curiosity.
|
||||
|
||||
You may struggle to pronounce large binary numbers, as saying a long list of 0s and 1s is very inefficient. Instead, we can do something like this:
|
||||
|
||||

|
||||
|
||||
To be able to say any binary number, list the number, starting by the last digit:
|
||||
|
||||

|
||||
|
||||
And pronounce the ones that correspond to a `1` bit.
|
||||
|
||||

|
||||
|
||||
#### Pronounce a Binary Number at a Glance
|
||||
|
||||
1. Break the number at its largest pair of bits.
|
||||
|
||||

|
||||
|
||||
2. Represent the left and right sides.
|
||||
|
||||

|
||||
|
||||
In this example, there is a `two` in the order of magnitude `hex`.
|
||||
|
||||
3. Continue to represent the left and right sides recursively.
|
||||
|
||||

|
||||
|
||||
The last number is `four`.
|
||||
|
||||
#### Decode a Spoken Binary Number
|
||||
|
||||
Starting with `two hex four`:
|
||||
|
||||
1. Find the largest power of two.
|
||||
|
||||

|
||||
|
||||
2. The number is equal to the left side, times the order of magnitude, plus the right side.
|
||||
|
||||

|
||||
|
||||
#### Avoiding Repetition
|
||||
|
||||
Repetition can be avoided by combining some very common, small numbers:
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
These shortcuts essentially create a quaternary system to pronounce binary, but in this case, the result improves spoken efficiency by a lot.
|
||||
|
||||
## Arithmetic Operations
|
||||
|
||||
### Addition
|
||||
|
||||
Adding two numbers can be done using a simple, manual algorithm: By adding the last bit of both numbers first, carry if necessary, then move on to the next number, and so on.
|
||||
|
||||
| **+** | 0 | 1 |
|
||||
| ------- | --- | ---- |
|
||||
| 0 | 0 | 1 |
|
||||
| 1 | 1 | 10 |
|
||||
|
||||

|
||||
|
||||
> To add numbers more efficiently by hand, you can group bits together and memorize the patters, effectively doubling your speed.
|
||||
>
|
||||
> 
|
||||
>
|
||||
> To improve calculation speed even further, you can group more bits, and learn those patterns as well.
|
||||
>
|
||||
> 
|
||||
|
||||
#### Half Adder
|
||||
|
||||
Add 2, single-digit binary numbers.
|
||||
|
||||
| **A** | **B** | **Carry** | **Sum** |
|
||||
| ----- | ----- | --------- | ------- |
|
||||
| 0 | 0 | 0 | 0 |
|
||||
| 0 | 1 | 0 | 1 |
|
||||
| 1 | 0 | 0 | 1 |
|
||||
| 1 | 1 | 1 | 0 |
|
||||
|
||||
![[image68.png]]
|
||||
|
||||
#### Full Adder
|
||||
|
||||
When adding 2 binary numbers, one operation might return a carry value, which the `half adder` can't accept, as it only has 2 inputs.
|
||||
|
||||
![[image69.png]]
|
||||
|
||||
To solve this issue, a `full adder` accepts 3 inputs.
|
||||
|
||||
![[image70.png]]
|
||||
|
||||
#### 8-Bit Adder
|
||||
|
||||
![[image71.png]]
|
||||
|
||||
### Subtraction
|
||||
|
||||
Subtraction can result in negative numbers. Like how additions need a carry, subtraction needs a borrow.
|
||||
|
||||
#### Half Subtractor
|
||||
|
||||
Subtract 2, single-digit binary numbers.
|
||||
|
||||
| **A** | **B** | Diff | **Borrow** |
|
||||
| ----- | ----- | ---- | ---------- |
|
||||
| 0 | 0 | 0 | 0 |
|
||||
| 0 | 1 | 1 | 1 |
|
||||
| 1 | 0 | 1 | 0 |
|
||||
| 1 | 1 | 0 | 0 |
|
||||
|
||||
![[image72.png]]
|
||||
|
||||
#### Full Subtractor
|
||||
|
||||
A `full subtractor` accepts the borrow value, allowing us to chain results.
|
||||
|
||||
| **A** | **B** | **B**in | **Diff** | **B**out |
|
||||
| ----- | ----- | ------- | -------- | -------- |
|
||||
| 0 | 0 | 0 | 0 | 0 |
|
||||
| 0 | 0 | 1 | 1 | 1 |
|
||||
| 0 | 1 | 0 | 1 | 1 |
|
||||
| 0 | 1 | 1 | 0 | 1 |
|
||||
| 1 | 0 | 0 | 1 | 0 |
|
||||
| 1 | 0 | 1 | 0 | 0 |
|
||||
| 1 | 1 | 0 | 0 | 0 |
|
||||
| 1 | 1 | 1 | 1 | 1 |
|
||||
|
||||
![[image73.png]]
|
||||
|
||||
#### 8-Bit Subtractor
|
||||
|
||||
![[image74.png]]
|
||||
|
||||
### Multiplication
|
||||
|
||||
Multiplication is also similar to its decimal counterpart, but because binary is so small compared to decimal, the steps are also much simpler.
|
||||
|
||||
First, multiply the top number to every digit of the bottom one, and then add the results together.
|
||||
|
||||
| X | 0 | 1 |
|
||||
| --- | --- | --- |
|
||||
| 0 | 0 | 0 |
|
||||
| 1 | 0 | 1 |
|
||||
|
||||
```Plain
|
||||
||.|
|
||||
x ||.
|
||||
....
|
||||
||.|
|
||||
+ ||.|
|
||||
|..|||.
|
||||
```
|
||||
|
||||
#### 2-Bit By 2-Bit Multiplier
|
||||
|
||||
![[image75.png]]
|
||||
|
||||
### Division
|
||||
|
||||
1. Find the smallest part of the dividend greater than or equal to the ==divisor==.
|
||||
|
||||
```Plain
|
||||
|.| ||..|
|
||||
```
|
||||
|
||||
2. Write the first digit of ==the answer==, and ==copy the original divisor down==.
|
||||
|
||||
```Plain
|
||||
|
|
||||
|.| ||..|
|
||||
|.|
|
||||
```
|
||||
|
||||
3. Subtract ==the aligned dividend digits== by ==the digits under the dividend==.
|
||||
|
||||
```Plain
|
||||
|
|
||||
|.| ||..|
|
||||
|.|
|
||||
|
|
||||
```
|
||||
|
||||
4. Lower ==the next dividend digit==.
|
||||
|
||||
```Plain
|
||||
|
|
||||
|.| ||..|
|
||||
|.|
|
||||
|.
|
||||
```
|
||||
|
||||
5. Is ==the total== greater or equal to the ==divisor==? If so, add a `1` to the answer. If not, ==add a== ==`0`== ==to the answer== ==and return to step 4==.
|
||||
|
||||
```Plain
|
||||
|.
|
||||
|.| ||..|
|
||||
|.|
|
||||
|.
|
||||
```
|
||||
|
||||
6. Return to step 2, until you reach the end of the number. If you reached the end, you found ==the answer==.
|
||||
|
||||
```Plain
|
||||
|.|
|
||||
|.| ||..|
|
||||
|.|
|
||||
|.|
|
||||
|.|
|
||||
.
|
||||
```
|
||||
|
||||
### ASCII
|
||||
|
||||
Binary can also be used to represent characters.
|
||||
|
||||
| Dec | Hex | Binary | HTML | Char | Description |
|
||||
| --- | --- | -------- | -------- | ----------- | ------------------------- |
|
||||
| 0 | 00 | 00000000 | `�` | NUL | Null |
|
||||
| 1 | 01 | 00000001 | `` | SOH | Start of Heading |
|
||||
| 2 | 02 | 00000010 | `` | STX | Start of Text |
|
||||
| 3 | 03 | 00000011 | `` | ETX | End of Text |
|
||||
| 4 | 04 | 00000100 | `` | EOT | End of Transmission |
|
||||
| 5 | 05 | 00000101 | `` | ENQ | Enquiry |
|
||||
| 6 | 06 | 00000110 | `` | ACK | Acknowledge |
|
||||
| 7 | 07 | 00000111 | `` | BEL | Bell |
|
||||
| 8 | 08 | 00001000 | `` | BS | Backspace |
|
||||
| 9 | 09 | 00001001 | `	` | HT | Horizontal Tab |
|
||||
| 10 | 0A | 00001010 | ` ` | LF | Line Feed |
|
||||
| 11 | 0B | 00001011 | `` | VT | Vertical Tab |
|
||||
| 12 | 0C | 00001100 | `` | FF | Form Feed |
|
||||
| 13 | 0D | 00001101 | ` ` | CR | Carriage Return |
|
||||
| 14 | 0E | 00001110 | `` | SO | Shift Out |
|
||||
| 15 | 0F | 00001111 | `` | SI | Shift In |
|
||||
| 16 | 10 | 00010000 | `` | DLE | Data Link Escape |
|
||||
| 17 | 11 | 00010001 | `` | DC1 | Device Control 1 |
|
||||
| 18 | 12 | 00010010 | `` | DC2 | Device Control 2 |
|
||||
| 19 | 13 | 00010011 | `` | DC3 | Device Control 3 |
|
||||
| 20 | 14 | 00010100 | `` | DC4 | Device Control 4 |
|
||||
| 21 | 15 | 00010101 | `` | NAK | Negative Acknowledge |
|
||||
| 22 | 16 | 00010110 | `` | SYN | Synchronize |
|
||||
| 23 | 17 | 00010111 | `` | ETB | End of Transmission Block |
|
||||
| 24 | 18 | 00011000 | `` | CAN | Cancel |
|
||||
| 25 | 19 | 00011001 | `` | EM | End of Medium |
|
||||
| 26 | 1A | 00011010 | `` | SUB | Substitute |
|
||||
| 27 | 1B | 00011011 | `` | ESC | Escape |
|
||||
| 28 | 1C | 00011100 | `` | FS | File Separator |
|
||||
| 29 | 1D | 00011101 | `` | GS | Group Separator |
|
||||
| 30 | 1E | 00011110 | `` | RS | Record Separator |
|
||||
| 31 | 1F | 00011111 | `` | US | Unit Separator |
|
||||
| 32 | 20 | 00100000 | ` ` | space | Space |
|
||||
| 33 | 21 | 00100001 | `!` | ! | exclamation mark |
|
||||
| 34 | 22 | 00100010 | `"` | " | double quote |
|
||||
| 35 | 23 | 00100011 | `#` | # | number |
|
||||
| 36 | 24 | 00100100 | `$` | $ | dollar |
|
||||
| 37 | 25 | 00100101 | `%` | % | percent |
|
||||
| 38 | 26 | 00100110 | `&` | & | ampersand |
|
||||
| 39 | 27 | 00100111 | `'` | ' | single quote |
|
||||
| 40 | 28 | 00101000 | `(` | ( | left parenthesis |
|
||||
| 41 | 29 | 00101001 | `)` | ) | right parenthesis |
|
||||
| 42 | 2A | 00101010 | `*` | * | asterisk |
|
||||
| 43 | 2B | 00101011 | `+` | + | plus |
|
||||
| 44 | 2C | 00101100 | `,` | , | comma |
|
||||
| 45 | 2D | 00101101 | `-` | - | minus |
|
||||
| 46 | 2E | 00101110 | `.` | . | period |
|
||||
| 47 | 2F | 00101111 | `/` | / | slash |
|
||||
| 48 | 30 | 00110000 | `0` | 0 | zero |
|
||||
| 49 | 31 | 00110001 | `1` | 1 | one |
|
||||
| 50 | 32 | 00110010 | `2` | 2 | two |
|
||||
| 51 | 33 | 00110011 | `3` | 3 | three |
|
||||
| 52 | 34 | 00110100 | `4` | 4 | four |
|
||||
| 53 | 35 | 00110101 | `5` | 5 | five |
|
||||
| 54 | 36 | 00110110 | `6` | 6 | six |
|
||||
| 55 | 37 | 00110111 | `7` | 7 | seven |
|
||||
| 56 | 38 | 00111000 | `8` | 8 | eight |
|
||||
| 57 | 39 | 00111001 | `9` | 9 | nine |
|
||||
| 58 | 3A | 00111010 | `:` | : | colon |
|
||||
| 59 | 3B | 00111011 | `;` | ; | semicolon |
|
||||
| 60 | 3C | 00111100 | `<` | < | less than |
|
||||
| 61 | 3D | 00111101 | `=` | = | equality sign |
|
||||
| 62 | 3E | 00111110 | `>` | > | greater than |
|
||||
| 63 | 3F | 00111111 | `?` | ? | question mark |
|
||||
| 64 | 40 | 01000000 | `@` | @ | at sign |
|
||||
| 65 | 41 | 01000001 | `A` | A | |
|
||||
| 66 | 42 | 01000010 | `B` | B | |
|
||||
| 67 | 43 | 01000011 | `C` | C | |
|
||||
| 68 | 44 | 01000100 | `D` | D | |
|
||||
| 69 | 45 | 01000101 | `E` | E | |
|
||||
| 70 | 46 | 01000110 | `F` | F | |
|
||||
| 71 | 47 | 01000111 | `G` | G | |
|
||||
| 72 | 48 | 01001000 | `H` | H | |
|
||||
| 73 | 49 | 01001001 | `I` | I | |
|
||||
| 74 | 4A | 01001010 | `J` | J | |
|
||||
| 75 | 4B | 01001011 | `K` | K | |
|
||||
| 76 | 4C | 01001100 | `L` | L | |
|
||||
| 77 | 4D | 01001101 | `M` | M | |
|
||||
| 78 | 4E | 01001110 | `N` | N | |
|
||||
| 79 | 4F | 01001111 | `O` | O | |
|
||||
| 80 | 50 | 01010000 | `P` | P | |
|
||||
| 81 | 51 | 01010001 | `Q` | Q | |
|
||||
| 82 | 52 | 01010010 | `R` | R | |
|
||||
| 83 | 53 | 01010011 | `S` | S | |
|
||||
| 84 | 54 | 01010100 | `T` | T | |
|
||||
| 85 | 55 | 01010101 | `U` | U | |
|
||||
| 86 | 56 | 01010110 | `V` | V | |
|
||||
| 87 | 57 | 01010111 | `W` | W | |
|
||||
| 88 | 58 | 01011000 | `X` | X | |
|
||||
| 89 | 59 | 01011001 | `Y` | Y | |
|
||||
| 90 | 5A | 01011010 | `Z` | Z | |
|
||||
| 91 | 5B | 01011011 | `[` | [ | left square bracket |
|
||||
| 92 | 5C | 01011100 | `\` | \|backslash | |
|
||||
| 93 | 5D | 01011101 | `]` | ] | right square bracket |
|
||||
| 94 | 5E | 01011110 | `^` | ^ | caret / circumflex |
|
||||
| 95 | 5F | 01011111 | `_` | _ | underscore |
|
||||
| 96 | 60 | 01100000 | ``` | ` | grave / accent |
|
||||
| 97 | 61 | 01100001 | `a` | a | |
|
||||
| 98 | 62 | 01100010 | `b` | b | |
|
||||
| 99 | 63 | 01100011 | `c` | c | |
|
||||
| 100 | 64 | 01100100 | `d` | d | |
|
||||
| 101 | 65 | 01100101 | `e` | e | |
|
||||
| 102 | 66 | 01100110 | `f` | f | |
|
||||
| 103 | 67 | 01100111 | `g` | g | |
|
||||
| 104 | 68 | 01101000 | `h` | h | |
|
||||
| 105 | 69 | 01101001 | `i` | i | |
|
||||
| 106 | 6A | 01101010 | `j` | j | |
|
||||
| 107 | 6B | 01101011 | `k` | k | |
|
||||
| 108 | 6C | 01101100 | `l` | l | |
|
||||
| 109 | 6D | 01101101 | `m` | m | |
|
||||
| 110 | 6E | 01101110 | `n` | n | |
|
||||
| 111 | 6F | 01101111 | `o` | o | |
|
||||
| 112 | 70 | 01110000 | `p` | p | |
|
||||
| 113 | 71 | 01110001 | `q` | q | |
|
||||
| 114 | 72 | 01110010 | `r` | r | |
|
||||
| 115 | 73 | 01110011 | `s` | s | |
|
||||
| 116 | 74 | 01110100 | `t` | t | |
|
||||
| 117 | 75 | 01110101 | `u` | u | |
|
||||
| 118 | 76 | 01110110 | `v` | v | |
|
||||
| 119 | 77 | 01110111 | `w` | w | |
|
||||
| 120 | 78 | 01111000 | `x` | x | |
|
||||
| 121 | 79 | 01111001 | `y` | y | |
|
||||
| 122 | 7A | 01111010 | `z` | z | |
|
||||
| 123 | 7B | 01111011 | `{` | { | left curly bracket |
|
||||
| 124 | 7C | 01111100 | `|` | \| | vertical bar |
|
||||
| 125 | 7D | 01111101 | `}` | } | right curly bracket |
|
||||
| 126 | 7E | 01111110 | `~` | ~ | tilde |
|
||||
| 127 | 7F | 01111111 | `` | DEL | delete |
|
||||
BIN
content/notes/ready/binary-operations/sb1.png
Normal file
|
After Width: | Height: | Size: 82 KiB |
BIN
content/notes/ready/binary-operations/sb10.png
Normal file
|
After Width: | Height: | Size: 86 KiB |
BIN
content/notes/ready/binary-operations/sb2.png
Normal file
|
After Width: | Height: | Size: 25 KiB |
BIN
content/notes/ready/binary-operations/sb3.png
Normal file
|
After Width: | Height: | Size: 23 KiB |
BIN
content/notes/ready/binary-operations/sb4.png
Normal file
|
After Width: | Height: | Size: 3.6 KiB |
BIN
content/notes/ready/binary-operations/sb5.png
Normal file
|
After Width: | Height: | Size: 16 KiB |
BIN
content/notes/ready/binary-operations/sb6.png
Normal file
|
After Width: | Height: | Size: 16 KiB |
BIN
content/notes/ready/binary-operations/sb7.png
Normal file
|
After Width: | Height: | Size: 16 KiB |
BIN
content/notes/ready/binary-operations/sb8.png
Normal file
|
After Width: | Height: | Size: 7.6 KiB |
BIN
content/notes/ready/binary-operations/sb9.png
Normal file
|
After Width: | Height: | Size: 91 KiB |
695
content/notes/ready/c-language.md
Normal file
@@ -0,0 +1,695 @@
|
||||
---
|
||||
title: C Language
|
||||
description:
|
||||
date: 2025-02-17T08:54:40+00:00
|
||||
draft: false
|
||||
tags:
|
||||
- c
|
||||
- programming
|
||||
author: TrudeEH
|
||||
showToc: true
|
||||
---
|
||||
|
||||
## Tools
|
||||
|
||||
- `indent` (format code)
|
||||
- `gcc` / `clang` (compile code)
|
||||
- `man <function>` (see function documentation)
|
||||
- `tldr <command>` (quick command usage examples)
|
||||
- `valgrind` (Look for memory leaks)
|
||||
- `valgrind —tool=massif` (check a program's RAM usage)
|
||||
- View the output with `Massif-Visualizer`
|
||||
- `gdb` (debugger)
|
||||
- `gdb —args <program>` (if the program has command line args)
|
||||
- Type `run` to start debugging, and `backtrace` for error details.
|
||||
- `file` Check file information and, if it is an executable, compilation details.
|
||||
- `perf stat -r 10 -d <program>` Benchmark a program.
|
||||
|
||||
## Data Types and Variables
|
||||
|
||||
The binary length of each data type depends on the CPU, OS, and compiler, but in general, they follow the C specifications. To check the exact values for your platform, see `limits.h`.
|
||||
|
||||
| Type | C SPEC | x64 Linux (Example) |
|
||||
| ------------- | --------- | ------------------- |
|
||||
| `char` | ≥ 8 bits | 8 bits |
|
||||
| `short` | ≥ 16 bits | 16 bits |
|
||||
| `int` | ≥ 16 bits | 32 bits |
|
||||
| `long` | ≥ 32 bits | 64 bits |
|
||||
| `long long` | ≥ 64 bits | 64 bits |
|
||||
| `float` | | 32 bits |
|
||||
| `double` | | 64 bits |
|
||||
| `long double` | | 128 bits |
|
||||
|
||||
| Unsigned Bytes (8 bits) | Maximum Decimal Value |
|
||||
| ----------------------- | --------------------------------------------------- |
|
||||
| 1 | 255 |
|
||||
| 2 | 65.535 |
|
||||
| 4 | 4.294.967.295 |
|
||||
| 8 | 18.446.744.073.709.551.615 |
|
||||
| 16 | 340.282.366.920.938.463.463.374.607.431.768.211.455 |
|
||||
| 32 | 1.157 × 10^76 |
|
||||
|
||||
Examples
|
||||
|
||||
```C
|
||||
char a = 'C'; // single character %c ''
|
||||
char b[] = "Trude" // array of characters %s ""
|
||||
unsigned int // Unsigned. The number must be positive.
|
||||
int // Signed. Negative and positive numbers.
|
||||
char f = 100; // %d (number) %c (character)
|
||||
unsigned char g = 255; // %d (number) %c (character)
|
||||
short h = 32767; // %d
|
||||
unsigned short i = 65535; // %d
|
||||
int j = 2147483647; // %d
|
||||
unsigned int k = 4294967295; // %u
|
||||
long long l = ... // %lld
|
||||
unsigned long long m = ...32U // %llu
|
||||
float c = 3.141592; // %f
|
||||
double d = 3.141592653589793; // %lf
|
||||
```
|
||||
|
||||
### Format Specifiers
|
||||
|
||||
These format codes indicate which data type is being used. They are needed for `printf` and `scanf`, for example.
|
||||
|
||||
| `%` | Description |
|
||||
| ------ | ------------------------------------------- |
|
||||
| `%%` | `%` |
|
||||
| `%-` | left align |
|
||||
| `%.1` | decimal precision |
|
||||
| `%1` | minimum field width |
|
||||
| `%c` | character |
|
||||
| `%d` | signed integer of base 10 |
|
||||
| `%e` | scientific notation |
|
||||
| `%f` | float |
|
||||
| `%hd` | small decimal (short) |
|
||||
| `%hhd` | very small decimal (char) |
|
||||
| `%i` | integer of any base (detects automatically) |
|
||||
| `%lf` | double |
|
||||
| `%o` | octal (base 8) |
|
||||
| `%p` | address/pointer |
|
||||
| `%s` | string (array of characters) |
|
||||
| `%u` | unsigned integer of base 10 |
|
||||
| `%x` | hexadecimal (base 16) |
|
||||
|
||||
```C
|
||||
float item1 = 5.75;
|
||||
printf("Item1: %-8.2\n", item1);
|
||||
```
|
||||
|
||||
## Numbers
|
||||
|
||||
`C` can handle multiple numeric bases.
|
||||
|
||||
```C
|
||||
int x = 255; // Decimal
|
||||
int y = 0xff; // Hexadecimal
|
||||
```
|
||||
|
||||
### Type Casting
|
||||
|
||||
Convert a type into another.
|
||||
|
||||
```C
|
||||
int x = 1, y = 10;
|
||||
float z = (float) x / (float) y;
|
||||
```
|
||||
|
||||
## Escape Sequences
|
||||
|
||||
Escape sequences are used to allow typing characters in a string that would otherwise be interpreted as `C` instructions.
|
||||
|
||||
| Seq | Name | Description |
|
||||
| ------ | ------------------ | -------------------------------------------------------------------------------------- |
|
||||
| `\a` | Alarm or Beep | It is used to generate a bell sound in the C program. |
|
||||
| `\b` | Backspace | It is used to move the cursor one place backward. |
|
||||
| `\f` | Form Feed | It is used to move the cursor to the start of the next logical page. |
|
||||
| `\n` | New Line | It moves the cursor to the start of the next line. |
|
||||
| `\r` | Carriage Return | It moves the cursor to the start of the current line. |
|
||||
| `\t` | Horizontal Tab | It inserts some whitespace to the left of the cursor and moves the cursor accordingly. |
|
||||
| `\v` | Vertical Tab | It is used to insert vertical space. |
|
||||
| `\\` | Backlash | Use to insert backslash character. |
|
||||
| `\'` | Single Quote | It is used to display a single quotation mark. |
|
||||
| `\"` | Double Quote | It is used to display double quotation marks. |
|
||||
| `\?` | Question Mark | It is used to display a question mark. |
|
||||
| `\ooo` | Octal Number | It is used to represent an octal number. |
|
||||
| `\xhh` | Hexadecimal Number | It represents the hexadecimal number. |
|
||||
| `\0` | `NULL` | It represents the NULL character. |
|
||||
| `\e` | Escape sequence | It represents the ASCII escape character. |
|
||||
| `\s` | Space Character | It represents the ASCII space character. |
|
||||
| `\d` | Delete Character | It represents the ASCII DEL character. |
|
||||
|
||||
## Constants
|
||||
|
||||
Add `const` before a variable declaration to prevent the value from being changed.
|
||||
|
||||
```C
|
||||
const float PI 3.14159;
|
||||
```
|
||||
|
||||
Another option is to use `define`.
|
||||
|
||||
```C
|
||||
#define MAX 9
|
||||
```
|
||||
|
||||
This command replaces the 'MAX' word with '9', using the preprocessor (before compiling). No extra memory required.
|
||||
|
||||
## Arithmetic Operators
|
||||
|
||||
```C
|
||||
// + (addition)
|
||||
// - (subtraction)
|
||||
// * (multiplication)
|
||||
// / (division)
|
||||
// % (modulus / remainder)
|
||||
// ++ (increment)
|
||||
// -- (decrement)
|
||||
int x = 1;
|
||||
int y = 2;
|
||||
int z = x + y; // 3
|
||||
// Augmented assignment operators
|
||||
x++; // x = x + 1
|
||||
y--; // y = y - 1
|
||||
x+=2; // x = x + 2
|
||||
x*=2; // x = x * 2
|
||||
```
|
||||
|
||||
## Control Flow
|
||||
|
||||
### Boolean Values
|
||||
|
||||
In `C`, there are no `true` or `false` keywords, so integers are used instead.
|
||||
- `0` generally represents `false`.
|
||||
- Any non-zero value (`1`, `-1`, etc…) represents `true`.
|
||||
|
||||
### IF Statement
|
||||
|
||||
```C
|
||||
if(a == 1) printf("A is 1.\\n");
|
||||
```
|
||||
|
||||
Use `{}` for multiple items.
|
||||
|
||||
```C
|
||||
if(age == 18){
|
||||
printf("You are 18.");
|
||||
}
|
||||
else if(age < 0){
|
||||
printf("You haven't been born yet.");
|
||||
}
|
||||
else{
|
||||
printf("You are not 18.");
|
||||
}
|
||||
```
|
||||
|
||||
### Switch Statement
|
||||
|
||||
Faster than IF when over 5 cases.
|
||||
|
||||
```C
|
||||
switch(grade){
|
||||
case 'A':
|
||||
printf("perfect.\n");
|
||||
break;
|
||||
case 'B':
|
||||
printf("good.\n");
|
||||
break;
|
||||
case 'C':
|
||||
printf("okay.\n");
|
||||
break;
|
||||
case 'D':
|
||||
printf("meh.\n");
|
||||
break;
|
||||
case 'F':
|
||||
printf("failed.\n");
|
||||
break;
|
||||
default:
|
||||
printf("Enter only valied grades.\n");
|
||||
}
|
||||
// If break; is missing, the next case is also executed.
|
||||
```
|
||||
|
||||
## Operators
|
||||
|
||||
### Logical Operators
|
||||
|
||||
#### AND (`&&`)
|
||||
|
||||
```C
|
||||
if(temp >= 0 && temp <= 30){
|
||||
printf("\nThe weather is good.")
|
||||
}
|
||||
```
|
||||
|
||||
#### OR (`||`)
|
||||
|
||||
```C
|
||||
if(temp <= 0 || temp >= 30){
|
||||
printf("\nThe weather is good.")
|
||||
}
|
||||
```
|
||||
|
||||
#### NOT (`!`)
|
||||
|
||||
```C
|
||||
if(!(temp <= 0 || temp >= 30)){
|
||||
printf("\nThe weather is bad.")
|
||||
}
|
||||
```
|
||||
|
||||
##### **NOT** Truth Table
|
||||
|
||||
| `condition` | `!(condition)` |
|
||||
| ----------- | -------------- |
|
||||
| 1 | 0 |
|
||||
| 0 | 1 |
|
||||
|
||||
### Ternary Operator
|
||||
|
||||
Shorthand syntax for if/else when assigning or returning a value.
|
||||
|
||||
```C
|
||||
// (condition) ? value if true : value if false
|
||||
int max = (x > y) ? x : y;
|
||||
```
|
||||
|
||||
### Bitwise Operators
|
||||
|
||||
Special operators used in bit-level programming. (Logic gates)
|
||||
|
||||
```C
|
||||
int x = 6; // 6 = 00000110
|
||||
int y = 12; // 12 = 00001100
|
||||
int z = 0; // 0 = 00000000
|
||||
z = x & y; // AND - 00000100 (4)
|
||||
z = x | y; // OR - 00001110 (14)
|
||||
z = x ^ y; // XOR - 00001010 (10)
|
||||
z = x << 1; // Left Shift - 00001100 (12) (Shift all bits to the left.)
|
||||
z = x >> 1; // Right Shift - 00000011 (3) (Shift all bits to the right.)
|
||||
```
|
||||
|
||||
## Functions
|
||||
|
||||
Functions are snippets of code that can be reused multiple times across the same file. These can receive multiple arguments as input, but can only return a single value.
|
||||
|
||||
```C
|
||||
void myFunction(); // Function Prototype
|
||||
int main() {
|
||||
myFunction(); // Call function
|
||||
return 0;
|
||||
}
|
||||
void myFunction() { // Function Definition
|
||||
//...
|
||||
}
|
||||
```
|
||||
|
||||
### Arguments
|
||||
|
||||
```C
|
||||
void greet(char x[], int y);
|
||||
int main() {
|
||||
char name[] = "Trude";
|
||||
int age = 132;
|
||||
greet(name, age);
|
||||
}
|
||||
void greet(char x[], int y) {
|
||||
printf("\nHello %s, you are %d years old.", x, y);
|
||||
}
|
||||
```
|
||||
|
||||
### Return Values
|
||||
|
||||
```C
|
||||
double square(double x);
|
||||
int main() {
|
||||
double x = square(3.14);
|
||||
printf("%lf", x);
|
||||
return 0;
|
||||
}
|
||||
double square(double x) {
|
||||
return x * x;
|
||||
}
|
||||
```
|
||||
|
||||
### Recursion
|
||||
|
||||
A function can call itself, creating a loop.
|
||||
|
||||
```C
|
||||
int i = 0;
|
||||
void plusOne(int n) {
|
||||
printf("%d", n);
|
||||
if (n < 10000) plusOne(n);
|
||||
}
|
||||
```
|
||||
|
||||
### Function Prototypes
|
||||
|
||||
Function declaration without a body, before `main()`.
|
||||
Prototypes ensure that calls to a function are made with the correct arguments, and allow functions to be defined under the function call.
|
||||
|
||||
```C
|
||||
void hello(char[], int); // Function Prototype
|
||||
int main() {
|
||||
hello(//...);
|
||||
return 0;
|
||||
}
|
||||
void hello(char name[], int age){
|
||||
//...
|
||||
}
|
||||
```
|
||||
|
||||
> **Note:** Many C compilers don't check for parameter matching, so missing arguments can lead to unexpected behavior.
|
||||
>
|
||||
> Function prototypes flag errors when arguments are missing.
|
||||
>
|
||||
> While not necessary if functions are declared before `main()`, using prototypes first and then declaring functions after `main()` improves readability and aids debugging.
|
||||
|
||||
## Loops
|
||||
|
||||
### For Loop
|
||||
|
||||
Loop through an interval.
|
||||
|
||||
```C
|
||||
for(int i = 0; i < 10; i++){
|
||||
printf("%d\n", I); //0-9
|
||||
}
|
||||
//Multiple initial variables
|
||||
for(int i = 0, int y = 1; i < 10; i++){
|
||||
printf("%d\n", I); //0-9
|
||||
}
|
||||
```
|
||||
|
||||
### While Loop
|
||||
|
||||
Loop until a condition is met.
|
||||
|
||||
```C
|
||||
while(test == 1){
|
||||
printf("Test is not 1.\n");
|
||||
}
|
||||
```
|
||||
|
||||
### Do While Loop
|
||||
|
||||
Run the code once, then repeat until a condition is met.
|
||||
|
||||
```C
|
||||
do {
|
||||
printf("Enter a number above 0: ");
|
||||
scanf("%d", &number)
|
||||
} while (number > 0);
|
||||
```
|
||||
|
||||
### Endless Loop
|
||||
|
||||
```C
|
||||
while (true) {
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
### Continue & Break Statements
|
||||
|
||||
- `continue` - Skips rest of code and forces the next iteration of the loop.
|
||||
- `break` - Exits a loop/switch.
|
||||
|
||||
## Structs
|
||||
|
||||
Structs can group values. They are similar to classes, but can't hold methods.
|
||||
Being able to group variables avoids repetition and name collision (when two variables have the same name).
|
||||
|
||||
```C
|
||||
struct Player {
|
||||
char name[12];
|
||||
int score;
|
||||
};
|
||||
int main(){
|
||||
struct Player player1;
|
||||
struct Player player2;
|
||||
strcpy(player1.name, "Trude");
|
||||
player1.score = 4;
|
||||
strcpy(player2.name, "JCionx");
|
||||
player2.score = 7;
|
||||
player1.score; //4
|
||||
}
|
||||
```
|
||||
|
||||
### Arrays of Structs
|
||||
|
||||
```C
|
||||
struct Student {
|
||||
char name[12];
|
||||
float gpa;
|
||||
};
|
||||
int main() {
|
||||
struct Student s1 = {"Peter", 3.0};
|
||||
struct Student s2 = {"Jean", 4.0};
|
||||
struct Student s3 = {"David", 2.5};
|
||||
struct Student students[] = {s1, s2, s3};
|
||||
printf("%f\n", students[0].gpa); // Print the student 1 gpa.
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
## Typedef
|
||||
|
||||
Create a shortcut for a type of data.
|
||||
|
||||
```C
|
||||
typedef char user[25];
|
||||
int main() {
|
||||
user user1 = "Trude";
|
||||
}
|
||||
```
|
||||
|
||||
Typedef can be used to simplify structs.
|
||||
|
||||
```C
|
||||
typedef struct {
|
||||
char name[25];
|
||||
char password[12];
|
||||
int id;
|
||||
} User;
|
||||
int main(){
|
||||
User user1 = {"Trude", "hello123", 12335};
|
||||
}
|
||||
```
|
||||
|
||||
## Nul Character
|
||||
|
||||
```C
|
||||
\0 // This character represents 00000000 and marks the end of a string.
|
||||
// Same as 0x0 and null.
|
||||
```
|
||||
|
||||
## Command-Line Arguments
|
||||
|
||||
- `argc` is the number of arguments in `argv`.
|
||||
- `argv[0]` is the name of the program, all others are the user arguments.
|
||||
|
||||
```C
|
||||
int main(int argc, char argv[]) {
|
||||
if (argc == 2) {
|
||||
printf("hello, %s\n", argv[1]);
|
||||
} else {
|
||||
printf("You need to add 1 argument.\n");
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
## Enums
|
||||
|
||||
Enums are a list of constant values that help make programs more readable.
|
||||
Enums are treated as integers.
|
||||
|
||||
```C
|
||||
// enum Day{Sun, Mon, Tue, Wed, Thu, Fri, Sat}; (This enum starts from 0 to 6.)
|
||||
enum Day{Sun = 1, Mon = 2, Tue = 3, Wed = 4, Thu = 5, Fri = 6, Sat = 7};
|
||||
int main(){
|
||||
enum Day today = Sun;
|
||||
if(today == Sun || today == Sat){
|
||||
printf("It's the weekend.");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Memory Management
|
||||
|
||||
- `a` - A variable
|
||||
- `&a` - The address of the variable `a` in memory. (The format is `%p`)
|
||||
- `int *p` - A pointer. Holds the memory address of another variable. (8 bits usually, depends on the CPU architecture (max RAM supported).
|
||||
- `*p` - Dereference a pointer. Returns the value in the address stored. (go to address's variable)
|
||||
|
||||
```C
|
||||
int age = 21;
|
||||
int *pAge = &age;
|
||||
int valueOfAge = *pAge;
|
||||
printf("%p and %p are the same.", &age, pAge);
|
||||
```
|
||||
|
||||
NOTE: A pointer must be `int`, as it points to a memory address.
|
||||
|
||||
### Strings
|
||||
|
||||
Strings are arrays of characters.
|
||||
A string can be returned as a memory address.
|
||||
A string ends in `\0`, the null character.
|
||||
|
||||
```C
|
||||
/* Use char[] when:
|
||||
- The maximum string length is known.
|
||||
- No need to modify the whole string.
|
||||
- No need to pass the string to a function [that modifies it]
|
||||
*/
|
||||
char name[] = "Trude"; // 6 bits on stack memory.
|
||||
name[0] = 'T'; // Elements of an array can be modified.
|
||||
/* Use char* when:
|
||||
- The maximum string length is NOT known.
|
||||
- The string will later be modified.
|
||||
- The string will be passed to a function [that modifies it].
|
||||
*/
|
||||
const char *name = "Trude"; // 8 bits in stack + 6 bits read-only.
|
||||
name = "TrudeEH"; // Pointers can be overwritten.
|
||||
name++; // rudeEH - Works because the pointer is shifted to the next value.
|
||||
peintf("%c\n", *(name+1)); // Prints 'r'.
|
||||
printf("%c\n", name[1]); // Works with both for reading.
|
||||
printf("%s\n", name); // Print a string.
|
||||
// The string in memory:
|
||||
// [T][r][u][d][e][\\0]
|
||||
// The memory address of T is stored.
|
||||
```
|
||||
|
||||
### String Operations
|
||||
|
||||
#### Compare String
|
||||
|
||||
```C
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
char s* = "Trude";
|
||||
char t* = "Trude";
|
||||
if (strcmp(s, t) == 0) {
|
||||
printf("Same string.");
|
||||
}
|
||||
```
|
||||
|
||||
#### Copy String (`malloc` example) Manually
|
||||
|
||||
```C
|
||||
#include <stdlib.h>
|
||||
char *s = "Trude";
|
||||
char *t = malloc(strlen(s) + 1);
|
||||
// 2 variables are declared, so strlen isn't called with every iteration.
|
||||
for (int i = 0, n = strlen(s) + 1; i < n; i++) {
|
||||
t[i] = s[i];
|
||||
)
|
||||
//...
|
||||
free(t);
|
||||
```
|
||||
|
||||
#### Copy String (string.h)
|
||||
|
||||
```C
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
char *s = "Trude";
|
||||
char *t = malloc(strlen(s) + 1);
|
||||
strcpy(t, s);
|
||||
//...
|
||||
free(t);
|
||||
```
|
||||
|
||||
Note: Use `valgrind` to detect memory leaks (lack of `free()`)
|
||||
|
||||
> **Always** initialize variables to a value, or random garbage values may be still in the variable's memory address.
|
||||
|
||||
### Input
|
||||
|
||||
#### Get Integer
|
||||
|
||||
```C
|
||||
#include <stdio.h>
|
||||
int main(void){
|
||||
int x;
|
||||
scanf("%i", &x);
|
||||
}
|
||||
```
|
||||
|
||||
#### Get String (Length is Known, safe)
|
||||
|
||||
`scanf` reads up to a whitespace.
|
||||
|
||||
```C
|
||||
#include <stdio.h>
|
||||
int main(void){
|
||||
char s[4];
|
||||
scanf("%4s", s); //No &, s is an address already.
|
||||
}
|
||||
```
|
||||
|
||||
`fgets` reads whitespaces.
|
||||
|
||||
```C
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
int age;
|
||||
char name[25];
|
||||
printf("What is your name? ");
|
||||
fgets(name, 25, stdin); // name of variable, max size, input.
|
||||
name[strlen(name)-1] = '\0'; // removes the line break fgets adds. String library is required.
|
||||
printf("How old are you? ");
|
||||
scanf("%d", &age);
|
||||
```
|
||||
|
||||
## Files
|
||||
|
||||
### Write to a File
|
||||
|
||||
```C
|
||||
#include <stdio.h>
|
||||
int main() {
|
||||
FILE *file = fopen("test.txt", "w"); // w - overwrite / a - append
|
||||
fprintf(file, "Some Text");
|
||||
fclose(file);
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
### Delete a File
|
||||
|
||||
```C
|
||||
#include <stdio.h>
|
||||
int main() {
|
||||
if(remove("test.txt") == 0){
|
||||
printf("File removed.\n");
|
||||
} else {
|
||||
printf("Failed to delete file.\n");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
### Read a File
|
||||
|
||||
```C
|
||||
#include <stdio.h>
|
||||
int main() {
|
||||
FILE *pF = fopen("test.txt", "r") // r - read.
|
||||
char buffer[255]; // Will hold 1 line of the file.
|
||||
if(pF == NULL){
|
||||
printf("File does not exist.");
|
||||
return 1;
|
||||
}
|
||||
fgets(buffer, 255, pF);
|
||||
printf("%s", buffer); // Print first line of file. Use in a while loop to print all of them.
|
||||
fclose(pF);
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
File manipulation accepts relative and absolute file paths.
|
||||
39
content/notes/ready/c-snippets.md
Normal file
@@ -0,0 +1,39 @@
|
||||
---
|
||||
title: C Snippets
|
||||
description:
|
||||
date: 2025-02-17T08:56:33+00:00
|
||||
draft: false
|
||||
tags:
|
||||
- c
|
||||
- programming
|
||||
author: TrudeEH
|
||||
showToc: true
|
||||
---
|
||||
|
||||
## Cast Strings to Numbers
|
||||
|
||||
The `atoi()` function in `stdlib` is implemented similarly to the one below.
|
||||
|
||||
ASCII encodes numbers in order, after special characters.
|
||||
|
||||
The encoded value for `'0'` is 48, so subtracting any numeric char by 48 outputs its real numerical value.
|
||||
|
||||
```C
|
||||
char number = '7';
|
||||
int result = number - 48;
|
||||
int same_result = number - '0';
|
||||
```
|
||||
|
||||
Algorithm to convert strings to numbers:
|
||||
|
||||
```C
|
||||
int str_to_int(char *str) {
|
||||
int result = 0;
|
||||
for (int i = 0; str[i] != '\0'; i++) {
|
||||
if (str[i] < '0' && str[1] > '9') return -1; // Error if NaN
|
||||
result = (result * 10) + (str[i] - '0');
|
||||
return result;
|
||||
}
|
||||
```
|
||||
|
||||
`(result * 10)` is shifting the previous number to the left, as it is an order of magnitude above the following digit.
|
||||
80
content/notes/ready/compiling.md
Normal file
@@ -0,0 +1,80 @@
|
||||
---
|
||||
title: Compiling [MAKE / GCC]
|
||||
description:
|
||||
date: 2025-02-17T08:59:53+00:00
|
||||
draft: false
|
||||
tags:
|
||||
- c
|
||||
- programming
|
||||
author: TrudeEH
|
||||
showToc: true
|
||||
---
|
||||
|
||||
|
||||
Convert `C` code into machine code in 4 steps:
|
||||
1. **Preprocessing** (Convert all preprocessor instructions: `#…`)
|
||||
2. **Compiling** (Convert `C` code to machine code)
|
||||
3. **Assembling** (Compile the necessary libraries)
|
||||
4. **Linking** (Merge the compiled code with the compiled libraries)
|
||||
|
||||
## Libraries
|
||||
|
||||
Libraries are pre-written collections of code that can be reused in other programs. On **UNIX* systems, they are usually located in the `/lib/` and `/usr/include` directories.
|
||||
|
||||
### Math.h
|
||||
|
||||
For example, `math.h` is very useful to implement complex arithmetic operations.
|
||||
|
||||
```C
|
||||
#include <math.h>
|
||||
double A = sqrt(9);
|
||||
double B = pow(2, 4);
|
||||
int C = round(3.14);
|
||||
int D = ceil(3.14);
|
||||
int E = floor(3.99);
|
||||
double F = fabs(-100);
|
||||
double G = log(3);
|
||||
double H = sin(45);
|
||||
double I = cos(45);
|
||||
double J = tan(45);
|
||||
```
|
||||
|
||||
### Using Libraries
|
||||
|
||||
To use a library, we first have to include it in the `C` code.
|
||||
|
||||
```C
|
||||
#include <cs50.h> // cs50.h library will be included.
|
||||
```
|
||||
|
||||
Then, the library must be linked at compile time.
|
||||
|
||||
```Shell
|
||||
gcc -o hello hello.c -lcs50
|
||||
./hello
|
||||
```
|
||||
|
||||
## Optimization Flags
|
||||
|
||||
- `-O2` Optimize for speed
|
||||
- `-O3` Optimize for speed aggressively
|
||||
- `-Os` Optimize for size
|
||||
- `-Og` Optimize for debugging
|
||||
- `-Oz` Optimize for size aggressively
|
||||
|
||||
## Make
|
||||
|
||||
`Make` Is a build automation tool that automates the process of compiling, linking and building executables.
|
||||
An example `Makefile` could look like the following:
|
||||
|
||||
```Makefile
|
||||
hello:
|
||||
gcc -o hello hello.c -lcs50
|
||||
clean:
|
||||
rm -f hello
|
||||
```
|
||||
|
||||
```Shell
|
||||
make #Compiles hello.c
|
||||
make clean #Removes the executable (hello) generated by the make command.
|
||||
```
|
||||
BIN
content/notes/ready/cpu_architecture/image10.png
Normal file
|
After Width: | Height: | Size: 213 KiB |
BIN
content/notes/ready/cpu_architecture/image11.png
Normal file
|
After Width: | Height: | Size: 219 KiB |
BIN
content/notes/ready/cpu_architecture/image12.png
Normal file
|
After Width: | Height: | Size: 36 KiB |
BIN
content/notes/ready/cpu_architecture/image13.png
Normal file
|
After Width: | Height: | Size: 186 KiB |
BIN
content/notes/ready/cpu_architecture/image14.png
Normal file
|
After Width: | Height: | Size: 214 KiB |
BIN
content/notes/ready/cpu_architecture/image15.png
Normal file
|
After Width: | Height: | Size: 297 KiB |
BIN
content/notes/ready/cpu_architecture/image16.png
Normal file
|
After Width: | Height: | Size: 306 KiB |
BIN
content/notes/ready/cpu_architecture/image17.png
Normal file
|
After Width: | Height: | Size: 121 KiB |
BIN
content/notes/ready/cpu_architecture/image18.png
Normal file
|
After Width: | Height: | Size: 139 KiB |
BIN
content/notes/ready/cpu_architecture/image19.png
Normal file
|
After Width: | Height: | Size: 358 KiB |
BIN
content/notes/ready/cpu_architecture/image20.png
Normal file
|
After Width: | Height: | Size: 357 KiB |
BIN
content/notes/ready/cpu_architecture/image21.png
Normal file
|
After Width: | Height: | Size: 244 KiB |
BIN
content/notes/ready/cpu_architecture/image22.png
Normal file
|
After Width: | Height: | Size: 217 KiB |
BIN
content/notes/ready/cpu_architecture/image23.png
Normal file
|
After Width: | Height: | Size: 205 KiB |
BIN
content/notes/ready/cpu_architecture/image24.png
Normal file
|
After Width: | Height: | Size: 89 KiB |
BIN
content/notes/ready/cpu_architecture/image25.png
Normal file
|
After Width: | Height: | Size: 313 KiB |
BIN
content/notes/ready/cpu_architecture/image26.png
Normal file
|
After Width: | Height: | Size: 318 KiB |
BIN
content/notes/ready/cpu_architecture/image27.png
Normal file
|
After Width: | Height: | Size: 338 KiB |
BIN
content/notes/ready/cpu_architecture/image28.png
Normal file
|
After Width: | Height: | Size: 324 KiB |
BIN
content/notes/ready/cpu_architecture/image29.png
Normal file
|
After Width: | Height: | Size: 187 KiB |
BIN
content/notes/ready/cpu_architecture/image30.png
Normal file
|
After Width: | Height: | Size: 228 KiB |
BIN
content/notes/ready/cpu_architecture/image31.png
Normal file
|
After Width: | Height: | Size: 216 KiB |
BIN
content/notes/ready/cpu_architecture/image32.png
Normal file
|
After Width: | Height: | Size: 97 KiB |
BIN
content/notes/ready/cpu_architecture/image33.png
Normal file
|
After Width: | Height: | Size: 64 KiB |
BIN
content/notes/ready/cpu_architecture/image34.png
Normal file
|
After Width: | Height: | Size: 314 KiB |
BIN
content/notes/ready/cpu_architecture/image35.png
Normal file
|
After Width: | Height: | Size: 298 KiB |
BIN
content/notes/ready/cpu_architecture/image36.png
Normal file
|
After Width: | Height: | Size: 90 KiB |
BIN
content/notes/ready/cpu_architecture/image37.png
Normal file
|
After Width: | Height: | Size: 41 KiB |
BIN
content/notes/ready/cpu_architecture/image38.png
Normal file
|
After Width: | Height: | Size: 60 KiB |
BIN
content/notes/ready/cpu_architecture/image39.png
Normal file
|
After Width: | Height: | Size: 72 KiB |
BIN
content/notes/ready/cpu_architecture/image8.png
Normal file
|
After Width: | Height: | Size: 132 KiB |
BIN
content/notes/ready/cpu_architecture/image9.png
Normal file
|
After Width: | Height: | Size: 205 KiB |
162
content/notes/ready/cpu_architecture/index.md
Normal file
@@ -0,0 +1,162 @@
|
||||
---
|
||||
title: CPU Architecture
|
||||
description:
|
||||
date: 2025-02-17T08:06:50+00:00
|
||||
draft: false
|
||||
tags:
|
||||
- computer-science
|
||||
author: TrudeEH
|
||||
showToc: true
|
||||
---
|
||||
|
||||
## Components
|
||||
|
||||
### Registers
|
||||
|
||||
We can combine registers to reduce the amount of wires needed.
|
||||
![[image8.png]]
|
||||
Using a data bus (wiring at the top) and a binary decoder, we can select which register to read/write to.
|
||||
|
||||
### Memory
|
||||
|
||||
![[image9.png]]
|
||||
|
||||
## Assembly
|
||||
|
||||
Assembly is a human-friendly representation of code: binary values that a computer can understand.
|
||||
![[image10.png]]
|
||||
An assembler converts ASM instructions into machine code, which is given to the CPU as input.
|
||||
|
||||
### Arithmetic Operations
|
||||
|
||||
For example, a simple computer architecture could use `00` to represent arithmetic operations.
|
||||
![[image11.png]]
|
||||
To decide which type of operation to execute (subtraction, multiplication, addition, etc), the 3rd and 4th bits could be used.
|
||||
![[image12.png]]
|
||||
Using a [[ready/binary-operations/index]], we can build an inefficient, but simple circuit to do this.
|
||||
![[image13.png]]
|
||||
This type of circuit is an Arithmetic Logic Unit (ALU).
|
||||
|
||||
### Memory Operations
|
||||
|
||||
Of course, assembly can also provide instructions to store or load values.
|
||||
![[image14.png]]
|
||||
|
||||
#### Load
|
||||
|
||||
```Assembly
|
||||
LOAD R2 1000 ;Load into register 2 the value in the memory address 1000
|
||||
```
|
||||
|
||||
![[image15.png]]
|
||||
|
||||
#### Store
|
||||
|
||||
```Assembly
|
||||
STORE R1 0110 ;Store the value in register 1 into the 0110 memory address
|
||||
```
|
||||
|
||||
![[image16.png]]
|
||||
|
||||
#### Select Which Instruction to Execute (first 2 bits)
|
||||
|
||||
To decide which operation to execute, a binary decoder can be used.
|
||||
![[image17.png]]
|
||||
For memory operations, the 3rd and 4th bits are used to select which register to use.
|
||||
![[image18.png]]
|
||||
The last 4 bits represent the memory address to read/write to.
|
||||
![[image19.png]]
|
||||
|
||||
### Instruction Register
|
||||
|
||||
For the instruction to be given, it is stored in a special register: An Instruction Register.
|
||||
![[image20.png]]
|
||||
|
||||
### Optimization
|
||||
|
||||
We can use a single Binary Decoder instead of two, to achieve the same result. (Optimization on the right pane)
|
||||
![[image21.png]]
|
||||
Different architectures can have the exact same functionality, while being implemented differently, or even having different instructions. This is why code that is compiled for Intel x64 is not compatible with ARM or RISC-V.
|
||||
|
||||
## Control Unit
|
||||
|
||||
We can finally add the ALU (Arithmetic Logic Unit) we built before into the new circuit, like so:
|
||||
![[image22.png]]
|
||||
The gray trapezoids are multiplexers:
|
||||
![[image23.png]]
|
||||
The output value is then stored in a temporary register, before replacing the first operand register's value.
|
||||
The component we just built to control the `ALU` is part of a `Control Unit`. The full `control unit` is very complex, as it needs to handle every possible instruction. (So far, we have seen how to implement the `ALU` and `RAM`.)
|
||||
![[image24.png]]
|
||||
Each register in the `CU` has a specific purpose, unlike `RAM`, which can be used to store any values.
|
||||
![[image25.png]]
|
||||
To read the first instruction, the `CU` will **fetch** data from the first address in memory.
|
||||
![[image26.png]]
|
||||
After **fetching**, the `CU` will **decode** the instruction: interpret the bit sequence in the `instruction register`, to send the necessary signals to the components that will **execute** the instruction. We can finally load instructions into the instruction register.
|
||||
![[image27.png]]
|
||||
Then, the `CU` increments 1 byte, to point the `address register` to the next instruction. (Modern architectures increment different values, as the instruction set is more complex)
|
||||
If the instruction is an arithmetic operation, the steps are similar. The ALU stores the output in a temporary register, which overwrites the register 0 with the result. The result can then be stored in `RAM`.
|
||||
![[image28.png]]
|
||||
|
||||
## Load a Program Into Memory
|
||||
|
||||
So far, we can store instructions in memory, but it is also necessary to store values, besides from the instructions themselves.
|
||||
For example:
|
||||
![[image29.png]]
|
||||
This program uses 2 numeric values. The first 2 instructions load these values into the registers, and then, these values are added together and stored in another memory address. The final instruction, `HALT`, marks the end of the program, to make sure the `CU` does not attempt to read the number 20 as an instruction.
|
||||
If the program is extended, all memory addresses must be altered. To fix this issue, we can instead store values at the end of the memory stack.
|
||||
![[image30.png]]
|
||||
|
||||
## Conditions and Loops
|
||||
|
||||
To create a loop, we can simply jump to a smaller address in memory.
|
||||
![[image31.png]]
|
||||
Internally, the `JMP` command overwrites the Address Register, making it so that the next CPU **cycle** *fetches* the chosen memory address, instead of the next one.
|
||||
![[image32.png]]
|
||||
|
||||
### Flags
|
||||
|
||||
Sometimes, we might want to loop only if a certain condition is met.
|
||||
For context, imagine subtracting a number from itself. In this case, the ALU will provide some extra information, using 1 bit registers called `flags`.
|
||||
![[image33.png]]
|
||||
|
||||
| N | Flag | Description |
|
||||
| --- | ------------ | --------------------------------------------------------- |
|
||||
| 0 | **O**verflow | When a number is too large to fit in the output register. |
|
||||
| 1 | **Z**ero | When the result is zero. |
|
||||
| 0 | **N**egative | When a number is negative. |
|
||||
|
||||
This additional information can be used to make decisions, and make **conditional jumps** possible.
|
||||
|
||||
| ASM | Command | Description |
|
||||
| -------------- | ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `JMP_OFW XXXX` | Jump Overflow | Overwrites the `Address Register` with the value `XXXX` if the `O_FLAG` is **ON**. If the flag is **OFF**, the `Address Register`'s value is incremented by **1**. |
|
||||
| `JMP_ZRO XXXX` | Jump Zero | Overwrites the `Address Register` with the value `XXXX` if the `Z_FLAG` is **ON**. If the flag is **OFF**, the `Address Register`'s value is incremented by **1**. |
|
||||
| `JMP_NEG XXXX` | Jump Negative | Overwrites the `Address Register` with the value `XXXX` if the `N_FLAG` is **ON**. If the flag is **OFF**, the `Address Register`'s value is incremented by **1**. |
|
||||
| `JMP_ABV XXXX` | Jump Above | Overwrites the `Address Register` with the value `XXXX` if **neither** the `Z_FLAG` nor `N_FLAG` are **ON**. If either is **ON,** the `Address Register`'s value is incremented by **1**. |
|
||||
|
||||
Comparing two numbers is the same as subtracting them.
|
||||
|
||||
$$a - 5 = b$$
|
||||
|
||||
| **b** is negative | **b** is zero | **b** is positive |
|
||||
| ----------------- | ------------- | ----------------- |
|
||||
| then | then | then |
|
||||
| a < 5 | a == 5 | a > 5 |
|
||||
|
||||
For example:
|
||||
![[image34.png]]
|
||||
An `IF` statement works in the exact same way, but without the need to loop:
|
||||
![[image35.png]]
|
||||
Note: These instructions are not from any real architecture. These are examples for this simple, custom architecture.
|
||||
|
||||
## Clock
|
||||
|
||||
The final piece of the puzzle is the clock. A clock can give us time before a circuit loops.
|
||||
![[image36.png]]
|
||||
This is necessary, because energy travels extremely quickly, and so, all memory would be reset before we could even use the stored values. Each clock tick corresponds to an action the `CU` performs (fetch, decode and execute).
|
||||
A `Data FLIP-FLOP`, for example, uses the clock to store data, acting as the manual `RESET` input.
|
||||
![[image37.png]]
|
||||
This circuit can be used to build a single bit register.
|
||||
![[image38.png]]
|
||||
To generate a clock pulse, we can use a circuit similar to this one:
|
||||
![[image39.png]]
|
||||
BIN
content/notes/ready/databases/image94.png
Normal file
|
After Width: | Height: | Size: 130 KiB |
BIN
content/notes/ready/databases/image95.png
Normal file
|
After Width: | Height: | Size: 27 KiB |
322
content/notes/ready/databases/index.md
Normal file
@@ -0,0 +1,322 @@
|
||||
---
|
||||
title: Databases [SQL]
|
||||
description:
|
||||
date: 2025-02-17T08:27:35+00:00
|
||||
draft: false
|
||||
tags:
|
||||
- programming
|
||||
- web
|
||||
author: TrudeEH
|
||||
showToc: true
|
||||
---
|
||||
|
||||
## Flat-File Databases
|
||||
|
||||
A "table" written into a single file. The most common file type for this purpose is `CSV`.
|
||||
The `CSV` format reads each line as a row, and each comma-separated value as a column.
|
||||
The first row on a `CSV` file is used to describe the data in each column. If a `,` is present on the dataset, surround that entry with `"` to 'escape' it.
|
||||
These files can be read and written to using languages like [[c-language]] and [[python]].
|
||||
|
||||
## Relational Databases
|
||||
|
||||
Instead of using a single table, a relational database can store data in multiple tables, and then define relationships between them.
|
||||
Each table must have one column with an unique key that identifies each row.
|
||||
![[image94.png]]
|
||||
|
||||
### Relationships
|
||||
|
||||
#### One-to-one Relationship
|
||||
|
||||
In this example, `id` in `shows` corresponds to the `show_id` in the `ratings` table.
|
||||
|
||||
#### One-to-many Relationship
|
||||
|
||||
`shows` has a one-to-many relationship with `genres`, because a single show entry can have many genders.
|
||||
|
||||
#### Many-to-many Relationship
|
||||
|
||||
Both the `people` and `writers` table have a field shared with `stars`.
|
||||
|
||||
## SQL
|
||||
|
||||
`SQL` is a language designed specifically for interfacing with relational databases.
|
||||
To use `SQL`, a database is needed, so, for this example, I will use `sqlite3`.
|
||||
|
||||
### Create a Database
|
||||
|
||||
```Shell
|
||||
sqlite3 name.db # Create a db file and initialize it.
|
||||
```
|
||||
|
||||
### `sqlite3` Commands
|
||||
|
||||
#### Import a `CSV` Table
|
||||
|
||||
```SQL
|
||||
.mode csv
|
||||
.import name.csv table_name
|
||||
```
|
||||
|
||||
#### General Commands
|
||||
|
||||
```SQL
|
||||
.schema -- Print all tables and fields (using the commands used for creation)
|
||||
.schema table -- Show the command used for creating a table
|
||||
.exit
|
||||
```
|
||||
|
||||
### Base Syntax
|
||||
|
||||
```SQL
|
||||
CREATE TABLE table (column type, ...); -- Create a new table
|
||||
SELECT columns FROM table; -- Output/Print data
|
||||
INSERT INTO table (column, ...) VALUES(value, ...); -- Add data
|
||||
UPDATE table SET column = value WHERE condition; -- Update values
|
||||
DELETE FROM table WHERE condition; -- Delete data
|
||||
```
|
||||
|
||||
> In `SQL`, there is **NO WAY** to undo actions. Especially when writing or deleting from the database, do not type `;` unless you know exactly what you are doing!
|
||||
|
||||
#### Wildcard
|
||||
|
||||
```SQL
|
||||
SELECT * FROM table; -- Outputs every column in the table (wildcard selector)
|
||||
```
|
||||
|
||||
### Functions
|
||||
|
||||
#### Math Functions
|
||||
|
||||
- `AVG`
|
||||
- `COUNT`
|
||||
- `DISTINCT`
|
||||
- `LOWER`
|
||||
- `MAX`
|
||||
- `MIN`
|
||||
- `UPPER`
|
||||
- `LOWER`
|
||||
- `…`
|
||||
|
||||
```SQL
|
||||
SELECT COUNT(*) FROM table; -- Counts the number of rows in a table
|
||||
SELECT DISTINCT column from table; -- Show only the unique values in a column
|
||||
SELECT COUNT(DISTINCT column) FROM table; -- Count the unique values in a column
|
||||
```
|
||||
|
||||
#### Logic Functions
|
||||
|
||||
- `GROUP BY`
|
||||
- `LIKE`
|
||||
- `LIMIT`
|
||||
- `ORDER BY`
|
||||
- `WHERE`
|
||||
- `…`
|
||||
|
||||
```SQL
|
||||
-- Count every instance of a value in a column
|
||||
SELECT COUNT(*) FROM table WHERE column = 'string';
|
||||
-- LIKE is used to select using formatting. '%' selects every character after)
|
||||
SELECT * FROM favorites WHERE prog_language = 'C' AND problem LIKE "Hello, %"
|
||||
-- Group all individual rows and display their count
|
||||
SELECT prog_language, COUNT(*) FROM favorites GROUP BY prog_language;
|
||||
-- Sort values by their count, ascending.
|
||||
SELECT prog_language, COUNT(*) FROM favorites GROUP BY prog_language ORDER BY COUNT(*);
|
||||
-- Sort values by their count, descending.
|
||||
SELECT prog_language, COUNT(*) FROM favorites GROUP BY prog_language ORDER BY COUNT(*) DESC;
|
||||
-- Limit the output to a single row (showing the most popular language, in this case)
|
||||
SELECT prog_language, COUNT(*) FROM favorites GROUP BY prog_language ORDER BY COUNT(*) DESC LIMIT 1;
|
||||
```
|
||||
|
||||
#### Operators
|
||||
|
||||
- `AND`
|
||||
- `OR`
|
||||
|
||||
```SQL
|
||||
-- Using the AND operator to select two values
|
||||
SELECT * FROM table WHERE column1 = 'a' AND column2 = 'b';
|
||||
-- AND and OR (' is escaped using '' (' twice))
|
||||
SELECT * FROM table WHERE prog_language = 'C' AND (problem = 'Hello, World' OR problem = 'Hello, It''s Me');
|
||||
```
|
||||
|
||||
#### Aliases
|
||||
|
||||
- `AS`
|
||||
|
||||
```SQL
|
||||
-- The column COUNT(*) will be renamed to 'n'.
|
||||
SELECT prog_language, COUNT(*) AS n FROM favorites GROUP BY prog_language ORDER BY n DESC;
|
||||
```
|
||||
|
||||
#### Conditions
|
||||
|
||||
- `IS`
|
||||
|
||||
```SQL
|
||||
-- Delete all values where timestamp1 is a NULL value.
|
||||
DELETE FROM favorites WHERE timestamp1 IS NULL;
|
||||
```
|
||||
|
||||
### Data Types
|
||||
|
||||
- `BLOB`
|
||||
- `INTEGER`
|
||||
- `NUMERIC`
|
||||
- `REAL`
|
||||
- `TEXT`
|
||||
|
||||
- `NULL`
|
||||
- `NOT NULL`
|
||||
- `UNIQUE`
|
||||
|
||||
- `PRIMARY KEY`
|
||||
- `FOREIGN KEY`
|
||||
|
||||
### Relationships
|
||||
|
||||
- `IN`
|
||||
- `JOIN`
|
||||
|
||||
#### One-to-one
|
||||
|
||||
```SQL
|
||||
-- 'shows' table
|
||||
CREATE TABLE shows (
|
||||
id INTEGER,
|
||||
title TEXT NOT NULL,
|
||||
year NUMERIC,
|
||||
episodes INTEGER,
|
||||
PRIMARY KEY(id)
|
||||
);
|
||||
-- Table connected with a one-to-one relationship with the 'shows' table
|
||||
CREATE TABLE ratings (
|
||||
show_id INTEGER NOT NULL,
|
||||
rating REAL NOT NULL,
|
||||
votes INTEGER NOT NULL,
|
||||
FOREIGN KEY(show_id) REFERENCES shows(id)
|
||||
);
|
||||
-- Lists 'show_id', but not the actual names of each show.
|
||||
SELECT show_id FROM ratings WHERE rating >= 6.0 LIMIT 10;
|
||||
-- Executes the nested query first, then shows the entries selected on 'shows'
|
||||
SELECT * FROM shows WHERE id IN
|
||||
(SELECT show_id FROM ratings WHERE rating >= 6.0)
|
||||
LIMIT 10;
|
||||
-- Join both tables
|
||||
SELECT title, rating FROM shows JOIN
|
||||
ratings ON shows.id = ratings.show_id WHERE rating >= 6.0
|
||||
LIMIT 10;
|
||||
```
|
||||
|
||||
#### One-to-many
|
||||
|
||||
- `ON`
|
||||
|
||||
```SQL
|
||||
CREATE TABLE genres (
|
||||
show_id INTEGER NOT NULL,
|
||||
genre TEXT NOT NULL,
|
||||
FOREIGN KEY(show_id) REFERENCES shows(id)
|
||||
);
|
||||
|
||||
-- Search for all genres for a show
|
||||
SELECT genre FROM genres WHERE show_id =
|
||||
(SELECT id FROM shows WHERE title = 'TitleOfShow');
|
||||
-- Join tables, to show title alongside genres of a show
|
||||
SELECT title, genre FROM shows JOIN genres ON shows.id =
|
||||
genres.show_id WHERE id =
|
||||
(SELECT id FROM shows WHERE title = 'TitleOfShow');
|
||||
```
|
||||
|
||||
#### Many-to-many
|
||||
|
||||
![[image95.png]]
|
||||
|
||||
```SQL
|
||||
-- Select every person who starred in a show
|
||||
SELECT name FROM people WHERE id IN
|
||||
(SELECT person_id FROM stars WHERE show_id =
|
||||
(SELECT id FROM shows WHERE title = 'Some Name'));
|
||||
-- Joined table with the show name and stars
|
||||
SELECT title FROM shows JOIN people.name WHERE id IN
|
||||
(SELECT person_id FROM stars WHERE show_id =
|
||||
(SELECT id FROM shows WHERE title = 'Some Name'));
|
||||
-- Another way to join tables
|
||||
SELECT title FROM shows, stars, people
|
||||
WHERE shows.id = stars.show_id
|
||||
AND people.id = stars.person_id
|
||||
AND name = 'Name';
|
||||
```
|
||||
|
||||
### Indexes
|
||||
|
||||
Load an index of the database into RAM to optimize searches.
|
||||
The underneath algorithm is a `B-Tree`, which takes up more space in memory and slightly slows write speed on the database.
|
||||
|
||||
```SQL
|
||||
CREATE INDEX name ON table (column, ...);
|
||||
.timer ON -- sqlite3 command to show how long operations take to complete
|
||||
SELECT * FROM shows WHERE title = 'Name'; -- 0.043s
|
||||
CREATE INDEX title_index ON shows(title); -- Index title on shows
|
||||
SELECT * FROM shows WHERE title = 'Name'; -- 0.001s
|
||||
SELECT name FROM people WHERE id IN
|
||||
(SELECT person_id FROM stars WHERE show_id =
|
||||
(SELECT id FROM shows WHERE title = 'Some Name')); -- 0.215s
|
||||
CREATE INDEX name_index ON people(name);
|
||||
CREATE INDEX person_index ON stars(person_id);
|
||||
SELECT name FROM people WHERE id IN
|
||||
(SELECT person_id FROM stars WHERE show_id =
|
||||
(SELECT id FROM shows WHERE title = 'Some Name')); -- 0.001s
|
||||
```
|
||||
|
||||
### Race Conditions
|
||||
|
||||
When `SQL` is integrated with languages such as `Python`, for example, or is being accessed by multiple instances, race conditions may arise.
|
||||
For example, consider the following code:
|
||||
|
||||
```Python
|
||||
...
|
||||
rows = db.execute("SELECT likes FROM posts WHERE id = ?", id);
|
||||
likes = rows[0]["likes"]
|
||||
db.execute("UPDATE posts SET likes = ? WHERE id = ?", likes + 1, id);
|
||||
```
|
||||
|
||||
If this code is executed twice at the same time, instead of adding 2 likes to the database, only one will be added, because the program would read the database in the same state, and then add +1 like to that same, previous state.
|
||||
`SQL` provides solutions to this in the form of **transactions**:
|
||||
- `BEGIN TRANSACTION`
|
||||
- `COMMIT`
|
||||
- `ROLLBACK`
|
||||
On `Python`, a solution could be:
|
||||
|
||||
```Python
|
||||
db.execute("BEGIN TRANSACTION")
|
||||
rows = db.execute("SELECT likes FROM posts WHERE id = ?", id);
|
||||
likes = rows[0]["likes"]
|
||||
db.execute("UPDATE posts SET likes = ? WHERE id = ?", likes + 1, id);
|
||||
db.execute("COMMIT")
|
||||
```
|
||||
|
||||
Where the database would be "locked" while the program ran.
|
||||
|
||||
### `SQL` Injection Attacks
|
||||
|
||||
If a program asks for user input, and that input is then passed over to the database, the user could write special `SQL` syntax to break the query.
|
||||
For example:
|
||||
If a program takes an email address as input, some user could type: `email@example.com'--`, which marks a comment.
|
||||
If the query was similar to the following:
|
||||
|
||||
```Python
|
||||
rows = db.execute(f"SELECT * FROM users WHERE email = '{email}' AND password = {psk}")
|
||||
```
|
||||
|
||||
Replacing values…
|
||||
|
||||
```Python
|
||||
rows = db.execute(f"SELEC * FROM users WHERE email = 'email@example.com'--' AND password = 'password123'")
|
||||
```
|
||||
|
||||
Which would result in the user being able to log in without needing a password.
|
||||
The solution to this is to use a library which uses placeholders to insert data in queries.
|
||||
|
||||
```Python
|
||||
rows = db.execute("SELECT * FROM users WHERE email = ? AND password = ?", email, psk)
|
||||
```
|
||||
110
content/notes/ready/diodes.md
Normal file
@@ -0,0 +1,110 @@
|
||||
---
|
||||
title: Diodes
|
||||
description:
|
||||
date: 2025-02-17T08:18:09+00:00
|
||||
draft: false
|
||||
tags:
|
||||
- electronics
|
||||
author: TrudeEH
|
||||
showToc: true
|
||||
---
|
||||
|
||||
|
||||
|
||||
A diode allows current to only flow in one direction in a circuit.
|
||||
|
||||
## Schematic
|
||||
|
||||
```Plain
|
||||
Anode (+) --|>|-- Cathode (-)
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
```Plain
|
||||
[Conventional Current (+) -> (-)]
|
||||
(+)------|>|------(-) Current can flow - The diode is now a conductor.
|
||||
(+)------|<|------(-) Current can't flow - The diode is now an insulator.
|
||||
```
|
||||
|
||||
## Use Cases
|
||||
|
||||
- Protect a circuit (if a battery is connected incorrectly, for example)
|
||||
- Convert AC to DC current
|
||||
Fun fact: An LED, for example, is a Light-Emitting Diode.
|
||||
|
||||
## How a Diode Works
|
||||
|
||||
### Conductors and Insulators
|
||||
|
||||
An atom contains the following elements:
|
||||
- Nucleus (Protons - Neutrons)
|
||||
- Orbital Shells (Holds the electrons, which orbit around the nucleus)
|
||||
- Conduction band
|
||||
The electrons closest to the nucleus hold the most energy.
|
||||
The outermost shell is the valence shell. A conductor has 1-3 electrons in the valence shell.
|
||||
If an electron reaches the conduction band, it can break free and move to another atom.
|
||||
An insulator, however, has a conduction band that is far from the valence shell, making it difficult for an electron to escape.
|
||||
For example, for copper (a great conductor), the valence shell and conduction band overlap, so it's very easy for an electron to jump between atoms.
|
||||
Semiconductors have a conduction band close to the valence shell, but have one extra electron in it, making it an insulator. However, given some external energy, some electrons will gain enough energy to reach the conduction band and become free.
|
||||
|
||||
### P-Type and N-Type Doping
|
||||
|
||||
Silicon is a good semiconductor, having 4 electrons in its valence shell. When close to other `Si` atoms, they share 4 electrons with their neighbors, thus, having 8, each, and becoming stable.
|
||||
|
||||
```Plain
|
||||
Silicon:
|
||||
Si Si Si Si Si Si Si Si Si Si Si
|
||||
Si Si Si Si Si Si Si Si Si Si Si
|
||||
Si Si Si Si Si Si Si Si Si Si Si
|
||||
Si Si Si Si Si Si Si Si Si Si Si
|
||||
Si Si Si Si Si Si Si Si Si Si Si
|
||||
Si Si Si Si Si Si Si Si Si Si Si
|
||||
```
|
||||
|
||||
#### N-Type
|
||||
|
||||
Some Phosphorus is added to the Silicon. ==`p`== has one extra electron in its valence shell.
|
||||
These electrons are not needed, and so, they flow freely from atom to atom.
|
||||
|
||||
```Plain
|
||||
Si Si p Si Si Si Si Si Si Si p
|
||||
p Si Si Si Si p Si Si Si Si Si
|
||||
Si Si Si p Si Si Si Si p Si Si
|
||||
Si p Si Si p Si Si Si Si Si Si
|
||||
Si Si Si Si Si Si p Si Si p Si
|
||||
Si p Si Si Si Si Si Si p Si Si
|
||||
```
|
||||
|
||||
#### P-Type
|
||||
|
||||
Some Aluminum is added to the Silicon. `Al` is missing one electron, so it can't provide its 4 neighbors with an electron to share.
|
||||
|
||||
```Plain
|
||||
Si Si Al Si Si Si Si Si Si Si Al
|
||||
Al Si Si Si Si Al Si Si Si Si Si
|
||||
Si Si Si Al Si Si Si Si Al Si Si
|
||||
Si Al Si Si Al Si Si Si Si Si Si
|
||||
Si Si Si Si Si Si Al Si Si Al Si
|
||||
Si Al Si Si Si Si Si Si Al Si Si
|
||||
```
|
||||
|
||||
### Combining both Types
|
||||
|
||||
When an N-Type is combined with a P-Type, some electrons from the N-Type side will move over to the P-Type side and occupy the missing electrons there. This creates a barrier between both types, creating an electric field that prevents more electrons from switching sides.
|
||||
|
||||
#### Forward Bias
|
||||
|
||||
If energy is provided to the Cathode, the electrons flow, as the voltage is superior to the barrier's.
|
||||
|
||||
```Plain
|
||||
(-)-----[P|N]-----(+)
|
||||
```
|
||||
|
||||
#### Reverse Bias
|
||||
|
||||
If energy is provided to the Anode, the electrons can't flow, as the barrier expands.
|
||||
|
||||
```Plain
|
||||
(-)--[P] [N]--(+)
|
||||
```
|
||||
118
content/notes/ready/encryption.md
Normal file
@@ -0,0 +1,118 @@
|
||||
---
|
||||
title: Encryption [GPG]
|
||||
description:
|
||||
date: 2025-02-17T09:02:06+00:00
|
||||
draft: false
|
||||
tags:
|
||||
- networking
|
||||
- tools
|
||||
author: TrudeEH
|
||||
showToc: true
|
||||
---
|
||||
|
||||
## Symmetric Encryption
|
||||
|
||||
- User A sends a password to user B.
|
||||
- The password is used to encrypt the messages.
|
||||
- A secure way to share the password is required.
|
||||
|
||||
## Asymmetric Encryption
|
||||
|
||||
- Users A and B have a public key and a private key.
|
||||
- The public keys are shared, and they are used to encrypt the messages.
|
||||
- The users can use their private keys to decrypt the messages.
|
||||
|
||||
## GPG
|
||||
|
||||
### Create a Set of Keys
|
||||
|
||||
```Shell
|
||||
gpg --full-gen-key
|
||||
Select ECC (sign and encrypt) - The most secure option
|
||||
Select default curve
|
||||
```
|
||||
|
||||
### Encrypt a File
|
||||
|
||||
```Shell
|
||||
gpg --encrypt -r email@example.org <file> # Encrypt with the recipient (-r) key.
|
||||
```
|
||||
|
||||
### Decrypt a File
|
||||
|
||||
```Shell
|
||||
gpg --decrypt --output <file-output> <file> # Use the private key to decrypt a file.
|
||||
```
|
||||
|
||||
### Encrypt a Message
|
||||
|
||||
```Shell
|
||||
echo "Very safe message" | --encrypt --armor -r email@example.org
|
||||
```
|
||||
|
||||
- `-armor` Saves the encrypted info in plain text. (Great for blog posts or copying/pasting)
|
||||
|
||||
### Decrypt a Message
|
||||
|
||||
GPG automatically figures out which private key to use. The encrypted file includes some metadata.
|
||||
|
||||
```Shell
|
||||
cat encrypted-message.txt | gpg --decrypt
|
||||
```
|
||||
|
||||
### Sign a Message
|
||||
|
||||
Uses a public key to sign a message, making sure that the contents are not tampered with.
|
||||
|
||||
```Shell
|
||||
echo "Very important message" | gpg --clearsign -u email@example.org
|
||||
```
|
||||
|
||||
- `-clearsign` Is used to sign plain (clear) text.
|
||||
|
||||
### Sign a File
|
||||
|
||||
The signature is embedded in the file
|
||||
|
||||
```Shell
|
||||
gpg --sign -u email@example.org <file>
|
||||
```
|
||||
|
||||
The signature is separate from the file
|
||||
|
||||
```Shell
|
||||
gpg --detach-sign -u email@example.org <file>
|
||||
```
|
||||
|
||||
### Verify Signed message/file
|
||||
|
||||
```Shell
|
||||
gpg --verify signed-message.txt
|
||||
# or, if detached
|
||||
gpg --verify <file.sig> <file>
|
||||
```
|
||||
|
||||
### Import
|
||||
|
||||
```Shell
|
||||
gpg --import public.pgp
|
||||
gpg --import private.pgp
|
||||
# To be able to use the key for encryption, it must be trusted.
|
||||
gpg --edit-key email@example.com
|
||||
> trust
|
||||
> 5
|
||||
```
|
||||
|
||||
### Export
|
||||
|
||||
```Shell
|
||||
gpg --output public.pgp --armor --export email@example.com
|
||||
gpg --output private.pgp --armor --export-secret-keys email@example.com
|
||||
```
|
||||
|
||||
### List Keys
|
||||
|
||||
```Shell
|
||||
gpg --list-keys # Same as gpg -k
|
||||
gpg --list-secret-keys
|
||||
```
|
||||
349
content/notes/ready/flask.md
Normal file
@@ -0,0 +1,349 @@
|
||||
---
|
||||
title: Flask
|
||||
description:
|
||||
date: 2025-02-17T09:01:01+00:00
|
||||
draft: false
|
||||
tags:
|
||||
- programming
|
||||
- web
|
||||
author: TrudeEH
|
||||
showToc: true
|
||||
---
|
||||
|
||||
|
||||
|
||||
Flask is a web framework for Python. It facilitates the creation of web apps (dynamic web pages).
|
||||
|
||||
## Run Flask
|
||||
|
||||
Flask comes with its own server for debugging purposes, which can be started with:
|
||||
|
||||
```Bash
|
||||
flask run
|
||||
```
|
||||
|
||||
## Folder Structure
|
||||
|
||||
```Bash
|
||||
app.py # main code
|
||||
requirements.txt # required libraries
|
||||
static/ # files that never change
|
||||
templates/ # dynamic files
|
||||
```
|
||||
|
||||
## "Hello, name" — Example App
|
||||
|
||||
**templates/index.html**
|
||||
|
||||
```HTML
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta name = "viewport" content="initial-scale=1, width=device-width">
|
||||
<title>Hello</title>
|
||||
</head>
|
||||
<body>
|
||||
hello, {{ name_placeholder }} <!-- Jinja template -->
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
**app.py**
|
||||
`http://website.domain/?name=Trude`
|
||||
|
||||
```Python
|
||||
from flask import Flask, render_template, request
|
||||
app = Flask(__name__)
|
||||
# When user visits / (the website root), load index.html.
|
||||
# If the key name exists, store the value in a variable. If not, store world.
|
||||
@app.route("/")
|
||||
def index():
|
||||
name = request.args.get("name", "world")
|
||||
return render_template("index.html", name_placeholder=name)
|
||||
```
|
||||
|
||||
## HTML Form
|
||||
|
||||
### Sample App
|
||||
|
||||
**templates/index.html**
|
||||
|
||||
```HTML
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta name = "viewport" content="initial-scale=1, width=device-width">
|
||||
<title>Hello</title>
|
||||
</head>
|
||||
<body>
|
||||
<form>
|
||||
<input autocomplete="off" autofocus name="name" placeholder="Name" type="text">
|
||||
<button type="submit">Greet</button>
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
**app.py**
|
||||
`http://website.domain/?name=Trude`
|
||||
|
||||
```Python
|
||||
from flask import Flask, render_template, request
|
||||
app = Flask(__name__)
|
||||
# When user visits / (the website root), load index.html.
|
||||
# If the key name exists, store the value in a variable. If not, store world.
|
||||
@app.route("/")
|
||||
def index():
|
||||
name = request.args.get("name", "world")
|
||||
return render_template("index.html", name_placeholder=name)
|
||||
```
|
||||
|
||||
### Custom Route
|
||||
|
||||
Both the form and /greet works.
|
||||
**templates/index.html**
|
||||
|
||||
```HTML
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta name = "viewport" content="initial-scale=1, width=device-width">
|
||||
<title>Hello</title>
|
||||
</head>
|
||||
<body>
|
||||
<form action="/greet" method="get">
|
||||
<input autocomplete="off" autofocus name="name" placeholder="Name" type="text">
|
||||
<button type="submit">Greet</button>
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
**templates/greet.html**
|
||||
|
||||
```HTML
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta name = "viewport" content="initial-scale=1, width=device-width">
|
||||
<title>Hello</title>
|
||||
</head>
|
||||
<body>
|
||||
hello,{{name}}
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
**app.py**
|
||||
`http://website.domain/?name=Trude`
|
||||
|
||||
```Python
|
||||
from flask import Flask, render_template, request
|
||||
app = Flask(__name__)
|
||||
# When user visits / (the website root), load index.html.
|
||||
# If the key name exists, store the value in a variable. If not, store world.
|
||||
@app.route("/")
|
||||
def index():
|
||||
name = request.args.get("name", "world")
|
||||
return render_template("index.html", name_placeholder=name)
|
||||
@app.route("/greet")
|
||||
def greet():
|
||||
return render_template("greet.html", name=request.args.get("name", "world"))
|
||||
```
|
||||
|
||||
### Avoid HTML Repetition
|
||||
|
||||
Use a layout instead of copying blocks.
|
||||
**templates/index.html**
|
||||
|
||||
```HTML
|
||||
{% extends "layout.html" %}
|
||||
{% block body %}
|
||||
<form action="/greet" method="get">
|
||||
<input autocomplete="off" autofocus name="name" placeholder="Name" type="text">
|
||||
<button type="submit">Greet</button>
|
||||
</form>
|
||||
{% endblock %}
|
||||
```
|
||||
|
||||
**templates/greet.html**
|
||||
|
||||
```HTML
|
||||
{% extends "layout.html" %}
|
||||
{% block body %}
|
||||
hello, {{name}}
|
||||
{% endblock %}
|
||||
```
|
||||
|
||||
**templates/layout.html**
|
||||
|
||||
```HTML
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta name = "viewport" content="initial-scale=1, width=device-width">
|
||||
<title>Hello</title>
|
||||
</head>
|
||||
<body>
|
||||
{% block body %}{% endblock %}
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
**app.py**
|
||||
`http://website.domain/?name=Trude`
|
||||
|
||||
```Python
|
||||
from flask import Flask, render_template, request
|
||||
app = Flask(__name__)
|
||||
# When user visits / (the website root), load index.html.
|
||||
# If the key name exists, store the value in a variable. If not, store world.
|
||||
@app.route("/")
|
||||
def index():
|
||||
name = request.args.get("name", "world")
|
||||
return render_template("index.html", name_placeholder=name)
|
||||
@app.route("/greet")
|
||||
def greet():
|
||||
return render_template("greet.html", name=request.args.get("name", "world"))
|
||||
```
|
||||
|
||||
### Hide Sensitive Requests from the URL
|
||||
|
||||
Use post instead of get.
|
||||
**templates/index.html**
|
||||
|
||||
```HTML
|
||||
{% extends "layout.html" %}
|
||||
{% block body %}
|
||||
<form action="/greet" method="post">
|
||||
<input autocomplete="off" autofocus name="name" placeholder="Name" type="text">
|
||||
<button type="submit">Greet</button>
|
||||
</form>
|
||||
{% endblock %}
|
||||
```
|
||||
|
||||
**templates/greet.html**
|
||||
|
||||
```HTML
|
||||
{% extends "layout.html" %}
|
||||
{% block body %}
|
||||
hello, {{name}}
|
||||
{% endblock %}
|
||||
```
|
||||
|
||||
**templates/layout.html**
|
||||
|
||||
```HTML
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta name = "viewport" content="initial-scale=1, width=device-width">
|
||||
<title>Hello</title>
|
||||
</head>
|
||||
<body>
|
||||
{% block body %}{% endblock %}
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
**app.py**
|
||||
`http://website.domain/greet`
|
||||
The name doesn't appear in the URL anymore.
|
||||
|
||||
```Python
|
||||
from flask import Flask, render_template, request
|
||||
app = Flask(__name__)
|
||||
# When user visits / (the website root), load index.html.
|
||||
# If the key name exists, store the value in a variable. If not, store world.
|
||||
@app.route("/")
|
||||
def index():
|
||||
name = request.args.get("name", "world")
|
||||
return render_template("index.html", name_placeholder=name)
|
||||
@app.route("/greet", methods=["POST"])
|
||||
def greet():
|
||||
return render_template("greet.html", name=request.form.get("name", "world"))
|
||||
```
|
||||
|
||||
### Combine Routes to save Resources
|
||||
|
||||
GET is always the default.
|
||||
POST is used to send information to the server.
|
||||
**templates/index.html**
|
||||
|
||||
```HTML
|
||||
{% extends "layout.html" %}
|
||||
{% block body %}
|
||||
<form action="/" method="post">
|
||||
<input autocomplete="off" autofocus name="name" placeholder="Name" type="text">
|
||||
<button type="submit">Greet</button>
|
||||
</form>
|
||||
{% endblock %}
|
||||
```
|
||||
|
||||
**templates/greet.html**
|
||||
|
||||
```HTML
|
||||
{% extends "layout.html" %}
|
||||
{% block body %}
|
||||
hello, {{name}}
|
||||
{% endblock %}
|
||||
```
|
||||
|
||||
**templates/layout.html**
|
||||
|
||||
```HTML
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta name = "viewport" content="initial-scale=1, width=device-width">
|
||||
<title>Hello</title>
|
||||
</head>
|
||||
<body>
|
||||
{% block body %}{% endblock %}
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
**app.py**
|
||||
`http://website.domain/`
|
||||
|
||||
```Python
|
||||
from flask import Flask, render_template, request
|
||||
app = Flask(__name__)
|
||||
# When user visits / (the website root), load index.html.
|
||||
# If the key name exists, store the value in a variable. If not, store world.
|
||||
@app.route("/", methods=["GET, POST"])
|
||||
def index():
|
||||
if request.method == "GET":
|
||||
return render_template("index.html")
|
||||
elif request.method == "POST":
|
||||
return render_template("greet.html", name=request.form.get("name", "world"))
|
||||
```
|
||||
|
||||
## Cookies - Session
|
||||
|
||||
Used to store data and to recognize the user.
|
||||
- Server → Client
|
||||
- `Set-Cookie session=value`
|
||||
- Client → Server
|
||||
- `Cookie session`
|
||||
|
||||
```Python
|
||||
from flask import session
|
||||
# Configure app
|
||||
app = Flask(__name__)
|
||||
# Configure session
|
||||
app.config["SESSION_PERMANENT"] = False
|
||||
app.config["SESSION_TYPE"] = "filesystem"
|
||||
Session(app)
|
||||
# Redirect to login if no cookie exists
|
||||
@app.route("/")
|
||||
def index():
|
||||
if not session.get("name"):
|
||||
return redirect("/login")
|
||||
return render_template("index.html")
|
||||
# EXAMPLES
|
||||
# session is a dictionary
|
||||
session["cart"] = []
|
||||
books = db.execute("SELECT * FROM books WHERE id IN (?)", session["cart"])
|
||||
```
|
||||
68
content/notes/ready/gdb.md
Normal file
@@ -0,0 +1,68 @@
|
||||
---
|
||||
title: Debugging [GDB]
|
||||
description:
|
||||
date: 2025-02-17T08:16:48+00:00
|
||||
draft: false
|
||||
tags:
|
||||
- programming
|
||||
author: TrudeEH
|
||||
showToc: true
|
||||
---
|
||||
|
||||
## GDB Debugging
|
||||
|
||||
### Compile with Debug Information
|
||||
|
||||
To allow `gdb` access to the source code (Provides debug symbols - Do not share publicly as it contains the source code).
|
||||
|
||||
```Shell
|
||||
gcc -g <file>
|
||||
```
|
||||
|
||||
### Look for / Fix Bugs
|
||||
|
||||
First, initialize `gdb` with the executable to debug.
|
||||
|
||||
```Shell
|
||||
gdb ./<executable> --tui
|
||||
```
|
||||
|
||||
After `gdb` is ready, we can use the following commands:
|
||||
|
||||
|Command|Description|
|
||||
|---|---|
|
||||
|`lay next`|Switch to the next layout (Enables TUI mode if disabled - Allows for reading the code while debugging both in `C` and `ASM`).|
|
||||
|`ref`|Refresh (if a program prints to the terminal, it can break `gdb`'s interface).`|
|
||||
|`q`|Quit `gdb`.|
|
||||
|||
|
||||
|`b main`|Add a breakpoint at the main function.|
|
||||
|`b`|Place a breakpoint at the current line.|
|
||||
|`b <N>`|Place a breakpoint at line `N`.|
|
||||
|`b +<N>`|Place a breakpoint N lines down.|
|
||||
|`b <fn>`|Place a breakpoint at `fn` function.|
|
||||
|`d`|Delete all breakpoints.|
|
||||
|`d <N>`|Delete breakpoint number `N`.|
|
||||
|`clear <fn>`|Clear the breakpoint set to `fn` function.|
|
||||
|||
|
||||
|`n`|Execute up to the next line in `C`. If a function call is found, execute the function completely.|
|
||||
|`s`|Execute up to the next line in `C`. (Jump over)|
|
||||
|`s <N>`|Run `N` lines.|
|
||||
|`u`|Same as `n`, but if in a loop, execute until the loop exits.|
|
||||
|`nexti`|Execute up to the next instruction (line in `ASM`).|
|
||||
|`r`|Run the program until a breakpoint or error is reached.|
|
||||
|`c`|Continue running the program until a breakpoint or error is reached.|
|
||||
|||
|
||||
|`x/i $pc`|Examine the previous instruction (View memory).|
|
||||
|`info registers`|Read the CPU registers used by the program.|
|
||||
|`bt`|See the call stack up to the current line. (How we got here, so to speak)|
|
||||
|`print sizeof(<variable>)`|Check the size of a struct/variable/pointer.|
|
||||
|`p <var>`|Print variable `var` value.|
|
||||
|`info break`|List breakpoints.|
|
||||
|
||||
## Check for Memory Leaks
|
||||
|
||||
Use `valgrind` to check for lost memory.
|
||||
|
||||
```Shell
|
||||
valgrind --leak-check=full ./<executable>
|
||||
```
|
||||
361
content/notes/ready/git.md
Normal file
@@ -0,0 +1,361 @@
|
||||
---
|
||||
title: Version Control [GIT]
|
||||
description:
|
||||
date: 2025-02-17T08:58:11+00:00
|
||||
draft: false
|
||||
tags:
|
||||
- programming
|
||||
- tools
|
||||
author: TrudeEH
|
||||
showToc: true
|
||||
---
|
||||
|
||||
|
||||
Git is a version control system first developed by Linus Torvalds. It facilitates collaboration on large projects, keeps track of changes, and allows mistakes to be rolled back into a previous state.
|
||||
|
||||
## Configure Git
|
||||
|
||||
Git uses a hierarchy of configuration files:
|
||||
- **System**: (`/etc/gitconfig`) Configuration for all users in a system.
|
||||
- **Global**: (`~/.gitconfig`) Configure Git for all project of the current user.
|
||||
- **Local**: (`.git/config`) Configure Git for the current project.
|
||||
- **Worktree**: (`.git/config.worktree`) Configure part of a project.
|
||||
|
||||
```Shell
|
||||
# Check if user name and email are set.
|
||||
git config --get user.name
|
||||
git config --get user.email
|
||||
# If not, set those values.
|
||||
git config --add --global user.name "username"
|
||||
git config --add --global user.email "email@example.com"
|
||||
git config --add --global init.defaultBranch main # GitHub's default
|
||||
git config --unset example.key # Remove a configuration value
|
||||
git config --unset-all example.key # Remove all instances of a configuration key
|
||||
git config --remove-section section # Remove an entire section
|
||||
# Rebase on pull by default to keep a linear history
|
||||
git config --global pull.rebase true
|
||||
```
|
||||
|
||||
## Create a Repository
|
||||
|
||||
Git stores all project information in the `.git` directory. This includes branches, commits, and metadata.
|
||||
|
||||
```Shell
|
||||
mkdir project && cd project
|
||||
git init
|
||||
```
|
||||
|
||||
## Status
|
||||
|
||||
A file can be in one of several states in a Git repository.
|
||||
- `untracked`: Not being tracked by Git
|
||||
- `staged`: Marked to be included in the next commit
|
||||
- `committed`: Saved to the repository's history
|
||||
|
||||
```Shell
|
||||
git status # Shows he state of a repository.
|
||||
```
|
||||
|
||||
## Staging
|
||||
|
||||
Untracked files need to be indexed before being committed.
|
||||
|
||||
```Shell
|
||||
git add filename.ext # Add a file
|
||||
git add . # Add every file in the current directory, recursively.
|
||||
```
|
||||
|
||||
## Commit
|
||||
|
||||
A commit is a snapshot of the entire repository at a given point in time. Each commit has a message that describes the changes made in that commit.
|
||||
To commit all staged files:
|
||||
|
||||
```Shell
|
||||
git commit -m "message" # Commit all staged files
|
||||
git commit --amend -m "message" # Replace the last commit's message
|
||||
```
|
||||
|
||||
## Git Log
|
||||
|
||||
The `git log` command shows the history of commits in a repository. It provides information on who made a commit, when it was made, and what files were changed.
|
||||
Each commit also has a unique identifier (commit hash).
|
||||
For example, this is a valid commit hash: `46a4b5904d4ad737447052fed90c754ce8c616b6`.
|
||||
Since these identifiers are very long, they are often shortened to their first `7` characters (`46a4b59` in this example).
|
||||
|
||||
```Shell
|
||||
git log # Show the log in an interactive pager
|
||||
git --no-pager log -n 10 # Show the last 10 lines from the log, without using the pager
|
||||
git log -1 # Fetch the header of the first commit
|
||||
git log --decorate=full # Shows the full pointer to a commit
|
||||
git log --decorate=no # Don't show branch names
|
||||
git log --oneline # Show each commit in a single line. ("compact" mode)
|
||||
git reflog # History of actions. Commits, clone, pull, etc.
|
||||
```
|
||||
|
||||
## Git Diff
|
||||
|
||||
Show differences:
|
||||
|
||||
```Shell
|
||||
git diff # Differences between the working tree and the last commit
|
||||
git diff HEAD~1 # Same, but includes the last commit and uncommitted changes
|
||||
git diff COMMIT_HASH_1 COMMIT_HASH_2 # Differences between two commits
|
||||
```
|
||||
|
||||
## Git Tags
|
||||
|
||||
A tag is a name linked to a commit that doesn't move between commits. Useful to mark versions.
|
||||
|
||||
```Shell
|
||||
git tag # List the current tag
|
||||
git tag -a "tag name" -m "tag message" # Add a new tag
|
||||
git tag -a v3.10.2 -m "Fixed a lil bug" # Example marking a release
|
||||
```
|
||||
|
||||
### Semantic Versioning (Semver)
|
||||
|
||||
Naming convention for versioning software.
|
||||
|
||||
```Plain
|
||||
v3.12.5
|
||||
| | |
|
||||
| | Patch (safe bug fixes)
|
||||
| Minor (safe features)
|
||||
Major (breaking changes)
|
||||
```
|
||||
|
||||
## Branch
|
||||
|
||||
A Git branch allows you to keep track of different changes separately.
|
||||
|
||||
```Plain
|
||||
D - E other_branch
|
||||
/
|
||||
A - B - C main
|
||||
```
|
||||
|
||||
```Shell
|
||||
git branch # Check which branches are available, and which one is selected
|
||||
git branch -m oldname newname # Rename a branch
|
||||
git branch my_new_branch # Create a new branch
|
||||
git switch -c my_new_branch # Create a new branch and switch to it immediately
|
||||
git switch branch_name # Switch to an existing branch
|
||||
git checkout branch_name # Deprecated alternative to git switch
|
||||
git branch -d branch_name # Delete a branch
|
||||
```
|
||||
|
||||
### Merge
|
||||
|
||||
After modifying a new branch, all commits performed on it can be merged into the main branch.
|
||||
|
||||
```Plain
|
||||
A - B - C - F main
|
||||
\ /
|
||||
D - E other_branch
|
||||
```
|
||||
|
||||
```Shell
|
||||
git log --oneline --graph --all # Show an ASCII representation of the commit history
|
||||
git log --oneline --decorate --graph --parents # Also display any parent branches
|
||||
git merge branch_name # Merge a branch into the current branch
|
||||
```
|
||||
|
||||
### Rebase
|
||||
|
||||
After a branch is created, it might fall behind its origin. A rebase includes the new changes from the origin into the current branch, without leaving a merge message behind. While merging can often accomplish the same task, a rebase keeps history linear and makes it easier to read. It's recommended to use it on the main branch, for example, when updating smaller ones.
|
||||
Before a rebase, the commit history might have the following structure:
|
||||
|
||||
```Plain
|
||||
A - B - C main
|
||||
\
|
||||
D - E feature_branch
|
||||
```
|
||||
|
||||
After a rebase, the target branch is updated against its origin:
|
||||
|
||||
```Plain
|
||||
A - B - C main
|
||||
\
|
||||
D - E feature_branch
|
||||
```
|
||||
|
||||
```Shell
|
||||
git rebase origin_name # Rebase against the origin
|
||||
```
|
||||
|
||||
> You should *never* rebase a public branch (like `main`) onto anything else, to not break commit history.
|
||||
|
||||
### Conflicts
|
||||
|
||||
If a modified is pushed to another branch where that same file has been modified as well, a conflict arises. These can be fixed manually by editing text, or using Git commands.
|
||||
|
||||
```Shell
|
||||
git checkout --theirs path/to/file # Discard the current branch's changes and accept the target's changes
|
||||
git checkout --ours path/to/file # Discard the target changes and replace with the ones in the current branch
|
||||
git reset --soft HEAD~1 # Undo an accidental conflict resolution
|
||||
```
|
||||
|
||||
### Squash
|
||||
|
||||
Combine various commits into one:
|
||||
1. Start an interactive rebase with the command `git rebase -i HEAD~n`, where `n` is the number of commits you want to squash.
|
||||
2. Git will open your default editor with a list of commits. Change the word `pick` to `squash` for all but the first commit.
|
||||
3. Save and close the editor.
|
||||
|
||||
> If the squashed commits already existed in the remote repository, it might be needed to push using: `git push origin main --force`.
|
||||
|
||||
### Stash
|
||||
|
||||
`git stash` saves the state of the current working directory and the index (staging area), then returns the repository to `HEAD`. This allows you to work on a different issue, and then resume your previous task.
|
||||
|
||||
```Shell
|
||||
git stash
|
||||
git stash -m "message" # It's also possible to stash with a message
|
||||
git stash list # List all stashes
|
||||
git stash pop # Apply the most recent stash to the working directory
|
||||
git stash apply # Same as before, but doesn't delete the stash after applying
|
||||
git stash drop # Discard a stash without applying changes
|
||||
git stash apply stash@{2} # Apply the third most recent stash
|
||||
```
|
||||
|
||||
### Worktrees
|
||||
|
||||
The directory where the code tracked with Git lives. (And where the `.git` directory is located).
|
||||
Use instead of a `stash` if the current worktree is too busy, or for long-lived changes. This acts like cloning the repo again and working there, except it doesn't take up space on the host machine.
|
||||
Any change done on a linked worktree is reflected on the main one instantly. Think of it as a different view of the main worktree.
|
||||
|
||||
```Shell
|
||||
git worktree list # Lists worktrees
|
||||
git worktree add <path> [<branch>] # Create a worktree linked to the main one
|
||||
git worktree remove WORKTREE_NAME # Remove a worktree
|
||||
git worktree prune # Remove an empty worktree if its directories were removed
|
||||
```
|
||||
|
||||
### Bisect
|
||||
|
||||
Find a specific commit with binary tree search.
|
||||
For example, if trying to find a bug in 100 commits, `git bisect` allows it to be found with only `7` attempts.
|
||||
1. `git bisect start`
|
||||
2. Use: `git bisect good <commitish>` to select a commit where the bug wasn't introduced yet.
|
||||
3. Select a commit where the bug exists using: `git bisect bad <commitish>`.
|
||||
4. Git will checkout a commit between the good and bad commits for you to test to see if the bug is present.
|
||||
5. Execute `git bisect good` or `git bisect bad`.
|
||||
6. Loop back to step 4 (until `git bisect` completes)
|
||||
7. Exit the bisect mode with `git bisect reset`
|
||||
|
||||
```Shell
|
||||
git bisect start
|
||||
git bisect good <commitish> # Select a commit where the bug wasn't introduced yet.
|
||||
git bisect bad <commitish> # Select a commit where the bug exists
|
||||
```
|
||||
|
||||
#### Automated Bisect
|
||||
|
||||
If you have a script that can tell if the current source code is good or bad, you can bisect by issuing the command:
|
||||
|
||||
```Shell
|
||||
git bisect run <script> <arguments>
|
||||
```
|
||||
|
||||
The script should exit with code `0` if the current source code is good/old, and exit with a code between `1` and `127` (inclusive), except `125`, if the current source code is bad/new.
|
||||
|
||||
### Cherry-Pick
|
||||
|
||||
Apply only the selected commit to the working directory.
|
||||
|
||||
```Shell
|
||||
git cherry-pick <commit-hash>
|
||||
```
|
||||
|
||||
## Undo Changes
|
||||
|
||||
```Shell
|
||||
git reset --soft COMMITHASH # Undo the last commit, but keep its changes staged (does not delete files)
|
||||
git reset --hard COMMITHASH # Undo the last commit and discard all changes (deletes files).
|
||||
git reset --hard a1b2c3d # Rollback to an earlier commit, deleting all changes up to that point.
|
||||
git revert COMMITHASH # Create a new commit that does the opposite of the one provided. (Reset, but keeps history)
|
||||
```
|
||||
|
||||
### Recover a Deleted Commit
|
||||
|
||||
`HEAD` always keeps track of every change, including rollbacks, so it can be used to recover lost files.
|
||||
|
||||
```Shell
|
||||
git merge HEAD@{1}
|
||||
```
|
||||
|
||||
## Git Remote
|
||||
|
||||
'Remotes' are eternal repositories with a similar Git history to our local one. GitHub, for example, is a remote repository. It is not part of Git, but is often used as the "source of truth" for convenience.
|
||||
If a repository is considered to be the project's "true" source, it should be named `origin`.
|
||||
|
||||
```Shell
|
||||
git remote add <name> <uri> # Add a remote repository (local folder or external url)
|
||||
git fetch # Download a copy of the origin's metadata (.git/objects)
|
||||
git log remote/branch # See the log of a remote branch after fetching data
|
||||
git merge remote/branch # Merge between local and remote repos
|
||||
git push origin main # Push (send) local changes to the selected remote
|
||||
git push origin <localbranch>:<remotebranch> # Push a local branch to a remote, with a different name
|
||||
git push origin :<remotebranch> # Push an empty branch to delete the remote branch
|
||||
git pull [<remote>/<branch>] # Update local repo with remote changes (downloads files).
|
||||
```
|
||||
|
||||
### Pull Requests
|
||||
|
||||
Propose changes to a repository, before they are actually applies. A pull request is typically accepted by a maintainer or other team members.
|
||||
|
||||
### GitHub
|
||||
|
||||
GitHub serves several purposes:
|
||||
- As a backup of all your code on the cloud in case something happens to your computer
|
||||
- As a central place to share your code and collaborate on it with others
|
||||
- As a public portfolio for your coding projects
|
||||
|
||||
```Shell
|
||||
# Install GitHub CLI either through a package manager, or using the command:
|
||||
curl -sS https://webi.sh/gh | sh
|
||||
# Login through the browser
|
||||
gh auth login
|
||||
# Add a remote from GitHub
|
||||
git remote add origin https://github.com/your-username/repo-name.git
|
||||
# List remote repos
|
||||
git ls-remote
|
||||
```
|
||||
|
||||
#### Forks
|
||||
|
||||
On GitHub (and similar platforms), a repository can be forked, or, copied, to serve as the base for a future pull request.
|
||||
The steps to submit a PR are usually as follows:
|
||||
1. Fork their repo into your account
|
||||
2. Clone your fork to your local machine
|
||||
3. Create a new branch (let's call it `your_feature`)
|
||||
4. Make changes
|
||||
5. Commit and push changes to your fork's remote `your_feature` branch
|
||||
6. Create a pull request to `original_owner/repo` `main` from `your_username/repo` `your_feature`
|
||||
|
||||
## `.gitignore`
|
||||
|
||||
Prevents the specified files from being tracked by git.
|
||||
|
||||
```Shell
|
||||
folder_name # Ignores all directories with that name, even subdirectories of different directories
|
||||
file.txt # Ignores a specific file in the current directory
|
||||
folder/file.txt # Ignores a file inside a subdirectory
|
||||
*.txt # Ignore all text files
|
||||
/main.py # Ignore a file only in the current directory, not subdirectories
|
||||
!important.txt # Track a file that would previously be ignored
|
||||
```
|
||||
|
||||
If a file was already staged or committed, it won't be ignored, however. Use the following command to remove it from cache and ignore it on the next commit:
|
||||
|
||||
```Shell
|
||||
git rm --cached file
|
||||
```
|
||||
|
||||
> It's common to have `.gitignore` files in subdirectories. These only affect the directories they are inside of.
|
||||
|
||||
**Which files should be ignored?**
|
||||
1. Ignore things that can be *generated* (e.g. compiled code, minified files, etc.)
|
||||
2. Ignore dependencies (e.g. `node_modules`, `venv`, `packages`, etc.)
|
||||
3. Ignore things that are personal or specific to how you like to work (e.g. editor settings)
|
||||
4. Ignore things that are sensitive or dangerous (e.g. `.env` files, passwords, API keys, etc.)
|
||||
203
content/notes/ready/html.md
Normal file
@@ -0,0 +1,203 @@
|
||||
---
|
||||
title: HTML
|
||||
description:
|
||||
date: 2025-02-17T09:11:23+00:00
|
||||
draft: false
|
||||
tags:
|
||||
- web
|
||||
author: TrudeEH
|
||||
showToc: true
|
||||
---
|
||||
|
||||
|
||||
*HTML* is a markup language: The foundation of every website, as it structures content and provides information such as text, images and other media to the browser.
|
||||
|
||||
## Hello World
|
||||
|
||||
HTML is not a programming language, only formatting to write a document as. The following 'code' is valid HTML.
|
||||
|
||||
```HTML
|
||||
Hello, world.
|
||||
```
|
||||
|
||||
A more complete solution, however, would be to define a structure for the document.
|
||||
|
||||
```HTML
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
|
||||
<title>Document</title>
|
||||
</head>
|
||||
<body>
|
||||
<p>Hello, world.</p>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
HTML uses tags to define a hierarchy. The `<head>` tag defines metadata for the site, such as the page's title, encoding types, and any external resources. The `<body>` tag is the content itself: any paragraphs (`<p>`), images, forms and scripts, to name a few.
|
||||
|
||||
> When reading HTML, the browser applies a set of default styles to make it more readable. HTML is **not** the place to style content, however. For example, a common mistake is to use headings based on their size or font weight, instead of their meaning. Everything can all be styled using CSS later, so try to ignore the design when writing HTML, and focus on the content instead.
|
||||
> Not all tags hold content, but for those that do, the end of that content is defined with a closing tag: `</tagname>`.
|
||||
|
||||
## Basic Tags
|
||||
|
||||
|Tag|Description|
|
||||
|---|---|
|
||||
|`<!DOCTYPE>`|Document type.|
|
||||
|`<html>`|Defines an HTML document.|
|
||||
|`<head>`|Contains metadata/information for the page.|
|
||||
|`<title>`|Title for the page.|
|
||||
|`<body>`|Defines the document's body.|
|
||||
|`<h1> to <h6>`|Defines HTML headings (titles). `<h1>` is the page's title, `<h2>` is the subtitle, and so on.|
|
||||
|`<p>`|Paragraph.|
|
||||
|`<br>`|Inserts a single line break.|
|
||||
|`<hr>`|Defines a thematic change in the content.|
|
||||
|`<!--...-->`|Comment.|
|
||||
|
||||
## Formatting
|
||||
|
||||
|Tag|Description|
|
||||
|---|---|
|
||||
|`<abbr>`|Abbreviation or acronym.|
|
||||
|`<address>`|Contact information for the author/owner of a document/article.|
|
||||
|`<b>`|Bold text.|
|
||||
|`<bdi>`|Isolates a part of text that might be formatted in a different direction from other text outside it.|
|
||||
|`<bdo>`|Overrides the current text direction.|
|
||||
|`<blockquote>`|Defines a section that is quoted from another source.|
|
||||
|`<cite>`|Defines the title of a work.|
|
||||
|`<code>`|Block of code.|
|
||||
|`<del>`|Defines text that has been deleted from a document.|
|
||||
|`<dfn>`|Specifies a term that is going to be defined within the content.|
|
||||
|`<em>`|Emphasized text.|
|
||||
|`<i>`|Defines a part of text in an alternate voice or mood.|
|
||||
|`<ins>`|Defines a text that has been inserted into a document.|
|
||||
|`<kbd>`|Keyboard input.|
|
||||
|`<mark>`|Marked/highlighted text.|
|
||||
|`<meter>`|Defines a scalar measurement within a known range (a gauge).|
|
||||
|`<pre>`|Preformatted text.|
|
||||
|`<progress>`|Represents the progress of a task.|
|
||||
|`<q>`|Short quotation.|
|
||||
|`<rp>`|Defines what to show in browsers that do not support ruby annotations.|
|
||||
|`<rt>`|Defines an explanation/pronunciation of characters (for East Asian typography).|
|
||||
|`<ruby>`|Defines a ruby annotation (for East Asian typography).|
|
||||
|`<s>`|Defines text that is no longer correct.|
|
||||
|`<samp>`|Defines sample output from a computer program.|
|
||||
|`<small>`|Smaller text.|
|
||||
|`<strong>`|Important text.|
|
||||
|`<sub>`|Subscripted text: `2₂`.|
|
||||
|`<sup>`|Superscripted text: `2²`.|
|
||||
|`<template>`|Defines a container for content that should be hidden when the page loads.|
|
||||
|`<time>`|Defines a specific time (or datetime).|
|
||||
|`<u>`|Defines some text that is unarticulated and styled differently from normal text.|
|
||||
|`<var>`|Variable.|
|
||||
|`<wbr>`|Defines a possible line-break.|
|
||||
|
||||
## Forms and Input
|
||||
|
||||
|Tag|Description|
|
||||
|---|---|
|
||||
|`<form>`|Defines an HTML form for user input.|
|
||||
|`<input>`|Defines an input control.|
|
||||
|`<textarea>`|Defines a multiline input control (text area).|
|
||||
|`<button>`|Clickable button.|
|
||||
|`<select>`|Drop-down list.|
|
||||
|`<optgroup>`|Defines a group of related options in a drop-down list.|
|
||||
|`<option>`|Defines an option in a drop-down list.|
|
||||
|`<label>`|Defines a label for an `<input>` element.|
|
||||
|`<fieldset>`|Groups related elements in a form.|
|
||||
|`<legend>`|Defines a caption for a `<fieldset>` element.|
|
||||
|`<datalist>`|List of pre-defined options for input controls.|
|
||||
|`<output>`|Defines the result of a calculation.|
|
||||
|
||||
## Media
|
||||
|
||||
|Tag|Description|
|
||||
|---|---|
|
||||
|`<img>`|Image.|
|
||||
|`<map>`|Defines a client-side image map.|
|
||||
|`<area>`|Defines an area inside an image map.|
|
||||
|`<canvas>`|Used to draw graphics in real time, via scripting (usually JavaScript).|
|
||||
|`<figcaption>`|Defines a caption for a `<figure>` element.|
|
||||
|`<figure>`|Specifies self-contained content.|
|
||||
|`<picture>`|Defines a container for multiple image resources.|
|
||||
|`<svg>`|Defines a container for SVG graphics.|
|
||||
|`<audio>`|Sound content.|
|
||||
|`<source>`|Defines multiple media resources for media elements (`<video>`, `<audio>` and `<picture>`).|
|
||||
|`<track>`|Defines text tracks for media elements (`<video>` and `<audio>`).|
|
||||
|`<video>`|Video or movie.|
|
||||
|
||||
## Links
|
||||
|
||||
|Tag|Description|
|
||||
|---|---|
|
||||
|`<iframe>`|Defines an inline frame.|
|
||||
|`<a>`|Defines a hyperlink.|
|
||||
|`<link>`|Defines the relationship between a document and an external resource (most used to link to style sheets).|
|
||||
|`<nav>`|Navigation links.|
|
||||
|
||||
## Lists
|
||||
|
||||
|Tag|Description|
|
||||
|---|---|
|
||||
|`<menu>`|Alternative unordered list.|
|
||||
|`<ul>`|Unordered list.|
|
||||
|`<ol>`|Ordered list.|
|
||||
|`<li>`|Defines a list item.|
|
||||
|`<dl>`|Description list|
|
||||
|`<dt>`|Defines a term/name in a description list.|
|
||||
|`<dd>`|Defines a description of a term/name in a description list.|
|
||||
|
||||
## Tables
|
||||
|
||||
|Tag|Description|
|
||||
|---|---|
|
||||
|`<table>`|Table.|
|
||||
|`<caption>`|Defines a table caption.|
|
||||
|`<th>`|Defines a header cell in a table.|
|
||||
|`<tr>`|Defines a row in a table.|
|
||||
|`<td>`|Defines a cell in a table.|
|
||||
|`<thead>`|Groups the header content in a table.|
|
||||
|`<tbody>`|Groups the body content in a table.|
|
||||
|`<tfoot>`|Groups the footer content in a table.|
|
||||
|`<col>`|Specifies column properties for each column within a `<colgroup>` element.|
|
||||
|`<colgroup>`|Specifies a group of one or more columns in a table for formatting.|
|
||||
|
||||
## Styles and Semantics
|
||||
|
||||
|Tag|Description|
|
||||
|---|---|
|
||||
|`<style>`|Defines style information for a document.|
|
||||
|`<div>`|Defines a section in a document.|
|
||||
|`<span>`|Defines a section in a document.|
|
||||
|`<header>`|Defines a header for a document or section.|
|
||||
|`<hgroup>`|Defines a header and related content.|
|
||||
|`<footer>`|Defines a footer for a document or section.|
|
||||
|`<main>`|Specifies the main content of a document.|
|
||||
|`<section>`|Defines a section in a document.|
|
||||
|`<search>`|Search section.|
|
||||
|`<article>`|Article.|
|
||||
|`<aside>`|Defines content aside from the page content.|
|
||||
|`<details>`|Defines additional details that the user can view or hide.|
|
||||
|`<dialog>`|Dialog box or window.|
|
||||
|`<summary>`|Defines a visible heading for the `<details>` element.|
|
||||
|`<data>`|Adds a machine-readable translation of a given content.|
|
||||
|
||||
## Meta
|
||||
|
||||
|Tag|Description|
|
||||
|---|---|
|
||||
|`<head>`|Contains information for the browser.|
|
||||
|`<meta>`|Contains metadata for the webpage.|
|
||||
|`<base>`|Specifies the base URL/target for all relative URLs in a document.|
|
||||
|
||||
## Programming
|
||||
|
||||
|Tag|Description|
|
||||
|---|---|
|
||||
|`<script>`|Client-side script.|
|
||||
|`<noscript>`|Defines an alternate content for users that do not support client-side scripts.|
|
||||
|`<object>`|Container for an external resource.|
|
||||
|`<param>`|Defines a parameter for an object.|
|
||||
142
content/notes/ready/http.md
Normal file
@@ -0,0 +1,142 @@
|
||||
---
|
||||
title: HTTP [CURL]
|
||||
description:
|
||||
date: 2025-02-17T09:22:33+00:00
|
||||
draft: false
|
||||
tags:
|
||||
- networking
|
||||
- tools
|
||||
- web
|
||||
author: TrudeEH
|
||||
showToc: true
|
||||
---
|
||||
|
||||
## HTTP
|
||||
|
||||
HTTP (Hypertext Transfer Protocol) is a communication protocol used to send messages between the client and server, mainly used for the web. It's stateless, meaning each request is independent, which is why web browsers often use cookies to save state.
|
||||
|
||||
### Request Structure
|
||||
|
||||
1. **Request Line**: Method, URI, HTTP version (e.g., `GET /index.html HTTP/1.1`).
|
||||
2. **Headers**: Metadata about the request.
|
||||
3. **Body (Optional)**: Data for `POST`, `PUT`, `PATCH` requests.
|
||||
|
||||
### Response Structure
|
||||
|
||||
1. **Status Line**: HTTP version, status code, reason phrase (e.g., `HTTP/1.1 200 OK`).
|
||||
2. **Headers**: Metadata about the response.
|
||||
3. **Body (Optional)**: Response data (HTML, JSON, etc.).
|
||||
|
||||
### Methods
|
||||
|
||||
- **GET**: Retrieve a resource. Should only retrieve data and not have side effects.
|
||||
- **POST**: Submit data to be processed.
|
||||
- **PUT**: Replace a resource.
|
||||
- **DELETE**: Delete a resource.
|
||||
- **PATCH**: Partially modify a resource.
|
||||
- **HEAD**: Retrieve headers only.
|
||||
- **OPTIONS**: Describe communication options.
|
||||
|
||||
### HTTP Headers
|
||||
|
||||
**HTTP headers** are key-value pairs providing additional information about requests and responses.
|
||||
|
||||
#### Header Categories
|
||||
|
||||
- **General Headers**: Apply to both requests and responses.
|
||||
- **Request Headers**: Information about the request context.
|
||||
- **Response Headers**: Information about the response context.
|
||||
- **Entity Headers**: Describe the body of the request or response.
|
||||
|
||||
#### General Headers
|
||||
|
||||
```Bash
|
||||
Cache-Control: max-age=3600 # Specifies caching directives. (1 hour)
|
||||
Connection: keep-alive # Controls whether the network connection stays open.
|
||||
Date: Tue, 09 Jul 2024 12:00:00 GMT # Date and time of the message.
|
||||
Transfer-Encoding: chunked # Encoding for safe transfer.
|
||||
Upgrade: HTTP/2 # Request to upgrade to another protocol.
|
||||
Via: 1.1 proxy.example.com # Indicates intermediate protocols and proxies.
|
||||
```
|
||||
|
||||
#### **Request Headers**
|
||||
|
||||
```Bash
|
||||
Accept: text/html, application/json # MIME types the client can handle.
|
||||
Accept-Encoding: gzip, deflate # Supported encoding algorithms.
|
||||
Accept-Language: en-US, en;q=0.9 # Preferred languages.
|
||||
Authorization: Basic <credentials> # Authentication credentials.
|
||||
Cookie: sessionid=123456789 # HTTP cookies.
|
||||
Host: www.example.com # Domain name of the server.
|
||||
Referer: https://www.example.com/page.html # URL of the linking page.
|
||||
User-Agent: Mozilla/5.0 ... # Client software identifier.
|
||||
```
|
||||
|
||||
#### Response Headers
|
||||
|
||||
```Bash
|
||||
Access-Control-Allow-Origin: * # Indicates whether the response can be shared with the given origin.
|
||||
Content-Type: application/json # MIME type of the response body.
|
||||
Content-Length: 1024 # Size of the response body in bytes.
|
||||
Content-Encoding: gzip # Encoding used for the data.
|
||||
Location: https://www.example.com/new-page # Redirect URL.
|
||||
Server: Apache/2.4.41 (Ubuntu) # Server software identifier.
|
||||
Set-Cookie: sessionid=987654321; Path=/; HttpOnly # Sends a cookie from the server to the client.
|
||||
```
|
||||
|
||||
#### Entity Headers
|
||||
|
||||
```Bash
|
||||
Allow: GET, POST, PUT, DELETE # Supported methods.
|
||||
Content-Language: en-US # Language(s) intended for the audience.
|
||||
Content-Location: /index.htm # URL where the entity was obtained.
|
||||
```
|
||||
|
||||
#### Custom Headers
|
||||
|
||||
Custom headers can be defined for application-specific purposes, typically prefixed with `X-` (e.g., `X-Custom-Header: custom-value`).
|
||||
|
||||
## Common HTTP Error Codes
|
||||
|
||||
- `200` OK
|
||||
- `301` Redirect (Moved to another location)
|
||||
- `302` Found
|
||||
- `304` Not Modified
|
||||
- `307` Temporary Redirect
|
||||
- `401` Unauthorized
|
||||
- `403` Forbidden
|
||||
- `404` Not Found
|
||||
- `418` I'm a Teapot
|
||||
- `500` Internal Server Error
|
||||
- `503` Service Unavailable
|
||||
|
||||
## CURL
|
||||
|
||||
`curl` is a command-line tool used for transferring data with URLs. It supports a wide range of protocols, including HTTP, HTTPS, FTP, SFTP, and more.
|
||||
|
||||
### Usage
|
||||
|
||||
```Shell
|
||||
# Fetches the content of <https://example.com> and prints it to standard output
|
||||
curl https://example.com
|
||||
# Saves the content to a file named output.html
|
||||
curl -o output.html https://example.com
|
||||
# Makes a POST request with URL-encoded data
|
||||
curl -X POST -d "param1=value1¶m2=value2" https://example.com/api
|
||||
# Makes a POST request with JSON data
|
||||
curl -X POST -H "Content-Type: application/json" -d '{"param1": "value1", "param2": "value2"}' https://example.com/api
|
||||
# Makes a PUT request with JSON data
|
||||
curl -X PUT -H "Content-Type: application/json" -d '{"key": "new_value"}' https://api.example.com/resource/123
|
||||
# Sets an Authorization header for API authentication
|
||||
curl -H "Authorization: Bearer YOUR_API_KEY" https://example.com/api
|
||||
# Tells curl to follow HTTP redirects
|
||||
curl -L https://example.com/redirecting-url
|
||||
# Saves cookies received from the server to cookies.txt
|
||||
curl -c cookies.txt https://example.com
|
||||
# Sends cookies from cookies.txt to the server
|
||||
curl -b cookies.txt https://example.com
|
||||
# Provides basic authentication credentials (username:password)
|
||||
curl -u username:password https://example.com/protected-resource
|
||||
# Sets the maximum time to wait for a connection and the entire operation
|
||||
curl --connect-timeout 10 --max-time 60 https://example.com
|
||||
```
|
||||
65
content/notes/ready/https-ssl-certs.md
Normal file
@@ -0,0 +1,65 @@
|
||||
---
|
||||
title: HTTPS and SSL Certificates
|
||||
description:
|
||||
date: 2025-02-17T09:17:30+00:00
|
||||
draft: false
|
||||
tags:
|
||||
- networking
|
||||
- web
|
||||
author: TrudeEH
|
||||
showToc: true
|
||||
---
|
||||
|
||||
## HTTP(s)
|
||||
|
||||
The `http` protocol sends data as plaintext, which is an issue when sharing sensitive data such as messages and passwords.
|
||||
`https` uses `TLS` to encrypt sensitive traffic between the client and server, creating a secure connection between the two.
|
||||
|
||||
## TLS
|
||||
|
||||
TLS is a form of [[encryption]], used to secure HTTPS connections.
|
||||
TLS replaces SSL (a deprecated protocol), however, the term SSL is still used often.
|
||||
|
||||
### Handshake
|
||||
|
||||
To establish a secure connection, a 'handshake' is performed between the client and the server.
|
||||
1. The client send a message with browser and OS info, and all supported encryption algorithms.
|
||||
2. The server selects the strongest supported algorithm, and responds with some server info, the selected algorithm, and an SSL Certificate (contains the domain name, certificate authority and public key).
|
||||
3. The client checks the certificate to ensure that it is valid and signed by a valid certificate authority.
|
||||
4. If the certificate is valid, the client generates a random session key, and encrypts it with the server's public key.
|
||||
5. The session key is sent to the server.
|
||||
6. The server decrypts the session key, using its own private key. If the key is valid, the server sends a finish message back to the client.
|
||||
7. The client sends its own finish message, and a secure connection is established.
|
||||
|
||||
### SSL Certificates
|
||||
|
||||
SSL Certificates are needed because without them, a malicious actor could intercept the client's first handshake message, and establish a secure connection with the client, obtaining its secrets.
|
||||
A trusted third party is needed to validate that the public key sent to the client matches the server's actual public key.
|
||||
[Let’s Encrypt](https://letsencrypt.org) is a non-profit organization that signs certificates for free.
|
||||
|
||||
#### Certbot
|
||||
|
||||
The easiest way to generate a *Let's Encrypt* certificate is through `certbot`, which is available as a snap package.
|
||||
|
||||
```Shell
|
||||
sudo apt install snapd
|
||||
sudo snap install core && sudo snap refresh core
|
||||
sudo snap install --classic certbot
|
||||
sudo ln -s /snap/bin/certbot /usr/bin/certbot
|
||||
```
|
||||
|
||||
> If you use a firewall, open port 80, as it is required for `certbot` to verify your domain information.
|
||||
> Once `certbot` is installed, you can either generate a standalone certificate (for example, to use for IRC), or follow the [official instructions](https://certbot.eff.org/instructions) for any web service that you already own.
|
||||
|
||||
For example, for an IRC server, run the following command:
|
||||
|
||||
```Shell
|
||||
sudo certbot certonly --standalone --preferred-challenges http -d irc.example.com
|
||||
```
|
||||
|
||||
Replace `irc.example.com` with your actual domain.
|
||||
The certificate will be stored as two files …
|
||||
- `/etc/letsencrypt/live/irc.example.com/fullchain.pem`
|
||||
- `/etc/letsencrypt/live/irc.example.com/privkey.pem`
|
||||
… which you can copy to any location you need.
|
||||
These files will be renewed every 90 days, so remember to either update them manually, or add a `crontab` entry to automate the process.
|
||||
208
content/notes/ready/irc.md
Normal file
@@ -0,0 +1,208 @@
|
||||
---
|
||||
title: IRC
|
||||
description:
|
||||
date: 2025-02-17T09:13:13+00:00
|
||||
draft: false
|
||||
tags:
|
||||
- networking
|
||||
author: TrudeEH
|
||||
showToc: true
|
||||
---
|
||||
|
||||
## The IRC Protocol
|
||||
|
||||
IRC is a very simple communication protocol that allows users to chat in real time. IRC is **very lightweight**, but does **not encrypt** messages by default.
|
||||
|
||||
## Using IRC
|
||||
|
||||
### Server
|
||||
|
||||
To be able to communicate, users must connect to a server. Each server has its own rules, bots and commands. The IRC protocol itself does not implement encryption, however, [[https-ssl-certs|SSL Certificates]] can be used to establish a secure connection **with the server**.
|
||||
Every message sent **can be read by the server**, including **private messages** between users.
|
||||
Separate IRC instances can communicate. This concept is often called **server federation**. This allows for users in different servers to send messages to each other.
|
||||
|
||||
### Client
|
||||
|
||||
To connect to a server, every user needs a client. Because IRC is an open protocol, there are many clients one can use, however, for this example I am using [halloy](https://halloy.squidowl.org/index.html).
|
||||
Halloy can be configured as follows:
|
||||
|
||||
```TOML
|
||||
# Example without encryption
|
||||
[servers.trude_unsafe]
|
||||
nickname = "trude"
|
||||
server = "server.trude.dev"
|
||||
port = 6667
|
||||
use_tls = false
|
||||
channels = ["\#general"]
|
||||
# Example with encryption (TLS)
|
||||
[servers.trude]
|
||||
nickname = "trude"
|
||||
server = "server.trude.dev"
|
||||
port = 6697
|
||||
use_tls = true
|
||||
channels = ["\#general"]
|
||||
```
|
||||
|
||||
### Modes (user roles)
|
||||
|
||||
- `@user` - Admin / Operator
|
||||
- `+user` - Voiced user
|
||||
- `user` - Regular user
|
||||
|
||||
### Channels
|
||||
|
||||
A `#channel` is a room where users can communicate. Channels can be public or invite-only.
|
||||
|
||||
### DMs
|
||||
|
||||
Two users can send private messages (aka, direct messages) to each other outside channels. However, the server is always able to read and log these messages due to the lack of encryption.
|
||||
|
||||
### [Commands](https://docs.inspircd.org/4/commands/)
|
||||
|
||||
Users are able to perform actions with simple text commands.
|
||||
|
||||
#### Basic Commands
|
||||
|
||||
|Command|Action|
|
||||
|---|---|
|
||||
|`/join #channel`|Join a channel.|
|
||||
|`/part #channel [message]`|Leave a channel with an optional goodbye message.|
|
||||
|`/msg nickname message`|Send a DM to one or more users.|
|
||||
|`/quit [message]`|Leave the server with an optional goodbye message.|
|
||||
|`/motd`|Read the server's "message of the day".|
|
||||
|`/nick nickname`|Change your nickname. (The name other people see when messaging you; the `/whois` command can still reveal your real name).|
|
||||
|`/whois nickname`|Get information about an user. By default, this includes: <br>- Hostname <br>- Real name <br>- IP Address <br>- Joined channels <br>- Last message/Login time <br>- User modes <br>- Origin server|
|
||||
|`/whowas nickname`|Same as whois, but for nicknames that were recently used. Can also reveal previous login times for connected users.|
|
||||
|`/me action`|Send a message as an action (third-person). (Usually for role playing purposes; only changes formatting).|
|
||||
|`/topic <#channel> <?text>`|View or set the topic for the channel. (Description of the channel).|
|
||||
|`/names #channel`|List all users in a channel.|
|
||||
|`/list`|List all available channels.|
|
||||
|`/ping`|Check connection with the server.|
|
||||
|`/admin`|Display administrative information about the server.|
|
||||
|`/time`|Display the current time on the server.|
|
||||
|
||||
#### Operator Commands
|
||||
|
||||
|Command|Description|
|
||||
|---|---|
|
||||
|`/kick nickname [reason]`|Removes a user from the channel.|
|
||||
|`/ban nickname`|Bans a user from the channel (usually combined with a kick).|
|
||||
|`/mode #channel +mode`|Changes channel modes (e.g., `/mode #chat +i` makes it invite-only).|
|
||||
|`/invite nickname #channel`|Invites a user to join a private or invite-only channel.|
|
||||
|`/op nickname`|Grants operator status to a user (if you are an operator).|
|
||||
|`/deop nickname`|Removes operator status from a user.|
|
||||
|
||||
#### User Modes
|
||||
|
||||
|Command|Description|
|
||||
|---|---|
|
||||
|`/mode nickname +mode`|Sets user modes (e.g., `/mode yourname +i` to become invisible).|
|
||||
|`/mode #channel +mode`|Sets modes for a channel (e.g., `/mode #chat +m` to make it moderated).|
|
||||
|`/away [message]`|Sets your status to "away" with an optional message.|
|
||||
|`/back`|Removes your "away" status. (Some servers use `/away` as a toggle, instead.|
|
||||
|
||||
|Common channel modes|Description|
|
||||
|---|---|
|
||||
|`+i`|Makes the channel invite-only.|
|
||||
|`+m`|Moderates the channel (only operators or voiced users can speak).|
|
||||
|`+n`|Prevents messages from users not in the channel.|
|
||||
|`+t`|Only operators can change the topic.|
|
||||
|`+k`|Requires a password to join the channel.|
|
||||
|
||||
|Common user modes|Description|
|
||||
|---|---|
|
||||
|`+i`|Makes your user "invisible" (hides you from `/who`).|
|
||||
|`+o`|Grants operator privileges.|
|
||||
|`+v`|Gives a user the ability to speak in a moderated channel
|
||||
|
||||
### Bots
|
||||
|
||||
A bot is an automated user (program/script) that can respond to commands, monitor chat or automate activities.
|
||||
Commands to bots are often prefixed with `!`, though, this is not always the case.
|
||||
|
||||
## Hosting an IRC Server
|
||||
|
||||
There are many ways to host an IRC server, and the exact steps vary depending on your platform, server software and encryption standards.
|
||||
|
||||
### Docker
|
||||
|
||||
One of the easiest ways to launch an IRC server is through Docker, using `inspircd`.
|
||||
For example, this `docker compose` file allows you to run a simple server.
|
||||
|
||||
```YAML
|
||||
name: inspircd
|
||||
services:
|
||||
main_app:
|
||||
cpu_shares: 50
|
||||
command: []
|
||||
container_name: inspircd
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
memory: 2048M # Max RAM usage
|
||||
environment:
|
||||
- INSP_SERVER_NAME=irc.local
|
||||
- INSPIRCD_ADMIN_EMAIL=nomail@example.com
|
||||
- INSPIRCD_ADMIN_NAME=admin
|
||||
hostname: inspircd
|
||||
image: inspircd/inspircd-docker:latest
|
||||
ports:
|
||||
- target: 6667
|
||||
published: "6667"
|
||||
- target: 6697
|
||||
published: "6697"
|
||||
restart: unless-stopped
|
||||
volumes:
|
||||
- type: bind
|
||||
source: /DATA/AppData/irc_server # Config directory
|
||||
target: /inspircd/conf
|
||||
devices: []
|
||||
cap_add: []
|
||||
network_mode: host
|
||||
privileged: false
|
||||
```
|
||||
|
||||
To properly configure your server, be sure to read the [container’s documentation](https://hub.docker.com/r/inspircd/inspircd-docker/).
|
||||
This container generates a self-signed SSL certificate for secure connections, however, it won't be accepted by actual clients. Refer to my [[https-ssl-certs|SSL guide]] to generate a real certificate for TLS to work. After generating your certificate, simply replace the old one with it.
|
||||
|
||||
### Linux
|
||||
|
||||
On Linux, the process is only a little more involved.
|
||||
First, install `inspircd` using your distro's package manager. (IRC server)
|
||||
|
||||
> If you use a firewall, enable ports 22, 6667 and 6697 (for TLS) before continuing.
|
||||
|
||||
```Shell
|
||||
sudo apt update
|
||||
sudo apt install inspircd -y
|
||||
```
|
||||
|
||||
Then, edit the configuration file to your liking.
|
||||
|
||||
```Shell
|
||||
sudoedit /etc/inspircd/inspircd.conf
|
||||
```
|
||||
|
||||
Finally, start `inspircd`.
|
||||
|
||||
```Shell
|
||||
sudo systemctl start inspircd
|
||||
```
|
||||
|
||||
To enable TLS, refer to my [[https-ssl-certs|SSL guide]]. After generating your certificate, copy it to `inspircd`'s ssl directory.
|
||||
|
||||
```Shell
|
||||
sudo cp /etc/letsencrypt/live/irc.example.com/fullchain.pem /etc/inspircd/ssl/cert.pem
|
||||
sudo cp /etc/letsencrypt/live/irc.example.com/privkey.pem /etc/inspircd/ssl/key.pem
|
||||
```
|
||||
|
||||
And add the following block to your `ispircd` configuration:
|
||||
|
||||
```JSON
|
||||
<bind address="" port="6697" type="clients" ssl="gnutls">
|
||||
<gnutls
|
||||
certfile="/etc/inspircd/ssl/cert.pem"
|
||||
keyfile="/etc/inspircd/ssl/key.pem"
|
||||
priority="SECURE192:-VERS-SSL3.0">
|
||||
<module name="m_ssl_gnutls.so">
|
||||
```
|
||||
BIN
content/notes/ready/logic_gates/image42.png
Normal file
|
After Width: | Height: | Size: 2.8 KiB |
BIN
content/notes/ready/logic_gates/image43.png
Normal file
|
After Width: | Height: | Size: 3.3 KiB |
BIN
content/notes/ready/logic_gates/image44.png
Normal file
|
After Width: | Height: | Size: 4.3 KiB |
BIN
content/notes/ready/logic_gates/image45.png
Normal file
|
After Width: | Height: | Size: 3.7 KiB |
BIN
content/notes/ready/logic_gates/image46.png
Normal file
|
After Width: | Height: | Size: 4.5 KiB |
BIN
content/notes/ready/logic_gates/image47.png
Normal file
|
After Width: | Height: | Size: 5.0 KiB |
BIN
content/notes/ready/logic_gates/image48.png
Normal file
|
After Width: | Height: | Size: 5.5 KiB |
BIN
content/notes/ready/logic_gates/image49.png
Normal file
|
After Width: | Height: | Size: 5.2 KiB |
BIN
content/notes/ready/logic_gates/image50.png
Normal file
|
After Width: | Height: | Size: 6.4 KiB |
BIN
content/notes/ready/logic_gates/image51.png
Normal file
|
After Width: | Height: | Size: 12 KiB |
BIN
content/notes/ready/logic_gates/image52.png
Normal file
|
After Width: | Height: | Size: 19 KiB |
BIN
content/notes/ready/logic_gates/image53.png
Normal file
|
After Width: | Height: | Size: 7.1 KiB |
123
content/notes/ready/logic_gates/index.md
Normal file
@@ -0,0 +1,123 @@
|
||||
---
|
||||
title: Logic Gates
|
||||
description:
|
||||
date: 2025-02-17T08:25:49+00:00
|
||||
draft: false
|
||||
tags:
|
||||
- electronics
|
||||
- computer-science
|
||||
author: TrudeEH
|
||||
showToc: true
|
||||
---
|
||||
|
||||
## NOT
|
||||
|
||||
Invert the input.
|
||||
![[image42.png]]
|
||||
|
||||
### Truth Table
|
||||
|
||||
|**Input**|**Output**|
|
||||
|---|---|
|
||||
|0|1|
|
||||
|1|0|
|
||||
|
||||
## AND
|
||||
|
||||
Output `1` only when both inputs are `1`.
|
||||
![[image43.png]]
|
||||
|
||||
### Truth Table
|
||||
|
||||
|A|**B**|**Output**|
|
||||
|---|---|---|
|
||||
|0|0|0|
|
||||
|0|1|0|
|
||||
|1|0|0|
|
||||
|1|1|1|
|
||||
|
||||
## OR
|
||||
|
||||
Output `1` if at least one input is `1`.
|
||||
![[image44.png]]
|
||||
|
||||
### Truth Table
|
||||
|
||||
|A|**B**|**Output**|
|
||||
|---|---|---|
|
||||
|0|0|0|
|
||||
|0|1|1|
|
||||
|1|0|1|
|
||||
|1|1|1|
|
||||
|
||||
## NAND
|
||||
|
||||
An `AND` gate followed by a `NOT` gate.
|
||||
![[image45.png]]
|
||||
|
||||
### Truth Table
|
||||
|
||||
|A|**B**|**Output**|
|
||||
|---|---|---|
|
||||
|0|0|1|
|
||||
|0|1|1|
|
||||
|1|0|1|
|
||||
|1|1|0|
|
||||
|
||||
## NOR
|
||||
|
||||
An `OR` gate followed by a `NOT` gate.
|
||||
![[image46.png]]
|
||||
|
||||
### Truth Table
|
||||
|
||||
|A|**B**|**Output**|
|
||||
|---|---|---|
|
||||
|0|0|1|
|
||||
|0|1|0|
|
||||
|1|0|0|
|
||||
|1|1|0|
|
||||
|
||||
## XOR
|
||||
|
||||
Either input is `1`, exclusively.
|
||||
![[image47.png]]
|
||||
![[image48.png]]
|
||||
|
||||
### Truth Table
|
||||
|
||||
|A|**B**|**Output**|
|
||||
|---|---|---|
|
||||
|0|0|0|
|
||||
|0|1|1|
|
||||
|1|0|1|
|
||||
|1|1|0|
|
||||
|
||||
## XNOR
|
||||
|
||||
Inverted `XOR`.
|
||||
![[image49.png]]
|
||||
|
||||
### Truth Table
|
||||
|
||||
|A|**B**|**Output**|
|
||||
|---|---|---|
|
||||
|0|0|1|
|
||||
|0|1|0|
|
||||
|1|0|0|
|
||||
|1|1|1|
|
||||
|
||||
## Implementation Examples
|
||||
|
||||
### NOT
|
||||
|
||||
![[image50.png]]
|
||||
|
||||
### AND
|
||||
|
||||
![[image51.png]]
|
||||
![[image52.png]]
|
||||
|
||||
### OR
|
||||
|
||||
![[image53.png]]
|
||||
BIN
content/notes/ready/memory/image76.png
Normal file
|
After Width: | Height: | Size: 13 KiB |
BIN
content/notes/ready/memory/image77.png
Normal file
|
After Width: | Height: | Size: 10 KiB |
BIN
content/notes/ready/memory/image78.png
Normal file
|
After Width: | Height: | Size: 11 KiB |
BIN
content/notes/ready/memory/image79.png
Normal file
|
After Width: | Height: | Size: 5.4 KiB |
BIN
content/notes/ready/memory/image80.png
Normal file
|
After Width: | Height: | Size: 21 KiB |
BIN
content/notes/ready/memory/image81.png
Normal file
|
After Width: | Height: | Size: 72 KiB |
BIN
content/notes/ready/memory/image82.png
Normal file
|
After Width: | Height: | Size: 136 KiB |
BIN
content/notes/ready/memory/image83.png
Normal file
|
After Width: | Height: | Size: 39 KiB |
BIN
content/notes/ready/memory/image84.png
Normal file
|
After Width: | Height: | Size: 129 KiB |
BIN
content/notes/ready/memory/image85.png
Normal file
|
After Width: | Height: | Size: 176 KiB |
BIN
content/notes/ready/memory/image86.png
Normal file
|
After Width: | Height: | Size: 63 KiB |
BIN
content/notes/ready/memory/image87.png
Normal file
|
After Width: | Height: | Size: 303 KiB |
BIN
content/notes/ready/memory/image88.png
Normal file
|
After Width: | Height: | Size: 50 KiB |