The Most Important CSS Selectors


/* https://code.tutsplus.com/tutorials/the-30-css-selectors-you-must-memorize--net-16048 */

/* every element on page */
* {
border: 1px solid lightgrey;
}

/* element */
li {
text-decoration: underline;
}

/* class */
.hello {

}
/* id */
#name {

}

/* Descendant Selectors - example only affects links in an unordered list */
li a {
color: red;
}

/* Adjacent Selectors - examples only affects unordered lists that follow a h3 */
h3 + ul {
border: 4px solid red;
}

/* Attribute Selectors - examples selects only links that include the given url - can be used for any attribute like images */
a[href="http://www.google.com"] {
background: blue;
}

input[type="text"] {
background: orange;
}

/* nth of type */
ul:nth-of-type(3) {
background: purple;
}

li:nth-of-type(even) {
background: green;
}

A proper HTML5 form

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>test form</title>
</head>
<body>
	<h1>Register</h1>

	<form action="">
		<label for="first">First Name</label>
		<input type="text" id="first" placeholder="first name" required>

		<label for="last">Last Name</label>
		<input type="text" id="last" placeholder="last name" required>

		<br /> 

		<label for="male">Male:</label>
		<input type="radio" name="gender" id="male" value="male">

		<label for="female">Female:</label>
		<input type="radio" name="gender" id="female" value="female">

		<label for="male">Other:</label>
		<input type="radio" name="gender" id="other" value="other">

		<br /> 

		<label for="email">E-Mail</label>
		<input type="email" id="email" placeholder="E-Mail" required>

		<label for="password">Password</label>
		<input type="password" id="password" placeholder="password" minlength="5" maxlength="10" required>

		<br />

		<span>Birthday:</span>

		<select name="month">
			<option>Month:</option>
			<option>January</option>
			<option>February</option>
		</select>

		<select name="year">
			<option>Year:</option>
			<option>2019</option>
			<option>2018</option>
			<option>2017</option>
		</select>

		<select name="day">
			<option>Day:</option>
			<option>1</option>
			<option>2</option>

		</select>

		<br /> 

		<input type="submit" name="submit" value="submit">

	</form>

</body>
</html>

Password-Manager with Salt and Pepper (commented version will follow soon)

from hashlib import pbkdf2_hmac

lower_case = list("abcdefghijklmnopqrstuvwxyz")
upper_case = list("ABCDEFGHJKLMNOPQRTUVWXYZ")
numbers = list("0123456789")
special_char = list("!§$%&/()=?[],.-")
password_chars = lower_case + upper_case + numbers + special_char
salt = "pepper"

def convert_bytes_to_password(hashed_bytes, length):
    number = int.from_bytes(hashed_bytes, byteorder="big")
    password = ""
    while number > 0 and len(password) < length:
        password = password + password_chars[number % len(password_chars)]
        number = number // len(password_chars)
    return password

master_password = input("Master Password: ")
domain = input("Website: ")

while len(domain) < 1:
    print("Enter a Website you want to generate the password for: ")
    domain = input("Website: ")

hash_string = domain + master_password

hashed_bytes = pbkdf2_hmac("sha512",
                            hash_string.encode("utf-8"),
                            salt.encode("utf-8"),
                            4096)

print("Passwort: " + convert_bytes_to_password(hashed_bytes, 10))

The Anatomy Of A Python Class

class Customer:

    #global limit = -1000

    def __init__(self):
        #in a real app these values would be provided most likely by a database
        self.balance = 0
        self.limit = -1000
        self.security_check = True
        self.is_active = True

    def credit_limit(self, balance):
        #limit = -1000
        if balance < self.limit:
            return False
        else:
            return True

    def withdraw(self, amount):
        #act_balance = self.balance - amount
        self.balance -= amount
        if (self.credit_limit(self.balance) == True):
            return self.balance
        else:
            return ("Withdrawl not possible. You reached the credit limit.")

    def deposit(self, amount):
        self.balance += amount
        return self.balance



a = Customer()

b = Customer()

print(a.withdraw(500))                        #   - 500
print(a.deposit(100))                         #   - 400

print(b.withdraw(1500))                       #   Withdrawl not possible. You reached the credit limit.

Day 69: Make Good Looking Tables With PrettyTable (Module)

 

Scripts running in the shell are pretty cool. But sometime you want to display tables that have no real format.

 

The module PrettyTable generates some – well pretty – tables with just a couple of lines.

 

The script takes a dictionary with the sizes of all planets in the solar system.

 

It exports it in a PrettyTable in descending order.

 

# PrettyTable module
# Create handsome tables in your shell
from prettytable import PrettyTable

planets = {"Mercury" : "4879",
        "Venus" : "12104",
        "Earth" : "12756",
        "Mars" : "6779",
        "Jupiter" : " 142984",
        "Saturn" : "120536",
        "Uranus" : "50724",
        "Neptune" : "49244"
        }

# create the table with two colums
size_table = PrettyTable(["Planet", "Diameter (km)"])

# go over every planet in dict and add a row for each
for item in planets:
    size_table.add_row([item, planets[str(item)]])

# sort planets from big to small
size_table.sort = True

print(size_table)

The output looks like this:

 

 

Day 66: Being A Scribe – Read From And Write To Files

# Read and write files

# open the file with 'write'-mode
test_file = open("files_test.txt", "r")


# full list of file modes
# "w" - write text file (overwrite possible)
# "r" - read text file
# 'x' - write text file (includes error is file exists)
# 'a' - append to end of file
# 'rb' - read binary files
# 'wb' - write binary
# 'w+b' - read and write binary file
# 'xb' - write binary file (includes error is file exists)
# 'ab' - append to end of binary file

# Read files
print(test_file.read())                     # This is a test - full text

# Read one line
print(test_file.readline())                  # This is a test - one line


# iterate over text files
for line in test_file:
    print(line)                              # This is a test - all lines

# readline() is not very well suited to iterate over big files

# close files - you should alway close a file after using it!!!
test_file.close()

# Write to files
texty = open("files_test.txt", 'w')
texty.write("11 This is a test\n")
print(texty.read())
texty.close()

Day 64: Check If A String is a Palindrome With Python

 

We get a string and check if it is a palindrome:

 

# Find out if a word is a palindrome
def palin(word):
    ''' take word, build inverted string
    and check if it is a palindrome '''

    word = word.replace(".", "")    # get rid of eventual "."
    word = word.lower()             # make lowercase

    length = len(word)
    new = list("")                  # build an empty list for the inversed string
    index = -1                      # -1 so we start building in reverse order

    # take every letter and add it to new list in reverse order
    for i in word:
        new.insert(index, i)
        index -= 1

    # change list to string
    new_str = "".join(new)

    # get rid of any spaces in a sentence
    word_stripped = word.replace(" ", "")
    new_stripped = new_str.replace(" ", "")

    # check if word and the reverse string are the same
    if (word_stripped == new_stripped):
        return (word + ": This is a palindrome")
    else:
        return (word + ": This is NOT a palindrome")

print(palin("Anna"))                    # anna: This is a palindrome

print(palin("peter"))                   # peter: This is NOT a palindrome

print(palin("Name not one man."))       # name not one man: This is a palindrome

Day 63: Indexing And Slicing

# Indexing
# note: sets can't be indexed

my_guitars = ["Gibson Les Paul", "Ibanez RG", "Fender Stratocaster"]

print(my_guitars[0])                # Gibson Les Paul

# Python allows negative indexing. -1 returns the last item aso
print(my_guitars[-1])               # Fender Stratocaster
print(my_guitars[-2])               # Ibanez RG


# indexing a tuple
print(("Marshall", "Laney", "Orange")[1])       # Laney

# indexing a string
print("Wampler"[3])                 # p - index starts at 0

# slicing
print(my_guitars[0:2])              # ['Gibson Les Paul', 'Ibanez RG']


# note: the first index is optional. negative indexing works here as well
print(my_guitars[:2])              # ['Gibson Les Paul', 'Ibanez RG']
print(my_guitars[:-1])              # ['Gibson Les Paul', 'Ibanez RG']


#Examples

# get first and last letter
name = "Robert"

print(name[0])                      # R
print(name[-1])                     # t

# delete the file extension
filename = "document.txt"

print(filename[0:-4])               # document