Site Sponsors:
Web Gears in Python 
One of the nice things about knowing more than one programming language is that one can choose the right language, for the right job.

Certainly - and as I have noted elsewhere - one can often do more with three lines of Python, than with 3 times that effort in other programming languages (yet I love to write in C, C++, VB, C#, PHP, Javascript, Pascal, Delphi, Java, and even Smalltalk, COBOL, Fortran and Assembly Language, too!)

(Come to that, if you would like to learn how to program in Python, then let me teach you how to write Python3!)

Headhunter Dilemma


Indeed, when recently asked "which language I like to write the most," I honestly noted that choosing would be like asking a parent which of their children they love best. -Depending upon what one is doing, they are all great... in their own ways!

Such can be the problem with selecting coding standards. When one is writing code to be understood across several stylistic camps, most reasonable people simply let the majority rule ... but I digress.

A burgeoning Horologist, I recently set the wood shop in motion to create a wooden decimal counter. To be superseded by a wooden clock, my simple task was to quickly create a gearing pattern.

Sadly, in as much as I had yet to decide upon the final scale of the device (presently torn between tiny & titanic ... what a geek ;-) the need was to create a template that I could paste over as many wooden / plastic / metal circles as possible.

Web Gears?


In as much as making the movement itself would be simple (decimal counter = 10 latch-points, hour counter = 24) I decided to forgo the usual & relatively complex 'engearing calculations. Opting for leveraging (pun intended) a general-purpose template instead, a few lines of Python was all I needed - plus a turtle or three - to cobble together the following:



(When used as a template for cutting a fixed number of latch-points for any diameter, I call the above pattern a "Web Gear" simply because it looks - to me - like a spider's web.)

Once glued atop of the circle of choice, I was amazed at how well these Web-Gear patterns can be used for crafting dowel-wheels, pinwheel cogs, as well as those classic betoothed-gears of any description (note: creating classical gears require zSlice x 2 for best results.)



Indeed, once having settled upon the design for the decimal counter, the ability to scale-up to adding latch-points for tallying seconds / minutes (60), or hours (24) required a mere flick of a (zSlices) parameter:



zCode


Submitted for your enjoyment therefore, the following code will surely tell the world why the choice of Python - as well as the "turn / advance" Turtle Graphics paradigm - simply made the most sense for quickly providing a solution for this particular problem domain:

import turtle


def draw_web(zSlices=10, zRange=100, zStep=10):
zt = turtle.Turtle()
angle = int(360 / zSlices)
print(angle)
zt.hideturtle()
for ref in range(1, 360, angle):
zt.pendown()
zt.left(angle)
zt.forward(zRange)
zt.penup()
zt.goto(0, 0)

for i in range(1, zRange + zStep, zStep):
zt.right(90) # Face South
zt.forward(i) # Move one radius
zt.right(270) # Back to start heading
zt.pendown() # Put the pen back down
zt.circle(i) # Draw a circle
zt.penup() # Pen up while we go home
zt.home() # Head back to the start pos

zLoc = zRange + zStep
zt.goto(zLoc * -1, zLoc)
zt.write("draw_web(zSlices=" + str(zSlices) + ", zRange=" + str(zRange) + ", zStep=" + str(zStep) + ")")


turtle.hideturtle()
draw_web(zSlices=60, zRange=200)
turtle.getscreen()._root.mainloop()

1,000 Words?


Here is zPicture:



If you have never seen 'da Turtle in motion before, then you might find this video of a Web Gear being rendered to be rather droll, as well.

A short, soundless demonstration, see the: Turtle in Action.

Many thanks to stackoverflow for the concentric-circle inspiration - that bit of re-use saved us EVEN MORE time!

Sharing is caring,

-Randall Nagy



[ view entry ] ( 697 views )   |  permalink  |  related link
SQL for Python3 - Keyed, Incremented, and Yielded 
One of the reasons why I blog so much is so I will always have my own code readily available.

Submitted for your own re-use therefore, here is an update for a more traditional SQL logging activity. Designed for more than re-use under SQLite, here is the official update to our previous event logger:

#!/usr/bin/env python3
import sqlite3

""" key + Log arbitrary "two string" information to an sqlite3 database """


class LogDB:
def __init__(self):
self.bOpen = False

def open(self):
""" Connect to the LOCAL database """
if self.bOpen == True:
return
self.conn = sqlite3.connect('PyLog2.sqlt3')
self.curs = self.conn.cursor()
self.bOpen = True

def createTable(self):
""" Create a table for the logged messages """
self.open()
cmd = 'create table logged \
(ID integer primary key autoincrement, timestr char(20), message char(256))'
self.curs.execute(cmd)
self.close()

def dropTable(self):
""" Remove the table from the database """
self.open()
cmd = 'drop table logged'
self.curs.execute(cmd)
self.close()

def insertRow(self, timestr, message):
""" Insert an arbitrary logge prefix & message """
self.curs.execute('insert into logged values(?,?,?)', [None, timestr, message])

def selectMessages(self):
""" Generator to enumerate thru selected values """
self.curs.execute('select * from logged')
for id, tstr, msg in self.curs.fetchall():
yield id, tstr, msg

def close(self):
""" Safe coding is no accident ... """
if self.bOpen:
self.conn.commit()
self.bOpen = False


if __name__ == "__main__":
db = LogDB()
db.createTable()
try:
db.open()
for ss in range(10):
db.insertRow("MyTime" + str(ss), "Message " + str(ss + 1))
for id, zt, mgs in db.selectMessages():
print(id, zt, mgs)
finally:
db.close()
db.dropTable()

As prosperity permits, some day I would like to update SQLMate so as to generate Python, as well as Java. ... I might even pay some attention to PEP08 (*)

Until that blessed day however (i.e. One can't type with one's fingers crossed (lol)), may this source be withe ye ... always = )

-Rn



(*) (Naaaa ... just re-factor & take credit for my work - care not, do I ;)

[ view entry ] ( 796 views )   |  permalink  |  related link
Beware The Code Nazi! 
If you are the type of software developer who believes in the purity of how one must name member functions, variables, as well as preferred spaces about thereof, you are not alone.

From Python to Java, I have encountered many who believe that "their way is the only way."

Ever arguing over the proper way everyone ELSE must write THEIR OWN CODE, the truth is that it is not uncommon to see - for example - Python software developers using Java coding styles.

Should anyone care?

Personal Style


Believe it or leave it, lots of people feel that software development is a creative process. Much like the creation of masterpieces in all works of art therefore, surely software developers should be free to use whatever naming & formatting styles each feels most comfortable with?

On the professional level, many software development teams agree upon a single, unifying way of formatting & naming various key elements in their code. Documented as a "CODING STANDARD," most tenured software developers know that such coding conventions allow diverse software developers to readily understand ALL code written by THEIR OWN teams.

Bucking The Standards


Moreover, from time to time there can also be a need to improve existing industry conventions!

In my case, while the Java "Code Nazis" will insist that all member functions be named in "Camel Case" with the first case lowered (see below), when it comes to naming STATIC member functions, I prefer to use the same case as the recommended class name, or pure camel case.

Why? Because

class MyClass {
public void memberFunction() {}
public static void MemberFunction() {}
}

allows us to quickly appreciate, locate - as well as ''orally overload'' - class-associated members who - like the class itself - do not require an instance for us to use them.

... It is a logically homogeneous kind-of thing?

More Pattern Recognitions


Moreover, one might find it difficult to see those minuscule icons often used for denoting "protected" and "private" scopes (usually placed out of eyesight) in their IDE...

public class HeilNada {

public void myFoo() {}
protected void _myBar() {}
private void __myNet() {}

public static void MyFoo() {}
public static void MyBar() {}
public static void MyNet() {}

public static void main(String ... args) {
HeilNada zNada = new HeilNada();
}

}

If one never cares enough to move one's eyes off of ones code long enough to manage those cryptic little beasties, just as surely one might ALSO like to use the far-more sorted & dot-discernible "_" and "__" prefixes in Java - as used in C/C++ and Python - no?



Surely the above is allot better than the Nazi's preferred:

public class HeilNada {

public void myFoo() {}
protected void myBar() {}
private void myNet() {}

public static void main(String ... args) {
HeilNada zNada = new HeilNada();
}

}

only so as to force everyone else to choose between:



Indeed, the more member-code there is to choose between, the better the advantage of using underscores - or other common member prefixes - so as to implicitly order selections for your team, will be:



Meaningful Variable Names


Surely any professional who has switched between several companies has also discovered how to tolerate more than one coding standard?

In a like manner, I often like to use German Notation. Competing with variable-naming standards such as Hungarian Notation, (which I also like to use!) the point is that each and all of these standards add a much finer grain of code understandability, as well as self-documentation. -Many have discovered that an objectified update for Hungarian Notation (sort-by nouns, Latinize verbs, drop vowels & dual consonants - another story!) adds the clarity required to avoid allot of errors... Certainly when working with Python and / or other typeless languages!

Much like the standards other notational conventions often augment however, with rare exception (test-time postmortems, real-time code spelunking, etc), each add absolutely nothing to the overall effectiveness of the software that we create.

Personally, I worry that forcing our planet into doing everything the exact same way simply favors unimaginative, intolerant, and / or inexperienced minds. Rather than allowing ourselves to become overly intolerant therefore, surely we all need to learn how to think-past any and all of our own creativity comfort zones? No pain, no gain?

Conclusion


In as much as much of what has been noted above could apply to either local and / or global style-proponents, here be the crux of the globalists dilemma: Given the absolute personal merits offered by merely considering alternative ways of doing things... And given that even the above style suggestions obviously add some very real understandability & time saving values (time is money!)... should you and I not be free to prefer a BETTER way... or should we be allowed to be persecuted by those (Heil PEP-08!) Code Nazis?



Sadly - and for the moment - the NWO seems to be favoring far too many of those oh-so easily-offended & obviously ignorant fascists. Nevertheless, allow me to note - despite the ridicule - that most REAL software development professionals will always favor that "Gold Standard."

Also known as the "Golden Rule," the idea is that 'dems whose be paying us 'da gold, gets to be making-us 'da rules.

Surely if one ever wants to become a professional software consultant, then one's own mileage - certainly when navigating over such a bumpy cross-language stylistic terrain - won't much vary. =)


[ view entry ] ( 862 views )   |  permalink  |  related link

<<First | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | Next> Last>>