text:
/**
   \file        staticdiskpartitionenumeration.cpp

   \brief       Implementation of the Enumeration of Static Disk Partition

   \date        09-12-11 14:12:00

*/
/*----------------------------------------------------------------------------*/

#include <scxcorelib/scxcmn.h>
#include <scxcorelib/scxexception.h>
#include <scxcorelib/scxdirectoryinfo.h>
#include <scxcorelib/scxfilepath.h>
#include <scxcorelib/stringaid.h>
#include <scxcorelib/scxprocess.h>
#include <scxcorelib/scxthread.h>
#include <scxcorelib/logsuppressor.h>

#include <scxsystemlib/diskdepend.h>
#include <scxsystemlib/staticdiskpartitionenumeration.h>
#include <scxsystemlib/staticdiskpartitioninstance.h>

#if defined(hpux)
#include <sys/diskio.h>
#endif
#if defined(aix)
#include <lvm.h>
#endif

using namespace SCXCoreLib;

namespace SCXSystemLib
{

    /** Module name string */
    const wchar_t *StaticDiskPartitionEnumeration::moduleIdentifier = L"scx.core.common.pal.system.disk.staticdiskpartitionenumeration";

    /*----------------------------------------------------------------------------*/
    /**
        Standard Constructor
    */
    StaticDiskPartitionEnumeration::StaticDiskPartitionEnumeration(SCXCoreLib::SCXHandle<DiskDepend> deps) :
        m_deps(deps), m_log(SCXLogHandleFactory::GetLogHandle(moduleIdentifier))
    {
        SCX_LOGTRACE(m_log, L"StaticDiskPartitionEnumeration Standard constructor");
    }

    /*----------------------------------------------------------------------------*/
    /**
       Destructor.
    */
    StaticDiskPartitionEnumeration::~StaticDiskPartitionEnumeration()
    {
        SCX_LOGTRACE(m_log, L"StaticDiskPartitionEnumeration::~StaticDiskPartitionEnumeration()");
    }

    /*----------------------------------------------------------------------------*/
    /**
        Creates the total DiskPartition instances.
    */
    void StaticDiskPartitionEnumeration::Init()
    {
        SCX_LOGTRACE(m_log, L"StaticDiskPartitionEnumeration Init()");
        Update(true);
    }

    /*----------------------------------------------------------------------------*/
    /**
       Enumeration Cleanup method.

       Release of cached resources.

    */
    void StaticDiskPartitionEnumeration::CleanUp()
    {
        EntityEnumeration<StaticDiskPartitionInstance>::CleanUp();
    }

    /*----------------------------------------------------------------------------*/
    /**
       Update the enumeration.

       \param updateInstances If true (default) all instances will be updated.
                              Otherwise only the content of the enumeration will be updated.

    */
    void StaticDiskPartitionEnumeration::Update(bool updateInstances /*=true*/)
    {
        SCX_LOGTRACE(m_log, L"StaticDiskPartitionEnumeration Update() Entering . . .");
        if (!updateInstances)
        {
            return;
        }

#if defined(linux)
        /************* Start Linux ************************************/
        const wchar_t * const proc_part = L"/proc/partitions"; // partitions file path
        int                major     = 0;                  // major number of a partition
        int                minor     = 0;                  // minor number of a partition
        int                blocks    = 0;                  // blocks of a partition
        vector<std::wstring>  allLines;                       // all lines read from partitions table
        std::wstring          partname;                       // name of the partition
        const std::wstring    dev_dir = L"/dev/";              // device directory

        SCXStream::NLFs nlfs;
        SCXFile::ReadAllLines(SCXFilePath(proc_part), allLines, nlfs);

        // Let's read through line-by-line the /proc/partitions pseudo-file.
        for (vector<std::wstring>::iterator it = allLines.begin(); it != allLines.end(); it++)
        {
            std::wstring devPath;
            std::wistringstream is(*it);

            // Each line of /proc/partitions has four fields. Here's the header:
            //     major minor  #blocks  name
            if (is>>major>>minor>>blocks>>partname)
            {
                devPath = dev_dir + partname;
            }
            else
            {
                SCX_LOGINFO(m_log, L"This line in /proc/partitions doesn't contain Blocksize and Partition Name. line:" + is.str());
                continue;
            }

            //Partition names end in the partitionIndex, skip the 'dm-*' because those are device-mapped
            if (m_deps->FileExists(devPath) && isdigit(partname[partname.size()-1]) && (std::wstring::npos == partname.find(L"-")))
            {
                SCXCoreLib::SCXHandle<StaticDiskPartitionInstance> partit = GetInstance(partname);
                if (NULL == partit)
                {
                    partit = new StaticDiskPartitionInstance();
                }
                partit->SetId(partname);
                partit->m_deviceID = devPath;
                //Last chars of partition name is the index. Need to handle 1, 2 or 3 digits
                partit->m_index =
                    SCXCoreLib::StrToUInt(partname.substr(partname.find_first_of(L"0123456789")));

                if (partit->CheckFdiskLinux())
                {
                   AddInstance(partit);
                }
                else
                {
                   SCX_LOGINFO(m_log, L"This partition is listed in /proc/partitions, but not in fdisk: Name: " + partname);
                   //delete partit;  Handle destructed when exiting this block
                }

            }

        } //EndFor
        /************* End Linux **************************************/

#elif defined(sun)
        static SCXCoreLib::LogSuppressor suppressor(SCXCoreLib::eWarning, SCXCoreLib::eTrace);

        // Sun doesn't have /proc/partitions or /proc/mounts, so we need to handle it differently.
        const std::wstring dev_dsk_dir = L"/dev/dsk";              // device directory

        bool firstInstance = true;
        std::wstring bootp;
        // ZFS partition indices start after regular partitions are assigned their indices.
        size_t zfsFirstIndex = 0;

        m_deps->RefreshMNTTab();
        for (std::vector<MntTabEntry>::const_iterator it = m_deps->GetMNTTab().begin();
             it != m_deps->GetMNTTab().end(); it++)
        {
            SCX_LOGTRACE(m_log, L"DPEnum::Update():: Inside FOR loop, Device=" + it->device + L"  And file=" + it->fileSystem + L"  MountPt=" + it->mountPoint);

            if (! m_deps->FileSystemIgnored(it->fileSystem) && ! m_deps->DeviceIgnored(it->device) &&
                 (std::wstring::npos != (it->device).find(dev_dsk_dir)))
            {

                SCXCoreLib::SCXHandle<StaticDiskPartitionInstance> partit = GetInstance(it->device);
                if (0 == partit)
                {
                    partit = new StaticDiskPartitionInstance();
                    std::wstring devPath(it->device);
                    std::wstring partname = devPath.substr(devPath.find_last_of(L"/")+1);

                    partit->SetId(partname);
                    partit->m_deviceID = devPath;
                    //Last char of partition name is the index.
                    partit->m_index =
                         SCXCoreLib::StrToUInt(partname.substr(partname.find_last_of(L"0123456789")));
                    if ((partit->m_index + 1) > zfsFirstIndex)
                    {
                        // ZFS partition indices start after last regular partition index.
                        zfsFirstIndex = partit->m_index + 1;
                    }

                    //Getting the bootdrive is expensive, let's just do it once.
                    if (firstInstance)
                    {
                       if (partit->GetBootDrivePath(bootp))
                       {
                          firstInstance = false;
                       }
                    }

                    if (devPath == bootp)
                    {
                       partit->m_bootPartition = true;
                    }
                    else
                    {
                       partit->m_bootPartition = false;
                    }

                    AddInstance(partit);

                }
            }
            else if (SCXCoreLib::StrToLower(it->fileSystem) == L"zfs")
            {
                // It is ZFS partition.
                SCXCoreLib::SCXHandle<StaticDiskPartitionInstance> partit = GetInstance(it->device);
                if (NULL == partit)
                {
                    partit = new StaticDiskPartitionInstance();
                    partit->m_isZfsPartition = true;
                    std::wstring zfsPath(it->device);
                    partit->SetId(zfsPath);
                    partit->m_deviceID = zfsPath;
                    // Get filesystem info.
                    struct statvfs64 stat;
                    memset(&stat, 0, sizeof(stat));
                    if (m_deps->statvfs64(SCXCoreLib::StrToMultibyte(it->mountPoint).c_str(), &stat) == 0)
                    {
                        partit->m_blockSize = stat.f_frsize;
                        partit->m_numberOfBlocks = stat.f_blocks;
                        partit->m_partitionSize = partit->m_blockSize * partit->m_numberOfBlocks;
                    }
                    else
                    {
                        // Just log in case we can not get file system data.
                        std::wstring noStatvfs = L"Statvfs failed for mountpoint \"" +
                            it->mountPoint + L"\", errno = " + StrFrom(errno);
                        SCXCoreLib::SCXLogSeverity severity(suppressor.GetSeverity(noStatvfs));
                        SCX_LOG(m_log, severity, noStatvfs);
                    }
                    // ZFS boot process works in a way that first the active boot environment is determined. Then
                    // the OS installed in the root file system of that boot environment is loaded. Finally the the
                    // root file system is mounted at '/'. Therefore the file system with the mountpoint '/' represents
                    // the boot file system. If administrator mounts some other root file system at some other mount
                    // point, this file system will be returned in our list of disk partitions as well. However,
                    // although it is possible to boot from that root file system as well, it will not be marked as
                    // a bootable file system.
                    if (it->mountPoint == L"/")
                    {
                        partit->m_bootPartition = true;
                    }
                    else
                    {
                        partit->m_bootPartition = false;
                    }
                    AddInstance(partit);
                }
            }
        }
        // All regular partitions received their indices. Continue assigning indices to the ZFS partitions.
        size_t i;
        for (i = 0; i < Size(); i++)
        {
            SCXCoreLib::SCXHandle<StaticDiskPartitionInstance> partit = GetInstance(i);
            if (partit->m_isZfsPartition == true)
            {
                partit->m_index = zfsFirstIndex;
                zfsFirstIndex++;
            }
        }

#elif defined(aix)

        // We are mapping AIX logical volumes to the Windows concept of partitions, because AIX
        // has no direct equivalent to partitions.

        // Get mounted file systems first. We will need them as we go through all logical volumes.
        int ret = -1;
        std::vector<char> vm;
        // Get the size of the required buffer.
        int vmsz = 0;
        ret = m_deps->mntctl(MCTL_QUERY, sizeof(vmsz), (char*)&vmsz);
        if(ret != 0)
        {
            throw SCXErrnoException(
                L"mntctl failed trying to get required buffer size", errno, SCXSRCLOCATION);
        }
        vm.resize(vmsz);
        // Fill the buffer with mount points data.
        int mount_point_cnt = m_deps->mntctl(MCTL_QUERY, vm.size(), &vm[0]);
        if(mount_point_cnt == -1)
        {
            throw SCXErrnoException(L"mntctl failed trying to get mount points", errno, SCXSRCLOCATION);
        }

        // Now get all of the partitions.

        unsigned int partition_index = 0;

        // Get list of all volume groups.
        struct queryvgs *vgs = NULL;
        int ret_lvmvgs = m_deps->lvm_queryvgs(&vgs, NULL);
        if (ret_lvmvgs != 0)
        {
            throw SCXInternalErrorException(L"lvm_queryvgs failed with error code: " + StrFrom(ret_lvmvgs) +
                L".", SCXSRCLOCATION);
        }
        // Iterate through volume groups.
        for (long ivg = 0; ivg < vgs->num_vgs; ivg++)
        {
            // For each volume group get list of logical volumes.
            struct queryvg *vg = NULL;
            int ret_lvmvg = m_deps->lvm_queryvg(&vgs->vgs[ivg].vg_id, &vg, NULL);
            if (ret_lvmvg != 0)
            {
                throw SCXInternalErrorException(L"lvm_queryvg failed with error code: " + StrFrom(ret_lvmvg) +
                    L".", SCXSRCLOCATION);
            }
            // Iterate through logical volumes.
            for (long ilv = 0; ilv < vg->num_lvs; ilv++)
            {
                // Get logical volume data. We use try catch so we don't crash just because
                // there was error getting data for one volume.
                try
                {
                    struct querylv *lv = NULL;
                    int ret_lvmlv = m_deps->lvm_querylv(&vg->lvs[ilv].lv_id, &lv, NULL);
                    if (ret_lvmlv != 0)
                    {
                        throw SCXInternalErrorException(L"lvm_querylv for logical volume \"" +
                            StrFromMultibyte(vg->lvs[ilv].lvname) + L"\" failed with error code: " +
                            StrFrom(ret_lvmlv) + L".", SCXSRCLOCATION);
                    }
                    ProcessOneDiskPartition(vm, mount_point_cnt, lv->lvname,
                        static_cast<scxlong>(lv->currentsize) << lv->ppsize, partition_index);
                }
                catch(SCXCoreLib::SCXException& e)
                {
                    SCX_LOGERROR(m_log, e.What() + L" " + e.Where());
                }
            }
        }
#elif defined(hpux)
        vector<SCXLogicalVolumes> logVol;
        bool bootLvFound = false;
        size_t fullBootLvIndex = 0;
        GetLogicalVolumesBoot(logVol, bootLvFound, fullBootLvIndex);
        size_t i;
        for(i = 0; i<logVol.size(); i++)
        {
            SCXCoreLib::SCXHandle<StaticDiskPartitionInstance> partition_instance = GetInstance(logVol[i].name);
            if (NULL == partition_instance)
            {
                partition_instance = new StaticDiskPartitionInstance();
                partition_instance->SetId(logVol[i].name);
                partition_instance->m_deviceID = logVol[i].name;
                partition_instance->m_index = i;

                if(logVol[i].mntDir.size() != 0)
                {
                    // We have a mount point for this logical volume. Get info about the file system.
                    struct statvfs64 stat;
                    memset(&stat, 0, sizeof(stat));
                    int r = m_deps->statvfs64(StrToMultibyte(logVol[i].mntDir).c_str(), &stat);
                    if(r != 0)
                    {
                        wstring msg = L"statvfs() failed for mountpoint \"" + logVol[i].mntDir + L"\".";
                        SCX_LOGERROR(m_log, msg);
                    }
                    // Now we have all file system data. Update the disk partition instance.
                    scxulong partition_size =
                        static_cast<scxulong>(stat.f_frsize) * static_cast<scxulong>(stat.f_blocks);

                    partition_instance->m_blockSize = stat.f_frsize;
                    partition_instance->m_numberOfBlocks = stat.f_blocks;
                    partition_instance->m_partitionSize = partition_size;
                }
                else
                {
                    // No mount point. Get the size by other means. We use try catch so we don't crash just because
                    // there was error getting one datafield for one volume.
                    try
                    {
                        // Before calling ioctl verify that name matches logical volume name. We expect name in format:
                        // "/def/some_vg_name/some_lv_name"
                        SCXRegex regEx(L"(^/dev/[^/]+/[^/]+$)");
                        vector<std::wstring> matches;
                        if (!regEx.ReturnMatch(logVol[i].name, matches, 0))
                        {
                            if (!matches[0].empty())
                            {
                                wstring msg = L"Error encountered when trying to verify device name \"" + logVol[i].name +
                                    L"\". " + matches[0];
                                throw SCXInternalErrorException(msg, SCXSRCLOCATION);
                            }
                            else
                            {
                                wstring msg = L"Device name \"" + logVol[i].name + L"\" is invalid.";
                                throw SCXInternalErrorException(msg, SCXSRCLOCATION);
                            }
                        }
                        // Name matches, make raw device name.
                        wstring rname = logVol[i].name;
                        size_t namePos = rname.rfind(L'/');
                        if (namePos == wstring::npos)
                        {
                            wstring msg = L"Device name \"" + rname + L"\" missing full path.";
                            throw SCXErrnoException(msg, errno, SCXSRCLOCATION);
                        }
                        rname.insert(namePos + 1, L"r");
                        // Open the device file, call ioctl(DIOC_CAPACITY), set the size value and close the device file.
                        int fd = m_deps->_open(StrToMultibyte(rname).c_str(), O_RDONLY);
                        if (fd == -1)
                        {
                            wstring msg = L"open(O_RDONLY) failed for device \"" + rname + L"\".";
                            throw SCXErrnoException(msg, errno, SCXSRCLOCATION);
                        }
                        capacity_type ct;
                        memset(&ct, 0, sizeof(ct));
                        int ret = m_deps->_ioctl(fd, DIOC_CAPACITY, &ct);
                        if (ret == -1)
                        {
                            wstring msg = L"ioctl(DIOC_CAPACITY) failed for device \"" + rname + L"\".";
                            throw SCXErrnoException(msg, errno, SCXSRCLOCATION);
                        }
                        partition_instance->m_partitionSize = ct.lba * DEV_BSIZE;
                        if (m_deps->_close(fd) != 0)
                        {
                            wstring msg = L"close() failed for device \"" + rname + L"\".";
                            throw SCXErrnoException(msg, errno, SCXSRCLOCATION);
                        }
                    }
                    catch(SCXCoreLib::SCXException& e)
                    {
                        SCX_LOGERROR(m_log, e.What() + L" " + e.Where());
                    }
                }
                if(bootLvFound && fullBootLvIndex == i)
                {
                    partition_instance->m_bootPartition = true;
                }
                AddInstance(partition_instance);
            }
        }
#endif
    }

#if defined(aix)
    /*----------------------------------------------------------------------------*/
    /**
        Processes one disk partition during enumeration.

        \param mountPoints Buffer containing mount points.
        \param mountPointCnt Number of mountpoints in the buffer.
        \param partitionName Partition name.
        \param partitionSize Partition size.
        \param partitionIndex Partition index.
    */
    void StaticDiskPartitionEnumeration::ProcessOneDiskPartition(const std::vector<char> &mountPoints, int mountPointCnt,
        const char* partitionName, scxlong partitionSize, unsigned int &partitionIndex)
    {
        SCXCoreLib::SCXHandle<SCXodm> odm_deps = m_deps->CreateOdm();
        std::string partition_name = partitionName;

        struct CuAt ret_data_at;
        void *ret_at;
        std::string criteria_at = "name=";
        criteria_at += partition_name;
        // Find disk partition instance or create one.
        SCXCoreLib::SCXHandle<StaticDiskPartitionInstance> partition_instance =
            GetInstance(StrFromMultibyte(partition_name));
        if (NULL == partition_instance)
        {
            partition_instance = new StaticDiskPartitionInstance();
            partition_instance->SetId(StrFromMultibyte(partition_name));

            std::string type;
            // Get first attribute of the partition.
            memset(&ret_data_at, 0, sizeof(ret_data_at));
            ret_at = odm_deps->Get(CuAt_CLASS, (char*)criteria_at.c_str(), &ret_data_at, SCXodm::eGetFirst);
            while(ret_at != NULL)
            {
                std::string attribute = ret_data_at.attribute;
                if(attribute == "type")
                {
                    type = ret_data_at.value;
                }

                // Get next attribute of the partition.
                memset(&ret_data_at, 0, sizeof(ret_data_at));
                ret_at = odm_deps->Get(CuAt_CLASS, NULL, &ret_data_at, SCXodm::eGetNext);
            }

            // Find the mount point for this partition.
            const struct vmount *vmp = reinterpret_cast<const struct vmount *>(&mountPoints[0]);
            int i;
            for(i = 0; i < mountPointCnt; i++)
            {
                if(vmp->vmt_flags & MNT_DEVICE)
                {
                    // Consider only physical device mounts.
                    std::string full_device_name = "/dev/" + partition_name;
                    if(full_device_name == reinterpret_cast<const char*>(vmp) + vmp->vmt_data[VMT_OBJECT].vmt_off)
                    {
                        // We have found our mount point. Get info about the file system.
                        struct statvfs64 stat;
                        memset(&stat, 0, sizeof(stat));
                        int r = m_deps->statvfs64(reinterpret_cast<const char*>(vmp) + vmp->vmt_data[VMT_STUB].vmt_off,
                            &stat);
                        if(r != 0)
                        {
                            throw SCXErrnoException(L"statvfs failed", errno, SCXSRCLOCATION);
                        }

                        // Now we have all file system data. Update the disk partition instance.
                        scxulong partition_size =
                            static_cast<scxulong>(stat.f_frsize) * static_cast<scxulong>(stat.f_blocks);

                        partition_instance->m_blockSize = stat.f_frsize;
                        partition_instance->m_numberOfBlocks = stat.f_blocks;
                        partition_instance->m_partitionSize = partition_size;
                        break;
                    }
                }

                // Get next mount point.
                vmp = reinterpret_cast<const struct vmount *>(reinterpret_cast<const char*>(vmp) + vmp->vmt_length);
            }

            partition_instance->m_deviceID = StrFromMultibyte(partition_name);
            partition_instance->m_index = partitionIndex;
            if(partition_instance->m_partitionSize == 0)
            {
                // Didn't get partition size from mount point. Use size from lvm.
                partition_instance->m_partitionSize = partitionSize;
            }
            if(type == "boot")
            {
                partition_instance->m_bootPartition = true;
            }

            AddInstance(partition_instance);
        }
        partitionIndex++;
    }
#endif

    /*----------------------------------------------------------------------------*/
    /**
        Dump object as string (for logging).

        Parameters:  None
        Retval:      The object represented as a string suitable for logging.

    */
    const std::wstring StaticDiskPartitionEnumeration::DumpString() const
    {
        return L"StaticDiskPartitionEnumeration";
    }

#if defined(hpux)

    void StaticDiskPartitionEnumeration::GetBootLV(
        const vector<SCXLogicalVolumes> &logVol, const vector<std::wstring> &logVolShort,
        const vector<size_t> &logVolVGIndex,
        const vector<std::wstring> &physVol, const vector<size_t> &physVolVGIndex,
        size_t &fullBootLvIndex)
    {
        // Execute 'vgdisplay -v' to get list of logical volumes.
        std::istringstream lvProcIn;
        std::ostringstream lvProcOut;
        std::ostringstream lvProcErr;
        std::wstring procCmd = L"lvlnboot -v";
        int procRet = m_deps->Run(procCmd, lvProcIn, lvProcOut, lvProcErr, 15000);
        std::string lvlnbootStr = lvProcOut.str();
        std::string errStr = lvProcErr.str();
        if(procRet == 0 && errStr.size() == 0)
        {
            // Read lines returned by 'lvlnboot -v'. We are looking for the lines in format:
            // [wspace | nothing]["Boot:" | "Root:"][wspace][short lv name][wspace]["on:"][wspace][pv name][endl]
            // For example:
            // Boot: lvol1   on:   /dev/dsk/c0t0d0s2
            std::istringstream lvlnbootStrm(lvlnbootStr);
            SCXCoreLib::SCXStream::NLFs nlfs;
            vector<std::wstring> lvlnbootLines;
            SCXCoreLib::SCXStream::ReadAllLinesAsUTF8(lvlnbootStrm, lvlnbootLines, nlfs);

            // Prepare SCXRegex regular expression to extract LG, LV or PV name from the lines.
            // This regular expression can match a boot or root line, for example "Boot: l vol 1  on: /dev/dsk/c0t0d0s2".
            // In the case of the match logical volume name is stripped of leading and trailing spaces and rule that the
            // name can not contain any '/' characters is enforced. Also rule is enforced that physical volume name must
            // have "/dev/" prefix and additional '/' character somewhere in the middle of the remainder of the name.
            // When match is made expression will load "Boot:" or "Root:" in the return value number 1. Logical volume
            // name, in the short form and stripped of leading and trailing spaces, will be loaded in the in the return
            // value number 2 and physical volume name will be loaded in the return value number 3.
            SCXRegex regEx(L"^[ \t]*(Boot:|Root:)[ \t]+([^/ \t]|[^/ \t][^/]+[^/ \t])[ \t]+on:[ \t]+(/dev/[^/]+/[^/]+)$");

            size_t i;
            std::wstring bootLvName;
            std::wstring bootPvName;
            bool bootOrRootFound = false;
            for(i = 0; i < lvlnbootLines.size(); i++)
            {
                std::wstring bootOrRoot;
                std::wstring lvN;
                std::wstring pvN;
                vector<std::wstring> regExMatches;
                if(regEx.ReturnMatch(lvlnbootLines[i], regExMatches, 0))
                {
                    // Boot or root volume is found.
                    bootOrRoot = regExMatches[1];
                    bootLvName = regExMatches[2];
                    bootPvName = regExMatches[3];
                    bootOrRootFound = true;
                    if(bootOrRoot == L"Boot:")
                    {
                        break;
                    }
                    // If no boot is found then root volume is also boot volume.
                }
            }
            if(bootOrRootFound == false)
            {
                throw SCXCoreLib::SCXInternalErrorException(
                    std::wstring(L"Output from 'lvlnboot -v' does not contain any boot or root data."), SCXSRCLOCATION);
            }

            // We have boot LV name but it is stripped of leading and trailing white spaces and is missing path
            // that contains VG name to which LV belongs to. We must recover the full logical volume name.
            // First match the boot PV with the one in the list of all PV's available on the system.
            vector<std::wstring>::const_iterator it = find(physVol.begin(), physVol.end(), bootPvName);
            if(it == physVol.end())
            {
                // PV name from "lvlnboot -v" not found in "vgdisplay -v".
                std::wstring invalidPvName = L"PV Name '" + bootPvName +
                    L"' from 'lvlnboot -v' output not found in 'vgdisplay -v' output.";
                throw SCXCoreLib::SCXInternalErrorException(invalidPvName, SCXSRCLOCATION);
            }
            // Get the index of the matched PV.
            size_t physVolIndex = distance(physVol.begin(), it);
            // Get the index of the VG the PV belongs to.
            size_t bootVGIndex = physVolVGIndex[physVolIndex];
            // Search list of logical volumes with same Volume Group index and find one that matches boot LV name.
            size_t lvFoundCount = 0;
            for(i = 0; i < logVolVGIndex.size(); i++)
            {
                if(logVolVGIndex[i] == bootVGIndex)
                {
                    if(logVolShort[i] == bootLvName)
                    {
                        fullBootLvIndex = i;
                        lvFoundCount++;
                    }
                }
            }
            if(lvFoundCount == 0)
            {
                // LV name from "lvlnboot -v" not found in "vgdisplay -v".
                std::wstring invalidLvName = L"Boot LV Name '" + bootLvName +
                    L"' from 'lvlnboot -v' output not found in 'vgdisplay -v' output.";
                throw SCXCoreLib::SCXInternalErrorException(invalidLvName, SCXSRCLOCATION);
            }
            if(lvFoundCount > 1)
            {
                std::wstring invalidLvName = L"Boot LV Name '" + bootLvName +
                    L"' from 'lvlnboot -v' output found multiple times in 'vgdisplay -v' output. Names differ "
                    L"only in leading and trailing spaces. impossible to determine actual boot logical volume.";
                throw SCXCoreLib::SCXInternalErrorException(invalidLvName, SCXSRCLOCATION);
            }

        }
        else
        {
            std::wstring procExcMsg = L"Execution of '" + procCmd + L"' failed with return code " +
                StrFrom(procRet) + L".\nOutput:\n" + StrFromMultibyte(lvlnbootStr) + L"\nError output:\n" +
                StrFromMultibyte(errStr) + L"\n";
            throw SCXCoreLib::SCXInternalErrorException(procExcMsg, SCXSRCLOCATION);
        }
    }

    /**
        Retrieves vector of mount points. This helper function is necessary to put HP-s fix that ensures data integrity
        around setmntent(), getmntent(), endmntent() sequence. Fix description and sample code is from
        HP-UX reference on getmntent(3X). To achieve data integrity we compare MNT_MNTTAB file size and modification time
        before and after data reads and use data only if there was no modification.

        \param log Handle to a log file.
        \param deps External dependencies.
        \param mountPoints Return vector to be filled with mount points.
    */
    void GetMountPoints(SCXCoreLib::SCXLogHandle &log, SCXCoreLib::SCXHandle<DiskDepend> &deps,
                        vector<SCXLogicalVolumes> &mountPoints)
    {
        static SCXCoreLib::LogSuppressor supressor(SCXCoreLib::eWarning, SCXCoreLib::eTrace);
        mountPoints.clear();

        // HP-s fix for flaw in setmntent(). To achieve data integrity we compare file modification time before and
        // after data reads. Data integrity code is from HP-UX reference on getmntent(3X).
        struct stat statbuf;
        FILE *fp;
        time_t origMtime;
        off_t origSize;
        bool readStatus = false;
        const int noOfRetries = 5;
        int retry;
        for (retry = 0; retry < noOfRetries; retry++)
        {
            if (deps->stat(MNT_MNTTAB, &statbuf) != 0)
            {
                throw SCXErrnoException(L"stat(MNT_MNTTAB, &statbuf)" , errno, SCXSRCLOCATION);
            }
            // If file is empty, do not bother reading it. Sleep and then retry the stat().
            if (statbuf.st_size == 0)
            {
                std::wstring emptyMntTabFileWarning(L"File MNT_MNTTAB is empty.");
                SCXCoreLib::SCXLogSeverity severity(supressor.GetSeverity(emptyMntTabFileWarning));
                SCX_LOG(log, severity, emptyMntTabFileWarning);
                SCXCoreLib::SCXThread::Sleep(100);
                if (deps->stat(MNT_MNTTAB, &statbuf) != 0)
                {
                    throw SCXErrnoException(L"stat(MNT_MNTTAB, &statbuf)" , errno, SCXSRCLOCATION);
                }
                else
                {
                    if (statbuf.st_size == 0)
                    {
                        continue;
                    }
                }
            }
            if ((fp = deps->setmntent(MNT_MNTTAB, "r")) == NULL)
            {
                throw SCXErrnoException(L"setmntent(MNT_MNTTAB, \"r\")" , errno, SCXSRCLOCATION);
            }

            // Get mount points.
            struct mntent *mountpoint = deps->getmntent(fp);
            while(mountpoint != NULL)
            {
                SCXLogicalVolumes currentMountPoint;
                currentMountPoint.name = SCXCoreLib::StrFromMultibyte(mountpoint->mnt_fsname);
                currentMountPoint.mntDir = SCXCoreLib::StrFromMultibyte(mountpoint->mnt_dir);
                currentMountPoint.mntType = SCXCoreLib::StrFromMultibyte(mountpoint->mnt_type);
                currentMountPoint.mntOpts = SCXCoreLib::StrFromMultibyte(mountpoint->mnt_opts);
                mountPoints.push_back(currentMountPoint);
                // Next mount point.
                mountpoint = deps->getmntent(fp);
            }
            deps->endmntent(fp);

            // Compare file time to ensure data integrity.
            origMtime = statbuf.st_mtime; origSize = statbuf.st_size;
            if (deps->stat(MNT_MNTTAB, &statbuf) != 0)
            {
                throw SCXErrnoException(L"stat(MNT_MNTTAB, &statbuf)" , errno, SCXSRCLOCATION);
            }
            if ((statbuf.st_mtime == origMtime) && (statbuf.st_size == origSize))
            {
                readStatus = true;
                break;
            }
        }

        // Delete data if data integrity is in question.
        if (readStatus == false)
        {
            mountPoints.clear();
        }
    }

    /*----------------------------------------------------------------------------*/
    /**
        Executes "vgdisplay -v" command and returns lists of volume groups, logical and physical volumes found on
        the system.

        \param log Logging handle.
        \param deps Dependencies handle.
        \param volGroup Returned list of volume groups found on the system.
        \param logVol Returned list of logical volumes found on the system.
        \param logVolShort Returned list of logical volume names in the short form, without path and with leading
                           and trailing spaces removed.
        \param logVolVGIndex Index of a volume group to which particular logical volume belongs to.
        \param physVol Returned list of physical volumes found on the system.
        \param physVolVGIndex Index of a volume group to which particular physical volume belongs to.
    */
    void GetVgLvPv(SCXCoreLib::SCXLogHandle &log,
            SCXCoreLib::SCXHandle<DiskDepend> &deps, vector<std::wstring> &volGroup,
            vector<SCXLogicalVolumes> &logVol, vector<std::wstring> &logVolShort, vector<size_t> &logVolVGIndex,
            vector<std::wstring> &physVol, vector<size_t> &physVolVGIndex)
    {
        volGroup.clear();
        logVol.clear();
        logVolShort.clear();
        logVolVGIndex.clear();
        physVol.clear();
        physVolVGIndex.clear();

        // Get mount points.
        vector<SCXLogicalVolumes> mountPoints;
        GetMountPoints(log, deps, mountPoints);
        // Execute 'vgdisplay -v' to get list of logical volumes.
        std::istringstream lvProcIn;
        std::ostringstream lvProcOut;
        std::ostringstream lvProcErr;
        std::wstring procCmd = L"vgdisplay -v";
        int procRet = deps->Run(procCmd, lvProcIn, lvProcOut, lvProcErr, 15000);
        std::string vgStr = lvProcOut.str();
        std::string errStr = lvProcErr.str();
        if(procRet == 0 && errStr.size() == 0)
        {
            // Read lines returned by 'vgdisplay -v'. We are looking for the lines in format:
            // [wspace | nothing]["VG" | "LV" | "PV"][wspace]["Name"][wspace][name][endl]
            // for example:
            //   LV Name /dev/vg00/lvol8
            std::istringstream vgStrm(vgStr);
            SCXCoreLib::SCXStream::NLFs nlfs;
            vector<std::wstring> lvLines;
            SCXCoreLib::SCXStream::ReadAllLinesAsUTF8(vgStrm, lvLines, nlfs);

            // Prepare SCXRegex regular expression to extract LG, LV or PV name from the lines.
            // This regular expression can match volume group line, logical volume line or physical volume line.
            // In the case of the volume group line, for example "VG Name /dev/vg00", it will enforce the rule
            // that name must contain "/dev/" prefix. When match is made it will load the full name "/dev/vg00"
            // into the return value number 1.
            // In the case of the logical or physical volume line, for example " LV Name /dev/vg00/ l vol 1 " it
            // will enforce the rule that name must contain "/dev/" prefix and one aditional '/' character somewhere
            // in the middle of the reminder of the name. When match is made it will load "LV" or "PV" in the return
            // value number 2, full name "/dev/vg00/ l vol 1 " into the return value number 3, and short name without
            // the path and stripped from leading and trailing spaces "l vol 1" into the return value number 4.
            SCXRegex regEx(L"^[ \t]*VG[ \t]+Name[ \t]+(/dev/[^/]+)$|"
                           L"^[ \t]*(LV|PV)[ \t]+Name[ \t]+(/dev/[^/]+/[ \t]*([^/ \t]|[^/ \t][^/]+[^/ \t])[ \t]*)$");

            size_t i;
            for(i = 0; i < lvLines.size(); i++)
            {
                vector<SCXRegExMatch> regExMatches;
                if(regEx.ReturnMatch(lvLines[i], regExMatches, 5, 0) == true)
                {
                    if(regExMatches[1].matchFound ==true)
                    {
                        // Volume group match.
                        volGroup.push_back(regExMatches[1].matchString);
                    }
                    else
                    {
                        // Logical volume or physical volume is matched.

                        // First check if there is volume group for this logical volume.
                        if(volGroup.size() == 0)
                        {
                            throw SCXCoreLib::SCXInternalErrorException(
                                std::wstring(L"vgdisplay -v returned corrupt data."
                                          L"LV or PV name encountered before it's VG name."),
                                          SCXSRCLOCATION);
                        }

                        std::wstring nameType = regExMatches[2].matchString;
                        std::wstring name = regExMatches[3].matchString;
                        if(nameType == L"LV")
                        {
                            // Logical volume name is found.
                            SCXLogicalVolumes currentLogVol;
                            currentLogVol.name = name;

                            // Find mount point for this logical volume, if any.
                            size_t m;
                            for(m = 0; m < mountPoints.size(); m++)
                            {
                                if(mountPoints[m].name == currentLogVol.name)
                                {
                                    currentLogVol = mountPoints[m];
                                    break;
                                }
                            }
                            // Add to the result logical volume and it's mount point if any.
                            logVol.push_back(currentLogVol);
                            logVolShort.push_back(regExMatches[4].matchString);
                            logVolVGIndex.push_back(volGroup.size() - 1);
                        }
                        else
                        {
                            //nameType == "PV"
                            physVol.push_back(name);
                            physVolVGIndex.push_back(volGroup.size() - 1);
                        }
                    }
                }
            }
        }
        else
        {
            std::wstring procExcMsg = L"Execution of '" + procCmd + L"' failed with return code " +
                StrFrom(procRet) + L".\nOutput:\n" + StrFromMultibyte(vgStr) + L"\nError output:\n" +
                StrFromMultibyte(errStr) + L"\n";
            throw SCXCoreLib::SCXInternalErrorException(procExcMsg, SCXSRCLOCATION);
        }
    }

    void GetLogicalVolumes(SCXCoreLib::SCXLogHandle &log,
            SCXCoreLib::SCXHandle<DiskDepend> &deps, vector<SCXLogicalVolumes> &logVol)
    {
        vector<std::wstring> volGroup;
        vector<std::wstring> logVolShort;
        vector<size_t> logVolVGIndex;
        vector<std::wstring> physVol;
        vector<size_t> physVolVGIndex;
        GetVgLvPv(log, deps, volGroup, logVol, logVolShort, logVolVGIndex, physVol, physVolVGIndex);
    }

    void StaticDiskPartitionEnumeration::GetLogicalVolumesBoot(vector<SCXLogicalVolumes> &logVol,
            bool &bootLvFound, size_t &fullBootLvIndex)
    {
        bootLvFound = false;
        fullBootLvIndex = 0;

        // Retrieve lists of volume groups, logical and physical volumes present in the system.
        vector<std::wstring> volGroup;
        vector<std::wstring> logVolShort;
        vector<size_t> logVolVGIndex;
        vector<std::wstring> physVol;
        vector<size_t> physVolVGIndex;
        GetVgLvPv(m_log, m_deps, volGroup, logVol, logVolShort, logVolVGIndex, physVol, physVolVGIndex);

        try
        {
            // Try to find whish is the boot volume.
            GetBootLV(logVol, logVolShort, logVolVGIndex, physVol, physVolVGIndex, fullBootLvIndex);
            bootLvFound = true;
        }
        catch(SCXCoreLib::SCXException& e)
        {
            // Catch all boot flag processing exceptions here. We don't want to lose all other
            // data just because boot flag processing failed.
            SCX_LOGERROR(m_log, "Failed to find boot logical volume.");
            SCX_LOGERROR(m_log, e.What());
        }
    }
#endif// hpux
}

/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/


text:
$(function() {
  var UpdatePost = {};

  $('#slackNotificationForm').on('submit', function(e) {
    $.post('/_api/admin/notification.add', $(this).serialize(), function(res) {
      if (res.ok) {
        // TODO Fix
        location.reload();
      }
    });

    return false;
  });

  $('form.admin-remove-updatepost').on('submit', function(e) {
    $.post('/_api/admin/notification.remove', $(this).serialize(), function(res) {
      if (res.ok) {
        // TODO Fix
        location.reload();
      }
    });
    return false;
  });

  $('#createdUserModal').modal('show');

  $('#admin-password-reset-modal').on('show.bs.modal', function(button) {
    var data = $(button.relatedTarget);
    var userId = data.data('user-id');
    var email = data.data('user-email');

    $('#admin-password-reset-user').text(email);
    $('#admin-users-reset-password input[name=user_id]').val(userId);
  });

  $('form#admin-users-reset-password').on('submit', function(e) {
    $.post('/_api/admin/users.resetPassword', $(this).serialize(), function(res) {
      if (res.ok) {
        // TODO Fix
        //location.reload();
        $('#admin-password-reset-modal').modal('hide');
        $('#admin-password-reset-modal-done').modal('show');

        $("#admin-password-reset-done-user").text(res.user.email);
        $("#admin-password-reset-done-password").text(res.newPassword);
        return ;
      }

      // fixme
      alert('Failed to reset password');
    });

    return false;
  });
});

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Diagnostics;
using System.Reflection;
using System.Threading;
using Gallio.Common.Platform;

#if DOTNET40
using Gallio.Common.Reflection.Impl.DotNet40;
#else
using Gallio.Common.Reflection.Impl.DotNet20;
#endif

namespace Gallio.Common.Reflection.Impl
{
    /// <summary>
    /// Creates instances of unresolved reflection objects based on <see cref="ICodeElementInfo"/> wrappers.
    /// </summary>
    /// <remarks>
    /// <para>
    /// All objects produced by this factory implement <see cref="IUnresolvedCodeElement" />.
    /// </para>
    /// </remarks>
    public abstract class UnresolvedCodeElementFactory
    {
        private static UnresolvedCodeElementFactory instance;

        /// <summary>
        /// Creates an instance of the factory.
        /// </summary>
        protected UnresolvedCodeElementFactory()
        {
        }

        /// <summary>
        /// Gets the singleton instance of the factory.
        /// </summary>
        [DebuggerNonUserCode]
        public static UnresolvedCodeElementFactory Instance
        {
            get
            {
                if (instance == null)
                {
                    UnresolvedCodeElementFactory newInstance = null;

                    if (DotNetFrameworkSupport.FrameworkVersion >= DotNetFrameworkVersion.DotNet40)
                    {
                        try
                        {
                            AssemblyName assemblyName = typeof(UnresolvedCodeElementFactory).Assembly.GetName();
                            assemblyName.Name = "Gallio40";

                            Assembly assembly = Assembly.Load(assemblyName);
                            Type factoryType = assembly.GetType("Gallio.Common.Reflection.Impl.DotNet40.UnresolvedCodeElementFactoryInternal");
                            newInstance = (UnresolvedCodeElementFactory) Activator.CreateInstance(factoryType, true);
                        }
                        catch
                        {
                            // Ignore the error and fallback on .Net 2.0 compatible version.
                        }
                    }

                    if (newInstance == null)
                        newInstance = new UnresolvedCodeElementFactoryInternal();

                    Interlocked.CompareExchange(ref instance, newInstance, null);
                }

                return instance;
            }
        }

        /// <summary>
        /// Creates an <see cref="Assembly" /> wrapper for <see cref="IAssemblyInfo" />.
        /// </summary>
        /// <param name="adapter">The adapter.</param>
        /// <returns>The unresolved assembly.</returns>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="adapter"/> is null.</exception>
        public abstract Assembly Wrap(IAssemblyInfo adapter);

        /// <summary>
        /// Creates a <see cref="ConstructorInfo" /> wrapper for <see cref="IConstructorInfo" />.
        /// </summary>
        /// <param name="adapter">The adapter.</param>
        /// <returns>The unresolved constructor.</returns>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="adapter"/> is null.</exception>
        public abstract ConstructorInfo Wrap(IConstructorInfo adapter);

        /// <summary>
        /// Creates a <see cref="EventInfo" /> wrapper for <see cref="IEventInfo" />.
        /// </summary>
        /// <param name="adapter">The adapter.</param>
        /// <returns>The unresolved event.</returns>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="adapter"/> is null.</exception>
        public abstract EventInfo Wrap(IEventInfo adapter);

        /// <summary>
        /// Creates a <see cref="FieldInfo" /> wrapper for <see cref="IFieldInfo" />.
        /// </summary>
        /// <param name="adapter">The adapter.</param>
        /// <returns>The unresolved field.</returns>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="adapter"/> is null.</exception>
        public abstract FieldInfo Wrap(IFieldInfo adapter);

        /// <summary>
        /// Creates a <see cref="MethodInfo" /> wrapper for <see cref="IMethodInfo" />.
        /// </summary>
        /// <param name="adapter">The adapter.</param>
        /// <returns>The unresolved method.</returns>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="adapter"/> is null.</exception>
        public abstract MethodInfo Wrap(IMethodInfo adapter);

        /// <summary>
        /// Creates a <see cref="ParameterInfo" /> wrapper for <see cref="IParameterInfo" />.
        /// </summary>
        /// <param name="adapter">The adapter.</param>
        /// <returns>The unresolved parameter.</returns>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="adapter"/> is null.</exception>
        public abstract ParameterInfo Wrap(IParameterInfo adapter);

        /// <summary>
        /// Creates a <see cref="PropertyInfo" /> wrapper for <see cref="IPropertyInfo" />.
        /// </summary>
        /// <param name="adapter">The adapter.</param>
        /// <returns>The unresolved property.</returns>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="adapter"/> is null.</exception>
        public abstract PropertyInfo Wrap(IPropertyInfo adapter);

        /// <summary>
        /// Creates a <see cref="Type" /> wrapper for <see cref="ITypeInfo" />.
        /// </summary>
        /// <param name="adapter">The adapter.</param>
        /// <returns>The unresolved type.</returns>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="adapter"/> is null.</exception>
        public abstract Type Wrap(ITypeInfo adapter);
    }
}


text:
BUILD_DIR=${SRC_DIR}
EXECUTABLES="bzip2"

NACLPORTS_CFLAGS+=" -Dmain=nacl_main -fPIC"
export NACLPORTS_LDFLAGS+=" ${NACL_CLI_MAIN_LIB} \
-lppapi_simple -lnacl_io -lppapi -l${NACL_CXX_LIB}"

ConfigureStep() {
  return
}

BuildStep() {
  SetupCrossEnvironment
  LogExecute make clean
  LogExecute make \
      CC="${CC}" AR="${AR}" RANLIB="${RANLIB}" \
      CFLAGS="${CFLAGS}" LDFLAGS="${LDFLAGS}" \
      -j${OS_JOBS} libbz2.a bzip2
  if [ "${NACL_SHARED}" = "1" ]; then
    LogExecute make -f Makefile-libbz2_so clean
    LogExecute make -f Makefile-libbz2_so \
      CC="${CC}" AR="${AR}" RANLIB="${RANLIB}" \
      CFLAGS="${CFLAGS}" LDFLAGS="${LDFLAGS}" \
      -j${OS_JOBS}
  fi
}

InstallStep() {
  # Don't rely on make install, as it implicitly builds executables
  # that need things not available in newlib.
  MakeDir ${DESTDIR_INCLUDE}
  MakeDir ${DESTDIR_LIB}
  LogExecute cp -f bzlib.h ${DESTDIR_INCLUDE}
  LogExecute chmod a+r ${DESTDIR_INCLUDE}/bzlib.h

  LogExecute cp -f libbz2.a ${DESTDIR_LIB}
  if [ -f libbz2.so.1.0 ]; then
    LogExecute ln -s libbz2.so.1.0 libbz2.so
    LogExecute cp -af libbz2.so* ${DESTDIR_LIB}
  fi
  LogExecute chmod a+r ${DESTDIR_LIB}/libbz2.*
}

PublishStep() {
  # TODO(bradnelson): Figure out why the newlib version gets:
  # Function not implemented
  # when compressing with the bzip2 command-line tool.
  PublishByArchForDevEnv
}


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

namespace DailySoccer.Shared.Models
{
    public class GetAllGuessHistoryRequest
    {
        public string UserId { get; set; }
    }
}


text:
CREATE TABLE pastes (
id           TEXT      PRIMARY KEY,
filename     TEXT,
created      TIMESTAMP,
expires      TIMESTAMP,
content      TEXT,
content_type TEXT);

CREATE INDEX pastes_index (
id
expires);


text:
.class public interface abstract Lcom/upsight/android/managedvariables/experience/UpsightUserExperience$Handler;
.super Ljava/lang/Object;
.source "UpsightUserExperience.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/upsight/android/managedvariables/experience/UpsightUserExperience;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x609
    name = "Handler"
.end annotation

# virtual methods
.method public abstract onReceive()Z
.end method

.method public abstract onSynchronize(Ljava/util/List;)V
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(",
            "Ljava/util/List",
            "<",
            "Ljava/lang/String;",
            ">;)V"
        }
    .end annotation
.end method


text:
This lecture provides a background on the OS process abstraction. It then
introduces the concept of concurrency and concurrent programming. Finally it
presents Go's CSP concept using several examples in Go.

## Outline

1. Processes and Threads
    - OS Basics
    - Synchronization Mechanisms
2. Concurrency
3. Concurrent Design in Go
4. goroutines and channels
5. Examples
    - Load Balancer
    - Query a Replicated Database
6. Beyond Single Nodes

## [Slides](http://go-talks.appspot.com/github.com/jf87/scalable_web_systems/session-04/slides/session04.slide)

## Readings
- Go Web Programming chapter 9
- [Hoare, C. A. R. (1978). "Communicating sequential processes". Communications of the ACM.](https://dl.acm.org/citation.cfm?id=359585)

### Questions

1. What is the difference (besides the syntax) of the concurrency model
   presented in Hoare's paper and the one implemented in Go?
2. Investigate how the HTTP server in Go is implemented. How does it handle multiple requests?

## Hands-on

1. [Hands-on-01](hands-on-01/README.md)

## Further Readings

- [Herb Sutter (2005). The Free Lunch Is Over: A Fundamental Turn Toward Concurrency in Software](http://www.gotw.ca/publications/concurrency-ddj.htm)
- [Herb Sutter (2012). Welcome to the Jungle](https://herbsutter.com/welcome-to-the-jungle/)

### On Concurrency in Go

- https://blog.golang.org/context
- https://blog.golang.org/pipelines
- https://blog.golang.org/advanced-go-concurrency-patterns
- https://blog.golang.org/share-memory-by-communicating
- https://blog.golang.org/go-concurrency-patterns-timing-out-and


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Copyright (C) 2012 FuseSource, Inc.
    http://fusesource.com

    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.

-->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.fusesource.hawtdispatch</groupId>
    <artifactId>hawtdispatch-project</artifactId>
    <version>1.11</version>
  </parent>

  <groupId>org.fusesource.hawtdispatch</groupId>
  <artifactId>hawtdispatch-transport</artifactId>
  <version>1.11</version>
  <packaging>bundle</packaging>

  <description>HawtDispatch Transport: Transport abstractions for HawtDispatch</description>

  <properties>
    <junit-version>4.7</junit-version>
    <asm-version>3.1</asm-version>
    <log4j-version>1.2.14</log4j-version>
    <osgi-version>4.2.0</osgi-version>
  </properties>

  <dependencies>

    <dependency>
      <groupId>org.fusesource.hawtdispatch</groupId>
      <artifactId>hawtdispatch</artifactId>
      <version>1.11</version>
    </dependency>
    <dependency>
      <groupId>org.fusesource.hawtbuf</groupId>
      <artifactId>hawtbuf</artifactId>
      <version>${hawtbuf-version}</version>
      <optional>true</optional>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit-version}</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>${log4j-version}</version>
      <scope>test</scope>
    </dependency>

  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.felix</groupId>
        <artifactId>maven-bundle-plugin</artifactId>
        <extensions>true</extensions>
        <inherited>true</inherited>
        <configuration>
          <instructions>
            <!-- <Bundle-Activator>org.fusesource.hawtdispatch.internal.Activator</Bundle-Activator>
            <Private-Package>org.fusesource.hawtdispatch.internal.*</Private-Package> -->
          </instructions>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">

<link rel="stylesheet" href="css/poole.css">
<link rel="stylesheet" href="css/syntax.css">
<link rel="stylesheet" href="css/hyde.css">
<link rel="stylesheet" href="css/theme.css">
<link rel="stylesheet" href="//fonts.googleapis.com/css?family=PT+Sans:400,700|Russo+One">
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css">
<link href="//block.blokada.org/favicon.png" rel="icon">

Benvingut i gràcies per utilitzar el Blokada DNS!

El Blokada és de codi obert i gratuït i respecta la vostra privadesa. En utilitzar-lo, accepteu les Condicions del servei i la Política de privadesa, que sempre podeu trobar aquí.

Ens agradaria ajudar-vos amb els vostres primers passos:

Actualment s'utilitzen servidors DNS per defecte. Podeu canviar-lo tocant la icona DNS per defecte.

El Blokada està configurat per iniciar-se quan el telèfon es posa en marxa. Podeu desactivar-lo si toqueu Arrenca a l'inici.

El Blokada s'executarà només quan estigueu connectat a Internet. Podeu canviar-ho desactivant les Només en línia.

A la Llista blanca, podeu definir quines aplicacions no han d'utilitzar els vostres servidors de DNS. Utilitzaran els servidors DNS del dispositiu per defecte.

En tocar la cantonada superior dreta podeu trobar més opcions i el menú d'Ajuda on podeu obtenir informació detallada sobre les diferents opcions del Blokada.


text:
class Moonshine::Manifest < ShadowPuppet::Manifest

  # Load a Moonshine Plugin
  #
  # *Deprecated*: plugins are now auto-loaded.
  #
  #   class MyManifest < Moonshine::Manifest
  #
  #     # Evals vendor/plugins/moonshine_awesome/moonshine/init.rb
  #     plugin :awesome
  #
  #     # Evals lib/my_recipe.rb
  #     plugin 'lib/my_recipe.rb'
  #
  #     ...
  #   end
  def self.plugin(name = nil)
    require 'active_support/core_ext/module/attribute_accessors'
    require 'active_support/core_ext/kernel/reporting'
    require 'active_support/deprecation'

    ActiveSupport::Deprecation.warn("explicitly calling the plugin method is deprecated, as plugins are now automatically loaded", caller)
    true
  end

  # The working directory of the Rails application this manifest describes.
  def self.rails_root
   @rails_root ||= Pathname.new(ENV["RAILS_ROOT"] || Dir.getwd).expand_path
  end

  def self.moonshine_yml
    rails_root.join('config', 'moonshine.yml')
  end

  def self.database_yml
    rails_root.join('config', 'database.yml')
  end

  # The current Rails environment
  def self.rails_env
    ENV["RAILS_ENV"] || 'production'
  end

  # HAX for cases where we evaluate ERB that refers to Rails.env
  def self.env
    rails_env
  end

  # The current environment's database configuration
  def database_environment
   if configuration[:database]
     configuration[:database][rails_env.to_sym]
    else
      {}
    end
  end

  # The current deployment target. Best when used with capistrano-ext's multistage settings.
  def self.deploy_stage
    ENV['DEPLOY_STAGE'] || 'undefined'
  end

  # Delegate missing methods to class, so we don't have to have so many convenience methods
  def method_missing(method, *args, &block)
    if self.class.respond_to?(method)
      self.class.send(method, *args, &block)
    else
      super
    end
  end

  def respond_to?(method, include_private = false)
    super || self.class.respond_to?(method, include_private)
  end

  # Only run tasks on the specified deploy_stage.
  #
  # You can call it with the exact stage you want to run on:
  #
  #  on_stage(:my_stage) do
  #    puts "I'm on my_stage"
  #  end
  #
  # Or you can pass an array of stages to run on:
  #
  #  on_stage(:my_stage, :my_other_stage) do
  #    puts "I'm on one of my stages"
  #  end
  #
  # Or you can run a task unless it is on a stage:
  #
  #  on_stage(:unless => :my_stage) do
  #    puts "I'm not on my_stage"
  #  end
  #
  # Or you can run a task unless it is on one of several stages:
  #
  #  on_stage(:unless => [:my_stage, :my_other_stage]) do
  #    puts "I'm not on my stages"
  #  end
  def self.on_stage(*args)
    options = args.extract_options!
    if_opt = options[:if]
    unless_opt = options[:unless]

    unless if_opt || unless_opt
      if_opt = args
    end

    if if_opt && if_opt.is_a?(Array) && if_opt.map {|x| x.to_s}.include?(deploy_stage)
      yield
    elsif if_opt && (if_opt.is_a?(String) || if_opt.is_a?(Symbol)) && deploy_stage == if_opt.to_s
      yield
    elsif unless_opt && unless_opt.is_a?(Array) && !unless_opt.map {|x| x.to_s}.include?(deploy_stage)
      yield
    elsif unless_opt && (unless_opt.is_a?(String) || unless_opt.is_a?(Symbol)) && deploy_stage != unless_opt.to_s
      yield
    end
  end

  def self.local_template_dir
    @local_template_dir ||= rails_root.join('app/manifests/templates')
  end

  def self.local_template(pathname)
   (local_template_dir + pathname.basename).expand_path
  end

  # Render the ERB template located at <tt>pathname</tt>. If a template exists
  # with the same basename at <tt>RAILS_ROOT/app/manifests/templates</tt>, it
  # is used instead. This is useful to override templates provided by plugins
  # to customize application configuration files.
  def self.template(pathname, b = binding)
    pathname = Pathname.new(pathname) unless pathname.kind_of?(Pathname)

    template_contents = if local_template(pathname).exist?
                          template_contents = local_template(pathname).read
                        elsif pathname.exist?
                          template_contents = pathname.read
                        else
                          raise LoadError, "Can't find template #{pathname}"
                        end
    ERB.new(template_contents).result(b)
  end

  def template(pathname, b = binding)
    self.class.template(pathname, b)
  end

  # autoload plugins
  Dir.glob(rails_root + 'vendor/plugins/*/moonshine/init.rb').each do |path|
    Kernel.eval(File.read(path), binding, path)
  end  # config/moonshine.yml

  if moonshine_yml.exist?
    configure(YAML::load(ERB.new(moonshine_yml.read).result))
  end

  # config/moonshine/#{rails_env}.yml
  env_config = rails_root.join('config', 'moonshine', rails_env + '.yml')
  if env_config.exist?
    configure(YAML::load(ERB.new(env_config.read).result))
  end

  # database config
  if database_yml.exist?
    configure(:database => YAML::load(ERB.new(database_yml.read).result))
  end

  # gems
  gems_yml = rails_root.join('config', 'gems.yml')
  if gems_yml.exist?
    configure(:gems => (YAML.load_file(gems_yml) rescue nil))
  end

end


text:
package pl.iterators.kebs

package object matchers extends KebsMatchers


text:
from rest_framework.test import APITestCase
from projects.models import Project
from rest_framework import status

class AuthenticationTests(APITestCase):

  def test_forbidden(self):
    response = self.client.get("/api/")
    self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

  def test_success(self):
    project = Project(name="TestProject", private_key="secret")
    project.save()

    headers = {
      'HTTP_PUBLIC_KEY': project.id,
      'HTTP_PRIVATE_KEY': project.private_key
    }

    response = self.client.get("/api/", {}, **headers)
    self.assertEqual(response.status_code, status.HTTP_200_OK)


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Ann. R. bot. Gdns Peradeniya 5(4): 254 (1912)

#### Original name
Uredo anthistiricae Petch

### Remarks
null


text:
package problems.medium;

import java.util.*;

/**
 * Why Did you create this class? what does it do?
 */
public class CheapestFlightsWithinKStops {
    public static void main(String[] args) {
        CheapestFlightsWithinKStops cheap = new CheapestFlightsWithinKStops();
        System.out.println(cheap.findCheapestPrice(6, new int[][] {
                { 0, 1, 5 }, { 1, 2, 6 }, { 0, 3, 2 }, { 3, 1, 2 }, { 1, 4, 2 }, { 4, 2, 2 }, { 0, 5, 7 }, { 5, 2, 3 },
                }, 0, 2, 3));
        System.out.println(cheap.findCheapestPrice(3, new int[][] {
                { 0, 1, 100 }, { 1, 2, 100 }, { 0, 2, 500 }
        }, 0, 2, 0));

    }

    public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) {
        if (n <= 1)
            return 0;

        Map<Integer, Map<Integer, Integer>> map = new HashMap<>();
        for (int[] flight : flights) {
            Map<Integer, Integer> pair = map.getOrDefault(flight[0], new HashMap<>());
            pair.put(flight[1], flight[2]);
            map.put(flight[0], pair);
        }
        Map<Integer, Map<Integer, Integer>> costs = new HashMap<>();
        costs.put(src, new HashMap<>());
        costs.get(src).put(-1, 0);

        for (int i = 0; i <= k; i++) {
            for (int current = 0; current < n; current++) {
                Map<Integer, Integer> currentCosts = costs.getOrDefault(current, new HashMap<>());
                Map<Integer, Integer> neis = map.get(current);
                if (neis == null)
                    continue;
                for (Integer step : currentCosts.keySet()) {
                    if (step >= k)
                        continue;
                    for (Integer nei : neis.keySet()) {
                        Map<Integer, Integer> neiCosts = costs.getOrDefault(nei, new HashMap<>());
                        int cost = neis.get(nei);
                        int min = Math.min(currentCosts.get(step) + cost, neiCosts.getOrDefault(step + 1, Integer.MAX_VALUE));
                        neiCosts.put(step + 1, min);
                        costs.put(nei, neiCosts);
                    }
                }
            }
        }
        Map<Integer, Integer> dstCosts = costs.getOrDefault(dst, new HashMap<>());
        if (dstCosts.isEmpty())
            return -1;
        int min = Integer.MAX_VALUE;
        for (Integer step : dstCosts.keySet()) {
            if (step <= k) {
                min = Math.min(min, dstCosts.get(step));
            }
        }
        return min == Integer.MAX_VALUE ? -1 : min;
    }

}


text:
BOOST_FIXTURE_TEST_SUITE(bech32_tests, BasicTestingSetup)

BOOST_AUTO_TEST_CASE(bech32_testvectors_valid)
{
    static const std::string CASES[] = {
        "A12UEL5L",
        "a12uel5l",
        "an83characterlonghumanreadablepartthatcontainsthenumber1andtheexcludedcharactersbio1tt5tgs",
        "abcdef1qpzry9x8gf2tvdw0s3jn54khce6mua7lmqqqxw",
        "11qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqc8247j",
        "split1checkupstagehandshakeupstreamerranterredcaperred2y9e3w",
        "?1ezyfcl",
    };
    for (const std::string& str : CASES) {
        const auto dec = bech32::Decode(str);
        BOOST_CHECK(dec.encoding == bech32::Encoding::BECH32);
        std::string recode = bech32::Encode(bech32::Encoding::BECH32, dec.hrp, dec.data);
        BOOST_CHECK(!recode.empty());
        BOOST_CHECK(CaseInsensitiveEqual(str, recode));
    }
}

BOOST_AUTO_TEST_CASE(bech32m_testvectors_valid)
{
    static const std::string CASES[] = {
        "A1LQFN3A",
        "a1lqfn3a",
        "an83characterlonghumanreadablepartthatcontainsthetheexcludedcharactersbioandnumber11sg7hg6",
        "abcdef1l7aum6echk45nj3s0wdvt2fg8x9yrzpqzd3ryx",
        "11llllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllludsr8",
        "split1checkupstagehandshakeupstreamerranterredcaperredlc445v",
        "?1v759aa"
    };
    for (const std::string& str : CASES) {
        const auto dec = bech32::Decode(str);
        BOOST_CHECK(dec.encoding == bech32::Encoding::BECH32M);
        std::string recode = bech32::Encode(bech32::Encoding::BECH32M, dec.hrp, dec.data);
        BOOST_CHECK(!recode.empty());
        BOOST_CHECK(CaseInsensitiveEqual(str, recode));
    }
}

BOOST_AUTO_TEST_CASE(bech32_testvectors_invalid)
{
    static const std::string CASES[] = {
        " 1nwldj5",
        "\x7f""1axkwrx",
        "\x80""1eym55h",
        "an84characterslonghumanreadablepartthatcontainsthenumber1andtheexcludedcharactersbio1569pvx",
        "pzry9x0s0muk",
        "1pzry9x0s0muk",
        "x1b4n0q5v",
        "li1dgmt3",
        "de1lg7wt\xff",
        "A1G7SGD8",
        "10a06t8",
        "1qzzfhee",
        "a12UEL5L",
        "A12uEL5L",
    };
    for (const std::string& str : CASES) {
        const auto dec = bech32::Decode(str);
        BOOST_CHECK(dec.encoding == bech32::Encoding::INVALID);
    }
}

BOOST_AUTO_TEST_CASE(bech32m_testvectors_invalid)
{
    static const std::string CASES[] = {
        " 1xj0phk",
        "\x7f""1g6xzxy",
        "\x80""1vctc34",
        "an84characterslonghumanreadablepartthatcontainsthetheexcludedcharactersbioandnumber11d6pts4",
        "qyrz8wqd2c9m",
        "1qyrz8wqd2c9m",
        "y1b0jsk6g",
        "lt1igcx5c0",
        "in1muywd",
        "mm1crxm3i",
        "au1s5cgom",
        "M1VUXWEZ",
        "16plkw9",
        "1p2gdwpf"
    };
    for (const std::string& str : CASES) {
        const auto dec = bech32::Decode(str);
        BOOST_CHECK(dec.encoding == bech32::Encoding::INVALID);
    }
}

BOOST_AUTO_TEST_SUITE_END()


text:
List of navigation items arranged as tabs.

## Features

- Two style variants.
- Four orientations.
- Rich tab-labels.
- Justified tab alignment.

## Usage

The tab bar containing the tabs is built from a unordered list and the
`vclTabs` class. It contains n `vclTab`s.
The tab items can be made of anchor tags or just textual.
An anchor tag is only needed if users should be able to open
a tab in a different window by an URL.
Buttons can be embedded as shown in the example below to offer an additional
interaction.
A tab with only a button, for example to open new tabs like in the
example below contains just a button as tab content.
The selected tab `vclSelected` is visually highlighted and can
be disabled via `vclDisabled`.

[basic example](/demo/example-basic.html)

In terms of accessibility, the following example with proper ARIA
attributes is optimal.

[basic no links](/demo/example-basic-no-links.html)

Apart from buttons, tabs may also contain other components like a badge as
in the example above. To get proper margins, all elements within
a `vclTab` get the `vclTabLabel`.

Add the modifier class `vclTabStyleUni` for uni colored tabs.
This style is more suitable for showing tabs unobtrusively within
content textual for example.

[uni example](/demo/example-uni.html)

The class `vclTabbable` is used to create a wrapper for the tabs
and the content area.
The content area can be built from various components
such as a panel or the included classes `vclTabContent` and `vclTabPanel`.

By default tabs are laid out as shown above.
Different layouts are possible as shown below.

Modifier class `vclTabLeft`.

[left1 example](/demo/example-left.html)

[left2 example](/demo/example-uni-left.html)

Modifier class `vclTabRight`.

[right1 example](/demo/example-right.html)

[right2 example](/demo/example-uni-right.html)

Justified tabs can be achieved using the appropriate layout attributes.

[uni example](/demo/example-uni-justified.html)

## Classes

- `vclTabbable`: Wrapper of tab bar and tab content area.
- `vclTabs`: Tab bar.
- `vclTab`: Tab.
- `vclTabLabel`: Optional class for the label(s) inside the tab.
- `vclTabContent`: Optional content area.
- `vclTabPanel`: Optional inner content area.

## Modifiers

### For `vclTabbable`

- `vclTabsLeft`
- `vclTabsRight`
- `vclTabsBottom`
- `vclNoBorder`: remove any border from `vclTabContent` and `vclTabs`.

### For `vclTabs`

- `vclTabStyleUni`
- `vclTabNavJustified`

### For `vclTab`

- `vclSelected`
- `vclDisabled`

## Variables

### Normal Variant

- `--tab-nav-border-color`
- `--tab-nav-tab-bg-color`
- `--tab-nav-tab-bg-hover-color`
- `--tab-nav-tab-bg-selected-color`
- `--tab-nav-tab-bg-disabled-color`
- `--tab-nav-tab-border-selected-color`
- `--tab-nav-tab-disabled-color`
- `--tab-nav-tab-color`
- `--tab-nav-tab-selected-color`
- `--tab-nav-tab-hover-color`
- `--tab-nav-tab-button-label-color`
- `--tab-nav-tab-button-label-hover-color`
- `--tab-nav-tab-button-selected-label-color`

### Uni Variant

- `--tab-nav-tab-bg-color--uni`
- `--tab-nav-tab-bg-selected-color--uni`
- `--tab-nav-tab-bg-disabled-color--uni`
- `--tab-nav-tab-color--uni`
- `--tab-nav-tab-hover-color--uni`
- `--tab-nav-tab-color-selected--uni`
- `--tab-nav-tab-disabled-color--uni`

## Demo

[example.html](/demo/example.html) on GH-pages.


text:
package cmd

import (
	"errors"
	"fmt"

	"github.com/spf13/cobra"
)

// updateCmd represents the update command
var updateCmd = &cobra.Command{
	Use:           "update environment",
	Short:         "Update an environment",
	Long:          ``,
	SilenceErrors: true,
	SilenceUsage:  true,
	RunE: func(cmd *cobra.Command, args []string) error {
		// abort if number of arguments is incorrect with an apropriate error
		if len(args) == 0 {
			return errors.New("environment not specified")
		}
		if len(args) > 1 {
			return errors.New("extra arguments")
		}

		// parse namespace & context from environment name
		namespace, context := kubectlParseEnvironment(args[0])

		// abort early if appropriate kubectl is not available
		kubectlCheckVersion(false)

		fmt.Println("--- Updating environment \"" + namespace + "." + context + "\"")

		fmt.Println("update command not implemented")

		return nil
	},
}

func init() {
	RootCmd.AddCommand(updateCmd)
}


text:
"""
    DWX_ZMQ_Execution.py
    --
    @author: Darwinex Labs (www.darwinex.com)

    Copyright (c) 2019 onwards, Darwinex. All rights reserved.

    Licensed under the BSD 3-Clause License, you may not use this file except
    in compliance with the License.

    You may obtain a copy of the License at:
    https://opensource.org/licenses/BSD-3-Clause
"""

from pandas import to_datetime
from time import sleep

class DWX_ZMQ_Execution():

    def __init__(self, _zmq):
        self._zmq = _zmq

    ##########################################################################

    def _execute_(self,
                  _exec_dict,
                  _verbose=False,
                  _delay=0.1,
                  _wbreak=10):

        _check = ''

        # Reset thread data output
        self._zmq._set_response_(None)

        # OPEN TRADE
        if _exec_dict['_action'] == 'OPEN':

            _check = '_action'
            self._zmq._DWX_MTX_NEW_TRADE_(_order=_exec_dict)

        # CLOSE TRADE
        elif _exec_dict['_action'] == 'CLOSE':

            _check = '_response_value'
            self._zmq._DWX_MTX_CLOSE_TRADE_BY_TICKET_(_exec_dict['_ticket'])

        if _verbose:
            print('\n[{}] {} -> MetaTrader'.format(_exec_dict['_comment'],
                                                   str(_exec_dict)))

        # While loop start time reference
        _ws = to_datetime('now')

        # While data not received, sleep until timeout
        while self._zmq._valid_response_('zmq') == False:
            sleep(_delay)

            if (to_datetime('now') - _ws).total_seconds() > (_delay * _wbreak):
                break

        # If data received, return DataFrame
        if self._zmq._valid_response_('zmq'):

            if _check in self._zmq._get_response_().keys():
                return self._zmq._get_response_()

        # Default
        return None

    ##########################################################################


text:
#ifndef _LINUX_SUNRPC_XPRT_H
#define _LINUX_SUNRPC_XPRT_H

#include <linux/uio.h>
#include <linux/socket.h>
#include <linux/in.h>
#include <linux/sunrpc/sched.h>
#include <linux/sunrpc/xdr.h>

extern unsigned int xprt_udp_slot_table_entries;
extern unsigned int xprt_tcp_slot_table_entries;

#define RPC_MIN_SLOT_TABLE	(2U)
#define RPC_DEF_SLOT_TABLE	(16U)
#define RPC_MAX_SLOT_TABLE	(128U)

/*
 * RPC call and reply header size as number of 32bit words (verifier
 * size computed separately)
 */
#define RPC_CALLHDRSIZE		6
#define RPC_REPHDRSIZE		4

/*
 * Parameters for choosing a free port
 */
extern unsigned int xprt_min_resvport;
extern unsigned int xprt_max_resvport;

#define RPC_MIN_RESVPORT	(1U)
#define RPC_MAX_RESVPORT	(65535U)
#define RPC_DEF_MIN_RESVPORT	(650U)
#define RPC_DEF_MAX_RESVPORT	(1023U)

/*
 * This describes a timeout strategy
 */
struct rpc_timeout {
	unsigned long		to_initval,		/* initial timeout */
				to_maxval,		/* max timeout */
				to_increment;		/* if !exponential */
	unsigned int		to_retries;		/* max # of retries */
	unsigned char		to_exponential;
};

struct rpc_task;
struct rpc_xprt;

/*
 * This describes a complete RPC request
 */
struct rpc_rqst {
	/*
	 * This is the user-visible part
	 */
	struct rpc_xprt *	rq_xprt;		/* RPC client */
	struct xdr_buf		rq_snd_buf;		/* send buffer */
	struct xdr_buf		rq_rcv_buf;		/* recv buffer */

	/*
	 * This is the private part
	 */
	struct rpc_task *	rq_task;	/* RPC task data */
	__u32			rq_xid;		/* request XID */
	int			rq_cong;	/* has incremented xprt->cong */
	int			rq_received;	/* receive completed */
	u32			rq_seqno;	/* gss seq no. used on req. */
	int			rq_enc_pages_num;
	struct page		**rq_enc_pages;	/* scratch pages for use by
						   gss privacy code */
	void (*rq_release_snd_buf)(struct rpc_rqst *); /* release rq_enc_pages */
	struct list_head	rq_list;

	__u32 *			rq_buffer;	/* XDR encode buffer */
	size_t			rq_bufsize;

	struct xdr_buf		rq_private_buf;		/* The receive buffer
							 * used in the softirq.
							 */
	unsigned long		rq_majortimeo;	/* major timeout alarm */
	unsigned long		rq_timeout;	/* Current timeout value */
	unsigned int		rq_retries;	/* # of retries */

	/*
	 * Partial send handling
	 */
	u32			rq_bytes_sent;	/* Bytes we have sent */

	unsigned long		rq_xtime;	/* when transmitted */
	int			rq_ntrans;
};
#define rq_svec			rq_snd_buf.head
#define rq_slen			rq_snd_buf.len

struct rpc_xprt_ops {
	void		(*set_buffer_size)(struct rpc_xprt *xprt, size_t sndsize, size_t rcvsize);
	int		(*reserve_xprt)(struct rpc_task *task);
	void		(*release_xprt)(struct rpc_xprt *xprt, struct rpc_task *task);
	void		(*set_port)(struct rpc_xprt *xprt, unsigned short port);
	void		(*connect)(struct rpc_task *task);
	void *		(*buf_alloc)(struct rpc_task *task, size_t size);
	void		(*buf_free)(struct rpc_task *task);
	int		(*send_request)(struct rpc_task *task);
	void		(*set_retrans_timeout)(struct rpc_task *task);
	void		(*timer)(struct rpc_task *task);
	void		(*release_request)(struct rpc_task *task);
	void		(*close)(struct rpc_xprt *xprt);
	void		(*destroy)(struct rpc_xprt *xprt);
};

struct rpc_xprt {
	struct rpc_xprt_ops *	ops;		/* transport methods */
	struct socket *		sock;		/* BSD socket layer */
	struct sock *		inet;		/* INET layer */

	struct rpc_timeout	timeout;	/* timeout parms */
	struct sockaddr_in	addr;		/* server address */
	int			prot;		/* IP protocol */

	unsigned long		cong;		/* current congestion */
	unsigned long		cwnd;		/* congestion window */

	size_t			rcvsize,	/* transport rcv buffer size */
				sndsize;	/* transport send buffer size */

	size_t			max_payload;	/* largest RPC payload size,
						   in bytes */
	unsigned int		tsh_size;	/* size of transport specific
						   header */

	struct rpc_wait_queue	sending;	/* requests waiting to send */
	struct rpc_wait_queue	resend;		/* requests waiting to resend */
	struct rpc_wait_queue	pending;	/* requests in flight */
	struct rpc_wait_queue	backlog;	/* waiting for slot */
	struct list_head	free;		/* free slots */
	struct rpc_rqst *	slot;		/* slot table storage */
	unsigned int		max_reqs;	/* total slots */
	unsigned long		state;		/* transport state */
	unsigned char		shutdown   : 1,	/* being shut down */
				resvport   : 1; /* use a reserved port */

	/*
	 * XID
	 */
	__u32			xid;		/* Next XID value to use */

	/*
	 * State of TCP reply receive stuff
	 */
	u32			tcp_recm,	/* Fragment header */
				tcp_xid,	/* Current XID */
				tcp_reclen,	/* fragment length */
				tcp_offset;	/* fragment offset */
	unsigned long		tcp_copied,	/* copied to request */
				tcp_flags;
	/*
	 * Connection of transports
	 */
	unsigned long		connect_timeout,
				bind_timeout,
				reestablish_timeout;
	struct work_struct	connect_worker;
	unsigned short		port;

	/*
	 * Disconnection of idle transports
	 */
	struct work_struct	task_cleanup;
	struct timer_list	timer;
	unsigned long		last_used,
				idle_timeout;

	/*
	 * Send stuff
	 */
	spinlock_t		transport_lock;	/* lock transport info */
	spinlock_t		reserve_lock;	/* lock slot table */
	struct rpc_task *	snd_task;	/* Task blocked in send */

	struct list_head	recv;

	void			(*old_data_ready)(struct sock *, int);
	void			(*old_state_change)(struct sock *);
	void			(*old_write_space)(struct sock *);
};

#define XPRT_LAST_FRAG		(1 << 0)
#define XPRT_COPY_RECM		(1 << 1)
#define XPRT_COPY_XID		(1 << 2)
#define XPRT_COPY_DATA		(1 << 3)

#ifdef __KERNEL__

/*
 * Transport operations used by ULPs
 */
struct rpc_xprt *	xprt_create_proto(int proto, struct sockaddr_in *addr, struct rpc_timeout *to);
void			xprt_set_timeout(struct rpc_timeout *to, unsigned int retr, unsigned long incr);

/*
 * Generic internal transport functions
 */
void			xprt_connect(struct rpc_task *task);
void			xprt_reserve(struct rpc_task *task);
int			xprt_reserve_xprt(struct rpc_task *task);
int			xprt_reserve_xprt_cong(struct rpc_task *task);
int			xprt_prepare_transmit(struct rpc_task *task);
void			xprt_transmit(struct rpc_task *task);
void			xprt_abort_transmit(struct rpc_task *task);
int			xprt_adjust_timeout(struct rpc_rqst *req);
void			xprt_release_xprt(struct rpc_xprt *xprt, struct rpc_task *task);
void			xprt_release_xprt_cong(struct rpc_xprt *xprt, struct rpc_task *task);
void			xprt_release(struct rpc_task *task);
int			xprt_destroy(struct rpc_xprt *xprt);

static inline u32 *xprt_skip_transport_header(struct rpc_xprt *xprt, u32 *p)
{
	return p + xprt->tsh_size;
}

/*
 * Transport switch helper functions
 */
void			xprt_set_retrans_timeout_def(struct rpc_task *task);
void			xprt_set_retrans_timeout_rtt(struct rpc_task *task);
void			xprt_wake_pending_tasks(struct rpc_xprt *xprt, int status);
void			xprt_wait_for_buffer_space(struct rpc_task *task);
void			xprt_write_space(struct rpc_xprt *xprt);
void			xprt_update_rtt(struct rpc_task *task);
void			xprt_adjust_cwnd(struct rpc_task *task, int result);
struct rpc_rqst *	xprt_lookup_rqst(struct rpc_xprt *xprt, u32 xid);
void			xprt_complete_rqst(struct rpc_task *task, int copied);
void			xprt_release_rqst_cong(struct rpc_task *task);
void			xprt_disconnect(struct rpc_xprt *xprt);

/*
 * Socket transport setup operations
 */
int			xs_setup_udp(struct rpc_xprt *xprt, struct rpc_timeout *to);
int			xs_setup_tcp(struct rpc_xprt *xprt, struct rpc_timeout *to);

/*
 * Reserved bit positions in xprt->state
 */
#define XPRT_LOCKED		(0)
#define XPRT_CONNECTED		(1)
#define XPRT_CONNECTING		(2)
#define XPRT_CLOSE_WAIT		(3)

static inline void xprt_set_connected(struct rpc_xprt *xprt)
{
	set_bit(XPRT_CONNECTED, &xprt->state);
}

static inline void xprt_clear_connected(struct rpc_xprt *xprt)
{
	clear_bit(XPRT_CONNECTED, &xprt->state);
}

static inline int xprt_connected(struct rpc_xprt *xprt)
{
	return test_bit(XPRT_CONNECTED, &xprt->state);
}

static inline int xprt_test_and_set_connected(struct rpc_xprt *xprt)
{
	return test_and_set_bit(XPRT_CONNECTED, &xprt->state);
}

static inline int xprt_test_and_clear_connected(struct rpc_xprt *xprt)
{
	return test_and_clear_bit(XPRT_CONNECTED, &xprt->state);
}

static inline void xprt_clear_connecting(struct rpc_xprt *xprt)
{
	smp_mb__before_clear_bit();
	clear_bit(XPRT_CONNECTING, &xprt->state);
	smp_mb__after_clear_bit();
}

static inline int xprt_connecting(struct rpc_xprt *xprt)
{
	return test_bit(XPRT_CONNECTING, &xprt->state);
}

static inline int xprt_test_and_set_connecting(struct rpc_xprt *xprt)
{
	return test_and_set_bit(XPRT_CONNECTING, &xprt->state);
}

#endif /* __KERNEL__*/

#endif /* _LINUX_SUNRPC_XPRT_H */


text:
/*
  @test %I% %E%
  @bug 6315717
  @summary verifies that robot could accept extra buttons
  @author Andrei Dmitriev : area=awt.mouse
  @library ../../regtesthelpers
  @build Util
  @run main RobotExtraButton
 */

import java.awt.*;
import java.awt.event.*;
import test.java.awt.regtesthelpers.Util;

public class RobotExtraButton extends Frame {
    static Robot robot;
    public static void main(String []s){
        RobotExtraButton frame = new RobotExtraButton();
        frame.setSize(300, 300);
        frame.setVisible(true);
        frame.addMouseListener(new MouseAdapter() {
                public void mousePressed(MouseEvent e) {
                    System.out.println("PRESSED "+e);
                }
                public void mouseReleased(MouseEvent e) {
                    System.out.println("RELEASED "+e);
                }
                public void mouseClicked(MouseEvent e) {
                    System.out.println("CLICKED "+e);
                }
            });
        Util.waitForIdle(robot);
        int [] buttonMask = new int[MouseInfo.getNumberOfButtons()]; // = InputEvent.getButtonDownMasks();
        for (int i = 0; i < MouseInfo.getNumberOfButtons(); i++){
            buttonMask[i] = InputEvent.getMaskForButton(i+1);
            System.out.println("TEST: "+buttonMask[i]);
        }

        try {
            robot = new Robot();
            robot.mouseMove(frame.getLocationOnScreen().x + frame.getWidth()/2, frame.getLocationOnScreen().y + frame.getHeight()/2);
            /*
            if (MouseInfo.getNumberOfButtons() <= 3) {
                System.out.println("Number Of Buttons = "+ MouseInfo.getNumberOfButtons() +". Finish!");
                return;
                }*/

            System.out.println("TEST: press 1");
            robot.mousePress(InputEvent.BUTTON1_MASK);
            robot.delay(50);
            robot.mouseRelease(InputEvent.BUTTON1_MASK);
            Util.waitForIdle(robot);

            System.out.println("TEST: press 2");

            robot.mousePress(InputEvent.BUTTON2_MASK);
            robot.delay(50);
            robot.mouseRelease(InputEvent.BUTTON2_MASK);
            Util.waitForIdle(robot);
            System.out.println("TEST: press 3");

            robot.mousePress(InputEvent.BUTTON3_MASK);
            robot.delay(50);
            robot.mouseRelease(InputEvent.BUTTON3_MASK);
            Util.waitForIdle(robot);
            System.out.println("--------------------------------------------------");
            for (int i = 0; i < buttonMask.length; i++){
                System.out.println("button would = " +i + " : value = " +buttonMask[i]);
                robot.mousePress(buttonMask[i]);
                robot.delay(50);
                robot.mouseRelease(buttonMask[i]);
                Util.waitForIdle(robot);
            }
        } catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("Test failed.", e);
        }
    }
}


text:
#include <aws/kinesisanalytics/model/UpdateApplicationRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::KinesisAnalytics::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

UpdateApplicationRequest::UpdateApplicationRequest() :
    m_applicationNameHasBeenSet(false),
    m_currentApplicationVersionId(0),
    m_currentApplicationVersionIdHasBeenSet(false),
    m_applicationUpdateHasBeenSet(false)
{
}

Aws::String UpdateApplicationRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_applicationNameHasBeenSet)
  {
   payload.WithString("ApplicationName", m_applicationName);

  }

  if(m_currentApplicationVersionIdHasBeenSet)
  {
   payload.WithInt64("CurrentApplicationVersionId", m_currentApplicationVersionId);

  }

  if(m_applicationUpdateHasBeenSet)
  {
   payload.WithObject("ApplicationUpdate", m_applicationUpdate.Jsonize());

  }

  return payload.View().WriteReadable();
}

Aws::Http::HeaderValueCollection UpdateApplicationRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "KinesisAnalytics_20150814.UpdateApplication"));
  return headers;

}


text:
;(function() {

var $ = document.querySelectorAll.bind(document)

// --- DOM elements ---------------------------------------

var $display = $('#display')[0]
var $diskSlot = $('#slot')[0]
var $powerSwitch = $('#power-switch')[0]
var $recordsScript = $('#records')[0]
var $groveWorkerScript = $('#grove-worker')[0]
var $modalOverlay = $('#overlay')[0]
var $hideDataLoaderButton = $('#load-data-modal .close-button button')[0]
var $showDataLoaderButton = $('#load-data-button')[0]
var $recordNameInput = $('#load-data-modal .data-record-selector input')[0]
var $recordContentInput = $('#load-data-modal textarea')[0]
var $dataEditorSaveButton = $('#load-data-modal .save')[0]
var $title = $('head title')[0]

// --- Initial state --------------------------------------

var dataRecords = RECORDS
var lastSaveTimestamp = +(new Date())
var urlToOpen = null
var contentToDisplayInNewWindow = null
var groveWorker = null

setTitleTo(getComputerName(dataRecords))

togglePower()

// --- Event handler setup --------------------------------

click($diskSlot, function() {
  $recordsScript.textContent
    = 'var RECORDS = ' + JSON.stringify(dataRecords)

  var now = new Date()
  var pageData = document.documentElement.outerHTML
  var blob = new Blob([pageData], {type: 'text/html'})
  var computerName = getComputerName(dataRecords)
  saveAs(blob, QuineFilename(computerName, now))
  lastSaveTimestamp = +now
})

click($showDataLoaderButton, function() {
  $modalOverlay.style.display = 'block';
  $recordNameInput.focus()
})

click($hideDataLoaderButton, function() {
  $modalOverlay.style.display = 'none';
})

click($dataEditorSaveButton, function() {
  var name    = $recordNameInput.value
  var content = $recordContentInput.value

  if (!name) return

  dataRecords[name] = content

  groveWorker.postMessage({
    type: 'updateDataRecord',
    name: name,
    content: content
  })
})

click($powerSwitch, togglePower)

window.addEventListener('beforeunload', function(e) {
  if (shouldWarnAboutUnsavedChanges()) {
    // This message isn't shown in Chrome but it might be in other browsers.
    return e.returnValue = "You have unsaved changes. Are you sure you want to leave?"
  }
})

window.addEventListener('keydown', function(e) {
  if (groveCanReceiveKeyEvents()) {
    e.preventDefault()
    groveWorker.postMessage({type: 'keyDown', event: {keyCode: e.keyCode}})

    setTimeout(function() {
      if (urlToOpen) {
        window.open(urlToOpen, '_blank')
      }
      urlToOpen = null

      if (contentToDisplayInNewWindow) {
        var newWindow = window.open('', '_blank')
        newWindow.document.open()
        newWindow.document.write(contentToDisplayInNewWindow)
        newWindow.document.close()
      }
      contentToDisplayInNewWindow = null
    }, 250)
  }
})

window.addEventListener('keyup', function(e) {
  if (groveCanReceiveKeyEvents()) {
    e.preventDefault()
    groveWorker.postMessage({type: 'keyUp', event: {keyCode: e.keyCode}})
  }
})

// --- Function definitions -------------------------------

function togglePower () {
  urlToOpen = null
  contentToDisplayInNewWindow = null
  if (groveWorker) {
    // turn off
    groveWorker.terminate()
    groveWorker = null
    $display.setAttribute('class', '')
    redraw([], true)
  } else {
    // turn on
    $display.setAttribute('class', 'power-on')
    groveWorker = GroveWorker(
      dataRecords,
      handleMessageFromWorker)
  }
}

function handleMessageFromWorker(msg) {
  switch (msg.data.type) {
    case 'redraw':
      redraw(msg.data.value)
      break
    case 'dataRecordChange':
      dataRecords[msg.data.name] = msg.data.content
      setTitleTo(getComputerName(dataRecords))
      break
    case 'openUrl':
      urlToOpen = urlToOpen || msg.data.url
      break
    case 'displayInNewWindow':
      contentToDisplayInNewWindow
        = contentToDisplayInNewWindow || msg.data.content
  }
}

function GroveWorker(dataRecords, messageCallback) {
  var scriptBlob = new Blob([
    'var RECORDS = ',
    JSON.stringify(dataRecords),
    ';',
    $groveWorkerScript.textContent
  ])

  var worker = new Worker(URL.createObjectURL(scriptBlob))
  worker.addEventListener('message', messageCallback)
  return worker
}

function click(elem, callback) {
  elem.addEventListener('click', callback)
}

function setTitleTo(title) {
  $title.textContent = title
}

var previouslyDrawn = []
var lineElements = $('#display p')
function redraw(text, force) {
  for (var i = 0; i < lineElements.length; i++) {
    var toDraw = text[i] || ''
    if (force || toDraw !== previouslyDrawn[i]) {
      lineElements[i].innerText = toDraw
      previouslyDrawn[i] = toDraw
    }
  }
}

function groveCanReceiveKeyEvents() {
  return groveWorker
    && $modalOverlay.style.display !== 'block'
    // if the modal is shown, don't let the Grove handle
    // key events since the user probably wants to type
    // in the form fields.
}

function createFilename(computerName) {
  var date = new Date()
  return computerName + '-' + formatDateForFilename(date)
}

function shouldWarnAboutUnsavedChanges() {
  return isNavigationWarningEnabled() && userHasntSavedInAWhile()
}

function userHasntSavedInAWhile() {
  return +(new Date()) - lastSaveTimestamp > 30 * 1000
}

function isNavigationWarningEnabled() {
  return !dataRecords['doNotWarnAboutUnsavedChanges']
}

})();


text: Just Docker images that I use


text:
using Fineness.Framework.Interfaces;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

public class LerpTimeManager : IDispose {

    private Dictionary<string, LerpTime> mLerpTimes;
    private List<string> mNames;

    public LerpTimeManager()
    {
        mNames = new List<string>();
        mLerpTimes = new Dictionary<string, LerpTime>();
    }

    public void Clean()
    {
        var max = mNames.Count;
        for (var i = 0; i < max; i++)
        {
            mLerpTimes[mNames[i]].Enabled = false;
        }
        mLerpTimes.Clear();
    }

    public void Dispose()
    {
        Clean();
        mLerpTimes = null;
    }

    public LerpTime GetLerpTime(string name, float time = 0, bool enableInStart = true)
    {
        if (!mLerpTimes.ContainsKey(name))
        {
            mLerpTimes[name] = new LerpTime(time, enableInStart);
            mNames.Add(name);
        }
        if (time != 0)
            mLerpTimes[name].SetTotalTime(time);
        return mLerpTimes[name];
    }
}


text:
<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.promotree</groupId>
    <artifactId>promotree</artifactId>
    <version>1.0-SNAPSHOT</version>
  </parent>
  <groupId>com.promotree</groupId>
  <artifactId>restful-webservices</artifactId>
  <version>1.0-SNAPSHOT</version>
  <name>restful-webservices</name>
  <properties>
    <jersey.version>2.6</jersey.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.glassfish.jersey</groupId>
        <artifactId>jersey-bom</artifactId>
        <version>${jersey.version}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>org.glassfish.jersey.containers</groupId>
      <artifactId>jersey-container-grizzly2-http</artifactId>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.9</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.5.1</version>
        <inherited>true</inherited>
        <configuration>
          <source>1.6</source>
          <target>1.6</target>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
        <version>1.2.1</version>
        <executions>
          <execution>
            <goals>
              <goal>java</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <mainClass>com.promotree.Main</mainClass>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>


text:
#include "tensorflow/core/kernels/cwise_ops_common.h"

namespace tensorflow {
REGISTER5(UnaryOp, CPU, "Inv", functor::inverse, float, Eigen::half, double,
          complex64, complex128);
#if GOOGLE_CUDA
REGISTER4(UnaryOp, GPU, "Inv", functor::inverse, float, Eigen::half, double,
          int64);
#endif

REGISTER5(SimpleBinaryOp, CPU, "InvGrad", functor::inverse_grad, float,
          Eigen::half, double, complex64, complex128);
#if GOOGLE_CUDA
REGISTER3(SimpleBinaryOp, GPU, "InvGrad", functor::inverse_grad, float,
          Eigen::half, double);
#endif

REGISTER5(UnaryOp, CPU, "Reciprocal", functor::inverse, float, Eigen::half,
          double, complex64, complex128);
#if GOOGLE_CUDA
REGISTER4(UnaryOp, GPU, "Reciprocal", functor::inverse, float, Eigen::half,
          double, int64);
#endif
#ifdef TENSORFLOW_USE_SYCL
REGISTER(UnaryOp, SYCL, "Reciprocal", functor::inverse, float);
#endif // TENSORFLOW_USE_SYCL

REGISTER5(SimpleBinaryOp, CPU, "ReciprocalGrad", functor::inverse_grad, float,
          Eigen::half, double, complex64, complex128);
#if GOOGLE_CUDA
REGISTER3(SimpleBinaryOp, GPU, "ReciprocalGrad", functor::inverse_grad, float,
          Eigen::half, double);
#endif
#ifdef TENSORFLOW_USE_SYCL
REGISTER(SimpleBinaryOp, SYCL, "ReciprocalGrad", functor::inverse_grad, float);
#endif // TENSORFLOW_USE_SYCL
}  // namespace tensorflow