Poss Blog

Just another WordPress.com weblog

Javascript Objects January 26, 2010

Filed under: Computers — jposs @ 3:52 pm
Tags: ,

Javascript objects are great. They are very flexible and easy to use. This blog attempts to provide a concise but clear description of how to use them. There are many facets of this topic that are not covered.

 

Grouping related elements into a single object:

x = {}; // creates empty object

x.max = 999;

x.min = -999;

x.verify = function(val) {

if(val < x.min || val > x.max) return false;

else return true;

}

var verified = x.verify(88);

 

Referencing a property of object x:

var prop = ‘max’;

x.max or x[‘max’] or x[prop] – all reference the same element

 

Iterating thru all the properties of object x:

for( prop in x ) {

alert( prop + ‘=’ + x[prop] );

}

 

Defining an object where multiple instances are needed:

function DataRec(recFields) {

this.recFields = recFields;

this.vals = [];

}

DataRec.prototype.get = function(fldName) {

var ndx = this.recFields[fldName];

return this.vals[ndx];

}

DataRec.prototype.set = function(fldName,val) {

var ndx = this.recFields[fldName];

this.vals[ndx] = val;

}

var carFields = {‘brand’:1, ‘model’:2, ‘mpg’:3};

var houseFields = {‘sqft’:1, ‘address’:2, ‘price’:3};

var carRecs = [];   //array for holding instances of DataRec

carRecs[0] = new DataRec(carFields));   // *** instance of object created ***

carRecs[0].set(‘brand’,’Ford’);     // sets vals[1] = ‘Ford’

 

Notes about the example shown above:

Vars carFields and houseFields are examples of another way to define an object. 

DataRec function defines the object.

Each instance of the DataRec object will contain an array of values (.vals) and a pointer to an object (.recFields) defining the vals index for each field in the record (ex.vals[3] holds mpg value). Each DataRec instance contains only a reference to the recFields object, not a copy of the object itself.

The .get and .set methods were added using the prototype feature. Properties added this way are shared by all instances of the object. If these methods were defined inside the DataRec function, then each instance would contain the code.

Ciao

 

Ajax Project Intro January 20, 2010

Filed under: Computers — jposs @ 11:30 pm
Tags: , , , ,

This is an introductory blog about my experiences developing an Ajax style application. This project is my first time to develop any type of web based program. I still have a ways to go before it is complete. Future blogs will present information I think might be useful to other developers. If you have a question or advice, please leave a comment.

Programming languages used: Javascript, HTML, CSS, Python
Web Service Framework: Django
Javascript library: JQuery
Editors: Notepad++ for everything but Python, Idle for Python
Web Hosting: WebFaction
FTP File Transfer (between my pc and WebFaction): FileZilla
SSH(secure command line connection to WebFaction): PuTTY
Client OS: Windows 7 Home Premium
Client PC: Lenovo laptop, 2 yrs old, 2 core intel 1.5ghz, 2.5gb ram, low end machine-paid $600

So far I am really pleased with all the tools used to work on this project. I just upgraded from WinXP to Win7 and am glad I did (very nice OS). Python and Javascript are great. Compared to Java or C?, these languages are a lot more fun to use. My next blog will probably be on Javascript objects, which are totally cool. If you plan to work with a web hosting company like WebFaction, get some type of Linux/Unix reference. Using a text command line interface, which is needed for some tasks, can be a pain especially if you haven’t worked in that environment. WebFaction does have a nice interface for some of the setup and loads all the Django files for you. They also have a nice feature that lets you put static files in a fast load area that doesn’t use your machine partition (I think).

I use Django to provide a data only web service. My html, javascript, css files are stored in the Webfaction fast load area (mentioned above). After the page loads in the browser, requests are sent to the Django web service. The service sends JSON formatted data back which is stored in javascript arrays. I came up with a really neat (my opinion) way to store/manipulate this data using javascript. Data updates are also sent in JSON format back to the service and the server side database is updated. I’m using Postgresql, but the Django object relational mapper reduces the need to know much about the db.

Django looks to be first class. Python may be my favorite language and in Django, pretty much everything is Python code, including setup files that other frameworks would probably store as xml. The whole approach is very clean.

Adios

 

Javascript/JQuery/HTML Tables: How to Determine Row/Recid September 28, 2009

Filed under: Computers — jposs @ 2:32 pm
Tags: , , , , ,
avascript/JQuery/HTML Tables: How to Determine Row/Recid
Situation:
HTML table is constructed from rows in a database
When user clicks on a table cell, determine row_number/rec_id of associated row
One Solution:
When constructing table, add following to each row:
<td>xx</td>  (xx = value of row number)
<td>xx</td>  (xx = value of database record id)
Hide these cells using CSS:
.tblrow_rowno {display: none}
.tblrow_recid {display: none}
Using JQuery bind click event function to cells user will click to select row:
$(“.selectorcells”).bind(‘click’, function(eventData) {
var parentTR = $(eventData.target).closest(“tr”);
var row = $(parentTR).children(“.tblrow_rowno”).text();
var recid = $(parentTR).children(“.tblrow_recid”).text();
});

Situation

  • HTML table is constructed from rows in a database
  • When user clicks on a table cell, determine row_number/rec_id of associated row

One Solution

When constructing table, add following to each row:

  • <td class=tblrow_rowno>xx</td>  (xx = value of row number)
  • <td class=tblrow_recid>xx</td>  (xx = value of database record id)

Hide these cells using CSS:

  • .tblrow_rowno {display: none}
  • .tblrow_recid {display: none}

Using JQuery bind click event function to cells user will click to select row:

$(“.selectorcells”).bind(‘click’, function(eventData) {

var parentTR = $(eventData.target).closest(“tr”);

var row = $(parentTR).children(“.tblrow_rowno”).text();

var recid = $(parentTR).children(“.tblrow_recid”).text();

});

 

Python Cracked #2 September 3, 2009

Filed under: Computers — jposs @ 6:44 pm
Tags: , , ,

This post has to do with Python variable binding (the way I understand it).

All variables are binded (point) to an object or None.

Everything is an object (numbers, strings, classes, modules, functions,etc.) 

A variable can point to any type of object.

Some objects are mutable (can be changed); some are immutable (cannot be changed).

Example mutable objects: lists, dictionaries

Example immutable objects: strings,  numbers of any type ,  tuples 

 

x = 1 ( var x points to integer object with value of 1)

x= x + 1 ( var x points to a different integer object with value of 2)

The original object x was bound to is  now unbound and will be removed by the garbage collector.

If x pointed to a list object and it was changed,  x would still point to the same object.

 

Variables as function parameters:

  • A pointer is passed to the original object for each parameter.
  • If the parameter object is immutable, then any changes will cause creation of a new object.
  • The variable used in the calling statement will still point to the original (unchanged) object. 
  • If the parameter object is mutable, then any changes will affect the original object.
  • The variable used in the calling statement will see affects of the changes made.
 

Python Cracked #1 September 2, 2009

Filed under: Computers — jposs @ 1:55 pm
Tags: ,

# This post is a working Python module that demonstrates key concepts.
# Target audience is programmers experienced with other languages (Java,C#).
# It is intended as a supplement to other reference materials.

# Copy and paste into an editor. Preferrably one that knows Python.

# Python is picky about formatting. Indents mean something. Each indent level should be 4 spaces.

# ———– CODE BEGINS HERE —————————————————
class Customer:
    “Customer Record”
   
    log = []           
    __nextCustNo = 0        # __private
   
    def __init__(self, name, city, st, contact=”unknown”): 
        Customer.__nextCustNo += 1
        self.custno = Customer.__nextCustNo
        self.name = name
        self.city = city
        self.st = st
        self.contact = contact
        self.sales = 0.00
        self.pastDue = 0.00
        Customer.log.append(name + ” – customer rec created”)
   
    def addSales(self, salesAmt):
        self.sales += salesAmt
        Customer.log.append(“%s sales amt of %d added” % (self.name, salesAmt))
       
    def addPastDue(self, pastDueAmt):
        self.pastDue += pastDueAmt
        Customer.log.append(“%s pastdue amt of %d added” % (self.name, pastDueAmt))
                           
# ———————————————————————–
def goodCust(cust):
    “return true, if cust (instance of Customer) is a good customer, else return false”
    if cust.sales > 1000 and cust.pastDue < (cust.sales * .10):
        return True
    else:
        return False
   
# ———————————————————————-
def printCustomerLog():    
    for logMsg in Customer.log:    
        print logMsg
       
# ———————————————————————-
def addAmts(custName, salesAmt=0, pastDueAmt=0):
    “Add specified salesAmt and pastDueAmt to Customer record in customers[]”
    findName = custName.upper()
    custFound = False
   
    for cust in customers:
        if cust.name.upper() == findName:
            cust.addSales(salesAmt)
            cust.addPastDue(pastDueAmt)
            custFound = True
            break
       
    if custFound: pass
    else:
        print “addAmts customer not found ” + custName
       
# ———————————————————————-
customers = []

customers.append( Customer(“Hughs Ton Parts”, “Houston”, “TX”) )
customers.append( Customer(“MyAmMe Inc.”, “Miami”, “FL”) )
customers.append( Customer(“Tamp Ahh”, “Tampa”, “FL”, contact=”S.S. Simpson”) )
customers.append( Customer(“Sana Tone”, “San Antonio”, “TX”, contact=”Dee Dee Dunby”) )

addAmts(“Hughs Ton Parts”, salesAmt=500)
addAmts(“MyAmMe Inc.”, salesAmt=333.33, pastDueAmt=75.00)
addAmts(“Tamp Ahh”, salesAmt=5000, pastDueAmt=475.00)
addAmts(“Sana Tone”, salesAmt=999, pastDueAmt=100)                           

# *** floridaCustomers and goodCustomers are created using a feature called “list comprehension”

floridaCustomers = [a.custno for a in customers if a.st == “FL”]

goodCustomers = [“%s – %s” % (a.custno,a.contact) for a in customers if goodCust(a)]

coastCities = (“Houston”, “Miami”, “Pensacola”, “Tampa”)   # a tuple

coastCustomers = []

for i in range( len(customers) ):        
    if customers[i].city in coastCities:
        coastCustomers.append(customers[i])
       
# ————————————————————————–

print “Doc string for addAmts function: \n” + addAmts.__doc__

print “\n\nCustomer Log”
printCustomerLog()

print “\n\nFlorida Customers – custno only”       
for x in floridaCustomers: print x

print “\n\nGood Customers – custno-contact”
for custno_contact in goodCustomers: print custno_contact

print “\n\nCoast Customers – Name City,St”
for x in coastCustomers: print x.name + ” ” + x.city + “,” + x.st

 

Intel Being ARM Wrestled June 12, 2009

Filed under: Computers — jposs @ 6:13 pm
Tags: , , ,

A slew of companies (Nvidia,TI,Qualcomm,Samsung,Freescale) have new chips based on versions of the ARM processor. ARM processors have always been known for using very little power, but also for having limited processing power. The new versions are still slower than typical x86 chips, but are getting fast enough to use in MIDs (mobile internet devices) which includes smartphones and netbooks.

The Palm Pre  and  iPhone use ARM based chips. Palm’s Web OS, Google’s  Android OS, and Windows Mobile all run on these processors. The roadmap of future ARM processors shows their ability expanding to power larger screen devices while probably using less power than Intel chips. With plenty of software and more capable hardware, the ARM world looks to be moving in on Intel’s turf.

Intel’s  domination of the personal computing chips business could be in peril. We like thin, light, long battery life, and cheap devices. ARM based devices excel at all these attributes. With 1Ghz+ multicore versions coming, the need for speed should be answered as well.