<commit_before># Copyright 2012 Google Inc.  All Rights Reserved.
# vim: set ts=4 sw=4 et sts=4 ai:
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License.  You may obtain a copy
# of the License at: http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distrib-
# uted under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
# OR CONDITIONS OF ANY KIND, either express or implied.  See the License for
# specific language governing permissions and limitations under the License.

"""Quick and dirty debugging output for tired programmers.

All output goes to /tmp/q, which you can watch with this shell command:

    tail -f /tmp/q

If TMPDIR is set, the output goes to $TMPDIR/q.

To print the value of foo, insert this into your program:

    import q; q(foo)

To print the value of something in the middle of an expression, insert
"q()", "q/", or "q|".  For example, given this statement:

    file.write(prefix + (sep or '').join(items))

...you can print out various values without using any temporary variables:

    file.write(prefix + q(sep or '').join(items))  # prints (sep or '')
    file.write(q/prefix + (sep or '').join(items))  # prints prefix
    file.write(q|prefix + (sep or '').join(items))  # prints the arg to write

To trace a function's arguments and return value, insert this above the def:

    import q
    @q

To start an interactive console at any point in your code, call q.d():

    import q; q.d()
"""

from __future__ import print_function

import sys

__author__ = 'Ka-Ping Yee <ping@zesty.ca>'

# WARNING: Horrible abuse of sys.modules, __call__, __div__, __or__, inspect,
# sys._getframe, and more!  q's behaviour changes depending on the text of the
# source code near its call site.  Don't ever do this in real code!

# These are reused below in both Q and Writer.
ESCAPE_SEQUENCES = ['\x1b[0m'] + ['\x1b[3%dm' % i for i in range(1, 7)]

if sys.version_info >= (3,):
    BASESTRING_TYPES = (str, bytes)
    TEXT_TYPES = (str,)
else:
    BASESTRING_TYPES = (basestring,)
    TEXT_TYPES = (unicode,)

# When we insert Q() into sys.modules, all the globals become None, so we
# have to keep everything we use inside the Q class.
class Q(object):
    __doc__ = __doc__  # from the module's __doc__ above

    import ast
    import code
    import inspect
    import os
    import pydoc
    import sys
    import random
    import re
    import time
    import functools

    # The debugging log will go to this file; temporary files will also have
    # this path as a prefix, followed by a random number.
    OUTPUT_PATH = os.path.join(
        os.environ.get('TMPDIR') or os.environ.get('TEMP') or '/tmp',
        'q')

    NORMAL, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN = ESCAPE_SEQUENCES
    TEXT_REPR = pydoc.TextRepr()

    # For portably converting strings between python2 and python3
    BASESTRING_TYPES = BASESTRING_TYPES
    TEXT_TYPES = TEXT_TYPES

    class FileWriter(object):
        """An object that appends to or overwrites a single file."""
        import sys
        # For portably converting strings between python2 and python3
        BASESTRING_TYPES = BASESTRING_TYPES
        TEXT_TYPES = TEXT_TYPES

        def __init__(self, path):
            self.path = path
            self.open = open
            # App Engine's dev_appserver patches 'open' to simulate security
            # restrictions in production; we circumvent this to write output.
            if open.__name__ == 'FakeFile':  # dev_appserver's patched 'file'
                self.open = open.__bases__[0]  # the original built-in 'file'

        def write(self, mode, content):
            if 'b' not in mode:
                mode = '%sb' % mode
            if (isinstance(content, self.BASESTRING_TYPES) and
                    isinstance(content, self.TEXT_TYPES)):
                content = content.encode('utf-8')
            try:
                f = self.open(self.path, mode)
                f.write(content)
                f.close()
            except IOError:
                pass

    class Writer:
        """Abstract away the output pipe, timestamping, and color support."""

        NORMAL, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN = ESCAPE_SEQUENCES

        def __init__(self, file_writer, time):
            self.color = True
            self.file_writer = file_writer
            self.gap_seconds = 2
            self.time = time  # the 'time' module (needed because no globals)
            self.start_time = self.time.time()
            self.last_write = 0

        def write(self, chunks):
            """Writes out a list of strings as a single timestamped unit."""
            if not self.color:
                chunks = [x for x in chunks if not x.startswith('\x1b')]
            content = ''.join(chunks)

            now = self.time.time()
            prefix = '%4.1fs ' % ((now - self.start_time) % 100)
            indent = ' ' * len(prefix)
            if self.color:
                prefix = self.YELLOW + prefix + self.NORMAL
            if now - self.last_write >= self.gap_seconds:
                prefix = '\n' + prefix
            self.last_write = now

            output = prefix + content.replace('\n', '\n' + indent)
            self.file_writer.write('a', output + '\n')

    class Stanza:
        """Abstract away indentation and line-wrapping."""

        def __init__(self, indent=0, width=80 - 7):
            self.chunks = [' '*indent]
            self.indent = indent
            self.column = indent
            self.width = width

        def newline(self):
            if len(self.chunks) > 1:
                self.column = self.width

        def add(self, items, sep='', wrap=True):
            """Adds a list of strings that are to be printed on one line."""
            items = list(map(str, items))
            size = sum([len(x) for x in items if not x.startswith('\x1b')])
            if (wrap and self.column > self.indent and
                    self.column + len(sep) + size > self.width):
                self.chunks.append(sep.rstrip() + '\n' + ' '*self.indent)
                self.column = self.indent
            else:
                self.chunks.append(sep)
                self.column += len(sep)
            self.chunks.extend(items)
            self.column += size

    def __init__(self):
        self.writer = self.Writer(self.FileWriter(self.OUTPUT_PATH), self.time)
        self.indent = 0
        # in_console tracks whether we're in an interactive console.
        # We use it to display the caller as "<console>" instead of "<module>".
        self.in_console = False

    def unindent(self, lines):
        """Removes any indentation that is common to all of the given lines."""
        indent = min(
            len(self.re.match(r'^ *', line).group()) for line in lines)
        return [line[indent:].rstrip() for line in lines]

    def safe_repr(self, value):
        # TODO: Use colour to distinguish '...' elision from actual '...'
        # TODO: Show a nicer repr for SRE.Match objects.
        # TODO: Show a nicer repr for big multiline strings.
        result = self.TEXT_REPR.repr(value)
        if isinstance(value, self.BASESTRING_TYPES) and len(value) > 80:
            # If the string is big, save it to a file for later examination.
            if isinstance(value,  self.TEXT_TYPES):
                value = value.encode('utf-8')
            path = self.OUTPUT_PATH + '%08d.txt' % self.random.randrange(1e8)
            self.FileWriter(path).write('w', value)
            result += ' (file://' + path + ')'
        return result

    def get_call_exprs(self, line):
        """Gets the argument expressions from the source of a function call."""
        line = line.lstrip()
        try:
            tree = self.ast.parse(line)
        except SyntaxError:
            return None
        for node in self.ast.walk(tree):
            if isinstance(node, self.ast.Call):
                offsets = []
                for arg in node.args:
                    # In Python 3.4 the col_offset is calculated wrong. See
                    # https://bugs.python.org/issue21295
                    if isinstance(arg, self.ast.Attribute) and (
                            self.sys.version_info[0] == 3 and
                            self.sys.version_info[1] == 4 and
                            self.sys.version_info[2] < 3):
                        offsets.append(arg.col_offset - len(arg.value.id) - 1)
                    else:
                        offsets.append(arg.col_offset)
                if node.keywords:
                    line = line[:node.keywords[0].value.col_offset]
                    line = self.re.sub(r'\w+\s*=\s*$', '', line)
                else:
                    line = self.re.sub(r'\s*\)\s*$', '', line)
                offsets.append(len(line))
                args = []
                for i in range(len(node.args)):
                    args.append(line[offsets[i]:offsets[i + 1]].rstrip(', '))
                return args

    def show(self, func_name, values, labels=None):
        """Prints out nice representations of the given values."""
        s = self.Stanza(self.indent)
        if func_name == '<module>' and self.in_console:
            func_name = '<console>'
        s.add([func_name + ': '])
        reprs = map(self.safe_repr, values)
        if labels:
            sep = ''
            for label, repr in zip(labels, reprs):
                s.add([label + '=', self.CYAN, repr, self.NORMAL], sep)
                sep = ', '
        else:
            sep = ''
            for repr in reprs:
                s.add([self.CYAN, repr, self.NORMAL], sep)
                sep = ', '
        self.writer.write(s.chunks)

    def trace(self, func):
        """Decorator to print out a function's arguments and return value."""

        def wrapper(*args, **kwargs):
            # Print out the call to the function with its arguments.
            s = self.Stanza(self.indent)
            s.add([self.GREEN, func.__name__, self.NORMAL, '('])
            s.indent += 4
            sep = ''
            for arg in args:
                s.add([self.CYAN, self.safe_repr(arg), self.NORMAL], sep)
                sep = ', '
            for name, value in sorted(kwargs.items()):
                s.add([name + '=', self.CYAN, self.safe_repr(value),
                       self.NORMAL], sep)
                sep = ', '
            s.add(')', wrap=False)
            self.writer.write(s.chunks)

            # Call the function.
            self.indent += 2
            try:
                result = func(*args, **kwargs)
            except:
                # Display an exception.
                self.indent -= 2
                etype, evalue, etb = self.sys.exc_info()
                info = self.inspect.getframeinfo(etb.tb_next, context=3)
                s = self.Stanza(self.indent)
                s.add([self.RED, '!> ', self.safe_repr(evalue), self.NORMAL])
                s.add(['at ', info.filename, ':', info.lineno], ' ')
                lines = self.unindent(info.code_context)
                firstlineno = info.lineno - info.index
                fmt = '%' + str(len(str(firstlineno + len(lines)))) + 'd'
                for i, line in enumerate(lines):
                    s.newline()
                    s.add([
                        i == info.index and self.MAGENTA or '',
                        fmt % (i + firstlineno),
                        i == info.index and '> ' or ': ', line, self.NORMAL])
                self.writer.write(s.chunks)
                raise

            # Display the return value.
            self.indent -= 2
            s = self.Stanza(self.indent)
            s.add([self.GREEN, '-> ', self.CYAN, self.safe_repr(result),
                   self.NORMAL])
            self.writer.write(s.chunks)
            return result
        return self.functools.update_wrapper(wrapper, func)

    def __call__(self, *args):
        """If invoked as a decorator on a function, adds tracing output to the
        function; otherwise immediately prints out the arguments."""
        info = self.inspect.getframeinfo(self.sys._getframe(1), context=9)

        # info.index is the index of the line containing the end of the call
        # expression, so this gets a few lines up to the end of the expression.
        lines = ['']
        if info.code_context:
            lines = info.code_context[:info.index + 1]

        # If we see "@q" on a single line, behave like a trace decorator.
        if lines[-1].strip().startswith('@') and args:
            return self.trace(args[0])

        # Otherwise, search for the beginning of the call expression; once it
        # parses, use the expressions in the call to label the debugging
        # output.
        for i in range(1, len(lines) + 1):
            labels = self.get_call_exprs(''.join(lines[-i:]).replace('\n', ''))
            if labels:
                break
        self.show(info.function, args, labels)
        return args and args[0]

    def __truediv__(self, arg):  # a tight-binding operator
        """Prints out and returns the argument."""
        info = self.inspect.getframeinfo(self.sys._getframe(1))
        self.show(info.function, [arg])
        return arg
    # Compat for Python 2 without from future import __division__ turned on
    __div__ = __truediv__

    __or__ = __div__  # a loose-binding operator
    q = __call__  # backward compatibility with @q.q
    t = trace  # backward compatibility with @q.t
    __name__ = 'Q'  # App Engine's import hook dies if this isn't present

    def d(self, depth=1):
        """Launches an interactive console at the point where it's called."""
        info = self.inspect.getframeinfo(self.sys._getframe(1))
        s = self.Stanza(self.indent)
        s.add([info.function + ': '])
        s.add([self.MAGENTA, 'Interactive console opened', self.NORMAL])
        self.writer.write(s.chunks)

        frame = self.sys._getframe(depth)
        env = frame.f_globals.copy()
        env.update(frame.f_locals)
        self.indent += 2
        self.in_console = True
        self.code.interact(
            'Python console opened by q.d() in ' + info.function, local=env)
        self.in_console = False
        self.indent -= 2

        s = self.Stanza(self.indent)
        s.add([info.function + ': '])
        s.add([self.MAGENTA, 'Interactive console closed', self.NORMAL])
        self.writer.write(s.chunks)

# Install the Q() object in sys.modules so that "import q" gives a callable q.
sys.modules['q'] = Q()
<commit_msg>Using Python's between structure.<commit_after># Copyright 2012 Google Inc.  All Rights Reserved.
# vim: set ts=4 sw=4 et sts=4 ai:
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License.  You may obtain a copy
# of the License at: http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distrib-
# uted under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
# OR CONDITIONS OF ANY KIND, either express or implied.  See the License for
# specific language governing permissions and limitations under the License.

"""Quick and dirty debugging output for tired programmers.

All output goes to /tmp/q, which you can watch with this shell command:

    tail -f /tmp/q

If TMPDIR is set, the output goes to $TMPDIR/q.

To print the value of foo, insert this into your program:

    import q; q(foo)

To print the value of something in the middle of an expression, insert
"q()", "q/", or "q|".  For example, given this statement:

    file.write(prefix + (sep or '').join(items))

...you can print out various values without using any temporary variables:

    file.write(prefix + q(sep or '').join(items))  # prints (sep or '')
    file.write(q/prefix + (sep or '').join(items))  # prints prefix
    file.write(q|prefix + (sep or '').join(items))  # prints the arg to write

To trace a function's arguments and return value, insert this above the def:

    import q
    @q

To start an interactive console at any point in your code, call q.d():

    import q; q.d()
"""

from __future__ import print_function

import sys

__author__ = 'Ka-Ping Yee <ping@zesty.ca>'

# WARNING: Horrible abuse of sys.modules, __call__, __div__, __or__, inspect,
# sys._getframe, and more!  q's behaviour changes depending on the text of the
# source code near its call site.  Don't ever do this in real code!

# These are reused below in both Q and Writer.
ESCAPE_SEQUENCES = ['\x1b[0m'] + ['\x1b[3%dm' % i for i in range(1, 7)]

if sys.version_info >= (3,):
    BASESTRING_TYPES = (str, bytes)
    TEXT_TYPES = (str,)
else:
    BASESTRING_TYPES = (basestring,)
    TEXT_TYPES = (unicode,)

# When we insert Q() into sys.modules, all the globals become None, so we
# have to keep everything we use inside the Q class.
class Q(object):
    __doc__ = __doc__  # from the module's __doc__ above

    import ast
    import code
    import inspect
    import os
    import pydoc
    import sys
    import random
    import re
    import time
    import functools

    # The debugging log will go to this file; temporary files will also have
    # this path as a prefix, followed by a random number.
    OUTPUT_PATH = os.path.join(
        os.environ.get('TMPDIR') or os.environ.get('TEMP') or '/tmp',
        'q')

    NORMAL, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN = ESCAPE_SEQUENCES
    TEXT_REPR = pydoc.TextRepr()

    # For portably converting strings between python2 and python3
    BASESTRING_TYPES = BASESTRING_TYPES
    TEXT_TYPES = TEXT_TYPES

    class FileWriter(object):
        """An object that appends to or overwrites a single file."""
        import sys
        # For portably converting strings between python2 and python3
        BASESTRING_TYPES = BASESTRING_TYPES
        TEXT_TYPES = TEXT_TYPES

        def __init__(self, path):
            self.path = path
            self.open = open
            # App Engine's dev_appserver patches 'open' to simulate security
            # restrictions in production; we circumvent this to write output.
            if open.__name__ == 'FakeFile':  # dev_appserver's patched 'file'
                self.open = open.__bases__[0]  # the original built-in 'file'

        def write(self, mode, content):
            if 'b' not in mode:
                mode = '%sb' % mode
            if (isinstance(content, self.BASESTRING_TYPES) and
                    isinstance(content, self.TEXT_TYPES)):
                content = content.encode('utf-8')
            try:
                f = self.open(self.path, mode)
                f.write(content)
                f.close()
            except IOError:
                pass

    class Writer:
        """Abstract away the output pipe, timestamping, and color support."""

        NORMAL, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN = ESCAPE_SEQUENCES

        def __init__(self, file_writer, time):
            self.color = True
            self.file_writer = file_writer
            self.gap_seconds = 2
            self.time = time  # the 'time' module (needed because no globals)
            self.start_time = self.time.time()
            self.last_write = 0

        def write(self, chunks):
            """Writes out a list of strings as a single timestamped unit."""
            if not self.color:
                chunks = [x for x in chunks if not x.startswith('\x1b')]
            content = ''.join(chunks)

            now = self.time.time()
            prefix = '%4.1fs ' % ((now - self.start_time) % 100)
            indent = ' ' * len(prefix)
            if self.color:
                prefix = self.YELLOW + prefix + self.NORMAL
            if now - self.last_write >= self.gap_seconds:
                prefix = '\n' + prefix
            self.last_write = now

            output = prefix + content.replace('\n', '\n' + indent)
            self.file_writer.write('a', output + '\n')

    class Stanza:
        """Abstract away indentation and line-wrapping."""

        def __init__(self, indent=0, width=80 - 7):
            self.chunks = [' '*indent]
            self.indent = indent
            self.column = indent
            self.width = width

        def newline(self):
            if len(self.chunks) > 1:
                self.column = self.width

        def add(self, items, sep='', wrap=True):
            """Adds a list of strings that are to be printed on one line."""
            items = list(map(str, items))
            size = sum([len(x) for x in items if not x.startswith('\x1b')])
            if (wrap and self.column > self.indent and
                    self.column + len(sep) + size > self.width):
                self.chunks.append(sep.rstrip() + '\n' + ' '*self.indent)
                self.column = self.indent
            else:
                self.chunks.append(sep)
                self.column += len(sep)
            self.chunks.extend(items)
            self.column += size

    def __init__(self):
        self.writer = self.Writer(self.FileWriter(self.OUTPUT_PATH), self.time)
        self.indent = 0
        # in_console tracks whether we're in an interactive console.
        # We use it to display the caller as "<console>" instead of "<module>".
        self.in_console = False

    def unindent(self, lines):
        """Removes any indentation that is common to all of the given lines."""
        indent = min(
            len(self.re.match(r'^ *', line).group()) for line in lines)
        return [line[indent:].rstrip() for line in lines]

    def safe_repr(self, value):
        # TODO: Use colour to distinguish '...' elision from actual '...'
        # TODO: Show a nicer repr for SRE.Match objects.
        # TODO: Show a nicer repr for big multiline strings.
        result = self.TEXT_REPR.repr(value)
        if isinstance(value, self.BASESTRING_TYPES) and len(value) > 80:
            # If the string is big, save it to a file for later examination.
            if isinstance(value,  self.TEXT_TYPES):
                value = value.encode('utf-8')
            path = self.OUTPUT_PATH + '%08d.txt' % self.random.randrange(1e8)
            self.FileWriter(path).write('w', value)
            result += ' (file://' + path + ')'
        return result

    def get_call_exprs(self, line):
        """Gets the argument expressions from the source of a function call."""
        line = line.lstrip()
        try:
            tree = self.ast.parse(line)
        except SyntaxError:
            return None
        for node in self.ast.walk(tree):
            if isinstance(node, self.ast.Call):
                offsets = []
                for arg in node.args:
                    # In Python 3.4 the col_offset is calculated wrong. See
                    # https://bugs.python.org/issue21295
                    if isinstance(arg, self.ast.Attribute) and (
                            (3, 4, 0) <= self.sys.version_info <= (3, 4, 3)):
                        offsets.append(arg.col_offset - len(arg.value.id) - 1)
                    else:
                        offsets.append(arg.col_offset)
                if node.keywords:
                    line = line[:node.keywords[0].value.col_offset]
                    line = self.re.sub(r'\w+\s*=\s*$', '', line)
                else:
                    line = self.re.sub(r'\s*\)\s*$', '', line)
                offsets.append(len(line))
                args = []
                for i in range(len(node.args)):
                    args.append(line[offsets[i]:offsets[i + 1]].rstrip(', '))
                return args

    def show(self, func_name, values, labels=None):
        """Prints out nice representations of the given values."""
        s = self.Stanza(self.indent)
        if func_name == '<module>' and self.in_console:
            func_name = '<console>'
        s.add([func_name + ': '])
        reprs = map(self.safe_repr, values)
        if labels:
            sep = ''
            for label, repr in zip(labels, reprs):
                s.add([label + '=', self.CYAN, repr, self.NORMAL], sep)
                sep = ', '
        else:
            sep = ''
            for repr in reprs:
                s.add([self.CYAN, repr, self.NORMAL], sep)
                sep = ', '
        self.writer.write(s.chunks)

    def trace(self, func):
        """Decorator to print out a function's arguments and return value."""

        def wrapper(*args, **kwargs):
            # Print out the call to the function with its arguments.
            s = self.Stanza(self.indent)
            s.add([self.GREEN, func.__name__, self.NORMAL, '('])
            s.indent += 4
            sep = ''
            for arg in args:
                s.add([self.CYAN, self.safe_repr(arg), self.NORMAL], sep)
                sep = ', '
            for name, value in sorted(kwargs.items()):
                s.add([name + '=', self.CYAN, self.safe_repr(value),
                       self.NORMAL], sep)
                sep = ', '
            s.add(')', wrap=False)
            self.writer.write(s.chunks)

            # Call the function.
            self.indent += 2
            try:
                result = func(*args, **kwargs)
            except:
                # Display an exception.
                self.indent -= 2
                etype, evalue, etb = self.sys.exc_info()
                info = self.inspect.getframeinfo(etb.tb_next, context=3)
                s = self.Stanza(self.indent)
                s.add([self.RED, '!> ', self.safe_repr(evalue), self.NORMAL])
                s.add(['at ', info.filename, ':', info.lineno], ' ')
                lines = self.unindent(info.code_context)
                firstlineno = info.lineno - info.index
                fmt = '%' + str(len(str(firstlineno + len(lines)))) + 'd'
                for i, line in enumerate(lines):
                    s.newline()
                    s.add([
                        i == info.index and self.MAGENTA or '',
                        fmt % (i + firstlineno),
                        i == info.index and '> ' or ': ', line, self.NORMAL])
                self.writer.write(s.chunks)
                raise

            # Display the return value.
            self.indent -= 2
            s = self.Stanza(self.indent)
            s.add([self.GREEN, '-> ', self.CYAN, self.safe_repr(result),
                   self.NORMAL])
            self.writer.write(s.chunks)
            return result
        return self.functools.update_wrapper(wrapper, func)

    def __call__(self, *args):
        """If invoked as a decorator on a function, adds tracing output to the
        function; otherwise immediately prints out the arguments."""
        info = self.inspect.getframeinfo(self.sys._getframe(1), context=9)

        # info.index is the index of the line containing the end of the call
        # expression, so this gets a few lines up to the end of the expression.
        lines = ['']
        if info.code_context:
            lines = info.code_context[:info.index + 1]

        # If we see "@q" on a single line, behave like a trace decorator.
        if lines[-1].strip().startswith('@') and args:
            return self.trace(args[0])

        # Otherwise, search for the beginning of the call expression; once it
        # parses, use the expressions in the call to label the debugging
        # output.
        for i in range(1, len(lines) + 1):
            labels = self.get_call_exprs(''.join(lines[-i:]).replace('\n', ''))
            if labels:
                break
        self.show(info.function, args, labels)
        return args and args[0]

    def __truediv__(self, arg):  # a tight-binding operator
        """Prints out and returns the argument."""
        info = self.inspect.getframeinfo(self.sys._getframe(1))
        self.show(info.function, [arg])
        return arg
    # Compat for Python 2 without from future import __division__ turned on
    __div__ = __truediv__

    __or__ = __div__  # a loose-binding operator
    q = __call__  # backward compatibility with @q.q
    t = trace  # backward compatibility with @q.t
    __name__ = 'Q'  # App Engine's import hook dies if this isn't present

    def d(self, depth=1):
        """Launches an interactive console at the point where it's called."""
        info = self.inspect.getframeinfo(self.sys._getframe(1))
        s = self.Stanza(self.indent)
        s.add([info.function + ': '])
        s.add([self.MAGENTA, 'Interactive console opened', self.NORMAL])
        self.writer.write(s.chunks)

        frame = self.sys._getframe(depth)
        env = frame.f_globals.copy()
        env.update(frame.f_locals)
        self.indent += 2
        self.in_console = True
        self.code.interact(
            'Python console opened by q.d() in ' + info.function, local=env)
        self.in_console = False
        self.indent -= 2

        s = self.Stanza(self.indent)
        s.add([info.function + ': '])
        s.add([self.MAGENTA, 'Interactive console closed', self.NORMAL])
        self.writer.write(s.chunks)

# Install the Q() object in sys.modules so that "import q" gives a callable q.
sys.modules['q'] = Q()
<|endoftext|>


<commit_before>##    Copyright (C) 2011 Oleg Kertanov <okertanov@gmail.com>
##    All rights reserved.

import os
import sys
import logging
import inspect
import GitLib

#
# GitLibTestDelegate class
#
class GitLibTestDelegate(GitLib.GitLibDelegate) :
    def __init__(self):
        super(GitLibTestDelegate, self).__init__()

    def GetLoggingEnabled(self):
        return (True, logging.DEBUG, None, None)

    def GetTopDir(self):
        return "~"

    def Process(self, event = None, data = None):
        pass

    def OnScanItem(self, item = None):
        pass

    def OnScanDone(self):
        pass

    def TestInit(self):
        self.git = GitLib.GitLib(self)
        self.git.SetupGit({'topdir':'../'});
        self.git.Version()

    def Test0(self):
        self.GetLoggingEnabled()
        self.GetTopDir()
        self.Process()
        self.OnScanItem()
        self.OnScanDone()

    def Test1(self):
        self.git.Scan();
        #map(lambda i: i.dump(), self.aList)

    def Test2(self):
        self.git.Init();
        self.git.Clone();
        self.git.Status();
        self.git.Log();
        self.git.Diff();
        self.git.Config();

    def Test3(self):
        self.worker = GitLib.GitWorker()
        self.worker.sleep(1)
        self.worker.enqueue(1).enqueue(2).enqueue(3)
        self.worker.enqueue(3).enqueue(2).enqueue(1)
        self.worker.execute()
        self.worker.block()
        self.worker.enqueue(10).enqueue(20).enqueue(30).execute()
        self.worker.enqueue('A').enqueue('B').enqueue('C').execute()
        self.worker.block()
        self.worker.enqueue(self.git.Init).enqueue(self.git.Status).enqueue(self.git.Log).execute()
        self.worker.block()

    def RunTests(self):
        test.TestInit()
        test.Test0()
        test.Test1()
        test.Test2()
        test.Test3()

if __name__ == '__main__':
    test = GitLibTestDelegate()
    test.RunTests()

<commit_msg>t.py Test4 added<commit_after>##    Copyright (C) 2011 Oleg Kertanov <okertanov@gmail.com>
##    All rights reserved.

import os
import sys
import logging
import inspect
import GitLib

#
# GitLibTestDelegate class
#
class GitLibTestDelegate(GitLib.GitLibDelegate) :
    def __init__(self):
        super(GitLibTestDelegate, self).__init__()

    def GetLoggingEnabled(self):
        return (True, logging.DEBUG, None, None)

    def GetTopDir(self):
        return "~"

    def Process(self, event = None, data = None):
        pass

    def OnScanItem(self, item = None):
        pass

    def OnScanDone(self):
        pass

    def TestInit(self):
        self.git = GitLib.GitLib(self)
        self.git.SetupGit({'topdir':'../'});
        self.git.Version()

    def Test0(self):
        self.GetLoggingEnabled()
        self.GetTopDir()
        self.Process()
        self.OnScanItem()
        self.OnScanDone()

    def Test1(self):
        self.git.Scan();
        #map(lambda i: i.dump(), self.aList)

    def Test2(self):
        self.git.Init();
        self.git.Clone();
        self.git.Status();
        self.git.Log();
        self.git.Diff();
        self.git.Config();

    def Test3(self):
        self.worker = GitLib.GitWorker()
        self.worker.sleep(1)
        self.worker.enqueue(1).enqueue(2).enqueue(3)
        self.worker.enqueue(3).enqueue(2).enqueue(1)
        self.worker.execute()
        self.worker.block()
        self.worker.enqueue(10).enqueue(20).enqueue(30).execute()
        self.worker.enqueue('A').enqueue('B').enqueue('C').execute()
        self.worker.block()
        self.worker.enqueue(self.git.Init).enqueue(self.git.Status).enqueue(self.git.Log).execute()
        self.worker.block()

    def Test4(self):
        #self.git.Help()
        self.git.Status(path='../useful-unix-commands.gist')
        pass

    def RunTests(self):
        test.TestInit()
        test.Test0()
        test.Test1()
        test.Test2()
        test.Test3()
        test.Test4()

if __name__ == '__main__':
    test = GitLibTestDelegate()
    test.RunTests()

<|endoftext|>


<commit_before>#!/usr/bin/env python

from __future__ import with_statement

import os, sys, hashlib, operator
from optparse import OptionParser

class InvalidTaskfile(Exception):
    pass
class AmbiguousPrefix(Exception):
    pass

_hash = lambda s: hashlib.sha1(s).hexdigest()

def _task_from_taskline(taskline):
    """Parse a taskline (from a task file) and return a task.

    A taskline should be in the format:

        summary text ... | meta1:meta1_value,meta2:meta2_value,...

    The task returned will be a dictionary such as:

        { 'id': <hash id>,
          'text': <summary text>,
           ... other metadata ... }

    """
    text, _, meta = taskline.partition('|')
    task = {'text': text.strip()}
    for piece in meta.strip().split(','):
        k, v = piece.split(':')
        task[k.strip()] = v.strip()
    return task

def _prefixes(ids):
    """return a mapping of ids to prefixes

    Each prefix will be the shortest possible substring of the ID that
    can uniquely identify it among the given group of IDs.

    """

    prefixes = {}
    for id in ids:
        others = set(ids).difference([id])
        for i in range(1, len(id)+1):
            prefix = id[:i]
            if not any(map(lambda o: o.startswith(prefix), others)):
                prefixes[id] = prefix
                break
    return prefixes

class TaskDict(object):
    def __init__(self, name='tasks'):
        self.tasks = {}
        self.done = {}
        self.name = name
        filemap = (('tasks', self.name), ('done', '.%s.done' % self.name))
        for kind, filename in filemap:
            if os.path.isdir(filename):
                raise InvalidTaskfile
            if os.path.exists(filename):
                with open(filename, 'r') as tfile:
                    tls = [tl.strip() for tl in tfile.xreadlines() if tl]
                    tasks = map(_task_from_taskline, tls)
                    for task in tasks:
                        getattr(self, kind)[task['id']] = task

    def add_task(self, text):
        id = _hash(text)
        self.tasks[id] = {'id': id, 'text': text}

    def write(self):
        filemap = (('tasks', self.name), ('done', '.%s.done' % self.name))
        for kind, filename in filemap:
            if os.path.isdir(filename):
                raise InvalidTaskfile
            with open(filename, 'w') as tfile:
                tasks = getattr(self, kind).values()
                tasks.sort(key=operator.itemgetter('id'))
                for task in tasks:
                    meta = [m for m in task.items() if m[0] != 'text']
                    meta_str = ', '.join('%s:%s' % m for m in meta)
                    tfile.write('%s | %s\n' % (task['text'], meta_str))

    def print_list(self, kind='tasks', verbose=False):
        tasks = dict(getattr(self, kind).items())
        label = 'prefix' if not verbose else 'id'
        if not verbose:
            for id, prefix in _prefixes(tasks).items():
                tasks[id]['prefix'] = prefix
        plen = max(map(lambda t: len(t[label]), tasks.values())) if tasks else 0
        for t in tasks.values():
            print ('%-' + str(plen) + 's - %s') % (t[label], t['text'])

    def finish_task(self, prefix):
        matched = filter(lambda id: id.startswith(prefix), self.tasks.keys())
        if len(matched) == 1:
            task = self.tasks.pop(matched[0])
            self.done[task['id']] = task
        else:
            raise AmbiguousPrefix

    def delete_finished(self):
        self.done = {}

def build_parser():
    parser = OptionParser()
    parser.add_option("-a", "--add",
                      action="store_true", dest="add", default=True,
                      help="add the text as a task (default)")
    parser.add_option("-e", "--edit", dest="edit",
                      help="edit TASK", metavar="TASK")
    parser.add_option("-f", "--finish", dest="finish",
                      help="mark TASK as finished", metavar="TASK")
    parser.add_option("-l", "--list", dest="name", default="tasks",
                      help="work on LIST", metavar="LIST")
    parser.add_option("-t", "--task-dir", dest="name",
                      help="work in DIR", metavar="DIR")
    parser.add_option("-D", "--delete-finished", dest="delete_finished",
                      action="store_true", default=False,
                      help="delete finished items to save space")
    parser.add_option("-v", "--verbose",
                      action="store_true", dest="verbose", default=False,
                      help="print more detailed output (full task ids, etc)")
    return parser

if __name__ == '__main__':
    (options, args) = build_parser().parse_args()

    td = TaskDict(options.name)
    text = ' '.join(args)

    if options.finish:
        td.finish_task(options.finish)
        td.write()
    elif options.delete_finished:
        td.delete_finished()
        td.write()
    elif text:
        td.add_task(text)
        td.write()
    else:
        td.print_list(verbose=options.verbose)

<commit_msg>Enable the taskdir option.<commit_after>#!/usr/bin/env python

from __future__ import with_statement

import os, sys, hashlib, operator
from optparse import OptionParser

class InvalidTaskfile(Exception):
    pass
class AmbiguousPrefix(Exception):
    pass

_hash = lambda s: hashlib.sha1(s).hexdigest()

def _task_from_taskline(taskline):
    """Parse a taskline (from a task file) and return a task.

    A taskline should be in the format:

        summary text ... | meta1:meta1_value,meta2:meta2_value,...

    The task returned will be a dictionary such as:

        { 'id': <hash id>,
          'text': <summary text>,
           ... other metadata ... }

    """
    text, _, meta = taskline.partition('|')
    task = {'text': text.strip()}
    for piece in meta.strip().split(','):
        k, v = piece.split(':')
        task[k.strip()] = v.strip()
    return task

def _prefixes(ids):
    """return a mapping of ids to prefixes

    Each prefix will be the shortest possible substring of the ID that
    can uniquely identify it among the given group of IDs.

    """

    prefixes = {}
    for id in ids:
        others = set(ids).difference([id])
        for i in range(1, len(id)+1):
            prefix = id[:i]
            if not any(map(lambda o: o.startswith(prefix), others)):
                prefixes[id] = prefix
                break
    return prefixes

class TaskDict(object):
    def __init__(self, taskdir='.', name='tasks'):
        self.tasks = {}
        self.done = {}
        self.name = name
        self.taskdir = taskdir
        filemap = (('tasks', self.name), ('done', '.%s.done' % self.name))
        for kind, filename in filemap:
            path = os.path.join(os.path.realpath(self.taskdir), filename)
            if os.path.isdir(path):
                raise InvalidTaskfile
            if os.path.exists(path):
                with open(path, 'r') as tfile:
                    tls = [tl.strip() for tl in tfile.xreadlines() if tl]
                    tasks = map(_task_from_taskline, tls)
                    for task in tasks:
                        getattr(self, kind)[task['id']] = task

    def add_task(self, text):
        id = _hash(text)
        self.tasks[id] = {'id': id, 'text': text}

    def write(self):
        filemap = (('tasks', self.name), ('done', '.%s.done' % self.name))
        for kind, filename in filemap:
            path = os.path.join(os.path.realpath(self.taskdir), filename)
            if os.path.isdir(path):
                raise InvalidTaskfile
            with open(path, 'w') as tfile:
                tasks = getattr(self, kind).values()
                tasks.sort(key=operator.itemgetter('id'))
                for task in tasks:
                    meta = [m for m in task.items() if m[0] != 'text']
                    meta_str = ', '.join('%s:%s' % m for m in meta)
                    tfile.write('%s | %s\n' % (task['text'], meta_str))

    def print_list(self, kind='tasks', verbose=False):
        tasks = dict(getattr(self, kind).items())
        label = 'prefix' if not verbose else 'id'
        if not verbose:
            for id, prefix in _prefixes(tasks).items():
                tasks[id]['prefix'] = prefix
        plen = max(map(lambda t: len(t[label]), tasks.values())) if tasks else 0
        for t in tasks.values():
            print ('%-' + str(plen) + 's - %s') % (t[label], t['text'])

    def finish_task(self, prefix):
        matched = filter(lambda id: id.startswith(prefix), self.tasks.keys())
        if len(matched) == 1:
            task = self.tasks.pop(matched[0])
            self.done[task['id']] = task
        else:
            raise AmbiguousPrefix

    def delete_finished(self):
        self.done = {}

def build_parser():
    parser = OptionParser()

    parser.add_option("-a", "--add",
                      action="store_true", dest="add", default=True,
                      help="add the text as a task (default)")

    parser.add_option("-e", "--edit", dest="edit",
                      help="edit TASK", metavar="TASK")

    parser.add_option("-f", "--finish", dest="finish",
                      help="mark TASK as finished", metavar="TASK")

    parser.add_option("-l", "--list", dest="name", default="tasks",
                      help="work on LIST", metavar="LIST")

    parser.add_option("-t", "--task-dir", dest="taskdir", default="",
                      help="work in DIR", metavar="DIR")

    parser.add_option("-D", "--delete-finished", dest="delete_finished",
                      action="store_true", default=False,
                      help="delete finished items to save space")

    parser.add_option("-v", "--verbose",
                      action="store_true", dest="verbose", default=False,
                      help="print more detailed output (full task ids, etc)")
    return parser

if __name__ == '__main__':
    (options, args) = build_parser().parse_args()

    td = TaskDict(taskdir=options.taskdir, name=options.name)
    text = ' '.join(args)

    if options.finish:
        td.finish_task(options.finish)
        td.write()
    elif options.delete_finished:
        td.delete_finished()
        td.write()
    elif text:
        td.add_task(text)
        td.write()
    else:
        td.print_list(verbose=options.verbose)

<|endoftext|>


<commit_before>#!/usr/bin/python -tt
# -*- coding: utf-8 -*-

import datetime
import hashlib
import htmlmin
import markdown2
import os
import shutil
import subprocess
from string import Template

# # Configurable options:
z = {}
## `d_source`: the directory that contains the source files:
d_source = '/home/marios/Public/Dropbox/Code/zindilis.com'
## `d_htdocs`: the directory served over HTTP:
d_htdocs = '/home/marios/Public/Dropbox/Code/marios-zindilis.github.io'
## `d_state`: the directory that contains the state files:
d_state = '/home/marios/Public/Dropbox/Code/zalza/state'
## `opt_path_build`: the directory in which zBuild logs are saved:
z['opt_path_build'] =  '/home/marios/Public/Dropbox/Code/zalza/build'
## `opt_path_templates`: the directory containing the HTML templates:
z['opt_path_templates'] = '/home/marios/Public/Dropbox/Code/zalza'
## `d_source_skip`: subdirectories of `d_source` to be ignored:
d_source_skip = ['.git']
## `skip_source_files`: files in `d_source` to be ignored:
z['skip_source_files'] = ['.gitignore', 'README.md']
## `generate_output`: whether or not the output will be generated
z['generate_output'] = False
## `site_name`: used as the title in web pages:
z['site_name'] = 'Marios Zindilis'
## `site_base_url`: used in reports and in generation of canonical URLs:
z['site_base_url'] = 'http://zindilis.com'
## `site_author`: the default author, if one is not specified in a source file
z['site_author'] = 'Marios Zindilis'
## `action_index`: serial number of action taken
action_index = 0
## `pages_changed`: list of URLs of pages that were either created or updated
pages_changed = []

p = subprocess.Popen('clear', shell=True)
p.communicate()

build = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')
output_buffer = 'zBuild ' + build + '\n'
output_buffer += '=' * len(output_buffer) + '\n\n'

# Traverse source directory:
for traverse_root, traverse_dirs, traverse_files in os.walk(d_source):
    for traverse_dir in traverse_dirs:
        d_section = traverse_root[len(d_source)+1:].split('/')[0]
        # Skip some subdirectories of `d_source`:
        if (traverse_root == d_source
            and traverse_dir in d_source_skip) \
        or d_section in d_source_skip:
            continue

        z['source_path'] = os.path.join(traverse_root, traverse_dir)
        z['target_path'] = os.path.join(d_htdocs, z['source_path'][len(d_source)+1:])
        z['state_path'] = os.path.join(d_state, z['source_path'][len(d_source)+1:])

        if not os.path.isdir(z['target_path']) or not os.path.isdir(z['state_path']):
            z['generate_output'] = True
            action_index += 1
            output_buffer += ('%s.' % (str(action_index))).ljust(4)
            output_buffer += 'Found a **source directory**:\n\n'
            output_buffer += '        %s\n\n' % (z['source_path'])

        if not os.path.isdir(z['target_path']):
            os.makedirs(z['target_path'])
            output_buffer += '    Created its **target directory**:\n\n'
            output_buffer += '        %s\n\n' % (z['target_path'])
            os.chdir(d_source)

        if not os.path.isdir(z['state_path']):
            os.makedirs(z['state_path'])
            output_buffer += '    Created its **state directory**:\n\n'
            output_buffer += '        %s\n\n' % (z['state_path'])

    for traverse_file in traverse_files:
        # Skip some files in `d_source`:
        if traverse_root == d_source and traverse_file in z['skip_source_files']:
            continue
        # Also skip some subdirectories of `d_source`:
        if traverse_root != d_source and traverse_root[len(d_source)+1:].split('/')[0] in d_source_skip:
            continue

        z['source_path'] = os.path.join(traverse_root, traverse_file)
        z['source_content'] = file(z['source_path']).read()
        z['state_path'] = os.path.join(d_state, z['source_path'][len(d_source)+1:]) + '.state'

        if not os.path.isfile(z['state_path']) \
        or (os.path.isfile(z['state_path']) and file(z['state_path']).read() != hashlib.md5(z['source_content']).hexdigest()):
            z['generate_output'] = True
            action_index += 1
            output_buffer += ('%s.' % (str(action_index))).ljust(4)
            output_buffer += 'Found a **source file**:\n\n'
            output_buffer += '        %s\n\n' % (z['source_path'])

            if not z['source_path'].endswith('.md'):
                z['target_path'] = os.path.join(d_htdocs, z['source_path'][len(d_source)+1:])
                shutil.copyfile(z['source_path'], z['target_path'])
                output_buffer += '    Copied verbatim at:\n\n'
                output_buffer += '        %s\n\n' % (z['target_path'])

                state_file = open(z['state_path'], 'w')
                state_file.write(hashlib.md5(file(z['source_path']).read()).hexdigest())
                state_file.close()
                output_buffer += '    Created state at:\n\n'
                output_buffer += '        %s\n\n' % (z['state_path'])

            else:
                # Get headers from source file:
                headers = {}
                output_buffer += '    Headers in this file:\n\n'
                for line in file(z['source_path']).readlines():
                    if ':' in line:
                        key, value = line.split(':', 1)
                        key = key.lstrip().rstrip()
                        value = value.lstrip().rstrip()
                        headers[key] = value
                        output_buffer += '        *   %s: %s\n' % (key, headers[key])
                    if line == '- -->\n':
                        output_buffer += '\n'
                        break

                z['page_title'] = z['site_name'] + ' - ' + headers['Title'] if headers.has_key('Title') else z['site_name']
                d_section = traverse_root[len(d_source)+1:].split('/')[0]
                z['target_path'] = os.path.join(d_htdocs, traverse_root[len(d_source)+1:], os.path.splitext(traverse_file)[0]) + '.html'
                z['canonical_url'] = '/'.join([z['site_base_url'], (os.path.splitext(z['source_path'][len(d_source)+1:])[0] + '.html')])
                target_content = Template(file(os.path.join(z['opt_path_templates'], 'tmpl_header.html')).read()).substitute(z)

                pages_changed.append(z['canonical_url'])

                if d_section == 'docs':
                    target_content += '
'
                elif d_section == 'blog':
                    target_content += '
'
                else:
                    target_content += '
'

                target_content = target_content.decode('utf-8')
                target_content += markdown2.markdown(z['source_content'], extras=['fenced-code-blocks'])

                z['page_info'] = ''
                if headers.has_key('Title'):
                    z['page_info'] += '
Title: %s
\n' % (headers['Title'])
                if headers.has_key('Author'):
                    z['page_info'] += '
Author: %s
\n' % (headers['Author'])
                else:
                    z['page_info'] += '
Author: %s
\n' % (z['site_author'])
                if headers.has_key('Editor'):
                    z['page_info'] += '
Editor: %s
\n' % (headers['Editor'])
                if headers.has_key('First Published'):
                    z['page_info'] += '
First Published: <meta itemprop="datePublished" content="%s">%s
\n' % (headers['First Published'], headers['First Published'])
                if headers.has_key('Last Updated'):
                    z['page_info'] += '
Last Updated: <meta itemprop="dateModified" content="%s">%s
\n' % (headers['Last Updated'], headers['Last Updated'])

                page_footer = Template(file(os.path.join(z['opt_path_templates'], 'tmpl_footer.html')).read()).substitute(z)
                page_footer = page_footer.decode('utf-8')
                target_content += page_footer

                target_file = open(z['target_path'], 'w')
                target_content = htmlmin.minify(target_content, remove_comments=True)
                target_file.write(target_content.encode('utf-8'))
                target_file.close()

                output_buffer += '    Created HTML file at:\n\n'
                output_buffer += '        %s\n\n' % (z['target_path'])

                state_file = open(z['state_path'], 'w')
                state_file.write(hashlib.md5(file(z['source_path']).read()).hexdigest())
                state_file.close()
                output_buffer += '    Create state at:\n\n'
                output_buffer += '        %s\n\n' % (z['state_path'])

            os.chdir(d_source)
            commit_path = z['source_path'][len(d_source)+1:]
            p = subprocess.Popen(['git', 'add', commit_path])
            p.communicate()
            commit_mark = 'zBuild %s' % (datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S'))
            p = subprocess.Popen(['git', 'commit', commit_path, '-m', commit_mark, '--quiet'])
            p.communicate()
            p = subprocess.Popen(['git', 'push', '--quiet'])
            p.communicate()
            output_buffer += '    Committed source to Git and pushed.\n\n'

            # Commit the target file:
            os.chdir(d_htdocs)
            commit_path = z['target_path'][len(d_htdocs)+1:]
            p = subprocess.Popen(['git', 'add', commit_path])
            p.communicate()
            commit_mark = 'zBuild %s' % (datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S'))
            p = subprocess.Popen(['git', 'commit', commit_path, '-m', commit_mark, '--quiet'])
            p.communicate()
            p = subprocess.Popen(['git', 'push', '--quiet'])
            p.communicate()
            output_buffer += '    Committed target to Git and pushed.\n\n'

if z['generate_output']:
    output_buffer += 'Pages Updated or Created during this Build\n'
    output_buffer += '------------------------------------------\n\n'
    for page_changed in pages_changed:
        output_buffer += '*   %s\n' % (page_changed)

    output_path = os.path.join(z['opt_path_build'], '%s.md' % (build))
    output_file = open(output_path, 'w')
    output_file.write(output_buffer)
    output_file.close()
    output_buffer += '\nThis log has been saved as: %s' % (output_path)
    print output_buffer
<commit_msg>Renamed some variables that do not need to be in a dictionary.<commit_after>#!/usr/bin/python -tt
# -*- coding: utf-8 -*-

import datetime
import hashlib
import htmlmin
import markdown2
import os
import shutil
import subprocess
from string import Template

# # Configurable options:
z = {}
## `d_source`: the directory that contains the source files:
d_source = '/home/marios/Public/Dropbox/Code/zindilis.com'
## `d_htdocs`: the directory served over HTTP:
d_htdocs = '/home/marios/Public/Dropbox/Code/marios-zindilis.github.io'
## `d_state`: the directory that contains the state files:
d_state = '/home/marios/Public/Dropbox/Code/zalza/state'
## `opt_path_build`: the directory in which zBuild logs are saved:
z['opt_path_build'] =  '/home/marios/Public/Dropbox/Code/zalza/build'
## `opt_path_templates`: the directory containing the HTML templates:
z['opt_path_templates'] = '/home/marios/Public/Dropbox/Code/zalza'
## `d_source_skip`: subdirectories of `d_source` to be ignored:
d_source_skip = ['.git']
## `f_source_skip`: files in `d_source` to be ignored:
f_source_skip = ['.gitignore', 'README.md']
## `generate_output`: whether or not the output will be generated
z['generate_output'] = False
## `site_name`: used as the title in web pages:
z['site_name'] = 'Marios Zindilis'
## `site_base_url`: used in reports and in generation of canonical URLs:
z['site_base_url'] = 'http://zindilis.com'
## `site_author`: the default author, if one is not specified in a source file
z['site_author'] = 'Marios Zindilis'
## `action_index`: serial number of action taken
action_index = 0
## `pages_changed`: list of URLs of pages that were either created or updated
pages_changed = []

p = subprocess.Popen('clear', shell=True)
p.communicate()

build = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')
output_buffer = 'zBuild ' + build + '\n'
output_buffer += '=' * len(output_buffer) + '\n\n'

# Traverse source directory:
for traverse_root, traverse_dirs, traverse_files in os.walk(d_source):
    for traverse_dir in traverse_dirs:
        d_section = traverse_root[len(d_source)+1:].split('/')[0]
        # Skip some subdirectories of `d_source`:
        if (traverse_root == d_source
            and traverse_dir in d_source_skip) \
        or d_section in d_source_skip:
            continue

        source_path = os.path.join(traverse_root, traverse_dir)
        target_path = os.path.join(d_htdocs, source_path[len(d_source)+1:])
        state_path = os.path.join(d_state, source_path[len(d_source)+1:])

        if not os.path.isdir(target_path) or not os.path.isdir(state_path):
            z['generate_output'] = True
            action_index += 1
            output_buffer += ('%s.' % (str(action_index))).ljust(4)
            output_buffer += 'Found a **source directory**:\n\n'
            output_buffer += '        %s\n\n' % (source_path)

        if not os.path.isdir(target_path):
            os.makedirs(target_path)
            output_buffer += '    Created its **target directory**:\n\n'
            output_buffer += '        %s\n\n' % (target_path)
            os.chdir(d_source)

        if not os.path.isdir(state_path):
            os.makedirs(state_path)
            output_buffer += '    Created its **state directory**:\n\n'
            output_buffer += '        %s\n\n' % (state_path)

    for traverse_file in traverse_files:
        # Skip some files in `d_source`:
        if traverse_root == d_source and traverse_file in f_source_skip:
            continue
        # Also skip some subdirectories of `d_source`:
        if traverse_root != d_source and traverse_root[len(d_source)+1:].split('/')[0] in d_source_skip:
            continue

        z['source_path'] = os.path.join(traverse_root, traverse_file)
        z['source_content'] = file(z['source_path']).read()
        z['state_path'] = os.path.join(d_state, z['source_path'][len(d_source)+1:]) + '.state'

        if not os.path.isfile(z['state_path']) \
        or (os.path.isfile(z['state_path']) and file(z['state_path']).read() != hashlib.md5(z['source_content']).hexdigest()):
            z['generate_output'] = True
            action_index += 1
            output_buffer += ('%s.' % (str(action_index))).ljust(4)
            output_buffer += 'Found a **source file**:\n\n'
            output_buffer += '        %s\n\n' % (z['source_path'])

            if not z['source_path'].endswith('.md'):
                z['target_path'] = os.path.join(d_htdocs, z['source_path'][len(d_source)+1:])
                shutil.copyfile(z['source_path'], z['target_path'])
                output_buffer += '    Copied verbatim at:\n\n'
                output_buffer += '        %s\n\n' % (z['target_path'])

                state_file = open(z['state_path'], 'w')
                state_file.write(hashlib.md5(file(z['source_path']).read()).hexdigest())
                state_file.close()
                output_buffer += '    Created state at:\n\n'
                output_buffer += '        %s\n\n' % (z['state_path'])

            else:
                # Get headers from source file:
                headers = {}
                output_buffer += '    Headers in this file:\n\n'
                for line in file(z['source_path']).readlines():
                    if ':' in line:
                        key, value = line.split(':', 1)
                        key = key.lstrip().rstrip()
                        value = value.lstrip().rstrip()
                        headers[key] = value
                        output_buffer += '        *   %s: %s\n' % (key, headers[key])
                    if line == '- -->\n':
                        output_buffer += '\n'
                        break

                z['page_title'] = z['site_name'] + ' - ' + headers['Title'] if headers.has_key('Title') else z['site_name']
                d_section = traverse_root[len(d_source)+1:].split('/')[0]
                z['target_path'] = os.path.join(d_htdocs, traverse_root[len(d_source)+1:], os.path.splitext(traverse_file)[0]) + '.html'
                z['canonical_url'] = '/'.join([z['site_base_url'], (os.path.splitext(z['source_path'][len(d_source)+1:])[0] + '.html')])
                target_content = Template(file(os.path.join(z['opt_path_templates'], 'tmpl_header.html')).read()).substitute(z)

                pages_changed.append(z['canonical_url'])

                if d_section == 'docs':
                    target_content += '
'
                elif d_section == 'blog':
                    target_content += '
'
                else:
                    target_content += '
'

                target_content = target_content.decode('utf-8')
                target_content += markdown2.markdown(z['source_content'], extras=['fenced-code-blocks'])

                z['page_info'] = ''
                if headers.has_key('Title'):
                    z['page_info'] += '
Title: %s
\n' % (headers['Title'])
                if headers.has_key('Author'):
                    z['page_info'] += '
Author: %s
\n' % (headers['Author'])
                else:
                    z['page_info'] += '
Author: %s
\n' % (z['site_author'])
                if headers.has_key('Editor'):
                    z['page_info'] += '
Editor: %s
\n' % (headers['Editor'])
                if headers.has_key('First Published'):
                    z['page_info'] += '
First Published: <meta itemprop="datePublished" content="%s">%s
\n' % (headers['First Published'], headers['First Published'])
                if headers.has_key('Last Updated'):
                    z['page_info'] += '
Last Updated: <meta itemprop="dateModified" content="%s">%s
\n' % (headers['Last Updated'], headers['Last Updated'])

                page_footer = Template(file(os.path.join(z['opt_path_templates'], 'tmpl_footer.html')).read()).substitute(z)
                page_footer = page_footer.decode('utf-8')
                target_content += page_footer

                target_file = open(z['target_path'], 'w')
                target_content = htmlmin.minify(target_content, remove_comments=True)
                target_file.write(target_content.encode('utf-8'))
                target_file.close()

                output_buffer += '    Created HTML file at:\n\n'
                output_buffer += '        %s\n\n' % (z['target_path'])

                state_file = open(z['state_path'], 'w')
                state_file.write(hashlib.md5(file(z['source_path']).read()).hexdigest())
                state_file.close()
                output_buffer += '    Create state at:\n\n'
                output_buffer += '        %s\n\n' % (z['state_path'])

            os.chdir(d_source)
            commit_path = z['source_path'][len(d_source)+1:]
            p = subprocess.Popen(['git', 'add', commit_path])
            p.communicate()
            commit_mark = 'zBuild %s' % (datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S'))
            p = subprocess.Popen(['git', 'commit', commit_path, '-m', commit_mark, '--quiet'])
            p.communicate()
            p = subprocess.Popen(['git', 'push', '--quiet'])
            p.communicate()
            output_buffer += '    Committed source to Git and pushed.\n\n'

            # Commit the target file:
            os.chdir(d_htdocs)
            commit_path = z['target_path'][len(d_htdocs)+1:]
            p = subprocess.Popen(['git', 'add', commit_path])
            p.communicate()
            commit_mark = 'zBuild %s' % (datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S'))
            p = subprocess.Popen(['git', 'commit', commit_path, '-m', commit_mark, '--quiet'])
            p.communicate()
            p = subprocess.Popen(['git', 'push', '--quiet'])
            p.communicate()
            output_buffer += '    Committed target to Git and pushed.\n\n'

if z['generate_output']:
    output_buffer += 'Pages Updated or Created during this Build\n'
    output_buffer += '------------------------------------------\n\n'
    for page_changed in pages_changed:
        output_buffer += '*   %s\n' % (page_changed)

    output_path = os.path.join(z['opt_path_build'], '%s.md' % (build))
    output_file = open(output_path, 'w')
    output_file.write(output_buffer)
    output_file.close()
    output_buffer += '\nThis log has been saved as: %s' % (output_path)
    print output_buffer
<|endoftext|>


<commit_before>import threading
import time

from SimpleCV import *

class TrackObj:

    def __init__(self):
        self.active = False
        self.hasObj = False

    def _trackObjByHue(self, hue, freq):

        cam = Camera()

        self.active = True

        while self.active:

            t0 = time.time()

            img = cam.getImage()

            topCropH = 60
            img = img.resize(w = 200)
            img = img.crop(0, topCropH, img.width, img.height - topCropH)

            col = Color.hueToBGR(hue)
            iBin = img.hueDistance(color = col, minsaturation = 150).binarize(40)

            blobs = iBin.findBlobs()

            if blobs is not None:
                self.hasObj = True
                blobs.sortArea()
                obj = blobs[0]
                x, y = obj.centroid()
                hPos = (img.width / 2 - x) / (img.width / 2)
                areaPct = obj.area() / img.area()
                dl = img.dl()
                obj.drawRect(layer = dl, color = (0, 255, 0), width = 2)
            else:
                self.hasObj = False

            img.show()

            dt = time.time() - t0
            if dt < 1 / freq:
                time.sleep(1 / freq -dt)

            return self.hasObj, hPos, areaPct,

    def trackObjByHue(self, hue, freq):
        th = threading.Thread(target = _trackObjByHue, args = (hue, freq))
        th.start()

    def stop():
        self.active = False
        self.hasObj = False
<commit_msg>Added Camera class and updated ObjTracker class<commit_after>import threading
import time

import SimpleCV

class Camera:

    def __init__(self):
        self.camera = SimpleCV.Camera()
        self.objTracker = ObjTracker(self.camera)
        self.display = False

    def _show(self, freq):

        self.display = True

        while self.display:

            t0 = time.time()

            img = self.camera.getImage()

            topCropH = 60
            img = img.resize(w = 200)
            img = img.crop(0, topCropH, img.width, img.height - topCropH)
            img.show()

            dt = time.time() - t0
            if dt < 1 / freq:
                time.sleep(1 / freq -dt)

    def show(self, freq = 10):
        th = threading.Thread(target = self._show, args = [freq])
        th.start()

    def stop(self):
        self.display = False

class ObjTracker:

    def __init__(self, camera):
        self.camera = camera
        self.display = True
        self.active = False
        self.nbObj = 0
        self.objHPos = []
        self.objVPos = []
        self.objAreaRatio = []

    def _trackObjByHue(self, hue, freq):

##        cam = SimpleCV.Camera()

        self.active = True

        while self.active:

            t0 = time.time()

            img = self.camera.getImage()

            topCropH = 60
            img = img.resize(w = 200)
            img = img.crop(0, topCropH, img.width, img.height - topCropH)

            col = SimpleCV.Color.hueToBGR(hue)
            iBin = img.hueDistance(color = col, minsaturation = 150).binarize(40)

            blobs = iBin.findBlobs()

            if blobs is not None:
                self.nbObj = 1
                blobs.sortArea()
                obj = blobs[0]
                x, y = obj.centroid()
                self.objHPos = (img.width / 2 - x) / (img.width / 2) # Inverse x axis so positive value corresponds to positive rotation in robot coord system
                self.objVPos = (y - img.height / 2) / (img.height / 2)
                self.objAreaRatio = obj.area() / img.area()
                if self.display:
                    dl = img.dl()
                    obj.drawRect(layer = dl, color = (0, 255, 0), width = 2)
            else:
                self.nbObj = 0
                self.objHPos = []
                self.objVPos = []
                self.objAreaRatio = []

            if self.display:
                img.show()

            dt = time.time() - t0
            if dt < 1 / freq:
                time.sleep(1 / freq -dt)

    def trackObjByHue(self, hue, freq = 10):
        th = threading.Thread(target = self._trackObjByHue, args = (hue, freq))
        th.start()

    def stop(self):
        self.active = False
        self.nbObj = 0
        self.objHPos = []
        self.objVPos = []
        self.objAreaRatio = []

    def hasObj(self):
        if self.nbObj > 0:
            return True
        else:
            return False

    def getObjHPos(self):
        return self.objHPos

    def getObjVPos(self):
        return self.objVPos

    def getObjAreaRatio(self):
        return self.objAreaRatio

    def setDisplay(self, display):
        self.display = display
<|endoftext|>


<commit_before>from oracle.tests import OracleTests
from client.tests import ClientTests

import unittest

TESTS = [
  OracleTests,
  ClientTests,
]

def test():
  suite = []
  for test_cls in TESTS:
    st = unittest.TestLoader().loadTestsFromTestCase(test_cls)
    suite.append(st)
  suite = unittest.TestSuite(suite)
  unittest.TextTestRunner(verbosity=2).run(suite)

if __name__=="__main__":
  test()

<commit_msg>Make test file executable<commit_after>#!/usr/bin/env python2.7
from oracle.tests import OracleTests
from client.tests import ClientTests

import unittest

TESTS = [
  OracleTests,
  ClientTests,
]

def test():
  suite = []
  for test_cls in TESTS:
    st = unittest.TestLoader().loadTestsFromTestCase(test_cls)
    suite.append(st)
  suite = unittest.TestSuite(suite)
  unittest.TextTestRunner(verbosity=2).run(suite)

if __name__=="__main__":
  test()

<|endoftext|>


<commit_before>import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import abroad.machine_learning as ML

# Import machine learning code
from sklearn.model_selection import GroupShuffleSplit, GridSearchCV
from sklearn import metrics
from sklearn import preprocessing
from sklearn import multiclass
from sklearn import svm
from sklearn.ensemble import RandomForestClassifier
from sklearn.pipeline import Pipeline
from sklearn.exceptions import UndefinedMetricWarning
import os, time, pprint, sys, warnings
warnings.simplefilter('ignore', UndefinedMetricWarning)
warnings.simplefilter('ignore', UserWarning)
import datetime

DATAPATH = os.path.join('.', 'data')

today=datetime.datetime.now().isoformat(sep='T')
os.makedirs(os.path.join(DATAPATH,"classification_scores", today))
classification_file=os.path.join(DATAPATH,"classification_scores",today,'classification-report.txt')

def generate_features():

    df7_dir = './data/df_7/'
    df13_dir = './data/df_13/'

    targets = {"All": ['Control', 'Horizontal', 'Vertical', 'Pressure', 'Frown', 'Ambient Light', 'Torch Light'],
              "Light":['Control', 'Ambient Light', 'Torch Light'],
          "Motion":['Control', 'Horizontal', 'Vertical', 'Pressure', 'Frown']}

    artefact_key = {"All": " ",
                   "Light": " light ",
                   "Motion": " motion "}

    features = [{"data":pd.read_csv(os.path.join(df7_dir,'parallel_features_7_%s.csv'%(x)), index_col=0),
                 "sensor": 7, "targets":targets[x],
                 "artefact": artefact_key[x],
                 "type": x} for x  in ['All', 'Light', 'Motion']]
    features.extend([{"data":pd.read_csv(os.path.join(df13_dir,'parallel_features_13_%s.csv'%(x)), index_col=0),
                      "sensor": 13, "targets":targets[x],
                      "artefact": artefact_key[x],
                      "type": x} for x  in ['All', 'Light', 'Motion']])

    return features

def classification(train, test, classifier="rfc", data_name=""):

    # Split data and then binarise y-values
    rand_state = np.random.randint(100)

    splitter = list(
        GroupShuffleSplit(n_splits=10, random_state=rand_state).split(train['X'], train['y'], train['groups']))

    lb_train = preprocessing.LabelBinarizer()
    lb_train.fit(train['y'])

    # Binarize the training data
    lb_test = preprocessing.LabelBinarizer()
    lb_test.fit(test['y'])

    svc_param_grid = [
        {'classify__estimator__C': [1, 10, 100, 1000], 'classify__estimator__kernel': ['linear']},
        {'classify__estimator__C': [1, 10, 100, 1000], 'classify__estimator__gamma': [0.01, 0.001, 0.0001, 0.00001],
         'classify__estimator__kernel': ['rbf']},
    ]

    rfc_param_grid = [
        {"classify__max_depth": [3, None],
         "classify__max_features": [1, 2, 3, 4],
         "classify__min_samples_split": [1, 5, 10],
         "classify__min_samples_leaf": [2, 5, 10],
         "classify__bootstrap": [True, False],
         "classify__criterion": ["gini", "entropy"]}
    ]

    svr = multiclass.OneVsRestClassifier(svm.SVC(class_weight="balanced", decision_function_shape="ovr"))
    rfc = RandomForestClassifier(n_estimators=100, class_weight="balanced")

    f1_score = metrics.make_scorer(metrics.f1_score, average="weighted")

    if classifier == "rfc":
        clf = rfc
        y_train = train['y']
        y_test = test['y']

    elif classifier=="svr":
        clf = svr
        y_train = lb_train.transform(train['y'])
        y_test = lb_test.transform(test['y'])

    c_dict = {"svr": svc_param_grid,
              "rfc": rfc_param_grid}

    pipe = Pipeline([
        ('normalise', preprocessing.RobustScaler()),
        ('classify', clf)
    ])

    classifier_info = {"params":None, "preds": None, "clf": None}

    now = time.time()
    grid = GridSearchCV(pipe, c_dict[classifier], scoring=f1_score, cv=splitter, n_jobs=-2, iid=False)
    grid.fit(train['X'], y_train)
    tt = time.time() - now
    tt_format = "{0} hours, {1} mins, {2} seconds and {3} ms\n".format(tt // 3600, tt % 3600 // 60, tt % 60 // 1,
                                                                       tt // 1)
    print("Training for \"{0}\" took {1}".format(data_name, tt_format))

    file_output = """Using {0} data\n\nUsing {1} classifier.
====================\n
Best parameters set found on development set:\n\n{2}\n
Detailed Classification Report
====================\n
The model is trained on the full training set.
The scores are computed on the full test set.\n
{3}\n"""
    means = grid.cv_results_['mean_test_score']
    stds = grid.cv_results_['std_test_score']
    grid_scores = "\n".join(["%0.3f (+/-%0.03f) for %r" % (mean, std * 2, params) for mean, std, params in zip(means, stds, grid.cv_results_['params'])])
    with open(os.path.join("logs","grid_scores.log"), "a") as gsf:
        gsf.write("Scores for {}".format(data_name))
        gsf.write(grid_scores)

    classifier_info['params'] = grid.best_params_
    y_true, y_pred = y_test, grid.predict(test['X'])
    classifier_info['preds'] = y_pred
    classifier_info['clf'] = grid.best_estimator_
    clf_report = metrics.classification_report(y_true, y_pred)
    best_param_string = "\n".join(['\t%s: %r' % (param_name, classifier_info['params'][param_name]) for param_name in sorted(classifier_info['params'])])
    print(file_output.format(data_name, classifier, best_param_string, clf_report))
    with open(classification_file, "a") as cf:
        cf.write(file_output.format(data_name, classifier, best_param_string, clf_report))

    return classifier_info

def pipeline(split_data, classifier="rfc", data_name=""):
    now_pipeline = time.time()
    info = classification(split_data[0], split_data[1], classifier, data_name)
    tt = time.time()-now_pipeline
    tt_format = "{0} hours, {1} mins, {2} seconds and {3} ms\n".format(tt//3600, tt%3600//60, tt%60//1, tt//1)
    print("Training and testing for \"{0}\" took {1}".format(data_name, tt_format))
    return info

if __name__=="__main__":

    feature_sets= ['Sensor 7 - All', 'Sensor 7 - Light', 'Sensor 7 - Motion', 'Sensor 13 - All', 'Sensor 13 - Light', 'Sensor 13 - Motion']

    features = generate_features()

    for idx, df in enumerate(features):
        print("Processing {type} artefacts for sensor {sensor}".format(**df))
        split_data = ML.test_train_split(df['data'])
        fname = "s{sensor}-{type}".format(**df)
        # Write data to file for later use
        for k, v in split_data[0].items():
            v.to_csv(os.path.join(DATAPATH, "partitioned_data","training","%s-%s.csv"%(fname,k)),index=False)
        for k, v in split_data[1].items():
            v.to_csv(os.path.join(DATAPATH, "partitioned_data","testing","%s-%s.csv"%(fname,k)),index=False)
        print("Testing for %s" % feature_sets[idx])
        for estimator in ['rfc', 'svr']:
            print("Estimator:\t%s" % estimator)
            info = pipeline(split_data, classifier = estimator, data_name = feature_sets[idx])
            pprint.pprint(info)

<commit_msg>Added TODO<commit_after>import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import abroad.machine_learning as ML

# Import machine learning code
from sklearn.model_selection import GroupShuffleSplit, GridSearchCV
from sklearn import metrics
from sklearn import preprocessing
from sklearn import multiclass
from sklearn import svm
from sklearn.ensemble import RandomForestClassifier
from sklearn.pipeline import Pipeline
from sklearn.exceptions import UndefinedMetricWarning
import os, time, pprint, sys, warnings
warnings.simplefilter('ignore', UndefinedMetricWarning)
warnings.simplefilter('ignore', UserWarning)
import datetime

DATAPATH = os.path.join('.', 'data')

today=datetime.datetime.now().isoformat(sep='T')
os.makedirs(os.path.join(DATAPATH,"classification_scores", today))
classification_file=os.path.join(DATAPATH,"classification_scores",today,'classification-report.txt')

def generate_features():

    df7_dir = './data/df_7/'
    df13_dir = './data/df_13/'

    targets = {"All": ['Control', 'Horizontal', 'Vertical', 'Pressure', 'Frown', 'Ambient Light', 'Torch Light'],
              "Light":['Control', 'Ambient Light', 'Torch Light'],
          "Motion":['Control', 'Horizontal', 'Vertical', 'Pressure', 'Frown']}

    artefact_key = {"All": " ",
                   "Light": " light ",
                   "Motion": " motion "}

    features = [{"data":pd.read_csv(os.path.join(df7_dir,'parallel_features_7_%s.csv'%(x)), index_col=0),
                 "sensor": 7, "targets":targets[x],
                 "artefact": artefact_key[x],
                 "type": x} for x  in ['All', 'Light', 'Motion']]
    features.extend([{"data":pd.read_csv(os.path.join(df13_dir,'parallel_features_13_%s.csv'%(x)), index_col=0),
                      "sensor": 13, "targets":targets[x],
                      "artefact": artefact_key[x],
                      "type": x} for x  in ['All', 'Light', 'Motion']])

    return features

def classification(train, test, classifier="rfc", data_name=""):

    # Split data and then binarise y-values
    rand_state = np.random.randint(100)

    splitter = list(
        GroupShuffleSplit(n_splits=10, random_state=rand_state).split(train['X'], train['y'], train['groups']))

    lb_train = preprocessing.LabelBinarizer()
    lb_train.fit(train['y'])

    # Binarize the training data
    lb_test = preprocessing.LabelBinarizer()
    lb_test.fit(test['y'])

    svc_param_grid = [
        {'classify__estimator__C': [1, 10, 100, 1000], 'classify__estimator__kernel': ['linear']},
        {'classify__estimator__C': [1, 10, 100, 1000], 'classify__estimator__gamma': [0.01, 0.001, 0.0001, 0.00001],
         'classify__estimator__kernel': ['rbf']},
    ]

    rfc_param_grid = [
        {"classify__max_depth": [3, None],
         "classify__max_features": [1, 2, 3, 4],
         "classify__min_samples_split": [1, 5, 10],
         "classify__min_samples_leaf": [2, 5, 10],
         "classify__bootstrap": [True, False],
         "classify__criterion": ["gini", "entropy"]}
    ]

    svr = multiclass.OneVsRestClassifier(svm.SVC(class_weight="balanced", decision_function_shape="ovr"))
    rfc = RandomForestClassifier(n_estimators=100, class_weight="balanced")
    #TODO: Include Naive Bayes. Check why SVR is assigning multiple labels - maybe remove it.
    f1_score = metrics.make_scorer(metrics.f1_score, average="weighted")

    if classifier == "rfc":
        clf = rfc
        y_train = train['y']
        y_test = test['y']

    elif classifier=="svr":
        clf = svr
        y_train = lb_train.transform(train['y'])
        y_test = lb_test.transform(test['y'])

    c_dict = {"svr": svc_param_grid,
              "rfc": rfc_param_grid}

    pipe = Pipeline([
        ('normalise', preprocessing.RobustScaler()),
        ('classify', clf)
    ])

    classifier_info = {"params":None, "preds": None, "clf": None}

    now = time.time()
    grid = GridSearchCV(pipe, c_dict[classifier], scoring=f1_score, cv=splitter, n_jobs=-2, iid=False)
    grid.fit(train['X'], y_train)
    tt = time.time() - now
    tt_format = "{0} hours, {1} mins, {2} seconds and {3} ms\n".format(tt // 3600, tt % 3600 // 60, tt % 60 // 1,
                                                                       tt // 1)
    print("Training for \"{0}\" took {1}".format(data_name, tt_format))

    file_output = """Using {0} data\n\nUsing {1} classifier.
====================\n
Best parameters set found on development set:\n\n{2}\n
Detailed Classification Report
====================\n
The model is trained on the full training set.
The scores are computed on the full test set.\n
{3}\n"""
    means = grid.cv_results_['mean_test_score']
    stds = grid.cv_results_['std_test_score']
    grid_scores = "\n".join(["%0.3f (+/-%0.03f) for %r" % (mean, std * 2, params) for mean, std, params in zip(means, stds, grid.cv_results_['params'])])
    with open(os.path.join("logs","grid_scores.log"), "a") as gsf:
        gsf.write("Scores for {}".format(data_name))
        gsf.write(grid_scores)

    classifier_info['params'] = grid.best_params_
    y_true, y_pred = y_test, grid.predict(test['X'])
    classifier_info['preds'] = y_pred
    classifier_info['clf'] = grid.best_estimator_
    clf_report = metrics.classification_report(y_true, y_pred)
    best_param_string = "\n".join(['\t%s: %r' % (param_name, classifier_info['params'][param_name]) for param_name in sorted(classifier_info['params'])])
    print(file_output.format(data_name, classifier, best_param_string, clf_report))
    with open(classification_file, "a") as cf:
        cf.write(file_output.format(data_name, classifier, best_param_string, clf_report))

    return classifier_info

def pipeline(split_data, classifier="rfc", data_name=""):
    now_pipeline = time.time()
    info = classification(split_data[0], split_data[1], classifier, data_name)
    tt = time.time()-now_pipeline
    tt_format = "{0} hours, {1} mins, {2} seconds and {3} ms\n".format(tt//3600, tt%3600//60, tt%60//1, tt//1)
    print("Training and testing for \"{0}\" took {1}".format(data_name, tt_format))
    return info

if __name__=="__main__":

    feature_sets= ['Sensor 7 - All', 'Sensor 7 - Light', 'Sensor 7 - Motion', 'Sensor 13 - All', 'Sensor 13 - Light', 'Sensor 13 - Motion']

    features = generate_features()

    for idx, df in enumerate(features):
        print("Processing {type} artefacts for sensor {sensor}".format(**df))
        split_data = ML.test_train_split(df['data'])
        fname = "s{sensor}-{type}".format(**df)
        # Write data to file for later use
        for k, v in split_data[0].items():
            v.to_csv(os.path.join(DATAPATH, "partitioned_data","training","%s-%s.csv"%(fname,k)),index=False)
        for k, v in split_data[1].items():
            v.to_csv(os.path.join(DATAPATH, "partitioned_data","testing","%s-%s.csv"%(fname,k)),index=False)
        print("Testing for %s" % feature_sets[idx])
        for estimator in ['rfc', 'svr']:
            print("Estimator:\t%s" % estimator)
            info = pipeline(split_data, classifier = estimator, data_name = feature_sets[idx])
            pprint.pprint(info)

<|endoftext|>


<commit_before>#!/usr/bin/env python

# Copyright (c) 2001, MetaSlash Inc.  All rights reserved.

"""
Python code operations.
"""

import dis

def LINE_NUM(op):              return dis.opname[op] == 'SET_LINENO'
def LOAD_GLOBAL(op):           return dis.opname[op] == 'LOAD_GLOBAL'
def LOAD_CONST(op):            return dis.opname[op] == 'LOAD_CONST'
def LOAD_NAME(op):             return dis.opname[op] == 'LOAD_NAME'
def LOAD_FAST(op):             return dis.opname[op] == 'LOAD_FAST'
def LOAD_ATTR(op):             return dis.opname[op] == 'LOAD_ATTR'
def STORE_ATTR(op):            return dis.opname[op] == 'STORE_ATTR'
def STORE_FAST(op):            return dis.opname[op] == 'STORE_FAST'
def STORE_GLOBAL(op):          return dis.opname[op] == 'STORE_GLOBAL'
def CALL_FUNCTION(op):         return dis.opname[op] == 'CALL_FUNCTION'
def BINARY_SUBSCR(op):         return dis.opname[op] == 'BINARY_SUBSCR'
def BINARY_ADD(op):            return dis.opname[op] == 'BINARY_ADD'
def BUILD_LIST(op):            return dis.opname[op] == 'BUILD_LIST'
def BUILD_MAP(op):             return dis.opname[op] == 'BUILD_MAP'
def BUILD_TUPLE(op):           return dis.opname[op] == 'BUILD_TUPLE'
def RETURN_VALUE(op):          return dis.opname[op] == 'RETURN_VALUE'
def COMPARE_OP(op):            return dis.opname[op] == 'COMPARE_OP'
def POP_TOP(op):               return dis.opname[op] == 'POP_TOP'
def DUP_TOP(op):               return dis.opname[op] == 'DUP_TOP'
def FOR_LOOP(op):              return dis.opname[op] == 'FOR_LOOP'

def UNPACK_SEQUENCE(op) :
    "Deal w/Python 1.5.2 (UNPACK_[LIST|TUPLE]) or 2.0 (UNPACK_SEQUENCE)"
    return dis.opname[op] in ['UNPACK_SEQUENCE', 'UNPACK_TUPLE', 'UNPACK_LIST']

HAVE_ARGUMENT = dis.HAVE_ARGUMENT

try:
    # EXTENDED_ARG is a Python2.0 feature
    EXTENDED_ARG = dis.EXTENDED_ARG
except:
    EXTENDED_ARG = None

hasname = dis.hasname
haslocal = dis.haslocal
hasconst = dis.hasconst
hascompare = dis.hascompare
name = dis.opname

def getOperand(op, func_code, oparg) :
    if op in hasname :
        return func_code.co_names[oparg]
    elif op in haslocal :
        return func_code.co_varnames[oparg]
    elif op in hasconst :
        return func_code.co_consts[oparg]
    elif op in hascompare :
        return dis.cmp_op[oparg]
    return None

def getLabel(op, oparg, i) :
    if op in dis.hasjrel :
        return i + oparg
    elif op in dis.hasjabs :
        return oparg
    return None

def getInfo(code, index, extended_arg) :
    op = ord(code[index])
    index = index + 1
    if op >= HAVE_ARGUMENT :
        oparg = ord(code[index]) + ord(code[index+1])*256 + extended_arg
        index = index + 2
        extended_arg = 0
        if op == EXTENDED_ARG :
        	extended_arg = oparg * 65536L
    else :
        oparg, extended_arg = 0, 0
    return op, oparg, index, extended_arg

def initFuncCode(func) :
    "Returns (func_code, code, i, maxCode, extended_arg) based on func"

    func_code = func.func_code
    code = func_code.co_code
    return func_code, code, 0, len(code), 0

<commit_msg>add comments/doc<commit_after>#!/usr/bin/env python

# Copyright (c) 2001, MetaSlash Inc.  All rights reserved.

"""
Python code operations.
"""

import dis

def LINE_NUM(op):              return dis.opname[op] == 'SET_LINENO'
def LOAD_GLOBAL(op):           return dis.opname[op] == 'LOAD_GLOBAL'
def LOAD_CONST(op):            return dis.opname[op] == 'LOAD_CONST'
def LOAD_NAME(op):             return dis.opname[op] == 'LOAD_NAME'
def LOAD_FAST(op):             return dis.opname[op] == 'LOAD_FAST'
def LOAD_ATTR(op):             return dis.opname[op] == 'LOAD_ATTR'
def STORE_ATTR(op):            return dis.opname[op] == 'STORE_ATTR'
def STORE_FAST(op):            return dis.opname[op] == 'STORE_FAST'
def STORE_GLOBAL(op):          return dis.opname[op] == 'STORE_GLOBAL'
def CALL_FUNCTION(op):         return dis.opname[op] == 'CALL_FUNCTION'
def BINARY_SUBSCR(op):         return dis.opname[op] == 'BINARY_SUBSCR'
def BINARY_ADD(op):            return dis.opname[op] == 'BINARY_ADD'
def BUILD_LIST(op):            return dis.opname[op] == 'BUILD_LIST'
def BUILD_MAP(op):             return dis.opname[op] == 'BUILD_MAP'
def BUILD_TUPLE(op):           return dis.opname[op] == 'BUILD_TUPLE'
def RETURN_VALUE(op):          return dis.opname[op] == 'RETURN_VALUE'
def COMPARE_OP(op):            return dis.opname[op] == 'COMPARE_OP'
def POP_TOP(op):               return dis.opname[op] == 'POP_TOP'
def DUP_TOP(op):               return dis.opname[op] == 'DUP_TOP'
def FOR_LOOP(op):              return dis.opname[op] == 'FOR_LOOP'

def UNPACK_SEQUENCE(op) :
    "Deal w/Python 1.5.2 (UNPACK_[LIST|TUPLE]) or 2.0 (UNPACK_SEQUENCE)"
    return dis.opname[op] in ['UNPACK_SEQUENCE', 'UNPACK_TUPLE', 'UNPACK_LIST']

HAVE_ARGUMENT = dis.HAVE_ARGUMENT

try:
    # EXTENDED_ARG is a Python2.0 feature
    EXTENDED_ARG = dis.EXTENDED_ARG
except:
    EXTENDED_ARG = None

hasname = dis.hasname
haslocal = dis.haslocal
hasconst = dis.hasconst
hascompare = dis.hascompare
name = dis.opname

def getOperand(op, func_code, oparg) :
    if op in hasname :
        return func_code.co_names[oparg]
    elif op in haslocal :
        return func_code.co_varnames[oparg]
    elif op in hasconst :
        return func_code.co_consts[oparg]
    elif op in hascompare :
        return dis.cmp_op[oparg]
    return None

def getLabel(op, oparg, i) :
    if op in dis.hasjrel :
        return i + oparg
    elif op in dis.hasjabs :
        return oparg
    return None

def getInfo(code, index, extended_arg) :
    """Returns (op, oparg, index, extended_arg) based on code
         this is a helper function while looping through byte code,
         refer to the standard module dis.disassemble() for more info"""

    # get the operation we are performing
    op = ord(code[index])
    index = index + 1
    if op >= HAVE_ARGUMENT :
        # get the argument to the operation
        oparg = ord(code[index]) + ord(code[index+1])*256 + extended_arg
        index = index + 2
        extended_arg = 0
        if op == EXTENDED_ARG :
        	extended_arg = oparg * 65536L
    else :
        oparg, extended_arg = 0, 0
    return op, oparg, index, extended_arg

def initFuncCode(func) :
    """Returns (func_code, code, i, maxCode, extended_arg) based on func,
         this is a helper function to setup looping through byte code"""

    func_code = func.func_code
    code = func_code.co_code
    return func_code, code, 0, len(code), 0

<|endoftext|>