text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE123_Write_What_Where_Condition__listen_socket_53c.c
Label Definition File: CWE123_Write_What_Where_Condition.label.xml
Template File: sources-sink-53c.tmpl.c
*/
/*
 * @description
 * CWE: 123 Write-What-Where Condition
 * BadSource: listen_socket Overwrite linked list pointers using a listen socket (server side)
 * GoodSource: Don't overwrite linked list pointers
 * Sink:
 *    BadSink : Remove element from list
 * Flow Variant: 53 Data flow: data passed as an argument from one function through two others to a fourth; all four functions are in different source files
 *
 * */

#include "std_testcase.h"

typedef struct _linkedList
{
    struct _linkedList *next;
    struct _linkedList *prev;
} linkedList;

typedef struct _badStruct
{
    linkedList list;
} badStruct;

static linkedList *linkedListPrev, *linkedListNext;

#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#include <direct.h>
#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */
#define CLOSE_SOCKET closesocket
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define CLOSE_SOCKET close
#define SOCKET int
#endif

#define TCP_PORT 27015
#define LISTEN_BACKLOG 5

/* all the sinks are the same, we just want to know where the hit originated if a tool flags one */

#ifndef OMITBAD

/* bad function declaration */
void CWE123_Write_What_Where_Condition__listen_socket_53d_badSink(badStruct data);

void CWE123_Write_What_Where_Condition__listen_socket_53c_badSink(badStruct data)
{
    CWE123_Write_What_Where_Condition__listen_socket_53d_badSink(data);
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* good function declaration */
void CWE123_Write_What_Where_Condition__listen_socket_53d_goodG2BSink(badStruct data);

/* goodG2B uses the GoodSource with the BadSink */
void CWE123_Write_What_Where_Condition__listen_socket_53c_goodG2BSink(badStruct data)
{
    CWE123_Write_What_Where_Condition__listen_socket_53d_goodG2BSink(data);
}

#endif /* OMITGOOD */


text:
<!DOCTYPE html>
<html>

<head>
  <base href="/">
  <title>ngRap</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <!-- Local bootstrap CSS & JS -->
  <link rel="stylesheet" media="screen" href="node_modules/bootstrap/dist/css/bootstrap.min.css">
  <link rel="stylesheet" media="screen" href="node_modules/font-awesome/css/font-awesome.css">
  <link rel="stylesheet" media="screen" href="src/simple-line-icons.css">
  <link rel="stylesheet" media="screen" href="src/app.css">
  <!-- 1. Load libraries -->
  <!-- Polyfill(s) for older browsers -->
  <script src="node_modules/core-js/client/shim.min.js"></script>
  <script src="node_modules/zone.js/dist/zone.js"></script>
  <script src="node_modules/reflect-metadata/Reflect.js"></script>
  <script src="node_modules/systemjs/dist/system.src.js"></script>
  <!-- 2. Configure SystemJS -->
  <script src="systemjs.config.js"></script>
  <script>
      System.import('app').catch(function(err){
         console.error(err);
        });
    </script>
</head>
<!-- 3. Display the application -->

<body>
  <app></app>
</body>

</html>

redpajama_set_name: RedPajamaGithub


text:
.class Landroid/accounts/AccountManager$2;
.super Landroid/accounts/AccountManager$Future2Task;
.source "AccountManager.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Landroid/accounts/AccountManager;->hasFeatures(Landroid/accounts/Account;[Ljava/lang/String;Landroid/accounts/AccountManagerCallback;Landroid/os/Handler;)Landroid/accounts/AccountManagerFuture;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "Landroid/accounts/AccountManager$Future2Task",
        "<",
        "Ljava/lang/Boolean;",
        ">;"
    }
.end annotation

# instance fields
.field final synthetic this$0:Landroid/accounts/AccountManager;

.field final synthetic val$account:Landroid/accounts/Account;

.field final synthetic val$features:[Ljava/lang/String;

# direct methods
.method constructor <init>(Landroid/accounts/AccountManager;Landroid/os/Handler;Landroid/accounts/AccountManagerCallback;Landroid/accounts/Account;[Ljava/lang/String;)V
    .locals 0
    .parameter
    .parameter "x0"
    .parameter
    .parameter
    .parameter

    .prologue
    .line 484
    .local p3, x1:Landroid/accounts/AccountManagerCallback;,"Landroid/accounts/AccountManagerCallback<Ljava/lang/Boolean;>;"
    iput-object p1, p0, Landroid/accounts/AccountManager$2;->this$0:Landroid/accounts/AccountManager;

    iput-object p4, p0, Landroid/accounts/AccountManager$2;->val$account:Landroid/accounts/Account;

    iput-object p5, p0, Landroid/accounts/AccountManager$2;->val$features:[Ljava/lang/String;

    invoke-direct {p0, p1, p2, p3}, Landroid/accounts/AccountManager$Future2Task;-><init>(Landroid/accounts/AccountManager;Landroid/os/Handler;Landroid/accounts/AccountManagerCallback;)V

    return-void
.end method

# virtual methods
.method public bundleToResult(Landroid/os/Bundle;)Ljava/lang/Boolean;
    .locals 2
    .parameter "bundle"
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/accounts/AuthenticatorException;
        }
    .end annotation

    .prologue
    .line 489
    const-string v0, "booleanResult"

    invoke-virtual {p1, v0}, Landroid/os/Bundle;->containsKey(Ljava/lang/String;)Z

    move-result v0

    if-nez v0, :cond_0

    .line 490
    new-instance v0, Landroid/accounts/AuthenticatorException;

    const-string/jumbo v1, "no result in response"

    invoke-direct {v0, v1}, Landroid/accounts/AuthenticatorException;-><init>(Ljava/lang/String;)V

    throw v0

    .line 492
    :cond_0
    const-string v0, "booleanResult"

    invoke-virtual {p1, v0}, Landroid/os/Bundle;->getBoolean(Ljava/lang/String;)Z

    move-result v0

    invoke-static {v0}, Ljava/lang/Boolean;->valueOf(Z)Ljava/lang/Boolean;

    move-result-object v0

    return-object v0
.end method

.method public bridge synthetic bundleToResult(Landroid/os/Bundle;)Ljava/lang/Object;
    .locals 1
    .parameter "x0"
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/accounts/AuthenticatorException;
        }
    .end annotation

    .prologue
    .line 484
    invoke-virtual {p0, p1}, Landroid/accounts/AccountManager$2;->bundleToResult(Landroid/os/Bundle;)Ljava/lang/Boolean;

    move-result-object v0

    return-object v0
.end method

.method public doWork()V
    .locals 4
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation

    .prologue
    .line 486
    iget-object v0, p0, Landroid/accounts/AccountManager$2;->this$0:Landroid/accounts/AccountManager;

    #getter for: Landroid/accounts/AccountManager;->mService:Landroid/accounts/IAccountManager;
    invoke-static {v0}, Landroid/accounts/AccountManager;->access$000(Landroid/accounts/AccountManager;)Landroid/accounts/IAccountManager;

    move-result-object v0

    iget-object v1, p0, Landroid/accounts/AccountManager$BaseFutureTask;->mResponse:Landroid/accounts/IAccountManagerResponse;

    iget-object v2, p0, Landroid/accounts/AccountManager$2;->val$account:Landroid/accounts/Account;

    iget-object v3, p0, Landroid/accounts/AccountManager$2;->val$features:[Ljava/lang/String;

    invoke-interface {v0, v1, v2, v3}, Landroid/accounts/IAccountManager;->hasFeatures(Landroid/accounts/IAccountManagerResponse;Landroid/accounts/Account;[Ljava/lang/String;)V

    .line 487
    return-void
.end method


text:
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using ICSharpCode.NRefactory;
using OmniSharp.AutoComplete;
using OmniSharp.Parser;
using OmniSharp.Configuration;

namespace OmniSharp.Tests.AutoComplete
{
    public class CompletionsSpecBase
    {
        private readonly FakeSolution _solution;

        public CompletionsSpecBase()
        {
            _solution = new FakeSolution();
        }

        public IEnumerable<CompletionData> GetCompletions(string editorText, bool includeImportableTypes)
        {
            int cursorOffset = editorText.IndexOf("$", StringComparison.Ordinal);
            if (cursorOffset == -1)
                throw new ArgumentException("Editor text should contain a $");

            TextLocation cursorPosition = TestHelpers.GetLineAndColumnFromIndex(editorText, cursorOffset);
            string partialWord = GetPartialWord(editorText);
            editorText = editorText.Replace("$", "");

            var project = new FakeProject();
            project.AddFile(editorText);
            _solution.Projects.Add(project);
            var provider = new AutoCompleteHandler(_solution, new BufferParser(_solution), new Logger(Verbosity.Quiet), new OmniSharpConfiguration());
            var request = new AutoCompleteRequest
            {
                FileName = "myfile",
                WordToComplete = partialWord,
                Buffer = editorText,
                Line = cursorPosition.Line,
                Column = cursorPosition.Column,
                WantDocumentationForEveryCompletionResult = false,
                WantImportableTypes = includeImportableTypes,
                WantMethodHeader = true,
                WantReturnType = true,
                WantSnippet = true
            };

            return provider.CreateProvider(request);
        }

        private static string GetPartialWord(string editorText)
        {
            MatchCollection matches = Regex.Matches(editorText, @"([a-zA-Z0-9_]*)\$");
            return matches[0].Groups[1].ToString();
        }
    }
}


text:
#include "db/v4/PwEntryV4.h"
#include "util/Util.h"
#include "db/v4/PwMetaV4.h"
#include "db/v4/PwDatabaseV4.h"
#include "db/v4/PwStreamUtilsV4.h"

// Standard entry fields
const static QString TITLE = QString("Title");
const static QString USERNAME = QString("UserName");
const static QString PASSWORD = QString("Password");
const static QString URL = QString("URL");
const static QString NOTES = QString("Notes");

PwField::PwField(QObject* parent) : QObject(parent),
        _name(""), _value(""), _isProtected(false) {
    // left empty
}

PwField::PwField(QObject* parent, const QString& name, const QString& value, const bool isProtected) : QObject(parent),
        _name(Util::deepCopy(name)), _value(Util::deepCopy(value)), _isProtected(isProtected) {
    // left empty
}

PwField::~PwField() {
    clear();
}

void PwField::clear() {
    Util::safeClear(_name);
    Util::safeClear(_value);
    _isProtected = false;
}

PwField* PwField::clone() const {
    PwField* copy = new PwField(this->parent(), _name, _value, _isProtected);
    return copy;
}

QString PwField::toString() const {
    return (_isProtected ? "<protected> " : "<not protected> ") + _name + " = " + _value;
}

bool PwField::matchesQuery(const QString& query) const {
    return getName().contains(query, Qt::CaseInsensitive) ||
            getValue().contains(query, Qt::CaseInsensitive);
}

void PwField::setName(const QString& name) {
    if (_name != name) {
        _name = Util::deepCopy(name);
        emit nameChanged(_name);
    }
}

void PwField::setValue(const QString& value) {
    if (_value != value) {
        _value = Util::deepCopy(value);
        emit valueChanged(_value);
    }
}
void PwField::setProtected(const bool isProtected) {
    if (_isProtected != isProtected) {
        _isProtected = isProtected;
        emit protectedChanged(isProtected);
    }
}

bool PwField::isStandardField() const {
    return isStandardName(_name);
}

bool PwField::isStandardName(const QString& name) {
    return (name == TITLE) || (name == USERNAME) || (name == PASSWORD) || (name == URL) || (name == NOTES);
}

/**
 * Sets field's in memory protection flag to that specified in Meta's properties.
 * Only applies for standard fields, does nothing for the others.
 */
void PwField::updateProtectionFlag(const PwMetaV4& meta) {
    const MemoryProtection* mp = meta.getMemoryProtection();
    if (_name == TITLE) {
        setProtected(mp->isProtectTitle());
    } else if (_name == USERNAME) {
        setProtected(mp->isProtectUserName());
    } else if (_name == PASSWORD) {
        setProtected(mp->isProtectPassword());
    } else if (_name == URL) {
        setProtected(mp->isProtectUrl());
    } else if (_name == NOTES) {
        setProtected(mp->isProtectNotes());
    }
}

ErrorCodesV4::ErrorCode PwField::readFromStream(QXmlStreamReader& xml, Salsa20& salsa20) {
    Q_ASSERT(XML_STRING == xml.name());

    clear();

    QString key, value;
    bool protect = false;

    QStringRef tagName = xml.name();
    while (!xml.hasError() && !(xml.isEndElement() && (tagName == XML_STRING))) {
        xml.readNext();
        tagName = xml.name();
        if (xml.isStartElement()) {
            if (tagName == XML_KEY) {
                key = PwStreamUtilsV4::readString(xml);
            } else if (tagName == XML_VALUE) {
                if (xml.attributes().value(XML_PROTECTED) == XML_TRUE) {
                    // the value is encrypted, need to decrypt it first
                    protect = true;
                    QByteArray valueBytes = PwStreamUtilsV4::readBase64(xml);
                    salsa20.xorWithNextBytes(valueBytes);
                    value = QString::fromUtf8(valueBytes, valueBytes.length());
                } else {
                    // simple plain-text value
                    protect = false;
                    value = PwStreamUtilsV4::readString(xml);
                }
            } else {
                LOG("unknown tag in PwField::readFromStream(): %s", tagName.toUtf8().constData());
                PwStreamUtilsV4::readUnknown(xml);
                return ErrorCodesV4::XML_ENTRY_FIELD_PARSING_ERROR_TAG;
            }
        }
    }
    if (xml.hasError())
        return ErrorCodesV4::XML_ENTRY_FIELD_PARSING_ERROR_GENERIC;

    // Even if either XML_KEY or XML_VALUE were missing in the stream, (re)init the field anyway
    setName(key);
    setValue(value);
    setProtected(protect);

    return ErrorCodesV4::SUCCESS;
}

void PwField::writeToStream(QXmlStreamWriter& xml, Salsa20& salsa20) const {
    xml.writeStartElement(XML_STRING);
    PwStreamUtilsV4::writeString(xml, XML_KEY, getName());
    if (isProtected()) {
        xml.writeStartElement(XML_VALUE);
        xml.writeAttribute(XML_PROTECTED, XML_TRUE);

        QByteArray encValue = getValue().toUtf8();
        salsa20.xorWithNextBytes(encValue);
        xml.writeCharacters(encValue.toBase64());
        xml.writeEndElement(); // XML_VALUE
    } else {
        PwStreamUtilsV4::writeString(xml, XML_VALUE, getValue());
    }
    xml.writeEndElement(); // XML_STRING
}

/**************************/
PwAutoType::PwAutoType() {
    clear();
}

PwAutoType::PwAutoType(const PwAutoType& original) :
    _enabled(original._enabled),
    _obfuscationType(original._obfuscationType),
    _defaultSequence(Util::deepCopy(original._defaultSequence)), // this is subject to safeClear(), so need a deep copy
    _associations(original._associations) { // a shallow copy, since we don't safeClear this list

}

PwAutoType::~PwAutoType() {
    clear();
}

void PwAutoType::clear() {
    _enabled = true;
    _obfuscationType = 0;
    Util::safeClear(_defaultSequence);
    _associations.clear();
}

ErrorCodesV4::ErrorCode PwAutoType::readFromStream(QXmlStreamReader& xml) {
    Q_ASSERT(XML_AUTO_TYPE == xml.name());

    clear();

    QString key, value;
    ErrorCodesV4::ErrorCode err;

    QStringRef tagName = xml.name();
    while (!xml.hasError() && !(xml.isEndElement() && (tagName == XML_AUTO_TYPE))) {
        xml.readNext();
        tagName = xml.name();
        if (xml.isStartElement()) {
            if (tagName == XML_AUTO_TYPE_ENABLED) {
                _enabled = PwStreamUtilsV4::readBool(xml, true);
            } else if (tagName == XML_AUTO_TYPE_OBFUSCATION) {
                _obfuscationType = PwStreamUtilsV4::readUInt32(xml, 0);
            } else if (tagName == XML_AUTO_TYPE_DEFAULT_SEQUENCE) {
                _defaultSequence = Util::deepCopy(PwStreamUtilsV4::readString(xml));
            } else if (tagName == XML_AUTO_TYPE_ITEM) {
                err = readAssociation(xml);
                if (err != ErrorCodesV4::SUCCESS)
                    return err;
            } else {
                LOG("unknown tag in PwAutoType: %s", tagName.toUtf8().constData());
                PwStreamUtilsV4::readUnknown(xml);
                return ErrorCodesV4::XML_ENTRY_AUTO_TYPE_PARSING_ERROR_TAG;
            }
        }
    }
    if (xml.hasError())
        return ErrorCodesV4::XML_ENTRY_AUTO_TYPE_PARSING_ERROR_GENERIC;

    return ErrorCodesV4::SUCCESS;
}

ErrorCodesV4::ErrorCode PwAutoType::readAssociation(QXmlStreamReader& xml) {
    Q_ASSERT(XML_AUTO_TYPE_ITEM == xml.name());

    QString window, sequence;
    QStringRef tagName = xml.name();

    while (!xml.hasError() && !(xml.isEndElement() && (tagName == XML_AUTO_TYPE_ITEM))) {
        xml.readNext();
        tagName = xml.name();
        if (xml.isStartElement()) {
            if (tagName == XML_AUTO_TYPE_WINDOW) {
                window = PwStreamUtilsV4::readString(xml);
            } else if (tagName == XML_AUTO_TYPE_KEYSTROKE_SEQUENCE) {
                sequence = PwStreamUtilsV4::readString(xml);
            } else {
                LOG("unknown tag in PwAutoType/association: %s", tagName.toUtf8().constData());
                PwStreamUtilsV4::readUnknown(xml);
                return ErrorCodesV4::XML_ENTRY_AUTO_TYPE_ASSOCIATION_PARSING_ERROR_TAG;
            }
        }
    }
    if (xml.hasError())
        return ErrorCodesV4::XML_ENTRY_AUTO_TYPE_ASSOCIATION_PARSING_ERROR_GENERIC;

    _associations.append(QStringPair(window, sequence));
    return ErrorCodesV4::SUCCESS;
}

void PwAutoType::writeToStream(QXmlStreamWriter& xml) const {
    xml.writeStartElement(XML_AUTO_TYPE);
    PwStreamUtilsV4::writeBool(xml, XML_AUTO_TYPE_ENABLED, _enabled);
    PwStreamUtilsV4::writeUInt32(xml, XML_AUTO_TYPE_OBFUSCATION, _obfuscationType);
    if (!_defaultSequence.isEmpty())
        PwStreamUtilsV4::writeString(xml, XML_AUTO_TYPE_DEFAULT_SEQUENCE, _defaultSequence);

    for (int i = 0; i < _associations.size(); i++) {
        QPair<QString, QString> item = _associations.at(i);
        xml.writeStartElement(XML_AUTO_TYPE_ITEM);
        PwStreamUtilsV4::writeString(xml, XML_AUTO_TYPE_WINDOW, item.first);
        PwStreamUtilsV4::writeString(xml, XML_AUTO_TYPE_KEYSTROKE_SEQUENCE, item.second);
        xml.writeEndElement(); // XML_AUTO_TYPE_ITEM
    }
    xml.writeEndElement(); // XML_AUTO_TYPE
}

/**************************/

PwEntryV4::PwEntryV4(QObject* parent) : PwEntry(parent) {
    // without setParent() the app crashes with repeated freeing of free memory
    _extraFieldsDataModel.setParent(this);
    _historyDataModel.setParent(this);

    clear();
}

PwEntryV4::~PwEntryV4() {
    clear();
}

void PwEntryV4::clear() {
    _customIconUuid.clear();
    _autoType.clear();
    setUsageCount(0);
    setLocationChangedTime(QDateTime::currentDateTime());
    Util::safeClear(_foregroundColor);
    Util::safeClear(_backgroundColor);
    Util::safeClear(_overrideUrl);
    Util::safeClear(_tags);

    _historyDataModel.clear(); // deletes owned objects
    emit historySizeChanged(0);

    _extraFieldsDataModel.clear(); // deletes owned objects
    emit extraSizeChanged(0);

    qDeleteAll(fields);
    fields.clear();
    PwEntry::clear();
}

/** Updates last access timestamp to current time and increases usage counter */
void PwEntryV4::registerAccessEvent() {
    PwEntry::registerAccessEvent();
    setUsageCount(getUsageCount() + 1);
}

/** Search helper. Returns true if any of the fields contain the query string. */
bool PwEntryV4::matchesQuery(const QString& query) const {
    if (PwEntry::matchesQuery(query))
        return true;

    for (int i = 0; i < _extraFieldsDataModel.size(); i++) {
        if (_extraFieldsDataModel.value(i)->matchesQuery(query))
            return true;
    }
    return false;
}

void PwEntryV4::addField(PwField* field) {
    fields.append(field);
    if (!field->isStandardField()) {
        // both fields and _extraFieldsDataModel contain pointer to the same PwField instance
        _extraFieldsDataModel.append(field); // takes ownership, if not already set
        emit extraSizeChanged(_extraFieldsDataModel.size());
    }
}

PwField* PwEntryV4::getField(const QString& name) const {
    PwField* result = NULL;
    for (int i = 0; i < fields.size(); i++) {
        PwField* field = fields.at(i);
        if (field->getName() == name) {
            result = field;
            break;
        }
    }
    return result;
}

void PwEntryV4::setField(const QString& name, const QString& value) {
    PwField* field = getField(name);
    if (field != NULL) {
        field->setValue(value);
        // Memory protection flag remains unchanged.
    } else {
        // Set memory protection off by default:
        // - for standard fields it will be updated according to DB Meta protection flags (on save)
        // - for other fields, it will be changed by some other method.
        field = new PwField(this, name, value, false);
        addField(field);
    }
}

bool PwEntryV4::containsFieldName(const QString& fieldName) const {
    return PwField::isStandardName(fieldName) || (getField(fieldName) != NULL);
}

/** Deletes extra field with the given name (ignores errors) without making backup */
void PwEntryV4::deleteExtraField(const QString& fieldName) {
    int size = _extraFieldsDataModel.size();
    for (int i = 0; i < size; i++) {
        PwField* field = _extraFieldsDataModel.value(i);
        if (fieldName == field->getName()) {
            fields.removeOne(field);
            _extraFieldsDataModel.removeAt(i); // also deletes objects owned by the model
            break;
        }
    }
}

/**
 * Updates the given field with a new name, value and protection flag.
 * If 'field' is null, creates and adds one.
 */
void PwEntryV4::setExtraField(PwField* field, const QString& name, const QString& value, bool protect) {
    if (field) {
        deleteExtraField(field->getName());
    }
    PwField* newField = new PwField(this, name, value, protect);
    addField(newField);
}

void PwEntryV4::addHistoryEntry(PwEntryV4* historyEntry) {
    // most recent entries should be at the top
    _historyDataModel.insert(0, historyEntry); // implicitly takes ownership
    emit historySizeChanged(_historyDataModel.size());
}

void PwEntryV4::clearHistory() {
    _historyDataModel.clear();
    emit historySizeChanged(_historyDataModel.size());
}

/** Removes old history items, if required by Meta settings */
void PwEntryV4::maintainHistorySize() {
    PwDatabaseV4* db = dynamic_cast<PwDatabaseV4*>(getDatabase());
    if (!db)
        return;

    PwMetaV4* meta = db->getMeta();
    if (!meta)
        return;

    qint32 historyMaxItems = meta->getHistoryMaxItems();
    if (historyMaxItems >= 0) {
        while (_historyDataModel.size() > historyMaxItems) {
            removeOldestHistoryItem();
        }
    }
    //TODO enforce historyMaxSize
}

/** Removes historical item with oldest modification date. */
void PwEntryV4::removeOldestHistoryItem() {
    int indexToRemove = -1;
    QDateTime oldestTime = QDateTime::currentDateTime().addYears(1000);
    for (int i = 0; i < _historyDataModel.size(); i++) {
        PwEntryV4* historyItem = _historyDataModel.value(i);
        if (historyItem->getLastModificationTime() < oldestTime) {
            oldestTime = historyItem->getLastModificationTime();
            indexToRemove = i;
        }
    }
    if (indexToRemove >= 0) {
        _historyDataModel.removeAt(indexToRemove);
        LOG("Removed history item dated %s", oldestTime.toString().toUtf8().constData());
    }
}

bb::cascades::DataModel* PwEntryV4::getExtraFieldsDataModel() {
    return &_extraFieldsDataModel;
}

bb::cascades::DataModel* PwEntryV4::getHistoryDataModel() {
    return &_historyDataModel;
}

QString PwEntryV4::getTitle() const {
    PwField* field = getField(TITLE);
    return (field ? field->getValue() : "");
}
void PwEntryV4::setTitle(const QString& title) {
    if (title != getTitle()) {
        setField(TITLE, title);
        emit titleChanged(title);
    }
}
QString PwEntryV4::getUserName() const {
    PwField* field = getField(USERNAME);
    return (field ? field->getValue() : "");
}
void PwEntryV4::setUserName(const QString& userName) {
    if (userName != getUserName()) {
        setField(USERNAME, userName);
        emit userNameChanged(userName);
    }
}
QString PwEntryV4::getPassword() const {
    PwField* field = getField(PASSWORD);
    return (field ? field->getValue() : "");
}
void PwEntryV4::setPassword(const QString& password) {
    if (password != getPassword()) {
        setField(PASSWORD, password);
        emit passwordChanged(password);
    }
}
QString PwEntryV4::getUrl() const {
    PwField* field = getField(URL);
    return (field ? field->getValue() : "");
}
void PwEntryV4::setUrl(const QString& url) {
    if (url != getUrl()) {
        setField(URL, url);
        emit urlChanged(url);
    }
}
QString PwEntryV4::getNotes() const {
    PwField* field = getField(NOTES);
    return (field ? field->getValue() : "");
}
void PwEntryV4::setNotes(const QString& notes) {
    if (notes != getNotes()) {
        setField(NOTES, notes);
        emit notesChanged(notes);
    }
}

void PwEntryV4::setCustomIconUuid(const PwUuid& uuid) {
    if (_customIconUuid != uuid) {
        _customIconUuid = uuid;
        emit customIconUuidChanged(_customIconUuid);
    }
}

void PwEntryV4::setUsageCount(const quint32 usageCount) {
    if (usageCount != _usageCount) {
        _usageCount = usageCount;
        emit usageCountChanged(usageCount);
    }
}
void PwEntryV4::setLocationChangedTime(const QDateTime& locationChangedTime) {
    if (locationChangedTime != _locationChangedTime) {
        _locationChangedTime = locationChangedTime;
        emit locationChangedTimeChanged(locationChangedTime);
    }
}
void PwEntryV4::setForegroundColor(const QString& fgColor) {
    if (fgColor != _foregroundColor) {
        _foregroundColor = Util::deepCopy(fgColor);
        emit foregroundColorChanged(_foregroundColor);
    }
}
void PwEntryV4::setBackgroundColor(const QString& bgColor) {
    if (bgColor != _backgroundColor) {
        _backgroundColor = Util::deepCopy(bgColor);
        emit backgroundColorChanged(_backgroundColor);
    }
}
void PwEntryV4::setOverrideUrl(const QString& url) {
    if (url != _overrideUrl) {
        _overrideUrl = Util::deepCopy(url);
        emit overrideUrlChanged(_overrideUrl);
    }
}
void PwEntryV4::setTags(const QString& tags) {
    if (tags != _tags) {
        _tags = Util::deepCopy(tags);
        emit tagsChanged(_tags);
    }
}

/** Returns a new entry instance with the same field values. */
PwEntry* PwEntryV4::clone() {
    PwEntryV4* entryCopy = new PwEntryV4(this->parent());

    entryCopy->setUuid(getUuid());
    entryCopy->setIconId(getIconId());
    entryCopy->setCustomIconUuid(getCustomIconUuid());
    entryCopy->setForegroundColor(getForegroundColor());
    entryCopy->setBackgroundColor(getBackgroundColor());
    entryCopy->setOverrideUrl(getOverrideUrl());
    entryCopy->setTags(getTags());

    for (int i = 0; i < fields.size(); i++) {
        PwField* fieldCopy = fields.at(i)->clone();
        fieldCopy->setParent(NULL); // will be taken by the container
        entryCopy->addField(fieldCopy);
    }

    PwAttachmentDataModel* attachDataModel = getAttachmentsDataModel();
    for (int i = 0; i < attachDataModel->size(); i++) {
        PwAttachment* attCopy = attachDataModel->value(i)->clone();
        attCopy->setParent(NULL); // will be taken by the data model
        entryCopy->addAttachment(attCopy);
    }

    entryCopy->_autoType = _autoType;

    entryCopy->setLastModificationTime(getLastModificationTime());
    entryCopy->setCreationTime(getCreationTime());
    entryCopy->setLastAccessTime(getLastAccessTime());
    entryCopy->setExpiryTime(getExpiryTime());
    entryCopy->setExpires(isExpires());
    entryCopy->setUsageCount(getUsageCount());
    entryCopy->setLocationChangedTime(getLocationChangedTime());

    for (int i = 0; i < _historyDataModel.size(); i++) {
        PwEntryV4* historyCopy = dynamic_cast<PwEntryV4*>(_historyDataModel.value(i)->clone());
        historyCopy->setParent(NULL); // will be taken by history data model
        entryCopy->addHistoryEntry(historyCopy);
    }

    // The clone is not inserted into the parent group because
    // sometimes the clones are needed in entry history (i.e. no parent group)
    // getParentGroup()->addEntry(copy);

    return entryCopy;
}

/**
 * Makes a backup copy of the current values/state of the entry.
 * Returns true if successful.
 */
bool PwEntryV4::backupState() {
    // KeePass 2 backups entry state by adding its copy to history.

    // Also, in V4 historical items preserve the same UUID (unlike in V3)
    PwEntryV4* entryCopy = dynamic_cast<PwEntryV4*>(this->clone());
    entryCopy->clearHistory(); // historical entries must not have history
    addHistoryEntry(entryCopy);

    maintainHistorySize(); // remove old history items if necessary

    return true;
}

/**
 * Moves the entry to the Recycle Bin group (or to DeletedObjects list if backup is disabled)
 * Returns true if successful.
 */
bool PwEntryV4::moveToBackup() {
    PwDatabaseV4* db = dynamic_cast<PwDatabaseV4*>(getDatabase());
    if (!db) {
        LOG("moveToBackup fail - no reference to the DB");
        return false;
    }

    PwGroup* backupGroup = db->getBackupGroup(true);
    if (backupGroup) {
        backupGroup->moveEntry(this);
        setParent(backupGroup); // parent in Qt terms, responsible for memory release
        registerAccessEvent();
        setDeleted(true);
    } else {
        // Backup group has been disabled for this DB...
        // So we delete the entry permanently and mention it
        // in the DeletedObjects list to facilitate synchronization.
        LOG("Backup group disabled, removing the entry permanently.");
        db->addDeletedObject(getUuid());
        deleteWithoutBackup();
    }

    LOG("moveToBackup OK");
    return true;
}

/**
 * Loads the given file and attaches it to the entry.
 * Makes a backup of the initial entry state.
 * Returns true if successful, false in case of any error.
 */
bool PwEntryV4::attachFile(const QString& filePath) {
    PwAttachment* newAtt = PwAttachment::createFromFile(filePath, true);
    if (!newAtt)
        return false;

    registerModificationEvent();
    backupState();

    return addAttachment(newAtt);
}

/**
 * Loads entry fields from the stream.
 */
ErrorCodesV4::ErrorCode PwEntryV4::readFromStream(QXmlStreamReader& xml, const PwMetaV4& meta, Salsa20& salsa20, ProgressObserver* progressObserver) {
    Q_ASSERT(xml.name() == XML_ENTRY);

    ErrorCodesV4::ErrorCode err = ErrorCodesV4::SUCCESS;

    // All the fields will be read from the stream, except parent group
    PwGroup* parentGroup = getParentGroup();
    clear();
    setParentGroup(parentGroup);

    // report reading progress
    if (progressObserver)
        progressObserver->setProgress(xml.characterOffset());

    xml.readNext();
    QStringRef tagName = xml.name();
    while (!xml.hasError() && !(xml.isEndElement() && (XML_ENTRY == tagName))) {
        if (xml.isStartElement()) {
            if (XML_UUID == tagName) {
                setUuid(PwStreamUtilsV4::readUuid(xml));
            } else if (XML_ICON_ID == tagName) {
                setIconId(PwStreamUtilsV4::readInt32(xml, 0));
            } else if (XML_CUSTOM_ICON_UUID == tagName) {
                setCustomIconUuid(PwStreamUtilsV4::readUuid(xml));
            } else if (XML_FOREGROUND_COLOR == tagName) {
                setForegroundColor(PwStreamUtilsV4::readString(xml));
            } else if (XML_BACKGROUND_COLOR == tagName) {
                setBackgroundColor(PwStreamUtilsV4::readString(xml));
            } else if (XML_OVERRIDE_URL == tagName) {
                setOverrideUrl(PwStreamUtilsV4::readString(xml));
            } else if (XML_TAGS == tagName) {
                setTags(PwStreamUtilsV4::readString(xml));
            } else if (XML_STRING == tagName) {
                PwField* field = new PwField(this);
                err = field->readFromStream(xml, salsa20);
                addField(field);
            } else if (XML_BINARY == tagName) {
                PwAttachment* attachment = new PwAttachment(this);
                err = readAttachment(xml, meta, salsa20, *attachment);
                addAttachment(attachment);
            } else if (XML_TIMES == tagName) {
                err = readTimes(xml);
            } else if (XML_AUTO_TYPE == tagName) {
                err = _autoType.readFromStream(xml);
            } else if (XML_HISTORY == tagName) {
                err = readHistory(xml, meta, salsa20);
            }
        }
        if (err != ErrorCodesV4::SUCCESS)
            return err;
        xml.readNext();
        tagName = xml.name();
    }

    if (xml.hasError())
        return ErrorCodesV4::XML_ENTRY_PARSING_ERROR_GENERIC;

    return ErrorCodesV4::SUCCESS;
}

ErrorCodesV4::ErrorCode PwEntryV4::readTimes(QXmlStreamReader& xml) {
    Q_ASSERT(XML_TIMES == xml.name());

    QString text;
    xml.readNext();
    QStringRef tagName = xml.name();
    bool conversionOk = true;
    while (!xml.hasError() && !(xml.isEndElement() && (tagName == XML_TIMES))) {
        if (xml.isStartElement()) {
            if (tagName == XML_LAST_MODIFICATION_TIME) {
                setLastModificationTime(PwStreamUtilsV4::readTime(xml, &conversionOk));
                if (!conversionOk)
                    return ErrorCodesV4::XML_ENTRY_TIMES_PARSING_ERROR_1;
            } else if (tagName == XML_CREATION_TIME) {
                setCreationTime(PwStreamUtilsV4::readTime(xml, &conversionOk));
                if (!conversionOk)
                    return ErrorCodesV4::XML_ENTRY_TIMES_PARSING_ERROR_2;
            } else if (tagName == XML_LAST_ACCESS_TIME) {
                setLastAccessTime(PwStreamUtilsV4::readTime(xml, &conversionOk));
                if (!conversionOk)
                    return ErrorCodesV4::XML_ENTRY_TIMES_PARSING_ERROR_3;
            } else if (tagName == XML_EXPIRY_TIME) {
                setExpiryTime(PwStreamUtilsV4::readTime(xml, &conversionOk));
                if (!conversionOk)
                    return ErrorCodesV4::XML_ENTRY_TIMES_PARSING_ERROR_4;
            } else if (tagName == XML_EXPIRES) {
                setExpires(PwStreamUtilsV4::readBool(xml, false));
            } else if (tagName == XML_USAGE_COUNT) {
                setUsageCount(PwStreamUtilsV4::readUInt32(xml, 0));
            } else if (tagName == XML_LOCATION_CHANGED_TIME) {
                setLocationChangedTime(PwStreamUtilsV4::readTime(xml, &conversionOk));
                if (!conversionOk)
                    return ErrorCodesV4::XML_ENTRY_TIMES_PARSING_ERROR_5;
            } else {
                LOG("unknown PwEntryV4/Times tag: %s", tagName.toUtf8().constData());
                PwStreamUtilsV4::readUnknown(xml);
                return ErrorCodesV4::XML_ENTRY_TIMES_PARSING_ERROR_TAG;
            }
        }

        xml.readNext();
        tagName = xml.name();
    }

    if (xml.hasError())
        return ErrorCodesV4::XML_ENTRY_TIMES_PARSING_ERROR_GENERIC;

    return ErrorCodesV4::SUCCESS;
}

ErrorCodesV4::ErrorCode PwEntryV4::readHistory(QXmlStreamReader& xml, const PwMetaV4& meta, Salsa20& salsa20) {
    Q_ASSERT(XML_HISTORY == xml.name());

    ErrorCodesV4::ErrorCode err;
    QStringRef tagName = xml.name();
    while (!xml.hasError() && !(xml.isEndElement() && (tagName == XML_HISTORY))) {
        if (xml.isStartElement() && (tagName == XML_ENTRY)) {
            PwEntryV4* historyEntry = new PwEntryV4(this); // 'this' is the parent, not a copy source
            err = historyEntry->readFromStream(xml, meta, salsa20, NULL); // no need for such frequent progress updates
            if (err != ErrorCodesV4::SUCCESS)
                return err;

            this->addHistoryEntry(historyEntry);
        }
        xml.readNext();
        tagName = xml.name();
    }

    if (xml.hasError())
        return ErrorCodesV4::XML_ENTRY_HISTORY_PARSING_ERROR_GENERIC;

    return ErrorCodesV4::SUCCESS;
}

ErrorCodesV4::ErrorCode PwEntryV4::readAttachment(QXmlStreamReader &xml, const PwMetaV4& meta, Salsa20& salsa20, PwAttachment& attachment) {
    Q_UNUSED(salsa20);
    Q_ASSERT(XML_BINARY == xml.name());

    QStringRef tagName = xml.name();
    while (!xml.hasError() && !(xml.isEndElement() && (tagName == XML_BINARY))) {
        xml.readNext();
        tagName = xml.name();
        if (xml.isStartElement()) {
            if (tagName == XML_KEY) {
                attachment.setName(PwStreamUtilsV4::readString(xml));
            } else if (tagName == XML_VALUE) {
                QString binaryIdStr = xml.attributes().value(XML_REF).toString();
                bool convOk;
                int binaryId = binaryIdStr.toInt(&convOk);
                if (convOk) {
                    //parent group is not defined here yet
                    PwBinaryV4* binary = meta.getBinaryById(binaryId);
                    if (!binary)
                        return ErrorCodesV4::INVALID_ATTACHMENT_REFERENCE_1;

                    attachment.setData(binary->getData(), binary->isCompressed());
                    attachment.setId(binaryId);
                } else {
                    return ErrorCodesV4::INVALID_ATTACHMENT_REFERENCE_2;
                }
            }
        }
    }
    if (xml.hasError())
        return ErrorCodesV4::XML_ENTRY_ATTACHMENT_PARSING_ERROR_GENERIC;

    return ErrorCodesV4::SUCCESS;
}

/**
 * Writes the entry to the stream.
 */
void PwEntryV4::writeToStream(QXmlStreamWriter& xml, PwMetaV4& meta, Salsa20& salsa20, ProgressObserver* progressObserver) {
    xml.writeStartElement(XML_ENTRY);
    PwStreamUtilsV4::writeUuid(xml, XML_UUID, getUuid());
    PwStreamUtilsV4::writeInt32(xml, XML_ICON_ID, getIconId());
    PwUuid customIconUuid = getCustomIconUuid();
    if (!customIconUuid.isEmpty())
        PwStreamUtilsV4::writeUuid(xml, XML_CUSTOM_ICON_UUID, customIconUuid);
    PwStreamUtilsV4::writeString(xml, XML_FOREGROUND_COLOR, getForegroundColor());
    PwStreamUtilsV4::writeString(xml, XML_BACKGROUND_COLOR, getBackgroundColor());
    PwStreamUtilsV4::writeString(xml, XML_OVERRIDE_URL, getOverrideUrl());
    PwStreamUtilsV4::writeString(xml, XML_TAGS, getTags());

    // write times
    xml.writeStartElement(XML_TIMES);
    PwStreamUtilsV4::writeTime(xml, XML_LAST_MODIFICATION_TIME, getLastModificationTime());
    PwStreamUtilsV4::writeTime(xml, XML_CREATION_TIME, getCreationTime());
    PwStreamUtilsV4::writeTime(xml, XML_LAST_ACCESS_TIME, getLastAccessTime());
    PwStreamUtilsV4::writeTime(xml, XML_EXPIRY_TIME, getExpiryTime());
    PwStreamUtilsV4::writeBool(xml, XML_EXPIRES, isExpires());
    PwStreamUtilsV4::writeUInt32(xml, XML_USAGE_COUNT, getUsageCount());
    PwStreamUtilsV4::writeTime(xml, XML_LOCATION_CHANGED_TIME, getLocationChangedTime());
    xml.writeEndElement(); // XML_TIMES

    // write <String> fields
    for (int i = 0; i < fields.size(); i++) {
        PwField* field = fields.at(i);
        field->updateProtectionFlag(meta);
        field->writeToStream(xml, salsa20);
    }

    writeAttachments(xml);

    _autoType.writeToStream(xml);

    int historySize = _historyDataModel.size();
    if (historySize > 0) {
        xml.writeStartElement(XML_HISTORY);
        for (int i = 0; i < historySize; i++) {
            PwEntryV4* historyEntry = _historyDataModel.value(i);
            historyEntry->writeToStream(xml, meta, salsa20, NULL);
        }
        xml.writeEndElement(); // XML_HISTORY
    }
    xml.writeEndElement(); // XML_ENTRY

    if (progressObserver)
        progressObserver->increaseProgress(1);
}

void PwEntryV4::writeAttachments(QXmlStreamWriter& xml) {
    PwAttachmentDataModel* attachDataModel = getAttachmentsDataModel();
    for (int i = 0; i < attachDataModel->size(); i++) {
        PwAttachment* att = attachDataModel->value(i);
        xml.writeStartElement(XML_BINARY);

        PwStreamUtilsV4::writeString(xml, XML_KEY, att->getName());

        xml.writeEmptyElement(XML_VALUE);
        xml.writeAttribute(XML_REF, QString::number(att->getId()));

        xml.writeEndElement(); // XML_BINARY
    }
}


text:
package com.dimowner.tastycocktails.analytics;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;

//import com.dimowner.tastycocktails.BuildConfig;
//import com.mixpanel.android.mpmetrics.MixpanelAPI;
//
//import com.dimowner.tastycocktails.R;
//
//import org.json.JSONException;
//import org.json.JSONObject;
//
//import timber.log.Timber;

public class MixPanel implements Application.ActivityLifecycleCallbacks {

	public static final String EVENT_RATING = "rating_screen";
	public static final String EVENT_HOME = "home_sceen";
	public static final String EVENT_COCKTAIL_DETAILS = "cocktails_details";
	public static final String EVENT_FAVORITES = "favorites_screen";
	public static final String EVENT_RANDOM = "random_screen";
	public static final String EVENT_HISTORY = "history_screen";
	public static final String EVENT_ABOUT = "about_screen";
	public static final String EVENT_LICENCES = "licences_screen";
	public static final String EVENT_SETTINGS = "settings_screen";
	public static final String EVENT_LICENCE_DETAILS = "licence_details";
	public static final String EVENT_RATE_APP = "rate_app";
	public static final String EVENT_ADD_TO_FAVORITES = "add_to_favorites";
	public static final String EVENT_REMOVE_FROM_FAVORITES = "remove_from_favorites";
	public static final String EVENT_REMOVE_FROM_HISTORY = "remove_from_history";
	public static final String EVENT_DRINK_IMAGE_PREVIEW = "drink_image_preview";
	public static final String EVENT_INGREDIENT_PREVIEW = "ingredient_image_preview";
	public static final String EVENT_SEARCH = "search";
	public static final String EVENT_NEW_RANDOM_DRINK = "new_random_drink";
	public static final String EVENT_SHOW_MENU = "show_menu";
	public static final String EVENT_HIDE = "hide_menu";
	public static final String EVENT_DISABLE_ADS = "disable_ads";
	public static final String EVENT_ENABLE_ADS = "enable_ads";

//	private MixpanelAPI mixpanel;

	@Override
	public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
//		mixpanel = MixpanelAPI.getInstance(activity.getApplicationContext(), activity.getApplicationContext().getString(R.string.mixpanel_token));
	}

	@Override public void onActivityStarted(Activity activity) {}
	@Override public void onActivityResumed(Activity activity) {}
	@Override public void onActivityPaused(Activity activity) {}
	@Override public void onActivityStopped(Activity activity) {}
	@Override public void onActivitySaveInstanceState(Activity activity, Bundle outState) {}

	@Override
	public void onActivityDestroyed(Activity activity) {
//		mixpanel.flush();
	}

	public void trackData(String event, Bundle params) {
		//TODO: send events only in release build
//		if (!BuildConfig.DEBUG) {
//			JSONObject props = new JSONObject();
//
//			for (String key : params.keySet()) {
//				try {
//					props.put(key, params.get(key));
//				} catch (JSONException e) {
//					e.printStackTrace();
//				}
//			}
//			mixpanel.track(event, props);
//		}
	}

	public void trackData(String event) {
		trackData(event, Bundle.EMPTY);
	}
}


text:
<?php

namespace Easybill\ZUGFeRD\Model\Trade;

use JMS\Serializer\Annotation\SerializedName;
use JMS\Serializer\Annotation\Type;
use JMS\Serializer\Annotation\XmlElement;

class CreditorFinancialInstitution
{
    /**
     * BIC (Bank Cdentifier Code) of a credit institution.
     *
     * @var string
     * @Type("string")
     * @XmlElement(cdata = false, namespace = "urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:12")
     * @SerializedName("BICID")
     */
    private $bic;

    /**
     * The german 'Bankleitzahl'.
     *
     * @var string
     * @Type("string")
     * @XmlElement(cdata = false, namespace = "urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:12")
     * @SerializedName("GermanBankleitzahlID")
     */
    private $germanBLZ;

    /**
     * Name of the credit institution.
     *
     * @var string
     * @Type("string")
     * @XmlElement(cdata = false, namespace = "urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:12")
     * @SerializedName("Name")
     */
    private $name;

    /**
     * CreditorFinancialInstitution constructor.
     *
     * @param string $bic
     * @param string $germanBLZ
     * @param string $name
     */
    public function __construct($bic, $germanBLZ, $name)
    {
        $this->bic = $bic;
        $this->germanBLZ = $germanBLZ;
        $this->name = $name;
    }

    /**
     * @return string
     */
    public function getBic()
    {
        return $this->bic;
    }

    /**
     * @param string $bic
     */
    public function setBic($bic)
    {
        $this->bic = $bic;
    }

    /**
     * @return string
     */
    public function getGermanBLZ()
    {
        return $this->germanBLZ;
    }

    /**
     * @param string $germanBLZ
     */
    public function setGermanBLZ($germanBLZ)
    {
        $this->germanBLZ = $germanBLZ;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @param string $name
     */
    public function setName($name)
    {
        $this->name = $name;
    }
}