text:
module WebkitRemote

class Client

# API for the Network domain.
module Network
  # Enables or disables the generation of events in the Network domain.
  #
  # @param [Boolean] new_network_events if true, the browser debugger will
  #     generate Network.* events
  def network_events=(new_network_events)
    new_network_events = !!new_network_events
    if new_network_events != network_events
      @rpc.call(new_network_events ? 'Network.enable' : 'Network.disable')
      @network_events = new_network_events
    end
    new_network_events
  end

  # Enables or disables the use of the network cache.
  #
  # @param [Boolean] new_disable_cache if true, the browser will not use its
  #     network cache, and will always generate HTTP requests
  def disable_cache=(new_disable_cache)
    new_disable_cache = !!new_disable_cache
    if new_disable_cache != disable_cache
      @rpc.call 'Network.setCacheDisabled', cacheDisabled: new_disable_cache
      @disable_cache = new_disable_cache
    end
    new_disable_cache
  end

  # Sets the User-Agent header that the browser will use to identify itself.
  #
  # @param [String] new_user_agent will be used instead of the browser's
  #     hard-coded User-Agent header
  def user_agent=(new_user_agent)
    if new_user_agent != user_agent
      @rpc.call 'Network.setUserAgentOverride', userAgent: new_user_agent
      @user_agent = new_user_agent
    end
    new_user_agent
  end

  # Sets extra headers to be sent with every HTTP request.
  #
  # @param [Hash<String, String>] new_extra_headers HTTP headers to be added to
  #     every HTTP request sent by the browser
  def http_headers=(new_http_headers)
    new_http_headers = Hash[new_http_headers.map { |k, v|
      [k.to_s, v.to_s]
    }].freeze
    if new_http_headers != http_headers
      @rpc.call 'Network.setExtraHTTPHeaders', headers: new_http_headers
      @http_headers = new_http_headers
    end
    new_http_headers
  end

  # Checks if the debugger can clear the browser's cookies.
  #
  # @return [Boolean] true if WebkitRemote::Client::Network#clear_cookies can
  #     be succesfully called
  def can_clear_cookies?
    response = @rpc.call 'Network.canClearBrowserCookies'
    !!response['result']
  end

  # Removes all the cookies in the debugged browser.
  #
  # @return [WebkitRemote::Client] self
  def clear_cookies
    @rpc.call 'Network.clearBrowserCookies'
    self
  end

  # Checks if the debugger can clear the browser's cache.
  #
  # @return [Boolean] true if WebkitRemote::Client::Network#clear_network_cache
  #     can be succesfully called
  def can_clear_network_cache?
    response = @rpc.call 'Network.canClearBrowserCache'
    !!response['result']
  end

  # Removes all the cached data in the debugged browser.
  #
  # @return [WebkitRemote::Client] self
  def clear_network_cache
    @rpc.call 'Network.clearBrowserCache'
    self
  end

  # @return [Boolean] true if the debugger generates Network.* events
  attr_reader :network_events

  # @return [Array<WebkitRemote::Client::NetworkResource>] the resources
  #     fetched during the debugging session
  #
  # This is only populated when Network events are received.
  attr_reader :network_resources

  # @return [Boolean] true if the browser's network cache is disabled, so every
  #     resource load generates an HTTP request
  attr_reader :disable_cache

  # @return [String] replaces the brower's built-in User-Agent string
  attr_reader :user_agent

  # @return [Hash<String, String>]
  attr_reader :http_headers

  # Looks up network resources by IDs assigned by the WebKit remote debugger.
  #
  # @private Use the #resource property of Network events instead of calling
  #     this directly.
  #
  # @param [String] remote_id the WebKit-assigned request_id
  # @return [WebkitRemote::Client::NetworkResource] the cached information
  #     about the resource with the given ID
  def network_resource(remote_id)
    if @network_resource_hash[remote_id]
      return @network_resource_hash[remote_id]
    end
    resource = WebkitRemote::Client::NetworkResource.new remote_id, self

    @network_resources << resource
    @network_resource_hash[remote_id] = resource
  end

  # Removes the cached network request information.
  #
  # @return [WebkitRemote::Client] self
  def clear_network
    @network_resource_hash.clear
    @network_resources.clear
    self
  end

  # @private Called by the Client constructor to set up Network data.
  def initialize_network
    @disable_cache = false
    @network_events = false
    @network_resources = []
    @network_resource_hash = {}
    @user_agent = nil
  end
end  # module WebkitRemote::Client::Network

initializer :initialize_network
include WebkitRemote::Client::Network

end  # namespace WebkitRemote::Client

end  # namespace WebkitRemote


text:
package org.carlspring.strongbox.booters;

import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.ILock;
import org.carlspring.strongbox.configuration.Configuration;
import org.carlspring.strongbox.configuration.ConfigurationManager;
import org.carlspring.strongbox.providers.layout.LayoutProviderRegistry;
import org.carlspring.strongbox.providers.repository.group.GroupRepositorySetCollector;
import org.carlspring.strongbox.repository.RepositoryManagementStrategyException;
import org.carlspring.strongbox.services.RepositoryManagementService;
import org.carlspring.strongbox.storage.Storage;
import org.carlspring.strongbox.storage.repository.Repository;
import org.carlspring.strongbox.storage.repository.RepositoryStatusEnum;

import javax.annotation.PostConstruct;
import javax.inject.Inject;
import java.io.IOException;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;

import org.carlspring.strongbox.util.ThrowingConsumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author mtodorov
 */
public class StorageBooter
{

    private static final Logger logger = LoggerFactory.getLogger(StorageBooter.class);

    @Inject
    private ConfigurationManager configurationManager;

    @Inject
    private LayoutProviderRegistry layoutProviderRegistry;

    @Inject
    private RepositoryManagementService repositoryManagementService;

    @Inject
    private GroupRepositorySetCollector groupRepositorySetCollector;

    @Inject
    private PropertiesBooter propertiesBooter;

    @Inject
    private HazelcastInstance hazelcastInstance;

    public StorageBooter()
    {
    }

    @PostConstruct
    public void initialize()
            throws IOException, RepositoryManagementStrategyException
    {
        ILock lock = hazelcastInstance.getLock("StorageBooterLock");

        if (lock.tryLock())
        {
            try
            {
                final Configuration configuration = configurationManager.getConfiguration();

                initializeStorages(configuration.getStorages());

                Collection<Repository> repositories = getRepositoriesHierarchy(configuration.getStorages());

                if (!repositories.isEmpty())
                {
                    logger.info(" -> Initializing repositories...");
                }

                repositories.forEach(ThrowingConsumer.unchecked(this::initializeRepository));
            }
            finally
            {
                lock.unlock();
            }
        }
        else
        {
            logger.debug("Failed to initialize the repositories. Another JVM may have already done this.");
        }
    }

    private void initializeStorages(final Map<String, Storage> storages)
            throws IOException
    {
        logger.info("Running Strongbox storage booter...");
        logger.info(" -> Creating storage directory skeleton...");

        for (Map.Entry<String, Storage> stringStorageEntry : storages.entrySet())
        {
            initializeStorage(stringStorageEntry.getValue());
        }

    }

    private void initializeStorage(Storage storage)
            throws IOException
    {
        logger.info("  * Initializing {}...", storage.getId());
    }

    private void initializeRepository(Repository repository)
            throws IOException, RepositoryManagementStrategyException
    {
        logger.info("  * Initializing {}:{}...", repository.getStorage().getId(), repository.getId());

        if (layoutProviderRegistry.getProvider(repository.getLayout()) == null)
        {
            logger.error("Failed to resolve layout [{}] for repository [{}].",
                         repository.getLayout(),
                         repository.getId());
            return;
        }

        repositoryManagementService.createRepository(repository.getStorage().getId(), repository.getId());

        if (RepositoryStatusEnum.IN_SERVICE.getStatus().equals(repository.getStatus()))
        {
            repositoryManagementService.putInService(repository.getStorage().getId(), repository.getId());
        }
    }

    private Collection<Repository> getRepositoriesHierarchy(final Map<String, Storage> storages)
    {
        final Map<String, Repository> repositoriesHierarchy = new LinkedHashMap<>();
        for (final Storage storage : storages.values())
        {
            for (final Repository repository : storage.getRepositories().values())
            {
                addRepositoriesByChildrenFirst(repositoriesHierarchy, repository);
            }
        }

        return repositoriesHierarchy.values();
    }

    private void addRepositoriesByChildrenFirst(final Map<String, Repository> repositoriesHierarchy,
                                                final Repository repository)
    {
        if (!repository.isGroupRepository())
        {
            repositoriesHierarchy.putIfAbsent(repository.getId(), repository);

            return;
        }

        groupRepositorySetCollector.collect(repository, true)
                                   .stream().forEach(r -> addRepositoriesByChildrenFirst(repositoriesHierarchy, r));

        repositoriesHierarchy.putIfAbsent(repository.getId(), repository);
    }

    public RepositoryManagementService getRepositoryManagementService()
    {
        return repositoryManagementService;
    }

    public void setRepositoryManagementService(RepositoryManagementService repositoryManagementService)
    {
        this.repositoryManagementService = repositoryManagementService;
    }

}

redpajama_set_name: RedPajamaGithub


text:
package com.bareknucklecoding.plato.json_models;

import java.util.List;
import java.util.ArrayList;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DataQuestion {
  public final String TABLE_NAME "question";
  public final class Columns {
      public final String type = "type"
      public final String text = "text"
      public final String answers = "answers"
  }

  public final class OpenHelper extends SQLiteOpenHelper {
    private static final int DATABASE_VERSION = 1;
    private static final String CREATE_TABLE_COMMAND = "CREATE TABLE "
    + TABLE_NAME
    + "("
      + Columns.type + " String",;
      + Columns.text + " String",;
      + Columns.answers + " List<Answer>";
    + ")";
  }

  public static create(class_name object) {
  }

  public DataQuestion unmarshal(JSONObject object) throws JSONException {
    String type = object.getString("type");
    String text = object.getString("text");
    List<Answer> answers = new ArrayList<Answer>();
    for(int x = 0; x < object.getJSONArray("answers").length(); x++) {
    JSONObject answersObject = object.getJSONArray("answers")
      .getJSONObject(x);
      answers.add(new Answer().unmarshal(answersObject));
    }
    return new DataQuestion(type, text, answers);
  }

  public JSONObject toJSONObject() throws JSONException {
    JSONObject object = new JSONObject();
    object.put("type", type);
    object.put("text", text);
    JSONArray answersArray = new JSONArray();
    for (Answer answer : answers) {
      answersArray.put(answer.toJSONObject());
    }
    object.put("answers", answersArray);
    return object;
  }
}


text:
package org.lastaflute.web.servlet.request;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletResponse;

import org.dbflute.exception.AccessContextNotFoundException;
import org.dbflute.helper.message.ExceptionMessageBuilder;
import org.lastaflute.web.exception.ResponseClientAbortIOException;
import org.lastaflute.web.exception.ResponseDownloadFailureException;
import org.lastaflute.web.exception.ResponseDownloadStreamCallUpdateException;
import org.lastaflute.web.servlet.request.stream.WrittenStreamCall;
import org.lastaflute.web.servlet.request.stream.WrittenStreamOut;
import org.lastaflute.web.servlet.request.stream.WritternZipStreamCall;
import org.lastaflute.web.servlet.request.stream.WritternZipStreamWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author jflute
 */
public class ResponseDownloadPerformer {

    // ===================================================================================
    //                                                                          Definition
    //                                                                          ==========
    private static final Logger logger = LoggerFactory.getLogger(ResponseDownloadPerformer.class);
    protected static final String LF = "\n";

    // ===================================================================================
    //                                                                           Byte Data
    //                                                                           =========
    public void downloadByteData(ResponseDownloadResource resource, HttpServletResponse response) {
        final byte[] byteData = resource.getByteData();
        if (byteData == null) {
            String msg = "Either byte data or input stream is required: " + resource;
            throw new IllegalArgumentException(msg);
        }
        try {
            final OutputStream out = response.getOutputStream();
            try {
                out.write(byteData);
            } finally {
                closeDownloadStream(out);
            }
        } catch (RuntimeException e) {
            throw new ResponseDownloadFailureException("Failed to download the byte data: " + resource, e);
        } catch (IOException e) {
            handleDownloadIOException(resource, e);
        }
    }

    // ===================================================================================
    //                                                                        Input Stream
    //                                                                        ============
    // switched to stream call way for closing headache
    public void downloadStreamCall(ResponseDownloadResource resource, HttpServletResponse response) {
        final WrittenStreamCall streamCall = resource.getStreamCall();
        if (streamCall == null) {
            String msg = "Either byte data or input stream is required: " + resource;
            throw new IllegalArgumentException(msg);
        }
        try {
            final Integer contentLength = resource.getContentLength();
            if (contentLength != null) {
                response.setContentLength(contentLength);
            }
            final OutputStream out = response.getOutputStream();
            try {
                callbackStream(streamCall, createWrittenStreamOut(out), /*for logging*/resource);
                flushDownloadStream(out);
            } finally {
                closeDownloadStream(out);
            }
        } catch (RuntimeException e) {
            throw new ResponseDownloadFailureException("Failed to download the input stream: " + resource, e);
        } catch (IOException e) {
            handleDownloadIOException(resource, e);
        }
    }

    protected void callbackStream(WrittenStreamCall streamCall, WrittenStreamOut streamOut, ResponseDownloadResource resource)
            throws IOException {
        try {
            streamCall.callback(streamOut);
        } catch (AccessContextNotFoundException e) {
            final ExceptionMessageBuilder br = new ExceptionMessageBuilder();
            br.addNotice("Could not DB-update statement in stream callback.");
            br.addItem("Advice");
            br.addElement("You cannot DB-update in stream callback as default.");
            br.addElement("So call() inActionTransaction() if you need it.");
            br.addElement("(Or split process if you doesn't need it)");
            br.addElement("  (x):");
            br.addElement("    return asStream(\"sea.txt\").stream(out -> { // *Bad");
            br.addElement("        memberBhv.insert(...);");
            br.addElement("        out.write(ins);");
            br.addElement("    });");
            br.addElement("  (o):");
            br.addElement("    return asStream(\"sea.txt\").inActionTransaction().stream(out -> { // Good");
            br.addElement("        memberBhv.insert(...);");
            br.addElement("        out.write(ins);");
            br.addElement("    });");
            br.addElement("  (o):");
            br.addElement("    memberBhv.insert(...); // Good");
            br.addElement("    return asStream(\"sea.txt\").stream(out -> {");
            br.addElement("        out.write(ins);");
            br.addElement("    });");
            br.addElement("");
            br.addElement("However response is already committed in transaction");
            br.addElement("so e.g. you cannot add headers in hookFinally()");
            br.addElement("if you call inActionTransaction().");
            br.addElement("");
            br.addElement("While, the method is valid in (transactional) execute method.");
            br.addElement("(no meaning in non-transactional process e.g. hookBefore())");
            br.addItem("Download Info");
            br.addElement(resource);
            final String msg = br.buildExceptionMessage();
            throw new ResponseDownloadStreamCallUpdateException(msg, e);
        }
    }

    protected WrittenStreamOut createWrittenStreamOut(OutputStream out) {
        return new WrittenStreamOut() {
            public OutputStream stream() {
                return new WrittenOutputStreamWrapper(out); // delegator, you cannot close
            }

            public void write(InputStream ins) throws IOException {
                writeDownloadStream(ins, out);
            }
        };
    }

    // ===================================================================================
    //                                                                          Zip Stream
    //                                                                          ==========
    public void downloadZipStreamCall(ResponseDownloadResource resource, HttpServletResponse response) {
        try (ZipOutputStream zipOus = new ZipOutputStream(response.getOutputStream(), getZipOutputCharset(resource))) {
            final Map<String, WritternZipStreamWriter> zipWriterMap = createZipWriterMap(resource);
            zipWriterMap.forEach((fileName, writer) -> {
                try (ByteArrayOutputStream byteOus = new ByteArrayOutputStream()) {
                    writer.write(byteOus);
                    zipOus.putNextEntry(new ZipEntry(fileName));
                    byteOus.writeTo(zipOus);
                } catch (IOException e) {
                    handleDownloadIOException(resource, fileName, e);
                } finally {
                    try {
                        zipOus.closeEntry();
                    } catch (IOException e) {
                        handleDownloadIOException(resource, fileName, e);
                    }
                }
            });
        } catch (IOException e) {
            handleDownloadIOException(resource, e);
        }
    }

    protected Charset getZipOutputCharset(ResponseDownloadResource resource) {
        return Charset.forName(resource.getZipStreamCall().zipStreamEncoding());
    }

    protected Map<String, WritternZipStreamWriter> createZipWriterMap(ResponseDownloadResource resource) throws IOException {
        final WritternZipStreamCall zipStreamCall = resource.getZipStreamCall();
        final Map<String, WritternZipStreamWriter> writerMap = new LinkedHashMap<String, WritternZipStreamWriter>();
        zipStreamCall.callback((fileName, writer) -> {
            assertArgumentNotNull("fileName", fileName);
            assertArgumentNotNull("writer", writer);
            writerMap.put(fileName, writer);
        });
        if (writerMap.isEmpty()) {
            throw new IllegalStateException("The callback of zip stream should have at least one writer: " + zipStreamCall);
        }
        return writerMap;
    }

    // ===================================================================================
    //                                                                        Stream Logic
    //                                                                        ============
    protected void writeDownloadStream(InputStream ins, OutputStream out) throws IOException {
        try {
            fromInputStreamToOutputStream(ins, out);
        } catch (IOException e) {
            throwDownloadIOException(e);
        }
    }

    protected void fromInputStreamToOutputStream(InputStream ins, OutputStream out) throws IOException {
        final byte[] buf = new byte[8192];
        int n = 0;
        while ((n = ins.read(buf, 0, buf.length)) != -1) {
            out.write(buf, 0, n);
        }
    }

    protected void flushDownloadStream(OutputStream out) throws IOException {
        try {
            out.flush();
        } catch (IOException e) {
            throwDownloadIOException(e);
        }
    }

    protected void closeDownloadStream(OutputStream out) throws IOException {
        try {
            out.close();
        } catch (IOException e) {
            throwDownloadIOException(e);
        }
    }

    // ===================================================================================
    //                                                                   Throw IOException
    //                                                                   =================
    protected void throwDownloadIOException(IOException e) throws IOException {
        if (isClientAbortIOException(e)) { // will catched immediately so simple message
            throw new ResponseClientAbortIOException("Download was aborted by client.", e);
        } else {
            throw e;
        }
    }

    protected boolean isClientAbortIOException(IOException cause) {
        return isJettyClientAbort(cause) || isTomcatClientAbort(cause);
    }

    protected boolean isJettyClientAbort(IOException cause) {
        if ("org.eclipse.jetty.io.EofException".equals(cause.getClass().getName())) { // yelp
            final Throwable nestedEx = cause.getCause();
            if (nestedEx != null) {
                final String nestedMsg = nestedEx.getMessage();
                if (nestedMsg != null && nestedMsg.contains("Broken pipe")) { // just in case
                    return true;
                }
            }
        }
        return false;
    }

    protected boolean isTomcatClientAbort(IOException cause) {
        return "org.apache.catalina.connector.ClientAbortException".equals(cause.getClass().getName());
    }

    // ===================================================================================
    //                                                                  Handle IOException
    //                                                                  ==================
    protected void handleDownloadIOException(ResponseDownloadResource resource, IOException e) {
        doHandleDownloadIOException(resource, null, e);
    }

    protected void handleDownloadIOException(ResponseDownloadResource resource, String nestedFile, IOException e) {
        doHandleDownloadIOException(resource, nestedFile, e);
    }

    protected void doHandleDownloadIOException(ResponseDownloadResource resource, String nestedFile, IOException e) {
        if (e instanceof ResponseClientAbortIOException) {
            handleClientAbortIOException(resource, (ResponseClientAbortIOException) e);
        } else {
            String msg = "Failed to download the file: " + (nestedFile != null ? nestedFile + " in " : "") + resource;
            throw new ResponseDownloadFailureException(msg, e);
        }
    }

    protected void handleClientAbortIOException(ResponseDownloadResource resource, ResponseClientAbortIOException cause) {
        if (logger.isDebugEnabled()) {
            logger.debug(buildClientAbortMessage(resource, cause));
        }
    }

    protected String buildClientAbortMessage(ResponseDownloadResource resource, ResponseClientAbortIOException cause) {
        final StringBuilder sb = new StringBuilder();
        sb.append("...Handling client abort of download (but continue):");
        sb.append("\n_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/");
        sb.append("\n[Client Abort Exception]");
        sb.append("\n download file : ").append(resource.getFileName());
        sb.append("\n content type  : ").append(resource.getContentType());
        sb.append("\n stream call   : ").append(resource.getStreamCall());
        sb.append("\n byte data     : ").append(resource.getByteData());
        sb.append("\n header map    : ").append(resource.getHeaderMap());
        buildClientAbortIOExceptionStackTrace(cause, sb, 0);
        sb.append("\n_/_/_/_/_/_/_/_/_/_/");
        return sb.toString();
    }

    protected void buildClientAbortIOExceptionStackTrace(Throwable cause, StringBuilder sb, int nestLevel) {
        sb.append(LF).append(nestLevel > 0 ? "Caused by: " : "");
        sb.append(cause.getClass().getName()).append(": ").append(cause.getMessage());
        final StackTraceElement[] stackTrace = cause.getStackTrace();
        if (stackTrace == null) { // just in case
            return;
        }
        final int limit = nestLevel == 0 ? 10 : 3;
        int index = 0;
        for (StackTraceElement element : stackTrace) {
            if (index > limit) { // not all because it's not error
                sb.append(LF).append("  ...");
                break;
            }
            final String className = element.getClassName();
            final String fileName = element.getFileName(); // might be null
            final int lineNumber = element.getLineNumber();
            final String methodName = element.getMethodName();
            sb.append(LF).append("  at ").append(className).append(".").append(methodName);
            sb.append("(").append(fileName);
            if (lineNumber >= 0) {
                sb.append(":").append(lineNumber);
            }
            sb.append(")");
            ++index;
        }
        final Throwable nested = cause.getCause();
        if (nested != null && nested != cause) {
            buildClientAbortIOExceptionStackTrace(nested, sb, nestLevel + 1);
        }
    }

    // ===================================================================================
    //                                                                        Small Helper
    //                                                                        ============
    protected void assertArgumentNotNull(String variableName, Object value) {
        if (variableName == null) {
            throw new IllegalArgumentException("The variableName should not be null.");
        }
        if (value == null) {
            throw new IllegalArgumentException("The argument '" + variableName + "' should not be null.");
        }
    }
}


text:
package org.finra.herd.service.activiti.task;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;

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

import org.activiti.bpmn.model.FieldExtension;
import org.junit.Test;

import org.finra.herd.model.api.xml.BusinessObjectDataAttribute;
import org.finra.herd.model.api.xml.BusinessObjectDataAttributeKey;
import org.finra.herd.model.api.xml.BusinessObjectDataKey;
import org.finra.herd.model.api.xml.Parameter;
import org.finra.herd.model.jpa.BusinessObjectDataAttributeEntity;
import org.finra.herd.service.activiti.ActivitiRuntimeHelper;

/**
 * Test suite for Delete Business Object Data Attribute Activiti wrapper.
 */
public class DeleteBusinessObjectDataAttributeTest extends HerdActivitiServiceTaskTest
{
    @Test
    public void testDeleteBusinessObjectDataAttribute() throws Exception
    {
        // Create a business object data key.
        BusinessObjectDataKey businessObjectDataKey =
            new BusinessObjectDataKey(BDEF_NAMESPACE, BDEF_NAME, FORMAT_USAGE_CODE, FORMAT_FILE_TYPE_CODE, FORMAT_VERSION, PARTITION_VALUE, SUBPARTITION_VALUES,
                DATA_VERSION);

        // Create a business object data attribute key.
        BusinessObjectDataAttributeKey businessObjectDataAttributeKey =
            businessObjectDataAttributeHelper.getBusinessObjectDataAttributeKey(businessObjectDataKey, ATTRIBUTE_NAME_1_MIXED_CASE);

        // Create a business object data attribute entity.
        BusinessObjectDataAttributeEntity businessObjectDataAttributeEntity = businessObjectDataAttributeDaoTestHelper
            .createBusinessObjectDataAttributeEntity(businessObjectDataKey, ATTRIBUTE_NAME_1_MIXED_CASE, ATTRIBUTE_VALUE_1);

        // Validate that the business object data attribute is created.
        assertNotNull(businessObjectDataAttributeDao.getBusinessObjectDataAttributeByKey(businessObjectDataAttributeKey));

        List<FieldExtension> fieldExtensionList = new ArrayList<>();

        fieldExtensionList.add(buildFieldExtension("namespace", "${namespace}"));
        fieldExtensionList.add(buildFieldExtension("businessObjectDefinitionName", "${businessObjectDefinitionName}"));
        fieldExtensionList.add(buildFieldExtension("businessObjectFormatUsage", "${businessObjectFormatUsage}"));
        fieldExtensionList.add(buildFieldExtension("businessObjectFormatFileType", "${businessObjectFormatFileType}"));
        fieldExtensionList.add(buildFieldExtension("businessObjectFormatVersion", "${businessObjectFormatVersion}"));
        fieldExtensionList.add(buildFieldExtension("partitionValue", "${partitionValue}"));
        fieldExtensionList.add(buildFieldExtension("subPartitionValues", "${subPartitionValues}"));
        fieldExtensionList.add(buildFieldExtension("businessObjectDataVersion", "${businessObjectDataVersion}"));
        fieldExtensionList.add(buildFieldExtension("businessObjectDataAttributeName", "${businessObjectDataAttributeName}"));

        List<Parameter> parameters = new ArrayList<>();

        parameters.add(buildParameter("namespace", BDEF_NAMESPACE));
        parameters.add(buildParameter("businessObjectDefinitionName", BDEF_NAME));
        parameters.add(buildParameter("businessObjectFormatUsage", FORMAT_USAGE_CODE));
        parameters.add(buildParameter("businessObjectFormatFileType", FORMAT_FILE_TYPE_CODE));
        parameters.add(buildParameter("businessObjectFormatVersion", FORMAT_VERSION.toString()));
        parameters.add(buildParameter("partitionValue", PARTITION_VALUE));
        parameters.add(buildParameter("subPartitionValues", herdStringHelper.buildStringWithDefaultDelimiter(SUBPARTITION_VALUES)));
        parameters.add(buildParameter("businessObjectDataVersion", DATA_VERSION.toString()));
        parameters.add(buildParameter("businessObjectDataAttributeName", ATTRIBUTE_NAME_1_MIXED_CASE));

        // Build the expected response object.
        BusinessObjectDataAttribute expectedBusinessObjectDataAttribute =
            new BusinessObjectDataAttribute(businessObjectDataAttributeEntity.getId(), businessObjectDataAttributeKey, ATTRIBUTE_VALUE_1);

        // Run the activiti task and validate the returned response object.
        Map<String, Object> variableValuesToValidate = new HashMap<>();
        variableValuesToValidate.put(DeleteBusinessObjectDataAttribute.VARIABLE_JSON_RESPONSE, jsonHelper.objectToJson(expectedBusinessObjectDataAttribute));
        testActivitiServiceTaskSuccess(DeleteBusinessObjectDataAttribute.class.getCanonicalName(), fieldExtensionList, parameters, variableValuesToValidate);

        // Validate that the business object data attribute is deleted.
        assertNull(businessObjectDataAttributeDao.getBusinessObjectDataAttributeByKey(businessObjectDataAttributeKey));
    }

    /**
     * This unit tests covers scenario when business object data attribute service fails due to a missing required parameter.
     */
    @Test
    public void testDeleteBusinessObjectDataAttributeMissingRequiredParameter() throws Exception
    {
        // Validate that activiti task fails when we do not pass a namespace value.
        List<FieldExtension> fieldExtensionList = new ArrayList<>();
        List<Parameter> parameters = new ArrayList<>();

        Map<String, Object> variableValuesToValidate = new HashMap<>();
        variableValuesToValidate.put(ActivitiRuntimeHelper.VARIABLE_ERROR_MESSAGE, "A namespace must be specified.");

        executeWithoutLogging(ActivitiRuntimeHelper.class, () -> {
            testActivitiServiceTaskFailure(DeleteBusinessObjectDataAttribute.class.getCanonicalName(), fieldExtensionList, parameters,
                variableValuesToValidate);
        });
    }

    @Test
    public void testDeleteBusinessObjectDataAttributeMissingOptionalParameters() throws Exception
    {
        // Create a business object data key without sub-partition values.
        BusinessObjectDataKey businessObjectDataKey =
            new BusinessObjectDataKey(BDEF_NAMESPACE, BDEF_NAME, FORMAT_USAGE_CODE, FORMAT_FILE_TYPE_CODE, FORMAT_VERSION, PARTITION_VALUE,
                NO_SUBPARTITION_VALUES, DATA_VERSION);

        // Create a business object data attribute key.
        BusinessObjectDataAttributeKey businessObjectDataAttributeKey =
            businessObjectDataAttributeHelper.getBusinessObjectDataAttributeKey(businessObjectDataKey, ATTRIBUTE_NAME_1_MIXED_CASE);

        // Create a business object data attribute entity.
        BusinessObjectDataAttributeEntity businessObjectDataAttributeEntity = businessObjectDataAttributeDaoTestHelper
            .createBusinessObjectDataAttributeEntity(businessObjectDataKey, ATTRIBUTE_NAME_1_MIXED_CASE, ATTRIBUTE_VALUE_1);

        // Validate that the business object data attribute is created.
        assertNotNull(businessObjectDataAttributeDao.getBusinessObjectDataAttributeByKey(businessObjectDataAttributeKey));

        List<FieldExtension> fieldExtensionList = new ArrayList<>();

        fieldExtensionList.add(buildFieldExtension("namespace", "${namespace}"));
        fieldExtensionList.add(buildFieldExtension("businessObjectDefinitionName", "${businessObjectDefinitionName}"));
        fieldExtensionList.add(buildFieldExtension("businessObjectFormatUsage", "${businessObjectFormatUsage}"));
        fieldExtensionList.add(buildFieldExtension("businessObjectFormatFileType", "${businessObjectFormatFileType}"));
        fieldExtensionList.add(buildFieldExtension("businessObjectFormatVersion", "${businessObjectFormatVersion}"));
        fieldExtensionList.add(buildFieldExtension("partitionValue", "${partitionValue}"));
        fieldExtensionList.add(buildFieldExtension("businessObjectDataVersion", "${businessObjectDataVersion}"));
        fieldExtensionList.add(buildFieldExtension("businessObjectDataAttributeName", "${businessObjectDataAttributeName}"));

        List<Parameter> parameters = new ArrayList<>();

        parameters.add(buildParameter("namespace", BDEF_NAMESPACE));
        parameters.add(buildParameter("businessObjectDefinitionName", BDEF_NAME));
        parameters.add(buildParameter("businessObjectFormatUsage", FORMAT_USAGE_CODE));
        parameters.add(buildParameter("businessObjectFormatFileType", FORMAT_FILE_TYPE_CODE));
        parameters.add(buildParameter("businessObjectFormatVersion", FORMAT_VERSION.toString()));
        parameters.add(buildParameter("partitionValue", PARTITION_VALUE));
        parameters.add(buildParameter("businessObjectDataVersion", DATA_VERSION.toString()));
        parameters.add(buildParameter("businessObjectDataAttributeName", ATTRIBUTE_NAME_1_MIXED_CASE));

        // Build the expected response object.
        BusinessObjectDataAttribute expectedBusinessObjectDataAttribute = new BusinessObjectDataAttribute(businessObjectDataAttributeEntity.getId(),
            businessObjectDataAttributeHelper.getBusinessObjectDataAttributeKey(businessObjectDataKey, ATTRIBUTE_NAME_1_MIXED_CASE), ATTRIBUTE_VALUE_1);

        // Run the activiti task and validate the returned response object.
        Map<String, Object> variableValuesToValidate = new HashMap<>();
        variableValuesToValidate.put(DeleteBusinessObjectDataAttribute.VARIABLE_JSON_RESPONSE, jsonHelper.objectToJson(expectedBusinessObjectDataAttribute));
        testActivitiServiceTaskSuccess(DeleteBusinessObjectDataAttribute.class.getCanonicalName(), fieldExtensionList, parameters, variableValuesToValidate);

        // Validate that the business object data attribute is deleted.
        assertNull(businessObjectDataAttributeDao.getBusinessObjectDataAttributeByKey(businessObjectDataAttributeKey));
    }

    @Test
    public void testDeleteBusinessObjectDataAttributeMissingOptionalParametersSubPartitionValuesAsEmptyString() throws Exception
    {
        // Create a business object data key without sub-partition values.
        BusinessObjectDataKey businessObjectDataKey =
            new BusinessObjectDataKey(BDEF_NAMESPACE, BDEF_NAME, FORMAT_USAGE_CODE, FORMAT_FILE_TYPE_CODE, FORMAT_VERSION, PARTITION_VALUE,
                NO_SUBPARTITION_VALUES, DATA_VERSION);

        // Create a business object data attribute key.
        BusinessObjectDataAttributeKey businessObjectDataAttributeKey =
            businessObjectDataAttributeHelper.getBusinessObjectDataAttributeKey(businessObjectDataKey, ATTRIBUTE_NAME_1_MIXED_CASE);

        // Create a business object data attribute entity.
        BusinessObjectDataAttributeEntity businessObjectDataAttributeEntity = businessObjectDataAttributeDaoTestHelper
            .createBusinessObjectDataAttributeEntity(businessObjectDataKey, ATTRIBUTE_NAME_1_MIXED_CASE, ATTRIBUTE_VALUE_1);

        // Validate that the business object data attribute is created.
        assertNotNull(businessObjectDataAttributeDao.getBusinessObjectDataAttributeByKey(businessObjectDataAttributeKey));

        List<FieldExtension> fieldExtensionList = new ArrayList<>();

        fieldExtensionList.add(buildFieldExtension("namespace", "${namespace}"));
        fieldExtensionList.add(buildFieldExtension("businessObjectDefinitionName", "${businessObjectDefinitionName}"));
        fieldExtensionList.add(buildFieldExtension("businessObjectFormatUsage", "${businessObjectFormatUsage}"));
        fieldExtensionList.add(buildFieldExtension("businessObjectFormatFileType", "${businessObjectFormatFileType}"));
        fieldExtensionList.add(buildFieldExtension("businessObjectFormatVersion", "${businessObjectFormatVersion}"));
        fieldExtensionList.add(buildFieldExtension("partitionValue", "${partitionValue}"));
        fieldExtensionList.add(buildFieldExtension("subPartitionValues", "${subPartitionValues}"));
        fieldExtensionList.add(buildFieldExtension("businessObjectDataVersion", "${businessObjectDataVersion}"));
        fieldExtensionList.add(buildFieldExtension("businessObjectDataAttributeName", "${businessObjectDataAttributeName}"));

        List<Parameter> parameters = new ArrayList<>();

        parameters.add(buildParameter("namespace", BDEF_NAMESPACE));
        parameters.add(buildParameter("businessObjectDefinitionName", BDEF_NAME));
        parameters.add(buildParameter("businessObjectFormatUsage", FORMAT_USAGE_CODE));
        parameters.add(buildParameter("businessObjectFormatFileType", FORMAT_FILE_TYPE_CODE));
        parameters.add(buildParameter("businessObjectFormatVersion", FORMAT_VERSION.toString()));
        parameters.add(buildParameter("partitionValue", PARTITION_VALUE));
        parameters.add(buildParameter("subPartitionValues", EMPTY_STRING));
        parameters.add(buildParameter("businessObjectDataVersion", DATA_VERSION.toString()));
        parameters.add(buildParameter("businessObjectDataAttributeName", ATTRIBUTE_NAME_1_MIXED_CASE));

        // Build the expected response object.
        BusinessObjectDataAttribute expectedBusinessObjectDataAttribute = new BusinessObjectDataAttribute(businessObjectDataAttributeEntity.getId(),
            businessObjectDataAttributeHelper.getBusinessObjectDataAttributeKey(businessObjectDataKey, ATTRIBUTE_NAME_1_MIXED_CASE), ATTRIBUTE_VALUE_1);

        // Run the activiti task and validate the returned response object.
        Map<String, Object> variableValuesToValidate = new HashMap<>();
        variableValuesToValidate.put(DeleteBusinessObjectDataAttribute.VARIABLE_JSON_RESPONSE, jsonHelper.objectToJson(expectedBusinessObjectDataAttribute));
        testActivitiServiceTaskSuccess(DeleteBusinessObjectDataAttribute.class.getCanonicalName(), fieldExtensionList, parameters, variableValuesToValidate);

        // Validate that the business object data attribute is deleted.
        assertNull(businessObjectDataAttributeDao.getBusinessObjectDataAttributeByKey(businessObjectDataAttributeKey));
    }

    /**
     * This unit tests validates that activiti service layer fails when we pass non-integer business object format version value.
     */
    @Test
    public void testDeleteBusinessObjectDataAttributeInvalidBusinessObjectFormatVersion() throws Exception
    {
        // Validate that activiti task fails when we pass non-integer value for a business object format version.
        List<FieldExtension> fieldExtensionList = new ArrayList<>();
        fieldExtensionList.add(buildFieldExtension("businessObjectFormatVersion", "${businessObjectFormatVersion}"));
        List<Parameter> parameters = new ArrayList<>();
        parameters.add(buildParameter("businessObjectFormatVersion", "NOT_AN_INTEGER"));

        Map<String, Object> variableValuesToValidate = new HashMap<>();
        variableValuesToValidate.put(ActivitiRuntimeHelper.VARIABLE_ERROR_MESSAGE, "\"businessObjectFormatVersion\" must be a valid integer value.");

        executeWithoutLogging(ActivitiRuntimeHelper.class, () -> {
            testActivitiServiceTaskFailure(DeleteBusinessObjectDataAttribute.class.getCanonicalName(), fieldExtensionList, parameters,
                variableValuesToValidate);
        });
    }

    /**
     * This unit tests validates that activiti service layer fails when we pass non-integer business object data version value.
     */
    @Test
    public void testDeleteBusinessObjectDataAttributeInvalidBusinessObjectDataVersion() throws Exception
    {
        // Validate that activiti task fails when we pass non-integer value for a business object data version.
        List<FieldExtension> fieldExtensionList = new ArrayList<>();
        fieldExtensionList.add(buildFieldExtension("businessObjectFormatVersion", "${businessObjectFormatVersion}"));
        fieldExtensionList.add(buildFieldExtension("businessObjectDataVersion", "${businessObjectDataVersion}"));
        List<Parameter> parameters = new ArrayList<>();
        parameters.add(buildParameter("businessObjectFormatVersion", FORMAT_VERSION.toString()));
        parameters.add(buildParameter("businessObjectDataVersion", "NOT_AN_INTEGER"));

        Map<String, Object> variableValuesToValidate = new HashMap<>();
        variableValuesToValidate.put(ActivitiRuntimeHelper.VARIABLE_ERROR_MESSAGE, "\"businessObjectDataVersion\" must be a valid integer value.");

        executeWithoutLogging(ActivitiRuntimeHelper.class, () -> {
            testActivitiServiceTaskFailure(DeleteBusinessObjectDataAttribute.class.getCanonicalName(), fieldExtensionList, parameters,
                variableValuesToValidate);
        });
    }
}


text:
<?php

namespace CmsCalendar\Mapping;

use DateTime;

interface EventRepeatInterface
{
    /**
     * @param DateTime $date
     */
    public function setStartDate(DateTime $date);

    /**
     * @return DateTime
     */
    public function getStartDate();

    /**
     * @param DateTime $date
     */
    public function setEndDate(DateTime $date);

    /**
     * @return DateTime
     */
    public function getEndDate();
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Docker - the Linux container runtime</title>

    <meta name="description" content="Docker encapsulates heterogeneous payloads in standard containers">
    <meta name="viewport" content="width=device-width">

    <link rel="stylesheet" href="../static/css/bootstrap.min.css">
    <link rel="stylesheet" href="../static/css/bootstrap-responsive.min.css">

    <link rel="stylesheet" href="../static/css/main.css">

Introduction

Getting started

Documentation

Blog

                 Fork us on Github

 GETTING STARTED

        Docker is still under heavy development. It should not yet be used in production. Check the repo for recent progress.

                    Installing on Ubuntu

Requirements

Ubuntu 12.04 (LTS) (64-bit)

 or Ubuntu 12.10 (quantal) (64-bit)

The 3.8 Linux Kernel

Install dependencies

                    The linux-image-extra package is only needed on standard Ubuntu EC2 AMIs in order to install the aufs kernel module.

sudo apt-get install linux-image-extra-`uname -r`

Install Docker

Add the Ubuntu PPA (Personal Package Archive) sources to your apt sources list, update and install.

This may import a new GPG key (key 63561DC6: public key "Launchpad PPA for dotcloud team" imported).

sudo apt-get install software-properties-common

sudo add-apt-repository ppa:dotcloud/lxc-docker

sudo apt-get update

sudo apt-get install lxc-docker

Run!

docker run -i -t ubuntu /bin/bash

                    Continue with the Hello world example.

                    Or check more detailed installation instructions

Contributing to Docker

Want to hack on Docker? Awesome! We have some instructions to get you started. They are probably not perfect, please let us know if anything feels wrong or incomplete.

Quick install on other operating systems

For other operating systems we recommend and provide a streamlined install with virtualbox,
                    vagrant and an Ubuntu virtual machine.

Mac OS X and other linuxes

Windows

Questions? Want to get in touch?

There are several ways to get in touch:

Join the discussion on IRC. We can be found in the #docker channel on chat.freenode.net

Discussions happen on our google group: docker-club at googlegroups.com

All our development and decisions are made out in the open on Github github.com/dotcloud/docker

Get help on using Docker by asking on Stackoverflow

And of course, tweet your tweets to twitter.com/getdocker

                    Fill out my online form.

                    Twitter
                    GitHub

                Docker is a project by dotCloud


text:
/* Kernel module implementing an IP set type: the bitmap:port type */

#include <linux/module.h>
#include <linux/ip.h>
#include <linux/skbuff.h>
#include <linux/errno.h>
#include <linux/netlink.h>
#include <linux/jiffies.h>
#include <linux/timer.h>
#include <net/netlink.h>

#include <linux/netfilter/ipset/ip_set.h>
#include <linux/netfilter/ipset/ip_set_bitmap.h>
#include <linux/netfilter/ipset/ip_set_getport.h>
#define IP_SET_BITMAP_TIMEOUT
#include <linux/netfilter/ipset/ip_set_timeout.h>

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Jozsef Kadlecsik <kadlec@blackhole.kfki.hu>");
MODULE_DESCRIPTION("bitmap:port type of IP sets");
MODULE_ALIAS("ip_set_bitmap:port");

/* Type structure */
struct bitmap_port {
	void *members;		/* the set members */
	u16 first_port;		/* host byte order, included in range */
	u16 last_port;		/* host byte order, included in range */
	size_t memsize;		/* members size */
	u32 timeout;		/* timeout parameter */
	struct timer_list gc;	/* garbage collection */
};

/* Base variant */

static int
bitmap_port_test(struct ip_set *set, void *value, u32 timeout, u32 flags)
{
	const struct bitmap_port *map = set->data;
	u16 id = *(u16 *)value;

	return !!test_bit(id, map->members);
}

static int
bitmap_port_add(struct ip_set *set, void *value, u32 timeout, u32 flags)
{
	struct bitmap_port *map = set->data;
	u16 id = *(u16 *)value;

	if (test_and_set_bit(id, map->members))
		return -IPSET_ERR_EXIST;

	return 0;
}

static int
bitmap_port_del(struct ip_set *set, void *value, u32 timeout, u32 flags)
{
	struct bitmap_port *map = set->data;
	u16 id = *(u16 *)value;

	if (!test_and_clear_bit(id, map->members))
		return -IPSET_ERR_EXIST;

	return 0;
}

static int
bitmap_port_list(const struct ip_set *set,
		 struct sk_buff *skb, struct netlink_callback *cb)
{
	const struct bitmap_port *map = set->data;
	struct nlattr *atd, *nested;
	u16 id, first = cb->args[2];
	u16 last = map->last_port - map->first_port;

	atd = ipset_nest_start(skb, IPSET_ATTR_ADT);
	if (!atd)
		return -EMSGSIZE;
	for (; cb->args[2] <= last; cb->args[2]++) {
		id = cb->args[2];
		if (!test_bit(id, map->members))
			continue;
		nested = ipset_nest_start(skb, IPSET_ATTR_DATA);
		if (!nested) {
			if (id == first) {
				nla_nest_cancel(skb, atd);
				return -EMSGSIZE;
			} else
				goto nla_put_failure;
		}
		if (nla_put_net16(skb, IPSET_ATTR_PORT,
				  htons(map->first_port + id)))
			goto nla_put_failure;
		ipset_nest_end(skb, nested);
	}
	ipset_nest_end(skb, atd);
	/* Set listing finished */
	cb->args[2] = 0;

	return 0;

nla_put_failure:
	nla_nest_cancel(skb, nested);
	ipset_nest_end(skb, atd);
	if (unlikely(id == first)) {
		cb->args[2] = 0;
		return -EMSGSIZE;
	}
	return 0;
}

/* Timeout variant */

static int
bitmap_port_ttest(struct ip_set *set, void *value, u32 timeout, u32 flags)
{
	const struct bitmap_port *map = set->data;
	const unsigned long *members = map->members;
	u16 id = *(u16 *)value;

	return ip_set_timeout_test(members[id]);
}

static int
bitmap_port_tadd(struct ip_set *set, void *value, u32 timeout, u32 flags)
{
	struct bitmap_port *map = set->data;
	unsigned long *members = map->members;
	u16 id = *(u16 *)value;

	if (ip_set_timeout_test(members[id]) && !(flags & IPSET_FLAG_EXIST))
		return -IPSET_ERR_EXIST;

	members[id] = ip_set_timeout_set(timeout);

	return 0;
}

static int
bitmap_port_tdel(struct ip_set *set, void *value, u32 timeout, u32 flags)
{
	struct bitmap_port *map = set->data;
	unsigned long *members = map->members;
	u16 id = *(u16 *)value;
	int ret = -IPSET_ERR_EXIST;

	if (ip_set_timeout_test(members[id]))
		ret = 0;

	members[id] = IPSET_ELEM_UNSET;
	return ret;
}

static int
bitmap_port_tlist(const struct ip_set *set,
		  struct sk_buff *skb, struct netlink_callback *cb)
{
	const struct bitmap_port *map = set->data;
	struct nlattr *adt, *nested;
	u16 id, first = cb->args[2];
	u16 last = map->last_port - map->first_port;
	const unsigned long *members = map->members;

	adt = ipset_nest_start(skb, IPSET_ATTR_ADT);
	if (!adt)
		return -EMSGSIZE;
	for (; cb->args[2] <= last; cb->args[2]++) {
		id = cb->args[2];
		if (!ip_set_timeout_test(members[id]))
			continue;
		nested = ipset_nest_start(skb, IPSET_ATTR_DATA);
		if (!nested) {
			if (id == first) {
				nla_nest_cancel(skb, adt);
				return -EMSGSIZE;
			} else
				goto nla_put_failure;
		}
		if (nla_put_net16(skb, IPSET_ATTR_PORT,
				  htons(map->first_port + id)) ||
		    nla_put_net32(skb, IPSET_ATTR_TIMEOUT,
				  htonl(ip_set_timeout_get(members[id]))))
			goto nla_put_failure;
		ipset_nest_end(skb, nested);
	}
	ipset_nest_end(skb, adt);

	/* Set listing finished */
	cb->args[2] = 0;

	return 0;

nla_put_failure:
	nla_nest_cancel(skb, nested);
	ipset_nest_end(skb, adt);
	if (unlikely(id == first)) {
		cb->args[2] = 0;
		return -EMSGSIZE;
	}
	return 0;
}

static int
bitmap_port_kadt(struct ip_set *set, const struct sk_buff *skb,
		 const struct xt_action_param *par,
		 enum ipset_adt adt, const struct ip_set_adt_opt *opt)
{
	struct bitmap_port *map = set->data;
	ipset_adtfn adtfn = set->variant->adt[adt];
	__be16 __port;
	u16 port = 0;

	if (!ip_set_get_ip_port(skb, opt->family,
				opt->flags & IPSET_DIM_ONE_SRC, &__port))
		return -EINVAL;

	port = ntohs(__port);

	if (port < map->first_port || port > map->last_port)
		return -IPSET_ERR_BITMAP_RANGE;

	port -= map->first_port;

	return adtfn(set, &port, opt_timeout(opt, map), opt->cmdflags);
}

static int
bitmap_port_uadt(struct ip_set *set, struct nlattr *tb[],
		 enum ipset_adt adt, u32 *lineno, u32 flags, bool retried)
{
	struct bitmap_port *map = set->data;
	ipset_adtfn adtfn = set->variant->adt[adt];
	u32 timeout = map->timeout;
	u32 port;	/* wraparound */
	u16 id, port_to;
	int ret = 0;

	if (unlikely(!ip_set_attr_netorder(tb, IPSET_ATTR_PORT) ||
		     !ip_set_optattr_netorder(tb, IPSET_ATTR_PORT_TO) ||
		     !ip_set_optattr_netorder(tb, IPSET_ATTR_TIMEOUT)))
		return -IPSET_ERR_PROTOCOL;

	if (tb[IPSET_ATTR_LINENO])
		*lineno = nla_get_u32(tb[IPSET_ATTR_LINENO]);

	port = ip_set_get_h16(tb[IPSET_ATTR_PORT]);
	if (port < map->first_port || port > map->last_port)
		return -IPSET_ERR_BITMAP_RANGE;

	if (tb[IPSET_ATTR_TIMEOUT]) {
		if (!with_timeout(map->timeout))
			return -IPSET_ERR_TIMEOUT;
		timeout = ip_set_timeout_uget(tb[IPSET_ATTR_TIMEOUT]);
	}

	if (adt == IPSET_TEST) {
		id = port - map->first_port;
		return adtfn(set, &id, timeout, flags);
	}

	if (tb[IPSET_ATTR_PORT_TO]) {
		port_to = ip_set_get_h16(tb[IPSET_ATTR_PORT_TO]);
		if (port > port_to) {
			swap(port, port_to);
			if (port < map->first_port)
				return -IPSET_ERR_BITMAP_RANGE;
		}
	} else
		port_to = port;

	if (port_to > map->last_port)
		return -IPSET_ERR_BITMAP_RANGE;

	for (; port <= port_to; port++) {
		id = port - map->first_port;
		ret = adtfn(set, &id, timeout, flags);

		if (ret && !ip_set_eexist(ret, flags))
			return ret;
		else
			ret = 0;
	}
	return ret;
}

static void
bitmap_port_destroy(struct ip_set *set)
{
	struct bitmap_port *map = set->data;

	if (with_timeout(map->timeout))
		del_timer_sync(&map->gc);

	ip_set_free(map->members);
	kfree(map);

	set->data = NULL;
}

static void
bitmap_port_flush(struct ip_set *set)
{
	struct bitmap_port *map = set->data;

	memset(map->members, 0, map->memsize);
}

static int
bitmap_port_head(struct ip_set *set, struct sk_buff *skb)
{
	const struct bitmap_port *map = set->data;
	struct nlattr *nested;

	nested = ipset_nest_start(skb, IPSET_ATTR_DATA);
	if (!nested)
		goto nla_put_failure;
	if (nla_put_net16(skb, IPSET_ATTR_PORT, htons(map->first_port)) ||
	    nla_put_net16(skb, IPSET_ATTR_PORT_TO, htons(map->last_port)) ||
	    nla_put_net32(skb, IPSET_ATTR_REFERENCES, htonl(set->ref - 1)) ||
	    nla_put_net32(skb, IPSET_ATTR_MEMSIZE,
			  htonl(sizeof(*map) + map->memsize)) ||
	    (with_timeout(map->timeout) &&
	     nla_put_net32(skb, IPSET_ATTR_TIMEOUT, htonl(map->timeout))))
		goto nla_put_failure;
	ipset_nest_end(skb, nested);

	return 0;
nla_put_failure:
	return -EMSGSIZE;
}

static bool
bitmap_port_same_set(const struct ip_set *a, const struct ip_set *b)
{
	const struct bitmap_port *x = a->data;
	const struct bitmap_port *y = b->data;

	return x->first_port == y->first_port &&
	       x->last_port == y->last_port &&
	       x->timeout == y->timeout;
}

static const struct ip_set_type_variant bitmap_port = {
	.kadt	= bitmap_port_kadt,
	.uadt	= bitmap_port_uadt,
	.adt	= {
		[IPSET_ADD] = bitmap_port_add,
		[IPSET_DEL] = bitmap_port_del,
		[IPSET_TEST] = bitmap_port_test,
	},
	.destroy = bitmap_port_destroy,
	.flush	= bitmap_port_flush,
	.head	= bitmap_port_head,
	.list	= bitmap_port_list,
	.same_set = bitmap_port_same_set,
};

static const struct ip_set_type_variant bitmap_tport = {
	.kadt	= bitmap_port_kadt,
	.uadt	= bitmap_port_uadt,
	.adt	= {
		[IPSET_ADD] = bitmap_port_tadd,
		[IPSET_DEL] = bitmap_port_tdel,
		[IPSET_TEST] = bitmap_port_ttest,
	},
	.destroy = bitmap_port_destroy,
	.flush	= bitmap_port_flush,
	.head	= bitmap_port_head,
	.list	= bitmap_port_tlist,
	.same_set = bitmap_port_same_set,
};

static void
bitmap_port_gc(unsigned long ul_set)
{
	struct ip_set *set = (struct ip_set *) ul_set;
	struct bitmap_port *map = set->data;
	unsigned long *table = map->members;
	u32 id;	/* wraparound */
	u16 last = map->last_port - map->first_port;

	/* We run parallel with other readers (test element)
	 * but adding/deleting new entries is locked out */
	read_lock_bh(&set->lock);
	for (id = 0; id <= last; id++)
		if (ip_set_timeout_expired(table[id]))
			table[id] = IPSET_ELEM_UNSET;
	read_unlock_bh(&set->lock);

	map->gc.expires = jiffies + IPSET_GC_PERIOD(map->timeout) * HZ;
	add_timer(&map->gc);
}

static void
bitmap_port_gc_init(struct ip_set *set)
{
	struct bitmap_port *map = set->data;

	init_timer(&map->gc);
	map->gc.data = (unsigned long) set;
	map->gc.function = bitmap_port_gc;
	map->gc.expires = jiffies + IPSET_GC_PERIOD(map->timeout) * HZ;
	add_timer(&map->gc);
}

/* Create bitmap:ip type of sets */

static bool
init_map_port(struct ip_set *set, struct bitmap_port *map,
	      u16 first_port, u16 last_port)
{
	map->members = ip_set_alloc(map->memsize);
	if (!map->members)
		return false;
	map->first_port = first_port;
	map->last_port = last_port;
	map->timeout = IPSET_NO_TIMEOUT;

	set->data = map;
	set->family = NFPROTO_UNSPEC;

	return true;
}

static int
bitmap_port_create(struct ip_set *set, struct nlattr *tb[],
		 u32 flags)
{
	struct bitmap_port *map;
	u16 first_port, last_port;

	if (unlikely(!ip_set_attr_netorder(tb, IPSET_ATTR_PORT) ||
		     !ip_set_attr_netorder(tb, IPSET_ATTR_PORT_TO) ||
		     !ip_set_optattr_netorder(tb, IPSET_ATTR_TIMEOUT)))
		return -IPSET_ERR_PROTOCOL;

	first_port = ip_set_get_h16(tb[IPSET_ATTR_PORT]);
	last_port = ip_set_get_h16(tb[IPSET_ATTR_PORT_TO]);
	if (first_port > last_port) {
		u16 tmp = first_port;

		first_port = last_port;
		last_port = tmp;
	}

	map = kzalloc(sizeof(*map), GFP_KERNEL);
	if (!map)
		return -ENOMEM;

	if (tb[IPSET_ATTR_TIMEOUT]) {
		map->memsize = (last_port - first_port + 1)
			       * sizeof(unsigned long);

		if (!init_map_port(set, map, first_port, last_port)) {
			kfree(map);
			return -ENOMEM;
		}

		map->timeout = ip_set_timeout_uget(tb[IPSET_ATTR_TIMEOUT]);
		set->variant = &bitmap_tport;

		bitmap_port_gc_init(set);
	} else {
		map->memsize = bitmap_bytes(0, last_port - first_port);
		pr_debug("memsize: %zu\n", map->memsize);
		if (!init_map_port(set, map, first_port, last_port)) {
			kfree(map);
			return -ENOMEM;
		}

		set->variant = &bitmap_port;
	}
	return 0;
}

static struct ip_set_type bitmap_port_type = {
	.name		= "bitmap:port",
	.protocol	= IPSET_PROTOCOL,
	.features	= IPSET_TYPE_PORT,
	.dimension	= IPSET_DIM_ONE,
	.family		= NFPROTO_UNSPEC,
	.revision_min	= 0,
	.revision_max	= 0,
	.create		= bitmap_port_create,
	.create_policy	= {
		[IPSET_ATTR_PORT]	= { .type = NLA_U16 },
		[IPSET_ATTR_PORT_TO]	= { .type = NLA_U16 },
		[IPSET_ATTR_TIMEOUT]	= { .type = NLA_U32 },
	},
	.adt_policy	= {
		[IPSET_ATTR_PORT]	= { .type = NLA_U16 },
		[IPSET_ATTR_PORT_TO]	= { .type = NLA_U16 },
		[IPSET_ATTR_TIMEOUT]	= { .type = NLA_U32 },
		[IPSET_ATTR_LINENO]	= { .type = NLA_U32 },
	},
	.me		= THIS_MODULE,
};

static int __init
bitmap_port_init(void)
{
	return ip_set_type_register(&bitmap_port_type);
}

static void __exit
bitmap_port_fini(void)
{
	ip_set_type_unregister(&bitmap_port_type);
}

module_init(bitmap_port_init);
module_exit(bitmap_port_fini);


text:
'use strict';

module.exports = function(kbox, frameworks) {

  // Npm modulez
  var _ = require('lodash');

  // Add options for each framework
  _.forEach(frameworks, function(framework) {

    // Allow user to specify a name
    kbox.create.add(framework, {
      option: {
        name: 'name',
        weight: -75,
        task: {
          kind: 'string',
          description: 'The name of your app.',
        },
        inquire: {
          type: 'input',
          message: 'What will you call this monster you have created',
          validate: function(value) {
            var domain = kbox.core.deps.get('globalConfig').domain;
            var kebabMe = kbox.util.domain.modKebabCase(value);
            return kbox.util.domain.validateDomain([kebabMe, domain].join('.'));
          },
          filter: function(value) {
            if (value) {
              return kbox.util.domain.modKebabCase(value);
            }
          },
          default: function(answers) {
            var options = kbox.core.deps.get('argv').options;
            return options.site || answers.site || 'My App';
          }
        },
        conf: {
          type: 'global'
        }
      }
    });

  });

};


text:
package com.wikidreams.haarcascade;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

import javax.swing.JOptionPane;

import com.wikidreams.properties.PropertiesManager;
import com.wikidreams.shellcommand.ShellManager;

public class HaarCascadeManager {

	static {
		PropertiesManager.loadProperties("resources/config.properties");
	}

	private String processName;
	private File[] positiveImages;
	private File bgFile;
	private String samplesByImage;
	private String maxxangle;
	private String maxyangle;
	private String maxzangle;
	private String width;
	private String height;
	private String num;
	private String numPos;
	private String numNeg;
	private String numStages;

	private File processDir;
	private File infoFile;

	public HaarCascadeManager(String processName, File[] positiveImages, File bgFile,
			String samplesByImage, String maxxangle, String maxyangle, String maxzangle,
			String width, String height, String numPos, String numNeg, String numStages) {
		super();
		this.processName = processName;
		this.positiveImages = positiveImages;
		this.bgFile = bgFile;
		this.samplesByImage = samplesByImage;
		this.maxxangle = maxxangle;
		this.maxyangle = maxyangle;
		this.maxzangle = maxzangle;
		this.width = width;
		this.height = height;
		this.numPos = numPos;
		this.numNeg = numNeg;
		this.numStages = numStages;

		// Create workspace folder.
		File dir = new File(PropertiesManager.properties.get("OpenCVBin").trim() + "\\Workspace");
		if (! dir.exists()) {
			dir.mkdir();
		}

		// Create cascades folder.
		dir = new File(PropertiesManager.properties.get("OpenCVBin").trim() + "\\Workspace\\Cascades");
		if (! dir.exists()) {
			dir.mkdir();
		}

		// Create samples.
		this.createSamples();
	}

	private void createSamples() {
		// Create process folder.
		this.processDir = new File(PropertiesManager.properties.get("OpenCVBin").trim() + "\\Workspace\\Cascades\\" + this.processName);
		if (this.processDir.exists()) {
			JOptionPane.showMessageDialog(null, "A process with this name already exists.");
			return;
		}
		this.processDir.mkdir();

		// Create info folder.
		File infoDir = new File(this.processDir + "\\info\\");
		infoDir.mkdir();

		// Create info.lst file.
		this.infoFile = new File(infoDir.getAbsolutePath() + "\\info.lst");

		StringBuilder sbInfoFile = new StringBuilder();
		File reportFile = new File(this.processDir + "\\samples_report.log");
		StringBuilder sbReportFile = new StringBuilder();

		for (File f : this.positiveImages) {

			// Create samples.bat file
			StringBuilder b = new StringBuilder();
			b.append(PropertiesManager.properties.get("OpenCVBin").trim() + "\\opencv_createsamples.exe");
			b.append(" -info ");
			b.append(infoDir.getAbsolutePath() + "\\info.lst");
			b.append(" -pngoutput ");
			b.append(infoDir.getAbsolutePath());
			b.append(" -img ");
			b.append(f.getAbsolutePath());
			b.append(" -bg ");
			b.append(this.bgFile.getAbsolutePath());
			b.append(" -num ");
			b.append(this.samplesByImage);
			b.append(" -maxxangle ");
			b.append(this.maxxangle);
			b.append(" -maxyangle ");
			b.append(this.maxyangle);
			b.append(" -maxzangle ");
			b.append(this.maxzangle);
			b.append(" -w ");
			b.append(this.width);
			b.append(" -h ");
			b.append(this.height);
			try {
				File tFile = new File(this.processDir.getAbsolutePath() + "\\create_samples.bat");
				FileWriter tFileWriter = new FileWriter(tFile);
				BufferedWriter tBufferedWriter = new BufferedWriter(tFileWriter);
				tBufferedWriter.write(b.toString());
				tBufferedWriter.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}

			// Execute samples.bat file.
			ArrayList<String> command = new ArrayList<>();
			command.add(this.processDir.getAbsolutePath() + "\\create_samples.bat");
			String output = ShellManager.executeCommand(command);

			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

			sbReportFile.append(output);
			sbReportFile.append("\n");

			if (this.infoFile.exists()) {
				try {
					BufferedReader br = new BufferedReader(new FileReader(this.infoFile.getAbsolutePath()));
					String line = br.readLine();
					while (line != null) {
						sbInfoFile.append(line);
						sbInfoFile.append("\n");
						line = br.readLine();
					}
					br.close();
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		// Save info and create samples report files.
		try{
			FileWriter infoFileWriter = new FileWriter(infoFile);
			BufferedWriter infoBufferedWriter = new BufferedWriter(infoFileWriter);
			infoBufferedWriter.write(sbInfoFile.toString());
			infoBufferedWriter.close();

			FileWriter reportFileWriter = new FileWriter(reportFile);
			BufferedWriter reportBufferedWriter = new BufferedWriter(reportFileWriter);
			reportBufferedWriter.write(sbReportFile.toString());
			reportBufferedWriter.close();
		}
		catch (Exception e){
			e.printStackTrace();
		}

		// Create vector file.
		this.createVectorFile();
	}

	private void createVectorFile() {
		// Create vector folder.
		File vecDir = new File(this.processDir.getAbsolutePath() + "\\vector");
		vecDir.mkdir();

		// Get number of created images.
		File infoDir = new File(this.processDir.getAbsolutePath() + "\\info");
		File[] allFiles = infoDir.listFiles();
		this.num = Integer.toString(allFiles.length - 1);

		// Create vector.bat file.
		StringBuilder b = new StringBuilder();
		b.append(PropertiesManager.properties.get("OpenCVBin").trim() + "\\opencv_createsamples.exe");
		b.append(" -info ");
		b.append(this.processDir.getAbsolutePath() + "\\info\\info.lst");
		b.append(" -num ");
		b.append(this.num);
		b.append(" -w ");
		b.append(this.width);
		b.append(" -h ");
		b.append(this.height);
		b.append(" -vec ");
		b.append(this.processDir.getAbsolutePath() + "\\vector\\samples.vec");
		try {
			File tFile = new File(this.processDir.getAbsolutePath() + "\\create_vector.bat");
			FileWriter tFileWriter = new FileWriter(tFile);
			BufferedWriter tBufferedWriter = new BufferedWriter(tFileWriter);
			tBufferedWriter.write(b.toString());
			tBufferedWriter.close();
		} catch (IOException e1) {
			e1.printStackTrace();
		}

		// Execute create_vector.bat file.
		ArrayList<String> command = new ArrayList<>();
		command.add(this.processDir.getAbsolutePath() + "\\create_vector.bat");
		String output = ShellManager.executeCommand(command);

		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		// Create vector report file.
		try {
			File reportFile = new File(this.processDir.getAbsolutePath() + "\\vector_report.log");
			FileWriter reportFileWriter = new FileWriter(reportFile);
			BufferedWriter reportBufferedWriter = new BufferedWriter(reportFileWriter);
			reportBufferedWriter.write(output);
			reportBufferedWriter.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		// Create train cascade file.
		this.createCascade();
	}

	private void createCascade() {
		// Create data folder.
		File dataDir = new File(this.processDir.getAbsolutePath() + "\\data");
		dataDir.mkdir();

		// Create bat file content.
		StringBuilder b = new StringBuilder();
		b.append(PropertiesManager.properties.get("OpenCVBin").trim() + "\\opencv_traincascade.exe");
		b.append(" -data " + dataDir.getAbsolutePath());
		b.append(" -vec " + this.processDir.getAbsolutePath() + "\\vector\\samples.vec");
		b.append(" -bg " + this.bgFile.getAbsolutePath());
		b.append(" -numPos " + this.numPos);
		b.append(" -numNeg " + this.numNeg);
		b.append(" -numStages " + this.numStages);
		b.append(" -w " + this.width);
		b.append(" -h " + this.height);
		b.append(" > " + this.processDir.getAbsolutePath() + "\\cascade_report.log");
		File tFile = new File(PropertiesManager.properties.get("OpenCVBin").trim() + "\\" + this.processName + "_train.bat");
		try {
			FileWriter tFileWriter = new FileWriter(tFile);
			BufferedWriter tBufferedWriter = new BufferedWriter(tFileWriter);
			tBufferedWriter.write(b.toString());
			tBufferedWriter.close();
		} catch (IOException e1) {
			e1.printStackTrace();
		}

		// Alert user to start the process.
		JOptionPane.showMessageDialog(null, "Start the process with the file: " + tFile.getAbsolutePath());
	}

}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="NoDuplicates.cs" company="">
//   Copyright (c) 2011 CslaGenFork project. Website: http://cslagenfork.codeplex.com/
// </copyright>
// <summary>
//   Business rule for checking a name property is unique at the parent collection level.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using Csla.Core;
using Csla.Rules;

namespace CslaGenFork.Rules.CollectionRules
{
    /// <summary>
    /// Business rule for checking a name property is unique at the parent collection level.
    /// </summary>
    public class NoDuplicates : CommonRuleWithMessage
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="NoDuplicates"/> class.
        /// </summary>
        /// <param name="primaryProperty">Primary property for this rule.</param>
        public NoDuplicates(IPropertyInfo primaryProperty)
            : base(primaryProperty)
        {
            InputProperties = new List<IPropertyInfo> {primaryProperty};
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="NoDuplicates"/> class.
        /// </summary>
        /// <param name="primaryProperty">Primary property for this rule.</param>
        /// <param name="message">The error message text.</param>
        public NoDuplicates(IPropertyInfo primaryProperty, string message)
            : this(primaryProperty)
        {
            MessageText = message;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="NoDuplicates"/> class.
        /// </summary>
        /// <param name="primaryProperty">Primary property for this rule.</param>
        /// <param name="messageDelegate">The error message function.</param>
        public NoDuplicates(IPropertyInfo primaryProperty, Func<string> messageDelegate)
            : this(primaryProperty)
        {
            MessageDelegate = messageDelegate;
        }

        /// <summary>
        /// Gets the error message.
        /// </summary>
        /// <returns>
        /// The error message.
        /// </returns>
        protected override string GetMessage()
        {
            return HasMessageDelegate ? base.GetMessage() : "{0} must be unique";
        }

        /// <summary>
        /// Business rule implementation.
        /// </summary>
        /// <param name="context">Rule context object.</param>
        protected override void Execute(RuleContext context)
        {
            var value = context.InputPropertyValues[PrimaryProperty] as string;
            if (value == null)
                return;

            var target = (BusinessBase)context.Target;
            dynamic parent = target.Parent;
            if (parent != null)
            {
                foreach (var item in parent)
                {
                    System.Reflection.PropertyInfo compare = item.GetType().GetProperty(PrimaryProperty.Name);
                    if (value.ToUpperInvariant() == compare.GetValue(item, null).ToUpperInvariant() &&
                        !(ReferenceEquals(item, target)))
                    {
                        var message = string.Format(GetMessage(), PrimaryProperty.FriendlyName);
                        context.Results.Add(new RuleResult(RuleName, PrimaryProperty, message) {Severity = Severity});
                    }
                }
            }
        }
    }
}


text:
package opt.android.datetimepicker;

import android.content.Context;
import android.util.AttributeSet;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.Button;
import android.widget.LinearLayout;

/**
 * Fake Button class, used so TextViews can announce themselves as Buttons, for accessibility.
 */
public class AccessibleLinearLayout extends LinearLayout {

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

    @Override
    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
        super.onInitializeAccessibilityEvent(event);
        event.setClassName(Button.class.getName());
    }

    @Override
    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
        super.onInitializeAccessibilityNodeInfo(info);
        info.setClassName(Button.class.getName());
    }
}


text:
package com.h6ah4i.android.example.advrecyclerview.common.utils;

import android.graphics.drawable.Drawable;

public class DrawableUtils {
    private static final int[] EMPTY_STATE = new int[] {};

    public static void clearState(Drawable drawable) {
        if (drawable != null) {
            drawable.setState(EMPTY_STATE);
        }
    }
}


text:
require 'chef/formatters/error_inspectors/api_error_formatting'

class Chef
  module Formatters
    module ErrorInspectors
      class CookbookResolveErrorInspector

        attr_reader :exception
        attr_reader :expanded_run_list

        include APIErrorFormatting

        def initialize(expanded_run_list, exception)
          @expanded_run_list = expanded_run_list
          @exception = exception
        end

        def add_explanation(error_description)
          case exception
          when Net::HTTPServerException, Net::HTTPFatalError
            humanize_http_exception(error_description)
          when *NETWORK_ERROR_CLASSES
            describe_network_errors(error_description)
          else
            error_description.section("Unexpected Error:","#{exception.class.name}: #{exception.message}")
          end
        end

        def humanize_http_exception(error_description)
          response = exception.response
          case response
          when Net::HTTPUnauthorized
            # TODO: this is where you'd see conflicts b/c of username/clientname stuff
            describe_401_error(error_description)
          when Net::HTTPForbidden
            # TODO: we're rescuing errors from Node.find_or_create
            # * could be no write on nodes container
            # * could be no read on the node
            error_description.section("Authorization Error",<<-E)
This client is not authorized to read some of the information required to
access its coobooks (HTTP 403).

To access its cookbooks, a client needs to be able to read its environment and
all of the cookbooks in its expanded run list.
E
            error_description.section("Expanded Run List:", expanded_run_list_ul)
            error_description.section("Server Response:", format_rest_error)
E
          when Net::HTTPPreconditionFailed
            describe_412_error(error_description)
          when Net::HTTPBadRequest
            describe_400_error(error_description)
          when Net::HTTPNotFound
          when Net::HTTPInternalServerError
            describe_500_error(error_description)
          when Net::HTTPBadGateway, Net::HTTPServiceUnavailable
            describe_503_error(error_description)
          else
            describe_http_error(error_description)
          end
        end

        def describe_412_error(error_description)
          explanation = ""
          error_reasons = extract_412_error_message
          if !error_reasons.respond_to?(:key?)
            explanation << error_reasons.to_s
          else
            if error_reasons.key?("non_existent_cookbooks") && !Array(error_reasons["non_existent_cookbooks"]).empty?
              explanation << "The following cookbooks are required by the client but don't exist on the server:\n"
              Array(error_reasons["non_existent_cookbooks"]).each do |cookbook|
                explanation << "* #{cookbook}\n"
              end
              explanation << "\n"
            end
            if error_reasons.key?("cookbooks_with_no_versions") && !Array(error_reasons["cookbooks_with_no_versions"]).empty?
              explanation << "The following cookbooks exist on the server, but there is no version that meets\nthe version constraints in this environment:\n"
              Array(error_reasons["cookbooks_with_no_versions"]).each do |cookbook|
                explanation << "* #{cookbook}\n"
              end
              explanation << "\n"
            end
          end

          error_description.section("Missing Cookbooks:", explanation)
          error_description.section("Expanded Run List:", expanded_run_list_ul)
        end

        def expanded_run_list_ul
          @expanded_run_list.map {|i| "* #{i}"}.join("\n")
        end

        # In my tests, the error from the server is double JSON encoded, but we
        # should not rely on this not getting fixed.
        #
        # Return *should* be a Hash like this:
        #   { "non_existent_cookbooks"     => ["nope"],
        #     "cookbooks_with_no_versions" => [],
        #     "message" => "Run list contains invalid items: no such cookbook nope."}
        def extract_412_error_message
          # Example:
          # "{\"error\":[\"{\\\"non_existent_cookbooks\\\":[\\\"nope\\\"],\\\"cookbooks_with_no_versions\\\":[],\\\"message\\\":\\\"Run list contains invalid items: no such cookbook nope.\\\"}\"]}"

          wrapped_error_message = attempt_json_parse(exception.response.body)
          unless wrapped_error_message.kind_of?(Hash) && wrapped_error_message.key?("error")
            return wrapped_error_message.to_s
          end

          error_description = Array(wrapped_error_message["error"]).first
          if error_description.kind_of?(Hash)
            return error_description
          end
          attempt_json_parse(error_description)
        end

        private

        def attempt_json_parse(maybe_json_string)
          Chef::JSONCompat.from_json(maybe_json_string)
        rescue Exception
          maybe_json_string
        end

      end
    end
  end
end


text:
package script

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"strings"
	"unicode"

	"github.com/mattn/go-shellwords"
)

type parseContext struct {
	lineNum int
	line    string
	errors  []error
	nodes   []node
}

func newParseContext() *parseContext {
	return &parseContext{errors: []error{}, nodes: []node{}}
}

func (pc *parseContext) addErrorf(format string, a ...interface{}) {
	pc.errors = append(pc.errors, fmt.Errorf(format, a...))
}

func parseFile(filePath string) (*parseContext, error) {
	f, err := os.Open(filePath)
	if err != nil {
		return nil, err
	}
	r := bufio.NewReader(f)
	return parseDescriptor(r)
}

func parseDescriptor(r io.Reader) (*parseContext, error) {
	ctx := newParseContext()
	parse := func(num int, line string) error {
		ctx.lineNum = num
		ctx.line = line
		return parseNode(ctx)
	}
	if err := ForEachLine(r, parse); err != nil {
		return nil, err
	}
	return ctx, nil
}

func ForEachLine(r io.Reader, apply func(num int, line string) error) error {
	scanner := bufio.NewScanner(r)
	i := 0
	for scanner.Scan() {
		i += 1
		if err := apply(i, scanner.Text()); err != nil {
			return err
		}
	}
	return scanner.Err()
}

//parseLine returns the command and args array if any. If line is empty empty string and args are returned
func parseLine(line string) (string, []string, error) {
	line = strings.TrimLeftFunc(line, unicode.IsSpace)
	shellwords.ParseEnv = false
	shellwords.ParseBacktick = false
	fields, err := shellwords.Parse(line)
	if err != nil {
		return "", []string{}, err
	}

	//ignore empty lines
	if len(fields) == 0 {
		return "", []string{}, nil
	}
	var cmd string
	if strings.HasPrefix(fields[0], "#") {
		cmd = "#"
	} else {
		cmd = fields[0]
	}
	args := fields[1:] //remove first element(cmd)
	for i, _ := range args {
		args[i] = strings.TrimFunc(args[i], unicode.IsSpace)
	}
	return cmd, args, nil
}

// parseCommand parses current line and creates a command
func parseNode(ctx *parseContext) error {
	prefix, args, err := parseLine(ctx.line)
	if err != nil {
		return fmt.Errorf("could not parse line %d: %s: %s", ctx.lineNum, ctx.line, err)
	}

	f, found := nodeFactories[prefix]
	if !found {
		return fmt.Errorf("could not parse line %d: %s", ctx.lineNum, ctx.line)
	}
	node, err := f(ctx, prefix, args)
	if err != nil {
		return err
	}
	if node.cmd != EMPTY {
		ctx.nodes = append(ctx.nodes, node)
	}
	return nil
}


text:
<?php ob_start(); ?>
<?php session_start(); ?>

<?php
    $_SESSION['username'] = null;
    $_SESSION['firstname'] = null;
    $_SESSION['lastname'] = null;
    $_SESSION['user_role'] = null;

    header("Location: ..");


text:
import sys
import os
import logging
import tempfile
from colorama import init, Fore

from androguard import __version__
from androguard.core.api_specific_resources import load_permission_mappings, load_permissions
ANDROGUARD_VERSION = __version__

log = logging.getLogger("androguard.default")

# initialize colorama, only has an effect on windows
init()

class InvalidResourceError(Exception):
    """
    Invalid Resource Erorr is thrown by load_api_specific_resource_module
    """
    pass

def is_ascii_problem(s):
    """
    Test if a string contains other chars than ASCII

    :param androguard.core.mutf8.MUTF8String s: a string to test
    :return: True if string contains other chars than ASCII, False otherwise
    :rtype: bool
    """
    try:
        # As MUTF8Strings are actually bytes, we can simply check if they are ASCII or not
        s.decode("ascii")
        return False
    except (UnicodeEncodeError, UnicodeDecodeError):
        return True

default_conf = {
    ## Configuration for executables used by androguard
    # Assume the binary is in $PATH, otherwise give full path
    "BIN_JADX": "jadx",
    # Dex2jar binary
    "BIN_DEX2JAR": "dex2jar.sh",

    # TODO Use apksigner instead
    "BIN_JARSIGNER": "jarsigner",  # TO BE REMOVED

    "BIN_DED": "ded.sh",  # TO BE REMOVED
    "BIN_JAD": "jad",  # TO BE REMOVED
    "BIN_WINEJAD": "jad.exe",  # TO BE REMOVED
    "BIN_FERNFLOWER": "fernflower.jar",  # TO BE REMOVED
    "OPTIONS_FERNFLOWER": {"dgs": '1',  # TO BE REMOVED
                           "asc": '1'},

    # Runtime variables
    #
    # A path to the temporary directory
    "TMP_DIRECTORY": tempfile.gettempdir(),

    # Function to print stuff
    "PRINT_FCT": sys.stdout.write,

    # Default API level, if requested API is not available
    "DEFAULT_API": 16,  # this is the minimal API version we have

    # Session, for persistence
    "SESSION": None,

    # Color output configuration
    "COLORS": {
        "OFFSET": Fore.YELLOW,
        "OFFSET_ADDR": Fore.GREEN,
        "INSTRUCTION_NAME": Fore.YELLOW,
        "BRANCH_FALSE": Fore.RED,
        "BRANCH_TRUE": Fore.GREEN,
        "BRANCH": Fore.BLUE,
        "EXCEPTION": Fore.CYAN,
        "BB": Fore.MAGENTA,
        "NOTE": Fore.RED,
        "NORMAL": Fore.RESET,
        "OUTPUT": {
            "normal": Fore.RESET,
            "registers": Fore.YELLOW,
            "literal": Fore.GREEN,
            "offset": Fore.MAGENTA,
            "raw": Fore.RED,
            "string": Fore.RED,
            "meth": Fore.CYAN,
            "type": Fore.BLUE,
            "field": Fore.GREEN,
        },
    },
}

class Configuration:
    instance = None

    def __init__(self):
        """
        A Wrapper for the CONF object
        This creates a singleton, which has the same attributes everywhere.
        """
        if not Configuration.instance:
            Configuration.instance = default_conf

    def __getattr__(self, item):
        return getattr(self.instance, item)

    def __getitem__(self, item):
        return self.instance[item]

    def __setitem__(self, key, value):
        self.instance[key] = value

    def __str__(self):
        return str(self.instance)

    def __repr__(self):
        return repr(self.instance)

CONF = Configuration()

def is_android(filename):
    """
    Return the type of the file

    :param filename : the filename
    :returns: "APK", "DEX", None
    """
    if not filename:
        return None

    with open(filename, "rb") as fd:
        f_bytes = fd.read()
        return is_android_raw(f_bytes)

def is_android_raw(raw):
    """
    Returns a string that describes the type of file, for common Android
    specific formats
    """
    val = None

    # We do not check for META-INF/MANIFEST.MF,
    # as you also want to analyze unsigned APKs...
    # AndroidManifest.xml should be in every APK.
    # classes.dex and resources.arsc are not required!
    # if raw[0:2] == b"PK" and b'META-INF/MANIFEST.MF' in raw:
    # TODO this check might be still invalid. A ZIP file with stored APK inside would match as well.
    # probably it would be better to rewrite this and add more sanity checks.
    if raw[0:2] == b"PK" and b'AndroidManifest.xml' in raw:
        val = "APK"
        # check out
    elif raw[0:3] == b"dex":
        val = "DEX"
    elif raw[0:3] == b"dey":
        val = "DEY"
    elif raw[0:4] == b"\x03\x00\x08\x00" or raw[0:4] == b"\x00\x00\x08\x00":
        val = "AXML"
    elif raw[0:4] == b"\x02\x00\x0C\x00":
        val = "ARSC"

    return val

def show_logging(level=logging.INFO):
    """
    enable log messages on stdout

    We will catch all messages here! From all loggers...
    """
    logger = logging.getLogger()

    h = logging.StreamHandler(stream=sys.stderr)
    h.setFormatter(logging.Formatter(fmt="[%(levelname)-8s] %(name)s: %(message)s"))

    logger.addHandler(h)
    logger.setLevel(level)

def set_options(key, value):
    """
    .. deprecated:: 3.3.5
        Use :code:`CONF[key] = value` instead
    """
    CONF[key] = value

def rrmdir(directory):
    """
    Recursivly delete a directory

    :param directory: directory to remove
    """
    for root, dirs, files in os.walk(directory, topdown=False):
        for name in files:
            os.remove(os.path.join(root, name))
        for name in dirs:
            os.rmdir(os.path.join(root, name))
    os.rmdir(directory)

def make_color_tuple(color):
    """
    turn something like "#000000" into 0,0,0
    or "#FFFFFF into "255,255,255"
    """
    R = color[1:3]
    G = color[3:5]
    B = color[5:7]

    R = int(R, 16)
    G = int(G, 16)
    B = int(B, 16)

    return R, G, B

def interpolate_tuple(startcolor, goalcolor, steps):
    """
    Take two RGB color sets and mix them over a specified number of steps.  Return the list
    """
    # white

    R = startcolor[0]
    G = startcolor[1]
    B = startcolor[2]

    targetR = goalcolor[0]
    targetG = goalcolor[1]
    targetB = goalcolor[2]

    DiffR = targetR - R
    DiffG = targetG - G
    DiffB = targetB - B

    buffer = []

    for i in range(0, steps + 1):
        iR = R + (DiffR * i // steps)
        iG = G + (DiffG * i // steps)
        iB = B + (DiffB * i // steps)

        hR = str.replace(hex(iR), "0x", "")
        hG = str.replace(hex(iG), "0x", "")
        hB = str.replace(hex(iB), "0x", "")

        if len(hR) == 1:
            hR = "0" + hR
        if len(hB) == 1:
            hB = "0" + hB

        if len(hG) == 1:
            hG = "0" + hG

        color = str.upper("#" + hR + hG + hB)
        buffer.append(color)

    return buffer

def color_range(startcolor, goalcolor, steps):
    """
    wrapper for interpolate_tuple that accepts colors as html ("#CCCCC" and such)
    """
    start_tuple = make_color_tuple(startcolor)
    goal_tuple = make_color_tuple(goalcolor)

    return interpolate_tuple(start_tuple, goal_tuple, steps)

def load_api_specific_resource_module(resource_name, api=None):
    """
    Load the module from the JSON files and return a dict, which might be empty
    if the resource could not be loaded.

    If no api version is given, the default one from the CONF dict is used.

    :param resource_name: Name of the resource to load
    :param api: API version
    :return: dict
    """
    loader = dict(aosp_permissions=load_permissions,
                  api_permission_mappings=load_permission_mappings)

    if resource_name not in loader:
        raise InvalidResourceError("Invalid Resource '{}', not in [{}]".format(resource_name, ", ".join(loader.keys())))

    if not api:
        api = CONF["DEFAULT_API"]

    ret = loader[resource_name](api)

    if ret == {}:
        # No API mapping found, return default
        log.warning("API mapping for API level {} was not found! "
                    "Returning default, which is API level {}".format(api, CONF['DEFAULT_API']))
        ret = loader[resource_name](CONF['DEFAULT_API'])

    return ret


text:
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Linq;

class HornetArmada
{
    static void Main()
    {
        Dictionary<string, long> lastActivityData =
            new Dictionary<string, long>();
        Dictionary<string, Dictionary<string, long>> soldierData =
            new Dictionary<string, Dictionary<string, long>>();

        InserData(lastActivityData, soldierData);

        string[] tokens = Console.ReadLine()
            .Split('\\')
            .ToArray();

        if (tokens.Length > 1)
        {
            PrintActivitySoldierType(lastActivityData, soldierData, tokens);
        }
        else
        {
            PrintSoldierType(lastActivityData, soldierData, tokens[0]);
        }
    }

    private static void InserData(Dictionary<string, long> lastActivityData, Dictionary<string, Dictionary<string, long>> soldierData)
    {
        int n = int.Parse(Console.ReadLine());

        while (n > 0)
        {
            Match regex = Regex.Match(Console.ReadLine(),
                @"(?<activity>\d+) = (?<name>.+) -> (?<type>.+):(?<count>\d+)");

            long activity = long.Parse(regex.Groups["activity"].Value);
            string name = regex.Groups["name"].Value;
            string type = regex.Groups["type"].Value;
            long count = long.Parse(regex.Groups["count"].Value);

            if (!lastActivityData.ContainsKey(name))
            {
                lastActivityData.Add(name, activity);
                soldierData.Add(name, new Dictionary<string, long>());
            }

            if (lastActivityData[name] < activity)
            {
                lastActivityData[name] = activity;
            }

            if (!soldierData[name].ContainsKey(type))
            {
                soldierData[name].Add(type, 0);
            }

            soldierData[name][type] += count;

            n--;
        }
    }

    private static void PrintSoldierType(Dictionary<string, long> lastActivityData, Dictionary<string, Dictionary<string, long>> soldierData, string type)
    {
        foreach (var kvp in lastActivityData.OrderByDescending(x => x.Value))
        {
            if (soldierData[kvp.Key].ContainsKey(type))
            {
                Console.WriteLine($"{kvp.Value} : {kvp.Key}");
            }
        }
    }

    private static void PrintActivitySoldierType(Dictionary<string, long> lastActivityData, Dictionary<string, Dictionary<string, long>> soldierData, string[] tokens)
    {
        int activity = int.Parse(tokens[0]);
        string type = tokens[1];

        foreach (var kvp in soldierData.Where(x => x.Value.ContainsKey(type)).OrderByDescending(x => x.Value[type]))
        {
            if (lastActivityData[kvp.Key] < activity)
            {
                Console.WriteLine($"{kvp.Key} -> {kvp.Value[type]}");
            }
        }
    }
}


text:
require 'csv'
require 'active_support/all'
require 'baseball_stats/data_source'

module CalculatorTestHelper
  def self.included(base)
    header_row = "playerID,yearID,league,teamID,G,AB,R,H,2B,3B,HR,RBI,SB,CS"
    base.before { BaseballStats::DataSource.raw_data = header_row }
    base.let(:stats) { BaseballStats::DataSource.raw_data }
  end

  def calculator
    @calculator
  end

  def build_calculator(*args)
    @calculator = subject.new(*args)
  end

  def assert_calculator_raised(error, *args)
    expect {
      build_calculator(*args)
      calculator.calculate
    }.to raise_error(error)
  end
end


text:
module StyleSass
    class Engine < Rails::Engine
    end
end