Python – DBAKevlar https://dbakevlar.com Making Technology Bulletproof Mon, 11 Dec 2023 22:49:12 +0000 en-US hourly 1 https://dbakevlar.com/wp-content/uploads/2019/06/cropped-dbakevlar_twt_logo2-1-32x32.jpg Python – DBAKevlar https://dbakevlar.com 32 32 Festive Tech Calendar 2023 https://dbakevlar.com/2023/12/festive-tech-calendar-2023/ Mon, 11 Dec 2023 22:00:19 +0000 https:/?p=9894 It’s almost my turn to present my video this year on December 13th, for the 2023 Festive Tech Calendar.  I chose to do something fun vs. something about the cloud or databases, etc.

This blog post has all the support info on the spinning Xmas tree, along with the RPI playing Xmas music and flashing Xmas colored lights, while the video goes into everything about the Raspberry Pi, why contribute to this year’s event donation and my project demo.

Project Goal

To use a Lego Xmas tree, attach it to a DC motor and use code with a Raspberry PI and a Pibrella RPI hat to light it up, spin it and play Xmas music.

Supplies

  • Raspberry Pi (Version 3B or above)
  • Adafruit’s Pibrella hat(just a personal preference) Even though no longer made, you can still purchase them on eBay for $10-20 and one of my favorite additions to a RPI
  • Connector wires for DC Motor if not already installed
  • DC Motor
  • Pibrella,Monitor/screen, Mouse, keyboard/touchscreen
  • Power supplies for RPI, pibrella and monitor.
  • Legos for Xmas tree and base- design is up to creator.
  • Adhesive to attach lego connector to DC Motor. I used gorilla glue.

Could also build a “Lego cage” or have the tree separate from the RPI.  My goal was to ensure the tree was secure as it spun so it wouldn’t fall over, but after my original motor burned out, I was unable to locate one that didn’t have a substantially faster rotation on the spin.  This caused me to change up my code from just spinning to a pulse, but still had issues with the tree spinning off of the base due to the faster rotation.

Software

  • Debian or other Linux distribution
  • Python 3.x
  • Libraries:
  • Pibrella, (as I’m using the Pibrella hat, if not, you will need to use a bread board or other component and the libraries to control lights and motor.)
  • Time
  • Signal
  • system used mplayer with subprocess.
  • Mp3 downloaded song from the web of Christmas song.

Code

Play_holiday.py

#/usr/bin/env python

######################################################
#Script to spin Xmas tree and play music and lights
#Kellyn Gorman, Silk.us
#Date: 12/1/2023
#MP3 should be saved in same folder as the script
######################################################

import os
import time
import pibrella
import subprocess

def firstrun():
    player = subprocess.Popen([“mplayer”, “jingle_bells_178759.mp3”, “-ss”, “30”], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    while True:
        pibrella.light.pulse(1,1,1,1) #flash lights slowly on pibrella
        time.sleep(2)
        pibrella.output.e.pulse(.5,1) #spin motor
        time.sleep(30) #music and tree spinning time match
    pibrella.output.e.off() #shut everything back off
    pibrella.light.off
    player.stdin.write(“q”)

firstrun()
quit()

Challenges

As I haven’t worked with Raspberry PI is a few years, it took me some time to get everything up and running.  I ended up having to reload the image to a newer OS, build out and install the necessary libraries needed for the project and then came to designing the project pieces.

I was able to get the 2023 Xmas tree from my local Portland Bricks store, but I had to redesign it to have a base that could be attached to a DC motor, which proved to be more challenging.  I simply didn’t have a lego that would attach and have significant locking to keep the Xmas tree steady while it spun.  If I’d had more time, I might have been able to, but not with the part-time allocation I’d given myself.

The secondary challenge was around the DC motor.  Not all motors are the made the same and my first motor was perfect for the application-  spinning slow and consistent, it was excellent for the project, but then, after gluing the Lego attachment, I inadvertently got adhesive into the top of the motor and it became glued in place!  I tried two subsequent motors, the first had challenges attaching to the tree securely and the second I ended up using, but the speed on both were upwards of ten times faster rotation than the original, impacting the ability of the Lego Xmas tree spinning apart!

If I had more time, again, I would search out for a motor like the first one I had, but they seem less available. 

Raspberry Pi Information

For those interested in getting a Raspberry Pi setup, but need more info that the video offered, check out the following comparison data and links to RPI recommendations:

Comparing Raspberry Pi Versions:

https://socialcompare.com/en/comparison/raspberrypi-models-comparison

Raspberry Pi Kit Recommendations:

  • RasTech RPI 4 Starter Kit, include 64G Micro SD Card, power supply, cables, etc.  $99.79 https://a.co/d/iSEjarD
  • Sunfounder Start Kit FOR RPI 4/4B, (RPI not included!). 87 projects, tutorials, etc. $46.99 https://a.co/d/9nI34Uv
  • SunFounder RPI Pico Ultimate Kit for the project geek, 320 items, 113 projects, $58.88 https://a.co/d/bCZIVSA

The time for the today’s reveal is above, and do watch to see if I succeed or explode the Xmas tree!

]]>
10 Things I Love About Tech- Python Edition https://dbakevlar.com/2017/05/10-things-love-tech-python-edition/ Fri, 05 May 2017 20:19:19 +0000 https:/?p=6739 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:

 

]]>