text:
package org.apache.cloudstack.ca;

import java.io.IOException;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateNotYetValidException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.inject.Inject;
import javax.naming.ConfigurationException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;

import org.apache.cloudstack.api.ApiErrorCode;
import org.apache.cloudstack.api.ServerApiException;
import org.apache.cloudstack.api.command.admin.ca.IssueCertificateCmd;
import org.apache.cloudstack.api.command.admin.ca.ListCAProvidersCmd;
import org.apache.cloudstack.api.command.admin.ca.ListCaCertificateCmd;
import org.apache.cloudstack.api.command.admin.ca.ProvisionCertificateCmd;
import org.apache.cloudstack.api.command.admin.ca.RevokeCertificateCmd;
import org.apache.cloudstack.context.CallContext;
import org.apache.cloudstack.framework.ca.CAProvider;
import org.apache.cloudstack.framework.ca.Certificate;
import org.apache.cloudstack.framework.config.ConfigKey;
import org.apache.cloudstack.managed.context.ManagedContextRunnable;
import org.apache.cloudstack.poll.BackgroundPollManager;
import org.apache.cloudstack.poll.BackgroundPollTask;
import org.apache.cloudstack.utils.identity.ManagementServerNode;
import org.apache.cloudstack.utils.security.CertUtils;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;

import com.cloud.agent.AgentManager;
import com.cloud.alert.AlertManager;
import com.cloud.certificate.CrlVO;
import com.cloud.certificate.dao.CrlDao;
import com.cloud.event.ActionEvent;
import com.cloud.event.EventTypes;
import com.cloud.exception.AgentUnavailableException;
import com.cloud.exception.OperationTimedoutException;
import com.cloud.host.Host;
import com.cloud.host.Status;
import com.cloud.host.dao.HostDao;
import com.cloud.utils.component.ManagerBase;
import com.cloud.utils.exception.CloudRuntimeException;
import com.google.common.base.Strings;

public class CAManagerImpl extends ManagerBase implements CAManager {
    public static final Logger LOG = Logger.getLogger(CAManagerImpl.class);

    @Inject
    private CrlDao crlDao;
    @Inject
    private HostDao hostDao;
    @Inject
    private AgentManager agentManager;
    @Inject
    private BackgroundPollManager backgroundPollManager;
    @Inject
    private AlertManager alertManager;

    private static CAProvider configuredCaProvider;
    private static Map<String, CAProvider> caProviderMap = new HashMap<>();
    private static Map<String, Date> alertMap = new ConcurrentHashMap<>();
    private static Map<String, X509Certificate> activeCertMap = new ConcurrentHashMap<>();

    private List<CAProvider> caProviders;

    private CAProvider getConfiguredCaProvider() {
        if (configuredCaProvider != null) {
            return configuredCaProvider;
        }
        if (caProviderMap.containsKey(CAProviderPlugin.value()) && caProviderMap.get(CAProviderPlugin.value()) != null) {
            configuredCaProvider = caProviderMap.get(CAProviderPlugin.value());
            return configuredCaProvider;
        }
        throw new CloudRuntimeException("Failed to find default configured CA provider plugin");
    }

    private CAProvider getCAProvider(final String provider) {
        if (Strings.isNullOrEmpty(provider)) {
            return getConfiguredCaProvider();
        }
        final String caProviderName = provider.toLowerCase();
        if (!caProviderMap.containsKey(caProviderName)) {
            throw new CloudRuntimeException(String.format("CA provider plugin '%s' not found", caProviderName));
        }
        final CAProvider caProvider = caProviderMap.get(caProviderName);
        if (caProvider == null) {
            throw new CloudRuntimeException(String.format("CA provider plugin '%s' returned is null", caProviderName));
        }
        return caProvider;
    }

    ///////////////////////////////////////////////////////////
    /////////////// CA Manager API Handlers ///////////////////
    ///////////////////////////////////////////////////////////

    @Override
    public List<CAProvider> getCaProviders() {
        return caProviders;
    }

    @Override
    public Map<String, X509Certificate> getActiveCertificatesMap() {
        return activeCertMap;
    }

    @Override
    public boolean canProvisionCertificates() {
        return getConfiguredCaProvider().canProvisionCertificates();
    }

    @Override
    public String getCaCertificate(final String caProvider) throws IOException {
        final CAProvider provider = getCAProvider(caProvider);
        return CertUtils.x509CertificatesToPem(provider.getCaCertificate());
    }

    @Override
    @ActionEvent(eventType = EventTypes.EVENT_CA_CERTIFICATE_ISSUE, eventDescription = "issuing certificate", async = true)
    public Certificate issueCertificate(final String csr, final List<String> domainNames, final List<String> ipAddresses, final Integer validityDuration, final String caProvider) {
        CallContext.current().setEventDetails("domain(s): " + domainNames + " addresses: " + ipAddresses);
        final CAProvider provider = getCAProvider(caProvider);
        Integer validity = CAManager.CertValidityPeriod.value();
        if (validityDuration != null) {
            validity = validityDuration;
        }
        if (Strings.isNullOrEmpty(csr)) {
            if (domainNames == null || domainNames.isEmpty()) {
                throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "No domains or CSR provided");
            }
            return provider.issueCertificate(domainNames, ipAddresses, validity);
        }
        return provider.issueCertificate(csr, domainNames, ipAddresses, validity);
    }

    @Override
    @ActionEvent(eventType = EventTypes.EVENT_CA_CERTIFICATE_REVOKE, eventDescription = "revoking certificate", async = true)
    public boolean revokeCertificate(final BigInteger certSerial, final String certCn, final String caProvider) {
        CallContext.current().setEventDetails("cert serial: " + certSerial);
        final CrlVO crl = crlDao.revokeCertificate(certSerial, certCn);
        if (crl != null && crl.getCertSerial().equals(certSerial)) {
            final CAProvider provider = getCAProvider(caProvider);
            return provider.revokeCertificate(certSerial, certCn);
        }
        return false;
    }

    @Override
    @ActionEvent(eventType = EventTypes.EVENT_CA_CERTIFICATE_PROVISION, eventDescription = "provisioning certificate for host", async = true)
    public boolean provisionCertificate(final Host host, final Boolean reconnect, final String caProvider) {
        if (host == null) {
            throw new CloudRuntimeException("Unable to find valid host to renew certificate for");
        }
        CallContext.current().setEventDetails("host id: " + host.getId());
        CallContext.current().putContextParameter(Host.class, host.getUuid());
        final String csr;
        try {
            csr = generateKeyStoreAndCsr(host, null);
            if (Strings.isNullOrEmpty(csr)) {
                return false;
            }
            final Certificate certificate = issueCertificate(csr, Arrays.asList(host.getName(), host.getPrivateIpAddress()), Arrays.asList(host.getPrivateIpAddress(), host.getPublicIpAddress(), host.getStorageIpAddress()), CAManager.CertValidityPeriod.value(), caProvider);
            return deployCertificate(host, certificate, reconnect, null);
        } catch (final AgentUnavailableException | OperationTimedoutException e) {
            LOG.error("Host/agent is not available or operation timed out, failed to setup keystore and generate CSR for host/agent id=" + host.getId() + ", due to: ", e);
            throw new CloudRuntimeException("Failed to generate keystore and get CSR from the host/agent id=" + host.getId());
        }
    }

    @Override
    public String generateKeyStoreAndCsr(final Host host, final Map<String, String> sshAccessDetails) throws AgentUnavailableException, OperationTimedoutException {
        final SetupKeyStoreCommand cmd = new SetupKeyStoreCommand(CertValidityPeriod.value());
        if (sshAccessDetails != null && !sshAccessDetails.isEmpty()) {
            cmd.setAccessDetail(sshAccessDetails);
        }
        CallContext.current().setEventDetails("generating keystore and CSR for host id: " + host.getId());
        final SetupKeystoreAnswer answer = (SetupKeystoreAnswer)agentManager.send(host.getId(), cmd);
        return answer.getCsr();
    }

    @Override
    public boolean deployCertificate(final Host host, final Certificate certificate, final Boolean reconnect, final Map<String, String> sshAccessDetails)
            throws AgentUnavailableException, OperationTimedoutException {
        final SetupCertificateCommand cmd = new SetupCertificateCommand(certificate);
        if (sshAccessDetails != null && !sshAccessDetails.isEmpty()) {
            cmd.setAccessDetail(sshAccessDetails);
        }
        CallContext.current().setEventDetails("deploying certificate for host id: " + host.getId());
        final SetupCertificateAnswer answer = (SetupCertificateAnswer)agentManager.send(host.getId(), cmd);
        if (answer.getResult()) {
            CallContext.current().setEventDetails("successfully deployed certificate for host id: " + host.getId());
        } else {
            CallContext.current().setEventDetails("failed to deploy certificate for host id: " + host.getId());
        }

        if (answer.getResult()) {
            getActiveCertificatesMap().put(host.getPrivateIpAddress(), certificate.getClientCertificate());
            if (sshAccessDetails == null && reconnect != null && reconnect) {
                LOG.info(String.format("Successfully setup certificate on host, reconnecting with agent with id=%d, name=%s, address=%s", host.getId(), host.getName(), host.getPublicIpAddress()));
                try {
                    agentManager.reconnect(host.getId());
                } catch (AgentUnavailableException | CloudRuntimeException e) {
                    LOG.debug("Error when reconnecting to host: " + host.getUuid(), e);
                }
            }
            return true;
        }
        return false;
    }

    @Override
    public void purgeHostCertificate(final Host host) {
        if (host == null) {
            return;
        }
        final String privateAddress = host.getPrivateIpAddress();
        final String publicAddress = host.getPublicIpAddress();
        final Map<String, X509Certificate> activeCertsMap = getActiveCertificatesMap();
        if (!Strings.isNullOrEmpty(privateAddress) && activeCertsMap.containsKey(privateAddress)) {
            activeCertsMap.remove(privateAddress);
        }
        if (!Strings.isNullOrEmpty(publicAddress) && activeCertsMap.containsKey(publicAddress)) {
            activeCertsMap.remove(publicAddress);
        }
    }

    @Override
    public void sendAlert(final Host host, final String subject, final String message) {
        if (host == null) {
            return;
        }
        alertManager.sendAlert(AlertManager.AlertType.ALERT_TYPE_CA_CERT, host.getDataCenterId(), host.getPodId(), subject, message);
    }

    @Override
    public SSLEngine createSSLEngine(final SSLContext sslContext, final String remoteAddress) throws GeneralSecurityException, IOException {
        if (sslContext == null) {
            throw new CloudRuntimeException("SSLContext provided to create SSLEngine is null, aborting");
        }
        if (Strings.isNullOrEmpty(remoteAddress)) {
            throw new CloudRuntimeException("Remote client address connecting to mgmt server cannot be empty/null");
        }
        return getConfiguredCaProvider().createSSLEngine(sslContext, remoteAddress, getActiveCertificatesMap());
    }

    @Override
    public KeyStore getManagementKeyStore() throws KeyStoreException {
        return getConfiguredCaProvider().getManagementKeyStore();
    }

    @Override
    public char[] getKeyStorePassphrase() {
        return getConfiguredCaProvider().getKeyStorePassphrase();
    }

    ////////////////////////////////////////////////////
    /////////////// CA Manager Setup ///////////////////
    ////////////////////////////////////////////////////

    public static final class CABackgroundTask extends ManagedContextRunnable implements BackgroundPollTask {
        private CAManager caManager;
        private HostDao hostDao;

        public CABackgroundTask(final CAManager caManager, final HostDao hostDao) {
            this.caManager = caManager;
            this.hostDao = hostDao;
        }

        @Override
        protected void runInContext() {
            try {
                if (LOG.isTraceEnabled()) {
                    LOG.trace("CA background task is running...");
                }
                final DateTime now = DateTime.now(DateTimeZone.UTC);
                final Map<String, X509Certificate> certsMap = caManager.getActiveCertificatesMap();
                for (final Iterator<Map.Entry<String, X509Certificate>> it = certsMap.entrySet().iterator(); it.hasNext();) {
                    final Map.Entry<String, X509Certificate> entry = it.next();
                    if (entry == null) {
                        continue;
                    }
                    final String hostIp = entry.getKey();
                    final X509Certificate certificate = entry.getValue();
                    if (certificate == null) {
                        it.remove();
                        continue;
                    }
                    final Host host = hostDao.findByIp(hostIp);
                    if (host == null || host.getManagementServerId() == null || host.getManagementServerId() != ManagementServerNode.getManagementServerId() || host.getStatus() != Status.Up) {
                        if (host == null || (host.getManagementServerId() != null && host.getManagementServerId() != ManagementServerNode.getManagementServerId())) {
                            it.remove();
                        }
                        continue;
                    }

                    final String hostDescription = String.format("host id=%d, uuid=%s, name=%s, ip=%s, zone id=%d", host.getId(), host.getUuid(), host.getName(), hostIp, host.getDataCenterId());

                    try {
                        certificate.checkValidity(now.plusDays(CertExpiryAlertPeriod.valueIn(host.getClusterId())).toDate());
                    } catch (final CertificateExpiredException | CertificateNotYetValidException e) {
                        LOG.warn("Certificate is going to expire for " + hostDescription);
                        if (AutomaticCertRenewal.valueIn(host.getClusterId())) {
                            try {
                                LOG.debug("Attempting certificate auto-renewal for " + hostDescription);
                                boolean result = caManager.provisionCertificate(host, false, null);
                                if (result) {
                                    LOG.debug("Succeeded in auto-renewing certificate for " + hostDescription);
                                } else {
                                    LOG.debug("Failed in auto-renewing certificate for " + hostDescription);
                                }
                            } catch (final Throwable ex) {
                                LOG.warn("Failed to auto-renew certificate for " + hostDescription + ", with error=", ex);
                                caManager.sendAlert(host, "Certificate auto-renewal failed for " + hostDescription,
                                        String.format("Certificate is going to expire for %s. Auto-renewal failed to renew the certificate, please renew it manually. It is not valid after %s.",
                                                hostDescription, certificate.getNotAfter()));
                            }
                        } else {
                            if (alertMap.containsKey(hostIp)) {
                                final Date lastSentDate = alertMap.get(hostIp);
                                if (now.minusDays(1).toDate().before(lastSentDate)) {
                                    continue;
                                }
                            }
                            caManager.sendAlert(host, "Certificate expiring soon for " + hostDescription,
                                    String.format("Certificate is going to expire for %s. Please renew it, it is not valid after %s.", hostDescription, certificate.getNotAfter()));
                            alertMap.put(hostIp, new Date());
                        }
                    }
                }
            } catch (final Throwable t) {
                LOG.error("Error trying to run CA background task", t);
            }
        }

        @Override
        public Long getDelay() {
            return CABackgroundJobDelay.value() * 1000L;
        }
    }

    public void setCaProviders(final List<CAProvider> caProviders) {
        this.caProviders = caProviders;
        initializeCaProviderMap();
    }

    private void initializeCaProviderMap() {
        if (caProviderMap != null && caProviderMap.size() != caProviders.size()) {
            for (final CAProvider caProvider : caProviders) {
                caProviderMap.put(caProvider.getProviderName().toLowerCase(), caProvider);
            }
        }
    }

    @Override
    public boolean start() {
        super.start();
        initializeCaProviderMap();
        if (caProviderMap.containsKey(CAProviderPlugin.value())) {
            configuredCaProvider = caProviderMap.get(CAProviderPlugin.value());
        }
        if (configuredCaProvider == null) {
            LOG.error("Failed to find valid configured CA provider, please check!");
            return false;
        }
        return true;
    }

    @Override
    public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException {
        backgroundPollManager.submitTask(new CABackgroundTask(this, hostDao));
        return true;
    }

    //////////////////////////////////////////////////////////
    /////////////// CA Manager Descriptors ///////////////////
    //////////////////////////////////////////////////////////

    @Override
    public List<Class<?>> getCommands() {
        final List<Class<?>> cmdList = new ArrayList<Class<?>>();
        cmdList.add(ListCAProvidersCmd.class);
        cmdList.add(ListCaCertificateCmd.class);
        cmdList.add(IssueCertificateCmd.class);
        cmdList.add(ProvisionCertificateCmd.class);
        cmdList.add(RevokeCertificateCmd.class);
        return cmdList;
    }

    @Override
    public String getConfigComponentName() {
        return CAManager.class.getSimpleName();
    }

    @Override
    public ConfigKey<?>[] getConfigKeys() {
        return new ConfigKey<?>[] {CAProviderPlugin, CertKeySize, CertSignatureAlgorithm, CertValidityPeriod, AutomaticCertRenewal, CABackgroundJobDelay, CertExpiryAlertPeriod};
    }
}


text:
/****************************************************************************
 * Included Files
 ****************************************************************************/

#include <nuttx/config.h>

#include <sys/types.h>
#include <sys/time.h>

#include <stdint.h>
#include <stdbool.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <pthread.h>
#include <semaphore.h>
#include <poll.h>
#include <errno.h>
#include <assert.h>
#include <debug.h>

#include <nuttx/kmalloc.h>
#include <nuttx/clock.h>
#include <nuttx/arch.h>
#include <nuttx/fs/fs.h>
#include <nuttx/spi/spi.h>
#include <arpa/inet.h>

#include <nuttx/wireless/wireless.h>
#include <nuttx/wireless/cc3000.h>
#include <nuttx/wireless/cc3000/include/cc3000_upif.h>
#include <nuttx/wireless/cc3000/cc3000_common.h>
#include <nuttx/wireless/cc3000/hci.h>
#include "cc3000_socket.h"
#include "cc3000.h"

/****************************************************************************
 * Pre-processor Definitions
 ****************************************************************************/
#ifndef CCASSERT
#define CCASSERT(predicate) _x_CCASSERT_LINE(predicate, __LINE__)
#define _x_CCASSERT_LINE(predicate, line) typedef char constraint_violated_on_line_##line[2*((predicate)!=0)-1];
#endif

CCASSERT(sizeof(cc3000_buffer_desc) <= CONFIG_MQ_MAXMSGSIZE);

#ifndef CONFIG_CC3000_WORKER_THREAD_PRIORITY
#  define CONFIG_CC3000_WORKER_THREAD_PRIORITY (SCHED_PRIORITY_MAX)
#endif

#ifndef CONFIG_CC3000_WORKER_STACKSIZE
#  define CONFIG_CC3000_WORKER_STACKSIZE 240
#endif

#ifndef CONFIG_CC3000_SELECT_THREAD_PRIORITY
#  define CONFIG_CC3000_SELECT_THREAD_PRIORITY (SCHED_PRIORITY_DEFAULT-1)
#endif

#ifndef CONFIG_CC3000_SELECT_STACKSIZE
#  define CONFIG_CC3000_SELECT_STACKSIZE 368
#endif

#ifndef ARRAY_SIZE
#  define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
#endif
#define NUMBER_OF_MSGS 1

#define FREE_SLOT -1
#define CLOSE_SLOT -2

#if defined(CONFIG_DEBUG) && defined(CONFIG_CC3000_PROBES)
#  define CC3000_GUARD (0xc35aa53c)
#  define INIT_GUARD(p) p->guard = CC3000_GUARD
#  define CHECK_GUARD(p) DEBUGASSERT(p->guard == CC3000_GUARD)
#  define PROBE(pin,state)  priv->config->probe(priv->config,pin, state)
#else
#  define INIT_GUARD(p)
#  define CHECK_GUARD(p)
#  define PROBE(pin,state)
#endif

#define waitlldbg(x,...)

/****************************************************************************
 * Private Types
 ****************************************************************************/

/****************************************************************************
 * Private Function Prototypes
 ****************************************************************************/

/* Low-level SPI helpers */

static void cc3000_lock_and_select(FAR struct spi_dev_s *spi);
static void cc3000_deselect_and_unlock(FAR struct spi_dev_s *spi);

/* Interrupts and data sampling */

static void cc3000_notify(FAR struct cc3000_dev_s *priv);
static void *cc3000_worker(FAR void *arg);
static int cc3000_interrupt(int irq, FAR void *context);

/* Character driver methods */

static int cc3000_open(FAR struct file *filep);
static int cc3000_close(FAR struct file *filep);
static ssize_t cc3000_read(FAR struct file *filep, FAR char *buffer,
                           size_t len);
static ssize_t cc3000_write(FAR struct file *filep,
                            FAR const char *buffer, size_t len);
static int cc3000_ioctl(FAR struct file *filep, int cmd, unsigned long arg);
#ifndef CONFIG_DISABLE_POLL
static int cc3000_poll(FAR struct file *filep, struct pollfd *fds,
                       bool setup);
#endif

static int cc3000_wait_data(FAR struct cc3000_dev_s *priv, int sockfd);
static int cc3000_accept_socket(FAR struct cc3000_dev_s *priv, int sd,
                                FAR struct sockaddr *addr,
                                socklen_t *addrlen);
static int cc3000_add_socket(FAR struct cc3000_dev_s *priv, int sd);
static int cc3000_remove_socket(FAR struct cc3000_dev_s *priv, int sd);
static int cc3000_remote_closed_socket(FAR struct cc3000_dev_s *priv, int sd);

/****************************************************************************
 * Private Data
 ****************************************************************************/

/* This the vtable that supports the character driver interface */

static const struct file_operations cc3000_fops =
{
  cc3000_open,      /* open */
  cc3000_close,     /* close */
  cc3000_read,      /* read */
  cc3000_write,     /* write */
  0,                /* seek */
  cc3000_ioctl,     /* ioctl */
#ifndef CONFIG_DISABLE_POLL
  cc3000_poll       /* poll */
#endif
};

/* If only a single CC3000 device is supported, then the driver state
 * structure may as well be pre-allocated.
 */

#ifndef CONFIG_CC3000_MULTIPLE
static struct cc3000_dev_s g_cc3000;

/* Otherwise, we will need to maintain allocated driver instances in a list */

#else
static struct cc3000_dev_s *g_cc3000list;
#endif

uint8_t spi_readCommand[] = READ_COMMAND;

/****************************************************************************
 * Private Functions
 ****************************************************************************/
/****************************************************************************
 * Name: cc3000_devtake() and cc3000_devgive()
 *
 * Description:
 *   Used to get exclusive access to a CC3000 driver.
 *
 ****************************************************************************/

static int cc3000_devtake(FAR struct cc3000_dev_s *priv)
{
  int rv;

  /* Take the semaphore (perhaps waiting) */

  while ((rv = sem_wait(&priv->devsem)) != 0)
    {
      /* The only case that an error should occur here is if the wait was awakened
       * by a signal.
       */

      DEBUGASSERT(rv == OK || errno == EINTR);
    }

  return rv;
}

static inline int cc3000_devgive(FAR struct cc3000_dev_s *priv)
{
  return sem_post(&priv->devsem);
}

/****************************************************************************
 * Function: cc3000_configspi
 *
 * Description:
 *   Configure the SPI for use with the CC3000.  This function should be
 *   called to configure the SPI
 *   bus.
 *
 * Parameters:
 *   spi  - Reference to the SPI driver structure
 *
 * Returned Value:
 *   None
 *
 * Assumptions:
 *
 ****************************************************************************/

static inline void cc3000_configspi(FAR struct spi_dev_s *spi)
{
  ndbg("Mode: %d Bits: 8 Frequency: %d\n",
       CONFIG_CC3000_SPI_MODE, CONFIG_CC3000_SPI_FREQUENCY);

  SPI_SETMODE(spi, CONFIG_CC3000_SPI_MODE);
  SPI_SETBITS(spi, 8);
  SPI_SETFREQUENCY(spi, CONFIG_CC3000_SPI_FREQUENCY);
}

/****************************************************************************
 * Function: cc3000_lock
 *
 * Description:
 *   Lock the SPI bus and re-configure as necessary.  This function must be
 *   to assure: (1) exclusive access to the SPI bus, and (2) to assure that
 *   the shared bus is properly configured for the cc3000 module.
 *
 * Parameters:
 *   spi  - Reference to the SPI driver structure
 *
 * Returned Value:
 *   None
 *
 * Assumptions:
 *
 ****************************************************************************/

static void cc3000_lock_and_select(FAR struct spi_dev_s *spi)
{
#ifndef CONFIG_SPI_OWNBUS
  /* Lock the SPI bus because there are multiple devices competing for the
   * SPI bus
   */

  /* Lock the SPI bus so that we have exclusive access */

  (void)SPI_LOCK(spi, true);
#endif

  /* We have the lock.  Now make sure that the SPI bus is configured for the
   * CC3000 (it might have gotten configured for a different device while
   * unlocked)
   */

  cc3000_configspi(spi);
  SPI_SELECT(spi, SPIDEV_WIRELESS, true);
}

/****************************************************************************
 * Function: cc3000_unlock
 *
 * Description:
 *   If we are sharing the SPI bus with other devices (CONFIG_SPI_OWNBUS
 *   undefined) then we need to un-lock the SPI bus for each transfer,
 *   possibly losing the current configuration.
 *
 * Parameters:
 *   spi  - Reference to the SPI driver structure
 *
 * Returned Value:
 *   None
 *
 * Assumptions:
 *
 ****************************************************************************/

static void cc3000_deselect_and_unlock(FAR struct spi_dev_s *spi)
{
   /* De select */

  SPI_SELECT(spi, SPIDEV_WIRELESS, false);

#ifndef CONFIG_SPI_OWNBUS
  /* Relinquish the SPI bus. */

  (void)SPI_LOCK(spi, false);
#endif
}

/****************************************************************************
 * Function: cc3000_wait
 *
 * Description:
 *  Helper function to wait on the semaphore signaled by the
 *
 * Parameters:
 *   priv - Reference to the CC3000 driver structure
 *   priv -
 *
 * Returned Value:
 *   0 - Semaphore signaled and devsem retaken
 *  < 0 - Some Error occurred
 * Assumptions:
 *   Own the devsem on entry
 *
 ****************************************************************************/

static int cc3000_wait(FAR struct cc3000_dev_s *priv, sem_t* psem)
{
  int ret;

  /* Give up */

  sched_lock();
  cc3000_devgive(priv);

  /* Wait on first psem to become signaled */

  ret = sem_wait(psem);
  if (ret >= 0)
    {
      /* Yes... then retake the mutual exclusion semaphore */

      ret = cc3000_devtake(priv);
    }

  sched_unlock();

  /* Was the semaphore wait successful? Did we successful re-take the
   * mutual exclusion semaphore?
   */

  if (ret < 0)
    {
      /* No.. One of the two sem_wait's failed. */

      ret = -errno;
    }

  return ret;
}

/****************************************************************************
 * Function: cc3000_wait_irq
 *
 * Description:
 *  Helper function to wait on the irqsem signaled by the interrupt
 *
 * Parameters:
 *   priv - Reference to the CC3000 driver structure
 *
 * Returned Value:
 *   0 - Semaphore signaled and devsem retaken
 *  < 0 - Some Error occurred
 * Assumptions:
 *   Own the devsem on entry
 *
 ****************************************************************************/

static inline int cc3000_wait_irq(FAR struct cc3000_dev_s *priv)
{
  return cc3000_wait(priv,&priv->irqsem);
}

/****************************************************************************
 * Function: cc3000_wait_ready
 *
 * Description:
 *  Helper function to wait on the readysem signaled by the interrupt
 *
 * Parameters:
 *   priv - Reference to the CC3000 driver structure
 *
 * Returned Value:
 *   0 - Semaphore signaled and devsem retaken
 *  < 0 - Some Error occurred
 * Assumptions:
 *   Own the devsem on entry
 *
 ****************************************************************************/

static inline int cc3000_wait_ready(FAR struct cc3000_dev_s *priv)
{
  return cc3000_wait(priv,&priv->readysem);
}

/****************************************************************************
 * Name: cc3000_pollnotify
 ****************************************************************************/

#ifndef CONFIG_DISABLE_POLL
static void cc3000_pollnotify(FAR struct cc3000_dev_s *priv, uint32_t type)
{
  int i;

  for (i = 0; i < CONFIG_CC3000_NPOLLWAITERS; i++)
    {
      struct pollfd *fds = priv->fds[i];
      if (fds)
        {
          fds->revents |= type;
          nllvdbg("Report events: %02x\n", fds->revents);
          sem_post(fds->sem);
        }
    }
}
#endif

/****************************************************************************
 * Name: cc3000_notify
 ****************************************************************************/

static void cc3000_notify(FAR struct cc3000_dev_s *priv)
{
  /* If there are threads waiting for read data, then signal one of them
   * that the read data is available.
   */

  if (priv->nwaiters > 0)
    {
      /* After posting this semaphore, we need to exit because the CC3000
       * is no longer available.
       */

      sem_post(&priv->waitsem);
    }

  /* If there are threads waiting on poll() for CC3000 data to become available,
   * then wake them up now.  NOTE: we wake up all waiting threads because we
   * do not know that they are going to do.  If they all try to read the data,
   * then some make end up blocking after all.
   */

#ifndef CONFIG_DISABLE_POLL
  cc3000_pollnotify(priv, POLLIN);
#endif
}

/****************************************************************************
 * Name: cc3000_worker
 ****************************************************************************/

static void * select_thread_func(FAR void *arg)
{
  FAR struct cc3000_dev_s *priv = (FAR struct cc3000_dev_s *)arg;
  struct timeval timeout;
  TICC3000fd_set readsds;
  TICC3000fd_set exceptsds;
  int ret = 0;
  int maxFD = 0;
  int s = 0;

  memset(&timeout, 0, sizeof(struct timeval));
  timeout.tv_sec  = 0;
  timeout.tv_usec = (500000);  /* 500 msecs */

  while (1)
    {
      sem_wait(&priv->selectsem);

      CHECK_GUARD(priv);

      /* Increase the count back by one to be decreased by the original caller */

      sem_post(&priv->selectsem);

      maxFD = -1;
      CC3000_FD_ZERO(&readsds);
      CC3000_FD_ZERO(&exceptsds);

      /* Ping correct socket descriptor param for select */

      for (s = 0; s < CONFIG_WL_MAX_SOCKETS; s++)
        {
          if (priv->sockets[s].sd != FREE_SLOT)
            {
              if (priv->sockets[s].sd == CLOSE_SLOT)
                {
                  priv->sockets[s].sd = FREE_SLOT;
                  waitlldbg("Close\n");
                  int count;
                  do
                    {
                      sem_getvalue(&priv->sockets[s].semwait, &count);
                      if (count < 0)
                        {
                          /* Release the waiting threads */

                          waitlldbg("Closed Signaled %d\n",count);
                          sem_post(&priv->sockets[s].semwait);
                        }
                    }
                  while (count < 0);

                  continue;
                }

              CC3000_FD_SET(priv->sockets[s].sd, &readsds);
              CC3000_FD_SET(priv->sockets[s].sd, &exceptsds);
              if (maxFD <= priv->sockets[s].sd)
                {
                  maxFD = priv->sockets[s].sd + 1;
                }
            }
        }

      if (maxFD < 0)
        {
          /* Handled only socket close. */

          continue;
        }

      /* Polling instead of blocking here to process "accept" below */

      ret = cc3000_select(maxFD, (fd_set *) &readsds, NULL,
                         (fd_set *) &exceptsds, &timeout);

      if (priv->selecttid == -1)
        {
          /* driver close will terminate the thread and by that all sync
           * objects owned by it will be released
           */

          return OK;
        }

      for (s = 0; s < CONFIG_WL_MAX_SOCKETS; s++)
        {
          if ((priv->sockets[s].sd != FREE_SLOT ||
               priv->sockets[s].sd != CLOSE_SLOT) &&                         /* Check that the socket is valid */
               priv->sockets[s].sd != priv->accepting_socket.acc.sd)         /* Verify this is not an accept socket */
            {
              if (ret > 0 && CC3000_FD_ISSET(priv->sockets[s].sd, &readsds)) /* and has pending data */
                {
                  waitlldbg("Signaled %d\n", priv->sockets[s].sd);
                  sem_post(&priv->sockets[s].semwait);                       /* release the waiting thread */
                }
              else if (ret > 0 && CC3000_FD_ISSET(priv->sockets[s].sd, &exceptsds)) /* or has pending exception */
                {
                  waitlldbg("Signaled %d (exception)\n", priv->sockets[s].sd);
                  sem_post(&priv->sockets[s].semwait);                       /* release the waiting thread */
                }
              else if (priv->sockets[s].received_closed_event)               /* or remote has closed connection and we have now read all of HW buffer. */
                {
                  waitlldbg("Signaled %d (closed & empty)\n", priv->sockets[s].sd);
                  priv->sockets[s].emptied_and_remotely_closed = true;
                  sem_post(&priv->sockets[s].semwait);                       /* release the waiting thread */
                }
            }
        }

      if (priv->accepting_socket.acc.sd != FREE_SLOT)                        /* If accept polling in needed */
        {
          if (priv->accepting_socket.acc.sd == CLOSE_SLOT)
            {
              ret = CC3000_SOC_ERROR;
            }
            else
            {
              ret = cc3000_do_accept(priv->accepting_socket.acc.sd,              /* Send the select command on non blocking */
                                     &priv->accepting_socket.addr,               /* Set up in ioctl */
                                     &priv->accepting_socket.addrlen);
            }

          if (ret != CC3000_SOC_IN_PROGRESS)                                 /* Not waiting => error or accepted */
            {
              priv->accepting_socket.acc.sd = FREE_SLOT;
              priv->accepting_socket.acc.status = ret;
              sem_post(&priv->accepting_socket.acc.semwait);                 /* Release the waiting thread */
            }
        }
    }

  return OK;
}

/****************************************************************************
 * Name: cc3000_worker
 ****************************************************************************/

static void * cc3000_worker(FAR void *arg)
{
  FAR struct cc3000_dev_s *priv = (FAR struct cc3000_dev_s *)arg;
  int ret;

  ASSERT(priv != NULL && priv->config != NULL);

  /* We have started  release our creator*/

  sem_post(&priv->readysem);
  while (1)
    {
      PROBE(0,1);
      CHECK_GUARD(priv);
      cc3000_devtake(priv);

      /* Done ? */

      if ((cc3000_wait_irq(priv) != -EINTR) && (priv->workertid != -1))
        {
          PROBE(0,0);
          nllvdbg("State%d\n",priv->state);
          switch (priv->state)
            {
            case eSPI_STATE_POWERUP:
              /* Signal the device has interrupted after power up */

              priv->state = eSPI_STATE_INITIALIZED;
              sem_post(&priv->readysem);
              break;

            case eSPI_STATE_WRITE_WAIT_IRQ:
              /* Signal the device has interrupted after Chip Select During a write operation */

              priv->state = eSPI_STATE_WRITE_PROCEED;
              sem_post(&priv->readysem);
              break;

            case eSPI_STATE_WRITE_DONE:  /* IRQ post a write => Solicited */
            case eSPI_STATE_IDLE: /* IRQ when Idel => cc3000 has data for the hosts Unsolicited */
              {
                uint16_t data_to_recv;
                priv->state = eSPI_STATE_READ_IRQ;

                /* Issue the read command */

                cc3000_lock_and_select(priv->spi); /* Assert CS */
                priv->state = eSPI_STATE_READ_PROCEED;
                SPI_EXCHANGE(priv->spi,spi_readCommand, priv->rx_buffer.pbuffer,
                             ARRAY_SIZE(spi_readCommand));

               /* Extract Length bytes from Rx Buffer.  Here we need to convert
                * unaligned data in network order (big endian, MS byte first) to
                * host order.  We cannot use ntohs here because the data is not
                * aligned.
                */

               data_to_recv = (uint16_t)priv->rx_buffer.pbuffer[READ_OFFSET_TO_LENGTH] << 8 |
                              (uint16_t)priv->rx_buffer.pbuffer[READ_OFFSET_TO_LENGTH + 1];

               if (data_to_recv)
                  {
                    /* We will read ARRAY_SIZE(spi_readCommand) + data_to_recv. is it odd? */

                    if ((data_to_recv +  ARRAY_SIZE(spi_readCommand)) & 1)
                      {
                        /* Odd so make it even */

                        data_to_recv++;
                      }

                    /* Read the whole payload in at the beginning of the buffer
                     * Will it fit?
                     */

                    if (data_to_recv >= priv->rx_buffer_max_len)
                      {
                        lowsyslog(LOG_INFO, "data_to_recv %d", data_to_recv);
                      }

                    DEBUGASSERT(data_to_recv < priv->rx_buffer_max_len);
                    SPI_RECVBLOCK(priv->spi, priv->rx_buffer.pbuffer, data_to_recv);
                  }

                cc3000_deselect_and_unlock(priv->spi); /* De assert CS */

                /* Disable more messages as the wl code will resume via CC3000IOC_COMPLETE */

                if (data_to_recv)
                  {
                    int count;

                    priv->state = eSPI_STATE_READ_READY;
                    priv->rx_buffer.len = data_to_recv;

                    ret = mq_send(priv->queue, &priv->rx_buffer, sizeof(priv->rx_buffer), 1);
                    DEBUGASSERT(ret >= 0);
                    UNUSED(ret);

                    /* Notify any waiters that new CC3000 data is available */

                    cc3000_notify(priv);

                    /* Give up driver */

                    cc3000_devgive(priv);

                    nllvdbg("Wait On Completion\n");
                    sem_wait(priv->wrkwaitsem);
                    nllvdbg("Completed S:%d irq :%d\n",
                            priv->state, priv->config->irq_read(priv->config));

                    sem_getvalue(&priv->irqsem, &count);
                    if (priv->config->irq_read(priv->config) && count==0)
                      {
                        sem_post(&priv->irqsem);
                      }

                    if (priv->state == eSPI_STATE_READ_READY)
                      {
                         priv->state = eSPI_STATE_IDLE;
                      }

                    continue;
                  }
              }
              break;

            default:
              nllvdbg("default: State%d\n",priv->state);
              break;
            }
        }

      cc3000_devgive(priv);
    }

  return OK;
}

/****************************************************************************
 * Name: cc3000_interrupt
 ****************************************************************************/

static int cc3000_interrupt(int irq, FAR void *context)
{
  FAR struct cc3000_dev_s    *priv;

  /* Which CC3000 device caused the interrupt? */

#ifndef CONFIG_CC3000_MULTIPLE
  priv = &g_cc3000;
#else
  for (priv = g_cc3000list;
       priv && priv->configs->irq != irq;
       priv = priv->flink);

  ASSERT(priv != NULL);
#endif

  /* Run the worker thread */

  PROBE(1,0);
  sem_post(&priv->irqsem);
  PROBE(1,1);

  /* Clear any pending interrupts and return success */

  priv->config->irq_clear(priv->config);
  return OK;
}

/****************************************************************************
 * Name: cc3000_open
 ****************************************************************************/

static int cc3000_open(FAR struct file *filep)
{
  FAR struct inode *inode;
  struct mq_attr attr;
  pthread_attr_t tattr;
  pthread_t threadid;
  struct sched_param param;
  char queuename[QUEUE_NAMELEN];
  FAR struct cc3000_dev_s *priv;
  uint8_t tmp;
  int ret;
#ifdef CONFIG_CC3000_MT
  int s;
#endif

  DEBUGASSERT(filep);
  inode = filep->f_inode;

  DEBUGASSERT(inode && inode->i_private);
  priv = (FAR struct cc3000_dev_s *)inode->i_private;

  CHECK_GUARD(priv);

  nllvdbg("crefs: %d\n", priv->crefs);

  /* Get exclusive access to the driver data structure */

  ret = cc3000_devtake(priv);
  if (ret < 0)
    {
      return -ret;
    }

  /* Increment the reference count */

  tmp = priv->crefs + 1;
  if (tmp == 0)
    {
      /* More than 255 opens; uint8_t overflows to zero */

      ret = -EMFILE;
      goto out_with_sem;
    }

  /* When the reference increments to 1, this is the first open event
   * on the driver.. and an opportunity to do any one-time initialization.
   */

  if (tmp == 1)
    {
      sem_init(&priv->waitsem, 0, 0);  /* Initialize event wait semaphore */
      sem_init(&priv->irqsem, 0, 0);   /* Initialize IRQ Ready semaphore */
      sem_init(&priv->readysem, 0, 0); /* Initialize Device Ready semaphore */

#ifdef CONFIG_CC3000_MT
      priv->accepting_socket.acc.sd = FREE_SLOT;
      sem_init(&priv->accepting_socket.acc.semwait, 0, 0);
      for (s = 0; s < CONFIG_WL_MAX_SOCKETS; s++)
        {
          priv->sockets[s].sd = FREE_SLOT;
          priv->sockets[s].received_closed_event = false;
          priv->sockets[s].emptied_and_remotely_closed = false;
          sem_init(&priv->sockets[s].semwait, 0, 0);
        }
#endif

      /* Ensure the power is off  so we get the falling edge of IRQ*/

      priv->config->power_enable(priv->config, false);

      attr.mq_maxmsg  = NUMBER_OF_MSGS;
      attr.mq_msgsize = sizeof(cc3000_buffer_desc);
      attr.mq_flags   = 0;

      /* Set the flags for the open of the queue.
       * Make it a blocking open on the queue, meaning it will block if
       * this process tries to send to the queue and the queue is full.
       *
       *   O_CREAT - the queue will get created if it does not already exist.
       *   O_WRONLY - we are only planning to write to the queue.
       *
       * Open the queue, and create it if the receiving process hasn't
       * already created it.
       */

      snprintf(queuename, QUEUE_NAMELEN, QUEUE_FORMAT, priv->minor);
      priv->queue = mq_open(queuename,O_WRONLY|O_CREAT, 0666, &attr);
      if (priv->queue < 0)
        {
          ret = -errno;
          goto errout_sem_destroy;
        }

      pthread_attr_init(&tattr);
      tattr.stacksize = CONFIG_CC3000_WORKER_STACKSIZE;
      param.sched_priority = CONFIG_CC3000_WORKER_THREAD_PRIORITY;
      pthread_attr_setschedparam(&tattr, &param);

      ret = pthread_create(&priv->workertid, &tattr, cc3000_worker,
                           (pthread_addr_t)priv);
      if (ret != 0)
        {
          ret = -ret; /* pthread_create does not modify errno. */
          goto errout_mq_close;
        }

      pthread_attr_init(&tattr);
      tattr.stacksize = CONFIG_CC3000_SELECT_STACKSIZE;
      param.sched_priority = CONFIG_CC3000_SELECT_THREAD_PRIORITY;
      pthread_attr_setschedparam(&tattr, &param);

      sem_init(&priv->selectsem, 0, 0);
      ret = pthread_create(&priv->selecttid, &tattr, select_thread_func,
                           (pthread_addr_t)priv);
      if (ret != 0)
        {
          ret = -ret; /* pthread_create does not modify errno. */
          goto errout_worker_cancel;
        }

      /* Do late allocation with hopes of realloc not fragmenting */

      priv->rx_buffer.pbuffer =  kmm_malloc(priv->rx_buffer_max_len);
      DEBUGASSERT(priv->rx_buffer.pbuffer);
      if (!priv->rx_buffer.pbuffer)
        {
          ret = -errno;
          goto errout_select_cancel;
        }

      priv->state = eSPI_STATE_POWERUP;
      priv->config->irq_clear(priv->config);

      /* Bring the device Online A) on http://processors.wiki.ti.com/index.php/File:CC3000_Master_SPI_Write_Sequence_After_Power_Up.png */

      priv->config->irq_enable(priv->config, true);

      /* Wait on child thread */

      cc3000_wait_ready(priv);
      priv->config->power_enable(priv->config, true);
    }

  /* Save the new open count on success */

  priv->crefs = tmp;
  ret = OK;

  goto out_with_sem;

errout_select_cancel:
  threadid = priv->selecttid;
  priv->selecttid = -1;
  pthread_cancel(threadid);
  pthread_join(threadid, NULL);
  sem_destroy(&priv->selectsem);

errout_worker_cancel:
  threadid = priv->workertid;
  priv->workertid = -1;
  pthread_cancel(threadid);
  pthread_join(threadid, NULL);

errout_mq_close:
  mq_close(priv->queue);
  priv->queue = 0;

errout_sem_destroy:
#ifdef CONFIG_CC3000_MT
  sem_destroy(&priv->accepting_socket.acc.semwait);

  for (s = 0; s < CONFIG_WL_MAX_SOCKETS; s++)
    {
      priv->sockets[s].sd = FREE_SLOT;
      sem_destroy(&priv->sockets[s].semwait);
    }
#endif

  sem_destroy(&priv->waitsem);
  sem_destroy(&priv->irqsem);
  sem_destroy(&priv->readysem);

out_with_sem:
  cc3000_devgive(priv);
  return ret;
}

/****************************************************************************
 * Name: cc3000_close
 ****************************************************************************/

static int cc3000_close(FAR struct file *filep)
{
  FAR struct inode         *inode;
  FAR struct cc3000_dev_s *priv;
  int                       ret;
#ifdef CONFIG_CC3000_MT
  int s;
#endif

  DEBUGASSERT(filep);
  inode = filep->f_inode;

  DEBUGASSERT(inode && inode->i_private);
  priv = (FAR struct cc3000_dev_s *)inode->i_private;

  CHECK_GUARD(priv);

  nllvdbg("crefs: %d\n", priv->crefs);

  /* Get exclusive access to the driver data structure */

  ret = cc3000_devtake(priv);
  if (ret < 0)
    {
      return -EINTR;
    }

  /* Decrement the reference count unless it would decrement a negative
   * value.  When the count decrements to zero, there are no further
   * open references to the driver.
   */

  int tmp = priv->crefs;
  if (priv->crefs >= 1)
    {
      priv->crefs--;
    }

  if (tmp == 1)
    {
      pthread_t id = priv->selecttid;
      priv->selecttid = -1;
      pthread_cancel(id);
      pthread_join(id, NULL);
      sem_destroy(&priv->selectsem);

      priv->config->irq_enable(priv->config, false);
      priv->config->irq_clear(priv->config);
      priv->config->power_enable(priv->config, false);

      id = priv->workertid;
      priv->workertid = -1;
      pthread_cancel(id);
      pthread_join(id, NULL);

      mq_close(priv->queue);
      priv->queue = 0;

      kmm_free(priv->rx_buffer.pbuffer);
      priv->rx_buffer.pbuffer = 0;

#ifdef CONFIG_CC3000_MT
      sem_destroy(&priv->accepting_socket.acc.semwait);

      for (s = 0; s < CONFIG_WL_MAX_SOCKETS; s++)
        {
          priv->sockets[s].sd = FREE_SLOT;
          sem_destroy(&priv->sockets[s].semwait);
        }
#endif

      sem_destroy(&priv->waitsem);
      sem_destroy(&priv->irqsem);
      sem_destroy(&priv->readysem);
    }

  cc3000_devgive(priv);
  return OK;
}

/****************************************************************************
 * Name: cc3000_read
 ****************************************************************************/

static ssize_t cc3000_read(FAR struct file *filep, FAR char *buffer, size_t len)
{
  FAR struct inode *inode;
  FAR struct cc3000_dev_s *priv;
  int ret;
  ssize_t nread;

  nllvdbg("buffer:%p len:%d\n", buffer, len);
  DEBUGASSERT(filep);
  inode = filep->f_inode;

  DEBUGASSERT(inode && inode->i_private);
  priv  = (FAR struct cc3000_dev_s *)inode->i_private;

  CHECK_GUARD(priv);

  /* Get exclusive access to the driver data structure */

  ret = cc3000_devtake(priv);

  if (ret < 0)
    {
      nread = -errno;
      goto errout_without_sem;
    }

  /* Verify that the caller has provided a buffer large enough to receive
   * the maximum data.
   */

  if (len < priv->rx_buffer_max_len)
    {
      ndbg("Unsupported read size: %d\n", len);
      nread = -ENOSYS;
      goto errout_with_sem;
    }

  for (nread = priv->rx_buffer.len; nread == 0; nread = priv->rx_buffer.len)
    {
      if (nread > 0)
        {
          /* Yes.. break out to return what we have. */

          break;
        }

      /* data is not available now.  We would have to wait to get
       * receive sample data.  If the user has specified the O_NONBLOCK
       * option, then just return an error.
       */

      nllvdbg("CC3000 data is not available\n");
      if (filep->f_oflags & O_NONBLOCK)
        {
          nread = -EAGAIN;
          break;
        }

      /* Otherwise, wait for something to be written to the
       * buffer. Increment the number of waiters so that the notify
       * will know that it needs to post the semaphore to wake us up.
       */

      sched_lock();
      priv->nwaiters++;
      cc3000_devgive(priv);

      /* We may now be pre-empted!  But that should be okay because we
       * have already incremented nwaiters.  Pre-emptions is disabled
       * but will be re-enabled while we are waiting.
       */

      nllvdbg("Waiting..\n");
      ret = sem_wait(&priv->waitsem);
      priv->nwaiters--;
      sched_unlock();

      /* Did we successfully get the waitsem? */

      if (ret >= 0)
        {
          /* Yes... then retake the mutual exclusion semaphore */

          ret = cc3000_devtake(priv);
        }

      /* Was the semaphore wait successful? Did we successful re-take the
       * mutual exclusion semaphore?
       */

      if (ret < 0)
        {
          /* No.. One of the two sem_wait's failed. */

          int errval = errno;

          /* Were we awakened by a signal?  Did we read anything before
           * we received the signal?
           */

          if (errval != EINTR || nread  >= 0)
            {
              /* Yes.. return the error. */

              nread = -errval;
            }

          /* Break out to return what we have.  Note, we can't exactly
           * "break" out because whichever error occurred, we do not hold
           * the exclusion semaphore.
           */

          goto errout_without_sem;
        }
    }

  if (nread > 0)
    {
      memcpy(buffer,priv->rx_buffer.pbuffer,priv->rx_buffer.len);
      priv->rx_buffer.len = 0;
     }

errout_with_sem:
  cc3000_devgive(priv);

errout_without_sem:
  nllvdbg("Returning: %d\n", nread);
#ifndef CONFIG_DISABLE_POLL
  if (nread > 0)
    {
      cc3000_pollnotify(priv, POLLOUT);
    }
#endif

  return nread;
}

/****************************************************************************
 * Name:cc3000_write
 *
 * Bit of non standard buffer management ahead
 * The buffer is memory allocated in the user space with space for the spi
 * header
 *
 ****************************************************************************/

static ssize_t cc3000_write(FAR struct file *filep, FAR const char *usrbuffer, size_t len)
{
  FAR struct inode *inode;
  FAR struct cc3000_dev_s *priv;
  FAR char *buffer = (FAR char *) usrbuffer;
  ssize_t nwritten = 0;
  int ret;

  /* Set the padding if count(buffer) is even ( as it will be come odd with header) */

  size_t tx_len = (len & 1) ? len : len +1;

  nllvdbg("buffer:%p len:%d tx_len:%d\n", buffer, len, tx_len );

  DEBUGASSERT(filep);
  inode = filep->f_inode;

  DEBUGASSERT(inode && inode->i_private);
  priv  = (FAR struct cc3000_dev_s *)inode->i_private;

  CHECK_GUARD(priv);

  /* Get exclusive access to the driver data structure */

  ret = cc3000_devtake(priv);
  if (ret < 0)
    {
      /* This should only happen if the wait was canceled by an signal */

      ndbg("sem_wait: %d\n", errno);
      nwritten = -errno;
      goto errout_without_sem;
    }

  /* Figure out the total length of the packet in order to figure out if there is padding or not */

  buffer[0] = WRITE;
  buffer[1] = HI(tx_len);
  buffer[2] = LO(tx_len);
  buffer[3] = 0;
  buffer[4] = 0;
  tx_len += SPI_HEADER_SIZE;

  /* The first write transaction to occur after release of the shutdown has
   * slightly different timing than the others.  The normal Master SPI
   * write sequence is nCS low, followed by IRQ low (CC3000 host),
   * indicating that the CC3000 core device is ready to accept data.
   * However, after power up the sequence is slightly different, as shown
   * in the following Figure:
   *
   *   http://processors.wiki.ti.com/index.php/File:CC3000_Master_SPI_Write_Sequence_After_Power_Up.png
   *
   * The following is a sequence of operations:
   *  - The master detects the IRQ line low: in this case the detection of
   *    IRQ low does not indicate the intention of the CC3000 device to
   *    communicate with the master but rather CC3000 readiness after power
   *    up.
   *  - The master asserts nCS.
   *  - The master introduces a delay of at least 50 μs before starting
   *    actual transmission of data.
   *  - The master transmits the first 4 bytes of the SPI header.
   *  - The master introduces a delay of at least an additional 50 μs.
   *  - The master transmits the rest of the packet.
   */

  if (priv->state == eSPI_STATE_POWERUP)
    {
      ret = cc3000_wait_ready(priv);
      if (ret < 0)
        {
          nwritten = ret;
          goto errout_without_sem;
        }
    }

  if (priv->state  == eSPI_STATE_INITIALIZED)
    {
      cc3000_lock_and_select(priv->spi); /* Assert CS */
      usleep(55);
      SPI_SNDBLOCK(priv->spi, buffer, 4);
      usleep(55);
      SPI_SNDBLOCK(priv->spi, buffer+4, tx_len-4);
    }
  else
    {
      nllvdbg("Assert CS\n");
      priv->state  = eSPI_STATE_WRITE_WAIT_IRQ;
      cc3000_lock_and_select(priv->spi); /* Assert CS */
      nllvdbg("Wait on IRQ Active\n");
      ret = cc3000_wait_ready(priv);
      nllvdbg("IRQ Signaled\n");
      if (ret < 0)
        {
          /* This should only happen if the wait was canceled by an signal */

          cc3000_deselect_and_unlock(priv->spi);
          nllvdbg("sem_wait: %d\n", errno);
          DEBUGASSERT(errno == EINTR);
          nwritten = ret;
          goto errout_without_sem;
        }

      SPI_SNDBLOCK(priv->spi, buffer, tx_len);
    }

  priv->state  = eSPI_STATE_WRITE_DONE;
  nllvdbg("Deassert CS S:eSPI_STATE_WRITE_DONE\n");
  cc3000_deselect_and_unlock(priv->spi);
  nwritten = tx_len;
  cc3000_devgive(priv);

errout_without_sem:
  nllvdbg("Returning: %d\n", ret);
  return nwritten;
}

/****************************************************************************
 * Name:cc3000_ioctl
 ****************************************************************************/

static int cc3000_ioctl(FAR struct file *filep, int cmd, unsigned long arg)
{
  FAR struct inode *inode;
  FAR struct cc3000_dev_s *priv;
  int ret;

  nllvdbg("cmd: %d arg: %ld\n", cmd, arg);
  DEBUGASSERT(filep);
  inode = filep->f_inode;

  DEBUGASSERT(inode && inode->i_private);
  priv = (FAR struct cc3000_dev_s *)inode->i_private;

  CHECK_GUARD(priv);

  /* Get exclusive access to the driver data structure */

  ret = cc3000_devtake(priv);
  if (ret < 0)
    {
      /* This should only happen if the wait was canceled by an signal */

      return -errno;
    }

  /* Process the IOCTL by command */

  ret = OK;
  switch (cmd)
    {
      case CC3000IOC_GETQUESEMID:
        {
          FAR int *pminor = (FAR int *)(arg);
          DEBUGASSERT(pminor != NULL);
          *pminor = priv->minor;
          break;
        }

      case CC3000IOC_ADDSOCKET:
        {
          FAR int *pfd = (FAR int *)(arg);
          DEBUGASSERT(pfd != NULL);
          *pfd = cc3000_add_socket(priv, *pfd);
          break;
        }

      case CC3000IOC_REMOVESOCKET:
        {
          FAR int *pfd = (FAR int *)(arg);
          DEBUGASSERT(pfd != NULL);
          *pfd = cc3000_remove_socket(priv, *pfd);
          break;
        }

      case CC3000IOC_REMOTECLOSEDSOCKET:
        {
          FAR int *pfd = (FAR int *)(arg);
          DEBUGASSERT(pfd != NULL);
          *pfd = cc3000_remote_closed_socket(priv, *pfd);
          break;
        }

      case CC3000IOC_SELECTDATA:
        {
          FAR int *pfd = (FAR int *)(arg);
          DEBUGASSERT(pfd != NULL);
          *pfd = cc3000_wait_data(priv, *pfd);
          break;
        }

      case CC3000IOC_SELECTACCEPT:
        {
          FAR cc3000_acceptcfg *pcfg = (FAR cc3000_acceptcfg *)(arg);
          DEBUGASSERT(pcfg != NULL);
          pcfg->sockfd = cc3000_accept_socket(priv, pcfg->sockfd, pcfg->addr, pcfg->addrlen);
          break;
        }

      case CC3000IOC_SETRX_SIZE:
        {
          irqstate_t flags;
          FAR int *psize = (FAR int *)(arg);
          int rv;

          DEBUGASSERT(psize != NULL);
          rv = priv->rx_buffer_max_len;
          flags = irqsave();
          priv->rx_buffer_max_len = *psize;
          priv->rx_buffer.pbuffer = kmm_realloc(priv->rx_buffer.pbuffer,*psize);
          irqrestore(flags);
          DEBUGASSERT(priv->rx_buffer.pbuffer);
          *psize = rv;
          break;
        }

      default:
        ret = -ENOTTY;
        break;
    }

  cc3000_devgive(priv);
  return ret;
}

/****************************************************************************
 * Name: cc3000_poll
 ****************************************************************************/

#ifndef CONFIG_DISABLE_POLL
static int cc3000_poll(FAR struct file *filep, FAR struct pollfd *fds,
                        bool setup)
{
  FAR struct inode *inode;
  FAR struct cc3000_dev_s *priv;
  int ret;
  int i;

  nllvdbg("setup: %d\n", (int)setup);
  DEBUGASSERT(filep && fds);
  inode = filep->f_inode;

  DEBUGASSERT(inode && inode->i_private);
  priv  = (FAR struct cc3000_dev_s *)inode->i_private;

  CHECK_GUARD(priv);

  /* Are we setting up the poll?  Or tearing it down? */

  ret = cc3000_devtake(priv);
  if (ret < 0)
    {
      /* This should only happen if the wait was canceled by an signal */

      return -errno;
    }

  if (setup)
    {
      /* Ignore waits that do not include POLLIN */

      if ((fds->events & POLLIN) == 0)
        {
          ret = -EDEADLK;
          goto errout;
        }

      /* This is a request to set up the poll.  Find an available
       * slot for the poll structure reference
       */

      for (i = 0; i < CONFIG_CC3000_NPOLLWAITERS; i++)
        {
          /* Find an available slot */

          if (!priv->fds[i])
            {
              /* Bind the poll structure and this slot */

              priv->fds[i] = fds;
              fds->priv    = &priv->fds[i];
              break;
            }
        }

      if (i >= CONFIG_CC3000_NPOLLWAITERS)
        {
          fds->priv    = NULL;
          ret          = -EBUSY;
          goto errout;
        }

      /* Should we immediately notify on any of the requested events? */

      if (priv->rx_buffer.len)
        {
          cc3000_notify(priv);
        }
    }
  else if (fds->priv)
    {
      /* This is a request to tear down the poll. */

      struct pollfd **slot = (struct pollfd **)fds->priv;
      DEBUGASSERT(slot != NULL);

      /* Remove all memory of the poll setup */

      *slot                = NULL;
      fds->priv            = NULL;
    }

errout:
  cc3000_devgive(priv);
  return ret;
}
#endif

/****************************************************************************
 * Public Functions
 ****************************************************************************/

/****************************************************************************
 * Name: cc3000_register
 *
 * Description:
 *   Configure the CC3000 to use the provided SPI device instance.  This
 *   will register the driver as /dev/inputN where N is the minor device
 *   number
 *
 * Input Parameters:
 *   dev     - An SPI driver instance
 *   config  - Persistent board configuration data
 *   minor   - The input device minor number
 *
 * Returned Value:
 *   Zero is returned on success.  Otherwise, a negated errno value is
 *   returned to indicate the nature of the failure.
 *
 ****************************************************************************/

int cc3000_register(FAR struct spi_dev_s *spi,
                      FAR struct cc3000_config_s *config, int minor)
{
  FAR struct cc3000_dev_s *priv;
  char drvname[DEV_NAMELEN];
  char semname[SEM_NAMELEN];
#ifdef CONFIG_CC3000_MULTIPLE
  irqstate_t flags;
#endif
  int ret;

  nllvdbg("spi: %p minor: %d\n", spi, minor);

  /* Debug-only sanity checks */

  DEBUGASSERT(spi != NULL && config != NULL && minor >= 0 && minor < 100);

  /* Create and initialize a CC3000 device driver instance */

#ifndef CONFIG_CC3000_MULTIPLE
  priv = &g_cc3000;
#else
  priv = (FAR struct cc3000_dev_s *)kmm_malloc(sizeof(struct cc3000_dev_s));
  if (!priv)
    {
      ndbg("kmm_malloc(%d) failed\n", sizeof(struct cc3000_dev_s));
      return -ENOMEM;
    }
#endif

  /* Initialize the CC3000 device driver instance */

  memset(priv, 0, sizeof(struct cc3000_dev_s));
  INIT_GUARD(priv);
  priv->minor  = minor;              /* Save the minor number */
  priv->spi    = spi;                /* Save the SPI device handle */
  priv->config = config;             /* Save the board configuration */

  priv->rx_buffer_max_len = config->max_rx_size;

  sem_init(&priv->devsem,  0, 1);    /* Initialize device structure semaphore */

  (void)snprintf(semname, SEM_NAMELEN, SEM_FORMAT, minor);
  priv->wrkwaitsem = sem_open(semname,O_CREAT,0,0); /* Initialize  Worker Wait semaphore */

#ifdef CONFIG_CC3000_MT
  pthread_mutex_init(&g_cc3000_mut, NULL);
#endif

  /* Make sure that interrupts are disabled */

  config->irq_clear(config);
  config->irq_enable(config, false);

  /* Attach the interrupt handler */

  ret = config->irq_attach(config, cc3000_interrupt);
  if (ret < 0)
    {
      ndbg("Failed to attach interrupt\n");
      goto errout_with_priv;
    }

  /* Register the device as an input device */

  (void)snprintf(drvname, DEV_NAMELEN, DEV_FORMAT, minor);
  nllvdbg("Registering %s\n", drvname);

  ret = register_driver(drvname, &cc3000_fops, 0666, priv);
  if (ret < 0)
    {
      ndbg("register_driver() failed: %d\n", ret);
      goto errout_with_priv;
    }

  /* If multiple CC3000 devices are supported, then we will need to add
   * this new instance to a list of device instances so that it can be
   * found by the interrupt handler based on the recieved IRQ number.
   */

#ifdef CONFIG_CC3000_MULTIPLE
  priv->flink    = g_cc3000list;
  g_cc3000list = priv;
  irqrestore(flags);
#endif

  /* And return success (?) */

  return OK;

errout_with_priv:
  sem_destroy(&priv->devsem);
  sem_close(priv->wrkwaitsem);
  sem_unlink(semname);

#ifdef CONFIG_CC3000_MT
  pthread_mutex_destroy(&g_cc3000_mut);
#endif

#ifdef CONFIG_CC3000_MULTIPLE
  kmm_free(priv);
#endif
  return ret;
}

/****************************************************************************
 * Name: cc3000_wait_data
 *
 * Description:
 *   Adds this socket for monitoring for the data available
 *
 * Input Parameters:
 *   priv   - The device cc3000_dev_s instance
 *   sockfd   cc3000 socket handle
 *
 * Returned Value:
 *   Zero is returned on success.  Otherwise, a -1 value is
 *   returned to indicate socket not found or shut down occured.
 *
 ****************************************************************************/

static int cc3000_wait_data(FAR struct cc3000_dev_s *priv, int sockfd)
{
  int s;

  for (s = 0; s < CONFIG_WL_MAX_SOCKETS; s++)
    {
      if (priv->sockets[s].sd == sockfd)
        {
          sched_lock();
          cc3000_devgive(priv);
          sem_post(&priv->selectsem);           /* Wake select thread if need be */
          sem_wait(&priv->sockets[s].semwait);  /* Wait caller on select to finish */
          sem_wait(&priv->selectsem);           /* Sleep select thread */
          cc3000_devtake(priv);
          sched_unlock();

          if (!priv->sockets[s].sd == sockfd)
            {
              return -1;
            }

          if (priv->sockets[s].emptied_and_remotely_closed)
            {
              return -ECONNABORTED;
            }

          return OK;
        }
    }

  return (s >= CONFIG_WL_MAX_SOCKETS || priv->selecttid == -1) ? -1 : OK;
}

/****************************************************************************
 * Name: cc3000_accept_socket
 *
 * Description:
 *   Adds this socket for monitoring for the accept operation
 *
 * Input Parameters:
 *   priv   - The device cc3000_dev_s instance
 *   sockfd - cc3000 socket handle to monitor
 *
 * Returned Value:
 *   Zero is returned on success.  Otherwise, a negative value is
 *   returned to indicate an error.
 *
 ****************************************************************************/

static int cc3000_accept_socket(FAR struct cc3000_dev_s *priv, int sd, struct sockaddr *addr,
                         socklen_t *addrlen)
{

  priv->accepting_socket.acc.status = CC3000_SOC_ERROR;
  priv->accepting_socket.acc.sd = sd;

  sched_lock();
  cc3000_devgive(priv);
  sem_post(&priv->selectsem);                    /* Wake select thread if need be */
  sem_wait(&priv->accepting_socket.acc.semwait); /* Wait caller on select to finish */
  sem_wait(&priv->selectsem);                    /* Sleep the Thread */
  cc3000_devtake(priv);
  sched_unlock();

  if (priv->accepting_socket.acc.status != CC3000_SOC_ERROR)
    {
      *addr = priv->accepting_socket.addr;
      *addrlen = priv->accepting_socket.addrlen;
      cc3000_add_socket(priv, priv->accepting_socket.acc.status);
    }

  return priv->accepting_socket.acc.status;
}

/****************************************************************************
 * Name: cc3000_add_socket
 *
 * Description:
 *   Adds a socket to the list for monitoring for long operation
 *
 * Input Parameters:
 *   sd      cc3000 socket handle
 *   minor   - The input device minor number
 *
 * Returned Value:
 *   Zero is returned on success.  Otherwise, a -1 value is
 *   returned to indicate socket not found.
 *
 ****************************************************************************/

static int cc3000_add_socket(FAR struct cc3000_dev_s *priv, int sd)
{
  irqstate_t flags;
  int s;

  if (sd < 0)
    {
      return sd;
    }

  flags = irqsave();
  for (s = 0; s < CONFIG_WL_MAX_SOCKETS; s++)
    {
      if (priv->sockets[s].sd == FREE_SLOT)
        {
          priv->sockets[s].received_closed_event = false;
          priv->sockets[s].emptied_and_remotely_closed = false;
          priv->sockets[s].sd = sd;
          break;
        }
    }

  irqrestore(flags);
  return s >= CONFIG_WL_MAX_SOCKETS ? -1 : OK;
}

/****************************************************************************
 * Name: cc3000_remove_socket
 *
 * Description:
 *   Removes a socket from the list of monitoring for long operation
 *
 * Input Parameters:
 *   sd      cc3000 socket handle
 *   minor   - The input device minor number
 *
 * Returned Value:
 *   Zero is returned on success.  Otherwise, a -1 value is
 *   returned to indicate socket not found.
 *
 ****************************************************************************/

static int cc3000_remove_socket(FAR struct cc3000_dev_s *priv, int sd)
{
  irqstate_t flags;
  int s;
  sem_t *ps = 0;

  if (sd < 0)
    {
      return sd;
    }

  flags = irqsave();
  if (priv->accepting_socket.acc.sd == sd)
    {
      priv->accepting_socket.acc.sd = CLOSE_SLOT;
      ps = &priv->accepting_socket.acc.semwait;
    }

  for (s = 0; s < CONFIG_WL_MAX_SOCKETS; s++)
    {
      if (priv->sockets[s].sd == sd)
        {
          priv->sockets[s].received_closed_event = false;
          priv->sockets[s].emptied_and_remotely_closed = false;
          priv->sockets[s].sd = CLOSE_SLOT;
          ps = &priv->sockets[s].semwait;
          break;
        }
    }

  irqrestore(flags);
  if (ps)
    {
      sched_lock();
      cc3000_devgive(priv);
      sem_post(&priv->selectsem);                    /* Wake select thread if need be */
      sem_wait(ps);
      sem_wait(&priv->selectsem);                    /* Sleep the Thread */
      cc3000_devtake(priv);
      sched_unlock();
    }

  return s >= CONFIG_WL_MAX_SOCKETS ? -1 : OK;
}

/****************************************************************************
 * Name: cc3000_remote_closed_socket
 *
 * Description:
 *   Mark socket as closed by remote host
 *
 * Input Parameters:
 *   sd      cc3000 socket handle
 *
 * Returned Value:
 *   Zero is returned on success.  Otherwise, a -1 value is
 *   returned to indicate socket not found.
 *
 ****************************************************************************/

static int cc3000_remote_closed_socket(FAR struct cc3000_dev_s *priv, int sd)
{
  irqstate_t flags;
  int s;

  if (sd < 0)
    {
      return sd;
    }

  flags = irqsave();
  for (s = 0; s < CONFIG_WL_MAX_SOCKETS; s++)
    {
      if (priv->sockets[s].sd == sd)
        {
          priv->sockets[s].received_closed_event = true;
        }
    }

  irqrestore(flags);

  return s >= CONFIG_WL_MAX_SOCKETS ? -1 : OK;
}

redpajama_set_name: RedPajamaGithub


text:
import Control.Monad
import Data.List
import Data.Ord
import Results
import System.Environment
import Text.Printf

main :: IO ()
main = do
  args <- getArgs
  forM_ args $ \file -> do
    printf "%-10s %10s %10s\n" ("Division" :: String) ("Mean" :: String) ("Std Dev" :: String)
    printf "%-10s %10s %10s\n" ("--------" :: String) ("----" :: String) ("-------" :: String)
    rs <- results file
    forM_ (sortBy (comparing rAverage) rs) $ \r ->
      printf "%-10s %10.2f %10.2f\n" (rDivision r) (rAverage r) (rStdDev r)


text:
from ..instruction import Instruction

class Sbc(Instruction):
    def execute(self, processor):
        acc = processor.a.value
        mem = self.read_source(processor)

        value = acc - mem
        if processor.p.c:
            value -= 1

        processor.p.n.update(value)
        processor.p.z.update(value)
        processor.p.v.update((acc ^ mem) & 0x80 and (acc ^ value) & 0x80)

        processor.p.c.update(value < 0x100)
        processor.a.value = value & 0xff


text:
module Brcobranca
  module Remessa
    module Cnab400
      class Base < Brcobranca::Remessa::Base
        # documento do cedente
        attr_accessor :documento_cedente

        validates_presence_of :carteira, message: 'não pode estar em branco.'

        # Data da geracao do arquivo seguindo o padrao DDMMAA
        #
        # @return [String]
        #
        def data_geracao
          Date.current.strftime('%d%m%y')
        end

        # Header do arquivo remessa
        #
        # @return [String]
        #
        def monta_header
          # CAMPO                 TAMANHO    VALOR
          # tipo do registro      [1]        0
          # operacao              [1]        1
          # literal remessa       [7]        REMESSA
          # Código do serviço     [2]        01
          # cod. servico          [15]       COBRANCA
          # info. conta           [20]
          # empresa mae           [30]
          # cod. banco            [3]
          # nome banco            [15]
          # data geracao          [6]        formato DDMMAA
          # complemento registro  [294]
          # num. sequencial       [6]        000001
          "01REMESSA01COBRANCA       #{info_conta}#{empresa_mae.format_size(30)}#{cod_banco}#{nome_banco}#{data_geracao}#{complemento}000001"
        end

        # Trailer do arquivo remessa
        #
        # @param sequencial
        #   num. sequencial do registro no arquivo
        #
        # @return [String]
        #
        def monta_trailer(sequencial)
          # CAMPO                   TAMANHO  VALOR
          # identificacao registro  [1]      9
          # complemento             [393]
          # num. sequencial         [6]
          "9#{''.rjust(393, ' ')}#{sequencial.to_s.rjust(6, '0')}"
        end

        # Registro detalhe do arquivo remessa
        #
        # Este metodo deve ser sobrescrevido na classe do banco
        #
        def monta_detalhe(_pagamento, _sequencial)
          raise Brcobranca::NaoImplementado, 'Sobreescreva este método na classe referente ao banco que você esta criando'
        end

        # Gera o arquivo com os registros
        #
        # @return [String]
        def gera_arquivo
          raise Brcobranca::RemessaInvalida, self unless valid?

          # contador de registros no arquivo
          contador = 1
          ret = [monta_header]
          pagamentos.each do |pagamento|
            contador += 1
            ret << monta_detalhe(pagamento, contador)
          end
          ret << monta_trailer(contador + 1)

          remittance = ret.join("\n").to_ascii.upcase
          remittance << "\n"

          remittance.encode(remittance.encoding, universal_newline: true).encode(remittance.encoding, crlf_newline: true)
        end

        # Informacoes referentes a conta do cedente
        #
        # Este metodo deve ser sobrescrevido na classe do banco
        #
        def info_conta
          raise Brcobranca::NaoImplementado, 'Sobreescreva este método na classe referente ao banco que você esta criando'
        end

        # Numero do banco na camara de compensacao
        #
        # Este metodo deve ser sobrescrevido na classe do banco
        #
        def cod_banco
          raise Brcobranca::NaoImplementado, 'Sobreescreva este método na classe referente ao banco que você esta criando'
        end

        # Nome por extenso do banco cobrador
        #
        # Este metodo deve ser sobrescrevido na classe do banco
        #
        def nome_banco
          raise Brcobranca::NaoImplementado, 'Sobreescreva este método na classe referente ao banco que você esta criando'
        end

        # Complemento do registro header
        #
        # Este metodo deve ser sobrescrevido na classe do banco
        #
        def complemento
          raise Brcobranca::NaoImplementado, 'Sobreescreva este método na classe referente ao banco que você esta criando'
        end
      end
    end
  end
end


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>exceptions.Exception</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css"></link>

       Home
       Trees
       Index
       Help

        Module exceptions ::
        Class Exception

[show private | hide private]

[frames | no frames]

Class Exception

Known Subclasses:

    Error,
    Error,
    Error,
    Error,
    RepositoryError,
    Error,
    Error

Common base class for all exceptions.

  Method Summary

  __init__(...)

  __getitem__(...)

  __str__(...)

       Home
       Trees
       Index
       Help

    Generated by Epydoc 2.0 on Sun Sep 25 20:49:07 2005
    http://epydoc.sf.net


text:
class Types::NotificationTemplateType < Types::BaseObject
  authorize_record

  field :id, ID, null: false
  field :event_key, String, null: false
  field :subject, String, null: true
  field :body_html, String, null: true
  field :body_text, String, null: true
  field :body_sms, String, null: true
end


text:
import { Component, Vue, Prop, p } from 'av-ts'
import IButton                     from 'iview/src/components/button'
import WtModal                     from '../../../components/wt-modal'
import WtPanel                     from '../../../components/wt-panel'

@Component({
  name      : 'reorder-all-confirm',
  components: {
    IButton,
    WtModal,
    WtPanel,
  },
})
export default class ReorderAllConfirm extends Vue {
  @Prop isShowing = p({ type: Boolean, default: false })
  @Prop total     = p({ type: Number, required: true })

  confirm() {
    this.$emit('confirm')
  }

  cancel() {
    this.$emit('cancel')
  }

  oneByOne() {
    this.$emit('oneByOne')
  }
}


text:
package com.blackducksoftware.integration.hub.detect.workflow.bdio;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

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

import com.blackducksoftware.integration.hub.detect.exception.DetectUserFriendlyException;
import com.blackducksoftware.integration.hub.detect.workflow.codelocation.BdioCodeLocation;
import com.synopsys.integration.bdio.SimpleBdioFactory;
import com.synopsys.integration.bdio.graph.DependencyGraph;
import com.synopsys.integration.bdio.model.SimpleBdioDocument;
import com.synopsys.integration.bdio.model.externalid.ExternalId;
import com.synopsys.integration.blackduck.codelocation.bdioupload.UploadTarget;
import com.synopsys.integration.util.NameVersion;

public class CodeLocationBdioCreator {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private final DetectBdioWriter detectBdioWriter;
    private SimpleBdioFactory simpleBdioFactory;

    public CodeLocationBdioCreator(final DetectBdioWriter detectBdioWriter, final SimpleBdioFactory simpleBdioFactory) {
        this.detectBdioWriter = detectBdioWriter;
        this.simpleBdioFactory = simpleBdioFactory;
    }

    public List<UploadTarget> createBdioFiles(File bdioOutput, final List<BdioCodeLocation> bdioCodeLocations, NameVersion projectNameVersion) throws DetectUserFriendlyException {
        final List<UploadTarget> uploadTargets = new ArrayList<>();
        for (final BdioCodeLocation bdioCodeLocation : bdioCodeLocations) {
            String codeLocationName = bdioCodeLocation.codeLocationName;
            ExternalId externalId = bdioCodeLocation.codeLocation.getExternalId();
            DependencyGraph dependencyGraph = bdioCodeLocation.codeLocation.getDependencyGraph();

            final SimpleBdioDocument simpleBdioDocument = simpleBdioFactory.createSimpleBdioDocument(codeLocationName, projectNameVersion.getName(), projectNameVersion.getVersion(), externalId, dependencyGraph);

            final File outputFile = new File(bdioOutput, bdioCodeLocation.bdioName);
            detectBdioWriter.writeBdioFile(outputFile, simpleBdioDocument);
            uploadTargets.add(UploadTarget.createDefault(codeLocationName, outputFile));
        }

        return uploadTargets;
    }
}


text:
package com.gs.collections.impl.block.procedure.primitive;

import com.gs.collections.api.block.function.primitive.ByteFunction;
import com.gs.collections.api.block.procedure.Procedure;
import com.gs.collections.api.collection.primitive.MutableByteCollection;

/**
 * Applies a byteFunction to an object and adds the result to a target byte collection.
 */
public final class CollectByteProcedure<T> implements Procedure<T>
{
    private static final long serialVersionUID = 1L;

    private final ByteFunction<? super T> byteFunction;
    private final MutableByteCollection byteCollection;

    public CollectByteProcedure(ByteFunction<? super T> byteFunction, MutableByteCollection targetCollection)
    {
        this.byteFunction = byteFunction;
        this.byteCollection = targetCollection;
    }

    public void value(T object)
    {
        byte value = this.byteFunction.byteValueOf(object);
        this.byteCollection.add(value);
    }

    public MutableByteCollection getByteCollection()
    {
        return this.byteCollection;
    }
}


text:
int init_global_hooks();

int deinit_global_hooks();

int cleanup_sdif();


text:
package io.neft.nimage;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.util.Base64;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.request.RequestOptions;

import io.neft.App;

public class NImage {
    private static App APP = App.getInstance();
    private static RequestOptions OPTIONS = new RequestOptions()
            .format(DecodeFormat.PREFER_ARGB_8888);

    private static RequestBuilder<Bitmap> buildBitmapRequest() {
        return Glide.with(APP.getActivity())
                .applyDefaultRequestOptions(OPTIONS)
                .asBitmap();
    }

    private static RequestBuilder<Drawable> buildDrawableRequest() {
        return Glide.with(APP.getActivity())
                .applyDefaultRequestOptions(OPTIONS)
                .asDrawable();
    }

    private static <T> RequestBuilder<T> request(RequestBuilder<T> request, String resource) {
        if (resource.startsWith("/static")) {
            return request.load(Uri.parse("file:///android_asset" + resource));
        }

        if (resource.startsWith("data:")) {
            String base64 = resource.substring(resource.indexOf(","));
            byte[] imageAsBytes = Base64.decode(base64.getBytes(), 0);
            return request.load(imageAsBytes);
        }

        return request.load(resource);
    }

    private static <T> boolean prepareLoad(NImageHolder<T> holder, String resource) {
        if (resource == null || resource.isEmpty()) {
            clear(holder);
            return false;
        }
        return true;
    }

    public static void loadBitmap(NImageHolder<Bitmap> holder, String resource) {
        if (!prepareLoad(holder, resource)) return;
        request(buildBitmapRequest(), resource).into(holder);
    }

    public static void loadDrawable(NImageHolder<Drawable> holder, String resource) {
        if (!prepareLoad(holder, resource)) return;
        request(buildDrawableRequest(), resource).into(holder);
    }

    public static void clear(NImageHolder holder) {
        Activity activity = APP.getActivity();
        if (activity.isDestroyed()) return;
        Glide.with(activity).clear(holder);
    }
}


text:
package org.apache.solr.handler;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.util.EntityUtils;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CloudSolrClient;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.request.CollectionAdminRequest;
import org.apache.solr.client.solrj.response.CollectionAdminResponse;
import org.apache.solr.cloud.AbstractFullDistribZkTestBase;
import org.apache.solr.common.cloud.DocCollection;
import org.apache.solr.common.cloud.Replica;
import org.apache.solr.common.cloud.ZkStateReader;
import org.apache.solr.core.ConfigOverlay;
import org.apache.solr.update.DirectUpdateHandler2;
import org.apache.solr.util.SimplePostTool;
import org.noggit.JSONParser;
import org.noggit.ObjectBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.StringReader;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static org.apache.solr.core.ConfigOverlay.getObjectByPath;

public class TestBlobHandler extends AbstractFullDistribZkTestBase {
  static final Logger log =  LoggerFactory.getLogger(TestBlobHandler.class);

  private void doBlobHandlerTest() throws Exception {
    SolrClient client = createNewSolrClient("", getBaseUrl((HttpSolrClient) clients.get(0)));
    try {
      CollectionAdminResponse response1;
      CollectionAdminRequest.Create createCollectionRequest = new CollectionAdminRequest.Create();
      createCollectionRequest.setCollectionName(".system");
      createCollectionRequest.setNumShards(1);
      createCollectionRequest.setReplicationFactor(2);
      response1 = createCollectionRequest.process(client);
      assertEquals(0, response1.getStatus());
      assertTrue(response1.isSuccess());
      DocCollection sysColl = cloudClient.getZkStateReader().getClusterState().getCollection(".system");
      Replica replica = sysColl.getActiveSlicesMap().values().iterator().next().getLeader();

      String baseUrl = replica.getStr(ZkStateReader.BASE_URL_PROP);
      String url = baseUrl + "/.system/config/requestHandler";
      Map map = TestSolrConfigHandlerConcurrent.getAsMap(url, cloudClient);
      assertNotNull(map);
      assertEquals("solr.BlobHandler", getObjectByPath(map, true, Arrays.asList(
          "config",
          "requestHandler",
          "/blob",
          "class")));

      byte[] bytarr  = new byte[1024];
      for (int i = 0; i < bytarr.length; i++) bytarr[i]= (byte) (i % 127);
      byte[] bytarr2  = new byte[2048];
      for (int i = 0; i < bytarr2.length; i++) bytarr2[i]= (byte) (i % 127);
      postAndCheck(cloudClient, baseUrl, ByteBuffer.wrap( bytarr), 1);
      postAndCheck(cloudClient, baseUrl, ByteBuffer.wrap( bytarr2), 2);

      url = baseUrl + "/.system/blob/test/1";
      map = TestSolrConfigHandlerConcurrent.getAsMap(url,cloudClient);
      List l = (List) ConfigOverlay.getObjectByPath(map, false, Arrays.asList("response", "docs"));
      assertNotNull(""+map, l);
      assertTrue("" + map, l.size() > 0);
      map = (Map) l.get(0);
      assertEquals(""+bytarr.length,String.valueOf(map.get("size")));

      compareInputAndOutput(baseUrl+"/.system/blob/test?wt=filestream", bytarr2);
      compareInputAndOutput(baseUrl+"/.system/blob/test/1?wt=filestream", bytarr);
    } finally {
      client.shutdown();
    }
  }

  public static  void createSysColl(SolrClient client) throws SolrServerException, IOException {
    CollectionAdminResponse response1;
    CollectionAdminRequest.Create createCollectionRequest = new CollectionAdminRequest.Create();
    createCollectionRequest.setCollectionName(".system");
    createCollectionRequest.setNumShards(1);
    createCollectionRequest.setReplicationFactor(2);
    response1 = createCollectionRequest.process(client);
    assertEquals(0, response1.getStatus());
    assertTrue(response1.isSuccess());
  }

  @Override
  public void tearDown() throws Exception {
    super.tearDown();
    System.clearProperty("numShards");
    System.clearProperty("zkHost");

    // insurance
    DirectUpdateHandler2.commitOnClose = true;
  }

  public static void postAndCheck(CloudSolrClient cloudClient, String baseUrl, ByteBuffer bytes, int count) throws Exception {
    postData(cloudClient, baseUrl, bytes);

    String url;
    Map map = null;
    List l;
    long start = System.currentTimeMillis();
    int i=0;
    for(;i<150;i++) {//10secs
      url = baseUrl + "/.system/blob/test";
      map = TestSolrConfigHandlerConcurrent.getAsMap(url, cloudClient);
      String numFound = String.valueOf(ConfigOverlay.getObjectByPath(map, false, Arrays.asList("response", "numFound")));
      if(!(""+count).equals(numFound)) {
        Thread.sleep(100);
        continue;
      }
      l = (List) ConfigOverlay.getObjectByPath(map, false, Arrays.asList("response", "docs"));
      assertNotNull(l);
      map = (Map) l.get(0);
      assertEquals("" + bytes.limit(), String.valueOf(map.get("size")));
      return;
    }
    fail(MessageFormat.format("Could not successfully add blob after {0} attempts. Expecting {1} items. time elapsed {2}  output  for url is {3}",
        i,count, System.currentTimeMillis()-start,  getAsString(map)));
  }

  public static String getAsString(Map map) {
    return new String(ZkStateReader.toJSON(map), StandardCharsets.UTF_8);
  }

  private void compareInputAndOutput(String url, byte[] bytarr) throws IOException {

    HttpClient httpClient = cloudClient.getLbClient().getHttpClient();

    HttpGet httpGet = new HttpGet(url);
    HttpResponse entity = httpClient.execute(httpGet);
    ByteBuffer b = SimplePostTool.inputStreamToByteArray(entity.getEntity().getContent());
    try {
      assertEquals(b.limit(), bytarr.length);
      for (int i = 0; i < bytarr.length; i++) {
        assertEquals(b.get(i), bytarr[i]);
      }
    } finally {
      httpGet.releaseConnection();
    }

  }

  public static void postData(CloudSolrClient cloudClient, String baseUrl, ByteBuffer bytarr) throws IOException {
    HttpPost httpPost = null;
    HttpEntity entity;
    String response = null;
    try {
      httpPost = new HttpPost(baseUrl+"/.system/blob/test");
      httpPost.setHeader("Content-Type","application/octet-stream");
      httpPost.setEntity(new ByteArrayEntity(bytarr.array(), bytarr.arrayOffset(), bytarr.limit()));
      entity = cloudClient.getLbClient().getHttpClient().execute(httpPost).getEntity();
      try {
        response = EntityUtils.toString(entity, StandardCharsets.UTF_8);
        Map m = (Map) ObjectBuilder.getVal(new JSONParser(new StringReader(response)));
        assertFalse("Error in posting blob "+ getAsString(m),m.containsKey("error"));
      } catch (JSONParser.ParseException e) {
        log.error(response);
        fail();
      }
    } finally {
      httpPost.releaseConnection();
    }
  }

  @Override
  public void doTest() throws Exception {
    doBlobHandlerTest();

  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".MainActivity"
    android:orientation="vertical"
    tools:showIn="@layout/activity_main">

        <EditText
            android:id="@+id/url"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:inputType="textUri"
            android:text="http://chromplex.com/"
            android:padding="20dp"/>

        <Button
            android:id="@+id/start_custom_tab"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal|bottom"
            android:layout_marginTop="16dp"
            android:text="Open Custom Chrome" />

</LinearLayout>


text:
namespace Azure.ResourceManager.ProviderHub.Models
{
    /// <summary> The ResourceGraphConfiguration. </summary>
    public partial class ResourceGraphConfiguration
    {
        /// <summary> Initializes a new instance of ResourceGraphConfiguration. </summary>
        public ResourceGraphConfiguration()
        {
        }

        /// <summary> Initializes a new instance of ResourceGraphConfiguration. </summary>
        /// <param name="enabled"></param>
        /// <param name="apiVersion"></param>
        internal ResourceGraphConfiguration(bool? enabled, string apiVersion)
        {
            Enabled = enabled;
            ApiVersion = apiVersion;
        }

        /// <summary> Gets or sets the enabled. </summary>
        public bool? Enabled { get; set; }
        /// <summary> Gets or sets the api version. </summary>
        public string ApiVersion { get; set; }
    }
}


text:
<?php

namespace PhlySimplePageTest;

use PhlySimplePage\Module;
use PhlySimplePage\PageController;
use PHPUnit_Framework_TestCase as TestCase;
use stdClass;
use Zend\EventManager\EventManager;
use Zend\EventManager\SharedEventManager;
use Zend\EventManager\StaticEventManager;
use Zend\Mvc\Application;
use Zend\Mvc\MvcEvent;
use Zend\Mvc\Router\RouteMatch;

/**
 * Unit tests for PhlySimplePage\Module
 */
class ModuleTest extends TestCase
{
    public function setUp()
    {
        $this->events       = new EventManager();
        $this->sharedEvents = new SharedEventManager();
        $this->events->setSharedManager($this->sharedEvents);

        $this->application = new TestAsset\Application();
        $this->application->setEventManager($this->events);

        $this->matches = new RouteMatch(array(
            'controller' => 'PhlySimplePage\Controller\Page',
        ));

        $this->event = new MvcEvent();
        $this->event->setApplication($this->application);
        $this->event->setRouteMatch($this->matches);
        $this->event->setTarget($this->application);

        $this->module = new Module();
    }

    public function tearDown()
    {
        // Need to do this to ensure other tests in suite do not get state
        StaticEventManager::resetInstance();
    }

    protected function getEmptyMockForServiceManager()
    {
        $services = $this->getMock('Zend\ServiceManager\ServiceLocatorInterface');
        $services->expects($this->once())
            ->method('has')
            ->with($this->equalTo('PhlySimplePage\PageCache'))
            ->will($this->returnValue(false));
        return $services;
    }

    public function testBootstrapListenerRegistersRouteListener()
    {
        $this->application->services = $this->getEmptyMockForServiceManager();
        $this->module->onBootstrap($this->event);
        $listeners = $this->events->getListeners('route');
        $this->assertCount(1, $listeners);
        foreach ($listeners as $listener) {
        }
        $this->assertEquals(-100, $listener->getMetadatum('priority'));
        $callback = $listener->getCallback();
        $this->assertEquals(array($this->module, 'onRoutePost'), $callback);
    }

    public function testRouteListenerRegistersSharedListenerForPageControllerDispatchEvent()
    {
        $this->module->onRoutePost($this->event);
        $listeners = $this->sharedEvents->getListeners('PhlySimplePage\PageController', 'dispatch');
        $this->assertCount(1, $listeners);
        foreach ($listeners as $listener) {
        }
        $callback = $listener->getCallback();
        $this->assertEquals(-1, $listener->getMetadatum('priority'));
        $this->assertEquals(array($this->module, 'onDispatchPost'), $callback);
    }

    public function testRouteListenerDoesNotRegistersSharedDispatchEventListenerWhenNoRouteMatchesPresentInEvent()
    {
        $event = new MvcEvent();
        $event->setApplication($this->application);
        $event->setTarget($this->application);

        $this->module->onRoutePost($event);
        $listeners = $this->sharedEvents->getListeners('PhlySimplePage\PageController', 'dispatch');
        $this->assertFalse($listeners);
    }

    public function testRouteListenerDoesNotRegistersSharedDispatchEventListenerWhenRouteMatchControllerDoesNotMatch()
    {
        $matches = new RouteMatch(array(
            'controller' => 'Some\Controller\Other',
        ));

        $event = new MvcEvent();
        $event->setApplication($this->application);
        $event->setRouteMatch($matches);
        $event->setTarget($this->application);

        $this->module->onRoutePost($event);
        $listeners = $this->sharedEvents->getListeners('PhlySimplePage\PageController', 'dispatch');
        $this->assertFalse($listeners);
    }

    public function testOnDispatchPostTriggersDispatchErrorIfEventHasInvalidControllerErrorComposed()
    {
        $controller = new PageController();
        $this->event->setTarget($controller);
        $this->event->setError(Application::ERROR_CONTROLLER_INVALID);

        $test = new stdClass;
        $test->called = false;
        $this->events->attach('dispatch.error', function ($e) use ($test) {
            $test->called = true;
        });

        $this->module->onDispatchPost($this->event);
        $this->assertTrue($test->called);
    }

    public function testOnDispatchDoesNotTriggerDispatchErrorIfTargetIsNotPageController()
    {
        $this->event->setError(Application::ERROR_CONTROLLER_INVALID);

        $test = new stdClass;
        $test->called = false;
        $this->events->attach('dispatch.error', function ($e) use ($test) {
            $test->called = true;
        });

        $this->module->onDispatchPost($this->event);
        $this->assertFalse($test->called);
    }

    public function testOnDispatchPostDoesNotTriggerDispatchErrorIfEventDoesNotHaveInvalidControllerErrorComposed()
    {
        $controller = new PageController();
        $this->event->setTarget($controller);

        $test = new stdClass;
        $test->called = false;
        $this->events->attach('dispatch.error', function ($e) use ($test) {
            $test->called = true;
        });

        $this->module->onDispatchPost($this->event);
        $this->assertFalse($test->called);
    }
}


text:
#include <redshift/boot/pit.h>
#include <redshift/kernel/asm.h>
#include <redshift/kernel/interrupt.h>
#include <redshift/kernel/timer.h>
#include <redshift/sched/process.h>

static void pit_handler(const struct cpu_state* regs)
{
    process_timer_queue(1000 / TICK_RATE);
    UNUSED(regs);
}

int pit_init(uint32_t freq)
{
    SAVE_INTERRUPT_STATE;
    static int handler_registered = 0;
    if (!(handler_registered)) {
        set_interrupt_handler(IRQ0, &pit_handler);
        handler_registered = 1;
    }
    if (!(freq)) {
        return -1;
    }
    uint32_t div = 1193180 / freq;
    io_outb(PIT_CMND, 0x36);
    io_outb(PIT_DATA, ((uint8_t)(div & 0xff)));
    io_outb(PIT_DATA, ((uint8_t)((div >> 8) & 0xff)));
    RESTORE_INTERRUPT_STATE;
    return 0;
}