text:
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class RoomController : MonoBehaviour
{
    public GameObject playerList;
    public GameObject playerPrefab;

    public Button startGameButton;

    private void Start()
    {
        foreach (PhotonPlayer p in PhotonNetwork.playerList)
            SpawnPlayer(p);

        if (PhotonNetwork.isMasterClient)
            startGameButton.interactable = true;
    }

    private void OnPhotonPlayerConnected(PhotonPlayer p)
    {
        SpawnPlayer(p);
    }

    private void SpawnPlayer(PhotonPlayer p)
    {
        var go = Instantiate(playerPrefab) as GameObject;
        go.transform.SetParent(playerList.transform);

        var txts = go.GetComponentsInChildren<Text>();
        txts[0].text = p.name;
    }

    public void StartGameButton()
    {
        GetComponent<PhotonView>().RPC("StartGame", PhotonTargets.All);
    }

    [PunRPC]
    private void StartGame()
    {
        SceneManager.LoadScene("Gym_OnlineArena");
    }
}


text:
namespace views {
namespace test {

namespace {
TestDesktopScreenOzone* g_instance = nullptr;
}

TestDesktopScreenOzone* TestDesktopScreenOzone::GetInstance() {
  if (!g_instance) {
    g_instance = base::Singleton<TestDesktopScreenOzone>::get();
    g_instance->Initialize();
  }
  return g_instance;
}

gfx::Point TestDesktopScreenOzone::GetCursorScreenPoint() {
  return cursor_screen_point_;
}

TestDesktopScreenOzone::TestDesktopScreenOzone() = default;
TestDesktopScreenOzone::~TestDesktopScreenOzone() = default;

}  // namespace test
}  // namespace views

redpajama_set_name: RedPajamaGithub


text:
#include "guiutil.h"
#include "guiconstants.h"
#include "bitcoinunits.h"
#include "optionsmodel.h"
#include "walletmodel.h"
#include "messagemodel.h"
#include "addresstablemodel.h"

#include "ui_interface.h"
#include "base58.h"
#include "json_spirit.h"

#include <QSet>
#include <QTimer>
#include <QDateTime>
#include <QSortFilterProxyModel>
#include <QClipboard>
#include <QMessageBox>
#include <QMenu>
#include <QFont>
#include <QColor>

Q_DECLARE_METATYPE(std::vector<unsigned char>);

QList<QString> ambiguous; /**< Specifies Ambiguous addresses */

const QString MessageModel::Sent = "Sent";
const QString MessageModel::Received = "Received";

struct MessageTableEntryLessThan
{
    bool operator()(const MessageTableEntry &a, const MessageTableEntry &b) const {return a.received_datetime < b.received_datetime;};
    bool operator()(const MessageTableEntry &a, const QDateTime         &b) const {return a.received_datetime < b;}
    bool operator()(const QDateTime         &a, const MessageTableEntry &b) const {return a < b.received_datetime;}
};

// Private implementation
class MessageTablePriv
{
public:
    QList<MessageTableEntry> cachedMessageTable;
    MessageModel *parent;

    MessageTablePriv(MessageModel *parent):
        parent(parent) {}

    void refreshMessageTable()
    {
        cachedMessageTable.clear();

        if (parent->getWalletModel()->getEncryptionStatus() == WalletModel::Locked)
        {
            // -- messages are stored encrypted, can't load them without the private keys
            return;
        };

        {
            LOCK(cs_smsgDB);

            SecMsgDB dbSmsg;

            if (!dbSmsg.Open("cr+"))
                //throw runtime_error("Could not open DB.");
                return;

            unsigned char chKey[18];
            std::vector<unsigned char> vchKey;
            vchKey.resize(18);

            SecMsgStored smsgStored;
            MessageData msg;
            QString label;
            QDateTime sent_datetime;
            QDateTime received_datetime;

            std::string sPrefix("im");
            leveldb::Iterator* it = dbSmsg.pdb->NewIterator(leveldb::ReadOptions());
            while (dbSmsg.NextSmesg(it, sPrefix, chKey, smsgStored))
            {
                uint32_t nPayload = smsgStored.vchMessage.size() - SMSG_HDR_LEN;
                if (SecureMsgDecrypt(false, smsgStored.sAddrTo, &smsgStored.vchMessage[0], &smsgStored.vchMessage[SMSG_HDR_LEN], nPayload, msg) == 0)
                {
                    label = parent->getWalletModel()->getAddressTableModel()->labelForAddress(QString::fromStdString(msg.sFromAddress));

                    sent_datetime    .setTime_t(msg.timestamp);
                    received_datetime.setTime_t(smsgStored.timeReceived);

                    memcpy(&vchKey[0], chKey, 18);

                    addMessageEntry(MessageTableEntry(vchKey,
                                                      MessageTableEntry::Received,
                                                      label,
                                                      QString::fromStdString(smsgStored.sAddrTo),
                                                      QString::fromStdString(msg.sFromAddress),
                                                      sent_datetime,
                                                      received_datetime,
                                                      (char*)&msg.vchMessage[0]),
                                    true);
                }
            };

            delete it;

            sPrefix = "sm";
            it = dbSmsg.pdb->NewIterator(leveldb::ReadOptions());
            while (dbSmsg.NextSmesg(it, sPrefix, chKey, smsgStored))
            {
                uint32_t nPayload = smsgStored.vchMessage.size() - SMSG_HDR_LEN;
                if (SecureMsgDecrypt(false, smsgStored.sAddrOutbox, &smsgStored.vchMessage[0], &smsgStored.vchMessage[SMSG_HDR_LEN], nPayload, msg) == 0)
                {
                    label = parent->getWalletModel()->getAddressTableModel()->labelForAddress(QString::fromStdString(smsgStored.sAddrTo));

                    sent_datetime    .setTime_t(msg.timestamp);
                    received_datetime.setTime_t(smsgStored.timeReceived);

                    memcpy(&vchKey[0], chKey, 18);

                    addMessageEntry(MessageTableEntry(vchKey,
                                                      MessageTableEntry::Sent,
                                                      label,
                                                      QString::fromStdString(smsgStored.sAddrTo),
                                                      QString::fromStdString(msg.sFromAddress),
                                                      sent_datetime,
                                                      received_datetime,
                                                      (char*)&msg.vchMessage[0]),
                                    true);
                }
            };

            delete it;
        }
    }

    void newMessage(const SecMsgStored& inboxHdr)
    {
        // we have to copy it, because it doesn't like constants going into Decrypt
        SecMsgStored smsgStored = inboxHdr;
        MessageData msg;
        QString label;
        QDateTime sent_datetime;
        QDateTime received_datetime;

        uint32_t nPayload = smsgStored.vchMessage.size() - SMSG_HDR_LEN;
        if (SecureMsgDecrypt(false, smsgStored.sAddrTo, &smsgStored.vchMessage[0], &smsgStored.vchMessage[SMSG_HDR_LEN], nPayload, msg) == 0)
        {
            label = parent->getWalletModel()->getAddressTableModel()->labelForAddress(QString::fromStdString(msg.sFromAddress));

            sent_datetime    .setTime_t(msg.timestamp);
            received_datetime.setTime_t(smsgStored.timeReceived);

            std::string sPrefix("im");
            SecureMessage* psmsg = (SecureMessage*) &smsgStored.vchMessage[0];

            std::vector<unsigned char> vchKey;
            vchKey.resize(18);
            memcpy(&vchKey[0],  sPrefix.data(),  2);
            memcpy(&vchKey[2],  &psmsg->timestamp, 8);
            memcpy(&vchKey[10], &smsgStored.vchMessage[SMSG_HDR_LEN], 8);    // sample

            addMessageEntry(MessageTableEntry(vchKey,
                                              MessageTableEntry::Received,
                                              label,
                                              QString::fromStdString(smsgStored.sAddrTo),
                                              QString::fromStdString(msg.sFromAddress),
                                              sent_datetime,
                                              received_datetime,
                                              (char*)&msg.vchMessage[0]),
                            false);
        }
    }

    void newOutboxMessage(const SecMsgStored& outboxHdr)
    {

        SecMsgStored smsgStored = outboxHdr;
        MessageData msg;
        QString label;
        QDateTime sent_datetime;
        QDateTime received_datetime;

        uint32_t nPayload = smsgStored.vchMessage.size() - SMSG_HDR_LEN;
        if (SecureMsgDecrypt(false, smsgStored.sAddrOutbox, &smsgStored.vchMessage[0], &smsgStored.vchMessage[SMSG_HDR_LEN], nPayload, msg) == 0)
        {
            label = parent->getWalletModel()->getAddressTableModel()->labelForAddress(QString::fromStdString(smsgStored.sAddrTo));

            sent_datetime    .setTime_t(msg.timestamp);
            received_datetime.setTime_t(smsgStored.timeReceived);

            std::string sPrefix("sm");
            SecureMessage* psmsg = (SecureMessage*) &smsgStored.vchMessage[0];
            std::vector<unsigned char> vchKey;
            vchKey.resize(18);
            memcpy(&vchKey[0],  sPrefix.data(),  2);
            memcpy(&vchKey[2],  &psmsg->timestamp, 8);
            memcpy(&vchKey[10], &smsgStored.vchMessage[SMSG_HDR_LEN], 8);    // sample

            addMessageEntry(MessageTableEntry(vchKey,
                                              MessageTableEntry::Sent,
                                              label,
                                              QString::fromStdString(smsgStored.sAddrTo),
                                              QString::fromStdString(msg.sFromAddress),
                                              sent_datetime,
                                              received_datetime,
                                              (char*)&msg.vchMessage[0]),
                            false);
        }
    }

    void walletUnlocked()
    {
        // -- wallet is unlocked, can get at the private keys now
        refreshMessageTable();

        //parent->reset(); // reload table view

        if (parent->proxyModel)
        {
            parent->proxyModel->setFilterRole(false);
            parent->proxyModel->setFilterFixedString("");
            parent->resetFilter();
            parent->proxyModel->setFilterRole(MessageModel::Ambiguous);
            parent->proxyModel->setFilterFixedString("true");
        }

        //invalidateFilter()
    }

    void setEncryptionStatus(int status)
    {
        if (status == WalletModel::Locked)
        {
            // -- Wallet is locked, clear secure message display.
            cachedMessageTable.clear();

            //parent->reset(); // reload table view
        };
    };

    MessageTableEntry *index(int idx)
    {
        if(idx >= 0 && idx < cachedMessageTable.size())
            return &cachedMessageTable[idx];
        else
            return 0;
    }

private:
    // Get the json value
    const json_spirit::mValue & find_value(json_spirit::mObject & obj, const char * key)
    {
        std::string newKey = key;

        json_spirit::mObject::const_iterator i = obj.find(newKey);

        if(i != obj.end() && i->first == newKey)
            return i->second;
        else
            return json_spirit::mValue::null;
    }

    const std::string get_value(json_spirit::mObject & obj, const char * key)
    {
        json_spirit::mValue val = find_value(obj, key);

        if(val.is_null())
            return "";
        else
            return val.get_str();
    }

    // Determine if it is a special message, i.e.: Invoice, Receipt, etc...
    void handleMessageEntry(const MessageTableEntry & message, const bool append)
    {
        addMessageEntry(message, append);
        json_spirit::mValue mVal;
        json_spirit::read(message.message.toStdString(), mVal);

        if(mVal.is_null())
        {
            addMessageEntry(message, append);
            return;
        }

        json_spirit::mObject mObj(mVal.get_obj());
        json_spirit::mValue mvType = find_value(mObj, "type");

    }

    void addMessageEntry(const MessageTableEntry & message, const bool & append)
    {
        if(append)
        {
            cachedMessageTable.append(message);
        } else
        {
            int index = qLowerBound(cachedMessageTable.begin(), cachedMessageTable.end(), message.received_datetime, MessageTableEntryLessThan()) - cachedMessageTable.begin();
            parent->beginInsertRows(QModelIndex(), index, index);
            cachedMessageTable.insert(
                        index,
                        message);
            parent->endInsertRows();
        }
    }

};

MessageModel::MessageModel(CWallet *wallet, WalletModel *walletModel, QObject *parent) :
    QAbstractTableModel(parent), wallet(wallet), walletModel(walletModel), optionsModel(0), priv(0)
{
    columns << tr("Type") << tr("Sent Date Time") << tr("Received Date Time") << tr("Label") << tr("To Address") << tr("From Address") <
getOptionsModel();

    priv = new MessageTablePriv(this);
    priv->refreshMessageTable();

    subscribeToCoreSignals();
}

MessageModel::~MessageModel()
{
    if (proxyModel)
        delete proxyModel;

    delete priv;
    unsubscribeFromCoreSignals();
}

bool MessageModel::getAddressOrPubkey(QString &address, QString &pubkey) const
{
    CBitcoinAddress addressParsed(address.toStdString());

    if(addressParsed.IsValid()) {
        CKeyID  destinationAddress;
        CPubKey destinationKey;

        addressParsed.GetKeyID(destinationAddress);

        if (SecureMsgGetStoredKey(destinationAddress, destinationKey) != 0
            && SecureMsgGetLocalKey(destinationAddress, destinationKey) != 0) // test if it's a local key
            return false;

        address = destinationAddress.ToString().c_str();
        pubkey = EncodeBase58(destinationKey.Raw()).c_str();

        return true;
    }

    return false;
}

WalletModel *MessageModel::getWalletModel()
{
    return walletModel;
}

OptionsModel *MessageModel::getOptionsModel()
{
    return optionsModel;
}

MessageModel::StatusCode MessageModel::sendMessages(const QList<SendMessagesRecipient> &recipients, const QString &addressFrom)
{

    QSet<QString> setAddress;

    if(recipients.empty())
        return OK;

    // Pre-check input data for validity
    foreach(const SendMessagesRecipient &rcp, recipients)
    {
        if(!walletModel->validateAddress(rcp.address))
            return InvalidAddress;

        if(rcp.message == "")
            return MessageCreationFailed;

        std::string sendTo  = rcp.address.toStdString();
        std::string pubkey  = rcp.pubkey.toStdString();
        std::string message = rcp.message.toStdString();
        std::string addFrom = addressFrom.toStdString();

        SecureMsgAddAddress(sendTo, pubkey);
        setAddress.insert(rcp.address);

        std::string sError;
        if (SecureMsgSend(addFrom, sendTo, message, sError) != 0)
        {
            QMessageBox::warning(NULL, tr("Send Secure Message"),
                tr("Send failed: %1.").arg(sError.c_str()),
                QMessageBox::Ok, QMessageBox::Ok);

            return FailedErrorShown;
        };

        // Add addresses / update labels that we've sent to to the address book
        std::string strAddress = rcp.address.toStdString();
        CTxDestination dest = CBitcoinAddress(strAddress).Get();
        std::string strLabel = rcp.label.toStdString();
        {
            LOCK(wallet->cs_wallet);

            std::map<CTxDestination, std::string>::iterator mi = wallet->mapAddressBook.find(dest);

            // Check if we have a new address or an updated label
            if (mi == wallet->mapAddressBook.end() || mi->second != strLabel)
            {
                wallet->SetAddressBookName(dest, strLabel);
            }
        }
    }

    if(recipients.size() > setAddress.size())
        return DuplicateAddress;

    return OK;
}

MessageModel::StatusCode MessageModel::sendMessages(const QList<SendMessagesRecipient> &recipients)
{
    return sendMessages(recipients, "anon");
}

int MessageModel::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    return priv->cachedMessageTable.size();
}

int MessageModel::columnCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    return columns.length();
}

QVariant MessageModel::data(const QModelIndex &index, int role) const
{
    if(!index.isValid())
        return QVariant();

    MessageTableEntry *rec = static_cast<MessageTableEntry*>(index.internalPointer());

    switch(role)
    {
    /*
    case Qt::DecorationRole:
        switch(index.column())
        {
            return txStatusDecoration(rec);
        case ToAddress:
            return txAddressDecoration(rec);
        }
        break;*/
    case Qt::DisplayRole:
        switch(index.column())
        {
            case Label:	           return (rec->label.isEmpty() ? tr("(no label)") : rec->label);
            case ToAddress:	       return rec->to_address;
            case FromAddress:      return rec->from_address;
            case SentDateTime:     return rec->sent_datetime;
            case ReceivedDateTime: return rec->received_datetime;
            case Message:          return rec->message;
            case TypeInt:          return rec->type;
            case HTML:             return rec->received_datetime.toString() + "
"  + (rec->label.isEmpty() ? rec->from_address : rec->label)  + "
" + rec->message;
            case Type:
                switch(rec->type)
                {
                    case MessageTableEntry::Sent:     return Sent;
                    case MessageTableEntry::Received: return Received;
                    default: break;
                }
            case Key:               return QVariant::fromValue(rec->chKey);
        }
        break;

    case KeyRole:           return QVariant::fromValue(rec->chKey);
    case TypeRole:          return rec->type;
    case SentDateRole:      return rec->sent_datetime;
    case ReceivedDateRole:  return rec->received_datetime;
    case FromAddressRole:   return rec->from_address;
    case ToAddressRole:     return rec->to_address;
    case FilterAddressRole: return (rec->type == MessageTableEntry::Sent ? rec->to_address + rec->from_address : rec->from_address + rec->to_address);
    case LabelRole:         return rec->label;
    case MessageRole:       return rec->message;
    case ShortMessageRole:  return rec->message; // TODO: Short message
    case HTMLRole:          return rec->received_datetime.toString() + "
"  + (rec->label.isEmpty() ? rec->from_address : rec->label)  + "
" + rec->message;
    case Ambiguous:
        int it;

        for (it = 0; it<ambiguous.length(); it++) {
            if(ambiguous[it] == (rec->type == MessageTableEntry::Sent ? rec->to_address + rec->from_address : rec->from_address + rec->to_address))
                return false;
        }
        QString address = (rec->type == MessageTableEntry::Sent ? rec->to_address + rec->from_address : rec->from_address + rec->to_address);
        ambiguous.append(address);

        return "true";
        break;
    }

    return QVariant();
}

QVariant MessageModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    return (orientation == Qt::Horizontal && role == Qt::DisplayRole ? columns[section] : QVariant());
}

Qt::ItemFlags MessageModel::flags(const QModelIndex & index) const
{
    if(index.isValid())
        return Qt::ItemIsSelectable | Qt::ItemIsEnabled;

    return 0;
}

QModelIndex MessageModel::index(int row, int column, const QModelIndex & parent) const
{
    Q_UNUSED(parent);
    MessageTableEntry *data = priv->index(row);
    return (data ? createIndex(row, column, priv->index(row)) : QModelIndex());
}

bool MessageModel::removeRows(int row, int count, const QModelIndex & parent)
{
    MessageTableEntry *rec = priv->index(row);
    if(count != 1 || !rec)
        // Can only remove one row at a time, and cannot remove rows not in model.
        // Also refuse to remove receiving addresses.
        return false;

    {
        LOCK(cs_smsgDB);
        SecMsgDB dbSmsg;

        if (!dbSmsg.Open("cr+"))
            //throw runtime_error("Could not open DB.");
            return false;

        dbSmsg.EraseSmesg(&rec->chKey[0]);
    }

    beginRemoveRows(parent, row, row);
    priv->cachedMessageTable.removeAt(row);
    endRemoveRows();

    return true;
}

void MessageModel::resetFilter()
{
    ambiguous.clear();
}

void MessageModel::newMessage(const SecMsgStored &smsg)
{
    priv->newMessage(smsg);
}

void MessageModel::newOutboxMessage(const SecMsgStored &smsgOutbox)
{
    priv->newOutboxMessage(smsgOutbox);
}

void MessageModel::walletUnlocked()
{
    priv->walletUnlocked();
}

void MessageModel::setEncryptionStatus(int status)
{
    priv->setEncryptionStatus(status);
}

static void NotifySecMsgInbox(MessageModel *messageModel, SecMsgStored inboxHdr)
{
    // Too noisy: OutputDebugStringF("NotifySecMsgInboxChanged %s\n", message);
    QMetaObject::invokeMethod(messageModel, "newMessage", Qt::QueuedConnection,
                              Q_ARG(SecMsgStored, inboxHdr));
}

static void NotifySecMsgOutbox(MessageModel *messageModel, SecMsgStored outboxHdr)
{
    QMetaObject::invokeMethod(messageModel, "newOutboxMessage", Qt::QueuedConnection,
                              Q_ARG(SecMsgStored, outboxHdr));
}

static void NotifySecMsgWallet(MessageModel *messageModel)
{
    QMetaObject::invokeMethod(messageModel, "walletUnlocked", Qt::QueuedConnection);
}

void MessageModel::subscribeToCoreSignals()
{
    qRegisterMetaType<SecMsgStored>("SecMsgStored");

    // Connect signals
    NotifySecMsgInboxChanged.connect(boost::bind(NotifySecMsgInbox, this, _1));
    NotifySecMsgOutboxChanged.connect(boost::bind(NotifySecMsgOutbox, this, _1));
    NotifySecMsgWalletUnlocked.connect(boost::bind(NotifySecMsgWallet, this));

    connect(walletModel, SIGNAL(encryptionStatusChanged(int)), this, SLOT(setEncryptionStatus(int)));
}

void MessageModel::unsubscribeFromCoreSignals()
{
    // Disconnect signals
    NotifySecMsgInboxChanged.disconnect(boost::bind(NotifySecMsgInbox, this, _1));
    NotifySecMsgOutboxChanged.disconnect(boost::bind(NotifySecMsgOutbox, this, _1));
    NotifySecMsgWalletUnlocked.disconnect(boost::bind(NotifySecMsgWallet, this));

    disconnect(walletModel, SIGNAL(encryptionStatusChanged(int)), this, SLOT(setEncryptionStatus(int)));
}


text:
package com.fererlab.pattern.structural.bridge.composition;

public class CircleComposition extends ShapeComposition {

    public CircleComposition(ColorComposition colorComposition) {
        super(colorComposition);
    }

    @Override
    public void applyColor() {
        colorComposition.applyColor();
    }

}


text:
<html>
	<head>
		<script>
			// Here comes the post office implementation...
			function PostOffice() {
				if(PostOffice.instance) {
					throw 'already created!';
				} else {
					this.subscribers={};
					PostOffice.instance=this;
				}
			}
			PostOffice.instance=undefined;
			PostOffice.getInstance=function() {
				if(PostOffice.instance==undefined) {
					PostOffice.instance=new PostOffice();
				}
				return PostOffice.instance;
			};
			PostOffice.prototype.subscribe=function(evt,obj,method) {
				if(!this.subscribers[evt]) {
					this.subscribers[evt]=[];
				}
				this.subscribers[evt].push([obj,method]);
			};
			PostOffice.prototype.publish=function(evt,data) {
				if(this.subscribers[evt]) {
					for(var x in this.subscribers[evt]) {
						var oam=this.subscribers[evt][x];
						var curr_obj=oam[0];
						var curr_method=oam[1];
						curr_obj[curr_method](data);
					}
				}
			};

			// Listener to test the post office...
			function Listener(name,age) {
				// keep lint happy
				console.log(name,age);
			}
			Listener.prototype.notify=function(data) {
				alert('this is an alert with data ['+data+']');
			};

			//var po=new PostOffice();
			var p=new Listener('mark',435);
			PostOffice.getInstance().subscribe('myeventname',p,'notify');
			// publish the event (no data for now...)
			PostOffice.getInstance().publish('myeventname',['this is some data']);
		</script>
	</head>
</html>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Class net.sf.jasperreports.engine.export.oasis.WriterHelper (JasperReports 5.6.0 API)</title>
<meta name="date" content="2014-05-27">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
net.sf.jasperreports.engine.export.oasis.WriterHelper

Packages that use WriterHelper

Package
Description

net.sf.jasperreports.engine.export.oasis

Provides utility classes for exporting reports to Open Document Format, such as
 ODT and ODS.

Uses of WriterHelper in net.sf.jasperreports.engine.export.oasis

Fields in net.sf.jasperreports.engine.export.oasis declared as WriterHelper

Modifier and Type
Field and Description

protected WriterHelper
Style.styleWriter

protected WriterHelper
JROdtExporter.tempBodyWriter

protected WriterHelper
JROdsExporter.tempBodyWriter

protected WriterHelper
JROdtExporter.tempStyleWriter

protected WriterHelper
JROdsExporter.tempStyleWriter

Constructors in net.sf.jasperreports.engine.export.oasis with parameters of type WriterHelper

Constructor and Description

BorderStyle(WriterHelper styleWriter)

CellStyle(WriterHelper styleWriter,
         JRExporterGridCell gridCell)

ColumnStyle(WriterHelper styleWriter,
           int columnWidth)

FrameStyle(WriterHelper styleWriter,
          JRPrintElement element)

GraphicStyle(WriterHelper styleWriter,
            JRPrintGraphicElement element)

JROdsExporter.OdsTableBuilder(DocumentBuilder documentBuilder,
                             JasperPrint jasperPrint,
                             int reportIndex,
                             int pageIndex,
                             WriterHelper bodyWriter,
                             WriterHelper styleWriter,
                             StyleCache styleCache,
                             java.util.Map<java.lang.Integer,java.lang.String> rowStyles,
                             java.util.Map<java.lang.Integer,java.lang.String> columnStyles)

JROdsExporter.OdsTableBuilder(DocumentBuilder documentBuilder,
                             JasperPrint jasperPrint,
                             int reportIndex,
                             int pageIndex,
                             WriterHelper bodyWriter,
                             WriterHelper styleWriter,
                             StyleCache styleCache,
                             java.util.Map<java.lang.Integer,java.lang.String> rowStyles,
                             java.util.Map<java.lang.Integer,java.lang.String> columnStyles,
                             java.lang.String sheetName)

ParagraphStyle(WriterHelper styleWriter,
              JRPrintText text)

RowStyle(WriterHelper styleWriter,
        int rowHeight)

Style(WriterHelper styleWriter)

StyleBuilder(ExporterInput exporterInput,
            WriterHelper writer)

StyleCache(JasperReportsContext jasperReportsContext,
          WriterHelper styleWriter,
          java.lang.String exporterKey)

TableBuilder(DocumentBuilder documentBuilder,
            JasperPrint jasperPrint,
            int reportIndex,
            int pageIndex,
            WriterHelper bodyWriter,
            WriterHelper styleWriter,
            StyleCache styleCache,
            java.util.Map<java.lang.Integer,java.lang.String> rowStyles,
            java.util.Map<java.lang.Integer,java.lang.String> columnStyles)

TableBuilder(DocumentBuilder documentBuilder,
            JasperPrint jasperPrint,
            java.lang.String name,
            WriterHelper bodyWriter,
            WriterHelper styleWriter,
            StyleCache styleCache,
            java.util.Map<java.lang.Integer,java.lang.String> rowStyles,
            java.util.Map<java.lang.Integer,java.lang.String> columnStyles)

TableStyle(WriterHelper styleWriter,
          int width,
          int reportIndex,
          boolean isFrame,
          boolean isPageBreak)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

© 2001-2010 Jaspersoft Corporation www.jaspersoft.com


text:
{% load static blog_tags twitter_tag cache compress %}

{% block widgets %}

Twitter

        {% cache 600 twitter_bar %} {% get_tweets for "instanssi" as tweets exclude "replies" limit 5 %}

            {% for tweet in tweets %}

                @{{ tweet.user.name }}:
                {{ tweet.text }}

                {{ tweet.datetime|date:"d.m.Y H:i" }}

            {% endfor %}

        {% endcache %}

Some

#instanssi @ IRCNet

{% endblock %}


text:
#include "tudat/astro/propagators/rotationalMotionExponentialMapStateDerivative.h"

namespace tudat
{

namespace propagators
{

//! Function to obtain the time derivative of exponantial map of body-fixed to inertial frame.
Eigen::Vector4d calculateExponentialMapDerivative( const Eigen::Vector4d& currentExponentialMapToBaseFrame,
                                                   const Eigen::Vector3d& angularVelocityVectorInBodyFixedFrame )
{
    // Define the tolerance of a singularity
    double singularityTolerance = 20.0 * std::numeric_limits< double >::epsilon( );

    // Declare eventual output vector
    Eigen::Vector4d exponentialMapDerivative = Eigen::Vector4d::Zero( );

    // Get intermediate variables
    Eigen::Vector3d exponentialMapVector = currentExponentialMapToBaseFrame.segment( 0, 3 );
    double exponentialMapMagnitude = exponentialMapVector.norm( );

    // Compute kinematic equation, i.e., derivative of exponential map (also valid for SEM)
    if ( exponentialMapMagnitude < singularityTolerance )
    {
        double exponentialMapMagnitudeSquared = std::pow( exponentialMapMagnitude, 2 );
        exponentialMapDerivative.segment( 0, 3 ) = 0.5 * (
                    ( ( 12.0 - exponentialMapMagnitudeSquared ) / 6.0 ) *
                    angularVelocityVectorInBodyFixedFrame - angularVelocityVectorInBodyFixedFrame.cross(
                        exponentialMapVector ) - angularVelocityVectorInBodyFixedFrame.dot(
                        exponentialMapVector ) *
                    ( ( 60.0 + exponentialMapMagnitudeSquared ) / 360.0 ) * exponentialMapVector );
    }
    else
    {
        double cotangentHalfExponentialMapMagnitude = std::cos( 0.5 * exponentialMapMagnitude ) /
                std::sin( 0.5 * exponentialMapMagnitude );
        Eigen::Vector3d exponentialMapCrossRotationalVelocityVector = exponentialMapVector.cross(
                    angularVelocityVectorInBodyFixedFrame );
        exponentialMapDerivative.segment( 0, 3 ) =
                angularVelocityVectorInBodyFixedFrame + 0.5 * exponentialMapCrossRotationalVelocityVector +
                ( 1 - 0.5 * exponentialMapMagnitude * cotangentHalfExponentialMapMagnitude ) /
                std::pow( exponentialMapMagnitude, 2 ) *
                exponentialMapVector.cross( exponentialMapCrossRotationalVelocityVector );
    }

    // Give output
    return exponentialMapDerivative;
}

template class RotationalMotionExponentialMapStateDerivative< double, double >;

#if( TUDAT_BUILD_WITH_EXTENDED_PRECISION_PROPAGATION_TOOLS )
template class RotationalMotionExponentialMapStateDerivative< long double, double >;
template class RotationalMotionExponentialMapStateDerivative< double, Time >;
template class RotationalMotionExponentialMapStateDerivative< long double, Time >;
#endif

} // namespace propagators

} // namespace tudat


text:
using System.Collections.Generic;

namespace org.apache.lucene.analysis.ckb
{

	using TokenFilterFactory = org.apache.lucene.analysis.util.TokenFilterFactory;

	///
	/// Factory for <seealso cref="SoraniStemFilter"/>.
	///

	/// <fieldType name="text_ckbstem" class="solr.TextField" positionIncrementGap="100">
	///   <analyzer>
	///     <tokenizer class="solr.StandardTokenizerFactory"/>
	///     <filter class="solr.SoraniNormalizationFilterFactory"/>
	///     <filter class="solr.SoraniStemFilterFactory"/>
	///   </analyzer>
	/// </fieldType>

	///
	public class SoraniStemFilterFactory : TokenFilterFactory
	{

	  ///
	  /// Creates a new SoraniStemFilterFactory
	  public SoraniStemFilterFactory(IDictionary<string, string> args) : base(args)
	  {
		if (args.Count > 0)
		{
		  throw new System.ArgumentException("Unknown parameters: " + args);
		}
	  }

	  public override SoraniStemFilter create(TokenStream input)
	  {
		return new SoraniStemFilter(input);
	  }
	}

}


text:
/**
 * Replace a key deeply in an object
 * @param obj
 * @param keyMap
 * @returns {Object}
 */
function replaceKeyDeep(obj, keyMap) {
  return Object.keys(obj).reduce((memo, key)=> {

    // determine which key we are going to use
    let targetKey = keyMap[key] ? keyMap[key] : key;

    // assign the new value
    memo[targetKey] = obj[key];

    // recurse if an array
    if (Array.isArray(memo[targetKey])) {
      memo[targetKey].forEach((val, idx) => {
        if (Object.prototype.toString.call(val) === '[object Object]') {
          memo[targetKey][idx] = replaceKeyDeep(val, keyMap);
        }
      });
    } else if (Object.prototype.toString.call(memo[targetKey]) === '[object Object]') {
      // recurse if Object
      memo[targetKey] = replaceKeyDeep(memo[targetKey], keyMap);
    }

    // return the modified object
    return memo;
  }, {});
}

/**
 * Replace the where arguments object and return the sequelize compatible version.
 * @param where arguments object in GraphQL Safe format meaning no leading "$" chars.
 * @returns {Object}
 */
export function replaceWhereOperators(where) {
  return replaceKeyDeep(where, {
    and: '$and',
    or: '$or',
    gt: '$gt',
    gte: '$gte',
    lt: '$lt',
    lte: '$lte',
    ne: '$ne',
    between: '$between',
    notBetween: '$notBetween',
    in: '$in',
    notIn: '$notIn',
    notLike: '$notLike',
    iLike: '$iLike',
    notILike: '$notILike',
    like: '$like',
    overlap: '$overlap',
    contains: '$contains',
    contained: '$contained',
    any: '$any',
    col: '$col'
  });
}


text:
<?xml version="1.0" ?>
<xliff version="1.0">
    <file original="apostrophe" source-language="en_US" datatype="plaintext">
        <body>
            <trans-unit id="1">
                <source>Forgot your password?</source>
                <target>Esqueceu sua senha?</target>
            </trans-unit>
            <trans-unit id="2">
                <source>Want to register?</source>
                <target>Quer se cadastrar?</target>
            </trans-unit>
        </body>
    </file>
</xliff>


text:
package org.apache.jackrabbit.oak.plugins.migration.version;

import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

import javax.jcr.RepositoryException;

import org.apache.commons.lang3.StringUtils;
import org.apache.jackrabbit.oak.api.CommitFailedException;
import org.apache.jackrabbit.oak.api.Root;
import org.apache.jackrabbit.oak.api.Tree;
import org.apache.jackrabbit.oak.api.Type;
import org.apache.jackrabbit.oak.commons.PathUtils;
import org.apache.jackrabbit.oak.core.ImmutableRoot;
import org.apache.jackrabbit.oak.namepath.NamePathMapper;
import org.apache.jackrabbit.oak.plugins.memory.MemoryNodeStore;
import org.apache.jackrabbit.oak.plugins.migration.DescendantsIterator;
import org.apache.jackrabbit.oak.plugins.migration.NodeStateCopier;
import org.apache.jackrabbit.oak.plugins.version.ReadOnlyVersionManager;
import org.apache.jackrabbit.oak.plugins.version.ReadWriteVersionManager;
import org.apache.jackrabbit.oak.spi.state.NodeBuilder;
import org.apache.jackrabbit.oak.spi.state.NodeState;
import org.apache.jackrabbit.oak.spi.state.NodeStore;
import org.junit.Ignore;
import org.junit.Test;

import static java.util.Collections.singletonList;
import static org.apache.jackrabbit.JcrConstants.JCR_FROZENNODE;
import static org.apache.jackrabbit.JcrConstants.JCR_MIXINTYPES;
import static org.apache.jackrabbit.JcrConstants.JCR_PRIMARYTYPE;
import static org.apache.jackrabbit.JcrConstants.JCR_UUID;
import static org.apache.jackrabbit.JcrConstants.MIX_VERSIONABLE;
import static org.apache.jackrabbit.JcrConstants.NT_UNSTRUCTURED;
import static org.apache.jackrabbit.oak.InitialContentHelper.INITIAL_CONTENT;
import static org.apache.jackrabbit.oak.InitialContentHelper.INITIAL_CONTENT_FROZEN_NODE_REFERENCEABLE;
import static org.apache.jackrabbit.oak.plugins.migration.NodeStateTestUtils.commit;
import static org.apache.jackrabbit.oak.plugins.migration.version.VersionHistoryUtil.getVersionHistoryBuilder;
import static org.apache.jackrabbit.oak.plugins.migration.version.VersionHistoryUtil.getVersionHistoryNodeState;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

public class VersionCopierTest {

    @Test
    public void copyVersionSourceFrozenNodeReferenceable() throws Exception {
        String path = "/foo";
        NodeStore source = createVersionFor(path, createStore(true));
        NodeStore target = createStore(false);

        copyContent(source, target, path);
        copyVersionStorage(source, target);
        assertVersionNotReferenceable(target.getRoot(), path);
    }

    @Test
    public void copyVersionSourceFrozenNodeNotReferenceable() throws Exception {
        String path = "/foo";
        NodeStore source = createVersionFor(path, createStore(false));
        NodeStore target = createStore(false);

        copyContent(source, target, path);
        copyVersionStorage(source, target);
        assertVersionNotReferenceable(target.getRoot(), path);
    }

    @Test
    public void copyVersionTargetFrozenNodeReferenceable() throws Exception {
        String path = "/foo";
        NodeStore source = createVersionFor(path, createStore(true));
        NodeStore target = createStore(true);

        copyContent(source, target, path);
        copyVersionStorage(source, target);
        assertVersionReferenceable(target.getRoot(), path);
    }

    @Ignore("VersionCopier does not generate referenceable target nt:frozenNode from source frozen nodes that are not referenceable")
    @Test
    public void copyVersionTargetGenerateReferenceableFrozenNode() throws Exception {
        String path = "/foo";
        NodeStore source = createVersionFor(path, createStore(false));
        NodeStore target = createStore(true);

        copyContent(source, target, path);
        copyVersionStorage(source, target);
        assertVersionReferenceable(target.getRoot(), path);
    }

    @Test
    public void copyVersionSourceRemovingTargetVersionHistory() throws Exception {
        String path = "/foo";
        NodeStore source = createVersionFor(path, createStore(false));
        NodeStore target = createVersionFor(path, createStore(false));

        // Copy source to target as starting point to duplicate.
        copyVersionStorage(source, target);

        // Add a test property to the nodes of the target version history.
        addVersionHistoryTestProperty(source, target);

        // Copy again, this time setting the remove target version history flag.
        copyVersionStorage(source, target, true);

        // Verify the test properties no longer exist in the target version history.
        assertVersionHistoryTestPropertyRemoved(source, target);
    }

    @Test
    public void copyVersionSourceNotRemovingTargetVersionHistory() throws Exception {
        String path = "/foo";
        NodeStore source = createVersionFor(path, createStore(false));
        NodeStore target = createStore(false);

        // Copy source to target as starting point to duplicate.
        copyContent(source, target, path);
        copyVersionStorage(source, target);

        // Add another version
        target = createNewVersion(path, target, "a");

        // copy versions again preserving any new target versions created
        VersionCopyConfiguration config = new VersionCopyConfiguration();
        config.setPreserveOnTarget(true);
        copyVersionStorageInternal(source, target, config);

        // Verify the test properties no longer exist in the target version history.
        assertVersionHistoryPreserveTarget(source, target);
    }

    private void addVersionHistoryTestProperty(NodeStore source, NodeStore target) throws CommitFailedException {
        final NodeState sourceVersionStorage = VersionHistoryUtil.getVersionStorage(source.getRoot());
        final NodeBuilder targetRootBuilder = target.getRoot().builder();
        final NodeBuilder targetVersionStorage = VersionHistoryUtil.getVersionStorage(targetRootBuilder);

        final Iterator<NodeState> versionStorageIterator = new DescendantsIterator(sourceVersionStorage, 3);
        final NodeState versionHistoryBucket = versionStorageIterator.next();
        for (String versionHistory : versionHistoryBucket.getChildNodeNames()) {
            getVersionHistoryBuilder(targetVersionStorage, versionHistory).setProperty("jcr:test", "test");
        }
        commit(target, targetRootBuilder);
    }

    private void assertVersionHistoryTestPropertyRemoved(NodeStore source, NodeStore target) {
        final NodeState sourceVersionStorage = VersionHistoryUtil.getVersionStorage(source.getRoot());
        final NodeState targetVersionStorage = VersionHistoryUtil.getVersionStorage(target.getRoot());

        final Iterator<NodeState> versionStorageIterator = new DescendantsIterator(sourceVersionStorage, 3);
        final NodeState versionHistoryBucket = versionStorageIterator.next();
        for (String versionHistory : versionHistoryBucket.getChildNodeNames()) {
            assertFalse(getVersionHistoryNodeState(targetVersionStorage, versionHistory).hasProperty("jcr:test"));
        }
    }

    private void assertVersionHistoryPreserveTarget(NodeStore source, NodeStore target) {
        final NodeState sourceVersionStorage = VersionHistoryUtil.getVersionStorage(source.getRoot());
        final NodeState targetVersionStorage = VersionHistoryUtil.getVersionStorage(target.getRoot());

        final Iterator<NodeState> versionStorageIterator = new DescendantsIterator(targetVersionStorage, 3);
        final NodeState versionHistoryBucket = versionStorageIterator.next();
        for (String versionHistory : versionHistoryBucket.getChildNodeNames()) {
            NodeState historyNodeState = getVersionHistoryNodeState(targetVersionStorage, versionHistory);
            List<String> targetList = StreamSupport.stream(historyNodeState.getChildNodeNames().spliterator(), false)
                .collect(Collectors.toList());

            NodeState srcHistoryNodeState = getVersionHistoryNodeState(sourceVersionStorage, versionHistory);
            List<String> sourceList = StreamSupport.stream(srcHistoryNodeState.getChildNodeNames().spliterator(), false)
                .collect(Collectors.toList());

            // Check all source versions in target
            assertTrue(targetList.containsAll(sourceList));
            // Check target has more versions
            assertTrue(targetList.size() > sourceList.size());
        }
    }

    private void copyContent(NodeStore source, NodeStore target, String path)
            throws CommitFailedException {
        NodeStateCopier.builder().include(path).copy(source, target);
    }

    private void copyVersionStorage(NodeStore source, NodeStore target)
        throws CommitFailedException {

        copyVersionStorage(source, target, false);
    }

    private void copyVersionStorage(NodeStore source, NodeStore target, boolean removeTargetVersionHistory)
            throws CommitFailedException {

        VersionCopyConfiguration config = new VersionCopyConfiguration();
        config.setRemoveTargetVersionHistory(removeTargetVersionHistory);

        copyVersionStorageInternal(source, target, config);
    }

    private void copyVersionStorageInternal(NodeStore source, NodeStore target, VersionCopyConfiguration config)
            throws CommitFailedException {

        NodeBuilder targetRootBuilder = target.getRoot().builder();
        VersionCopier.copyVersionStorage(
            targetRootBuilder,
            VersionHistoryUtil.getVersionStorage(source.getRoot()),
            VersionHistoryUtil.getVersionStorage(targetRootBuilder),
            config
        );
        commit(target, targetRootBuilder);
    }

    private void assertVersionReferenceable(NodeState rootState,
                                            String versionablePath)
            throws RepositoryException {
        assertTrue(getFrozenNode(rootState, versionablePath).hasProperty(JCR_UUID));
    }

    private void assertVersionNotReferenceable(NodeState rootState,
                                               String versionablePath)
            throws RepositoryException {
        assertFalse(getFrozenNode(rootState, versionablePath).hasProperty(JCR_UUID));
    }

    private Tree getFrozenNode(NodeState rootState, String versionablePath)
            throws RepositoryException {
        Root root = new ImmutableRoot(rootState);
        ReadOnlyVersionManager vMgr = ReadOnlyVersionManager.getInstance(
                root, NamePathMapper.DEFAULT);
        Tree version = vMgr.getBaseVersion(root.getTree(versionablePath));
        assertNotNull(version);
        Tree frozenNode = version.getChild(JCR_FROZENNODE);
        assertNotNull(frozenNode);
        return frozenNode;
    }

    private NodeStore createStore(boolean referenceableFrozenNodes) {
        NodeState initial = INITIAL_CONTENT;
        if (referenceableFrozenNodes) {
            initial = INITIAL_CONTENT_FROZEN_NODE_REFERENCEABLE;
        }
        return new MemoryNodeStore(initial);
    }

    private NodeStore createVersionFor(String path, NodeStore ns) throws Exception {
        return createVersion(path, ns, "");
    }

    private NodeStore createVersion(String path, NodeStore ns, String property) throws Exception {
        NodeBuilder rootBuilder = ns.getRoot().builder();
        NodeBuilder builder = rootBuilder;
        for (String name : PathUtils.elements(path)) {
            builder = builder.child(name);
        }
        builder.setProperty(JCR_PRIMARYTYPE, NT_UNSTRUCTURED, Type.NAME);
        builder.setProperty(JCR_MIXINTYPES, singletonList(MIX_VERSIONABLE), Type.NAMES);
        builder.setProperty(JCR_UUID, UUID.randomUUID().toString());
        if (StringUtils.isNotEmpty(property)) {
            builder.setProperty(property, property);
        }
        ReadWriteVersionManager vMgr = new ReadWriteVersionManager(
                VersionHistoryUtil.getVersionStorage(rootBuilder),
                rootBuilder
        );
        vMgr.checkin(builder);
        commit(ns, rootBuilder);
        return ns;
    }

    private NodeStore createNewVersion(String path, NodeStore ns, String property) throws Exception {
        NodeBuilder rootBuilder = ns.getRoot().builder();
        NodeBuilder builder = rootBuilder;
        for (String name : PathUtils.elements(path)) {
            builder = builder.child(name);
        }
        if (StringUtils.isNotEmpty(property)) {
            builder.setProperty(property, property);
        }
        ReadWriteVersionManager vMgr = new ReadWriteVersionManager(
            VersionHistoryUtil.getVersionStorage(rootBuilder),
            rootBuilder
        );
        vMgr.checkout(builder);
        vMgr.checkin(builder);
        commit(ns, rootBuilder);
        return ns;
    }
}


text:
using System.IO;

namespace NuPattern.Runtime
{
    /// <summary>
    /// Helper methods for dealing with a schema state.
    /// </summary>
    internal static class SchemaReaderExtensions
    {
        /// <summary>
        /// Loads the model from the given model file.
        /// </summary>
        public static IPatternModelInfo Load(this ISchemaReader reader, string modelFile)
        {
            Guard.NotNull(() => reader, reader);
            Guard.NotNullOrEmpty(() => modelFile, modelFile);

            using (var stream = new FileStream(modelFile, FileMode.Open))
            {
                return reader.Load(stream);
            }
        }

        /// <summary>
        /// Loads the model using the information on the given resource to locate it.
        /// </summary>
        public static IPatternModelInfo Load(this ISchemaReader reader, ISchemaResource resource)
        {
            Guard.NotNull(() => reader, reader);
            Guard.NotNull(() => resource, resource);

            return reader.Load(resource.CreateStream());
        }
    }
}


text:
namespace ExactOnline.Client.Models.SalesOrder
{
    using System;

    [SupportedActionsSDK(true, true, true, true)]
    [DataServiceKey("ID")]
    public class SalesOrderLine
    {
        /// Amount in the default currency of the company
        [SDKFieldType(FieldType.ReadOnly)]
        public double AmountDC { get; set; }
        /// Amount in the currency of the transaction
        public double AmountFC { get; set; }
        /// Reference to Cost center
        public string CostCenter { get; set; }
        /// Description of CostCenter
        [SDKFieldType(FieldType.ReadOnly)]
        public string CostCenterDescription { get; set; }
        /// Item cost price
        [SDKFieldType(FieldType.ReadOnly)]
        public double? CostPriceFC { get; set; }
        /// Reference to Cost unit
        public string CostUnit { get; set; }
        /// Description of CostUnit
        [SDKFieldType(FieldType.ReadOnly)]
        public string CostUnitDescription { get; set; }
        /// Delivery date of this line
        public DateTime? DeliveryDate { get; set; }
        /// Description
        public string Description { get; set; }
        /// Discount given on the default price. Discount = (DefaultPrice of Item - PriceItem in line) / DefaultPrice of Item
        public double? Discount { get; set; }
        /// Division code
        [SDKFieldType(FieldType.ReadOnly)]
        public Int32 Division { get; set; }
        /// Primary key
        public Guid ID { get; set; }
        /// Reference to the item that is sold in this sales order line
        public Guid? Item { get; set; }
        /// Code of Item
        [SDKFieldType(FieldType.ReadOnly)]
        public string ItemCode { get; set; }
        /// Description of Item
        [SDKFieldType(FieldType.ReadOnly)]
        public string ItemDescription { get; set; }
        /// Item Version
        public Guid? ItemVersion { get; set; }
        /// Description of Item Version
        [SDKFieldType(FieldType.ReadOnly)]
        public string ItemVersionDescription { get; set; }
        /// Line number
        [SDKFieldType(FieldType.ReadOnly)]
        public Int32 LineNumber { get; set; }
        /// Sales margin of the sales order line
        public double? Margin { get; set; }
        /// Net price of the sales order line
        public double? NetPrice { get; set; }
        /// Extra notes
        public string Notes { get; set; }
        /// The OrderID identifies the sales order. All the lines of a sales order have the same OrderID
        public Guid OrderID { get; set; }
        /// Number of sales order
        public Int32 OrderNumber { get; set; }
        /// Price list
        public Guid? Pricelist { get; set; }
        /// Description of Pricelist
        [SDKFieldType(FieldType.ReadOnly)]
        public string PricelistDescription { get; set; }
        /// The project to which the sales order line is linked. The project can be different per line. Sometimes also the project in the header is filled although this is not really used
        public Guid? Project { get; set; }
        /// Description of Project
        [SDKFieldType(FieldType.ReadOnly)]
        public string ProjectDescription { get; set; }
        /// Purchase order that is linked to the sales order
        [SDKFieldType(FieldType.ReadOnly)]
        public Guid? PurchaseOrder { get; set; }
        /// Purchase order line of the purchase order that is linked to the sales order
        [SDKFieldType(FieldType.ReadOnly)]
        public Guid? PurchaseOrderLine { get; set; }
        /// Number of the purchase order line
        [SDKFieldType(FieldType.ReadOnly)]
        public Int32? PurchaseOrderLineNumber { get; set; }
        /// Number of the purchase order
        [SDKFieldType(FieldType.ReadOnly)]
        public Int32? PurchaseOrderNumber { get; set; }
        /// The number of items sold in default units. The quantity shown in the entry screen is Quantity * UnitFactor
        public double? Quantity { get; set; }
        /// The number of items delivered
        [SDKFieldType(FieldType.ReadOnly)]
        public double? QuantityDelivered { get; set; }
        /// The number of items invoiced
        [SDKFieldType(FieldType.ReadOnly)]
        public double? QuantityInvoiced { get; set; }
        /// Reference to ShopOrder
        public Guid? ShopOrder { get; set; }
        /// Obsolete
        public Guid? TaxSchedule { get; set; }
        /// Obsolete
        [SDKFieldType(FieldType.ReadOnly)]
        public string TaxScheduleCode { get; set; }
        /// Obsolete
        [SDKFieldType(FieldType.ReadOnly)]
        public string TaxScheduleDescription { get; set; }
        /// Code of item unit
        public string UnitCode { get; set; }
        /// Description of Unit
        [SDKFieldType(FieldType.ReadOnly)]
        public string UnitDescription { get; set; }
        /// Price per unit in the currency of the transaction
        public double? UnitPrice { get; set; }
        /// Indicates if drop shipment is used (delivery directly to customer, invoice to wholesaler)
        public byte UseDropShipment { get; set; }
        /// VAT amount in the currency of the transaction
        public double? VATAmount { get; set; }
        /// VAT code
        public string VATCode { get; set; }
        /// Description of VATCode
        [SDKFieldType(FieldType.ReadOnly)]
        public string VATCodeDescription { get; set; }
        /// The vat percentage of the VAT code. This is the percentage at the moment the sales order is created. It's also used for the default calculation of VAT amounts and VAT base amounts
        public double? VATPercentage { get; set; }
    }
}


text:
@interface M9ProgressCoverView ()

@property (nonatomic, readwrite) UILabel *progressLabel;
@property (nonatomic, readwrite) UIView *progressView;

@end

@implementation M9ProgressCoverView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.15];

        self.floatEdge = UIRectEdgeTop;
        self.removeFromSuperViewOnCompleted = YES;

        self.progressLabel = ({
            UILabel *label = [[UILabel alloc] initWithFrame:self.bounds];
            label.textColor = [UIColor whiteColor];
            label.backgroundColor = [UIColor clearColor];
            label.textAlignment = NSTextAlignmentCenter;
            _RETURN label;
        });
        [self addSubview:self.progressLabel];
        [self.progressLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self);
        }];

        self.progressView = ({
            UIView *view = [[UIView alloc] initWithFrame:self.bounds];
            view.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.25];
            _RETURN view;
        });
        [self addSubview:self.progressView];

        self.hidden = YES;
    }
    return self;
}

- (void)updateConstraints {
    [self.progressView mas_remakeConstraints:^(MASConstraintMaker *make) {
        switch (self.floatEdge) {
            case UIRectEdgeLeft:
                make.width.equalTo(self).multipliedBy(self.progress);
                make.right.and.bottom.equalTo(self);
                break;
            case UIRectEdgeRight:
                make.width.equalTo(self).multipliedBy(self.progress);
                make.left.top.and.bottom.equalTo(self);
                break;
            case UIRectEdgeBottom:
                make.height.equalTo(self).multipliedBy(self.progress);
                make.left.right.and.top.equalTo(self);
                break;
            default:
                make.height.equalTo(self).multipliedBy(self.progress);
                make.left.right.and.bottom.equalTo(self);
                break;
        }
    }];
    [super updateConstraints];
}

- (void)setProgress:(CGFloat)progress {
    self.completed = NO;

    progress = MIN(MAX(progress, 0.0), 1.0);
    _progress = progress;
    self.progressLabel.text = [NSString stringWithFormat:@" %ld%%", (long)floor(progress * 100)];

    [self setNeedsUpdateConstraints];
}

@dynamic completed;

- (BOOL)isCompleted {
    return self.hidden;
}

- (void)setCompleted:(BOOL)completed {
    if (completed) {
        self.progress = 0.0;
    }

    BOOL removeFromSuperView = (self.removeFromSuperViewOnCompleted
                                && (!self.completed && completed));

    self.hidden = completed;

    if (removeFromSuperView) {
        [self removeFromSuperview];
    }
}

@end


text:
1. Make sure that Npm is installed on your machine (only the first time)

2. Make sure that Bower is installed globally on your machine (only the first time)
$ npm install --global bower

3. Make sure that Gulp is installed globally on your machine (only the first time)
$ npm install --global gulp

4. Restore npm packages
$ npm install

5. Restore bower packages
$ bower install

6. Execute gulp default task
$ gulp


text:
using System.Data.Entity.ModelConfiguration;
using NTierApplications.Domain.Entities;

namespace NTierApplications.Data.Mappings
{
	public class SkillMapping : EntityTypeConfiguration<Skill>
	{
		public SkillMapping()
		{
			Property(x => x.Name)
				.IsRequired()
				.HasMaxLength(50)
				;
		}
	}
}


text:
.class public interface abstract Landroid/content/om/ISamsungOverlayCallback;
.super Ljava/lang/Object;
.source "ISamsungOverlayCallback.java"

# interfaces
.implements Landroid/os/IInterface;

# annotations
.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Landroid/content/om/ISamsungOverlayCallback$Stub;
    }
.end annotation

# virtual methods
.method public abstract overlayStateChanged(Ljava/lang/String;Z)V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method


text:
// Filename: GoogleMapView.js
    // TODO: finish this if we need to use Google Maps.  Import these into main.js

    /* Google Map Addons libraries (if using google maps) */
    //markercluster: 'libs/MarkerClusterer/src/markerclusterer',
    //markermanager: 'libs/MarkerManager/srcmarkermanager',
    //maplabel: 'libs/js-map-label/src/maplabel',
    //infobubble: 'libs/js-info-bubble/src/infobubble',
    //daynightoverlay: 'libs/google-maps-api-addons/daynightoverlay/daynightoverlay'
    //templates: '../templates'

    // Place this into Require.js inside app.js
    // Async loads googlemap api, and provides access to it at the app level
    //'async!http://maps.googleapis.com/maps/api/js?v=3.exp&libraries=visualization',

define([
  'jquery',
  'underscore',
  'backbone',
  'markercluster',
  'collections/Regions',
  'views/map/MapHelper',
], function($, _, Backbone, Marker, Regions, Helper) {

    var MapView = Backbone.View.extend({

    	el: $("#map"),

    	events: {
    	},

   		initialize: function () {
   			console.log('entered mapView:initialize');
   			var that = this;

   			that.regions = new Regions();
   			this.regions.add({ name: "Australia", geoJsonCode: "AUS" });

			var LatLng = new google.maps.LatLng(34, -20);
			var styles = [
				{
					featureType: "road",
					elementType: "geometry",
					stylers: [
						{lightness: 100},
						{visibility: "simplified" }
					],
				},
				{
					featureType: "road",
					elementType: "labels",
					stylers: [
						{visibilty: "off"}
					]
				}
			];
            var myOptions = {
                zoom: 2,
                center: LatLng,
                mapTypeControl: false,
                mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
                navigationControl: false,
                streetViewControl: false,
                zoomControl: false,
                panControl: false,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                styles: styles
            };

            that.map = new google.maps.Map(this.el, myOptions);
   		},

    	render: function() {
    		console.log('entered mapView:render');
    		var theMap = this.map;
    		this.regions.each(function(log) {
    			$.get('https://raw.githubusercontent.com/johan/world.geo.json/master/countries/AUS.geo.json', log.populateGeoJsonData);
		        console.log('log item.', log);

		        theMap.data.addGeoJson(log.get('geoJsonData'));
		    });
    		return this;
    	},

    });
    return MapView;
 });


text:
package org.apache.lucene.search;

import org.apache.lucene.util.BytesRef;

/**
 * A Filter that restricts search results to a range of term
 * values in a given field.
 *
 *
This filter matches the documents looking for terms that fall into the
 * supplied range according to {@link
 * Byte#compareTo(Byte)},  It is not intended
 * for numerical ranges; use {@link NumericRangeFilter} instead.
 *
 *
If you construct a large number of range filters with different ranges but on the
 * same field, {@link FieldCacheRangeFilter} may have significantly better performance.
 * @since 2.9
 */
public class TermRangeFilter extends MultiTermQueryWrapperFilter<TermRangeQuery> {

  /**
   * @param fieldName The field this range applies to
   * @param lowerTerm The lower bound on this range
   * @param upperTerm The upper bound on this range
   * @param includeLower Does this range include the lower bound?
   * @param includeUpper Does this range include the upper bound?
   * @throws IllegalArgumentException if both terms are null or if
   *  lowerTerm is null and includeLower is true (similar for upperTerm
   *  and includeUpper)
   */
  public TermRangeFilter(String fieldName, BytesRef lowerTerm, BytesRef upperTerm,
                     boolean includeLower, boolean includeUpper) {
      super(new TermRangeQuery(fieldName, lowerTerm, upperTerm, includeLower, includeUpper));
  }

  /**
   * Factory that creates a new TermRangeFilter using Strings for term text.
   */
  public static TermRangeFilter newStringRange(String field, String lowerTerm, String upperTerm, boolean includeLower, boolean includeUpper) {
    BytesRef lower = lowerTerm == null ? null : new BytesRef(lowerTerm);
    BytesRef upper = upperTerm == null ? null : new BytesRef(upperTerm);
    return new TermRangeFilter(field, lower, upper, includeLower, includeUpper);
  }

  /**
   * Constructs a filter for field fieldName matching
   * less than or equal to upperTerm.
   */
  public static TermRangeFilter Less(String fieldName, BytesRef upperTerm) {
      return new TermRangeFilter(fieldName, null, upperTerm, false, true);
  }

  /**
   * Constructs a filter for field fieldName matching
   * greater than or equal to lowerTerm.
   */
  public static TermRangeFilter More(String fieldName, BytesRef lowerTerm) {
      return new TermRangeFilter(fieldName, lowerTerm, null, true, false);
  }

  /** Returns the lower value of this range filter */
  public BytesRef getLowerTerm() { return query.getLowerTerm(); }

  /** Returns the upper value of this range filter */
  public BytesRef getUpperTerm() { return query.getUpperTerm(); }

  /** Returns true if the lower endpoint is inclusive */
  public boolean includesLower() { return query.includesLower(); }

  /** Returns true if the upper endpoint is inclusive */
  public boolean includesUpper() { return query.includesUpper(); }
}


text:
package springfox.documentation.schema;

import com.fasterxml.classmate.ResolvedType;
import com.fasterxml.classmate.TypeResolver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import springfox.documentation.schema.plugins.SchemaPluginsManager;
import springfox.documentation.schema.property.ModelPropertiesProvider;
import springfox.documentation.schema.property.ModelSpecificationFactory;
import springfox.documentation.spi.schema.EnumTypeDeterminer;
import springfox.documentation.spi.schema.contexts.ModelContext;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Collectors;

import static java.util.Optional.*;
import static java.util.function.Function.*;
import static springfox.documentation.schema.Collections.*;
import static springfox.documentation.schema.Maps.*;
import static springfox.documentation.schema.ResolvedTypes.*;
import static springfox.documentation.schema.property.PackageNames.*;

@Component
@Qualifier("default")
public class DefaultModelSpecificationProvider implements ModelSpecificationProvider {
  private static final Logger LOG = LoggerFactory.getLogger(DefaultModelSpecificationProvider.class);
  private final TypeResolver resolver;
  private final ModelPropertiesProvider propertiesProvider;
  private final ModelDependencyProvider dependencyProvider;
  private final SchemaPluginsManager schemaPluginsManager;
  private final TypeNameExtractor typeNameExtractor;
  private final EnumTypeDeterminer enumTypeDeterminer;
  private final ModelSpecificationFactory modelSpecifications;

  @Autowired
  public DefaultModelSpecificationProvider(
      TypeResolver resolver,
      @Qualifier("cachedModelProperties") ModelPropertiesProvider propertiesProvider,
      @Qualifier("cachedModelDependencies") ModelDependencyProvider dependencyProvider,
      SchemaPluginsManager schemaPluginsManager,
      TypeNameExtractor typeNameExtractor,
      EnumTypeDeterminer enumTypeDeterminer,
      ModelSpecificationFactory modelSpecifications) {
    this.resolver = resolver;
    this.propertiesProvider = propertiesProvider;
    this.dependencyProvider = dependencyProvider;
    this.schemaPluginsManager = schemaPluginsManager;
    this.typeNameExtractor = typeNameExtractor;
    this.enumTypeDeterminer = enumTypeDeterminer;
    this.modelSpecifications = modelSpecifications;
  }

  @Override
  public Optional<ModelSpecification> modelSpecificationsFor(ModelContext modelContext) {
    ResolvedType propertiesHost = modelContext.alternateEvaluatedType();

    if (isContainerType(propertiesHost)
        || isMapType(propertiesHost)
        || enumTypeDeterminer.isEnum(propertiesHost.getErasedType())
        || ScalarTypes.builtInScalarType(propertiesHost).isPresent()
        || modelContext.hasSeenBefore(propertiesHost)) {
      LOG.debug(
          "Skipping model of type {} as its either a container type, map, enum or base type, or its already "
              + "been handled",
          resolvedTypeSignature(propertiesHost).orElse("<null>"));
      return empty();
    }

    Optional<ModelSpecification> syntheticModel = schemaPluginsManager.syntheticModelSpecification(modelContext);
    if (syntheticModel.isPresent()) {
      return of(schemaPluginsManager.modelSpecification(modelContext));
    }
    return reflectionBasedModel(
        modelContext,
        propertiesHost);
  }

  private Optional<ModelSpecification> reflectionBasedModel(
      ModelContext modelContext,
      ResolvedType propertiesHost) {
    Map<String, PropertySpecification> propertiesIndex
        = properties(
        modelContext,
        propertiesHost).stream()
        .collect(Collectors.toMap(
            PropertySpecification::getName,
            identity()));
    LOG.debug(
        "Inferred {} properties. Properties found {}",
        propertiesIndex.size(),
        String.join(
            ", ",
            propertiesIndex.keySet()));
    return of(modelBuilder(
        propertiesHost,
        new TreeMap<>(propertiesIndex),
        modelContext));
  }

  private ModelSpecification modelBuilder(
      ResolvedType propertiesHost,
      Map<String, PropertySpecification> properties,
      ModelContext modelContext) {
    String typeName = typeNameExtractor.typeName(ModelContext.fromParent(
        modelContext,
        propertiesHost));
    modelContext.getModelSpecificationBuilder()
        .name(typeName)
        .compoundModel(cm ->
            cm.modelKey(m ->
                m.qualifiedModelName(q ->
                    q.namespace(safeGetPackageName(propertiesHost))
                        .name(typeName))
                    .viewDiscriminator(modelContext.getView().orElse(null))
                    .validationGroupDiscriminators(modelContext.getValidationGroups())
                    .isResponse(modelContext.isReturnType())
                    .build())
                .properties(properties.values()));
    return schemaPluginsManager.modelSpecification(modelContext);
  }

  @Override
  public Set<ModelSpecification> modelDependenciesSpecifications(ModelContext modelContext) {
    Set<ModelSpecification> models = new HashSet<>();
    for (ResolvedType resolvedType : dependencyProvider.dependentModels(modelContext)) {
      ModelContext parentContext = ModelContext.fromParent(
          modelContext,
          resolvedType);
      Optional<ModelSpecification> model = modelSpecificationsFor(parentContext);
      if (model.isPresent()) {
        models.add(model.get());
      } else {
        mapModel(parentContext, resolvedType).ifPresent(models::add);
      }
    }
    return models;
  }

  private Optional<ModelSpecification> mapModel(
      ModelContext mapContext,
      ResolvedType resolvedType) {
    if (isMapType(resolvedType) && !mapContext.hasSeenBefore(resolvedType)) {
      ResolvedType keyType = resolver.resolve(String.class);
      ModelContext keyContext = ModelContext.fromParent(
          mapContext,
          keyType);
      ResolvedType valueType = mapValueType(resolvedType);
      ModelContext valueContext = ModelContext.fromParent(
          mapContext,
          valueType);
      return of(
          mapContext.getModelSpecificationBuilder()
              .mapModel(m ->
                  m.key(k ->
                      k.copyOf(modelSpecifications.create(
                          keyContext,
                          keyType)))
                      .value(v -> v.copyOf(modelSpecifications.create(
                          valueContext,
                          valueType))))
              .build());
    }
    return empty();
  }

  private List<PropertySpecification> properties(
      ModelContext context,
      ResolvedType propertiesHost) {
    String typeName = typeNameExtractor.typeName(context);
    return propertiesProvider.propertySpecificationsFor(
        propertiesHost,
        context);
  }
}


text:
/**
 * This script has two purposes
 * - Advanced search engine
 */

var getUrlParameter = function getUrlParameter(sParam) {
    var sPageURL = decodeURIComponent(window.location.search.substring(1)),
            sURLVariables = sPageURL.split('&'),
            sParameterName,
            i;

    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');

        if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ? true : sParameterName[1];
        }
    }
};
var Filter = function (name, category) {
    this.name = name;
};
//se crea Objeto para guardar datos
var advStorage = new Storage();
var advSearchSrcUrl = baseUrl + "advancedsearch";
var filterColumnClass = ".advs-filters-colum";
var mainContainerClass = '.advs-container';//config
var filterTagClass = '.advs-filter';//config
var filterSelectedClass = 'advs-filter-selected';//config
var appliedFilters = [];//filtros aplicados
$(document).ready(function () {
    var query = getUrlParameter('query');
    if (query !== undefined) {//maybe show error
        setQueryParam(query);
    }
//load applied filters ON DOCUMENT READY!->
    if (advStorage.getSiteWideValue("advs-applied-filters") !== undefined && JSON.parse(advStorage.getSiteWideValue("advs-applied-filters")).length > 0)
        appliedFilters = JSON.parse(advStorage.getSiteWideValue("advs-applied-filters"));
//poner como seleccionado a los que se encuentran seleccionados
    $(filterTagClass).each(function () {
        if (appliedFilters.length === 0)
            return;

        var name = $(this).attr('data-filter-name');
        if (name.length > 0 && $.inArray(name, appliedFilters) > -1) {
            //esta dentro del array de filtros aplicados
            $(this).addClass(filterSelectedClass);
        }
        //mostrar
        $(mainContainerClass).show();

    });
    function getQueryParam() {
        return $("#advs-query").val();
    }
    function setQueryParam(value) {
        $("#advs-query").val(value);
    }

    $("#advs-query").keyup(function (e) {
        if (e.keyCode === 13) {
            //do search
            var page = getUrlParameter('page');
            if (page === undefined)
                page = '1';
            filters = '';
            appliedFilters.forEach(function (n) {
                filters += n + ",";
            });
            window.location.href = advSearchSrcUrl + '?query=' + $(this).val() + '&filters=' + filters + '&page=' + page;
            return;
        }
    });

    $(filterTagClass).click(function () {

        var query = getQueryParam();
        if (query === undefined) {//maybe show error
            alert("No hay nada que buscar");
            return;
        }
        var name = $(this).attr('data-filter-name');
        if (!$(this).hasClass(filterSelectedClass)) {

            //check if there is already a value selected in this column to unselect it
            var sibilings = $(this).parents(filterColumnClass).find(filterTagClass);
            sibilings.each(function (i, o) {
                if ($(o).hasClass(filterSelectedClass)) {
                    var oname = $(o).attr('data-filter-name');
                    $(o).removeClass(filterSelectedClass);
                    appliedFilters.forEach(function (n, index) {
                        if (n === oname) {
                            appliedFilters.splice(index, 1);
                        }
                    });
                }
            });
            //adding. . .
            appliedFilters.push(name);
            advStorage.setSiteWideValue("advs-applied-filters", JSON.stringify(appliedFilters));
            $(this).addClass(filterSelectedClass);

            var page = getUrlParameter('page');
            if (page === undefined)
                page = '1';
            filters = '';
            appliedFilters.forEach(function (n) {
                filters += n + ",";
            });
            window.location.href = advSearchSrcUrl + '?query=' + query + '&filters=' + filters + '&page=' + page;
            return;
        } else {
            //removing. . .
            $(this).removeClass(filterSelectedClass);
            //sacar del array appliedFilters
            appliedFilters.forEach(function (n, index) {
                if (name === n) {
                    appliedFilters.splice(index, 1);
                    return;//break?
                }
            });

            advStorage.setSiteWideValue("advs-applied-filters", JSON.stringify(appliedFilters));
            var page = getUrlParameter('page');
            if (page === undefined)
                page = '1';
            filters = '';
            appliedFilters.forEach(function (n) {
                filters += n + ",";
            });
            window.location.href = advSearchSrcUrl + '?query=' + query + '&filters=' + filters + '&page=' + page;
            return;
        }
    });
//<-ON DOCUMENT READY!
});

advStorage.setSiteWideValue("COOKIE1", "TASTY!!!");
console.log(advStorage.getSiteWideValue("COOKIE1"));


text:
require 'spec_helper'

describe "Sessions" do

  subject { page }

  describe "signin page" do
    before { visit new_user_session_path }

    it { should have_selector "h2", text: "Zugang für Organisatoren" }
    it { should have_field "E-Mail", type: "email", text: "" }
    it { should have_field "Passwort", type: "password", text: "" }
    it { should have_button "Anmelden" }
  end

  describe "signin via the signin page" do
    before { visit new_user_session_path }

    describe "with incorrect credentials" do
      before { click_button "Anmelden" }

      it "should not display any inside stuff" do
        page.should_not have_selector "li", text: "Verwalten"
        page.should_not have_link "Vorspiele"
      end

      it { should_not have_link "Abmelden", href: destroy_user_session_path }
      it { should have_link "Interne Seiten »", href: new_user_session_path }

      it "should redirect to the signin page" do
        current_path.should eq new_user_session_path
      end

      it { should have_error_message }
      it { should have_content "Die E-Mailadresse oder das Passwort war falsch." }

      describe "after revisiting the page" do
        before { click_link "Interne Seiten »" }

        it { should_not have_error_message }
      end
    end

    describe "with valid credentials" do
      let(:user) { create(:user) }
      before { sign_in user }

      it "should display some inside stuff" do
        page.should have_selector "li", text: "Einsehen"
        page.should have_link "Aktuelle Vorspiele"
      end

      it "should have a link to the user profile"
      it "should display the user's full name in the top bar" do
        page.should have_selector "header a", text: user.full_name
      end

      it { should have_link "Abmelden", href: destroy_user_session_path }
      it { should_not have_link "Interne Seiten »", href: new_user_session_path }

      describe "followed by signout" do
        before { click_link "Abmelden" }

        it { should have_link "Interne Seiten »", href: new_user_session_path }
      end
    end
  end

  describe "requesting a page restricted to signed-in users" do
    before { visit list_current_jmd_performances_path }

    it "should ask the user to sign in first" do
      current_path.should eq new_user_session_path
      page.should have_alert_message
      page.should have_content "Bitte melde dich mit ausreichenden Rechten an, um diese Seite zu besuchen."
    end

    it "should present a signin form" do

    end

    it "should redirect to the requested page after signing in through the form" do
      user = create(:user)
      fill_in "session_email", with: user.email
      fill_in "session_password", with: user.password
      click_button "session_submit"

      current_path.should eq list_current_jmd_performances_path
      page.should have_info_message
      page.should have_content "Willkommen, #{user.full_name}! Du bist jetzt angemeldet."
    end
  end

  describe "requesting a page restricted to admins" do
    before { visit jmd_users_path }

    it "should ask the user to sign in first" do
      current_path.should eq new_user_session_path
      page.should have_alert_message
      page.should have_content "Bitte melde dich mit ausreichenden Rechten an, um diese Seite zu besuchen."
    end

    context "as a non-admin user" do

      it "should ask the user to sign in with sufficient rights" do
        user = create(:user)
        sign_in(user)

        current_path.should eq new_user_session_path
        page.should have_alert_message
        page.should have_content "Bitte melde dich mit ausreichenden Rechten an, um diese Seite zu besuchen."
      end
    end

    context "as an admin user" do

      it "should give access to the page" do
        admin = create(:admin)
        sign_in(admin)

        current_path.should eq jmd_users_path
        page.should have_info_message
        page.should have_content "Willkommen, #{admin.full_name}! Du bist jetzt angemeldet."
      end
    end
  end

  describe "inside sidebar" do
    before { visit root_path }

    describe "for non-admins" do
      let(:user) { create(:user) }
      before { sign_in user }

      it { should_not have_link "Benutzer", href: jmd_users_path }
      it { should_not have_link "Wettbewerbe", href: jmd_competitions_path }
      it { should have_link "Aktuelle Vorspiele", href: list_current_jmd_performances_path }
    end

    describe "for admins" do
      let(:admin) { create(:admin) }
      before { sign_in admin }

      it { should have_link "Benutzer", href: jmd_users_path }
      it { should have_link "Wettbewerbe", href: jmd_competitions_path }
      it { should have_link "Aktuelle Vorspiele", href: list_current_jmd_performances_path }
    end
  end
end


text:
Currently, Programming Battle has only been tested and supported on Ubuntu Trusty.

## Step 1: set up the database

* Install postgres
* Create an empty databse
* Create a user who owns the database
* Enter the database connection string in your battle.yaml config

## Step 2: create programming battle folders

* /opt/progbattle which is owned by the user running the backend and frontend
* /opt/progbattle/runs which is world writable (this is where judging happens)
* /opt/progbattle/bin

## Step 3: setup isolate

* Setup Linux cgroups
* Compile isolate (make external/isolate)
* Move the isolate binary to /opt/progbattle/bin
* Make root the owner of the binary
* Make the binary setuid

## Step 4: Python dependencies

* Install the dependencies listed in battle/setup.py

## Step 5: running

* PYTHONPATH=battle:. ./scripts/start_web.py
* PYTHONPATH=battle:. ./scripts/start_daemon.py


text:
#################################################################################
#
# The MIT License (MIT)
#
# Copyright (c) 2015 Dmitry Sovetov
#
# https://github.com/dmsovetov
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
#################################################################################

from Resource       import Resource
from ObjectList     import ObjectList
from ...Template    import Template

# class ConfigurationList
class ConfigurationList( Resource ):
	# ctor
	def __init__( self, default, owner ):
		Resource.__init__( self, 'XCConfigurationList', None )

		self.default = default
		self.owner   = owner
		self.items   = ObjectList()

	# add
	def add( self, item ):
		self.items.add( item )

	# forEach
	def forEach( self, callback ):
		for item in self.items.items:
			callback( item )

	# compile
	def compile( self ):
		return Template( ConfigurationList.Root ).compile( { 'id': self.id, 'isa': self.isa, 'items': self.items.compileList(), 'default': self.default, 'owner': self.owner.name, 'owner.isa': self.owner.isa } )

	# Root
	Root = """
		{id} /* Build configuration list for {owner.isa} {owner} */ = {
			isa = {isa};
			buildConfigurations = (
{items}
			);
			defaultConfigurationIsVisible = 0;
			defaultConfigurationName = {default};
		};
"""


text:
@implementation UIAlertController (MKAdd)

#pragma mark - ***** system style *****
+ (instancetype)mk_alertWithTitle:(NSString *)title
                          message:(NSString *)message
                   preferredStyle:(UIAlertControllerStyle)style
                            block:(void (^)(NSInteger buttonIndex))block
                     buttonTitles:(NSString *)cancelTitle, ... NS_REQUIRES_NIL_TERMINATION{

    NSMutableArray *argsArray = [[NSMutableArray alloc] init];
    if (cancelTitle) {
        [argsArray addObject:cancelTitle];
        va_list argList;
        va_start(argList, cancelTitle);
        NSString *btnTitle;
        while ((btnTitle = va_arg(argList, NSString *))) {
            [argsArray addObject:btnTitle];
        }
        va_end(argList);
    }
    return [self mk_alertWithTitle:title message:message buttonTitles:argsArray preferredStyle:style block:block];
}

+ (instancetype)mk_alertWithTitle:(NSString *)title
                          message:(NSString *)message
                      cancelTitle:(NSString *)cancelTitle
                     confirmTitle:(NSString *)confirmTitle
                   preferredStyle:(UIAlertControllerStyle)style
                            block:(void (^)(NSInteger buttonIndex))block{
    return [self mk_alertWithTitle:title message:message cancelTitle:cancelTitle confirmTitle:confirmTitle preferredStyle:style config:nil block:block];
}

+ (instancetype)mk_alertWithTitle:(NSString *)title
                          message:(NSString *)message
                     buttonTitles:(NSArray *)buttonTitles
                   preferredStyle:(UIAlertControllerStyle)style
                            block:(void (^)(NSInteger buttonIndex))block{
    return [self mk_alertWithTitle:title message:message buttonTitles:buttonTitles preferredStyle:style config:nil block:block];

}

#pragma mark - ***** custom style *****
+ (instancetype)mk_alertWithTitle:(NSString *)title
                          message:(NSString *)message
                   preferredStyle:(UIAlertControllerStyle)style
                           config:(MKAlertCtrlConfig *)config
                            block:(void (^)(NSInteger buttonIndex))block
                     buttonTitles:(NSString *)cancelTitle, ... NS_REQUIRES_NIL_TERMINATION{

    NSMutableArray *argsArray = [[NSMutableArray alloc] init];
    if (cancelTitle) {
        [argsArray addObject:cancelTitle];
        va_list argList;
        va_start(argList, cancelTitle);
        NSString *btnTitle;
        while ((btnTitle = va_arg(argList, NSString *))) {
            [argsArray addObject:btnTitle];
        }
        va_end(argList);
    }
    return [self mk_alertWithTitle:title message:message buttonTitles:argsArray preferredStyle:style config:config block:block];
}

+ (instancetype)mk_alertWithTitle:(NSString *)title
                          message:(NSString *)message
                      cancelTitle:(NSString *)cancelTitle
                     confirmTitle:(NSString *)confirmTitle
                   preferredStyle:(UIAlertControllerStyle)style
                           config:(MKAlertCtrlConfig *)config
                            block:(void (^)(NSInteger buttonIndex))block{

    if (config == nil) {
        config = [[MKAlertCtrlConfig alloc] init];
    }
    NSMutableArray *buttons = @[].mutableCopy;
    if (cancelTitle && cancelTitle.length > 0) {
        [buttons addObject:cancelTitle];
        if (config.cancelIndex < 0) {
            config.cancelIndex = 0;
        }
    }

    if (confirmTitle && confirmTitle.length > 0) {
        [buttons addObject:confirmTitle];
    }
    return [self mk_alertWithTitle:title message:message buttonTitles:buttons preferredStyle:style config:config block:block];
}

+ (instancetype)mk_alertWithTitle:(NSString *)title
                          message:(NSString *)message
                     buttonTitles:(NSArray *)buttonTitles
                   preferredStyle:(UIAlertControllerStyle)style
                           config:(MKAlertCtrlConfig *)config
                            block:(void (^)(NSInteger buttonIndex))block{

    if (!buttonTitles || buttonTitles.count == 0) {
        NSAssert(NO, @"MKAlertView: buttonTitles count 必须大于 0");
        return  nil;
    }else if ([[[UIDevice currentDevice] systemVersion] floatValue] < 8.0){
        NSAssert(NO, @"UIDevice system version must more than 8.0");
        return nil;
    }
    UIAlertController *alertController = [self alertControllerWithTitle:title message:message preferredStyle:style];
    alertController.title = title;
    alertController.message = message;
    if (!config) {
        config = [[MKAlertCtrlConfig alloc] init];
    }

    [alertController mk_setupUIWith:buttonTitles config:config block:block];
    [alertController.view setNeedsLayout];
    [alertController.view layoutIfNeeded];
    return alertController;

}

- (void)mk_setupUIWith:(NSArray *)buttons config:(MKAlertCtrlConfig *)config block:(void (^)(NSInteger buttonIndex))block{
    if (buttons && buttons.count > 0 ) {
        for (int i = 0; i < buttons.count; i++) {
            UIAlertActionStyle style = UIAlertActionStyleDefault;
            if (i == config.cancelIndex) {
                style = UIAlertActionStyleCancel;
            }else if (i == config.destructiveIndex){
                style = UIAlertActionStyleDestructive;
            }
            UIAlertAction *action = [UIAlertAction actionWithTitle:buttons[i] style:style handler:^(UIAlertAction * _Nonnull action) {
                if (block) {
                    block(i);
                }
            }];
            [self addAction:action];
        }
    }
    [self mk_setCustomStyleWith:config];
}

- (void)mk_setCustomStyleWith:(MKAlertCtrlConfig *)config{

    unsigned int count = 0;
    //runtime
    //message text
    Ivar *property = class_copyIvarList([UIAlertController class], &count);
    for(int k = 0; k < count; k++){
        Ivar ivar = property[k];
        NSString *ivarName = [NSString stringWithCString:ivar_getName(ivar) encoding:NSUTF8StringEncoding];
        NSString *ivarType = [NSString stringWithCString:ivar_getTypeEncoding(ivar) encoding:NSUTF8StringEncoding];

        if ([ivarName isEqualToString:@"_attributedTitle"] && [ivarType isEqualToString:@"@\"NSAttributedString\""]){
            if (self.title && self.title.length) {
                NSRange titleRange = NSMakeRange(0, self.title.length);
                NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:self.title attributes:nil];
                if (config.titleFont) {
                    [attributedString addAttribute:NSFontAttributeName value:config.titleFont range:titleRange];
                }
                if (config.titleColor) {
                    [attributedString addAttribute:NSForegroundColorAttributeName value:config.titleColor range:titleRange];
                }

                NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
                paragraphStyle.alignment = config.titleAlignment;//设置对齐方式
                [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:titleRange];
                [self setValue:attributedString forKey:@"attributedTitle"];
            }
        }else if ([ivarName isEqualToString:@"_attributedMessage"] && [ivarType isEqualToString:@"@\"NSAttributedString\""]) {
            if (self.message && self.message.length) {
                NSRange messageRange = NSMakeRange(0, self.message.length);
                NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:self.message attributes:nil];
                if (config.messageFont) {
                    [attributedString addAttribute:NSFontAttributeName value:config.messageFont range:messageRange];
                }
                if (config.messageColor) {
                    [attributedString addAttribute:NSForegroundColorAttributeName value:config.messageColor range:messageRange];
                }

                NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
                paragraphStyle.alignment = config.messageAlignment;//设置对齐方式
                [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:messageRange];
                [self setValue:attributedString forKey:@"attributedMessage"];
            }
        }
    }
    free(property);
    //action
    Ivar *ivars = class_copyIvarList([UIAlertAction class], &count);
    for (int i = 0; i < self.actions.count; i++) {
        UIAlertAction *action = self.actions[i];
        for(int j = 0; j < count; j++){
            Ivar ivar = ivars[j];
            NSString *ivarName = [NSString stringWithCString:ivar_getName(ivar) encoding:NSUTF8StringEncoding];
            if ([ivarName isEqualToString:@"_titleTextColor"]) {
                if (i == config.destructiveIndex || action.style == UIAlertActionStyleDestructive) {
                    if (config.destructiveColor) {
                        [action setValue:config.destructiveColor forKey:@"titleTextColor"];
                    }else{
                        [action setValue:[UIColor redColor] forKey:@"titleTextColor"];
                    }
                }else{
                    [action setValue:config.actionColor forKey:@"titleTextColor"];
                }
            }
        }
    }
    free(ivars);
}

@end

@implementation MKAlertCtrlConfig
- (id)init{
    if (self = [super init]) {
        _titleFont = [UIFont boldSystemFontOfSize:17];
        _titleColor = [UIColor blackColor];
        _titleAlignment = NSTextAlignmentCenter;
        _messageFont = [UIFont systemFontOfSize:13];
        _messageColor = [UIColor blackColor];
        _messageAlignment = NSTextAlignmentCenter;
        _cancelIndex = -1;
        _destructiveIndex = -1;
    }
    return self;
}
@end


text:
<?php

class LogController extends Zend_Controller_Action
{
    public function xmlAction()
    {
        header("Content-type: text/xml");
        echo file_get_contents("/tmp/myosg.log.xml");
        $this->render("none", null, true);
    }
}


text:
var express = require('express');
var router = express.Router();
var mongodb = require('mongodb');
var monk = require('monk');
var credentials = require('../credentials');
var db = monk(credentials.uri);
var cors = require('cors');

// GET scores
router.get('/', cors(), function(req, res) {
  console.log('GET scores');
  var collection = db.get('scores');
  // Find all entries, sort by score (ascending)
  collection.find({}, { sort: { score: 1 } }, function (err, docs) {
    if (err) {
        // Handle error
        console.error('Failed to get scores', err);
        res.status(500).send('Failed to get scores');
    } else {
        res.json(docs);
    }
  });
});

module.exports = router;


text:
Load message data per locale.

### Parameters

**locale**

Locale string.

**messageData**

JSON object with message data;

### Example

```javascript
Globalize.loadMessages( "pt_BR", {
  greetings: {
    hello: "Olá",
    bye: "Tchau"
  }
});
```