Python iterating over collection with index


Python interation with index example source code;


listIterationWithIndex = ['Test1','Goose','Bison','Pelican']

#iterate over list with index
for i, withIndex in enumerate(listIterationWithIndex):
    print ("element -- ", i , withIndex)

'''
output
element --  0 Test1
element --  1 Goose
element --  2 Bison
element --  3 Pelican
'''

tuple_ =  ('Cat','Dog','Elephant','Bird','Tiger','Lion',\
           'Rabbit')

#iterate over tuple with index
for i, withIndex in enumerate(tuple_):
    print ("element -- ", i , withIndex)

'''
output
element --  0 Cat
element --  1 Dog
element --  2 Elephant
element --  3 Bird
element --  4 Tiger
element --  5 Lion
element --  6 Rabbit
'''
    
dictionaryAnimalSpeed = {'tiger': 65, 'monkey': 25 ,'bison': 35, 'cheetah': 113 }

#iterate over dictionary with index
for i, withIndex in enumerate(dictionaryAnimalSpeed.keys()):
    print ("element -- ", i , withIndex)

'''
output
element --  0 bison
element --  1 cheetah
element --  2 monkey
element --  3 tiger
'''    
    

Django OperationalError: unable to open database file


tuna@tuna-VirtualBox:~/Desktop/djangoprojects/mysite$ python manage.py syncdb
OperationalError: unable to open database file

if you get this error most probably you have typo inside settings.py file (NAME field), also arrange chmod 777 for sqllite.db file

DATABASES = {

‘default’: {
‘ENGINE’: ‘django.db.backends.sqlite3‘, # Add ‘postgresql_psycopg2’, ‘mysql’, ‘sqlite3’ or ‘oracle’.
‘NAME’: ‘/home/tuna/Desktop/djangodb/sqllite.db’, # Or path to database file if using sqlite3.
# The following settings are not used with sqlite3:
‘USER’: ”,
‘PASSWORD’: ”,
‘HOST’: ”, # Empty for localhost through domain sockets or ‘127.0.0.1’ for localhost through TCP.
‘PORT’: ”, # Set to empty string for default.
}
}

after that you will see that the tables are created automatically;

tuna@tuna-VirtualBox:~/Desktop/djangoprojects/mysite$ python manage.py syncdb
Creating tables …
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_groups
Creating table auth_user_user_permissions
Creating table auth_user
Creating table django_content_type
Creating table django_session
Creating table django_site

You just installed Django’s auth system, which means you don’t have any superusers defined.
Would you like to create one now? (yes/no): yes
Username (leave blank to use ‘tuna’): tuna

Python JSON parsing example



#Created on Jul 30, 2013
#@author: tunatore

import json

# you can create a json structure
pythonStructure = { 'JavaLevel':'Expert', 'PythonLevel':"Beginner", 'C#Level':"Good" }

print ("Python Structure = " , pythonStructure)

#dumps will load python structure as json
print ("JSON Converted Structure = ", json.dumps(pythonStructure))
print ("JSON Converted Structure Sorted Keys = " , json.dumps(pythonStructure, sort_keys=True))

#pretty printed JSON
print ("pretty printed JSON \n")
print (json.dumps(pythonStructure, sort_keys=True, indent=5, separators=(',', ' : ')))

#dumps will load json structure as python structure
print ("Python Structure = " , (json.loads(json.dumps(pythonStructure))))

#another python struct conversion

pythonData = dict(
 key1 = "Val 1",
 key2 = "Val 2",
 key3 = "Val 3",
 key4 = 4
)

print ("JSON Converted Structure = ", json.dumps(pythonData,sort_keys=True))
#loading and parsing JSON data from url
import urllib.request
url = "http://carma.org/api/1.1/searchLocations?name=Idaho"
request = urllib.request.Request(url)
response = urllib.request.urlopen(request)
loadJSON = json.loads(response.read().decode('utf-8'))
print (json.dumps(loadJSON, indent=4, sort_keys=True))

# get carbon JSON item
carbon = loadJSON[0]['carbon']
print ("carbon future" , carbon['future'])
print ("carbon past" , carbon['past'])
print ("carbon present" , carbon['present'])

Output;

Python Structure = {‘PythonLevel’: ‘Beginner’, ‘C#Level’: ‘Good’, ‘JavaLevel’: ‘Expert’}
JSON Converted Structure = {“PythonLevel”: “Beginner”, “C#Level”: “Good”, “JavaLevel”: “Expert”}
JSON Converted Structure Sorted Keys = {“C#Level”: “Good”, “JavaLevel”: “Expert”, “PythonLevel”: “Beginner”}
pretty printed JSON

{
“C#Level” : “Good”,
“JavaLevel” : “Expert”,
“PythonLevel” : “Beginner”
}
Python Structure = {‘PythonLevel’: ‘Beginner’, ‘C#Level’: ‘Good’, ‘JavaLevel’: ‘Expert’}
JSON Converted Structure = {“key1”: “Val 1”, “key2”: “Val 2”, “key3”: “Val 3”, “key4”: 4}
[
{
“carbon”: {
“future”: “2068400.0000”,
“past”: “758970.0000”,
“present”: “838420.0000”
},
“country”: {
“id”: “6252001”,
“name”: “United States”
},
“energy”: {
“future”: “18787000.0000”,
“past”: “10677000.0000”,
“present”: “13059000.0000”
},
“fossil”: {
“future”: “0.2371”,
“past”: “0.1666”,
“present”: “0.1339”
},
“hydro”: {
“future”: “0.5648”,
“past”: “0.7809”,
“present”: “0.7996”
},
“id”: “5596512”,
“intensity”: {
“future”: “110.0000”,
“past”: “71.1000”,
“present”: “64.2000”
},
“name”: “Idaho”,
“nuclear”: {
“future”: “0.0000”,
“past”: “0.0000”,
“present”: “0.0000”
},
“plant_count”: “92”,
“renewable”: {
“future”: “0.1981”,
“past”: “0.0525”,
“present”: “0.0664”
},
“type”: “province”
}
]
carbon future 2068400.0000
carbon past 758970.0000
carbon present 838420.0000

How to learn django version


tuna@tuna-VirtualBox:~/Downloads/Django-1.5.1$ python
Python 2.7.3 (default, Aug 1 2012, 05:14:39)
[GCC 4.6.3] on linux2
Type “help”, “copyright”, “credits” or “license” for more information.
>>> import django
>>> print (django.get_version())

1.5.1
>>>

second way;

tuna@tuna-VirtualBox:~/Downloads/Django-1.5.1$ python -c “import django; print(django.get_version())”
1.5.1

Python Collections, Tuple, Dictionary and List simple example


You can check the following code piece in order to  have basic knowledge regarding Python collections;

#Created on Jul 26, 2013
#@author: tunatore

#python collections

#tuple example which is generally not mutable
animals = ('Cat','Dog','Elephant','Bird','Tiger','Lion',\
 'Rabbit')

#tuples are accessed by index and similar to list
print ("this will print", animals[0]) #index starts from 0
print ("this will print", animals[6])

#IndexError: tuple index out of range
#print (animals[7])

listAnimals = ['','Goose','Bison','Pelican']

#list access
print ("list print", listAnimals[0])
print ("list print", listAnimals[1])
print ("list print", listAnimals[3])

#list difference, you can change lists
listAnimals.append('Whale')
print ("list print", listAnimals[4])

#add Whale again to list
listAnimals.append('Whale')
print ("list print", listAnimals[5])

#count Whale element in List

print ("list Whale count is", listAnimals.count('Whale'))

#remove Whale element first occurrence
listAnimals.remove('Whale')

print ("list Whale count is", listAnimals.count('Whale'))

#list total elements count
print("Count Elements in listAnimals", len(listAnimals))

#you can also count tuples with len
print("Count Elements in animals Tuple", len(animals))

#before list sort
print ("before sort", listAnimals[1])
print ("before sort", listAnimals[2])
print ("before sort", listAnimals[3])

listAnimals.sort()

#after list sort
print ("after sort", listAnimals[1])
print ("after sort", listAnimals[2])
print ("after sort", listAnimals[3])

#python dictionary example
dictionaryAnimalSpeed = {'tiger': 65, 'monkey': 25 ,'bison': 35, 'cheetah': 113 }

#accessing dictionary with key
print ("monkey's speed -",dictionaryAnimalSpeed['monkey'])
print ("tiger's speed -",dictionaryAnimalSpeed['tiger'])

#you can even change tiger's speed
dictionaryAnimalSpeed['tiger'] = 71
print ("new tiger's speed -",dictionaryAnimalSpeed['tiger'])
#adding new element
dictionaryAnimalSpeed['cow'] = 25

#getting dictonary keys
animalNamesInDictionary = dictionaryAnimalSpeed.keys()
for animal in animalNamesInDictionary:
 print ("animal name ", animal)

#ordered dictionary

import collections
print ("\nordered dictionary")
orderedDictionary = collections.OrderedDict(sorted(dictionaryAnimalSpeed.items()))
for key, value in orderedDictionary.items():
 print (key, value)

this will print Cat
this will print Rabbit
list print
list print Goose
list print Pelican
list print Whale
list print Whale
list Whale count is 2
list Whale count is 1
Count Elements in listAnimals 5
Count Elements in animals Tuple 7
before sort Goose
before sort Bison
before sort Pelican
after sort Bison
after sort Goose
after sort Pelican
monkey’s speed – 25
tiger’s speed – 65
new tiger’s speed – 71
animal name cheetah
animal name tiger
animal name monkey
animal name bison
animal name cow

ordered dictionary
bison 35
cheetah 113
cow 25
monkey 25
tiger 71

Spring Core 3.0 Framework Certification (certification result)


      Click here to attend Spring Framework 4.x and certification course with a discount

Hi,

Today, I received my official Spring Core Framework 3.0 Certification, You can see how the certification looks like as below;

TTSpringCore3.0

In case you have questions regarding this exam, you can ask me by replying to this post;

Regards,

T.T

      Click here to attend Spring Framework 4.x and certification course with a discount

Python datetime formatting using time, calendar and datetime


Python date/time formatting example;

#Created on Jul 25, 2013

#@author: tunatore

import time;
import calendar;
from datetime import date;

currenTimeTuple = time.localtime(time.time())
print ("current timeTuple :", currenTimeTuple)

#accessing tuple values
print ("current year:", currenTimeTuple[0])
print ("current month:", currenTimeTuple[1])
print ("current day:", currenTimeTuple[2])

print ("current hour:", currenTimeTuple[3])
print ("current minute:", currenTimeTuple[4])
print ("current second:", currenTimeTuple[5])

print ("\n")
#getting calendar
calenderTxt = calendar.month(2013,7)
print (calenderTxt)

#formatted times
print (time.asctime(currenTimeTuple))
print (time.strftime("%Y-%m-%d %H:%M:%S", currenTimeTuple))
print (time.strftime("%d-%m-%Y %H:%M:%S", currenTimeTuple))

#current date formatted
nowDate = date.fromtimestamp(time.time())

#ISO format current
print ("Now" , nowDate.isoformat())
print ("Now Custom Format", nowDate.strftime("%d/%m/%y"))

output;

current timeTuple : time.struct_time(tm_year=2013, tm_mon=7, tm_mday=25, tm_hour=18, tm_min=12, tm_sec=19, tm_wday=3, tm_yday=206, tm_isdst=1)
current year: 2013
current month: 7
current day: 25
current hour: 18
current minute: 12
current second: 19

July 2013
Mo Tu We Th Fr Sa Su
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31

Thu Jul 25 18:12:19 2013
2013-07-25 18:12:19
25-07-2013 18:12:19
Now 2013-07-25
Now Custom Format 25/07/13