Restrict date range within DatePicker component

So I had to restrict days in the WPF DatePicker component. Only the days falling within a specific range should be available for selection and all others (past & future values) should be disabled.

The solution is to use the DisplayDateStart & DisplayDateEnd properties on the DatePicker

<DatePicker Name="dtPicker"
    DisplayDateStart="5/10/2012"
    DisplayDateEnd="5/20/2012" />

0  

N-dimensional aka N-ary Tree

N-dimensional tree is used to represent the UI of any application. Buttons, ComboBoxes and various other components are assembled together in this data structure and then rendered on the screen.

I had to enhance the design of a commercial Tree UI component (add improved searching features) and thought of creating my own n-ary Tree data structure to hold the data which will be passed into the Tree UI component.

class Node(object):
    
    def __init__(self, **kwargs):
        self.value      = kwargs.get('value')
        self.children   = []

    def __str__(self):
        return 'Val: {0} Children: {1}'.format(self.value, self.children)

    def __hash__(self):
        return hash((self.value, self.children,))

    __repr__ = __str__

class nAryTree(object):

    def __init__(self):
        self._root = Node()

    def getRoot(self):
        return self._root

    def insert(self, data):
        self._insertValues(data, self._root)

    def _insertValues(self, data, currNode):
        if not data:
            return
        
        if currNode and not currNode.value:
            tmpChild = None

            for child in currNode.children:
                if data[0] == child.value:
                    tmpChild = child
                    break

            if tmpChild:
                self._insertValues(data, tmpChild)
            else:
                newNode = Node(value=data[0])
                currNode.children.append(newNode)
                self._insertValues(data, newNode)
        else:
            if len(data) > 1:
                tmpChild = None

                for child in currNode.children:
                    if data[1] == child.value:
                        tmpChild = child
                        break
                
                if tmpChild:
                    self._insertValues(data[1:], tmpChild)
                else:
                    newNode = Node(value=data[1])
                    currNode.children.append(newNode)
                    self._insertValues(data[1:], newNode)

    def show(self):
        self.showContainer = []
        self._showTree(self._root)

    def _showTree(self, currNode):
        if currNode and not currNode.value:
            print '*Root'
        else:
            self.showContainer.append('--')
            self.showContainer.append(currNode.value)
            print ''.join(self.showContainer)
            self.showContainer.pop()
            self.showContainer.pop()

        if currNode and currNode.children:
            self.showContainer.append('  |')
            print ''.join(self.showContainer)
        
        for child in currNode.children:
            self._showTree(child)

        if currNode.children and self.showContainer:
            self.showContainer.pop()

    def deleteNode(self, tgt=''):
        searchContainer = []
        result          = {}
        res             = self._search(self._root, tgt, searchContainer, None, result)
        parentNode      = result.get('parentNode')

        for idx in xrange(len(parentNode.children)):
            if parentNode.children[idx].value == tgt:
                del parentNode.children[idx]
                break

        return searchContainer[1:]

    def searchTree(self, tgt=''):
        searchContainer = []
        res             = self._search(self._root, tgt, searchContainer)

        return searchContainer[1:]

    def _search(self, currNode, tgt, path=[], parentNodeOfTgt=None, result={}):
        if (not tgt and tgt.strip()) or not currNode:
            return False

        if currNode.value == tgt:
            path.append(currNode.value)
            result['parentNode']    = parentNodeOfTgt
            result['tgtNode']       = currNode
            print 'Path: {0}'.format('>'.join(path))

            return True
        else:
            path.append(currNode.value if currNode.value else 'Root')
            for child in currNode.children:
                if self._search(child, tgt, path, currNode, result):
                    return True
            else:
                path.pop()

    def nestedTuples(self):
        data = self._naryToNestedTuples(self._root)
        return data[1] if data else ()

    def _naryToNestedTuples(self, t):
        return (t.value, tuple(map(self._naryToNestedTuples, t.children)), ) if t.children and isinstance(t.children, (tuple, list,)) \
            else t.value

    def nestedLists(self):
        data = self._naryToNestedLists(self._root)
        return data[1] if data else []

    def _naryToNestedLists(self, t):
        return [t.value, map(self._naryToNestedLists, t.children)] if t.children and isinstance(t.children, (tuple, list,)) \
            else t.value

def main():
    tree = nAryTree()
    tree.insert(('A', 'B', 'C', 'D',))
    tree.insert(('A', 'B', 'C', 'E',))
    tree.insert(('A', 'B', 'F', 'X',))
    tree.insert(('A', 'B', 'C', 'Y',))
    tree.show()

    print '\nSearch result for {0}: {1}\n\n'.format('X', tree.searchTree('X'))

    print 'Accounting Organizational Structure'
    # http://www.chesterfield.gov/uploadedImages/Department_Information/Management_Services/Accounting/Media/Images/Accounting%20Organizational%20Structure.jpg?n=5909
    tree2 = nAryTree()
    tree2.insert(('Director',))
    tree2.insert(('Director', 'Financial Services & Grants Coordinators',))
    tree2.insert(('Director', 'Assistant Director-I',))
    tree2.insert(('Director', 'Assistant Director-I', 'Financial Systems Section',))
    tree2.insert(('Director', 'Assistant Director-I', 'General Accounting Section',))
    tree2.insert(('Director', 'Assistant Director-II',))
    tree2.insert(('Director', 'Assistant Director-II', 'Accounts Payable Section',))
    tree2.insert(('Director', 'Assistant Director-II', 'Payroll Section',))
    tree2.insert(('Director', 'Assistant Director-II', 'Administration Section',))
    tree2.show()

    print '\nSearch result for {0}: {1}\n\n'.format('Payroll Section', tree2.searchTree('Payroll Section'))
    raw_input()

if __name__ == '__main__':
    main()

 

Output >>

*Root
  |
  |--A
  |  |
  |  |--B
  |  |  |
  |  |  |--C
  |  |  |  |
  |  |  |  |--D
  |  |  |  |--E
  |  |  |  |--Y
  |  |  |--F
  |  |  |  |
  |  |  |  |--X
Path: Root>A>B>F>X

Search result for X: ['A', 'B', 'F', 'X']


Accounting Organizational Structure
*Root
  |
  |--Director
  |  |
  |  |--Financial Services & Grants Coordinators
  |  |--Assistant Director-I
  |  |  |
  |  |  |--Financial Systems Section
  |  |  |--General Accounting Section
  |  |--Assistant Director-II
  |  |  |
  |  |  |--Accounts Payable Section
  |  |  |--Payroll Section
  |  |  |--Administration Section
Path: Root>Director>Assistant Director-II>Payroll Section

Search result for Payroll Section: ['Director', 'Assistant Director-II', 'Payroll Section']
1  

Achieving optimal performance in code

Is there any difference between the following two expressions\statements?

def func1(a):
    return a == 'TRUE'
def func2(a):
    return True if a == 'TRUE' else False

Well, both of them do the same thing but interestingly, the former one is faster in terms of performance by atleast one CPU cycle! Let’s tear into assembly language of each of these funcs to see the real difference …. Smile

Assembly of Func1 >>

  2           0 LOAD_FAST                0 (a)
              3 LOAD_CONST               1 ('TRUE')
              6 COMPARE_OP               2 (==)
              9 RETURN_VALUE

Assembly of Func2 >>

  2           0 LOAD_FAST                0 (a)
              3 LOAD_CONST               1 ('TRUE')
              6 COMPARE_OP               2 (==)
              9 JUMP_IF_FALSE            5 (to 17)
             12 POP_TOP
             13 LOAD_GLOBAL              0 (True)
             16 RETURN_VALUE
             17 POP_TOP
             18 LOAD_GLOBAL              1 (False)
             21 RETURN_VALUE

JUMP_IF_FALSE evaluation takes the extra cpu cycle in this case.

0  

Logging in Java, C# and Python

In Java & C#, the most commonly used logging utilities are log4j and log4net. Python has it’s own inbuilt logging module which includes the exact same features as other log4X brethren!

Setting up logging module in python >>

import logging

def initLogger(appName='Application', handlerType='StreamHandler', \
    loggerLevel='INFO', handlerLevel='DEBUG'):
    '''
        * There are many handler types available such as >>
            StreamHandler
            FileHandler
            RotatingFileHandler
            TimedRotatingFileHandler
            SocketHandler
            DatagramHandler
            SysLogHandler
            NTEventLogHandler
            SMTPHandler
            MemoryHandler
            HTTPHandler

            You may have to customize this func to use other handlers.

        * Many levels available such as >>
            debug
            info
            warning
            error
            critical
    '''
    # Creating the logger object
    log = logging.getLogger(appName)
    log.setLevel(getattr(logging, loggerLevel))

    # Initializing logging settings in handler
    handler = getattr(logging, handlerType)()
    handler.setLevel(getattr(logging, handlerLevel))
    handler.setFormatter(logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s'))

    # binding the handler to Logger object
    log.addHandler(handler)

    return log

def main():
    logger = initLogger('Test App')
    logger.info('Hello World!')

    raw_input()

if __name__ == '__main__':
    main()

More information found at >> http://onlamp.com/pub/a/python/2005/06/02/logging.html

Setting up logger in C# >>

You’ll need to create a configuration file (similar to the one below) and then define a logger instance in Code mapped to the configuration.

More information can be found >> http://logging.apache.org/log4net/release/manual/configuration.html

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net"
       type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>
  <log4net>

    <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
      <param name="File" value="c:\LogTest2.txt" />

      <param name="AppendToFile" value="true" />
      <param name="rollingStyle" value="Size" />

      <param name="maxSizeRollBackups" value="10" />
      <param name="maximumFileSize" value="10MB" />
      <param name="staticLogFileName" value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%d [%t] %-5p %c %m%n" />
      </layout>
    </appender>

    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender" >
      <layout type="log4net.Layout.PatternLayout">
        <param name="Header" value="[Header]\r\n" />
        <param name="Footer" value="[Footer]\r\n" />
        <param name="ConversionPattern" value="%d [%t] %-5p %c %m%n" />
      </layout>
    </appender>

    <root>
      <level value="ALL" />
      <appender-ref ref="LogFileAppender" />
      <appender-ref ref="ConsoleAppender" />
    </root>
  </log4net>
</configuration>
0  

Implementing a Stack in python

To implement a Stack in python, we simply need to extend the existing list class! Winking smile

class Stack(list):

    def push(self, data):
        self.append(data)

    def tos(self):
        if self:
            return self[-1]

    def peek(self, index):
        if self and 0 <= index < len(self):
            return self[index]

    def __iter__(self):
        if self:
            ptr = len(self) - 1
            while ptr >= 0:
                yield self[ptr]
                ptr -= 1

def main():
    st = Stack()
    st.push(10)
    st.push(20)
    st.push(30)
    st.push(40)
    st.push(50)

    for x, y in enumerate(st):
        print 'Index: {0} Value: {1}'.format(x, y)

    print '\nTop of Stack: ', st.tos()

    print '\n'
    for x in xrange(6):
        print 'Deleting ', st.pop()
        # will throw exception in the last iteration since only 5 items are in stack

    raw_input()

if __name__ == '__main__': main()

Output >>

Index: 0 Value: 50
Index: 1 Value: 40
Index: 2 Value: 30
Index: 3 Value: 20
Index: 4 Value: 10

Top of Stack:  50

Deleting  50
Deleting  40
Deleting  30
Deleting  20
Deleting  10
IndexError: pop from empty list
Press any key to continue . . .
0