text:
package ezy.ui.view;

import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Rect;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import ezy.library.numberstepper.R;

public class NumberStepper extends LinearLayout {

    private int mStep = 1, mValue = 0, mMaxValue = 0, mMinValue = 0;
    ImageView btnLeft, btnRight;
    EditText txtValue;
    OnValueChangedListener mOnValueChanged;

    public NumberStepper(Context context) {
        this(context, null);
    }

    public NumberStepper(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public NumberStepper(Context context, AttributeSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr, 0);
    }

    public NumberStepper(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    public void init(int step, int min, int max, int value) {

        if (min == max) {
            txtValue.setFocusable(false);
            txtValue.setFocusableInTouchMode(false);
            mMinValue = max;
            mMaxValue = max;
        } else {
            txtValue.setFocusable(true);
            txtValue.setFocusableInTouchMode(true);
            mMinValue = Math.min(min, max);
            mMaxValue = Math.max(min, max);
        }

        mStep = Math.max(step, 1);
        if (mStep != 1) {
            mMinValue = normalize(mMinValue);
            mMaxValue = normalize(mMaxValue);
        }

        mValue = Integer.MAX_VALUE;
        setValue(value, false);
    }

    private static int dp2px(DisplayMetrics dm, float dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, dm);
    }

    private void init(Context context, AttributeSet attrs) {
        TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.NumberStepper);

        int buttonSize = dp2px(Resources.getSystem().getDisplayMetrics(), 35);

        try {
            buttonSize = (int) a.getDimension(R.styleable.NumberStepper_nsButtonSize, buttonSize);
            mStep = a.getInt(R.styleable.NumberStepper_nsStep, 1);
            mValue = a.getInt(R.styleable.NumberStepper_nsValue, 0);
            mMinValue = a.getInt(R.styleable.NumberStepper_nsMinValue, Integer.MIN_VALUE);
            mMaxValue = a.getInt(R.styleable.NumberStepper_nsMaxValue, Integer.MAX_VALUE);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            a.recycle();
        }
        setOrientation(HORIZONTAL);
        setFocusableInTouchMode(true);

        btnLeft = new ImageView(context, null, R.attr.nsStyleLeft);
        btnRight = new ImageView(context, null, R.attr.nsStyleRight);
        txtValue = new EditText(context, null, R.attr.nsStyleValue);
        txtValue.setFocusableInTouchMode(true);
        txtValue.setInputType(InputType.TYPE_CLASS_NUMBER);
        txtValue.setFilters(new InputFilter[]{new InputFilter.LengthFilter(6)});
        txtValue.setImeOptions(EditorInfo.IME_ACTION_DONE);
        txtValue.setSelectAllOnFocus(true);

        init(mStep, mMinValue, mMaxValue, mValue);

        addView(btnLeft, new LayoutParams(buttonSize, buttonSize));
        addView(txtValue, new LayoutParams(buttonSize, buttonSize, 1));
        addView(btnRight, new LayoutParams(buttonSize, buttonSize));

        btnLeft.setOnClickListener(onClick);
        btnRight.setOnClickListener(onClick);
        txtValue.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    mKeyboardObserver.register(v);
                } else {
                    syncValue();
                    mKeyboardObserver.unregister();
                }
            }
        });
        txtValue.addOnAttachStateChangeListener(new OnAttachStateChangeListener() {
            @Override
            public void onViewAttachedToWindow(View v) {

            }

            @Override
            public void onViewDetachedFromWindow(View v) {
                mKeyboardObserver.unregister();
            }
        });
        mKeyboardObserver.listen(new OnKeyboardVisibleListener() {
            @Override
            public void onVisibleChanged(boolean visible) {
                if (!visible) {
                    syncValue();
                }
            }
        });

    }

    public void setOnValueChangedListener(OnValueChangedListener onValueChanged) {
        mOnValueChanged = onValueChanged;
    }

    private void syncValue() {
        setValue(editableValue(), true);
    }

    private int editableValue() {
        Editable value = txtValue.getText();
        return value.length() == 0 ? 0 : Integer.valueOf(value.toString());
    }

    public void notifyValueChanged() {
        if (mOnValueChanged != null) {
            mOnValueChanged.onValueChanged(this, mValue);
        }
    }
    public int getValue() {
        if (txtValue.hasFocus()) {
            txtValue.clearFocus();
        }
        return mValue;
    }

    public void setValue(int value) {
        setValue(value, true);
    }

    public void setValue(int value, boolean notifyValueChanged) {
        if (value == mValue) {
            return;
        }
        int valid = Math.min(Math.max(normalize(value), mMinValue), mMaxValue);
        txtValue.setText(String.valueOf(valid));
        if (valid == mValue) { // valid != value
            return;
        }
        mValue = valid;
        btnLeft.setEnabled(mValue != mMinValue);
        btnRight.setEnabled(mValue != mMaxValue);
        if (notifyValueChanged && mOnValueChanged != null) {
            mOnValueChanged.onValueChanged(this, mValue);
        }
    }

    private int normalize(int value) {
        return value - value % mStep;
    }

    OnClickListener onClick = new OnClickListener() {
        @Override
        public void onClick(View v) {
            int value = editableValue();
            setValue(btnLeft == v ? (value - mStep) : (value + mStep), true);
        }
    };

    KeyboardObserver mKeyboardObserver = new KeyboardObserver();

    private class KeyboardObserver implements ViewTreeObserver.OnGlobalLayoutListener {
        private View root;
        private OnKeyboardVisibleListener listener;

        public KeyboardObserver listen(OnKeyboardVisibleListener l) {
            listener = l;
            return this;
        }
        private boolean isKeyboardVisible(View root) {
            final int softKeyboardHeight = 100;
            Rect rect = new Rect();
            root.getWindowVisibleDisplayFrame(rect);
            DisplayMetrics dm = root.getResources().getDisplayMetrics();
            int diff = root.getBottom() - rect.bottom;
            return diff > softKeyboardHeight * dm.density;
        }
        @Override
        public void onGlobalLayout() {
            if (listener != null) {
                listener.onVisibleChanged(isKeyboardVisible(root));
            }
        }

        public void register(View v) {
            unregister();
            root = v.getRootView();
            root.getViewTreeObserver().addOnGlobalLayoutListener(this);
        }
        public void unregister() {
            if (root != null) {
                root.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                root = null;
            }
        }
    }

    interface OnKeyboardVisibleListener {
        void onVisibleChanged(boolean visible);
    }

    public interface OnValueChangedListener {
        void onValueChanged(NumberStepper view, int value);
    }
}


text:
{% extends "base.html" %}
{% block body %}
  {% if session.logged_in %}

  <form action="{{ url_for('add_entry') }}" method="POST" class="add_entry">

      Title
      <input type="text" size="30" name="title" id="title"/>

      Text
      <textarea name="text" id="text" rows="5" cols="80"></textarea>

      <input type="submit" value="Share" name="Share"/>

  </form>

  {% endif %}

Entries

  {% for entry in entries %}

{{ entry.title }}

{{ entry.created.strftime('%b, %d, %Y') }}

      {{ entry.text|safe }}

    {% if session.logged_in %}
      <form id="twit" action="{{ url_for('twitter_post', tweet_title=entry.title) }}" method="POST">
        <button type="submit" style="float:left">Tweet</button>
      </form>
      <form id="{{entry.id}}" action="{{ url_for('edit_entry', id=entry.id) }}" method="GET" class="edit_entry">
        <input Value="Edit" name="submit" type="submit" style="float:left"/>
      </form>

    {% endif %}

  {% else %}

No entries here so far

  {% endfor %}
{% endblock %}

redpajama_set_name: RedPajamaGithub


text:
bash get.sh

bash convert.sh


text:
'use strict';

exports = module.exports = function(app, mongoose) {
  var closingTitleSchema = new mongoose.Schema({
    title: { type: String, default: '' },
    isTitle: {type: String, default: ''},
    isShow: {type: Number, default: 0}
  });

  app.db.model('ClosingTitle', closingTitleSchema);
};


text:
package com.ctrip.framework.apollo.portal.util;

import org.junit.Test;

import java.util.HashMap;
import java.util.Map;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

public class KeyValueUtilsTest {

    @Test
    public void testFilterWithKeyEndswith() {
        // map
        Map<String, String> map = new HashMap<>();
        map.put("abc.met", "none");
        map.put("abc_meta", "none");
        map.put("2bc.meta", "none");
        map.put("abc?met", "none");
        Map<String, String> afterFilter = KeyValueUtils.filterWithKeyIgnoreCaseEndsWith(map, "_meta");
        for(Map.Entry<String, String> entry : afterFilter.entrySet()) {
            String key = entry.getKey();
            assertTrue(key.endsWith("_meta"));
        }
    }

    @Test
    public void testRemoveKeySuffix() {
        Map<String, String> map = new HashMap<>();
        map.put("abc_meta", "none");
        map.put("234_meta", "none");
        map.put("888_meta", "none");
        Map<String, String> afterFilter = KeyValueUtils.removeKeySuffix(map, "_meta".length());
        for(Map.Entry<String, String> entry : afterFilter.entrySet()) {
            String key = entry.getKey();
            assertFalse(key.endsWith("_meta"));
            assertFalse(key.contains("_meta"));
        }
    }

}


text:
package com.onemightyroar.campfire.api.models;

import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

import com.onemightyroar.campfire.api.utils.ToStringBuilder;

public class Room implements Serializable {

	private static final long serialVersionUID = 1L;

	private Long id;
	private String name;
	private Integer membershipLimit;
	private String topic;
	private boolean openToGuests;
	private boolean full;
	private boolean present;
	private String activeTokenValue;
	private Map<Long, User> activeUsers = new HashMap<Long, User>();
	private Map<Long, User> inactiveUsers = new HashMap<Long, User>();
	private Date createdAt;
	private Date updatedAt;
	private JSONObject json;

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getMembershipLimit() {
		return membershipLimit;
	}

	public void setMembershipLimit(Integer membershipLimit) {
		this.membershipLimit = membershipLimit;
	}

	public String getTopic() {
		return topic;
	}

	public void setTopic(String topic) {
		this.topic = topic;
	}

	public boolean isOpenToGuests() {
		return openToGuests;
	}

	public void setOpenToGuests(boolean openToGuests) {
		this.openToGuests = openToGuests;
	}

	public boolean isFull() {
		return full;
	}

	public void setFull(boolean full) {
		this.full = full;
	}

	public String getActiveTokenValue() {
		return activeTokenValue;
	}

	public void setActiveTokenValue(String activeTokenValue) {
		this.activeTokenValue = activeTokenValue;
	}

	public Map<Long, User> getActiveUsers() {
		return activeUsers;
	}

	public User getActiveUser(Long userId) {
		return activeUsers.get(userId);
	}

	public void setActiveUsers(List<User> activeUsers) {
		for(User user : activeUsers)
		this.activeUsers.put(user.getId(), user);
	}

	public void addActiveUser(User user) {
		this.activeUsers.put(user.getId(), user);
		this.inactiveUsers.remove(user.getId());
	}

	public Map<Long, User> getInactiveUsers() {
		return inactiveUsers;
	}

	public User getInactiveUser(Long userId) {
		return inactiveUsers.get(userId);
	}

	public void addInactiveUser(User user) {
		this.activeUsers.remove(user.getId());
		this.inactiveUsers.put(user.getId(), user);
	}

	public void setPresence(boolean present) {
		this.present = present;
	}

	public boolean isPresent() {
		return present;
	}

	public Date getCreatedAt() {
		return createdAt;
	}

	public void setCreatedAt(Date createdAt) {
		this.createdAt = createdAt;
	}

	public Date getUpdatedAt() {
		return updatedAt;
	}

	public void setUpdatedAt(Date updatedAt) {
		this.updatedAt = updatedAt;
	}

	public User findUserById(Long id) {
		User user;

		user = this.getActiveUser(id);
		if(user != null) return user;

		user = this.getInactiveUser(id);
		if(user != null) return user;

		return null;
	}

	public void setJSON(JSONObject json){
		this.json = json;
	}

	public JSONObject getJSON(){
		return json;
	}

	@Override
	public String toString() {
		return new ToStringBuilder(this)
			.append("id",getId())
			.append("name",getName())
			.append("membershipLimit",getMembershipLimit())
			.append("topic",getTopic())
			.append("openToGuests",isOpenToGuests())
			.append("full",isFull())
			.append("activeTokenValue",getActiveTokenValue())
			.append("activeUsers",getActiveUsers().toString())
			.append("createdAt",getCreatedAt())
			.append("updatedAt",getUpdatedAt())
			.toString();
	}

}


text:
package org.auraframework.impl.root.parser.handler;

import org.auraframework.def.ComponentDef;
import org.auraframework.def.DefDescriptor;
import org.auraframework.def.EventDef;
import org.auraframework.impl.AuraImplTestCase;
import org.auraframework.impl.root.parser.XMLParser;
import org.auraframework.impl.source.StringSource;
import org.auraframework.impl.system.DefDescriptorImpl;
import org.auraframework.system.Parser.Format;

import org.auraframework.throwable.quickfix.InvalidDefinitionException;

public class EventHandlerDefHandlerTest extends AuraImplTestCase {

    public EventHandlerDefHandlerTest(String name) {
        super(name);
    }

    public void testEventHandlerDefHandler() throws Exception {
        XMLParser parser = XMLParser.getInstance();
        DefDescriptor<ComponentDef> descriptor = DefDescriptorImpl.getInstance("test:fakeparser", ComponentDef.class);
        StringSource<ComponentDef> source = new StringSource<ComponentDef>(descriptor,
                "<aura:component><aura:handler event='aura:click' action='{!c.action}'/></aura:component>", "myID",
                Format.XML);
        ComponentDef def = parser.parse(descriptor, source);
        assertNotNull(def);
    }

    public void testRegisterDuplicateEventNames() throws Exception {
        XMLParser parser = XMLParser.getInstance();
        DefDescriptor<ComponentDef> descriptor = DefDescriptorImpl.getInstance("test:fakeparser", ComponentDef.class);
        StringSource<ComponentDef> source = new StringSource<ComponentDef>(descriptor, "<aura:component>"
                + "<aura:registerevent name='dupName' type='aura:click'/>"
                + "<aura:registerevent name='dupName' type='aura:click'/>" + "</aura:component>", "myID", Format.XML);
        ComponentDef cd = parser.parse(descriptor, source);
        try {
            cd.validateDefinition();
            fail("Should have thrown AuraRuntimeException for registering two events with the same name");
        } catch (Exception e) {
            checkExceptionContains(e, InvalidDefinitionException.class,
                    "Multiple events registered with name");
        }

    }

    /**
     * Events cannot be abstract
     *
     * @throws Exception
     */
    public void testAbstractEvent() throws Exception {
        XMLParser parser = XMLParser.getInstance();
        DefDescriptor<EventDef> descriptor = DefDescriptorImpl.getInstance("aura:testevent", EventDef.class);
        StringSource<EventDef> source = new StringSource<EventDef>(descriptor,
                "<aura:event type='component' abstract='true'></aura:event>", "myID", Format.XML);
        EventDef ed = parser.parse(descriptor, source);
        try {
            ed.validateDefinition();
            fail("Should have thrown AuraRuntimeException for creating an abstract event");
        } catch (Exception e) {
            checkExceptionContains(e, InvalidDefinitionException.class,
                    "Invalid attribute \"abstract\"");
        }
    }
}


text:
package stash.sources.modules;

import android.support.annotation.NonNull;

import rx.functions.Func1;
import stash.Aggregable;
import stash.SourceModuleBuilder;
import stash.aggregables.SimpleAggregable;
import stash.params.StashableParams;
import stash.sources.AggregableSource;
import stash.sources.builder.SourceHandler;

@stash.annotations.SourceModule(AggregableSource.class)
public final class AggregableSourceStashableModule<P extends StashableParams<?>> implements SourceModuleBuilder {
    private final AggregableSourceModule<P> module = new AggregableSourceModule<P>();

    @NonNull public AggregableSourceStashableModule<P> aggregate() {
        return aggregate(SimpleAggregable.DEFAULT_KEEP_ALIVE_SECONDS);
    }

    @NonNull public AggregableSourceStashableModule<P> aggregate(int keepAliveSeconds) {
        return aggregate(keepAliveSeconds, SimpleAggregable.DEFAULT_KEEP_ALIVE_ON_ERROR);
    }

    @NonNull
    public AggregableSourceStashableModule<P> aggregate(int keepAliveSeconds, boolean keepAliveOnError) {
        return aggregateInternal(this, keepAliveSeconds, keepAliveOnError);
    }

    @NonNull public AggregableSourceStashableModule<P> aggregate(@NonNull Func1<P, Aggregable> aggregable) {
        module.aggregate(aggregable);
        return this;
    }

    @NonNull @Override public SourceHandler build() {
        return module.build();
    }

    private static <P extends StashableParams<?>> AggregableSourceStashableModule<P> aggregateInternal(
            @NonNull AggregableSourceStashableModule<P> module, final int keepAliveSeconds,
            final boolean keepAliveOnError) {
        // Create anonymous inner class in static context to avoid holding Module instance in memory
        module.module.aggregate(new Func1<P, Aggregable>() {
            @Override public Aggregable call(P p) {
                return new SimpleAggregable(p.getKey(), keepAliveSeconds, keepAliveOnError);
            }
        });
        return module;
    }
}


text:
create class dummy( a int );
insert into dummy values (1);

select months_between(date'',date'') from dummy;

drop class dummy;


text:
[![Build Status](https://travis-ci.org/vinzenz/uripp.png?branch=master)](https://travis-ci.org/vinzenz/uripp)
[![Coverity Scan Build Status](https://scan.coverity.com/projects/2059/badge.svg)](https://scan.coverity.com/projects/2059)

uripp - URI C++ library
See: https://sourceforge.net/projects/uripp


text:
layout: page
title: About
---
Just a few words and photos about my time in Copenhagen, Denmark.


text:
<?php

namespace TomPHPTest\SpecificationExample\Application\Repository;

use TomPHP\SpecificationExample\Application\Date;
use TomPHP\SpecificationExample\Application\Price;
use TomPHP\SpecificationExample\Application\Video;
use TomPHP\SpecificationExample\Application\Specification\AndSpecification;
use TomPHP\SpecificationExample\Application\Specification\IsFreeSpecification;
use TomPHP\SpecificationExample\Application\Specification\NewerThanSpecification;
use TomPHP\SpecificationExample\Application\Specification\Specification;

abstract class VideoRepositoryTest extends \PHPUnit_Framework_TestCase
{
    /** @var VideoRepository */
    protected $repository;

    /** @var Video[] */
    private $videos = [];

    protected function setUp()
    {
        $this->videos[] = new Video('free vid 1', Date::fromDate('2014-02-04'), new Price(0));
        $this->videos[] = new Video('premium vid 1', Date::fromDate('2014-02-12'), new Price(10));
        $this->videos[] = new Video('free vid 2', Date::fromDate('2014-03-12'), new Price(0));

        foreach ($this->videos as $video) {
            $this->repository->save($video);
        }
    }

    private function assertGetBySpecificationMatchesFor(Specification $specification)
    {
        $videos = array_filter(
            $this->repository->fetchAll(),
            function (Video $video) use ($specification) {
                return $specification->isSatisfiedBy($video);
            }
        );

        $this->assertEquals(
            array_values($videos),
            array_values($this->repository->fetchBySpecification($specification))
        );
    }

    public function test_it_is_a_VideoRepository()
    {
        $this->assertInstanceOf(
            'TomPHP\SpecificationExample\Application\Repository\VideoRepository',
            $this->repository
        );
    }

    public function test_it_fetches_all_videos()
    {
        $this->assertEquals($this->videos, $this->repository->fetchAll());
    }

    public function test_is_free_specification()
    {
        $this->assertGetBySpecificationMatchesFor(new IsFreeSpecification());
    }

    public function test_new_than_specification()
    {
        $this->assertGetBySpecificationMatchesFor(
            new NewerThanSpecification(Date::fromDate('2014-02-10'))
        );
    }

    public function test_is_free_and_new_than_specification()
    {
        $this->assertGetBySpecificationMatchesFor(
            new AndSpecification(
                new IsFreeSpecification(),
                new NewerThanSpecification(Date::fromDate('2014-02-10'))
            )
        );
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project name="facades" default="facades-base">
    <dirname property="module.root.folder" file="${ant.file}" />
    <property name="facades.root.folder" value="${module.root.folder}" />
    <dirname property="gitcloud.root.folder" file="${facades.root.folder}" />
    <property name="gitcloud.parent.folder" value="${gitcloud.root.folder}${file.separator}parent" />
    <import file="${gitcloud.parent.folder}${file.separator}build-gitcloud.xml" />

	<target name="facades-base" depends="gitcloud-base" />
</project>


text:
package com.chefooff.servicedesk.resource;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class PropertyConf {

	static Properties conFile;
	static{
		conFile = new Properties();
		try {
			InputStream stream = PropertyConf.class.getClassLoader().getResourceAsStream("com/chefooff/servicedesk/resource/portlet.properties");
			try {
				conFile.load(stream);
			} finally {
				stream.close();
			}
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

	public static Properties getPropfile(){
		return conFile;
	}
}


text:
static LeveyTabBarController *leveyTabBarController;

@implementation UIViewController (LeveyTabBarControllerSupport)

- (LeveyTabBarController *)leveyTabBarController
{
	return leveyTabBarController;
}

@end

@interface LeveyTabBarController (private)
- (void)displayViewAtIndex:(NSUInteger)index;
@end

@implementation LeveyTabBarController
@synthesize delegate = _delegate;
@synthesize selectedViewController = _selectedViewController;
@synthesize viewControllers = _viewControllers;
@synthesize selectedIndex = _selectedIndex;
@synthesize tabBarHidden = _tabBarHidden;
@synthesize animateDriect;

#pragma mark -
#pragma mark lifecycle
- (id)initWithViewControllers:(NSArray *)vcs imageArray:(NSArray *)arr buttonTexts:(NSArray *)buttonTextArray
{
	self = [super init];
	if (self)
	{
		_viewControllers = [NSMutableArray arrayWithArray:vcs];

		CGRect rt = [[UIScreen mainScreen] applicationFrame];
        if(IOS_7)
            rt.size.height += 20;
        _containerView = [[UIView alloc] initWithFrame:rt];

		_transitionView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320.0f, _containerView.frame.size.height - kTabBarHeight)];

		_tabBar = [[LeveyTabBar alloc] initWithFrame:CGRectMake(0, _containerView.frame.size.height - kTabBarHeight, 320.0f, kTabBarHeight) buttonImages:arr buttonTexts:buttonTextArray];
        [_tabBar setBackgroundImage:[self imageWithColor:[UIColor colorWithRed:242.0f/255.0f green:88.0f/255.0f blue:118.0f/255.0f alpha:1.0f]]];
        //[_tabBar setShadowImage:[UIImage imageNamed:@"login_bg.png"]];
        //[_tabBar setClipsToBounds:YES];
        //[_tabBar setShadowImage:[[UIImage alloc]init]];
		_tabBar.inner_delegate = self;

        leveyTabBarController = self;
        animateDriect = 0;

	}
	return self;
}

- (void)loadView
{
	[super loadView];
    _containerView.backgroundColor = [UIColor whiteColor];
	[_containerView addSubview:_transitionView];
	[_containerView addSubview:_tabBar];
	self.view = _containerView;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.selectedIndex = 0;
}

#pragma mark - instant methods

- (LeveyTabBar *)tabBar
{
	return _tabBar;
}

- (BOOL)tabBarTransparent
{
	return _tabBarTransparent;
}

- (void)setTabBarTransparent:(BOOL)yesOrNo
{
	if (yesOrNo == YES)
	{
		_transitionView.frame = _containerView.bounds;
	}
	else
	{
		_transitionView.frame = CGRectMake(0, 0, 320.0f, _containerView.frame.size.height - kTabBarHeight);
	}
}

- (void)hidesTabBar:(BOOL)yesOrNO animated:(BOOL)animated
{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3f];
    [self setTabBarTransparent:YES];
    if (yesOrNO) {
        self.tabBar.hidden = YES;
    }else{
        self.tabBar.hidden = NO;
    }

    [UIView commitAnimations];
}

- (NSUInteger)selectedIndex
{
	return _selectedIndex;
}
- (UIViewController *)selectedViewController
{
    return [_viewControllers objectAtIndex:_selectedIndex];
}

-(void)setSelectedIndex:(NSUInteger)index
{
    [self displayViewAtIndex:index];
    [_tabBar selectTabAtIndex:index];
}

- (void)removeViewControllerAtIndex:(NSUInteger)index
{
    if (index >= [_viewControllers count])
    {
        return;
    }
    // Remove view from superview.
    [[(UIViewController *)[_viewControllers objectAtIndex:index] view] removeFromSuperview];
    // Remove viewcontroller in array.
    [_viewControllers removeObjectAtIndex:index];
    // Remove tab from tabbar.
    [_tabBar removeTabAtIndex:index];
}

- (void)insertViewController:(UIViewController *)vc withImageDic:(NSDictionary *)dict atIndex:(NSUInteger)index
{
    [_viewControllers insertObject:vc atIndex:index];
    [_tabBar insertTabWithImageDic:dict atIndex:index];
}

#pragma mark - Private methods
- (void)displayViewAtIndex:(NSUInteger)index
{
    // Before change index, ask the delegate should change the index.
    if ([_delegate respondsToSelector:@selector(tabBarController:shouldSelectViewController:)])
    {
        if (![_delegate tabBarController:self shouldSelectViewController:[self.viewControllers objectAtIndex:index]])
        {
            return;
        }
    }
    // If target index if equal to current index, do nothing.
    if (_selectedIndex == index && [[_transitionView subviews] count] != 0)
    {
        return;
    }
    _selectedIndex = index;

	UIViewController *selectedVC = [self.viewControllers objectAtIndex:index];

	selectedVC.view.frame = _transitionView.frame;
	if ([selectedVC.view isDescendantOfView:_transitionView])
	{
		[_transitionView bringSubviewToFront:selectedVC.view];
	}
	else
	{
		[_transitionView addSubview:selectedVC.view];
	}

    // Notify the delegate, the viewcontroller has been changed.
    if ([_delegate respondsToSelector:@selector(tabBarController:didSelectViewController:)])
    {
        [_delegate tabBarController:self didSelectViewController:selectedVC];
    }

}

#pragma mark -
#pragma mark tabBar delegates
- (void)tabBar:(LeveyTabBar *)tabBar didSelectIndex:(NSInteger)index
{
	if (self.selectedIndex == index) {
        UINavigationController *nav = [self.viewControllers objectAtIndex:index];
        [nav popToRootViewControllerAnimated:YES];
    }else {
        [self displayViewAtIndex:index];
    }
}

-(UIImage *)imageWithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}
@end


text:
        var config = require('../config');

        /**
         * @exports zrender/tool/log
         * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
         */
        module.exports = function() {
            if (config.debugMode === 0) {
                return;
            }
            else if (config.debugMode == 1) {
                for (var k in arguments) {
                    throw new Error(arguments[k]);
                }
            }
            else if (config.debugMode > 1) {
                for (var k in arguments) {
                    console.log(arguments[k]);
                }
            }
        };

        /* for debug
        return function(mes) {
            document.getElementById('wrong-message').innerHTML =
                mes + ' ' + (new Date() - 0)
                + '<br/>'
                + document.getElementById('wrong-message').innerHTML;
        };
        */


text:
package com.bardframework.bard.core;

public interface HandlerFactory {
    public <HandlerClass extends GenericHandler> HandlerClass initHandler(
        Class<HandlerClass> handlerClass) throws HandlerInitException;

    public static class HandlerInitException extends Exception {
        public HandlerInitException(Exception e) {
            super(e);
        }
    }
}


text:
"""pygatt Class Definitions"""

__author__ = 'Greg Albrecht <gba@orionlabs.co>'
__license__ = 'Apache License, Version 2.0'
__copyright__ = 'Copyright 2015 Orion Labs'

import logging
import logging.handlers
import string
import time
import threading

from collections import defaultdict

import pexpect

import pygatt.constants
import pygatt.exceptions
import pygatt.util

class BluetoothLEDevice(object):
    logger = logging.getLogger('pygatt')
    logger.setLevel(pygatt.constants.LOG_LEVEL)
    console_handler = logging.StreamHandler()
    console_handler.setLevel(pygatt.constants.LOG_LEVEL)
    formatter = logging.Formatter(pygatt.constants.LOG_FORMAT)
    console_handler.setFormatter(formatter)
    logger.addHandler(console_handler)

    GATTTOOL_PROMPT = r".*> "

    def __init__(self, mac_address, hci_device='hci0', logfile=None, **kwargs):
        self.handles = {}
        self.subscribed_handlers = {}
        self.address = mac_address

        self.running = True

        self.lock = threading.Lock()

        self.connection_lock = threading.RLock()

        mac_random_option_str = ''  # added by lijun
        for k, v in kwargs.items():
            if k.lower() == 'mac_random':
                if bool(v) == True:
                    mac_random_option_str = '-t random'

        gatttool_cmd = ' '.join([
            'gatttool',
            '-b',
            self.address,
            '-i',
            hci_device,
            '-I',
            mac_random_option_str
        ])

        self.logger.debug('gatttool_cmd=%s', gatttool_cmd)
        self.con = pexpect.spawn(gatttool_cmd, logfile=logfile)

        self.con.expect(r'\[LE\]>', timeout=1)

        self.callbacks = defaultdict(set)

        self.thread = threading.Thread(target=self.run)
        self.thread.daemon = True
        self.thread.start()

    def bond(self):
        """Securely Bonds to the BLE device."""
        self.logger.info('Bonding')
        self.con.sendline('sec-level medium')
        self.con.expect(self.GATTTOOL_PROMPT, timeout=1)

    def connect(self, timeout=pygatt.constants.DEFAULT_CONNECT_TIMEOUT_S):
        """Connect to the device."""
        self.logger.info('Connecting with timeout=%s', timeout)
        try:
            with self.connection_lock:
                self.con.sendline('connect')
                self.con.expect(r'Connection successful.*\[LE\]>', timeout)
        except pexpect.TIMEOUT:
            message = ("Timed out connecting to %s after %s seconds."
                       % (self.address, timeout))
            self.logger.error(message)
            raise pygatt.exceptions.NotConnectedError(message)

    def get_handle(self, uuid):
        """
        Look up and return the handle for an attribute by its UUID.

        :param uuid: The UUID of the characteristic.
        :type uuid: str
        :return: None if the UUID was not found.
        """
        if uuid not in self.handles:
            self.logger.debug("Looking up handle for characteristic %s", uuid)
            with self.connection_lock:
                self.con.sendline('characteristics')

                timeout = 2
                while True:
                    try:
                        self.con.expect(
                            r"handle: 0x([a-fA-F0-9]{4}), "
                            "char properties: 0x[a-fA-F0-9]{2}, "
                            "char value handle: 0x[a-fA-F0-9]{4}, "
                            "uuid: ([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\r\n",  # noqa
                            timeout=timeout)
                    except pexpect.TIMEOUT:
                        break
                    except pexpect.EOF:
                        break
                    else:
                        try:
                            handle = int(self.con.match.group(1), 16)
                            char_uuid = self.con.match.group(2).strip()
                            self.handles[char_uuid] = handle
                            self.logger.debug(
                                "Found characteristic %s, handle: %d", uuid,
                                handle)

                            # The characteristics all print at once, so after
                            # waiting 1-2 seconds for them to all fetch, you can
                            # load the rest without much delay at all.
                            timeout = .01
                        except AttributeError:
                            pass
        handle = self.handles.get(uuid)
        if handle is None:
            message = "No characteristic found matching %s" % uuid
            self.logger.warn(message)
            raise pygatt.exceptions.BluetoothLEError(message)

        self.logger.debug(
            "Characteristic %s, handle: %d", uuid, handle)
        return handle

    def _expect(self, expected, timeout=pygatt.constants.DEFAULT_TIMEOUT_S):
        """We may (and often do) get an indication/notification before a
        write completes, and so it can be lost if we "expect()"'d something
        that came after it in the output, e.g.:

        > char-write-req 0x1 0x2
        Notification handle: xxx
        Write completed successfully.
        >

        Anytime we expect something we have to expect noti/indication first for
        a short time.
        """
        with self.connection_lock:
            patterns = [
                expected,
                'Notification handle = .*? \r',
                'Indication   handle = .*? \r',
                '.*Invalid file descriptor.*',
                '.*Disconnected\r',
            ]
            while True:
                try:
                    matched_pattern_index = self.con.expect(patterns, timeout)
                    if matched_pattern_index == 0:
                        break
                    elif matched_pattern_index in [1, 2]:
                        self._handle_notification(self.con.after)
                    elif matched_pattern_index in [3, 4]:
                        if self.running:
                            message = ("Unexpectedly disconnected - do you "
                                       "need to clear bonds?")
                            self.logger.error(message)
                            self.running = False
                        raise pygatt.exceptions.NotConnectedError()
                except pexpect.TIMEOUT:
                    raise pygatt.exceptions.NotificationTimeout(
                        "Timed out waiting for a notification")

    def char_write(self, handle, value, wait_for_response=False):
        """
        Writes a value to a given characteristic handle.

        :param handle:
        :param value:
        :param wait_for_response:
        """
        with self.connection_lock:
            hexstring = ''.join('%02x' % byte for byte in value)

            if wait_for_response:
                cmd = 'req'
            else:
                cmd = 'cmd'

            cmd = 'char-write-%s 0x%02x %s' % (cmd, handle, hexstring)

            self.logger.debug('Sending cmd=%s', cmd)
            self.con.sendline(cmd)

            if wait_for_response:
                try:
                    self._expect('Characteristic value written successfully')
                except pygatt.exceptions.NoResponseError:
                    self.logger.error("No response received", exc_info=True)
                    raise

            self.logger.info('Sent cmd=%s', cmd)

    def char_read_uuid(self, uuid):
        """
        Reads a Characteristic by UUID.

        :param uuid: UUID of Characteristic to read.
        :type uuid: str
        :return: bytearray of result.
        :rtype: bytearray
        """
        with self.connection_lock:
            self.con.sendline('char-read-uuid %s' % uuid)
            self._expect('value: .*? \r')

            rval = self.con.after.split()[1:]

            return bytearray([int(x, 16) for x in rval])

    def char_read_hnd(self, handle):
        """
        Reads a Characteristic by Handle.

        :param handle: Handle of Characteristic to read.
        :type handle: str
        :return:
        :rtype:
        """
        with self.connection_lock:
            self.con.sendline('char-read-hnd 0x%02x' % handle)
            self._expect('descriptor: .*?\r')

            rval = self.con.after.split()[1:]

            return [int(n, 16) for n in rval]

    def subscribe(self, uuid, callback=None, indication=False):
        """
        Enables subscription to a Characteristic with ability to call callback.

        :param uuid:
        :param callback:
        :param indication:
        :return:
        :rtype:
        """
        self.logger.info(
            'Subscribing to uuid=%s with callback=%s and indication=%s',
            uuid, callback, indication)
        definition_handle = self.get_handle(uuid)
        # Expect notifications on the value handle...
        value_handle = definition_handle + 1
        # but write to the characteristic config to enable notifications
        characteristic_config_handle = value_handle + 1

        if indication:
            properties = bytearray([0x02, 0x00])
        else:
            properties = bytearray([0x01, 0x00])

        try:
            self.lock.acquire()

            if callback is not None:
                self.callbacks[value_handle].add(callback)

            if self.subscribed_handlers.get(value_handle, None) != properties:
                self.char_write(
                    characteristic_config_handle,
                    properties,
                    wait_for_response=False
                )
                self.logger.debug("Subscribed to uuid=%s", uuid)
                self.subscribed_handlers[value_handle] = properties
            else:
                self.logger.debug("Already subscribed to uuid=%s", uuid)
        finally:
            self.lock.release()

    def _handle_notification(self, msg):
        """
        Receive a notification from the connected device and propagate the value
        to all registered callbacks.
        """
        hex_handle, _, hex_value = string.split(msg.strip(), maxsplit=5)[3:]
        handle = int(hex_handle, 16)
        value = bytearray.fromhex(hex_value)

        self.logger.info('Received notification on handle=%s, value=%s',
                         hex_handle, hex_value)
        try:
            self.lock.acquire()

            if handle in self.callbacks:
                for callback in self.callbacks[handle]:
                    callback(handle, value)
        finally:
            self.lock.release()

    def stop(self):
        """Stop the backgroud notification handler in preparation for a
        disconnect.
        """
        self.logger.info('Stopping')
        self.running = False

        if self.con.isalive():
            self.con.sendline('exit')
            while True:
                if not self.con.isalive():
                    break
                time.sleep(0.1)
            self.con.close()

    def run(self):
        """Run a background thread to listen for notifications.
        """
        self.logger.info('Running...')
        while self.running:
            with self.connection_lock:
                try:
                    self._expect("fooooooo", timeout=.1)
                except pygatt.exceptions.NotificationTimeout:
                    pass
                except (pygatt.exceptions.NotConnectedError, pexpect.EOF):
                    break
            # TODO need some delay to avoid aggresively grabbing the lock,
            # blocking out the others. worst case is 1 second delay for async
            # not received as a part of another request
            time.sleep(.01)
        self.logger.info("Listener thread finished")


text:
'use strict';

var Q = require('q');
var electron = require('electron-prebuilt');
var pathUtil = require('path');
var childProcess = require('child_process');
var kill = require('tree-kill');
var utils = require('./utils');
var watch;

var gulpPath = pathUtil.resolve('./node_modules/.bin/gulp');
if (process.platform === 'win32') {
  gulpPath += '.cmd';
}

var runBuild = function() {
  var deferred = Q.defer();

  var build = childProcess.spawn(gulpPath, [
      'build',
      '--env=' + utils.getEnvName(),
      '--color',
    ], {
      stdio: 'inherit',
    });

  build.on('close', function(code) {
    deferred.resolve();
  });

  return deferred.promise;
};

var runGulpWatch = function() {
  watch = childProcess.spawn(gulpPath, [
      'watch',
      '--env=' + utils.getEnvName(),
      '--color',
    ], {
      stdio: 'inherit',
    });

  watch.on('close', function(code) {
    // Gulp watch exits when error occured during build.
    // Just respawn it then.
    runGulpWatch();
  });
};

var runApp = function() {
  var app = childProcess.spawn(electron, ['./build'], {
    stdio: 'inherit',
  });

  app.on('close', function(code) {
    // User closed the app. Kill the host process.
    kill(watch.pid, 'SIGKILL', function() {
      process.exit();
    });
  });
};

runBuild()
.then(function() {
  runGulpWatch();
  runApp();
});


text:
<?php
/*
 * Created on 16/04/2006
 */

class CustomValidator extends TPage
{
	function CustomValidation($sender, $params)
	{
		$params->isValid = $this->text1->Text == "Prado";
	}
}


text:
/**
 * Author: Jeff Whelpley
 * Date: 2/15/15
 *
 * This uses an HTML parser to precompile HTML files into Jyt objects.
 */
var htmlparser  = require('htmlparser');
var runtime     = require('./jyt.runtime');
var utils       = require('./jyt.utils');

/**
 * Convert the HTML parser DOM format to Jyt format
 * @param dom
 */
function convertDomToJyt(dom) {
    var i, elems, tempElem;

    // if just one element in the array, bump it up a level
    if (utils.isArray(dom) && dom.length === 1) {
        dom = dom[0];
    }
    // if multiple, then we create a sibling array of elems and return it
    else if (utils.isArray(dom)) {
        elems = [];
        for (i = 0; i < dom.length; i++) {
            tempElem = convertDomToJyt(dom[i]);
            if (tempElem !== null) {
                elems.push(tempElem);
            }
        }

        return runtime.naked(elems, null);
    }

    // if type is string, then just return it
    if (dom.type === 'text') {
        return dom.data;
    }
    // if no dom name, then just return empty string since it is likely a comment
    if (!dom.name) {
        return null;
    }

    // if we get here then we have just one element
    var elem = runtime.elem(dom.name);
    var childCount = dom.children && dom.children.length;

    // attributes should be the same
    elem.attributes = dom.attribs;

    // recursively add children
    if (dom.children && dom.children.length) {
        elem.children = [];
        for (i = 0; i < childCount; i++) {
            tempElem = convertDomToJyt(dom.children[i]);
            if (tempElem !== null) {
                elem.children.push(tempElem);
            }
        }

        // if one child that is a string, bring it up a level
        if (elem.children.length === 1 && utils.isString(elem.children[0])) {
            elem.text = elem.children[0];
            delete elem.children;
        }
        // if no children, remove it
        else if (elem.children.length === 0) {
            delete elem.children;
        }
    }

    return elem;
}

/**
 * Parse the HTML into Jyt format
 * @param html
 * @param cb
 * @returns {*}
 */
function parse(html, cb) {

    if (!cb) {
        throw new Error('Must pass in callback to parse() as 2nd param');
    }

    var handler = new htmlparser.DefaultHandler(function (error, dom) {
        if (error) {
            cb('Error while parsing: ' + error);
        }
        else {
            var jytObj = convertDomToJyt(dom);
            cb(null, jytObj);
        }
    }, { ignoreWhitespace: true });

    var parser = new htmlparser.Parser(handler);
    parser.parseComplete(html);
}

// expose functions
module.exports = {
    convertDomToJyt: convertDomToJyt,
    parse: parse
};


text:
import {Component} from '@angular/core'

@Component({
    templateUrl: 'app/sipv2/sipv2.component.html'
})
export class Sipv2Component {
    pageTitle: string = 'sipv2';
}


text:
/**
 * Craft Upgrade Modal
 */
Craft.UpgradeModal = Garnish.Modal.extend(
{
	$container: null,
	$body: null,
	$compareScreen: null,
	$checkoutScreen: null,
	$successScreen: null,

	$checkoutForm: null,
	$checkoutLogo: null,
	$checkoutSubmitBtn: null,
	$checkoutSpinner: null,
	$checkoutFormError: null,
	$checkoutSecure: null,
	clearCheckoutFormTimeout: null,
	$customerNameInput: null,
	$customerEmailInput: null,
	$ccField: null,
	$ccNumInput: null,
	$ccExpInput: null,
	$ccCvcInput: null,
	$businessFieldsToggle: null,
	$businessNameInput: null,
	$businessAddress1Input: null,
	$businessAddress2Input: null,
	$businessCityInput: null,
	$businessStateInput: null,
	$businessCountryInput: null,
	$businessZipInput: null,
	$businessTaxIdInput: null,
	$purchaseNotesInput: null,
	$couponInput: null,
	$couponSpinner: null,
	submittingPurchase: false,

	stripePublicKey: null,
	editions: null,
	countries: null,
	states: null,
	edition: null,
	initializedCheckoutForm: false,

	applyingCouponCode: false,
	applyNewCouponCodeAfterDoneLoading: false,
	couponPrice: null,
	formattedCouponPrice: null,

	init: function(settings)
	{
		this.$container = $('
').appendTo(Garnish.$bod);

		this.base(this.$container, $.extend({
			resizable: true
		}, settings));

		Craft.postActionRequest('app/getUpgradeModal', $.proxy(function(response, textStatus)
		{
			this.$container.removeClass('loading');

			if (textStatus == 'success')
			{
				if (response.success)
				{
					this.stripePublicKey = response.stripePublicKey;
					this.editions = response.editions;
					this.countries = response.countries;
					this.states = response.states;

					this.$container.append(response.modalHtml);
					this.$container.append('');

					this.$compareScreen     = this.$container.children('#upgrademodal-compare');
					this.$checkoutScreen    = this.$container.children('#upgrademodal-checkout');
					this.$successScreen     = this.$container.children('#upgrademodal-success');

					this.$checkoutLogo           = this.$checkoutScreen.find('.logo:first');
					this.$checkoutForm           = this.$checkoutScreen.find('form:first');
					this.$checkoutSubmitBtn      = this.$checkoutForm.find('#pay-button');
					this.$checkoutSpinner        = this.$checkoutForm.find('#pay-spinner');
					this.$customerNameInput      = this.$checkoutForm.find('#customer-name');
					this.$customerEmailInput     = this.$checkoutForm.find('#customer-email');
					this.$ccField                = this.$checkoutForm.find('#cc-inputs');
					this.$ccNumInput             = this.$ccField.find('#cc-num');
					this.$ccExpInput             = this.$ccField.find('#cc-exp');
					this.$ccCvcInput             = this.$ccField.find('#cc-cvc');
					this.$businessFieldsToggle   = this.$checkoutForm.find('.fieldtoggle');
					this.$businessNameInput      = this.$checkoutForm.find('#business-name');
					this.$businessAddress1Input  = this.$checkoutForm.find('#business-address1');
					this.$businessAddress2Input  = this.$checkoutForm.find('#business-address2');
					this.$businessCityInput      = this.$checkoutForm.find('#business-city');
					this.$businessStateInput     = this.$checkoutForm.find('#business-state');
					this.$businessCountryInput   = this.$checkoutForm.find('#business-country');
					this.$businessZipInput       = this.$checkoutForm.find('#business-zip');
					this.$businessTaxIdInput     = this.$checkoutForm.find('#business-taxid');
					this.$purchaseNotesInput     = this.$checkoutForm.find('#purchase-notes');
					this.$checkoutSecure         = this.$checkoutScreen.find('.secure:first');
					this.$couponInput            = this.$checkoutForm.find('#coupon-input');
					this.$couponSpinner          = this.$checkoutForm.find('#coupon-spinner');

					var $buyBtns = this.$compareScreen.find('.buybtn');
					this.addListener($buyBtns, 'click', 'onBuyBtnClick');

					var $testBtns = this.$compareScreen.find('.btn.test');
					this.addListener($testBtns, 'click', 'onTestBtnClick');

					var $cancelCheckoutBtn = this.$checkoutScreen.find('#upgrademodal-cancelcheckout');
					this.addListener($cancelCheckoutBtn, 'click', 'cancelCheckout');
				}
				else
				{
					var error;

					if (response.error)
					{
						error = response.error;
					}
					else
					{
						error = Craft.t('An unknown error occurred.');
					}

					this.$container.append('
'+error+'
');
				}

				// Include Stripe.js
				$('').appendTo(Garnish.$bod);
			}
		}, this));
	},

	initializeCheckoutForm: function()
	{
		this.$ccNumInput.payment('formatCardNumber');
		this.$ccExpInput.payment('formatCardExpiry');
		this.$ccCvcInput.payment('formatCardCVC');

		this.$businessFieldsToggle.fieldtoggle();

		this.$businessCountryInput.selectize({ valueField: 'iso', labelField: 'name', searchField: ['name', 'iso'], dropdownParent: 'body', inputClass: 'selectize-input text' });
		this.$businessCountryInput[0].selectize.addOption(this.countries);
		this.$businessCountryInput[0].selectize.refreshOptions(false);

		this.$businessStateInput.selectize({ valueField: 'abbr', labelField: 'name', searchField: ['name', 'abbr'], dropdownParent: 'body', inputClass: 'selectize-input text', create: true });
		this.$businessStateInput[0].selectize.addOption(this.states);
		this.$businessStateInput[0].selectize.refreshOptions(false);

		this.addListener(this.$couponInput, 'textchange', {delay: 500}, 'applyCoupon');
		this.addListener(this.$checkoutForm, 'submit', 'submitPurchase');
	},

	applyCoupon: function()
	{
		if (this.applyingCouponCode)
		{
			this.applyNewCouponCodeAfterDoneLoading = true;
			return;
		}

		var couponCode = this.$couponInput.val();

		if (couponCode)
		{
			var data = {
				edition: this.edition,
				couponCode: couponCode
			};

			this.applyingCouponCode = true;
			this.$couponSpinner.removeClass('hidden');

			Craft.postActionRequest('app/getCouponPrice', data, $.proxy(function(response, textStatus)
			{
				this.applyingCouponCode = false;

				// Are we just waiting to apply a new code?
				if (this.applyNewCouponCodeAfterDoneLoading)
				{
					this.applyNewCouponCodeAfterDoneLoading = false;
					this.applyCoupon();
				}
				else
				{
					this.$couponSpinner.addClass('hidden');

					if (textStatus == 'success' && response.success)
					{
						this.couponPrice = response.couponPrice;
						this.formattedCouponPrice = response.formattedCouponPrice;
						this.updateCheckoutUi();
					}
				}
			}, this));
		}
		else
		{
			// Clear out the coupon price
			this.couponPrice = null;
			this.updateCheckoutUi();
		}
	},

	onHide: function()
	{
		if (this.initializedCheckoutForm)
		{
			this.$businessCountryInput[0].selectize.blur();
			this.$businessStateInput[0].selectize.blur();
		}

		this.clearCheckoutFormInABit();
		this.base();
	},

	onBuyBtnClick: function(ev)
	{
		var $btn = $(ev.currentTarget);
		this.edition = $btn.data('edition');
		this.couponPrice = null;
		this.formattedCouponPrice = null;

		switch (this.edition)
		{
			case 1:
			{
				this.$checkoutLogo.attr('class', 'logo craftclient').text('Client');
				break;
			}
			case 2:
			{
				this.$checkoutLogo.attr('class', 'logo craftpro').text('Pro');
				break;
			}
		}

		this.updateCheckoutUi();

		if (this.clearCheckoutFormTimeout)
		{
			clearTimeout(this.clearCheckoutFormTimeout);
		}

		// Slide it in

		var width = this.getWidth();

		this.$compareScreen.velocity('stop').animateLeft(-width, 'fast', $.proxy(function()
		{
			this.$compareScreen.addClass('hidden');

			if (!this.initializedCheckoutForm)
			{
				this.initializeCheckoutForm();
				this.initializedCheckoutForm = true;
			}
		}, this));

		this.$checkoutScreen.velocity('stop').css(Craft.left, width).removeClass('hidden').animateLeft(0, 'fast');
	},

	updateCheckoutUi: function()
	{
		// Only show the CC fields if there is a price
		if (this.getPrice() == 0)
		{
			this.$ccField.hide();
		}
		else
		{
			this.$ccField.show();
		}

		// Update the Pay button
		this.$checkoutSubmitBtn.val(Craft.t('Pay {price}', {
			price: this.getFormattedPrice()
		}));
	},

	getPrice: function()
	{
		if (this.couponPrice !== null)
		{
			return this.couponPrice;
		}

		if (this.editions[this.edition].salePrice)
		{
			return this.editions[this.edition].salePrice;
		}

		return this.editions[this.edition].price;
	},

	getFormattedPrice: function()
	{
		if (this.couponPrice !== null)
		{
			return this.formattedCouponPrice;
		}

		if (this.editions[this.edition].salePrice)
		{
			return this.editions[this.edition].formattedSalePrice;
		}

		return this.editions[this.edition].formattedPrice;
	},

	onTestBtnClick: function(ev)
	{
		var data = {
			edition: $(ev.currentTarget).data('edition')
		};

		Craft.postActionRequest('app/testUpgrade', data, $.proxy(function(response, textStatus)
		{
			if (textStatus == 'success')
			{
				var width = this.getWidth();

				this.$compareScreen.velocity('stop').animateLeft(-width, 'fast', $.proxy(function()
				{
					this.$compareScreen.addClass('hidden');
				}, this));

				this.onUpgrade();
			}
		}, this));
	},

	cancelCheckout: function()
	{
		var width = this.getWidth();

		this.$compareScreen.velocity('stop').removeClass('hidden').animateLeft(0, 'fast');
		this.$checkoutScreen.velocity('stop').animateLeft(width, 'fast', $.proxy(function()
		{
			this.$checkoutScreen.addClass('hidden');
		}, this));

		this.clearCheckoutFormInABit();
	},

	getExpiryValues: function()
	{
		return this.$ccExpInput.payment('cardExpiryVal');
	},

	submitPurchase: function(ev)
	{
		ev.preventDefault();

		if (this.submittingPurchase)
		{
			return;
		}

		this.cleanupCheckoutForm();

		// Get the price
		var price = this.getPrice();

		// Get the CC data
		var expVal = this.getExpiryValues();
		var ccData = {
			name:      this.$customerNameInput.val(),
			number:    this.$ccNumInput.val(),
			exp_month: expVal.month,
			exp_year:  expVal.year,
			cvc:       this.$ccCvcInput.val()
		};

		// Validate it
		var validates = true;

		if (!ccData.name)
		{
			validates = false;
			this.$customerNameInput.addClass('error');
		}

		if (price != 0)
		{
			if (!Stripe.validateCardNumber(ccData.number))
			{
				validates = false;
				this.$ccNumInput.addClass('error');
			}

			if (!Stripe.validateExpiry(ccData.exp_month, ccData.exp_year))
			{
				validates = false;
				this.$ccExpInput.addClass('error');
			}

			if (!Stripe.validateCVC(ccData.cvc))
			{
				validates = false;
				this.$ccCvcInput.addClass('error');
			}
		}

		if (validates)
		{
			this.submittingPurchase = true;

			// Get a CC token from Stripe.js
			this.$checkoutSubmitBtn.addClass('active');
			this.$checkoutSpinner.removeClass('hidden');

			if (price != 0)
			{
				Stripe.setPublishableKey(this.stripePublicKey);
				Stripe.createToken(ccData, $.proxy(function(status, response)
				{
					if (!response.error)
					{
						this.sendPurchaseRequest(price, response.id);
					}
					else
					{
						this.onPurchaseResponse();
						this.showError(response.error.message);
						Garnish.shake(this.$checkoutForm, 'left');
					}
				}, this));
			}
			else
			{
				this.sendPurchaseRequest(0, null);
			}
		}
		else
		{
			Garnish.shake(this.$checkoutForm, 'left');
		}
	},

	sendPurchaseRequest: function(expectedPrice, ccTokenId)
	{
		// Pass the token along to Elliott to charge the card
		var expVal = expectedPrice != 0 ? this.getExpiryValues() : {month: null, year: null};

		var data = {
			ccTokenId:            ccTokenId,
			expMonth:             expVal.month,
			expYear:              expVal.year,
			edition:              this.edition,
			expectedPrice:        expectedPrice,
			name:                 this.$customerNameInput.val(),
			email:                this.$customerEmailInput.val(),
			businessName:         this.$businessNameInput.val(),
			businessAddress1:     this.$businessAddress1Input.val(),
			businessAddress2:     this.$businessAddress2Input.val(),
			businessCity:         this.$businessCityInput.val(),
			businessState:        this.$businessStateInput.val(),
			businessCountry:      this.$businessCountryInput.val(),
			businessZip:          this.$businessZipInput.val(),
			businessTaxId:        this.$businessTaxIdInput.val(),
			purchaseNotes:        this.$purchaseNotesInput.val(),
			couponCode:           this.$couponInput.val()
		};

		Craft.postActionRequest('app/purchaseUpgrade', data, $.proxy(this, 'onPurchaseUpgrade'));
	},

	onPurchaseResponse: function()
	{
		this.submittingPurchase = false;
		this.$checkoutSubmitBtn.removeClass('active');
		this.$checkoutSpinner.addClass('hidden');
	},

	onPurchaseUpgrade: function(response, textStatus)
	{
		this.onPurchaseResponse();

		if (textStatus == 'success')
		{
			if (response.success)
			{
				var width = this.getWidth();

				this.$checkoutScreen.velocity('stop').animateLeft(-width, 'fast', $.proxy(function()
				{
					this.$checkoutScreen.addClass('hidden');
				}, this));

				this.onUpgrade();
			}
			else
			{
				if (response.errors)
				{
					var errorText = '';

					for (var i in response.errors)
					{
						if (errorText)
						{
							errorText += '
';
						}

						errorText += response.errors[i];
					}

					this.showError(errorText);
				}
				else
				{
					var errorText = Craft.t('An unknown error occurred.');
				}

				Garnish.shake(this.$checkoutForm, 'left');
			}
		}
	},

	showError: function(error)
	{
		this.$checkoutFormError = $('
'+error+'
').insertBefore(this.$checkoutSecure);
	},

	onUpgrade: function()
	{
		this.$successScreen.css(Craft.left, this.getWidth()).removeClass('hidden').animateLeft(0, 'fast');

		var $refreshBtn = this.$successScreen.find('.btn:first');
		this.addListener($refreshBtn, 'click', function()
		{
			location.reload();
		});

		this.trigger('upgrade');
	},

	cleanupCheckoutForm: function()
	{
		this.$checkoutForm.find('.error').removeClass('error');

		if (this.$checkoutFormError)
		{
			this.$checkoutFormError.remove();
			this.$checkoutFormError = null;
		}
	},

	clearCheckoutForm: function()
	{
		this.$customerNameInput.val('');
		this.$customerEmailInput.val('');
		this.$ccNumInput.val('');
		this.$ccExpInput.val('');
		this.$ccCvcInput.val('');
		this.$businessNameInput.val('');
		this.$businessAddress1Input.val('');
		this.$businessAddress2Input.val('');
		this.$businessCityInput.val('');
		this.$businessStateInput.val('');
		this.$businessCountryInput.val('');
		this.$businessZipInput.val('');
		this.$businessTaxIdInput.val('');
		this.$purchaseNotesInput.val('');
		this.$couponInput.val('');
	},

	clearCheckoutFormInABit: function()
	{
		// Clear the CC info after a period of inactivity
		this.clearCheckoutFormTimeout = setTimeout(
			$.proxy(this, 'clearCheckoutForm'),
			Craft.UpgradeModal.clearCheckoutFormTimeoutDuration
		);
	}
},
{
	clearCheckoutFormTimeoutDuration: 30000 // 1000 x 60 x 5
});


text:
package org.kuali.rice.kns.service.impl;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import org.kuali.rice.core.api.config.property.ConfigurationService;
import org.kuali.rice.kim.api.KimConstants;
import org.kuali.rice.kim.api.identity.Person;
import org.kuali.rice.kim.api.permission.PermissionService;
import org.kuali.rice.kim.api.services.KimApiServiceLocator;
import org.kuali.rice.kns.datadictionary.BusinessObjectEntry;
import org.kuali.rice.kns.datadictionary.FieldDefinition;
import org.kuali.rice.kns.datadictionary.InquiryCollectionDefinition;
import org.kuali.rice.kns.datadictionary.InquirySectionDefinition;
import org.kuali.rice.kns.datadictionary.MaintainableCollectionDefinition;
import org.kuali.rice.kns.datadictionary.MaintainableItemDefinition;
import org.kuali.rice.kns.datadictionary.MaintainableSectionDefinition;
import org.kuali.rice.kns.datadictionary.MaintenanceDocumentEntry;
import org.kuali.rice.kns.document.MaintenanceDocument;
import org.kuali.rice.kns.document.authorization.BusinessObjectRestrictions;
import org.kuali.rice.kns.document.authorization.BusinessObjectRestrictionsBase;
import org.kuali.rice.kns.document.authorization.InquiryOrMaintenanceDocumentRestrictions;
import org.kuali.rice.kns.document.authorization.InquiryOrMaintenanceDocumentRestrictionsBase;
import org.kuali.rice.kns.document.authorization.MaintenanceDocumentRestrictions;
import org.kuali.rice.kns.document.authorization.MaintenanceDocumentRestrictionsBase;
import org.kuali.rice.kns.inquiry.InquiryRestrictions;
import org.kuali.rice.kns.service.BusinessObjectAuthorizationService;
import org.kuali.rice.kns.service.KNSServiceLocator;
import org.kuali.rice.kns.service.MaintenanceDocumentDictionaryService;
import org.kuali.rice.krad.authorization.BusinessObjectAuthorizer;
import org.kuali.rice.krad.bo.BusinessObject;
import org.kuali.rice.krad.bo.authorization.InquiryOrMaintenanceDocumentAuthorizer;
import org.kuali.rice.krad.bo.authorization.InquiryOrMaintenanceDocumentPresentationController;
import org.kuali.rice.krad.datadictionary.AttributeDefinition;
import org.kuali.rice.krad.datadictionary.DataObjectEntry;
import org.kuali.rice.krad.document.Document;
import org.kuali.rice.krad.document.authorization.MaintenanceDocumentAuthorizer;
import org.kuali.rice.krad.document.authorization.MaintenanceDocumentPresentationController;
import org.kuali.rice.krad.inquiry.InquiryAuthorizer;
import org.kuali.rice.krad.inquiry.InquiryPresentationController;
import org.kuali.rice.krad.service.BusinessObjectDictionaryService;
import org.kuali.rice.krad.service.DataDictionaryService;
import org.kuali.rice.krad.service.DocumentHelperService;
import org.kuali.rice.krad.service.KRADServiceLocator;
import org.kuali.rice.krad.service.KRADServiceLocatorWeb;
import org.kuali.rice.krad.service.impl.DataObjectAuthorizationServiceImpl;
import org.kuali.rice.krad.util.KRADConstants;
import org.kuali.rice.krad.util.KRADUtils;
import org.kuali.rice.krad.util.ObjectUtils;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Deprecated
public class BusinessObjectAuthorizationServiceImpl extends DataObjectAuthorizationServiceImpl implements BusinessObjectAuthorizationService {
	private DataDictionaryService dataDictionaryService;
	private PermissionService permissionService;
	private BusinessObjectDictionaryService businessObjectDictionaryService;
	private DocumentHelperService documentHelperService;
	private MaintenanceDocumentDictionaryService maintenanceDocumentDictionaryService;
	private ConfigurationService kualiConfigurationService;

	public BusinessObjectRestrictions getLookupResultRestrictions(
			Object dataObject, Person user) {
		BusinessObjectRestrictions businessObjectRestrictions = new BusinessObjectRestrictionsBase();
		considerBusinessObjectFieldUnmaskAuthorization(dataObject, user,
				businessObjectRestrictions, "", null);
		return businessObjectRestrictions;
	}

	public InquiryRestrictions getInquiryRestrictions(
			BusinessObject businessObject, Person user) {
		InquiryRestrictions inquiryRestrictions = new InquiryOrMaintenanceDocumentRestrictionsBase();
		BusinessObjectEntry businessObjectEntry = (BusinessObjectEntry) getDataDictionaryService()
				.getDataDictionary().getBusinessObjectEntry(
						businessObject.getClass().getName());
		InquiryPresentationController inquiryPresentationController = getBusinessObjectDictionaryService()
				.getInquiryPresentationController(businessObject.getClass());
		InquiryAuthorizer inquiryAuthorizer = getBusinessObjectDictionaryService()
				.getInquiryAuthorizer(businessObject.getClass());
		considerBusinessObjectFieldUnmaskAuthorization(businessObject, user,
				inquiryRestrictions, "", null);
		considerBusinessObjectFieldViewAuthorization(businessObjectEntry,
				businessObject, null, user, inquiryAuthorizer, inquiryRestrictions,
				"");
		considerInquiryOrMaintenanceDocumentPresentationController(
				inquiryPresentationController, businessObject,
				inquiryRestrictions);
		considerInquiryOrMaintenanceDocumentAuthorizer(inquiryAuthorizer,
				businessObject, user, inquiryRestrictions);
		for (InquirySectionDefinition inquirySectionDefinition : businessObjectEntry.getInquiryDefinition().getInquirySections()) {
			if (inquirySectionDefinition.getInquiryCollections() != null) {
				addInquirableItemRestrictions(inquirySectionDefinition.getInquiryCollections().values(), inquiryAuthorizer,
						inquiryRestrictions, businessObject, businessObject, "", user);
			}
			// Collections may also be stored in the inquiry fields, so we need to parse through that
			List<FieldDefinition> inquiryFields = inquirySectionDefinition.getInquiryFields();
			if (inquiryFields != null) {
				for (FieldDefinition fieldDefinition : inquiryFields) {
					addInquirableItemRestrictions(inquiryFields, inquiryAuthorizer,
							inquiryRestrictions, businessObject, businessObject, "", user);
				}
			}
		}

		return inquiryRestrictions;
	}

	public MaintenanceDocumentRestrictions getMaintenanceDocumentRestrictions(
			MaintenanceDocument maintenanceDocument, Person user) {

		MaintenanceDocumentRestrictions maintenanceDocumentRestrictions = new MaintenanceDocumentRestrictionsBase();
		DataObjectEntry dataObjectEntry = getDataDictionaryService()
				.getDataDictionary().getDataObjectEntry(
						maintenanceDocument.getNewMaintainableObject()
								.getDataObject().getClass().getName());
		MaintenanceDocumentPresentationController maintenanceDocumentPresentationController = (MaintenanceDocumentPresentationController) getDocumentHelperService()
				.getDocumentPresentationController(maintenanceDocument);
		MaintenanceDocumentAuthorizer maintenanceDocumentAuthorizer = (MaintenanceDocumentAuthorizer) getDocumentHelperService()
				.getDocumentAuthorizer(maintenanceDocument);
		considerBusinessObjectFieldUnmaskAuthorization(maintenanceDocument
				.getNewMaintainableObject().getDataObject(), user,
				maintenanceDocumentRestrictions, "", maintenanceDocument );
		considerBusinessObjectFieldViewAuthorization(dataObjectEntry,
				maintenanceDocument.getNewMaintainableObject().getDataObject(),
				null, user, maintenanceDocumentAuthorizer,
				maintenanceDocumentRestrictions, "");
		considerBusinessObjectFieldModifyAuthorization(dataObjectEntry,
				maintenanceDocument.getNewMaintainableObject().getDataObject(),
				null, user, maintenanceDocumentAuthorizer,
				maintenanceDocumentRestrictions, "");
		considerCustomButtonFieldAuthorization(dataObjectEntry,
				maintenanceDocument.getNewMaintainableObject().getDataObject(),
				null, user, maintenanceDocumentAuthorizer,
				maintenanceDocumentRestrictions, "");
		considerInquiryOrMaintenanceDocumentPresentationController(
				maintenanceDocumentPresentationController, maintenanceDocument,
				maintenanceDocumentRestrictions);
		considerInquiryOrMaintenanceDocumentAuthorizer(
				maintenanceDocumentAuthorizer, maintenanceDocument, user,
				maintenanceDocumentRestrictions);
		considerMaintenanceDocumentPresentationController(
				maintenanceDocumentPresentationController, maintenanceDocument,
				maintenanceDocumentRestrictions);
		considerMaintenanceDocumentAuthorizer(maintenanceDocumentAuthorizer,
				maintenanceDocument, user, maintenanceDocumentRestrictions);

		MaintenanceDocumentEntry maintenanceDocumentEntry = getMaintenanceDocumentDictionaryService().getMaintenanceDocumentEntry(maintenanceDocument
				.getDocumentHeader().getWorkflowDocument().getDocumentTypeName());
		for (MaintainableSectionDefinition maintainableSectionDefinition : maintenanceDocumentEntry.getMaintainableSections()) {
			addMaintainableItemRestrictions(maintainableSectionDefinition.getMaintainableItems(), maintenanceDocumentAuthorizer, maintenanceDocumentRestrictions,
					maintenanceDocument, maintenanceDocument.getNewMaintainableObject().getBusinessObject(), "", user);
		}
		return maintenanceDocumentRestrictions;
	}

	protected void considerBusinessObjectFieldUnmaskAuthorization(Object dataObject, Person user, BusinessObjectRestrictions businessObjectRestrictions, String propertyPrefix, Document document) {
		DataObjectEntry objectEntry = getDataDictionaryService().getDataDictionary().getDataObjectEntry(dataObject.getClass().getName());
		for (String attributeName : objectEntry.getAttributeNames()) {
			AttributeDefinition attributeDefinition = objectEntry.getAttributeDefinition(attributeName);
			if (attributeDefinition.getAttributeSecurity() != null) {
				if (attributeDefinition.getAttributeSecurity().isMask() &&
						!canFullyUnmaskField(user, dataObject.getClass(), attributeName, document)) {
					businessObjectRestrictions.addFullyMaskedField(propertyPrefix + attributeName, attributeDefinition.getAttributeSecurity().getMaskFormatter());
				}
				if (attributeDefinition.getAttributeSecurity().isPartialMask() &&
						!canPartiallyUnmaskField(user, dataObject.getClass(), attributeName, document)) {
					businessObjectRestrictions.addPartiallyMaskedField(propertyPrefix + attributeName, attributeDefinition.getAttributeSecurity().getPartialMaskFormatter());
				}
			}
		}
	}

	/**
	 * @param dataObjectEntry if collectionItemBusinessObject is not null, then it is the DD entry for collectionItemBusinessObject.
	 * Otherwise, it is the entry for primaryBusinessObject
	 * @param primaryDataObject the top-level BO that is being inquiried or maintained
	 * @param collectionItemBusinessObject an element of a collection under the primaryBusinessObject that we are evaluating view auths for
	 * @param user the logged in user
	 * @param businessObjectAuthorizer
	 * @param inquiryOrMaintenanceDocumentRestrictions
	 * @param propertyPrefix
	 */
	protected void considerBusinessObjectFieldViewAuthorization(
			DataObjectEntry dataObjectEntry,
			Object primaryDataObject,
			BusinessObject collectionItemBusinessObject,
			Person user,
			BusinessObjectAuthorizer businessObjectAuthorizer,
			InquiryOrMaintenanceDocumentRestrictions inquiryOrMaintenanceDocumentRestrictions,
			String propertyPrefix) {
		for (String attributeName : dataObjectEntry.getAttributeNames()) {
			AttributeDefinition attributeDefinition = dataObjectEntry
					.getAttributeDefinition(attributeName);
			if (attributeDefinition.getAttributeSecurity() != null) {
				if (attributeDefinition.getAttributeSecurity().isHide()) {
					Map<String, String> collectionItemPermissionDetails = new HashMap<String, String>();
					Map<String, String> collectionItemRoleQualifications = null;
					if (ObjectUtils.isNotNull(collectionItemBusinessObject)) {
						collectionItemPermissionDetails.putAll(getFieldPermissionDetails(collectionItemBusinessObject, attributeName));
						collectionItemPermissionDetails.putAll(businessObjectAuthorizer.
								getCollectionItemPermissionDetails(collectionItemBusinessObject));
						collectionItemRoleQualifications = new HashMap<String, String>(businessObjectAuthorizer.
								getCollectionItemRoleQualifications(collectionItemBusinessObject));
					}
					else {
						collectionItemPermissionDetails.putAll(getFieldPermissionDetails(primaryDataObject, attributeName));
					}
					if (!businessObjectAuthorizer
							.isAuthorizedByTemplate(
									primaryDataObject,
									KRADConstants.KRAD_NAMESPACE,
									KimConstants.PermissionTemplateNames.VIEW_FIELD,
									user.getPrincipalId(),
									collectionItemPermissionDetails,
									collectionItemRoleQualifications)) {
						inquiryOrMaintenanceDocumentRestrictions
								.addHiddenField(propertyPrefix + attributeName);
					}
				}
			}
		}
	}

	/**
	 * @param dataObjectEntry if collectionItemBusinessObject is not null, then it is the DD entry for collectionItemBusinessObject.
	 * Otherwise, it is the entry for primaryBusinessObject
	 * @param primaryDataObject the top-level BO that is being inquiried or maintained
	 * @param collectionItemBusinessObject an element of a collection under the primaryBusinessObject that we are evaluating view auths for
	 * @param user the logged in user
	 * @param businessObjectAuthorizer
	 * @param inquiryOrMaintenanceDocumentRestrictions
	 * @param propertyPrefix
	 */
	protected void considerBusinessObjectFieldModifyAuthorization(
			DataObjectEntry dataObjectEntry,
			Object primaryDataObject,
			BusinessObject collectionItemBusinessObject, Person user,
			BusinessObjectAuthorizer businessObjectAuthorizer,
			MaintenanceDocumentRestrictions maintenanceDocumentRestrictions,
			String propertyPrefix) {
		for (String attributeName : dataObjectEntry.getAttributeNames()) {
			AttributeDefinition attributeDefinition = dataObjectEntry
					.getAttributeDefinition(attributeName);
			if (attributeDefinition.getAttributeSecurity() != null) {
				Map<String, String> collectionItemPermissionDetails = new HashMap<String, String>();
				Map<String, String> collectionItemRoleQualifications = null;
				if (ObjectUtils.isNotNull(collectionItemBusinessObject)) {
					collectionItemPermissionDetails.putAll(getFieldPermissionDetails(collectionItemBusinessObject, attributeName));
					collectionItemPermissionDetails.putAll(businessObjectAuthorizer.
							getCollectionItemPermissionDetails(collectionItemBusinessObject));
					collectionItemRoleQualifications = new HashMap<String, String>(businessObjectAuthorizer.
							getCollectionItemRoleQualifications(collectionItemBusinessObject));
				}
				else {
					collectionItemPermissionDetails.putAll(getFieldPermissionDetails(primaryDataObject, attributeName));
				}
				if (attributeDefinition.getAttributeSecurity().isReadOnly()) {
					if (!businessObjectAuthorizer
								.isAuthorizedByTemplate(
										primaryDataObject,
										KRADConstants.KRAD_NAMESPACE,
										KimConstants.PermissionTemplateNames.MODIFY_FIELD,
										user.getPrincipalId(),
										collectionItemPermissionDetails,
										collectionItemRoleQualifications)) {
						maintenanceDocumentRestrictions
								.addReadOnlyField(propertyPrefix + attributeName);
					}
				}
			}
		}
	}

	/**
	 * @param dataObjectEntry if collectionItemBusinessObject is not null, then it is the DD entry for collectionItemBusinessObject.
	 * Otherwise, it is the entry for primaryBusinessObject
	 * @param primaryDataObject the top-level BO that is being inquiried or maintained
	 * @param collectionItemBusinessObject an element of a collection under the primaryBusinessObject that we are evaluating view auths for
	 * @param user the logged in user
	 * @param businessObjectAuthorizer
	 * @param inquiryOrMaintenanceDocumentRestrictions
	 * @param propertyPrefix
	 */
	protected void considerCustomButtonFieldAuthorization(
			DataObjectEntry dataObjectEntry,
			Object primaryDataObject,
			BusinessObject collectionItemBusinessObject,
			Person user,
			BusinessObjectAuthorizer businessObjectAuthorizer,
			MaintenanceDocumentRestrictions maintenanceDocumentRestrictions,
			String propertyPrefix) {
		for (String attributeName : dataObjectEntry.getAttributeNames()) {
			AttributeDefinition attributeDefinition = dataObjectEntry
					.getAttributeDefinition(attributeName);
			// TODO what is the equivalent of control.isButton in KRAD
			if (attributeDefinition.getControl() != null &&
			        attributeDefinition.getControl().isButton()) {
				Map<String, String> collectionItemPermissionDetails = new HashMap<String, String>();
				Map<String, String> collectionItemRoleQualifications = null;
				if (ObjectUtils.isNotNull(collectionItemBusinessObject)) {
					collectionItemPermissionDetails.putAll(getButtonFieldPermissionDetails(collectionItemBusinessObject, attributeName));
					collectionItemPermissionDetails.putAll(businessObjectAuthorizer.
							getCollectionItemPermissionDetails(collectionItemBusinessObject));
					collectionItemRoleQualifications = new HashMap<String, String>(businessObjectAuthorizer.
							getCollectionItemRoleQualifications(collectionItemBusinessObject));
				}
				else {
					getButtonFieldPermissionDetails(primaryDataObject, attributeName);
				}

				if (!businessObjectAuthorizer
						.isAuthorizedByTemplate(
								primaryDataObject,
								KRADConstants.KRAD_NAMESPACE,
								KimConstants.PermissionTemplateNames.PERFORM_CUSTOM_MAINTENANCE_DOCUMENT_FUNCTION,
								user.getPrincipalId(),
								collectionItemPermissionDetails,
								collectionItemRoleQualifications)) {
					maintenanceDocumentRestrictions
							.addHiddenField(propertyPrefix + attributeName);
				}
			}
		}
	}

	protected void considerInquiryOrMaintenanceDocumentPresentationController(
			InquiryOrMaintenanceDocumentPresentationController businessObjectPresentationController,
			BusinessObject businessObject,
			InquiryOrMaintenanceDocumentRestrictions inquiryOrMaintenanceDocumentRestrictions) {
		for (String attributeName : businessObjectPresentationController
				.getConditionallyHiddenPropertyNames(businessObject)) {
			inquiryOrMaintenanceDocumentRestrictions
					.addHiddenField(attributeName);
		}
		for (String sectionId : businessObjectPresentationController
				.getConditionallyHiddenSectionIds(businessObject)) {
			inquiryOrMaintenanceDocumentRestrictions
					.addHiddenSectionId(sectionId);
		}
	}

	protected void considerInquiryOrMaintenanceDocumentAuthorizer(
			InquiryOrMaintenanceDocumentAuthorizer authorizer,
			BusinessObject businessObject, Person user,
			InquiryOrMaintenanceDocumentRestrictions restrictions) {
		for (String sectionId : authorizer
				.getSecurePotentiallyHiddenSectionIds()) {
			Map<String, String> additionalPermissionDetails = new HashMap<String, String>();
			additionalPermissionDetails
					.put(KimConstants.AttributeConstants.SECTION_ID, sectionId);
			if (!authorizer.isAuthorizedByTemplate(businessObject,
					KRADConstants.KRAD_NAMESPACE,
					KimConstants.PermissionTemplateNames.VIEW_SECTION, user
							.getPrincipalId(), additionalPermissionDetails,
					null)) {
				restrictions.addHiddenSectionId(sectionId);
			}
		}
	}

	protected void considerMaintenanceDocumentPresentationController(
			MaintenanceDocumentPresentationController presentationController,
			MaintenanceDocument document,
			MaintenanceDocumentRestrictions restrictions) {
		for (String attributeName : presentationController
				.getConditionallyReadOnlyPropertyNames(document)) {
			restrictions.addReadOnlyField(attributeName);
		}
		for (String sectionId : presentationController
				.getConditionallyReadOnlySectionIds(document)) {
			restrictions.addReadOnlySectionId(sectionId);
		}
	}

	protected void considerMaintenanceDocumentAuthorizer(
			MaintenanceDocumentAuthorizer authorizer,
			MaintenanceDocument document, Person user,
			MaintenanceDocumentRestrictions restrictions) {
		for (String sectionId : authorizer
				.getSecurePotentiallyReadOnlySectionIds()) {
			Map<String, String> additionalPermissionDetails = new HashMap<String, String>();
			additionalPermissionDetails
					.put(KimConstants.AttributeConstants.SECTION_ID, sectionId);
			if (!authorizer.isAuthorizedByTemplate(document,
					KRADConstants.KRAD_NAMESPACE,
					KimConstants.PermissionTemplateNames.MODIFY_SECTION, user
							.getPrincipalId(), additionalPermissionDetails,
					null)) {
				restrictions.addReadOnlySectionId(sectionId);
			}
		}
	}

	@SuppressWarnings("unchecked")
	protected void addInquirableItemRestrictions(Collection sectionDefinitions,
			InquiryAuthorizer authorizer, InquiryRestrictions restrictions,
			BusinessObject primaryBusinessObject,
			BusinessObject businessObject, String propertyPrefix, Person user) {
		for (Object inquirableItemDefinition : sectionDefinitions) {
			if (inquirableItemDefinition instanceof InquiryCollectionDefinition) {
				InquiryCollectionDefinition inquiryCollectionDefinition = (InquiryCollectionDefinition) inquirableItemDefinition;
				BusinessObjectEntry collectionBusinessObjectEntry = (BusinessObjectEntry) getDataDictionaryService()
						.getDataDictionary().getBusinessObjectEntry(
								inquiryCollectionDefinition.getBusinessObjectClass().getName());

				try {
					Collection<BusinessObject> collection = (Collection<BusinessObject>) PropertyUtils
							.getProperty(businessObject,
									inquiryCollectionDefinition.getName());
					int i = 0;
					for (Iterator<BusinessObject> iterator = collection.iterator(); iterator
							.hasNext();) {
						String newPropertyPrefix = propertyPrefix + inquiryCollectionDefinition.getName() + "[" + i + "].";
						BusinessObject collectionItemBusinessObject = iterator.next();
						considerBusinessObjectFieldUnmaskAuthorization(
								collectionItemBusinessObject, user, restrictions,
								newPropertyPrefix, null);
						considerBusinessObjectFieldViewAuthorization(
								collectionBusinessObjectEntry, primaryBusinessObject, collectionItemBusinessObject,
								user, authorizer, restrictions, newPropertyPrefix);
						addInquirableItemRestrictions(
								inquiryCollectionDefinition
										.getInquiryCollections(),
								authorizer,
								restrictions,
								primaryBusinessObject,
								collectionItemBusinessObject,
								newPropertyPrefix,
								user);
						i++;
					}
				} catch (Exception e) {
					throw new RuntimeException(
							"Unable to resolve collection property: "
									+ businessObject.getClass() + ":"
									+ inquiryCollectionDefinition.getName(), e);
				}
			}
		}
	}

	@SuppressWarnings("unchecked")
	protected void addMaintainableItemRestrictions(List<? extends MaintainableItemDefinition> itemDefinitions,
			MaintenanceDocumentAuthorizer authorizer,
			MaintenanceDocumentRestrictions restrictions,
			MaintenanceDocument maintenanceDocument,
			BusinessObject businessObject, String propertyPrefix, Person user) {
		for (MaintainableItemDefinition maintainableItemDefinition : itemDefinitions) {
			if (maintainableItemDefinition instanceof MaintainableCollectionDefinition) {
				try {
					MaintainableCollectionDefinition maintainableCollectionDefinition = (MaintainableCollectionDefinition) maintainableItemDefinition;

					Collection<BusinessObject> collection = (Collection<BusinessObject>) ObjectUtils
							.getNestedValue(businessObject,
									maintainableItemDefinition.getName());
					BusinessObjectEntry collectionBusinessObjectEntry = (BusinessObjectEntry) getDataDictionaryService()
							.getDataDictionary().getBusinessObjectEntry(
									maintainableCollectionDefinition.getBusinessObjectClass().getName());
					if (collection != null && !collection.isEmpty()) {
				    	int i = 0;
			     		for (Iterator<BusinessObject> iterator = collection.iterator(); iterator
							.hasNext();) {
			     			String newPropertyPrefix = propertyPrefix + maintainableItemDefinition.getName() + "[" + i + "].";
					    	BusinessObject collectionBusinessObject = iterator.next();
					    	considerBusinessObjectFieldUnmaskAuthorization(
								collectionBusinessObject, user, restrictions,
								newPropertyPrefix, maintenanceDocument);
					    	considerBusinessObjectFieldViewAuthorization(
								collectionBusinessObjectEntry, maintenanceDocument, collectionBusinessObject, user,
								authorizer, restrictions, newPropertyPrefix);
					    	considerBusinessObjectFieldModifyAuthorization(
								collectionBusinessObjectEntry, maintenanceDocument, collectionBusinessObject, user,
								authorizer, restrictions, newPropertyPrefix);
					    	addMaintainableItemRestrictions(
								((MaintainableCollectionDefinition) maintainableItemDefinition)
										.getMaintainableCollections(),
								authorizer, restrictions, maintenanceDocument,
								collectionBusinessObject, newPropertyPrefix,
								user);
				     		addMaintainableItemRestrictions(
								((MaintainableCollectionDefinition) maintainableItemDefinition)
										.getMaintainableFields(), authorizer,
								restrictions, maintenanceDocument,
								collectionBusinessObject, newPropertyPrefix,
								user);
					    	i++;
				    	}
					}
				} catch (Exception e) {
					throw new RuntimeException(
							"Unable to resolve collection property: "
									+ businessObject.getClass() + ":"
									+ maintainableItemDefinition.getName(), e);
				}
			}
		}
	}

	public boolean canFullyUnmaskField(Person user,
			Class<?> dataObjectClass, String fieldName, Document document) {
		// KFSMI-5095
		if(isNonProductionEnvAndUnmaskingTurnedOff())
			return false;

		if(user==null || StringUtils.isEmpty(user.getPrincipalId()))
			return false;
		Boolean result = null;
		if (document != null) { // if a document was passed, evaluate the permission in the context of a document
			try { // try/catch and fallthrough is a fix for KULRICE-3365
				result = getDocumentHelperService().getDocumentAuthorizer( document )
				.isAuthorizedByTemplate( document,
						KRADConstants.KRAD_NAMESPACE,
						KimConstants.PermissionTemplateNames.FULL_UNMASK_FIELD,
						user.getPrincipalId(), getFieldPermissionDetails(dataObjectClass, fieldName), null  );
			} catch (IllegalArgumentException e) {
				// document didn't have needed metadata
				// TODO: this requires intimate knowledge of DocumentHelperServiceImpl
			}
		}
		if (result == null) {
			result = getPermissionService().isAuthorizedByTemplateName(
					user.getPrincipalId(),
					KRADConstants.KRAD_NAMESPACE,
					KimConstants.PermissionTemplateNames.FULL_UNMASK_FIELD,
					new HashMap<String, String>(getFieldPermissionDetails(dataObjectClass, fieldName)),
					Collections.<String, String>emptyMap());
		}
		return result; // should be safe to return Boolean here since the only circumstances that
		               // will leave it null will result in an exception being thrown above.
	}

	public boolean canPartiallyUnmaskField(
			Person user, Class<?> dataObjectClass, String fieldName, Document document) {
		// KFSMI-5095
		if(isNonProductionEnvAndUnmaskingTurnedOff())
			return false;

		if(user==null || StringUtils.isEmpty(user.getPrincipalId()))
			return false;

		if ( document == null ) {
			return getPermissionService().isAuthorizedByTemplateName(
					user.getPrincipalId(),
					KRADConstants.KRAD_NAMESPACE,
					KimConstants.PermissionTemplateNames.PARTIAL_UNMASK_FIELD,
					new HashMap<String, String>(getFieldPermissionDetails(dataObjectClass,fieldName)),
					Collections.<String, String>emptyMap());
		} else { // if a document was passed, evaluate the permission in the context of a document
			return getDocumentHelperService().getDocumentAuthorizer( document )
					.isAuthorizedByTemplate( document,
											 KRADConstants.KRAD_NAMESPACE,
											 KimConstants.PermissionTemplateNames.PARTIAL_UNMASK_FIELD,
											 user.getPrincipalId(), getFieldPermissionDetails(dataObjectClass, fieldName), Collections.<String, String>emptyMap()  );
		}
	}

	protected Map<String, String> getFieldPermissionDetails(
			Class<?> dataObjectClass, String attributeName) {
		try {
			return getFieldPermissionDetails(dataObjectClass.newInstance(),
					attributeName);
		} catch (Exception e) {
			throw new RuntimeException(
					"The getPermissionDetails method of BusinessObjectAuthorizationServiceImpl was unable to instantiate the dataObjectClass"
							+ dataObjectClass, e);
		}
	}

	protected Map<String, String> getFieldPermissionDetails(
			Object dataObject, String attributeName) {
		Map<String, String> permissionDetails = null;
		String namespaceCode = null;
		String componentName = null;
		String propertyName = null;
		// JHK: commenting out for KFSMI-2398 - permission checks need to be done at the level specified
		// that is, if the parent object specifies the security, that object should be used for the
		// component
//		if (attributeName.contains(".")) {
//			try {
//				permissionDetails = KimCommonUtils
//						.getNamespaceAndComponentSimpleName(PropertyUtils
//								.getPropertyType(businessObject, attributeName
//										.substring(0, attributeName
//												.lastIndexOf("."))));
//			} catch (Exception e) {
//				throw new RuntimeException(
//						"Unable to discover nested business object class: "
//								+ businessObject.getClass() + " : "
//								+ attributeName, e);
//			}
//			permissionDetails.put(KimAttributes.PROPERTY_NAME, attributeName
//					.substring(attributeName.indexOf(".") + 1));
//		} else {
			permissionDetails = KRADUtils
					.getNamespaceAndComponentSimpleName(dataObject.getClass());
			permissionDetails.put(KimConstants.AttributeConstants.PROPERTY_NAME, attributeName);
//		}
		return permissionDetails;
	}

	protected Map<String, String> getButtonFieldPermissionDetails(
			Object businessObject, String attributeName) {
		Map<String, String> permissionDetails = new HashMap<String, String>();
		if (attributeName.contains(".")) {
			permissionDetails.put(KimConstants.AttributeConstants.BUTTON_NAME, attributeName);
		} else {
			permissionDetails.put(KimConstants.AttributeConstants.BUTTON_NAME, attributeName);
		}
		return permissionDetails;
	}

	private PermissionService getPermissionService() {
		if (permissionService == null) {
			permissionService = KimApiServiceLocator
					.getPermissionService();
		}
		return permissionService;
	}

	private BusinessObjectDictionaryService getBusinessObjectDictionaryService() {
		if (businessObjectDictionaryService == null) {
			businessObjectDictionaryService = KRADServiceLocatorWeb
					.getBusinessObjectDictionaryService();
		}
		return businessObjectDictionaryService;
	}

	private MaintenanceDocumentDictionaryService getMaintenanceDocumentDictionaryService() {
		if (maintenanceDocumentDictionaryService == null) {
			maintenanceDocumentDictionaryService = KNSServiceLocator
					.getMaintenanceDocumentDictionaryService();
		}
		return maintenanceDocumentDictionaryService;
	}

	private ConfigurationService getKualiConfigurationService() {
		if (kualiConfigurationService == null) {
			kualiConfigurationService = KRADServiceLocator.getKualiConfigurationService();
		}
		return kualiConfigurationService;
	}

	private boolean isNonProductionEnvAndUnmaskingTurnedOff(){
		return !getKualiConfigurationService().getPropertyValueAsString(KRADConstants.PROD_ENVIRONMENT_CODE_KEY)
                .equalsIgnoreCase(
                        getKualiConfigurationService().getPropertyValueAsString(KRADConstants.ENVIRONMENT_KEY)) &&
				!getKualiConfigurationService().getPropertyValueAsBoolean(KRADConstants.ENABLE_NONPRODUCTION_UNMASKING);
	}

}