text:
package org.apache.fontbox.ttf;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.fontbox.ttf.gsub.GlyphSubstitutionDataExtractor;
import org.apache.fontbox.ttf.model.GsubData;
import org.apache.fontbox.ttf.table.common.CoverageTable;
import org.apache.fontbox.ttf.table.common.CoverageTableFormat1;
import org.apache.fontbox.ttf.table.common.CoverageTableFormat2;
import org.apache.fontbox.ttf.table.common.FeatureListTable;
import org.apache.fontbox.ttf.table.common.FeatureRecord;
import org.apache.fontbox.ttf.table.common.FeatureTable;
import org.apache.fontbox.ttf.table.common.LangSysRecord;
import org.apache.fontbox.ttf.table.common.LangSysTable;
import org.apache.fontbox.ttf.table.common.LookupListTable;
import org.apache.fontbox.ttf.table.common.LookupSubTable;
import org.apache.fontbox.ttf.table.common.LookupTable;
import org.apache.fontbox.ttf.table.common.RangeRecord;
import org.apache.fontbox.ttf.table.common.ScriptRecord;
import org.apache.fontbox.ttf.table.common.ScriptTable;
import org.apache.fontbox.ttf.table.gsub.LigatureSetTable;
import org.apache.fontbox.ttf.table.gsub.LigatureTable;
import org.apache.fontbox.ttf.table.gsub.LookupTypeLigatureSubstitutionSubstFormat1;
import org.apache.fontbox.ttf.table.gsub.LookupTypeSingleSubstFormat1;
import org.apache.fontbox.ttf.table.gsub.LookupTypeSingleSubstFormat2;

/**
 * A glyph substitution 'GSUB' table in a TrueType or OpenType font.
 *
 * @author Aaron Madlon-Kay
 */
public class GlyphSubstitutionTable extends TTFTable
{
    private static final Log LOG = LogFactory.getLog(GlyphSubstitutionTable.class);

    public static final String TAG = "GSUB";

    private Map<String, ScriptTable> scriptList;
    // featureList and lookupList are not maps because we need to index into them
    private FeatureListTable featureListTable;
    private LookupListTable lookupListTable;

    private final Map<Integer, Integer> lookupCache = new HashMap<>();
    private final Map<Integer, Integer> reverseLookup = new HashMap<>();

    private String lastUsedSupportedScript;

    private GsubData gsubData;

    GlyphSubstitutionTable()
    {
        super();
    }

    @Override
    @SuppressWarnings({"squid:S1854"})
    void read(TrueTypeFont ttf, TTFDataStream data) throws IOException
    {
        long start = data.getCurrentPosition();
        @SuppressWarnings({"unused"})
        int majorVersion = data.readUnsignedShort();
        int minorVersion = data.readUnsignedShort();
        int scriptListOffset = data.readUnsignedShort();
        int featureListOffset = data.readUnsignedShort();
        int lookupListOffset = data.readUnsignedShort();
        @SuppressWarnings({"unused"})
        long featureVariationsOffset = -1L;
        if (minorVersion == 1L)
        {
            featureVariationsOffset = data.readUnsignedInt();
        }

        scriptList = readScriptList(data, start + scriptListOffset);
        featureListTable = readFeatureList(data, start + featureListOffset);
        lookupListTable = readLookupList(data, start + lookupListOffset);

        GlyphSubstitutionDataExtractor glyphSubstitutionDataExtractor = new GlyphSubstitutionDataExtractor();

        gsubData = glyphSubstitutionDataExtractor
                .getGsubData(scriptList, featureListTable, lookupListTable);
    }

    private Map<String, ScriptTable> readScriptList(TTFDataStream data, long offset)
            throws IOException
    {
        data.seek(offset);
        int scriptCount = data.readUnsignedShort();
        ScriptTable[] scriptTables= new ScriptTable[scriptCount];
        int[] scriptOffsets = new int[scriptCount];
        String[] scriptTags = new String[scriptCount];
        for (int i = 0; i < scriptCount; i++)
        {
            scriptTags[i] = data.readString(4);
            scriptOffsets[i] = data.readUnsignedShort();
        }
        for (int i = 0; i < scriptCount; i++)
        {
            scriptTables[i] = readScriptTable(data, offset + scriptOffsets[i]);
        }
        Map<String, ScriptTable> resultScriptList = new LinkedHashMap<>(scriptCount);
        for (int i = 0; i < scriptCount; i++)
        {
            ScriptRecord scriptRecord = new ScriptRecord(scriptTags[i], scriptTables[i]);
            resultScriptList.put(scriptRecord.getScriptTag(), scriptRecord.getScriptTable());
        }
        return Collections.unmodifiableMap(resultScriptList);
    }

    private ScriptTable readScriptTable(TTFDataStream data, long offset) throws IOException
    {
        data.seek(offset);
        int defaultLangSys = data.readUnsignedShort();
        int langSysCount = data.readUnsignedShort();
        LangSysRecord[] langSysRecords = new LangSysRecord[langSysCount];
        String[] langSysTags = new String[langSysCount];
        int[] langSysOffsets = new int[langSysCount];
        for (int i = 0; i < langSysCount; i++)
        {
            langSysTags[i] = data.readString(4);
            if (i > 0 && langSysTags[i].compareTo(langSysTags[i-1]) <= 0)
            {
                // PDFBOX-4489: catch corrupt file
                // https://docs.microsoft.com/en-us/typography/opentype/spec/chapter2#slTbl_sRec
                LOG.error("LangSysRecords not alphabetically sorted by LangSys tag: " +
                          langSysTags[i] + " <= " + langSysTags[i - 1]);
                return new ScriptTable(null, new LinkedHashMap<>());
            }
            langSysOffsets[i] = data.readUnsignedShort();
        }

        LangSysTable defaultLangSysTable = null;

        if (defaultLangSys != 0)
        {
            defaultLangSysTable = readLangSysTable(data, offset + defaultLangSys);
        }
        for (int i = 0; i < langSysCount; i++)
        {
            LangSysTable langSysTable = readLangSysTable(data, offset + langSysOffsets[i]);
            langSysRecords[i] = new LangSysRecord(langSysTags[i], langSysTable);
        }
        Map<String, LangSysTable> langSysTables = new LinkedHashMap<>(langSysCount);
        for (LangSysRecord langSysRecord : langSysRecords)
        {
            langSysTables.put(langSysRecord.getLangSysTag(),
                    langSysRecord.getLangSysTable());
        }
        return new ScriptTable(defaultLangSysTable, Collections.unmodifiableMap(langSysTables));
    }

    private LangSysTable readLangSysTable(TTFDataStream data, long offset) throws IOException
    {
        data.seek(offset);
        int lookupOrder = data.readUnsignedShort();
        int requiredFeatureIndex = data.readUnsignedShort();
        int featureIndexCount = data.readUnsignedShort();
        int[] featureIndices = new int[featureIndexCount];
        for (int i = 0; i < featureIndexCount; i++)
        {
            featureIndices[i] = data.readUnsignedShort();
        }
        return new LangSysTable(lookupOrder, requiredFeatureIndex, featureIndexCount,
                featureIndices);
    }

    private FeatureListTable readFeatureList(TTFDataStream data, long offset) throws IOException
    {
        data.seek(offset);
        int featureCount = data.readUnsignedShort();
        FeatureRecord[] featureRecords = new FeatureRecord[featureCount];
        int[] featureOffsets = new int[featureCount];
        String[] featureTags = new String[featureCount];
        for (int i = 0; i < featureCount; i++)
        {
            featureTags[i] = data.readString(4);
            if (i > 0 && featureTags[i].compareTo(featureTags[i-1]) < 0)
            {
                // catch corrupt file
                // https://docs.microsoft.com/en-us/typography/opentype/spec/chapter2#flTbl
                if (featureTags[i].matches("\\w{4}") && featureTags[i-1].matches("\\w{4}"))
                {
                    // ArialUni.ttf has many warnings but isn't corrupt, so we assume that only
                    // strings with trash characters indicate real corruption
                    LOG.debug("FeatureRecord array not alphabetically sorted by FeatureTag: " +
                              featureTags[i] + " < " + featureTags[i - 1]);
                }
                else
                {
                    LOG.warn("FeatureRecord array not alphabetically sorted by FeatureTag: " +
                              featureTags[i] + " < " + featureTags[i - 1]);
                    return new FeatureListTable(0, new FeatureRecord[0]);
                }
            }
            featureOffsets[i] = data.readUnsignedShort();
        }
        for (int i = 0; i < featureCount; i++)
        {
            FeatureTable featureTable = readFeatureTable(data, offset + featureOffsets[i]);
            featureRecords[i] = new FeatureRecord(featureTags[i], featureTable);
        }
        return new FeatureListTable(featureCount, featureRecords);
    }

    private FeatureTable readFeatureTable(TTFDataStream data, long offset) throws IOException
    {
        data.seek(offset);
        int featureParams = data.readUnsignedShort();
        int lookupIndexCount = data.readUnsignedShort();
        int[] lookupListIndices = new int[lookupIndexCount];
        for (int i = 0; i < lookupIndexCount; i++)
        {
            lookupListIndices[i] = data.readUnsignedShort();
        }
        return new FeatureTable(featureParams, lookupIndexCount, lookupListIndices);
    }

    private LookupListTable readLookupList(TTFDataStream data, long offset) throws IOException
    {
        data.seek(offset);
        int lookupCount = data.readUnsignedShort();
        int[] lookups = new int[lookupCount];
        for (int i = 0; i < lookupCount; i++)
        {
            lookups[i] = data.readUnsignedShort();
        }
        LookupTable[] lookupTables = new LookupTable[lookupCount];
        for (int i = 0; i < lookupCount; i++)
        {
            lookupTables[i] = readLookupTable(data, offset + lookups[i]);
        }
        return new LookupListTable(lookupCount, lookupTables);
    }

    private LookupTable readLookupTable(TTFDataStream data, long offset) throws IOException
    {
        data.seek(offset);
        int lookupType = data.readUnsignedShort();
        int lookupFlag = data.readUnsignedShort();
        int subTableCount = data.readUnsignedShort();
        int[] subTableOffsets = new int[subTableCount];
        for (int i = 0; i < subTableCount; i++)
        {
            subTableOffsets[i] = data.readUnsignedShort();
        }

        int markFilteringSet;
        if ((lookupFlag & 0x0010) != 0)
        {
            markFilteringSet = data.readUnsignedShort();
        }
        else
        {
            markFilteringSet = 0;
        }
        LookupSubTable[] subTables = new LookupSubTable[subTableCount];
        switch (lookupType)
        {
        case 1:
            // Single
            // https://docs.microsoft.com/en-us/typography/opentype/spec/gsub#SS
            for (int i = 0; i < subTableCount; i++)
            {
                subTables[i] = readLookupSubTable(data, offset + subTableOffsets[i]);
            }
            break;
        case 4:
            // Ligature Substitution Subtable
            // https://docs.microsoft.com/en-us/typography/opentype/spec/gsub#LS
            for (int i = 0; i < subTableCount; i++)
            {
                subTables[i] = readLigatureSubstitutionSubtable(data, offset + subTableOffsets[i]);
            }
            break;
        default:
            // Other lookup types are not supported
            LOG.debug("Type " + lookupType
                    + " GSUB lookup table is not supported and will be ignored");
        }
        return new LookupTable(lookupType, lookupFlag, markFilteringSet, subTables);
    }

    private LookupSubTable readLookupSubTable(TTFDataStream data, long offset) throws IOException
    {
        data.seek(offset);
        int substFormat = data.readUnsignedShort();
        switch (substFormat)
        {
        case 1:
        {
            // LookupType 1: Single Substitution Subtable
            // https://docs.microsoft.com/en-us/typography/opentype/spec/gsub#11-single-substitution-format-1
            int coverageOffset = data.readUnsignedShort();
            short deltaGlyphID = data.readSignedShort();
            CoverageTable coverageTable = readCoverageTable(data, offset + coverageOffset);
            return new LookupTypeSingleSubstFormat1(substFormat, coverageTable, deltaGlyphID);
        }
        case 2:
        {
            // Single Substitution Format 2
            // https://docs.microsoft.com/en-us/typography/opentype/spec/gsub#12-single-substitution-format-2
            int coverageOffset = data.readUnsignedShort();
            int glyphCount = data.readUnsignedShort();
            int[] substituteGlyphIDs = new int[glyphCount];
            for (int i = 0; i < glyphCount; i++)
            {
                substituteGlyphIDs[i] = data.readUnsignedShort();
            }
            CoverageTable coverageTable = readCoverageTable(data, offset + coverageOffset);
            return new LookupTypeSingleSubstFormat2(substFormat, coverageTable, substituteGlyphIDs);
        }
        default:
            throw new IOException("Unknown substFormat: " + substFormat);
        }
    }

    private LookupSubTable readLigatureSubstitutionSubtable(TTFDataStream data, long offset)
            throws IOException
    {
        data.seek(offset);
        int substFormat = data.readUnsignedShort();

        if (substFormat != 1)
        {
            throw new IOException(
                    "The expected SubstFormat for LigatureSubstitutionTable is 1");
        }

        int coverage = data.readUnsignedShort();
        int ligSetCount = data.readUnsignedShort();

        int[] ligatureOffsets = new int[ligSetCount];

        for (int i = 0; i < ligSetCount; i++)
        {
            ligatureOffsets[i] = data.readUnsignedShort();
        }

        CoverageTable coverageTable = readCoverageTable(data, offset + coverage);

        if (ligSetCount != coverageTable.getSize())
        {
            throw new IOException(
                    "According to the OpenTypeFont specifications, the coverage count should be equal to the no. of LigatureSetTables");
        }

        LigatureSetTable[] ligatureSetTables = new LigatureSetTable[ligSetCount];

        for (int i = 0; i < ligSetCount; i++)
        {

            int coverageGlyphId = coverageTable.getGlyphId(i);

            ligatureSetTables[i] = readLigatureSetTable(data,
                    offset + ligatureOffsets[i], coverageGlyphId);
        }

        return new LookupTypeLigatureSubstitutionSubstFormat1(substFormat, coverageTable,
                ligatureSetTables);
    }

    private LigatureSetTable readLigatureSetTable(TTFDataStream data, long ligatureSetTableLocation,
            int coverageGlyphId) throws IOException
    {
        data.seek(ligatureSetTableLocation);

        int ligatureCount = data.readUnsignedShort();
        LOG.debug("ligatureCount=" + ligatureCount);

        int[] ligatureOffsets = new int[ligatureCount];
        LigatureTable[] ligatureTables = new LigatureTable[ligatureCount];

        for (int i = 0; i < ligatureOffsets.length; i++)
        {
            ligatureOffsets[i] = data.readUnsignedShort();
        }

        for (int i = 0; i < ligatureOffsets.length; i++)
        {
            int ligatureOffset = ligatureOffsets[i];
            ligatureTables[i] = readLigatureTable(data,
                    ligatureSetTableLocation + ligatureOffset, coverageGlyphId);
        }

        return new LigatureSetTable(ligatureCount, ligatureTables);
    }

    private LigatureTable readLigatureTable(TTFDataStream data, long ligatureTableLocation,
            int coverageGlyphId) throws IOException
    {
        data.seek(ligatureTableLocation);

        int ligatureGlyph = data.readUnsignedShort();

        int componentCount = data.readUnsignedShort();

        int[] componentGlyphIDs = new int[componentCount];

        if (componentCount > 0)
        {
            componentGlyphIDs[0] = coverageGlyphId;
        }

        for (int i = 1; i <= componentCount - 1; i++)
        {
            componentGlyphIDs[i] = data.readUnsignedShort();
        }

        return new LigatureTable(ligatureGlyph, componentCount, componentGlyphIDs);

    }

    private CoverageTable readCoverageTable(TTFDataStream data, long offset) throws IOException
    {
        data.seek(offset);
        int coverageFormat = data.readUnsignedShort();
        switch (coverageFormat)
        {
        case 1:
        {
            int glyphCount = data.readUnsignedShort();
            int[] glyphArray = new int[glyphCount];
            for (int i = 0; i < glyphCount; i++)
            {
                glyphArray[i] = data.readUnsignedShort();
            }
            return new CoverageTableFormat1(coverageFormat, glyphArray);
        }
        case 2:
        {
            int rangeCount = data.readUnsignedShort();
            RangeRecord[] rangeRecords = new RangeRecord[rangeCount];

            for (int i = 0; i < rangeCount; i++)
            {
                rangeRecords[i] = readRangeRecord(data);
            }

            return new CoverageTableFormat2(coverageFormat, rangeRecords);
        }
        default:
            // Should not happen (the spec indicates only format 1 and format 2)
            throw new IOException("Unknown coverage format: " + coverageFormat);
        }
    }

    /**
     * Choose from one of the supplied OpenType script tags, depending on what the font supports and potentially on
     * context.
     *
     * @param tags
     * @return The best OpenType script tag
     */
    private String selectScriptTag(String[] tags)
    {
        if (tags.length == 1)
        {
            String tag = tags[0];
            if (OpenTypeScript.INHERITED.equals(tag)
                    || (OpenTypeScript.TAG_DEFAULT.equals(tag) && !scriptList.containsKey(tag)))
            {
                // We don't know what script this should be.
                if (lastUsedSupportedScript == null)
                {
                    // We have no past context and (currently) no way to get future context so we guess.
                    lastUsedSupportedScript = scriptList.keySet().iterator().next();
                }
                // else use past context

                return lastUsedSupportedScript;
            }
        }
        for (String tag : tags)
        {
            if (scriptList.containsKey(tag))
            {
                // Use the first recognized tag. We assume a single font only recognizes one version ("ver. 2")
                // of a single script, or if it recognizes more than one that it prefers the latest one.
                lastUsedSupportedScript = tag;
                return lastUsedSupportedScript;
            }
        }
        return tags[0];
    }

    private Collection<LangSysTable> getLangSysTables(String scriptTag)
    {
        Collection<LangSysTable> result = Collections.emptyList();
        ScriptTable scriptTable = scriptList.get(scriptTag);
        if (scriptTable != null)
        {
            if (scriptTable.getDefaultLangSysTable() == null)
            {
                result = scriptTable.getLangSysTables().values();
            }
            else
            {
                result = new ArrayList<>(scriptTable.getLangSysTables().values());
                result.add(scriptTable.getDefaultLangSysTable());
            }
        }
        return result;
    }

    /**
     * Get a list of {@code FeatureRecord}s from a collection of {@code LangSysTable}s. Optionally
     * filter the returned features by supplying a list of allowed feature tags in
     * {@code enabledFeatures}.
     *
     * Note that features listed as required ({@code LangSysTable#requiredFeatureIndex}) will be
     * included even if not explicitly enabled.
     *
     * @param langSysTables The {@code LangSysTable}s indicating {@code FeatureRecord}s to search
     * for
     * @param enabledFeatures An optional list of feature tags ({@code null} to allow all)
     * @return The indicated {@code FeatureRecord}s
     */
    private List<FeatureRecord> getFeatureRecords(Collection<LangSysTable> langSysTables,
            final List<String> enabledFeatures)
    {
        if (langSysTables.isEmpty())
        {
            return Collections.emptyList();
        }
        List<FeatureRecord> result = new ArrayList<>();
        langSysTables.forEach(langSysTable ->
        {
            int required = langSysTable.getRequiredFeatureIndex();
            FeatureRecord[] featureRecords = featureListTable.getFeatureRecords();
            if (required != 0xffff && required < featureRecords.length) // if no required features = 0xFFFF
            {
                result.add(featureRecords[required]);
            }
            for (int featureIndex : langSysTable.getFeatureIndices())
            {
                if (featureIndex < featureRecords.length &&
                        (enabledFeatures == null ||
                         enabledFeatures.contains(featureRecords[featureIndex].getFeatureTag())))
                {
                    result.add(featureRecords[featureIndex]);
                }
            }
        });

        // 'vrt2' supersedes 'vert' and they should not be used together
        // https://www.microsoft.com/typography/otspec/features_uz.htm
        if (containsFeature(result, "vrt2"))
        {
            removeFeature(result, "vert");
        }

        if (enabledFeatures != null && result.size() > 1)
        {
            result.sort((o1, o2) -> Integer.compare(enabledFeatures.indexOf(o1.getFeatureTag()),
                                                    enabledFeatures.indexOf(o2.getFeatureTag())));
        }

        return result;
    }

    private boolean containsFeature(List<FeatureRecord> featureRecords, String featureTag)
    {
        return featureRecords.stream().anyMatch(
                   featureRecord -> featureRecord.getFeatureTag().equals(featureTag));
    }

    private void removeFeature(List<FeatureRecord> featureRecords, String featureTag)
    {
        Iterator<FeatureRecord> iter = featureRecords.iterator();
        while (iter.hasNext())
        {
            if (iter.next().getFeatureTag().equals(featureTag))
            {
                iter.remove();
            }
        }
    }

    private int applyFeature(FeatureRecord featureRecord, int gid)
    {
        int lookupResult = gid;
        for (int lookupListIndex : featureRecord.getFeatureTable().getLookupListIndices())
        {
            LookupTable lookupTable = lookupListTable.getLookups()[lookupListIndex];
            if (lookupTable.getLookupType() != 1)
            {
                LOG.debug("Skipping GSUB feature '" + featureRecord.getFeatureTag()
                        + "' because it requires unsupported lookup table type "
                        + lookupTable.getLookupType());
                continue;
            }
            lookupResult = doLookup(lookupTable, lookupResult);
        }
        return lookupResult;
    }

    private int doLookup(LookupTable lookupTable, int gid)
    {
        for (LookupSubTable lookupSubtable : lookupTable.getSubTables())
        {
            int coverageIndex = lookupSubtable.getCoverageTable().getCoverageIndex(gid);
            if (coverageIndex >= 0)
            {
                return lookupSubtable.doSubstitution(gid, coverageIndex);
            }
        }
        return gid;
    }

    /**
     * Apply glyph substitutions to the supplied gid. The applicable substitutions are determined by the
     * {@code scriptTags} which indicate the language of the gid, and by the list of {@code enabledFeatures}.
     *
     * To ensure that a single gid isn't mapped to multiple substitutions, subsequent invocations with the same gid will
     * return the same result as the first, regardless of script or enabled features.
     *
     * @param gid GID
     * @param scriptTags Script tags applicable to the gid (see {@link OpenTypeScript})
     * @param enabledFeatures list of features to apply
     *
     * @return the id of the glyph substituion
     */
    public int getSubstitution(int gid, String[] scriptTags, List<String> enabledFeatures)
    {
        if (gid == -1)
        {
            return -1;
        }
        Integer cached = lookupCache.get(gid);
        if (cached != null)
        {
            // Because script detection for indeterminate scripts (COMMON, INHERIT, etc.) depends on context,
            // it is possible to return a different substitution for the same input. However we don't want that,
            // as we need a one-to-one mapping.
            return cached;
        }
        String scriptTag = selectScriptTag(scriptTags);
        Collection<LangSysTable> langSysTables = getLangSysTables(scriptTag);
        List<FeatureRecord> featureRecords = getFeatureRecords(langSysTables, enabledFeatures);
        int sgid = gid;
        for (FeatureRecord featureRecord : featureRecords)
        {
            sgid = applyFeature(featureRecord, sgid);
        }
        lookupCache.put(gid, sgid);
        reverseLookup.put(sgid, gid);
        return sgid;
    }

    /**
     * For a substitute-gid (obtained from {@link #getSubstitution(int, String[], List)}), retrieve the original gid.
     *
     * Only gids previously substituted by this instance can be un-substituted. If you are trying to unsubstitute before
     * you substitute, something is wrong.
     *
     * @param sgid Substitute GID
     *
     * @return the original gid of a substitute-gid
     */
    public int getUnsubstitution(int sgid)
    {
        Integer gid = reverseLookup.get(sgid);
        if (gid == null)
        {
            LOG.warn("Trying to un-substitute a never-before-seen gid: " + sgid);
            return sgid;
        }
        return gid;
    }

    public GsubData getGsubData()
    {
        return gsubData;
    }

    private RangeRecord readRangeRecord(TTFDataStream data) throws IOException
    {
        int startGlyphID = data.readUnsignedShort();
        int endGlyphID = data.readUnsignedShort();
        int startCoverageIndex = data.readUnsignedShort();
        return new RangeRecord(startGlyphID, endGlyphID, startCoverageIndex);
    }

}


text:
#pragma once

#include <camp/detail/simplepropertyimpl.hpp>
#include <camp/detail/arraypropertyimpl.hpp>
#include <camp/detail/enumpropertyimpl.hpp>
#include <camp/detail/userpropertyimpl.hpp>
#include <camp/detail/functiontraits.hpp>
#include <boost/function.hpp>
#include <boost/utility/enable_if.hpp>

namespace camp
{
namespace detail
{
/*
 * Instanciate simple properties
 */
template <typename A, int T>
struct PropertyMapper
{
    typedef SimplePropertyImpl<A> Type;
};

/*
 * Instanciate array properties
 */
template <typename A>
struct PropertyMapper<A, camp::arrayType>
{
    typedef ArrayPropertyImpl<A> Type;
};

/*
 * Instanciate enum properties
 */
template <typename A>
struct PropertyMapper<A, camp::enumType>
{
    typedef EnumPropertyImpl<A> Type;
};

/*
 * Instanciate user properties
 */
template <typename A>
struct PropertyMapper<A, camp::userType>
{
    typedef UserPropertyImpl<A> Type;
};

/**
 * Helper structure to perform copy and assignment
 *
 * The purpose of this structure is to avoid a compiler error when the copied
 * type is not copyable. Instead, we just return an error so that the caller
 * can throw a CAMP exception.
 */
template <typename T, typename E = void>
struct CopyHelper
{
    static bool copy(T& destination, const Value& source)
    {
        destination = source.to<T>();
        return true;
    }
};

/**
 * Specialization of CopyHelper for non-copyable types
 */
template <typename T>
struct CopyHelper<T, typename boost::enable_if_c<!StaticTypeId<T>::copyable>::type>
{
    static bool copy(T&, const Value&)
    {
        // We don't really return an error, we just skip the assignment
        return true;
    }
};

/**
 * Helper structure to return values
 *
 * The purpose of this structure is to provide workarounds for types
 * that don't exactly satisfy the compiler when returned. For example,
 * it converts smart pointer types to the corresponding raw pointer types.
 */
template <typename T, typename E = void>
struct ReturnHelper
{
    typedef T Type;
    static Type get(T value) {return value;}
};

/**
 * Specialization of ReturnHelper for smart pointer types
 */
template <template <typename> class T, typename U>
struct ReturnHelper<T<U>, typename boost::enable_if<IsSmartPointer<T<U>, U> >::type>
{
    typedef U* Type;
    static Type get(T<U> value) {return boost::get_pointer(value);}
};

/**
 * Specialization of ReturnHelper for built-in array types
 */
template <typename T, int N>
struct ReturnHelper<T[N]>
{
    typedef T (&Type)[N];
    static Type get(T (&value)[N]) {return value;}
};

/*
 * Property accessor composed of 1 getter
 */
template <typename C, typename R, typename E = void>
class Accessor1
{
public:

    typedef ObjectTraits<R> Traits;
    typedef typename Traits::DataType DataType;
    typedef C ClassType;

    enum
    {
        canRead = true,
        canWrite = false
    };

    template <typename F>
    Accessor1(F getter)
        : m_getter(getter)
    {
    }

    typename ReturnHelper<R>::Type get(C& object) const
    {
        return ReturnHelper<R>::get(m_getter(object));
    }

    bool set(C&, const Value&) const
    {
        // Not available
        return false;
    }

private:

    boost::function<R (C&)> m_getter;
};

/*
 * Property accessor composed of 1 read-write accessor
 */
template <typename C, typename R>
class Accessor1<C, R, typename boost::enable_if_c<ObjectTraits<R>::isWritable>::type>
{
public:

    typedef ObjectTraits<R> Traits;
    typedef typename Traits::DataType DataType;
    typedef C ClassType;

    enum
    {
        canRead = true,
        canWrite = true
    };

    template <typename F>
    Accessor1(F getter)
        : m_getter(getter)
    {
    }

    typename ReturnHelper<R>::Type get(C& object) const
    {
        return ReturnHelper<R>::get(m_getter(object));
    }

    bool set(C& object, const Value& value) const
    {
        return CopyHelper<DataType>::copy(*Traits::getPointer(m_getter(object)), value);
    }

private:

    boost::function<R (C&)> m_getter;
};

/*
 * Property accessor composed of 1 getter and 1 setter
 */
template <typename C, typename R>
class Accessor2
{
public:

    typedef ObjectTraits<R> Traits;
    typedef typename Traits::DataType DataType;
    typedef C ClassType;
    typedef typename std::remove_reference<R>::type ArgumentType;

    enum
    {
        canRead = true,
        canWrite = true
    };

    template <typename F1, typename F2>
    Accessor2(F1 getter, F2 setter)
        : m_getter(getter)
        , m_setter(setter)
    {
    }

    typename ReturnHelper<R>::Type get(C& object) const
    {
        return ReturnHelper<R>::get(m_getter(object));
    }

    bool set(C& object, const Value& value) const
    {
        m_setter(object, value.to<ArgumentType>());
        return true;
    }

private:

    boost::function<R (C&)> m_getter;
    boost::function<void (C&, ArgumentType)> m_setter;
};

/*
 * Property accessor composed of 1 composed getter
 */
template <typename C, typename N, typename R, typename E = void>
class Accessor3
{
public:

    typedef ObjectTraits<R> Traits;
    typedef typename Traits::DataType DataType;
    typedef C ClassType;

    enum
    {
        canRead = true,
        canWrite = false
    };

    template <typename F1, typename F2>
    Accessor3(F1 getter1, F2 getter2)
        : m_getter1(getter1)
        , m_getter2(getter2)
    {
    }

    typename ReturnHelper<R>::Type get(C& object) const
    {
        return ReturnHelper<R>::get(m_getter1(m_getter2(object)));
    }

    bool set(C&, const Value&) const
    {
        // Not available
        return false;
    }

private:

    boost::function<R (N&)> m_getter1;
    boost::function<N& (C&)> m_getter2;
};

/*
 * Property accessor composed of 1 composed read-write accessor
 */
template <typename C, typename N, typename R>
class Accessor3<C, N, R, typename boost::enable_if_c<ObjectTraits<R>::isWritable>::type>
{
public:

    typedef ObjectTraits<R> Traits;
    typedef typename Traits::DataType DataType;
    typedef C ClassType;

    enum
    {
        canRead = true,
        canWrite = true
    };

    template <typename F1, typename F2>
    Accessor3(F1 getter1, F2 getter2)
        : m_getter1(getter1)
        , m_getter2(getter2)
    {
    }

    typename ReturnHelper<R>::Type get(C& object) const
    {
        return ReturnHelper<R>::get(m_getter1(m_getter2(object)));
    }

    bool set(C& object, const Value& value) const
    {
        return CopyHelper<DataType>::copy(*Traits::getPointer(m_getter1(m_getter2(object))), value);
    }

private:

    boost::function<R (N&)> m_getter1;
    boost::function<N& (C&)> m_getter2;
};

/*
 * Property factory which instanciates the proper type of property from 1 accessor
 */
template <typename C, typename F>
struct PropertyFactory1
{
    typedef typename FunctionTraits<F>::ReturnType ReturnType;

    static Property* get(const char* name, F accessor)
    {
        typedef Accessor1<C, ReturnType> AccessorType;

        typedef camp_ext::ValueMapper<typename AccessorType::DataType> ValueMapper;
        typedef typename PropertyMapper<AccessorType, ValueMapper::type>::Type PropertyType;

        return new PropertyType(name, AccessorType(accessor));
    }
};

/*
 * Property factory which instanciates the proper type of property from 2 accessors
 */
template <typename C, typename F1, typename F2, typename E = void>
struct PropertyFactory2
{
    typedef typename FunctionTraits<F1>::ReturnType ReturnType;

    static Property* get(const char* name, F1 accessor1, F2 accessor2)
    {
        typedef Accessor2<C, ReturnType> AccessorType;

        typedef camp_ext::ValueMapper<typename AccessorType::DataType> ValueMapper;
        typedef typename PropertyMapper<AccessorType, ValueMapper::type>::Type PropertyType;

        return new PropertyType(name, AccessorType(accessor1, accessor2));
    }
};

/*
 * Specialization of PropertyFactory2 with 2 getters (which will produce 1 composed getter)
 */
template <typename C, typename F1, typename F2>
struct PropertyFactory2<C, F1, F2, typename boost::enable_if_c<!std::is_void<typename FunctionTraits<F2>::ReturnType>::value>::type>
{
    typedef typename FunctionTraits<F1>::ReturnType ReturnType;
    typedef typename std::remove_reference<typename FunctionTraits<F2>::ReturnType>::type OtherClassType;

    static Property* get(const char* name, F1 accessor1, F2 accessor2)
    {
        typedef Accessor3<C, OtherClassType, ReturnType> AccessorType;

        typedef camp_ext::ValueMapper<typename AccessorType::DataType> ValueMapper;
        typedef typename PropertyMapper<AccessorType, ValueMapper::type>::Type PropertyType;

        return new PropertyType(name, AccessorType(accessor1, accessor2));
    }
};

/*
 * Property factory which instanciates the proper type of property from 3 accessors
 */
template <typename C, typename F1, typename F2, typename F3>
struct PropertyFactory3
{
    typedef typename FunctionTraits<F1>::ReturnType ReturnType;
    typedef typename FunctionTraits<F3>::ReturnType InnerType;

    static Property* get(const char* name, F1 accessor1, F2 accessor2, F3 accessor3)
    {
        typedef Accessor2<C, ReturnType> AccessorType;

        typedef camp_ext::ValueMapper<typename AccessorType::DataType> ValueMapper;
        typedef typename PropertyMapper<AccessorType, ValueMapper::type>::Type PropertyType;

        return new PropertyType(name, AccessorType(boost::bind(boost::type<ReturnType>(), accessor1, boost::bind(boost::type<InnerType>(), accessor3, _1)),
                                                   boost::bind(boost::type<void>(), accessor2, boost::bind(boost::type<InnerType>(), accessor3, _1), _2)));
    }
};

} // namespace detail

} // namespace camp

redpajama_set_name: RedPajamaGithub


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

namespace FamousQuoteQuiz.Data.Repositories
{
    public class GenericRepository<T> : IRepository<T> where T : class
    {
        public GenericRepository(DbContext context)
        {
            if (context == null)
            {
                throw new ArgumentException("An instance of DbContext is required to use this repository.", "context");
            }

            Context = context;
            DbSet = Context.Set<T>();
        }

        protected IDbSet<T> DbSet { get; set; }

        protected DbContext Context { get; set; }

        public virtual IQueryable<T> All()
        {
            return DbSet.AsQueryable();
        }

        public virtual T GetById(int id)
        {
            return DbSet.Find(id);
        }

        public virtual void Add(T entity)
        {
            DbEntityEntry entry = Context.Entry(entity);
            if (entry.State != EntityState.Detached)
            {
                entry.State = EntityState.Added;
            }
            else
            {
                DbSet.Add(entity);
            }
        }

        public virtual void Update(T entity)
        {
            DbEntityEntry entry = Context.Entry(entity);
            if (entry.State == EntityState.Detached)
            {
                DbSet.Attach(entity);
            }

            entry.State = EntityState.Modified;
        }

        public virtual void Delete(T entity)
        {
            DbEntityEntry entry = Context.Entry(entity);
            if (entry.State != EntityState.Deleted)
            {
                entry.State = EntityState.Deleted;
            }
            else
            {
                DbSet.Attach(entity);
                DbSet.Remove(entity);
            }
        }

        public virtual void Delete(int id)
        {
            var entity = GetById(id);

            if (entity != null)
            {
                Delete(entity);
            }
        }

        public virtual void Detach(T entity)
        {
            DbEntityEntry entry = Context.Entry(entity);

            entry.State = EntityState.Detached;
        }

        public int SaveChanges()
        {
            return Context.SaveChanges();
        }

        public void Dispose()
        {
            Context.Dispose();
        }
    }
}


text:
from __future__ import unicode_literals

from django.db import models, migrations
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='Conference',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('name', models.CharField(max_length=150)),
                ('theme', models.TextField(blank=True)),
                ('date_start', models.DateField(blank=True)),
                ('date_end', models.DateField(blank=True)),
                ('date_created', models.DateField(auto_now_add=True)),
                ('date_updated', models.DateField(auto_now=True)),
                ('is_current', models.BooleanField(default=False)),
                ('location_address', models.TextField(blank=True)),
                ('location_name', models.TextField(blank=True)),
                ('map_link', models.CharField(max_length=255, blank=True)),
                ('user_updated', models.ForeignKey(to=settings.AUTH_USER_MODEL)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
    ]


text:
package com.imadcn.system.test;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

import com.imadcn.system.test.idworker.SpringIdWorkerTest;

@RunWith(Suite.class)
@SuiteClasses({SpringIdWorkerTest.class})
public final class AllSpringTests {

}


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

<title>ContactsTable.Reactor</title>
<meta name="date" content="2015-10-21">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

virtualpondgui

Interface ContactsTable.Reactor

All Superinterfaces:

java.util.EventListener, java.awt.event.MouseListener, javax.swing.table.TableModel

All Known Implementing Classes:

ContactsTableReactor

Enclosing class:

ContactsTable

public static interface ContactsTable.Reactor
extends javax.swing.table.TableModel, java.awt.event.MouseListener

Method Summary

All Methods Instance Methods Abstract Methods

Modifier and Type
Method and Description

void
setTable(javax.swing.JTable table)

void
sortByColumn(int column)

Methods inherited from interface javax.swing.table.TableModel

addTableModelListener, getColumnClass, getColumnCount, getColumnName, getRowCount, getValueAt, isCellEditable, removeTableModelListener, setValueAt

Methods inherited from interface java.awt.event.MouseListener

mouseClicked, mouseEntered, mouseExited, mousePressed, mouseReleased

Method Detail

setTable

void setTable(javax.swing.JTable table)

sortByColumn

void sortByColumn(int column)

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
A Kubernetes pod is a group of containers that are deployed together on the same host. If you frequently deploy single containers, you can generally replace the word "pod" with "container" and accurately understand the concept.

Pods operate at one level higher than individual containers because it's very common to have a group of containers work together to produce an artifact or process a set of work.

For example, consider this pair of containers: a caching server and a cache "warmer". You could build these two functions into a single container, but now they can each be tailored to the specific task and shared between different projects/teams.

Another example is an app server pod that contains three separate containers: the app server itself, a monitoring adapter, and a logging adapter. The logging and monitoring containers could be shared across all projects in your organization. These adapters could provide an abstraction between different cloud monitoring vendors or other destinations.

Any project requiring logging or monitoring can include these containers in their pods, but not have to worry about the specific logic. All they need to do is send logs from the app server to a known location within the pod. How does that work? Let's walk through it.

## Shared Namespaces, Volumes and Secrets

By design, all of the containers in a pod are connected to facilitate intra-pod communication, ease of management and flexibility for application architectures. If you've ever fought with connecting two raw containers together, the concept of a pod will save you time and is much more powerful.

### Shared Network

All containers share the same network namespace & port space. Communication over localhost is encouraged. Each container can also communicate with any other pod or service within the cluster.

### Shared Volumes

Volumes attached to the pod may be mounted inside of one or more containers. In the logging example above, a volume named `logs` is attached to the pod. The app server would log output to `logs` mounted at `/volumes/logs` and the logging adapter would have a read-only mount to the same volume. If either of these containers needed to restarted, the log data is preserved instead of being lost.

There are many types of volumes supported by Kubernetes, including native support for mounting GitHub repos, network disks (EBS, NFS, etc), local machine disks, and a few special volume types, like secrets.

Here's an example pod:

```
apiVersion: v1
kind: Pod
metadata:
  name: example-app
  labels:
    app: example-app
    version: v1
    role: backend
spec:
  containers:
  - name: java
    image: companyname/java
    ports:
    - containerPort: 443
    volumeMounts:
    - mountPath: /volumes/logs
      name: logs
  - name: logger
    image: companyname/logger:v1.2.3
    ports:
    - containerPort: 9999
    volumeMounts:
    - mountPath: /logs
      name: logs
  - name: monitoring
    image: companyname/monitoring:v4.5.6
    ports:
    - containerPort: 1234
```

### Resources

Resource limits such as CPU and RAM are shared between all containers in the pod.

## Creating Pods

Pods are considered ephemeral "cattle" and won't survive a machine failure and may be terminated for machine maintenance. For high resiliency, pods are managed by a [replication controller][controller-overview], which creates and destroys replicas of pods as needed. Individual pods can also be created outside of a replication controller, but this isn't a common practice.

[Kubernetes services][service-overview] should always be used to expose pod(s) to the rest of the cluster in order to provide the proper level of abstraction since individual pods will come and go.

Replication controllers and services use the *pod labels* to select a group of pods that they interact with. Your pods will typically have labels for the application name, role, environment, version, etc. Each of these can be combined in order to select all pods with a certain role, a certain application, or a more complex query. The label system is extremely flexible by design and experimentation is encouraged to establish the practices that work best for your company or team.

Are you familiar with replication controllers and services?

  Replication Controller overview
  Services overview
  Back to Listing

[controller-overview]: replication-controller.md
[service-overview]: services.md


text:
package com.example;

import java.net.URI;

import org.assertj.core.api.BDDAssertions;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.cloud.contract.stubrunner.junit.StubRunnerExtension;
import org.springframework.cloud.contract.stubrunner.spring.StubRunnerProperties;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

/**
 * @author Marcin Grzejszczak
 */
@SpringBootTest(webEnvironment = WebEnvironment.NONE)
@Disabled("TODO: Need to update the GraphQL example")
public class BeerControllerGraphQLTest extends AbstractTest {

	@RegisterExtension
	static StubRunnerExtension rule = new StubRunnerExtension()
			.downloadStub("com.example","beer-api-producer-graphql")
			.stubsMode(StubRunnerProperties.StubsMode.LOCAL);

	@BeforeAll
	public static void beforeClass() {
		Assumptions.assumeTrue(atLeast300(), "Spring Cloud Contract must be in version at least 3.0.0");
		Assumptions.assumeTrue(StringUtils.isEmpty(System.getenv("OLD_PRODUCER_TRAIN")), "Env var OLD_PRODUCER_TRAIN must not be set");
	}

	private static boolean atLeast300() {
		try {
			Class.forName("org.springframework.cloud.contract.verifier.dsl.wiremock.SpringCloudContractRequestMatcher");
		} catch (Exception ex) {
			return false;
		}
		return true;
	}

	private static final String REQUEST_BODY = "{\n"
			+ "\"query\":\"query queryName($personName: String!) {\\n  personToCheck(name: $personName) {\\n    name\\n    age\\n  }\\n}\","
			+ "\"variables\":{\"personName\":\"Old Enough\"},\n"
			+ "\"operationName\":\"queryName\"\n"
			+ "}";

	@Test
	public void should_send_a_graphql_request() throws Exception {
		ResponseEntity<String> responseEntity = new RestTemplate()
				.exchange(RequestEntity
						.post(URI.create("http://localhost:" + rule.findStubUrl("beer-api-producer-graphql").getPort() + "/graphql"))
						.contentType(MediaType.APPLICATION_JSON)
						.body(REQUEST_BODY), String.class);

		BDDAssertions.then(responseEntity.getStatusCodeValue()).isEqualTo(200);

	}
}


text:
SPREE_ROOT = File.expand_path(File.join(File.dirname(__FILE__), "..")) unless defined? SPREE_ROOT

unless defined? Spree::Version
  module Spree
    module Version
      Major = '0'
      Minor = '8'
      Tiny  = '99'

      class << self
        def to_s
          [Major, Minor, Tiny].join('.')
        end
        alias :to_str :to_s
      end
    end
  end
end


text:
try:
    from setuptools import setup, find_packages
except ImportError:
    try:
        from distribute_setup import use_setuptools
        use_setuptools()
        from setuptools import setup, find_packages
    except ImportError:
        raise RuntimeError("python setuptools is required to build Marvin")

VERSION = "4.16.0.0-SNAPSHOT"

setup(name="Marvin",
      version=VERSION,
      description="Marvin - Python client for Apache CloudStack",
      author="The Apache CloudStack Team",
      author_email="dev@cloudstack.apache.org",
      maintainer="The Apache CloudStack Team",
      maintainer_email="dev@cloudstack.apache.org",
      long_description="Marvin is the Apache CloudStack python "
                       "client written around the unittest framework",
      platforms=("Any",),
      url="https://builds.apache.org/job/cloudstack-marvin/",
      packages=["marvin", "marvin.cloudstackAPI",
                "marvin.lib", "marvin.config", "marvin.sandbox",
                "marvin.sandbox.advanced", "marvin.sandbox.advancedsg",
                "marvin.sandbox.basic"],
      license="LICENSE.txt",
      install_requires=[
          "mysql-connector-python >= 1.1.6",
          "requests >= 2.2.1",
          "paramiko >= 1.13.0",
          "nose >= 1.3.3",
          "ddt >= 0.4.0",
          "pyvmomi >= 5.5.0",
          "netaddr >= 0.7.14",
          "dnspython",
          "ipmisim >= 0.7",
          "pytz",
          "retries",
          "PyCrypt"
      ],
      py_modules=['marvin.marvinPlugin'],
      zip_safe=False,
      entry_points={
          'nose.plugins': ['marvinPlugin = marvin.marvinPlugin:MarvinPlugin'],
          'console_scripts': ['marvincli = marvin.deployAndRun:main']
      },
      )


text:
{{ site.title }}

{{ site.tagline }}

Início

Sobre


text:
import React from 'react';
import { Link } from 'react-router-dom';
import AppBar from 'material-ui/AppBar';

const barTitle = (
  <Link to="/" style={{color: '#FFF', textDecoration:'none'}}>
    LEO<b style={{ color: '#ffcd57'}}>MANGA</b>
  </Link>
);

const barStyle = {
  background: 'linear-gradient(rgb(71, 81, 175), rgb(71, 88, 171))'
};

const HeaderBar = (props) => (
    <AppBar
      title={barTitle}
      style={barStyle}
      {...props}
    />
);

export default HeaderBar;


text:
namespace content {

PepperProxyChannelDelegateImpl::~PepperProxyChannelDelegateImpl() {
}

base::MessageLoopProxy* PepperProxyChannelDelegateImpl::GetIPCMessageLoop() {
  // This is called only in the renderer so we know we have a child process.
  DCHECK(ChildProcess::current()) << "Must be in the renderer.";
  return ChildProcess::current()->io_message_loop_proxy();
}

base::WaitableEvent* PepperProxyChannelDelegateImpl::GetShutdownEvent() {
  DCHECK(ChildProcess::current()) << "Must be in the renderer.";
  return ChildProcess::current()->GetShutDownEvent();
}

IPC::PlatformFileForTransit
PepperProxyChannelDelegateImpl::ShareHandleWithRemote(
    base::PlatformFile handle,
    const IPC::SyncChannel& channel,
    bool should_close_source) {
  return content::BrokerGetFileHandleForProcess(handle, channel.peer_pid(),
                                                should_close_source);
}

}  // namespace content


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

using SharpDX;
using SharpDX.Windows;
using SharpDX.DXGI;
using SharpDX.Direct3D11;

using Common;

// Resolve class name conflicts by explicitly stating
// which class they refer to:
using Buffer = SharpDX.Direct3D11.Buffer;

namespace Ch06_01DisplacementMapping
{
    /// <summary>
    /// Assumes that the 2nd and 3rd textures for a material is the normal and displacement textures
    /// </summary>
    public class MeshRenderer: RendererBase
    {
        // The vertex buffer
        List<Buffer> vertexBuffers = new List<Buffer>();
        // The index buffer
        List<Buffer> indexBuffers = new List<Buffer>();

        // texture resources
        List<ShaderResourceView> textureViews = new List<ShaderResourceView>();
        public List<ShaderResourceView> TextureViews { get { return textureViews; } }
        // Control sampling behavior with this state
        SamplerState samplerState;

        Common.Mesh mesh;
        // Provide access to the underlying mesh object
        public Common.Mesh Mesh { get { return this.mesh; } }

        // The per material buffer to use so that the mesh parameters can be used
        public Buffer PerMaterialBuffer { get; set; }
        // The per armature constant buffer to use
        public Buffer PerArmatureBuffer { get; set; }

        // Enable normal map?
        public bool EnableNormalMap { get; set; }

        public MeshRenderer(Common.Mesh mesh)
        {
            this.mesh = mesh;
            this.EnableNormalMap = true;
        }

        protected override void CreateDeviceDependentResources()
        {
            // Dispose of each vertex and index buffer
            vertexBuffers.ForEach(vb => RemoveAndDispose(ref vb));
            vertexBuffers.Clear();
            indexBuffers.ForEach(ib => RemoveAndDispose(ref ib));
            indexBuffers.Clear();
            textureViews.ForEach(tv => RemoveAndDispose(ref tv));
            textureViews.Clear();
            RemoveAndDispose(ref samplerState);

            // Retrieve our SharpDX.Direct3D11.Device1 instance
            var device = this.DeviceManager.Direct3DDevice;

            // Initialize vertex buffers
            for (int indx = 0; indx < mesh.VertexBuffers.Count; indx++)
            {
                var vb = mesh.VertexBuffers[indx];
                Vertex[] vertices = new Vertex[vb.Length];
                for (var i = 0; i < vb.Length; i++)
                {
                    // Retrieve skinning information for vertex
                    Common.Mesh.SkinningVertex skin = new Common.Mesh.SkinningVertex();
                    if (mesh.SkinningVertexBuffers.Count > 0)
                        skin = mesh.SkinningVertexBuffers[indx][i];

                    // Create vertex
                    vertices[i] = new Vertex(vb[i].Position, vb[i].Normal, vb[i].Color, vb[i].UV, skin, vb[i].Tangent);
                }

                vertexBuffers.Add(ToDispose(Buffer.Create(device, BindFlags.VertexBuffer, vertices.ToArray())));
                vertexBuffers[vertexBuffers.Count - 1].DebugName = "VertexBuffer_" + indx.ToString();
            }

            // Initialize index buffers
            foreach (var ib in mesh.IndexBuffers)
            {
                indexBuffers.Add(ToDispose(Buffer.Create(device, BindFlags.IndexBuffer, ib)));
                indexBuffers[indexBuffers.Count - 1].DebugName = "IndexBuffer_" + (indexBuffers.Count - 1).ToString();
            }

            // Load textures if a material has any.
            foreach (var m in mesh.Materials)
            {
                for (var i = 0; i < m.Textures.Length; i++)
                {
                    if (System.IO.File.Exists(m.Textures[i]))
                        textureViews.Add(ToDispose(TextureLoader.ShaderResourceViewFromFile(device, m.Textures[i])));
                    else
                        textureViews.Add(null);
                }
            }

            // Create our sampler state
            samplerState = ToDispose(new SamplerState(device, new SamplerStateDescription()
            {
                AddressU = TextureAddressMode.Clamp,
                AddressV = TextureAddressMode.Clamp,
                AddressW = TextureAddressMode.Clamp,
                BorderColor = new Color4(0, 0, 0, 0),
                ComparisonFunction = Comparison.Never,
                Filter = Filter.MinMagMipLinear,
                MaximumAnisotropy = 16,
                MaximumLod = float.MaxValue,
                MinimumLod = 0,
                MipLodBias = 0.0f
            }));
        }

        // Create and allow access to a timer
        System.Diagnostics.Stopwatch clock = new System.Diagnostics.Stopwatch();
        public System.Diagnostics.Stopwatch Clock
        {
            get { return clock; }
            set { clock = value; }
        }

        // The currently active animation (allows nulls)
        public Mesh.Animation? CurrentAnimation { get; set; }

        // Play once or loop the animation?
        public bool PlayOnce { get; set; }

        protected override void DoRender()
        {
            // Calculate elapsed seconds
            var time = clock.ElapsedMilliseconds / 1000.0f;

            // Retrieve device context
            var context = this.DeviceManager.Direct3DContext;

            // Calculate skin matrices for each bone
            ConstantBuffers.PerArmature skinMatrices = new ConstantBuffers.PerArmature();
            if (mesh.Bones != null)
            {
                // Retrieve each bone's local transform
                for (var i = 0; i < mesh.Bones.Count; i++)
                {
                    skinMatrices.Bones[i] = mesh.Bones[i].BoneLocalTransform;
                }

                // Load bone transforms from animation frames
                if (CurrentAnimation.HasValue)
                {
                    // Keep track of the last key-frame used for each bone
                    Mesh.Keyframe?[] lastKeyForBones = new Mesh.Keyframe?[mesh.Bones.Count];
                    // Keep track of whether a bone has been interpolated
                    bool[] lerpedBones = new bool[mesh.Bones.Count];
                    for (var i = 0; i < CurrentAnimation.Value.Keyframes.Count; i++)
                    {
                        // Retrieve current key-frame
                        var frame = CurrentAnimation.Value.Keyframes[i];

                        // If the current frame is not in the future
                        if (frame.Time <= time)
                        {
                            // Keep track of last key-frame for bone
                            lastKeyForBones[frame.BoneIndex] = frame;
                            // Retrieve transform from current key-frame
                            skinMatrices.Bones[frame.BoneIndex] = frame.Transform;
                        }
                        // Frame is in the future, check if we should interpolate
                        else
                        {
                            // Only interpolate a bone's key-frames ONCE
                            if (!lerpedBones[frame.BoneIndex])
                            {
                                // Retrieve the previous key-frame if exists
                                Mesh.Keyframe prevFrame;
                                if (lastKeyForBones[frame.BoneIndex] != null)
                                    prevFrame = lastKeyForBones[frame.BoneIndex].Value;
                                else
                                    continue; // nothing to interpolate
                                // Make sure we only interpolate with
                                // one future frame for this bone
                                lerpedBones[frame.BoneIndex] = true;

                                // Calculate time difference between frames
                                var frameLength = frame.Time - prevFrame.Time;
                                var timeDiff = time - prevFrame.Time;
                                var amount = timeDiff / frameLength;

                                // Interpolation using Lerp on scale and translation, and Slerp on Rotation (Quaternion)
                                Vector3 t1, t2;   // Translation
                                Quaternion q1, q2;// Rotation
                                float s1, s2;     // Scale
                                // Decompose the previous key-frame's transform
                                prevFrame.Transform.DecomposeUniformScale(out s1, out q1, out t1);
                                // Decompose the current key-frame's transform
                                frame.Transform.DecomposeUniformScale(out s2, out q2, out t2);

                                // Perform interpolation and reconstitute matrix
                                skinMatrices.Bones[frame.BoneIndex] =
                                    Matrix.Scaling(MathUtil.Lerp(s1, s2, amount)) *
                                    Matrix.RotationQuaternion(Quaternion.Slerp(q1, q2, amount)) *
                                    Matrix.Translation(Vector3.Lerp(t1, t2, amount));
                            }
                        }

                    }
                }

                // Apply parent bone transforms
                // We assume here that the first bone has no parent
                // and that each parent bone appears before children
                for (var i = 1; i < mesh.Bones.Count; i++)
                {
                    var bone = mesh.Bones[i];
                    if (bone.ParentIndex > -1)
                    {
                        var parentTransform = skinMatrices.Bones[bone.ParentIndex];
                        skinMatrices.Bones[i] = (skinMatrices.Bones[i] * parentTransform);
                    }
                }

                // Change the bone transform from rest pose space into bone space (using the inverse of the bind/rest pose)
                for (var i = 0; i < mesh.Bones.Count; i++)
                {
                   skinMatrices.Bones[i] = Matrix.Transpose(mesh.Bones[i].InvBindPose * skinMatrices.Bones[i]);
                }

                // Check need to loop animation
                if (!PlayOnce && CurrentAnimation.HasValue && CurrentAnimation.Value.EndTime <= time)
                {
                    this.Clock.Restart();
                }
            }

            // Update the constant buffer with the skin matrices for each bone
            context.UpdateSubresource(skinMatrices.Bones, PerArmatureBuffer);

            // Draw sub-meshes grouped by material
            for (var mIndx = 0; mIndx < mesh.Materials.Count; mIndx++)
            {
                // Retrieve sub meshes for this material
                var subMeshesForMaterial =
                    (from sm in mesh.SubMeshes
                        where sm.MaterialIndex == mIndx
                        select sm).ToArray();

                // If the material buffer is available and there are submeshes
                // using the material update the PerMaterialBuffer
                if (PerMaterialBuffer != null && subMeshesForMaterial.Length > 0)
                {
                    // update the PerMaterialBuffer constant buffer
                    var material = new ConstantBuffers.PerMaterial()
                    {
                        Ambient = new Color4(mesh.Materials[mIndx].Ambient),
                        Diffuse = new Color4(mesh.Materials[mIndx].Diffuse),
                        Emissive = new Color4(mesh.Materials[mIndx].Emissive),
                        Specular = new Color4(mesh.Materials[mIndx].Specular),
                        SpecularPower = mesh.Materials[mIndx].SpecularPower,
                        UVTransform = mesh.Materials[mIndx].UVTransform,
                    };

                    int texIndxOffset = mIndx * Common.Mesh.MaxTextures;
                    material.HasTexture = (uint)(textureViews[texIndxOffset] != null ? 1 : 0); // 0=false
                    material.HasNormalMap = (uint)(EnableNormalMap && textureViews[texIndxOffset+1] != null ? 1 : 0); // 0=false

                    // Bind textures to the pixel shader
                    context.PixelShader.SetShaderResources(0, textureViews.GetRange(texIndxOffset, Common.Mesh.MaxTextures).ToArray());

                    // Set texture sampler state
                    context.PixelShader.SetSampler(0, samplerState);

                    // Update material buffer
                    context.UpdateSubresource(ref material, PerMaterialBuffer);
                }

                // For each sub-mesh
                foreach (var subMesh in subMeshesForMaterial)
                {
                    // Ensure the vertex buffer and index buffers are in range
                    if (subMesh.VertexBufferIndex < vertexBuffers.Count && subMesh.IndexBufferIndex < indexBuffers.Count)
                    {
                        // Retrieve and set the vertex and index buffers
                        var vertexBuffer = vertexBuffers[(int)subMesh.VertexBufferIndex];
                        context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, Utilities.SizeOf<Vertex>(), 0));
                        context.InputAssembler.SetIndexBuffer(indexBuffers[(int)subMesh.IndexBufferIndex], Format.R16_UInt, 0);
                        // Set topology
                        context.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList;
                    }

                    // Draw the sub-mesh (includes Primitive count which we multiply by 3)
                    // The submesh also includes a start index into the vertex buffer
                    context.DrawIndexed((int)subMesh.PrimCount * 3, (int)subMesh.StartIndex, 0);
                }
            }

            // If there are no materials
            if (mesh.Materials.Count == 0)
            {
                foreach (var subMesh in mesh.SubMeshes)
                {
                    // Ensure the vertex buffer and index buffers are in range
                    if (subMesh.VertexBufferIndex < vertexBuffers.Count && subMesh.IndexBufferIndex < indexBuffers.Count)
                    {
                        // Retrieve and set the vertex and index buffers
                        var vertexBuffer = vertexBuffers[(int)subMesh.VertexBufferIndex];
                        context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, Utilities.SizeOf<Vertex>(), 0));
                        context.InputAssembler.SetIndexBuffer(indexBuffers[(int)subMesh.IndexBufferIndex], Format.R16_UInt, 0);
                        // Set topology
                        context.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList;
                    }

                    // Draw the sub-mesh (includes Primitive count which we multiply by 3)
                    // The submesh also includes a start index into the vertex buffer
                    context.DrawIndexed((int)subMesh.PrimCount * 3, (int)subMesh.StartIndex, 0);
                }
            }
        }
    }
}


text:
"""Stuff about BMC's"""

__all__ = ['BMC', 'BMCInfo', 'BMCGuid', 'BMCEnables', 'LanBMC']

class BMCResult(object):
    """superclass for BMC result objects

    Sets attribute names from a dict passed to init, and allows comparison
    with other results based on dict equality.
    """
    def __init__(self, **entries):
        """each kwarg's value to an attribute of the same name"""
        self.__dict__.update(entries)

    def __eq__(self, other):
        """BMCInfo's are equivalent if their attributes are the same"""
        return self.__dict__ == other.__dict__

class BMCInfo(BMCResult):
    """Describes a BMC info record result

    "bmc info" is just the ipmitool name - this is really "get device id"
    """
    device_id = None
    device_revision = None
    firmware_revision = None
    ipmi_version = None
    is_chassis_device = None
    is_bridge = None
    is_ipmb_event_generator = None
    is_ipmb_event_receiver = None
    is_fru_inventory_device = None
    is_sel_device = None
    is_sdr_repository_device = None
    is_sensor_device = None
    manufacturer_id = None
    product_id = None
    device_available = None
    aux_firmware_revision_info = None

class BMCGuid(BMCResult):
    """Result record for bmc guid command

    this is really "get device guid" - bmc guid is the ipmitool command name.
    """
    system_guid = None
    time_stamp = None

class BMCEnables(BMCResult):
    """Result record for get command enables

    The names for the attributes here come from the command line syntax for ipmitool
    """
    recv_msg_intr = None
    event_msg_intr = None
    event_msg = None
    system_event_log = None
    oem0 = None
    oem1 = None
    oem2 = None

class BMCResetResult(BMCResult):
    """Result record for bmc reset command"""
    pass

class BMC(object):
    """A BMC - what you're talking to when you're talking IPMI

    I think this should ultimately be the interface for all commands issued
    from IPMI.. or maybe just commands "about the bmc". This needs to be
    resolved!
    """
    def __init__(self, handle_class, tool_class, command_list):
        """
        Arguments:
        handle_class -- class to use for Handles created
        tool_class -- class to use for the Tool for each handle
        command_list -- the list of commands available for this BMC
        """
        self.handle = handle_class(self, tool_class, command_list)

    def info(self):
        """Get the BMC's info"""
        return self.handle.get_device_id()

    def selftest(self):
        """Get BMC self test results"""
        return self.handle.selftest()

    def bmc_reset(self, type='warm'):
        return self.handle.bmc_reset(type=type)

    def guid(self):
        """Get the BMC's guid"""
        return self.handle.get_system_guid()

    def sdr_list(self):
        """Get a list of SDR's for the BMC"""
        return self.handle.get_sdr_list()

    def enables(self):
        """Return a BMCEnables object for the BMC"""
        return self.handle.get_command_enables()

    def set_chassis_power(self, mode):
        return self.handle.chassis_control(mode=mode)

    def set_chassis_policy(self, state):
        return self.handle.chassis_policy(state=state)

    def get_chassis_status(self):
        return self.handle.chassis_status()

    def update_socman(self, filename, partition, tftp_addr):
        return self.update_firmware(filename, partition, '3', tftp_addr)

    def update_firmware(self, filename, partition, image_type, tftp_addr):
        return self.handle.fw_download(filename=filename, partition=partition,
                                       image_type=image_type,
                                       tftp_addr=tftp_addr)

    def retrieve_firmware(self, filename, partition, image_type, tftp_addr):
        return self.handle.fw_upload(filename=filename, partition=partition,
                                     image_type=image_type,
                                     tftp_addr=tftp_addr)

    def register_firmware_read(self, filename, partition, image_type):
        return self.handle.fw_register_read(filename=filename,
                                            partition=partition,
                                            image_type=image_type)

    def register_firmware_write(self, filename, partition, image_type):
        return self.handle.fw_register_write(filename=filename,
                                             partition=partition,
                                             image_type=image_type)

    def activate_firmware(self, partition):
        return self.handle.fw_activate(partition=partition)

    def invalidate_firmware(self, partition):
        return self.handle.fw_invalidate(partition=partition)

    def set_firmware_flags(self, partition, flags):
        return self.handle.fw_flags(partition=partition, flags=flags)

    def get_firmware_status(self, tftp_handle):
        return self.handle.fw_status(tftp_handle=tftp_handle)

    def check_firmware(self, partition):
        return self.handle.fw_check(partition=partition)

    def cancel_firmware(self, job_id):
        return self.handle.fw_cancel(job_id=job_id)

    def update_raw_firmware(self, filename, offset, size, tftp_addr):
        return self.handle.fw_put(filename=filename, offset=offset,
                                  size=size, tftp_addr=tftp_addr)

    def retrieve_raw_firmware(self, filename, offset, size, tftp_addr):
        return self.handle.fw_get(filename=filename, offset=offset,
                                  size=size, tftp_addr=tftp_addr)

    def get_firmware_info(self):
        return self.handle.fw_info()

    def reset_firmware(self):
        return self.handle.fw_reset()

    def set_firmware_version(self, version):
        return self.handle.fw_version(version=version)

    def get_sel_time(self):
        """Get the time for the SEL"""
        return self.handle.get_sel_time()

    def set_sel_time(self, time):
        """Set the time for the SEL"""
        return self.handle.set_sel_time(time=time)

    def sel_info(self):
        """Get SEL info"""
        return self.handle.sel_info()

    def sel_alloc_info(self):
        """Get SEL alloc info"""
        return self.handle.sel_alloc_info()

    def sel_add(self, *records):
        """Add records to the SEL"""
        return self.handle.sel_add(records=records)

    def sel_get(self, *record_ids):
        """Get SEL Records"""
        return self.handle.sel_get(record_ids=record_ids)

    def sel_list(self):
        """List SEL entries"""
        return self.handle.sel_list()

    def sel_elist(self):
        """Extended SEL list"""
        return self.handle.sel_elist()

    def sel_clear(self):
        """Clear the SEL"""
        return self.handle.sel_clear()

    def set_sol_config_param(self, param, value):
        """Set SOL Configuration Parameter"""
        return self.handle.set_sol_config_params(param=param, value=value)

    def get_sol_config_params(self, *params):
        """Get SOL Configuration Parameters"""
        return self.handle.get_sol_config_params(params=params)

    def activate_payload(self):
        """Activate an SOL session"""
        return self.handle.activate_payload()

    def deactivate_payload(self):
        """Deactivate an SOL session"""
        return self.handle.deactivate_payload()

    def dcmi_get_capabilities(self):
        return self.handle.dcmi_get_capabilities()

    def dcmi_set_asset_tag(self, tag):
        return self.handle.dcmi_set_asset_tag(tag=tag)

    def dcmi_get_asset_tag(self):
        return self.handle.dcmi_get_asset_tag()

    def dcmi_get_controller_id(self):
        return self.handle.dcmi_get_controller_id()

    def dcmi_set_controller_id(self, controller):
        return self.handle.dcmi_set_controller_id(controller=controller)

    def dcmi_get_sensor_info(self):
        return self.handle.dcmi_get_sensor_info()

    def dcmi_get_power_statistics(self):
        return self.handle.dcmi_get_power_statistics()

    def dcmi_get_power_limit(self):
        return self.handle.dcmi_get_power_limit()

    def dcmi_set_power_limit(self):
        return self.handle.dcmi_set_power_limit()

    def dcmi_power_limit_requested(self, limit, exception=None):
        return self.handle.dcmi_power_limit_requested(limit=limit, exception=exception)

    def dcmi_correction_time_limit(self, time_limit, exception=None):
        return self.handle.dcmi_correction_time_limit(time_limit=time_limit, exception=exception)

    def dcmi_statistics_sampling_period(self, period, exception=None):
        return self.handle.dcmi_statistics_sampling_period(period=period, exception=exception)

    def dcmi_activate_power_limit(self, action):
        if action != "activate" and action != "deactivate":
            raise Exception("Invalid argument to dcmi_activate_power_limit: %s" % action)
        return self.handle.dcmi_activate_power_limit(action=action)

    def pef_get_info(self):
        return self.handle.pef_get_info()

    def pef_get_status(self):
        return self.handle.pef_get_status()

    def pef_get_policies(self):
        return self.handle.pef_get_policies()

    def pef_list_entries(self):
        return self.handle.pef_list_entries()

    def pef_config_get_info(self):
        return self.handle.pef_config_info()

    def pef_checkout(self, section=None, filename=None, key=None):
        return self.handle.pef_checkout(section=section, filename=filename,
                                        key=key)

    def pef_commit(self, section=None, filename=None, key_value_pair=None):
        return self.handle.pef_commit(section=section, filename=filename,
                                        key_value_pair=key_value_pair)

    def pef_diff(self, section=None, filename=None, key=None):
        return self.handle.pef_diff(section=section, filename=filename,
                                        key=key)

    def pef_list_sections(self):
        return self.handle.pef_list_sections()

    def generate_generic_event(self, event_type):
        return self.handle.generic_event(event_type=event_type)

    def generate_sensor_event(self, sensor_id, state):
        return self.handle.assert_sensor_event(sensor_id=sensor_id,
                                               state=state)

    def get_watchdog_status(self):
        return self.handle.watchdog_get()

    def reset_watchdog(self):
        return self.handle.watchdog_reset()

    def disable_watchdog(self):
        return self.handle.watchdog_off()

    def fru_get_inventory(self):
        return self.handle.fru_print()

    def fru_read(self, fru_id, filename):
        return self.handle.fru_read(fru_id=fru_id, filename=filename)

    def fru_write(self, fru_id, filename):
        return self.handle.fru_write(fru_id=fru_id, filename=filename)

    def fru_upg_e_key(self, fru_id, filename):
        return self.handle.fru_upg_e_key(fru_id=fru_id, filename=filename)

    def fru_show(self, filename):
        return self.handle.fru_show(filename=filename)

    def lan_print(self, channel=None):
        return self.handle.lan_print(channel=channel)

    def lan_set(self, channel, command, param):
        return self.handle.lan_set(channel=channel, command=command,
                                   param=param)

    def channel_info(self):
        return self.handle.channel_info()

    def channel_get_access(self, channel, userid=""):
        return self.handle.channel_get_access(channel=channel, userid=userid)

    def channel_set_access(self, channel, userid, callin=None, ipmi=None,
                           link=None, priv_level=None):
        return self.handle.channel_set_access(channel=channel, userid=userid,
                                              callin=callin, ipmi=ipmi,
                                              link=link, priv_level=priv_level)

    def channel_get_ciphers(self, mode='ipmi'):
        return self.handle.channel_get_ciphers(mode=mode)

    def user_list(self, channel=None):
        return self.handle.user_list(channel=channel)

    def user_set_name(self, userid, name):
        return self.handle.user_set_name(userid=userid, name=name)

    def user_set_password(self, userid, password=None):
        return self.handle.user_set_password(userid=userid, password=password)

    def user_enable(self, userid):
        return self.handle.user_enable(userid=userid)

    def user_disable(self, userid):
        return self.handle.user_disable(userid=userid)

    def user_priv(self, userid, priv_level, channel=None):
        return self.handle.user_priv(userid=userid, priv_level=priv_level,
                                     channel=channel)
    """Fabric commands

    In pyipmi/fabric.py, these commands are mapped to classes that
    are subclasses of the Command class. Those subclasses contain the
    string arguments that are run by pyipmi/ipmitool.py

    """
    def fabric_update_config(self):
        return self.handle.fabric_updateconfig()

    def fabric_get_node_id(self):
        return self.handle.fabric_getnodeid()

    def fabric_get_ip_addr(self, nodeid="", iface=""):
        return self.handle.fabric_getipaddr(nodeid=nodeid, iface=iface)

    def fabric_get_mac_addr(self, nodeid="", iface=0):
        return self.handle.fabric_getmacaddr(nodeid=nodeid, iface=iface)

    def fabric_get_linkspeed(self, link=None, actual=None):
        return self.handle.fabric_getlinkspeed(link=link, actual=actual)

    def fabric_get_linkstats(self, filename=None, tftp_addr=None, link=None):
        return self.handle.fabric_getlinkstats(
            filename=filename,
            tftp_addr=tftp_addr,
            link=link
        )

    def fabric_get_linkmap(self, filename, tftp_addr=None):
        return self.handle.fabric_getlinkmap(filename=filename,
                                             tftp_addr=tftp_addr)

    def fabric_get_routingtable(self, filename, tftp_addr=None):
        return self.handle.fabric_getroutingtable(filename=filename,
                                                  tftp_addr=tftp_addr)

    def fabric_get_depthchart(self, filename, tftp_addr=None):
        return self.handle.fabric_getdepthchart(filename=filename,
                                                tftp_addr=tftp_addr)

    def fabric_add_macaddr(self, iface, macaddr, nodeid=None):
        return self.handle.fabric_addmacaddr(nodeid=nodeid, iface=iface, macaddr=macaddr)

    def fabric_rm_macaddr(self, iface, macaddr, nodeid=None):
        return self.handle.fabric_rmmacaddr(nodeid=nodeid, iface=iface, macaddr=macaddr)

    def fabric_get_uplink_speed(self):
        return self.handle.fabric_getuplinkspeed()

    def fabric_get_uplink_info(self):
        return self.handle.fabric_getuplinkinfo()

    def fabric_set_chassis_serial_num(self, serial):
        return self.handle.fabric_setchassisserialnum(serial=serial)

    def fabric_get_chassis_serial_num(self):
        return self.handle.fabric_getchassisserialnum()

    def fabric_get_uplink_status(self):
        return self.handle.fabric_get_uplink_status()

    """Fabric config commands

    In pyipmi/fabric_config.py, these commands are mapped to classes that
    are subclasses of the Command class. Those subclasses contain the
    string arguments that are run by pyipmi/ipmitool.py

    """
    def fabric_config_get_network_mac(self, mac):
        return self.handle.fabric_config_get_network_mac(mac=mac)

    def fabric_config_set_mac(self, mac, network):
        return self.handle.fabric_config_set_mac(mac=mac, network=network)

    def fabric_config_add_network(self, name, uplink=None, private=False):
        return self.handle.fabric_config_add_network(
            name=name,
            uplink=uplink,
            private=private
        )

    def fabric_config_rm_network(self, name, uplink=None):
        return self.handle.fabric_config_rm_network(name=name, uplink=uplink)

    def fabric_config_get_uplinks(self, filename, tftp_addr=None):
        return self.handle.fabric_config_get_uplinks(filename=filename,
                                            tftp_addr=tftp_addr)

    def fabric_config_get_networks(self, filename, tftp_addr=None):
        return self.handle.fabric_config_get_networks(filename=filename,
                                            tftp_addr=tftp_addr)

    def fabric_config_get_uplink_mode(self):
        return self.handle.fabric_config_get_uplink_mode()

    def fabric_config_set_uplink_mode(self, uplink_mode):
        return self.handle.fabric_config_set_uplink_mode(
            uplink_mode=uplink_mode
        )

    def fabric_config_update_config(self):
        return self.handle.fabric_config_updateconfig()

    def fabric_config_get_ip_info(self, filename, tftp_addr=None):
        return self.handle.fabric_config_getipinfo(filename=filename,
                                            tftp_addr=tftp_addr)

    def fabric_config_get_mac_addresses(self, filename, tftp_addr=None):
        return self.handle.fabric_config_getmacaddresses(filename=filename,
                                                  tftp_addr=tftp_addr)

    def fabric_config_get_uplink_info(self, filename, tftp_addr=None):
        return self.handle.fabric_config_getuplinkinfo(filename=filename,
                                                  tftp_addr=tftp_addr)

    def fabric_config_get_ip_src(self):
        return self.handle.fabric_config_getipsrc()

    def fabric_config_set_ip_src(self, ipsrc_mode):
        return self.handle.fabric_config_setipsrc(ipsrc_mode=ipsrc_mode)

    def fabric_config_factory_default(self):
        return self.handle.fabric_config_factory_default()

    def fabric_config_get_ip_addr_base(self):
        return self.handle.fabric_config_get_ipaddr_base()

    def fabric_config_set_ipaddr_base(self, ipaddr):
        return self.handle.fabric_config_set_ipaddr_base(ipaddr=ipaddr)

    def fabric_config_get_linkspeed(self):
        return self.handle.fabric_config_getlinkspeed()

    def fabric_config_set_linkspeed(self, linkspeed):
        return self.handle.fabric_config_setlinkspeed(linkspeed=linkspeed)

    def fabric_config_get_linkspeed_policy(self):
        return self.handle.fabric_config_getlinkspeedpolicy()

    def fabric_config_set_linkspeed_policy(self, ls_policy):
        return self.handle.fabric_config_setlinkspeedpolicy(ls_policy=ls_policy)

    def fabric_config_get_uplink(self, iface=0):
        return self.handle.fabric_config_getuplink(iface=iface)

    def fabric_config_set_uplink(self, uplink=0, iface=0):
        return self.handle.fabric_config_setuplink(uplink=uplink, iface=iface)

    def fabric_config_get_link_users_factor(self):
        return self.handle.fabric_config_getlinkusersfactor()

    def fabric_config_set_link_users_factor(self, lu_factor):
        return self.handle.fabric_config_setlinkusersfactor(lu_factor=lu_factor)

    def fabric_config_set_macaddr_base(self, macaddr):
        return self.handle.fabric_config_set_macaddr_base(macaddr=macaddr)

    def fabric_config_get_macaddr_base(self):
        return self.handle.fabric_config_get_macaddr_base()

    def fabric_config_set_macaddr_mask(self, mask):
        return self.handle.fabric_config_set_macaddr_mask(mask=mask)

    def fabric_config_get_macaddr_mask(self):
        return self.handle.fabric_config_get_macaddr_mask()

    def fabric_config_set_netmask(self, netmask):
        return self.handle.fabric_config_set_netmask(netmask=netmask)

    def fabric_config_set_defgw(self, ipaddr):
        return self.handle.fabric_config_set_defgw(ipaddr=ipaddr)

    def fabric_config_set_nodenum_offset(self, offset):
        return self.handle.fabric_config_set_nodenum_offset(offset=offset)

    def fabric_config_add_sc_route(self, node_start, node_end, guardian_node_id):
        return self.handle.fabric_config_add_sc_route(
                node_start=node_start, node_end=node_end, via=guardian_node_id)

    def fabric_config_get_sc_discovery(self, filename, tftp_addr=None):
        return self.handle.fabric_config_get_sc_discovery(
            filename=filename, tftp_addr=tftp_addr)

    def set_bootdev(self, device, options=None):
        return self.handle.bootdev_set(device=device, options=options)

    def get_bootdev(self):
        return self.handle.bootdev_get()

    def get_bootparam(self, param):
        return self.handle.bootparam_get(param=param)

    def mc_reset(self, mode):
        return self.handle.mc_reset(mode=mode)

    def mem_read(self, length, address, fmt=None):
        return self.handle.data_memread(length=length, addr=address,
                                        fmt=fmt)

    def mem_write(self, length, address, value):
        return self.handle.data_memwrite(length=length, addr=address,
                                         value=value)

    def cdb_read(self, length, cid, fmt=None):
        return self.handle.data_cdbread(length=length, cid=cid,
                                        fmt=fmt)

    def cdb_write(self, length, cid, value):
        return self.handle.data_cdbwrite(length=length, cid=cid,
                                         value=value)

    def get_info_basic(self):
        return self.handle.info_basic()

    def get_info_card(self):
        return self.handle.info_card()

    #
    # fabric info commands
    #

    def fabric_info_get_routing_table(self, filename, tftp_addr=None):
        return self.handle.fabric_info_getroutingtable(filename=filename,
                                                       tftp_addr=tftp_addr)

    def fabric_info_get_link_map(self, filename, tftp_addr=None):
        return self.handle.fabric_info_getlinkmap(filename=filename,
                                                  tftp_addr=tftp_addr)

    def fabric_info_get_depth_chart(self, filename, tftp_addr=None):
        return self.handle.fabric_info_getdepthchart(filename=filename,
                                                     tftp_addr=tftp_addr)

    def fabric_info_partition_config(self, filename, tftp_addr=None):
        return self.handle.fabric_info_partition_config(filename=filename,
                                                        tftp_addr=tftp_addr)

    def pmic_get_version(self):
        return self.handle.pmic_get_version()

class LanBMC(BMC):
    """A BMC that's accessed over the LAN"""
    def __init__(self,
                    hostname,
                    username=None,
                    password=None,
                    authtype=None,
                    level=None,
                    port=623,
                    interface='lan',
                    **kwargs):

        self.params = {
            'hostname' : hostname,
            'username' : username,
            'password' : password,
            'authtype' : authtype,
            'level'    : level,
            'port'     : port,
            'interface' : interface
        }

        super(LanBMC, self).__init__(**kwargs)


text:
namespace tensorflow {

auto pad_shape_fun = [](::tensorflow::shape_inference::InferenceContext* c) {
  auto top_shape = c->input(0);
  TF_RETURN_IF_ERROR(c->ReplaceDim(top_shape, 2, c->UnknownDim(), &top_shape));
  c->set_output(0, top_shape);
  return Status::OK();
};

REGISTER_OP("OctreePad")
    .Input("btm_data: float")
    .Input("octree: int8")
    .Attr("depth: int")
    .Attr("dval: float = 0.0")
    .Output("top_data: float")
    .SetShapeFn(pad_shape_fun)
    .Doc(R"doc(Octree padding operator.)doc");

REGISTER_OP("OctreeDepad")
    .Input("top_data: float")
    .Input("octree: int8")
    .Attr("depth: int")
    .Output("btm_data: float")
    .SetShapeFn(pad_shape_fun)
    .Doc(R"doc(Octree depadding operator.)doc");

class OctreePadBase : public OpKernel {
 public:
  explicit OctreePadBase(OpKernelConstruction* context)
    : OpKernel(context) {
    OP_REQUIRES_OK(context, context->GetAttr("depth", &depth_));
    CHECK_GE(depth_, 1) << "Depth should be larger than 1";
  }

  void set_octree_parser(OpKernelContext* context, OctreeParser& octree_) {
    auto octree_ptr = context->input(1).flat<int8>().data();
    octree_.set_gpu(octree_ptr);
  }

 protected:
  int depth_;
};

class OctreePadOp : public OctreePadBase {
 public:
  explicit OctreePadOp(OpKernelConstruction* context)
    : OctreePadBase(context) {
    OP_REQUIRES_OK(context, context->GetAttr("dval", &dval_));
  }

  void Compute(OpKernelContext* context) override {
    // in octree
    OctreeParser octree_;
    this->set_octree_parser(context, octree_);

    // btm data
    const Tensor& btm_data = context->input(0);
    const TensorShape& btm_shape = btm_data.shape();
    auto btm_ptr = btm_data.flat<float>().data();
    int channel = btm_shape.dim_size(1);
    int btm_h = btm_shape.dim_size(2);

    // check
    int depth = this->depth_;
    CHECK_EQ(octree_.info().node_num_nempty(depth), btm_h)
        << ", pad, d = " << depth << ", channel = " << channel;

    // top data
    TensorShape top_shape = btm_shape;
    int top_h = octree_.info().node_num(depth);
    top_shape.set_dim(2, top_h);
    Tensor* top_data = nullptr;
    OP_REQUIRES_OK(context, context->allocate_output(0, top_shape, &top_data));
    auto top_ptr = top_data->flat<float>().data();

    // padding data
    pad_forward_gpu(top_ptr, top_h, channel,
        btm_ptr, btm_h, octree_.children_gpu(depth), dval_);
  }

 protected:
  float dval_;
};

class OctreeDepadOp : public OctreePadBase {
 public:
  explicit OctreeDepadOp(OpKernelConstruction* context)
    : OctreePadBase(context) {}

  void Compute(OpKernelContext* context) override {
    // in octree
    OctreeParser octree_;
    this->set_octree_parser(context, octree_);

    // top grad
    const Tensor& top_data = context->input(0);
    const TensorShape& top_shape = top_data.shape();
    auto top_ptr = top_data.flat<float>().data();
    int channel = top_shape.dim_size(1);
    int top_h = top_shape.dim_size(2);

    // check
    int depth = this->depth_;
    CHECK_EQ(octree_.info().node_num(depth), top_h)
        << ", depad, d = " << depth << ", channel = " << channel;

    // btm grad
    TensorShape btm_shape = top_shape;
    int btm_h = octree_.info().node_num_nempty(depth);
    btm_shape.set_dim(2, btm_h);
    Tensor* btm_data = nullptr;
    OP_REQUIRES_OK(context, context->allocate_output(0, btm_shape, &btm_data));
    auto btm_ptr = btm_data->flat<float>().data();

    // padding data
    pad_backward_gpu(btm_ptr, btm_h, channel,
        top_ptr, top_h, octree_.children_gpu(depth));
  }
};

REGISTER_KERNEL_BUILDER(Name("OctreePad").Device(DEVICE_GPU), OctreePadOp);
REGISTER_KERNEL_BUILDER(Name("OctreeDepad").Device(DEVICE_GPU), OctreeDepadOp);

}  // namespace tensorflow


text:
module.exports = {
  name: 'CollapseSideMenu',
  type: 'checkbox',
  default: false,
  section: 'general',
  title: 'Collapsable Side Menu',
  description: 'Adds a button that can collapse the menu on the left so you can see more of your accounts or budget data.'
};


text:
<?php
$title = "FAQs";
include "inc/header.php";
?>

What is Magnificent?

Magnificent is an Austin, TX based marketing agency servicing the publishing industry.

Why would I want to convert PDFs to WordPress?

Many of our clients have piles of PDFed content (such as magazines, instructional texts, and historically-significant documents) that they publish to their blog for mobile-friendly, accessible-from-anywhere, easy-access by all. That's where we come in.

How can I contact you guys if I need help?

You can contact our support staff here.

<?php include "inc/footer.php"; ?>


text: ({"pageBreak":"Salt de pàgina"})


text:
using System;
using System.ComponentModel;

namespace Azure.ResourceManager.Relay.Models
{
    /// <summary> Name of this SKU. </summary>
    public readonly partial struct RelaySkuName : IEquatable<RelaySkuName>
    {
        private readonly string _value;

        /// <summary> Initializes a new instance of <see cref="RelaySkuName"/>. </summary>
        /// <exception cref="ArgumentNullException"> <paramref name="value"/> is null. </exception>
        public RelaySkuName(string value)
        {
            _value = value ?? throw new ArgumentNullException(nameof(value));
        }

        private const string StandardValue = "Standard";

        /// <summary> Standard. </summary>
        public static RelaySkuName Standard { get; } = new RelaySkuName(StandardValue);
        /// <summary> Determines if two <see cref="RelaySkuName"/> values are the same. </summary>
        public static bool operator ==(RelaySkuName left, RelaySkuName right) => left.Equals(right);
        /// <summary> Determines if two <see cref="RelaySkuName"/> values are not the same. </summary>
        public static bool operator !=(RelaySkuName left, RelaySkuName right) => !left.Equals(right);
        /// <summary> Converts a string to a <see cref="RelaySkuName"/>. </summary>
        public static implicit operator RelaySkuName(string value) => new RelaySkuName(value);

        /// <inheritdoc />
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override bool Equals(object obj) => obj is RelaySkuName other && Equals(other);
        /// <inheritdoc />
        public bool Equals(RelaySkuName other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase);

        /// <inheritdoc />
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override int GetHashCode() => _value?.GetHashCode() ?? 0;
        /// <inheritdoc />
        public override string ToString() => _value;
    }
}