text:
package org.apache.harmony.test.func.api.javax.management.monitor.stringmonitor;

import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.ObjectName;
import javax.management.monitor.StringMonitor;

import org.apache.harmony.test.func.api.javax.management.monitor.share.ErrorProducer;
import org.apache.harmony.test.func.api.javax.management.monitor.share.NotifListener;
import org.apache.harmony.test.func.api.javax.management.monitor.share.Timer;
import org.apache.harmony.test.func.api.javax.management.monitor.share.Unit;
import org.apache.harmony.share.MultiCase;
import org.apache.harmony.share.Result;

/**
 * This test is intended to check the functionality of StringMonitor class when
 * its configuration is not correct: jmx.monitor.error.runtime, threshold, type,
 * attribute and MBean notifications are analyzed.

 *

 *
testMBeanUnreg

 * Test verifies if observed MBean doesn't registered error.mbean notification
 * is sent
 *
testMBeanRegUnreg

 * Test verifies if observed MBean is unregistered error.mbean notification is
 * sent
 *
testMBeanUnregOneOf

 * Test verifies if one of observed MBeans doesn't registered error.mbean
 * notification is sent.

 * After error notification threshold notification is induced.
 *
testAttributeAbsent

 * Test verifies if the observed attribute doesn't exist in the observed MBean
 * error.attribute notification is sent
 *
testAttributeAbsentInOne

 * Test verifies if the observed attribute doesn't exist in one of the observed
 * MBeans error.attribute notification is sent
 *
testTypeObject

 * Test verifies if the observed attribute type is Object (not supported by
 * monitor) error.type notification is sent
 *
testTypeNull

 * Test verifies if the observed attribute type is null error.type notification
 * is sent
 *
testRuntimeDontRegMonitor

 * Test verifies error.attribute notification if the monitor is not registered
 *
testRuntimeException

 * Test verifies error.attribute notification if the monitor is not registered
 *
 */
public class ErrorTest extends MultiCase {

    /** Test result */
    public static boolean res = true;

    /** Object for synchronization */
    private static final Object sync = new Object();

    /**
     * Timer to prevent test hangs
     */
    private Timer timer;

    /** Notification Listener */
    private NotifListener nListener = new NotifListener(sync);

    /** Monitor to test */
    private StringMonitor monitor;

    private ObjectName monitorName;

    /** MyStingBuffer class represents object to observe */
    private ObjectName mySbName;

    private ErrorProducer mySb = new ErrorProducer();

    private MBeanServer server;

    public static void main(String[] args) {
        System.exit(new ErrorTest().test(args));
    }

    /** Actions before every test case (common) */
    public void setUp() {

        res = true;
        mySb.setString("match");
        mySb.setExceptionFlag(false);
        mySb.setNullFlag(false);

        server = MBeanServerFactory.createMBeanServer();
        monitor = new StringMonitor();

        try {
            monitorName = new ObjectName(
                    "org.apache.harmony.test.func.api.javax.management.monitor."
                            + "stringMonitor:type=StringMonitor,id=1");
            mySbName = new ObjectName(MyStringBuffer.MSB_NAME_TEMPLATE + "1");
        } catch (Throwable e) {
            e.printStackTrace();
            System.err.println("Test: ERROR: Internal error!");
            System.exit(106);
        }

        monitor.addNotificationListener(nListener, null, "handback");
    }

    /** Actions after every test case */
    public void tearDown() {

        monitor.stop();
        monitor = null;

    }

    /**
     * Test verifies if observed MBean doesn't registered error.mbean
     * notification is sent
     *
     * @throws Exception
     */
    public Result testMBeanUnreg() throws Exception {

        server.registerMBean(monitor, monitorName);

        /* Observed object is unregistered */
        monitor.addObservedObject(mySbName);
        monitor.setObservedAttribute("String");
        monitor.setStringToCompare("match");
        monitor.setGranularityPeriod(100);

        nListener.setParameters("String", mySbName, "jmx.monitor.error.mbean");

        /*
         * wait for notification handler's notification on sync. And enable
         * timer that notifies after 15 secs (to prevent test hang if no
         * notification had been sent)
         */
        enableTimer();
        monitor.start();
        synchronized (sync) {
            sync.wait();
        }
        res &= timer.getRes();
        res &= nListener.getRes();
        timer.interrupt();

        if (!res) {
            return failed("mbean.error notification if observed object "
                    + "doesn't registered hasn't been received or incorrect");
        }
        return passed();
    }

    /**
     * Test verifies if observed MBean is unregistered error.mbean notification
     * is sent
     *
     * @throws Exception
     */
    public Result testMBeanRegUnreg() throws Exception {

        server.registerMBean(monitor, monitorName);
        server.registerMBean(mySb, mySbName);

        monitor.addObservedObject(mySbName);
        monitor.setObservedAttribute("String");
        monitor.setStringToCompare("match");
        monitor.setGranularityPeriod(100);

        monitor.start();

        /* Verify the monitor is started */
        Thread.sleep(200);
        if (!monitor.isActive()) {
            return new Result(Result.ERROR,
                    "Monitor doesn't start in 200 milliseconds");
        }

        nListener.setParameters("String", mySbName, "jmx.monitor.error.mbean");

        enableTimer();
        /* Unregister Observed object */
        server.unregisterMBean(mySbName);
        synchronized (sync) {
            sync.wait();
        }
        res &= timer.getRes();
        res &= nListener.getRes();
        timer.interrupt();

        if (!res) {
            return failed("mbean.error notification if observed object "
                    + "is unregistered hasn't been received or incorrect");
        }
        return passed();
    }

    /**
     * Test verifies if one of observed MBeans doesn't registered error.mbean
     * notification is sent.
     *
     * After error notification threshold notification is induced.
     *
     * @throws Exception
     */
    public Result testMBeanUnregOneOf() throws Exception {

        server.registerMBean(monitor, monitorName);
        server.registerMBean(mySb, mySbName);

        monitor.addObservedObject(mySbName);
        /* Add an unregistered observed object */
        ObjectName unregName = new ObjectName(MyStringBuffer.MSB_NAME_TEMPLATE
                + "2");
        monitor.addObservedObject(unregName);
        monitor.setObservedAttribute("String");
        monitor.setStringToCompare("match");
        monitor.setNotifyDiffer(true);
        monitor.setGranularityPeriod(100);

        nListener.setParameters("String", unregName, "jmx.monitor.error.mbean");

        enableTimer();
        monitor.start();
        synchronized (sync) {
            sync.wait();
        }
        res &= timer.getRes();
        res &= nListener.getRes();
        timer.interrupt();

        res &= checkDifferNotification();

        if (!res) {
            return failed("mbean.error notification if one of observed objects "
                    + "doesn't registered hasn't been received or incorrect");
        }
        return passed();
    }

    /**
     * Test verifies if the observed attribute doesn't exist in the observed
     * MBean error.attribute notification is sent
     *
     * @throws Exception
     */
    public Result testAttributeAbsent() throws Exception {

        server.registerMBean(monitor, monitorName);
        server.registerMBean(mySb, mySbName);

        monitor.addObservedObject(mySbName);
        /* Observed object is absent in mySb MBean */
        monitor.setObservedAttribute("This Attribute is absent");
        monitor.setStringToCompare("match");
        monitor.setGranularityPeriod(100);

        nListener.setParameters("This Attribute is absent", mySbName,
                "jmx.monitor.error.attribute");

        enableTimer();
        monitor.start();
        synchronized (sync) {
            sync.wait();
        }
        res &= timer.getRes();
        res &= nListener.getRes();
        timer.interrupt();

        /* Now try to set incorrect attribute again */
        nListener.setParameters("This Attribute is still absent", mySbName,
                "jmx.monitor.error.attribute");
        monitor.setObservedAttribute("This Attribute is still absent");

        enableTimer();
        synchronized (sync) {
            sync.wait();
        }
        res &= timer.getRes();
        res &= nListener.getRes();
        timer.interrupt();

        if (!res) {
            return failed("error.attribute notification if the observed attribute "
                    + "doesn't exist hasn't been received or incorrect");
        }
        return passed();
    }

    /**
     * Test verifies if the observed attribute doesn't exist in one of the
     * observed MBeans error.attribute notification is sent
     *
     * @throws Exception
     */
    public Result testAttributeAbsentInOne() throws Exception {

        server.registerMBean(new Unit(), Unit.getUnitOblectName());
        server.registerMBean(monitor, monitorName);
        server.registerMBean(mySb, mySbName);

        monitor.addObservedObject(mySbName);
        /* Observed attribute is absent in Unit MBean */
        monitor.addObservedObject(Unit.getUnitOblectName());
        monitor.setObservedAttribute("String");
        monitor.setNotifyDiffer(true);
        monitor.setStringToCompare("match");
        monitor.setGranularityPeriod(100);

        nListener.setParameters("String", Unit.getUnitOblectName(),
                "jmx.monitor.error.attribute");

        enableTimer();
        monitor.start();
        synchronized (sync) {
            sync.wait();
        }
        res &= timer.getRes();
        res &= nListener.getRes();
        timer.interrupt();

        res &= checkDifferNotification();

        if (!res) {
            return failed("error.attribute notification if the observed attribute "
                    + "doesn't exist hasn't been received or incorrect");
        }
        return passed();
    }

    /**
     * Test verifies if the observed attribute type is Object (not supported by
     * monitor) error.type notification is sent
     *
     * @throws Exception
     */
    public Result testTypeObject() throws Exception {

        server.registerMBean(monitor, monitorName);
        server.registerMBean(mySb, mySbName);

        monitor.addObservedObject(mySbName);
        /**/
        monitor.setObservedAttribute("Object");
        monitor.setNotifyDiffer(true);
        monitor.setStringToCompare("match");
        monitor.setGranularityPeriod(100);

        nListener.setParameters("Object", mySbName, "jmx.monitor.error.type");

        enableTimer();
        monitor.start();
        synchronized (sync) {
            sync.wait();
        }
        res &= timer.getRes();
        res &= nListener.getRes();
        timer.interrupt();

        monitor.setObservedAttribute("String");
        res &= checkDifferNotification();

        if (!res) {
            return failed("error.type notification if the observed attribute "
                    + "type is differs from possible hasn't been received or incorrect");
        }
        return passed();
    }

    /**
     * Test verifies if the observed attribute type is null error.type
     * notification is sent
     *
     * @throws Exception
     */
    public Result testTypeNull() throws Exception {

        server.registerMBean(monitor, monitorName);
        server.registerMBean(mySb, mySbName);

        monitor.addObservedObject(mySbName);
        monitor.setObservedAttribute("String");
        monitor.setNotifyDiffer(true);
        monitor.setStringToCompare("match");
        monitor.setGranularityPeriod(100);

        mySb.setString(null);

        nListener.setParameters("String", mySbName, "jmx.monitor.error.type");

        enableTimer();
        monitor.start();
        synchronized (sync) {
            sync.wait();
        }
        res &= timer.getRes();
        res &= nListener.getRes();
        timer.interrupt();

        mySb.setString("match");
        res &= checkDifferNotification();

        if (!res) {
            return failed("error.type notification if the observed attribute "
                    + "type is differs from possible hasn't been received or incorrect");
        }
        return passed();
    }

    /**
     * Test verifies error.attribute notification if the monitor is not
     * registered
     */
    public Result testRuntimeDontRegMonitor() throws Exception {

        server.registerMBean(mySb, mySbName);

        monitor.addObservedObject(mySbName);
        monitor.setObservedAttribute("String");
        monitor.setNotifyDiffer(true);
        monitor.setStringToCompare("match");
        monitor.setGranularityPeriod(100);

        nListener
                .setParameters("String", mySbName, "jmx.monitor.error.runtime");

        enableTimer();
        monitor.start();
        synchronized (sync) {
            sync.wait();
        }
        res &= timer.getRes();
        res &= nListener.getRes();
        timer.interrupt();

        server.registerMBean(monitor, monitorName);
        res &= checkDifferNotification();

        if (!res) {
            return failed("error.type notification if the observed attribute "
                    + "type is differs from possible hasn't been received or incorrect");
        }
        return passed();
    }

    /**
     * Test verifies error.attribute notification if the monitor is not
     * registered
     */
    public Result testRuntimeException() throws Exception {

        server.registerMBean(mySb, mySbName);
        server.registerMBean(monitor, monitorName);

        mySb.setExceptionFlag(true);

        monitor.addObservedObject(mySbName);
        monitor.setObservedAttribute("String");
        monitor.setNotifyDiffer(true);
        monitor.setStringToCompare("match");
        monitor.setGranularityPeriod(100);

        nListener.setParameters("String", mySbName,
                "jmx.monitor.error.runtime");

        enableTimer();
        monitor.start();
        synchronized (sync) {
            sync.wait();
        }
        res &= timer.getRes();
        res &= nListener.getRes();
        timer.interrupt();

        mySb.setExceptionFlag(false);
        res &= checkDifferNotification();

        if (!res) {
            return failed("error.type notification if the observed attribute "
                    + "type is differs from possible hasn't been received or incorrect");
        }
        return passed();
    }

    /** Tests use this method to verify is the monitor operate correct */
    private boolean checkDifferNotification() {

        boolean lRes = true;

        nListener.setParameters("String", mySbName,
                "jmx.monitor.string.differs");

        if (!monitor.isActive()) {
            log.add("Monitor is dead!");
            return false;
        }

        enableTimer();
        mySb.setString("differ");
        synchronized (sync) {
            try {
                sync.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        lRes &= timer.getRes();
        lRes &= nListener.getRes();
        timer.interrupt();

        return lRes;
    }

    private void enableTimer() {
        timer = new Timer(5000, sync);
        timer.setDaemon(true);
        timer.start();
    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataExplorer.Application.Core.Commands;
using DataExplorer.Application.Filters.Commands;
using DataExplorer.Domain.Filters;

namespace DataExplorer.Presentation.Panes.Filter.StringFilters
{
    public class StringFilterViewModel : FilterViewModel
    {
        private readonly StringFilter _filter;

        public StringFilterViewModel(
            ICommandBus commandBus,
            StringFilter filter)
            : base(commandBus, filter)
        {
            _filter = filter;
        }

        public string Value
        {
            get { return _filter.Value; }
            set
            {
                _filter.Value = value;
                OnPropertyChanged(() => Value);
                _commandBus.Execute(new UpdateFilterCommand(_filter));
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
{{$ctrl.userInfo.name}}

        {{$ctrl.userInfo.type}}


text:
package net.jini.url.httpmd;

import com.sun.jini.logging.Levels;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.MessageDigest;
import java.util.logging.Logger;

/**
 * An input stream that checks the contents of another input stream against a
 * message digest. The stream throws WrongMessageDigestException if the end of
 * the other input stream is reached and the contents did not have the expected
 * message digest. The message digest is not checked unless the end of the
 * input stream is reached.
 *
 * @author Sun Microsystems, Inc.
 *
 */
class MdInputStream extends InputStream {

    /** Logger. */
    private static final Logger logger =
	Logger.getLogger("net.jini.url.httpmd");

    /** The size buffer to use when skipping input. */
    private static final int SKIP_BUFFER_SIZE = 512;

    /** The HTTPMD URL associated with the input stream being checked. */
    private final URL url;

    /** The input stream whose contents should be checked. */
    private final InputStream in;

    /**
     * The object to use to compute the message digest of the stream contents.
     */
    private final MessageDigest messageDigest;

    /** The expected digest. */
    private final byte[] expectedDigest;

    /** Set to the buffer to use when skipping input. */
    private byte[] skipBuffer;

    /**
     * Set to true when the contents have been checked against the message
     * digest.
     */
    private boolean checked;

    /**
     * The exception message if the message digest was incorrect, or null if no
     * exception should be thrown.
     */
    private String failed;

    /**
     * Creates an input stream that checks the contents of another input stream
     * against a message digest. The stream throws WrongMessageDigestException
     * if the end of the other input stream is reached and the contents did not
     * have the expected message digest.
     *
     * @param url the HTTPMD URL associated with the input stream being checked
     * @param in the input stream whose contents should be checked
     * @param messageDigest the object to use for computing the message digest
     *	      of the stream contents
     * @param expectedDigest the expected message digest of the stream contents
     * @throws NullPointerException if any of the arguments is null
     */
    MdInputStream(URL url,
		  InputStream in,
		  MessageDigest messageDigest,
		  byte[] expectedDigest)
    {
	if (url == null || in == null || messageDigest == null) {
	    throw new NullPointerException();
	}
	this.url = url;
	this.in = in;
	this.messageDigest = messageDigest;
	this.expectedDigest = (byte[]) expectedDigest.clone();
    }

    public synchronized int read() throws IOException {
	checkFailed();
	int result = in.read();
	if (result < 0) {
	    checkDigest();
	} else {
	    messageDigest.update((byte) result);
	}
	return result;
    }

    /**
     * Throws an exception if the message digest was found to be
     * incorrect. Call this method before performing any I/O operations to
     * insure that the same exception continues to be thrown after an incorrect
     * message digest is discovered.
     */
    private void checkFailed() throws WrongMessageDigestException {
	if (failed != null) {
	    WrongMessageDigestException exception =
		new WrongMessageDigestException(failed);
	    logger.log(Levels.FAILED, "Incorrect message digest", exception);
	    throw exception;
	}
    }

    /**
     * Checks the message digest. Call this method when the end of the other
     * input stream is reached.
     */
    private void checkDigest() throws WrongMessageDigestException {
	if (!checked) {
	    byte[] result = messageDigest.digest();
	    checked = true;
	    if (!MessageDigest.isEqual(result, expectedDigest)) {
		failed = "Incorrect message digest for " + url + ": " +
		    HttpmdUtil.digestString(result);
		checkFailed();
	    }
	}
    }

    public synchronized int read(byte b[], int off, int len)
	throws IOException
    {
	checkFailed();
	int n = in.read(b, off, len);
	if (n < 0) {
	    checkDigest();
	} else {
	    messageDigest.update(b, off, n);
	}
	return n;
    }

    public synchronized long skip(long n) throws IOException {
	if (skipBuffer == null) {
	    skipBuffer = new byte[SKIP_BUFFER_SIZE];
	}
	long remaining = n;
	while (remaining > 0) {
	    int nr = read(
		skipBuffer, 0, (int) Math.min(SKIP_BUFFER_SIZE, remaining));
	    if (nr < 0) {
		break;
	    }
	    remaining -= nr;
	}
	return n - remaining;
    }

    public synchronized int available() throws IOException {
	checkFailed();
	return in.available();
    }

    public synchronized void close() throws IOException {
	checkFailed();
	in.close();
    }
}


text:
<bill session="115" type="h" number="943" updated="2017-07-19T19:45:13Z">
  <state datetime="2017-02-07">REFERRED</state>
  <status>
    <introduced datetime="2017-02-07"/>
  </status>
  <introduced datetime="2017-02-07"/>
  <titles>
    <title type="short" as="introduced">Finding Innovative Lionfish Elimination Technologies Act of 2017</title>
    <title type="short" as="introduced">Finding Innovative Lionfish Elimination Technologies Act of 2017</title>
    <title type="official" as="introduced">To authorize the Secretary of Commerce to award competitive grants to combat the certain species of lionfish in the Atlantic Ocean and the Gulf of Mexico.</title>
    <title type="display">Finding Innovative Lionfish Elimination Technologies Act of 2017</title>
  </titles>
  <sponsor bioguide_id="C001107"/>
  <cosponsors>
    <cosponsor bioguide_id="D000600" joined="2017-02-14"/>
    <cosponsor bioguide_id="H000324" joined="2017-02-07"/>
    <cosponsor bioguide_id="M001199" joined="2017-05-23"/>
    <cosponsor bioguide_id="S001200" joined="2017-02-13"/>
  </cosponsors>
  <actions>
    <action datetime="2017-02-07">
      <text>Introduced in House</text>
    </action>
    <action datetime="2017-02-07" state="REFERRED">
      <text>Referred to the House Committee on Natural Resources.</text>
    </action>
    <action datetime="2017-02-23">
      <text>Referred to the Subcommittee on Water, Power and Oceans.</text>
    </action>
  </actions>
  <committees>
    <committee subcommittee="" code="HSII" name="House Natural Resources" activity="Referral"/>
    <committee subcommittee="Water, Power and Oceans" code="HSII13" name="House Natural Resources" activity="Referral"/>
  </committees>
  <relatedbills/>
  <subjects>
    <term name="Public lands and natural resources"/>
    <term name="Aquatic ecology"/>
    <term name="Atlantic Ocean"/>
    <term name="Education programs funding"/>
    <term name="Environmental assessment, monitoring, research"/>
    <term name="Fishes"/>
    <term name="Gulf of Mexico"/>
    <term name="Higher education"/>
    <term name="Marine and coastal resources, fisheries"/>
    <term name="Research administration and funding"/>
  </subjects>
  <amendments/>
  <summary date="2017-02-07T05:00:00Z" status="Introduced in House">Finding Innovative Lionfish Elimination Technologies Act of 2017

This bill directs the National Oceanic and Atmospheric Administration to award competitive grants for colleges, universities, and nonprofit research organizations to research lionfish and their impact on the Atlantic Ocean and Gulf of Mexico ecosystems.

The bill prescribes specific requirements for an entity to be eligible for a grant. Grants awarded must be used to develop innovative technologies that can detect, monitor, and help mitigate the spread of lionfish in the Atlantic Ocean and Gulf of Mexico.</summary>
  <committee-reports/>
</bill>


text:
@implementation RYXTableView

- (instancetype)initWithCoder:(NSCoder *)coder {
    self = [super initWithCoder:coder];
    if (self) {
        [self setup];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame style:(UITableViewStyle)style{
    self = [super initWithFrame:frame style:style];
    if (self) {
        [self setup];
    }
    return self;
}

- (void)setup{
    self.tableFooterView = [[UIView alloc] init];   // 去掉尾部空cell
}

#pragma mark - Setter
- (void)setRefreshDelegate:(id <RYXTableViewRefresh>)refreshDelegate {
    __weak id<RYXTableViewRefresh> weakDelegate = refreshDelegate;
    _refreshDelegate = weakDelegate;

    if ([_refreshDelegate respondsToSelector:@selector(headerBeginRefresh:)] || [_refreshDelegate respondsToSelector:@selector(headerEndRefresh:)]) {
        MJRefreshNormalHeader *header = [[MJRefreshNormalHeader alloc] init];
        __weak typeof(self) weakSelf = self;
        if ([_refreshDelegate respondsToSelector:@selector(headerBeginRefresh:)]) {
            [header setRefreshingBlock:^{
                [weakSelf.refreshDelegate performSelector:@selector(headerBeginRefresh:) withObject:weakSelf];
            }];
        }

        if ([_refreshDelegate respondsToSelector:@selector(headerEndRefresh:)]) {
            [header setEndRefreshingCompletionBlock:^{
                [weakSelf.refreshDelegate performSelector:@selector(headerEndRefresh:) withObject:weakSelf];
            }];
        }

        header.lastUpdatedTimeLabel.hidden = YES;
        header.stateLabel.hidden = YES;
        header.arrowView.image = nil;
        self.mj_header = header;
    }

    if ([_refreshDelegate respondsToSelector:@selector(footerBeginRefresh:)] || [_refreshDelegate respondsToSelector:@selector(footerEndRefresh:)]) {
        MJRefreshAutoNormalFooter *footer = [[MJRefreshAutoNormalFooter alloc] init];
        __weak typeof(self) weakSelf = self;
        if ([_refreshDelegate respondsToSelector:@selector(footerBeginRefresh:)]) {
            [footer setRefreshingBlock:^{
                [weakSelf.refreshDelegate performSelector:@selector(footerBeginRefresh:) withObject:weakSelf];
            }];
        }

        if ([_refreshDelegate respondsToSelector:@selector(footerEndRefresh:)]) {
            [footer setEndRefreshingCompletionBlock:^{
                [weakSelf.refreshDelegate performSelector:@selector(footerEndRefresh:) withObject:weakSelf];
            }];
        }

        footer.stateLabel.hidden = YES;
        footer.automaticallyRefresh = NO;
        footer.refreshingTitleHidden = YES;
        self.mj_footer = footer;
    }
}

@end

@implementation RYXTableView(Refresh)

- (void)endRefresh {
    [self.mj_header endRefreshing];
    [self.mj_footer endRefreshing];
}

- (void)endRefreshingWithNoMoreData {
    [self.mj_footer endRefreshingWithNoMoreData];
}

- (void)resetNoMoreData {
    [self.mj_footer resetNoMoreData];
}

@end


text:
package org.clintonhealthaccess.lmis.app.models.api;

import org.simpleframework.xml.Element;
import org.simpleframework.xml.Path;
import org.simpleframework.xml.Root;

@Root(strict = false)
public class FDroid {

    @Path("application/package")
    @Element
    private String version;

    public String getVersion() {
        return version;
    }

    public static boolean checkVersion(String remoteVersion, String currentVersion) {
        if (remoteVersion.compareTo(currentVersion) > 0) {
            return true;
        }
        return false;
    }

    public static class FDroidRepo {

        @Element
        private String description;
    }
}


text:
#include <iostream>
using std::cin; using std::cout; using std::endl;

#include <string>
using std::string;

#include <regex>
using std::regex; using std::sregex_iterator; using std::smatch;
using std::regex_error;

// the area code doesn't have a separator;
// the remaining separators must be equal
// OR the area code parens are correct and
// the next separator is blank or missing
bool valid(const smatch& m)
{
	// if there is an open parenthesis before the area code
	if(m[1].matched)
		// the area code must be followed by a close parenthesis
		// and followed immediately by the rest of the number or a space
	    return m[3].matched
		       && (m[4].matched == 0 || m[4].str() == " ");
	else
		// then there can't be a close after the area code
		// the delimiters between the other two components must match
		return !m[3].matched
		       && m[4].str() == m[6].str();
}
int main()
{
	// phone has 10 digits, optional parentheses around the area code
	// components are separated by an optional space, ',' or '-'
	string phone = "\\(?\\d{3}\\)?[-. ]?\\d{3}[-. ]?\\d{4}";

	// our overall expression has seven subexpressions:
	//    ( ddd ) separator ddd separator dddd
	// subexpressions 1, 3, 4, and 6 are optional;
	// subexpressions 2, 5, and 7 hold the number
	phone = "(\\()?(\\d{3})(\\))?([-. ])?(\\d{3})([-. ]?)(\\d{4})";
	regex r(phone);  // a regex to find our pattern
	smatch m;        // a match object to hold the results
	string s;        // a string to search

	// read each record from the input file
	while (getline(cin, s)) {
		// for each matching phone number
		for (sregex_iterator it(s.begin(), s.end(), r), end_it;
			       it != end_it; ++it)
			// check whether the number's formatting is valid
			if (valid(*it))
				cout << "valid: " << it->str() << endl;
			else
				cout << "not valid: " << it->str() << endl;
	}

	return 0;
}


text:
from flask import Flask
app = Flask(__name__)

app.config.from_object('flask_default_config')
app.config.from_object('flask_config')

import pythonserver.views


text:
package com.intel.analytics.bigdl.dllib.keras.layers

import com.intel.analytics.bigdl.dllib.nn.abstractnn.AbstractModule
import com.intel.analytics.bigdl.dllib.tensor.Tensor
import com.intel.analytics.bigdl.dllib.utils.Shape
import com.intel.analytics.bigdl.dllib.keras.Sequential
import com.intel.analytics.bigdl.dllib.keras.serializer.ModuleSerializationTest

class SimpleRNNSpec extends KerasBaseSpec {

  "SimpleRNN computeOutputShape" should "work properly" in {
    val seq = Sequential[Float]()
    val rnn = SimpleRNN[Float](10, inputShape = Shape(3, 6))
    seq.add(rnn)
    seq.add(Dense[Float](5))
    seq.getOutputShape().toSingle().toArray should be (Array(-1, 5))
  }

  def weightConverter(in: Array[Tensor[Float]]): Array[Tensor[Float]] =
    Array(in(0).t(), in(1).t(), in(2))

  "SimpleRNN not return sequences" should "be the same as Keras" in {
    val kerasCode =
      """
        |input_tensor = Input(shape=[4, 5])
        |input = np.random.random([2, 4, 5])
        |output_tensor = SimpleRNN(8, activation="relu")(input_tensor)
        |model = Model(input=input_tensor, output=output_tensor)
      """.stripMargin
    val seq = Sequential[Float]()
    val layer = SimpleRNN[Float](8, activation = "relu", inputShape = Shape(4, 5))
    seq.add(layer)
    seq.getOutputShape().toSingle().toArray should be (Array(-1, 8))
    checkOutputAndGrad(seq.asInstanceOf[AbstractModule[Tensor[Float], Tensor[Float], Float]],
      kerasCode, weightConverter)
  }

  "SimpleRNN return sequences" should "be the same as Keras" in {
    val kerasCode =
      """
        |input_tensor = Input(shape=[5, 8])
        |input = np.random.random([3, 5, 8])
        |output_tensor = SimpleRNN(12, return_sequences=True)(input_tensor)
        |model = Model(input=input_tensor, output=output_tensor)
      """.stripMargin
    val seq = Sequential[Float]()
    val layer = SimpleRNN[Float](12, returnSequences = true, inputShape = Shape(5, 8))
    seq.add(layer)
    seq.getOutputShape().toSingle().toArray should be (Array(-1, 5, 12))
    checkOutputAndGrad(seq.asInstanceOf[AbstractModule[Tensor[Float], Tensor[Float], Float]],
      kerasCode, weightConverter)
  }

  "SimpleRNN go backwards" should "be the same as Keras" in {
    val kerasCode =
      """
        |input_tensor = Input(shape=[12, 12])
        |input = np.random.random([3, 12, 12])
        |output_tensor = SimpleRNN(4, go_backwards=True, activation="sigmoid")(input_tensor)
        |model = Model(input=input_tensor, output=output_tensor)
      """.stripMargin
    val seq = Sequential[Float]()
    val layer = SimpleRNN[Float](4, goBackwards = true,
      activation = "sigmoid", inputShape = Shape(12, 12))
    seq.add(layer)
    seq.getOutputShape().toSingle().toArray should be (Array(-1, 4))
    checkOutputAndGrad(seq.asInstanceOf[AbstractModule[Tensor[Float], Tensor[Float], Float]],
      kerasCode, weightConverter)
  }

}

class SimpleRNNSerialTest extends ModuleSerializationTest {
  override def test(): Unit = {
    val layer = SimpleRNN[Float](8, activation = "relu", inputShape = Shape(4, 5))
    layer.build(Shape(3, 4, 5))
    val input = Tensor[Float](3, 4, 5).rand()
    runSerializationTest(layer, input)
  }
}


text:
package pprof_test

import (
	"bufio"
	"bytes"
	"fmt"
	"io"
	"os/exec"
	"sort"
	"strconv"
	"strings"
)

// Event describes one event in the trace.
type Event struct {
	off   int       // offset in input file (for debugging and error reporting)
	typ   byte      // one of traceEv*
	ts    int64     // timestamp in nanoseconds
	p     int       // P on which the event happened (can be one of timerP, netpollP, syscallP)
	g     uint64    // G on which the event happened
	stkID uint64    // unique stack ID
	stk   []*Frame  // stack trace (can be empty)
	args  [2]uint64 // event-type-specific arguments
	// linked event (can be nil), depends on event type:
	// for GCStart: the GCStop
	// for GCScanStart: the GCScanDone
	// for GCSweepStart: the GCSweepDone
	// for GoCreate: first GoStart of the created goroutine
	// for GoStart: the associated GoEnd, GoBlock or other blocking event
	// for GoSched/GoPreempt: the next GoStart
	// for GoBlock and other blocking events: the unblock event
	// for GoUnblock: the associated GoStart
	// for blocking GoSysCall: the associated GoSysExit
	// for GoSysExit: the next GoStart
	link *Event
}

// Frame is a frame in stack traces.
type Frame struct {
	pc   uint64
	fn   string
	file string
	line int
}

const (
	// Special P identifiers:
	timerP   = 1000000 + iota // depicts timer unblocks
	netpollP                  // depicts network unblocks
	syscallP                  // depicts returns from syscalls
)

// parseTrace parses, post-processes and verifies the trace.
func parseTrace(r io.Reader) ([]*Event, error) {
	rawEvents, err := readTrace(r)
	if err != nil {
		return nil, err
	}
	events, err := parseEvents(rawEvents)
	if err != nil {
		return nil, err
	}
	err = postProcessTrace(events)
	if err != nil {
		return nil, err
	}
	return events, nil
}

// RawEvent is a helper type used during parsing.
type RawEvent struct {
	off  int
	typ  byte
	args []uint64
}

// readTrace does wire-format parsing and verification.
// It does not care about specific event types and argument meaning.
func readTrace(r io.Reader) ([]RawEvent, error) {
	// Read and validate trace header.
	var buf [8]byte
	off, err := r.Read(buf[:])
	if off != 8 || err != nil {
		return nil, fmt.Errorf("failed to read header: read %v, err %v", off, err)
	}
	if bytes.Compare(buf[:], []byte("gotrace\x00")) != 0 {
		return nil, fmt.Errorf("not a trace file")
	}

	// Read events.
	var events []RawEvent
	for {
		// Read event type and number of arguments (1 byte).
		off0 := off
		n, err := r.Read(buf[:1])
		if err == io.EOF {
			break
		}
		if err != nil || n != 1 {
			return nil, fmt.Errorf("failed to read trace at offset 0x%x: n=%v err=%v", off0, n, err)
		}
		off += n
		typ := buf[0] << 2 >> 2
		narg := buf[0]>>6 + 1
		ev := RawEvent{typ: typ, off: off0}
		if narg <= 3 {
			for i := 0; i < int(narg); i++ {
				var v uint64
				v, off, err = readVal(r, off)
				if err != nil {
					return nil, err
				}
				ev.args = append(ev.args, v)
			}
		} else {
			// If narg == 4, the first value is length of the event in bytes.
			var v uint64
			v, off, err = readVal(r, off)
			if err != nil {
				return nil, err
			}
			evLen := v
			off1 := off
			for evLen > uint64(off-off1) {
				v, off, err = readVal(r, off)
				if err != nil {
					return nil, err
				}
				ev.args = append(ev.args, v)
			}
			if evLen != uint64(off-off1) {
				return nil, fmt.Errorf("event has wrong length at offset 0x%x: want %v, got %v", off0, evLen, off-off1)
			}
		}
		events = append(events, ev)
	}
	return events, nil
}

// Parse events transforms raw events into events.
// It does analyze and verify per-event-type arguments.
func parseEvents(rawEvents []RawEvent) (events []*Event, err error) {
	var ticksPerSec, lastTs int64
	var lastG, timerGoid uint64
	var lastP int
	lastGs := make(map[int]uint64) // last goroutine running on P
	stacks := make(map[uint64][]*Frame)
	for _, raw := range rawEvents {
		if raw.typ == traceEvNone || raw.typ >= traceEvCount {
			err = fmt.Errorf("unknown event type %v at offset 0x%x", raw.typ, raw.off)
			return
		}
		desc := evDescriptions[raw.typ]
		if desc.name == "" {
			err = fmt.Errorf("missing description for event type %v", raw.typ)
			return
		}
		if raw.typ != traceEvStack {
			narg := len(desc.args)
			if desc.stack {
				narg++
			}
			if raw.typ != traceEvBatch && raw.typ != traceEvFrequency && raw.typ != traceEvTimerGoroutine {
				narg++ // timestamp
			}
			if len(raw.args) != narg {
				err = fmt.Errorf("%v has wrong number of arguments at offset 0x%x: want %v, got %v",
					desc.name, raw.off, narg, len(raw.args))
				return
			}
		}
		switch raw.typ {
		case traceEvBatch:
			lastGs[lastP] = lastG
			lastP = int(raw.args[0])
			lastG = lastGs[lastP]
			lastTs = int64(raw.args[1])
		case traceEvFrequency:
			ticksPerSec = int64(raw.args[0])
			if ticksPerSec <= 0 {
				err = fmt.Errorf("traceEvFrequency contains invalid frequency %v at offset 0x%x",
					ticksPerSec, raw.off)
				return
			}
		case traceEvTimerGoroutine:
			timerGoid = raw.args[0]
		case traceEvStack:
			if len(raw.args) < 2 {
				err = fmt.Errorf("traceEvStack has wrong number of arguments at offset 0x%x: want at least 2, got %v",
					raw.off, len(raw.args))
				return
			}
			size := raw.args[1]
			if size > 1000 {
				err = fmt.Errorf("traceEvStack has bad number of frames at offset 0x%x: %v",
					raw.off, size)
				return
			}
			id := raw.args[0]
			if id != 0 && size > 0 {
				stk := make([]*Frame, size)
				for i := 0; i < int(size); i++ {
					stk[i] = &Frame{pc: raw.args[i+2]}
				}
				stacks[id] = stk
			}
		default:
			e := &Event{off: raw.off, typ: raw.typ, p: lastP, g: lastG}
			e.ts = lastTs + int64(raw.args[0])
			lastTs = e.ts
			for i := range desc.args {
				e.args[i] = raw.args[i+1]
			}
			if desc.stack {
				e.stkID = raw.args[len(desc.args)+1]
			}
			switch raw.typ {
			case traceEvGoStart:
				lastG = e.args[0]
				e.g = lastG
			case traceEvGCStart, traceEvGCDone, traceEvGCScanStart, traceEvGCScanDone:
				e.g = 0
			case traceEvGoEnd, traceEvGoStop, traceEvGoSched, traceEvGoPreempt,
				traceEvGoSleep, traceEvGoBlock, traceEvGoBlockSend, traceEvGoBlockRecv,
				traceEvGoBlockSelect, traceEvGoBlockSync, traceEvGoBlockCond, traceEvGoBlockNet,
				traceEvGoSysBlock:
				lastG = 0
			}
			events = append(events, e)
		}
	}

	// Attach stack traces.
	for _, ev := range events {
		if ev.stkID != 0 {
			ev.stk = stacks[ev.stkID]
		}
	}

	// Sort by time and translate cpu ticks to real time.
	sort.Sort(EventList(events))
	if ticksPerSec == 0 {
		err = fmt.Errorf("no traceEvFrequency event")
		return
	}
	minTs := events[0].ts
	for _, ev := range events {
		ev.ts = (ev.ts - minTs) * 1e9 / ticksPerSec
		// Move timers and syscalls to separate fake Ps.
		if timerGoid != 0 && ev.g == timerGoid && ev.typ == traceEvGoUnblock {
			ev.p = timerP
		}
		if ev.typ == traceEvGoSysExit {
			ev.p = syscallP
			ev.g = ev.args[0]
		}
	}

	return
}

// postProcessTrace does inter-event verification and information restoration.
// The resulting trace is guaranteed to be consistent
// (for example, a P does not run two Gs at the same time, or a G is indeed
// blocked before an unblock event).
func postProcessTrace(events []*Event) error {
	const (
		gDead = iota
		gRunnable
		gRunning
		gWaiting
	)
	type gdesc struct {
		state   int
		ev      *Event
		evStart *Event
	}
	type pdesc struct {
		running bool
		g       uint64
		evGC    *Event
		evScan  *Event
		evSweep *Event
	}

	gs := make(map[uint64]gdesc)
	ps := make(map[int]pdesc)
	gs[0] = gdesc{state: gRunning}

	checkRunning := func(p pdesc, g gdesc, ev *Event) error {
		name := evDescriptions[ev.typ].name
		if g.state != gRunning {
			return fmt.Errorf("g %v is not running while %v (offset %v, time %v)", ev.g, name, ev.off, ev.ts)
		}
		if p.g != ev.g {
			return fmt.Errorf("p %v is not running g %v while %v (offset %v, time %v)", ev.p, ev.g, name, ev.off, ev.ts)
		}
		return nil
	}

	for _, ev := range events {
		g := gs[ev.g]
		p := ps[ev.p]

		switch ev.typ {
		case traceEvProcStart:
			if p.running {
				return fmt.Errorf("p %v is running before start (offset %v, time %v)", ev.p, ev.off, ev.ts)
			}
			p.running = true
		case traceEvProcStop:
			if !p.running {
				return fmt.Errorf("p %v is not running before stop (offset %v, time %v)", ev.p, ev.off, ev.ts)
			}
			if p.g != 0 {
				return fmt.Errorf("p %v is running a goroutine %v during stop (offset %v, time %v)", ev.p, p.g, ev.off, ev.ts)
			}
			p.running = false
		case traceEvGCStart:
			if p.evGC != nil {
				return fmt.Errorf("previous GC is not ended before a new one (offset %v, time %v)", ev.off, ev.ts)
			}
			p.evGC = ev
		case traceEvGCDone:
			if p.evGC == nil {
				return fmt.Errorf("bogus GC end (offset %v, time %v)", ev.off, ev.ts)
			}
			p.evGC.link = ev
			p.evGC = nil
		case traceEvGCScanStart:
			if p.evScan != nil {
				return fmt.Errorf("previous scanning is not ended before a new one (offset %v, time %v)", ev.off, ev.ts)
			}
			p.evScan = ev
		case traceEvGCScanDone:
			if p.evScan == nil {
				return fmt.Errorf("bogus scanning end (offset %v, time %v)", ev.off, ev.ts)
			}
			p.evScan.link = ev
			p.evScan = nil
		case traceEvGCSweepStart:
			if p.evSweep != nil {
				return fmt.Errorf("previous sweeping is not ended before a new one (offset %v, time %v)", ev.off, ev.ts)
			}
			p.evSweep = ev
		case traceEvGCSweepDone:
			if p.evSweep == nil {
				return fmt.Errorf("bogus sweeping end (offset %v, time %v)", ev.off, ev.ts)
			}
			p.evSweep.link = ev
			p.evSweep = nil
		case traceEvGoWaiting:
			g1 := gs[ev.args[0]]
			if g1.state != gRunnable {
				return fmt.Errorf("g %v is not runnable before traceEvGoWaiting (offset %v, time %v)", ev.args[0], ev.off, ev.ts)
			}
			g1.state = gWaiting
			gs[ev.args[0]] = g1
		case traceEvGoInSyscall:
			// this case is intentionally left blank
		case traceEvGoCreate:
			if err := checkRunning(p, g, ev); err != nil {
				return err
			}
			if _, ok := gs[ev.args[0]]; ok {
				return fmt.Errorf("g %v already exists (offset %v, time %v)", ev.args[0], ev.off, ev.ts)
			}
			gs[ev.args[0]] = gdesc{state: gRunnable, ev: ev}
		case traceEvGoStart:
			if g.state != gRunnable {
				return fmt.Errorf("g %v is not runnable before start (offset %v, time %v)", ev.g, ev.off, ev.ts)
			}
			if p.g != 0 {
				return fmt.Errorf("p %v is already running g %v while start g %v (offset %v, time %v)", ev.p, p.g, ev.g, ev.off, ev.ts)
			}
			g.state = gRunning
			g.evStart = ev
			p.g = ev.g
			if g.ev != nil {
				if g.ev.typ == traceEvGoCreate {
					// +1 because symblizer expects return pc.
					ev.stk = []*Frame{&Frame{pc: g.ev.args[1] + 1}}
				}
				g.ev.link = ev
				g.ev = nil
			}
		case traceEvGoEnd, traceEvGoStop:
			if err := checkRunning(p, g, ev); err != nil {
				return err
			}
			g.evStart.link = ev
			g.evStart = nil
			g.state = gDead
			p.g = 0
		case traceEvGoSched, traceEvGoPreempt:
			if err := checkRunning(p, g, ev); err != nil {
				return err
			}
			g.state = gRunnable
			g.evStart.link = ev
			g.evStart = nil
			p.g = 0
			g.ev = ev
		case traceEvGoUnblock:
			if g.state != gRunning {
				return fmt.Errorf("g %v is not running while unpark (offset %v, time %v)", ev.g, ev.off, ev.ts)
			}
			if ev.p != timerP && p.g != ev.g {
				return fmt.Errorf("p %v is not running g %v while unpark (offset %v, time %v)", ev.p, ev.g, ev.off, ev.ts)
			}
			g1 := gs[ev.args[0]]
			if g1.state != gWaiting {
				return fmt.Errorf("g %v is not waiting before unpark (offset %v, time %v)", ev.args[0], ev.off, ev.ts)
			}
			if g1.ev != nil && g1.ev.typ == traceEvGoBlockNet && ev.p != timerP {
				ev.p = netpollP
			}
			if g1.ev != nil {
				g1.ev.link = ev
			}
			g1.state = gRunnable
			g1.ev = ev
			gs[ev.args[0]] = g1
		case traceEvGoSysCall:
			if err := checkRunning(p, g, ev); err != nil {
				return err
			}
			g.ev = ev
		case traceEvGoSysBlock:
			if err := checkRunning(p, g, ev); err != nil {
				return err
			}
			g.state = gRunnable
			g.evStart.link = ev
			g.evStart = nil
			p.g = 0
		case traceEvGoSysExit:
			if g.state != gRunnable {
				return fmt.Errorf("g %v is not runnable during syscall exit (offset %v, time %v)", ev.g, ev.off, ev.ts)
			}
			if g.ev != nil && g.ev.typ == traceEvGoSysCall {
				g.ev.link = ev
			}
			g.ev = ev
		case traceEvGoSleep, traceEvGoBlock, traceEvGoBlockSend, traceEvGoBlockRecv,
			traceEvGoBlockSelect, traceEvGoBlockSync, traceEvGoBlockCond, traceEvGoBlockNet:
			if err := checkRunning(p, g, ev); err != nil {
				return err
			}
			g.state = gWaiting
			g.ev = ev
			g.evStart.link = ev
			g.evStart = nil
			p.g = 0
		}

		gs[ev.g] = g
		ps[ev.p] = p
	}

	return nil
}

// symbolizeTrace attaches func/file/line info to stack traces.
func symbolizeTrace(events []*Event, bin string) error {
	// First, collect and dedup all pcs.
	pcs := make(map[uint64]*Frame)
	for _, ev := range events {
		for _, f := range ev.stk {
			pcs[f.pc] = nil
		}
	}

	// Start addr2line.
	cmd := exec.Command("go", "tool", "addr2line", bin)
	in, err := cmd.StdinPipe()
	if err != nil {
		return fmt.Errorf("failed to pipe addr2line stdin: %v", err)
	}
	out, err := cmd.StdoutPipe()
	if err != nil {
		return fmt.Errorf("failed to pipe addr2line stdout: %v", err)
	}
	err = cmd.Start()
	if err != nil {
		return fmt.Errorf("failed to start addr2line: %v", err)
	}
	outb := bufio.NewReader(out)

	// Write all pcs to addr2line.
	// Need to copy pcs to an array, because map iteration order is non-deterministic.
	var pcArray []uint64
	for pc := range pcs {
		pcArray = append(pcArray, pc)
		_, err := fmt.Fprintf(in, "0x%x\n", pc-1)
		if err != nil {
			return fmt.Errorf("failed to write to addr2line: %v", err)
		}
	}
	in.Close()

	// Read in answers.
	for _, pc := range pcArray {
		fn, err := outb.ReadString('\n')
		if err != nil {
			return fmt.Errorf("failed to read from addr2line: %v", err)
		}
		file, err := outb.ReadString('\n')
		if err != nil {
			return fmt.Errorf("failed to read from addr2line: %v", err)
		}
		f := &Frame{pc: pc}
		f.fn = fn[:len(fn)-1]
		f.file = file[:len(file)-1]
		if colon := strings.LastIndex(f.file, ":"); colon != -1 {
			ln, err := strconv.Atoi(f.file[colon+1:])
			if err == nil {
				f.file = f.file[:colon]
				f.line = ln
			}
		}
		pcs[pc] = f
	}
	cmd.Wait()

	// Replace frames in events array.
	for _, ev := range events {
		for i, f := range ev.stk {
			ev.stk[i] = pcs[f.pc]
		}
	}

	return nil
}

// readVal reads unsigned base-128 value from r.
func readVal(r io.Reader, off0 int) (v uint64, off int, err error) {
	off = off0
	for i := 0; i < 10; i++ {
		var buf [1]byte
		var n int
		n, err = r.Read(buf[:])
		if err != nil || n != 1 {
			return 0, 0, fmt.Errorf("failed to read trace at offset: read %v, error %v", off0, n, err)
		}
		off++
		v |= uint64(buf[0]&0x7f) << (uint(i) * 7)
		if buf[0]&0x80 == 0 {
			return
		}
	}
	return 0, 0, fmt.Errorf("bad value at offset 0x%x", off0)
}

type EventList []*Event

func (l EventList) Len() int {
	return len(l)
}

func (l EventList) Less(i, j int) bool {
	return l[i].ts < l[j].ts
}

func (l EventList) Swap(i, j int) {
	l[i], l[j] = l[j], l[i]
}

// Event types in the trace.
// Verbatim copy from src/runtime/trace.go.
const (
	traceEvNone           = 0  // unused
	traceEvBatch          = 1  // start of per-P batch of events [pid, timestamp]
	traceEvFrequency      = 2  // contains tracer timer frequency [frequency (ticks per second)]
	traceEvStack          = 3  // stack [stack id, number of PCs, array of PCs]
	traceEvGomaxprocs     = 4  // current value of GOMAXPROCS [timestamp, GOMAXPROCS, stack id]
	traceEvProcStart      = 5  // start of P [timestamp]
	traceEvProcStop       = 6  // stop of P [timestamp]
	traceEvGCStart        = 7  // GC start [timestamp, stack id]
	traceEvGCDone         = 8  // GC done [timestamp]
	traceEvGCScanStart    = 9  // GC scan start [timestamp]
	traceEvGCScanDone     = 10 // GC scan done [timestamp]
	traceEvGCSweepStart   = 11 // GC sweep start [timestamp, stack id]
	traceEvGCSweepDone    = 12 // GC sweep done [timestamp]
	traceEvGoCreate       = 13 // goroutine creation [timestamp, new goroutine id, start PC, stack id]
	traceEvGoStart        = 14 // goroutine starts running [timestamp, goroutine id]
	traceEvGoEnd          = 15 // goroutine ends [timestamp]
	traceEvGoStop         = 16 // goroutine stops (like in select{}) [timestamp, stack]
	traceEvGoSched        = 17 // goroutine calls Gosched [timestamp, stack]
	traceEvGoPreempt      = 18 // goroutine is preempted [timestamp, stack]
	traceEvGoSleep        = 19 // goroutine calls Sleep [timestamp, stack]
	traceEvGoBlock        = 20 // goroutine blocks [timestamp, stack]
	traceEvGoUnblock      = 21 // goroutine is unblocked [timestamp, goroutine id, stack]
	traceEvGoBlockSend    = 22 // goroutine blocks on chan send [timestamp, stack]
	traceEvGoBlockRecv    = 23 // goroutine blocks on chan recv [timestamp, stack]
	traceEvGoBlockSelect  = 24 // goroutine blocks on select [timestamp, stack]
	traceEvGoBlockSync    = 25 // goroutine blocks on Mutex/RWMutex [timestamp, stack]
	traceEvGoBlockCond    = 26 // goroutine blocks on Cond [timestamp, stack]
	traceEvGoBlockNet     = 27 // goroutine blocks on network [timestamp, stack]
	traceEvGoSysCall      = 28 // syscall enter [timestamp, stack]
	traceEvGoSysExit      = 29 // syscall exit [timestamp, goroutine id]
	traceEvGoSysBlock     = 30 // syscall blocks [timestamp, stack]
	traceEvGoWaiting      = 31 // denotes that goroutine is blocked when tracing starts [goroutine id]
	traceEvGoInSyscall    = 32 // denotes that goroutine is in syscall when tracing starts [goroutine id]
	traceEvHeapAlloc      = 33 // memstats.heap_alloc change [timestamp, heap_alloc]
	traceEvNextGC         = 34 // memstats.next_gc change [timestamp, next_gc]
	traceEvTimerGoroutine = 35 // denotes timer goroutine [timer goroutine id]
	traceEvCount          = 36
)

var evDescriptions = [traceEvCount]struct {
	name  string
	stack bool
	args  []string
}{
	traceEvNone:           {"None", false, []string{}},
	traceEvBatch:          {"Batch", false, []string{"p", "ticks"}},
	traceEvFrequency:      {"Frequency", false, []string{"freq"}},
	traceEvStack:          {"Stack", false, []string{"id", "siz"}},
	traceEvGomaxprocs:     {"Gomaxprocs", true, []string{"procs"}},
	traceEvProcStart:      {"ProcStart", false, []string{}},
	traceEvProcStop:       {"ProcStop", false, []string{}},
	traceEvGCStart:        {"GCStart", true, []string{}},
	traceEvGCDone:         {"GCDone", false, []string{}},
	traceEvGCScanStart:    {"GCScanStart", false, []string{}},
	traceEvGCScanDone:     {"GCScanDone", false, []string{}},
	traceEvGCSweepStart:   {"GCSweepStart", true, []string{}},
	traceEvGCSweepDone:    {"GCSweepDone", false, []string{}},
	traceEvGoCreate:       {"GoCreate", true, []string{"g", "pc"}},
	traceEvGoStart:        {"GoStart", false, []string{"g"}},
	traceEvGoEnd:          {"GoEnd", false, []string{}},
	traceEvGoStop:         {"GoStop", true, []string{}},
	traceEvGoSched:        {"GoSched", true, []string{}},
	traceEvGoPreempt:      {"GoPreempt", true, []string{}},
	traceEvGoSleep:        {"GoSleep", true, []string{}},
	traceEvGoBlock:        {"GoBlock", true, []string{}},
	traceEvGoUnblock:      {"GoUnblock", true, []string{"g"}},
	traceEvGoBlockSend:    {"GoBlockSend", true, []string{}},
	traceEvGoBlockRecv:    {"GoBlockRecv", true, []string{}},
	traceEvGoBlockSelect:  {"GoBlockSelect", true, []string{}},
	traceEvGoBlockSync:    {"GoBlockSync", true, []string{}},
	traceEvGoBlockCond:    {"GoBlockCond", true, []string{}},
	traceEvGoBlockNet:     {"GoBlockNet", true, []string{}},
	traceEvGoSysCall:      {"GoSysCall", true, []string{}},
	traceEvGoSysExit:      {"GoSysExit", false, []string{"g"}},
	traceEvGoSysBlock:     {"GoSysBlock", true, []string{}},
	traceEvGoWaiting:      {"GoWaiting", false, []string{"g"}},
	traceEvGoInSyscall:    {"GoInSyscall", false, []string{"g"}},
	traceEvHeapAlloc:      {"HeapAlloc", false, []string{"mem"}},
	traceEvNextGC:         {"NextGC", false, []string{"mem"}},
	traceEvTimerGoroutine: {"TimerGoroutine", false, []string{"g"}},
}


text:
class Image::ContentsController < ApplicationController
  include Concerns::RicohApiAccess

  def show
    data = storage_api_client.download(params[:image_id])
    send_data data, type: 'image/jpeg', disposition: 'inline'
  end
end


text:
"""The group type API controller module."""

from oslo_utils import strutils
from oslo_utils import uuidutils
import six
import webob
from webob import exc

from manila.api.openstack import wsgi
from manila.api.views import share_group_types as views
from manila import exception
from manila.i18n import _
from manila.share_group import share_group_types

class ShareGroupTypesController(wsgi.Controller):
    """The share group types API controller for the OpenStack API."""

    resource_name = 'share_group_type'
    _view_builder_class = views.ShareGroupTypeViewBuilder

    def _check_body(self, body, action_name):
        if not self.is_valid_body(body, action_name):
            raise webob.exc.HTTPBadRequest()
        access = body[action_name]
        project = access.get('project')
        if not uuidutils.is_uuid_like(project):
            msg = _("Project value (%s) must be in uuid format.") % project
            raise webob.exc.HTTPBadRequest(explanation=msg)

    @wsgi.Controller.api_version('2.31', experimental=True)
    @wsgi.Controller.authorize
    def index(self, req):
        """Returns the list of share group types."""
        limited_types = self._get_share_group_types(req)
        return self._view_builder.index(req, limited_types)

    @wsgi.Controller.api_version('2.31', experimental=True)
    @wsgi.Controller.authorize
    def show(self, req, id):
        """Return a single share group type item."""
        context = req.environ['manila.context']
        try:
            share_group_type = share_group_types.get(context, id)
        except exception.NotFound:
            msg = _("Share group type with id %s not found.")
            raise exc.HTTPNotFound(explanation=msg % id)

        share_group_type['id'] = six.text_type(share_group_type['id'])
        return self._view_builder.show(req, share_group_type)

    @wsgi.Controller.api_version('2.31', experimental=True)
    @wsgi.Controller.authorize
    def default(self, req):
        """Return default share group type."""
        context = req.environ['manila.context']
        share_group_type = share_group_types.get_default(context)
        if not share_group_type:
            msg = _("Default share group type not found.")
            raise exc.HTTPNotFound(explanation=msg)

        share_group_type['id'] = six.text_type(share_group_type['id'])
        return self._view_builder.show(req, share_group_type)

    def _get_share_group_types(self, req):
        """Helper function that returns a list of share group type dicts."""
        filters = {}
        context = req.environ['manila.context']
        if context.is_admin:
            # Only admin has query access to all group types
            filters['is_public'] = self._parse_is_public(
                req.params.get('is_public'))
        else:
            filters['is_public'] = True
        limited_types = share_group_types.get_all(
            context, search_opts=filters).values()
        return list(limited_types)

    @staticmethod
    def _parse_is_public(is_public):
        """Parse is_public into something usable.

        :returns:
            - True: API should list public share group types only
            - False: API should list private share group types only
            - None: API should list both public and private share group types
        """
        if is_public is None:
            # preserve default value of showing only public types
            return True
        elif six.text_type(is_public).lower() == "all":
            return None
        else:
            try:
                return strutils.bool_from_string(is_public, strict=True)
            except ValueError:
                msg = _('Invalid is_public filter [%s]') % is_public
                raise exc.HTTPBadRequest(explanation=msg)

    @wsgi.Controller.api_version('2.31', experimental=True)
    @wsgi.action("create")
    @wsgi.Controller.authorize('create')
    def _create(self, req, body):
        """Creates a new share group type."""
        context = req.environ['manila.context']
        if not self.is_valid_body(body, 'share_group_type'):
            raise webob.exc.HTTPBadRequest()

        share_group_type = body['share_group_type']
        name = share_group_type.get('name')
        specs = share_group_type.get('group_specs', {})
        is_public = share_group_type.get('is_public', True)

        if not share_group_type.get('share_types'):
            msg = _("Supported share types must be provided.")
            raise webob.exc.HTTPBadRequest(explanation=msg)
        share_types = share_group_type.get('share_types')

        if name is None or name == "" or len(name) > 255:
            msg = _("Share group type name is not valid.")
            raise webob.exc.HTTPBadRequest(explanation=msg)
        if not (specs is None or isinstance(specs,  dict)):
            msg = _("Group specs can be either of 'None' or 'dict' types.")
            raise webob.exc.HTTPBadRequest(explanation=msg)
        if specs:
            for element in list(specs.keys()) + list(specs.values()):
                if not isinstance(element, six.string_types):
                    msg = _("Group specs keys and values should be strings.")
                    raise webob.exc.HTTPBadRequest(explanation=msg)
        try:
            share_group_types.create(
                context, name, share_types, specs, is_public)
            share_group_type = share_group_types.get_by_name(
                context, name)
        except exception.ShareGroupTypeExists as err:
            raise webob.exc.HTTPConflict(explanation=six.text_type(err))
        except exception.ShareTypeDoesNotExist as err:
            raise webob.exc.HTTPNotFound(explanation=six.text_type(err))
        except exception.NotFound:
            raise webob.exc.HTTPNotFound()
        return self._view_builder.show(req, share_group_type)

    @wsgi.Controller.api_version('2.31', experimental=True)
    @wsgi.action("delete")
    @wsgi.Controller.authorize('delete')
    def _delete(self, req, id):
        """Deletes an existing group type."""
        context = req.environ['manila.context']
        try:
            share_group_type = share_group_types.get(context, id)
            share_group_types.destroy(context, share_group_type['id'])
        except exception.ShareGroupTypeInUse:
            msg = _('Target share group type with id %s is still in use.')
            raise webob.exc.HTTPBadRequest(explanation=msg % id)
        except exception.NotFound:
            raise webob.exc.HTTPNotFound()
        return webob.Response(status_int=204)

    @wsgi.Controller.api_version('2.31', experimental=True)
    @wsgi.Controller.authorize('list_project_access')
    def share_group_type_access(self, req, id):
        context = req.environ['manila.context']
        try:
            share_group_type = share_group_types.get(
                context, id, expected_fields=['projects'])
        except exception.ShareGroupTypeNotFound:
            explanation = _("Share group type %s not found.") % id
            raise webob.exc.HTTPNotFound(explanation=explanation)

        if share_group_type['is_public']:
            expl = _("Access list not available for public share group types.")
            raise webob.exc.HTTPNotFound(explanation=expl)

        projects = []
        for project_id in share_group_type['projects']:
            projects.append(
                {'share_group_type_id': share_group_type['id'],
                 'project_id': project_id}
            )
        return {'share_group_type_access': projects}

    @wsgi.Controller.api_version('2.31', experimental=True)
    @wsgi.action('addProjectAccess')
    @wsgi.Controller.authorize('add_project_access')
    def _add_project_access(self, req, id, body):
        context = req.environ['manila.context']
        self._check_body(body, 'addProjectAccess')
        project = body['addProjectAccess']['project']
        self._assert_non_public_share_group_type(context, id)
        try:
            share_group_types.add_share_group_type_access(
                context, id, project)
        except exception.ShareGroupTypeAccessExists as err:
            raise webob.exc.HTTPConflict(explanation=six.text_type(err))
        return webob.Response(status_int=202)

    @wsgi.Controller.api_version('2.31', experimental=True)
    @wsgi.action('removeProjectAccess')
    @wsgi.Controller.authorize('remove_project_access')
    def _remove_project_access(self, req, id, body):
        context = req.environ['manila.context']
        self._check_body(body, 'removeProjectAccess')
        project = body['removeProjectAccess']['project']
        self._assert_non_public_share_group_type(context, id)
        try:
            share_group_types.remove_share_group_type_access(
                context, id, project)
        except exception.ShareGroupTypeAccessNotFound as err:
            raise webob.exc.HTTPNotFound(explanation=six.text_type(err))
        return webob.Response(status_int=202)

    def _assert_non_public_share_group_type(self, context, type_id):
        try:
            share_group_type = share_group_types.get(
                context, type_id)
            if share_group_type['is_public']:
                msg = _("Type access modification is not applicable to "
                        "public share group type.")
                raise webob.exc.HTTPConflict(explanation=msg)
        except exception.ShareGroupTypeNotFound as err:
            raise webob.exc.HTTPNotFound(explanation=six.text_type(err))

def create_resource():
    return wsgi.Resource(ShareGroupTypesController())


text:
package com.rometools.modules.fyyd.io;

import com.rometools.modules.fyyd.modules.FyydModule;
import com.rometools.rome.feed.module.Module;
import com.rometools.rome.io.ModuleGenerator;
import org.jdom2.Element;
import org.jdom2.Namespace;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 * The ModuleGenerator implementation for the Fyyd module.
 */
public class FyydGenerator implements ModuleGenerator {

    private static final Namespace NS = Namespace.getNamespace(FyydElement.PREFIX, FyydModule.URI);
    private static final Set<Namespace> NAMESPACES;

    static {
        final Set<Namespace> nss = new HashSet<Namespace>();
        nss.add(NS);
        NAMESPACES = Collections.unmodifiableSet(nss);
    }

    @Override
    public String getNamespaceUri() {
        return FyydModule.URI;
    }

    @Override
    public Set<Namespace> getNamespaces() {
        return NAMESPACES;
    }

    @Override
    public void generate(Module module, Element element) {
        if (module instanceof FyydModule) {
            final FyydModule fyyd = (FyydModule) module;
            generateVerify(fyyd.getVerify(), element);
        }
    }

    private void generateVerify(String verify, Element parent) {
        final Element child = new Element(FyydElement.VERIFY, NS);
        child.setText(verify);
        parent.addContent(child);
    }

}


text:
from flask import current_app

from changes.artifacts import manager
from changes.backends.base import UnrecoverableException
from changes.constants import Result
from changes.models import Artifact, JobPlan
from changes.queue.task import tracked_task

@tracked_task
def sync_artifact(artifact_id=None, **kwargs):
    """
    Downloads an artifact from jenkins.
    """
    artifact = Artifact.query.get(artifact_id)
    if artifact is None:
        return

    step = artifact.step

    if step.result == Result.aborted:
        return

    # TODO(dcramer): we eventually want to abstract the entirety of Jenkins
    # artifact syncing so that we pull files and then process them
    if artifact.file:
        try:
            manager.process(artifact)
        except Exception:
            current_app.logger.exception(
                'Unrecoverable exception processing artifact %s: %s',
                artifact.step_id, artifact)
    else:
        jobplan, implementation = JobPlan.get_build_step_for_job(job_id=step.job_id)

        try:
            implementation.fetch_artifact(artifact=artifact, **kwargs)

        except UnrecoverableException:
            current_app.logger.exception(
                'Unrecoverable exception fetching artifact %s: %s',
                artifact.step_id, artifact)


text:
package org.apache.bval.xml;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.bval.model.Validation;
import org.apache.commons.lang3.ClassUtils;

import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
import com.thoughtworks.xstream.annotations.XStreamOmitField;

/**
 * Description: root element of a xml-beanInfos document<br/>
 */
@XStreamAlias("beanInfos")
public class XMLMetaBeanInfos {
    @XStreamAsAttribute
    private String id;
    @XStreamAsAttribute
    private String version;
    @XStreamImplicit
    private List<XMLMetaValidator> validators;
    @XStreamImplicit
    private List<XMLMetaBean> beans;
    @XStreamOmitField
    private Map<String, XMLMetaBean> beanLookup;
    @XStreamOmitField
    private Map<String, XMLMetaValidator> validationLookup;

    /**
     * used for identification, may be empty, if there is no database origin for this object.
     * could also contain a file-name - can be used flexible...
     */
    public String getId() {
        return id;
    }

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

    /**
     * used for change-detection, when some other component caches MetaBeans based on this
     * object. when the version changes, the cache could compare to its version state and recompute.
     * can be used flexible...
     */
    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public List<XMLMetaValidator> getValidators() {
        return validators;
    }

    public void setValidators(List<XMLMetaValidator> validators) {
        this.validators = validators;
    }

    public List<XMLMetaBean> getBeans() {
        return beans;
    }

    public void setBeans(List<XMLMetaBean> beans) {
        this.beans = beans;
    }

    public XMLMetaBean getBean(String id) {
        if (beans == null) return null;
        if (beanLookup == null) initBeanLookup();
        return beanLookup.get(id);
    }

    private void initBeanLookup() {
        final HashMap<String, XMLMetaBean> map = new HashMap<String, XMLMetaBean>(beans.size());
        for (XMLMetaBean bean : beans) {
            map.put(bean.getId(), bean);
        }
        beanLookup = new ConcurrentHashMap<String, XMLMetaBean>(map);
    }

    private void initValidationLookup() throws Exception {
        final HashMap<String, XMLMetaValidator> map = new HashMap<String, XMLMetaValidator>(validators.size());
        for (XMLMetaValidator xv : validators) {
            if (xv.getJava() != null) {
                Validation validation =
                        (Validation) ClassUtils.getClass(xv.getJava()).newInstance();
                xv.setValidation(validation);
                map.put(xv.getId(), xv);
            }
        }
        validationLookup = new ConcurrentHashMap<String, XMLMetaValidator>(map);
    }

    public void addBean(XMLMetaBean bean) {
        if (beans == null) beans = new ArrayList<XMLMetaBean>();
        beans.add(bean);
    }

    public XMLMetaValidator getValidator(String id) throws Exception {
        if (validators == null) return null;
        if (validationLookup == null) initValidationLookup();
        return validationLookup.get(id);
    }

    public void addValidator(XMLMetaValidator validator) {
        if (validators == null) validators = new ArrayList<XMLMetaValidator>();
        validators.add(validator);
    }
}


text:
package com.example;

import org.rapidoid.annotation.Valid;
import org.rapidoid.log.Log;
import org.rapidoid.security.Auth;
import org.rapidoid.setup.App;
import org.rapidoid.setup.My;
import org.rapidoid.u.U;

public class GettingStartedExample {

    public static void main(String[] args) {
        App app = new App(args, "secret=YOUR-SECRET");

        Log.info("Starting application");

        app.beans(new MyCtrl()); // provide beans (controllers, services etc.)

        app.get("/books").json(() -> {
            // TODO get all books
            return U.list();
        });

        app.post("/books").json((@Valid Book book) -> {
            // TODO insert new book
            return book;
        });

        app.put("/books/{id}").json((Long id, @Valid Book book) -> {
            // TODO update/replace book
            return true;
        });

        app.delete("/books/{id}").json((Long id) -> {
            // TODO delete book
            return true;
        });

        // Dummy login: successful if the username is the same as the password, or a proper password is entered
        My.loginProvider((req, username, password) -> username.equals(password) || Auth.login(username, password));

        // Gives the 'manager' role to every logged-in user except 'admin'
        My.rolesProvider((req, username) -> U.eq(username, "admin") ? Auth.getRolesFor(username) : U.set("manager"));

        app.start(); // now everything is ready, so start the application
    }

}


text:
<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <artifactId>emb-components</artifactId>
    <groupId>org.commonjava.emb.components</groupId>
    <version>0.6-SNAPSHOT</version>
  </parent>

  <artifactId>emb-graph-support</artifactId>
  <name>EMB Graph Support</name>

  <dependencies>
    <dependency>
      <groupId>org.jgrapht</groupId>
      <artifactId>jgrapht-jdk1.5</artifactId>
      <version>0.7.3</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
    </dependency>
  </dependencies>
</project>


text:
<?php

/**
 * Class SiteOrigin_Widget_Field_Section
 */
class SiteOrigin_Widget_Field_Section extends SiteOrigin_Widget_Field_Container_Base {

	protected function render_field( $value, $instance ) {
		?>
		<div class="siteorigin-widget-section <?php if( $this->state == 'closed' ) echo 'siteorigin-widget-section-hide'; ?>"><?php
		if ( !isset( $this->fields ) || empty($this->fields ) ) {
			echo '
';
			return;
		}
		$this->create_and_render_sub_fields( $value, array( 'name' => $this->base_name, 'type' => 'section' ) );
		?>
			<input type="hidden"
			       name="<?php echo esc_attr( $this->element_name . '[so_field_container_state]' ) ?>" id="<?php echo esc_attr( $this->element_id . '-so_field_container_state' ) ?>"
			       class="siteorigin-widget-input siteorigin-widget-field-container-state" value="<?php echo esc_attr( $this->state ) ?>"/>

<?php
	}

}


text:
package com.google.auto.factory.processor;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;

import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Messager;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.inject.Inject;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.ExecutableType;
import javax.lang.model.util.ElementFilter;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
import javax.tools.Diagnostic.Kind;

import com.google.auto.factory.AutoFactory;
import com.google.auto.factory.Provided;
import com.google.auto.service.AutoService;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Multimaps;

import dagger.ObjectGraph;

/**
 * The annotation processor that generates factories for {@link AutoFactory} annotations.
 *
 * @author Gregory Kick
 */
@AutoService(Processor.class)
public final class AutoFactoryProcessor extends AbstractProcessor {
  @Inject FactoryDescriptorGenerator factoryDescriptorGenerator;
  @Inject AutoFactoryDeclaration.Factory declarationFactory;
  @Inject ProvidedChecker providedChecker;
  @Inject Messager messager;
  @Inject Elements elements;
  @Inject Types types;
  @Inject FactoryWriter factoryWriter;

  @Override
  public synchronized void init(ProcessingEnvironment processingEnv) {
    super.init(processingEnv);
    ObjectGraph.create(new ProcessorModule(processingEnv), new AutoFactoryProcessorModule())
        .inject(this);
  }

  @Override
  public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    try {
      doProcess(annotations, roundEnv);
    } catch (Throwable e) {
      messager.printMessage(Kind.ERROR, "Failed to process @AutoFactory annotations:\n"
          + Throwables.getStackTraceAsString(e));
    }
    return false;
  }

  private void doProcess(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    for (Element element : roundEnv.getElementsAnnotatedWith(Provided.class)) {
      providedChecker.checkProvidedParameter(element);
    }

    ImmutableListMultimap.Builder<String, FactoryMethodDescriptor> indexedMethods =
        ImmutableListMultimap.builder();
    ImmutableSet.Builder<ImplemetationMethodDescriptor> implemetationMethodDescriptors =
        ImmutableSet.builder();
    for (Element element : roundEnv.getElementsAnnotatedWith(AutoFactory.class)) {
      Optional<AutoFactoryDeclaration> declaration = declarationFactory.createIfValid(element);
      if (declaration.isPresent()) {
        TypeElement extendingType = declaration.get().extendingType();
        List<ExecutableElement> supertypeMethods =
            ElementFilter.methodsIn(elements.getAllMembers(extendingType));
        for (ExecutableElement supertypeMethod : supertypeMethods) {
          if (supertypeMethod.getModifiers().contains(Modifier.ABSTRACT)) {
            ExecutableType methodType = Elements2.getExecutableElementAsMemberOf(
                types, supertypeMethod, extendingType);
            implemetationMethodDescriptors.add(new ImplemetationMethodDescriptor.Builder()
                .name(supertypeMethod.getSimpleName().toString())
                .returnType(getAnnotatedType(element).getQualifiedName().toString())
                .publicMethod()
                .passedParameters(Parameter.forParameterList(
                    supertypeMethod.getParameters(), methodType.getParameterTypes()))
                .build());
          }
        }
        for (TypeElement implementingType : declaration.get().implementingTypes()) {
          List<ExecutableElement> interfaceMethods =
              ElementFilter.methodsIn(elements.getAllMembers(implementingType));
          for (ExecutableElement interfaceMethod : interfaceMethods) {
            if (interfaceMethod.getModifiers().contains(Modifier.ABSTRACT)) {
              ExecutableType methodType = Elements2.getExecutableElementAsMemberOf(
                  types, interfaceMethod, implementingType);
              implemetationMethodDescriptors.add(new ImplemetationMethodDescriptor.Builder()
                  .name(interfaceMethod.getSimpleName().toString())
                  .returnType(getAnnotatedType(element).getQualifiedName().toString())
                  .publicMethod()
                  .passedParameters(Parameter.forParameterList(
                      interfaceMethod.getParameters(), methodType.getParameterTypes()))
                  .build());
            }
          }
        }
      }

      ImmutableSet<FactoryMethodDescriptor> descriptors =
          factoryDescriptorGenerator.generateDescriptor(element);
      indexedMethods.putAll(
          Multimaps.index(descriptors, new Function<FactoryMethodDescriptor, String>() {
            @Override public String apply(FactoryMethodDescriptor descriptor) {
              return descriptor.factoryName();
            }
          }));
    }

    for (Entry<String, Collection<FactoryMethodDescriptor>> entry
        : indexedMethods.build().asMap().entrySet()) {
      ImmutableSet.Builder<String> extending = ImmutableSet.builder();
      ImmutableSortedSet.Builder<String> implementing = ImmutableSortedSet.naturalOrder();
      boolean publicType = false;
      for (FactoryMethodDescriptor methodDescriptor : entry.getValue()) {
        extending.add(methodDescriptor.declaration().extendingType().getQualifiedName().toString());
        for (TypeElement implementingType : methodDescriptor.declaration().implementingTypes()) {
          implementing.add(implementingType.getQualifiedName().toString());
        }
        publicType |= methodDescriptor.publicMethod();
      }
      try {
        factoryWriter.writeFactory(
            new FactoryDescriptor(
                entry.getKey(),
                Iterables.getOnlyElement(extending.build()),
                implementing.build(),
                publicType,
                ImmutableSet.copyOf(entry.getValue()),
                // TODO(gak): this needs to be indexed too
                implemetationMethodDescriptors.build()));
      } catch (IOException e) {
        messager.printMessage(Kind.ERROR, "failed");
      }
    }
  }

  private TypeElement getAnnotatedType(Element element) {
    List<TypeElement> types = ImmutableList.of();
    while (types.isEmpty()) {
      types = ElementFilter.typesIn(Arrays.asList(element));
      element = element.getEnclosingElement();
    }
    return Iterables.getOnlyElement(types);
  }

  @Override
  public Set<String> getSupportedAnnotationTypes() {
    return ImmutableSet.of(AutoFactory.class.getName(), Provided.class.getName());
  }

  @Override
  public SourceVersion getSupportedSourceVersion() {
    return SourceVersion.latestSupported();
  }
}


text:
package j.util.concurrent;

import org.junit.Test;

import java.util.concurrent.Semaphore;
import static org.junit.Assert.assertEquals;

/**
 * Created by Rybalko on 05.04.2016.
 */
public class SemaphoreTest {
    private final Semaphore semaphore = new Semaphore(3, true);

    public static void main(String[] args) {
        SemaphoreTest test = new SemaphoreTest();
        test.test1();
    }

    @Test
    public void test1() {
        assertEquals(true, semaphore.tryAcquire());
        assertEquals(true, semaphore.tryAcquire());
        assertEquals(true, semaphore.tryAcquire());
        assertEquals(false, semaphore.tryAcquire());
        semaphore.release();
        assertEquals(true, semaphore.tryAcquire());
        assertEquals(false, semaphore.tryAcquire());
    }
}


text:
import { expect } from 'chai';
import 'mocha';

import {ContructorsArgumentIsNotIntegerError} from '../../gun-tree-ts/common';
import {Vector2D} from '../../gun-tree-ts/vector';
import {Bullet} from '../../gun-tree-ts/bullet';
import {Effect} from '../../gun-tree-ts/effect';
import {Gun, AimingDirectionType, UnusableDirectionTypeError} from '../../gun-tree-ts/gun-base';
import {FiringProperty} from '../../gun-tree-ts/player';
import {Nop, Fire, Combine} from '../../gun-tree-ts/gun-contents/gun-primitive';
import {DebuggerGunTreePlayer} from '../../gun-tree-ts/debugger/debugger-player';
import {SetAim, RestrictAimAngle}
    from '../../gun-tree-ts/gun-contents/gun-modifier-aiming';

class TestSetAim extends SetAim {
    public computeAngle(property: FiringProperty): number {
        return super.computeAngle(property);
    }
}

describe('SetAim_gun_unit_test', () => {
    it('throw_exception_if_unusable_direction_type_was_used', () => {
        const player = new DebuggerGunTreePlayer();
        const property = new FiringProperty(player);
        const muzzleId = 10;
        property.muzzleId = muzzleId;

        const gun = new SetAim(AimingDirectionType.CurrentDirection);
        const generator = gun.activate(property);
        expect(() => {generator.next();}).to.throws(UnusableDirectionTypeError);
    });

    it('activate', () => {
        const player = new DebuggerGunTreePlayer();
        const property = new FiringProperty(player);
        const muzzleId = 10;
        property.muzzleId = muzzleId;

        const absAngle = 5;
        player.absoluteAngle = absAngle;

        const gun = new SetAim(AimingDirectionType.Absolute);
        for (const _ of gun.activate(property)) {}
        expect(property.baseAngle).to.equals(absAngle);
    });

    it('absolute', () => {
        const player = new DebuggerGunTreePlayer();
        const property = new FiringProperty(player);
        const muzzleId = 10;
        property.muzzleId = muzzleId;

        const absAngle = 5;
        player.absoluteAngle = absAngle;

        const gun = new TestSetAim(AimingDirectionType.Absolute);
        expect(gun.computeAngle(property)).to.equals(absAngle);
    });

    it('muzzle', () => {
        const player = new DebuggerGunTreePlayer();
        const property = new FiringProperty(player);
        const muzzleId = 10;
        property.muzzleId = muzzleId;

        const muzzleAngle = 5;
        player.muzzleAngles[muzzleId] = muzzleAngle;
        player.muzzleLocations[muzzleId] = new Vector2D(1, 2);

        const gun = new TestSetAim(AimingDirectionType.Muzzle);
        expect(gun.computeAngle(property)).to.equals(muzzleAngle);
    });

    it('aiming_from_fire_location', () => {
        const smallNum = 10**-3;
        const rt3 = Math.sqrt(3);
        const player = new DebuggerGunTreePlayer();
        const property = new FiringProperty(player);
        const muzzleId = 10;
        property.muzzleId = muzzleId;

        const muzzleLoc = new Vector2D(1, 2);
        player.muzzleAngles[muzzleId] = 0;
        player.muzzleLocations[muzzleId] = muzzleLoc;

        const fireOffset = new Vector2D(3, 4);
        property.fireLocationOffset = fireOffset;

        const fireLoc = Vector2D.add(muzzleLoc, fireOffset);
        const enemyLoc = Vector2D.add(fireLoc, new Vector2D(1, rt3));  // 60 degrees.
        player.hasAnyTarget = true;
        player.targetLocation = enemyLoc;

        const targetAngle = 60;
        const gun = new TestSetAim(AimingDirectionType.AimFromFireLocation);
        expect(gun.computeAngle(property)).to.closeTo(targetAngle, smallNum);
    });

    it('aiming_from_muzzle', () => {
        const smallNum = 10**-3;
        const rt3 = Math.sqrt(3);
        const player = new DebuggerGunTreePlayer();
        const property = new FiringProperty(player);
        const muzzleId = 10;
        property.muzzleId = muzzleId;

        const muzzleLoc = new Vector2D(1, 2);
        player.muzzleAngles[muzzleId] = 0;
        player.muzzleLocations[muzzleId] = muzzleLoc;

        const fireOffset = new Vector2D(3, 4);
        property.fireLocationOffset = fireOffset;

        const fireLoc = Vector2D.add(muzzleLoc, fireOffset);
        const enemyLoc = Vector2D.add(muzzleLoc, new Vector2D(1, rt3));  // 60 degrees.
        player.hasAnyTarget = true;
        player.targetLocation = enemyLoc;

        const targetAngle = 60;
        const gun = new TestSetAim(AimingDirectionType.AimFromMuzzle);
        expect(gun.computeAngle(property)).to.closeTo(targetAngle, smallNum);
    });
});

describe('RestrictAimAngle_gun_unit_test', () => {
    it('restrict', () => {
        const smallNum = 10**-3;
        const player = new DebuggerGunTreePlayer();
        const property = new FiringProperty(player);
        const muzzleId = 10;

        const wayNum = 4;
        const gun = new RestrictAimAngle(wayNum);

        const targetAngle = 360 / wayNum;
        const angle1 = targetAngle + (360 / wayNum / 2 - 0.01);
        const angle2 = targetAngle - (360 / wayNum / 2 - 0.01);
        expect(gun.computeRestrictedAngle(angle1)).to.closeTo(targetAngle, smallNum);
        expect(gun.computeRestrictedAngle(angle2)).to.closeTo(targetAngle, smallNum);
    });

    it('bad_way_num', () => {
        const smallNum = 10**-3;
        const player = new DebuggerGunTreePlayer();
        const property = new FiringProperty(player);
        const muzzleId = 10;

        const wayNum = 0;
        const gun = new RestrictAimAngle(wayNum);

        const targetAngle = 1.5;
        expect(gun.computeRestrictedAngle(targetAngle)).to.equals(targetAngle);
    });

    it('activate', () => {
        const smallNum = 10**-3;
        const player = new DebuggerGunTreePlayer();
        const property = new FiringProperty(player);
        const muzzleId = 10;

        const wayNum = 4;
        const gun = new RestrictAimAngle(wayNum);

        const targetAngle = 360 / wayNum;
        const angle1 = targetAngle + (360 / wayNum / 2 - 0.01);
        property.baseAngle = angle1;
        for (const _ of gun.activate(property)) {}
        expect(property.baseAngle).to.closeTo(targetAngle, smallNum);
    });

    it('throw_exception_if_constructor_argument_is_not_int_1', () => {
        // Check exception.
        expect(() => {new RestrictAimAngle(0.1);}).to.throw(ContructorsArgumentIsNotIntegerError);
    });
});


text:
package org.unc.hive.services.rs;

import java.util.TreeMap;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.xml.namespace.QName;

import edu.unc.ils.mrc.hive.api.SKOSScheme;
import edu.unc.ils.mrc.hive.api.SKOSServer;

/**
 * The SchemesResource class utilizes the SKOSServer
 * interface to provides JAX-RS based RESTful access to SKOSScheme objects
 * and their attributes and to query a scheme for its index of concepts.
 *
 * The basic URI pattern for all methods in the class is "schemes"
 *
 * Many, though not all, of the methods return "text/plain" output,
 * so this is the default Content-Type. Other methods return "application/xml"
 * and these use the @Produces annotation to override the default setting.
 *
 * @author dcosta
 *
 */
@Produces("text/plain")
@Path("schemes")
public class SchemesResource {

  /**
   * Gets the list of scheme names supported by the HIVE-CORE system,
   * one scheme name per line.
   *
   * @return         a list of scheme names, one per line. For example:
   *                   lter
   *                   nbii
   */
  @GET
  @Path("schemeNames")
  public String getSchemeNames() {
    StringBuffer schemeNames = new StringBuffer("");
    SKOSServer skosServer = ConfigurationListener.getSKOSServer();

    TreeMap<String, SKOSScheme> skosSchemes = skosServer.getSKOSSchemas();

    for (String s : skosSchemes.keySet()) {
      schemeNames.append(s);
      schemeNames.append("\n");
    }

    return schemeNames.toString().trim();
  }

  /**
   * Gets the lastDate value for a given scheme.
   *
   * @param schemeName      the specified scheme name, e.g. "nbii"
   * @return                the lastDate timestamp value, for example:
   *                            "Fri Jun 25 14:28:32 MDT 2010"
   */
  @GET
  @Path("{schemeName}/lastDate")
  public String getLastDate(@PathParam("schemeName") String schemeName) {
    String lastDate = "";
    SKOSServer skosServer = ConfigurationListener.getSKOSServer();

    if (schemeName != null) {
      TreeMap<String, SKOSScheme> skosSchemes = skosServer.getSKOSSchemas();

      for (String s : skosSchemes.keySet()) {
        if (s.equalsIgnoreCase(schemeName)) {
          SKOSScheme skosScheme = skosSchemes.get(s);
          if (skosScheme != null) {
            lastDate = skosScheme.getLastDate();
          }
        }
      }
    }

    return lastDate;
  }

  /**
   * Gets the name value for a given scheme. Essentially the
   * same name that is passed in is returned, but in its
   * case-sensitive form.
   *
   * @param schemeName      the specified scheme, e.g. "nbii"
   * @return                the name value, for example: "NBII"
   */
  @GET
  @Path("{schemeName}/name")
  public String getName(@PathParam("schemeName") String schemeName) {
    String name = "";
    SKOSServer skosServer = ConfigurationListener.getSKOSServer();

    if (schemeName != null) {
      TreeMap<String, SKOSScheme> skosSchemes = skosServer.getSKOSSchemas();

      for (String s : skosSchemes.keySet()) {
        if (s.equalsIgnoreCase(schemeName)) {
          SKOSScheme skosScheme = skosSchemes.get(s);
          if (skosScheme != null) {
            name = skosScheme.getName();
          }
        }
      }
    }

    return name;
  }

  /**
   * Gets the longName value for a given scheme.
   *
   * @param schemeName      the specified scheme name, e.g. "nbii"
   * @return                the longName value, for example:
   *                           "CSA/NBII Biocomplexity Thesaurus"
   */
  @GET
  @Path("{schemeName}/longName")
  public String getLongName(@PathParam("schemeName") String schemeName) {
    String longName = "";
    SKOSServer skosServer = ConfigurationListener.getSKOSServer();

    if (schemeName != null) {
      TreeMap<String, SKOSScheme> skosSchemes = skosServer.getSKOSSchemas();

      for (String s : skosSchemes.keySet()) {
        if (s.equalsIgnoreCase(schemeName)) {
          SKOSScheme skosScheme = skosSchemes.get(s);
          if (skosScheme != null) {
            longName = skosScheme.getLongName();
          }
        }
      }
    }

    return longName;
  }

  /**
   * Gets the number of concepts for a given scheme.
   *
   * @param schemeName      the specified scheme name, e.g. "nbii"
   * @return                the number of concepts, e.g. "10000"
   */
  @GET
  @Path("{schemeName}/numberOfConcepts")
  public String getNumberOfConcepts(@PathParam("schemeName") String schemeName) {
    Long numberOfConcepts = -1L;
    SKOSServer skosServer = ConfigurationListener.getSKOSServer();

    if (schemeName != null) {
      TreeMap<String, SKOSScheme> skosSchemes = skosServer.getSKOSSchemas();

      for (String s : skosSchemes.keySet()) {
        if (s.equalsIgnoreCase(schemeName)) {
          SKOSScheme skosScheme = skosSchemes.get(s);
          if (skosScheme != null) {
            numberOfConcepts = skosScheme.getNumberOfConcepts();
          }
        }
      }
    }

    return numberOfConcepts.toString();
  }

  /**
   * Gets the number of relations for a given scheme.
   *
   * @param schemeName      the specified scheme name, e.g. "nbii"
   * @return                the number of relations, e.g. "22356"
   */
  @GET
  @Path("{schemeName}/numberOfRelations")
  public String getNumberOfRelations(@PathParam("schemeName") String schemeName) {
    Long numberOfRelations = -1L;
    SKOSServer skosServer = ConfigurationListener.getSKOSServer();

    if (schemeName != null) {
      TreeMap<String, SKOSScheme> skosSchemes = skosServer.getSKOSSchemas();

      for (String s : skosSchemes.keySet()) {
        if (s.equalsIgnoreCase(schemeName)) {
          SKOSScheme skosScheme = skosSchemes.get(s);
          if (skosScheme != null) {
            numberOfRelations = skosScheme.getNumberOfRelations();
          }
        }
      }
    }

    return numberOfRelations.toString();
  }

  /**
   * Gets the schema URI value for a given scheme.
   *
   * @param schemeName   the specified scheme name, e.g. "nbii"
   * @return             the schema URI value, e.g. "http://thesaurus.nbii.gov"
   */
  @GET
  @Path("{schemeName}/schemaURI")
  public String getSchemaURI(@PathParam("schemeName") String schemeName) {
    String schemaURI = "";
    SKOSServer skosServer = ConfigurationListener.getSKOSServer();

    if (schemeName != null) {
      TreeMap<String, SKOSScheme> skosSchemes = skosServer.getSKOSSchemas();

      for (String s : skosSchemes.keySet()) {
        if (s.equalsIgnoreCase(schemeName)) {
          SKOSScheme skosScheme = skosSchemes.get(s);
          if (skosScheme != null) {
            schemaURI = skosScheme.getSchemaURI();
          }
        }
      }
    }

    return schemaURI;
  }

  /**
   * Gets the alpha index for a given scheme, represented as an XML formatted
   * list of concepts.
   *
   * @param schemeName      the specified scheme name, e.g. "nbii"
   * @return                an XML formatted list of concepts
   */
  @GET
  @Path("{schemeName}/alphaIndex")
  @Produces("application/xml")
  public String getAlphaIndex(@PathParam("schemeName") String schemeName) {
    String xmlString = "";
    SKOSServer skosServer = ConfigurationListener.getSKOSServer();

    if (schemeName != null) {
      TreeMap<String, SKOSScheme> skosSchemes = skosServer.getSKOSSchemas();

      for (String s : skosSchemes.keySet()) {
        if (s.equalsIgnoreCase(schemeName)) {
          SKOSScheme skosScheme = skosSchemes.get(s);
          if (skosScheme != null) {
            TreeMap<String, QName> alphaIndex = (TreeMap<String, QName>) skosScheme.getAlphaIndex();
            if (alphaIndex != null) {
              xmlString =
                ConceptsResource.conceptTreeMapToXML(alphaIndex);
            }
          }
        }
      }
    }

    return xmlString;
  }

  /**
   * Gets the alpha index for a given scheme for all concepts that start
   * with the specified letter sequence.
   *
   * @param schemeName      the specified scheme name, e.g. "nbii"
   * @param  startLetters   the specified start letter sequence
   * @return                an XML formatted list of concepts
   */
  @GET
  @Path("{schemeName}/subAlphaIndex/{startLetters}")
  @Produces("application/xml")
  public String getSubAlphaIndex(@PathParam("schemeName") String schemeName,
                                 @PathParam("startLetters") String startLetters
                                ) {
    String xmlString = "";
    SKOSServer skosServer = ConfigurationListener.getSKOSServer();

    if (schemeName != null && startLetters != null) {
      TreeMap<String, SKOSScheme> skosSchemes = skosServer.getSKOSSchemas();

      for (String s : skosSchemes.keySet()) {
        if (s.equalsIgnoreCase(schemeName)) {
          SKOSScheme skosScheme = skosSchemes.get(s);
          if (skosScheme != null) {
            TreeMap<String, QName> subAlphaIndex =
              skosScheme.getSubAlphaIndex(startLetters);
            if (subAlphaIndex != null) {
              xmlString = ConceptsResource.conceptTreeMapToXML(subAlphaIndex);
            }
          }
        }
      }
    }

    return xmlString;
  }

  /**
   * Gets the top concept index for a given scheme. (Top concepts are any
   * concepts in the scheme that do not have any parent concepts.)
   *
   * @param schemeName      the specified scheme name, e.g. "nbii"
   * @return                an XML formatted list of top concepts
   */
  @GET
  @Path("{schemeName}/topConceptIndex")
  @Produces("application/xml")
  public String getTopConceptIndex(@PathParam("schemeName") String schemeName) {
    String xmlString = "";
    SKOSServer skosServer = ConfigurationListener.getSKOSServer();

    if (schemeName != null) {
      TreeMap<String, SKOSScheme> skosSchemes = skosServer.getSKOSSchemas();

      for (String s : skosSchemes.keySet()) {
        if (s.equalsIgnoreCase(schemeName)) {
          SKOSScheme skosScheme = skosSchemes.get(s);
          if (skosScheme != null) {
            TreeMap<String, QName> topConceptIndex =
            	(TreeMap<String, QName>) skosScheme.getTopConceptIndex();
            if (topConceptIndex != null) {
              xmlString =
                ConceptsResource.conceptTreeMapToXML(topConceptIndex);
            }
          }
        }
      }
    }

    return xmlString;
  }

  /**
   * Gets the sub-top-concept index for a given scheme for all top concepts
   * that start with the specified letter sequence.
   *
   * @param schemeName      the specified scheme name, e.g. "nbii"
   * @param  startLetters   the specified start letter sequence
   * @return                an XML formatted list of top concepts
   */
  @GET
  @Path("{schemeName}/subTopConceptIndex/{startLetters}")
  @Produces("application/xml")
  public String getSubTopConceptIndex(@PathParam("schemeName") String schemeName,
                                 @PathParam("startLetters") String startLetters
                                ) {
    String xmlString = "";
    SKOSServer skosServer = ConfigurationListener.getSKOSServer();

    if (schemeName != null && startLetters != null) {
      TreeMap<String, SKOSScheme> skosSchemes = skosServer.getSKOSSchemas();

      for (String s : skosSchemes.keySet()) {
        if (s.equalsIgnoreCase(schemeName)) {
          SKOSScheme skosScheme = skosSchemes.get(s);
          if (skosScheme != null) {
            TreeMap<String, QName> topConceptIndex =
              (TreeMap<String, QName>) skosScheme.getSubTopConceptIndex(startLetters);
            if (topConceptIndex != null) {
              xmlString =
                ConceptsResource.conceptTreeMapToXML(topConceptIndex);
            }
          }
        }
      }
    }

    return xmlString;
  }

}