đ« CS50x Certificate of Completion đ« - Thanks to Flowy for the help and encouragement throughout this course :)
CS50x final project using Flask
Raise virtual pets while improving your language skills! The site is setup using Python, Flask with Jinja templates, and a custom CSS stylesheet. View Distant Life website
Principles:
Ethic principles of democracy:
Framework - a way of organizing your code
Flask:
Running locally (Mac) assuming application.py is entry:
python3 -m venv venv
. venv/bin/activate
pip install Flask
export FLASK_APP=application
flask run
Basic application.py:
# Greets user
from flask import Flask, render_template, request
# turn the current file into a web application
# __name__ refers to current file
app = Flask(__name__)
# define paths
# @ is a python decorator
@app.route("/")
# template pages go in the /templates/ folder
# request libraries allows us to pass ?name=arg in the URL
# arg defaults to None if not set
# passes variable name into function with name value
def index():
return render_template("index.html", name=request.args.get("name", "world"))
Pass into index.html template:
hello,
In cs50 IDE: flask run
TCP/IP governs what goes outside the envelopes. HTTP governs what goes inside of the envelopes.
curl
- connect to URL
We can nest queries:
SELECT title FROM shows WHERE id IN (SELECT show_id FROM genres WHERE genre = "Musical");
Loosely-typed language:
print("hello, " + answer)
# or new print format syntax
print(f"hello, {answer}")
Simple for loop
for i in [0, 1, 2]:
print("mew")
# or use range
for i in range(0,3):
print("mew")
python
translates Python code to computer codeUsing library imports
from cs50 import get_int
x = get_int("x: ")
y = get_int("y: ")
# or use namespace
import cs50
x = cs50.get_int("x: ")
y = cs50.get_int("y: ")
Function hoisting
def main()
to call the functions and call main()
to initdef main():
for i in range(3):
meow()
def meow():
print("meow")
main()
Scope
print("I'll print with a newline")
# You can use an end argument to specify end of line
print("I'll print on the same line", end="")
Errors
import sys
# error (1)
sys.exit(1)
# all good (0)
sys.exit(0)
Files
with open
will automatically close the fileHelpful terms:
struct
- letâs us define our own structures.
- letâs you access a property*
dereference operator - goto / get the value at a pointer->
combines .
and *
functionality1
or 3
0x456
or 0x00
(NULL)Example of LL as custom struct, where next
is a pointer to the next node
typedef struct
{
int number;
node *next; // What is a node here?
}
node;
But since node doesnât exist to refer to the pointer for a type node, we also add the name node
to the top of the struct def and struct
to the pointer variable def:
typedef struct node
{
int number;
struct node *next;
}
node;
More on Linked Lists
malloc
gives you the address of the first byte (size 1 or 100!)NULL
; create empty LL: node *list = NULL;
node *n = malloc(sizeof(node));
(syntax for storing an address)n
is not NULL
before doing any work on it(*n).number = 1;
// or equivalent:
n->number = 1;
n->node = NULL;
next
value NULL to nlist[0]
bracket notation adds to stackint *list = malloc(sizeof(int));
adds to heapReallocate
realloc
- reallocates memory we used earlierint *tmp = realloc(list, 4 * sizeof(int));
Example for loop for linked list items:
for (node *tmp = list; tmp != NULL; tmp = tmp->next)
{
printf("%i\n", tmp->number);
}
How to allocate more nodes in the middle (sorted)
n->next = list;
list = n;
Linked lists are 1-dimensional
typedef struct node
{
int number;
struct node *left;
struct node *right;
}
node;
Essentially an array of linked lists; allows you to âbucketizeâ data to let you get data more quickly
More âbucketsâ
bc
for a CLI calculator!AKA Prefix tree
Hex
FF
works out perfectly for 4 bits: 16 x F
(240) + 1 x F
(15) = 2550x
eg 0x49
Addresses
&
What is the address*
Go to the address; whatâs inside?int n = 50;
printf("%i", n); // 50 - value of n
printf("%p", &n); // 0x123 - address
printf("%i", *&n); // 50 - print value at 0x123 (address)
Pointers
int *p = &n
- declare a pointer of type int*p
to print the value of n
(*&n
)Mailbox example
p
[0x123] - contains value of an address; points to mailbox 0x123n
[50] - contains value of 50p
) addressStrings
typedef char *string
[H][I][!][\0]
, where addresses would be consecutive, eg: [0x123][0x124][0x125][0x126]
, 1 byte apartstring
= char *s = "HI!";
where address of s = &s[0]
printf("%c", *s); \\ H
- print value at address\0
or 0
as type intget_string
returns address of first characterHow would you copy a string?
malloc(4)
, or malloc(strlen(s) + 1)
(to account for \0
)n <= i
) and copy all values, including \0
strcpy(s, t)
Libraries
strcpy(s, t)
- create a new copy of s to tstrcmp(v1, v2) == 0
malloc()
returns the address of the first bytemalloc()
, give the memory back free(t)
get_string()
uses malloc()
and free()
valgrind()
shows where you touched memory; use it debug code'scanf()
scan from userâs keyboardDefining a string variable w/ allocation:
char *s = malloc(4);
// uses heap, needs to also use free()
char s[4];
// uses stack, doens't need free()
Memory layout
File I/O - taking input and output from files
FILE *file = fopen("phonebook.csv", "a");
// a - append
// w - write
// r - read
Full example of reading input and printing to a file:
// Saves names and numbers to a CSV file
#include <cs50.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
// Open CSV file
// FILE is a native C type
FILE *file = fopen("phonebook.csv", "a");
// Check if file is not null
if (!file)
{
return 1;
}
// Get name and number
string name = get_string("Name: ");
string number = get_string("Number: ");
// Print to file
fprintf(file, "%s,%s\n", name, number);
// Close file
fclose(file);
}
fopen(pathname, mode)
- returns a pointer to the FILE or NULLfclose(pointer)
- close the file (previously opened by fopen
) at the given pointerfprintf(pointer, format, values)
- prints to a filefread(pointerToStoreAt, size, numberToRead, filePointer)
- read bytes from a file and store at the pointerToStoreAtFor iterating thru bytes, we need to define a custom typedef:
typedef uint8_t BYTE;
Then we can copy, using buffer
as a temporary value
// Copy source to destination, one BYTE at a time
BYTE buffer;
while (fread(&buffer, sizeof(BYTE), 1, source))
{
fwrite(&buffer, sizeof(BYTE), 1, destination);
}
Images
Many file types have âmagic numbersâ the first N bytes in a file that establish what type of file it is; for example, every JPG will start with 0xff 0xd8 0xff
Common formulas:
Comparing string values
==
for comparing string valuesstrcmp()
from string.h
include: strcmp(compare_to_string, word_to_find)
returning 0 (equal), negative (first str comes before second), positive (first str comes after second) â compares ASCII order, not alphabetical\0
Hertz defs
Creating custom types / data structuresâallows you to keep related data tied together
typedef struct
{
string name;
string number;
}
person;
int main(void)
{
person people[2]; // Init person structure of size 2
people[0].name = "Brian";
people[0].number = "555-555-5555";
...
}
Selection Sort
For i from 0 to n-1
Find smallest item between i'th item and last item
Swap smallest item with i'th item
Bubble Sort
(n-2)
because we donât compare the last number to another number (out of bounds)Repeat n-1 times
For i from 0 to n-2
If i'th and i+1'th elements out of order
Swap them
If no swaps
Quit
Merge Sort
If only one number // Needs recursive base case
Quit
Else
Sort left half of numbers
Sort right half of numbers
Merge sorted halves
Recursion
Clang
clang
is used as a compiler when you type make
clang -o hello hello.c -lcs50
: passes in arguments, -o, hello, hello.c, -lcs50Compiling
#include cs50.h
, and copies the contents of the file into the program; implements prototypesxorl %ebx, %ebx
would be like i = 0
)Debugging
debug50
on your compiled code, e.g. debug50 ./buggy
Size of C Types
âcode smellâ - when something is off with the code, but you canât quite pinpoint it
C Notes:
char brick = '#'
string pyramid = "###"
\0
(the Null character)For loop to get chars from string, check for null character:
string s = get_string("Input: ");
printf("Output: ");
for (int i = 0; s[i] != '\0'; i++) {
printf("%c", s[i])
}
for (int i = 0, n = strlen(s); s[i] < n; i++) {
printf("%c", s[i])
}
Or use string.h and strlen()
ctype.h
Manual pages for the C standard library, C POSIX library, and the CS50 Library.
int main(int argc, string argv[]) {
# argv[0] will be the file name
# argv[1] would be the command line argument
# argc automatically saves how many words typed in (including filename, so 2 here)
}
Successful c functions return 0
for normal or return 1
for errors
đ„„ Shorts
#include <studio.h>
#include <cs50.h>
bool main(void) {
int side1 = get_int("Side 1: ");
int side2 = get_int("Side 2: ");
int side3 = get_int("Side 3: ");
return valid_triangle(side1, side2, side3);
}
bool valid_triangle(int side1, int side2, int side3) {
if (side1 <= 0 || side2 <= 0 || side3 <= 0) {
return false;
}
if (side1 + side2 > side3) {
if (side2 + side3 > side1) {
if (side3 + side1 > side 2) {
return true;
}
}
}
return false;
}
Arrays in C
type name[size]
or bool truths[3] = { true, false, true }
Command line args
help50 make file
, style50 make file
or check50 make file
as needed#include <cs50.h>
#include <stdio.h>
// Prototype
void meow(void);
int main(void)
{
meow();
}
void meow(void)
{
string answer = get_string("what's your name? ");
printf("meow, %s\n", answer);
}
5 Types built-in to C:
Types not built-in to C available in CS50 library:
You can init two variables in one line, for example: int height, width;