Saturday, October 10, 2015

Learning Python

Python is one hell of a programming language. The flexibility with if statements, for example, is amazing. There's so many ways to do things.  More than this, but just to demonstrate the flexibility of being able to say:

if (this or that) or (not this and not that) or (that and not this)
    doSomething()
else:
    doSomethingElseEntirely()


.. is just plain liberating, from a programming point of view. To do that in bash, you'd probably have to do something like:

this = "true" 
that = "true" 
if [[ this == true && that == true]]
then
     do_STUFF()
elif
     [[that == true]] && [[this != true]]
else
     do_MORE_STUFF()
fi 

But than again, BASH will evaluate anything and everything as true, and there's also a /bin/true and /bin/false floating around, so that is not the most reliable code.. So we ought to use arithmetical operations:

#!/bin/bash

false=0
true=1

((false)) && echo false
((true)) && echo true
((!false)) && echo not false
((!true)) && echo not true


Python, however, is much more forgiving when it comes to boolean stuff (but not forgiving at all regarding indentation...) It also makes great use of parameter expansion. How many different ways can you calculate leap years? At least two that I know of. (Some kid in my class was asking for help with this one, so here ya go..)

########################
#!/usr/bin/env python  #
# Leap Year Calculator #
########################

# Declaring error messages here is a lot prettier than everywhere
erNocomp = ("Sorry... that doesn't compute!")
mathIsBroken = ("Something is terribly wrong here! Bailing!")

# Python does not seem to understand unset variables outside of functions so #declare them here:
year = ""
##########
# exit cleanly. got sick of programs crashing upon completion
def exit_0():
    while True:
        try:
            x = input("Press Ctrl + c to quit ")
        except KeyboardInterrupt:
                break
                exit(0)  
  
#

print("""
######################
# Is it a leap year? #
######################

"""
)
# Another library we can use to save some code
import calendar
# 1 will always equal 1; 1 will always return true.

# This is the standard way to validate input. Here we're just saying "till the  

# end of time, or until y = an integer, keep asking for input"
 while 1:
    try:

        y = int(input("Please enter a year...: "))
        break
    except ValueError:("That's not a year!")
    print (erNocomp)
    

#
# This is how to calculate leap years manually, because that was the assignment:

# I feel this is pretty straightforward...
#
# def isLEAP(year):
      return (y % 4 == 0 and y % 100 != 0) or (y % 400 == 0)
#
#   if
isLEAP(year):
#       print ("%s is a leapyear." % y)
#   elif not isLEAP(year):
#       print ("Nope")
#
# but its better to trust the calender library that's already meticulously #written.. this is another thing about python that I totally love-- all these #built in functions like isLeap(year) or toRoman(int) to calculate roman numerals

#
# I can pull it off using the math and the library in one if statement,
 

# for the sake of ultimate reliability.
#
######## Note how to combine variables and strings in output:

isOrIs = ("Python or math says %s is a leap year!" % y)
isntAndIsnt = ("Python and math says %s is not a leap year!" % y)
## Prepare for Transdimensional Scenarios
isAndIsnt = ("Python says it's a leapyear, math says not. What universe is this?")
isntAndIs = ("Python says it's not a leapyear, math says it is. What's going on here?")
#########
# Here I'm asking "does the math check out, and does calendar also say it's so?
#

if calendar.isleap(y) or
isLEAP(year):
    print(isOrIs)
    if
calendar.isleap(y) and not isLEAP(year):
        print (isAndIsnt)
    elif not
calendar.isleap(y) and isLEAP(year):
        print (IsntAndIs)
elif not
calendar.isleap(y) and not isLEAP(year):
    print (isntAndIsnt)
else:
    print(mathIsBroken) # just in case the universe ends or whatever
    exit(1)

#
# figured i needed a clean exit func at some point
#
exit_0()

# not a whole lot different than doing
# exit(0)
# just catches the traceback errors


Fun stuff, right? I've decided to post all my python homework scripts on Github, (after the due date, of course!) on the off chance someone learns something from them, but also for own record... Github is very reliable for backing up code and discs tend to fail as per Murphy's law...

That's all for today, folks. BTW does anyone have a CSS script or API for proper python colour coding? That'd be great.

Friday, October 9, 2015

How to Not Have One of *Those* Days

Did you feel a bit groggy after your alarm clock awoke you this morning? Did you roll over and say "Can't do it..", than snooze through 3 ten minute cycles causing you to have to rush out the door? That was how one of my mornings went last week, and the reason that happened is because I forgot to turn on sleep-tracking on my phone before I went to bed. There is this ingenious app called Sleep as Android, in case you have not heard of it, that utilizes your phones accelerometer to track your sleep patterns.

Don't follow? Sleep cycles are directly correlated with movement. Accelerometers are sensors that detect motion, and they're quite sensitive. So, if you put the phone on your mattress when you go to bed, the accelerometer can track movement, hence tracking sleep cycles. I read somewhere that this is almost as accurate as what the doctors use when conducting a sleep study, although I can't confirm that. However, I can confirm that when the app wakes me up, rather than a sleep-cycle naive alarm clock, I feel much more refreshed. I also got used to waking up feeling that way, and it really sucked waking up during deep sleep the other day.

I am groggy all day if I am awoken at the wrong time... This app has enabled me to function while adjusting from getting up at 3 PM to 6:40 AM over the last couple months. It's totally worth a try. It's also interesting to analyse your sleep patters, as the app nicely graphs it all out. You can also record noises to figure out what's waking you up, or detect snoring, etc.

This is the quantum age, and incredible technological advances are also improving quality of life. Smart phones are just computers with lots and lots of sensors, consequently they can be used for obscure purposes. I wonder what my phone will do next year? They used to say the sky is the limit. But we're way past the sky, as the space age started over 50 years ago. There are no more limits. Don't let an old fashioned alarm clock slow you down, try Sleep as Android. No, I was not paid to write this, I just think you ought to know.