refactoring and add various comments
authorOrakaro <nhatminh_179@hotmail.com>
Mon, 21 Jul 2014 14:52:23 +0000 (23:52 +0900)
committerOrakaro <nhatminh_179@hotmail.com>
Mon, 21 Jul 2014 14:52:23 +0000 (23:52 +0900)
rainbowstream/c_image.py
rainbowstream/colors.py
rainbowstream/config.py
rainbowstream/db.py
rainbowstream/pure_image.py
rainbowstream/rainbow.py
setup.py

index e440d405e509b66ba0e4264ddff597e310cd32ec..8bd93288812662f2ac19b074d8cce8071d050362 100644 (file)
@@ -8,6 +8,9 @@ import os
 
 
 def call_c():
+    """
+    Call the C program for converting RGB to Ansi colors
+    """
     library = expanduser('~/.image.so')
     sauce = join(dirname(__file__), 'image.c')
     if not exists(library) or getmtime(sauce) > getmtime(library):
@@ -21,10 +24,16 @@ rgb2short = call_c()
 
 
 def pixel_print(ansicolor):
+    """
+    Print a pixel with given Ansi color
+    """
     sys.stdout.write('\033[48;5;%sm \033[0m' % (ansicolor))
 
 
 def image_to_display(path, start=None, length=None):
+    """
+    Display an image
+    """
     rows, columns = os.popen('stty size', 'r').read().split()
     if not start:
         start = c['IMAGE_SHIFT']
@@ -48,5 +57,9 @@ def image_to_display(path, start=None, length=None):
             pixel_print(rgb2short(r, g, b))
         sys.stdout.write('\n')
 
+
+"""
+For direct using purpose
+"""
 if __name__ == '__main__':
     image_to_display(sys.argv[1])
index 95d34c3bafe9124c33ecf742be6b6cdf1e85045b..bdbc4b44c14d6af7c4009af898b13ed3e86bd44f 100644 (file)
@@ -1,4 +1,3 @@
-
 def basic_color(code):
     """
     16 colors supported
@@ -21,6 +20,9 @@ def term_color(code):
     return inner
 
 
+"""
+16 basic colors
+"""
 default = basic_color('39')
 black = basic_color('30')
 red = basic_color('31')
@@ -38,6 +40,9 @@ light_magenta = basic_color('95')
 light_cyan = basic_color('96')
 white = basic_color('97')
 
+"""
+16 basic colors on background
+"""
 on_default = basic_color('49')
 on_black = basic_color('40')
 on_red = basic_color('41')
index 70325044e9ff3af1fd42bce06e968a20ad660562..4645409f9633e09b40d3e15fb985866ac1f3d60f 100644 (file)
@@ -4,12 +4,15 @@ import os
 import os.path
 from collections import OrderedDict
 
-# Regular expression for comments
+# Regular expression for comments in config file
 comment_re = re.compile(
     '(^)?[^\S\n]*/(?:\*(.*?)\*/[^\S\n]*|/[^\n]*)($)?',
     re.DOTALL | re.MULTILINE
 )
 
+# Config dictionary
+c = {}
+
 
 def fixup(adict, k, v):
     """
@@ -110,38 +113,41 @@ def reload_config():
         print('It seems that ~/.rainbow_config.json has wrong format :(')
 
 
-# Config dictionary
-c = {}
+def init_config():
+    """
+    Init configuration
+    """
+    # Load the initial config
+    config = os.path.dirname(
+        __file__) + '/colorset/config'
+    try:
+        data = load_config(config)
+        for d in data:
+            c[d] = data[d]
+    except:
+        pass
+    # Load user's config
+    rainbow_config = os.environ.get(
+        'HOME',
+        os.environ.get(
+            'USERPROFILE',
+            '')) + os.sep + '.rainbow_config.json'
+    try:
+        data = load_config(rainbow_config)
+        for d in data:
+            c[d] = data[d]
+    except:
+        print('It seems that ~/.rainbow_config.json has wrong format :(')
+    # Load default theme
+    theme_file = os.path.dirname(
+        __file__) + '/colorset/' + c['THEME'] + '.json'
+    try:
+        data = load_config(theme_file)
+        for d in data:
+            c[d] = data[d]
+    except:
+        pass
+
 
-# Load the initial config
-config = os.path.dirname(
-    __file__) + '/colorset/config'
-try:
-    data = load_config(config)
-    for d in data:
-        c[d] = data[d]
-except:
-    pass
-
-# Load user's config
-rainbow_config = os.environ.get(
-    'HOME',
-    os.environ.get(
-        'USERPROFILE',
-        '')) + os.sep + '.rainbow_config.json'
-try:
-    data = load_config(rainbow_config)
-    for d in data:
-        c[d] = data[d]
-except:
-    print('It seems that ~/.rainbow_config.json has wrong format :(')
-
-# Load default theme
-theme_file = os.path.dirname(
-    __file__) + '/colorset/' + c['THEME'] + '.json'
-try:
-    data = load_config(theme_file)
-    for d in data:
-        c[d] = data[d]
-except:
-    pass
+# Init config
+init_config()
\ No newline at end of file
index f8a11397933484e6f3ed2368ffee35000a22f135..1714005d77a4154d9052144b595e5b978a855640 100644 (file)
@@ -9,10 +9,14 @@ class RainbowDB():
     engine = None
 
     def __init__(self):
+        """
+        Init DB
+        """
         if not os.path.isfile('rainbow.db'):
             init_db()
         self.engine = create_engine('sqlite:///rainbow.db', echo=False)
 
+
     def tweet_store(self, tweet_id):
         """
         Store tweet id
@@ -23,6 +27,7 @@ class RainbowDB():
         session.add(t)
         session.commit()
 
+
     def rainbow_to_tweet_query(self, rid):
         """
         Query base of rainbow id
@@ -32,6 +37,7 @@ class RainbowDB():
         res = session.query(Tweet).filter_by(rainbow_id=rid).all()
         return res
 
+
     def tweet_to_rainbow_query(self, tid):
         """
         Query base of tweet id
@@ -41,6 +47,7 @@ class RainbowDB():
         res = session.query(Tweet).filter_by(tweet_id=tid).all()
         return res
 
+
     def message_store(self, message_id):
         """
         Store message id
@@ -51,6 +58,7 @@ class RainbowDB():
         session.add(m)
         session.commit()
 
+
     def rainbow_to_message_query(self, rid):
         """
         Query base of rainbow id
@@ -60,6 +68,7 @@ class RainbowDB():
         res = session.query(Message).filter_by(rainbow_id=rid).all()
         return res
 
+
     def message_to_rainbow_query(self, mid):
         """
         Query base of message id
@@ -69,6 +78,7 @@ class RainbowDB():
         res = session.query(Message).filter_by(message_id=mid).all()
         return res
 
+
     def theme_store(self, theme_name):
         """
         Store theme
@@ -79,6 +89,7 @@ class RainbowDB():
         session.add(th)
         session.commit()
 
+
     def theme_update(self, theme_name):
         """
         Update theme
@@ -90,6 +101,7 @@ class RainbowDB():
             r.theme_name = theme_name
         session.commit()
 
+
     def theme_query(self):
         """
         Query theme
@@ -99,6 +111,7 @@ class RainbowDB():
         res = session.query(Theme).all()
         return res
 
+
     def semaphore_store(self, flag):
         """
         Store semaphore flag
@@ -109,6 +122,7 @@ class RainbowDB():
         session.add(th)
         session.commit()
 
+
     def semaphore_update(self, flag):
         """
         Update semaphore flag
@@ -120,6 +134,7 @@ class RainbowDB():
             r.flag = flag
         session.commit()
 
+
     def semaphore_query(self):
         """
         Query semaphore
index f321797593cfe80c1e069665bb6ea6f599085071..0f0a377c3ac350efdf0dfbdc6aa12eda4724aa5d 100644 (file)
@@ -281,6 +281,9 @@ CLUT = [  # color look-up table
 
 
 def _create_dicts():
+    """
+    Create dictionary
+    """
     short2rgb_dict = dict(CLUT)
     rgb2short_dict = {}
     for k, v in short2rgb_dict.items():
@@ -291,24 +294,39 @@ RGB2SHORT_DICT, SHORT2RGB_DICT = _create_dicts()
 
 
 def short2rgb(short):
+    """
+    Short to RGB
+    """
     return SHORT2RGB_DICT[short]
 
 
 def pixel_print(ansicolor):
+    """
+    Print a pixel with given Ansi color
+    """
     sys.stdout.write('\033[48;5;%sm \033[0m' % (ansicolor))
 
 
 def hex_to_rgb(value):
+    """
+    Hex to RGB
+    """
     value = value.lstrip('#')
     lv = len(value)
     return tuple(int(value[i:i + lv / 3], 16) for i in range(0, lv, lv / 3))
 
 
 def rgb_to_hex(rgb):
+    """
+    RGB to Hex
+    """
     return '%02x%02x%02x' % rgb
 
 
 def rgb2short(r, g, b):
+    """
+    RGB to short
+    """
     dist = lambda s, d: (s[0] - d[0]) ** 2 + \
         (s[1] - d[1]) ** 2 + (s[2] - d[2]) ** 2
     ary = [hex_to_rgb(hex) for hex in RGB2SHORT_DICT]
@@ -317,6 +335,9 @@ def rgb2short(r, g, b):
 
 
 def image_to_display(path, start=None, length=None):
+    """
+    Display an image
+    """
     rows, columns = os.popen('stty size', 'r').read().split()
     if not start:
         start = IMAGE_SHIFT
@@ -340,5 +361,9 @@ def image_to_display(path, start=None, length=None):
             pixel_print(rgb2short(r, g, b))
         sys.stdout.write('\n')
 
+
+"""
+For direct using purpose
+"""
 if __name__ == '__main__':
     image_to_display(sys.argv[1])
index b33ffbbbb451cf29587abc7e7765f643fcd76c17..55e062cb5b0a5c38243dabbe54048cb6513c1c42 100644 (file)
@@ -11,7 +11,6 @@ import argparse
 import time
 import requests
 import webbrowser
-import json
 
 from twitter.stream import TwitterStream, Timeout, HeartbeatTimeout, Hangup
 from twitter.api import *
@@ -28,9 +27,13 @@ from .db import *
 from .c_image import *
 from .py3patch import *
 
-
+# Global values
 g = {}
+
+# Database
 db = RainbowDB()
+
+# Commands
 cmdset = [
     'switch',
     'trend',
@@ -134,7 +137,7 @@ def authen():
         CONSUMER_SECRET)
 
 
-def get_decorated_name():
+def init():
     """
     Init function
     """
@@ -143,13 +146,11 @@ def get_decorated_name():
     name = '@' + t.account.verify_credentials()['screen_name']
     g['original_name'] = name[1:]
     g['decorated_name'] = color_func(c['DECORATED_NAME'])('[' + name + ']: ')
-
     # Theme init
     files = os.listdir(os.path.dirname(__file__) + '/colorset')
     themes = [f.split('.')[0] for f in files if f.split('.')[-1] == 'json']
     g['themes'] = themes
     db.theme_store(c['THEME'])
-
     # Semaphore init
     db.semaphore_store(False)
 
@@ -160,7 +161,6 @@ def switch():
     """
     try:
         target = g['stuff'].split()[0]
-
         # Filter and ignore
         args = parse_arguments()
         try:
@@ -175,7 +175,6 @@ def switch():
         except:
             printNicely(red('Sorry, wrong format.'))
             return
-
         # Public stream
         if target == 'public':
             keyword = g['stuff'].split()[1]
@@ -192,7 +191,6 @@ def switch():
                     args))
             p.start()
             g['stream_pid'] = p.pid
-
         # Personal stream
         elif target == 'mine':
             # Kill old process
@@ -230,7 +228,6 @@ def trend():
         town = g['stuff'].split()[1]
     except:
         town = ''
-
     avail = t.trends.available()
     # World wide
     if not country:
@@ -1354,7 +1351,6 @@ def help():
     """
     s = ' ' * 2
     h, w = os.popen('stty size', 'r').read().split()
-
     # Start
     usage = '\n'
     usage += s + 'Hi boss! I\'m ready to serve you right now!\n'
@@ -1364,7 +1360,6 @@ def help():
     usage += s + 'Any update from Twitter will show up ' + \
         light_yellow('immediately') + '.\n'
     usage += s + 'In addtion, following commands are available right now:\n'
-
     # Twitter help section
     usage += '\n'
     usage += s + grey(u'\u266A' + ' Twitter help\n')
@@ -1380,7 +1375,6 @@ def help():
         ' will show help for list commands.\n'
     usage += s * 2 + light_green('h stream') + \
         ' will show help for stream commands.\n'
-
     # Smart shell
     usage += '\n'
     usage += s + grey(u'\u266A' + ' Smart shell\n')
@@ -1388,7 +1382,6 @@ def help():
         'will be evaluate by Python interpreter.\n'
     usage += s * 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
         ' for current month.\n'
-
     # Config
     usage += '\n'
     usage += s + grey(u'\u266A' + ' Config \n')
@@ -1406,19 +1399,16 @@ def help():
         light_green('config ASCII_ART = False') + ' will set value of ' + \
         light_yellow('ASCII_ART') + ' config key to ' + \
         light_yellow('False') + '.\n'
-
     # Screening
     usage += '\n'
     usage += s + grey(u'\u266A' + ' Screening \n')
     usage += s * 2 + light_green('h') + ' will show this help again.\n'
     usage += s * 2 + light_green('c') + ' will clear the screen.\n'
     usage += s * 2 + light_green('q') + ' will quit.\n'
-
     # End
     usage += '\n'
     usage += s + '-' * (int(w) - 4) + '\n'
     usage += s + 'Have fun and hang tight! \n'
-
     # Show help
     d = {
         'discover': help_discover,
@@ -1612,7 +1602,6 @@ def stream(domain, args, name='Rainbow Stream'):
     """
     Track the stream
     """
-
     # The Logo
     art_dict = {
         c['USER_DOMAIN']: name,
@@ -1621,24 +1610,20 @@ def stream(domain, args, name='Rainbow Stream'):
     }
     if c['ASCII_ART']:
         ascii_art(art_dict[domain])
-
     # These arguments are optional:
     stream_args = dict(
         timeout=args.timeout,
         block=not args.no_block,
         heartbeat_timeout=args.heartbeat_timeout)
-
     # Track keyword
     query_args = dict()
     if args.track_keywords:
         query_args['track'] = args.track_keywords
-
     # Get stream
     stream = TwitterStream(
         auth=authen(),
         domain=domain,
         **stream_args)
-
     try:
         if domain == c['USER_DOMAIN']:
             tweet_iter = stream.user(**query_args)
@@ -1649,8 +1634,6 @@ def stream(domain, args, name='Rainbow Stream'):
                 tweet_iter = stream.statuses.filter(**query_args)
             else:
                 tweet_iter = stream.statuses.sample()
-
-        # Iterate over the stream.
         for tweet in tweet_iter:
             if tweet is None:
                 printNicely("-- None --")
@@ -1679,11 +1662,10 @@ def fly():
     """
     Main function
     """
-    # Spawn stream process
+    # Initial
     args = parse_arguments()
     try:
-        get_decorated_name()
-
+        init()
     except TwitterHTTPError:
         printNicely('')
         printNicely(
@@ -1693,7 +1675,7 @@ def fly():
         save_history()
         os.system('rm -rf rainbow.db')
         sys.exit()
-
+    # Spawn stream process
     p = Process(
         target=stream,
         args=(
@@ -1701,7 +1683,6 @@ def fly():
             args,
             g['original_name']))
     p.start()
-
     # Start listen process
     time.sleep(0.5)
     g['reset'] = True
index 2223acbf74072870390eb9933ede4ca5f9378353..06883651c6280d6386453863a1f76697ddfc46f1 100644 (file)
--- a/setup.py
+++ b/setup.py
@@ -2,7 +2,7 @@ from setuptools import setup, find_packages
 import os, sys
 
 # Bumped version
-version = '0.4.1'
+version = '0.4.2'
 
 # Require
 install_requires = [
@@ -13,6 +13,7 @@ install_requires = [
     "twitter",
     "Pillow",
 ]
+
 # Python 3 doesn't hava pysqlite
 if sys.version[0] == "2":
     install_requires += ["pysqlite"]