<repo_name>komtex/cs50-18<file_sep>/pset3/recover/recover.c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <cs50.h>
int main(int argc, char *argv[])
{
    char *infile = argv[1];
    if (argc != 2)
    {
        fprintf(stderr, "usage: ./recover image\n");
        return 1;
    }

    //open memory card
    FILE *inptr = fopen(infile, "r");
    if (inptr == NULL)
    {
        fprintf(stderr, "Could not open %s.\n", infile);
        return 2;
    }
    unsigned char buffer[512];
    bool openFile = false;
    int jpegStart = 0;
    char filename [10];
    FILE *img_file;
    while (fread(&buffer, 512, 1, inptr))
    {
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
            //yes started jpeg
        {
            if (openFile)
            {
                //close prev. opened file
                fclose(img_file);
                //set to false
                openFile = false;
                sprintf(filename, "%03d.jpg", jpegStart);
                img_file = fopen(filename, "a");
                openFile = true;
                jpegStart ++;
            }
            //do not have an open file
            if (!openFile)
            {
                //name a new one
                sprintf(filename, "%03d.jpg", jpegStart);
                img_file = fopen(filename, "w");
                openFile = true;
                jpegStart ++;
            }
            fwrite(&buffer, 512, 1, img_file);
        }
        else
        {
            if (openFile)
            {
                fwrite(&buffer, 512, 1, img_file);
            }
            if (!openFile)
            {
                //does nothing
            }
        }

    }

    fclose(inptr);
    fclose(img_file);

    return 0;
}
<file_sep>/pset6/vigenere/vigenere3.py
import cs50
import sys

# Implements a Caesar cipher.
def main():

    # Gets key as int; validates
    cipher = sys.argv[1]

    if not cipher.isalpha or not len(sys.argv) == 2:
        exit(1)

    # Gets plaintext
    print("Plaintext: ", end="")
    ptext = cs50.get_string()

    print("Ciphertext: ", end="")

    # Counter for cipher
    n = 0

    # Enciphers while preserving case, prints
    for c in ptext:

        key = get_key(cipher, n)

        # Character is uppercase
        if c.isupper():
            upper = (((ord(c) - ord('A')) + key) % 26) + ord('A')
            print(chr(upper), end="")
            n += 1

        # Character is lowercase
        elif c.islower():
            lower = (((ord(c) - ord('a')) + key) % 26) + ord('a')
            print(chr(lower), end="")
            n += 1

        elif not c.isalpha():
            print("{}".format(c), end="")

    # Prints newline
    print()

    import sys
from cs50 import get_string


def is_valid(k):
    for ch in k:
        if not ch.isalpha():
            return False
    return True


def main():
    if len(sys.argv) != 2 or not is_valid(sys.argv[1]):
        print("Usage: ./vigenere k")
        sys.exit(1)

    k = sys.argv[1]
    plaintext = get_string("plaintext: ")
    j = 0

    print("ciphertext: ", end="")

    for ch in plaintext:
        if not ch.isalpha():
            print(ch, end="")
            continue

        ascii_offset = 65 if ch.isupper() else 97

        pi = ord(ch) - ascii_offset
        kj = ord(k[j % len(k)].upper()) - 65
        ci = (pi + kj) % 26
        j += 1

        print(chr(ci + ascii_offset), end="")

    print()

    return 0


if __name__ == "__main__":
    main()<file_sep>/pset6/caesar/caesar.py
from cs50 import get_string
from sys import argv
import sys
import cs50


def main():
    # validate right command line
    if len(sys.argv) != 2:
        print("Usage: python caesar.py k")
        sys.exit(1)
    elif sys.argv[1].isdigit == 0:
        print(f"Usage: python caesar.py k")
    # get key as int, gets plaintext
    else:
        k = int(sys.argv[1])
        s = get_string("plaintext: ")
        print("ciphertext: ", end="")
    # enciphers plaintext
    for i in range(len(s)):
        # Character is uppercase
        if str.isupper(s[i]):
            upper = (((ord(s[i]) - 65) + k) % 26) + 65
            print(chr(upper), end="")
     # Characters is lowercase
        elif str.islower(s[i]):
            lower = (((ord(s[i]) - 97) + k) % 26) + 97
            print(chr(lower), end="")
        else:
            print("{}".format(s[i]), end="")
     # print new line
    print()

# print ciphertext


if __name__ == "__main__":
    main()
<file_sep>/pset4/speller/dictionary3.c
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <ctype.h>
#include "dictionary.h"

/**
 * Returns true if word is in dictionary else false.
 */

int hashvalue(const char* a);

int word_count=0;
char word[LENGTH+1];
typedef struct node
{
    char* word;
    struct node* next;
}
node;

//each element in htable will contain an address to a node
node* htable[HT_SIZE];

bool check(const char* word)
{
    int hv = hashvalue(word);
    node* ptr = malloc(sizeof(node));
    ptr = htable[hv]->next;
    while(ptr!=NULL)
    {
        //if ( (int)toupper(ptr->word[1])<(int)toupper(word[1]))
        //    return false;
        if (strcasecmp(ptr->word,word)==0)
        {
            return true;
        }

        else
        {
            ptr = ptr->next;
        }
    }
    return false;
}

/**
 * Loads dictionary into memory.  Returns true if successful else false.
 */
bool load(const char* dictionary)
{
    // Open the given file location
    FILE* inptr = fopen(dictionary,"r");
    // create a keeper for the word which is a character array of length Large
    for (int i = 0; i < HT_SIZE; i++)
    {
        htable[i] = malloc(sizeof(node));
    }

    if (inptr == NULL)
    {
        printf("Could not open %s.\n", dictionary);
        return false;
    }


    while (fscanf(inptr,"%s\n",word) != EOF)
    {

        node* newword = malloc(sizeof(node));
        newword->word = malloc(strlen(word)+1);
        strcpy(newword->word,word);
        newword->next = NULL;
        int hv = hashvalue(word);
        word_count++;
        if (htable[hv]==NULL)
        {
            htable[hv]->next = newword;
        }
        else
        {
            node* nodenext = malloc(sizeof(node));
            nodenext = htable[hv]->next;
            htable[hv]->next = newword;
            newword->next = nodenext;
        }
    }
    return true;

}

/**
 Returns number of words in dictionary if loaded else 0 if not yet loaded.
 */
unsigned int size(void)
{
    return word_count;
    return 0;
}

/**
 * Unloads dictionary from memory.  Returns true if successful else false.
 */
bool unload(void)
{
    node* pnode;
    node* ptr;
    for(int i=0;i<HT_SIZE;i++)
    {
       ptr = htable[i];
       while(ptr!=NULL)
        {
            pnode=ptr;
            ptr = ptr->next;
            free(pnode);
        }
    }
    free(ptr);
    return true;
}


int hashvalue(const char* a)
{
    int x =  a[0];
    int y =  a[1];
    int hash = 0 ;

    if (x > 64 && x < 91 )
    {
        x = x + 32;
    }
    if (y > 64 && y < 91 )
    {
        y =y+32;

    }
    hash = (x*y)%(HT_SIZE);
    return hash;
}


#include <stdbool.h>
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

#include "dictionary.h"


// size of hashtable
#define SIZE 1000000

// create nodes for linked list
typedef struct node
{
    char word[LENGTH+1];
    struct node* next;
}
node;

// create hashtable
node* hashtable[SIZE] = {NULL};

// create hash function
int hash (const char* word)
{
    int hash = 0;
    int n;
    for (int i = 0; word[i] != '\0'; i++)
    {
        // alphabet case
        if(isalpha(word[i]))
            n = word [i] - 'a' + 1;

        // comma case
        else
            n = 27;

        hash = ((hash << 3) + n) % SIZE;
    }
    return hash;
}

// create global variable to count size
int dictionarySize = 0;

/**
 * Loads dictionary into memory.  Returns true if successful else false.
 */
bool load(const char* dictionary)
{
    // TODO
    // opens dictionary
    FILE* file = fopen(dictionary, "r");
    if (file == NULL)
        return false;

    // create an array for word to be stored in
    char word[LENGTH+1];

    // scan through the file, loading each word into the hash table
    while (fscanf(file, "%s\n", word)!= EOF)
    {
        // increment dictionary size
        dictionarySize++;

        // allocate memory for new word
        node* newWord = malloc(sizeof(node));

        // put word in the new node
        strcpy(newWord->word, word);

        // find what index of the array the word should go in
        int index = hash(word);

        // if hashtable is empty at index, insert
        if (hashtable[index] == NULL)
        {
            hashtable[index] = newWord;
            newWord->next = NULL;
        }

        // if hashtable is not empty at index, append
        else
        {
            newWord->next = hashtable[index];
            hashtable[index] = newWord;
        }
    }

    // close file
    fclose(file);

    // return true if successful
    return true;
}

/**
 * Returns true if word is in dictionary else false.
 */
bool check(const char* word)
{
    // TODO
    // creates a temp variable that stores a lower-cased version of the word
    char temp[LENGTH + 1];
    int len = strlen(word);
    for(int i = 0; i < len; i++)
        temp[i] = tolower(word[i]);
    temp[len] = '\0';

    // find what index of the array the word should be in
    int index = hash(temp);

    // if hashtable is empty at index, return false
    if (hashtable[index] == NULL)
    {
        return false;
    }

    // create cursor to compare to word
    node* cursor = hashtable[index];

    // if hashtable is not empty at index, iterate through words and compare
    while (cursor != NULL)
    {
        if (strcmp(temp, cursor->word) == 0)
        {
            return true;
        }
        cursor = cursor->next;
    }

    // if you don't find the word, return false
    return false;
}

/**
 * Returns number of words in dictionary if loaded else 0 if not yet loaded.
 */
unsigned int size(void)
{
    // TODO
    // if dictionary is loaded, return number of words
    if (dictionarySize > 0)
    {
        return dictionarySize;
    }

    // if dictionary hasn't been loaded, return 0
    else
        return 0;
}

/**
 * Unloads dictionary from memory.  Returns true if successful else false.
 */
bool unload(void)
{
    // TODO
    // create a variable to go through index
    int index = 0;

    // iterate through entire hashtable array
    while (index < SIZE)
    {
        // if hashtable is empty at index, go to next index
        if (hashtable[index] == NULL)
        {
            index++;
        }

        // if hashtable is not empty, iterate through nodes and start freeing
        else
        {
            while(hashtable[index] != NULL)
            {
                node* cursor = hashtable[index];
                hashtable[index] = cursor->next;
                free(cursor);
            }

            // once hashtable is empty at index, go to next index
            index++;
        }
    }

    // return true if successful
    return true;
}
//hash function
 int hash = 0;
    int n;
    for (int i = 0; word[i] != '\0'; i++)
    {
        // alphabet case
        if(isalpha(word[i]))
            n = word [i] - 'a' + 1;

        // comma case
        else
            n = 27;

        hash = ((hash << 3) + n) % N;
    }
    return hash;<file_sep>/README.md
CS50 is an outstanding resource which makes the fundementals of computer science available to everyone, for free.
Hats off to Harvard, EDX and everyone involved in putting it all together.
This repository is where I'm storing my personal progress on the course,
which I'm taking in 2019. In the spirit of academic honesty,
I would encourage you to not look if you're also taking the course or looking to enroll.
<file_sep>/pset6/caesar/caesar2.py
import cs50
import sys

# Implements a Caesar cipher.
def main():

    # Gets key as int; validates
    while True:
        key = int(sys.argv[1])
        if key > 0:
            break

    # Gets plaintext
    print("Plaintext: ", end="")
    ptext = cs50.get_string()

    print("Ciphertext: ", end="")

    # Enciphers while preserving case
    for i in range(len(ptext)):

        # Character is uppercase
        if str.isupper(ptext[i]):
            upper = (((ord(ptext[i]) - 65) + key) % 26) + 65
            print(chr(upper), end="")

        # Character is lowercase
        elif str.islower(ptext[i]):
            lower = (((ord(ptext[i]) - 97 ) + key ) % 26 ) + 97
            print(chr(lower), end="")

        else:
            print("{}".format(ptext[i]), end="")

    # Prints newline
    print()

# print ciphertext

if __name__ == "__main__":
    main()
<file_sep>/pset6/mario/less/mario.py


from cs50 import get_int


while True:
    n = get_int("height:")
    if n > 0 and n <= 8:
        break


for i in range(n):

    for j in range(i, n-1):
        print(" ", end="")
    for k in range(n, i+n+1):
        print("#", end="")
    print()
<file_sep>/pset6/vigenere/vigenere.py

from cs50 import get_string
from sys import argv
import sys
import cs50


def main():
    # validate right command line
    if len(sys.argv) != 2 or sys.argv[1].isalpha() == 0:
        print("Usage: python vigenere.py k")
        sys.exit(1)

    # get key as int, gets plaintext
    else:
        key = sys.argv[1]
        s = get_string("plaintext: ")
        # counter for cipher
        j = 0
        print("ciphertext: ", end="")
        # Enciphers casa, print
    for i in s:
        # character is uppercase
        if i.isupper():
            upper = (((ord(i) - 65) + (ord(key[j % len(key)].upper()) - 65)) % 26) + 65
            j += 1
            print(chr(upper), end="")
            # character is lowercase
        elif i.islower():
            lower = (((ord(i) - 97) + (ord(key[j % len(key)].upper()) - 65)) % 26) + 97
            j += 1
            print(chr(lower), end="")

        elif not i.isalpha():
            print("{}".format(i), end="")
     # print new line
    print()


if __name__ == "__main__":
    main()
<file_sep>/pset6/bleep/bleep.py
from cs50 import get_string
from sys import argv
import sys


def main():

         #check command-line argument
    if len(sys.argv) != 2:
        print("Usage: python bleep.py dictionary")
        sys.exit(1)

    else:
        #load txt file
        load(argv[1])
        #prompt user input
        user_in = get_string("What message would you like to censor?")



def load(banned):
    file = open("banned.txt","r")
    words = file.read()
   print(words)
   file.close()


if __name__ == "__main__":
    main()
<file_sep>/pset6/cash/cash.py
from cs50 import get_float


x = 0
while True:
    n = get_float("Change owed:")
    if n > 0:
        break

coins = (round(n * 100))

while coins >= 25:
    coins = coins - 25
    x += 1
while coins >= 10:
    coins = coins - 10
    x += 1

while coins >= 5:
    coins = coins - 5
    x += 1

while coins >= 1:
    coins = coins - 1
    x += 1

print(x)<file_sep>/pset6/credit/credit.py
from cs50 import get_int
from math import floor
from cs50 import get_string


def main():
    digit1 = 0
    digit2 = 0
    num_digits = 0
    double_odds = 0
    evens = 0
    numbers = get_int("Number: ")

    while numbers > 0:
        # first and second digits at the beginning are equals
        digit2 = digit1
        digit1 = numbers % 10
        # multiply each second digit and sum odd and even
        if num_digits % 2 == 0:
            evens += digit1
        else:
            m = 2 * digit1
            double_odds += (m // 10) + (m % 10)
        # loop till the end of digits
        numbers //= 10
        num_digits += 1
        # test for validity by dividing to 10
    is_valid = (evens + double_odds) % 10 == 0
    first_two_digits = (digit1 * 10) + digit2

    if digit1 == 4 and num_digits >= 13 and num_digits <= 16 and is_valid:
        print("VISA\n")
    elif first_two_digits >= 51 and first_two_digits <= 55 and num_digits == 16 and is_valid:
        print("MASTERCARD\n")
    elif (first_two_digits == 34 or first_two_digits == 37) and num_digits == 15 and is_valid:
        print("AMEX\n")
    else:
        print("INVALID\n")


if __name__ == "__main__":
    main()<file_sep>/pset7/survey/application.py
import cs50
import csv
import os

from flask import Flask, jsonify, redirect, render_template, request

# Configure application
app = Flask(__name__)

# Reload templates when they are changed
app.config["TEMPLATES_AUTO_RELOAD"] = True


@app.after_request
def after_request(response):
    """Disable caching"""
    response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
    response.headers["Expires"] = 0
    response.headers["Pragma"] = "no-cache"
    return response


@app.route("/", methods=["GET"])
def get_index():
    return redirect("/form")


@app.route("/form", methods=["GET"])
def get_form():
    return render_template("form.html")

@app.route("/form", methods=["POST"])
def post_form():
    if not request.form.get("name") or not request.form.get("group") or not request.form.get("phone"):
        return render_template("error.html", message = "You must fill input field")
    with open("survey.csv", "a") as file:
        writer = csv.DictWriter(file, fieldnames = ["name", "phone", "group", "k1", "k2"])
        writer.writerow({"name": request.form.get("name"), "phone": request.form.get("phone"), "group": request.form.get("group"), "k1": request.form.get("k1"), "k2": request.form.get("k2")})
    return redirect("/sheet")

@app.route("/sheet", methods=["GET"])
def get_sheet():
    with open('survey.csv', 'r') as file:
        reader = csv.reader(file)
        table_rows = list(reader)

    return render_template("sheet.html", table_rows=table_rows)
<file_sep>/pset6/bleep/bleep1.py
from cs50 import get_string
from sys import argv
import sys


def main():
    words = 0
         #check command-line argument
    if len(sys.argv) != 2:
        print("Usage: python bleep.py dictionary")
        sys.exit(1)

    else:
        #load txt file
        load(argv[1])
        #prompt user input
        user_in = get_string("What message would you like to censor?")



        #tokenize input
        tokens = user_in.split()

        #check with txt
    for i in tokens:
        if check(i):
            for j in i:
                print("*", end="")
        else:
            print(i, end="")
        print(" ", end="")

    return True

def load(banned.txt):
    #load word in txt file
    file = open(banned.txt, "r")
    for line in file:
        words.add(line.rstrip("\n"))
    file.close()
    return True

def check(word):
    #Return true if word is in dictionary else false
    return word.lower() in words



if __name__ == "__main__":
    main()
