From 361d76f92e94689ea74c225d95b9b44662a0731b Mon Sep 17 00:00:00 2001 From: Enoch Carter Date: Mon, 17 Jun 2013 23:42:42 -0700 Subject: [PATCH] completed assignments --- django_test/README.md | 0 .../django_test/applications/__init__.py | 0 .../applications/userprofile/__init__.py | 0 .../applications/userprofile/forms.py | 54 +++++++++ .../applications/userprofile/models.py | 58 +++++++++ django_test/django_test/settings.py | 30 +++-- django_test/django_test/templates/base.html | 14 +++ django_test/django_test/templates/home.html | 10 ++ django_test/django_test/templates/login.html | 31 +++++ .../django_test/templates/register.html | 8 ++ django_test/django_test/templates/todo.html | 113 ++++++++++++++++++ django_test/django_test/urls.py | 17 ++- django_test/django_test/utils/__init__.py | 0 django_test/django_test/utils/tools.py | 29 +++++ django_test/django_test/views.py | 93 ++++++++++++++ django_test/django_test/wsgi.py | 0 django_test/manage.py | 2 +- palinodrome_product.py | 10 ++ prime.py | 30 +++++ series_product.py | 17 +++ 20 files changed, 499 insertions(+), 17 deletions(-) mode change 100644 => 100755 django_test/README.md create mode 100644 django_test/django_test/applications/__init__.py create mode 100644 django_test/django_test/applications/userprofile/__init__.py create mode 100644 django_test/django_test/applications/userprofile/forms.py create mode 100644 django_test/django_test/applications/userprofile/models.py mode change 100644 => 100755 django_test/django_test/settings.py create mode 100644 django_test/django_test/templates/base.html create mode 100644 django_test/django_test/templates/home.html create mode 100644 django_test/django_test/templates/login.html create mode 100644 django_test/django_test/templates/register.html create mode 100644 django_test/django_test/templates/todo.html mode change 100644 => 100755 django_test/django_test/urls.py create mode 100644 django_test/django_test/utils/__init__.py create mode 100644 django_test/django_test/utils/tools.py create mode 100644 django_test/django_test/views.py mode change 100644 => 100755 django_test/django_test/wsgi.py mode change 100644 => 100755 django_test/manage.py diff --git a/django_test/README.md b/django_test/README.md old mode 100644 new mode 100755 diff --git a/django_test/django_test/applications/__init__.py b/django_test/django_test/applications/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/django_test/django_test/applications/userprofile/__init__.py b/django_test/django_test/applications/userprofile/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/django_test/django_test/applications/userprofile/forms.py b/django_test/django_test/applications/userprofile/forms.py new file mode 100644 index 0000000..2aaabe0 --- /dev/null +++ b/django_test/django_test/applications/userprofile/forms.py @@ -0,0 +1,54 @@ +from django import forms +from django.contrib.auth.models import User +from django.contrib.localflavor.us.forms import USPhoneNumberField +from django.contrib.auth import authenticate + +from models import Userprofile + +from utils.tools import USPhoneNumberMultiWidget + +class Userform(forms.ModelForm): + + + class Meta: + model = Userprofile + exclude = ('user',) + + def __init__(self, *args, **kwargs): + super(Userform, self).__init__(*args, **kwargs) + self.fields.keyOrder = [ + 'username', + 'firstname', + 'lastname', + 'email', + 'telephone', + 'password'] + + username = forms.CharField(min_length=5) + firstname = forms.CharField() + lastname = forms.CharField() + telephone = USPhoneNumberField(label="Phone", widget=USPhoneNumberMultiWidget()) + email = forms.EmailField() + password = forms.CharField(max_length=32, widget=forms.PasswordInput) + + def clean_username(self): + cd = self.cleaned_data + users = User.objects.filter(username__iexact=cd['username']) + if users.count() > 0: + raise forms.ValidationError("username is not unique") + return cd['username'] + + + def save(self): + cd = self.cleaned_data + print cd['username'] + user = User.objects.create_user(cd['username'], password=cd['password'], email=cd['email']) + user.save() + user = authenticate(username=cd['username'], password=cd['password']) + userprofile = Userprofile( + user=user, + telephone=cd['telephone'], + ) + userprofile.save() + return userprofile + \ No newline at end of file diff --git a/django_test/django_test/applications/userprofile/models.py b/django_test/django_test/applications/userprofile/models.py new file mode 100644 index 0000000..603f6b4 --- /dev/null +++ b/django_test/django_test/applications/userprofile/models.py @@ -0,0 +1,58 @@ +try: + import simplejson as json +except: + import json + +from django.db import models +from django.contrib.auth.models import User + +class Userprofile(models.Model): + + user = models.ForeignKey(User, related_name='profile') + telephone = models.CharField(max_length=15) + + + +class Todo(models.Model): + user = models.ForeignKey(User, related_name="todo_list") + list = models.TextField() + + def add(self, item, status='active'): + list = self.get_list() + list.append({'value':item, 'status':status}) + self.list = json.dumps(list) + self.save() + + def update(self, item): + list = self.get_list() + for l in list: + if l.get('value') == item: + if l['status'] == "active": + l['status'] = "complete" + else: + l['status'] = "active" + break + + self.list = json.dumps(list) + self.save() + return l['status'] + + def remove(self, item): + list = self.get_list() + for l in list: + if l.get('value') == item: + list.pop(list.index(l)) + break + + self.list = json.dumps(list) + self.save() + + + def get_list(self): + if self.list is None or self.list == "": + todos = [] + else: + print self.list + todos = json.loads(self.list) + return todos + diff --git a/django_test/django_test/settings.py b/django_test/django_test/settings.py old mode 100644 new mode 100755 index 3468225..503e5e9 --- a/django_test/django_test/settings.py +++ b/django_test/django_test/settings.py @@ -1,4 +1,10 @@ # Django settings for django_test project. +import os +import sys + +BASE_DIR = os.path.dirname(os.path.abspath(__file__)) +sys.path.append('%s/applications' % BASE_DIR) +sys.path.append('%s' % BASE_DIR) DEBUG = True TEMPLATE_DEBUG = DEBUG @@ -11,15 +17,17 @@ DATABASES = { 'default': { - 'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. - 'NAME': '', # Or path to database file if using sqlite3. - 'USER': '', # Not used with sqlite3. + 'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. + 'NAME': 'test',# Or path to database file if using sqlite3. + 'USER': 'root', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. - 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. - 'PORT': '', # Set to empty string for default. Not used with sqlite3. + 'HOST': 'localhost', # Set to empty string for localhost. Not used with sqlite3. + #'PORT': '', # Set to empty string for default. Not used with sqlite3. } } - +AUTHENTICATION_BACKENDS = ( + 'django.contrib.auth.backends.ModelBackend', + ) # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. @@ -106,6 +114,7 @@ # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. + "%s/templates/"%BASE_DIR, ) INSTALLED_APPS = ( @@ -115,6 +124,8 @@ 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', + + 'userprofile', # Uncomment the next line to enable the admin: # 'django.contrib.admin', # Uncomment the next line to enable admin documentation: @@ -129,15 +140,10 @@ LOGGING = { 'version': 1, 'disable_existing_loggers': False, - 'filters': { - 'require_debug_false': { - '()': 'django.utils.log.RequireDebugFalse' - } - }, + 'handlers': { 'mail_admins': { 'level': 'ERROR', - 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' } }, diff --git a/django_test/django_test/templates/base.html b/django_test/django_test/templates/base.html new file mode 100644 index 0000000..f7ee4fd --- /dev/null +++ b/django_test/django_test/templates/base.html @@ -0,0 +1,14 @@ + +Home >> +{%if not user.is_authenticated%} +login +{%else%} +todo >> +logout +{%endif%} +
+
+ +{%block content%} + +{%endblock%} diff --git a/django_test/django_test/templates/home.html b/django_test/django_test/templates/home.html new file mode 100644 index 0000000..387d273 --- /dev/null +++ b/django_test/django_test/templates/home.html @@ -0,0 +1,10 @@ +{%extends 'base.html'%} + +{%block content%} +youre home + +{%if user.is_authenticated%} +Welcome {{user.username}} +{%endif%} + +{%endblock%} \ No newline at end of file diff --git a/django_test/django_test/templates/login.html b/django_test/django_test/templates/login.html new file mode 100644 index 0000000..7637a17 --- /dev/null +++ b/django_test/django_test/templates/login.html @@ -0,0 +1,31 @@ + + + +
+ {% if errors %} +

Your username and password didn't match. Please try again.

+ {% endif %} + +
+ {% csrf_token %} + + + +
+ + + +
+
\ No newline at end of file diff --git a/django_test/django_test/templates/register.html b/django_test/django_test/templates/register.html new file mode 100644 index 0000000..86858c2 --- /dev/null +++ b/django_test/django_test/templates/register.html @@ -0,0 +1,8 @@ +
+{% csrf_token %} + +{{form.as_table}} +
+ + +
diff --git a/django_test/django_test/templates/todo.html b/django_test/django_test/templates/todo.html new file mode 100644 index 0000000..ff40067 --- /dev/null +++ b/django_test/django_test/templates/todo.html @@ -0,0 +1,113 @@ +{%extends 'base.html'%} + +{%block content%} + + + + +
+ +
+ {%for item in list%} +
+ + {{item.value}} + X +
+ {%endfor%} + all | + active | + complete +
+
+ +{%endblock%} \ No newline at end of file diff --git a/django_test/django_test/urls.py b/django_test/django_test/urls.py old mode 100644 new mode 100755 index 7b952d9..1d2b1aa --- a/django_test/django_test/urls.py +++ b/django_test/django_test/urls.py @@ -1,8 +1,10 @@ -from django.conf.urls import patterns, include, url +from django.conf.urls.defaults import patterns, include, url # Uncomment the next two lines to enable the admin: -# from django.contrib import admin +from django.contrib import admin # admin.autodiscover() +from views import * + urlpatterns = patterns('', # Examples: @@ -12,6 +14,13 @@ # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), - # Uncomment the next line to enable the admin: - # url(r'^admin/', include(admin.site.urls)), + url(r'^login/', login, name='login'), + url(r'^logout/', logout, name='logout'), + url(r'^register/', register, name='register'), + url(r'^todo/', todo, name='todo'), + url(r'^save_todo/', save_todo, name='save_todo'), + url(r'^update_todo/', update_todo, name='update_todo'), + url(r'^remove_todo/', remove_todo, name='remove_todo'), + #url(r'^admin/', include(admin.site.urls)), + url(r'^$', home, name='home'), ) diff --git a/django_test/django_test/utils/__init__.py b/django_test/django_test/utils/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/django_test/django_test/utils/tools.py b/django_test/django_test/utils/tools.py new file mode 100644 index 0000000..62dd629 --- /dev/null +++ b/django_test/django_test/utils/tools.py @@ -0,0 +1,29 @@ +from django import forms + +class USPhoneNumberMultiWidget(forms.MultiWidget): + """ + A Widget that splits US Phone number input into three boxes. + """ + def __init__(self,attrs=None): + widgets = ( + forms.TextInput(attrs={'size':'3','maxlength':'3', 'class':'phone'}), + forms.TextInput(attrs={'size':'3','maxlength':'3', 'class':'phone'}), + forms.TextInput(attrs={'size':'4','maxlength':'4', 'class':'phone'}), + ) + super(USPhoneNumberMultiWidget, self).__init__(widgets, attrs) + + def decompress(self, value): + if value: + return value.split('-') + return (None,None,None) + + def value_from_datadict(self, data, files, name): + value = [u'',u'',u''] + # look for keys like name_1, get the index from the end + # and make a new list for the string replacement values + for d in filter(lambda x: x.startswith(name), data): + index = int(d[len(name)+1:]) + value[index] = data[d] + if value[0] == value[1] == value[2] == u'': + return None + return u'%s-%s-%s' % tuple(value) diff --git a/django_test/django_test/views.py b/django_test/django_test/views.py new file mode 100644 index 0000000..2d51460 --- /dev/null +++ b/django_test/django_test/views.py @@ -0,0 +1,93 @@ +import json + +from django.shortcuts import render_to_response +from django.http import HttpResponseRedirect, HttpResponse +from django.template import RequestContext +from django.contrib.auth import authenticate +from django.contrib.auth import login as auth_login, logout as auth_logout +from django.views.decorators.csrf import csrf_exempt + + +from applications.userprofile.models import Userprofile, Todo +from applications.userprofile.forms import Userform + +def home(request): + return render_to_response('home.html', + {}, + context_instance=RequestContext(request)) + +def login(request): + if request.method == "GET": + return render_to_response('login.html', + {}, + context_instance=RequestContext(request)) + + elif request.method == "POST": + username = request.POST['username'] + password = request.POST['password'] + + user = authenticate(username=username, password=password) + if user is not None: + if user.is_active: + auth_login(request, user) + return HttpResponseRedirect("/") + + return render_to_response('login.html', + {'errors':True}, + context_instance=RequestContext(request)) + +def register(request): + if request.method == "GET": + form = Userform() + return render_to_response('register.html', + {'form':form}, + context_instance=RequestContext(request)) + + elif request.method == "POST": + form = Userform(request.POST) + if not form.is_valid(): + return render_to_response('register.html', + {'form':form}, + context_instance=RequestContext(request)) + else: + up = form.save() + + auth_login(request, up.user) + return HttpResponseRedirect("/") + + +def logout(request): + auth_logout(request) + return HttpResponseRedirect("/login") + +def todo(request): + list, created = Todo.objects.get_or_create(user = request.user) + list = list.get_list() + return render_to_response('todo.html', + {'list':list}, + context_instance=RequestContext(request)) + +@csrf_exempt +def save_todo(request): + item = request.POST.get('todo') + if item: + todo = Todo.objects.get(user=request.user) + todo.add(item) + return HttpResponse(json.dumps({"success":True}), mimetype="application/json") + +@csrf_exempt +def update_todo(request): + item = request.POST.get('todo') + if item: + todo = Todo.objects.get(user=request.user) + status = todo.update(item) + return HttpResponse(json.dumps({"success":True, 'status':status}), mimetype="application/json") + +@csrf_exempt +def remove_todo(request): + item = request.POST.get('todo') + if item: + todo = Todo.objects.get(user=request.user) + status = todo.remove(item) + return HttpResponse(json.dumps({"success":True}), mimetype="application/json") + diff --git a/django_test/django_test/wsgi.py b/django_test/django_test/wsgi.py old mode 100644 new mode 100755 diff --git a/django_test/manage.py b/django_test/manage.py old mode 100644 new mode 100755 index 221e92e..ad4e1bc --- a/django_test/manage.py +++ b/django_test/manage.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python2.7 import os import sys diff --git a/palinodrome_product.py b/palinodrome_product.py index ac77e59..8d67430 100644 --- a/palinodrome_product.py +++ b/palinodrome_product.py @@ -1,3 +1,13 @@ """A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 99.Find the largest palindrome made from the product of two 3-digit numbers.""" + +h=0 +for a in xrange(999, 0, -1): + for b in xrange(999, 0, -1): + c = a * b + d, e = len(str(c)) / 2, str(c) + f, g = e[:d:], e[d:][::-1] + if c > h and f == g: + h = c +print h \ No newline at end of file diff --git a/prime.py b/prime.py index b54dead..f527019 100644 --- a/prime.py +++ b/prime.py @@ -1,2 +1,32 @@ """Write a program to find the 10 001st prime number using the sieve of aristothanes.""" + + +def sieve_of_aristothanes(limit): + + limitn = limit + 1 + + # Create a list of prime markers + not_prime = [False] * limitn + # Create a list of primes + primes = [] + + + for x in range(2, limitn): + # Get the next not marked # in the list + if not_prime[x]: + continue + + for f in xrange(x+x, limitn, x): + # Mark each sequential instance in the list as not prime + not_prime[f] = True + + # Add our not prime # to the list of primes + primes.append(x) + + return primes + +# adjusted the list in include at least 10001 prime numbers +primes = sieve_of_aristothanes(200000) +print primes[10001] # 104759 + diff --git a/series_product.py b/series_product.py index 2d6a53a..a722c04 100644 --- a/series_product.py +++ b/series_product.py @@ -1,3 +1,20 @@ """Complete this program to find the greatest produdct of five consecutive digits in the list""" +import re in_file = open('array.txt') + + +stnum = re.sub(r"\n","", in_file.read()) +print stnum +s = 0 +e = 5 +largeval = 0 +while e <= len(stnum): + subset = stnum[s:e] + prod = reduce(lambda x,y : x*y, [int(x) for x in subset]) + if prod > largeval: + largeval = prod + s += 1 + e += 1 + +print largeval