text:
require_relative 'authorization'
require_relative 'api/actions'
require_relative 'api/factory'
require_relative 'api/arguments'
require_relative 'configuration'
require_relative 'constants'
require_relative 'mime_type'
require_relative 'null_encoder'
require_relative 'rate_limit'
require_relative 'request/verbs'
require_relative 'validations'

module Github
  # Core class responsible for api interface operations
  class API
    include Constants
    include Authorization
    include MimeType
    include RateLimit
    include Request::Verbs

    attr_reader(*Github.configuration.property_names)

    attr_accessor(*Validations::VALID_API_KEYS)

    attr_accessor :current_options

    # Callback to update current configuration options
     class_eval do
       Github.configuration.property_names.each do |key|
         define_method "#{key}=" do |arg|
           self.instance_variable_set("@#{key}", arg)
           self.current_options.merge!({:"#{key}" => arg})
         end
       end
     end

    # Requires internal libraries
    #
    # @param [String] prefix
    #   the relative path prefix
    # @param [Array[String]] libs
    #   the array of libraries to require
    #
    # @return [self]
    #
    # @api public
    def self.require_all(prefix, *libs)
      libs.each do |lib|
        require "#{File.join(prefix, lib)}"
      end
    end

    # Create new API
    #
    # @api public
    def initialize(options={}, &block)
      opts = Github.configuration.fetch.merge(options)
      @current_options = opts

      Github.configuration.property_names.each do |key|
        send("#{key}=", opts[key])
      end
      if opts.key?(:login) && !opts[:login].nil?
        @login, @password = opts[:login], opts[:password]
      elsif opts.key?(:basic_auth) && !opts[:basic_auth].nil?
        @login, @password = extract_basic_auth(opts[:basic_auth])
      end

      yield_or_eval(&block) if block_given?
    end

    # Call block with argument
    #
    # @api private
    def yield_or_eval(&block)
      return unless block
      block.arity > 0 ? yield(self) : self.instance_eval(&block)
    end

    # Extract login and password from basic_auth parameter
    #
    # @api private
    def extract_basic_auth(auth)
      case auth
      when String
        auth.split(':', 2)
      when Hash
        [auth[:login], auth[:password]]
      end
    end

    # Disable following redirects inside a block
    #
    # @api public
    def disable_redirects
      self.follow_redirects = false
      yield
    ensure
      self.follow_redirects = true
    end

    # List of before callbacks
    #
    # @api public
    def self.before_callbacks
      @before_callbacks ||= []
    end

    # List of after callbacks
    #
    # @api public
    def self.after_callbacks
      @after_callbacks ||= []
    end

    # Before request filter
    #
    # @api public
    def self.before_request(callback, params = {})
      before_callbacks << params.merge(callback: callback)
    end

    # After request filter
    #
    # @api public
    def self.after_request(callback, params = {})
      after_callbacks << params.merge(callback: callback)
    end

    class << self
      attr_reader :root
      alias_method :root?, :root
    end

    def self.root!
      @root = true
    end

    def self.inherited(child_class)
      before_callbacks.reverse_each { |callback|
        child_class.before_callbacks.unshift(callback)
      }
      after_callbacks.reverse_each { |callback|
        child_class.after_callbacks.unshift(callback)
      }
      extend_with_actions(child_class)
      unless child_class.instance_variable_defined?(:@root)
        child_class.instance_variable_set(:@root, false)
      end
      super
    end

    root!

    def self.internal_methods
      api = self
      api = api.superclass until api.root?
      api.public_instance_methods(true)
    end

    def self.extra_methods
      ['actions']
    end

    # Find all the api methods that should be considred by
    # request callbacks.
    #
    # @return [Set]
    #
    # @api private
    def self.request_methods
      @request_methods ||= begin
        methods = (public_instance_methods(true) -
                   internal_methods +
                   public_instance_methods(false)).uniq.map(&:to_s)
        Set.new(methods - extra_methods)
      end
    end

    def self.clear_request_methods!
      @request_methods = nil
    end

    def self.method_added(method_name)
      method_name = method_name.to_s.gsub(/_with(out)?_callback_.*$/, '')
      # Only subclasses matter
      return if self.root?
      return if extra_methods.include?(method_name)
      # Only public methods are of interest
      return unless request_methods.include?(method_name)
      # Do not redefine
      return if (@__methods_added ||= []).include?(method_name)

      class_name     = self.name.to_s.split('::').last.downcase
      with_method    = "#{method_name}_with_callback_#{class_name}"
      without_method = "#{method_name}_without_callback_#{class_name}"

      return if public_method_defined?(with_method)

      [method_name, with_method, without_method].each do |met|
        @__methods_added << met
      end
      return if public_method_defined?(with_method)

      define_method(with_method) do |*args, &block|
        send(:execute, without_method, *args, &block)
      end
      alias_method without_method, method_name
      alias_method method_name, with_method
      clear_request_methods!
    end

    # Filter callbacks based on kind
    #
    # @param [Symbol] kind
    #   one of :before or :after
    #
    # @return [Array[Hash]]
    #
    # @api private
    def filter_callbacks(kind, action_name)
      self.class.send("#{kind}_callbacks").select do |callback|
        callback[:only].nil? || callback[:only].include?(action_name)
      end
    end

    # Run all callbacks associated with this action
    #
    # @param [Symbol] action_name
    #
    # @api private
    def run_callbacks(action_name, &block)
      filter_callbacks(:before, action_name).each { |hook| send hook[:callback] }
      yield if block_given?
      filter_callbacks(:after, action_name).each { |hook| send hook[:callback] }
    end

    # Execute action
    #
    # @param [Symbol] action
    #
    # @api private
    def execute(action, *args, &block)
      action_name = action.to_s.gsub(/_with(out)?_callback_.*$/, '')
      result = nil
      run_callbacks(action_name) do
        result = send(action, *args, &block)
      end
      result
    end

    # Responds to attribute query or attribute clear
    #
    # @api private
    def method_missing(method_name, *args, &block) # :nodoc:
      case method_name.to_s
      when /^(.*)\?$/
        return !!send($1.to_s)
      when /^clear_(.*)$/
        send("#{$1.to_s}=", nil)
      else
        super
      end
    end

    def respond_to?(method_name, include_private = false)
      method_name.to_s.start_with?('clear_') || super
    end

    # Acts as setter and getter for api requests arguments parsing.
    #
    # Returns Arguments instance.
    #
    def arguments(args=(not_set = true), options={}, &block)
      if not_set
        @arguments
      else
        @arguments = Arguments.new(options.merge!(api: self)).parse(*args, &block)
      end
    end

    # Set a configuration option for a given namespace
    #
    # @param [String] option
    # @param [Object] value
    # @param [Boolean] ignore_setter
    #
    # @return [self]
    #
    # @api public
    def set(option, value=(not_set=true), ignore_setter=false, &block)
      raise ArgumentError, 'value not set' if block and !not_set
      return self if !not_set and value.nil?

      if not_set
        set_options option
        return self
      end

      if respond_to?("#{option}=") and not ignore_setter
        return __send__("#{option}=", value)
      end

      define_accessors option, value
      self
    end

    # Defines a namespace
    #
    # @param [Array[Symbol]] names
    #   the name for the scope
    #
    # @example
    #   namespace :scopes
    #
    # @return [self]
    #
    # @api public
    def self.namespace(*names)
      options = names.last.is_a?(Hash) ? names.pop : {}
      names   = names.map(&:to_sym)
      name    = names.pop

      if public_method_defined?(name)
        raise ArgumentError, "namespace '#{name}' is already defined"
      end

      class_name = extract_class_name(name, options)

      define_method(name) do |*args, &block|
        options = args.last.is_a?(Hash) ? args.pop : {}
        API::Factory.new(class_name, current_options.merge(options), &block)
      end
    end

    # Extracts class name from options
    #
    # @param [Hash] options
    # @option options [String] :full_name
    #   the full name for the class
    # @option options [Boolean] :root
    #   if the class is at the root or not
    #
    # @example
    #   extract_class_name(:stats, class_name: :statistics)
    #
    # @return [String]
    #
    # @api private
    def self.extract_class_name(name, options)
      converted  = options.fetch(:full_name, name).to_s
      converted  = converted.split('_').map(&:capitalize).join
      class_name = options.fetch(:root, false) ? '': "#{self.name}::"
      class_name += converted
      class_name
    end

    private

    # Set multiple options
    #
    # @api private
    def set_options(options)
      unless options.respond_to?(:each)
        raise ArgumentError, 'cannot iterate over value'
      end
      options.each { |key, value| set(key, value) }
    end

    # Define setters and getters
    #
    # @api private
    def define_accessors(option, value)
      setter = proc { |val|  set option, val, true }
      getter = proc { value }

      define_singleton_method("#{option}=", setter) if setter
      define_singleton_method(option, getter) if getter
    end

    # Dynamically define a method for setting request option
    #
    # @api private
    def define_singleton_method(method_name, content=Proc.new)
      (class << self; self; end).class_eval do
        undef_method(method_name) if method_defined?(method_name)
        if String === content
          class_eval("def #{method_name}() #{content}; end")
        else
          define_method(method_name, &content)
        end
      end
    end
  end # API
end # Github


text:
package com.wt.studio.plugin.wizard.projects.services.components;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;

import com.wt.studio.plugin.wizard.projects.services.util.HTML5Model;

public class ListView implements Component{
	private ComponentType type = ComponentType.ListView;

	private static String[] popmenus = new String[] { "ADD SubTitle",  "ADD TemplateSubTitle", "Delete ListView" };

	public Menu getSubMenu(final Tree tree) {
		Menu menu = null;
		if (menu != null)
			return menu;

		menu = new Menu(tree);
		tree.setMenu(menu);
		MenuItem menu1 = new MenuItem(menu, SWT.PUSH);
		menu1.setText(popmenus[0]);
		menu1.addListener(SWT.Selection, new Listener() {
			@Override
			public void handleEvent(Event e) {

				TreeItem i = new TreeItem(tree.getSelection()[0], SWT.NULL);
				i.setText(ComponentType.SubTitle.toString());
				i.setText(1,"title");
				tree.getSelection()[0].setExpanded(true);
			}
		});

		MenuItem menu2 = new MenuItem(menu, SWT.PUSH);
		menu2.setText(popmenus[1]);
		menu2.addListener(SWT.Selection, new Listener() {
			@Override
			public void handleEvent(Event e) {
				TreeItem iroot = new TreeItem(tree.getSelection()[0], SWT.NULL);
				iroot.setText(ComponentType.TemplateSubTitle.toString());
				iroot.setText(1,"title");
				tree.getSelection()[0].setExpanded(true);
			}
		});

		MenuItem delMenu = new MenuItem(menu, SWT.PUSH);
		delMenu.setText(popmenus[2]);
		delMenu.addListener(SWT.Selection, new Listener() {
			@Override
			public void handleEvent(Event e) {
				TreeItem i = tree.getSelection()[0];
				i.removeAll();
				i.dispose();
			}
		});

		return menu;
	}

	public String getBeforeHTML5Code(HTML5Model model) {
		return "
\n";
	}

	public String getAfterHTML5Code(HTML5Model model) {
		return "
\n";

	}

	@Override
	public String getJavaScriptCode(HTML5Model model) {
		return "";
	}

	@Override
	public String getJavaCode(HTML5Model model) {
		return  "";
	}

	@Override
	public String getAfterJavaCode(HTML5Model model) {
		return  "";
	}

}

redpajama_set_name: RedPajamaGithub


text:
import React, {PropTypes} from 'react';
import cx from 'classnames';
import _ from 'lodash'
module.exports = React.createClass({
  displayName: 'TabList',

  propTypes: {
    className: PropTypes.string,
    children: PropTypes.oneOfType([
      PropTypes.object,
      PropTypes.array
    ])
  },

  render() {
    const { children } = this.props;
    let activeIndex = 0;
    let cList = React.Children.map(children,(item,index)=>{
        const { selected } = item.props;
        if(selected){
            activeIndex = index;
        }
        return React.cloneElement(item,{
            selectTab:this.selectTab
        });

    });

    return (

        {cList}

    );
  },
  selectTab(item) {

        this.props.onSelectTab && this.props.onSelectTab(item);
  }

});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Repo2.Core.ns11.Exceptions;
using Repo2.Core.ns11.Extensions.StringExtensions;
using Repo2.Core.ns11.ReflectionTools;

namespace Repo2.Core.ns11.Comparisons
{
    public abstract class PropertyComparerBase<T>
    {
        public PropertyComparerBase(T obj1, T obj2)
        {
            _1 = obj1;
            _2 = obj2;
            _methods = new Dictionary<Type, Func<object, object, bool>>
            {
                { typeof(string   ), (b1, b2) => CompareString  (b1, b2) },
                { typeof(int      ), (b1, b2) => CompareInt     (b1, b2) },
                { typeof(int?     ), (b1, b2) => CompareInt_    (b1, b2) },
                { typeof(DateTime ), (b1, b2) => CompareDate    (b1, b2) },
                { typeof(DateTime?), (b1, b2) => CompareDate_   (b1, b2) },
                { typeof(decimal  ), (b1, b2) => CompareDecimal (b1, b2) },
                { typeof(uint     ), (b1, b2) => CompareUInt    (b1, b2) },
                { typeof(ulong    ), (b1, b2) => CompareULong   (b1, b2) },
                { typeof(double   ), (b1, b2) => CompareDouble  (b1, b2) },
                { typeof(bool     ), (b1, b2) => CompareBool    (b1, b2) },
            };
        }

        protected T _1;
        protected T _2;
        private List<string> _diff = new List<string>();
        protected string _diffText;
        protected Dictionary<Type, Func<object, object, bool>> _methods;

        protected abstract List<string> GetPropertiesToCompare();

        public bool SameValues => _diff.Count == 0;
        public string DiffText => string.Join(Environment.NewLine, _diff);

        public bool Only1HasValue  => (_1 != null) && (_2 == null);
        public bool Only2HasValue  => (_1 == null) && (_2 != null);
        public bool BothHaveValues => (_1 != null) && (_2 != null);
        public bool BothAreNull    => (_1 == null) && (_2 == null);

        public virtual bool CompareValues(out string diffText)
        {
            _diff.Clear();
            if (BothAreNull) goto Return;
            if (_1 == null) AddDiffText("self", "NULL", "has_value");
            if (_2 == null) AddDiffText("self", "has_value", "NULL");
            if (!SameValues) goto Return;
            var comparableProps = GetPropertiesToCompare();

            foreach (var propName in comparableProps)
            {
                var prop = GetRuntimePropertyByName(propName);
                var typ = GetRuntimePropertyType(prop);
                var val1 = prop.GetValue(_1);
                var val2 = prop.GetValue(_2);
                if (val1 == null && val2 == null) continue;
                if (BothBlank(typ, val1, val2)) continue;

                if (val1 == null)
                {
                    AddDiffText(propName, "NULL", val2);
                    continue;
                }
                if (val2 == null)
                {
                    AddDiffText(propName, val1, "NULL");
                    continue;
                }

                var b1 = val1;
                var b2 = val2;

                if (typ.Namespace == "System")
                {
                    try   { b1 = Convert.ChangeType(val1, typ); }
                    catch { }
                    try   { b2 = Convert.ChangeType(val2, typ); }
                    catch { }
                }

                if (!_methods[typ](b1, b2)) AddDiffText(propName, b1, b2);
            }

            CompareNonListedProperties();

            Return:
            diffText = DiffText;
            return SameValues;
        }

        private static PropertyInfo GetRuntimePropertyByName(string propName)
        {
            var prop = typeof(T).GetRuntimeProperty(propName);

            if (prop == null)
                prop = typeof(T).GetRuntimeProperties()
                    .SingleOrDefault(x => x.Name == propName);

            if (prop == null)
            {
                var props = typeof(T).GetRuntimeProperties();
                prop = props.SingleOrDefault(x => x.Name == propName);
            }
            if (prop == null) throw Fault.NoMember(propName);
            return prop;
        }

        private Type GetRuntimePropertyType(PropertyInfo prop)
        {
            var typ = prop.PropertyType.IsNullableType()
                    ? Nullable.GetUnderlyingType(prop.PropertyType)
                    : prop.PropertyType;

            if (typ.GetTypeInfo().IsEnum) typ = typeof(int);

            if (!_methods.ContainsKey(typ))
                throw Fault.Unsupported(typ);

            return typ;
        }

        private bool BothBlank(Type typ, object val1, object val2)
        {
            if (typ != typeof(string)) return false;
            var s1 = val1?.ToString() ?? string.Empty;
            var s2 = val2?.ToString() ?? string.Empty;
            return s1.IsBlank()
                && s2.IsBlank();
        }

        protected virtual void CompareNonListedProperties()
        {
        }

        protected void AddDiffText(string propName, object value1, object value2)
            => _diff.Add($"{propName} : [{value1}] -vs- [{value2}]");

        protected bool Compare(string propName, int value1, int value2)
        {
            var same = CompareInt(value1, value2);
            if (!same) AddDiffText(propName, value1, value2);
            return same;
        }

        protected bool Compare(string propName, string value1, string value2)
        {
            var same = CompareString(value1, value2);
            if (!same) AddDiffText(propName, value1, value2);
            return same;
        }

        /*
         *
         *
         *   Overridable Compare methods
         *
         *
         */

        protected virtual bool CompareString(object value1, object value2)
            => value1?.ToString()?.Trim()?.ToLower()
            == value2?.ToString()?.Trim()?.ToLower();

        protected virtual bool CompareInt(object value1, object value2)
            => (int)value1 == (int)value2;

        protected virtual bool CompareInt_(object value1, object value2)
            => (int?)value1 == (int?)value2;

        protected virtual bool CompareDate(object value1, object value2)
            => (DateTime)value1 == (DateTime)value2;

        protected virtual bool CompareDate_(object value1, object value2)
            => (DateTime?)value1 == (DateTime?)value2;

        protected virtual bool CompareDecimal(object value1, object value2)
            => (decimal)value1 == (decimal)value2;

        protected virtual bool CompareUInt(object value1, object value2)
            => (uint)value1 == (uint)value2;

        protected virtual bool CompareULong(object value1, object value2)
            => (ulong)value1 == (ulong)value2;

        protected virtual bool CompareDouble(object value1, object value2)
            => (double)value1 == (double)value2;

        protected virtual bool CompareBool(object value1, object value2)
            => (bool)value1 == (bool)value2;
    }
}


text:
;(function($) {
	$.widget('naxx.config_disk', $.naxx.config, {
		options: {
			index: 0
		},
		object: {
			$tab: null,
			$smart: null,
			$smarttestresult_short: null,
			$smarttestresult_long: null,
			$progress: []
		},
		buttons: [
			{
				type: 'settingBtn',
				text: 'Scan disk',
				attr: {
					symbol: 'text:scan_disk'
				},
				callback: function(self, element){
					$(':naxx-config_disk').config_disk('badblock');
					return false;
				}
			}
		],
		resizePrivate: function(){
			var self = this, element = $(this.element);
			self.object.$smart.setGridHeight(element.find('.statusPanel').height() - $('.ui-tabs-nav', $(this)).height());
			//self.object.$smart.setGridWidth(element.find('.tablePanel').width());
		},
		initTable: function(){
			var self = this, element = $(this.element);
			self.object.$grid = element.find('table.grid').jqGrid({
				altRows: true,
				scrollrows: true,
				autowidth: true,
				height: 'auto',
				datatype: 'local',
				rownumbers: true,
				colNames : ['Model', 'size', 'smart', 'state', 'checking'],
				colModel : [
					{ name : 'model', width : 100, align: 'left', sortable: false},
					{ name : 'size_GB', width : 50, align: 'left', sortable: false},
					{ name : 'smart_info_color', width : 30, align: 'left', sortable: false},
					{ name : 'state', width : 50, align: 'left', sortable: false},
					{ name : 'state_badblocks', width : 50, align: 'left', sortable: false}
				],
				shrikToFit: true,
				onSelectRow: function(id){
					$('div.statusPanel span[name]').text('');
					$('span[name=disk_health]:eq(0)').html('');
					self.options.index = id - 1 ;
					self.object.$tab.trigger('tabsselect');
				}
			}).show();

			self.object.$smart = element.find('table.smart').jqGrid({
				altRows: true,
				scrollrows: true,
				width: '100%',
				height: 210,
				datatype: 'local',
				colNames : ['id' ,'attribute name' ,'value', 'raw value', 'worst', 'threshold', 'status'],
				colModel : [
					{ name : 'id', width : 10, align: 'left', sortable: false},
					{ name : 'attribute', width : 200, align: 'left', sortable: false},
					{ name : 'value', width : 50, align: 'left', sortable: false},
					{ name : 'raw_value', width : 50, align: 'left', sortable: false},
					{ name : 'worst', width : 50, align: 'left', sortable: false},
					{ name : 'threshold', width : 50, align: 'left', sortable: false},
					{ name : 'status', width : 50, align: 'left', sortable: false}
				],
				shrikToFit: true,
				onSelectRow: function(id){
				}
			}).show();

			//self.object.$smart.setGridHeight($('#smartinfo').height()-$('smartinfo .ui-jqgrid-labels').height());

			self.object.$grid.setGridHeight(element.find('.tablePanel').height() - $('.ui-jqgrid-hdiv', '.tablePanel').height());
			self.object.$grid.setGridWidth(element.find('.tablePanel').width());
		},

		//重新填入所有攝影機資料
		reload : function(bRefreshTableOnly)
		{
			var self = this, element = $(this.element);
			var reload = false;
			if(bRefreshTableOnly == null) bRefreshTableOnly = false;
			self.object.$progress = [];

			clearTimeout(self.object.$timeout);
			if(self.object.$grid.getGridParam('records') > 0) bFirst = false;
			else bFirst = true;
			$.naxx.teleport.Exec($.naxx.path.disk, 'disk_query', '', function(res){
				if($(':naxx-config_disk').length == 0) return;
				//if(self.object.$grid != null) self.object.$grid.jqGrid('clearGridData');
				$.extend($.naxx.disk, res);
				self.parseDisk();
				for (var i = 0; i < $.naxx.capability.disk; i++)
				{
					if(!bFirst)
						self.object.$grid.setRowData(i+1, $.naxx.disk[i]);
					else
						self.object.$grid.addRowData(i+1, $.naxx.disk[i]);
					if($.naxx.disk[i].state == 'DISK_UNCONNECTED')
						$('#'+(i+1), element).hide();
					if($.naxx.disk[i].badblocks_progress>=0)
					{
						self.object.$progress.push('Disk '+(i+1)+' checking bad blocks: '+$.naxx.disk[i].badblocks_progress+'%');
						reload = true;
					}
				}
				if ($('.jqgrow:visible').length > 0 && !bRefreshTableOnly)
					self.object.$grid.setSelection($('.jqgrow:visible').eq(0).attr('id'));
				if (self.object.$progress.length>0 || reload)
					self.object.$timeout = setTimeout(function(){self.reload(true)}, 1500);
			});
		},

		updateForm: function(){
			var self = this, element = $(this.element);
			$('form fieldset:eq(0) div', element).remove();
			$.each(self.object.$progress, function(index, value){
					$('
'+value+'
').appendTo($('form fieldset', element));
			});
		},

		parseDisk: function(){
			var self = this, element = $(this.element);
			for (var i = 0; i < $.naxx.capability.disk; i++)
			{
				$.naxx.disk[i]['size_GB'] = ($.naxx.disk[i]['size']/1024).toFixed(3)+' GB';
				$.naxx.disk[i]['state_badblocks'] = $.naxx.disk[i]['badblocks_progress'] >= 0 ? $.naxx.disk[i]['badblocks_progress']+'%' : '';
				$.naxx.disk[i]['smart_info_color'] = $.naxx.disk[i]['smart_info'] == 'PASSED' ? ''+$.naxx.disk[i]['smart_info']+'' : ''+$.naxx.disk[i]['smart_info']+'';
			}
		},

		initOther: function(){
			var self = this, element = $(this.element);
			$('#long_test').button().click(function(){self.smarttest('long')});
			$('#short_test').button().click(function(){self.smarttest('short')});
			$('#shedule_setting').button().click(function(){self.smartschedule()});
			$('div#short_hour_list a').addClass('short');
			$('div#long_hour_list a').addClass('long');
			$('input#short_hour').menu({
					content: $('#short_hour_list').html(),
					width: 50,
					maxHeight: 100,
					bindings: {
						'ul a.short': function(){
							$('#short_hour').val($(this).text());
						}
					}
			});
			$('input#long_hour').menu({
					content: $('#long_hour_list').html(),
					width: 50,
					maxHeight: 100,
					bindings: {
						'ul a.long': function(){
							$('#long_hour').val($(this).text());
						}
					}
			});
			self.object.$tab = $('div.statusPanel').tabs({
					selected: 0,
					select: function(e, ui)
					{
						clearTimeout(self.object.$smarttestresult_long);
						clearTimeout(self.object.$smarttestresult_short);
						switch(ui.tab.hash)
						{
						case '#manual_test':
							$('[name=manual_test_result]').html('');
							$('[name=manual_test_result_long]').html('');
							self.getsmarttest('short');
							self.getsmarttest('long');
							break;
						case '#overview':
							self.disksummary();
							break;
						case '#diskinfo':
							self.diskinfo();
							break;
						case '#smartinfo':
							self.smartinfo();
							break;
						case '#schedule':
							break;
						}
					}
			});
			$("div.statusPanel").bind("tabsselect", function() {
					clearTimeout(self.object.$smarttestresult_long);
					clearTimeout(self.object.$smarttestresult_short);
					switch($('div.statusPanel').tabs('option', 'selected'))
					{
						case 3:
							$('[name=manual_test_result]').html('');
							$('[name=manual_test_result_long]').html('');
							self.getsmarttest('short');
							self.getsmarttest('long');
							break;
						case 0:
							self.disksummary();
							break;
						case 1:
							self.diskinfo();
							break;
						case 2:
							self.smartinfo();
							break;
						case '#schedule':
							break;
					}
			});
		},

		smartinfo: function(){
			var self = this, element = $(this.element);
			if(self.object.$smart != null) self.object.$smart.jqGrid('clearGridData');
			$.naxx.teleport.Exec($.naxx.path.disk, 'smart_info', 'target='+self.options.index, function(data){
				var id = 1;
				$.each(data, function(key, value){
					value['id'] = key;
					self.object.$smart.jqGrid('addRowData', id, value);
					id++;
				});
			});
		},

		diskinfo: function(){
			var self = this, element = $(this.element);
			$.naxx.teleport.Exec($.naxx.path.disk, 'disk_info', 'target='+self.options.index, function(data){
				$.each(data, function(key, value){
					$('[name='+key+']').html(value);
				});
			});
		},

		disksummary: function(){
			var self = this, element = $(this.element);
			$.naxx.teleport.Exec($.naxx.path.disk, 'disk_summary', 'target='+self.options.index, function(data){
				$.each(data, function(key, value){
					$('[name='+key+']').html(value);
				});
			});
		},

		badblock: function(){
			var self = this, element = $(this.element);
			$.blockUI({message: '
<button id="yes" symbol="text:yes"></button><button id="cancel" symbol="text:cancel">
'});
			$('#yes').button().click(function(){
				$.naxx.teleport.Exec($.naxx.path.disk, 'disk_bad_blocks', 'target='+self.options.index, function(){
					self.reload(true);
				});
			});
			$('#cancel').button().click(function(){$.unblockUI()});
			$.naxx.translate($.naxx.acl.language, $('.blockUI'));
		},

		getsmarttest: function(type){
			var self = this, element = $(this.element);
			if($(':naxx-config_disk').length == 0) return;
			$.naxx.teleport.Exec($.naxx.path.disk, 'smart_test_result', 'target='+self.options.index+'&test_type='+type, function(data){
					if (data.search('%') >= 0)
					{
						if(type == 'short')
						{
							$('[name=manual_test_result]').html(data+'');
							self.object.$smarttesttimer_short = setTimeout(function(){
								self.getsmarttest('short');
							}, 2000);
						}
						else
						{
							$('[name=manual_test_result_long]').html(data+'');
							self.object.$smarttesttimer_long = setTimeout(function(){
								self.getsmarttest('long');
							}, 2000);
						}
					}
					else
					{
						if (data == '')
							data = ''
						if(type == 'short')
							$('[name=manual_test_result]').html(data);
						else
							$('[name=manual_test_result_long]').html(data);
					}
					$.naxx.translate($.naxx.acl.language, $('div.statusPanel #manual_test'));
			});
		},

		smarttest: function(type){
			var self = this, element = $(this.element);
			$.naxx.teleport.Exec($.naxx.path.disk, 'smart_test', 'target='+self.options.index+'&test_type='+type, function(){
					self.getsmarttest(type);
			});
		},
		destroy : function(){
			$.Widget.prototype.destroy.apply(this, arguments);
			var self = this, element = $(this.element);
			clearInterval(self.object.$interval);
			clearTimeout(self.object.$timeout);
			clearTimeout(self.object.$smarttesttimer_short);
			clearTimeout(self.object.$smarttesttimer_long);
		}
	});
})(jQuery);


text:
package proxy

import (
	corev1 "k8s.io/api/core/v1"
)

// IsOverridden returns true if the given container overrides proxy env variable(s).
// We apply the following rule:
//   If a container already defines any of the proxy env variable then it
//   overrides all of these.
func IsOverridden(envVar []corev1.EnvVar) (overrides bool) {
	for _, envVarName := range allProxyEnvVarNames {
		_, found := find(envVar, envVarName)
		if found {
			overrides = true
			return
		}
	}

	return
}

func find(proxyEnvVar []corev1.EnvVar, name string) (envVar *corev1.EnvVar, found bool) {
	for i := range proxyEnvVar {
		if name == proxyEnvVar[i].Name {
			// Environment variable names are case sensitive.
			found = true
			envVar = &proxyEnvVar[i]

			break
		}
	}

	return
}


text:
"""Schur decomposition functions."""

import numpy
from numpy import asarray_chkfinite, single

# Local imports.
import misc
from misc import LinAlgError, _datacopied
from lapack import get_lapack_funcs
from decomp import eigvals

__all__ = ['schur', 'rsf2csf']

_double_precision = ['i','l','d']

def schur(a, output='real', lwork=None, overwrite_a=False):
    """Compute Schur decomposition of a matrix.

    The Schur decomposition is

        A = Z T Z^H

    where Z is unitary and T is either upper-triangular, or for real
    Schur decomposition (output='real'), quasi-upper triangular.  In
    the quasi-triangular form, 2x2 blocks describing complex-valued
    eigenvalue pairs may extrude from the diagonal.

    Parameters
    ----------
    a : array, shape (M, M)
        Matrix to decompose
    output : {'real', 'complex'}
        Construct the real or complex Schur decomposition (for real matrices).
    lwork : integer
        Work array size. If None or -1, it is automatically computed.
    overwrite_a : boolean
        Whether to overwrite data in a (may improve performance)

    Returns
    -------
    T : array, shape (M, M)
        Schur form of A. It is real-valued for the real Schur decomposition.
    Z : array, shape (M, M)
        An unitary Schur transformation matrix for A.
        It is real-valued for the real Schur decomposition.

    See also
    --------
    rsf2csf : Convert real Schur form to complex Schur form

    """
    if not output in ['real','complex','r','c']:
        raise ValueError("argument must be 'real', or 'complex'")
    a1 = asarray_chkfinite(a)
    if len(a1.shape) != 2 or (a1.shape[0] != a1.shape[1]):
        raise ValueError('expected square matrix')
    typ = a1.dtype.char
    if output in ['complex','c'] and typ not in ['F','D']:
        if typ in _double_precision:
            a1 = a1.astype('D')
            typ = 'D'
        else:
            a1 = a1.astype('F')
            typ = 'F'
    overwrite_a = overwrite_a or (_datacopied(a1, a))
    gees, = get_lapack_funcs(('gees',), (a1,))
    if lwork is None or lwork == -1:
        # get optimal work array
        result = gees(lambda x: None, a1, lwork=-1)
        lwork = result[-2][0].real.astype(numpy.int)
    result = gees(lambda x: None, a1, lwork=lwork, overwrite_a=overwrite_a)
    info = result[-1]
    if info < 0:
        raise ValueError('illegal value in %d-th argument of internal gees'
                                                                    % -info)
    elif info > 0:
        raise LinAlgError("Schur form not found.  Possibly ill-conditioned.")
    return result[0], result[-3]

eps = numpy.finfo(float).eps
feps = numpy.finfo(single).eps

_array_kind = {'b':0, 'h':0, 'B': 0, 'i':0, 'l': 0, 'f': 0, 'd': 0, 'F': 1, 'D': 1}
_array_precision = {'i': 1, 'l': 1, 'f': 0, 'd': 1, 'F': 0, 'D': 1}
_array_type = [['f', 'd'], ['F', 'D']]

def _commonType(*arrays):
    kind = 0
    precision = 0
    for a in arrays:
        t = a.dtype.char
        kind = max(kind, _array_kind[t])
        precision = max(precision, _array_precision[t])
    return _array_type[kind][precision]

def _castCopy(type, *arrays):
    cast_arrays = ()
    for a in arrays:
        if a.dtype.char == type:
            cast_arrays = cast_arrays + (a.copy(),)
        else:
            cast_arrays = cast_arrays + (a.astype(type),)
    if len(cast_arrays) == 1:
        return cast_arrays[0]
    else:
        return cast_arrays

def rsf2csf(T, Z):
    """Convert real Schur form to complex Schur form.

    Convert a quasi-diagonal real-valued Schur form to the upper triangular
    complex-valued Schur form.

    Parameters
    ----------
    T : array, shape (M, M)
        Real Schur form of the original matrix
    Z : array, shape (M, M)
        Schur transformation matrix

    Returns
    -------
    T : array, shape (M, M)
        Complex Schur form of the original matrix
    Z : array, shape (M, M)
        Schur transformation matrix corresponding to the complex form

    See also
    --------
    schur : Schur decompose a matrix

    """
    Z, T = map(asarray_chkfinite, (Z, T))
    if len(Z.shape) != 2 or Z.shape[0] != Z.shape[1]:
        raise ValueError("matrix must be square.")
    if len(T.shape) != 2 or T.shape[0] != T.shape[1]:
        raise ValueError("matrix must be square.")
    if T.shape[0] != Z.shape[0]:
        raise ValueError("matrices must be same dimension.")
    N = T.shape[0]
    arr = numpy.array
    t = _commonType(Z, T, arr([3.0],'F'))
    Z, T = _castCopy(t, Z, T)
    conj = numpy.conj
    dot = numpy.dot
    r_ = numpy.r_
    transp = numpy.transpose
    for m in range(N-1, 0, -1):
        if abs(T[m,m-1]) > eps*(abs(T[m-1,m-1]) + abs(T[m,m])):
            k = slice(m-1, m+1)
            mu = eigvals(T[k,k]) - T[m,m]
            r = misc.norm([mu[0], T[m,m-1]])
            c = mu[0] / r
            s = T[m,m-1] / r
            G = r_[arr([[conj(c), s]], dtype=t), arr([[-s, c]], dtype=t)]
            Gc = conj(transp(G))
            j = slice(m-1, N)
            T[k,j] = dot(G, T[k,j])
            i = slice(0, m+1)
            T[i,k] = dot(T[i,k], Gc)
            i = slice(0, N)
            Z[i,k] = dot(Z[i,k], Gc)
        T[m,m-1] = 0.0;
    return T, Z


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- From: file:/C:/Users/Krirk/AndroidStudioProjects/kitchensink/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/21.0.3/res/values-w500dp/values.xml -->
    <eat-comment/>
    <integer name="abc_max_action_buttons">4</integer>
</resources>


text:
package org.bdgenomics.adam.rich

import org.scalatest.FunSuite
import org.bdgenomics.formats.avro._
import org.bdgenomics.adam.rich.RichGenotype._
import scala.collection.JavaConversions._

class RichGenotypeSuite extends FunSuite {

  def v0 = Variant.newBuilder
    .setContigName("chr1")
    .setStart(0).setReferenceAllele("A").setAlternateAllele("T")
    .build

  test("different ploidy") {
    val gb = Genotype.newBuilder.setVariant(v0).setSampleId("NA12878")
    for (ploidy <- 0 until 3) {
      val g = gb.setAlleles(List.fill(ploidy)(GenotypeAllele.Ref)).build
      assert(g.ploidy === ploidy)
    }
  }

  test("all types for diploid genotype") {
    val gb = Genotype.newBuilder.setVariant(v0).setSampleId("NA12878")

    val hom_ref = gb.setAlleles(List(GenotypeAllele.Ref, GenotypeAllele.Ref)).build
    assert(hom_ref.getType === GenotypeType.HOM_REF)

    val het1 = gb.setAlleles(List(GenotypeAllele.Ref, GenotypeAllele.Alt)).build
    assert(het1.getType === GenotypeType.HET)
    val het2 = gb.setAlleles(List(GenotypeAllele.Alt, GenotypeAllele.Ref)).build
    assert(het2.getType === GenotypeType.HET)

    val hom_alt = gb.setAlleles(List(GenotypeAllele.Alt, GenotypeAllele.Alt)).build
    assert(hom_alt.getType === GenotypeType.HOM_ALT)

    for (a <- GenotypeAllele.values) {
      val no_call1 = gb.setAlleles(List(GenotypeAllele.NoCall, a)).build
      assert(no_call1.getType === GenotypeType.NO_CALL)
      val no_call2 = gb.setAlleles(List(a, GenotypeAllele.NoCall)).build
      assert(no_call2.getType === GenotypeType.NO_CALL)
    }
  }

}


text:
var mongoose = require('mongoose'),
    db = require('../db'),
    async = require('async'),
    Pool = require('./pool'),
    fs = require('fs'),
    analytics = require('../../analytics/batch'),
    minerDir = "../cgminer";

var SETTING_TYPES = {
    EMAIL_NOTIFICATION: 'EMAIL_NOTIFICATION',
    DEVICE_INFO: 'DEVICE_INFO',
    MINER_CONFIG: 'MINER_CONFIG',
    ANALYTICS_CONFIG: 'ANALYTICS_CONFIG'
};
exports.SETTING_TYPES = SETTING_TYPES;

var SettingSchema = new mongoose.Schema({
    type: {
        type: String,
        enum: [
            SETTING_TYPES.EMAIL_NOTIFICATION,
            SETTING_TYPES.DEVICE_INFO,
            SETTING_TYPES.MINER_CONFIG,
            SETTING_TYPES.ANALYTICS_CONFIG
        ]
    },
    value: Object
});

SettingSchema.virtual('id').get(function(){
    return this._id.toHexString();
});
SettingSchema.set('toJSON', {
    virtuals: true
});

var Setting = mongoose.model('settings', SettingSchema);

exports.getSettings = function(callback){
    var dbFetches = [];
    for(var type in SETTING_TYPES){
        dbFetches.push(function(done){
            Setting.find({type: type}, function(err, settings){
                if(err){
                    console.log('<ERROR> While fetching '+type+' setting from db.', err);
                    done(err, null);
                }else{
                    done(null, settings);
                }
            });
        });
    }
    return async.parallel(dbFetches,
        function(err, results){
            if(err){
                console.log('<ERROR> While completing parallel callbacks for fetching settings...', err);
            }
            callback(results);
        });

};

exports.find = function(req, res){
    var query = req.query ? req.query : {};
    return Setting.find(query, function(err, settings){
        if(!err){
            settings.forEach(function(setting){
                if(setting.type === SETTING_TYPES.EMAIL_NOTIFICATION){
                    setting.value.smtpAuthPassword = null;
                }
            });
            return db.sendAjaxResponse(res, settings);
        }else{
            return console.log(err);
        }
    });
};

exports.findById = function(req, res){
    return Setting.findById(req.params.id, function(err, setting){
        if(!err){
            if(setting.type === SETTING_TYPES.EMAIL_NOTIFICATION){
                setting.value.smtpAuthPassword = null;
            }
            return db.sendAjaxResponse(res, setting);
        }else{
            return console.log(err);
        }
    });
};

exports.updateSetting = function(req, res){
    var s = req.body.setting,
        id = req.params.id;
    return Setting.findById(id, function(err, setting){
        setting.type = s.type;
        setting.value = s.value;
        return setting.save(function(err){
            if(!err){
                console.log('Updated setting!');
                if(setting.type === SETTING_TYPES.EMAIL_NOTIFICATION){
                    setting.value.smtpAuthPassword = null;
                }else if(setting.type === SETTING_TYPES.MINER_CONFIG){
                    saveConfigToFlatFile(SETTING_TYPES.MINER_CONFIG, id);
                }else if(setting.type === SETTING_TYPES.ANALYTICS_CONFIG){
                    analytics.startAnalyticsCollection();
                }
                return db.sendAjaxResponse(res, setting);
            }else{
                return console.log(err);
            }
        });
    });
};

exports.createSetting = function(req, res){
    var s = req.body.setting,
        setting = null;
    setting = new Setting({
        type: s.type,
        value: s.value
    });
    setting.save(function(err){
        if(!err){
            console.log('Setting created!');
            if(setting.type === SETTING_TYPES.MINER_CONFIG){
                saveConfigToFlatFile(SETTING_TYPES.MINER_CONFIG, setting.id);
            }
            return db.sendAjaxResponse(res, setting);
        }else{
            return console.log(err);
        }
    });
};

exports.deleteSetting = function(req, res){
    return Setting.findById(req.params.id, function (err, setting) {
        return setting.remove(function (err) {
            if (!err) {
                console.log("Deleted setting.");
                return db.sendAjaxResponse(res, setting);
            } else {
                return console.log(err);
            }
        });
    });
};

var saveConfigToFlatFile = function(type, id){
    if(type === SETTING_TYPES.MINER_CONFIG){
        Setting.findById(id, function(err, config){
            if(!err){
                if(config && config.value){
                    if(config.value.enabled && config.value.config){
                        writeMinerConfigToFile(config.value.config);
                    }else{
                        writeMinerConfigToFile("");
                    }
                }
            }else{
                return console.log(err);
            }
        });
    }
};

var writeMinerConfigToFile = function(config){
    var configFile = minerDir+'/config.txt';
    fs.writeFile(configFile, config, function(err){
        if(err){
            return console.log(err);
        }
    });
};

exports.getAnalyticsConfig = function(callback){
    Setting.find({type: SETTING_TYPES.ANALYTICS_CONFIG}, function(err, config){
        if(!err){
            var configObj = config[0];
            if(configObj && configObj.value){
                return callback(configObj.value.dataCollectionEnabled, configObj.value.dataInterval * 1000);
            }else{
                return callback(false, 15000);
            }
        }else{
            return console.log('<ERROR>: While fetching the analytics configuration.');
        }
    });
};


text:
#import "UIFont+Paco.h"

@implementation UIFont (Paco)

+ (UIFont *)pacoTableCellFont {
  static UIFont* font = nil;

  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    font = [UIFont fontWithName:@"HelveticaNeue" size:18];
  });
  return font;
}

+ (UIFont *)pacoTableCellDetailFont {
  static UIFont* font = nil;

  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    font = [UIFont fontWithName:@"HelveticaNeue" size:12];
  });
  return font;
}

+ (UIFont *)pacoMenuButtonFont {
  static UIFont* font = nil;

  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    font = [UIFont fontWithName:@"HelveticaNeue" size:12];
  });
  return font;
}

+ (UIFont *)pacoNavbarTitleFont {
  static UIFont* font = nil;

  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    font = [UIFont fontWithName:@"HelveticaNeue-Medium" size:23];
  });
  return font;
}

+ (UIFont *)pacoNormalButtonFont {
  static UIFont* font = nil;

  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    font = [UIFont fontWithName:@"HelveticaNeue-Bold" size:15];
  });
  return font;
}

+ (UIFont *)pacoBoldFont {
  static UIFont* font = nil;

  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    font = [UIFont fontWithName:@"HelveticaNeue-Bold" size:12];
  });
  return font;
}

@end


text:
layout: post
title: CSE 167 Final Project
---
    Team Name: Praise the Sun
    Project Name: On the Sea
    Members: Kunyao Chen & Wenchuan Wei

## Short Description

This writeup is for `CSE 167` final project in which we will implement some groundbreaking real-time rendering techniques. One of them is screen space ray tracing. We will build our project based on [Morgan McGuire etc](http://jcgt.org/published/0003/04/04/). Also, using modeled water as our main object, vivid wave effect will be created. In the end, we hope we can achieve a fancy sea scene with natural environment lights and soft shadows in real time.

## Plan

With a toy ray tracer in hand already, it may take less than a week to get screen space ray tracer work. At the same time, we will take care of the water modeling part. After that, we will integrate everything and maybe add other components.

## Technical Point

    1. Screen space post-processed lights;
    2. Water effect with waves, reflection and refraction;
    3. Sound effects.

## Update on June 3, 2016
We have completed most parts of the water effect and screen space ray tracing.

### Water effect with reflection and refraction

For the water effect, we first create a plane as the water surface. The normal of every point on this plane is (0,1,0). Then for each frame, we take 2 pictures as the reflection and refraction textures.
Suppose that the physical camera is places somewhere above the water. And we use it to take a picture only for objects under the water (i.e., the water plane is a clipping plane) as the refraction texture.
For reflection, the camera should be put in the symmetric position under the water surface and only takes picture for objects above the water surface. By mixing the two textures and mapping them onto the water plane, we can see the reflection and refraction effect as shown below.
The picture shows a simple scene. One bunny is placed above the water, and another one's head is above the water while the body is under the water.

### Ripples on the water surface

To make the water more realistic, we want to add some ripples on the water surface. We used a dudv map to realize ripples. Using the red and green components of dudv map as offsets, we can distort the pixels of the reflection and refraction textures. The water surface with ripples is shown below.

### Screen space ray tracing

It could save much time to trace ray in screen space. We choose to build up everything in fragment shader, so the procedure is just like in deferred shading: we save world space normal, position, diffuse color, depth for every pixel in a buffer in the first pass. Then do the ray tracing in screen space in the second pass. The biggest issues are as following: 1. There is no simple proportional relationship between camera space cooridnates and screen space cooridnates. The reuslt in [Morgan McGuire's paper](http://jcgt.org/published/0003/04/04/) is not quite accurate. 2. There is an aliasing problem as sample rate of depth buffer is limited. We have to carefully choose `bias` and  `zThickness` to make it right.

We test the result with a simple scene(floor, bunny and a mirror). As we can see, although there is still some aliasings when the angle between view direction and normal is large, also, the bunny in the mirror is sort of blurred, the overall result is quite satisfying. As we focus on real time application, the artifect is enduarable.

![](../img5/bunnyInTheMirror.gif)

## Update on June 6, 2016

    Note: We change our Team name to PTS,
          and project name to "Bunny and Water"

## The following shows all the technical features of our final project.

(1) Water effect with reflection and refraction

In the following screenshot, head of the bunny is above the water and the body is under the water. You can see both the reflection and refractions, as well as the ripples.

We also use a normal map on the water surface, which enables specular highlight on the water surface.

(2) Screen Space Ray Tracing

With ray tracing, we can implement fancier environment mapping. As you can see in the screen shot, bunny can map floor texture and the other bunny, floor can reflect those bunnies.

In addition, we can obtain shadows:

Better than shadow mapping, using ray cones, we can achieve soft shadows:

## For more details, please see: [our short video](https://www.youtube.com/watch?v=TyTje1frdk0)


text:
'''
Return the version number of the currently installed 'willowtree' package.
Version numbering follows a major.macro.micro convention, with micro omitted
if equal to 0.

To display version number in a Python environment, either call:

willowtree.__version__

or, if willowtree is imported as wt:

wt.__version__
'''

__version__ = '0.9'


text:
"""Debug Plugin for EasyEngine"""

from cement.core.controller import CementBaseController, expose
from cement.core import handler, hook
from ee.core.logging import Log
from ee.cli.plugins.site_functions import logwatch
from ee.core.variables import EEVariables
from ee.core.fileutils import EEFileUtils
from ee.core.shellexec import EEShellExec
from ee.core.sendmail import EESendMail
from ee.core.mysql import EEMysql
import os
import glob
import gzip

def ee_log_hook(app):
    # do something with the ``app`` object here.
    pass

class EELogController(CementBaseController):
    class Meta:
        label = 'log'
        description = 'Perform operations on Nginx, PHP, MySQL log file'
        stacked_on = 'base'
        stacked_type = 'nested'
        usage = "ee log [<site_name>] [options]"

    @expose(hide=True)
    def default(self):
        self.app.args.print_help()

class EELogShowController(CementBaseController):
    class Meta:
        label = 'show'
        description = 'Show Nginx, PHP, MySQL log file'
        stacked_on = 'log'
        stacked_type = 'nested'
        arguments = [
            (['--all'],
                dict(help='Show All logs file', action='store_true')),
            (['--nginx'],
                dict(help='Show Nginx Error logs file', action='store_true')),
            (['--php'],
                dict(help='Show PHP Error logs file', action='store_true')),
            (['--fpm'],
                dict(help='Show PHP5-fpm slow logs file',
                     action='store_true')),
            (['--mysql'],
                dict(help='Show MySQL logs file', action='store_true')),
            (['--wp'],
                dict(help='Show Site specific WordPress logs file',
                     action='store_true')),
            (['--access'],
                dict(help='Show Nginx access log file',
                     action='store_true')),
            (['site_name'],
                dict(help='Website Name', nargs='?', default=None))
            ]
        usage = "ee log show [<site_name>] [options]"

    @expose(hide=True)
    def default(self):
        """Default function of log show"""
        self.msg = []

        if self.app.pargs.php:
            self.app.pargs.nginx = True

        if ((not self.app.pargs.nginx) and (not self.app.pargs.fpm)
           and (not self.app.pargs.mysql) and (not self.app.pargs.access)
           and (not self.app.pargs.wp) and (not self.app.pargs.site_name)):
            self.app.pargs.nginx = True
            self.app.pargs.fpm = True
            self.app.pargs.mysql = True
            self.app.pargs.access = True

        if ((not self.app.pargs.nginx) and (not self.app.pargs.fpm)
           and (not self.app.pargs.mysql) and (not self.app.pargs.access)
           and (not self.app.pargs.wp) and (self.app.pargs.site_name)):
            self.app.pargs.nginx = True
            self.app.pargs.wp = True
            self.app.pargs.access = True
            self.app.pargs.mysql = True

        if self.app.pargs.nginx and (not self.app.pargs.site_name):
            self.msg = self.msg + ["/var/log/nginx/*error.log"]

        if self.app.pargs.access and (not self.app.pargs.site_name):
            self.msg = self.msg + ["/var/log/nginx/*access.log"]

        if self.app.pargs.fpm:
            open('/var/log/php5/slow.log', 'a').close()
            open('/var/log/php5/fpm.log', 'a').close()
            self.msg = self.msg + ['/var/log/php5/slow.log',
                                   '/var/log/php5/fpm.log']
        if self.app.pargs.mysql:
            # MySQL debug will not work for remote MySQL
            if EEVariables.ee_mysql_host is "localhost":
                if os.path.isfile('/var/log/mysql/mysql-slow.log'):
                    self.msg = self.msg + ['/var/log/mysql/mysql-slow.log']
                else:
                    Log.info(self, "MySQL slow-log not found, skipped")
            else:
                Log.warn(self, "Remote MySQL found, EasyEngine is not able to"
                         "show MySQL log file")

        if self.app.pargs.site_name:
            webroot = "{0}{1}".format(EEVariables.ee_webroot,
                                      self.app.pargs.site_name)

            if not os.path.isdir(webroot):
                Log.error(self, "Site not present, quitting")
            if self.app.pargs.access:
                self.msg = self.msg + ["{0}/{1}/logs/access.log"
                                       .format(EEVariables.ee_webroot,
                                               self.app.pargs.site_name)]
            if self.app.pargs.nginx:
                self.msg = self.msg + ["{0}/{1}/logs/error.log"
                                       .format(EEVariables.ee_webroot,
                                               self.app.pargs.site_name)]
            if self.app.pargs.wp:
                if os.path.isdir('{0}/htdocs/wp-content'.format(webroot)):
                    if not os.path.isfile('{0}/logs/debug.log'
                                          .format(webroot)):
                        if not os.path.isfile('{0}/htdocs/wp-content/debug.log'
                                              .format(webroot)):
                            open("{0}/htdocs/wp-content/debug.log"
                                 .format(webroot),
                                 encoding='utf-8', mode='a').close()
                            EEShellExec.cmd_exec(self, "chown {1}: {0}/htdocs/"
                                                 "wp-content/debug.log"
                                                 "".format(webroot,
                                                           EEVariables
                                                           .ee_php_user)
                                                 )
                    # create symbolic link for debug log
                    EEFileUtils.create_symlink(self, ["{0}/htdocs/wp-content/"
                                                      "debug.log"
                                                      .format(webroot),
                                                      '{0}/logs/debug.log'
                                                      .format(webroot)])

                    self.msg = self.msg + ["{0}/{1}/logs/debug.log"
                                           .format(EEVariables.ee_webroot,
                                                   self.app.pargs.site_name)]
                else:
                    Log.info(self, "Site is not WordPress site, skipping "
                             "WordPress logs")

        watch_list = []
        for w_list in self.msg:
            watch_list = watch_list + glob.glob(w_list)

        logwatch(self, watch_list)

class EELogResetController(CementBaseController):
    class Meta:
        label = 'reset'
        description = 'Reset Nginx, PHP, MySQL log file'
        stacked_on = 'log'
        stacked_type = 'nested'
        arguments = [
            (['--all'],
                dict(help='Reset All logs file', action='store_true')),
            (['--nginx'],
                dict(help='Reset Nginx Error logs file', action='store_true')),
            (['--php'],
                dict(help='Reset PHP Error logs file', action='store_true')),
            (['--fpm'],
                dict(help='Reset PHP5-fpm slow logs file',
                     action='store_true')),
            (['--mysql'],
                dict(help='Reset MySQL logs file', action='store_true')),
            (['--wp'],
                dict(help='Reset Site specific WordPress logs file',
                     action='store_true')),
            (['--access'],
                dict(help='Reset Nginx access log file',
                     action='store_true')),
            (['--slow-log-db'],
                dict(help='Drop all rows from slowlog table in database',
                     action='store_true')),
            (['site_name'],
                dict(help='Website Name', nargs='?', default=None))
            ]
        usage = "ee log reset [<site_name>] [options]"

    @expose(hide=True)
    def default(self):
        """Default function of log reset"""
        self.msg = []

        if self.app.pargs.php:
            self.app.pargs.nginx = True

        if ((not self.app.pargs.nginx) and (not self.app.pargs.fpm)
           and (not self.app.pargs.mysql) and (not self.app.pargs.access)
           and (not self.app.pargs.wp) and (not self.app.pargs.site_name)
           and (not self.app.pargs.slow_log_db)):
            self.app.pargs.nginx = True
            self.app.pargs.fpm = True
            self.app.pargs.mysql = True
            self.app.pargs.access = True
            self.app.pargs.slow_log_db = True

        if ((not self.app.pargs.nginx) and (not self.app.pargs.fpm)
           and (not self.app.pargs.mysql) and (not self.app.pargs.access)
           and (not self.app.pargs.wp) and (self.app.pargs.site_name)
           and (not self.app.pargs.slow-log-db)):
            self.app.pargs.nginx = True
            self.app.pargs.wp = True
            self.app.pargs.access = True
            self.app.pargs.mysql = True

        if self.app.pargs.slow_log_db:
            if os.path.isdir("/var/www/22222/htdocs/db/anemometer"):
                Log.info(self, "Resetting MySQL slow_query_log database table")
                EEMysql.execute(self, "TRUNCATE TABLE  "
                                "slow_query_log.global_query_review_history")
                EEMysql.execute(self, "TRUNCATE TABLE "
                                "slow_query_log.global_query_review")

        if self.app.pargs.nginx and (not self.app.pargs.site_name):
            self.msg = self.msg + ["/var/log/nginx/*error.log"]

        if self.app.pargs.access and (not self.app.pargs.site_name):
            self.msg = self.msg + ["/var/log/nginx/*access.log"]

        if self.app.pargs.fpm:
            open('/var/log/php5/slow.log', 'a').close()
            open('/var/log/php5/fpm.log', 'a').close()
            self.msg = self.msg + ['/var/log/php5/slow.log',
                                   '/var/log/php5/fpm.log']
        if self.app.pargs.mysql:
            # MySQL debug will not work for remote MySQL
            if EEVariables.ee_mysql_host is "localhost":
                if os.path.isfile('/var/log/mysql/mysql-slow.log'):
                    self.msg = self.msg + ['/var/log/mysql/mysql-slow.log']
                else:
                    Log.info(self, "MySQL slow-log not found, skipped")
            else:
                Log.warn(self, "Remote MySQL found, EasyEngine is not able to"
                         "show MySQL log file")

        if self.app.pargs.site_name:
            webroot = "{0}{1}".format(EEVariables.ee_webroot,
                                      self.app.pargs.site_name)

            if not os.path.isdir(webroot):
                Log.error(self, "Site not present, quitting")
            if self.app.pargs.access:
                self.msg = self.msg + ["{0}/{1}/logs/access.log"
                                       .format(EEVariables.ee_webroot,
                                               self.app.pargs.site_name)]
            if self.app.pargs.nginx:
                self.msg = self.msg + ["{0}/{1}/logs/error.log"
                                       .format(EEVariables.ee_webroot,
                                               self.app.pargs.site_name)]
            if self.app.pargs.wp:
                if os.path.isdir('{0}/htdocs/wp-content'.format(webroot)):
                    if not os.path.isfile('{0}/logs/debug.log'
                                          .format(webroot)):
                        if not os.path.isfile('{0}/htdocs/wp-content/debug.log'
                                              .format(webroot)):
                            open("{0}/htdocs/wp-content/debug.log"
                                 .format(webroot),
                                 encoding='utf-8', mode='a').close()
                            EEShellExec.cmd_exec(self, "chown {1}: {0}/htdocs/"
                                                 "wp-content/debug.log"
                                                 "".format(webroot,
                                                           EEVariables
                                                           .ee_php_user)
                                                 )
                    # create symbolic link for debug log
                    EEFileUtils.create_symlink(self, ["{0}/htdocs/wp-content/"
                                                      "debug.log"
                                                      .format(webroot),
                                                      '{0}/logs/debug.log'
                                                      .format(webroot)])

                    self.msg = self.msg + ["{0}/{1}/logs/debug.log"
                                           .format(EEVariables.ee_webroot,
                                                   self.app.pargs.site_name)]
                else:
                    Log.info(self, "Site is not WordPress site, skipping "
                             "WordPress logs")

        reset_list = []
        for r_list in self.msg:
            reset_list = reset_list + glob.glob(r_list)

        # Clearing content of file
        for r_list in reset_list:
            Log.info(self, "Resetting file {file}".format(file=r_list))
            open(r_list, 'w').close()

class EELogGzipController(CementBaseController):
    class Meta:
        label = 'gzip'
        description = 'GZip Nginx, PHP, MySQL log file'
        stacked_on = 'log'
        stacked_type = 'nested'
        arguments = [
            (['--all'],
                dict(help='GZip All logs file', action='store_true')),
            (['--nginx'],
                dict(help='GZip Nginx Error logs file', action='store_true')),
            (['--php'],
                dict(help='GZip PHP Error logs file', action='store_true')),
            (['--fpm'],
                dict(help='GZip PHP5-fpm slow logs file',
                     action='store_true')),
            (['--mysql'],
                dict(help='GZip MySQL logs file', action='store_true')),
            (['--wp'],
                dict(help='GZip Site specific WordPress logs file',
                     action='store_true')),
            (['--access'],
                dict(help='GZip Nginx access log file',
                     action='store_true')),
            (['site_name'],
                dict(help='Website Name', nargs='?', default=None))
            ]
        usage = "ee log gzip [<site_name>] [options]"

    @expose(hide=True)
    def default(self):
        """Default function of log GZip"""
        self.msg = []

        if self.app.pargs.php:
            self.app.pargs.nginx = True

        if ((not self.app.pargs.nginx) and (not self.app.pargs.fpm)
           and (not self.app.pargs.mysql) and (not self.app.pargs.access)
           and (not self.app.pargs.wp) and (not self.app.pargs.site_name)):
            self.app.pargs.nginx = True
            self.app.pargs.fpm = True
            self.app.pargs.mysql = True
            self.app.pargs.access = True

        if ((not self.app.pargs.nginx) and (not self.app.pargs.fpm)
           and (not self.app.pargs.mysql) and (not self.app.pargs.access)
           and (not self.app.pargs.wp) and (self.app.pargs.site_name)):
            self.app.pargs.nginx = True
            self.app.pargs.wp = True
            self.app.pargs.access = True
            self.app.pargs.mysql = True

        if self.app.pargs.nginx and (not self.app.pargs.site_name):
            self.msg = self.msg + ["/var/log/nginx/*error.log"]

        if self.app.pargs.access and (not self.app.pargs.site_name):
            self.msg = self.msg + ["/var/log/nginx/*access.log"]

        if self.app.pargs.fpm:
            open('/var/log/php5/slow.log', 'a').close()
            open('/var/log/php5/fpm.log', 'a').close()
            self.msg = self.msg + ['/var/log/php5/slow.log',
                                   '/var/log/php5/fpm.log']
        if self.app.pargs.mysql:
            # MySQL debug will not work for remote MySQL
            if EEVariables.ee_mysql_host is "localhost":
                if os.path.isfile('/var/log/mysql/mysql-slow.log'):
                    self.msg = self.msg + ['/var/log/mysql/mysql-slow.log']
                else:
                    Log.info(self, "MySQL slow-log not found, skipped")

            else:
                Log.warn(self, "Remote MySQL found, EasyEngine is not able to"
                         "show MySQL log file")

        if self.app.pargs.site_name:
            webroot = "{0}{1}".format(EEVariables.ee_webroot,
                                      self.app.pargs.site_name)

            if not os.path.isdir(webroot):
                Log.error(self, "Site not present, quitting")
            if self.app.pargs.access:
                self.msg = self.msg + ["{0}/{1}/logs/access.log"
                                       .format(EEVariables.ee_webroot,
                                               self.app.pargs.site_name)]
            if self.app.pargs.nginx:
                self.msg = self.msg + ["{0}/{1}/logs/error.log"
                                       .format(EEVariables.ee_webroot,
                                               self.app.pargs.site_name)]
            if self.app.pargs.wp:
                if os.path.isdir('{0}/htdocs/wp-content'.format(webroot)):
                    if not os.path.isfile('{0}/logs/debug.log'
                                          .format(webroot)):
                        if not os.path.isfile('{0}/htdocs/wp-content/debug.log'
                                              .format(webroot)):
                            open("{0}/htdocs/wp-content/debug.log"
                                 .format(webroot),
                                 encoding='utf-8', mode='a').close()
                            EEShellExec.cmd_exec(self, "chown {1}: {0}/htdocs/"
                                                 "wp-content/debug.log"
                                                 "".format(webroot,
                                                           EEVariables
                                                           .ee_php_user)
                                                 )
                    # create symbolic link for debug log
                    EEFileUtils.create_symlink(self, ["{0}/htdocs/wp-content/"
                                                      "debug.log"
                                                      .format(webroot),
                                                      '{0}/logs/debug.log'
                                                      .format(webroot)])

                    self.msg = self.msg + ["{0}/{1}/logs/debug.log"
                                           .format(EEVariables.ee_webroot,
                                                   self.app.pargs.site_name)]
                else:
                    Log.info(self, "Site is not WordPress site, skipping "
                             "WordPress logs")

        gzip_list = []
        for g_list in self.msg:
            gzip_list = gzip_list + glob.glob(g_list)

        # Gzip content of file
        for g_list in gzip_list:
            Log.info(self, "Gzipping file {file}".format(file=g_list))
            in_file = g_list
            in_data = open(in_file, "rb").read()
            out_gz = g_list + ".gz"
            gzf = gzip.open(out_gz, "wb")
            gzf.write(in_data)
            gzf.close()

class EELogMailController(CementBaseController):
    class Meta:
        label = 'mail'
        description = 'Mail Nginx, PHP, MySQL log file'
        stacked_on = 'log'
        stacked_type = 'nested'
        arguments = [
            (['--all'],
                dict(help='Mail All logs file', action='store_true')),
            (['--nginx'],
                dict(help='Mail Nginx Error logs file', action='store_true')),
            (['--php'],
                dict(help='Mail PHP Error logs file', action='store_true')),
            (['--fpm'],
                dict(help='Mail PHP5-fpm slow logs file',
                     action='store_true')),
            (['--mysql'],
                dict(help='Mail MySQL logs file', action='store_true')),
            (['--wp'],
                dict(help='Mail Site specific WordPress logs file',
                     action='store_true')),
            (['--access'],
                dict(help='Mail Nginx access log file',
                     action='store_true')),
            (['site_name'],
                dict(help='Website Name', nargs='?', default=None)),
            (['--to'],
             dict(help='EMail addresses to send log files', action='append',
                  dest='to', nargs=1, required=True)),
            ]
        usage = "ee log mail [<site_name>] [options]"

    @expose(hide=True)
    def default(self):
        """Default function of log Mail"""
        self.msg = []

        if self.app.pargs.php:
            self.app.pargs.nginx = True

        if ((not self.app.pargs.nginx) and (not self.app.pargs.fpm)
           and (not self.app.pargs.mysql) and (not self.app.pargs.access)
           and (not self.app.pargs.wp) and (not self.app.pargs.site_name)):
            self.app.pargs.nginx = True
            self.app.pargs.fpm = True
            self.app.pargs.mysql = True
            self.app.pargs.access = True

        if ((not self.app.pargs.nginx) and (not self.app.pargs.fpm)
           and (not self.app.pargs.mysql) and (not self.app.pargs.access)
           and (not self.app.pargs.wp) and (self.app.pargs.site_name)):
            self.app.pargs.nginx = True
            self.app.pargs.wp = True
            self.app.pargs.access = True
            self.app.pargs.mysql = True

        if self.app.pargs.nginx and (not self.app.pargs.site_name):
            self.msg = self.msg + ["/var/log/nginx/*error.log"]

        if self.app.pargs.access and (not self.app.pargs.site_name):
            self.msg = self.msg + ["/var/log/nginx/*access.log"]

        if self.app.pargs.fpm:
            open('/var/log/php5/slow.log', 'a').close()
            open('/var/log/php5/fpm.log', 'a').close()
            self.msg = self.msg + ['/var/log/php5/slow.log',
                                   '/var/log/php5/fpm.log']
        if self.app.pargs.mysql:
            # MySQL debug will not work for remote MySQL
            if EEVariables.ee_mysql_host is "localhost":
                if os.path.isfile('/var/log/mysql/mysql-slow.log'):
                    self.msg = self.msg + ['/var/log/mysql/mysql-slow.log']
                else:
                    Log.info(self, "MySQL slow-log not found, skipped")
            else:
                Log.warn(self, "Remote MySQL found, EasyEngine is not able to"
                         "show MySQL log file")

        if self.app.pargs.site_name:
            webroot = "{0}{1}".format(EEVariables.ee_webroot,
                                      self.app.pargs.site_name)

            if not os.path.isdir(webroot):
                Log.error(self, "Site not present, quitting")
            if self.app.pargs.access:
                self.msg = self.msg + ["{0}/{1}/logs/access.log"
                                       .format(EEVariables.ee_webroot,
                                               self.app.pargs.site_name)]
            if self.app.pargs.nginx:
                self.msg = self.msg + ["{0}/{1}/logs/error.log"
                                       .format(EEVariables.ee_webroot,
                                               self.app.pargs.site_name)]
            if self.app.pargs.wp:
                if os.path.isdir('{0}/htdocs/wp-content'.format(webroot)):
                    if not os.path.isfile('{0}/logs/debug.log'
                                          .format(webroot)):
                        if not os.path.isfile('{0}/htdocs/wp-content/debug.log'
                                              .format(webroot)):
                            open("{0}/htdocs/wp-content/debug.log"
                                 .format(webroot),
                                 encoding='utf-8', mode='a').close()
                            EEShellExec.cmd_exec(self, "chown {1}: {0}/htdocs/"
                                                 "wp-content/debug.log"
                                                 "".format(webroot,
                                                           EEVariables
                                                           .ee_php_user)
                                                 )
                    # create symbolic link for debug log
                    EEFileUtils.create_symlink(self, ["{0}/htdocs/wp-content/"
                                                      "debug.log"
                                                      .format(webroot),
                                                      '{0}/logs/debug.log'
                                                      .format(webroot)])

                    self.msg = self.msg + ["{0}/{1}/logs/debug.log"
                                           .format(EEVariables.ee_webroot,
                                                   self.app.pargs.site_name)]
                else:
                    Log.info(self, "Site is not WordPress site, skipping "
                             "WordPress logs")

        mail_list = []
        for m_list in self.msg:
            mail_list = mail_list + glob.glob(m_list)

        for tomail in self.app.pargs.to:
            Log.info(self, "Sending mail to {0}".format(tomail[0]))
            EESendMail("easyengine", tomail[0], "{0} Log Files"
                       .format(EEVariables.ee_fqdn),
                       "Hey Hi,\n  Please find attached server log files"
                       "\n\n\nYour's faithfully,\nEasyEngine",
                       files=mail_list, port=25, isTls=False)

def load(app):
    # register the plugin class.. this only happens if the plugin is enabled
    handler.register(EELogController)
    handler.register(EELogShowController)
    handler.register(EELogResetController)
    handler.register(EELogGzipController)
    handler.register(EELogMailController)
    # register a hook (function) to run after arguments are parsed.
    hook.register('post_argument_parsing', ee_log_hook)


text:
<!DOCTYPE html>

<title>Simple WiDi Demo</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="style.css" />

 Simple WiDi Demo

Display Availability: N/A

Result: N/A

Received message: N/A

    <input class="button" type="button" value="Request Show Presentation" onclick="requestShow();"></input>

    <input class="button" type="button" value="Close Presentation" onclick="closePresentationWindow();"></input>


text:
import logging
import os
from hamster.QtVariant import QtCore, QtGui, QtLoadUI

log = logging.getLogger(__name__)
logging.getLogger('PyQt4').setLevel(logging.WARNING)

class ItemsWidget(QtGui.QWidget):

    def __init__(self, things, parent=None):
        super(ItemsWidget, self).__init__(parent)

        self.item_tree_view = ItemTreeView(self)
        self.add_item_button = QtGui.QPushButton("New Item", self)
        self.item_prop_widget = ItemPropertiesWidget(None, self)

        self.__setup_ui()
        self.__initialize_item_view(things)

    def __setup_ui(self):
        vert_widget = QtGui.QWidget(self)
        vert = QtGui.QVBoxLayout(vert_widget)
        vert.addWidget(self.item_tree_view)
        vert.addWidget(self.add_item_button)

        hori_widget = QtGui.QSplitter(QtCore.Qt.Horizontal, self)
        hori_widget.addWidget(vert_widget)
        hori_widget.addWidget(self.item_prop_widget)

        hori = QtGui.QHBoxLayout(self)
        hori.addWidget(hori_widget)

        self.add_item_button.released.connect(self.item_added)

    def __initialize_item_view(self, things):
        for thing in things:
            item = QtGui.QStandardItem(thing['Name'])
            item.setData(thing)
            self.item_tree_view.model.appendRow(item)

    def item_dropEvent(self, event):
        log.error("TODO: Implement item_dropEvent")

    def item_added(self):
        thing_id = self.parent().create_thing({'Id': 0, "Name": "New thing"})
        if not thing_id:
            return

        item = QtGui.QStandardItem("New thing")
        item.setData({'Id': thing_id, "Name": "New thing"})
        self.item_tree_view.model.appendRow(item)

    def item_deleted(self):
        log.error("TODO: Implement item_deleted")

    def item_changed(self, item):
        log.error("TODO: Implement item_changed")
        item_data = item.data()
        log.info(item_data)

    def item_saved(self):
        log.error("TODO: Implement item_saved")
        #index = self.item_tree_view.currentIndex()
        #item = self.item_tree_view.model.itemFromIndex(index)
        #item_data = item.data()

        self.item_prop_widget.get_data()

    def selection_changed(self, current, previous):
        if not current.indexes():
            return

        index = current.indexes()[0]
        if not index.isValid():
            return

        item = self.item_tree_view.model.itemFromIndex(index)
        item_data = item.data()
        self.item_prop_widget.set_data(item_data)

class ItemTreeView(QtGui.QTreeView):

    def __init__(self, parent):
        super(ItemTreeView, self).__init__(parent)
        self.model = QtGui.QStandardItemModel(self)
        self.model.setHorizontalHeaderLabels(["Items"])
        self.setModel(self.model)

        self.setSelectionMode(QtGui.QTreeView.SingleSelection)
        self.setDragDropMode(QtGui.QAbstractItemView.InternalMove)
        self.setAcceptDrops(True)
        self.setAnimated(True)

        self.model.itemChanged.connect(self.parent().item_changed)
        self.selectionModel().selectionChanged.connect(self.parent().selection_changed)

    def dropEvent(self, event):
        self.parent().item_dropEvent(event)
        super(ItemTreeView, self).dropEvent(event)

class ItemPropertiesWidget(QtGui.QWidget):

    def __init__(self, data, parent):
        super(ItemPropertiesWidget, self).__init__(parent)
        self.edit_state = False

        self.__setup_ui(data)

        self.input_widgets = [
            [self.name_lineEdit, lambda w: w.setReadOnly],
            [self.description_textEdit, lambda w: w.setReadOnly],
            [self.usage_lineEdit, lambda w: w.setReadOnly],
            [self.owner_comboBox, lambda w: w.setEditable],
            [self.maintainer_comboBox, lambda w: w.setEditable],
        ]
        self.input_dict = {
            "Name": self.name_lineEdit.setText,
            "Description": self.description_textEdit.setText
        }

    def __setup_ui(self, data):
        QtLoadUI(os.path.join("hamster", "ItemPropertiesWidget.ui"), self)

        self.save_button.setHidden(True)

        self.edit_button.released.connect(self.edit_properties)
        self.delete_button.released.connect(self.delete_item)
        self.save_button.released.connect(self.save_item)

        if data:
            log.error("TODO: Implement data fill for input widgets on creation")
            self.set_data(data)

    def set_data(self, data):
        for key, value in data.iteritems():
            f = self.input_dict.get(key, None)
            if f:
                log.debug("Set value for %s: %s", key, value)
                f(value)

    def get_data(self):
        log.error("TODO: Implement get_data")

    def edit_properties(self):
        self.edit_state = not self.edit_state

        if self.edit_state is True:
            self.save_button.setHidden(False)
            for widget in self.input_widgets:
                widget[1](widget[0])(False)
        else:
            self.save_button.setHidden(True)
            for widget in self.input_widgets:
                widget[1](widget[0])(True)

        '''
        for w in self.input_widgets:
            if self.edit_state is True:
                w.setReadOnly(False)
            else:
                w.setReadOnly(True)
        '''

    def delete_item(self):
        self.parent().parent().item_deleted()

    def save_item(self):
        log.error("TODO: Implement save_item")
        self.parent().parent().item_saved()

def test():
    pass
    #app = QtGui.QApplication(sys.argv)
    #
    #w = ItemsWidget()
    #w.resize(800, 400)
    #w.show()
    #
    #sys.exit(app.exec_())

if __name__ == '__main__':
    import signal

    logging.basicConfig(level=logging.DEBUG)
    signal.signal(signal.SIGINT, signal.SIG_DFL)

    #import cProfile
    #stats_file = "stats.prof"
    #cProfile.run("test()", stats_file)

    test()

    print("done")


text:
<!DOCTYPE html>

    <textarea></textarea>


text:
module Codeprimate
  # = Wizard Controller
  #
  # Wizard controller provides a base class (Inheriting from ActionController::Base)
  # that provides a DSL for quickly making Wizards.
  #
  # VERY IMPORTANT!!! DONT OVERRIDE INDEX!
  # Doing so will break all functionality. WizardController works by defining an
  # "index" method that does all the work.  To start a wizard, go to the "index" method.
  #
  # === Setup and Configuration
  #
  # Add the following gem configuration to <tt>config/environment.rb</tt>
  #
  #   config.gem "wizard_controller"
  #
  # Ensure the following is present in <tt>config/routes.rb</tt>
  #
  #   map.connect ':controller/:action/:id'
  #
  # === Example Controller
  #
  #   class ExampleController < Codeprimate::Wizard::Base
  #     # Define the method names of the wixard steps
  #     define_steps :page_one, :page_two, :page_three
  #
  #     # Specify where the Wizard should redirect upon completion.
  #     set_finish_path "http://www.example.com/go_here_when_done.html"
  #
  #
  #     # Ensure "index" is not defined!
  #     # def index
  #     # end
  #
  #     def start
  #       # Create a "safe"  index method for this controller, and handle it appropriately
  #     end
  #
  #     def foobar
  #       # You can define whatever actions you want.  WizardController doesnt get in the way.
  #     end
  #
  #     def page_one
  #       # This is a regular action method. Create indiviual views for action methods.
  #     end
  #
  #     def process_page_one
  #       # Place logic to handle any output from page one here.
  #       # No view will be shown for this
  #       #
  #       # Return true if your logic wants you to go to the next step
  #       # Return false if you want to return to the page_one view
  #       return true
  #     end
  #
  #     def page_two
  #       # Let's say this action/view is merely informative.
  #       # We will not supply a process method, and the user will always be able
  #       # to go to the next step
  #     end
  #
  #     def page_three
  #       # Just another step method here
  #     end
  #
  #     def process_page_three
  #       # Since this is the last step, if this process method returns true
  #       # the user will be redirected to the URL specified in the
  #       # "set_finish_path" declaration at the beginning of the Controller definition
  #     end
  #   end
  #
  # === View Helper Methods
  #
  # * <tt>step_number()</tt>: Current step index.
  # * <tt>total_steps()</tt>: Total Number of steps in the wizard.
  # * <tt>step_completed()</tt>: Returns boolean, whether the step has been completed.
  # * <tt>wizard_path()</tt>: Wizard index path.  <b>THIS SHOULD BE THE ACTION PATH OF ALL FORMS/VIEWS WITH A "process" action.</b>
  # * <tt>next_step_path()</tt>: URL to the next step.
  # * <tt>previous_step_path()</tt>: URL to the previous step.
  # * <tt>reset_wizard_path()</tt>: URL to reset the Wizard.
  # * <tt>abort_wizard_path()</tt>: URL to abort the Wizard.
  module Wizard
    VERSION = "0.1.7"

    class Base < ApplicationController
      before_filter :restrict_access, :init_wizard_session

      ### CLASS METHODS
      class << self
        @wizard_steps = []
        @finish_path = '/'
        @wizard_default_error = 'There was a problem processing the last step.'
        attr_accessor :wizard_steps, :finish_path, :abort_path, :wizard_default_error

        # Define steps of the wizard.
        #
        # Should be an array of symbols.
        def define_steps(*args)
          self.wizard_steps = args
        end

        # Set the URL that a user is redirected to after finishing the Wizard.
        #
        # Should be a string
        def set_finish_path(p)
          self.finish_path = p
        end

        # Set the URL that a user is redirected to after aborting the Wizard.
        #
        # Should be a string
        def set_abort_path(p)
          self.abort_path = p
        end

        # Set the flash message a user sees when a process_action method returns false
        #
        # Should be a string
        def set_default_error(e)
          self.wizard_default_error = e
        end
      end

      ### PUBLIC ACTIONS

      # Internal.
      def index
        if finished
          handle_finished_wizard
        else
          handle_unfinished_wizard
        end
      end

      # Internal.
      def next_step
        if step_completed
          incr_step
        else
          flash[:error] ||= self.class.wizard_default_error
        end
        self.finish_path = params[:redirect] unless params[:redirect].blank?
        redirect_to :action => :index
      end

      # Internal.
      def previous_step
        decr_step
        redirect_to :action => :index
      end

      # Internal.
      def direct_step
        step = params[:id].to_i
        if step_completed(step)
          set_current_wizard_step([1, step].max)
        else
          flash[:error] ||= self.class.wizard_default_error
        end
        redirect_to :action => :index
      end

      # Public action to reset the wizard
      def reset
        reset_wizard
        redirect_to :action => :index
      end

      # Assign finish path.
      #
      # Accepts a string.
      def finish_path=(p)
        unless p.blank?
          session[:finish_path] = p
        end
        finish_path
      end

      private

      ### PRIVATE CONTROLLER METHODS

      def handle_finished_wizard
        redirect_to finish_path
        reset_wizard
      end

      def handle_unfinished_wizard
        if request.get?
          handle_get_action
        else
          handle_post_action
        end
      end

      def handle_get_action
        execute_method
        render_step_view
      end

      def handle_post_action
        if (self.wizard_step_completion = execute_process_method)
          next_step
        else
          flash[:error] ||= self.class.wizard_default_error
          render_step_view
        end
      end

      def restrict_access
        ['index', 'next_step', 'previous_step', 'direct_step', 'reset'].include?(params[:action])
      end

      def execute_method(m=current_wizard_step_method)
        return send(m)
      end

      def execute_process_method
        return execute_method("process_#{current_wizard_step_method}".to_sym)
      end

      def render_step_view
        render :action => current_wizard_step_method
      end

      helper_method :step_number
      def step_number
        current_wizard_step
      end

      helper_method :total_steps
      def total_steps
        self.class.wizard_steps.size
      end

      helper_method :next_step_path
      def next_step_path(options={})
        url_for(({:controller => self.controller_name, :action => :next_step}).merge(options))
      end

      helper_method :previous_step_path
      def previous_step_path
        url_for(:controller => self.controller_name, :action => :previous_step)
      end

      helper_method :direct_step_path
      def direct_step_path(step)
        url_for(:controller => self.controller_name, :action => :direct_step, :id => step)
      end

      helper_method :step_completed
      def step_completed(direct_step = current_wizard_step)
        session[:wizard][self.class.to_s][:completed][direct_step] == true
      end

      helper_method :wizard_path
      def wizard_path
        url_for(:controller => self.controller_name)
      end

      helper_method :reset_wizard_path
      def reset_wizard_path
        url_for(:controller => self.controller_name, :action => :reset)
      end

      helper_method :abort_wizard_path
      def abort_wizard_path
        abort_path
      end

      #### SESSION MANAGEMENT

      def current_wizard_step
        @wizard_step ||= session[:wizard][self.class.to_s][:step].to_i
      end

      def set_current_wizard_step(step)
        session[:wizard][self.class.to_s][:step] = step
        @wizard_step = step
      end

      def incr_step
        set_current_wizard_step(current_wizard_step + 1)
      end

      def decr_step
        set_current_wizard_step([1, (current_wizard_step - 1)].max)
      end

      def current_wizard_step_method
        self.class.wizard_steps[(current_wizard_step - 1)]
      end

      def finished
        self.class.wizard_steps.size < current_wizard_step
      end

      def finish_path
        # should be set to self.class.finish_path but that comes out to nil here somehow. --Dallas
        fp = session[:finish_path] ||= self.class.finish_path ||= '/'
        return fp
      end

      def abort_path=(p)
        unless p.blank?
          session[:abort_return_to] = p
        end
        abort_path
      end

      def abort_path
        session[:abort_return_to] ||= self.class.abort_path ||= '/'
      end

      def no_processing
        self.wizard_step_completion = true
      end

      def set_as_not_completed
        self.wizard_step_completion = false
      end

      def wizard_step_completion=(completed)
        session[:wizard][self.class.to_s][:completed][current_wizard_step] = completed
      end

      def reset_wizard
        session[:wizard][self.class.to_s] = nil
        init_wizard_session
      end

      def init_wizard_session
        session[:wizard] ||= {}
        session[:wizard][self.class.to_s] ||= {}
        session[:wizard][self.class.to_s][:step] ||= 1
        session[:wizard][self.class.to_s][:completed] ||= {}
        session[:finish_path] ||= self.class.finish_path
        @wizard_step = session[:wizard][self.class.to_s][:step].to_i
      end

    end
  end

end