text:
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2011-2013 The PPCoin developers
// Copyright (c) 2013-2014 The Peershares developers
// Copyright (c) 2014-2015 The Nu developers

// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "db.h"
#include "walletdb.h"
#include "bitcoinrpc.h"
#include "net.h"
#include "init.h"
#include "util.h"
#include "wallet.h"
#include "ui_interface.h"
#include "checkpoints.h"
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/filesystem/convenience.hpp>
#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/format.hpp>
#include <boost/lexical_cast.hpp>
#include <curl/curl.h>

#ifndef WIN32
#include <signal.h>
#endif

using namespace std;
using namespace boost;

//////////////////////////////////////////////////////////////////////////////
//
// Shutdown
//

void ExitTimeout(void* parg)
{
#ifdef WIN32
    Sleep(5000);
    ExitProcess(0);
#endif
}

void StartShutdown()
{
#ifdef QT_GUI
    // ensure we leave the Qt main loop for a clean GUI exit (Shutdown() is called in bitcoin.cpp afterwards)
    QueueShutdown();
#else
    // Without UI, Shutdown() can simply be started in a new thread
    CreateThread(Shutdown, NULL);
#endif
}

void Shutdown(void* parg)
{
    static CCriticalSection cs_Shutdown;
    static bool fTaken;
    bool fFirstThread = false;
    {
        TRY_LOCK(cs_Shutdown, lockShutdown);
        if (lockShutdown)
        {
            fFirstThread = !fTaken;
            fTaken = true;
        }
    }
    static bool fExit;
    if (fFirstThread)
    {
        fShutdown = true;
        nTransactionsUpdated++;
        DBFlush(false);
        StopNode();
        DBFlush(true);
        curl_global_cleanup();
        boost::filesystem::remove(GetPidFile());
        UnregisterAndDeleteAllWallets();
        CreateThread(ExitTimeout, NULL);
        Sleep(50);
        printf("Nu exiting\n\n");
        fExit = true;
#ifndef QT_GUI
        // ensure non UI client get's exited here, but let Nu-Qt reach return 0; in bitcoin.cpp
        exit(0);
#endif
    }
    else
    {
        while (!fExit)
            Sleep(500);
        Sleep(100);
        ExitThread(0);
    }
}

void HandleSIGTERM(int)
{
    fRequestShutdown = true;
}

//////////////////////////////////////////////////////////////////////////////
//
// Start
//
#if !defined(QT_GUI)
int main(int argc, char* argv[])
{
    bool fRet = false;
    fRet = AppInit(argc, argv);

    if (fRet && fDaemon)
        return 0;

    return 1;
}
#endif

bool AppInit(int argc, char* argv[])
{
    bool fRet = false;
    try
    {
        fRet = AppInit2(argc, argv);
    }
    catch (std::exception& e) {
        PrintException(&e, "AppInit()");
    } catch (...) {
        PrintException(NULL, "AppInit()");
    }
    if (!fRet)
        Shutdown(NULL);
    return fRet;
}

bool AppInit2(int argc, char* argv[])
{
#ifdef _MSC_VER
    // Turn off microsoft heap dump noise
    _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
    _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
#endif
#if _MSC_VER >= 1400
    // Disable confusing "helpful" text message on abort, ctrl-c
    _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
#endif
#ifndef WIN32
    umask(077);
#endif
#ifndef WIN32
    // Clean shutdown on SIGTERM
    struct sigaction sa;
    sa.sa_handler = HandleSIGTERM;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;
    sigaction(SIGTERM, &sa, NULL);
    sigaction(SIGINT, &sa, NULL);
    sigaction(SIGHUP, &sa, NULL);
#endif

    //
    // Parameters
    //
    // If Qt is used, parameters/nu.conf are parsed in qt/bitcoin.cpp's main()
#if !defined(QT_GUI)
    ParseParameters(argc, argv);
    if (!boost::filesystem::is_directory(GetDataDir(false)))
    {
        fprintf(stderr, "Error: Specified directory does not exist\n");
        Shutdown(NULL);
    }
    ReadConfigFile(mapArgs, mapMultiArgs);
    ReadPeercoinConfigFile(mapPeercoinArgs);
#endif

    if (mapArgs.count("-?") || mapArgs.count("--help"))
    {
        string strUsage = string() +
          _("Nu version") + " " + FormatFullVersion() + "\n\n" +
          _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
            "  nud [options]                   \t  " + "\n" +
            "  nud [options] <command> [params]\t  " + _("Send command to -server or nud") + "\n" +
            "  nud [options] help              \t\t  " + _("List commands") + "\n" +
            "  nud [options] help <command>    \t\t  " + _("Get help for a command") + "\n" +
          _("Options:") + "\n" +
            "  -conf=<file>     \t\t  " + _("Specify configuration file (default: nu.conf)") + "\n" +
            "  -pid=<file>      \t\t  " + _("Specify pid file (default: nud.pid)") + "\n" +
            "  -gen             \t\t  " + _("Generate coins") + "\n" +
            "  -gen=0           \t\t  " + _("Don't generate coins") + "\n" +
            "  -min             \t\t  " + _("Start minimized") + "\n" +
            "  -splash          \t\t  " + _("Show splash screen on startup (default: 1)") + "\n" +
            "  -datadir=<dir>   \t\t  " + _("Specify data directory") + "\n" +
            "  -dbcache=<n>     \t\t  " + _("Set database cache size in megabytes (default: 25)") + "\n" +
            "  -dblogsize=<n>   \t\t  " + _("Set database disk log size in megabytes (default: 100)") + "\n" +
            "  -timeout=<n>     \t  "   + _("Specify connection timeout (in milliseconds)") + "\n" +
            "  -proxy=<ip:port> \t  "   + _("Connect through socks4 proxy") + "\n" +
            "  -dns             \t  "   + _("Allow DNS lookups for addnode and connect") + "\n" +
            "  -port=<port>     \t\t  " + _("Listen for connections on <port> (default: 7890 or testnet: 7895)") + "\n" +
            "  -maxconnections=<n>\t  " + _("Maintain at most <n> connections to peers (default: 125)") + "\n" +
            "  -addnode=<ip>    \t  "   + _("Add a node to connect to and attempt to keep the connection open") + "\n" +
            "  -connect=<ip>    \t\t  " + _("Connect only to the specified node") + "\n" +
            "  -listen          \t  "   + _("Accept connections from outside (default: 1)") + "\n" +
#ifdef QT_GUI
            "  -lang=<lang>     \t\t  " + _("Set language, for example \"de_DE\" (default: system locale)") + "\n" +
#endif
            "  -dnsseed         \t  "   + _("Find peers using DNS lookup (default: 1)") + "\n" +
            "  -banscore=<n>    \t  "   + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" +
            "  -bantime=<n>     \t  "   + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" +
            "  -maxreceivebuffer=<n>\t  " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 10000)") + "\n" +
            "  -maxsendbuffer=<n>\t  "   + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 10000)") + "\n" +
#ifdef USE_UPNP
#if USE_UPNP
            "  -upnp            \t  "   + _("Use Universal Plug and Play to map the listening port (default: 1)") + "\n" +
#else
            "  -upnp            \t  "   + _("Use Universal Plug and Play to map the listening port (default: 0)") + "\n" +
#endif
            "  -detachdb        \t  "   + _("Detach block and address databases. Increases shutdown time (default: 0)") + "\n" +
#endif
#ifdef QT_GUI
            "  -server          \t\t  " + _("Accept command line and JSON-RPC commands") + "\n" +
#endif
#if !defined(WIN32) && !defined(QT_GUI)
            "  -daemon          \t\t  " + _("Run in the background as a daemon and accept commands") + "\n" +
#endif
            "  -testnet         \t\t  " + _("Use the test network") + "\n" +
            "  -debug           \t\t  " + _("Output extra debugging information") + "\n" +
            "  -logtimestamps   \t  "   + _("Prepend debug output with timestamp") + "\n" +
            "  -printtoconsole  \t  "   + _("Send trace/debug info to console instead of debug.log file") + "\n" +
#ifdef WIN32
            "  -printtodebugger \t  "   + _("Send trace/debug info to debugger") + "\n" +
#endif
            "  -rpcuser=<user>  \t  "   + _("Username for JSON-RPC connections") + "\n" +
            "  -rpcpassword=<pw>\t  "   + _("Password for JSON-RPC connections") + "\n" +
            "  -rpcport=<port>  \t\t  " + _("Listen for JSON-RPC connections on <port> (default: 14001 or testnet: 15001)") + "\n" +
            "  -rpcallowip=<ip> \t\t  " + _("Allow JSON-RPC connections from specified IP address") + "\n" +
            "  -rpcconnect=<ip> \t  "   + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" +
            "  -blocknotify=<cmd> "     + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n" +
            "  -walletnotify=<cmd> "    + _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)") + "\n" +
            "  -votenotify=<cmd>  "     + _("Execute command when the vote changes") + "\n" +
            "  -upgradewallet   \t  "   + _("Upgrade wallet to latest format") + "\n" +
            "  -keypool=<n>     \t  "   + _("Set key pool size to <n> (default: 100)") + "\n" +
            "  -rescan          \t  "   + _("Rescan the block chain for missing wallet transactions") + "\n" +
            "  -checkblocks=<n> \t\t  " + _("How many blocks to check at startup (default: 2500, 0 = all)") + "\n" +
            "  -checklevel=<n>  \t\t  " + _("How thorough the block verification is (0-6, default: 1)") + "\n";

        strUsage += string() +
            _("\nSSL options: (see the Nu Wiki for SSL setup instructions)") + "\n" +
            "  -rpcssl                                \t  " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n" +
            "  -rpcsslcertificatechainfile=<file.cert>\t  " + _("Server certificate file (default: server.cert)") + "\n" +
            "  -rpcsslprivatekeyfile=<file.pem>       \t  " + _("Server private key (default: server.pem)") + "\n" +
            "  -rpcsslciphers=<ciphers>               \t  " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n";

        strUsage += string() +
            "  -?               \t\t  " + _("This help message") + "\n";

        // Remove tabs
        strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
#if defined(QT_GUI) && defined(WIN32)
        // On windows, show a message box, as there is no stderr
        ThreadSafeMessageBox(strUsage, _("Usage"), wxOK | wxMODAL);
#else
        fprintf(stderr, "%s", strUsage.c_str());
#endif
        return false;
    }

    curl_global_init(CURL_GLOBAL_NOTHING);

#ifdef TESTING
    if (mapArgs.count("-timetravel"))
        nTimeShift = GetArg("-timetravel", 0);
#endif

    fTestNet = GetBoolArg("-testnet");
    if (fTestNet)
    {
        SoftSetBoolArg("-irc", true);
    }

    fDebug = GetBoolArg("-debug");
    fDetachDB = GetBoolArg("-detachdb", false);

#if !defined(WIN32) && !defined(QT_GUI)
    fDaemon = GetBoolArg("-daemon");
#else
    fDaemon = false;
#endif

    if (fDaemon)
        fServer = true;
    else
        fServer = GetBoolArg("-server");

    /* force fServer when running without GUI */
#if !defined(QT_GUI)
    fServer = true;
#endif
    fPrintToConsole = GetBoolArg("-printtoconsole");
    fPrintToDebugger = GetBoolArg("-printtodebugger");
    fLogTimestamps = GetBoolArg("-logtimestamps");

#ifndef QT_GUI
    for (int i = 1; i < argc; i++)
        if (!IsSwitchChar(argv[i][0]) && !(strlen(argv[i]) >= 3 && strncasecmp(argv[i], "Nu:", 3) == 0))
            fCommandLine = true;

    if (fCommandLine)
    {
        int ret = CommandLineRPC(argc, argv);
        exit(ret);
    }
#endif

#if !defined(WIN32) && !defined(QT_GUI)
    if (fDaemon)
    {
        // Daemonize
        pid_t pid = fork();
        if (pid < 0)
        {
            fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
            return false;
        }
        if (pid > 0)
        {
            CreatePidFile(GetPidFile(), pid);
            return true;
        }

        pid_t sid = setsid();
        if (sid < 0)
            fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
    }
#endif

    if (!fDebug)
        ShrinkDebugFile();
    printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
    printf("Nu version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str());
    printf("Default data directory %s\n", GetDefaultDataDir().string().c_str());

    if (GetBoolArg("-loadblockindextest"))
    {
        CTxDB txdb("r");
        txdb.LoadBlockIndex();
        PrintBlockTree();
        return false;
    }

    // Make sure only a single Nu process is using the data directory.
    boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
    FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
    if (file) fclose(file);
    static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
    if (!lock.try_lock())
    {
        ThreadSafeMessageBox(strprintf(_("Cannot obtain a lock on data directory %s.  Nu is probably already running."), GetDataDir().string().c_str()), _("Nu"), wxOK|wxMODAL);
        return false;
    }

    std::ostringstream strErrors;
    //
    // Load data files
    //
    if (fDaemon)
        fprintf(stdout, "Nu server starting\n");
    int64 nStart;

    InitMessage(_("Loading addresses..."));
    printf("Loading addresses...\n");
    nStart = GetTimeMillis();
    if (!LoadAddresses())
        strErrors << _("Error loading addr.dat") << "\n";
    printf(" addresses   %15"PRI64d"ms\n", GetTimeMillis() - nStart);

    InitMessage(_("Loading block index..."));
    printf("Loading block index...\n");
    nStart = GetTimeMillis();
    if (!LoadBlockIndex())
        strErrors << _("Error loading blkindex.dat") << "\n";

    // as LoadBlockIndex can take several minutes, it's possible the user
    // requested to kill Nu-Qt during the last operation. If so, exit.
    // As the program has not fully started yet, Shutdown() is possibly overkill.
    if (fRequestShutdown)
    {
        printf("Shutdown requested. Exiting.\n");
        return false;
    }
    printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);

    InitMessage(_("Loading wallets..."));
    printf("Loading portfolio...\n");
    nStart = GetTimeMillis();

    BOOST_FOREACH(unsigned char unit, sAvailableUnits)
    {
        printf("Loading wallet for unit %c...\n", unit);
        nStart = GetTimeMillis();
        bool fFirstRun;
        string walletFilename((format("wallet%c.dat") % unit).str());

        CWallet* pwalletMain;
        pwalletMain = new CWallet(walletFilename);
        pwalletMain->SetUnit(unit);

        int nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
        if (nLoadWalletRet != DB_LOAD_OK)
        {
            if (nLoadWalletRet == DB_CORRUPT)
                strErrors << format(_("Error loading %s: Wallet corrupted")) % walletFilename << "\n";
            else if (nLoadWalletRet == DB_TOO_NEW)
                strErrors << format(_("Error loading %s: Wallet requires newer version of Nu")) % walletFilename << "\n";
            else if (nLoadWalletRet == DB_NEED_REWRITE)
            {
                strErrors << _("Wallet needed to be rewritten: restart Nu to complete") << "\n";
                printf("%s", strErrors.str().c_str());
                ThreadSafeMessageBox(strErrors.str(), _("Nu"), wxOK | wxICON_ERROR | wxMODAL);
                return false;
            }
            else
                strErrors << format(_("Error loading %s")) % walletFilename << "\n";
        }

        if (GetBoolArg("-upgradewallet", fFirstRun))
        {
            int nMaxVersion = GetArg("-upgradewallet", 0);
            if (nMaxVersion == 0) // the -walletupgrade without argument case
            {
                printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
                nMaxVersion = CLIENT_VERSION;
                pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
            }
            else
                printf("Allowing wallet upgrade up to %i\n", nMaxVersion);
            if (nMaxVersion < pwalletMain->GetVersion())
                strErrors << _("Cannot downgrade wallet") << "\n";
            pwalletMain->SetMaxVersion(nMaxVersion);
        }

    if (fFirstRun)
    {
        // Create new keyUser and set as default key
        RandAddSeedPerfmon();

        CPubKey newDefaultKey;
        if (!pwalletMain->GetKeyFromPool(newDefaultKey, false))
            strErrors << _("Cannot initialize keypool") << "\n";
        pwalletMain->SetDefaultKey(newDefaultKey);
        if (!pwalletMain->SetAddressBookName(pwalletMain->vchDefaultKey.GetID(), ""))
            strErrors << _("Cannot write default address") << "\n";
    }

        printf("%s", strErrors.str().c_str());
        printf(" wallet      %15"PRI64d"ms\n", GetTimeMillis() - nStart);

        RegisterWallet(pwalletMain);

        CBlockIndex *pindexRescan = pindexBest;
        if (GetBoolArg("-rescan"))
            pindexRescan = pindexGenesisBlock;
        else
        {
            CWalletDB walletdb(walletFilename);
            CBlockLocator locator;
            if (walletdb.ReadBestBlock(locator))
                pindexRescan = locator.GetBlockIndex();
        }
        if (pindexBest != pindexRescan && pindexBest && pindexRescan && pindexBest->nHeight > pindexRescan->nHeight)
        {
            InitMessage(_("Rescanning..."));
            printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
            nStart = GetTimeMillis();
            pwalletMain->ScanForWalletTransactions(pindexRescan, true);
            printf(" rescan      %15"PRI64d"ms\n", GetTimeMillis() - nStart);
        }

        InitMessage(_("Done loading"));
        printf("Done loading\n");

        //// debug print
        printf("mapBlockIndex.size() = %d\n",   mapBlockIndex.size());
        printf("nBestHeight = %d\n",            nBestHeight);
        printf("setKeyPool.size() = %d\n",      pwalletMain->setKeyPool.size());
        printf("mapWallet.size() = %d\n",       pwalletMain->mapWallet.size());
        printf("mapAddressBook.size() = %d\n",  pwalletMain->mapAddressBook.size());
    }

    if (!strErrors.str().empty())
    {
        ThreadSafeMessageBox(strErrors.str(), _("Nu"), wxOK | wxICON_ERROR | wxMODAL);
        return false;
    }

    BOOST_FOREACH(CWallet* wallet, setpwalletRegistered)
    {
        // Add wallet transactions that aren't already in a block to mapTransactions
        wallet->ReacceptWalletTransactions();
    }

    // Note: Nu-Qt stores several settings in the wallet, so we want
    // to load the wallet BEFORE parsing command-line arguments, so
    // the command-line/nu.conf settings override GUI setting.

    //
    // Parameters
    //
    if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
    {
        PrintBlockTree();
        return false;
    }

    if (mapArgs.count("-timeout"))
    {
        int nNewTimeout = GetArg("-timeout", 5000);
        if (nNewTimeout > 0 && nNewTimeout < 600000)
            nConnectTimeout = nNewTimeout;
    }

    if (mapArgs.count("-printblock"))
    {
        string strMatch = mapArgs["-printblock"];
        int nFound = 0;
        for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
        {
            uint256 hash = (*mi).first;
            if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
            {
                CBlockIndex* pindex = (*mi).second;
                CBlock block;
                block.ReadFromDisk(pindex);
                block.BuildMerkleTree();
                block.print();
                printf("\n");
                nFound++;
            }
        }
        if (nFound == 0)
            printf("No blocks matching %s were found\n", strMatch.c_str());
        return false;
    }

    if (mapArgs.count("-proxy"))
    {
        fUseProxy = true;
        addrProxy = CService(mapArgs["-proxy"], 9050);
        if (!addrProxy.IsValid())
        {
            ThreadSafeMessageBox(_("Invalid -proxy address"), _("Nu"), wxOK | wxMODAL);
            return false;
        }
    }

    bool fTor = (fUseProxy && addrProxy.GetPort() == 9050);
    if (fTor)
    {
        // Use SoftSetBoolArg here so user can override any of these if they wish.
        // Note: the GetBoolArg() calls for all of these must happen later.
        SoftSetBoolArg("-listen", false);
        SoftSetBoolArg("-irc", false);
        SoftSetBoolArg("-dnsseed", false);
        SoftSetBoolArg("-upnp", false);
        SoftSetBoolArg("-dns", false);
    }

    fAllowDNS = GetBoolArg("-dns");
    fNoListen = !GetBoolArg("-listen", true);

    if (mapArgs.count("-splitshareoutputs"))
        nSplitShareOutputs = boost::lexical_cast<double>(mapArgs["-splitshareoutputs"]) * COIN;
    else
        nSplitShareOutputs = MIN_COINSTAKE_VALUE;

    // Continue to put "/P2SH/" in the coinbase to monitor
    // BIP16 support.
    // This can be removed eventually...
    const char* pszP2SH = "/P2SH/";
    COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));

    if (!fNoListen)
    {
        std::string strError;
        if (!BindListenPort(strError))
        {
            ThreadSafeMessageBox(strError, _("Nu"), wxOK | wxMODAL);
            return false;
        }
    }

    if (mapArgs.count("-addnode"))
    {
        BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
        {
            CAddress addr(CService(strAddr, GetDefaultPort(), fAllowDNS));
            addr.nTime = 0; // so it won't relay unless successfully connected
            if (addr.IsValid())
                addrman.Add(addr, CNetAddr("127.0.0.1"));
        }
    }

    if (mapArgs.count("-reservebalance")) // Nu: reserve balance amount
    {
        int64 nReserveBalance = 0;
        if (!ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
        {
            ThreadSafeMessageBox(_("Invalid amount for -reservebalance=<amount>"), _("Nu"), wxOK | wxMODAL);
            return false;
        }
    }

    if (mapArgs.count("-checkpointkey")) // Nu: checkpoint master priv key
    {
        if (!Checkpoints::SetCheckpointPrivKey(GetArg("-checkpointkey", "")))
            ThreadSafeMessageBox(_("Unable to sign checkpoint, wrong checkpointkey?\n"), _("Nu"), wxOK | wxMODAL);
    }

    //
    // Start the node
    //
    if (!CheckDiskSpace())
        return false;

    RandAddSeedPerfmon();

    if (!CreateThread(StartNode, NULL))
        ThreadSafeMessageBox(_("Error: CreateThread(StartNode) failed"), _("Nu"), wxOK | wxMODAL);

    if (fServer)
    {
        BOOST_FOREACH(CWallet *wallet, setpwalletRegistered)
            CreateThread(ThreadRPCServer, wallet);
    }

#ifdef QT_GUI
    if (GetStartOnSystemStartup())
        SetStartOnSystemStartup(true); // Remove startup links
#endif

#if !defined(QT_GUI)
    while (1)
        Sleep(5000);
#endif

    return true;
}


text:
#ifndef __OSL_CLOSURES_H__
#define __OSL_CLOSURES_H__

#include "util_types.h"
#include "kernel_types.h"

#include <OSL/oslclosure.h>
#include <OSL/oslexec.h>
#include <OSL/genclosure.h>

CCL_NAMESPACE_BEGIN

OSL::ClosureParam *closure_emission_params();
OSL::ClosureParam *closure_background_params();
OSL::ClosureParam *closure_holdout_params();
OSL::ClosureParam *closure_ambient_occlusion_params();
OSL::ClosureParam *closure_bsdf_diffuse_ramp_params();
OSL::ClosureParam *closure_bsdf_phong_ramp_params();
OSL::ClosureParam *closure_bssrdf_cubic_params();
OSL::ClosureParam *closure_bssrdf_gaussian_params();
OSL::ClosureParam *closure_henyey_greenstein_volume_params();

void closure_emission_prepare(OSL::RendererServices *, int id, void *data);
void closure_background_prepare(OSL::RendererServices *, int id, void *data);
void closure_holdout_prepare(OSL::RendererServices *, int id, void *data);
void closure_ambient_occlusion_prepare(OSL::RendererServices *, int id, void *data);
void closure_bsdf_diffuse_ramp_prepare(OSL::RendererServices *, int id, void *data);
void closure_bsdf_phong_ramp_prepare(OSL::RendererServices *, int id, void *data);
void closure_bssrdf_cubic_prepare(OSL::RendererServices *, int id, void *data);
void closure_bssrdf_gaussian_prepare(OSL::RendererServices *, int id, void *data);
void closure_henyey_greenstein_volume_prepare(OSL::RendererServices *, int id, void *data);

#define CCLOSURE_PREPARE(name, classname)          \
void name(RendererServices *, int id, void *data) \
{                                                 \
	memset(data, 0, sizeof(classname));           \
	new (data) classname();                       \
}

#define CCLOSURE_PREPARE_STATIC(name, classname) static CCLOSURE_PREPARE(name, classname)

#define CLOSURE_FLOAT3_PARAM(st, fld) \
	{ TypeDesc::TypeVector, reckless_offsetof(st, fld), NULL, sizeof(OSL::Vec3) }

#define TO_VEC3(v) OSL::Vec3(v.x, v.y, v.z)
#define TO_COLOR3(v) OSL::Color3(v.x, v.y, v.z)
#define TO_FLOAT3(v) make_float3(v[0], v[1], v[2])

/* Closure */

class CClosurePrimitive {
public:
	enum Category {
		BSDF,             ///< Reflective and/or transmissive surface
		BSSRDF,           ///< Sub-surface light transfer
		Emissive,         ///< Light emission
		Background,       ///< Background emission
		Volume,           ///< Volume scattering
		Holdout,          ///< Holdout from alpha
		AmbientOcclusion, ///< Ambient occlusion
	};

	CClosurePrimitive (Category category_) : category (category_) {}
	virtual ~CClosurePrimitive() {}
	virtual void setup() {}

	Category category;
};

/* BSDF */

class CBSDFClosure : public CClosurePrimitive {
public:
	ShaderClosure sc;

	CBSDFClosure(int scattering) : CClosurePrimitive(BSDF),
	  m_scattering_label(scattering), m_shaderdata_flag(0)
	{}

	int scattering() const { return m_scattering_label; }
	int shaderdata_flag() const { return m_shaderdata_flag; }

	virtual void blur(float roughness) = 0;
	virtual float3 eval_reflect(const float3 &omega_out, const float3 &omega_in, float &pdf) const = 0;
	virtual float3 eval_transmit(const float3 &omega_out, const float3 &omega_in, float &pdf) const = 0;

	virtual int sample(const float3 &Ng,
	                   const float3 &omega_out, const float3 &domega_out_dx, const float3 &domega_out_dy,
	                   float randu, float randv,
	                   float3 &omega_in, float3 &domega_in_dx, float3 &domega_in_dy,
	                   float &pdf, float3 &eval) const = 0;

protected:
	int m_scattering_label;
	int m_shaderdata_flag;
};

#define BSDF_CLOSURE_CLASS_BEGIN(Upper, lower, svmlower, TYPE) \
\
class Upper##Closure : public CBSDFClosure { \
public: \
	Upper##Closure() : CBSDFClosure(TYPE) \
	{ \
	} \
\
	void setup() \
	{ \
		sc.prim = NULL; \
		m_shaderdata_flag = bsdf_##lower##_setup(&sc); \
	} \
\
	void blur(float roughness) \
	{ \
	} \
\
	float3 eval_reflect(const float3 &omega_out, const float3 &omega_in, float& pdf) const \
	{ \
		pdf = 0; \
		return make_float3(0, 0, 0); \
	} \
\
	float3 eval_transmit(const float3 &omega_out, const float3 &omega_in, float& pdf) const \
	{ \
		pdf = 0; \
		return make_float3(0, 0, 0); \
	} \
\
	int sample(const float3 &Ng, \
	           const float3 &omega_out, const float3 &domega_out_dx, const float3 &domega_out_dy, \
	           float randu, float randv, \
	           float3 &omega_in, float3 &domega_in_dx, float3 &domega_in_dy, \
	           float &pdf, float3 &eval) const \
	{ \
		pdf = 0; \
		return LABEL_NONE; \
	} \
}; \
\
static ClosureParam *bsdf_##lower##_params() \
{ \
	static ClosureParam params[] = {

/* parameters */

#define BSDF_CLOSURE_CLASS_END(Upper, lower) \
		CLOSURE_STRING_KEYPARAM("label"), \
	    CLOSURE_FINISH_PARAM(Upper##Closure) \
	}; \
	return params; \
} \
\
CCLOSURE_PREPARE_STATIC(bsdf_##lower##_prepare, Upper##Closure)

/* Volume */

class CVolumeClosure : public CClosurePrimitive {
public:
	ShaderClosure sc;

	CVolumeClosure(int scattering) : CClosurePrimitive(Volume),
	  m_scattering_label(scattering), m_shaderdata_flag(0)
	{}
	~CVolumeClosure() { }

	int scattering() const { return m_scattering_label; }
	int shaderdata_flag() const { return m_shaderdata_flag; }

protected:
	int m_scattering_label;
	int m_shaderdata_flag;
};

#define VOLUME_CLOSURE_CLASS_BEGIN(Upper, lower, TYPE) \
\
class Upper##Closure : public CVolumeClosure { \
public: \
	Upper##Closure() : CVolumeClosure(TYPE) {} \
\
	void setup() \
	{ \
		sc.prim = NULL; \
		m_shaderdata_flag = volume_##lower##_setup(&sc); \
	} \
}; \
\
static ClosureParam *volume_##lower##_params() \
{ \
	static ClosureParam params[] = {

/* parameters */

#define VOLUME_CLOSURE_CLASS_END(Upper, lower) \
		CLOSURE_STRING_KEYPARAM("label"), \
	    CLOSURE_FINISH_PARAM(Upper##Closure) \
	}; \
	return params; \
} \
\
CCLOSURE_PREPARE_STATIC(volume_##lower##_prepare, Upper##Closure)

CCL_NAMESPACE_END

#endif /* __OSL_CLOSURES_H__ */

redpajama_set_name: RedPajamaGithub


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="RegisteringInstanceFactoryTests.cs" company="Bijectiv">
//   The MIT License (MIT)
//
//   Copyright (c) 2014 Brian Tyler
//
//   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.
// </copyright>
// <summary>
//   Defines the RegisteringInstanceFactoryTests type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Bijectiv.Tests.KernelFactory
{
    using System;
    using System.Linq;

    using Bijectiv.KernelFactory;
    using Bijectiv.TestUtilities;
    using Bijectiv.TestUtilities.TestTypes;
    using Bijectiv.Utilities;

    using Microsoft.VisualStudio.TestTools.UnitTesting;

    using Moq;

    /// <summary>
    /// This class tests the <see cref="RegisteringInstanceFactory{TRegistration}"/> class.
    /// </summary>
    [TestClass]
    public class RegisteringInstanceFactoryTests
    {
        [TestMethod]
        [TestCategory("Unit")]
        [ArgumentNullExceptionExpected]
        public void CreateInstance_InstanceTypeParameterIsNull_Throws()
        {
            // Arrange

            // Act
            // ReSharper disable once AssignNullToNotNullAttribute
            new RegisteringInstanceFactory<RegistrationTest>(null, () => Stub.Create<IRegisterTest>()).Naught();

            // Assert
        }

        [TestMethod]
        [TestCategory("Unit")]
        [ArgumentNullExceptionExpected]
        public void CreateInstance_InstanceFactoryParameterIsNull_Throws()
        {
            // Arrange

            // Act
            // ReSharper disable once AssignNullToNotNullAttribute
            new RegisteringInstanceFactory<RegistrationTest>(typeof(IRegisterTest), null).Naught();

            // Assert
        }

        [TestMethod]
        [TestCategory("Unit")]
        public void CreateInstance_ValidParameters_InstanceCreated()
        {
            // Arrange

            // Act
            new RegisteringInstanceFactory<RegistrationTest>(
                typeof(IRegisterTest), () => Stub.Create<IRegisterTest>()).Naught();

            // Assert
        }

        [TestMethod]
        [TestCategory("Unit")]
        public void CreateInstance_InstanceTypeParameter_IsAssignedToInstanceTypeProperty()
        {
            // Arrange
            var instanceType = typeof(IRegisterTest);

            // Act
            var testTarget = new RegisteringInstanceFactory<RegistrationTest>(
                instanceType, () => Stub.Create<IRegisterTest>());

            // Assert
            Assert.AreEqual(instanceType, testTarget.InstanceType);
        }

        [TestMethod]
        [TestCategory("Unit")]
        public void CreateInstance_InstanceFactoryParameter_IsAssignedToInstanceFactoryProperty()
        {
            // Arrange
            Func<object> instanceFactory = () => Stub.Create<IRegisterTest>();

            // Act
            var testTarget = new RegisteringInstanceFactory<RegistrationTest>(
                typeof(IRegisterTest), instanceFactory);

            // Assert
            Assert.AreEqual(instanceFactory, testTarget.InstanceFactory);
        }

        [TestMethod]
        [TestCategory("Unit")]
        [ArgumentNullExceptionExpected]
        public void Create_RegistryParameterIsNull_Throws()
        {
            // Arrange
            var testTarget = new RegisteringInstanceFactory<RegistrationTest>(
                typeof(IRegisterTest), () => Stub.Create<IRegisterTest>());

            // Act
            // ReSharper disable once AssignNullToNotNullAttribute
            testTarget.Create(null);

            // Assert
        }

        [TestMethod]
        [TestCategory("Unit")]
        public void Create_ValidParameters_ReturnsInstanceFactoryResult()
        {
            // Arrange
            var repository = new MockRepository(MockBehavior.Strict);
            var instance = Stub.Create<IRegisterTest>();
            var testTarget = new RegisteringInstanceFactory<RegistrationTest>(typeof(IRegisterTest), () => instance);
            var registryMock = repository.Create<IInstanceRegistry>();
            registryMock
                .Setup(_ => _.ResolveAll<RegistrationTest>())
                .Returns(Enumerable.Empty<RegistrationTest>());

            // Act
            var result = testTarget.Create(registryMock.Object);

            // Assert
            repository.VerifyAll();
            Assert.AreEqual(typeof(IRegisterTest), result.Item1);
            Assert.AreEqual(instance, result.Item2);
        }

        [TestMethod]
        [TestCategory("Unit")]
        public void Create_ValidParameters_RegistersEachResolvedItemWithInstance()
        {
            // Arrange
            var repository = new MockRepository(MockBehavior.Strict);
            var instanceMock = repository.Create<IRegisterTest>();
            var testTarget = new RegisteringInstanceFactory<RegistrationTest>(
                typeof(IRegisterTest), () => instanceMock.Object);

            var registrations = new[] { new RegistrationTest(), new RegistrationTest(), new RegistrationTest() };
            var registryMock = repository.Create<IInstanceRegistry>();
            registryMock
                .Setup(_ => _.ResolveAll<RegistrationTest>())
                .Returns(registrations);

            registrations.ForEach(item => instanceMock.Setup(_ => _.Register(item)));

            // Act
            testTarget.Create(registryMock.Object);

            // Assert
            repository.VerifyAll();
        }
    }
}


text:
package io.quarkus.resteasy.reactive.server.test.customproviders;

import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assertions.fail;

import java.util.function.Supplier;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.UriInfo;

import org.jboss.resteasy.reactive.server.ServerRequestFilter;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

import io.quarkus.arc.profile.IfBuildProfile;
import io.quarkus.test.QuarkusUnitTest;

public class InvalidConditionalBeanFiltersTest {

    @RegisterExtension
    static QuarkusUnitTest test = new QuarkusUnitTest()
            .setArchiveProducer(new Supplier<>() {
                @Override
                public JavaArchive get() {
                    return ShrinkWrap.create(JavaArchive.class)
                            .addClasses(TestResource.class, Filters.class);
                }
            }).assertException(t -> {
                String message = t.getMessage();
                assertTrue(message.contains("@IfBuildProfile"));
                assertTrue(message.contains("request"));
                assertTrue(message.contains(InvalidConditionalBeanFiltersTest.Filters.class.getName()));
            });

    @Test
    public void test() {
        fail("Should never have been called");
    }

    @Path("test")
    public static class TestResource {

        @GET
        public String hello() {
            return "hello";
        }

    }

    public static class Filters {

        @IfBuildProfile("test")
        @ServerRequestFilter
        public void request(UriInfo info) {

        }

    }
}


text:
import { makeTest, TestBedConfig } from './scaffolding/runner';
import { generateItem } from './miscellaneous/items';
import { Misc } from './miscellaneous/misc';
import { getDatasourceReplacementsClass } from './scaffolding/datasources/class';

const baseSettings = {
  startIndex: 1,
  minIndex: 1,
  maxIndex: 100,
  adapter: true,
  itemSize: 20
};

interface ICustom {
  token: 'first' | 'last' | 'middle';
  indexesToReplace: number[]; // indexes to remove
  amount: number; // how many items to insert
  fixRight?: boolean;
}

const configList: TestBedConfig[] = [{
  datasourceSettings: { ...baseSettings },
  custom: {
    indexesToReplace: [baseSettings.minIndex + 1],
    token: 'middle',
    amount: 1
  } as ICustom
}, {
  datasourceSettings: { ...baseSettings },
  custom: {
    indexesToReplace: [baseSettings.minIndex],
    token: 'first',
    amount: 1
  } as ICustom
}, {
  datasourceSettings: { ...baseSettings, startIndex: baseSettings.maxIndex },
  custom: {
    indexesToReplace: [baseSettings.maxIndex],
    token: 'last',
    amount: 1
  } as ICustom
}].map(config => ({
  ...config,
  datasourceClass: getDatasourceReplacementsClass(config.datasourceSettings)
}));

const manyToOneConfigList: TestBedConfig[] = [{
  datasourceSettings: { ...baseSettings },
  custom: {
    indexesToReplace: [
      baseSettings.minIndex + 1,
      baseSettings.minIndex + 2,
      baseSettings.minIndex + 3
    ],
    token: 'middle',
    amount: 1
  } as ICustom
}, {
  datasourceSettings: { ...baseSettings },
  custom: {
    indexesToReplace: [
      baseSettings.minIndex,
      baseSettings.minIndex + 1,
      baseSettings.minIndex + 2
    ],
    token: 'first',
    amount: 1
  } as ICustom
}, {
  datasourceSettings: { ...baseSettings, startIndex: baseSettings.maxIndex },
  custom: {
    indexesToReplace: [
      baseSettings.maxIndex - 2,
      baseSettings.maxIndex - 1,
      baseSettings.maxIndex
    ],
    token: 'last',
    amount: 1
  } as ICustom
}].map(config => ({
  ...config,
  datasourceClass: getDatasourceReplacementsClass(config.datasourceSettings)
}));

const manyToOneIncreaseConfigList = manyToOneConfigList.map(config => ({
  ...config,
  custom: {
    ...config.custom,
    fixRight: true
  } as ICustom
}));

const manyToManyConfigList = [
  ...manyToOneConfigList.map(config => ({
    ...config, custom: { ...config.custom, amount: 2 } as ICustom
  })),
  ...manyToOneConfigList.map(config => ({
    ...config, custom: { ...config.custom, amount: 3 } as ICustom
  })),
  ...manyToOneConfigList.map(config => ({
    ...config, custom: { ...config.custom, amount: 4 } as ICustom
  })),
];

const manyToManyIncreaseConfigList = manyToManyConfigList
  .filter((i, j) => [0, 5, 8].includes(j))
  .map(config => ({
    ...config, custom: { ...config.custom, fixRight: true } as ICustom
  }));

const shouldReplace = (config: TestBedConfig) => (misc: Misc) => async (done: Function) => {
  await misc.relaxNext();
  const { adapter } = misc;
  const { indexesToReplace: indexes, amount, token, fixRight } = config.custom;
  const { datasourceSettings: { minIndex, itemSize } } = config;
  const diff = amount - indexes.length; // inserted - removed
  const viewportSize = misc.getScrollableSize();
  const sizeToChange = diff * misc.getItemSize();
  const maxScrollPosition = misc.getMaxScrollPosition() + sizeToChange;
  const newIndexFirst = indexes[0] - (fixRight ? diff : 0);
  const newIndexLast = newIndexFirst + amount - 1;
  const newAbsMinIndex = fixRight ? minIndex - diff : minIndex;
  const position = token === 'last' ? maxScrollPosition : (newIndexFirst - newAbsMinIndex) * itemSize;
  const items = Array.from({ length: amount }).map((j, i) => generateItem(newIndexFirst + i, false, '*'));

  // replace at the Datasource level (component)
  if (indexes.length === 1 && amount === 1) {
    (misc.datasource as any).replaceOneToOne(indexes[0], items[0]);
  } else if (indexes.length > 1 && amount === 1) {
    (misc.datasource as any).replaceManyToOne(indexes, items[0], fixRight);
  } else if (indexes.length > 1 && amount > 1) {
    (misc.datasource as any).replaceManyToMany(indexes, items, fixRight);
  }

  // replace at the Viewport level (scroller)
  await adapter.replace({
    predicate: ({ $index }) => indexes.includes($index),
    items,
    fixRight
  });

  // refresh the view via scroll to edges
  await misc.scrollMinMax();

  // scroll to replaced item
  if (misc.getScrollPosition() !== position) {
    adapter.fix({ scrollPosition: position });
    await misc.relaxNext();
  }

  // check edge replaced items
  if (token === 'last') {
    expect(adapter.lastVisible.$index).toEqual(newIndexLast);
  } else {
    expect(adapter.firstVisible.$index).toEqual(newIndexFirst);
  }
  expect(misc.getElementText(newIndexFirst)).toEqual(newIndexFirst + ': ' + items[0].text);
  expect(misc.getElementText(newIndexLast)).toEqual(newIndexLast + ': ' + items[items.length - 1].text);

  // check the item next to the last replaced one
  if (token === 'last') {
    expect(misc.checkElementContent(newIndexFirst - 1, newIndexFirst - (fixRight ? 1 - diff : 1))).toEqual(true);
  } else {
    expect(misc.checkElementContent(newIndexLast + 1, newIndexLast + (fixRight ? 1 : 1 - diff))).toEqual(true);
  }

  expect(misc.getScrollableSize()).toBe(viewportSize + sizeToChange);
  done();
};

describe('Adapter Replace Spec', () => {

  const getTitle = ({ custom: { token, indexesToReplace: { length }, amount } }: TestBedConfig) =>
    `should replace ${token} ${length === 1 ? 'one' : length} to ${amount === 1 ? 'one' : amount}`;

  describe('one-to-ne replacement', () =>
    configList.forEach(config =>
      makeTest({
        title: getTitle(config),
        config,
        it: shouldReplace(config)
      })
    )
  );

  describe('many-to-one replacement', () =>
    manyToOneConfigList.forEach(config =>
      makeTest({
        title: getTitle(config),
        config,
        it: shouldReplace(config)
      })
    )
  );

  describe('many-to-one fixRight replacement', () =>
    manyToOneIncreaseConfigList.forEach(config =>
      makeTest({
        title: getTitle(config),
        config,
        it: shouldReplace(config)
      })
    )
  );

  describe('many-to-many replacement', () =>
    manyToManyConfigList.forEach(config =>
      makeTest({
        title: getTitle(config),
        config,
        it: shouldReplace(config)
      })
    )
  );

  describe('many-to-many fixRight replacement', () =>
    manyToManyIncreaseConfigList.forEach(config =>
      makeTest({
        title: getTitle(config),
        config,
        it: shouldReplace(config)
      })
    )
  );

});


text:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;

namespace OpenWeatherMap.Standard.Models
{
    /// <summary>
    /// rain model
    /// </summary>
    [Serializable]
    public class Rain : BaseModel
    {
        private float lastHour, lastThreeHours;

        /// <summary>
        /// last hour, mm
        /// </summary>
        [JsonProperty("1h")]
        public float LastHour
        {
            get => lastHour;
            set => SetProperty(ref lastHour, value);
        }

        /// <summary>
        /// last three hours, mm
        /// </summary>
        [JsonProperty("3h")]
        public float LastThreeHours
        {
            get => lastThreeHours;
            set => SetProperty(ref lastThreeHours, value);
        }
    }
}


text:
using System;
using System.Xml.Serialization;

namespace Aop.Api.Domain
{
    /// <summary>
    /// BusinessPermission Data Structure.
    /// </summary>
    [Serializable]
    public class BusinessPermission : AopObject
    {
        /// <summary>
        /// 业务隔离字段
        /// </summary>
        [XmlElement("domain")]
        public string Domain { get; set; }

        /// <summary>
        /// 权限码名称
        /// </summary>
        [XmlElement("permission_code")]
        public string PermissionCode { get; set; }

        /// <summary>
        /// 权限码值
        /// </summary>
        [XmlElement("source_permission_code")]
        public string SourcePermissionCode { get; set; }
    }
}


text:
var Promise = require('bluebird');
module.exports = function(){}
module.exports.prototype.start = function(metalogin,data){
	this.client = data.client;
};
module.exports.prototype.invalidate = function(id,data){
	this.client.del('cache:' + id);
}
module.exports.prototype.set = function(id,data){
	this.client.set('cache:' + id,JSON.stringify(data));
}
module.exports.prototype.get = Promise.promisify(function(id,done){
	this.client.get('cache:' + id,function(err,reply){
		if (err){
			return done(err);
		} else if (!reply){
			return done(null,null);
		}
		return done(null,JSON.parse(reply));
	});
});


text:
#pragma once

#include <defines.h>

#include <stdint.h>
#include <string>
#include <vector>
#include <iostream>
#include <Eigen/Core>
#include <Eigen/Dense>
#include <Eigen/QR>
#include <unsupported/Eigen/MatrixFunctions>

// CUDA runtime
#include <cuda_runtime.h>
// Utilities and system includes
#include <nvidia/helper_cuda.h>
#include <timer.hpp>

using namespace Eigen;
using namespace std;

#ifdef WEIGHTED
extern "C" void robustSquaredAngleCostFctGPU(float *h_cost, float *d_cost,
    float *d_x, float* d_weights, uint16_t *d_z, float *d_mu, float sigma_sq,
    int w, int h);

extern "C" void robustSquaredAngleCostFctAssignmentGPU(float *h_cost,
    float *d_cost,uint32_t *h_N, uint32_t *d_N, float *d_x, float* d_weights,
    float * d_errs,
    uint16_t *d_z, float *d_mu, float sigma_sq, int w, int h);

extern "C" void robustSquaredAngleCostFctJacobianGPU(float *h_J, float *d_J,
    float *d_x, float *d_weights, uint16_t *d_z, float *d_mu, float sigma_sq,
    int w, int h);
#else
extern "C" void robustSquaredAngleCostFctGPU(float *h_cost, float *d_cost,
    float *d_x, uint16_t *d_z, float *d_mu, float sigma_sq, int w, int h);

extern "C" void robustSquaredAngleCostFctAssignmentGPU(float *h_cost,
    float *d_cost, uint32_t *h_N, uint32_t *d_N, float *d_x, uint16_t *d_z, float *d_mu,
    float sigma_sq, int w, int h);

extern "C" void robustSquaredAngleCostFctJacobianGPU(float *h_J, float *d_J,
    float *d_x, uint16_t *d_z, float *d_mu, float sigma_sq, int w, int h);
#endif

extern "C" void meanInTpS2GPU(float *h_p, float *d_p, float *h_mu_karch,
    float *d_mu_karch, float *d_q, uint16_t *d_z, float* d_weights,int w, int h);

extern "C" void sufficientStatisticsOnTpS2GPU(float *h_p, float *d_p,
  float *h_Rnorths, float *d_Rnorths, float *d_q, uint16_t *d_z ,int w, int h,
  float *h_SSs, float *d_SSs);

extern "C" void loadRGBvaluesForMFaxes();

class OptSO3
{
protected:
  const int w_,h_;
  float *d_cost, *d_J, *d_mu_;
  float *h_errs_;
  uint32_t *d_N_;
  float t_max_, dt_;

public:
  float *d_errs_;
  float *d_q_, *d_weights_;
  const float sigma_sq_;
  uint16_t *d_z, *h_z;

  float dtPrep_; // time for preparation (here assignemnts)
  float dtCG_; // time for cunjugate gradient

  uint32_t t_; // timestep
  Matrix3f Rprev_; // previous rotation

  OptSO3(float sigma, float *d_q, int w, int h, float *d_weights =NULL):
    w_(w),h_(h),t_max_(1.0f),dt_(0.1f),
    d_q_(d_q),d_weights_(d_weights),
    sigma_sq_(sigma*sigma), dtPrep_(0.0f), dtCG_(0.0f),
    t_(0), Rprev_(Matrix3f::Identity())
  {init();};

  ~OptSO3();

  double D_KL_axisUnif();

  float *getErrs(int w, int h);

  virtual double conjugateGradientCUDA(Matrix3f& R, uint32_t maxIter=100)
  {
    Timer t0;
    uint32_t N = 0;
    if( fabs(R.determinant()-1.0) > 1e-6)
    {
      cout<<" == renormalizing rotation to get back to det(R) = 1"<<endl;
      R.col(0) = R.col(0)/R.col(0).norm();
      R.col(1) = R.col(1)/R.col(1).norm();
      R.col(2) = R.col(0).cross(R.col(1));
    }
    float res0 = conjugateGradientPreparation_impl(R,N);
    dtPrep_ = t0.toctic("--- association ");
    float resEnd = conjugateGradientCUDA_impl(R,res0, N, maxIter);
    conjugateGradientPostparation_impl(R);
    dtCG_ = t0.toctic("--- conjugateGradientCUDA ");
    t_++; // keep track of timesteps
    Rprev_ = R; // keep track of previous rotation estimate for rot. velocity computation
    return resEnd;
  };

  /* return a skew symmetric matrix from A */
  Matrix3f enforceSkewSymmetry(const Matrix3f &A) const
  {return 0.5*(A-A.transpose());};

  float dtPrep(void) const { return dtPrep_;};
  float dtCG(void) const { return dtCG_;};
protected:
  virtual float conjugateGradientPreparation_impl(Matrix3f& R, uint32_t& N);
  virtual float conjugateGradientCUDA_impl(Matrix3f& R, float res0, uint32_t N, uint32_t maxIter=100);
  virtual void conjugateGradientPostparation_impl(Matrix3f& R){;};
  /* evaluate cost function for a given assignment of npormals to axes */
  virtual float evalCostFunction(Matrix3f& R);
  /* compute Jacobian */
  virtual void computeJacobian(Matrix3f&J, Matrix3f& R, float N);
  /* recompute assignment based on rotation R and return residual as well */
  virtual float computeAssignment(Matrix3f& R, uint32_t& N);
  /* updates G and H from rotation R and jacobian J
   */
  virtual void updateGandH(Matrix3f& G, Matrix3f& G_prev, Matrix3f& H,
      const Matrix3f& R, const Matrix3f& J, const Matrix3f& M_t_min,
      bool resetH);
  /* performs line search starting at R in direction of H
   * returns min of cost function and updates R, and M_t_min
   */
  virtual float linesearch(Matrix3f& R, Matrix3f& M_t_min, const Matrix3f& H,
    float N, float t_max=1.0f, float dt=0.1f);
  /* mainly init GPU arrays */
  void init();
  /* copy rotation to device */
  void Rot2Device(Matrix3f& R);
  /* convert a Rotation matrix R to a MF representaiton of the axes */
  void Rot2M(Matrix3f& R, float *mu);
  //deprecated
  void rectifyRotation(Matrix3f& R);
};


text:
/**
 */
package org.osate.xtext.aadl2.agcl.agcl;

/**
 *
 * A representation of the model object 'Output'.
 *
 *
 *

 * The following features are supported:
 *

 *
{@link org.osate.xtext.aadl2.agcl.agcl.Output#getLink Link}

 *
{@link org.osate.xtext.aadl2.agcl.agcl.Output#getEvent Event}

 *

 *

 *
 * @see org.osate.xtext.aadl2.agcl.agcl.AgclPackage#getOutput()
 * @model
 * @generated
 */
public interface Output extends AtomicProposition
{
  /**
   * Returns the value of the 'Link' attribute.
   *
   *

   * If the meaning of the 'Link' attribute isn't clear,
   * there really should be more of a description here...
   *

   *
   * @return the value of the 'Link' attribute.
   * @see #setLink(String)
   * @see org.osate.xtext.aadl2.agcl.agcl.AgclPackage#getOutput_Link()
   * @model
   * @generated
   */
  String getLink();

  /**
   * Sets the value of the '{@link org.osate.xtext.aadl2.agcl.agcl.Output#getLink Link}' attribute.
   *
   *
   * @param value the new value of the 'Link' attribute.
   * @see #getLink()
   * @generated
   */
  void setLink(String value);

  /**
   * Returns the value of the 'Event' attribute.
   *
   *

   * If the meaning of the 'Event' attribute isn't clear,
   * there really should be more of a description here...
   *

   *
   * @return the value of the 'Event' attribute.
   * @see #setEvent(String)
   * @see org.osate.xtext.aadl2.agcl.agcl.AgclPackage#getOutput_Event()
   * @model
   * @generated
   */
  String getEvent();

  /**
   * Sets the value of the '{@link org.osate.xtext.aadl2.agcl.agcl.Output#getEvent Event}' attribute.
   *
   *
   * @param value the new value of the 'Event' attribute.
   * @see #getEvent()
   * @generated
   */
  void setEvent(String value);

} // Output


text:
Jdrampage::Application.config.session_store :cookie_store, :key => '_jdrampage_session'

# Use the database for sessions instead of the cookie-based default,
# which shouldn't be used to store highly confidential information
# (create the session table with "rake db:sessions:create")
# Jdrampage::Application.config.session_store :active_record_store


text:
using System;

namespace FluentSecurity.Policy.ViolationHandlers.Conventions
{
	public abstract class PolicyViolationHandlerTypeConvention : IPolicyViolationHandlerConvention
	{
		public Func<Type, object> PolicyViolationHandlerProvider = t => ServiceLocation.ServiceLocator.Current.Resolve(t);

		public abstract Type GetHandlerTypeFor(PolicyViolationException exception);

		public IPolicyViolationHandler GetHandlerFor(PolicyViolationException exception)
		{
			var type = GetHandlerTypeFor(exception);
			if (type != null)
			{
				if (typeof(IPolicyViolationHandler).IsAssignableFrom(type))
					return PolicyViolationHandlerProvider.Invoke(type) as IPolicyViolationHandler;
			}
			return null;
		}
	}
}


text:
import asyncio

def commits(func):
    def func_wrapper(self, *args, **kwargs):
        func(self, *args, **kwargs)

        if 'commit' not in kwargs or kwargs['commit']:
            asyncio.ensure_future(self.commit())

    return func_wrapper


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataSegmentExchangePattern
{
    public interface ISegmentModel
    {

    }
}


text:
#pragma once
#include <aws/ds/DirectoryService_EXPORTS.h>
#include <aws/ds/DirectoryServiceRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <utility>

namespace Aws
{
namespace DirectoryService
{
namespace Model
{

  /**
   *
Contains the inputs for the DescribeSnapshots operation.

See
   * Also:
   AWS
   * API Reference

   */
  class AWS_DIRECTORYSERVICE_API DescribeSnapshotsRequest : public DirectoryServiceRequest
  {
  public:
    DescribeSnapshotsRequest();
    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
The identifier of the directory for which to retrieve snapshot
     * information.

     */
    inline const Aws::String& GetDirectoryId() const{ return m_directoryId; }

    /**
     *
The identifier of the directory for which to retrieve snapshot
     * information.

     */
    inline void SetDirectoryId(const Aws::String& value) { m_directoryIdHasBeenSet = true; m_directoryId = value; }

    /**
     *
The identifier of the directory for which to retrieve snapshot
     * information.

     */
    inline void SetDirectoryId(Aws::String&& value) { m_directoryIdHasBeenSet = true; m_directoryId = std::move(value); }

    /**
     *
The identifier of the directory for which to retrieve snapshot
     * information.

     */
    inline void SetDirectoryId(const char* value) { m_directoryIdHasBeenSet = true; m_directoryId.assign(value); }

    /**
     *
The identifier of the directory for which to retrieve snapshot
     * information.

     */
    inline DescribeSnapshotsRequest& WithDirectoryId(const Aws::String& value) { SetDirectoryId(value); return *this;}

    /**
     *
The identifier of the directory for which to retrieve snapshot
     * information.

     */
    inline DescribeSnapshotsRequest& WithDirectoryId(Aws::String&& value) { SetDirectoryId(std::move(value)); return *this;}

    /**
     *
The identifier of the directory for which to retrieve snapshot
     * information.

     */
    inline DescribeSnapshotsRequest& WithDirectoryId(const char* value) { SetDirectoryId(value); return *this;}

    /**
     *
A list of identifiers of the snapshots to obtain the information for. If this
     * member is null or empty, all snapshots are returned using the Limit and
     * NextToken members.

     */
    inline const Aws::Vector<Aws::String>& GetSnapshotIds() const{ return m_snapshotIds; }

    /**
     *
A list of identifiers of the snapshots to obtain the information for. If this
     * member is null or empty, all snapshots are returned using the Limit and
     * NextToken members.

     */
    inline void SetSnapshotIds(const Aws::Vector<Aws::String>& value) { m_snapshotIdsHasBeenSet = true; m_snapshotIds = value; }

    /**
     *
A list of identifiers of the snapshots to obtain the information for. If this
     * member is null or empty, all snapshots are returned using the Limit and
     * NextToken members.

     */
    inline void SetSnapshotIds(Aws::Vector<Aws::String>&& value) { m_snapshotIdsHasBeenSet = true; m_snapshotIds = std::move(value); }

    /**
     *
A list of identifiers of the snapshots to obtain the information for. If this
     * member is null or empty, all snapshots are returned using the Limit and
     * NextToken members.

     */
    inline DescribeSnapshotsRequest& WithSnapshotIds(const Aws::Vector<Aws::String>& value) { SetSnapshotIds(value); return *this;}

    /**
     *
A list of identifiers of the snapshots to obtain the information for. If this
     * member is null or empty, all snapshots are returned using the Limit and
     * NextToken members.

     */
    inline DescribeSnapshotsRequest& WithSnapshotIds(Aws::Vector<Aws::String>&& value) { SetSnapshotIds(std::move(value)); return *this;}

    /**
     *
A list of identifiers of the snapshots to obtain the information for. If this
     * member is null or empty, all snapshots are returned using the Limit and
     * NextToken members.

     */
    inline DescribeSnapshotsRequest& AddSnapshotIds(const Aws::String& value) { m_snapshotIdsHasBeenSet = true; m_snapshotIds.push_back(value); return *this; }

    /**
     *
A list of identifiers of the snapshots to obtain the information for. If this
     * member is null or empty, all snapshots are returned using the Limit and
     * NextToken members.

     */
    inline DescribeSnapshotsRequest& AddSnapshotIds(Aws::String&& value) { m_snapshotIdsHasBeenSet = true; m_snapshotIds.push_back(std::move(value)); return *this; }

    /**
     *
A list of identifiers of the snapshots to obtain the information for. If this
     * member is null or empty, all snapshots are returned using the Limit and
     * NextToken members.

     */
    inline DescribeSnapshotsRequest& AddSnapshotIds(const char* value) { m_snapshotIdsHasBeenSet = true; m_snapshotIds.push_back(value); return *this; }

    /**
     *
The DescribeSnapshotsResult.NextToken value from a previous call to
     * DescribeSnapshots. Pass null if this is the first call.

     */
    inline const Aws::String& GetNextToken() const{ return m_nextToken; }

    /**
     *
The DescribeSnapshotsResult.NextToken value from a previous call to
     * DescribeSnapshots. Pass null if this is the first call.

     */
    inline void SetNextToken(const Aws::String& value) { m_nextTokenHasBeenSet = true; m_nextToken = value; }

    /**
     *
The DescribeSnapshotsResult.NextToken value from a previous call to
     * DescribeSnapshots. Pass null if this is the first call.

     */
    inline void SetNextToken(Aws::String&& value) { m_nextTokenHasBeenSet = true; m_nextToken = std::move(value); }

    /**
     *
The DescribeSnapshotsResult.NextToken value from a previous call to
     * DescribeSnapshots. Pass null if this is the first call.

     */
    inline void SetNextToken(const char* value) { m_nextTokenHasBeenSet = true; m_nextToken.assign(value); }

    /**
     *
The DescribeSnapshotsResult.NextToken value from a previous call to
     * DescribeSnapshots. Pass null if this is the first call.

     */
    inline DescribeSnapshotsRequest& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;}

    /**
     *
The DescribeSnapshotsResult.NextToken value from a previous call to
     * DescribeSnapshots. Pass null if this is the first call.

     */
    inline DescribeSnapshotsRequest& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;}

    /**
     *
The DescribeSnapshotsResult.NextToken value from a previous call to
     * DescribeSnapshots. Pass null if this is the first call.

     */
    inline DescribeSnapshotsRequest& WithNextToken(const char* value) { SetNextToken(value); return *this;}

    /**
     *
The maximum number of objects to return.

     */
    inline int GetLimit() const{ return m_limit; }

    /**
     *
The maximum number of objects to return.

     */
    inline void SetLimit(int value) { m_limitHasBeenSet = true; m_limit = value; }

    /**
     *
The maximum number of objects to return.

     */
    inline DescribeSnapshotsRequest& WithLimit(int value) { SetLimit(value); return *this;}

  private:
    Aws::String m_directoryId;
    bool m_directoryIdHasBeenSet;
    Aws::Vector<Aws::String> m_snapshotIds;
    bool m_snapshotIdsHasBeenSet;
    Aws::String m_nextToken;
    bool m_nextTokenHasBeenSet;
    int m_limit;
    bool m_limitHasBeenSet;
  };

} // namespace Model
} // namespace DirectoryService
} // namespace Aws


text:
using Microsoft.Owin;
using Owin;

[assembly: OwinStartupAttribute(typeof(FootballPredictions.Web.Startup))]
namespace FootballPredictions.Web
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
        }
    }
}


text:
<!doctype html>
<html ⚡>
<head>
  <link rel="preload" href="/amp/v0.js" as="script">
  <link rel="preload" href="/amp/v0.css" as="style">
  <script async custom-element=amp-experiment src=/amp/v0/amp-experiment-0.1.js></script>
  <script async src="/amp/v0.js"></script>
  <link rel=stylesheet href=/amp/v0.css>
  <link href=https://fonts.googleapis.com/css?foobar rel=stylesheet type=text/css>
  <link href=https://example.com/favicon.ico rel=icon>
</head>
<body></body>
</html>


text:
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE erlref SYSTEM "erlref.dtd">

<erlref>

    <copyright>
      <year>1998</year><year>2016</year>
      <holder>Ericsson AB. All Rights Reserved.</holder>
    </copyright>
    <legalnotice>
      Licensed under the Apache License, Version 2.0 (the "License");
      you may not use this file except in compliance with the License.
      You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

      Unless required by applicable law or agreed to in writing, software
      distributed under the License is distributed on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      See the License for the specific language governing permissions and
      limitations under the License.

    </legalnotice>

    <title>snmp_target_mib</title>
    <prepared></prepared>
    <responsible></responsible>
    <docno></docno>
    <approved></approved>
    <checked></checked>
    <date></date>
    <rev></rev>
    <file>snmp_target_mib.xml</file>

  <module>snmp_target_mib</module>
  <modulesummary>Instrumentation Functions for SNMP-TARGET-MIB</modulesummary>
  <description>

The module <c>snmp_target_mib</c> implements the instrumentation
      functions for the SNMP-TARGET-MIB,
      and functions for configuring the database.

The configuration files are described in the SNMP User's Manual.

Legacy API functions <c>add_addr/10</c> that does not specify
      transport domain, and <c>add_addr/11</c> that has got separate
      <c>IpAddr</c> and <c>PortNumber</c> arguments still work as before
      for backwards compatibility reasons.

    <marker id="types"></marker>
  </description>

    <title>DATA TYPES</title>

See the <seealso marker="snmpa_conf#types">
    data types in <c>snmpa_conf</c></seealso>.

    <marker id="configure"></marker>

  <funcs>
    <func>
      <name>configure(ConfDir) -> void()</name>
      <fsummary>Configure the SNMP-TARGET-MIB</fsummary>
      <type>
        <v>ConfDir = string()</v>
      </type>
      <desc>

This function is called from the supervisor at system
          start-up.

Inserts all data in the configuration files into the
          database and destroys all old rows with StorageType
          <c>volatile</c>.  The rows created from the configuration file
          will have StorageType <c>nonVolatile</c>.

All <c>snmp</c> counters are set to zero.

If an error is found in the configuration file, it is
          reported using the function <c>config_err/2</c> of the error
          report module, and the function fails with the reason
          <c>configuration_error</c>.

<c>ConfDir</c> is a string which points to the directory
          where the configuration files are found.

The configuration files read are: <c>target_addr.conf</c>
          and <c>target_params.conf</c>.

	<marker id="reconfigure"></marker>
      </desc>
    </func>

    <func>
      <name>reconfigure(ConfDir) -> void()</name>
      <fsummary>Configure the SNMP-TARGET-MIB</fsummary>
      <type>
        <v>ConfDir = string()</v>
      </type>
      <desc>

Inserts all data in the configuration files into the
          database and destroys all old data, including the rows with
          StorageType <c>nonVolatile</c>.  The rows created from the
          configuration file will have StorageType <c>nonVolatile</c>.

Thus, the data in the SNMP-TARGET-MIB, after this
          function has been called, is the data from the configuration
          files.

All <c>snmp</c> counters are set to zero.

If an error is found in the configuration file, it is
          reported using the function <c>config_err/2</c> of the ,
          and the function fails with the reason
          <c>configuration_error</c>.

<c>ConfDir</c> is a string which points to the directory
          where the configuration files are found.

The configuration files read are: <c>target_addr.conf</c>
          and <c>target_params.conf</c>.

	<marker id="set_target_engine_id"></marker>
      </desc>
    </func>

    <func>
      <name>set_target_engine_id(TargetAddrName, EngineId) -> boolean()</name>
      <fsummary>Set the engine id for a targetAddr row.</fsummary>
      <type>
        <v>TargetAddrName = string()</v>
        <v>EngineId = string()</v>
      </type>
      <desc>

Changes the engine id for a target in the
          <c>snmpTargetAddrTable</c>.
          If notifications are sent as Inform requests to a target, its
          engine id must be set.

	<marker id="add_addr"></marker>
      </desc>
    </func>

    <func>
      <name>add_addr(Name, Domain, Addr, Timeout, Retry, TagList, Params, EngineId, TMask, MMS) -> Ret</name>
      <fsummary>Add one target address definition</fsummary>
      <type>
        <v>Name = string()</v>
        <v>Domain = transportDomain()</v>
	<v>Addr = transportAddress()  % Default port is 162</v>
        <v>Timeout = integer()</v>
        <v>Retry = integer()</v>
        <v>TagList = string()</v>
        <v>ParamsName = string()</v>
        <v>EngineId = string()</v>
        <v>TMask = transportAddressMask()  % Depends on Domain</v>
        <v>MMS = integer()</v>
        <v>Ret = {ok, Key} | {error, Reason}</v>
        <v>Key = term()</v>
        <v>Reason = term()</v>
      </type>
      <desc>

Adds a target address definition to the agent config.
          Equivalent to one line in the <c>target_addr.conf</c> file.

        <marker id="delete_addr"></marker>
      </desc>
    </func>

    <func>
      <name>delete_addr(Key) -> Ret</name>
      <fsummary>Delete one target address definition</fsummary>
      <type>
        <v>Key = term()</v>
        <v>Ret = ok | {error, Reason}</v>
        <v>Reason = term()</v>
      </type>
      <desc>

Delete a target address definition from the agent config.

        <marker id="add_params"></marker>
      </desc>
    </func>

    <func>
      <name>add_params(Name, MPModel, SecModel, SecName, SecLevel) -> Ret</name>
      <fsummary>Add one target parameter definition</fsummary>
      <type>
        <v>Name = string()</v>
        <v>MPModel = v1 | v2c | v3</v>
        <v>SecModel = v1 | v2c | usm</v>
        <v>SecName = string()</v>
        <v>SecLevel = noAuthNoPriv | authNoPriv | authPriv</v>
        <v>Ret = {ok, Key} | {error, Reason}</v>
        <v>Key = term()</v>
        <v>Reason = term()</v>
      </type>
      <desc>

Adds a target parameter definition to the agent config.
          Equivalent to one line in the <c>target_params.conf</c> file.

        <marker id="delete_params"></marker>
      </desc>
    </func>
    <func>
      <name>delete_params(Key) -> Ret</name>
      <fsummary>Delete one target parameter definition</fsummary>
      <type>
        <v>Key = term()</v>
        <v>Ret = ok | {error, Reason}</v>
        <v>Reason = term()</v>
      </type>
      <desc>

Delete a target parameter definition from the agent config.

      </desc>
    </func>
  </funcs>

</erlref>


text:
using System.Collections.Generic;

namespace ClipperLib
{
    public class MyIntersectNodeSort : IComparer<IntersectNode>
    {
        public int Compare(IntersectNode node1, IntersectNode node2)
        {
            int i = node2.Pt.Y - node1.Pt.Y;
            if (i > 0) return 1;
            else if (i < 0) return -1;
            else return 0;
        }
    }
}


text:
/**
 *
 * Process Editor - UML Package
 *
 * (C) 2008,2009 Frank Puhlmann
 *
 * http://frapu.net
 *
 */
package net.frapu.code.visualization.uml;

import net.frapu.code.visualization.*;

import javax.swing.*;

/**
 *
 * @author frank
 */
public class UMLEditorTest {

    private ProcessEditor editor;

    public UMLEditorTest() {
        // Show editor
        JFrame f = new JFrame("UML Editor Demo");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        editor = new ProcessEditor(createExample());

        // Add pane to frame and show
        f.add(new JScrollPane(editor));
        f.pack();
        f.setVisible(true);
    }

    private ClassModel createExample() {

        // Prepare model
        ClassModel model = new ClassModel("UML Class model");

        // Create sample Class
        UMLClass c1 = new UMLClass("Class 1");
        c1.setPos(100, 100);

        model.addNode(c1);

        return model;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                new UMLEditorTest();
            }
        });
    }
}


text:
package org.scientist.word;

public class WordSegmentException extends Exception{

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	public WordSegmentException(String ex) {
		super(ex);
	}
}


text:
module PaperTrail
  # Base Version class for tracking model activity
  class Version < ActiveRecord::Base
    include PaperTrail::VersionConcern
    self.abstract_class = true
  end
end


text:
<#

.SYNOPSIS
This Azure Automation Runbook, when triggered via Webhook, will look for Nano Server VMs with a Tag Text of 'CoreWebAppDemo' and attempt to deploy
the .NET Core Web Application to that Nano Server.

.DESCRIPTION

.PARAMETER WebhookData
This is the WebhookData that is automatically passed from the Webhook to the Runbook. The Runbook will exit if this Data Object is empty.

.NOTES
Filename:   rb-parsing-github-webhooks.ps1
Author:     Ryan Irujo (https://github.com/starkfell)
Language:   PowerShell 5.0

.EXAMPLE
./rb-parsing-github-webhooks.ps1

#>

param(
    [Object]$WebhookData
)

# Parsing information out of the WebhookData.
If ($WebhookData)
{
    Write-Output "RAW WEBHOOK DATA"
    $WebhookData | FL *
    Write-Output "                "

    # Parsing the RequestBody from the WebhookData.
    $RequestBody = ConvertFrom-Json -InputObject $WebhookData.RequestBody

    Write-Output "REQUEST BODY"
    $RequestBody
    Write-Output "            "

    # Commit Message
    $Message = $RequestBody.head_commit.message

    # Name of person who made the commit.
    $Name = $RequestBody.head_commit.author.name

    # Username of the person who pushed the update.
    $Username = $RequestBody.pusher.name

    # E-mail address of the person pushed the update.
    $Email = $RequestBody.pusher.email

    Write-Output "Commit Message:  $Message "
    Write-Output "Name:            $Name "
    Write-Output "Username:        $Username "
    Write-Output "E-mail Address:  $Email "

    exit 0

    #$Login = $RequestBody.Sender.login
    #Write-Output "Login: $Login "
    #$Login
}

# If this Runbook is not triggered from a Webhook or no WebhookData is found, the script will exit.
If (!$WebhookData)
{
	Write-Output "Runbook wasn't triggered from Webhook or no WebhookData was passed. Exiting."
	exit 1
}


text:
/**
 *

 * Fault Injection Simulator is a managed service that enables you to perform fault injection experiments on your Amazon
 * Web Services workloads. For more information, see the Fault Injection Simulator User Guide.
 *

 */
package com.amazonaws.services.fis;


text:
package com.nominanuda.zen.xml;

import org.xml.sax.SAXException;
import org.xml.sax.ext.LexicalHandler;

public class NullLexicalHandler implements LexicalHandler {

	public void startDTD(String name, String publicId, String systemId)
			throws SAXException {
	}

	public void endDTD() throws SAXException {
	}

	public void startEntity(String name) throws SAXException {
	}

	public void endEntity(String name) throws SAXException {
	}

	public void startCDATA() throws SAXException {
	}

	public void endCDATA() throws SAXException {
	}

	public void comment(char[] ch, int start, int length) throws SAXException {
	}
}


text:
package org.jls.toolbox.io.serial;

import gnu.io.SerialPort;

/**
 * Represents the serial link's parameters.
 *
 * @author Julien LE SAUCE
 * @date 20 févr. 2016
 */
public class SerialLinkParameters {

    private String comId;
    private int baudRate;
    private int flowControlIn;
    private int flowControlOut;
    private int databits;
    private int stopbits;
    private int parity;
    private int recvTimeout;

    /**
     * Instantiates a default set of parameters ("DEFAULT", 9600 bauds, no flow
     * control, 8 data bits, 1 stop bit, no parity).
     */
    public SerialLinkParameters() {
        this("DEFAULT", 9600, SerialPort.FLOWCONTROL_NONE, SerialPort.FLOWCONTROL_NONE, SerialPort.DATABITS_8,
                SerialPort.STOPBITS_1, SerialPort.PARITY_NONE, 200);
    }

    /**
     * Instantiates a new set of parameters using the specifies values.
     *
     * @param id
     *            Serial link's identifier.
     * @param baudRate
     *            The baud rate.
     * @param flowControlIn
     *            The reception's flow control type.
     * @param flowControlOut
     *            The transmission's flow control type.
     * @param databits
     *            The number of data bits.
     * @param stopbits
     *            The number of stop bits.
     * @param parity
     *            Parity type.
     * @param recvTimeout
     *            Reception timeout in milliseconds.
     */
    public SerialLinkParameters(String id, int baudRate, int flowControlIn, int flowControlOut, int databits,
            int stopbits, int parity, int recvTimeout) {
        this.comId = id;
        this.baudRate = baudRate;
        this.flowControlIn = flowControlIn;
        this.flowControlOut = flowControlOut;
        this.databits = databits;
        this.stopbits = stopbits;
        this.parity = parity;
        this.recvTimeout = recvTimeout;
    }

    /**
     * Specifies the serial link's identifier.
     *
     * @param id
     *            Serial link's identifier.
     */
    public void setComId (String id) {
        this.comId = id;
    }

    /**
     * Returns the serial link's identifier.
     *
     * @return The serial link's identifier.
     */
    public String getComId () {
        return this.comId;
    }

    /**
     * Specifies the baud rate.
     *
     * @param baudRate
     *            Baud rate in bauds.
     */
    public void setBaudRate (int baudRate) {
        this.baudRate = baudRate;
    }

    /**
     * Returns the baud rate.
     *
     * @return Baud rate in bauds.
     */
    public int getBaudRate () {
        return this.baudRate;
    }

    /**
     * Specifies the reception's flow control type.
     *
     * @param flowControl
     *            Flow control type.
     */
    public void setFlowControlIn (String flowControl) {
        if ("NONE".equals(flowControl)) {
            this.flowControlIn = SerialPort.FLOWCONTROL_NONE;
        } else if ("RTSCTS_IN".equals(flowControl)) {
            this.flowControlIn = SerialPort.FLOWCONTROL_RTSCTS_IN;
        } else if ("XONXOFF_IN".equals(flowControl)) {
            this.flowControlIn = SerialPort.FLOWCONTROL_XONXOFF_IN;
        } else {
            throw new IllegalArgumentException("Invalid flowControlIn value : " + flowControl);
        }
    }

    /**
     * Returns the reception's flow control type.
     *
     * @return Flow control type.
     */
    public int getFlowControlIn () {
        return this.flowControlIn;
    }

    /**
     * Specifies the transmission's flow control type.
     *
     * @param flowControl
     *            Flow control type.
     */
    public void setFlowControlOut (String flowControl) {
        if ("NONE".equals(flowControl)) {
            this.flowControlOut = SerialPort.FLOWCONTROL_NONE;
        } else if ("RTSCTS_OUT".equals(flowControl)) {
            this.flowControlOut = SerialPort.FLOWCONTROL_RTSCTS_OUT;
        } else if ("XONXOFF_OUT".equals(flowControl)) {
            this.flowControlOut = SerialPort.FLOWCONTROL_XONXOFF_OUT;
        } else {
            throw new IllegalArgumentException("Invalid flowControlOut value : " + flowControl);
        }
    }

    /**
     * Returns the transmission's flow control type.
     *
     * @return Flow control type.
     */
    public int getFlowControlOut () {
        return this.flowControlOut;
    }

    /**
     * Specifies the number of data bits.
     *
     * @param nbBits
     *            Number of data bits (see {@link SerialPort} to know the available
     *            set of values).
     */
    public void setDatabits (int nbBits) {
        switch (nbBits) {
            case 5:
                this.databits = SerialPort.DATABITS_5;
                break;
            case 6:
                this.databits = SerialPort.DATABITS_6;
                break;
            case 7:
                this.databits = SerialPort.DATABITS_7;
                break;
            case 8:
                this.databits = SerialPort.DATABITS_8;
                break;
            default:
                throw new IllegalArgumentException("Invalid databits value : " + nbBits);
        }
    }

    /**
     * Returns the number of data bits.
     *
     * @return Number of data bits.
     */
    public int getDatabits () {
        return this.databits;
    }

    /**
     * Specifies the number of stop bits.
     *
     * @param nbBits
     *            Number of stop bits (see {@link SerialPort} to know the available
     *            set of values).
     */
    public void setStopbits (String nbBits) {
        if (nbBits.equals("1")) {
            this.stopbits = SerialPort.STOPBITS_1;
        } else if (nbBits.equals("1.5") || nbBits.equals("1,5") || nbBits.equals("1_5")) {
            this.stopbits = SerialPort.STOPBITS_1_5;
        } else if (nbBits.equals("2")) {
            this.stopbits = SerialPort.STOPBITS_2;
        } else {
            throw new IllegalArgumentException("Invalid stopbits value : " + nbBits);
        }
    }

    /**
     * Returns the number of stop bits.
     *
     * @return Number of stop bits.
     */
    public int getStopbits () {
        return this.stopbits;
    }

    /**
     * Specifies the parity type.
     *
     * @param parity
     *            Parity type
     */
    public void setParity (String parity) {
        if ("NONE".equals(parity)) {
            this.parity = SerialPort.PARITY_NONE;
        } else if ("EVEN".equals(parity)) {
            this.parity = SerialPort.PARITY_EVEN;
        } else if ("MARK".equals(parity)) {
            this.parity = SerialPort.PARITY_MARK;
        } else if ("ODD".equals(parity)) {
            this.parity = SerialPort.PARITY_ODD;
        } else if ("SPACE".equals(parity)) {
            this.parity = SerialPort.PARITY_SPACE;
        } else {
            throw new IllegalArgumentException("Invalid parity value");
        }
    }

    /**
     * Returns the parity type.
     *
     * @return Parity type.
     */
    public int getParity () {
        return this.parity;
    }

    /**
     * Returns the timeout time used to read on the serial link whatever data comes
     * in or not.
     *
     * @return Timeout in milliseconds.
     */
    public int getRecvTimeout () {
        return this.recvTimeout;
    }

    /**
     * Specifies the timeout time used to read on the serial link whatever data
     * comes in or not.
     *
     * @param tMillis
     *            Timeout in milliseconds.
     */
    public void setRecvTimeout (int tMillis) {
        this.recvTimeout = tMillis;
    }
}


text:
package org.wso2.carbon.usage.agent.util;

/**
 * this class define constants for UsageAgent component
 */
public class UsageAgentConstants {
    public static final String ELEMENT_NAME_DATA = "Data";
    public static final String ELEMENT_NAME_KEY = "Key";
    public static final String ELEMENT_NAME_VALUE = "Value";

    public static final String STATISTICS_DATA_NS_URI = "http://wso2.org/ns/2009/09/bam/server/user-defined/data";
    public static final String STATISTICS_DATA_NS_PREFIX = "svrusrdata";

    // OM element names
    public static final String STATISTICS_DATA_ELEMENT_NAME_EVENT = "Event";
    public static final String STATISTICS_DATA_ELEMENT_NAME_SERVICE_STATISTICS_DATA = "ServerUserDefinedData";
    public static final String STATISTICS_DATA_ELEMENT_NAME_TENANT_ID = "TenantID";
    public static final String STATISTICS_DATA_ELEMENT_NAME_SERVER_NAME = "ServerName";

    public static final String BAM_SERVER_URL = "BamServerURL";
    public static final String BAM_SERVER_STAT_SERVICE = "BAMServerUserDefinedDataSubscriberService";
    public static final String BAM_SERVER_STAT_FILTER = "carbon/bam/data/publishers/bandwidth-stat";

    public static final String TOPIC_SEPARATOR = "/";
    public static final String EVENT_NAME = "UsageMeteringEvent";

    public static final String BANDWIDTH_USAGE_TOPIC = BAM_SERVER_STAT_FILTER;
//    public static final String BANDWIDTH_USAGE_TOPIC = BAM_SERVER_STAT_FILTER + TOPIC_SEPARATOR + EVENT_NAME;

    public static final String BANDWIDTH_USAGE_SERVICES_CONTEXT = "services";
    public static final String BANDWIDTH_USAGE_WEBAPPS_CONTEXT = "webapps";
    public static final String BANDWIDTH_CARBON = "carbon";
}


text:
package models

import (
	"bytes"
	"io"
	"strings"

    "database/sql/driver"
    "encoding/json"

    "github.com/satori/go.uuid"
    "github.com/golang/glog"
)

func NewInterfaceMap() map[string]interface{} {
	return make(map[string]interface{})
}

type InterfaceMap map[string]interface{}

func (m *InterfaceMap) Scan(value interface{}) error {
    return json.Unmarshal(value.([]byte), m)
}

func (m InterfaceMap) Value() (driver.Value, error) {
	if len(m) == 0 {
		return string("{}"), nil
	}

    b, err := json.Marshal(m)
    if err != nil {
        return string("{}"), err
    }
    return string(b), nil
}

type StringMap map[string]string

func NewStringMap() map[string]string {
	return make(map[string]string)
}

func (m *StringMap) Scan(value interface{}) error {
    return json.Unmarshal(value.([]byte), m)
}

func (m StringMap) Value() (driver.Value, error) {
	if len(m) == 0 {
		return string("{}"), nil
	}

    b, err := json.Marshal(m)
    if err != nil {
        return string("{}"), err
    }
    return string(b), nil
}

type StringArray []string

func (c *StringArray) FromArray(v interface{}) *StringArray {
	switch v.(type) {
	case []uuid.UUID:
		for _, _v := range v.([]uuid.UUID) {
			c.Add(_v.String())
		}
	case []string:
		for _, _v := range v.([]string) {
			c.Add(_v)
		}
	case []interface{}:
		for _, _v := range v.([]interface{}) {
			c.Add(_v.(string))
		}
	case StringArray:
		for _, _v := range []string(v.(StringArray)) {
			c.Add(_v)
		}
	default:
		glog.Warningf("Not supported type %T", v)
	}

	return c
}

func (c StringArray) Array() []string {
	return []string(c)
}

func (c *StringArray) AddAsArray(in []string) {
	for _, str := range in {
		c.Add(str)
	}
}

func (c *StringArray) AddAsFields(in string) {
	for _, str := range strings.Fields(in) {
		c.Add(str)
	}
}

func (c *StringArray) Del(str string) *StringArray {
	str = strings.TrimSpace(str)

	if !c.IsExist(str) {
		return c
	}

	for index, value := range *c {

		if bytes.Equal([]byte(str), []byte(value)) {
			(*c)[index] = (*c)[len((*c))-1]
			(*c) = (*c)[:len((*c))-1]

			return c
		}
	}

	return c
}

func (c *StringArray) IsExist(str string) bool {
	str = strings.TrimSpace(str)

	for _, value := range *c {

		if bytes.Equal([]byte(str), []byte(value)) {

			return true
		}
	}

	return false
}

func (c *StringArray) Add(str string) *StringArray {
	str = strings.TrimSpace(str)

	if len(str) == 0 {
		return c
	}

	if !c.IsExist(str) {
		*c = append(*c, str)
	}

	return c
}

// extractFieldsFromMap if len(without) == 0 return all fileds
func ExtractFieldsFromMap(m map[string]interface{}, without ...string) (keys []string, fields []interface{}) {
	_without := make(map[string]bool)
	var flagAllFields = len(without) == 0

	for _, v := range without {
		_without[v] = true
	}

	for fieldName, field := range m {
		if !flagAllFields {
			if !_without[fieldName] {
				continue
			}
		}

		keys = append(keys, fieldName)
		fields = append(fields, field)
	}

	return
}

// FromJson extract object from data (io.Reader OR []byte)
func FromJson(obj interface{}, data interface{}) error {
	switch data.(type) {
	case io.Reader:
		decoder := json.NewDecoder(data.(io.Reader))
		return decoder.Decode(obj)
	case []byte:
		return json.Unmarshal(data.([]byte), obj)
	}

	return ErrNotSupported
}


text:
package apple.foundation;

import apple.NSObject;
import org.moe.natj.c.ann.FunctionPtr;
import org.moe.natj.general.NatJ;
import org.moe.natj.general.Pointer;
import org.moe.natj.general.ann.Generated;
import org.moe.natj.general.ann.Library;
import org.moe.natj.general.ann.Mapped;
import org.moe.natj.general.ann.NInt;
import org.moe.natj.general.ann.NUInt;
import org.moe.natj.general.ann.Owned;
import org.moe.natj.general.ann.Runtime;
import org.moe.natj.general.ptr.VoidPtr;
import org.moe.natj.objc.Class;
import org.moe.natj.objc.ObjCRuntime;
import org.moe.natj.objc.SEL;
import org.moe.natj.objc.ann.ObjCBlock;
import org.moe.natj.objc.ann.ObjCClassBinding;
import org.moe.natj.objc.ann.Selector;
import org.moe.natj.objc.map.ObjCObjectMapper;

/**
 * NSURLSessionDownloadTask is a task that represents a download to
 * local storage.
 */
@Generated
@Library("Foundation")
@Runtime(ObjCRuntime.class)
@ObjCClassBinding
public class NSURLSessionDownloadTask extends NSURLSessionTask {
    static {
        NatJ.register();
    }

    @Generated
    protected NSURLSessionDownloadTask(Pointer peer) {
        super(peer);
    }

    @Generated
    @Selector("accessInstanceVariablesDirectly")
    public static native boolean accessInstanceVariablesDirectly();

    @Generated
    @Owned
    @Selector("alloc")
    public static native NSURLSessionDownloadTask alloc();

    @Owned
    @Generated
    @Selector("allocWithZone:")
    public static native NSURLSessionDownloadTask allocWithZone(VoidPtr zone);

    @Generated
    @Selector("automaticallyNotifiesObserversForKey:")
    public static native boolean automaticallyNotifiesObserversForKey(String key);

    @Generated
    @Selector("cancelPreviousPerformRequestsWithTarget:")
    public static native void cancelPreviousPerformRequestsWithTarget(@Mapped(ObjCObjectMapper.class) Object aTarget);

    @Generated
    @Selector("cancelPreviousPerformRequestsWithTarget:selector:object:")
    public static native void cancelPreviousPerformRequestsWithTargetSelectorObject(
            @Mapped(ObjCObjectMapper.class) Object aTarget, SEL aSelector,
            @Mapped(ObjCObjectMapper.class) Object anArgument);

    @Generated
    @Selector("classFallbacksForKeyedArchiver")
    public static native NSArray<String> classFallbacksForKeyedArchiver();

    @Generated
    @Selector("classForKeyedUnarchiver")
    public static native Class classForKeyedUnarchiver();

    @Generated
    @Selector("debugDescription")
    public static native String debugDescription_static();

    @Generated
    @Selector("description")
    public static native String description_static();

    @Generated
    @Selector("hash")
    @NUInt
    public static native long hash_static();

    @Generated
    @Selector("instanceMethodForSelector:")
    @FunctionPtr(name = "call_instanceMethodForSelector_ret")
    public static native NSObject.Function_instanceMethodForSelector_ret instanceMethodForSelector(SEL aSelector);

    @Generated
    @Selector("instanceMethodSignatureForSelector:")
    public static native NSMethodSignature instanceMethodSignatureForSelector(SEL aSelector);

    @Generated
    @Selector("instancesRespondToSelector:")
    public static native boolean instancesRespondToSelector(SEL aSelector);

    @Generated
    @Selector("isSubclassOfClass:")
    public static native boolean isSubclassOfClass(Class aClass);

    @Generated
    @Selector("keyPathsForValuesAffectingValueForKey:")
    public static native NSSet<String> keyPathsForValuesAffectingValueForKey(String key);

    @Generated
    @Owned
    @Selector("new")
    public static native NSURLSessionDownloadTask new_objc();

    @Generated
    @Selector("resolveClassMethod:")
    public static native boolean resolveClassMethod(SEL sel);

    @Generated
    @Selector("resolveInstanceMethod:")
    public static native boolean resolveInstanceMethod(SEL sel);

    @Generated
    @Selector("setVersion:")
    public static native void setVersion_static(@NInt long aVersion);

    @Generated
    @Selector("superclass")
    public static native Class superclass_static();

    @Generated
    @Selector("version")
    @NInt
    public static native long version_static();

    /**
     * Cancel the download (and calls the superclass -cancel). If
     * conditions will allow for resuming the download in the future, the
     * callback will be called with an opaque data blob, which may be used
     * with -downloadTaskWithResumeData: to attempt to resume the download.
     * If resume data cannot be created, the completion handler will be
     * called with nil resumeData.
     */
    @Generated
    @Selector("cancelByProducingResumeData:")
    public native void cancelByProducingResumeData(
            @ObjCBlock(name = "call_cancelByProducingResumeData") Block_cancelByProducingResumeData completionHandler);

    @Generated
    @Selector("init")
    public native NSURLSessionDownloadTask init();

    @Runtime(ObjCRuntime.class)
    @Generated
    public interface Block_cancelByProducingResumeData {
        @Generated
        void call_cancelByProducingResumeData(NSData resumeData);
    }
}


text:
package com.turnos.restservice.servicios;

import io.swagger.annotations.Api;

import java.util.ArrayList;

import javax.validation.Valid;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.turnos.datos.WebServUtils;
import com.turnos.datos.handlers.TurnoHandler;
import com.turnos.datos.vo.ErrorBean;
import com.turnos.datos.vo.ResidenciaBean;
import com.turnos.datos.vo.TurnoBean;
import com.turnos.datos.vo.TurnoBean.TipoTurno;
import com.turnos.datos.vo.UsuarioBean;

@Api(value = "Turno")
@Produces(MediaType.APPLICATION_JSON)
@Path(WebServUtils.PREF_RES_PATH + WebServUtils.COD_RES_PATH + WebServUtils.PREF_TURNO_PATH)
public class TurnoServicio extends GenericServicio{

	protected TurnoServicio(UsuarioBean usuarioLog) {
		super(usuarioLog);
	}

	protected TurnoServicio(@Context ContainerRequestContext request) {
		super(request);
	}

	// ---------------------GET-----------------------------------------------

	@GET
	@Valid
	public Response listaTurnos (@PathParam(WebServUtils.P_PARAM_COD_RES) String codRes,
			@QueryParam(WebServUtils.Q_PARAM_TIPO_TURNO) String tipoStr,
			@QueryParam(WebServUtils.Q_PARAM_INC_SERVS) @DefaultValue("false") boolean includeServs) {
		ErrorBean errorBean = new ErrorBean();
		ArrayList<TurnoBean> listaTurnos;

		if (tipoStr == null) {
			listaTurnos = TurnoHandler.listTodosTurnos(null, codRes, includeServs, errorBean);
		} else {
			TipoTurno tipo = TipoTurno.safeValueOf(tipoStr);
			listaTurnos = TurnoHandler.listTurnosTipo(null, codRes, tipo, includeServs, errorBean);
		}

		return creaRespuestaGenericaGETLista(listaTurnos, errorBean);
	}

	@GET
	@Path(WebServUtils.COD_TURNO_PATH)
	@Valid
	public Response getTurno (@PathParam(WebServUtils.P_PARAM_COD_RES) String codRes,
			@PathParam(WebServUtils.P_PARAM_COD_TURNO) String codTurno,
			@QueryParam(WebServUtils.Q_PARAM_INC_SERVS) @DefaultValue("false") boolean includeServs) {
		ErrorBean errorBean = new ErrorBean();
		TurnoBean turno = TurnoHandler.getTurno(null, codRes, codTurno, includeServs, errorBean);

		return creaRespuestaGenericaGET(turno, errorBean);
	}

	@POST
	@Consumes(MediaType.APPLICATION_JSON)
	@Valid
	public Response nuevoTurno(TurnoBean turnoRaw,
			@PathParam(WebServUtils.P_PARAM_COD_RES) String codRes) {
		ErrorBean errorBean = new ErrorBean();
		TurnoBean turno = TurnoHandler.insertTurno(null, codRes, turnoRaw, errorBean);

		return creaRespuestaGenericaPOST(turno, errorBean);
	}

	@PUT
	@Path(WebServUtils.COD_TURNO_PATH)
	@Consumes(MediaType.APPLICATION_JSON)
	@Valid
	public Response modTurno(TurnoBean turnoRaw,
			@PathParam(WebServUtils.P_PARAM_COD_RES) String codRes,
			@PathParam(WebServUtils.P_PARAM_COD_TURNO) String codTurno) {
		ErrorBean errorBean = new ErrorBean();
		TurnoBean turno = TurnoHandler.updateTurno(null, codRes, codTurno, turnoRaw, errorBean);

		return creaRespuestaGenericaPUT(turno, errorBean);
	}

	@DELETE
	@Path(WebServUtils.COD_TURNO_PATH)
	@Valid
	public Response borraTurno(@PathParam(WebServUtils.P_PARAM_COD_RES) String codRes,
			@PathParam(WebServUtils.P_PARAM_COD_TURNO) String codTurno) {
		ErrorBean errorBean = new ErrorBean();
		boolean borrado = TurnoHandler.deleteTurno(null, codRes, codTurno, errorBean);

		return creaRespuestaGenericaDELETE(borrado, ResidenciaBean.class, errorBean);
	}

}