text:
package com.esri.core.geometry;

import java.util.ArrayList;

final class IntervalTreeImpl {
	static final class IntervalTreeIteratorImpl {
		/**
		 * Resets the iterator to a starting state on the Interval_tree_impl
		 * using the input Envelope_1D interval as the query \param query The
		 * Envelope_1D interval used for the query. \param tolerance The
		 * tolerance used for the intersection tests.
		 */
		void resetIterator(Envelope1D query, double tolerance) {
			m_query.vmin = query.vmin - tolerance;
			m_query.vmax = query.vmax + tolerance;
			m_tertiary_stack.resize(0);
			m_function_index = 0;
			m_function_stack[0] = State.initialize;
		}

		/**
		 * Resets the iterator to a starting state on the Interval_tree_impl
		 * using the input Envelope_1D interval as the query \param query The
		 * Envelope_1D interval used for the query. \param tolerance The
		 * tolerance used for the intersection tests.
		 */
		void resetIterator(double query_min, double query_max, double tolerance) {
			if (query_min > query_max)
				throw new IllegalArgumentException();

			m_query.vmin = query_min - tolerance;
			m_query.vmax = query_max + tolerance;
			m_tertiary_stack.resize(0);
			m_function_index = 0;
			m_function_stack[0] = State.initialize;
		}

		/**
		 * Resets the iterator to a starting state on the Interval_tree_impl
		 * using the input double as the stabbing query \param query The double
		 * used for the query. \param tolerance The tolerance used for the
		 * intersection tests.
		 */
		void resetIterator(double query, double tolerance) {
			m_query.vmin = query - tolerance;
			m_query.vmax = query + tolerance;
			m_tertiary_stack.resize(0);
			m_function_index = 0;
			m_function_stack[0] = State.initialize;
		}

		/**
		 * Iterates over all intervals which interset the query interval.
		 * Returns an index to an interval that intersects the query.
		 */
		int next() {
			if (!m_interval_tree.m_b_construction_ended)
				throw new GeometryException("invalid call");

			if (m_function_index < 0)
				return -1;

			boolean b_searching = true;

			while (b_searching) {
				switch (m_function_stack[m_function_index]) {
				case State.pIn:
					b_searching = pIn_();
					break;
				case State.pL:
					b_searching = pL_();
					break;
				case State.pR:
					b_searching = pR_();
					break;
				case State.pT:
					b_searching = pT_();
					break;
				case State.right:
					b_searching = right_();
					break;
				case State.left:
					b_searching = left_();
					break;
				case State.all:
					b_searching = all_();
					break;
				case State.initialize:
					b_searching = initialize_();
					break;
				default:
					throw new GeometryException("internal error");
				}
			}

			if (m_current_end_handle != -1)
				return getCurrentEndIndex_() >> 1;

			return -1;
		}

		// Creates an iterator on the input Interval_tree using the input
		// Envelope_1D interval as the query.
		IntervalTreeIteratorImpl(IntervalTreeImpl interval_tree,
				Envelope1D query, double tolerance) {
			m_interval_tree = interval_tree;
			m_tertiary_stack.reserve(20);
			resetIterator(query, tolerance);
		}

		// Creates an iterator on the input Interval_tree using the input double
		// as the stabbing query.
		IntervalTreeIteratorImpl(IntervalTreeImpl interval_tree, double query,
				double tolerance) {
			m_interval_tree = interval_tree;
			m_tertiary_stack.reserve(20);
			resetIterator(query, tolerance);
		}

		// Creates an iterator on the input Interval_tree.
		IntervalTreeIteratorImpl(IntervalTreeImpl interval_tree) {
			m_interval_tree = interval_tree;
			m_tertiary_stack.reserve(20);
			m_function_index = -1;
		}

		private IntervalTreeImpl m_interval_tree;
		private Envelope1D m_query = new Envelope1D();
		private int m_primary_handle;
		private int m_next_primary_handle;
		private int m_forked_handle;
		private int m_current_end_handle;
		private int m_next_end_handle;
		private AttributeStreamOfInt32 m_tertiary_stack = new AttributeStreamOfInt32(
				0);
		private int m_function_index;
		private int[] m_function_stack = new int[2];

		private interface State {
			static final int initialize = 0;
			static final int pIn = 1;
			static final int pL = 2;
			static final int pR = 3;
			static final int pT = 4;
			static final int right = 5;
			static final int left = 6;
			static final int all = 7;
		}

		private boolean initialize_() {
			m_primary_handle = -1;
			m_next_primary_handle = -1;
			m_forked_handle = -1;
			m_current_end_handle = -1;

			if (m_interval_tree.m_primary_nodes != null
					&& m_interval_tree.m_primary_nodes.size() > 0) {
				m_function_stack[0] = State.pIn; // overwrite initialize
				m_next_primary_handle = m_interval_tree.m_root;
				return true;
			}

			m_function_index = -1;
			return false;
		}

		private boolean pIn_() {
			m_primary_handle = m_next_primary_handle;

			if (m_primary_handle == -1) {
				m_function_index = -1;
				m_current_end_handle = -1;
				return false;
			}

			double discriminant = m_interval_tree
					.getDiscriminant_(m_primary_handle);

			if (m_query.vmax < discriminant) {
				int secondary_handle = m_interval_tree
						.getSecondaryFromPrimary(m_primary_handle);
				m_next_primary_handle = m_interval_tree
						.getLPTR_(m_primary_handle);

				if (secondary_handle != -1) {
					m_next_end_handle = m_interval_tree
							.getFirst_(secondary_handle);
					m_function_stack[++m_function_index] = State.left;
				}

				return true;
			}

			if (discriminant < m_query.vmin) {
				int secondary_handle = m_interval_tree
						.getSecondaryFromPrimary(m_primary_handle);
				m_next_primary_handle = m_interval_tree
						.getRPTR_(m_primary_handle);

				if (secondary_handle != -1) {
					m_next_end_handle = m_interval_tree
							.getLast_(secondary_handle);
					m_function_stack[++m_function_index] = State.right;
				}

				return true;
			}

			assert (m_query.contains(discriminant));

			m_function_stack[m_function_index] = State.pL; // overwrite pIn
			m_forked_handle = m_primary_handle;
			int secondary_handle = m_interval_tree
					.getSecondaryFromPrimary(m_primary_handle);
			m_next_primary_handle = m_interval_tree.getLPTR_(m_primary_handle);

			if (secondary_handle != -1) {
				m_next_end_handle = m_interval_tree.getFirst_(secondary_handle);
				m_function_stack[++m_function_index] = State.all;
			}

			return true;
		}

		private boolean pL_() {
			m_primary_handle = m_next_primary_handle;

			if (m_primary_handle == -1) {
				m_function_stack[m_function_index] = State.pR; // overwrite pL
				m_next_primary_handle = m_interval_tree
						.getRPTR_(m_forked_handle);
				return true;
			}

			double discriminant = m_interval_tree
					.getDiscriminant_(m_primary_handle);

			if (discriminant < m_query.vmin) {
				int secondary_handle = m_interval_tree
						.getSecondaryFromPrimary(m_primary_handle);
				m_next_primary_handle = m_interval_tree
						.getRPTR_(m_primary_handle);

				if (secondary_handle != -1) {
					m_next_end_handle = m_interval_tree
							.getLast_(secondary_handle);
					m_function_stack[++m_function_index] = State.right;
				}

				return true;
			}

			assert (m_query.contains(discriminant));

			int secondary_handle = m_interval_tree
					.getSecondaryFromPrimary(m_primary_handle);
			m_next_primary_handle = m_interval_tree.getLPTR_(m_primary_handle);

			if (secondary_handle != -1) {
				m_next_end_handle = m_interval_tree.getFirst_(secondary_handle);
				m_function_stack[++m_function_index] = State.all;
			}

			int rptr = m_interval_tree.getRPTR_(m_primary_handle);

			if (rptr != -1) {
				m_tertiary_stack.add(rptr); // we'll search this in the pT state
			}

			return true;
		}

		private boolean pR_() {
			m_primary_handle = m_next_primary_handle;

			if (m_primary_handle == -1) {
				m_function_stack[m_function_index] = State.pT; // overwrite pR
				return true;
			}

			double discriminant = m_interval_tree
					.getDiscriminant_(m_primary_handle);

			if (m_query.vmax < discriminant) {
				int secondary_handle = m_interval_tree
						.getSecondaryFromPrimary(m_primary_handle);
				m_next_primary_handle = m_interval_tree
						.getLPTR_(m_primary_handle);

				if (secondary_handle != -1) {
					m_next_end_handle = m_interval_tree
							.getFirst_(secondary_handle);
					m_function_stack[++m_function_index] = State.left;
				}

				return true;
			}

			assert (m_query.contains(discriminant));

			int secondary_handle = m_interval_tree
					.getSecondaryFromPrimary(m_primary_handle);

			m_next_primary_handle = m_interval_tree.getRPTR_(m_primary_handle);

			if (secondary_handle != -1) {
				m_next_end_handle = m_interval_tree.getFirst_(secondary_handle);
				m_function_stack[++m_function_index] = State.all;
			}

			int lptr = m_interval_tree.getLPTR_(m_primary_handle);

			if (lptr != -1) {
				m_tertiary_stack.add(lptr); // we'll search this in the pT state
			}

			return true;
		}

		private boolean pT_() {
			if (m_tertiary_stack.size() == 0) {
				m_function_index = -1;
				m_current_end_handle = -1;
				return false;
			}

			m_primary_handle = m_tertiary_stack
					.get(m_tertiary_stack.size() - 1);
			m_tertiary_stack.resize(m_tertiary_stack.size() - 1);

			int secondary_handle = m_interval_tree
					.getSecondaryFromPrimary(m_primary_handle);

			if (secondary_handle != -1) {
				m_next_end_handle = m_interval_tree.getFirst_(secondary_handle);
				m_function_stack[++m_function_index] = State.all;
			}

			if (m_interval_tree.getLPTR_(m_primary_handle) != -1)
				m_tertiary_stack
						.add(m_interval_tree.getLPTR_(m_primary_handle));

			if (m_interval_tree.getRPTR_(m_primary_handle) != -1)
				m_tertiary_stack
						.add(m_interval_tree.getRPTR_(m_primary_handle));

			return true;
		}

		private boolean left_() {
			m_current_end_handle = m_next_end_handle;

			if (m_current_end_handle != -1
					&& IntervalTreeImpl.isLeft_(getCurrentEndIndex_())
					&& m_interval_tree.getValue_(getCurrentEndIndex_()) <= m_query.vmax) {
				m_next_end_handle = getNext_();
				return false;
			}

			m_function_index--;
			return true;
		}

		private boolean right_() {
			m_current_end_handle = m_next_end_handle;

			if (m_current_end_handle != -1
					&& IntervalTreeImpl.isRight_(getCurrentEndIndex_())
					&& m_interval_tree.getValue_(getCurrentEndIndex_()) >= m_query.vmin) {
				m_next_end_handle = getPrev_();
				return false;
			}

			m_function_index--;
			return true;
		}

		private boolean all_() {
			m_current_end_handle = m_next_end_handle;

			if (m_current_end_handle != -1
					&& IntervalTreeImpl.isLeft_(getCurrentEndIndex_())) {
				m_next_end_handle = getNext_();
				return false;
			}

			m_function_index--;
			return true;
		}

		private int getNext_() {
			if (!m_interval_tree.m_b_offline_dynamic)
				return m_interval_tree.m_secondary_lists
						.getNext(m_current_end_handle);

			return m_interval_tree.m_secondary_treaps
					.getNext(m_current_end_handle);
		}

		private int getPrev_() {
			if (!m_interval_tree.m_b_offline_dynamic)
				return m_interval_tree.m_secondary_lists
						.getPrev(m_current_end_handle);

			return m_interval_tree.m_secondary_treaps
					.getPrev(m_current_end_handle);
		}

		private int getCurrentEndIndex_() {
			if (!m_interval_tree.m_b_offline_dynamic)
				return m_interval_tree.m_secondary_lists
						.getData(m_current_end_handle);

			return m_interval_tree.m_secondary_treaps
					.getElement(m_current_end_handle);
		}
	}

	IntervalTreeImpl(boolean b_offline_dynamic) {
		m_b_offline_dynamic = b_offline_dynamic;
		m_b_constructing = false;
		m_b_construction_ended = false;
	}

	void startConstruction() {
		reset_(true);
	}

	void addInterval(Envelope1D interval) {
		if (!m_b_constructing)
			throw new GeometryException("invalid call");

		m_intervals.add(interval);
	}

	void addInterval(double min, double max) {
		if (!m_b_constructing)
			throw new GeometryException("invald call");

		m_intervals.add(new Envelope1D(min, max));
	}

	void endConstruction() {
		if (!m_b_constructing)
			throw new GeometryException("invalid call");

		m_b_constructing = false;
		m_b_construction_ended = true;

		if (!m_b_offline_dynamic) {
			insertIntervalsStatic_();
			m_c_count = m_intervals.size();
		}
	}

	/**
	 * Inserts the interval from the given index into the Interval_tree_impl.
	 * This operation can only be performed in the offline dynamic case. \param
	 * index The index containing the interval to be inserted.
	 */
	void insert(int index) {
		if (!m_b_offline_dynamic || !m_b_construction_ended)
			throw new IllegalArgumentException("invalid call");

		if (m_root == -1) {

			int size = m_intervals.size();

			if (m_b_sort_intervals) {
				// sort
				AttributeStreamOfInt32 end_point_indices_sorted = new AttributeStreamOfInt32(
						0);
				end_point_indices_sorted.reserve(2 * size);
				querySortedEndPointIndices_(end_point_indices_sorted);

				// remove duplicates
				m_end_indices_unique.reserve(2 * size);
				m_end_indices_unique.resize(0);
				querySortedDuplicatesRemoved_(end_point_indices_sorted);
				m_interval_handles.resize(size, -1);
				m_interval_handles.setRange(-1, 0, size);
				m_b_sort_intervals = false;
			} else {
				m_interval_handles.setRange(-1, 0, size);
			}

			m_root = createPrimaryNode_();
		}

		int interval_handle = insertIntervalEnd_(index << 1, m_root);
		int secondary_handle = getSecondaryFromInterval_(interval_handle);
		int right_end_handle = m_secondary_treaps.addElement((index << 1) + 1,
				secondary_handle);
		setRightEnd_(interval_handle, right_end_handle);
		m_interval_handles.set(index, interval_handle);
		m_c_count++;
		// assert(check_validation_());
	}

	/**
	 * Deletes the interval from the Interval_tree_impl. \param index The index
	 * containing the interval to be deleted from the Interval_tree_impl.
	 */
	void remove(int index) {
		if (!m_b_offline_dynamic || !m_b_construction_ended)
			throw new GeometryException("invalid call");

		int interval_handle = m_interval_handles.get(index);

		if (interval_handle == -1)
			throw new IllegalArgumentException(
					"the interval does not exist in the interval tree");

		m_interval_handles.set(index, -1);

		assert (getSecondaryFromInterval_(interval_handle) != -1);
		assert (getLeftEnd_(interval_handle) != -1);
		assert (getRightEnd_(interval_handle) != -1);

		m_c_count--;

		int size;
		int secondary_handle = getSecondaryFromInterval_(interval_handle);
		int primary_handle;

		primary_handle = m_secondary_treaps.getTreapData(secondary_handle);
		m_secondary_treaps.deleteNode(getLeftEnd_(interval_handle),
				secondary_handle);
		m_secondary_treaps.deleteNode(getRightEnd_(interval_handle),
				secondary_handle);
		size = m_secondary_treaps.size(secondary_handle);

		if (size == 0) {
			m_secondary_treaps.deleteTreap(secondary_handle);
			setSecondaryToPrimary_(primary_handle, -1);
		}

		m_interval_nodes.deleteElement(interval_handle);
		int tertiary_handle = getPPTR_(primary_handle);
		int lptr = getLPTR_(primary_handle);
		int rptr = getRPTR_(primary_handle);

		int iterations = 0;
		while (!(size > 0 || primary_handle == m_root || (lptr != -1 && rptr != -1))) {
			assert (size == 0);
			assert (lptr == -1 || rptr == -1);
			assert (primary_handle != 0);

			if (primary_handle == getLPTR_(tertiary_handle)) {
				if (lptr != -1) {
					setLPTR_(tertiary_handle, lptr);
					setPPTR_(lptr, tertiary_handle);
					setLPTR_(primary_handle, -1);
					setPPTR_(primary_handle, -1);
				} else if (rptr != -1) {
					setLPTR_(tertiary_handle, rptr);
					setPPTR_(rptr, tertiary_handle);
					setRPTR_(primary_handle, -1);
					setPPTR_(primary_handle, -1);
				} else {
					setLPTR_(tertiary_handle, -1);
					setPPTR_(primary_handle, -1);
				}
			} else {
				if (lptr != -1) {
					setRPTR_(tertiary_handle, lptr);
					setPPTR_(lptr, tertiary_handle);
					setLPTR_(primary_handle, -1);
					setPPTR_(primary_handle, -1);
				} else if (rptr != -1) {
					setRPTR_(tertiary_handle, rptr);
					setPPTR_(rptr, tertiary_handle);
					setRPTR_(primary_handle, -1);
					setPPTR_(primary_handle, -1);
				} else {
					setRPTR_(tertiary_handle, -1);
					setPPTR_(primary_handle, -1);
				}
			}

			iterations++;
			primary_handle = tertiary_handle;
			secondary_handle = getSecondaryFromPrimary(primary_handle);
			size = (secondary_handle != -1 ? m_secondary_treaps
					.size(secondary_handle) : 0);
			lptr = getLPTR_(primary_handle);
			rptr = getRPTR_(primary_handle);
			tertiary_handle = getPPTR_(primary_handle);
		}

		assert (iterations <= 2);
		// assert(check_validation_());
	}

	/*
	 * Resets the Interval_tree_impl to an empty state, but maintains a handle
	 * on the current intervals.
	 */
	void reset() {
		if (!m_b_offline_dynamic || !m_b_construction_ended)
			throw new IllegalArgumentException("invalid call");

		reset_(false);
	}

	/**
	 * Returns the number of intervals stored in the Interval_tree_impl
	 */
	int size() {
		return m_c_count;
	}

	/**
	 * Gets an iterator on the Interval_tree_impl using the input Envelope_1D
	 * interval as the query. To reuse the existing iterator on the same
	 * Interval_tree_impl but with a new query, use the reset_iterator function
	 * on the Interval_tree_iterator_impl. \param query The Envelope_1D interval
	 * used for the query. \param tolerance The tolerance used for the
	 * intersection tests.
	 */
	IntervalTreeIteratorImpl getIterator(Envelope1D query, double tolerance) {
		return new IntervalTreeImpl.IntervalTreeIteratorImpl(this, query,
				tolerance);
	}

	/**
	 * Gets an iterator on the Interval_tree_impl using the input double as the
	 * stabbing query. To reuse the existing iterator on the same
	 * Interval_tree_impl but with a new query, use the reset_iterator function
	 * on the Interval_tree_iterator_impl. \param query The double used for the
	 * stabbing query. \param tolerance The tolerance used for the intersection
	 * tests.
	 */
	IntervalTreeIteratorImpl getIterator(double query, double tolerance) {
		return new IntervalTreeImpl.IntervalTreeIteratorImpl(this, query,
				tolerance);
	}

	/**
	 * Gets an iterator on the Interval_tree_impl.
	 */
	IntervalTreeIteratorImpl getIterator() {
		return new IntervalTreeImpl.IntervalTreeIteratorImpl(this);
	}

	private static final class SecondaryComparator extends Treap.Comparator {
		SecondaryComparator(IntervalTreeImpl interval_tree) {
			m_interval_tree = interval_tree;
		}

		@Override
		public int compare(Treap treap, int e_1, int node) {
			int e_2 = treap.getElement(node);
			double v_1 = m_interval_tree.getValue_(e_1);
			double v_2 = m_interval_tree.getValue_(e_2);

			if (v_1 < v_2)
				return -1;
			if (v_1 == v_2) {
				if (isLeft_(e_1) && isRight_(e_2))
					return -1;
				if (isLeft_(e_2) && isRight_(e_1))
					return 1;
				return 0;
			}
			return 1;
		}

		private IntervalTreeImpl m_interval_tree;
	};

	private boolean m_b_offline_dynamic;
	private ArrayList<Envelope1D> m_intervals;
	private StridedIndexTypeCollection m_primary_nodes; // 8 elements for
														// offline dynamic case,
														// 7 elements for static
														// case
	private StridedIndexTypeCollection m_interval_nodes; // 3 elements
	private AttributeStreamOfInt32 m_interval_handles; // for offline dynamic
														// case
	private IndexMultiDCList m_secondary_lists; // for static case
	private Treap m_secondary_treaps; // for off-line dynamic case
	private AttributeStreamOfInt32 m_end_indices_unique; // for both offline
															// dynamic and
															// static cases
	private int m_c_count;
	private int m_root;
	private boolean m_b_sort_intervals;
	private boolean m_b_constructing;
	private boolean m_b_construction_ended;

	private void querySortedEndPointIndices_(AttributeStreamOfInt32 end_indices) {
		int size = m_intervals.size();

		for (int i = 0; i < 2 * size; i++)
			end_indices.add(i);

		sortEndIndices_(end_indices, 0, 2 * size);
	}

	private void querySortedDuplicatesRemoved_(
			AttributeStreamOfInt32 end_indices_sorted) {
		// remove duplicates

		double prev = NumberUtils.TheNaN;
		for (int i = 0; i < end_indices_sorted.size(); i++) {
			int e = end_indices_sorted.get(i);
			double v = getValue_(e);

			if (v != prev) {
				m_end_indices_unique.add(e);
				prev = v;
			}
		}
	}

	private void insertIntervalsStatic_() {
		int size = m_intervals.size();

		assert (m_b_sort_intervals);

		// sort
		AttributeStreamOfInt32 end_indices_sorted = new AttributeStreamOfInt32(
				0);
		end_indices_sorted.reserve(2 * size);
		querySortedEndPointIndices_(end_indices_sorted);

		// remove duplicates
		m_end_indices_unique.reserve(2 * size);
		m_end_indices_unique.resize(0);
		querySortedDuplicatesRemoved_(end_indices_sorted);

		assert (m_primary_nodes.size() == 0);
		m_interval_nodes.setCapacity(size); // one for each interval being
											// inserted. each element contains a
											// primary node, a left secondary
											// node, and a right secondary node.
		m_secondary_lists.reserveNodes(2 * size); // one for each end point of
													// the original interval set
													// (not the unique set)

		AttributeStreamOfInt32 interval_handles = (AttributeStreamOfInt32) AttributeStreamBase
				.createIndexStream(size);
		interval_handles.setRange(-1, 0, size);

		m_root = createPrimaryNode_();

		for (int i = 0; i < end_indices_sorted.size(); i++) {
			int e = end_indices_sorted.get(i);
			int interval_handle = interval_handles.get(e >> 1);

			if (interval_handle != -1) {// insert the right end point
				assert (isRight_(e));
				int secondary_handle = getSecondaryFromInterval_(interval_handle);
				setRightEnd_(interval_handle,
						m_secondary_lists.addElement(secondary_handle, e));
			} else {// insert the left end point
				assert (isLeft_(e));
				interval_handle = insertIntervalEnd_(e, m_root);
				interval_handles.set(e >> 1, interval_handle);
			}
		}

		assert (m_secondary_lists.getNodeCount() == 2 * size);
	}

	private int insertIntervalEnd_(int end_index, int root) {
		assert (isLeft_(end_index));
		int primary_handle = root;
		int tertiary_handle = root;
		int ptr = root;
		int secondary_handle;
		int interval_handle = -1;
		int il = 0, ir = m_end_indices_unique.size() - 1, im = 0;
		int index = end_index >> 1;
		double discriminant_tertiary = NumberUtils.TheNaN;
		double discriminant_ptr = NumberUtils.TheNaN;
		boolean bSearching = true;

		double min = getMin_(index);
		double max = getMax_(index);

		while (bSearching) {
			if (il < ir) {
				im = il + (ir - il) / 2;

				if (getDiscriminantIndex1_(primary_handle) == -1)
					setDiscriminantIndices_(primary_handle,
							m_end_indices_unique.get(im),
							m_end_indices_unique.get(im + 1));
			} else {
				assert (il == ir);
				assert (min == max);

				if (getDiscriminantIndex1_(primary_handle) == -1)
					setDiscriminantIndices_(primary_handle,
							m_end_indices_unique.get(il),
							m_end_indices_unique.get(il));
			}

			double discriminant = getDiscriminant_(primary_handle);
			assert (!NumberUtils.isNaN(discriminant));

			if (max < discriminant) {
				if (ptr != -1) {
					if (ptr == primary_handle) {
						tertiary_handle = primary_handle;
						discriminant_tertiary = discriminant;
						ptr = getLPTR_(primary_handle);

						if (ptr != -1)
							discriminant_ptr = getDiscriminant_(ptr);
						else
							discriminant_ptr = NumberUtils.TheNaN;
					} else if (discriminant_ptr > discriminant) {
						if (discriminant < discriminant_tertiary)
							setLPTR_(tertiary_handle, primary_handle);
						else
							setRPTR_(tertiary_handle, primary_handle);

						setRPTR_(primary_handle, ptr);

						if (m_b_offline_dynamic) {
							setPPTR_(primary_handle, tertiary_handle);
							setPPTR_(ptr, primary_handle);
						}

						tertiary_handle = primary_handle;
						discriminant_tertiary = discriminant;
						ptr = -1;
						discriminant_ptr = NumberUtils.TheNaN;

						assert (getLPTR_(primary_handle) == -1);
						assert (getRightPrimary_(primary_handle) != -1);
					}
				}

				int left_handle = getLeftPrimary_(primary_handle);

				if (left_handle == -1) {
					left_handle = createPrimaryNode_();
					setLeftPrimary_(primary_handle, left_handle);
				}

				primary_handle = left_handle;
				ir = im;

				continue;
			}

			if (min > discriminant) {
				if (ptr != -1) {
					if (ptr == primary_handle) {
						tertiary_handle = primary_handle;
						discriminant_tertiary = discriminant;
						ptr = getRPTR_(primary_handle);

						if (ptr != -1)
							discriminant_ptr = getDiscriminant_(ptr);
						else
							discriminant_ptr = NumberUtils.TheNaN;
					} else if (discriminant_ptr < discriminant) {
						if (discriminant < discriminant_tertiary)
							setLPTR_(tertiary_handle, primary_handle);
						else
							setRPTR_(tertiary_handle, primary_handle);

						setLPTR_(primary_handle, ptr);

						if (m_b_offline_dynamic) {
							setPPTR_(primary_handle, tertiary_handle);
							setPPTR_(ptr, primary_handle);
						}

						tertiary_handle = primary_handle;
						discriminant_tertiary = discriminant;
						ptr = -1;
						discriminant_ptr = NumberUtils.TheNaN;

						assert (getRPTR_(primary_handle) == -1);
						assert (getLeftPrimary_(primary_handle) != -1);
					}
				}

				int right_handle = getRightPrimary_(primary_handle);

				if (right_handle == -1) {
					right_handle = createPrimaryNode_();
					setRightPrimary_(primary_handle, right_handle);
				}

				primary_handle = right_handle;
				il = im + 1;

				continue;
			}

			secondary_handle = getSecondaryFromPrimary(primary_handle);

			if (secondary_handle == -1) {
				secondary_handle = createSecondary_(primary_handle);
				setSecondaryToPrimary_(primary_handle, secondary_handle);
			}

			int left_end_handle = addEndIndex(secondary_handle, end_index);
			interval_handle = createIntervalNode_();
			setSecondaryToInterval_(interval_handle, secondary_handle);
			setLeftEnd_(interval_handle, left_end_handle);

			if (primary_handle != ptr) {
				assert (primary_handle != -1);
				assert (getLPTR_(primary_handle) == -1
						&& getRPTR_(primary_handle) == -1 && (!m_b_offline_dynamic || getPPTR_(primary_handle) == -1));

				if (discriminant < discriminant_tertiary)
					setLPTR_(tertiary_handle, primary_handle);
				else
					setRPTR_(tertiary_handle, primary_handle);

				if (m_b_offline_dynamic)
					setPPTR_(primary_handle, tertiary_handle);

				if (ptr != -1) {
					if (discriminant_ptr < discriminant)
						setLPTR_(primary_handle, ptr);
					else
						setRPTR_(primary_handle, ptr);

					if (m_b_offline_dynamic)
						setPPTR_(ptr, primary_handle);
				}
			}

			bSearching = false;
		}

		return interval_handle;
	}

	private int createPrimaryNode_() {
		return m_primary_nodes.newElement();
	}

	private int createSecondary_(int primary_handle) {
		if (!m_b_offline_dynamic)
			return m_secondary_lists.createList(primary_handle);

		return m_secondary_treaps.createTreap(primary_handle);
	}

	private int createIntervalNode_() {
		return m_interval_nodes.newElement();
	}

	private void reset_(boolean b_new_intervals) {
		if (b_new_intervals) {
			m_b_sort_intervals = true;
			m_b_constructing = true;
			m_b_construction_ended = false;

			if (m_end_indices_unique == null)
				m_end_indices_unique = (AttributeStreamOfInt32) (AttributeStreamBase
						.createIndexStream(0));
			else
				m_end_indices_unique.resize(0);

			if (m_intervals == null)
				m_intervals = new ArrayList<Envelope1D>(0);
			else
				m_intervals.clear();
		} else {
			assert (m_b_offline_dynamic && m_b_construction_ended);
			m_b_sort_intervals = false;
		}

		if (m_b_offline_dynamic) {
			if (m_interval_handles == null) {
				m_interval_handles = (AttributeStreamOfInt32) (AttributeStreamBase
						.createIndexStream(0));
				m_secondary_treaps = new Treap();
				m_secondary_treaps.setComparator(new SecondaryComparator(this));
			} else {
				m_secondary_treaps.clear();
			}
		} else {
			if (m_secondary_lists == null)
				m_secondary_lists = new IndexMultiDCList();
			else
				m_secondary_lists.clear();
		}

		if (m_primary_nodes == null) {
			m_interval_nodes = new StridedIndexTypeCollection(3);
			m_primary_nodes = new StridedIndexTypeCollection(
					m_b_offline_dynamic ? 8 : 7);
		} else {
			m_interval_nodes.deleteAll(false);
			m_primary_nodes.deleteAll(false);
		}

		m_root = -1;
		m_c_count = 0;
	}

	private void setDiscriminantIndices_(int primary_handle, int e_1, int e_2) {
		setDiscriminantIndex1_(primary_handle, e_1);
		setDiscriminantIndex2_(primary_handle, e_2);
	}

	private double getDiscriminant_(int primary_handle) {
		int e_1 = getDiscriminantIndex1_(primary_handle);
		if (e_1 == -1)
			return NumberUtils.TheNaN;

		int e_2 = getDiscriminantIndex2_(primary_handle);
		assert (e_2 != -1);

		double v_1 = getValue_(e_1);
		double v_2 = getValue_(e_2);

		if (v_1 == v_2)
			return v_1;

		return 0.5 * (v_1 + v_2);
	}

	private boolean isActive_(int primary_handle) {
		int secondary_handle = getSecondaryFromPrimary(primary_handle);

		if (secondary_handle != -1)
			return true;

		int left_handle = getLeftPrimary_(primary_handle);

		if (left_handle == -1)
			return false;

		int right_handle = getRightPrimary_(primary_handle);

		if (right_handle == -1)
			return false;

		return true;
	}

	private void setDiscriminantIndex1_(int primary_handle, int end_index) {
		m_primary_nodes.setField(primary_handle, 0, end_index);
	}

	private void setDiscriminantIndex2_(int primary_handle, int end_index) {
		m_primary_nodes.setField(primary_handle, 1, end_index);
	}

	private void setLeftPrimary_(int primary_handle, int left_handle) {
		m_primary_nodes.setField(primary_handle, 3, left_handle);
	}

	private void setRightPrimary_(int primary_handle, int right_handle) {
		m_primary_nodes.setField(primary_handle, 4, right_handle);
	}

	private void setSecondaryToPrimary_(int primary_handle, int secondary_handle) {
		m_primary_nodes.setField(primary_handle, 2, secondary_handle);
	}

	private void setLPTR_(int primary_handle, int lptr) {
		m_primary_nodes.setField(primary_handle, 5, lptr);
	}

	private void setRPTR_(int primary_handle, int rptr) {
		m_primary_nodes.setField(primary_handle, 6, rptr);
	}

	private void setPPTR_(int primary_handle, int pptr) {
		m_primary_nodes.setField(primary_handle, 7, pptr);
	}

	private void setSecondaryToInterval_(int interval_handle,
			int secondary_handle) {
		m_interval_nodes.setField(interval_handle, 0, secondary_handle);
	}

	private int addEndIndex(int secondary_handle, int end_index) {
		int end_index_handle;

		if (!m_b_offline_dynamic)
			end_index_handle = m_secondary_lists.addElement(secondary_handle,
					end_index);
		else
			end_index_handle = m_secondary_treaps.addElement(end_index,
					secondary_handle);

		return end_index_handle;
	}

	private void setLeftEnd_(int interval_handle, int left_end_handle) {
		m_interval_nodes.setField(interval_handle, 1, left_end_handle);
	}

	private void setRightEnd_(int interval_handle, int right_end_handle) {
		m_interval_nodes.setField(interval_handle, 2, right_end_handle);
	}

	private int getFirst_(int secondary_handle) {
		if (!m_b_offline_dynamic)
			return m_secondary_lists.getFirst(secondary_handle);

		return m_secondary_treaps.getFirst(secondary_handle);
	}

	private int getLast_(int secondary_handle) {
		if (!m_b_offline_dynamic)
			return m_secondary_lists.getLast(secondary_handle);

		return m_secondary_treaps.getLast(secondary_handle);
	}

	private static boolean isLeft_(int end_index) {
		return (end_index & 0x1) == 0;
	}

	private static boolean isRight_(int end_index) {
		return (end_index & 0x1) == 1;
	}

	private int getDiscriminantIndex1_(int primary_handle) {
		return m_primary_nodes.getField(primary_handle, 0);
	}

	private int getDiscriminantIndex2_(int primary_handle) {
		return m_primary_nodes.getField(primary_handle, 1);
	}

	private int getSecondaryFromPrimary(int primary_handle) {
		return m_primary_nodes.getField(primary_handle, 2);
	}

	private int getLeftPrimary_(int primary_handle) {
		return m_primary_nodes.getField(primary_handle, 3);
	}

	private int getRightPrimary_(int primary_handle) {
		return m_primary_nodes.getField(primary_handle, 4);
	}

	private int getLPTR_(int primary_handle) {
		return m_primary_nodes.getField(primary_handle, 5);
	}

	private int getRPTR_(int primary_handle) {
		return m_primary_nodes.getField(primary_handle, 6);
	}

	private int getPPTR_(int primary_handle) {
		return m_primary_nodes.getField(primary_handle, 7);
	}

	private int getSecondaryFromInterval_(int interval_handle) {
		return m_interval_nodes.getField(interval_handle, 0);
	}

	private int getLeftEnd_(int interval_handle) {
		return m_interval_nodes.getField(interval_handle, 1);
	}

	private int getRightEnd_(int interval_handle) {
		return m_interval_nodes.getField(interval_handle, 2);
	}

	private double getMin_(int i) {
		Envelope1D interval = m_intervals.get(i);
		return interval.vmin;
	}

	private double getMax_(int i) {
		Envelope1D interval = m_intervals.get(i);
		return interval.vmax;
	}

	// *********** Helpers for Bucket sort**************
	private BucketSort m_bucket_sort;

	private void sortEndIndices_(AttributeStreamOfInt32 end_indices,
			int begin_, int end_) {
		if (m_bucket_sort == null)
			m_bucket_sort = new BucketSort();

		IntervalTreeBucketSortHelper sorter = new IntervalTreeBucketSortHelper(
				this);
		m_bucket_sort.sort(end_indices, begin_, end_, sorter);
	}

	private void sortEndIndicesHelper_(AttributeStreamOfInt32 end_indices,
			int begin_, int end_) {
		end_indices.Sort(begin_, end_, new EndPointsComparer(this));
	}

	private double getValue_(int e) {
		Envelope1D interval = m_intervals.get(e >> 1);
		double v = (isLeft_(e) ? interval.vmin : interval.vmax);
		return v;
	}

	private static final class EndPointsComparer extends
			AttributeStreamOfInt32.IntComparator { // For user sort
		EndPointsComparer(IntervalTreeImpl interval_tree) {
			m_interval_tree = interval_tree;
		}

		@Override
		public int compare(int e_1, int e_2) {
			double v_1 = m_interval_tree.getValue_(e_1);
			double v_2 = m_interval_tree.getValue_(e_2);

			if (v_1 < v_2 || (v_1 == v_2 && isLeft_(e_1) && isRight_(e_2)))
				return -1;

			return 1;
		}

		private IntervalTreeImpl m_interval_tree;
	}

	private class IntervalTreeBucketSortHelper extends ClassicSort { // For
																		// bucket
																		// sort
		IntervalTreeBucketSortHelper(IntervalTreeImpl interval_tree) {
			m_interval_tree = interval_tree;
		}

		@Override
		public void userSort(int begin, int end, AttributeStreamOfInt32 indices) {
			m_interval_tree.sortEndIndicesHelper_(indices, begin, end);
		}

		@Override
		public double getValue(int e) {
			return m_interval_tree.getValue_(e);
		}

		private IntervalTreeImpl m_interval_tree;
	}
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Pformat — VCS 2.4.1 documentation</title>

    <link rel="stylesheet" href="../../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />

    <link rel="shortcut icon" href="../../_static/globe.png"/>
    <link rel="top" title="VCS 2.4.1 documentation" href="../../index.html" />
    <link rel="up" title="Templating" href="templ.html" />
    <link rel="next" title="Plegend" href="Plegend.html" />
    <link rel="prev" title="Pdata" href="Pdata.html" />

Navigation

          index

          modules |

          next |

          previous |

VCS 2.4.1 documentation »

VCS »

Templating »

Pformat¶

# Template Format (Pf) module

class vcs.Pformat.Pf(member)[source]¶

The Template text object allows the manipulation of line type, width, and color index.

This class is used to define an line table entry used in VCS, or it
can be used to change some or all of the line attributes in an
existing line table entry.

Useful Functions:

# VCS Canvas Constructor
a=vcs.init()
# Show predefined line objects
a.show('line')
# Updates the VCS Canvas at user's request
a.update()

Make a Canvas object to work with:

a=vcs.init()

Create a new instance of line:

# Copies content of 'red' to 'new'
ln=a.createline('new','red')
# Copies content of 'default' to 'new'
ln=a.createline('new')

Modify an existing line:

ln=a.getline('red')

Overview of line attributes:

Listing line attributes:

# Will list all the line attribute values
ln.list()
# Range from 1 to 256
ln.color=100
# Range from 1 to 300
ln.width=100

Specifying the line type:

# Same as ln.type=0
ln.type='solid'
# Same as ln.type=1
ln.type='dash'
# Same as ln.type=2
ln.type='dot'
# Same as ln.type=3
ln.type='dash-dot'
# Same as ln.type=4
ln.type='long-dash'

Previous topic

Pdata

Next topic

Plegend

This Page

Show Source

Quick search

    <form class="search" action="../../search.html" method="get">

<input type="text" name="q" />

<input type="submit" value="Go" />

      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

Navigation

          index

          modules |

          next |

          previous |

VCS 2.4.1 documentation »

VCS »

Templating »

        © Copyright 2016, LLNL.
      Created using Sphinx 1.4.6.

redpajama_set_name: RedPajamaGithub


text:
[![Version](https://img.shields.io/cocoapods/v/PXMultiForwarder.svg?style=flat)](http://cocoapods.org/pods/PXMultiForwarder)
[![License](https://img.shields.io/cocoapods/l/PXMultiForwarder.svg?style=flat)](http://cocoapods.org/pods/PXMultiForwarder)
[![Platform](https://img.shields.io/cocoapods/p/PXMultiForwarder.svg?style=flat)](http://cocoapods.org/pods/PXMultiForwarder)

## Usage

A small utility class you can use to wrap objects and message all of them as if you were working with one.

To run the example project, clone the repo, and run `pod install` from the Example directory first.

## Requirements

- Computer

## Installation

PXMultiForwarder is available through [CocoaPods](http://cocoapods.org). To install
it, simply add the following line to your Podfile:

```ruby
pod "PXMultiForwarder"
```

## Author

Spencer Phippen, spencer.phippen@gmail.com

## License

PXMultiForwarder is available under the MIT license. See the LICENSE file for more info.


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace CMS.Client.Admin {

    public partial class EditDownload {

        /// <summary>
        /// imgIcon control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Image imgIcon;

        /// <summary>
        /// litModules control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Literal litModules;

        /// <summary>
        /// btn_home control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.HyperLink btn_home;

        /// <summary>
        /// btn_editpage control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.HyperLink btn_editpage;

        /// <summary>
        /// HyperLink1 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.HyperLink HyperLink1;

        /// <summary>
        /// btn_add control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.HyperLink btn_add;

        /// <summary>
        /// ImageButton1 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.ImageButton ImageButton1;

        /// <summary>
        /// btn_edit control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.HyperLink btn_edit;

        /// <summary>
        /// ImageButton3 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.ImageButton ImageButton3;

        /// <summary>
        /// HyperLink3 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.HyperLink HyperLink3;

        /// <summary>
        /// clientview control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Literal clientview;

        /// <summary>
        /// Label1 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label Label1;

        /// <summary>
        /// ddlCateDownload control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.DropDownList ddlCateDownload;

        /// <summary>
        /// Label2 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label Label2;

        /// <summary>
        /// txtTitle control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox txtTitle;

        /// <summary>
        /// RequiredFieldValidator1 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator1;

        /// <summary>
        /// Label3 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label Label3;

        /// <summary>
        /// file_image_thumb control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.FileUpload file_image_thumb;

        /// <summary>
        /// RegularExpressionValidator1 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.RegularExpressionValidator RegularExpressionValidator1;

        /// <summary>
        /// Label11 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label Label11;

        /// <summary>
        /// file_attached control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.FileUpload file_attached;

        /// <summary>
        /// RegularExpressionValidator2 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.RegularExpressionValidator RegularExpressionValidator2;

        /// <summary>
        /// Label4 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label Label4;

        /// <summary>
        /// txtRadShort control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Telerik.Web.UI.RadEditor txtRadShort;

        /// <summary>
        /// Label5 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label Label5;

        /// <summary>
        /// txtRadFull control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Telerik.Web.UI.RadEditor txtRadFull;

        /// <summary>
        /// Label10 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label Label10;

        /// <summary>
        /// rdbIshot control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.RadioButtonList rdbIshot;

        /// <summary>
        /// Label6 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label Label6;

        /// <summary>
        /// txtRadDate control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Telerik.Web.UI.RadDatePicker txtRadDate;

        /// <summary>
        /// Label7 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label Label7;

        /// <summary>
        /// txtAuthor control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox txtAuthor;

        /// <summary>
        /// Label8 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label Label8;

        /// <summary>
        /// rdbStatus control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.RadioButtonList rdbStatus;

        /// <summary>
        /// Label9 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label Label9;

        /// <summary>
        /// rdbIshome control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.RadioButtonList rdbIshome;

        /// <summary>
        /// Label12 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label Label12;

        /// <summary>
        /// rdbComment control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.RadioButtonList rdbComment;

        /// <summary>
        /// Label13 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label Label13;

        /// <summary>
        /// rdbApproval control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.RadioButtonList rdbApproval;

        /// <summary>
        /// hddDownloadID control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.HiddenField hddDownloadID;

        /// <summary>
        /// hddImageThumb control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.HiddenField hddImageThumb;

        /// <summary>
        /// hddFileName control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.HiddenField hddFileName;

        /// <summary>
        /// hddRelationTotal control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.HiddenField hddRelationTotal;

        /// <summary>
        /// hddParentDownloadID control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.HiddenField hddParentDownloadID;

        /// <summary>
        /// hddCommentTotal control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.HiddenField hddCommentTotal;

        /// <summary>
        /// hddIsView control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.HiddenField hddIsView;

        /// <summary>
        /// hddCreateUserName control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.HiddenField hddCreateUserName;

        /// <summary>
        /// hddApprovalUserName control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.HiddenField hddApprovalUserName;

        /// <summary>
        /// hddApprovalDate control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.HiddenField hddApprovalDate;
    }
}


text:
/**
 *
 */
package rms.common.utils;

import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * セッション管理Utils
 * @author
 */
public class RmsSessionUtils {
    /** logger */
    @SuppressWarnings("unused")
    private static final Logger logger = LoggerFactory.getLogger(RmsSessionUtils.class);

    // TODO どっかのタイミングできれいにする
    /** セッションキー除外対象リスト */
    private static final List<String> ignoreKeyList = Arrays.asList("SPRING_SECURITY_CONTEXT", // SPRING_SECURITY_CONTEXT
                                                                    "org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository.CSRF_TOKEN", // CRLFトークン
                                                                    RmsSessionInfo.SESSION_KEY // アプリケーション固有セッション情報
    );

    /**
     * セッション情報を破棄

     * セッションキー除外対象リストを除く
     * @param session
     */
    public static void remove(HttpSession session) {
        Enumeration<String> e = session.getAttributeNames();
        while (e.hasMoreElements()) {
            String key = e.nextElement();
            if (!ignoreKeyList.contains(key)) {
                // logger.debug("remove session -> {}", key);
                session.removeAttribute(key);
            }
        }
    }

    /**
     * セッション情報をMapに変換
     * @param session
     * @return
     */
    public static Map<String, ?> convertSessionToMap(HttpSession session) {
        Map<String, Object> attributes = new HashMap<>();

        Enumeration<String> names = session.getAttributeNames();
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            Object obj = session.getAttribute(name);
            attributes.put(name, obj);
        }
        return attributes;
    }

    /**
     * アプリケーション固有セッション情報の取得

     * 取得できない場合は新規作成する。
     * @param session
     * @return
     */
    public static RmsSessionInfo getRmsSessionInfo(HttpSession session) {
        RmsSessionInfo rmsSessionInfo;
        Object obj = session.getAttribute(RmsSessionInfo.SESSION_KEY);
        if (obj != null) {
            // 存在する場合はそのまま返却
            rmsSessionInfo = (RmsSessionInfo) obj;
        } else {
            // 存在しない場合は新規生成して返却
            rmsSessionInfo = new RmsSessionInfo();
            session.setAttribute(RmsSessionInfo.SESSION_KEY, rmsSessionInfo);
        }

        return rmsSessionInfo;
    }

    // /**
    // * セッションから指定されたクラスのフォーム情報の取得
    // * @param <T>
    // * @param session
    // * @param cls
    // * @return
    // */
    // @SuppressWarnings("unchecked")
    // public static <T> T getSessionForm(HttpSession session,
    // Class<T> cls) {
    //
    // try {
    // // クラスオブジェクトからSpringの自動生成keyを取得
    // String key = Conventions.getVariableName(cls.newInstance());
    // // セッションから取得
    // Object obj = session.getAttribute(key);
    // if (obj != null && obj.getClass() == cls) {
    // return (T) obj;
    // }
    // } catch (Exception e) {
    // throw new RuntimeException("class instance error", e);
    // }
    // return null;
    // }

}


text:
import os, urllib, urllib2, json, pandas, numpy, IPython, datetime, calendar, math, traceback, types, time
from IPython.utils.traitlets import Unicode

class OutputContainer:
    def __init__(self):
        self.items = []
    def clear(self):
        self.items = [ ]
    def addItem(self, obj):
        self.items.append(obj)
    def getItems(self):
        return self.items

class BeakerCodeCell:
    def __init__(self, cellId, evaluatorId):
        self.cellId = cellId
        self.evaluatorId = evaluatorId
        self.code = ''
        self.outputtype = ''
        self.output = None
        self.tags = ''
    def getCellId(self):
        return self.cellId
    def getEvaluatorId(self):
        return self.evaluatorId
    def getCode(self):
        return self.code
    def getOutputType(self):
        return self.outputtype
    def getOutput(self):
        return self.output
    def getTags(self):
        return self.tags

def convertTypeName(typ):
    if typ.startswith("float"):
        return "double"
    if typ.startswith("int") or typ.startswith("uint") or typ.startswith("short") or typ.startswith("ushort") or typ.startswith("long") or typ.startswith("ulong"):
        return "integer"
    if typ.startswith("bool"):
        return "boolean"
    if typ.startswith("date") or typ.startswith("Time"):
        return "time"
    return "string"

def isPrimitiveType(typ):
    if typ.startswith("float"):
        return True
    if typ.startswith("int") or typ.startswith("uint") or typ.startswith("short") or typ.startswith("ushort") or typ.startswith("long") or typ.startswith("ulong"):
        return True
    if typ.startswith("bool"):
        return True
    if typ.startswith("date") or typ.startswith("Time"):
        return True
    if typ.startswith("str"):
        return True
    return False

def isListOfMaps(data):
    if type(data) != list:
        return False
    for w in data:
        if type(w) != dict:
            return False
        for v in w.itervalues():
            if not isPrimitiveType(type(v).__name__):
                return False
    return True

def isDictionary(data):
    if type(data) != dict:
        return False
    for v in data.itervalues():
        if not isPrimitiveType(type(v).__name__):
            return False
    return True

def transformNaN(obj):
    if not isinstance(obj, types.FloatType):
        return obj
    if math.isnan(obj):
        return "Nan";
    if math.isinf(obj):
        if obj>0:
            return "Infinity"
        else:
            return "-Infinity"
    return obj

def transformNaNs(obj):
    for x in range(0,len(obj)):
        i = obj[x];
        if not isinstance(i, types.FloatType):
            continue
        if math.isnan(i):
            obj[x] = "NaN";
        if math.isinf(i):
            if i>0:
                obj[x] = "Infinity"
            else:
                obj[x] = "-Infinity"

def fixNaNBack(obj):
    if not isinstance(obj, types.StringType):
        return obj
    if obj == "NaN":
        return float('nan')
    if obj == "Infinity":
        return float('inf')
    if obj == "-Infinity":
        return float('-inf')
    return obj

def fixNaNsBack(obj):
    for x in range(0,len(obj)):
        i = obj[x];
        if not isinstance(i, types.StringType):
            continue
        if i == "NaN":
            obj[x] = float('nan')
        if i == "Infinity":
            obj[x] = float('inf')
        if i == "-Infinity":
            obj[x] = float('-inf')

def transform(obj):
    if type(obj) == unicode:
        return str(obj)
    if isListOfMaps(obj):
        out = {}
        out['type'] = "TableDisplay"
        out['subtype'] = "ListOfMaps"
        cols = []
        for l in obj:
            cols.extend(l.iterkeys())
        cols = list(set(cols))
        out['columnNames'] = cols
        vals = []
        for l in obj:
            row = []
            for r in cols:
                if r in l:
                    row.append(transform(l[r]))
                else:
                    row.append('')
            vals.append(row)
        out['values'] = vals
        return out
    if isDictionary(obj):
        out = {}
        out['type'] = "TableDisplay"
        out['subtype'] = "Dictionary"
        out['columnNames'] = [ "Key", "Value" ]
        values = []
        for k,v in obj.iteritems():
            values.append( [k, transform(v)] )
        out['values'] = values
        return out
    if type(obj) == dict:
        out = {}
        for k,v in obj.iteritems():
            out[k] = transform(v)
        return out
    if type(obj) == list:
        out = []
        for v in obj:
            out.append(transform(v))
        return out
    if isinstance(obj, OutputContainer):
        out = {}
        out['type'] = "OutputContainer"
        items = []
        for v in obj.getItems():
            items.append(transform(v))
        out['items'] = items
        return out
    if isinstance(obj, BeakerCodeCell):
        out = {}
        out['type'] = "BeakerCodeCell"
        out['cellId'] = obj.getCellId()
        out['evaluatorId'] = obj.getEvaluatorId()
        out['code'] = obj.getCode()
        out['outputtype'] = obj.getOutputType()
        out['output'] = transform(obj.getOutput())
        out['tags'] = obj.getTags()
        return out
    return transformNaN(obj)

def transformBack(obj):
    if type(obj) == dict:
        out = {}
        for k,v in obj.iteritems():
            out[str(k)] = transformBack(v)
        if "type" in out:
            if out['type'] == "BeakerCodeCell":
                c = BeakerCodeCell(out['cellId'], out['evaluatorId'])
                if 'code' in out:
                    c.code = out['code']
                if 'outputtype' in out:
                    c.outputtype = out['outputtype']
                if 'output' in out:
                    c.output = transformBack(out['output'])
                if 'tags' in out:
                    c.tags = out['tags']
                return c
            if out['type'] == "OutputContainer":
                c = OutputContainer()
                if 'items' in out:
                    for i in out['items']:
                        c.addItem(i)
                return c;
            if out['type'] == "Date":
                return datetime.datetime.fromtimestamp(out["timestamp"]/1000)
            if out['type'] == "TableDisplay":
                if 'subtype' in out:
                    if out['subtype'] == "Dictionary":
                        out2 = { }
                        for r in out['values']:
                            out2[r[0]] = fixNaNBack(r[1])
                        if out['columnNames'][0] == "Index":
                            return pandas.Series(out2)
                        return out2
                    if out['subtype'] == "Matrix":
                        vals = out['values']
                        fixNaNsBack(vals)
                        return numpy.matrix(vals)
                    if out['subtype'] == "ListOfMaps":
                        out2 = []
                        cnames = out['columnNames']
                        for r in out['values']:
                            out3 = { }
                            for i in range(len(cnames)):
                                if r[i] != '':
                                    out3[ cnames[i] ] = r[i]
                            out2.append(out3)
                        return out2
                # transform to dataframe
                # first column becomes the index
                vals = out['values']
                cnames = out['columnNames'][1:]
                index = []
                for x in range(0,len(vals)):
                    index.append(transformBack(vals[x][0]))
                    v = vals[x][1:]
                    fixNaNsBack(v)
                    vals[x] = v
                return pandas.DataFrame(data=vals, columns=cnames, index=index)
        return out
    if type(obj) == list:
        out = []
        for v in obj:
            out.append(transformBack(v))
        return out
    try:
        if type(obj) == unicode:
            obj = str(obj)
    except Exception as e:
        return obj
    return obj

# should be inner class to Beaker
class DataFrameEncoder(json.JSONEncoder):
    def default(self, obj):
        # similarly handle Panels.
        # make this extensible by the user to handle their own types.
        if isinstance(obj, numpy.generic):
            return transformNaN(obj.item())
        if isinstance(obj, numpy.ndarray) and obj.ndim == 2:
            out = {}
            out['type'] = "TableDisplay"
            out['subtype'] = "Matrix"
            cols = [ ]
            for i in range(obj.shape[1]):
                cols.append( "c" + str(i) )
            out['columnNames'] = cols
            vars = obj.tolist()
            for x in range(0,len(vars)):
                transformNaNs(vars[x])
            out['values'] = vars
            return out
        if isinstance(obj, numpy.ndarray):
            ret = obj.tolist()
            transformNaNs(ret)
            return ret
        if type(obj) == datetime.datetime or type(obj) == datetime.date or type(obj).__name__ == 'Timestamp':
            out = {}
            out['type'] = "Date"
            out['timestamp'] = int(obj.strftime("%s"))*1000
            return out
        if type(obj) == pandas.core.frame.DataFrame:
            out = {}
            out['type'] = "TableDisplay"
            out['subtype'] = "TableDisplay"
            out['columnNames'] = ['Index'] + obj.columns.tolist()
            vals = obj.values.tolist()
            idx = obj.index.tolist()
            for x in range(0,len(vals)):
                vals[x] = [ idx[x] ] + vals[x]
            ty = []
            num = len(obj.columns.tolist())
            x = 0;
            for x in range(0,num+1):
              	ty.append( convertTypeName(type(vals[0][x]).__name__))
            out['types'] = ty
            for x in range(0,len(vals)):
                transformNaNs(vals[x])
            out['values'] = vals
            return out
        if type(obj) == pandas.core.series.Series:
            basict = True
            for i in range(len(obj)):
                if not isPrimitiveType(type(obj[i]).__name__):
                    basict = False
                    break
            if basict:
                out = {}
                out['type'] = "TableDisplay"
                out['subtype'] = "Dictionary"
                out['columnNames'] = [ "Index", "Value" ]
                values = []
                for k,v in obj.iteritems():
                    values.append( [k, transform(v)] )
                out['values'] = values
                return out
            return obj.to_dict()
        return json.JSONEncoder.default(self, obj)

class MyJSONFormatter(IPython.core.formatters.BaseFormatter):
    format_type = Unicode('application/json')
    def __call__(self, obj):
        try:
            obj = transform(obj)
            return json.dumps(obj, cls=DataFrameEncoder)
        except Exception as e:
            #print(e)
            #traceback.print_exc()
            return None

class Beaker:
    """Runtime support for Python code in Beaker."""
    session_id = ''
    core_url = '127.0.0.1:' + os.environ['beaker_core_port']
    _beaker_password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
    _beaker_password_mgr.add_password(None, core_url, 'beaker',
                              os.environ['beaker_core_password'])
    _beaker_url_opener = urllib2.build_opener(urllib2.HTTPBasicAuthHandler(_beaker_password_mgr), urllib2.ProxyHandler({}))

    def set4(self, var, val, unset, sync):
        args = {'name': var, 'session':self.session_id, 'sync':sync}
        if not unset:
            val = transform(val)
            args['value'] = json.dumps(val, cls=DataFrameEncoder)
        req = urllib2.Request('http://' + self.core_url + '/rest/namespace/set',
                              urllib.urlencode(args))
        conn = self._beaker_url_opener.open(req)
        reply = conn.read()
        if reply != 'ok':
            raise NameError(reply)

    def get(self, var):
        req = urllib2.Request('http://' + self.core_url + '/rest/namespace/get?' +
                              urllib.urlencode({'name': var, 'session':self.session_id}))
        conn = self._beaker_url_opener.open(req)
        result = json.loads(conn.read())
        if not result['defined']:
            raise NameError('name \'' + var + '\' is not defined in notebook namespace')
        return transformBack(result['value'])

    def set_session(self, id):
        self.session_id = id

    def register_output(self):
        ip = IPython.InteractiveShell.instance()
        ip.display_formatter.formatters['application/json'] = MyJSONFormatter(parent=ip.display_formatter)

    def set(self, var, val):
        return self.set4(var, val, False, True)

    def createOutputContainer(self):
        return OutputContainer()

    def showProgressUpdate(self):
        return "WARNING: python language plugin does not support progress updates"

    def evaluate(self,filter):
        args = {'filter': filter, 'session':self.session_id}
        req = urllib2.Request('http://' + self.core_url + '/rest/notebookctrl/evaluate',
                              urllib.urlencode(args))
        conn = self._beaker_url_opener.open(req)
        result = json.loads(conn.read())
        return transformBack(result)

    def evaluateCode(self, evaluator,code):
        args = {'evaluator': evaluator, 'code' : code, 'session':self.session_id}
        req = urllib2.Request('http://' + self.core_url + '/rest/notebookctrl/evaluateCode',
                              urllib.urlencode(args))
        conn = self._beaker_url_opener.open(req)
        result = json.loads(conn.read())
        return transformBack(result)

    def showStatus(self,msg):
        args = {'msg': msg, 'session':self.session_id}
        req = urllib2.Request('http://' + self.core_url + '/rest/notebookctrl/showStatus',
                              urllib.urlencode(args))
        conn = self._beaker_url_opener.open(req)
        result = conn.read()
        return result=="true"

    def clearStatus(self,msg):
        args = {'msg': msg, 'session':self.session_id}
        req = urllib2.Request('http://' + self.core_url + '/rest/notebookctrl/clearStatus',
                              urllib.urlencode(args))
        conn = self._beaker_url_opener.open(req)
        result = conn.read()
        return result=="true"

    def showTransientStatus(self,msg):
        args = {'msg': msg, 'session':self.session_id}
        req = urllib2.Request('http://' + self.core_url + '/rest/notebookctrl/showTransientStatus',
                              urllib.urlencode(args))
        conn = self._beaker_url_opener.open(req)
        result = conn.read()
        return result=="true"

    def getEvaluators(self):
        req = urllib2.Request('http://' + self.core_url + '/rest/notebookctrl/getEvaluators?' +
                              urllib.urlencode({'session':self.session_id}))
        conn = self._beaker_url_opener.open(req)
        result = json.loads(conn.read())
        return transformBack(result)

    def getCodeCells(self,filter):
        req = urllib2.Request('http://' + self.core_url + '/rest/notebookctrl/getCodeCells?' +
                              urllib.urlencode({'session':self.session_id, 'filter':filter}))
        conn = self._beaker_url_opener.open(req)
        result = json.loads(conn.read())
        return transformBack(result)

    def setCodeCellBody(self,name,body):
        args = {'name': name, 'body':body, 'session':self.session_id}
        req = urllib2.Request('http://' + self.core_url + '/rest/notebookctrl/setCodeCellBody',
                              urllib.urlencode(args))
        conn = self._beaker_url_opener.open(req)
        result = conn.read()
        return result=="true"

    def setCodeCellEvaluator(self,name,evaluator):
        args = {'name': name, 'evaluator':evaluator, 'session':self.session_id}
        req = urllib2.Request('http://' + self.core_url + '/rest/notebookctrl/setCodeCellEvaluator',
                              urllib.urlencode(args))
        conn = self._beaker_url_opener.open(req)
        result = conn.read()
        return result=="true"

    def setCodeCellTags(self,name,tags):
        args = {'name': name, 'tags':tags, 'session':self.session_id}
        req = urllib2.Request('http://' + self.core_url + '/rest/notebookctrl/setCodeCellTags',
                              urllib.urlencode(args))
        conn = self._beaker_url_opener.open(req)
        result = conn.read()
        return result=="true"

    def __setattr__(self, name, value):
        if 'session_id' == name:
            self.__dict__['session_id'] = value
            return
        return self.set(name, value)

    def __getattr__(self, name):
        return self.get(name)


text:
package org.apache.derbyTesting.junit;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class SQLUtilities {

    public static String VALID_DATE_STRING = "'2000-01-01'";
    public static String VALID_TIME_STRING = "'15:30:20'";
    public static String VALID_TIMESTAMP_STRING = "'2000-01-01 15:30:20'";
    public static String NULL_VALUE="NULL";

    public static String[] allDataTypesColumnNames =
    {
            "SMALLINTCOL",
            "INTEGERCOL",
            "BIGINTCOL",
            "DECIMALCOL",
            "REALCOL",
            "DOUBLECOL",
            "CHARCOL",
            "VARCHARCOL",
            "LONGVARCHARCOL",
            "CHARFORBITCOL",
            "VARCHARFORBITCOL",
            "LVARCHARFORBITCOL",
            "CLOBCOL",
            "DATECOL",
            "TIMECOL",
            "TIMESTAMPCOL",
            "BLOBCOL",

    };

    private static String[][]allDataTypesSQLData =
    {
            {NULL_VALUE, "0","1","2"},       // SMALLINT
            {NULL_VALUE,"0","1","21"},       // INTEGER
            {NULL_VALUE,"0","1","22"},       // BIGINT
            {NULL_VALUE,"0.0","1.0","23.0"},      // DECIMAL(10,5)
            {NULL_VALUE,"0.0","1.0","24.0"},      // REAL,
            {NULL_VALUE,"0.0","1.0","25.0"},      // DOUBLE
            {NULL_VALUE,"'0'","'aa'","'2.0'"},      // CHAR(60)
            {NULL_VALUE,"'0'","'aa'",VALID_TIME_STRING},      //VARCHAR(60)",
            {NULL_VALUE,"'0'","'aa'",VALID_TIMESTAMP_STRING},      // LONG VARCHAR
            {NULL_VALUE,"X'10aa'",NULL_VALUE,"X'10aaaa'"},  // CHAR(60)  FOR BIT DATA
            {NULL_VALUE,"X'10aa'",NULL_VALUE,"X'10aaba'"},  // VARCHAR(60) FOR BIT DATA
            {NULL_VALUE,"X'10aa'",NULL_VALUE,"X'10aaca'"},  //LONG VARCHAR FOR BIT DATA
            {NULL_VALUE,"'13'","'14'",NULL_VALUE},     //CLOB(1k)
            {NULL_VALUE,SQLUtilities.VALID_DATE_STRING,SQLUtilities.VALID_DATE_STRING,NULL_VALUE},        // DATE
            {NULL_VALUE,VALID_TIME_STRING,VALID_TIME_STRING,VALID_TIME_STRING},        // TIME
            {NULL_VALUE,VALID_TIMESTAMP_STRING,VALID_TIMESTAMP_STRING,VALID_TIMESTAMP_STRING},   // TIMESTAMP
            {NULL_VALUE,NULL_VALUE,NULL_VALUE,NULL_VALUE}                 // BLOB
    };

    /**
     * Create a table AllDataTypesTable and populate with data
     * @param s
     * @throws SQLException
     */
    public  static void createAndPopulateAllDataTypesTable(Statement s) throws SQLException {
        try {
            s.executeUpdate("DROP TABLE AllDataTypesTable");
        } catch (SQLException se) {
        }

        StringBuffer createSQL = new StringBuffer(
                "create table AllDataTypesTable (");
        for (int type = 0; type < SQLUtilities.SQLTypes.length - 1; type++) {
            createSQL.append(allDataTypesColumnNames[type] + " " + SQLUtilities.SQLTypes[type]
                    + ",");
        }
        createSQL.append(allDataTypesColumnNames[SQLUtilities.SQLTypes.length - 1] + " "
                + SQLUtilities.SQLTypes[SQLUtilities.SQLTypes.length - 1] + ")");
        s.executeUpdate(createSQL.toString());

        for (int row = 0; row < allDataTypesSQLData[0].length; row++) {
            createSQL = new StringBuffer(
                    "insert into AllDataTypesTable values(");
            for (int type = 0; type < SQLUtilities.SQLTypes.length - 1; type++) {
                createSQL.append(allDataTypesSQLData[type][row] + ",");
            }
            createSQL.append(allDataTypesSQLData[SQLUtilities.SQLTypes.length - 1][row] + ")");

            s.executeUpdate(createSQL.toString());
        }
    }

    /**
     *
     * Assumes user previously executed
     * "call SYSCS_UTIL.SYSCS_SET_RUNTIMESTATISTICS(1)";
     * @param s Statement to use for calling runtime statistics function
     * @return a runtime statistics parser
     * @throws SQLException
     */
    public static RuntimeStatisticsParser  getRuntimeStatisticsParser(Statement s) throws SQLException
    {
        ResultSet rs = s.executeQuery("values SYSCS_UTIL.SYSCS_GET_RUNTIMESTATISTICS()");
        rs.next();
        String rts = rs.getString(1);
        rs.close();
        return new RuntimeStatisticsParser(rts);
    }

    public static RuntimeStatisticsParser executeAndGetRuntimeStatistics(Connection conn, String sql ) throws SQLException
    {
        Statement s = conn.createStatement();
        Statement s2 = conn.createStatement();
        CallableStatement cs = conn.prepareCall("call SYSCS_UTIL.SYSCS_SET_RUNTIMESTATISTICS(1)");
        cs.execute();
        cs.close();
        s.execute(sql);
        ResultSet rs = s.getResultSet();
        if (rs != null)
            JDBC.assertDrainResults(rs);
        RuntimeStatisticsParser parser = getRuntimeStatisticsParser(s2);
        s.close();
        s2.close();
        return parser;
    }

	// Note: This array is accessed in lang.NullIfTest
	public static String[] SQLTypes =
	{
	        "SMALLINT",
	        "INTEGER",
	        "BIGINT",
	        "DECIMAL(10,5)",
	        "REAL",
	        "DOUBLE",
	        "CHAR(60)",
	        "VARCHAR(60)",
	        "LONG VARCHAR",
	        "CHAR(60) FOR BIT DATA",
	        "VARCHAR(60) FOR BIT DATA",
	        "LONG VARCHAR FOR BIT DATA",
	        "CLOB(1k)",
	        "DATE",
	        "TIME",
	        "TIMESTAMP",
	        "BLOB(1k)",
	};

}