<commit_before>/*
Copyright (C) 2011-2012 Yubico AB.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

   1. Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.

   2. Redistributions in binary form must reproduce the above
      copyright notice, this list of conditions and the following
      disclaimer in the documentation and/or other materials provided
      with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "yubikeyfinder.h"

YubiKeyFinder* YubiKeyFinder::_instance = 0;

// first version is inclusive, second is exclusive
const unsigned int YubiKeyFinder::FEATURE_MATRIX[][2] = {
    { YK_VERSION(2,0,0), 0 },   //Feature_MultipleConfigurations
    { YK_VERSION(2,0,0), 0 },   //Feature_ProtectConfiguration2
    { YK_VERSION(1,3,0), 0 },   //Feature_StaticPassword
    { YK_VERSION(2,0,0), 0 },   //Feature_ScanCodeMode
    { YK_VERSION(2,0,0), 0 },   //Feature_ShortTicket
    { YK_VERSION(2,0,0), 0 },   //Feature_StrongPwd
    { YK_VERSION(2,1,0), 0 },   //Feature_OathHotp
    { YK_VERSION(2,2,0), 0 },   //Feature_ChallengeResponse
    { YK_VERSION(2,1,4), 0 },   //Feature_SerialNumber
    { YK_VERSION(2,1,7), 0 },   //Feature_MovingFactor
    { YK_VERSION(2,3,0), 0 },   //Feature_ChallengeResponseFixed
    { YK_VERSION(2,3,0), 0 },   //Feature_Updatable
    { YK_VERSION(2,1,4), 0 },   //Feature_Ndef
};

// when a featureset should be excluded from versions (NEO, I'm looking at you.)
const unsigned int YubiKeyFinder::FEATURE_MATRIX_EXCLUDE[][2] = {
    { YK_VERSION(2,1,4), YK_VERSION(2,2,0) }, //Feature_MultipleConfigurations
    { YK_VERSION(2,1,4), YK_VERSION(2,2,0) }, //Feature_ProtectConfiguration2
    { YK_VERSION(2,1,4), YK_VERSION(2,1,8) }, //Feature_StaticPassword
    { YK_VERSION(2,1,4), YK_VERSION(2,1,8) }, //Feature_ScanCodeMode
    { 0, 0 },                                 //Feature_ShortTicket
    { YK_VERSION(2,1,4), YK_VERSION(2,1,8) }, //Feature_StrongPwd
    { 0, 0 },                                 //Feature_OathHotp
    { 0, 0 },                                 //Feature_ChallengeResponse
    { 0, 0 },                                 //Feature_SerialNumber
    { 0, 0 },                                 //Feature_MovingFactor
    { 0, 0 },                                 //Feature_ChallengeResponseFixed
    { 0, 0 },                                 //Feature_Updatable
    { YK_VERSION(2,2,0), YK_VERSION(3,0,0) }, //Feature_Ndef
};

YubiKeyFinder::YubiKeyFinder() {
    // init the ykpers library
    yk_init();

    //Initialize fields
    init();

    //Create timer
    m_timer = new QTimer( this );
    connect(m_timer, SIGNAL(timeout()),
            this, SLOT(findKey()));
}

YubiKeyFinder::~YubiKeyFinder() {
    yk_release();

    if(m_timer != 0) {
        delete m_timer;
        m_timer = 0;
    }

    if(_instance) {
        delete _instance;
    }
}

YubiKeyFinder* YubiKeyFinder::getInstance() {
    if(_instance == NULL) {
        _instance = new YubiKeyFinder();
    }
    return _instance;
}

QString YubiKeyFinder::versionStr() {
    if(m_version > 0) {
        return tr("%1.%2.%3").
                arg(m_versionMajor).
                arg(m_versionMinor).
                arg(m_versionBuild);
    }
    return "";
}

void YubiKeyFinder::reportError() {
    if (ykp_errno) {
        //qDebug("Yubikey personalization error: %s\n", ykp_strerror(ykp_errno));
        ykp_errno = 0;
    } else if (yk_errno) {
        if (yk_errno == YK_EUSBERR) {
            //qDebug("USB error: %s\n", yk_usb_strerror());
        } else {
            //qDebug("Yubikey core error: %s\n", yk_strerror(yk_errno));
        }

        yk_errno = 0;
    }

    emit errorOccurred(ERR_KEY_NOT_FOUND);
}

bool YubiKeyFinder::checkFeatureSupport(Feature feature) {
    if(m_version > 0 &&
       (unsigned int) feature < sizeof(FEATURE_MATRIX)/sizeof(FEATURE_MATRIX[0])) {
        bool supported = (
                m_version >= FEATURE_MATRIX[feature][0] &&
                (FEATURE_MATRIX[feature][1] == 0 || m_version < FEATURE_MATRIX[feature][1])
                );
        if(supported)
            if(FEATURE_MATRIX_EXCLUDE[feature][0] != 0)
                if(m_version >= FEATURE_MATRIX_EXCLUDE[feature][0])
                    if(m_version < FEATURE_MATRIX_EXCLUDE[feature][1])
                        return false;
        return supported;
    }
    return false;
}

void YubiKeyFinder::init() {
    m_state = State_Absent;
    m_yk = 0;
    m_version = 0;
    m_versionMajor = 0;
    m_versionMinor = 0;
    m_versionBuild = 0;
    m_serial = 0;
}

void YubiKeyFinder::start() {
    //Start timer
    init();
    if(m_timer && !m_timer->isActive()) {
        m_timer->start(TIMEOUT_FINDER);
    }
}

void YubiKeyFinder::stop() {
    //Stop timer
    if(m_timer && m_timer->isActive()) {
        m_timer->stop();
        // doing closeKey() here might look out of place and may cause findKey()
        // to fail unexpectedly, but it's needed to not leak file descriptors
        // when writing the key.
        closeKey();
    }
}

bool YubiKeyFinder::openKey() {
    bool flag = true;
    if (!(m_yk = yk_open_first_key())) {
        flag = false;
    }

    return flag;
}

bool YubiKeyFinder::closeKey() {
    bool flag = true;
    if(m_yk != 0) {
        if (!yk_close_key(m_yk)) {
            flag = false;
        }
        m_yk = 0;
    }

    return flag;
}

void YubiKeyFinder::findKey() {
    YK_STATUS *ykst = ykds_alloc();
    bool error = false;

    //qDebug() << "-------------------------";
    //qDebug() << "Starting key search";
    //qDebug() << "-------------------------";

    try {
        if(m_yk == 0 && !openKey()) {
            throw 0;
        }

        if (!yk_get_status(m_yk, ykst)) {
            throw 0;
        }

        //qDebug() << "Key found";

        //Check pervious state
        if(m_state == State_Absent) {

            m_state = State_Present;

            //Get version
            m_versionMajor = ykds_version_major(ykst);
            m_versionMinor = ykds_version_minor(ykst);
            m_versionBuild = ykds_version_build(ykst);
            m_version = YK_VERSION(m_versionMajor,
                                   m_versionMinor,
                                   m_versionBuild);

            m_touchLevel = ykds_touch_level(ykst);

            //Get serial number
            if(checkFeatureSupport(Feature_SerialNumber)) {
                if (!yk_get_serial(m_yk, 0, 0, &m_serial)) {
                    qDebug() << "Failed to read serial number (serial-api-visible disabled?).";
                } else {
                    qDebug() << "Serial number: " << m_serial;
                }
            }

            //Get supported features
            size_t featuresCount = sizeof(FEATURE_MATRIX)/sizeof(FEATURE_MATRIX[0]);
            bool featuresMatrix[featuresCount];
            for(size_t i = 0; i < featuresCount; i++) {
                featuresMatrix[i] = checkFeatureSupport((Feature)i);
            }

            emit keyFound(true, featuresMatrix);
        }
    }
    catch(...) {
        error = true;
    }

    if(ykst) {
        ykds_free(ykst);
    }

    closeKey();

    if(error) {
        init();
        m_state = State_Absent;
        reportError();
        emit keyFound(false, NULL);
    }

    //qDebug() << "-------------------------";
    //qDebug() << "Stopping key search";
    //qDebug() << "-------------------------";
}
<commit_msg>Only lock the YubiKey when we have window focus.<commit_after>/*
Copyright (C) 2011-2012 Yubico AB.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

   1. Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.

   2. Redistributions in binary form must reproduce the above
      copyright notice, this list of conditions and the following
      disclaimer in the documentation and/or other materials provided
      with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "yubikeyfinder.h"

YubiKeyFinder* YubiKeyFinder::_instance = 0;

// first version is inclusive, second is exclusive
const unsigned int YubiKeyFinder::FEATURE_MATRIX[][2] = {
    { YK_VERSION(2,0,0), 0 },   //Feature_MultipleConfigurations
    { YK_VERSION(2,0,0), 0 },   //Feature_ProtectConfiguration2
    { YK_VERSION(1,3,0), 0 },   //Feature_StaticPassword
    { YK_VERSION(2,0,0), 0 },   //Feature_ScanCodeMode
    { YK_VERSION(2,0,0), 0 },   //Feature_ShortTicket
    { YK_VERSION(2,0,0), 0 },   //Feature_StrongPwd
    { YK_VERSION(2,1,0), 0 },   //Feature_OathHotp
    { YK_VERSION(2,2,0), 0 },   //Feature_ChallengeResponse
    { YK_VERSION(2,1,4), 0 },   //Feature_SerialNumber
    { YK_VERSION(2,1,7), 0 },   //Feature_MovingFactor
    { YK_VERSION(2,3,0), 0 },   //Feature_ChallengeResponseFixed
    { YK_VERSION(2,3,0), 0 },   //Feature_Updatable
    { YK_VERSION(2,1,4), 0 },   //Feature_Ndef
};

// when a featureset should be excluded from versions (NEO, I'm looking at you.)
const unsigned int YubiKeyFinder::FEATURE_MATRIX_EXCLUDE[][2] = {
    { YK_VERSION(2,1,4), YK_VERSION(2,2,0) }, //Feature_MultipleConfigurations
    { YK_VERSION(2,1,4), YK_VERSION(2,2,0) }, //Feature_ProtectConfiguration2
    { YK_VERSION(2,1,4), YK_VERSION(2,1,8) }, //Feature_StaticPassword
    { YK_VERSION(2,1,4), YK_VERSION(2,1,8) }, //Feature_ScanCodeMode
    { 0, 0 },                                 //Feature_ShortTicket
    { YK_VERSION(2,1,4), YK_VERSION(2,1,8) }, //Feature_StrongPwd
    { 0, 0 },                                 //Feature_OathHotp
    { 0, 0 },                                 //Feature_ChallengeResponse
    { 0, 0 },                                 //Feature_SerialNumber
    { 0, 0 },                                 //Feature_MovingFactor
    { 0, 0 },                                 //Feature_ChallengeResponseFixed
    { 0, 0 },                                 //Feature_Updatable
    { YK_VERSION(2,2,0), YK_VERSION(3,0,0) }, //Feature_Ndef
};

YubiKeyFinder::YubiKeyFinder() {
    // init the ykpers library
    yk_init();

    //Initialize fields
    init();

    //Create timer
    m_timer = new QTimer( this );
    connect(m_timer, SIGNAL(timeout()),
            this, SLOT(findKey()));
}

YubiKeyFinder::~YubiKeyFinder() {
    yk_release();

    if(m_timer != 0) {
        delete m_timer;
        m_timer = 0;
    }

    if(_instance) {
        delete _instance;
    }
}

YubiKeyFinder* YubiKeyFinder::getInstance() {
    if(_instance == NULL) {
        _instance = new YubiKeyFinder();
    }
    return _instance;
}

QString YubiKeyFinder::versionStr() {
    if(m_version > 0) {
        return tr("%1.%2.%3").
                arg(m_versionMajor).
                arg(m_versionMinor).
                arg(m_versionBuild);
    }
    return "";
}

void YubiKeyFinder::reportError() {
    if (ykp_errno) {
        //qDebug("Yubikey personalization error: %s\n", ykp_strerror(ykp_errno));
        ykp_errno = 0;
    } else if (yk_errno) {
        if (yk_errno == YK_EUSBERR) {
            //qDebug("USB error: %s\n", yk_usb_strerror());
        } else {
            //qDebug("Yubikey core error: %s\n", yk_strerror(yk_errno));
        }

        yk_errno = 0;
    }

    emit errorOccurred(ERR_KEY_NOT_FOUND);
}

bool YubiKeyFinder::checkFeatureSupport(Feature feature) {
    if(m_version > 0 &&
       (unsigned int) feature < sizeof(FEATURE_MATRIX)/sizeof(FEATURE_MATRIX[0])) {
        bool supported = (
                m_version >= FEATURE_MATRIX[feature][0] &&
                (FEATURE_MATRIX[feature][1] == 0 || m_version < FEATURE_MATRIX[feature][1])
                );
        if(supported)
            if(FEATURE_MATRIX_EXCLUDE[feature][0] != 0)
                if(m_version >= FEATURE_MATRIX_EXCLUDE[feature][0])
                    if(m_version < FEATURE_MATRIX_EXCLUDE[feature][1])
                        return false;
        return supported;
    }
    return false;
}

void YubiKeyFinder::init() {
    m_state = State_Absent;
    m_yk = 0;
    m_version = 0;
    m_versionMajor = 0;
    m_versionMinor = 0;
    m_versionBuild = 0;
    m_serial = 0;
}

void YubiKeyFinder::start() {
    //Start timer
    init();
    if(m_timer && !m_timer->isActive()) {
        m_timer->start(TIMEOUT_FINDER);
    }
}

void YubiKeyFinder::stop() {
    //Stop timer
    if(m_timer && m_timer->isActive()) {
        m_timer->stop();
        // doing closeKey() here might look out of place and may cause findKey()
        // to fail unexpectedly, but it's needed to not leak file descriptors
        // when writing the key.
        closeKey();
    }
}

bool YubiKeyFinder::openKey() {
    bool flag = true;
    if (!(m_yk = yk_open_first_key())) {
        flag = false;
    }

    return flag;
}

bool YubiKeyFinder::closeKey() {
    bool flag = true;
    if(m_yk != 0) {
        if (!yk_close_key(m_yk)) {
            flag = false;
        }
        m_yk = 0;
    }

    return flag;
}

void YubiKeyFinder::findKey() {
    YK_STATUS *ykst = ykds_alloc();
    bool error = false;

    if(QApplication::activeWindow() == 0) {
        //No focus, avoid locking the YubiKey.
        return;
    }
    //qDebug() << "-------------------------";
    //qDebug() << "Starting key search";
    //qDebug() << "-------------------------";

    try {
        if(m_yk == 0 && !openKey()) {
            throw 0;
        }

        if (!yk_get_status(m_yk, ykst)) {
            throw 0;
        }

        //qDebug() << "Key found";

        //Check pervious state
        if(m_state == State_Absent) {

            m_state = State_Present;

            //Get version
            m_versionMajor = ykds_version_major(ykst);
            m_versionMinor = ykds_version_minor(ykst);
            m_versionBuild = ykds_version_build(ykst);
            m_version = YK_VERSION(m_versionMajor,
                                   m_versionMinor,
                                   m_versionBuild);

            m_touchLevel = ykds_touch_level(ykst);

            //Get serial number
            if(checkFeatureSupport(Feature_SerialNumber)) {
                if (!yk_get_serial(m_yk, 0, 0, &m_serial)) {
                    qDebug() << "Failed to read serial number (serial-api-visible disabled?).";
                } else {
                    qDebug() << "Serial number: " << m_serial;
                }
            }

            //Get supported features
            size_t featuresCount = sizeof(FEATURE_MATRIX)/sizeof(FEATURE_MATRIX[0]);
            bool featuresMatrix[featuresCount];
            for(size_t i = 0; i < featuresCount; i++) {
                featuresMatrix[i] = checkFeatureSupport((Feature)i);
            }

            emit keyFound(true, featuresMatrix);
        }
    }
    catch(...) {
        error = true;
    }

    if(ykst) {
        ykds_free(ykst);
    }

    closeKey();

    if(error) {
        init();
        m_state = State_Absent;
        reportError();
        emit keyFound(false, NULL);
    }

    //qDebug() << "-------------------------";
    //qDebug() << "Stopping key search";
    //qDebug() << "-------------------------";
}
<|endoftext|>


<commit_before>/*
Copyright (C) 2011-2013 Yubico AB.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

   1. Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.

   2. Redistributions in binary form must reproduce the above
      copyright notice, this list of conditions and the following
      disclaimer in the documentation and/or other materials provided
      with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "yubikeylogger.h"
#include "yubikeyutil.h"
#include <QFile>
#include <QDir>
#include <QDebug>
#include <QDateTime>
#include <QFileDialog>
#include <QSettings>

#define LOG_FILENAME_DEF   "configuration_log.csv"
#define LOG_SEPARATOR      ","

QString YubiKeyLogger::m_filename   = defaultLogFilename();
bool YubiKeyLogger::m_enabled       = true;
bool YubiKeyLogger::m_started       = true;
YubiKeyLogger::Format YubiKeyLogger::m_format = Format_Traditional;
QFile* YubiKeyLogger::m_logFile     = NULL;
QString YubiKeyLogger::m_flexibleFormat = "";

#define STRING 1
#define BOOL   2
#define INT    3
#define UINT   4

struct logging_st YubiKeyLogger::logging_map[] = {
    { "eventType", NULL, STRING, YubiKeyLogger::resolve_eventType },
    { "timestampLocal", NULL, STRING, YubiKeyLogger::resolve_timestamp },
    { "configSlot", "configSlot", INT, NULL },
    { "pubIdTxt", "pubIdTxt", STRING, NULL },
    { "oathIdTxt", NULL, STRING, YubiKeyLogger::resolve_oathId },
    { "pvtIdTxt", "pvtIdTxt", STRING, NULL },
    { "secretKeyTxt", "secretKeyTxt", STRING, NULL },
    { "secretKeyB64", NULL, STRING, YubiKeyLogger::resolve_secretKeyB64 },
    { "currentAccessCodeTxt", "currentAccessCodeTxt", STRING, NULL },
    { "currentAccessCodeTxtPadded", NULL, STRING, YubiKeyLogger::resolve_accessCode },
    { "newAccessCodeTxt", "newAccessCodeTxt", STRING, NULL },
    { "newAccessCodeTxtPadded", NULL, STRING, YubiKeyLogger::resolve_accessCode },
    { "hotpDigits", NULL, STRING, YubiKeyLogger::resolve_hotpDigits },
    { "oathMovingFactorSeed", "oathMovingFactorSeed", UINT, NULL },
    { "strongPw1", "strongPw1", BOOL, NULL },
    { "strongPw2", "strongPw2", BOOL, NULL },
    { "sendRef", "sendRef", BOOL, NULL },
    { "chalBtnTrig", "chalBtnTrig", BOOL, NULL },
    { "hmacLT64", "hmacLT64", BOOL, NULL },
    { "timestampFixed", NULL, STRING, YubiKeyLogger::resolve_timestamp },
    { "oathFixedModhex1", "oathFixedModhex1", BOOL, NULL },
    { "oathFixedModhex2", "oathFixedModhex2", BOOL, NULL },
    { "oathFixedModhex", "oathFixedModhex", BOOL, NULL },
    { "tokenLength", NULL, STRING, YubiKeyLogger::resolve_tokenLength },
    { "serial", "serial", STRING, NULL },
    { "endl", NULL, STRING, YubiKeyLogger::resolve_symbol },
    { "tab", NULL, STRING, YubiKeyLogger::resolve_symbol },
};

YubiKeyLogger::~YubiKeyLogger() {
}

QFile *YubiKeyLogger::getLogFile() {
    if(m_logFile == NULL) {
        m_filename = QFileDialog::getSaveFileName(NULL, tr("Select Log File"), m_filename, tr("Comma-sepparated values (*.csv)"), NULL, QFileDialog::DontConfirmOverwrite);
        if(m_filename.isEmpty()) {
            qDebug() << "No filename returned for logging";
            return NULL;
        }
        m_logFile = new QFile(m_filename);
        if(!m_logFile->open(QIODevice::WriteOnly | QIODevice::Append)) {
            qDebug() << "File could not be opened for writing";
            return NULL;
        }
        QSettings settings;
        settings.setValue(SG_LOG_FILENAME, m_filename);
    }
    return m_logFile;
}

void YubiKeyLogger::closeLogFile() {
    if(m_logFile != NULL) {
        if(m_format == Format_PSKC) {
            endPSKC();
        }
        m_logFile->close();
        delete(m_logFile);
        m_logFile = NULL;
        m_started = true;
    }
}

QString YubiKeyLogger::formatLog(YubiKeyConfig *ykConfig, QString format) {
    for(unsigned long i = 0; i < (sizeof(logging_map) / sizeof(logging_st)); i++) {
        QString token = QString("{") + logging_map[i].name + QString("}");
        if(!format.contains(token)) {
            continue;
        }
        QString out;
        int type = logging_map[i].returnType;
        const char *configName = logging_map[i].configName;
        if(logging_map[i].resolver != NULL) {
            out = logging_map[i].resolver(ykConfig, logging_map[i].name);
        } else if(type == STRING) {
            QMetaObject::invokeMethod(ykConfig, configName,
                    Qt::DirectConnection, Q_RETURN_ARG(QString, out));
        } else if(type == BOOL) {
            bool ret;
            QMetaObject::invokeMethod(ykConfig, configName,
                    Qt::DirectConnection, Q_RETURN_ARG(bool, ret));
            out = ret ? "1" : "0";
        } else if(type == INT) {
            int ret;
            QMetaObject::invokeMethod(ykConfig, configName,
                    Qt::DirectConnection, Q_RETURN_ARG(int, ret));
            out = QString::number(ret);
        } else if(type == UINT) {
            unsigned int ret;
            QMetaObject::invokeMethod(ykConfig, configName,
                    Qt::DirectConnection, Q_RETURN_ARG(unsigned int, ret));
            out = QString::number(ret);
        }

        qDebug() << "replacing " << token << " with " << out << " from " << configName << " type " << type;
        format.replace(token, out);
    }
    return format;
}

void YubiKeyLogger::logConfig(YubiKeyConfig *ykConfig) {
    //Check if logging is enabled
    if(!m_enabled) {
        return;
    }

    QString format = "";
    if(m_format == Format_Traditional) {
        if(m_started) {
            format += "LOGGING START,{timestampLocal}{endl}";
            m_started = false;
        }

        format += "{eventType},{timestampLocal},{configSlot},{pubIdTxt},{pvtIdTxt},{secretKeyTxt},{currentAccessCodeTxt},{newAccessCodeTxt},{oathFixedModhex1},{oathFixedModhex2},{oathFixedModhex},{hotpDigits},{oathMovingFactorSeed},{strongPw1},{strongPw2},{sendRef},{chalBtnTrig},{hmacLT64}";
    } else if(m_format == Format_Yubico) {
        format = "{serial},";
        if(ykConfig->programmingMode() == YubiKeyConfig::Mode_YubicoOtp) {
            format += "{pubIdTxt},{pvtIdTxt},";
        } else if(ykConfig->programmingMode() == YubiKeyConfig::Mode_OathHotp) {
            format += "{pubIdTxt},{oathMovingFactorSeed},";
        } else if(ykConfig->programmingMode() == YubiKeyConfig::Mode_ChalRespHmac) {
            format += ",0,";
        } else {
            format += ",,";
        }
        format += "{secretKeyTxt},{newAccessCodeTxtPadded},{timestampFixed},";
    } else if(m_format == Format_PSKC) {
        if(m_started) {
            format += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>{endl}<KeyContainer Version=\"1.0\" xmlns=\"urn:ietf:params:xml:ns:keyprov:pskc\">{endl}";
            m_started = false;
        }
        format += "<KeyPackage><DeviceInfo><Manufacturer>Yubico</Manufacturer><SerialNo>{serial}</SerialNo></DeviceInfo>";
        QString id = "\"{serial}:{configSlot}\"";
        if(ykConfig->programmingMode() == YubiKeyConfig::Mode_OathHotp && ykConfig->pubIdTxt().length() > 0) {
            id = "\"{oathIdTxt}\"";
        }
        format += "<CryptoModuleInfo><Id>{configSlot}</Id></CryptoModuleInfo><Key Id=" + id;
        if(ykConfig->programmingMode() == YubiKeyConfig::Mode_YubicoOtp) {
            format += " Algorithm=\"http://www.yubico.com/#yubikey-aes\"><AlgorithmParameters><ResponseFormat Length=\"{tokenLength}\" Encoding=\"ALPHANUMERIC\"/></AlgorithmParameters>";
        } else if(ykConfig->programmingMode() == YubiKeyConfig::Mode_OathHotp) {
            format += " Algorithm=\"urn:ietf:params:xml:ns:keyprov:pskc:hotp\"><AlgorithmParameters><ResponseFormat Length=\"{tokenLength}\" Encoding=\"DECIMAL\"/></AlgorithmParameters>";
        } else {
            qDebug() << "PSKC is primarily for Oath-HOTP and Yubico-OTP";
            format += ">";
        }
        format += "<Data><Secret><PlainValue>{secretKeyB64}</PlainValue></Secret>";
        if(ykConfig->programmingMode() == YubiKeyConfig::Mode_OathHotp) {
            format += "<Counter><PlainValue>{oathMovingFactorSeed}</PlainValue></Counter>";
        }
        format += "</Data>";
        if(ykConfig->programmingMode() == YubiKeyConfig::Mode_YubicoOtp) {
            format += "<UserId>CN={pubIdTxt}, UID={pvtIdTxt}</UserId>";
        }
        format += "</Key></KeyPackage>";
    } else if(m_format == Format_Flexible) {
        format = m_flexibleFormat;
    } else {
        qDebug() << "unknown format" << m_format;
        return;
    }
    format = formatLog(ykConfig, format);
    logString(format);
}

void YubiKeyLogger::enableLogging() {
    m_enabled = true;
}

void YubiKeyLogger::disableLogging() {
    m_enabled = false;
}

bool YubiKeyLogger::isLogging() {
    return m_enabled;
}

void YubiKeyLogger::setLogFilename(const QString &filename) {
    closeLogFile();
    m_filename = filename;
}

QString YubiKeyLogger::logFilename() {
    return m_filename;
}

QString YubiKeyLogger::defaultLogFilename() {
    return QDir::homePath() + "/" + LOG_FILENAME_DEF;
}

void YubiKeyLogger::setLogFormat(Format format) {
    closeLogFile();
    m_format = format;
}

void YubiKeyLogger::setFlexibleFormat(QString format) {
    m_flexibleFormat = format;
}

QString YubiKeyLogger::resolve_hotpDigits(YubiKeyConfig *ykConfig, QString name __attribute__((unused))) {
    QString ret = "0";
    if(ykConfig->programmingMode() == YubiKeyConfig::Mode_OathHotp) {
        ret = (ykConfig->oathHotp8()? "8": "6");
    }
    return ret;
}

QString YubiKeyLogger::resolve_eventType(YubiKeyConfig *ykConfig, QString name __attribute__((unused))) {
    switch(ykConfig->programmingMode()) {
        case YubiKeyConfig::Mode_YubicoOtp:
            return(tr("Yubico OTP"));
        case YubiKeyConfig::Mode_Static:
            {
                QString eventType = tr("Static Password");
                if(ykConfig->shortTicket()) {
                    if(ykConfig->staticTicket()) {
                        eventType.append(tr(": Short"));
                    } else {
                        eventType.append(tr(": Scan Code"));
                    }
                }
                return eventType;
            }
        case YubiKeyConfig::Mode_OathHotp:
            return(tr("OATH-HOTP"));
        case YubiKeyConfig::Mode_ChalRespYubico:
            return(tr("Challenge-Response: Yubico OTP"));
        case YubiKeyConfig::Mode_ChalRespHmac:
            return(tr("Challenge-Response: HMAC-SHA1"));
        case YubiKeyConfig::Mode_Update:
            return(tr("Configuration Update"));
        case YubiKeyConfig::Mode_Swap:
            return(tr("Configuration Swap"));
    }
    return(tr("Unknown programming mode"));
}

QString YubiKeyLogger::resolve_timestamp(YubiKeyConfig *ykConfig __attribute__((unused)), QString name) {
        QDateTime ts = QDateTime::currentDateTime();
        if(name == "timestampLocal") {
            return ts.toString(Qt::SystemLocaleDate);
        } else {
            return ts.toString("yyyy-MM-ddThh:mm:ss");
        }
}

QString YubiKeyLogger::resolve_symbol(YubiKeyConfig *ykConfig __attribute__((unused)), QString name) {
    if(name == "endl") {
        return "\n";
    } else if(name == "tab") {
        return "\t";
    }
    return "";
}

QString YubiKeyLogger::resolve_secretKeyB64(YubiKeyConfig *ykConfig, QString name __attribute__((unused))) {
    QByteArray decodedSecret = QByteArray::fromHex(ykConfig->secretKeyTxt().toLatin1());
    return decodedSecret.toBase64();
}

QString YubiKeyLogger::resolve_tokenLength(YubiKeyConfig *ykConfig, QString name __attribute__((unused))) {
    int len = ykConfig->pubIdTxt().length();

    if(ykConfig->programmingMode() == YubiKeyConfig::Mode_YubicoOtp) {
        len += 32;
    } else if(ykConfig->programmingMode() == YubiKeyConfig::Mode_OathHotp) {
        len += ykConfig->oathHotp8() ? 8 : 6;
    }
    return QString::number(len);
}

QString YubiKeyLogger::resolve_accessCode(YubiKeyConfig *ykConfig, QString name) {
    QString code;
    if(name == "currentAccessCodeTxtPadded") {
        code = ykConfig->currentAccessCodeTxt();
    } else {
        code = ykConfig->newAccessCodeTxt();
    }
    return code.rightJustified(12, '0');
}

QString YubiKeyLogger::resolve_oathId(YubiKeyConfig *ykConfig, QString name __attribute__((unused))) {
    QString id;
    QString pubid = ykConfig->pubIdTxt();
    int modhex = 0;
    if(ykConfig->oathFixedModhex()) {
        modhex = pubid.length();
    } else if(ykConfig->oathFixedModhex1()) {
        modhex = 2;
    } else if(ykConfig->oathFixedModhex2()) {
        modhex = 4;
    }
    id = pubid.left(modhex);
    if(modhex != pubid.length()) {
        unsigned char buf[16];
        size_t len = sizeof(buf);
        YubiKeyUtil::qstrModhexDecode(buf, &len, pubid.right(pubid.length() - modhex));
        id += YubiKeyUtil::qstrHexEncode(buf, len);
    }
    return id;
}

QStringList YubiKeyLogger::getLogNames() {
    QStringList list;
    for(unsigned int i = 0; i < (sizeof(logging_map) / sizeof(logging_st)); i++) {
        list << logging_map[i].name;
    }
    return list;
}

void YubiKeyLogger::endPSKC() {
    logString("</KeyContainer>");
}

void YubiKeyLogger::logString(QString string) {
    QFile *file = getLogFile();
    if(file == NULL) {
        qDebug() << "Failed to get logfile";
        return;
    }

    QTextStream out(file);
    out << string << "\n";
    file->flush();
}
<commit_msg>Fix typo<commit_after>/*
Copyright (C) 2011-2013 Yubico AB.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

   1. Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.

   2. Redistributions in binary form must reproduce the above
      copyright notice, this list of conditions and the following
      disclaimer in the documentation and/or other materials provided
      with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "yubikeylogger.h"
#include "yubikeyutil.h"
#include <QFile>
#include <QDir>
#include <QDebug>
#include <QDateTime>
#include <QFileDialog>
#include <QSettings>

#define LOG_FILENAME_DEF   "configuration_log.csv"
#define LOG_SEPARATOR      ","

QString YubiKeyLogger::m_filename   = defaultLogFilename();
bool YubiKeyLogger::m_enabled       = true;
bool YubiKeyLogger::m_started       = true;
YubiKeyLogger::Format YubiKeyLogger::m_format = Format_Traditional;
QFile* YubiKeyLogger::m_logFile     = NULL;
QString YubiKeyLogger::m_flexibleFormat = "";

#define STRING 1
#define BOOL   2
#define INT    3
#define UINT   4

struct logging_st YubiKeyLogger::logging_map[] = {
    { "eventType", NULL, STRING, YubiKeyLogger::resolve_eventType },
    { "timestampLocal", NULL, STRING, YubiKeyLogger::resolve_timestamp },
    { "configSlot", "configSlot", INT, NULL },
    { "pubIdTxt", "pubIdTxt", STRING, NULL },
    { "oathIdTxt", NULL, STRING, YubiKeyLogger::resolve_oathId },
    { "pvtIdTxt", "pvtIdTxt", STRING, NULL },
    { "secretKeyTxt", "secretKeyTxt", STRING, NULL },
    { "secretKeyB64", NULL, STRING, YubiKeyLogger::resolve_secretKeyB64 },
    { "currentAccessCodeTxt", "currentAccessCodeTxt", STRING, NULL },
    { "currentAccessCodeTxtPadded", NULL, STRING, YubiKeyLogger::resolve_accessCode },
    { "newAccessCodeTxt", "newAccessCodeTxt", STRING, NULL },
    { "newAccessCodeTxtPadded", NULL, STRING, YubiKeyLogger::resolve_accessCode },
    { "hotpDigits", NULL, STRING, YubiKeyLogger::resolve_hotpDigits },
    { "oathMovingFactorSeed", "oathMovingFactorSeed", UINT, NULL },
    { "strongPw1", "strongPw1", BOOL, NULL },
    { "strongPw2", "strongPw2", BOOL, NULL },
    { "sendRef", "sendRef", BOOL, NULL },
    { "chalBtnTrig", "chalBtnTrig", BOOL, NULL },
    { "hmacLT64", "hmacLT64", BOOL, NULL },
    { "timestampFixed", NULL, STRING, YubiKeyLogger::resolve_timestamp },
    { "oathFixedModhex1", "oathFixedModhex1", BOOL, NULL },
    { "oathFixedModhex2", "oathFixedModhex2", BOOL, NULL },
    { "oathFixedModhex", "oathFixedModhex", BOOL, NULL },
    { "tokenLength", NULL, STRING, YubiKeyLogger::resolve_tokenLength },
    { "serial", "serial", STRING, NULL },
    { "endl", NULL, STRING, YubiKeyLogger::resolve_symbol },
    { "tab", NULL, STRING, YubiKeyLogger::resolve_symbol },
};

YubiKeyLogger::~YubiKeyLogger() {
}

QFile *YubiKeyLogger::getLogFile() {
    if(m_logFile == NULL) {
        m_filename = QFileDialog::getSaveFileName(NULL, tr("Select Log File"), m_filename, tr("Comma-separated values (*.csv)"), NULL, QFileDialog::DontConfirmOverwrite);
        if(m_filename.isEmpty()) {
            qDebug() << "No filename returned for logging";
            return NULL;
        }
        m_logFile = new QFile(m_filename);
        if(!m_logFile->open(QIODevice::WriteOnly | QIODevice::Append)) {
            qDebug() << "File could not be opened for writing";
            return NULL;
        }
        QSettings settings;
        settings.setValue(SG_LOG_FILENAME, m_filename);
    }
    return m_logFile;
}

void YubiKeyLogger::closeLogFile() {
    if(m_logFile != NULL) {
        if(m_format == Format_PSKC) {
            endPSKC();
        }
        m_logFile->close();
        delete(m_logFile);
        m_logFile = NULL;
        m_started = true;
    }
}

QString YubiKeyLogger::formatLog(YubiKeyConfig *ykConfig, QString format) {
    for(unsigned long i = 0; i < (sizeof(logging_map) / sizeof(logging_st)); i++) {
        QString token = QString("{") + logging_map[i].name + QString("}");
        if(!format.contains(token)) {
            continue;
        }
        QString out;
        int type = logging_map[i].returnType;
        const char *configName = logging_map[i].configName;
        if(logging_map[i].resolver != NULL) {
            out = logging_map[i].resolver(ykConfig, logging_map[i].name);
        } else if(type == STRING) {
            QMetaObject::invokeMethod(ykConfig, configName,
                    Qt::DirectConnection, Q_RETURN_ARG(QString, out));
        } else if(type == BOOL) {
            bool ret;
            QMetaObject::invokeMethod(ykConfig, configName,
                    Qt::DirectConnection, Q_RETURN_ARG(bool, ret));
            out = ret ? "1" : "0";
        } else if(type == INT) {
            int ret;
            QMetaObject::invokeMethod(ykConfig, configName,
                    Qt::DirectConnection, Q_RETURN_ARG(int, ret));
            out = QString::number(ret);
        } else if(type == UINT) {
            unsigned int ret;
            QMetaObject::invokeMethod(ykConfig, configName,
                    Qt::DirectConnection, Q_RETURN_ARG(unsigned int, ret));
            out = QString::number(ret);
        }

        qDebug() << "replacing " << token << " with " << out << " from " << configName << " type " << type;
        format.replace(token, out);
    }
    return format;
}

void YubiKeyLogger::logConfig(YubiKeyConfig *ykConfig) {
    //Check if logging is enabled
    if(!m_enabled) {
        return;
    }

    QString format = "";
    if(m_format == Format_Traditional) {
        if(m_started) {
            format += "LOGGING START,{timestampLocal}{endl}";
            m_started = false;
        }

        format += "{eventType},{timestampLocal},{configSlot},{pubIdTxt},{pvtIdTxt},{secretKeyTxt},{currentAccessCodeTxt},{newAccessCodeTxt},{oathFixedModhex1},{oathFixedModhex2},{oathFixedModhex},{hotpDigits},{oathMovingFactorSeed},{strongPw1},{strongPw2},{sendRef},{chalBtnTrig},{hmacLT64}";
    } else if(m_format == Format_Yubico) {
        format = "{serial},";
        if(ykConfig->programmingMode() == YubiKeyConfig::Mode_YubicoOtp) {
            format += "{pubIdTxt},{pvtIdTxt},";
        } else if(ykConfig->programmingMode() == YubiKeyConfig::Mode_OathHotp) {
            format += "{pubIdTxt},{oathMovingFactorSeed},";
        } else if(ykConfig->programmingMode() == YubiKeyConfig::Mode_ChalRespHmac) {
            format += ",0,";
        } else {
            format += ",,";
        }
        format += "{secretKeyTxt},{newAccessCodeTxtPadded},{timestampFixed},";
    } else if(m_format == Format_PSKC) {
        if(m_started) {
            format += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>{endl}<KeyContainer Version=\"1.0\" xmlns=\"urn:ietf:params:xml:ns:keyprov:pskc\">{endl}";
            m_started = false;
        }
        format += "<KeyPackage><DeviceInfo><Manufacturer>Yubico</Manufacturer><SerialNo>{serial}</SerialNo></DeviceInfo>";
        QString id = "\"{serial}:{configSlot}\"";
        if(ykConfig->programmingMode() == YubiKeyConfig::Mode_OathHotp && ykConfig->pubIdTxt().length() > 0) {
            id = "\"{oathIdTxt}\"";
        }
        format += "<CryptoModuleInfo><Id>{configSlot}</Id></CryptoModuleInfo><Key Id=" + id;
        if(ykConfig->programmingMode() == YubiKeyConfig::Mode_YubicoOtp) {
            format += " Algorithm=\"http://www.yubico.com/#yubikey-aes\"><AlgorithmParameters><ResponseFormat Length=\"{tokenLength}\" Encoding=\"ALPHANUMERIC\"/></AlgorithmParameters>";
        } else if(ykConfig->programmingMode() == YubiKeyConfig::Mode_OathHotp) {
            format += " Algorithm=\"urn:ietf:params:xml:ns:keyprov:pskc:hotp\"><AlgorithmParameters><ResponseFormat Length=\"{tokenLength}\" Encoding=\"DECIMAL\"/></AlgorithmParameters>";
        } else {
            qDebug() << "PSKC is primarily for Oath-HOTP and Yubico-OTP";
            format += ">";
        }
        format += "<Data><Secret><PlainValue>{secretKeyB64}</PlainValue></Secret>";
        if(ykConfig->programmingMode() == YubiKeyConfig::Mode_OathHotp) {
            format += "<Counter><PlainValue>{oathMovingFactorSeed}</PlainValue></Counter>";
        }
        format += "</Data>";
        if(ykConfig->programmingMode() == YubiKeyConfig::Mode_YubicoOtp) {
            format += "<UserId>CN={pubIdTxt}, UID={pvtIdTxt}</UserId>";
        }
        format += "</Key></KeyPackage>";
    } else if(m_format == Format_Flexible) {
        format = m_flexibleFormat;
    } else {
        qDebug() << "unknown format" << m_format;
        return;
    }
    format = formatLog(ykConfig, format);
    logString(format);
}

void YubiKeyLogger::enableLogging() {
    m_enabled = true;
}

void YubiKeyLogger::disableLogging() {
    m_enabled = false;
}

bool YubiKeyLogger::isLogging() {
    return m_enabled;
}

void YubiKeyLogger::setLogFilename(const QString &filename) {
    closeLogFile();
    m_filename = filename;
}

QString YubiKeyLogger::logFilename() {
    return m_filename;
}

QString YubiKeyLogger::defaultLogFilename() {
    return QDir::homePath() + "/" + LOG_FILENAME_DEF;
}

void YubiKeyLogger::setLogFormat(Format format) {
    closeLogFile();
    m_format = format;
}

void YubiKeyLogger::setFlexibleFormat(QString format) {
    m_flexibleFormat = format;
}

QString YubiKeyLogger::resolve_hotpDigits(YubiKeyConfig *ykConfig, QString name __attribute__((unused))) {
    QString ret = "0";
    if(ykConfig->programmingMode() == YubiKeyConfig::Mode_OathHotp) {
        ret = (ykConfig->oathHotp8()? "8": "6");
    }
    return ret;
}

QString YubiKeyLogger::resolve_eventType(YubiKeyConfig *ykConfig, QString name __attribute__((unused))) {
    switch(ykConfig->programmingMode()) {
        case YubiKeyConfig::Mode_YubicoOtp:
            return(tr("Yubico OTP"));
        case YubiKeyConfig::Mode_Static:
            {
                QString eventType = tr("Static Password");
                if(ykConfig->shortTicket()) {
                    if(ykConfig->staticTicket()) {
                        eventType.append(tr(": Short"));
                    } else {
                        eventType.append(tr(": Scan Code"));
                    }
                }
                return eventType;
            }
        case YubiKeyConfig::Mode_OathHotp:
            return(tr("OATH-HOTP"));
        case YubiKeyConfig::Mode_ChalRespYubico:
            return(tr("Challenge-Response: Yubico OTP"));
        case YubiKeyConfig::Mode_ChalRespHmac:
            return(tr("Challenge-Response: HMAC-SHA1"));
        case YubiKeyConfig::Mode_Update:
            return(tr("Configuration Update"));
        case YubiKeyConfig::Mode_Swap:
            return(tr("Configuration Swap"));
    }
    return(tr("Unknown programming mode"));
}

QString YubiKeyLogger::resolve_timestamp(YubiKeyConfig *ykConfig __attribute__((unused)), QString name) {
        QDateTime ts = QDateTime::currentDateTime();
        if(name == "timestampLocal") {
            return ts.toString(Qt::SystemLocaleDate);
        } else {
            return ts.toString("yyyy-MM-ddThh:mm:ss");
        }
}

QString YubiKeyLogger::resolve_symbol(YubiKeyConfig *ykConfig __attribute__((unused)), QString name) {
    if(name == "endl") {
        return "\n";
    } else if(name == "tab") {
        return "\t";
    }
    return "";
}

QString YubiKeyLogger::resolve_secretKeyB64(YubiKeyConfig *ykConfig, QString name __attribute__((unused))) {
    QByteArray decodedSecret = QByteArray::fromHex(ykConfig->secretKeyTxt().toLatin1());
    return decodedSecret.toBase64();
}

QString YubiKeyLogger::resolve_tokenLength(YubiKeyConfig *ykConfig, QString name __attribute__((unused))) {
    int len = ykConfig->pubIdTxt().length();

    if(ykConfig->programmingMode() == YubiKeyConfig::Mode_YubicoOtp) {
        len += 32;
    } else if(ykConfig->programmingMode() == YubiKeyConfig::Mode_OathHotp) {
        len += ykConfig->oathHotp8() ? 8 : 6;
    }
    return QString::number(len);
}

QString YubiKeyLogger::resolve_accessCode(YubiKeyConfig *ykConfig, QString name) {
    QString code;
    if(name == "currentAccessCodeTxtPadded") {
        code = ykConfig->currentAccessCodeTxt();
    } else {
        code = ykConfig->newAccessCodeTxt();
    }
    return code.rightJustified(12, '0');
}

QString YubiKeyLogger::resolve_oathId(YubiKeyConfig *ykConfig, QString name __attribute__((unused))) {
    QString id;
    QString pubid = ykConfig->pubIdTxt();
    int modhex = 0;
    if(ykConfig->oathFixedModhex()) {
        modhex = pubid.length();
    } else if(ykConfig->oathFixedModhex1()) {
        modhex = 2;
    } else if(ykConfig->oathFixedModhex2()) {
        modhex = 4;
    }
    id = pubid.left(modhex);
    if(modhex != pubid.length()) {
        unsigned char buf[16];
        size_t len = sizeof(buf);
        YubiKeyUtil::qstrModhexDecode(buf, &len, pubid.right(pubid.length() - modhex));
        id += YubiKeyUtil::qstrHexEncode(buf, len);
    }
    return id;
}

QStringList YubiKeyLogger::getLogNames() {
    QStringList list;
    for(unsigned int i = 0; i < (sizeof(logging_map) / sizeof(logging_st)); i++) {
        list << logging_map[i].name;
    }
    return list;
}

void YubiKeyLogger::endPSKC() {
    logString("</KeyContainer>");
}

void YubiKeyLogger::logString(QString string) {
    QFile *file = getLogFile();
    if(file == NULL) {
        qDebug() << "Failed to get logfile";
        return;
    }

    QTextStream out(file);
    out << string << "\n";
    file->flush();
}
<|endoftext|>


<commit_before>/* This file is part of Strigi Desktop Search
 *
 * Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */
#include <pluginthroughanalyzer.h>

/* test class 1 */
class Analyzer1 : public Strigi::StreamThroughAnalyzer {
private:
    Strigi::AnalysisResult* idx;
public:
    void setIndexable(Strigi::AnalysisResult*i) {
        idx = i;
    }
    Strigi::InputStream *connectInputStream(Strigi::InputStream *in) {
//        idx->addValue("hi", "hi");
        return in;
    }
};

/* test class 2 */
class Analyzer2 : public Strigi::StreamThroughAnalyzer {
    void setIndexable(Strigi::AnalysisResult*) {}
    Strigi::InputStream *connectInputStream(Strigi::InputStream *in) {
        return in;
    }
};

REGISTER_THROUGHANALYZER(Analyzer1)
REGISTER_THROUGHANALYZER(Analyzer2)
<commit_msg>remove unneeded file<commit_after><|endoftext|>


<commit_before><commit_msg>Avoid vector reallocations in THeader::readHeaderFormat<commit_after><|endoftext|>


<commit_before>/*
  This is a tool shipped by 'Aleph - A Library for Exploring Persistent
  Homology'.

  It permits the calculation of different entropy measures defined for
  persistence diagrams.

  Original author: Bastian Rieck
*/

#include <aleph/config/FLANN.hh>

#ifdef ALEPH_WITH_FLANN
  #include <aleph/geometry/FLANN.hh>
#endif

#include <aleph/containers/PointCloud.hh>

#include <aleph/geometry/BruteForce.hh>

#include <aleph/geometry/distances/Euclidean.hh>

#include <aleph/math/KahanSummation.hh>

#include <aleph/persistenceDiagrams/Entropy.hh>
#include <aleph/persistenceDiagrams/PersistenceDiagram.hh>

#include <aleph/persistenceDiagrams/io/Raw.hh>

#include <algorithm>
#include <iostream>
#include <string>
#include <vector>

#include <cmath>

using DataType           = double;
using PersistenceDiagram = aleph::PersistenceDiagram<DataType>;
using PointCloud         = aleph::containers::PointCloud<DataType>;
using Distance           = aleph::geometry::distances::Euclidean<DataType>;

#ifdef ALEPH_WITH_FLANN
  using NearestNeighbours = aleph::geometry::FLANN<PointCloud, Distance>;
#else
  using NearestNeighbours = aleph::geometry::BruteForce<PointCloud, Distance>;
#endif

class RegularGrid
{
public:
  RegularGrid( unsigned width, unsigned height,
               DataType x0, DataType x1,
               DataType y0, DataType y1 )
    : _width( width )
    , _height( height )
    , _x0( x0 ), _x1( x1 ), _xOffset( (_x1 - _x0) / ( _width - 1 ) )
    , _y0( y0 ), _y1( y1 ), _yOffset( (_y1 - _y0) / ( _height - 1 ) )
    , _cells( new unsigned[ _width * _height ] )
  {
    std::fill( this->begin(), this->end(), 0 );
  }

  unsigned* begin() { return _cells; }
  unsigned* end()   { return _cells + _width * _height; }

  unsigned& operator()( DataType x, DataType y )
  {
    x = x - _x0;
    y = y - _y0;

    unsigned i = unsigned( x / _xOffset );
    unsigned j = unsigned( y / _yOffset );

    return this->operator()(i,j);
  }

  unsigned& operator()( unsigned i, unsigned j )
  {
    return _cells[j * _width + i];
  }

  unsigned size() const noexcept
  {
    return _width * _height;
  }

private:
  unsigned _width;
  unsigned _height;

  DataType _x0, _x1, _xOffset;
  DataType _y0, _y1, _yOffset;

  unsigned* _cells;
};

struct Input
{
  std::string filename;
  PersistenceDiagram persistenceDiagram;
  PointCloud pointCloud;
};

PointCloud makePointCloud( const PersistenceDiagram& diagram )
{
  PointCloud pc( diagram.size(), 2 );
  std::size_t i = 0;

  for( auto&& point : diagram )
  {
    std::vector<DataType> p = { point.x(), point.y() };
    pc.set(i++, p.begin(), p.end() );
  }

  return pc;
}

template <class T> T log( T x )
{
  if( x == T() )
    return T();
  else
    return std::log( x );
}

void usage()
{
}

int main( int argc, char** argv )
{
  if( argc <= 1 )
  {
    usage();
    return -1;
  }

  std::vector<Input> inputs;
  inputs.reserve( argc );

  for( int i = 1; i < argc; i++ )
  {
    std::string filename = argv[i];

    std::cerr << "* Loading '" << filename << "'...";

    auto&& diagram = aleph::io::load<DataType>( filename );

    Input input = {
      filename,
      diagram,
      makePointCloud( diagram )
    };

    inputs.push_back( input );

    std::cerr << "finished\n";
  }

  for( auto&& input : inputs )
  {
    auto e_nn = aleph::nearestNeighbourAreaEntropy( input.persistenceDiagram );
    auto e_rg = aleph::gridEntropy( input.persistenceDiagram, 20 );

    std::cout << e_nn << "\t" << e_rg << "\n";
  }
}
<commit_msg>Removed obsolete code from entropy calculation tool<commit_after>/*
  This is a tool shipped by 'Aleph - A Library for Exploring Persistent
  Homology'.

  It permits the calculation of different entropy measures defined for
  persistence diagrams.

  Original author: Bastian Rieck
*/

#include <aleph/persistenceDiagrams/Entropy.hh>
#include <aleph/persistenceDiagrams/PersistenceDiagram.hh>

#include <aleph/persistenceDiagrams/io/Raw.hh>

#include <iostream>
#include <string>
#include <vector>

#include <cmath>

using DataType           = double;
using PersistenceDiagram = aleph::PersistenceDiagram<DataType>;

struct Input
{
  std::string filename;
  PersistenceDiagram persistenceDiagram;
};

void usage()
{
}

int main( int argc, char** argv )
{
  if( argc <= 1 )
  {
    usage();
    return -1;
  }

  std::vector<Input> inputs;
  inputs.reserve( argc );

  for( int i = 1; i < argc; i++ )
  {
    std::string filename = argv[i];

    std::cerr << "* Loading '" << filename << "'...";

    auto&& diagram = aleph::io::load<DataType>( filename );

    Input input = {
      filename,
      diagram
    };

    inputs.push_back( input );

    std::cerr << "finished\n";
  }

  for( auto&& input : inputs )
  {
    auto e_nn = aleph::nearestNeighbourAreaEntropy( input.persistenceDiagram );
    auto e_rg = aleph::gridEntropy( input.persistenceDiagram, 20 );

    std::cout << e_nn << "\t" << e_rg << "\n";
  }
}
<|endoftext|>


<commit_before>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
 * Ceph - scalable distributed file system
 *
 * Copyright (C) 2004-2006 Sage Weil <sage@newdream.net>
 *
 * This is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1, as published by the Free Software
 * Foundation.  See file COPYING.
 *
 */

#include <sys/stat.h>
#include <iostream>
#include <string>
using namespace std;

#include "common/config.h"

#include "mon/MonMap.h"
#include "mon/MonClient.h"
#include "msg/SimpleMessenger.h"
#include "messages/MPing.h"

#include "common/Timer.h"
#include "global/global_init.h"
#include "common/ceph_argparse.h"

#ifndef DARWIN
#include <envz.h>
#endif // DARWIN

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

Messenger *messenger = 0;

Mutex lock("mylock");
Cond cond;

uint64_t received = 0;

class Admin : public Dispatcher {
public:
  Admin()
    : Dispatcher(g_ceph_context)
  {
  }
private:
  bool ms_dispatch(Message *m) {

    //cerr << "got ping from " << m->get_source() << std::endl;
    dout(0) << "got ping from " << m->get_source() << dendl;
    lock.Lock();
    ++received;
    cond.Signal();
    lock.Unlock();

    m->put();
    return true;
  }

  bool ms_handle_reset(Connection *con) { return false; }
  void ms_handle_remote_reset(Connection *con) {}

} dispatcher;

int main(int argc, const char **argv, const char *envp[]) {

  vector<const char*> args;
  argv_to_vec(argc, argv, args);
  env_to_vec(args);

  global_init(args, CEPH_ENTITY_TYPE_CLIENT, CODE_ENVIRONMENT_UTILITY, 0);
  common_init_finish(g_ceph_context);

  vec_to_argv(args, argc, argv);

  dout(0) << "i am mon " << args[0] << dendl;

  // get monmap
  MonClient mc(g_ceph_context);
  if (mc.build_initial_monmap() < 0)
    return -1;

  // start up network
  int whoami = mc.monmap.get_rank(args[0]);
  assert(whoami >= 0);
  g_conf->public_addr = mc.monmap.get_addr(whoami);
  SimpleMessenger *rank = new SimpleMessenger(g_ceph_context);
  int err = rank->bind(getpid());
  if (err < 0)
    return 1;

  // start monitor
  rank->register_entity(entity_name_t::MON(whoami));
  messenger = rank;
  messenger->set_default_send_priority(CEPH_MSG_PRIO_HIGH);
  messenger->add_dispatcher_head(&dispatcher);

  rank->start();

  int isend = 0;
  if (whoami == 0)
    isend = 100;

  lock.Lock();
  uint64_t sent = 0;
  while (1) {
    while (received + isend <= sent) {
      //cerr << "wait r " << received << " s " << sent << " is " << isend << std::endl;
      dout(0) << "wait r " << received << " s " << sent << " is " << isend << dendl;
      cond.Wait(lock);
    }

    int t = rand() % mc.get_num_mon();
    if (t == whoami)
      continue;

    if (rand() % 10 == 0) {
      //cerr << "mark_down " << t << std::endl;
      dout(0) << "mark_down " << t << dendl;
      messenger->mark_down(mc.get_mon_addr(t));
    }
    //cerr << "pinging " << t << std::endl;
    dout(0) << "pinging " << t << dendl;
    messenger->send_message(new MPing, mc.get_mon_inst(t));
    cerr << isend << "\t" << ++sent << "\t" << received << "\r";
  }
  lock.Unlock();

  // wait for messenger to finish
  rank->wait();

  return 0;
}

<commit_msg>testmsgr.cc: use set_val / apply_changes<commit_after>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
 * Ceph - scalable distributed file system
 *
 * Copyright (C) 2004-2006 Sage Weil <sage@newdream.net>
 *
 * This is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1, as published by the Free Software
 * Foundation.  See file COPYING.
 *
 */

#include <sys/stat.h>
#include <iostream>
#include <string>
using namespace std;

#include "common/config.h"

#include "mon/MonMap.h"
#include "mon/MonClient.h"
#include "msg/SimpleMessenger.h"
#include "messages/MPing.h"

#include "common/Timer.h"
#include "global/global_init.h"
#include "common/ceph_argparse.h"

#ifndef DARWIN
#include <envz.h>
#endif // DARWIN

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

Messenger *messenger = 0;

Mutex lock("mylock");
Cond cond;

uint64_t received = 0;

class Admin : public Dispatcher {
public:
  Admin()
    : Dispatcher(g_ceph_context)
  {
  }
private:
  bool ms_dispatch(Message *m) {

    //cerr << "got ping from " << m->get_source() << std::endl;
    dout(0) << "got ping from " << m->get_source() << dendl;
    lock.Lock();
    ++received;
    cond.Signal();
    lock.Unlock();

    m->put();
    return true;
  }

  bool ms_handle_reset(Connection *con) { return false; }
  void ms_handle_remote_reset(Connection *con) {}

} dispatcher;

int main(int argc, const char **argv, const char *envp[]) {

  vector<const char*> args;
  argv_to_vec(argc, argv, args);
  env_to_vec(args);

  global_init(args, CEPH_ENTITY_TYPE_CLIENT, CODE_ENVIRONMENT_UTILITY, 0);
  common_init_finish(g_ceph_context);

  vec_to_argv(args, argc, argv);

  dout(0) << "i am mon " << args[0] << dendl;

  // get monmap
  MonClient mc(g_ceph_context);
  if (mc.build_initial_monmap() < 0)
    return -1;

  // start up network
  int whoami = mc.monmap.get_rank(args[0]);
  assert(whoami >= 0);
  ostringstream ss;
  ss << mc.monmap.get_addr(whoami);
  std::string sss(ss.str());
  g_ceph_context->_conf->set_val("public_addr", sss.c_str());
  g_ceph_context->_conf->apply_changes(NULL);
  SimpleMessenger *rank = new SimpleMessenger(g_ceph_context);
  int err = rank->bind(getpid());
  if (err < 0)
    return 1;

  // start monitor
  rank->register_entity(entity_name_t::MON(whoami));
  messenger = rank;
  messenger->set_default_send_priority(CEPH_MSG_PRIO_HIGH);
  messenger->add_dispatcher_head(&dispatcher);

  rank->start();

  int isend = 0;
  if (whoami == 0)
    isend = 100;

  lock.Lock();
  uint64_t sent = 0;
  while (1) {
    while (received + isend <= sent) {
      //cerr << "wait r " << received << " s " << sent << " is " << isend << std::endl;
      dout(0) << "wait r " << received << " s " << sent << " is " << isend << dendl;
      cond.Wait(lock);
    }

    int t = rand() % mc.get_num_mon();
    if (t == whoami)
      continue;

    if (rand() % 10 == 0) {
      //cerr << "mark_down " << t << std::endl;
      dout(0) << "mark_down " << t << dendl;
      messenger->mark_down(mc.get_mon_addr(t));
    }
    //cerr << "pinging " << t << std::endl;
    dout(0) << "pinging " << t << dendl;
    messenger->send_message(new MPing, mc.get_mon_inst(t));
    cerr << isend << "\t" << ++sent << "\t" << received << "\r";
  }
  lock.Unlock();

  // wait for messenger to finish
  rank->wait();

  return 0;
}

<|endoftext|>


<commit_before>#include <string.h>
#include "countTokens.h"
#include "misc.h"
#include "processTokens.h"
#include "yy.h"
#ifndef MODULE_FINDER
#include "chapel.tab.h"
#else
#include "modulefinder.tab.h"
#define countNewline()
#define countSingleLineComment(x)
#define countMultiLineComment(x)
#define countCommentLine()
#endif

static int stringBuffLen = 0;
static int stringLen = 0;
static char* stringBuffer = NULL;

static void newString(void) {
  stringLen = 0;
  if (stringBuffLen) {
    stringBuffer[stringLen] = '\0';
  }
}

static void addChar(char c) {
  if (stringLen+2 > stringBuffLen) {
    stringBuffLen = 2*(stringBuffLen + 1);
    stringBuffer = (char*)realloc(stringBuffer, stringBuffLen*sizeof(char));
  }
  stringBuffer[stringLen] = c;
  stringLen++;
  stringBuffer[stringLen] = '\0';
}

void processNewline(void) {
  chplLineno++;
  yylloc.first_column = yylloc.last_column = 0;
  yylloc.first_line = yylloc.last_line = chplLineno;
  countNewline();
}

char* eatStringLiteral(const char* startChar) {
  register int c;

  newString();
  while (1) {
    while ((c = getNextYYChar()) != *startChar && c != EOF) {
      if (*startChar == '\'' && c == '\"') {
        addChar('\\');
      }
    FORCE_NEXT:
      addChar(c);
      if (c == '\\') {
        c = getNextYYChar();
        if (c != EOF) {
          goto FORCE_NEXT;
        }
      }
    } /* eat up string */
    if (c == EOF) {
      yyerror("EOF in string");
    }
    break;
  }
  return stringBuffer;
}

void processSingleLineComment(void) {
  register int c;

  newString();
  countCommentLine();
  while (1) {
    while ( (c = getNextYYChar()) != '\n' && c != EOF ) {
      addChar(c);
    }    /* eat up text of comment */
    countSingleLineComment(stringBuffer);
    if (c != EOF) {
      processNewline();
    }
    break;
  }
}

void processMultiLineComment(void) {
  register int c;

  newString();
  countCommentLine();
  while (1) {
    while ((c = getNextYYChar()) != '*' && c != EOF ) {
      if (c == '\n') {
        countMultiLineComment(stringBuffer);
        processNewline();
        newString();
        countCommentLine();
      } else {
        addChar(c);
      }
    }    /* eat up text of comment */

    if ( c == '*' ) {
      while ( (c = getNextYYChar()) == '*' ) {
        addChar(c);
      }
      if ( c == '/' ) {
        countMultiLineComment(stringBuffer);
        newString();
        break;    /* found the end */
      } else if (c == '\n') {
        countMultiLineComment(stringBuffer);
        processNewline();
        newString();
        countCommentLine();
      }
    } else {      // c == EOF
      yyerror( "EOF in comment" );
      break;
    }
  }
}

void processWhitespace(const char* tabOrSpace) {
  // might eventually want to keep track of column numbers and do
  // something here
}

void processInvalidToken() {
  yyerror("Invalid token");
}
<commit_msg><commit_after>#include <string.h>
#include "countTokens.h"
#include "misc.h"
#include "processTokens.h"
#include "yy.h"
#ifndef MODULE_FINDER
#include "chapel.tab.h"
#else
#include "modulefinder.tab.h"
#define countNewline()
#define countSingleLineComment(x)
#define countMultiLineComment(x)
#define countCommentLine()
#endif

static int stringBuffLen = 0;
static int stringLen = 0;
static char* stringBuffer = NULL;

static void newString(void) {
  stringLen = 0;
  if (stringBuffLen) {
    stringBuffer[stringLen] = '\0';
  }
}

static void addChar(char c) {
  if (stringLen+2 > stringBuffLen) {
    stringBuffLen = 2*(stringBuffLen + 1);
    stringBuffer = (char*)realloc(stringBuffer, stringBuffLen*sizeof(char));
  }
  stringBuffer[stringLen] = c;
  stringLen++;
  stringBuffer[stringLen] = '\0';
}

void processNewline(void) {
  chplLineno++;
  yylloc.first_column = yylloc.last_column = 0;
  yylloc.first_line = yylloc.last_line = chplLineno;
  countNewline();
}

char* eatStringLiteral(const char* startChar) {
  register int c;

  newString();
  while (1) {
    while ((c = getNextYYChar()) != *startChar && c != EOF) {
      if (*startChar == '\'' && c == '\"') {
        addChar('\\');
      }
    FORCE_NEXT:
      addChar(c);
      if (c == '\\') {
        c = getNextYYChar();
        if (c != EOF) {
          goto FORCE_NEXT;
        }
      }
    } /* eat up string */
    if (c == EOF) {
      yyerror("EOF in string");
    }
    break;
  }
  return stringBuffer;
}

void processSingleLineComment(void) {
  register int c;

  newString();
  countCommentLine();
  while (1) {
    while ( (c = getNextYYChar()) != '\n' && c != EOF && c != 0 ) {
      addChar(c);
    }    /* eat up text of comment */
    countSingleLineComment(stringBuffer);
    if (c != EOF && c != 0) {
      processNewline();
    }
    break;
  }
}

void processMultiLineComment(void) {
  register int c;

  newString();
  countCommentLine();
  while (1) {
    while ((c = getNextYYChar()) != '*' && c != EOF ) {
      if (c == '\n') {
        countMultiLineComment(stringBuffer);
        processNewline();
        newString();
        countCommentLine();
      } else {
        addChar(c);
      }
    }    /* eat up text of comment */

    if ( c == '*' ) {
      while ( (c = getNextYYChar()) == '*' ) {
        addChar(c);
      }
      if ( c == '/' ) {
        countMultiLineComment(stringBuffer);
        newString();
        break;    /* found the end */
      } else if (c == '\n') {
        countMultiLineComment(stringBuffer);
        processNewline();
        newString();
        countCommentLine();
      }
    } else {      // c == EOF
      yyerror( "EOF in comment" );
      break;
    }
  }
}

void processWhitespace(const char* tabOrSpace) {
  // might eventually want to keep track of column numbers and do
  // something here
}

void processInvalidToken() {
  yyerror("Invalid token");
}
<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <memory>
#include <algorithm>

#include <sndfile.hh>

#define kiss_fft_scalar float
#include "kiss_fft.h"

int main(int argc, char *argv[])
{
    const int I = 2;
    const int D = 1;
    const int N = 256;
    const int M = I/D*N;

    if (argc != 2) {
        std::cerr << "Usage upsampling_algorithm_short_sequence <filename>\n";
        return -1;
    }

    const std::string infilename = argv[argc-1];
    const std::string resfilename = "res.wav";
    SndfileHandle  infile(infilename);
    SndfileHandle resfile(resfilename, SFM_WRITE, infile.format(), infile.channels(), infile.samplerate() * I/D);

    // Input data
    std::vector<kiss_fft_scalar> buffer(N);
    if (infile.read(buffer.data(), N) != N) {
        std::cerr << "Error reading " << N << " samples from " << infilename << ".\n";
    }

    // Kiss FFT configurations
    auto fwd_cfg = std::unique_ptr<std::remove_pointer<kiss_fft_cfg>::type, decltype(kiss_fft_free) *> {
        kiss_fft_alloc(N, 0, NULL, NULL),
        kiss_fft_free
    };

    auto inv_cfg = std::unique_ptr<std::remove_pointer<kiss_fft_cfg>::type, decltype(kiss_fft_free) *> {
        kiss_fft_alloc(M, 1, NULL, NULL),
        kiss_fft_free
    };

    if (fwd_cfg == nullptr || inv_cfg == nullptr) {
        std::cerr << "Error allocating Kiss FFT configurations.\n";
    }

    // FFT input/output buffers
    std::vector<kiss_fft_cpx> fwd_fft_in_buffer(N);
    std::vector<kiss_fft_cpx> fwd_fft_out_buffer(N);

    // IFFT input/output buffers
    std::vector<kiss_fft_cpx> bwd_fft_in_buffer(M);
    std::vector<kiss_fft_cpx> bwd_fft_out_buffer(M);

    // Create FFT input buffer
    for (int i=0; i < N; ++i) {
        fwd_fft_in_buffer[i].r = buffer[i];
        fwd_fft_in_buffer[i].i = 0.0;
        std::cout << i << " " << fwd_fft_in_buffer[i].r << " " << fwd_fft_in_buffer[i].i << "\n";
    }
    std::cout << "\n";

    // Forward N points FFT
    kiss_fft(fwd_cfg.get(), fwd_fft_in_buffer.data(), fwd_fft_out_buffer.data());
    for (int i=0; i < N; ++i) {
        std::cout << " FFT: " << i << " " << fwd_fft_out_buffer[i].r << " " << fwd_fft_out_buffer[i].i << "\n";
    }

    // Create IFFT input buffer
    for (int i=0; i < N/2; ++i) {
        bwd_fft_in_buffer[i].r = static_cast<kiss_fft_scalar>(I/D) * fwd_fft_out_buffer[i].r;
        bwd_fft_in_buffer[i].i = static_cast<kiss_fft_scalar>(I/D) * fwd_fft_out_buffer[i].i;
    }
    for (int i=N/2; i < M - N/2; ++i) {
        bwd_fft_in_buffer[i].r = static_cast<kiss_fft_scalar>(I/D) * 0.0;
        bwd_fft_in_buffer[i].i = static_cast<kiss_fft_scalar>(I/D) * 0.0;
    }
    for (int i=M - N/2; i < M; ++i) {
        bwd_fft_in_buffer[i].r = static_cast<kiss_fft_scalar>(I/D) * fwd_fft_out_buffer[i - N].r;
        bwd_fft_in_buffer[i].i = static_cast<kiss_fft_scalar>(I/D) * fwd_fft_out_buffer[i - N].i;
    }
    for (int i=0; i < M; ++i) {
        //std::cout << i << " " << bwd_fft_in_buffer[i].r << " " << bwd_fft_in_buffer[i].i << "\n";
    }

    // Backward M points IFFT
    kiss_fft(inv_cfg.get(), bwd_fft_in_buffer.data(), bwd_fft_out_buffer.data());
    for(int i=0; i < M; ++i) {
        //std::cout << "IFFT: " << i << ": " << bwd_fft_out_buffer[i].r << "\n";
    }

    kiss_fft_cleanup();
    return 0;
}
<commit_msg>Fix scaling factor in the ifft.<commit_after>#include <iostream>
#include <fstream>
#include <vector>
#include <memory>
#include <algorithm>

#include <sndfile.hh>

#define kiss_fft_scalar float
#include "kiss_fft.h"

// https://stackoverflow.com/a/2284805/496459
template <typename Stream>
void reopen(Stream& pStream, const char * pFile,
            std::ios_base::openmode pMode = std::ios_base::out)
{
    pStream.close();
    pStream.clear();
    pStream.open(pFile, pMode);
}

int main(int argc, char *argv[])
{
    const int I = 2;
    const int D = 1;
    const int N = 256;
    const int M = I/D*N;

    if (argc != 2) {
        std::cerr << "Usage upsampling_algorithm_short_sequence <filename>\n";
        return -1;
    }

    const std::string infilename = argv[argc-1];
    const std::string resfilename = "res.wav";
    SndfileHandle  infile(infilename);
    SndfileHandle resfile(resfilename, SFM_WRITE, infile.format(), infile.channels(), infile.samplerate() * I/D);

    // Input data
    std::vector<kiss_fft_scalar> buffer(N);
    if (infile.read(buffer.data(), N) != N) {
        std::cerr << "Error reading " << N << " samples from " << infilename << ".\n";
    }

    // Kiss FFT configurations
    auto fwd_cfg = std::unique_ptr<std::remove_pointer<kiss_fft_cfg>::type, decltype(kiss_fft_free) *> {
        kiss_fft_alloc(N, 0, NULL, NULL),
        kiss_fft_free
    };

    auto inv_cfg = std::unique_ptr<std::remove_pointer<kiss_fft_cfg>::type, decltype(kiss_fft_free) *> {
        kiss_fft_alloc(M, 1, NULL, NULL),
        kiss_fft_free
    };

    if (fwd_cfg == nullptr || inv_cfg == nullptr) {
        std::cerr << "Error allocating Kiss FFT configurations.\n";
    }

    // FFT input/output buffers
    std::vector<kiss_fft_cpx> fwd_fft_in_buffer(N);
    std::vector<kiss_fft_cpx> fwd_fft_out_buffer(N);

    // IFFT input/output buffers
    std::vector<kiss_fft_cpx> bwd_fft_in_buffer(M);
    std::vector<kiss_fft_cpx> bwd_fft_out_buffer(M);

    // Create FFT input buffer
    std::ofstream ofs("fft_input_buffer.asc");
    for (int i=0; i < N; ++i) {
        fwd_fft_in_buffer[i].r = buffer[i];
        fwd_fft_in_buffer[i].i = 0.0;
        ofs << i << " " << fwd_fft_in_buffer[i].r << " " << fwd_fft_in_buffer[i].i << "\n";
    }

    // Forward N points FFT
    reopen(ofs, "fft_output_buffer.asc");
    kiss_fft(fwd_cfg.get(), fwd_fft_in_buffer.data(), fwd_fft_out_buffer.data());
    for (int i=0; i < N; ++i) {
        ofs << i << " " << fwd_fft_out_buffer[i].r << " " << fwd_fft_out_buffer[i].i << "\n";
    }

    // Create IFFT input buffer
    reopen(ofs, "ifft_input_buffer.asc");
    for (int i=0; i < N/2; ++i) {
        bwd_fft_in_buffer[i].r = static_cast<kiss_fft_scalar>(I/D) * fwd_fft_out_buffer[i].r;
        bwd_fft_in_buffer[i].i = static_cast<kiss_fft_scalar>(I/D) * fwd_fft_out_buffer[i].i;
    }
    for (int i=N/2; i < M - N/2; ++i) {
        bwd_fft_in_buffer[i].r = static_cast<kiss_fft_scalar>(I/D) * 0.0;
        bwd_fft_in_buffer[i].i = static_cast<kiss_fft_scalar>(I/D) * 0.0;
    }
    for (int i=M - N/2; i < M; ++i) {
        bwd_fft_in_buffer[i].r = static_cast<kiss_fft_scalar>(I/D) * fwd_fft_out_buffer[i - N].r;
        bwd_fft_in_buffer[i].i = static_cast<kiss_fft_scalar>(I/D) * fwd_fft_out_buffer[i - N].i;
    }
    for (int i=0; i < M; ++i) {
        ofs << i << " " << bwd_fft_in_buffer[i].r << " " << bwd_fft_in_buffer[i].i << "\n";
    }

    // Backward M points IFFT
    reopen(ofs, "ifft_output_buffer.asc");
    kiss_fft(inv_cfg.get(), bwd_fft_in_buffer.data(), bwd_fft_out_buffer.data());
    for(int i=0; i < M; ++i) {
        bwd_fft_out_buffer[i].r = 1.0/M * bwd_fft_out_buffer[i].r;
        bwd_fft_out_buffer[i].i = 1.0/M * bwd_fft_out_buffer[i].i;
        ofs << i << " " << bwd_fft_out_buffer[i].r << " " << bwd_fft_out_buffer[i].i << "\n";
    }

    kiss_fft_cleanup();
    return 0;
}
<|endoftext|>


<commit_before>#include "tracker.h"

#include <QNetworkRequest>
#include <QNetworkReply>
#include <QUrl>
#include <QJsonObject>
#include <QJsonDocument>
#include <QTimer>

Tracker::Tracker() {
  QTimer::singleShot(0, this, SLOT(EnsureAccountIsSetUp()));
}

void Tracker::EnsureAccountIsSetUp() {
  if(!IsAccountSetUp()) {
    logger << "No account setup. Creating one for ye" << endl;
    CreateAndStoreAccount();
  } else {
    logger << "Account " << Username().toStdString() << " found" << endl;
  }
}

void Tracker::AddResult(GameMode mode, Outcome outcome, GoingOrder order, Class ownClass, Class opponentClass) {
  // TODO DISALLOW API CALL WHEN ANYTHING IS UNKNOWN
  logger << "GameMode " << mode <<
    " Outcome " << outcome <<
    " Order " << order <<
    " OwnCl " << ownClass <<
    " OppCl " << opponentClass << endl;

  QUrl url("http://webtracker.dev/results.json");
  url.setUserName(Username());
  url.setPassword(Password());

  QNetworkRequest request(url);
  request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

  QJsonObject result;
  result["coin"]     = (order == GOING_FIRST);
  result["hero"]     = CLASS_NAMES[ownClass];
  result["opponent"] = CLASS_NAMES[opponentClass];
  result["win"]      = (outcome == OUTCOME_VICTORY);
  result["mode"]     = MODE_NAMES[mode];

  QJsonObject params;
  params["result"] = result;

  QJsonDocument doc(params);
  QByteArray data = doc.toJson();
  QNetworkReply *reply = networkManager.post(request, data);
  connect(reply, SIGNAL(finished()), this, SLOT(AddResultHandleReply()));
}

void Tracker::AddResultHandleReply() {
  QNetworkReply *reply = static_cast<QNetworkReply *>(sender());
  if(reply->error() == QNetworkReply::NoError) {
    logger << "Adding of the result was a success!" << endl;
  } else {
    logger << "There was a problem adding the result. Code: " << reply->error() << endl;
  }
}

void Tracker::CreateAndStoreAccount() {
  QUrl url("http://webtracker.dev/users.json");
  QNetworkRequest request(url);
  QNetworkReply *reply = networkManager.post(request, "");
  connect(reply, SIGNAL(finished()), this, SLOT(CreateAndStoreAccountHandleReply()));
}

void Tracker::CreateAndStoreAccountHandleReply() {
  QNetworkReply *reply = static_cast<QNetworkReply *>(sender());
  if(reply->error() == QNetworkReply::NoError) {
    logger << "Account creation was successful!" << endl;

    QByteArray jsonData = reply->readAll();
    QJsonDocument doc = QJsonDocument::fromJson(jsonData);
    if(doc.isNull()) {
      logger << "Invalid data" << endl;
    } else {
      QJsonObject user = doc.object();
      logger << "Welcome " << user["username"].toString().toStdString() << endl;

      QSettings settings;
      settings.setValue("username", user["username"].toString());
      settings.setValue("password", user["password"].toString());
    }
  } else {
    logger << "There was a problem creating an account. Code: " << reply->error() << endl;
  }
}

QString Tracker::Username() {
  return settings.value("username").toString();
}

QString Tracker::Password() {
  return settings.value("password").toString();
}

void Tracker::SetUsername(const QString& username) {
  settings.setValue("username", username);
}

void Tracker::SetPassword(const QString& password) {
  settings.setValue("password", password);
}

bool Tracker::IsAccountSetUp() {
  return settings.contains("username") && settings.contains("password");
}
<commit_msg>add HTTP status code to log<commit_after>#include "tracker.h"

#include <QNetworkRequest>
#include <QNetworkReply>
#include <QUrl>
#include <QJsonObject>
#include <QJsonDocument>
#include <QTimer>

Tracker::Tracker() {
  QTimer::singleShot(0, this, SLOT(EnsureAccountIsSetUp()));
}

void Tracker::EnsureAccountIsSetUp() {
  if(!IsAccountSetUp()) {
    logger << "No account setup. Creating one for ye" << endl;
    CreateAndStoreAccount();
  } else {
    logger << "Account " << Username().toStdString() << " found" << endl;
  }
}

void Tracker::AddResult(GameMode mode, Outcome outcome, GoingOrder order, Class ownClass, Class opponentClass) {
  // TODO DISALLOW API CALL WHEN ANYTHING IS UNKNOWN
  logger << "GameMode " << mode <<
    " Outcome " << outcome <<
    " Order " << order <<
    " OwnCl " << ownClass <<
    " OppCl " << opponentClass << endl;

  QUrl url("http://webtracker.dev/results.json");
  url.setUserName(Username());
  url.setPassword(Password());

  QNetworkRequest request(url);
  request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

  QJsonObject result;
  result["coin"]     = (order == GOING_FIRST);
  result["hero"]     = CLASS_NAMES[ownClass];
  result["opponent"] = CLASS_NAMES[opponentClass];
  result["win"]      = (outcome == OUTCOME_VICTORY);
  result["mode"]     = MODE_NAMES[mode];

  QJsonObject params;
  params["result"] = result;

  QJsonDocument doc(params);
  QByteArray data = doc.toJson();
  QNetworkReply *reply = networkManager.post(request, data);
  connect(reply, SIGNAL(finished()), this, SLOT(AddResultHandleReply()));
}

void Tracker::AddResultHandleReply() {
  QNetworkReply *reply = static_cast<QNetworkReply *>(sender());
  if(reply->error() == QNetworkReply::NoError) {
    logger << "Adding of the result was a success!" << endl;
  } else {
    int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
    logger << "There was a problem adding the result. Error: " << reply->error() << " HTTP Status Code: " << statusCode << endl;
  }
}

void Tracker::CreateAndStoreAccount() {
  QUrl url("http://webtracker.dev/users.json");
  QNetworkRequest request(url);
  QNetworkReply *reply = networkManager.post(request, "");
  connect(reply, SIGNAL(finished()), this, SLOT(CreateAndStoreAccountHandleReply()));
}

void Tracker::CreateAndStoreAccountHandleReply() {
  QNetworkReply *reply = static_cast<QNetworkReply *>(sender());
  if(reply->error() == QNetworkReply::NoError) {
    logger << "Account creation was successful!" << endl;

    QByteArray jsonData = reply->readAll();
    QJsonDocument doc = QJsonDocument::fromJson(jsonData);
    if(doc.isNull()) {
      logger << "Invalid data" << endl;
    } else {
      QJsonObject user = doc.object();
      logger << "Welcome " << user["username"].toString().toStdString() << endl;

      QSettings settings;
      settings.setValue("username", user["username"].toString());
      settings.setValue("password", user["password"].toString());
    }
  } else {
    int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
    logger << "There was a problem creating an account. Error: " << reply->error() << " HTTP Status Code: " << statusCode << endl;
  }
}

QString Tracker::Username() {
  return settings.value("username").toString();
}

QString Tracker::Password() {
  return settings.value("password").toString();
}

void Tracker::SetUsername(const QString& username) {
  settings.setValue("username", username);
}

void Tracker::SetPassword(const QString& password) {
  settings.setValue("password", password);
}

bool Tracker::IsAccountSetUp() {
  return settings.contains("username") && settings.contains("password");
}
<|endoftext|>


<commit_before>/*
**  Copyright (C) 2012 Aldebaran Robotics
**  See COPYING for the license
*/
#include <boost/type_traits/is_signed.hpp>

#include <qitype/type.hpp>

namespace qi {

template<typename T> class TypeIntImpl:
  public TypeInt
{
public:
  typedef typename detail::TypeImplMethodsBySize<T>::type
   ImplType;
  virtual int64_t get(void* value) const
  {
    return *(T*)ImplType::Access::ptrFromStorage(&value);
  }
  virtual void set(void** storage, int64_t value)
  {
    *(T*)ImplType::Access::ptrFromStorage(storage) = (T)value;
  }
  virtual unsigned int size() const
  {
    return sizeof(T);
  }
  virtual bool isSigned() const
  {
    return boost::is_signed<T>::value;
  }
  _QI_BOUNCE_TYPE_METHODS(ImplType);
};

  template<typename T> class TypeBoolImpl:
    public TypeInt
  {
  public:
    typedef typename detail::TypeImplMethodsBySize<T>::type
     ImplType;
    virtual int64_t get(void* value) const
    {
      return *(T*)ImplType::Access::ptrFromStorage(&value);
    }
    virtual void set(void** storage, int64_t value)
    {
      *(T*)ImplType::Access::ptrFromStorage(storage) = (T)value;
    }
    virtual unsigned int size() const
    {
      return 0;
    }
    virtual bool isSigned() const
    {
      return 0;
    }
    _QI_BOUNCE_TYPE_METHODS(ImplType);
  };

// Force 64bit long
template<> class TypeIntImpl<long>: public TypeIntImpl<long long>{};
template<> class TypeIntImpl<unsigned long>: public TypeIntImpl<unsigned long long>{};

#define INTEGRAL_TYPE(t) \
static bool BOOST_PP_CAT(unused_ , __LINE__) = registerType(typeid(t), new TypeIntImpl<t>());

/** Integral types.
 * Since long is neither int32 nor uint32 on 32 bit platforms,
 * use all known native types instead of size/signedness explicit
 * types.
 */
INTEGRAL_TYPE(char);
INTEGRAL_TYPE(signed char);
INTEGRAL_TYPE(unsigned char);
INTEGRAL_TYPE(short);
INTEGRAL_TYPE(unsigned short);
INTEGRAL_TYPE(int);
INTEGRAL_TYPE(unsigned int);
INTEGRAL_TYPE(long);
INTEGRAL_TYPE(unsigned long);
INTEGRAL_TYPE(long long);
INTEGRAL_TYPE(unsigned long long);
}

QI_TYPE_REGISTER_CUSTOM(bool, qi::TypeBoolImpl<char>);

namespace qi {

template<typename T> class TypeFloatImpl: public TypeFloat
{
public:
  typedef typename detail::TypeImplMethodsBySize<T>::type
  ImplType;
  virtual double get(void* value) const
  {
    return *(T*)ImplType::Access::ptrFromStorage(&value);
  }
  virtual void set(void** storage, double value)
  {
    *(T*)ImplType::Access::ptrFromStorage(storage) = (T)value;
  }
  virtual unsigned int size() const
  {
    return sizeof(T);
  }
  _QI_BOUNCE_TYPE_METHODS(ImplType);
};

#define FLOAT_TYPE(t) \
static bool BOOST_PP_CAT(unused_ , __LINE__) = registerType(typeid(t), new TypeFloatImpl<t>());

FLOAT_TYPE(float);
FLOAT_TYPE(double);
}

<commit_msg>typeint: fix bool type support<commit_after>/*
**  Copyright (C) 2012 Aldebaran Robotics
**  See COPYING for the license
*/
#include <boost/type_traits/is_signed.hpp>

#include <qitype/type.hpp>

namespace qi {

template<typename T> class TypeIntImpl:
  public TypeInt
{
public:
  typedef typename detail::TypeImplMethodsBySize<T>::type
   ImplType;
  virtual int64_t get(void* value) const
  {
    return *(T*)ImplType::Access::ptrFromStorage(&value);
  }
  virtual void set(void** storage, int64_t value)
  {
    *(T*)ImplType::Access::ptrFromStorage(storage) = (T)value;
  }
  virtual unsigned int size() const
  {
    return sizeof(T);
  }
  virtual bool isSigned() const
  {
    return boost::is_signed<T>::value;
  }
  _QI_BOUNCE_TYPE_METHODS(ImplType);
};

  template<typename T> class TypeBoolImpl:
    public TypeInt
  {
  public:
    typedef typename detail::TypeImplMethodsBySize<T>::type
     ImplType;
    virtual int64_t get(void* value) const
    {
      return *(T*)ImplType::Access::ptrFromStorage(&value);
    }
    virtual void set(void** storage, int64_t value)
    {
      *(T*)ImplType::Access::ptrFromStorage(storage) = (T)value;
    }
    virtual unsigned int size() const
    {
      return 0;
    }
    virtual bool isSigned() const
    {
      return 0;
    }
    _QI_BOUNCE_TYPE_METHODS(ImplType);
  };

// Force 64bit long
template<> class TypeIntImpl<long>: public TypeIntImpl<long long>{};
template<> class TypeIntImpl<unsigned long>: public TypeIntImpl<unsigned long long>{};

#define INTEGRAL_TYPE(t) \
static bool BOOST_PP_CAT(unused_ , __LINE__) = registerType(typeid(t), new TypeIntImpl<t>());

/** Integral types.
 * Since long is neither int32 nor uint32 on 32 bit platforms,
 * use all known native types instead of size/signedness explicit
 * types.
 */
INTEGRAL_TYPE(char);
INTEGRAL_TYPE(signed char);
INTEGRAL_TYPE(unsigned char);
INTEGRAL_TYPE(short);
INTEGRAL_TYPE(unsigned short);
INTEGRAL_TYPE(int);
INTEGRAL_TYPE(unsigned int);
INTEGRAL_TYPE(long);
INTEGRAL_TYPE(unsigned long);
INTEGRAL_TYPE(long long);
INTEGRAL_TYPE(unsigned long long);
}

QI_TYPE_REGISTER_CUSTOM(bool, qi::TypeBoolImpl<bool>);

namespace qi {

template<typename T> class TypeFloatImpl: public TypeFloat
{
public:
  typedef typename detail::TypeImplMethodsBySize<T>::type
  ImplType;
  virtual double get(void* value) const
  {
    return *(T*)ImplType::Access::ptrFromStorage(&value);
  }
  virtual void set(void** storage, double value)
  {
    *(T*)ImplType::Access::ptrFromStorage(storage) = (T)value;
  }
  virtual unsigned int size() const
  {
    return sizeof(T);
  }
  _QI_BOUNCE_TYPE_METHODS(ImplType);
};

#define FLOAT_TYPE(t) \
static bool BOOST_PP_CAT(unused_ , __LINE__) = registerType(typeid(t), new TypeFloatImpl<t>());

FLOAT_TYPE(float);
FLOAT_TYPE(double);
}

<|endoftext|>


<commit_before>#include <cstdio>
#include <algorithm>
#include <string>
#include <map>
#include <cstdlib>
#include <iostream>
#include <cstring>
using namespace std;

map <string ,int> dict;
bool end=false;
//debug
#ifdef LOCAL
#define fp stdin
#else
FILE *fp;
#endif

char last=0;
char ch;
string getword(){

	string s;

	if (last){
		s.push_back(last);
		last=0;
	}

	while((ch=getc(fp))!=EOF){
		//printf("is :%c\n",ch);
		if(ch=='-'){

			if((ch=getc(fp))=='\n'){
				continue;
			}else{
				last=ch;
				break;
			}

		}

		if(ch>='A'&&ch<='Z' || ch>='a'&&ch<='z')
			s.push_back(ch);
		else
			break;

	}

	if(ch==EOF) end=true;

	transform(s.begin(), s.end(), s.begin(), (int (*)(int))tolower);
	return s;
}
void printdict(){
	map <string, int>::iterator dit;
	 for ( dit = dict.begin( ); dit != dict.end( ); dit++ ){
	 	cout<<dit->first<<"="<<DIT->second<<endl;
	 }
}
int main(int argc, char const *argv[])
{
	#ifndef LOCAL
	fp=fopen("case1.in","r");
	#else
	printf("used LOCAL");
	#endif
	string word;
	while(!end){
		word=getword();
		if(!dict.count(word)) dict[word]=0;
		else{
			dict[word]++;
		}
		cout<<word<<endl;
	}
	printdict();

	return 0;
}

<commit_msg>update uoj1109<commit_after>#include <cstdio>
#include <algorithm>
#include <string>
#include <map>
#include <cstdlib>
#include <iostream>
#include <cstring>
using namespace std;

map <string ,int> dict;
bool end=false;
//debug
#ifdef LOCAL
#define fp stdin
#else
FILE *fp;
#endif

char last=0;
char ch;
string getword(){

	string s;

	if (last){
		s.push_back(last);
		last=0;
	}

	while((ch=getc(fp))!=EOF){
		//printf("is :%c\n",ch);
		if(ch=='-'){

			if((ch=getc(fp))=='\n'){
				continue;
			}else{
				last=ch;
				break;
			}

		}

		if(ch>='A'&&ch<='Z' || ch>='a'&&ch<='z')
			s.push_back(ch);
		else
			break;

	}

	if(ch==EOF) end=true;

	transform(s.begin(), s.end(), s.begin(), (int (*)(int))tolower);
	return s;
}
void printdict(){
	map <string, int>::iterator dit;
	 for ( dit = dict.begin( ); dit != dict.end( ); dit++ ){
	 	cout<<dit->first<<"="<<dit->second<<endl;
	 }
}
int main(int argc, char const *argv[])
{
	#ifndef LOCAL
	fp=fopen("case1.in","r");
	#else
	printf("used LOCAL");
	#endif
	string word;
	while(!end){
		word=getword();
		if(!dict.count(word)) dict[word]=0;
		else{
			dict[word]++;
		}
		cout<<word<<endl;
	}
	printdict();

	return 0;
}

<|endoftext|>


<commit_before>#pragma once

#include <utility>
#include <memory>
#include <string>
#include <uv.h>
#include "resource.hpp"

namespace uvw {

namespace details {

template<typename T> struct IsFunc: std::false_type { };
template<typename R, typename... A> struct IsFunc<R(A...)>: std::true_type { };

}

class SharedLib final {
    explicit SharedLib(std::shared_ptr<Loop> ref, std::string filename) noexcept
        : pLoop{std::move(ref)},
          lib{}
    {
        opened = (0 == uv_dlopen(filename.data(), &lib));
    }

public:
    template<typename... Args>
    static std::shared_ptr<SharedLib> create(Args&&... args) noexcept {
        return std::shared_ptr<SharedLib>{new SharedLib{std::forward<Args>(args)...}};
    }

    SharedLib(const SharedLib &) = delete;
    SharedLib(SharedLib &&) = delete;

    ~SharedLib() noexcept {
        uv_dlclose(&lib);
    }

    SharedLib& operator=(const SharedLib &) = delete;
    SharedLib& operator=(SharedLib &&) = delete;

    explicit operator bool() const noexcept { return !opened; }

    template<typename F>
    F * sym(std::string name) {
        static_assert(details::IsFunc<F>::value, "!");
        F *func;
        auto err = uv_dlsym(&lib, name.data(), reinterpret_cast<void**>(&func));
        if(err) { func = nullptr; }
        return func;
    }

    const char * error() const noexcept {
        return uv_dlerror(&lib);
    }

    Loop& loop() const noexcept { return *pLoop; }

private:
    std::shared_ptr<Loop> pLoop;
    uv_lib_t lib;
    bool opened;
};

}
<commit_msg>clean up<commit_after>#pragma once

#include <utility>
#include <memory>
#include <string>
#include <uv.h>

namespace uvw {

namespace details {

template<typename T> struct IsFunc: std::false_type { };
template<typename R, typename... A> struct IsFunc<R(A...)>: std::true_type { };

}

class SharedLib final {
    explicit SharedLib(std::shared_ptr<Loop> ref, std::string filename) noexcept
        : pLoop{std::move(ref)},
          lib{}
    {
        opened = (0 == uv_dlopen(filename.data(), &lib));
    }

public:
    template<typename... Args>
    static std::shared_ptr<SharedLib> create(Args&&... args) noexcept {
        return std::shared_ptr<SharedLib>{new SharedLib{std::forward<Args>(args)...}};
    }

    SharedLib(const SharedLib &) = delete;
    SharedLib(SharedLib &&) = delete;

    ~SharedLib() noexcept {
        uv_dlclose(&lib);
    }

    SharedLib& operator=(const SharedLib &) = delete;
    SharedLib& operator=(SharedLib &&) = delete;

    explicit operator bool() const noexcept { return !opened; }

    template<typename F>
    F * sym(std::string name) {
        static_assert(details::IsFunc<F>::value, "!");
        F *func;
        auto err = uv_dlsym(&lib, name.data(), reinterpret_cast<void**>(&func));
        if(err) { func = nullptr; }
        return func;
    }

    const char * error() const noexcept {
        return uv_dlerror(&lib);
    }

    Loop& loop() const noexcept { return *pLoop; }

private:
    std::shared_ptr<Loop> pLoop;
    uv_lib_t lib;
    bool opened;
};

}
<|endoftext|>


<commit_before>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>

#include "version.h"

// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("HoboNickels");

// Client version number
#define CLIENT_VERSION_SUFFIX   "-hobo"

// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
//   generated by the build environment, possibly containing the output
//   of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
//   be defined (automatically using the export-subst git attribute), and
//   GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
//   * if BUILD_DESC is defined, use that literally (output of git-describe)
//   * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
//   * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added

// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#    include "build.h"
#endif

// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
c722db8
#    define GIT_COMMIT_ID "c722bd8"

#    define GIT_COMMIT_DATE "Sun Feb 09 14:18:00 2014"
#endif

#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit

#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"

#ifndef BUILD_DESC
#    ifdef GIT_COMMIT_ID
#        define BUILD_DESC BUILD_DESC_FROM_COMMIT(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD, GIT_COMMIT_ID)
#    else
#        define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD)
#    endif
#endif

#ifndef BUILD_DATE
#    ifdef GIT_COMMIT_DATE
#        define BUILD_DATE GIT_COMMIT_DATE
#    else
#        define BUILD_DATE __DATE__ ", " __TIME__
#    endif
#endif

const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<commit_msg>Removed accidental gitid paste<commit_after>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>

#include "version.h"

// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("HoboNickels");

// Client version number
#define CLIENT_VERSION_SUFFIX   "-hobo"

// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
//   generated by the build environment, possibly containing the output
//   of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
//   be defined (automatically using the export-subst git attribute), and
//   GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
//   * if BUILD_DESC is defined, use that literally (output of git-describe)
//   * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
//   * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added

// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#    include "build.h"
#endif

// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE

#    define GIT_COMMIT_ID "c722bd8"

#    define GIT_COMMIT_DATE "Sun Feb 09 14:18:00 2014"
#endif

#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit

#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"

#ifndef BUILD_DESC
#    ifdef GIT_COMMIT_ID
#        define BUILD_DESC BUILD_DESC_FROM_COMMIT(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD, GIT_COMMIT_ID)
#    else
#        define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD)
#    endif
#endif

#ifndef BUILD_DATE
#    ifdef GIT_COMMIT_DATE
#        define BUILD_DATE GIT_COMMIT_DATE
#    else
#        define BUILD_DATE __DATE__ ", " __TIME__
#    endif
#endif

const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<|endoftext|>