stuff
This commit is contained in:
commit
91d67e7aeb
12
1-coffee-maker/README.md
Normal file
12
1-coffee-maker/README.md
Normal file
@ -0,0 +1,12 @@
|
||||
## Coffee Maker
|
||||
|
||||
You will be designing a software implementation of a simple coffee maker. The following hardware needs to be monitored. Write the methods for:
|
||||
|
||||
* The heating element for the boiler. It can be turned on or off.
|
||||
* The heating element for the warmer plate. It can be turned on or off.
|
||||
* The sensor for the warmer plate. It has three states: warmerEmpty, potEmpty, potNotEmpty.
|
||||
* A sensor for the boiler, which determines whether there is water present. It has two states: boilerEmpty or boilerNotEmpty.
|
||||
* The Brew button. This is a momentary button that starts the brewing cycle. It has an indicator that lights up when the brewing cycle is over and the coffee is ready.
|
||||
* A pressure-relief valve that opens to reduce the pressure in the boiler. The drop in pressure stops the flow of water to the filter. It can be opened or closed.
|
||||
|
||||
You should do this OO. Think about the flow of information and the flow of state. Your methods should not have to worry about each other's implementations, just their interface. Take your time to make sure everything is interacting with each other as they should. This is an exercise in design, not code. If you design well, the coding will be easy.
|
0
1-coffee-maker/coffee-maker.py
Normal file
0
1-coffee-maker/coffee-maker.py
Normal file
33
10-django-departments/README.md
Normal file
33
10-django-departments/README.md
Normal file
@ -0,0 +1,33 @@
|
||||
Employees and Departments
|
||||
=========================
|
||||
|
||||
#### Database Creation - One to Many Relationship
|
||||
|
||||
Using the Django ORM, create tables with these values and relationships:
|
||||
|
||||
An employee has a name and a birthdate.
|
||||
An employee belongs to a department.
|
||||
|
||||
A department has a name and a budget.
|
||||
A department has many employees.
|
||||
|
||||
Don't forget to makemigrations and migrate your db.
|
||||
|
||||
#### Build it out
|
||||
|
||||
Now we've got some additional requirements.
|
||||
|
||||
An employee can be a manager.
|
||||
A manager has a team of employees.
|
||||
Employees can belong to multiple teams.
|
||||
An employee can be in multiple departments.
|
||||
|
||||
After you make each change, makemigrations and migrate again to test it. What happens? What do the migration files look like inside?
|
||||
|
||||
Continue to sandbox and see how your relationships work. If you are having trouble seeing the relationships, think about adding a `__str__` method to each of your tables, so that you get easier to read feedback.
|
||||
|
||||
Resources
|
||||
---------
|
||||
|
||||
[Django's ORM Docs](https://docs.djangoproject.com/en/dev/topics/db/models/)
|
||||
[Many to many example](https://docs.djangoproject.com/en/dev/topics/db/examples/many_to_many/)
|
0
10-django-departments/departments/app/__init__.py
Normal file
0
10-django-departments/departments/app/__init__.py
Normal file
3
10-django-departments/departments/app/admin.py
Normal file
3
10-django-departments/departments/app/admin.py
Normal file
@ -0,0 +1,3 @@
|
||||
from django.contrib import admin
|
||||
|
||||
# Register your models here.
|
3
10-django-departments/departments/app/models.py
Normal file
3
10-django-departments/departments/app/models.py
Normal file
@ -0,0 +1,3 @@
|
||||
from django.db import models
|
||||
|
||||
# Create your models here.
|
3
10-django-departments/departments/app/tests.py
Normal file
3
10-django-departments/departments/app/tests.py
Normal file
@ -0,0 +1,3 @@
|
||||
from django.test import TestCase
|
||||
|
||||
# Create your tests here.
|
3
10-django-departments/departments/app/views.py
Normal file
3
10-django-departments/departments/app/views.py
Normal file
@ -0,0 +1,3 @@
|
||||
from django.shortcuts import render
|
||||
|
||||
# Create your views here.
|
83
10-django-departments/departments/departments/settings.py
Normal file
83
10-django-departments/departments/departments/settings.py
Normal file
@ -0,0 +1,83 @@
|
||||
"""
|
||||
Django settings for departments project.
|
||||
|
||||
For more information on this file, see
|
||||
https://docs.djangoproject.com/en/1.7/topics/settings/
|
||||
|
||||
For the full list of settings and their values, see
|
||||
https://docs.djangoproject.com/en/1.7/ref/settings/
|
||||
"""
|
||||
|
||||
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
|
||||
import os
|
||||
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
|
||||
|
||||
|
||||
# Quick-start development settings - unsuitable for production
|
||||
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
|
||||
|
||||
# SECURITY WARNING: keep the secret key used in production secret!
|
||||
SECRET_KEY = '(%zg=9c2rm11!af7g&95z#99*_rwf4cj_%&r8a#)r6yxneo(wn'
|
||||
|
||||
# SECURITY WARNING: don't run with debug turned on in production!
|
||||
DEBUG = True
|
||||
|
||||
TEMPLATE_DEBUG = True
|
||||
|
||||
ALLOWED_HOSTS = []
|
||||
|
||||
|
||||
# Application definition
|
||||
|
||||
INSTALLED_APPS = (
|
||||
'django.contrib.admin',
|
||||
'django.contrib.auth',
|
||||
'django.contrib.contenttypes',
|
||||
'django.contrib.sessions',
|
||||
'django.contrib.messages',
|
||||
'django.contrib.staticfiles',
|
||||
)
|
||||
|
||||
MIDDLEWARE_CLASSES = (
|
||||
'django.contrib.sessions.middleware.SessionMiddleware',
|
||||
'django.middleware.common.CommonMiddleware',
|
||||
'django.middleware.csrf.CsrfViewMiddleware',
|
||||
'django.contrib.auth.middleware.AuthenticationMiddleware',
|
||||
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
|
||||
'django.contrib.messages.middleware.MessageMiddleware',
|
||||
'django.middleware.clickjacking.XFrameOptionsMiddleware',
|
||||
)
|
||||
|
||||
ROOT_URLCONF = 'departments.urls'
|
||||
|
||||
WSGI_APPLICATION = 'departments.wsgi.application'
|
||||
|
||||
|
||||
# Database
|
||||
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
|
||||
|
||||
DATABASES = {
|
||||
'default': {
|
||||
'ENGINE': 'django.db.backends.sqlite3',
|
||||
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
|
||||
}
|
||||
}
|
||||
|
||||
# Internationalization
|
||||
# https://docs.djangoproject.com/en/1.7/topics/i18n/
|
||||
|
||||
LANGUAGE_CODE = 'en-us'
|
||||
|
||||
TIME_ZONE = 'UTC'
|
||||
|
||||
USE_I18N = True
|
||||
|
||||
USE_L10N = True
|
||||
|
||||
USE_TZ = True
|
||||
|
||||
|
||||
# Static files (CSS, JavaScript, Images)
|
||||
# https://docs.djangoproject.com/en/1.7/howto/static-files/
|
||||
|
||||
STATIC_URL = '/static/'
|
10
10-django-departments/departments/departments/urls.py
Normal file
10
10-django-departments/departments/departments/urls.py
Normal file
@ -0,0 +1,10 @@
|
||||
from django.conf.urls import patterns, include, url
|
||||
from django.contrib import admin
|
||||
|
||||
urlpatterns = patterns('',
|
||||
# Examples:
|
||||
# url(r'^$', 'departments.views.home', name='home'),
|
||||
# url(r'^blog/', include('blog.urls')),
|
||||
|
||||
url(r'^admin/', include(admin.site.urls)),
|
||||
)
|
14
10-django-departments/departments/departments/wsgi.py
Normal file
14
10-django-departments/departments/departments/wsgi.py
Normal file
@ -0,0 +1,14 @@
|
||||
"""
|
||||
WSGI config for departments project.
|
||||
|
||||
It exposes the WSGI callable as a module-level variable named ``application``.
|
||||
|
||||
For more information on this file, see
|
||||
https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/
|
||||
"""
|
||||
|
||||
import os
|
||||
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "departments.settings")
|
||||
|
||||
from django.core.wsgi import get_wsgi_application
|
||||
application = get_wsgi_application()
|
10
10-django-departments/departments/manage.py
Normal file
10
10-django-departments/departments/manage.py
Normal file
@ -0,0 +1,10 @@
|
||||
#!/usr/bin/env python
|
||||
import os
|
||||
import sys
|
||||
|
||||
if __name__ == "__main__":
|
||||
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "departments.settings")
|
||||
|
||||
from django.core.management import execute_from_command_line
|
||||
|
||||
execute_from_command_line(sys.argv)
|
32
11-django-orm-clubs/README.md
Normal file
32
11-django-orm-clubs/README.md
Normal file
@ -0,0 +1,32 @@
|
||||
Club Maker
|
||||
==========
|
||||
|
||||
You've been commissioned to build software to manage student clubs on a college campus.
|
||||
|
||||
#### The Relationships
|
||||
|
||||
Design the schema in SQL designer, then in the Django ORM.
|
||||
|
||||
A student can have memberships to many clubs
|
||||
A club can have many students
|
||||
A student can have many interests
|
||||
A club can have many interests
|
||||
A student can have a title for each club they belong in
|
||||
|
||||
#### Making Queries
|
||||
|
||||
Create queries to show that your database has all of these relationships.
|
||||
|
||||
Show all the students that belong to a given club, along with their titles.
|
||||
|
||||
Show all of the students that have a given interest.
|
||||
|
||||
Given a student, find the clubs that match their interests.
|
||||
|
||||
If you are having trouble seeing the relationships while you're in shell, think about adding a `__str__` method to each of your tables, so that you get easier to read feedback.
|
||||
|
||||
Resources
|
||||
---------
|
||||
|
||||
[Django's ORM Docs](https://docs.djangoproject.com/en/dev/topics/db/models/)
|
||||
[Many to many example](https://docs.djangoproject.com/en/dev/topics/db/examples/many_to_many/)
|
0
11-django-orm-clubs/club/app/__init__.py
Normal file
0
11-django-orm-clubs/club/app/__init__.py
Normal file
3
11-django-orm-clubs/club/app/admin.py
Normal file
3
11-django-orm-clubs/club/app/admin.py
Normal file
@ -0,0 +1,3 @@
|
||||
from django.contrib import admin
|
||||
|
||||
# Register your models here.
|
0
11-django-orm-clubs/club/app/migrations/__init__.py
Normal file
0
11-django-orm-clubs/club/app/migrations/__init__.py
Normal file
3
11-django-orm-clubs/club/app/models.py
Normal file
3
11-django-orm-clubs/club/app/models.py
Normal file
@ -0,0 +1,3 @@
|
||||
from django.db import models
|
||||
|
||||
# Create your models here.
|
3
11-django-orm-clubs/club/app/tests.py
Normal file
3
11-django-orm-clubs/club/app/tests.py
Normal file
@ -0,0 +1,3 @@
|
||||
from django.test import TestCase
|
||||
|
||||
# Create your tests here.
|
3
11-django-orm-clubs/club/app/views.py
Normal file
3
11-django-orm-clubs/club/app/views.py
Normal file
@ -0,0 +1,3 @@
|
||||
from django.shortcuts import render
|
||||
|
||||
# Create your views here.
|
0
11-django-orm-clubs/club/club/__init__.py
Normal file
0
11-django-orm-clubs/club/club/__init__.py
Normal file
83
11-django-orm-clubs/club/club/settings.py
Normal file
83
11-django-orm-clubs/club/club/settings.py
Normal file
@ -0,0 +1,83 @@
|
||||
"""
|
||||
Django settings for club project.
|
||||
|
||||
For more information on this file, see
|
||||
https://docs.djangoproject.com/en/1.7/topics/settings/
|
||||
|
||||
For the full list of settings and their values, see
|
||||
https://docs.djangoproject.com/en/1.7/ref/settings/
|
||||
"""
|
||||
|
||||
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
|
||||
import os
|
||||
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
|
||||
|
||||
|
||||
# Quick-start development settings - unsuitable for production
|
||||
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
|
||||
|
||||
# SECURITY WARNING: keep the secret key used in production secret!
|
||||
SECRET_KEY = 'urob^c25u&5we3)80b$w9u9mne2o9^6@hj%#&aq#8%76d1duv*'
|
||||
|
||||
# SECURITY WARNING: don't run with debug turned on in production!
|
||||
DEBUG = True
|
||||
|
||||
TEMPLATE_DEBUG = True
|
||||
|
||||
ALLOWED_HOSTS = []
|
||||
|
||||
|
||||
# Application definition
|
||||
|
||||
INSTALLED_APPS = (
|
||||
'django.contrib.admin',
|
||||
'django.contrib.auth',
|
||||
'django.contrib.contenttypes',
|
||||
'django.contrib.sessions',
|
||||
'django.contrib.messages',
|
||||
'django.contrib.staticfiles',
|
||||
)
|
||||
|
||||
MIDDLEWARE_CLASSES = (
|
||||
'django.contrib.sessions.middleware.SessionMiddleware',
|
||||
'django.middleware.common.CommonMiddleware',
|
||||
'django.middleware.csrf.CsrfViewMiddleware',
|
||||
'django.contrib.auth.middleware.AuthenticationMiddleware',
|
||||
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
|
||||
'django.contrib.messages.middleware.MessageMiddleware',
|
||||
'django.middleware.clickjacking.XFrameOptionsMiddleware',
|
||||
)
|
||||
|
||||
ROOT_URLCONF = 'club.urls'
|
||||
|
||||
WSGI_APPLICATION = 'club.wsgi.application'
|
||||
|
||||
|
||||
# Database
|
||||
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
|
||||
|
||||
DATABASES = {
|
||||
'default': {
|
||||
'ENGINE': 'django.db.backends.sqlite3',
|
||||
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
|
||||
}
|
||||
}
|
||||
|
||||
# Internationalization
|
||||
# https://docs.djangoproject.com/en/1.7/topics/i18n/
|
||||
|
||||
LANGUAGE_CODE = 'en-us'
|
||||
|
||||
TIME_ZONE = 'UTC'
|
||||
|
||||
USE_I18N = True
|
||||
|
||||
USE_L10N = True
|
||||
|
||||
USE_TZ = True
|
||||
|
||||
|
||||
# Static files (CSS, JavaScript, Images)
|
||||
# https://docs.djangoproject.com/en/1.7/howto/static-files/
|
||||
|
||||
STATIC_URL = '/static/'
|
10
11-django-orm-clubs/club/club/urls.py
Normal file
10
11-django-orm-clubs/club/club/urls.py
Normal file
@ -0,0 +1,10 @@
|
||||
from django.conf.urls import patterns, include, url
|
||||
from django.contrib import admin
|
||||
|
||||
urlpatterns = patterns('',
|
||||
# Examples:
|
||||
# url(r'^$', 'club.views.home', name='home'),
|
||||
# url(r'^blog/', include('blog.urls')),
|
||||
|
||||
url(r'^admin/', include(admin.site.urls)),
|
||||
)
|
14
11-django-orm-clubs/club/club/wsgi.py
Normal file
14
11-django-orm-clubs/club/club/wsgi.py
Normal file
@ -0,0 +1,14 @@
|
||||
"""
|
||||
WSGI config for club project.
|
||||
|
||||
It exposes the WSGI callable as a module-level variable named ``application``.
|
||||
|
||||
For more information on this file, see
|
||||
https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/
|
||||
"""
|
||||
|
||||
import os
|
||||
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "club.settings")
|
||||
|
||||
from django.core.wsgi import get_wsgi_application
|
||||
application = get_wsgi_application()
|
10
11-django-orm-clubs/club/manage.py
Normal file
10
11-django-orm-clubs/club/manage.py
Normal file
@ -0,0 +1,10 @@
|
||||
#!/usr/bin/env python
|
||||
import os
|
||||
import sys
|
||||
|
||||
if __name__ == "__main__":
|
||||
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "club.settings")
|
||||
|
||||
from django.core.management import execute_from_command_line
|
||||
|
||||
execute_from_command_line(sys.argv)
|
48
12-threading/README.md
Normal file
48
12-threading/README.md
Normal file
@ -0,0 +1,48 @@
|
||||
Threading 101
|
||||
=============
|
||||
|
||||
We're going to give a short introduction to multithreading. Threads deal with the issue of concurrency. Threads usually emulate concurrency. Rather than actually having multiple processes running the same time completely independent of each other, the computer will switch between processes quickly enough where the processes will be 'concurrent enough'. With multiple processors, it is possible to have truly concurrent operations.
|
||||
|
||||
Understanding threading will be important to your futures as finance programmers. The issue of concurrency becomes very important when you have writes coming from many places into one--for example, your database. Different databases deal with concurrency differently, and understanding how your database handles these things is a good thing to know. We're going to be using PostgreSQL, which is known for being very good with at concurrency and write heavy apps.
|
||||
|
||||
To deal with concurrent reads/writes that you want to have happen sequentially, there are locks. It does what it sounds like. You can set a lock so that none of the other threads can access the data until it's their turn in line. For example, you can have a lock every time a thread is writing to your file, and release the lock once it is done. This way you don't end up having, basically, a merge conflict (kind of like what you see with git). This is, obviously, good for data integrity.
|
||||
|
||||
Another way to deal with this issue is to have multiple threads that once done with their operation, send it to a queue. The queue then does the operations in the order they came (the one thing queues do).
|
||||
[Read atleast the intro to threads here. Feel free to read through all of it](http://en.wikipedia.org/wiki/Thread_(computing)).
|
||||
|
||||
We will be doing some trivial things with threads, so you can see how they work.
|
||||
|
||||
We will be using Python's threading library, which is a higher level interface for using threads. It's a little easier to use than Python's thread library, and offers better functionality.
|
||||
|
||||
#### Step 1
|
||||
|
||||
[Keep this link open in your browser](https://docs.python.org/2/library/threading.html#lock-objects)
|
||||
|
||||
* import the threading library
|
||||
* make a class myThread (or whatever you want to call it) and have it inherit from ```threading.Thread```.
|
||||
* the threading library comes with a built in ```__init__```. We're going to overwrite it.
|
||||
* Inside your ```__init__```, add this line ```threading.Thread.__init__(self)```.
|
||||
* Give the thread some properties... Let's go with string, counter, and delay.
|
||||
* Threads also come with a run instance method. 'run' runs once you start the thread (```my_thread.start()```).
|
||||
* We're going to overwrite run and give it the print_string method provided. Pass in the properties from myThread into it.
|
||||
* Create two or more instances of myThread, and then call start on them.
|
||||
* Run the code and watch it.
|
||||
* Play with it a bit until you feel like you see what's going on.
|
||||
* Once you feel like you know what's going on, trace through the code once more and look at the [Python docs]((https://docs.python.org/2/library/threading.html#lock-objects)) again.
|
||||
|
||||
#### Step 2
|
||||
|
||||
We're going to add a lock to this.
|
||||
|
||||
* In the document's main thread (Every process is a thread, even if there is only one), define and instantiate a lock.
|
||||
* Inside your run method, call ```lock.acquire()``` and ```lock.release()``` around your print_string method.
|
||||
* Run the code. What happened?
|
||||
|
||||
As you can imagine, while doing a read/write, this can be helpful to make sure nothing else is also read/writing to a file or to the database. This is good for the integrity of your data.
|
||||
|
||||
#### Step 3
|
||||
|
||||
* Call join on one of your threads. What happens?
|
||||
* Call join on all of your threads. What happens?
|
||||
|
||||
If you're having trouble following along with what's happening, make sure to ask us questions. Also, make sure you're playing with your code. Every time you run your code, you're being given information. Use that to your advantage. Imagine you're a detective building a case.
|
12
12-threading/threads.py
Normal file
12
12-threading/threads.py
Normal file
@ -0,0 +1,12 @@
|
||||
import time
|
||||
|
||||
def print_string(string, counter, delay):
|
||||
count = 0
|
||||
while count < counter:
|
||||
time.sleep(delay)
|
||||
print(string+" "+str(count))
|
||||
count += 1
|
||||
print("exiting "+string+" thread")
|
||||
|
||||
|
||||
print("main thread done")
|
71
13-unix-ninja-3/README.md
Normal file
71
13-unix-ninja-3/README.md
Normal file
@ -0,0 +1,71 @@
|
||||
Unix Ninja 3
|
||||
============
|
||||
|
||||
Today we're going to take a look at a few more commands.
|
||||
|
||||
#### uniq
|
||||
|
||||
Type `$ man uniq` into your terminal and read the man page.
|
||||
|
||||
Type `$ uniq text.txt`. What do you get?
|
||||
|
||||
Can you get only one of each word?
|
||||
|
||||
How about the counts for each word?
|
||||
|
||||
Can you combine the two?
|
||||
|
||||
#### ps and top
|
||||
|
||||
Open a new tab in your terminal and type `$ ps`.
|
||||
|
||||
What is that? Let's man it.
|
||||
|
||||
While we're at it, let's type `$ man kill`.
|
||||
|
||||
Take the PID from one of your terminal processes and type `kill -9 [PID]`. Don't type PID, insert your PID where I typed it.
|
||||
|
||||
What does PID stand for?
|
||||
|
||||
What happened when you did that?
|
||||
|
||||
Remember this command. Sometimes when you're running a local server, it won't close it connection to a port. You can kill the process to open the port again.
|
||||
|
||||
Now try `$ top`. What's the difference between ps and top?
|
||||
|
||||
#### diff
|
||||
|
||||
Type `$ man diff` and read the man page.
|
||||
|
||||
Get the diff of text.txt and yo.txt. See how the syntax works. Change the files around, and see how it changes the diff. This may look similar to when you've had a merge conflict, or if you've ever used `git diff`.
|
||||
|
||||
#### chmod
|
||||
|
||||
Here is some reading on [chmod](http://www.perlfect.com/articles/chmod.shtml).
|
||||
|
||||
Read the man on chmod and [chown](http://www.computerhope.com/unix/uchown.htm), as well.
|
||||
|
||||
There won't be any exercises on these functions, but you should know them. How do file permissions work in Unix?
|
||||
|
||||
#### stdio
|
||||
|
||||
Read about [stdio](http://en.wikipedia.org/wiki/Standard_streams). This plays a big role in backend processes. It's a little hard to grasp, so I just want to introduce you to the concept.
|
||||
|
||||
#### du
|
||||
|
||||
$ man du
|
||||
$ du
|
||||
$ du text.txt
|
||||
$ du ../
|
||||
|
||||
This doesn't matter as much, anymore, since your computer has so much space. Back in the day you had to be much more frugal with disk space. Still, now you know how to know how much space a file or folder is taking.
|
||||
|
||||
#### cksum
|
||||
|
||||
Read about what a checksum is [here](http://en.wikipedia.org/wiki/Checksum)
|
||||
|
||||
The command cksum generates a checksum for any data or file.
|
||||
|
||||
Get the checksum of text.txt and compare it to the checksum of yo.txt.
|
||||
|
||||
Now duplicate text.txt using cat and compare the checksums again.
|
9
13-unix-ninja-3/text.txt
Normal file
9
13-unix-ninja-3/text.txt
Normal file
@ -0,0 +1,9 @@
|
||||
hi
|
||||
hi
|
||||
hi
|
||||
hi
|
||||
yo
|
||||
yo
|
||||
weee
|
||||
hi
|
||||
yo
|
9
13-unix-ninja-3/yo.txt
Normal file
9
13-unix-ninja-3/yo.txt
Normal file
@ -0,0 +1,9 @@
|
||||
hi
|
||||
hi
|
||||
hi
|
||||
|
||||
yo
|
||||
hi
|
||||
yo
|
||||
omgomgomgomg
|
||||
omg
|
23
14-scrape-coinmarketcap/README.md
Normal file
23
14-scrape-coinmarketcap/README.md
Normal file
@ -0,0 +1,23 @@
|
||||
Scraping the Web
|
||||
================
|
||||
|
||||
Have you ever wanted to use the information from a website? A lot of our favorite sites have public APIs - but many don't. The information is still out there though - we've just got to scrape for it.
|
||||
|
||||
[Coin Market Cap](http://www.coinmarketcap.com) is the gold standard for crypto-currency values. Unfortunately, they don't have an official API. Several people have built APIs for them using web scrapers - and they were showered in bitcoin, dogecoin, and pizza. Time to get in on the action!
|
||||
|
||||
Use pip3 to install requests and beautifulsoup4.
|
||||
|
||||
```
|
||||
pip3 install requests
|
||||
pip3 install beautifulsoup4
|
||||
```
|
||||
|
||||
#### Scrape Coin Market Cap
|
||||
|
||||
Use [this tutorial](http://blog.miguelgrinberg.com/post/easy-web-scraping-with-python) as a guide to scraping using requests and bs4. This is for a different site and case, but you should skim and read enough of the code snippets to get the idea. Your code should return the name of currency and it's current value as key-value pairs for all 100 coins on the market.
|
||||
|
||||
The complete list should be ordered as they are ordered on the market.
|
||||
|
||||
#### Save it to a CSV
|
||||
|
||||
Now export your list to a CSV file and save it in the directory. Push it up!
|
7
14-scrape-coinmarketcap/scraper.py
Normal file
7
14-scrape-coinmarketcap/scraper.py
Normal file
@ -0,0 +1,7 @@
|
||||
import requests
|
||||
import bs4
|
||||
import re
|
||||
|
||||
class ScrapeCoinMarket:
|
||||
def __init__(self):
|
||||
pass
|
38
15-reddit-scraper/README.md
Normal file
38
15-reddit-scraper/README.md
Normal file
@ -0,0 +1,38 @@
|
||||
Reddit Miner
|
||||
============
|
||||
|
||||
Now that you've completed mining coinmarketcap for data, you've seen that scraping data using HTML can be kind of messy. If they decide to change an id of a div or something, we're screwed. It's extremely useful, but not an exact science by any stretch.
|
||||
|
||||
Now we're going to move on to reddit. Reddit is a beast. It's huge and constantly changing. Thank doge that they will serve us json.
|
||||
|
||||
What does that mean? Well go to http://www.reddit.com/.json and take a look.
|
||||
|
||||
The front page is one massive json object. In fact, every page on reddit is.
|
||||
|
||||
Let's parse that beast.
|
||||
|
||||
#### Getting the JSON
|
||||
|
||||
Using requests, get that big json file and load it.
|
||||
|
||||
#### Our database
|
||||
|
||||
We're going to build an app that saves every front page post into the database when it is run. For each post, we'll want its title, author, url, subreddit it was posted in, number of upvotes, and the datetime it was posted on Reddit.
|
||||
|
||||
Create the necessary table using the django ORM.
|
||||
|
||||
#### Getting the correct data
|
||||
|
||||
That json return is a little scary. It's huge and complex. How can you search it in the terminal to figure out what fields you need?
|
||||
|
||||
Access the correct fields in the object and save them to your db. We don't want duplicate entries - ensure uniqueness in a way that makes sense.
|
||||
|
||||
If you run your program again and an entry already exists, update it so we get the most recent score.
|
||||
|
||||
#### Indexing
|
||||
|
||||
Whatever column you decide to use to ensure uniqueness, we'll want to add an [index](http://en.wikipedia.org/wiki/Database_index) to this field because we're going to be searching it alot. What is the big o when searching by index? What is it without one?
|
||||
|
||||
#### The final product
|
||||
|
||||
Create a function that just pulls a random row from your reddit frontpage database and prints it to the screen. Since you've got the crontab running, you should soon have a huge database of the top reddit posts and links. In 6 months, repost and reap those sweet sweet internet points. Oh yeah!
|
10
15-reddit-scraper/reddit_project/manage.py
Normal file
10
15-reddit-scraper/reddit_project/manage.py
Normal file
@ -0,0 +1,10 @@
|
||||
#!/usr/bin/env python
|
||||
import os
|
||||
import sys
|
||||
|
||||
if __name__ == "__main__":
|
||||
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "reddit_project.settings")
|
||||
|
||||
from django.core.management import execute_from_command_line
|
||||
|
||||
execute_from_command_line(sys.argv)
|
83
15-reddit-scraper/reddit_project/reddit_project/settings.py
Normal file
83
15-reddit-scraper/reddit_project/reddit_project/settings.py
Normal file
@ -0,0 +1,83 @@
|
||||
"""
|
||||
Django settings for reddit_project project.
|
||||
|
||||
For more information on this file, see
|
||||
https://docs.djangoproject.com/en/1.7/topics/settings/
|
||||
|
||||
For the full list of settings and their values, see
|
||||
https://docs.djangoproject.com/en/1.7/ref/settings/
|
||||
"""
|
||||
|
||||
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
|
||||
import os
|
||||
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
|
||||
|
||||
|
||||
# Quick-start development settings - unsuitable for production
|
||||
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
|
||||
|
||||
# SECURITY WARNING: keep the secret key used in production secret!
|
||||
SECRET_KEY = '-820u&ao04y97d)%!s@%k01*4+-f&!+i9$&k!6%ddt7osm72gk'
|
||||
|
||||
# SECURITY WARNING: don't run with debug turned on in production!
|
||||
DEBUG = True
|
||||
|
||||
TEMPLATE_DEBUG = True
|
||||
|
||||
ALLOWED_HOSTS = []
|
||||
|
||||
|
||||
# Application definition
|
||||
|
||||
INSTALLED_APPS = (
|
||||
'django.contrib.admin',
|
||||
'django.contrib.auth',
|
||||
'django.contrib.contenttypes',
|
||||
'django.contrib.sessions',
|
||||
'django.contrib.messages',
|
||||
'django.contrib.staticfiles',
|
||||
)
|
||||
|
||||
MIDDLEWARE_CLASSES = (
|
||||
'django.contrib.sessions.middleware.SessionMiddleware',
|
||||
'django.middleware.common.CommonMiddleware',
|
||||
'django.middleware.csrf.CsrfViewMiddleware',
|
||||
'django.contrib.auth.middleware.AuthenticationMiddleware',
|
||||
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
|
||||
'django.contrib.messages.middleware.MessageMiddleware',
|
||||
'django.middleware.clickjacking.XFrameOptionsMiddleware',
|
||||
)
|
||||
|
||||
ROOT_URLCONF = 'reddit_project.urls'
|
||||
|
||||
WSGI_APPLICATION = 'reddit_project.wsgi.application'
|
||||
|
||||
|
||||
# Database
|
||||
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
|
||||
|
||||
DATABASES = {
|
||||
'default': {
|
||||
'ENGINE': 'django.db.backends.sqlite3',
|
||||
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
|
||||
}
|
||||
}
|
||||
|
||||
# Internationalization
|
||||
# https://docs.djangoproject.com/en/1.7/topics/i18n/
|
||||
|
||||
LANGUAGE_CODE = 'en-us'
|
||||
|
||||
TIME_ZONE = 'UTC'
|
||||
|
||||
USE_I18N = True
|
||||
|
||||
USE_L10N = True
|
||||
|
||||
USE_TZ = True
|
||||
|
||||
|
||||
# Static files (CSS, JavaScript, Images)
|
||||
# https://docs.djangoproject.com/en/1.7/howto/static-files/
|
||||
|
||||
STATIC_URL = '/static/'
|
10
15-reddit-scraper/reddit_project/reddit_project/urls.py
Normal file
10
15-reddit-scraper/reddit_project/reddit_project/urls.py
Normal file
@ -0,0 +1,10 @@
|
||||
from django.conf.urls import patterns, include, url
|
||||
from django.contrib import admin
|
||||
|
||||
urlpatterns = patterns('',
|
||||
# Examples:
|
||||
# url(r'^$', 'reddit_project.views.home', name='home'),
|
||||
# url(r'^blog/', include('blog.urls')),
|
||||
|
||||
url(r'^admin/', include(admin.site.urls)),
|
||||
)
|
14
15-reddit-scraper/reddit_project/reddit_project/wsgi.py
Normal file
14
15-reddit-scraper/reddit_project/reddit_project/wsgi.py
Normal file
@ -0,0 +1,14 @@
|
||||
"""
|
||||
WSGI config for reddit_project project.
|
||||
|
||||
It exposes the WSGI callable as a module-level variable named ``application``.
|
||||
|
||||
For more information on this file, see
|
||||
https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/
|
||||
"""
|
||||
|
||||
import os
|
||||
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "reddit_project.settings")
|
||||
|
||||
from django.core.wsgi import get_wsgi_application
|
||||
application = get_wsgi_application()
|
3
15-reddit-scraper/reddit_project/scraper/admin.py
Normal file
3
15-reddit-scraper/reddit_project/scraper/admin.py
Normal file
@ -0,0 +1,3 @@
|
||||
from django.contrib import admin
|
||||
|
||||
# Register your models here.
|
3
15-reddit-scraper/reddit_project/scraper/models.py
Normal file
3
15-reddit-scraper/reddit_project/scraper/models.py
Normal file
@ -0,0 +1,3 @@
|
||||
from django.db import models
|
||||
|
||||
# Create your models here.
|
3
15-reddit-scraper/reddit_project/scraper/tests.py
Normal file
3
15-reddit-scraper/reddit_project/scraper/tests.py
Normal file
@ -0,0 +1,3 @@
|
||||
from django.test import TestCase
|
||||
|
||||
# Create your tests here.
|
3
15-reddit-scraper/reddit_project/scraper/views.py
Normal file
3
15-reddit-scraper/reddit_project/scraper/views.py
Normal file
@ -0,0 +1,3 @@
|
||||
from django.shortcuts import render
|
||||
|
||||
# Create your views here.
|
16
16-debugging/README.md
Normal file
16
16-debugging/README.md
Normal file
@ -0,0 +1,16 @@
|
||||
Debugging Challenge
|
||||
===================
|
||||
|
||||
So you and your buddies made a sweet MMORPG. You don't have any players yet, and you wanted to test the database, so you hired someone to write code to seed it.
|
||||
|
||||
It _should_ be all done - you'll just have to make the migrations, migrate the DB, and run the seed file successfully. But _should_ is a bad word in programming. Turns out, this guy had no idea how to do it and his code is a mess.
|
||||
|
||||
To run the seed, you should just have to instantiate the class once like so:
|
||||
```
|
||||
SeedDatabase(players = 50, heroes = 150, teams = 20)
|
||||
```
|
||||
It takes three keyword arguments - number of players to create, number of heroes to create, number of teams to create. In the database, Players have many Heroes. Heroes have many Teams and Teams have many Heroes.
|
||||
|
||||
#### Goal
|
||||
|
||||
Using the error statements and your knowledge of Python and Django, go through and debug the code. When you are done, go in the Django shell and test your relations. Read through the docs from Django on [Many to Many](https://docs.djangoproject.com/en/1.4/topics/db/examples/many_to_many/) and [One to Many](https://docs.djangoproject.com/en/1.4/topics/db/examples/many_to_one/) relationships if you haven't already.
|
83
16-debugging/debugging_project/debugging_project/settings.py
Normal file
83
16-debugging/debugging_project/debugging_project/settings.py
Normal file
@ -0,0 +1,83 @@
|
||||
"""
|
||||
Django settings for debugging_project project.
|
||||
|
||||
For more information on this file, see
|
||||
https://docs.djangoproject.com/en/1.7/topics/settings/
|
||||
|
||||
For the full list of settings and their values, see
|
||||
https://docs.djangoproject.com/en/1.7/ref/settings/
|
||||
"""
|
||||
|
||||
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
|
||||
import os
|
||||
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
|
||||
|
||||
|
||||
# Quick-start development settings - unsuitable for production
|
||||
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
|
||||
|
||||
# SECURITY WARNING: keep the secret key used in production secret!
|
||||
SECRET_KEY = 'gr6(3zd1pbpgs(99#6g^+)=h6w7yqp38dib9pli08)(1z_24+)'
|
||||
|
||||
# SECURITY WARNING: don't run with debug turned on in production!
|
||||
DEBUG = True
|
||||
|
||||
TEMPLATE_DEBUG = True
|
||||
|
||||
ALLOWED_HOSTS = []
|
||||
|
||||
|
||||
# Application definition
|
||||
|
||||
INSTALLED_APPS = (
|
||||
'django.contrib.admin',
|
||||
'django.contrib.auth',
|
||||
'django.contrib.contenttypes',
|
||||
'django.contrib.sessions',
|
||||
'django.contrib.messages',
|
||||
'django.contrib.staticfiles',
|
||||
)
|
||||
|
||||
MIDDLEWARE_CLASSES = (
|
||||
'django.contrib.sessions.middleware.SessionMiddleware',
|
||||
'django.middleware.common.CommonMiddleware',
|
||||
'django.middleware.csrf.CsrfViewMiddleware',
|
||||
'django.contrib.auth.middleware.AuthenticationMiddleware',
|
||||
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
|
||||
'django.contrib.messages.middleware.MessageMiddleware',
|
||||
'django.middleware.clickjacking.XFrameOptionsMiddleware',
|
||||
)
|
||||
|
||||
ROOT_URLCONF = 'debugging_project.urls'
|
||||
|
||||
WSGI_APPLICATION = 'debugging_project.wsgi.application'
|
||||
|
||||
|
||||
# Database
|
||||
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
|
||||
|
||||
DATABASES = {
|
||||
'default': {
|
||||
'ENGINE': 'django.db.backends.sqlite3',
|
||||
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
|
||||
}
|
||||
}
|
||||
|
||||
# Internationalization
|
||||
# https://docs.djangoproject.com/en/1.7/topics/i18n/
|
||||
|
||||
LANGUAGE_CODE = 'en-us'
|
||||
|
||||
TIME_ZONE = 'UTC'
|
||||
|
||||
USE_I18N = True
|
||||
|
||||
USE_L10N = True
|
||||
|
||||
USE_TZ = True
|
||||
|
||||
|
||||
# Static files (CSS, JavaScript, Images)
|
||||
# https://docs.djangoproject.com/en/1.7/howto/static-files/
|
||||
|
||||
STATIC_URL = '/static/'
|
10
16-debugging/debugging_project/debugging_project/urls.py
Normal file
10
16-debugging/debugging_project/debugging_project/urls.py
Normal file
@ -0,0 +1,10 @@
|
||||
from django.conf.urls import patterns, include, url
|
||||
from django.contrib import admin
|
||||
|
||||
urlpatterns = patterns('',
|
||||
# Examples:
|
||||
# url(r'^$', 'debugging_project.views.home', name='home'),
|
||||
# url(r'^blog/', include('blog.urls')),
|
||||
|
||||
url(r'^admin/', include(admin.site.urls)),
|
||||
)
|
14
16-debugging/debugging_project/debugging_project/wsgi.py
Normal file
14
16-debugging/debugging_project/debugging_project/wsgi.py
Normal file
@ -0,0 +1,14 @@
|
||||
"""
|
||||
WSGI config for debugging_project project.
|
||||
|
||||
It exposes the WSGI callable as a module-level variable named ``application``.
|
||||
|
||||
For more information on this file, see
|
||||
https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/
|
||||
"""
|
||||
|
||||
import os
|
||||
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "debugging_project.settings")
|
||||
|
||||
from django.core.wsgi import get_wsgi_application
|
||||
application = get_wsgi_application()
|
0
16-debugging/debugging_project/game/__init__.py
Normal file
0
16-debugging/debugging_project/game/__init__.py
Normal file
3
16-debugging/debugging_project/game/admin.py
Normal file
3
16-debugging/debugging_project/game/admin.py
Normal file
@ -0,0 +1,3 @@
|
||||
from django.contrib import admin
|
||||
|
||||
# Register your models here.
|
28
16-debugging/debugging_project/game/models.py
Normal file
28
16-debugging/debugging_project/game/models.py
Normal file
@ -0,0 +1,28 @@
|
||||
from django.core.exceptions import ValidationError
|
||||
|
||||
class Players(models.Model):
|
||||
username = models.CharField(max_length = 30)
|
||||
password = models.CharField(max_length = 30)
|
||||
email = models.CharField(max_length = 50)
|
||||
created_at = models.DateTimeField('date created')
|
||||
|
||||
def clean(self):
|
||||
if(len(self.password) < 8):
|
||||
raise ValidationError("password too short")
|
||||
email_validator = re.compile('^[A-Z0-9-.]+[a-z0-9-]+[a-zA-Z]{4,}$')
|
||||
if(email_validator.match(self.email) == None):
|
||||
raise ValidationError("invalid email")
|
||||
|
||||
def save(self, **kwargs):
|
||||
self.full_clean()
|
||||
return super(Players, self).save(**kwargs)
|
||||
|
||||
class Heroes(models.Model):
|
||||
player = ForeignKey(Players)
|
||||
name = models.CharField(max_length = 20)
|
||||
type = models.CharField()
|
||||
strength = models.IntegerField(default=10)
|
||||
|
||||
class Teams(models.Model):
|
||||
name = models.CharField()
|
||||
heroes = ManyToManyField(Hero)
|
56
16-debugging/debugging_project/game/seeds.py
Normal file
56
16-debugging/debugging_project/game/seeds.py
Normal file
@ -0,0 +1,56 @@
|
||||
import os
|
||||
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
|
||||
from faker import Factory
|
||||
import random
|
||||
from app.models import Players, Heroes
|
||||
|
||||
class SeedDatabase:
|
||||
def __init__(self, **kwargs):
|
||||
self.fake = Factory.create()
|
||||
self.player_num = kwargs[players]
|
||||
self.hero_num = kwargs[heroes]
|
||||
self.team_num = kwargs[teams]
|
||||
player_seed = Seed.seed_players()
|
||||
hero_seed = Seed.seed_heroes()
|
||||
team_seed = Seed.seed_teams()
|
||||
if(player_seed == True) and (hero_seed == True) and (team_seed == True):
|
||||
print("Success!")
|
||||
|
||||
def seed_players():
|
||||
for i in self.player_num:
|
||||
Players.create(username = ''.split(self.fake.name())[1],\
|
||||
password = random_password(),\
|
||||
email = self.fake.email(),\
|
||||
created_at = __random_datetime())
|
||||
return True
|
||||
|
||||
def seed_heroes():
|
||||
for i in self.hero_num:
|
||||
Heroes.create(name = self.fake.text().split()[3],\
|
||||
type = self.__random_hero(),\
|
||||
strength = random.randrange(6,55),\
|
||||
player = self.__random_player())
|
||||
return True
|
||||
|
||||
def seed_teams():
|
||||
for i in self.team_num:
|
||||
team = Teams.create(name = self.fake.company())
|
||||
for j in random.randrange(3,12):
|
||||
team.heroes.add(self.__random_hero())
|
||||
return True
|
||||
|
||||
def __random_password():
|
||||
return ''.join(random.sample(string.ascii_lowercase, random.randrange(4,14)))
|
||||
|
||||
def __random_datetime():
|
||||
return datetime.now() - datetime.timedelta(random.randrange(2,3123))
|
||||
|
||||
def __random_hero_type():
|
||||
types = ['Wizard', 'Warrior', 'Ranger', 'Druid', 'Shaman', 'Bard']
|
||||
return ''.join(random.sample(heroes, 1))
|
||||
|
||||
def __random_player():
|
||||
return Players.objects.filter(pk=random.randrange(1,self.player_num))
|
||||
|
||||
def __random_hero():
|
||||
return Heroes.objects.filter(pk=random.randrange(1,self.hero_num))
|
3
16-debugging/debugging_project/game/tests.py
Normal file
3
16-debugging/debugging_project/game/tests.py
Normal file
@ -0,0 +1,3 @@
|
||||
from django.test import TestCase
|
||||
|
||||
# Create your tests here.
|
3
16-debugging/debugging_project/game/views.py
Normal file
3
16-debugging/debugging_project/game/views.py
Normal file
@ -0,0 +1,3 @@
|
||||
from django.shortcuts import render
|
||||
|
||||
# Create your views here.
|
10
16-debugging/debugging_project/manage.py
Normal file
10
16-debugging/debugging_project/manage.py
Normal file
@ -0,0 +1,10 @@
|
||||
#!/usr/bin/env python
|
||||
import os
|
||||
import sys
|
||||
|
||||
if __name__ == "__main__":
|
||||
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "debugging_project.settings")
|
||||
|
||||
from django.core.management import execute_from_command_line
|
||||
|
||||
execute_from_command_line(sys.argv)
|
31
17-django-warehouse-orm/README.md
Normal file
31
17-django-warehouse-orm/README.md
Normal file
@ -0,0 +1,31 @@
|
||||
Warehouse Database
|
||||
==================
|
||||
|
||||
We're going to model a warehouse database. Imagine one of Amazon's warehouses, or any warehouse that will help you think about this problem.
|
||||
|
||||
Specifically, we're going to model their inventory and sales system.
|
||||
|
||||
Warehouses have a lot of things stored around the warehouse. When an order comes, they will know where things are in the warehouse by looking up where the item with that SKU is stored. Then they will put together an order and ship it to the customer.
|
||||
|
||||
Below is the start of a very simple schema. You're being given some necessary tables and some columns. Feel free to build this in whatever way you think will be the best inventory management system possible.
|
||||
|
||||
You can model this any way you like, but know this... You will be asked to justify every decision you make in your database.
|
||||
|
||||
If you can't give a good reason for why you did something, I will cry. Don't make me cry.
|
||||
|
||||
We will all be sharing what we come up with later today.
|
||||
|
||||
1. Parts
|
||||
* SKU
|
||||
* Description
|
||||
* Picture
|
||||
2. Stock (Inventory)
|
||||
* SKU
|
||||
* Quantity
|
||||
* Reorder quantity (low water mark)
|
||||
* Bin information
|
||||
3. Users
|
||||
* Name
|
||||
* email
|
||||
* password
|
||||
4. Orders
|
10
17-django-warehouse-orm/warehouseproject/manage.py
Normal file
10
17-django-warehouse-orm/warehouseproject/manage.py
Normal file
@ -0,0 +1,10 @@
|
||||
#!/usr/bin/env python
|
||||
import os
|
||||
import sys
|
||||
|
||||
if __name__ == "__main__":
|
||||
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "warehouseproject.settings")
|
||||
|
||||
from django.core.management import execute_from_command_line
|
||||
|
||||
execute_from_command_line(sys.argv)
|
@ -0,0 +1,3 @@
|
||||
from django.contrib import admin
|
||||
|
||||
# Register your models here.
|
@ -0,0 +1,3 @@
|
||||
from django.db import models
|
||||
|
||||
# Create your models here.
|
@ -0,0 +1,3 @@
|
||||
from django.test import TestCase
|
||||
|
||||
# Create your tests here.
|
@ -0,0 +1,3 @@
|
||||
from django.shortcuts import render
|
||||
|
||||
# Create your views here.
|
@ -0,0 +1,84 @@
|
||||
"""
|
||||
Django settings for warehouseproject project.
|
||||
|
||||
For more information on this file, see
|
||||
https://docs.djangoproject.com/en/1.7/topics/settings/
|
||||
|
||||
For the full list of settings and their values, see
|
||||
https://docs.djangoproject.com/en/1.7/ref/settings/
|
||||
"""
|
||||
|
||||
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
|
||||
import os
|
||||
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
|
||||
|
||||
|
||||
# Quick-start development settings - unsuitable for production
|
||||
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
|
||||
|
||||
# SECURITY WARNING: keep the secret key used in production secret!
|
||||
SECRET_KEY = 'jhp^fv=n9dxfq@8)g1ku@*m4oxa51@z74%fqr!pr3!@_$&dh^+'
|
||||
|
||||
# SECURITY WARNING: don't run with debug turned on in production!
|
||||
DEBUG = True
|
||||
|
||||
TEMPLATE_DEBUG = True
|
||||
|
||||
ALLOWED_HOSTS = []
|
||||
|
||||
|
||||
# Application definition
|
||||
|
||||
INSTALLED_APPS = (
|
||||
'django.contrib.admin',
|
||||
'django.contrib.auth',
|
||||
'django.contrib.contenttypes',
|
||||
'django.contrib.sessions',
|
||||
'django.contrib.messages',
|
||||
'django.contrib.staticfiles',
|
||||
'warehouse'
|
||||
)
|
||||
|
||||
MIDDLEWARE_CLASSES = (
|
||||
'django.contrib.sessions.middleware.SessionMiddleware',
|
||||
'django.middleware.common.CommonMiddleware',
|
||||
'django.middleware.csrf.CsrfViewMiddleware',
|
||||
'django.contrib.auth.middleware.AuthenticationMiddleware',
|
||||
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
|
||||
'django.contrib.messages.middleware.MessageMiddleware',
|
||||
'django.middleware.clickjacking.XFrameOptionsMiddleware',
|
||||
)
|
||||
|
||||
ROOT_URLCONF = 'warehouseproject.urls'
|
||||
|
||||
WSGI_APPLICATION = 'warehouseproject.wsgi.application'
|
||||
|
||||
|
||||
# Database
|
||||
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
|
||||
|
||||
DATABASES = {
|
||||
'default': {
|
||||
'ENGINE': 'django.db.backends.sqlite3',
|
||||
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
|
||||
}
|
||||
}
|
||||
|
||||
# Internationalization
|
||||
# https://docs.djangoproject.com/en/1.7/topics/i18n/
|
||||
|
||||
LANGUAGE_CODE = 'en-us'
|
||||
|
||||
TIME_ZONE = 'UTC'
|
||||
|
||||
USE_I18N = True
|
||||
|
||||
USE_L10N = True
|
||||
|
||||
USE_TZ = True
|
||||
|
||||
|
||||
# Static files (CSS, JavaScript, Images)
|
||||
# https://docs.djangoproject.com/en/1.7/howto/static-files/
|
||||
|
||||
STATIC_URL = '/static/'
|
@ -0,0 +1,10 @@
|
||||
from django.conf.urls import patterns, include, url
|
||||
from django.contrib import admin
|
||||
|
||||
urlpatterns = patterns('',
|
||||
# Examples:
|
||||
# url(r'^$', 'warehouseproject.views.home', name='home'),
|
||||
# url(r'^blog/', include('blog.urls')),
|
||||
|
||||
url(r'^admin/', include(admin.site.urls)),
|
||||
)
|
@ -0,0 +1,14 @@
|
||||
"""
|
||||
WSGI config for warehouseproject project.
|
||||
|
||||
It exposes the WSGI callable as a module-level variable named ``application``.
|
||||
|
||||
For more information on this file, see
|
||||
https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/
|
||||
"""
|
||||
|
||||
import os
|
||||
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "warehouseproject.settings")
|
||||
|
||||
from django.core.wsgi import get_wsgi_application
|
||||
application = get_wsgi_application()
|
66
2-baby-orm-querying/README.md
Normal file
66
2-baby-orm-querying/README.md
Normal file
@ -0,0 +1,66 @@
|
||||
Baby ORM - Querying
|
||||
===================
|
||||
|
||||
Are you ready for this? Today we're going to build the first half of our own ORM, or Object-relational mapper. Read more about ORM [here](http://en.wikipedia.org/wiki/Object-relational_mapping)
|
||||
|
||||
This is to prepare you for how you will be interacting with the DB in Django and many other web frameworks. This will also be your first foray in to meta-programming - as in code that writes code for you. In this case, our Python code will build and execute the SQL queries for us.
|
||||
|
||||
To put it simply, the ORM treats a table in our SQL database like a Python class, and each row in that table can be an instance of that class. While we have been building classes for our database to provide an easy to use interface, this takes it one step further and gives uniform database methods to every model class.
|
||||
|
||||
For example, to get all rows from the Users table:
|
||||
|
||||
In SQL:
|
||||
```sql
|
||||
SELECT * FROM Users;
|
||||
```
|
||||
In Baby ORM:
|
||||
```py
|
||||
Users.all()
|
||||
```
|
||||
To get all users named Greg:
|
||||
|
||||
In SQL:
|
||||
```sql
|
||||
SELECT * FROM Users WHERE name = 'Greg';
|
||||
```
|
||||
In Baby ORM:
|
||||
```py
|
||||
Users.filter(name="Greg")
|
||||
```
|
||||
Get the idea?
|
||||
|
||||
#### Round 1: Create your Model class that all other models will inherit from
|
||||
|
||||
We've already created the skeleton you will need in orm_class.py. Don't touch the methods yet - just initialize the Model class.
|
||||
|
||||
Remember we want any model class, with any attributes to be able to inherit from this class and read from the appropriate database table.
|
||||
|
||||
You will need to use \*\*kwargs, known as keyword arguments. This allows you to pass any number of arguments with values, such as `name='Greg'` and the class or function will treat it like a dictionary.
|
||||
|
||||
In conjunction with the kwargs, you will also need to use the setattr() function.
|
||||
|
||||
Google these for further explanation.
|
||||
|
||||
#### Round 2: Write your all() method
|
||||
|
||||
The all() class method should return all rows in the database for a table whose name matches the class. The rows should be instances of the class - not just sqlite's return value.
|
||||
|
||||
In a class method, the keyword "self" refers to the class.
|
||||
|
||||
You'll probably want to look up how to get the name of the class that self refers to. Remember that it could be anything the user decides, so long as it inherits from your Model class. You'll also need to get the column names from sqlite cursor.
|
||||
|
||||
Test this and all your methods against the included babyorm.db - there is data in the Users table and Stocks table. Check out the create_db.py file to see the schema.
|
||||
|
||||
#### Round 3: Write your get() method
|
||||
|
||||
Finally we start doing some heavy lifting. get() should take a simple equality condition as an argument and return just 1 row as an object from that table. Limit the return to 1 in SQL, not in your program.
|
||||
|
||||
#### Round 4: Write your filter() method
|
||||
|
||||
Like get(), filter should also take a simple equality condition as an argument. However it should return all rows from the table that match the condition as objects of the class.
|
||||
|
||||
#### Refactor
|
||||
|
||||
Assumably if you are reading this your code is working - how did you do on OO? Are your class methods big balls of mud? Were you able to reuse some of the code between `.all()`, `.filter()`, and `.get()`?
|
||||
|
||||
Refactor so every single step that the methods use is also a function. Name everything well so your code is easy to read.
|
BIN
2-baby-orm-querying/__pycache__/orm_class.cpython-34.pyc
Normal file
BIN
2-baby-orm-querying/__pycache__/orm_class.cpython-34.pyc
Normal file
Binary file not shown.
BIN
2-baby-orm-querying/babyorm.db
Normal file
BIN
2-baby-orm-querying/babyorm.db
Normal file
Binary file not shown.
20
2-baby-orm-querying/create_db.py
Normal file
20
2-baby-orm-querying/create_db.py
Normal file
@ -0,0 +1,20 @@
|
||||
import sqlite3
|
||||
|
||||
conn = sqlite3.connect('babyorm.db')
|
||||
c = conn.cursor()
|
||||
c.execute("""CREATE TABLE `Users` (
|
||||
`id` INTEGER,
|
||||
`name` VARCHAR,
|
||||
`address` VARCHAR,
|
||||
`balance` REAL,
|
||||
PRIMARY KEY (`id`)
|
||||
)""")
|
||||
|
||||
c.execute("""CREATE TABLE `Stocks` (
|
||||
`id` INTEGER,
|
||||
`symbol` VARCHAR,
|
||||
`price` REAL,
|
||||
PRIMARY KEY (`id`)
|
||||
)""")
|
||||
conn.commit()
|
||||
conn.close()
|
59
2-baby-orm-querying/orm_class.py
Normal file
59
2-baby-orm-querying/orm_class.py
Normal file
@ -0,0 +1,59 @@
|
||||
import sqlite3
|
||||
|
||||
conn = sqlite3.connect( 'babyorm.db' )
|
||||
conn.row_factory = sqlite3.Row
|
||||
c = conn.cursor()
|
||||
|
||||
class Model( dict ):
|
||||
def __init__( self, **kwargs ):
|
||||
for key, value in kwargs.items():
|
||||
self[key] = value
|
||||
|
||||
@staticmethod
|
||||
def __build_row( row ):
|
||||
return dict(zip(row.keys(), row))
|
||||
|
||||
@staticmethod
|
||||
def __parse_args( obj ):
|
||||
return " AND ".join("{} = '{}'".format(name, value) for name, value in obj.items())
|
||||
|
||||
@classmethod
|
||||
def all( cls ):
|
||||
c.execute( "SELECT * FROM {}".format(cls.__name__) )
|
||||
|
||||
return [ cls(**cls.__build_row( row )) for row in c ]
|
||||
|
||||
@classmethod
|
||||
def get( cls, **kwargs ):
|
||||
c.execute( "SELECT * FROM {} WHERE {} limit 1".format(
|
||||
cls.__name__,
|
||||
cls.__parse_args( kwargs )
|
||||
) )
|
||||
|
||||
return cls( **cls.__build_row( c.fetchone() ) )
|
||||
|
||||
@classmethod
|
||||
def filter( cls, **kwargs ):
|
||||
c.execute( "SELECT * FROM {} WHERE {} ".format(
|
||||
cls.__name__,
|
||||
cls.__parse_args( kwargs )
|
||||
) )
|
||||
|
||||
return [ cls(**cls.__build_row( row )) for row in c ]
|
||||
|
||||
###don't touch the code for these
|
||||
class Users(Model):
|
||||
pass
|
||||
|
||||
class Stocks(Model):
|
||||
pass
|
||||
|
||||
if __name__ == '__main__':
|
||||
from pprint import pprint
|
||||
|
||||
print( 'all' )
|
||||
pprint( Users.all() )
|
||||
print( 'get' )
|
||||
pprint( Users.get(name="Kenny") )
|
||||
print( 'filter' )
|
||||
pprint( Users.filter(name="Dr.") )
|
6
2-baby-orm-querying/test.py
Normal file
6
2-baby-orm-querying/test.py
Normal file
@ -0,0 +1,6 @@
|
||||
def myfun(**kwargs):
|
||||
print(kwargs['name'], kwargs['address'])
|
||||
|
||||
d = {'name':'matt', 'address':'23 23st', 'asdsa':342}
|
||||
|
||||
myfun(**d)
|
78
3-regular-expressions/README.md
Normal file
78
3-regular-expressions/README.md
Normal file
@ -0,0 +1,78 @@
|
||||
Regular Expressions
|
||||
===================
|
||||
|
||||
Sometimes you gotta regulate on your friends and family. As programmers, we gotta regulate on strings.
|
||||
|
||||
Regular expressions are patterns to match your strings. At first they look like somebody just jammed the keyboard with their forehead, but don't fret - they will soon make sense.
|
||||
|
||||
Use [rubular](http://rubular.com/) to test your regular expressions.
|
||||
```
|
||||
[A-Z]
|
||||
```
|
||||
This is a range of capital letters. Any one capital letter matches this pattern.
|
||||
```
|
||||
[A-Z]{3,}
|
||||
```
|
||||
This is same range of capital letters, with a condition that it is 3 characters or more.
|
||||
```
|
||||
[A-Za-z0-9]{6}
|
||||
```
|
||||
The first range lets us use any letter, capital or lowercase, and any number, in any order. There must be 6 characters to match.
|
||||
```
|
||||
^LOL\s[A-Za-z]*
|
||||
```
|
||||
Ok, now it looks weird. The ^ means that the string must start with the first expression, which is LOL. \s means whitespace. And it ends with a range of all letters. * means that that range of all letters can be any length. Here's what matches:
|
||||
```py
|
||||
'LOL Hi' # Matches
|
||||
'LOL whatsupdog' # Matches
|
||||
'LOLyo' # doesn't match, no whitespace
|
||||
'LOL hey d00d' # doesnt match, only letters allowed
|
||||
'whats up' # doesn't match, must start with LOL
|
||||
```
|
||||
You got it? Sandbox in rubular and read the quick reference guide. Write your answers in the answers.md file.
|
||||
|
||||
#### Round 1: Name
|
||||
|
||||
Make a regex pattern that matches a properly written name, like the following:
|
||||
|
||||
Miley Cyrus
|
||||
Justin Bieber
|
||||
Katy Perry
|
||||
|
||||
Notice the pattern - the first letter of the first name is capitalized, the rest is lower case. There is a space. The first letter of the last name is capitalized, the rest is lower case.
|
||||
|
||||
#### Round 2: Phone Number
|
||||
|
||||
Write a regex pattern that validates a correct phone number, like any of the following:
|
||||
|
||||
212-555-1023
|
||||
(917)888-2424
|
||||
5164329123
|
||||
|
||||
Area codes cannot start with 0 or 1. There may be parentheses around the area code. There must be a set of 3 numbers (area code) a set of 3 numbers(city) and set of 4 numbers. There may be dashes between them. There must be 10 numbers in total, no more no less.
|
||||
|
||||
#### Round 3: Email Address
|
||||
|
||||
Write a regex pattern that validates a correct email address, like the following:
|
||||
|
||||
sales@somestore.com
|
||||
roger.smith@yahoo.net
|
||||
hi@my-domain.info
|
||||
|
||||
#### Round 4: URL
|
||||
|
||||
Write a regex pattern to validate URLs, like the following:
|
||||
|
||||
http://www.google.com
|
||||
http://yahoo.net
|
||||
http://my-site.github.io
|
||||
|
||||
#### Round 5: grep with regex
|
||||
|
||||
Now use regex with grep to search files on your computer!
|
||||
|
||||
Search for all files that end in .py
|
||||
Search for all files that end in .jpg
|
||||
Search for all files that contain your name
|
||||
|
||||
Have fun and sandbox.
|
9
3-regular-expressions/answers.md
Normal file
9
3-regular-expressions/answers.md
Normal file
@ -0,0 +1,9 @@
|
||||
<!-- Your answers here -->
|
||||
|
||||
1.
|
||||
|
||||
2.
|
||||
|
||||
3.
|
||||
|
||||
4.
|
46
4-unix-ninja/README.md
Normal file
46
4-unix-ninja/README.md
Normal file
@ -0,0 +1,46 @@
|
||||
Unix Ninja Part 1
|
||||
=================
|
||||
|
||||
Are you ready to become a Unix ninja?
|
||||
|
||||
Today you're going to start on the path to mastering your Terminal. If you want to be a master young grasshopper, you must not be afraid of the sandbox.
|
||||
|
||||
#### cat
|
||||
|
||||
The first command you need to know is [cat](http://en.wikipedia.org/wiki/Cat_(Unix)). cat will output a file, or "catenate" multiple files.
|
||||
|
||||
Try to cat both csv files in the directory, seperately and together.
|
||||
|
||||
You can even save join them and save them combined to a new file. Do it!
|
||||
|
||||
#### grep
|
||||
|
||||
The next command we need is [grep](http://en.wikipedia.org/wiki/Grep).
|
||||
|
||||
Grep searches any file or output for a [regular expression](http://en.wikipedia.org/wiki/Regular_expression) you provide.
|
||||
|
||||
grep each csv file just for occurences of the string 'tie'.
|
||||
|
||||
Now output both files using cat and grep them both for the string 'tie'. You'll need to use a [pipe](http://en.wikipedia.org/wiki/Pipeline_(Unix)) to pass the output of cat to grep.
|
||||
|
||||
Sandbox! grep more stuff and get results from both files.
|
||||
|
||||
Now pipe commands you use all the time to grep - like ls, git status and anything else you can think of.
|
||||
|
||||
#### sort
|
||||
|
||||
Add [sort](http://en.wikipedia.org/wiki/Sort_(Unix)) into the mix. Sort each file, and sort them combined with cat.
|
||||
|
||||
Join them with cat, pipe to grep and look for all lines that contain the string "zo" and pipe them to sort to sort them.
|
||||
|
||||
#### wc
|
||||
|
||||
[wc](http://en.wikipedia.org/wiki/Wc_(Unix)) is word count. It will give you the number of words, lines, and characters from an output. What is the total number of full names in the name file? What is the total number of words for occurences of the string 'tie' in both files? Pipe them all together!
|
||||
|
||||
How about some more? How many words are in the man page for grep? How many lines contain the word "repo" in git --help?
|
||||
|
||||
#### Bonus - curl
|
||||
|
||||
curl will output a web data in your terminal. curl http://www.seamless.com and grep for all occurrences of the word "sandwich". How about we get all the links on the page? grep for occurrences of "href". How many lines are returned?
|
||||
|
||||
curl [reddit](http://www.reddit.com/) and save the page to an html file.
|
2501
4-unix-ninja/emails.csv
Normal file
2501
4-unix-ninja/emails.csv
Normal file
File diff suppressed because it is too large
Load Diff
6001
4-unix-ninja/names.csv
Normal file
6001
4-unix-ninja/names.csv
Normal file
File diff suppressed because it is too large
Load Diff
51
5-monty-hall-problem/README.md
Normal file
51
5-monty-hall-problem/README.md
Normal file
@ -0,0 +1,51 @@
|
||||
## The Monty Hall Problem
|
||||
|
||||
Loosely based on the 1960s game show "Let's Make a Deal", the Monty Hall problem is a paradox in probability.
|
||||
|
||||
A player is presented with three doors from which to choose. Behind one of the doors is a brand new car. Behind the other two are goats. The winning door is completely random.
|
||||
|
||||
Obviously the player wants to win the new car, and must pick a door to open, hoping to reveal it.
|
||||
|
||||
Before it is revealed however, the host will open one of the doors for the player to reveal one of the goats. The player can choose to stick with their original choice, or change their choice and pick the one other possible door.
|
||||
|
||||
## First Iteration
|
||||
|
||||
Using the Model-View-Controller pattern, let's first build out a terminal application for users to play the game.
|
||||
|
||||
#### The View
|
||||
|
||||
Let's keep all messages and user prompts inside the views file. If you would like to create a class to hold the views, or just use the file as a module is up to you.
|
||||
|
||||
Just don't hold any state in the views. Every variable, likely just user choices, should be passed back to the controller.
|
||||
|
||||
#### The Models
|
||||
|
||||
We'll be using the models for two things:
|
||||
|
||||
1. To handle any "business logic" the program needs. An example would be generating what's behind each door.
|
||||
|
||||
2. To commit to the database. Let's save user names, whether they chose to switch their choice or not when prompted, and whether they won the car.
|
||||
|
||||
A model in general should not communicate with other models, and should definitely not communicate directly with views. All communication should be handled through the controller.
|
||||
|
||||
#### The Controller
|
||||
|
||||
No spaghetti code! All user choices should be passed from the views back to the controller. Any business logic should be passed from the models to the controller. Any data that needs persistence should be sent from the controller to the model that writes to the db.
|
||||
|
||||
Before you move on, make sure you can play your game without error, that it tells you whether you won or not, and that it commits the correct data to the db.
|
||||
|
||||
## Second Iteration
|
||||
|
||||
Now for the fun part.
|
||||
|
||||
Copy your code into a different folder because we're going to hack it up. You shouldn't even need your views anymore.
|
||||
|
||||
Change your code so that it runs automated - the computer is the one choosing the door, and choosing whether or not to change their choice after the host's reveal. This should all be at random to ensure an equitable range of choices.
|
||||
|
||||
You should write the same data to the db as previously.
|
||||
|
||||
Run your program 100,000 times.
|
||||
|
||||
Write another program to query the database and return to you the percentage of times the choice was changed after the reveal and the car was won, and the percentage of times the choice was not changed after the reveal and the car was won.
|
||||
|
||||
Write your findings in this file. Read through the [wikipedia](http://en.wikipedia.org/wiki/Monty_Hall_problem)
|
6
5-monty-hall-problem/controller.py
Normal file
6
5-monty-hall-problem/controller.py
Normal file
@ -0,0 +1,6 @@
|
||||
#from models import
|
||||
from views import View
|
||||
|
||||
class Controller:
|
||||
def __init__(self):
|
||||
pass
|
0
5-monty-hall-problem/models.py
Normal file
0
5-monty-hall-problem/models.py
Normal file
3
5-monty-hall-problem/views.py
Normal file
3
5-monty-hall-problem/views.py
Normal file
@ -0,0 +1,3 @@
|
||||
class View:
|
||||
def __init__(self):
|
||||
pass
|
44
6-baby-orm-save/README.md
Normal file
44
6-baby-orm-save/README.md
Normal file
@ -0,0 +1,44 @@
|
||||
ORM Save
|
||||
========
|
||||
|
||||
You're going to write the save function for your Baby ORM. After this, your Baby ORM is complete and usable!
|
||||
|
||||
#### Pseudocode
|
||||
|
||||
Before we write any real code, we're going to write pseudocode. Read through the rest of this README, and pseudocode the two methods. Please include it in comments in your file.
|
||||
|
||||
#### The Save Method
|
||||
|
||||
You want to be able to take any number or arguments from whatever table is supplied, and either create the row, if it doesn't exist, or update the row, if it does exist. The save method should not take parameters, and is an instance method.
|
||||
```py
|
||||
user = Users(name="Cassie") # new instance
|
||||
user.save() # creates new row in table, stores id, returns True on success
|
||||
|
||||
cassie = Users.get(name="Cassie") # existing row instance
|
||||
cassie.hair = "purple"
|
||||
cassie.save() # updates row, returns True
|
||||
```
|
||||
|
||||
#### The Create Method
|
||||
|
||||
The create function is a class method, that creates a new row and returns the instance.
|
||||
```py
|
||||
user = Users.create(name="Greg") # returns newly created instance of User class
|
||||
```
|
||||
Think about the simplest way you can accomplish this.
|
||||
|
||||
|
||||
Recommendations
|
||||
---------------
|
||||
|
||||
If you haven't already become familiar, google the following:
|
||||
```py
|
||||
setattr()
|
||||
hasattr()
|
||||
__name__
|
||||
type(self)
|
||||
__dict__
|
||||
**kwargs
|
||||
```
|
||||
Map this out before starting. Plan for what you need to solve this.
|
||||
Go back to your game plan to make sure you're on track. Was your pseudocode accurate? If not, adjust it.
|
BIN
6-baby-orm-save/__pycache__/save.cpython-34.pyc
Normal file
BIN
6-baby-orm-save/__pycache__/save.cpython-34.pyc
Normal file
Binary file not shown.
BIN
6-baby-orm-save/babyorm.db
Normal file
BIN
6-baby-orm-save/babyorm.db
Normal file
Binary file not shown.
15
6-baby-orm-save/create_db.py
Normal file
15
6-baby-orm-save/create_db.py
Normal file
@ -0,0 +1,15 @@
|
||||
import sqlite3
|
||||
|
||||
conn = sqlite3.connect('babyorm.db')
|
||||
c = conn.cursor()
|
||||
c.execute("DROP TABLE IF EXISTS Users")
|
||||
c.execute("""CREATE TABLE Users(
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name VARCHAR,
|
||||
username VARCHAR,
|
||||
email VARCHAR,
|
||||
created_at DATE,
|
||||
updated_at DATE
|
||||
)""")
|
||||
conn.commit()
|
||||
conn.close()
|
121
6-baby-orm-save/save.py
Normal file
121
6-baby-orm-save/save.py
Normal file
@ -0,0 +1,121 @@
|
||||
from pprint import pprint
|
||||
import sqlite3
|
||||
|
||||
conn = sqlite3.connect( 'babyorm.db' )
|
||||
c = conn.cursor()
|
||||
|
||||
class Model( dict ):
|
||||
def __init__(self, **kwargs):
|
||||
# c.execute('pragma table_info("{}")'.format(self.__class__.__name__))
|
||||
self.columns = self.__columns()
|
||||
|
||||
for key, value in kwargs.items():
|
||||
setattr(self, key, value)
|
||||
|
||||
def __setitem__(self, key, value):
|
||||
if key in self.columns:
|
||||
return super().__setitem__(key, value)
|
||||
else:
|
||||
return False
|
||||
|
||||
def __setattr__(self, key, value):
|
||||
self.__setitem__(key, value)
|
||||
|
||||
return super().__setattr__(key, value)
|
||||
|
||||
@staticmethod
|
||||
def __parse_args(obj, on_join=" AND "): # needs better name
|
||||
return on_join.join("{} = '{}'".format(name, value) for name, value in obj.items())
|
||||
|
||||
@classmethod
|
||||
def __row_to_dict(cls, row):
|
||||
return {column:row[index] for index, column in enumerate( cls.__columns() )}
|
||||
|
||||
@classmethod
|
||||
def __columns(cls, force_update=False):
|
||||
if force_update or hasattr(cls, 'column'):
|
||||
return cls.column
|
||||
|
||||
c.execute('pragma table_info("{}")'.format(cls.__name__))
|
||||
cls.columns = tuple(d[1] for d in c)
|
||||
|
||||
return cls.columns
|
||||
|
||||
@classmethod
|
||||
def all(cls):
|
||||
c.execute( "SELECT * FROM {}".format(cls.__name__) )
|
||||
|
||||
return [cls(**cls.__row_to_dict(row)) for row in c.fetchall()]
|
||||
|
||||
@classmethod
|
||||
def get(cls, *args, **kwargs):
|
||||
kwargs_ = {'id': args[0]} if args else kwargs
|
||||
c.execute("SELECT * FROM {} WHERE {} limit 1".format(
|
||||
cls.__name__,
|
||||
cls.__parse_args(kwargs_)
|
||||
))
|
||||
|
||||
return cls(**cls.__row_to_dict(c.fetchone()))
|
||||
|
||||
@classmethod
|
||||
def filter(cls, **kwargs):
|
||||
|
||||
c.execute("SELECT * FROM {} WHERE {} ".format(
|
||||
cls.__name__,
|
||||
cls.__parse_args(kwargs)
|
||||
))
|
||||
|
||||
return [cls(**cls.__row_to_dict(row)) for row in c.fetchall()]
|
||||
|
||||
def save( self ):
|
||||
if 'id' in self:
|
||||
self.update()
|
||||
else:
|
||||
self.create()
|
||||
|
||||
def create( self ):
|
||||
keys = ','.join( [key for key in self.keys()] )
|
||||
values = ','.join( ["'{}'".format(value) for value in self.values()] )
|
||||
|
||||
sql_string = "INSERT INTO {} ({}) VALUES ({})".format(
|
||||
self.__class__.__name__,
|
||||
keys,
|
||||
values
|
||||
)
|
||||
print(sql_string)
|
||||
c.execute(sql_string)
|
||||
|
||||
setattr(self, 'id', c.lastrowid)
|
||||
conn.commit()
|
||||
return self
|
||||
|
||||
def update( self ):
|
||||
c.execute("UPDATE {} SET {} WHERE id={}".format(
|
||||
self.__class__.__name__,
|
||||
self.__parse_args(self, ', '),
|
||||
self['id']
|
||||
) )
|
||||
|
||||
conn.commit()
|
||||
|
||||
###don't touch the code for these
|
||||
class Users(Model):
|
||||
pass
|
||||
|
||||
class Stocks(Model):
|
||||
pass
|
||||
|
||||
if __name__ == '__main__':
|
||||
pass
|
||||
# dan = Users(name='dan')
|
||||
# dan.save()
|
||||
# dan.email = "dan@gmail.com"
|
||||
# dan.save()
|
||||
# pprint(dan)
|
||||
|
||||
# print( 'all' )
|
||||
# pprint( Users.all() )
|
||||
# print( 'get' )
|
||||
# pprint( Users.get(name="Kenny") )
|
||||
# print( 'filter' )
|
||||
# pprint( Users.filter(id=dan['id']) )
|
35
7-todos-baby-orm/README.md
Normal file
35
7-todos-baby-orm/README.md
Normal file
@ -0,0 +1,35 @@
|
||||
Todos App with Baby ORM
|
||||
=======================
|
||||
|
||||
Now we'll put your fully fledged ORM to good use. Create a terminal app that creates a todo list using ARGV, and saves the lists using your baby ORM.
|
||||
|
||||
For example:
|
||||
```
|
||||
python3 todolist.py add do laundry
|
||||
python3 todolist.py add buy groceries
|
||||
python3 todolist.py list
|
||||
python3 todolist.py complete <task id>
|
||||
python3 todolist.py delete <task id>
|
||||
```
|
||||
#### Design and create your database
|
||||
|
||||
Design the schema you'll need and create the DB. Of course, import and integrate the baby ORM.
|
||||
|
||||
#### Outline your models and methods
|
||||
|
||||
Look at example above - we have the commands add, complete, delete, and list. These aren't just for the user - these are actual backend functionality in your code. Create a skeleton of methods for any db classes you might need.
|
||||
|
||||
#### Implement functionality
|
||||
|
||||
add() should append an item to the list.
|
||||
|
||||
list() should display the list of tasks and their id. If it is completed, it should be noted as such.
|
||||
```
|
||||
python3 todolist.py list
|
||||
$ My Todo List
|
||||
$ 1. do laundry
|
||||
$ 2. buy groceries
|
||||
```
|
||||
delete() should take the id of the task and remove it from the database.
|
||||
|
||||
complete() should take the id of the task and mark it complete.
|
26
8-unix-ninja-2/README.md
Normal file
26
8-unix-ninja-2/README.md
Normal file
@ -0,0 +1,26 @@
|
||||
Unix Ninja 2
|
||||
============
|
||||
|
||||
ARE YOU READY FOR SOME MORE UNIX FUN?!!?!?!!?!!!!!!!!!!!!!??????
|
||||
|
||||
type these command into terminal
|
||||
|
||||
```bash
|
||||
$ a=yo
|
||||
$ b="armen and greg are the greatest, one"
|
||||
$ echo $a
|
||||
$ echo $b
|
||||
```
|
||||
|
||||
Isn't that neat? We can store variables in our shell. That seems like it would be useful for if we wanted to write shell scripts...
|
||||
Anyways. write the variable b that you just saved to a .txt file. If you don't know how to do that, I recommend referring to yesterday's work. After you finish writing it to a txt file, take the contents of the text file you created, and tweet it.
|
||||
|
||||
We're going to have some fun with the text file attached.
|
||||
Python is a scripting language. So we can write scripts in it to do a lot of work for us. Write a script that creates 5 files and writes each consecutive line to it's respective file.
|
||||
|
||||
Make a sixth file. Have it write all of the lines with the word 'sculpture', and how many times the word appears. You can just make the files .txt, feel free to name them whatever you want.
|
||||
You should not be naming these manually. Your script should do all of it.
|
||||
|
||||
If I gave you a 100 line text file, it would make 100 folders with .txt files in them, and one file with all of the lines that contain the word 'sculpture', and the word count as the last night.
|
||||
|
||||
You will find the [subprocess](https://docs.python.org/3/library/subprocess.html) module helpful for this assignment. What does the shell parameter do?
|
0
8-unix-ninja-2/ninja.py
Normal file
0
8-unix-ninja-2/ninja.py
Normal file
5
8-unix-ninja-2/text.txt
Normal file
5
8-unix-ninja-2/text.txt
Normal file
@ -0,0 +1,5 @@
|
||||
OMG look at this sculpture.
|
||||
I code all day;
|
||||
I code all night.
|
||||
My code is like a sculpture.
|
||||
Check my ninja sculpture...
|
100
9-simple-migrations/README.md
Normal file
100
9-simple-migrations/README.md
Normal file
@ -0,0 +1,100 @@
|
||||
Django ORM Simple Migrations
|
||||
============================
|
||||
|
||||
If you haven't already, let install the latest version of Django:
|
||||
```
|
||||
pip3 install django
|
||||
```
|
||||
Luckily, you've created your own baby ORM otherwise we wouldn't have one to use! JK, Django has a it's own built in ORM and we're going to be using it from here on out. To begin, let's create a model that will not only mimic the table in our database, but which will also create the schema for our table in the database.
|
||||
|
||||
Don't worry about what every file in this skeleton does just yet. The files we are concerned with now are:
|
||||
```
|
||||
manage.py
|
||||
app/models.py
|
||||
```
|
||||
We'll be desiging our schema in app/models.py. You should read and follow along with this [tutorial](https://docs.djangoproject.com/en/dev/topics/db/models/)
|
||||
|
||||
Just as our Users class from yesterday inherited from Model, our classes will similarly inherit from models.Model. As an example, if we were going to create a simple person table, it might look like this:
|
||||
|
||||
```py
|
||||
class Person(models.Model):
|
||||
first_name = models.CharField(max_length=30)
|
||||
last_name = models.CharField(max_length=30)
|
||||
birthday = models.DateField()
|
||||
```
|
||||
first_name, last_name and birthday are columns in the persons table.
|
||||
|
||||
Once you have defined your models, you need to tell Django you’re going to use those models. Do this by editing your setting.py file and changing the INSTALLED_APPS setting to add the name of the module that contains your models.py
|
||||
|
||||
```
|
||||
python3 manage.py makemigrations app
|
||||
python3 manage.py migrate
|
||||
```
|
||||
|
||||
#### The Employee Model
|
||||
|
||||
Create an employees model with the following fields:
|
||||
|
||||
```py
|
||||
first_name
|
||||
last_name
|
||||
email
|
||||
job_title
|
||||
salary
|
||||
birthday
|
||||
hired_date
|
||||
```
|
||||
|
||||
Once you've done that, let's test by entering the interactive shell:
|
||||
|
||||
```py
|
||||
$ python3 manage.py shell
|
||||
>>> from app.models import Employee
|
||||
```
|
||||
Run a few queries such as Employees.objects.all() and see what it returns!
|
||||
|
||||
#### Extend employees
|
||||
|
||||
Let's now extend our employee model and add our very own instance methods that return the following information:
|
||||
|
||||
* How many years old they are
|
||||
* How many years and days they have worked at the company
|
||||
* Their full name (i.e. first name + last name)
|
||||
|
||||
#### Validate your fields
|
||||
|
||||
Validations are crucial to ensuring the data we are entering into our datbase are acceptable as descriptions of data and/or business logic. Read up on validators [here](https://docs.djangoproject.com/en/dev/ref/models/instances/#validating-objects) and [here](http://stackoverflow.com/questions/12945339/is-this-the-way-to-validate-django-model-fields)
|
||||
|
||||
After a week of entering data in our DB. Rak finds out that you didn't have any validations on your employee model, and now a 4 year old got hired! And she's making half a million a year! How could you let this happen?
|
||||
|
||||
Validate that the employees are at least 18 years of age. Also we've got a hiring freeze on senior level personnel - make sure no new employees can be entered with a salary greater than 200k.
|
||||
|
||||
Overwrite the clean method for your class so that it raises a ValidationError if any of the constraints are not met.
|
||||
|
||||
Then overwrite the save function for the model like so:
|
||||
```py
|
||||
def save(self, *args, **kwargs):
|
||||
self.full_clean()
|
||||
super(Players, self).save(*args, **kwargs)
|
||||
```
|
||||
There's a slightly different way to do this when we get into the complete Django suite - so you can't trust everything you read online if you google past the two articles above. However, all validations use the clean method, and overwriting it as well as save() seems to be a common practice.
|
||||
|
||||
Read about how clean and full_clean work. What does super do? Do not move on until you understand what is happening and have a general idea what the above stack overflow link is going on about.
|
||||
|
||||
#### Regex Validator
|
||||
|
||||
Now using the regex re library (`import re`) add a validator condition to your clean method to ensure a valid email address.
|
||||
|
||||
Note - there is a built in RegexValidator class in Django. Don't use it, it's specifically for forms. Use Python's built in library 're' to match regular expressions.
|
||||
|
||||
#### Bonus - seed your DB!
|
||||
|
||||
When you are in a small development team, then everyone has to enter in some data. Rather than do this independently, it is better to write a script so that everyone has similar data, and so that everyone has useful and appropriate data, rather than junk test data. To do this, you will need to navigate to the seeds.py file in your project's root directory and add to the `add_employee` function.
|
||||
|
||||
Hint:
|
||||
|
||||
Let's make use of the `convenience get_or_create()`method for creating model instances. As we don’t want to create duplicates of the same entry, we can use `get_or_create()` to check if the entry exists in the database for us. If it doesn’t exist, the method creates it. This can remove a lot of repetitive code for us - rather than doing this laborious check ourselves, we can make use of code that does exactly this for us. As we mentioned previously, why reinvent the wheel if it’s already there?
|
||||
|
||||
|
||||
|
||||
When you're finished, have some fun querying your DB. Practice the [Django ORM queries](https://docs.djangoproject.com/en/dev/topics/db/queries/), like objects.all, objects.filter, and objects.get.
|
BIN
9-simple-migrations/simple_migrations/app/__init__.pyc
Normal file
BIN
9-simple-migrations/simple_migrations/app/__init__.pyc
Normal file
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user