text:
/* $Id: SpaceResolver.java 1067756 2011-02-06 20:50:56Z adelmelle $ */

package org.apache.fop.layoutmgr;

import java.util.List;
import java.util.ListIterator;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.apache.fop.traits.MinOptMax;

/**
 * This class resolves spaces and conditional borders and paddings by replacing the
 * UnresolvedListElements descendants by the right combination of KnuthElements on an element
 * list.
 */
public final class SpaceResolver {

    /** Logger instance */
    private static final Log LOG = LogFactory.getLog(SpaceResolver.class);

    private UnresolvedListElementWithLength[] firstPart;
    private BreakElement breakPoss;
    private UnresolvedListElementWithLength[] secondPart;
    private UnresolvedListElementWithLength[] noBreak;

    private MinOptMax[] firstPartLengths;
    private MinOptMax[] secondPartLengths;
    private MinOptMax[] noBreakLengths;

    private boolean isFirst;
    private boolean isLast;

    /**
     * Main constructor.
     * @param first Element list before a break (optional)
     * @param breakPoss Break possibility (optional)
     * @param second Element list after a break (or if no break possibility in vicinity)
     * @param isFirst Resolution at the beginning of a (full) element list
     * @param isLast Resolution at the end of a (full) element list
     */
    private SpaceResolver(List first, BreakElement breakPoss, List second,
            boolean isFirst, boolean isLast) {
        this.isFirst = isFirst;
        this.isLast = isLast;
        //Create combined no-break list
        int c = 0;
        if (first != null) {
            c += first.size();
        }
        if (second != null) {
            c += second.size();
        }
        noBreak = new UnresolvedListElementWithLength[c];
        noBreakLengths = new MinOptMax[c];
        int i = 0;
        ListIterator iter;
        if (first != null) {
            iter = first.listIterator();
            while (iter.hasNext()) {
                noBreak[i] = (UnresolvedListElementWithLength)iter.next();
                noBreakLengths[i] = noBreak[i].getLength();
                i++;
            }
        }
        if (second != null) {
            iter = second.listIterator();
            while (iter.hasNext()) {
                noBreak[i] = (UnresolvedListElementWithLength)iter.next();
                noBreakLengths[i] = noBreak[i].getLength();
                i++;
            }
        }

        //Add pending elements from higher level FOs
        if (breakPoss != null) {
            if (breakPoss.getPendingAfterMarks() != null) {
                if (LOG.isTraceEnabled()) {
                    LOG.trace("    adding pending before break: "
                            + breakPoss.getPendingAfterMarks());
                }
                first.addAll(0, breakPoss.getPendingAfterMarks());
            }
            if (breakPoss.getPendingBeforeMarks() != null) {
                if (LOG.isTraceEnabled()) {
                    LOG.trace("    adding pending after break: "
                            + breakPoss.getPendingBeforeMarks());
                }
                second.addAll(0, breakPoss.getPendingBeforeMarks());
            }
        }
        if (LOG.isTraceEnabled()) {
            LOG.trace("before: " + first);
            LOG.trace("  break: " + breakPoss);
            LOG.trace("after: " + second);
            LOG.trace("NO-BREAK: " + toString(noBreak, noBreakLengths));
        }

        if (first != null) {
            firstPart = new UnresolvedListElementWithLength[first.size()];
            firstPartLengths = new MinOptMax[firstPart.length];
            first.toArray(firstPart);
            for (i = 0; i < firstPart.length; i++) {
                firstPartLengths[i] = firstPart[i].getLength();
            }
        }
        this.breakPoss = breakPoss;
        if (second != null) {
            secondPart = new UnresolvedListElementWithLength[second.size()];
            secondPartLengths = new MinOptMax[secondPart.length];
            second.toArray(secondPart);
            for (i = 0; i < secondPart.length; i++) {
                secondPartLengths[i] = secondPart[i].getLength();
            }
        }
        resolve();
    }

    private String toString(Object[] arr1, Object[] arr2) {
        if (arr1.length != arr2.length) {
            throw new IllegalArgumentException("The length of both arrays must be equal");
        }
        StringBuffer sb = new StringBuffer("[");
        for (int i = 0; i < arr1.length; i++) {
            if (i > 0) {
                sb.append(", ");
            }
            sb.append(String.valueOf(arr1[i]));
            sb.append("/");
            sb.append(String.valueOf(arr2[i]));
        }
        sb.append("]");
        return sb.toString();
    }

    private void removeConditionalBorderAndPadding(
            UnresolvedListElement[] elems, MinOptMax[] lengths, boolean reverse) {
        for (int i = 0; i < elems.length; i++) {
            int effIndex;
            if (reverse) {
                effIndex = elems.length - 1 - i;
            } else {
                effIndex = i;
            }
            if (elems[effIndex] instanceof BorderOrPaddingElement) {
                BorderOrPaddingElement bop = (BorderOrPaddingElement)elems[effIndex];
                if (bop.isConditional() && !(bop.isFirst() || bop.isLast())) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Nulling conditional element: " + bop);
                    }
                    lengths[effIndex] = null;
                }
            }
        }
        if (LOG.isTraceEnabled() && elems.length > 0) {
            LOG.trace("-->Resulting list: " + toString(elems, lengths));
        }
    }

    private void performSpaceResolutionRule1(UnresolvedListElement[] elems, MinOptMax[] lengths,
            boolean reverse) {
        for (int i = 0; i < elems.length; i++) {
            int effIndex;
            if (reverse) {
                effIndex = elems.length - 1 - i;
            } else {
                effIndex = i;
            }
            if (lengths[effIndex] == null) {
                //Zeroed border or padding doesn't create a fence
                continue;
            } else if (elems[effIndex] instanceof BorderOrPaddingElement) {
                //Border or padding form fences!
                break;
            } else if (!elems[effIndex].isConditional()) {
                break;
            }
            if (LOG.isDebugEnabled()) {
                LOG.debug("Nulling conditional element using 4.3.1, rule 1: " + elems[effIndex]);
            }
            lengths[effIndex] = null;
        }
        if (LOG.isTraceEnabled() && elems.length > 0) {
            LOG.trace("-->Resulting list: " + toString(elems, lengths));
        }
    }

    private void performSpaceResolutionRules2to3(UnresolvedListElement[] elems,
            MinOptMax[] lengths, int start, int end) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("rule 2-3: " + start + "-" + end);
        }
        SpaceElement space;
        int remaining;

        //Rule 2 (4.3.1, XSL 1.0)
        boolean hasForcing = false;
        remaining = 0;
        for (int i = start; i <= end; i++) {
            if (lengths[i] == null) {
                continue;
            }
            remaining++;
            space = (SpaceElement)elems[i];
            if (space.isForcing()) {
                hasForcing = true;
                break;
            }
        }
        if (remaining == 0) {
            return; //shortcut
        }
        if (hasForcing) {
            for (int i = start; i <= end; i++) {
                if (lengths[i] == null) {
                    continue;
                }
                space = (SpaceElement)elems[i];
                if (!space.isForcing()) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Nulling non-forcing space-specifier using 4.3.1, rule 2: "
                                + elems[i]);
                    }
                    lengths[i] = null;
                }
            }
            return; //If rule is triggered skip rule 3
        }

        //Rule 3 (4.3.1, XSL 1.0)
        //Determine highes precedence
        int highestPrecedence = Integer.MIN_VALUE;
        for (int i = start; i <= end; i++) {
            if (lengths[i] == null) {
                continue;
            }
            space = (SpaceElement)elems[i];
            highestPrecedence = Math.max(highestPrecedence, space.getPrecedence());
        }
        if (highestPrecedence != 0 && LOG.isDebugEnabled()) {
            LOG.debug("Highest precedence is " + highestPrecedence);
        }
        //Suppress space-specifiers with lower precedence
        remaining = 0;
        int greatestOptimum = Integer.MIN_VALUE;
        for (int i = start; i <= end; i++) {
            if (lengths[i] == null) {
                continue;
            }
            space = (SpaceElement)elems[i];
            if (space.getPrecedence() != highestPrecedence) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Nulling space-specifier with precedence "
                            + space.getPrecedence() + " using 4.3.1, rule 3: "
                            + elems[i]);
                }
                lengths[i] = null;
            } else {
                greatestOptimum = Math.max(greatestOptimum, space.getLength().getOpt());
                remaining++;
            }
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("Greatest optimum: " + greatestOptimum);
        }
        if (remaining <= 1) {
            return;
        }
        //Suppress space-specifiers with smaller optimum length
        remaining = 0;
        for (int i = start; i <= end; i++) {
            if (lengths[i] == null) {
                continue;
            }
            space = (SpaceElement)elems[i];
            if (space.getLength().getOpt() < greatestOptimum) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Nulling space-specifier with smaller optimum length "
                            + "using 4.3.1, rule 3: "
                            + elems[i]);
                }
                lengths[i] = null;
            } else {
                remaining++;
            }
        }
        if (remaining <= 1) {
            return;
        }
        //Construct resolved space-specifier from the remaining spaces
        int min = Integer.MIN_VALUE;
        int max = Integer.MAX_VALUE;
        for (int i = start; i <= end; i++) {
            if (lengths[i] == null) {
                continue;
            }
            space = (SpaceElement)elems[i];
            min = Math.max(min, space.getLength().getMin());
            max = Math.min(max, space.getLength().getMax());
            if (remaining > 1) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Nulling non-last space-specifier using 4.3.1, rule 3, second part: "
                            + elems[i]);
                }
                lengths[i] = null;
                remaining--;
            } else {
                lengths[i] = MinOptMax.getInstance(min, lengths[i].getOpt(), max);
            }
        }

        if (LOG.isTraceEnabled() && elems.length > 0) {
            LOG.trace("Remaining spaces: " + remaining);
            LOG.trace("-->Resulting list: " + toString(elems, lengths));
        }
    }

    private void performSpaceResolutionRules2to3(UnresolvedListElement[] elems,
            MinOptMax[] lengths) {
        int start = 0;
        int i = start;
        while (i < elems.length) {
            if (elems[i] instanceof SpaceElement) {
                while (i < elems.length) {
                    if (elems[i] == null || elems[i] instanceof SpaceElement) {
                        i++;
                    } else {
                        break;
                    }
                }
                performSpaceResolutionRules2to3(elems, lengths, start, i - 1);
            }
            i++;
            start = i;
        }
    }

    private boolean hasFirstPart() {
        return firstPart != null && firstPart.length > 0;
    }

    private boolean hasSecondPart() {
        return secondPart != null && secondPart.length > 0;
    }

    private void resolve() {
        if (breakPoss != null) {
            if (hasFirstPart()) {
                removeConditionalBorderAndPadding(firstPart, firstPartLengths, true);
                performSpaceResolutionRule1(firstPart, firstPartLengths, true);
                performSpaceResolutionRules2to3(firstPart, firstPartLengths);
            }
            if (hasSecondPart()) {
                removeConditionalBorderAndPadding(secondPart, secondPartLengths, false);
                performSpaceResolutionRule1(secondPart, secondPartLengths, false);
                performSpaceResolutionRules2to3(secondPart, secondPartLengths);
            }
            if (noBreak != null) {
                performSpaceResolutionRules2to3(noBreak, noBreakLengths);
            }
        } else {
            if (isFirst) {
                removeConditionalBorderAndPadding(secondPart, secondPartLengths, false);
                performSpaceResolutionRule1(secondPart, secondPartLengths, false);
            }
            if (isLast) {
                removeConditionalBorderAndPadding(firstPart, firstPartLengths, true);
                performSpaceResolutionRule1(firstPart, firstPartLengths, true);
            }

            if (hasFirstPart()) {
                //Now that we've handled isFirst/isLast conditions, we need to look at the
                //active part in its normal order so swap it back.
                LOG.trace("Swapping first and second parts.");
                UnresolvedListElementWithLength[] tempList;
                MinOptMax[] tempLengths;
                tempList = secondPart;
                tempLengths = secondPartLengths;
                secondPart = firstPart;
                secondPartLengths = firstPartLengths;
                firstPart = tempList;
                firstPartLengths = tempLengths;
                if (hasFirstPart()) {
                    throw new IllegalStateException("Didn't expect more than one parts in a"
                            + "no-break condition.");
                }
            }
            performSpaceResolutionRules2to3(secondPart, secondPartLengths);
        }
    }

    private MinOptMax sum(MinOptMax[] lengths) {
        MinOptMax sum = MinOptMax.ZERO;
        for (int i = 0; i < lengths.length; i++) {
            if (lengths[i] != null) {
                sum = sum.plus(lengths[i]);
            }
        }
        return sum;
    }

    private void generate(ListIterator iter) {
        MinOptMax spaceBeforeBreak = sum(firstPartLengths);
        MinOptMax spaceAfterBreak = sum(secondPartLengths);

        boolean hasPrecedingNonBlock = false;
        if (breakPoss != null) {
            if (spaceBeforeBreak.isNonZero()) {
                iter.add(new KnuthPenalty(0, KnuthPenalty.INFINITE, false, null, true));
                iter.add(new KnuthGlue(spaceBeforeBreak, null, true));
                if (breakPoss.isForcedBreak()) {
                    //Otherwise, the preceding penalty and glue will be cut off
                    iter.add(new KnuthBox(0, null, true));
                }
            }
            iter.add(new KnuthPenalty(breakPoss.getPenaltyWidth(), breakPoss.getPenaltyValue(),
                    false, breakPoss.getBreakClass(),
                    new SpaceHandlingBreakPosition(this, breakPoss), false));
            if (breakPoss.getPenaltyValue() <= -KnuthPenalty.INFINITE) {
                return; //return early. Not necessary (even wrong) to add additional elements
            }

            // No break
            // TODO: We can't use a MinOptMax for glue2,
            // because min <= opt <= max is not always true - why?
            MinOptMax noBreakLength = sum(noBreakLengths);
            MinOptMax spaceSum = spaceBeforeBreak.plus(spaceAfterBreak);
            int glue2width = noBreakLength.getOpt() - spaceSum.getOpt();
            int glue2stretch = noBreakLength.getStretch() - spaceSum.getStretch();
            int glue2shrink = noBreakLength.getShrink() - spaceSum.getShrink();

            if (glue2width != 0 || glue2stretch != 0 || glue2shrink != 0) {
                iter.add(new KnuthGlue(glue2width, glue2stretch, glue2shrink, null, true));
            }
        } else {
            if (spaceBeforeBreak.isNonZero()) {
                throw new IllegalStateException("spaceBeforeBreak should be 0 in this case");
            }
        }
        Position pos = null;
        if (breakPoss == null) {
            pos = new SpaceHandlingPosition(this);
        }
        if (spaceAfterBreak.isNonZero() || pos != null) {
            iter.add(new KnuthBox(0, pos, true));
        }
        if (spaceAfterBreak.isNonZero()) {
            iter.add(new KnuthPenalty(0, KnuthPenalty.INFINITE, false, null, true));
            iter.add(new KnuthGlue(spaceAfterBreak, null, true));
            hasPrecedingNonBlock = true;
        }
        if (isLast && hasPrecedingNonBlock) {
            //Otherwise, the preceding penalty and glue will be cut off
            iter.add(new KnuthBox(0, null, true));
        }
    }

    /**
     * Position class for break possibilities. It is used to notify layout manager about the
     * effective spaces and conditional lengths.
     */
    public static class SpaceHandlingBreakPosition extends Position {

        private SpaceResolver resolver;
        private Position originalPosition;

        /**
         * Main constructor.
         * @param resolver the space resolver that provides the info about the actual situation
         * @param breakPoss the original break possibility that creates this Position
         */
        public SpaceHandlingBreakPosition(SpaceResolver resolver, BreakElement breakPoss) {
            super(null);
            this.resolver = resolver;
            this.originalPosition = breakPoss.getPosition();
            //Unpack since the SpaceHandlingBreakPosition is a non-wrapped Position, too
            while (this.originalPosition instanceof NonLeafPosition) {
                this.originalPosition = this.originalPosition.getPosition();
            }
        }

        /** @return the space resolver */
        public SpaceResolver getSpaceResolver() {
            return this.resolver;
        }

        /**
         * Notifies all affected layout managers about the current situation in the part to be
         * handled for area generation.
         * @param isBreakSituation true if this is a break situation.
         * @param side defines to notify about the situation whether before or after the break.
         *             May be null if isBreakSituation is null.
         */
        public void notifyBreakSituation(boolean isBreakSituation, RelSide side) {
            if (isBreakSituation) {
                if (RelSide.BEFORE == side) {
                    for (int i = 0; i < resolver.secondPart.length; i++) {
                        resolver.secondPart[i].notifyLayoutManager(resolver.secondPartLengths[i]);
                    }
                } else {
                    for (int i = 0; i < resolver.firstPart.length; i++) {
                        resolver.firstPart[i].notifyLayoutManager(resolver.firstPartLengths[i]);
                    }
                }
            } else {
                for (int i = 0; i < resolver.noBreak.length; i++) {
                    resolver.noBreak[i].notifyLayoutManager(resolver.noBreakLengths[i]);
                }
            }
        }

        /** {@inheritDoc} */
        public String toString() {
            StringBuffer sb = new StringBuffer();
            sb.append("SpaceHandlingBreakPosition(");
            sb.append(this.originalPosition);
            sb.append(")");
            return sb.toString();
        }

        /**
         * @return the original Position instance set at the BreakElement that this Position was
         *         created for.
         */
        public Position getOriginalBreakPosition() {
            return this.originalPosition;
        }

        /** {@inheritDoc} */
        public Position getPosition() {
            return originalPosition;
        }

    }

    /**
     * Position class for no-break situations. It is used to notify layout manager about the
     * effective spaces and conditional lengths.
     */
    public static class SpaceHandlingPosition extends Position {

        private SpaceResolver resolver;

        /**
         * Main constructor.
         * @param resolver the space resolver that provides the info about the actual situation
         */
        public SpaceHandlingPosition(SpaceResolver resolver) {
            super(null);
            this.resolver = resolver;
        }

        /** @return the space resolver */
        public SpaceResolver getSpaceResolver() {
            return this.resolver;
        }

        /**
         * Notifies all affected layout managers about the current situation in the part to be
         * handled for area generation.
         */
        public void notifySpaceSituation() {
            if (resolver.breakPoss != null) {
                throw new IllegalStateException("Only applicable to no-break situations");
            }
            for (int i = 0; i < resolver.secondPart.length; i++) {
                resolver.secondPart[i].notifyLayoutManager(resolver.secondPartLengths[i]);
            }
        }

        /** {@inheritDoc} */
        public String toString() {
            return "SpaceHandlingPosition";
        }
    }

    /**
     * Resolves unresolved elements applying the space resolution rules defined in 4.3.1.
     * @param elems the element list
     */
    public static void resolveElementList(List elems) {
        if (LOG.isTraceEnabled()) {
            LOG.trace(elems);
        }
        boolean first = true;
        boolean last = false;
        boolean skipNextElement = false;
        List unresolvedFirst = new java.util.ArrayList();
        List unresolvedSecond = new java.util.ArrayList();
        List currentGroup;
        ListIterator iter = elems.listIterator();
        while (iter.hasNext()) {
            ListElement el = (ListElement)iter.next();
            if (el.isUnresolvedElement()) {
                if (LOG.isTraceEnabled()) {
                    LOG.trace("unresolved found: " + el + " " + first + "/" + last);
                }
                BreakElement breakPoss = null;
                //Clear temp lists
                unresolvedFirst.clear();
                unresolvedSecond.clear();
                //Collect groups
                if (el instanceof BreakElement) {
                    breakPoss = (BreakElement)el;
                    currentGroup = unresolvedSecond;
                } else {
                    currentGroup = unresolvedFirst;
                    currentGroup.add(el);
                }
                iter.remove();
                last = true;
                skipNextElement = true;
                while (iter.hasNext()) {
                    el = (ListElement)iter.next();
                    if (el instanceof BreakElement && breakPoss != null) {
                        skipNextElement = false;
                        last = false;
                        break;
                    } else if (currentGroup == unresolvedFirst && (el instanceof BreakElement)) {
                        breakPoss = (BreakElement)el;
                        iter.remove();
                        currentGroup = unresolvedSecond;
                    } else if (el.isUnresolvedElement()) {
                        currentGroup.add(el);
                        iter.remove();
                    } else {
                        last = false;
                        break;
                    }
                }
                //last = !iter.hasNext();
                if (breakPoss == null && unresolvedSecond.isEmpty() && !last) {
                    LOG.trace("Swap first and second parts in no-break condition,"
                            + " second part is empty.");
                    //The first list is reversed, so swap if this shouldn't happen
                    List swapList = unresolvedSecond;
                    unresolvedSecond = unresolvedFirst;
                    unresolvedFirst = swapList;
                }

                LOG.debug("----start space resolution (first=" + first + ", last=" + last + ")...");
                SpaceResolver resolver = new SpaceResolver(
                        unresolvedFirst, breakPoss, unresolvedSecond, first, last);
                if (!last) {
                    iter.previous();
                }
                resolver.generate(iter);
                if (!last && skipNextElement) {
                    iter.next();
                }
                LOG.debug("----end space resolution.");
            }
            first = false;
        }
    }

    /**
     * Inspects an effective element list and notifies all layout managers about the state of
     * the spaces and conditional lengths.
     * @param effectiveList the effective element list
     * @param startElementIndex index of the first element in the part to be processed
     * @param endElementIndex index of the last element in the part to be processed
     * @param prevBreak index of the the break possibility just before this part (used to
     *                  identify a break condition, lastBreak <= 0 represents a no-break condition)
     */
    public static void performConditionalsNotification(List effectiveList,
            int startElementIndex, int endElementIndex, int prevBreak) {
        KnuthElement el = null;
        if (prevBreak > 0) {
            el = (KnuthElement)effectiveList.get(prevBreak);
        }
        SpaceResolver.SpaceHandlingBreakPosition beforeBreak = null;
        SpaceResolver.SpaceHandlingBreakPosition afterBreak = null;
        if (el != null && el.isPenalty()) {
            Position pos = el.getPosition();
            if (pos instanceof SpaceResolver.SpaceHandlingBreakPosition) {
                beforeBreak = (SpaceResolver.SpaceHandlingBreakPosition)pos;
                beforeBreak.notifyBreakSituation(true, RelSide.BEFORE);
            }
        }
        el = (KnuthElement)effectiveList.get(endElementIndex);
        if (el != null && el.isPenalty()) {
            Position pos = el.getPosition();
            if (pos instanceof SpaceResolver.SpaceHandlingBreakPosition) {
                afterBreak = (SpaceResolver.SpaceHandlingBreakPosition)pos;
                afterBreak.notifyBreakSituation(true, RelSide.AFTER);
            }
        }
        for (int i = startElementIndex; i <= endElementIndex; i++) {
            Position pos = ((KnuthElement)effectiveList.get(i)).getPosition();
            if (pos instanceof SpaceResolver.SpaceHandlingPosition) {
                ((SpaceResolver.SpaceHandlingPosition)pos).notifySpaceSituation();
            } else if (pos instanceof SpaceResolver.SpaceHandlingBreakPosition) {
                SpaceResolver.SpaceHandlingBreakPosition noBreak;
                noBreak = (SpaceResolver.SpaceHandlingBreakPosition)pos;
                if (noBreak != beforeBreak && noBreak != afterBreak) {
                    noBreak.notifyBreakSituation(false, null);
                }
            }
        }
    }

}


text:
module Raven
  class Interface
    def initialize(attributes = nil)
      attributes&.each do |attr, value|
        public_send "#{attr}=", value
      end

      yield self if block_given?
    end

    def self.inherited(klass)
      name = klass.name.split("::").last.downcase.gsub("interface", "")
      registered[name.to_sym] = klass
      super
    end

    def self.registered
      @@registered ||= {} # rubocop:disable Style/ClassVars
    end

    def to_hash
      Hash[instance_variables.map { |name| [name[1..-1].to_sym, instance_variable_get(name)] }]
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
template <class TClient>
class SocketServerBase : public thread::Thread {
public:
	explicit SocketServerBase(int maxConnections, int port)
		: Thread(__FUNCTION__)
		, m_MaxConnections(maxConnections)
		, m_Port(port)
		, m_Pool(maxConnections)
	{ }

	virtual ~SocketServerBase() { }

protected:

	virtual void OnConnection(TClient* client)
	{
		client->Create();
	}

	virtual void Process()
	{
		sockets::SocketAddress serverA(AF_INET);
		serverA.SetAddress("127.0.0.1");
		serverA.SetPort(m_Port);
		sockets::Socket serverS;

		if (serverS.Open() && serverS.Bind(serverA)) {
			Log(LOG_INFO, __FUNCTION__ " listening");
			while (serverS.Listen(m_MaxConnections)) {
				sockets::Socket connectedS;
				sockets::SocketAddress connectedA(AF_INET);
				if (connectedS.Accept(serverS, connectedA))
				{
					Log(LOG_INFO, __FUNCTION__ " accepted");
					TClient* sc = m_Pool.Get();
					if (sc != nullptr)
					{
						sc->SetConnection(connectedS, connectedA);
						OnConnection(sc);
						Log(LOG_INFO, __FUNCTION__ " client spawned");
					}
					else
					{
						Log(LOG_WARNING, __FUNCTION__ " client not spawned");
					}
				}
			}
		}
	}

	int m_MaxConnections;
	int m_Port;

	thread::ThreadPool<TClient> m_Pool;
};

#endif // SOCKETSERVERBASE_H_


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

<title>Java Security Architecture: -</title>
<link rel="stylesheet" type="text/css" href="../../../../technotes/css/guide.css" />

Documentation Contents

CONTENTS | PREV | NEXT

6 Security
Management

 6.1 Managing
Applets and Applications

 Currently, all Java 2 SDK
system code invokes SecurityManager methods to check the policy
currently in effect and perform access control checks. There is
typically a security manager (SecurityManager implementation)
installed whenever an applet is running; the appletviewer and most
browsers, including those from Netscape and Microsoft, install a
security manager.

 A security manager is
not automatically installed when an application is
running. To apply the same security policy to an application found
on the local file system as to downloaded applets, either the user
running the application must invoke the Java Virtual Machine with
the new "-Djava.security.manager" command-line argument
(which sets the value of the java.security.manager
property), as in

    java -Djava.security.manager  SomeApp

 or the application itself
must call the setSecurityManager method in the
java.lang.System class to install a security manager.

 It is possible to
specify on the command line a particular security manager to be
utilized, by following "-Djava.security.manager" with an
equals and the name of the class to be used as the security
manager, as in

    java -Djava.security.manager=COM.abc.MySecMgr  SomeApp

 If no security manager is
specified, the built-in default security manager is utilized
(unless the application installs a different security manager). All
of the following are equivalent and result in usage of the default
security manager:

    java -Djava.security.manager  SomeApp
    java -Djava.security.manager=""  SomeApp
    java -Djava.security.manager=default  SomeApp

 Java 2 SDK includes a
property named java.class.path. Classes that are stored on
the local file system but should not be treated as base classes
(e.g., classes built into the SDK) should be on this path. Classes
on this path are loaded with a secure class loader and are thus
subjected to the security policy being enforced.

 There is also a
"-Djava.security.policy" command-line argument whose usage
determines what policy files are utilized. This command-line
argument is described in detail in the "Default System and User
Policy Files" section. Basically, if you don't include
"-Djava.security.policy" on the command line, then the
policy files specified in the security properties file will be
used.

 You can use a
"-Djava.security.policy" command-line argument to specify
an additional or a different policy file when invoking execution of
an application. For example, if you type the following, where
pURL is a URL specifying the location of a policy file,
then the specified policy file will be loaded in addition to all
the policy files specified in the security properties file:

    java -Djava.security.manager -Djava.security.policy=pURL SomeApp

 If you instead type the
following command, using a double equals, then just the specified
policy file will be used; all others will be ignored:

java -Djava.security.manager -Djava.security.policy==pURL SomeApp

 6.2
SecurityManager versus AccessController

 The new access control
mechanism is fully backward compatible. For example, all
check methods in SecurityManager are still supported,
although most of their implementations are changed to call the new
SecurityManager checkPermission method, whose default
implementation calls the AccessController
checkPermission method. Note that certain internal
security checks may stay in the SecurityManager class, unless it
can be parameterized.

 We have not at this
time revised any system code to call AccessController instead of
calling SecurityManager (and checking for the existence of a
classloader), because of the potential of existing third-party
applications that subclass the SecurityManager and customize the
check methods. In fact, we added a new method
SecurityManager.checkPermission that by default simply
invokes AccessController.checkPermission.

 To understand the
relationship between SecurityManager and AccessController, it is
sufficient to note that SecurityManager represents the concept of a
central point of access control, while AccessController implements
a particular access control algorithm, with special features such
as the doPrivileged method. By keeping SecurityManager
up to date, we maintain backward compatibility (e.g., for those
applications that have written their own security manager classes
based on earlier versions of the JDK) and flexibility (e.g., for
someone wanting to customize the security model to implement
mandatory access control or multilevel security). By providing
AccessController, we build in the algorithm that we believe is the
most restrictive and that relieves the typical programmer from the
burden of having to write extensive security code in most
scenarios.

 We encourage the use
of AccessController in application code, while customization of a
security manager (via subclassing) should be the last resort and
should be done with extreme care. Moreover, a customized security
manager, such as one that always checks the time of the day before
invoking standard security checks, could and should utilize the
algorithm provided by AccessController whenever appropriate.

One thing to remember is that, when you implement your own SecurityManager, you should install it as trusted software and grant it java.security.AllPermission. There are several ways to do this:

You can install your SecurityManager as an extension, because all extensions are granted AllPermission by default. For more information, see Lesson: Creating and Using Extensions.

You can adjust the policy file to grant AllPermission to your SecurityManager. For more information, see Default Policy Implementation and Policy File Syntax.

 6.3 Auxiliary
Tools

 This section briefly
describes the usage of three tools that assist in the deployment of
the new security features. These tools may be packaged together in
the future.

6.3.1 The Key and Certificate Management Tool

 keytool is a key
and certificate management utility. It enables users to administer
their own public/private key pairs and associated certificates for
use in self-authentication (where the user authenticates
himself/herself to other users/services) or data integrity and
authentication services, using digital signatures. The
authentication information includes both a sequence (chain) of
X.509 certificates, and an associated private key, which can be
referenced by a so-called "alias". This tool also manages
certificates (that are "trusted" by the user), which are
stored in the same database as the authentication information, and
can be referenced by an "alias".

 keytool stores
the keys and certificates in a so-called keystore. The
default keystore implementation implements the keystore as a file.
It protects private keys with a password.

 The chains of X.509
certificates are provided by organizations called Certification
Authorities, or CAs. Identities (including CAs) use their private
keys to authenticate their association with objects (such as with
channels which are secured using SSL), with archives of code they
signed, or (for CAs) with X.509 certificates they have issued. As a
bootstrapping tool, certificates generated using the -genkey
command may be used until a Certification Authority returns a
certificate chain.

 The private keys in
this database are always stored in encrypted form, to make it
difficult to disclose these private keys inappropriately. A
password is required to access or modify the database. These
private keys are encrypted using the "password", which
should be several words long. If the password is lost, those
authentication keys cannot be recovered.

 In fact, each private
key in the keystore can be protected using its own individual
password, which may or may not be the same as the password that
protects the keystore's overall integrity.

 This tool is
(currently) intended to be used from the command line, where one
simply types "keytool" as a shell prompt. keytool is
a script that executes the appropriate Java classes and is built
together with the SDK.

 The command line
options for each command may be provided in any order. Typing an
incorrect option or typing "keytool -help" will cause the
tool's usage to be summarized on the output device (such as a
shell window), as given below.

% keytool -help
KeyTool usage:

-certreq     [-v] [-alias <alias>] [-sigalg <sigalg>]
             [-file <certreq_file>] [-keypass <keypass>]
             [-keystore <keystore>] [-storepass <storepass>]
             [-storetype <i>storetype</i>]

-delete      [-v] -alias <alias>
             [-keystore <keystore>] [-storepass <storepass>]
             [-storetype <i>storetype</i>]

-export      [-v] [rfc] [-alias <alias>] [-file <cert_file>]
             [-keystore <keystore>] [-storepass <storepass>]
             [-storetype <i>storetype</i>]

-genkey      [-v] [-alias <alias>] [-keyalg <keyalg>]
             [-keysize <keysize>] [-sigalg <sigalg>]
             [-dname <distinguished_name>] [-validity <valDays>]
             [-keypass <keypass>] [-keystore <keystore>]
             [-storepass <storepass>]
             [-storetype <i>storetype</i>]

-help

-identitydb  [-v] [-file <idb_file>] [-keystore <keystore>]
             [-storepass <storepass>]
             [-storetype <i>storetype</i>]

-import      [-v] [-noprompt] [-alias <alias>]
             [-file <cert_file>] [-keypass <keypass>]
             [-keystore <keystore>] [-storepass <storepass>]
             [-storetype <i>storetype</i>]

-keyclone    [-v] [-alias <alias>] -dest <dest_alias>
             [-keypass <keypass>] [-new <new_keypass>]
             [-keystore <keystore>] [-storepass <storepass>]
             [-storetype <i>storetype</i>]

-keypasswd   [-v] [-alias <alias>]
             [-keypass <old_keypass>] [-new <new_keypass>]
             [-keystore <keystore>] [-storepass <storepass>]
             [-storetype <i>storetype</i>]

-list        [-v | -rfc] [-alias <alias>]
             [-keystore <keystore>] [-storepass <storepass>]
             [-storetype <i>storetype</i>]

-printcert   [-v] [-file <cert_file>]

-selfcert    [-v] [-alias <alias>] [-sigalg <sigalg>]
             [-dname <distinguished_name>] [-validity <valDays>]
             [-keypass <keypass>] [-keystore <keystore>]
             [-storepass <storepass>]
             [-storetype <i>storetype</i>]

-storepasswd  [-v] [-new <new_storepass>]
             [-keystore <keystore>] [-storepass <storepass>]
              [-storetype <i>storetype</i>]

6.3.2 PolicyTool

 The PolicyTool is
a graphical user interface (illustrated below with a screen shot)
that assists a user (such as a system administrator) in specifying,
generating, editing, exporting, or importing a security policy. The
tool is invoked from the command line as policytool.
This again is a script built with the SDK that invokes the
appropriate (non-public) implementation classes.

 See the
PolicyTool documentation for usage information and examples
with up-to-date screen shots. The documentation can be found in the
policytool.html file in the

/docs/technotes/tools/unix/

 or

/docs/technotes/tools/windows/

 directory in the
directory in which the SDK was installed (where the file separators
are actually backslashes on Windows systems).

6.3.3 The JAR Signing and Verification Tool

 The jarsigner tool
can be used to digitally sign Java archives (JAR files), and to
verify such signatures. This tool, like the PolicyTool,
depends on the keystore that is managed by the keytool. Its
usage is quickly summarized below.

% jarsigner
Usage: jarsigner [options] jar-file alias
       jarsigner -verify [options] jar-file
  [-keystore <url>]         keystore file location
  [-storepass <password>]   password for keystore integrity
  [-keypass <password>]     password for private key (if different)
  [-sigfile <file>]         name of .SF/.DSA file
  [-signedjar <file>]       name of signed JAR file
  [-verify]                 verify a signed JAR file
  [-verbose]                verbose output when signing/verifying
  [-certs]          display certificates when verbose and verifying
  [-internalsf]             include .SF file inside signature block
  [-sectionsonly]           don't compute hash of entire manifest

 Again, this tool is a
script built with the SDK. Note that it is expected that this tool
and the existing jar tool script may be merged in the near
future to form a single command-line primitive to create JARs,
either signed or unsigned.

CONTENTS | PREV | NEXT

Copyright
© 1993, 2015, Oracle and/or its affiliates. All rights
reserved.

Contact
Us


text:
{% extends "mobileadmin/mobile_safari/registration/password_change_form.html" %}
{% load i18n %}

{% block title %}{% trans 'Password change successful' %}{% endblock %}

{% block content %}

{% trans 'Your password was changed.' %}

{% endblock %}


text:
from setuptools import setup, find_packages

setup(
    name='django-db-cascade',
    version='0.1.5',
    description='Optionally use postgres db ON CASCADE DELETE on django foreign keys',
    url='http://github.com/nickstefan/django-db-cascade',
    author='Nick Stefan',
    author_email='nickstefan12@gmail.com',
    license='MIT',
    packages=find_packages(),
    install_requires=[
        'Django >= 1.8',
        'psycopg2 >= 2.5'
    ],
    classifiers=[
        'Framework :: Django',
        'Topic :: Database',
    ],
    zip_safe=False
)


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.IO;
using Xunit;

namespace Tests.System.IO
{
    public class PathInternalTests
    {
        public void CheckInvalidPathChars_ThrowsOnNull(string path, string expected)
        {
            Assert.Throws<ArgumentNullException>(() => PathInternal.CheckInvalidPathChars(null));
        }
    }
}


text:
import * as React from 'react';
import { shouldComponentUpdate } from 'react-immutable-render-mixin';
import { Link } from 'react-router-dom';
import { fromJS, Map, List as ImmutableList } from 'immutable';

import { withState } from 'recompose';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemText from '@material-ui/core/ListItemText';
import ListItemSecondaryAction from '@material-ui/core/ListItemSecondaryAction';
import Avatar from '@material-ui/core/Avatar';
import IconButton from '@material-ui/core/IconButton';
import ExpandLess from '@material-ui/icons/ExpandLess';
import ExpandMore from '@material-ui/icons/ExpandMore';
import Collapse from '@material-ui/core/Collapse';

import pathToRootWikiGroupTree from '../utils/pathToRootWikiGroupTree';
import getRootWikiHref from '../utils/getRootWikiHref';
import getWikisHref from '../utils/getWikisHref';

function defaultGetHrefFunc() {
  return '';
}

export function getRootWikiGroupTreeListItemsIter(
  rootWikiGroupTree,
  queryRootWikiGroupTree,
  getHrefFunc = defaultGetHrefFunc,
  path = [],
  depth = 0,
  base = Map()
) {
  if (Map.isMap(rootWikiGroupTree)) {
    const name = rootWikiGroupTree.get('name');
    const children = rootWikiGroupTree.get('children');
    const finalPath = path.concat(name);
    const nestedItems = children
      ? getRootWikiGroupTreeListItemsIter(
          children,
          queryRootWikiGroupTree,
          getHrefFunc,
          finalPath,
          depth + 1,
          base
        ).toJS()
      : null;
    const href = getHrefFunc(pathToRootWikiGroupTree(finalPath));
    const value = href;
    const enhance = withState('open', 'setOpen', false);
    const Items = enhance(({ open, setOpen }) => {
      return (
        <React.Fragment>
          <ListItem
            button
            component={Link}
            replace={true}
            to={href}
            style={{ paddingLeft: 12 * depth + 5 }}
          >
            <ListItemText primary={name} />
            {nestedItems ? (
              <ListItemSecondaryAction
                onClick={() => {
                  setOpen(o => !o);
                }}
              >
                <IconButton>{open ? <ExpandLess /> : <ExpandMore />}</IconButton>
              </ListItemSecondaryAction>
            ) : null}
          </ListItem>
          {nestedItems ? (
            <Collapse component="li" in={open} timeout="auto" unmountOnExit>
              <List disablePadding>{nestedItems}</List>
            </Collapse>
          ) : null}
        </React.Fragment>
      );
    });
    return <Items key={value} />;
  } else if (ImmutableList.isList(rootWikiGroupTree)) {
    return rootWikiGroupTree.map(node => {
      return getRootWikiGroupTreeListItemsIter(
        node,
        queryRootWikiGroupTree,
        getHrefFunc,
        path,
        depth,
        base
      );
    });
  } else {
    return null;
  }
}

export function getRootWikiGroupTreeListItems(
  rootWikiGroupTree,
  queryRootWikiGroupTree,
  getHrefFunc
) {
  return getRootWikiGroupTreeListItemsIter(
    rootWikiGroupTree,
    queryRootWikiGroupTree,
    getHrefFunc,
    [],
    0,
    rootWikiGroupTree
  ).toJS();
}

const _rootWikiGroupTree = fromJS([
  {
    name: '裝備',
    children: [
      {
        name: '武器',
        children: [
          {
            name: '長劍',
          },
          {
            name: '斧',
          },
          {
            name: '槍',
          },
        ],
      },
      {
        name: '防具',
        children: [
          {
            name: '皮甲',
          },
          {
            name: '重甲',
          },
        ],
      },
    ],
  },
  {
    name: '卡片',
    children: [
      {
        name: '法師',
      },
      {
        name: '盜賊',
      },
    ],
  },
  {
    name: '深度測試(一)',
    children: [
      {
        name: '深度測試(二)',
        children: [
          {
            name: '深度測試(三)',
            children: [
              {
                name: '你看見我了!',
              },
            ],
          },
        ],
      },
    ],
  },
]);

class RootWikiGroupTreeList extends React.Component {
  static defaultProps = {
    baseRootWikiGroupTree: _rootWikiGroupTree,
  };

  constructor(props) {
    super(props);
    this.shouldComponentUpdate = shouldComponentUpdate.bind(this);
  }

  getRootWikiHref = () => {
    const { rootWikiId } = this.props;
    return getRootWikiHref(rootWikiId);
  };

  getWikisHref = rootWikiGroupTree => {
    const prefix = this.getRootWikiHref();
    const wikisHref = getWikisHref(rootWikiGroupTree);
    return `${prefix}${wikisHref}`;
  };

  render() {
    const { rootWikiId } = this.props;
    if (!rootWikiId) {
      return
需要建立主維基
;
    }
    const { baseRootWikiGroupTree, queryRootWikiGroupTree } = this.props;
    const rootWikiGroupTreeListItems = getRootWikiGroupTreeListItems(
      baseRootWikiGroupTree,
      queryRootWikiGroupTree,
      this.getWikisHref
    );
    return (

(尚未完成)

        <List>
          <ListItem
            button
            component={Link}
            replace={true}
            to={this.getRootWikiHref()}
            value={this.getRootWikiHref()}
          >
            <Avatar>主</Avatar>
            <ListItemText primary="維基首頁" />
          </ListItem>
          <ListItem
            button
            component={Link}
            replace={true}
            to={this.getWikisHref('all')}
            value={this.getWikisHref('all')}
          >
            <Avatar>全</Avatar>
            <ListItemText primary="全部" />
          </ListItem>
          {rootWikiGroupTreeListItems}
          <ListItem
            button
            component={Link}
            replace={true}
            to={this.getWikisHref('null')}
            value={this.getWikisHref('null')}
          >
            <Avatar>未</Avatar>
            <ListItemText primary="未分類" />
          </ListItem>
        </List>

    );
  }
}

export default RootWikiGroupTreeList;


text:
<resources>
    <string name="app_name">IP控制网关</string>
</resources>


text:
<!doctype html>
<meta charset="utf-8">
<title>CSS Test: will-change: opacity should create a stacking context for inlines.</title>
<link rel="author" title="Philip Rogers" href="mailto:pdr@chromium.org">
<link rel="help" href="https://bugs.chromium.org/p/chromium/issues/detail?id=1119651">
<link rel="help" href="https://drafts.csswg.org/css-will-change/#will-change">
<link rel="match" href="green-square-100-by-100-ref.html">


text:
package com.github.pockethub.android.ui.issue;

import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.github.pockethub.android.R;
import com.github.pockethub.android.core.issue.IssueUtils;
import com.github.pockethub.android.util.AvatarLoader;
import com.github.pockethub.android.util.TypefaceUtils;
import com.meisolsson.githubsdk.model.Issue;

/**
 * Adapter to display a list of dashboard issues
 */
public class DashboardIssueListAdapter extends
        IssueListAdapter<Issue> {

    private int numberPaintFlags;

    /**
     * Create adapter
     *
     * @param avatars
     * @param inflater
     * @param elements
     */
    public DashboardIssueListAdapter(AvatarLoader avatars,
            LayoutInflater inflater, Issue[] elements) {
        super(R.layout.dashboard_issue_item, inflater, elements, avatars);
    }

    @Override
    public long getItemId(final int position) {
        return getItem(position).id();
    }

    @Override
    protected int getNumber(final Issue issue) {
        return (int) issue.number();
    }

    @Override
    protected View initialize(View view) {
        view = super.initialize(view);

        numberPaintFlags = textView(view, 1).getPaintFlags();
        TypefaceUtils.setOcticons(textView(view, 6),
                (TextView) view.findViewById(R.id.tv_comment_icon));
        return view;
    }

    @Override
    protected int[] getChildViewIds() {
        return new int[] { R.id.tv_issue_repo_name, R.id.tv_issue_number,
                R.id.tv_issue_title, R.id.iv_avatar, R.id.tv_issue_creation,
                R.id.tv_issue_comments, R.id.tv_pull_request_icon, R.id.v_label0,
                R.id.v_label1, R.id.v_label2, R.id.v_label3, R.id.v_label4,
                R.id.v_label5, R.id.v_label6, R.id.v_label7 };
    }

    @Override
    protected void update(int position, Issue issue) {
        updateNumber(issue.number(), issue.state(), numberPaintFlags, 1);

        avatars.bind(imageView(3), issue.user());

        String[] segments = issue.url().split("/");
        int length = segments.length;
        if (length >= 4)
            setText(0, segments[length - 4] + '/' + segments[length - 3]);
        else
            setText(0, null);

        setGone(6, !IssueUtils.isPullRequest(issue));

        setText(2, issue.title());

        updateReporter(issue.user().login(), issue.createdAt(), 4);
        setNumber(5, issue.comments());
        updateLabels(issue.labels(), 7);
    }
}


text:
from __future__ import division
import inspect

class error(Exception):
  """ libtbx.python_frame error """

def named(name):
  """ Returns an object representing the frame of the function of the given name.
      This frame will be searched upward from the current frame

      Synopsis:

      from libtbx import pyframe

      def f(i):
        for j in xrange(i):
          g(j)

      def g(j):
        return k(j)

      def k(j):
        f = pyframe.named('f')
        if f.j == 3: ....

      This is particularly useful for conditional breakpoints in the WingIDE debugger.
      Let's say we have a function 'test' which tests a function 'clever_algorithm' and that
      one wants to put a breakpoint in the latter that only triggers
      for one particular test (that we know is going to fail e.g.). Let's say tests are
      identified by a local variable 'idx' in function 'test'. Then we can put a conditional
      breakpoint somewhere in function 'clever_algorithm' like so:

        pyframe.named('test').idx == 5

      The advantage of conditional tests is that they don't require modifying code for
      debugging purposes, which is always a dangerous thing to do as one may inadvertantly
      leave debugging code in.

  """
  f = inspect.currentframe()
  while f.f_code.co_name != name:
    if f.f_back is None:
      raise error("frame '%s' cannot be found among the frames calling the current frame.")
    f = f.f_back
  return frame_locals(f)

def up(n):
  """ Returns an object representing the frame of the function that is n steps up in
      the calling stack, starting from the function that called this function 'up'.
      Thus n=0 corresponds to the function F that called this, n=1 to the function
      that called F, etc.
  """
  f = inspect.currentframe()
  f = f.f_back
  caller_name = f.f_code.co_name
  for i in xrange(n):
    if f is None:
      raise error("asked for the frame %i steps up the function '%s'"
                  " but the calling stack is not that tall.")
    f = f.f_back
  return frame_locals(f)

class frame_locals(object):

  def __init__(self, f):
    self.__dict__.update(f.f_locals)


text:
import mock
import unittest

from .. import BaseApi
from .. import BaseModel
from ..domain import Domain
from ..request_paginator import RequestPaginator

PAGINATOR = 'helpscout.base_api.RequestPaginator'

class TestApi(BaseApi):
    __object__ = BaseModel

class TestBaseApi(unittest.TestCase):

    ENDPOINT = '/endpoint'
    DATA = {'test': 1234}
    REQUEST_TYPE = RequestPaginator.POST

    def new_api(self, endpoint=ENDPOINT, data=DATA, request_type=REQUEST_TYPE,
                singleton=False, session=None, out_type=None):
        return TestApi(
            endpoint, data, request_type, singleton, session, out_type,
        )

    def test_new(self):
        """It should return a new TestApi instance."""
        self.assertIsInstance(self.new_api(), TestApi)

    def test_new_paginator(self):
        """It should return a new API object with a paginator."""
        self.assertIsInstance(self.new_api().paginator, RequestPaginator)

    def test_new_paginator_create(self):
        """It should create the paginator with the proper args."""
        session = 'session'
        with mock.patch.object(RequestPaginator, '__init__') as init:
            init.return_value = None
            self.new_api(session=session)
            init.assert_called_once_with(
                endpoint='https://api.helpscout.net/v1%s' % self.ENDPOINT,
                data=self.DATA,
                output_type=TestApi.__object__.from_api,
                request_type=self.REQUEST_TYPE,
                session=session,
            )

    @mock.patch(PAGINATOR)
    def test_new_paginator_singleton(self, paginator):
        """It should return the record if singleton and found."""
        paginator().call.return_value = [{'id': 9876}]
        res = self.new_api(singleton=True)
        self.assertIsInstance(res, BaseModel)
        self.assertEqual(res.id, 9876)

    @mock.patch(PAGINATOR)
    def test_new_paginator_singleton_not_found(self, paginator):
        """It should return None if singleton and not found."""
        paginator().call.return_value = []
        res = self.new_api(singleton=True)
        self.assertIs(res, None)

    @mock.patch(PAGINATOR)
    def test_new_paginator_singleton_none(self, paginator):
        """It should return None if singleton and return value is None."""
        paginator().call.return_value = None
        res = self.new_api(singleton=True)
        self.assertIs(res, None)

    @mock.patch(PAGINATOR)
    def test_base_api_iterates_paginator(self, paginator):
        """It should pass iteration to the paginator."""
        expect = [BaseModel(id=1), BaseModel(id=2)]
        paginator().call.return_value = expect
        for idx, value in enumerate(self.new_api()):
            self.assertEqual(value, expect[idx])

    @mock.patch(PAGINATOR)
    def test_new_paginator_singleton_out_type(self, paginator):
        """It should return an object of the correct type if defined."""
        paginator().call.return_value = [{'id': 9876}]
        res = self.new_api(singleton=True, out_type=mock.MagicMock())
        self.assertIsInstance(res, mock.MagicMock)

    def test_get_search_domain_domain(self):
        """It should return the input if it is a `Domain` obj."""
        expect = Domain()
        self.assertEqual(BaseApi.get_search_domain(expect), expect)

    def test_get_search_domain_tuple(self):
        """It should return the input if it is a `Domain` obj."""
        expect = [('state', True)]
        with mock.patch.object(Domain, 'from_tuple') as from_tuple:
            res = BaseApi.get_search_domain(expect)
            from_tuple.assert_called_once_with(expect)
            self.assertEqual(res, from_tuple())

    def test_new_object(self):
        """It should return the proper object."""
        expect = 123
        res = BaseApi.new_object({'id': expect})
        self.assertIsInstance(res, BaseModel)
        self.assertEqual(res.id, expect)


text:
from django.shortcuts import render
from django.views.generic import TemplateView

class HomeView(TemplateView):
    template_name = "home.html"

    def get_context_data(self, **kwargs):
        context = super(HomeView, self).get_context_data()

        return context

def robots(request):
    return render(request, "robots.txt", content_type="text/plain")


text:
============
Installation
============

At the command line either via easy_install or pip::

    $ easy_install pylunar
    $ pip install pylunar

Or, if you have virtualenvwrapper installed::

    $ mkvirtualenv pylunar
    $ pip install pylunar


text:
<?php

use App\Service;
use Illuminate\Database\Seeder;

class ServiceHeaderSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        DB::table('service_header')->insert([
            'service_id'    => Service::where('name', 'GitHub')->first()->id,
            'type'          => 'Accept',
            'value'         => 'application/vnd.github.v3+json',
        ]);
    }
}


text:
package org.dasein.cloud.compute;

import org.dasein.util.uom.storage.Megabyte;
import org.dasein.util.uom.storage.Storage;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/**
 * Options for filtering virtual machine products when querying the cloud provider. You may optionally filter on
 * any or all set criteria. If a value has not been set for a specific criterion, it is not included in the filtering
 * process.
 *
Created by Drew Lyall: 04/07/14 15:00 AM

 * @author Drew Lyall
 * @version 2014.08 initial version
 * @since 2014.08
 */
public class VirtualMachineProductFilterOptions{
    private boolean           matchesAny;
    private String            regex;
    private int               cpuCount = 0;
    private Storage<Megabyte> ramSize;
    private String            datacenterId;

    /**
     * Constructs an empty set of filtering options that will force match against any VM Product by default.
     * @return an empty filtering options objects
     */
    public static @Nonnull VirtualMachineProductFilterOptions getInstance() {
        return new VirtualMachineProductFilterOptions(false);
    }

    /**
     * Constructs filter options that will match either any criteria or all criteria, but has no actual criteria
     * associated with it.
     * @param matchesAny true if it is sufficient that just one of the criteria are matched, false if all are needed to be matched
     * @return a newly constructed set of VM Product filtering options
     */
    public static @Nonnull VirtualMachineProductFilterOptions getInstance(boolean matchesAny) {
        return new VirtualMachineProductFilterOptions(matchesAny);
    }

    /**
     * Constructs a filter against a Java regular expression that must match all criteria.
     * @param regex the regular expression to match against the VM Product name or description
     * @return a VM Product filter options object
     */
    public static @Nonnull VirtualMachineProductFilterOptions getInstance(@Nonnull String regex) {
        VirtualMachineProductFilterOptions options = new VirtualMachineProductFilterOptions(false);

        options.regex = regex;
        return options;
    }

    /**
     * Constructs a filter against a Java regular expression that must match criteria as specified
     * @param matchesAny true if it is sufficient that just one of the criteria are matched, false if all are needed to be matched
     * @param regex      the regular expression to match against the VM Product name or description
     * @return a VM Product filter options object
     */
    public static @Nonnull VirtualMachineProductFilterOptions getInstance(boolean matchesAny, @Nonnull String regex){
        VirtualMachineProductFilterOptions options = new VirtualMachineProductFilterOptions(matchesAny);

        options.regex = regex;
        return options;
    }

    private VirtualMachineProductFilterOptions(boolean matchesAny) {
        this.matchesAny = matchesAny;
    }

    public @Nullable String getRegex(){
        return regex;
    }

    public int getCpuCount(){
        return cpuCount;
    }

    public @Nullable Storage<Megabyte> getRamSize(){
        return ramSize;
    }

    public @Nullable String getDatacenterId(){
        return datacenterId;
    }

    /**
     * Indicates whether there are any criteria associated with these options.
     * @return true if this filter options object has any criteria associated with it
     */
    public boolean hasCriteria() {
        return (cpuCount > 0 || (ramSize != null && ramSize.intValue() > 0) || regex != null || datacenterId != null);
    }

    /**
     * Indicates whether these options can match a single criterion (true) or if all criteria must be
     * matched in order for the VM Product to pass the filter (false).
     * @return whether matching any single criterion is sufficient to consider a VM Product a match
     */
    public boolean isMatchesAny() {
        return matchesAny;
    }

    /**
     * Indicates that the criteria associated with this filter must match all set criteria.
     * @return this
     */
    public @Nonnull VirtualMachineProductFilterOptions matchingAll(){
        this.matchesAny = false;
        return this;
    }

    /**
     * Indicates that the criteria associated with this filter must match just one single criterion.
     * @return this
     */
    public @Nonnull VirtualMachineProductFilterOptions matchingAny(){
        this.matchesAny = true;
        return this;
    }

    /**
     * Adds a regex to the set of filtering options. This regular expression is a standard Java regular expression
     * matches against the VM Product name or description
     * @param regex the Java regular expression string to match against
     * @return this
     */
    public @Nonnull VirtualMachineProductFilterOptions matchingRegex(@Nonnull String regex){
        this.regex = regex;
        return this;
    }

    public @Nonnull VirtualMachineProductFilterOptions withCpuCount(int cpuCount){
        this.cpuCount = cpuCount;
        return this;
    }

    public @Nonnull VirtualMachineProductFilterOptions withRamSize(@Nonnull Storage<Megabyte> ramSize){
        this.ramSize = ramSize;
        return this;
    }

    public @Nonnull VirtualMachineProductFilterOptions withDatacenterId(@Nonnull String datacenterId){
        this.datacenterId = datacenterId;
        return this;
    }

    /**
     * Matches a VM Product against the criteria in this set of filter options.
     * @param product the VM Product to test
     * @return true if the VM Product matches all criteria
     */
    public boolean matches(@Nonnull VirtualMachineProduct product) {
        if( regex != null ) {
            boolean matches = (product.getName().matches(regex) || product.getDescription().matches(regex));
            if( !matches && !matchesAny ) {
                return false;
            }
            else if( matches && matchesAny ) {
                return true;
            }
        }
        else if(cpuCount > 0){
            boolean matches = product.getCpuCount() == cpuCount;
            if( !matches && !matchesAny ) {
                return false;
            }
            else if( matches && matchesAny ) {
                return true;
            }
        }
        else if(ramSize != null){
            boolean matches = product.getRamSize() == ramSize;
            if( !matches && !matchesAny ) {
                return false;
            }
            else if( matches && matchesAny ) {
                return true;
            }
        }
        else if(datacenterId != null){
            boolean matches = product.getDataCenterId().equals(datacenterId);
            if( !matches && !matchesAny ) {
                return false;
            }
            else if( matches && matchesAny ) {
                return true;
            }
        }
        return !matchesAny;
    }
}


text:
using BizHawk.Common;
using BizHawk.Common.BizInvoke;
using BizHawk.Common.BufferExtensions;
using BizHawk.Emulation.Common;
using BizHawk.Emulation.Cores.Waterbox;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace BizHawk.Emulation.Cores.Consoles.Nintendo.VB
{
	[Core("Virtual Boyee", "Mednafen Team", true, true, "0.9.44.1",
		"https://mednafen.github.io/releases/", false)]
	public class VirtualBoyee : WaterboxCore, ISettable<VirtualBoyee.Settings, VirtualBoyee.SyncSettings>
	{
		private LibVirtualBoyee _boyee;

		[CoreConstructor("VB")]
		public VirtualBoyee(CoreComm comm, byte[] rom, Settings settings, SyncSettings syncSettings)
			: base(comm, new Configuration
			{
				DefaultFpsNumerator = 20000000,
				DefaultFpsDenominator = 397824,
				DefaultWidth = 384,
				DefaultHeight = 224,
				MaxWidth = 1024,
				MaxHeight = 1024,
				MaxSamples = 8192,
				SystemId = "VB"
			})
		{
			_settings = settings ?? new Settings();
			_syncSettings = syncSettings ?? new SyncSettings();

			_boyee = PreInit<LibVirtualBoyee>(new PeRunnerOptions
			{
				Filename = "vb.wbx",
				SbrkHeapSizeKB = 256,
				SealedHeapSizeKB = 4 * 1024,
				InvisibleHeapSizeKB = 256,
				PlainHeapSizeKB = 256
			});

			if (!_boyee.Load(rom, rom.Length, LibVirtualBoyee.NativeSyncSettings.FromFrontendSettings(_syncSettings)))
				throw new InvalidOperationException("Core rejected the rom");

			// do a quick hack up for frame zero size
			var tmp = new LibVirtualBoyee.FrameInfo();
			_boyee.PredictFrameSize(tmp);
			BufferWidth = tmp.Width;
			BufferHeight = tmp.Height;

			PostInit();

			_boyee.SetSettings(LibVirtualBoyee.NativeSettings.FromFrontendSettings(_settings));
		}

		protected override LibWaterboxCore.FrameInfo FrameAdvancePrep(IController controller, bool render, bool rendersound)
		{
			if (controller.IsPressed("Power"))
				_boyee.HardReset();

			return new LibVirtualBoyee.FrameInfo { Buttons = GetButtons(controller) };
		}

		#region Controller

		private LibVirtualBoyee.Buttons GetButtons(IController c)
		{
			var ret = 0;
			var val = 1;
			foreach (var s in CoreButtons)
			{
				if (c.IsPressed(s))
					ret |= val;
				val <<= 1;
			}
			return (LibVirtualBoyee.Buttons)ret;
		}

		private static readonly string[] CoreButtons =
		{
			"A", "B", "R", "L",
			"R_Up", "R_Right",
			"L_Right", "L_Left", "L_Down", "L_Up",
			"Start", "Select", "R_Left", "R_Down"
		};

		private static readonly Dictionary<string, int> _buttonOrdinals = new Dictionary<string, int>
		{
			["L_Up"] = 1,
			["L_Down"] = 2,
			["L_Left"] = 3,
			["L_Right"] = 4,
			["R_Up"] = 5,
			["R_Down"] = 6,
			["R_Left"] = 7,
			["R_Right"] = 8,
			["B"] = 9,
			["A"] = 10,
			["L"] = 11,
			["R"] = 12,
			["Select"] = 13,
			["Start"] = 14
		};

		private static readonly ControllerDefinition VirtualBoyController = new ControllerDefinition
		{
			Name = "VirtualBoy Controller",
			BoolButtons = CoreButtons
				.OrderBy(b => _buttonOrdinals[b])
				.Concat(new[] { "Power" })
				.ToList()
		};

		public override ControllerDefinition ControllerDefinition => VirtualBoyController;

		#endregion

		#region ISettable

		public class SyncSettings
		{
			[DefaultValue(false)]
			[Description("Reduce input latency.  Works with all known commercial games, may have homebrew issues.")]
			public bool InstantReadHack { get; set; }
			[DefaultValue(false)]
			[Description("Disable parallax for rendering.")]
			public bool DisableParallax { get; set; }

			public SyncSettings Clone()
			{
				return (SyncSettings)MemberwiseClone();
			}

			public static bool NeedsReboot(SyncSettings x, SyncSettings y)
			{
				return !DeepEquality.DeepEquals(x, y);
			}

			public SyncSettings()
			{
				SettingsUtil.SetDefaultValues(this);
			}
		}

		public class Settings
		{
			public enum ThreeDeeModes : int
			{
				Anaglyph = 0,
				CyberScope = 1,
				SideBySide = 2,
				//OverUnder,
				VerticalInterlaced = 4,
				HorizontalInterlaced = 5
			}

			[DefaultValue(ThreeDeeModes.Anaglyph)]
			[Description("How to display the 3d image.  Use whichever method works with your VR hardware.")]
			public ThreeDeeModes ThreeDeeMode { get; set; }

			[DefaultValue(false)]
			[Description("Swap the left and right views.")]
			public bool SwapViews { get; set; }

			public enum AnaglyphPresets : int
			{
				Custom,
				RedBlue,
				RedCyan,
				RedElectricCyan,
				RedGreen,
				GreenMagneto,
				YellowBlue
			}

			[DefaultValue(AnaglyphPresets.RedBlue)]
			[Description("Color preset for Anaglyph mode.")]
			public AnaglyphPresets AnaglyphPreset { get; set; }

			[DefaultValue(typeof(Color), "Green")]
			[Description("Left anaglyph color.  Ignored unless Preset is Custom.")]
			public Color AnaglyphCustomLeftColor { get; set; }
			[DefaultValue(typeof(Color), "Purple")]
			[Description("Right anaglyph color.  Ignored unless Preset is Custom.")]
			public Color AnaglyphCustomRightColor { get; set; }

			[DefaultValue(typeof(Color), "White")]
			[Description("Display color for all of the non-anaglyph modes.  Real hardware was red, but other colors may be easier on your eyes.")]
			public Color NonAnaglyphColor { get; set; }

			[DefaultValue(1750)]
			[Range(1000, 2000)]
			[Description("LED gamma ramp.  Range of 1000 to 2000")]
			public int LedOnScale { get; set; }

			[DefaultValue(2)]
			[Range(1, 10)]
			public int InterlacePrescale { get; set; }

			[DefaultValue(0)]
			[Range(0, 1024)]
			[Description("How many pixels to put between views in Side By Side mode")]
			public int SideBySideSeparation { get; set; }

			public Settings Clone()
			{
				return (Settings)MemberwiseClone();
			}

			public static bool NeedsReboot(Settings x, Settings y)
			{
				return !DeepEquality.DeepEquals(x, y);
			}

			public Settings()
			{
				SettingsUtil.SetDefaultValues(this);
			}
		}

		private Settings _settings;
		private SyncSettings _syncSettings;

		public Settings GetSettings()
		{
			return _settings.Clone();
		}

		public SyncSettings GetSyncSettings()
		{
			return _syncSettings.Clone();
		}

		public bool PutSettings(Settings o)
		{
			var ret = Settings.NeedsReboot(_settings, o);
			_settings = o;
			return ret;
		}

		public bool PutSyncSettings(SyncSettings o)
		{
			var ret = SyncSettings.NeedsReboot(_syncSettings, o);
			_syncSettings = o;
			return ret;
		}

		#endregion
	}
}


text:
package snake.server;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

/**
 *
 * @author Gustavo
 */
public class ServerMain {
    public static void main(String[] args) {
        if ( args.length < 1 ) {
            System.err.println("Usage: <folder> <ip>");
            System.exit(1);
        }

        Path parentFolderPath = Paths.get(args[0]);
        Path absoluteParentFolderPath = parentFolderPath.toAbsolutePath();
        if ( Files.exists(parentFolderPath, LinkOption.NOFOLLOW_LINKS) &&
                Files.isDirectory(parentFolderPath, LinkOption.NOFOLLOW_LINKS) ) {
            System.out.println("Snake Server's folder: " + absoluteParentFolderPath);
            try {
                Registry registry = LocateRegistry.createRegistry(Settings.port);
                registry.rebind("Server", new SnakeServer(absoluteParentFolderPath));
                System.out.println("Snake Server is ready");
            } catch (Exception e) {
                System.err.println(e);
            }
        } else {
            System.err.println(absoluteParentFolderPath + " is an invalid folder, check its existence and permissions");
        }
    }
}


text:
CREATE TABLE `wh_etl_job` (
  `wh_etl_job_id`   INT(10) UNSIGNED  NOT NULL AUTO_INCREMENT
  COMMENT 'id of the etl job',
  `wh_etl_job_name` VARCHAR(127)      NOT NULL
  COMMENT 'etl job name',
  `wh_etl_type`     VARCHAR(127)               DEFAULT NULL
  COMMENT 'type of the etl service',
  `cron_expr`       VARCHAR(127)               DEFAULT NULL
  COMMENT 'frequency in crob expression',
  `ref_id`          SMALLINT(6)       NOT NULL
  COMMENT 'id of application/database where etl job runs',
  `ref_id_type`     ENUM('APP', 'DB') NOT NULL
  COMMENT 'flag the ref_id is an application or a database',
  `timeout`         INT(11)                    DEFAULT NULL
  COMMENT 'timeout in seconds for this etl job',
  `next_run`        INT(10) UNSIGNED           DEFAULT NULL
  COMMENT 'next run time',
  `comments`        VARCHAR(200)               DEFAULT NULL,
  `cmd_param`       VARCHAR(500)               DEFAULT ''
  COMMENT 'command line parameters for launch the job',
  `is_active`       CHAR(1)                    DEFAULT 'Y'
  COMMENT 'determine if this job is active or not',
  PRIMARY KEY (`wh_etl_job_id`),
  UNIQUE KEY `etl_unique` (`wh_etl_job_name`, `ref_id`)
)
  ENGINE = InnoDB
  AUTO_INCREMENT = 1
  DEFAULT CHARSET = utf8
  COMMENT = 'WhereHows ETL jobs table';

CREATE TABLE `wh_etl_job_execution` (
  `wh_etl_exec_id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT
  COMMENT 'job execution id',
  `wh_etl_job_id`  INT(10) UNSIGNED             DEFAULT NULL
  COMMENT 'id of the etl job',
  `status`         VARCHAR(31)                  DEFAULT NULL
  COMMENT 'status of etl job execution',
  `request_time`   INT(10) UNSIGNED             DEFAULT NULL
  COMMENT 'request time of the execution',
  `start_time`     INT(10) UNSIGNED             DEFAULT NULL
  COMMENT 'start time of the execution',
  `end_time`       INT(10) UNSIGNED             DEFAULT NULL
  COMMENT 'end time of the execution',
  `message`        VARCHAR(1024)                DEFAULT NULL
  COMMENT 'debug information message',
  `host_name`      VARCHAR(200)                 DEFAULT NULL
  COMMENT 'host machine name of the job execution',
  `process_id`     INT UNSIGNED                 DEFAULT NULL
  COMMENT 'job execution process id',
  PRIMARY KEY (`wh_etl_exec_id`)
)
  ENGINE = InnoDB
  DEFAULT CHARSET = utf8
  COMMENT = 'WhereHows ETL execution table';

CREATE TABLE `wh_etl_job_property` (
  `id`              INT(10)           NOT NULL AUTO_INCREMENT,
  `wh_etl_job_name` VARCHAR(127)      NOT NULL
  COMMENT 'etl job name',
  `ref_id`          SMALLINT(6)       NOT NULL
  COMMENT 'id of application/database where etl job runs',
  `ref_id_type`     ENUM('APP', 'DB') NOT NULL
  COMMENT 'flag the ref_id is an application or a database',
  `property_name`   VARCHAR(127)      NOT NULL
  COMMENT 'property name',
  `property_value`  TEXT COMMENT 'property value',
  `is_encrypted`    CHAR(1)                    DEFAULT 'N'
  COMMENT 'whether the value is encrypted',
  `comments`        VARCHAR(100)               DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `property_unique` (`wh_etl_job_name`, `ref_id`, `property_name`)
)
  ENGINE = InnoDB
  AUTO_INCREMENT = 1
  DEFAULT CHARSET = utf8
  COMMENT = 'Etl job configuration table';

CREATE TABLE `wh_property` (
  `property_name`  VARCHAR(127) NOT NULL
  COMMENT 'property name',
  `property_value` TEXT COMMENT 'property value',
  `is_encrypted`   CHAR(1)      DEFAULT 'N'
  COMMENT 'whether the value is encrypted',
  `group_name`     VARCHAR(127) DEFAULT NULL
  COMMENT 'group name for the property',
  PRIMARY KEY (`property_name`)
)
  ENGINE = InnoDB
  DEFAULT CHARSET = utf8
  COMMENT = 'WhereHows properties table';

CREATE TABLE `cfg_application` (
  `app_id`                  SMALLINT    UNSIGNED NOT NULL,
  `app_code`                VARCHAR(128)         NOT NULL,
  `description`             VARCHAR(512)         NOT NULL,
  `tech_matrix_id`          SMALLINT(5) UNSIGNED DEFAULT '0',
  `doc_url`                 VARCHAR(512)         DEFAULT NULL,
  `parent_app_id`           INT(11) UNSIGNED     NOT NULL,
  `app_status`              CHAR(1)              NOT NULL,
  `last_modified`           TIMESTAMP            NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `is_logical`              CHAR(1)                       DEFAULT NULL,
  `uri_type`                VARCHAR(25)                   DEFAULT NULL,
  `uri`                     VARCHAR(1000)                 DEFAULT NULL,
  `lifecycle_layer_id`      TINYINT(4) UNSIGNED           DEFAULT NULL,
  `short_connection_string` VARCHAR(50)                   DEFAULT NULL,
  PRIMARY KEY (`app_id`),
  UNIQUE KEY `idx_cfg_application__appcode` (`app_code`) USING HASH
)
  ENGINE = InnoDB
  DEFAULT CHARSET = utf8;

CREATE TABLE cfg_database  (
	db_id                  	smallint(6) UNSIGNED NOT NULL,
	db_code                	varchar(30) COMMENT 'Unique string without space'  NOT NULL,
	primary_dataset_type    varchar(30) COMMENT 'What type of dataset this DB supports' NOT NULL DEFAULT '*',
	description            	varchar(128) NOT NULL,
	is_logical             	char(1) COMMENT 'Is a group, which contains multiple physical DB(s)'  NOT NULL DEFAULT 'N',
	deployment_tier        	varchar(20) COMMENT 'Lifecycle/FabricGroup: local,dev,sit,ei,qa,canary,preprod,pr'  NULL DEFAULT 'prod',
	data_center            	varchar(200) COMMENT 'Code name of its primary data center. Put * for all data cen'  NULL DEFAULT '*',
	associated_dc_num      	tinyint(4) UNSIGNED COMMENT 'Number of associated data centers'  NOT NULL DEFAULT '1',
	cluster                	varchar(200) COMMENT 'Name of Fleet, Group of Servers or a Server'  NULL DEFAULT '*',
	cluster_size           	smallint(6) COMMENT 'Num of servers in the cluster'  NOT NULL DEFAULT '1',
	extra_deployment_tag1  	varchar(50) COMMENT 'Additional tag. Such as container_group:HIGH'  NULL,
	extra_deployment_tag2  	varchar(50) COMMENT 'Additional tag. Such as slice:i0001'  NULL,
	extra_deployment_tag3  	varchar(50) COMMENT 'Additional tag. Such as region:eu-west-1'  NULL,
	replication_role       	varchar(10) COMMENT 'master or slave or broker'  NULL,
	jdbc_url               	varchar(1000) NULL,
	uri                    	varchar(1000) NULL,
	short_connection_string	varchar(50) COMMENT 'Oracle TNS Name, ODBC DSN, TDPID...' NULL,
  last_modified          	timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
	PRIMARY KEY(db_id),
  UNIQUE KEY `uix_cfg_database__dbcode` (db_code) USING HASH
)
ENGINE = InnoDB
DEFAULT CHARSET = utf8
COMMENT = 'Abstract different storage instances as databases' ;

CREATE TABLE stg_cfg_object_name_map  (
	object_type             	varchar(100) NOT NULL,
	object_sub_type         	varchar(100) NULL,
	object_name             	varchar(350) NOT NULL,
	object_urn              	varchar(350) NULL,
	object_dataset_id       	int(11) UNSIGNED NULL,
	map_phrase              	varchar(100) NULL,
	is_identical_map        	char(1) NULL DEFAULT 'N',
	mapped_object_type      	varchar(100) NOT NULL,
	mapped_object_sub_type  	varchar(100) NULL,
	mapped_object_name      	varchar(350) NOT NULL,
	mapped_object_urn       	varchar(350) NULL,
	mapped_object_dataset_id	int(11) UNSIGNED NULL,
	description             	varchar(500) NULL,
	last_modified           	timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
	PRIMARY KEY(object_name, mapped_object_name),
  KEY idx_stg_cfg_object_name_map__mappedobjectname (mapped_object_name) USING BTREE
)
ENGINE = InnoDB
CHARACTER SET latin1
COLLATE latin1_swedish_ci
COMMENT = 'Map alias (when is_identical_map=Y) and view dependency' ;

CREATE TABLE cfg_object_name_map  (
  obj_name_map_id         int(11) AUTO_INCREMENT NOT NULL,
  object_type             varchar(100) NOT NULL,
  object_sub_type         varchar(100) NULL,
  object_name             varchar(350) NOT NULL COMMENT 'this is the derived/child object',
  map_phrase              varchar(100) NULL,
  object_dataset_id       int(11) UNSIGNED NULL COMMENT 'can be the abstract dataset id for versioned objects',
  is_identical_map        char(1) NOT NULL DEFAULT 'N' COMMENT 'Y/N',
  mapped_object_type      varchar(100) NOT NULL,
  mapped_object_sub_type  varchar(100) NULL,
  mapped_object_name      varchar(350) NOT NULL COMMENT 'this is the original/parent object',
  mapped_object_dataset_id	int(11) UNSIGNED NULL COMMENT 'can be the abstract dataset id for versioned objects',
  description             varchar(500) NULL,
  last_modified           timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY(obj_name_map_id),
  KEY idx_cfg_object_name_map__mappedobjectname (mapped_object_name) USING BTREE,
  CONSTRAINT uix_cfg_object_name_map__objectname_mappedobjectname UNIQUE (object_name, mapped_object_name)
)
ENGINE = InnoDB
CHARACTER SET latin1
AUTO_INCREMENT = 1
COMMENT = 'Map alias (when is_identical_map=Y) and view dependency. Always map from Derived/Child (object) back to its Original/Parent (mapped_object)' ;

CREATE TABLE cfg_deployment_tier  (
  tier_id      	tinyint(4) NOT NULL,
  tier_code    	varchar(25) COMMENT 'local,dev,test,qa,stg,prod' NOT NULL,
  tier_label    varchar(50) COMMENT 'display full name' NULL,
  sort_id       smallint(6) COMMENT '3-digit for group, 3-digit within group' NOT NULL,
  last_modified timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY(tier_id),
  UNIQUE KEY uix_cfg_deployment_tier__tiercode (tier_code)
)
ENGINE = InnoDB
AUTO_INCREMENT = 0
COMMENT = 'http://en.wikipedia.org/wiki/Deployment_environment';

CREATE TABLE cfg_data_center  (
	data_center_id    	smallint(6) NOT NULL DEFAULT '0',
	data_center_code  	varchar(30) NOT NULL,
	data_center_name  	varchar(50) NOT NULL,
	time_zone         	varchar(50) NOT NULL,
	city              	varchar(50) NOT NULL,
	state             	varchar(25) NULL,
	country           	varchar(50) NOT NULL,
	longtitude        	decimal(10,6) NULL,
	latitude          	decimal(10,6) NULL,
	data_center_status	char(1) COMMENT 'A,D,U' NULL,
	last_modified     	timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
	PRIMARY KEY(data_center_id),
  UNIQUE KEY uix_cfg_data_center__datacentercode (data_center_code)
)
ENGINE = InnoDB
AUTO_INCREMENT = 0
COMMENT = 'https://en.wikipedia.org/wiki/Data_center' ;

CREATE TABLE cfg_cluster  (
	cluster_id    	        smallint(6) NOT NULL DEFAULT '0',
	cluster_code  	        varchar(80) NOT NULL,
	cluster_short_name      varchar(50) NOT NULL,
	cluster_type       	varchar(50) NOT NULL,
	deployment_tier_code    varchar(25) NOT NULL,
	data_center_code        varchar(30) NULL,
	description             varchar(200) NULL,
	last_modified     	timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
	PRIMARY KEY(cluster_id),
  UNIQUE KEY uix_cfg_cluster__clustercode (cluster_code)
)
COMMENT = 'https://en.wikipedia.org/wiki/Computer_cluster' ;

CREATE TABLE IF NOT EXISTS cfg_search_score_boost (
  `id` INT COMMENT 'dataset id',
  `static_boosting_score` INT COMMENT 'static boosting score for elastic search',
  PRIMARY KEY (`id`)
) ENGINE = InnoDB DEFAULT CHARSET = latin1;


text:
namespace boost {
namespace beast {
namespace websocket {

class read1_test : public unit_test::suite
{
public:
    void
    testTimeout()
    {
        using tcp = net::ip::tcp;

        net::io_context ioc;

        // success

        {
            stream<tcp::socket> ws1(ioc);
            stream<tcp::socket> ws2(ioc);
            test::connect(ws1.next_layer(), ws2.next_layer());
            ws1.async_handshake("test", "/", test::success_handler());
            ws2.async_accept(test::success_handler());
            test::run(ioc);

            flat_buffer b;
            ws1.async_write(net::const_buffer("Hello, world!", 13),
                test::success_handler());
            ws2.async_read(b, test::success_handler());
            test::run(ioc);
        }

        {
            stream<test::stream> ws1(ioc);
            stream<test::stream> ws2(ioc);
            test::connect(ws1.next_layer(), ws2.next_layer());
            ws1.async_handshake("test", "/", test::success_handler());
            ws2.async_accept(test::success_handler());
            test::run(ioc);

            flat_buffer b;
            ws1.async_write(net::const_buffer("Hello, world!", 13),
                test::success_handler());
            ws2.async_read(b, test::success_handler());
            test::run(ioc);
        }

        // success, timeout enabled

        {
            stream<tcp::socket> ws1(ioc);
            stream<tcp::socket> ws2(ioc);
            test::connect(ws1.next_layer(), ws2.next_layer());
            ws1.async_handshake("test", "/", test::success_handler());
            ws2.async_accept(test::success_handler());
            test::run(ioc);

            flat_buffer b;
            ws1.set_option(stream_base::timeout{
                stream_base::none(),
                std::chrono::milliseconds(50),
                false});
            ws1.async_read(b, test::success_handler());
            ws2.async_write(net::const_buffer("Hello, world!", 13),
                test::success_handler());
            test::run(ioc);
        }

        {
            stream<test::stream> ws1(ioc);
            stream<test::stream> ws2(ioc);
            test::connect(ws1.next_layer(), ws2.next_layer());
            ws1.async_handshake("test", "/", test::success_handler());
            ws2.async_accept(test::success_handler());
            test::run(ioc);

            flat_buffer b;
            ws1.set_option(stream_base::timeout{
                stream_base::none(),
                std::chrono::milliseconds(50),
                false});
            ws1.async_read(b, test::success_handler());
            ws2.async_write(net::const_buffer("Hello, world!", 13),
                test::success_handler());
            test::run(ioc);
        }

        // timeout

        {
            stream<tcp::socket> ws1(ioc);
            stream<tcp::socket> ws2(ioc);
            test::connect(ws1.next_layer(), ws2.next_layer());
            ws1.async_handshake("test", "/", test::success_handler());
            ws2.async_accept(test::success_handler());
            test::run(ioc);

            flat_buffer b;
            ws1.set_option(stream_base::timeout{
                stream_base::none(),
                std::chrono::milliseconds(50),
                false});
            ws1.async_read(b, test::fail_handler(
                beast::error::timeout));
            test::run(ioc);
        }

        {
            stream<test::stream> ws1(ioc);
            stream<test::stream> ws2(ioc);
            test::connect(ws1.next_layer(), ws2.next_layer());
            ws1.async_handshake("test", "/", test::success_handler());
            ws2.async_accept(test::success_handler());
            test::run(ioc);

            flat_buffer b;
            ws1.set_option(stream_base::timeout{
                stream_base::none(),
                std::chrono::milliseconds(50),
                false});
            ws1.async_read(b, test::fail_handler(
                beast::error::timeout));
            test::run(ioc);
        }
    }

    void
    run() override
    {
        testTimeout();
    }
};

BEAST_DEFINE_TESTSUITE(beast,websocket,read1);

} // websocket
} // beast
} // boost


text:
package org.apereo.cas.ticket.registry.pub;

import org.apereo.cas.redis.core.CasRedisTemplate;
import org.apereo.cas.ticket.Ticket;
import org.apereo.cas.ticket.registry.RedisCompositeKey;
import org.apereo.cas.util.PublisherIdentifier;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.val;

/**
 * This is {@link DefaultRedisTicketRegistryMessagePublisher}.
 *
 * @author Misagh Moayyed
 * @since 7.0.0
 */
@RequiredArgsConstructor
@Slf4j
public class DefaultRedisTicketRegistryMessagePublisher implements RedisTicketRegistryMessagePublisher {
    private final CasRedisTemplate<String, Ticket> redisTemplate;

    private final PublisherIdentifier publisherIdentifier;

    @Override
    public void deleteAll() {
        val payload = getRedisMessagePayload(RedisMessagePayload.RedisMessageTypes.DELETE_ALL);
        sendPayload(payload);
    }

    @Override
    public void delete(final String id) {
        val payload = getRedisMessagePayload(RedisMessagePayload.RedisMessageTypes.DELETE).withTicket(id);
        sendPayload(payload);
    }

    @Override
    public void add(final Ticket id) {
        val payload = getRedisMessagePayload(RedisMessagePayload.RedisMessageTypes.ADD).withTicket(id);
        sendPayload(payload);
    }

    @Override
    public void update(final Ticket id) {
        val payload = getRedisMessagePayload(RedisMessagePayload.RedisMessageTypes.UPDATE).withTicket(id);
        sendPayload(payload);
    }

    private void sendPayload(final RedisMessagePayload payload) {
        LOGGER.trace("Publishing Redis event payload [{}] from [{}]", payload, publisherIdentifier);
        redisTemplate.convertAndSend(RedisCompositeKey.REDIS_TICKET_REGISTRY_MESSAGE_TOPIC, payload);
    }

    private RedisMessagePayload getRedisMessagePayload(final RedisMessagePayload.RedisMessageTypes type) {
        return RedisMessagePayload.builder()
            .messageType(type)
            .identifier(publisherIdentifier)
            .build();
    }
}


text:
for markdown in *.markdown
do
    html=html/`basename $markdown .markdown`.html
    echo $markdown '=>' $html
    node ../doctool/doctool.js template.html $markdown > $html
done