May 5th, 2017 by dbakevlar

So since I already complained about what I hate about tech from a diversity and culture perspective, I felt I needed to explain all the things I love about tech and why I wouldn’t want to be anywhere else.

Everyone would expect me to start with databases or virtualization, but I thought I’d keep everyone on their toes and start with my favorite programming language- PYTHON!

1.Timed Pauses, Stops and Waits

Sometimes systems are just too fast for humans.  It’s important to have proper delays between tasks so that people are able to interact or systems are able to respond to each other in the proper amount of time.  This is where the “sleep” command comes in.  Just like in Bash shell, sleep is used to tell a command to wait:

@logged("%b %d %Y - %H:%M:%S")
def add2(x, y):
    time.sleep(2)
    return x + y

The command above translates to “Time to sleep [in seconds] and then proceed with the next command[s].”  This comes in handy as you time out spaces between tasks and is a common command you’ll see in any python program.

2. Context Managers

The ability to write to files or create scripts dynamically is an important one in any programming language.  We write and append to files as needed and this is something we can do with Python using context management.  Simply open a file, write to it and then remember to close it afterwards, (which I didn’t add

>>>file = open(“/var/testfile.txt”,”w”) 
 
>>>file.write(“#Fix File Script”) 
>>>file.write(“mv /var/testfile.txt /usr/mvfile.sh”) 
>>>file.write(“chmod 774 /var/testfile.txt”) 
>>>file.write(“exit”) 
 
>>>file.close()

3.  Generators

As DBAs, we understand the value of a sequence.  We use them all the time in databases and create them with the simple command:

CREATE SEQUENCE emp_seq
 START WITH     1
 INCREMENT BY   1;

In programming languages, often its just as easy and with Python, we’re able to do all kinds of tasks via a function in a sequential manner.  There are distinct requirements to use a generator, but one of them is to use the word yield, as each function call must yield a value of some sort.

>>> def f():
...   print("-- Ready --")
...   yield 1
...   print("-- Set --")
...   yield 2
...   print("-- Go --")
...   yield 3
>>> gen = f()
>>> next(gen)
-- Ready --
1
>>> next(gen)
-- Set --
2
>>> next(gen)
-- Go --
3

Each of the yield values are stored in the object created by this function.  As you can see, this could be a bit cumbersome, so how can we do it in a simpler manner with Python?

4.  Iterators

Another way to perform something sequentially and simply, is to use an iterator.  While the iterator can save us a lot of time by building out from a list-

>>> f = [1, 2, 3]  
>>> iter(f)
<...iterator object at ...>
>>> f.__iter__()

We can save even more time by using a file as an iterator.  Yes, you heard me-  The file is the iterator and at no time does it create a separate object.  Keep in mind, only sequential access with a single thread is allowed here, too.

>>> f = open('/home/python/dbakevlar/file.txt')
>>> f is f.__iter__()
True
5.  Replacing Values
Sometimes what data is shown, isn’t the data you want returned.  This is pretty easy to change in Python and why its such a common language to use.
>>> local = [80031, 80204, 80221] 
>>> "Westminster","Denver","Aurora" = local

>>> Westminster
80031 
>>> Denver
80204
>>> Aurora
80221
6.  Decorator Function
No, this doesn’t mean we all become Martha Stewart, but these are gorgeous functions that make it easy to do a lot with very little.  In Python, decorators are functions (or objects that can be called) that require an input of optional arguments, a function or class, and return a function or class.

 

from inspect import getargspec as gas   

def decorate(fn):
    argspec = gas(fn)
    scd_argname = argspec[0][1]
    def inner(*args, **kwargs):
        special_value = (kwargs[scd_argname] 
                         if scd_argname in kwargs else args[1])
        if special_value == 2:
            print "nada"
        else:
            print "nada happening"
        return fn(*args, **kwargs)
    return inner

@decorate
def nada(a, b, c=3):
    pass

nada(1,2,3)
nada(1,b=2,c=4)
nada(1,3,5)
nada(1,b=6,c=5)
Note that nada can return the correct values depending on the arguments and is as flexible as we need it to be for a given program, wrapping functions inside another function.
7.  Unpacking with a Range
So I’ve decided I’m working with a range of 10, but I’ll have a set to the first value of 10, (which starts with 0, not 1, peeps) and then B can be anywhere in the range:
>>> a, *rest, b = range(10) 
>>> a 
0
>>> b 
9 
>>> rest [1, 2, 3, 4, 5, 6, 7, 8]
We could also just say we have b that’s a value anywhere in our range:
>>> *rest, b = range(10) 
>> rest 
[0, 1, 2, 3, 4, 5, 6, 7, 8] 
>>> b 
9
8. Reversing Any String
Sometimes you just need to reverse what you see.  Now for reversing searches on zipcodes, it’s very valuable to search by reversing the zipcode and index to remove “hot spots” on location searches.  The ability to reverse data easily in Python can ease this:
>>> Geocode = "80031" 

>>> print a[::-1] 

13008
9. Named String Formatting
Formatting of text is quite simple in Python.  There’s not a lot of complicated additions, just give a few parameter names and go!
print("The %(foo)s is %(bar)i." % {'foo': 'answer', 'bar':42})
The answer is always 42… 🙂
10.  Cool Mathematic Functions:
math.gcd(a)
Return the greatest common divisor, (GCD) for the value provided.
math.isfinite(b)
Return TRUE if x is neither an infinity nor a Not a Number, (NaN), otherwise FALSE.  Interesting enough, 0.0 is considered finite.
min(a), max(b)

Just as you would expect, these functions return the min and the max values for what is shown.

There are a lot more ways that make Python my favorite language to teach anyone just coming into programming, but it’s also robust enough to support an enterprise environment, too.

If you’d like to learn more, I really like the tutorials and slides from the following sites:

 

Posted in Python Tagged with:

September 2nd, 2015 by dbakevlar

So one of the things I like to do is test out a lot of my python gaming code, (as far as for the coding and syntax) on my Oracle Virtualbox image of my Raspberry Pi.  Another great thing about building games on the Raspberry Pi, is a built in module called Pygame.  Well, that doesn’t exist on the Raspberry Pi image and it really limits what we can do when it comes to the VNC build we play on the Oracle Virtualbox, (that’s a mouthful… :))

Get Outside Access

The first step is to first get out to all the libraries, as the ports the image is a bit locked down.  At the top, click on Devices, Network, Network Settings.  Add a check mark for “Cable Connected” and then click on the “Port Forwarding” settings.  Update the settings to reflect what I have for the open ports, (remember, this is Oracle Virtualbox… :))

vbox_rpi1

Once you’ve updated the Host and Guest Port, click OK.

Installing Pygame

As I want to stay with Python 3 as much as possible, we’re going to install it with our Vbox image with the Python 3 build.  Let’s start by installing:

sudo apt-get install mercurial

Choose “Y” for both questions and proceed with the installation.  There are a lot of files here, (over 500) so it will take just a few minutes to install everything.  Now, we need to run the clone step:

sudo hg clone https://bitbucket.org/pygame/pygame

Once this complete, which is just a matter of seconds, again, choosing “Y” for the questions, we need to build the dependencies after we download those:

sudo apt-get build-dep pygame
sudo apt-get install python3-dev
sudo apt-get install python3-numpy
cd pygame
sudo python3 config.py

You shouldn’t run into any failures at this step, as I didn’t with my own image.  If you do, you can go back to the first step and instead run:

sudo apt-get update

If all is successful at this point, then it’s time to build and install:

sudo python3 setup.py build
sudo python3 setup.py install

Alsa Sound Libraries

Now we need the Alsa Sound Library that isn’t in this image.  These are called by the Pygame module and come by default on Raspberry Pi, but yep, not here! You can check first to verify that they aren’t there, (if you’re curious…):

apt-cache policy alsa-base libasound2 alsa-tools

Now run the install with the following command:

sudo apt-get install alsa-utils
sudo apt-get install alsamixer

You’ll now see the ALSA sounds libraries if you run the check command again.

Now you’re ready to code Pygame games on your Virtualbox image of the Raspberry Pi! 🙂

Posted in Raspberry Pi Tagged with: , ,

August 24th, 2015 by dbakevlar

Back on August 7th, the RMOUG’s Quarterly Education Workshop, I walked everyone through using a Pibrella board to create an art or flyer project that was powered with a python script and a motor.

Today, we’re going to take that same code and reuse it with a simple robotics kit to control power and rotation speeds/time to the Insectoid.  This kit, puchased from the Go! store in Flat Irons Crossing mall, was $16 and can be built in less than an hour, even for a small child. If you’re interested, you can also purchase the kit online at Amazon, but it was cheaper for me in the store to get him than online…

insection1

It requires only a small screw driver and is powered by a AAA 1.5 volt battery.  With the power required to the motor, I recommend leaving the battery wired in and the device off, (Raspberry Pi will be glad to supplement the power and you’ll know if you’ve overwhelmed your power requirements to a secondary project just by the sudden cycle of the OS,  so keep this in mind….)

After following the instructions and assembling the gears, the body and legs to complete the robotic insectoid, test it out with the battery and power switch.  Once he tests successfully, then comes the fun part of wiring him to the Pibrella board to control him from our Raspberry Pi.

Using red and black female/male breadboard jumper wires like the ones below-

gpio_wires

Create a long black and long red “extension” to connect the insectoid to the Pibrella board.  Now, undo the cap that is connecting the battery and motor wires to the top of the Insectoid.  If the battery is wired into the motor wire in a way that makes the motor wire inseparable from it, re-wrap the battery wire to the motor wire at the base, leaving just the motor battery straight.  Take the motor battery, matching black to black and red to red, inserting the motor wire into the female jumper wire “extension” and ensure it’s tight.  You shouldn’t need any electrical tape to secure it and it should look like the following picture when you’re finished.

20150824_111525

You can re-secure the connections under the cap after you’ve added the connection to the female jumper, (as seen for the red, (negative) connector.

Once this is done, it’s time to “recycle” our python script.  Log into the Raspberry Pi and open up a Terminal window.  Review your Python script from the earlier project OR just create a new python script, (.py) in your favorite text editor and type in the following-

 import pibrella
 import time
while true:
 if pibrella.button.read():
 pibrella.output.e.on()
 time.sleep(10)
 pibrella.output.e.off()
 cleanup()

You must have a Pibrella card connected to your Raspberry Pi or you’ll need to follow instructions for controlling a motor with GPIO commands, etc. that can be found here.

The Python code does the following:

  1. imports the Pibrella module to use the Pibrella board, (you can do this with a bread board and the Raspberry Pi directly, just love the Pibrella, makes it so much easier.)
  2. import the TIME module to instruct our code how long to perform a specific function.
  3. Then-  after the button on the Pibrella is pushed
    1. turn the pibrella GPIO on and the wires attached are to run the motor.
    2. for TEN seconds
    3. Then shut off and break out.

You execute the script as we do any of our python scripts, using Python 3-

>sudo python3 <name of script>.py

A video of the run with the robotics project can be seen on YouTube.

The next step is to enhance our script and have our robot do more than just walk forward and/or stop at a certain time.  We’ll want to build out a robot to have a Raspberry Pi control board ON BOARD and control his movements to turn, go in reverse and so forth.

Until next time-

raspion

 

Posted in Raspberry Pi Tagged with: ,

August 20th, 2015 by dbakevlar

So I don’t doubt that many parents are bleeding out money for kid’s school fees, supplies, clothing and other demands this time of year.  How many of you are in their local Target, Walmart or other store and after filling the cart with the necessary, the kids eye up the toy aisle and start to ask for something?

Even teens are not immune and may be asking for games.  If you could turn around and say to them, “If you want the game, then why don’t you build it instead of buying it?”

Now as many of you have figured out, I’m starting to build an arsenal of Raspberry Pi content to teach in classes and meetups.  The following is to simulate the game “Pass the Pigs”.  If you’ve ever played this popular game that uses plastic pigs in the place of dice, it required my brain to rethink how I was coding my dice games to how I would code a game that used the fall placement of a plastic pig.  This demonstrated one of the greatest things about Python-  I still was using the same module, but I just used it in a different way to code my new game!

So let’s say we want to code a simple roll of dice game.

#Dice Roll
import random
#Insert space between import and code...
for x in range(1, 2):
dice_1 = random.randint(1, 6)
dice_2 = random.randint(1, 6)
print(dice_1 + ' + ' + dice_2)

The above code will do the following:

  1. Import the RANDOM module.
  2. Will “roll” the dice 2 times
  3. Will use two dice, with random calls of 1-6.
  4. Will output the first dice ‘+’ the second dice.

Now to change the code and create the Pass the Pigs game, we get to use the RANDOM module again,  but the code changes as we are going to use a function to tell Random what “word options” will be used instead of random numbers to return.  It will then use two pigs and then will output the roll, (which is a function).

#Pass the Pigs
import random

pig_fall = ['Razorback', 'Trotter', 'Snouter', 'Leaning Jowl', 'Pig Out', 'Oinker']
def pick_pigs():
        Pig1 = random.randint(0, len(pig_fall) -1)
        Pig2 = random.randint(0, len(pig_fall) -1)
        return pig_fall[Pig1] + ' + ' + pig_fall[Pig2]
print (pick_pigs())

This code is different from the first one, even though it really ends up doing the same thing.  Notice that there are six options, just like there are six sides to a die.  This is really very similar to the dice game, we’ve just used different code that works more efficiently with our requirements.  By execution the code, we can then play the game!

>sudo python3 <script_name>.py
Leaning Jowl + Pig Out

Trotter + Pig Out

Leaning Jowl + Razorback

We can use the game instructions, (can be found online) to then add up our scores for our three players-

passthepigs

So there you have it and next time your kids ask you for toys and games, consider getting them a Raspberry Pi instead and make it pay forward, creating projects and games with it instead!

Until next time…

raspion

 

 

Posted in Raspberry Pi Tagged with: ,

August 18th, 2015 by dbakevlar

There’s an old joke about the evolution of a programmer. It starts with the programmer in their infancy and typing:

Print “Hello World” and so the output returns:

helloworld

The programmer continues to evolve. His coding knowledge increases and his code in the end of his evolution becomes a script of 5000 to 10,000 lines. What does the output return? You guessed it:

helloworld

I often joked that I’d make a terrible developer. I over think everything, but the truth is, I may have just evolved too much and need to devolve to improve. There used to be a sign up on my door of my office years ago, put there by an Operations Manager that read-

Go away before I write an efficient script to replace you.

It wasn’t far off from the truth. My shell scripts made the world go round, but they also were built with a certain mindset design. There was almost always a wrapper shell script that called subsequent scripts to perform different tasks and arguments to do what was expected. This was the design and mindset of shell scripting I’d been taught by a great scripting teacher.

Now that I’ve been working in Python for the last four months, I’ve had to admit to myself that my mindset has to change. I need to move to the Pythonic way of thinking. What is Pythonic thinking?  It is the particular style that has emerged over time trhough experience using the language by those that know it best.  This challenge is also quite normal for anyone coming to Python. Doesn’t matter if the programmer is skilled at Java, C++ or Ruby Rails, they all go through it. Python is very efficient, but below, you’ll find a perfect example of how one can really work hard instead of smart, i.e. the Pythonic way.

Coding Hard, Not Coding Smart

For my latest project, after noting the lights and built in sounds for the Pibrella board add-on for the Raspberry Pi, I decided I wanted to create a gaming script that when combined with kids imagination, could be used in a variety of ways. The game, “Red Light, Green Light” was the source of the inspiration.

The requirements were as follows:

  1. Use the lights on the board to have different variations and times lit to mark movement.
  2. Use different sounds in conjunction with the lights to signal a change or an alarm when the game play must stop, (i.e. red light.)
  3. The game play must be random so that the players wouldn’t know which light would execute, (green for go, yellow for slow motion and red for stop movement) without human intervention.

Now I created the initial script to test the process without issue. I used the Pibrella and time modules-

import pibrella
import time

#start game with success and green light. During green, (25 seconds) people will move as fast as want.
pibrella.buzzer.success()
time.sleep(3)
pibrella.buzzer.off()
pibrella.light.green.on()
time.sleep(25)
pibrella.light.green.off()
pNow lets go in slow motion. Signal the yellow alarm and then light for 15 seconds of slow motion movement.
pibrella.buzzer.buzz( frequency )
pibrella.buzzer.note( 1 ) #this is the frequency for the Note A
time.sleep(2)
pibrella.buzzer.off()
pibrella.light.yellow.on()
time.sleep(15)
pibrella.light.yellow.off()
#Now for a stop movement or red light in the game.
pibrella.light.red.pulse(2,4,2,1) #we’ll make the light pulse instead of just light up
pibrella.buzzer.fail()
time.sleep(2)
pibrella.buzzer.off()
pibrella.light.red.off()

 

Now this seems pretty straight forward, but now I wanted to add in the logic to have random runs on times and variations of colored light sequence. I started by duplicating the script and adding in different rotations and time. I planned on six different scripts with different amount of time included in it and rotations…about 150 lines of code when I finished.

Why? Because this is how I would have built in the logic to Shell scripts. I would have had a wrapper script that would call the other scripts to run different rotations to keep the players on their toes.

What’s the problem with this logic? It’s not the Pythonic way of doing things- secondary scripts called from a main script and adds to complexity that doesn’t belong in the code. It’s also the wrong way to teach python coding and would have added confusion to the class.

So how should these requirements be coded?

Pythonic Smart Instead of Coding Hard

The latest Python script looks very different from the first and it includes everything in one script, using three modules. I’ve added the Random module, which allows me to build out a random number generator that acts like a throw of a dice. Depending on the results, a different light and duration occurs. I chose six variations, three green, two yellow and one red. With the red, (throw on a six) there is a break to leave the execution of the script, but the code is built to run for 30 times as is.

import random
import pibrella
import time

for x in range(1, 31): #run for 30 iterations
   dice_1 = random.randint(1, 6) #options, just like a die.
   if dice_1 == 1:
       pibrella.buzzer.success()
       time.sleep(3)
       pibrella.buzzer.off()
       pibrella.light.green.on()
       time.sleep(25) #green for 25 seconds
       pibrella.light.green.off()
   if dice_1 == 2:
       pibrella.buzzer.success()
       time.sleep(3)
       pibrella.buzzer.off()
       pibrella.light.green.on()
       time.sleep(15) #green for 15 seconds
        pibrella.light.green.off()
   if dice_1 == 3:
       pibrella.buzzer.success()
       time.sleep(3)
       pibrella.buzzer.off()
       pibrella.light.green.on()
       time.sleep(10) #green for 10 seconds
       pibrella.light.green.off()
   if dice_1 == 4:
      pibrella.buzzer.note( 1 ) #solid note for tone
       time.sleep(2)
       pibrella.buzzer.off()
      pibrella.light.yellow.on()
       time.sleep(25) #yellow for 25 seconds
       pibrella.light.yellow.off()
   if dice_1 == 5: 
      pibrella.buzzer.note( 1 ) #solid note for tone
       time.sleep(2)
       pibrella.buzzer.off()
       pibrella.light.yellow.on()
       time.sleep(15) #yellow for 15 seconds
       pibrella.light.yellow.off()
   if dice_1 == 6:
       pibrella.light.red.pulse(2,4,2,1) #red, you’re done!
       pibrella.buzzer.fail()
       time.sleep(2)
       pibrella.buzzer.off()
       pibrella.light.red.off()
       break #escape out of the loop

What the Code Does

This code now randomly runs different variations of green and yellow with their notifying buzzer, up to 30 times or until it results in a “6”, which then will alarm, pulse the red light and exit out of the script. No other scripts or logic is required because I coded it with the Pythonic way of thinking.

To execute the code, looks like this:

sudo python <script_name>.py

Playing a Game with the Code

So what does this code look like when I remove the extended times in the lights so the random generations goes at an accelerated rate of change between each?

Just like this video

Now I want you to imagine playing the game of Musical Chairs to this. Green means go fast for the time elapsed, (10, 15, 20 or 25 seconds…) Yellow requests all the players must go in slow motion, (which is also amusing for the spectators… :)) and then the red light, (and alarm) signifies everyone tries to immediately find a seat before there isn’t one left!

In a larger room, you could use it to play “Red Light, Green Light”.  You could still expect the players to go in slow motion during the yellow iterations and just as in the standard game, anyone still moving when the alarm and red light go off, must return to the starting line.

The completion of the project, after working with the kids to create the code, test and verify, is then to ask them to use their imagination on how they would use the code or enhance it to play other games.  The random libraries could easily be used for dice games, displaying the role and even incorporate more than one die for the game.

Until next time…

raspion

Posted in Oracle, Raspberry Pi Tagged with: ,

  • Facebook
  • Google+
  • LinkedIn
  • Twitter