Thursday, February 5, 2015

HOWTO Create lockfile logic using BATCH language

Overview

The goal of this HOWTO is to show how to manage a lock file in batch language. This is handy for scheduled processes.

Example

@echo off
REM
REM Example of howto use a lockfile in BATCH language
REM

:INIT
CD \BatchJobs
ECHO Current Working Directory
CD

:START
IF EXIST NIGHTLYRUN.LOCK GOTO SKIP_WORK
ECHO Turning on Lock
ECHO ""LOCK"" > NIGHTLYRUN.LOCK
REM Do work here. this is where your program or process goes. 
ECHO Turning off Lock
DEL NIGHTLYRUN.LOCK

GOTO DONE

:SKIP_WORK
ECHO ""This process is already running..""

:DONE

Conclusion

Using this approach you can prevent multiple instances of something running. A possible enhancement is something that can sense a stale lock if there is a crash or something. however this should help for most situations.

HOWTO Python Setup UNICODE Logging

Overview

Python does a very good job handling UNICODE for most modules, however, logging is not one of then. To get around this is easy but a special technique is required.

Common Approach

Normally with logging you pass a file to the logger and then write to it as you need though the logger interface. This approach is fast but does not allow the setting of the file encoding.
import logging
logging.basicConfig(
    level=logging.DEBUG,
    filename=filename,
    filemode="w")

formatter = logging.Formatter('%(asctime)-15s: %(levelname)-7s - %(message)s')
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(formatter)

log = logging.getLogger("MAIN")
log.addHandler(ch)
_logger = log

Improved Approach

To get around this and to ensure you control the formatting, a file stream will need to be created first and then that stream can be passed to logger.
import logging
import logging.handlers
log_fh = open("/logs/my_unicode.log", "w", encoding="utf-8")
logging.basicConfig(
    level=logging.DEBUG,
    format=config.FORMAT)

formatter = logging.Formatter('%(asctime)-15s: %(levelname)-7s - %(message)s')
ch = logging.StreamHandler(log_fh)
ch.setLevel(logging.DEBUG)
ch.setFormatter(formatter)

log = logging.getLogger("MAIN")
log.addHandler(ch)
The log_fh holds the handle to the UTF–8 stream which is passed to the logger StreamHandler. Once set, text will be properly encoded as it is passed to the logger.

Conclusion

Using a slightly altered technique it should be possible to write anything to a python log using the build in logger module. There is no reason to use this technique for all logging even if you do not think UNICODE will be used.

Sunday, February 1, 2015

HOWTO Add/Subtract Days or Time

Objective

Show different database techniques for determining the date in the past (or future). The following will show you HOWTO get three days ago based on CURRENT_TIMESTAMP. All will generate something like this.
CurrentTime ThreeDaysAgo
2015–02–01 11:42:04 2015–01–29 11:42:04
Below you will find information MySQL, SQL Server, SQLITE3, and PostgreSQL.

MySQL

Using MySQL, take a timestamp DB property (like CURRENT_TIMESTAMP for “now” or a property from a table). Then add + or - followed by the keyword INTERVAL. Then a number followed by a unit like day if you (for example) want to add or subtract a certain amount of days. The fllowing code subtracts three days from now.
mysql> SELECT CURRENT_TIMESTAMP as CurrentTime,
         CURRENT_TIMESTAMP - INTERVAL 3 day as ThreeDaysAgo;
For More Information

Microsoft SQL Server

Using SQL Server, the end result is the same but they use a function to do the same thing. Using the DateAdd function, you specify a unit, quantity, and DB property. In the following example I use “now” and subtract three days from it.
SELECT CURRENT_TIMESTAMP as CurrentTime,  
    DateAdd(day,-3,CURRENT_TIMESTAMP) as ThreeDaysAgo;

SQLITE3

For SQLITE, you need two wrapper the date time property in the datetime(…) function with a paramter telling it what manipulations you would like to do. In this case, I want to do subtract three days.
sqlite> SELECT CURRENT_TIMESTAMP as CurrentTime, 
datetime(CURRENT_TIMESTAMP, '-3 days') as ThreeDaysAgo
For More Information

PostgreSQL

I have not had a chace to work this out for postgresql yet.
For Information on this point visit

Conclusions

Using the above syntax, you will be able to manipulate dates to add or subtract time as your code requires.

Thursday, October 4, 2012

Alex Lifeson as Greatest Guitar Player of All Time

I don't typically do this but I a am a pretty big fan of RUSH.   They have always produce cool and interesting music.

Recently "Guitar World" magazine decided to have a poll for the "Greatest Guitar Player" of all time.  If you have a minutes, hop online and vote for him.  


He has always been underestimated as far as influence and ability.   If you can, please vote.

Tuesday, March 15, 2011

Jetbrains PyCharm Simply Rocks - Initial Impressions

Overview
I have not had time to write a blog about PyCharm yet. With 1.2 released today, I have had only good experiences with it. Since the first 1.0 release, I have worked on 7 different projects using it.
  • New projects
  • Import existing projects
In all cases, my projects
  • Use the standard python unittest
  • Are stored and managed using Subversion.
Unit Test Integration
About as simple as it gets. PyCharm gives you a lot of flexibility. You can flag a folder as a "test" folder. When you right click, you can Mark Directory As "test" which will turn the folder "green".

If you want to execute all tests, simply right click on the folder and Run "Tests in...." menu option.

If there is a single file of tests you want to run, simply right click on the file and Run the file.

In both case, a nice panel that pops up showing you the test progress. There is a filter that can be turned on or off allowing you to see all test results or just the failed ones. Visual queue help you know how well things are going.

Since Python is fast to run/re-run, I get in the habit of adjusting code and re-running my tests. The unit test module lets you do this by simply clicking on a green double triangle icon in the left side of the Run panel. This is very handy.

This feature is clean and simple to use.

Subversion
Importing and checking out code works as expected. As code is developed, PyCharm provides a "Changes" panel that you can view to see what files are modified.

By right clicking on a folder or file, you can Commit your changes. In reverse, to update your local working copy, you can update a file or folder.

The UI provides clear feedback as to what it is doing in both cases, and lets you know what version your working copy is.

Inspections
I did an experiment. How good is the advice PyCharm provides to improve your code? I took an old project I wrote and imported it into PyCharm. The old code was written using emacs and not much else.

I address all of the suggestions provided by the PyCharm's code Inspection. I was surprised by the sense many of the changes suggested. In my experience, the suggestions provided did not break or cause issues in my code.

It is possible to fine tune the suggestions in the settings/preferences. The options provided are very detailed (in my mind).

Python Interpreter
PyCharm lets you configured one or many version of python. Adding a new version is pretty easy. If you don't have a project open, you can set the default interpreter in the settings/preferences. If you have a project open, you can set the interpreter version for the open project.

Final Thoughts
These are just a few items of many productive features within PyCharm. I am very happy with what I have been using so far. In just about all cases, I have not needed to use any of the docs. It just works the way I would expect it to behave.

I want to try Django support next. But that is for a future blog.