text:
#include "cpl_port.h"
#include "gmlreader.h"
#include "gmlreaderp.h"

#include <cstddef>
#include <cstring>

#include "cpl_conv.h"
#include "cpl_error.h"
#include "cpl_http.h"
#include "cpl_minixml.h"
#include "cpl_string.h"

CPL_CVSID("$Id: resolvexlinks.cpp 002b050d9a9ef403a732c1210784736ef97216d4 2018-04-09 21:34:55 +0200 Even Rouault $")

/************************************************************************/
/*                              GetID()                                 */
/*                                                                      */
/*      Returns the reference to the gml:id of psNode. NULL if not      */
/*      found.                                                          */
/************************************************************************/

static const char *GetID( CPLXMLNode *psNode )

{
    if( psNode == nullptr )
        return nullptr;

    for( CPLXMLNode *psChild = psNode->psChild;
         psChild != nullptr;
         psChild = psChild->psNext )
    {
        if( psChild->eType == CXT_Attribute &&
            EQUAL(psChild->pszValue, "gml:id") )
        {
            return psChild->psChild->pszValue;
        }
    }
    return nullptr;
}

/************************************************************************/
/*                       CompareNodeIDs()                               */
/*                                                                      */
/*      Compares two nodes by their IDs                                 */
/************************************************************************/

/*static int CompareNodeIDs( CPLXMLNode * psNode1, CPLXMLNode * psNode2 )

{
    if( psNode2 == NULL )
        return TRUE;

    if( psNode1 == NULL )
        return FALSE;

    return strcmp( GetID(psNode2), GetID(psNode1) ) > 0;
}*/

/************************************************************************/
/*                       BuildIDIndex()                                 */
/*                                                                      */
/*      Returns an array of nodes sorted by their gml:id strings        */
/*      XXX: This method can be used to build an array of pointers to   */
/*      nodes sorted by their id values.                                */
/************************************************************************/
/*
static std::vector<CPLXMLNode*> BuildIDIndex( CPLXMLNode* psNode,
                                   std::vector<CPLXMLNode*> &apsNode )

{
    for( CPLXMLNode *psSibling = psNode;
         psSibling != NULL;
         psSibling = psSibling->psNext )
    {
        if( GetID( psSibling ) != NULL )
            apsNode.push_back( psSibling );
        BuildIDIndex( psNode->psChild, apsNode );
    }
    return NULL;
}*/

/************************************************************************/
/*                          FindElementByID()                           */
/*                                                                      */
/*      Find a node with the indicated "gml:id" in the node tree and    */
/*      its siblings.                                                   */
/************************************************************************/

static CPLXMLNode *FindElementByID( CPLXMLNode *psRoot, const char *pszID )

{
    if( psRoot == nullptr )
        return nullptr;

    // Check for id attribute.
    for( CPLXMLNode *psSibling = psRoot;
         psSibling != nullptr;
         psSibling = psSibling->psNext )
    {
        if( psSibling->eType == CXT_Element )
        {
            // check that sibling for id value
            const char *pszIDOfSibling = GetID(psSibling);
            if( pszIDOfSibling != nullptr && EQUAL( pszIDOfSibling, pszID) )
                return psSibling;
        }
    }

    // Search the child elements of all the psRoot's siblings.
    for( CPLXMLNode *psSibling = psRoot;
         psSibling != nullptr;
         psSibling = psSibling->psNext )
    {
        if( psSibling->eType == CXT_Element )
        {
            CPLXMLNode *psReturn = FindElementByID(psSibling->psChild, pszID);
            if( psReturn != nullptr )
                return psReturn;
        }
    }
    return nullptr;
}

/************************************************************************/
/*                          RemoveIDs()                                 */
/*                                                                      */
/*      Remove all the gml:id nodes. Doesn't check psRoot's siblings    */
/************************************************************************/

static void RemoveIDs( CPLXMLNode *psRoot )

{
    if( psRoot == nullptr )
        return;

    CPLXMLNode *psChild = psRoot->psChild;

    // Check for id attribute.
    while( psChild != nullptr &&
           !(psChild->eType == CXT_Attribute &&
             EQUAL(psChild->pszValue, "gml:id")) )
        psChild = psChild->psNext;
    CPLRemoveXMLChild(psRoot, psChild);
    CPLDestroyXMLNode(psChild);

    // Search the child elements of psRoot.
    for( psChild = psRoot->psChild; psChild != nullptr; psChild = psChild->psNext )
        if( psChild->eType == CXT_Element )
            RemoveIDs(psChild);
}

/************************************************************************/
/*                          TrimTree()                                  */
/*                                                                      */
/*      Remove all nodes without a gml:id node in the descendants.      */
/*      Returns TRUE if there is a gml:id node in the descendants.      */
/************************************************************************/

static bool TrimTree( CPLXMLNode *psRoot )

{
    if( psRoot == nullptr )
        return false;

    CPLXMLNode *psChild = psRoot->psChild;

    // Check for id attribute.
    while( psChild != nullptr &&
           !(psChild->eType == CXT_Attribute &&
             EQUAL(psChild->pszValue, "gml:id")) )
        psChild = psChild->psNext;

    if( psChild != nullptr )
        return true;

    // Search the child elements of psRoot.
    bool bReturn = false;
    for( psChild = psRoot->psChild; psChild != nullptr;)
    {
        CPLXMLNode *psNextChild = psChild->psNext;
        if( psChild->eType == CXT_Element )
        {
            const bool bRemove = TrimTree(psChild);
            if( bRemove )
            {
                bReturn = bRemove;
            }
            else
            {
                // Remove this child.
                CPLRemoveXMLChild(psRoot, psChild);
                CPLDestroyXMLNode(psChild);
            }
        }

        psChild = psNextChild;
    }
    return bReturn;
}

/************************************************************************/
/*                          CorrectURLs()                               */
/*                                                                      */
/*  Processes the node and all its children recursively. Siblings of   */
/*  psRoot are ignored.                                                 */
/*  - Replaces all every URL in URL#id pairs with pszURL.               */
/*  - Leaves it alone if the paths are same or the URL is not relative. */
/*  - If it is relative, the path from pszURL is prepended.             */
/************************************************************************/

static void CorrectURLs( CPLXMLNode *psRoot, const char *pszURL )

{
    if( psRoot == nullptr || pszURL == nullptr )
        return;
    if( pszURL[0] == '\0' )
        return;

    CPLXMLNode *psChild = psRoot->psChild;

    // Check for xlink:href attribute.
    while( psChild != nullptr &&
           !((psChild->eType == CXT_Attribute) &&
             (EQUAL(psChild->pszValue, "xlink:href"))) )
        psChild = psChild->psNext;

    if( psChild != nullptr &&
        !(strstr(psChild->psChild->pszValue, pszURL) ==
              psChild->psChild->pszValue &&
          psChild->psChild->pszValue[strlen(pszURL)] == '#') )
    {
        // href has a different url.
        if( psChild->psChild->pszValue[0] == '#' )
        {
            // Empty URL: prepend the given URL.
            const size_t nLen = CPLStrnlen(pszURL, 1024) +
                                CPLStrnlen(psChild->psChild->pszValue, 1024) +
                                1;
            char *pszNew = static_cast<char *>(CPLMalloc(nLen * sizeof(char)));
            CPLStrlcpy(pszNew, pszURL, nLen);
            CPLStrlcat(pszNew, psChild->psChild->pszValue, nLen);
            CPLSetXMLValue(psRoot, "#xlink:href", pszNew);
            CPLFree(pszNew);
        }
        else
        {
            size_t nPathLen = strlen(pszURL);  // Used after for.
            for( ;
                 nPathLen > 0 &&
                 pszURL[nPathLen - 1] != '/' &&
                 pszURL[nPathLen - 1] != '\\';
                 nPathLen-- )
                {}

            const char *pszDash = strchr(psChild->psChild->pszValue, '#');
            if( pszDash != nullptr &&
                strncmp(pszURL, psChild->psChild->pszValue, nPathLen) != 0 )
            {
                // Different path.
                const int nURLLen =
                    static_cast<int>(pszDash - psChild->psChild->pszValue);
                char *pszURLWithoutID = static_cast<char *>(
                    CPLMalloc((nURLLen + 1) * sizeof(char)));
                strncpy(pszURLWithoutID, psChild->psChild->pszValue, nURLLen);
                pszURLWithoutID[nURLLen] = '\0';

                if( CPLIsFilenameRelative(pszURLWithoutID) &&
                    strstr(pszURLWithoutID, ":") == nullptr )
                {
                    // Relative URL: prepend the path of pszURL.
                    const size_t nLen =
                        nPathLen +
                        CPLStrnlen(psChild->psChild->pszValue, 1024) + 1;
                    char *pszNew =
                        static_cast<char *>(CPLMalloc(nLen * sizeof(char)));
                    for( size_t i = 0; i < nPathLen; i++ )
                        pszNew[i] = pszURL[i];
                    pszNew[nPathLen] = '\0';
                    CPLStrlcat(pszNew, psChild->psChild->pszValue, nLen);
                    CPLSetXMLValue(psRoot, "#xlink:href", pszNew);
                    CPLFree(pszNew);
                }
                CPLFree(pszURLWithoutID);
            }
        }
    }

    // Search the child elements of psRoot.
    for( psChild = psRoot->psChild; psChild != nullptr; psChild = psChild->psNext)
        if( psChild->eType == CXT_Element )
            CorrectURLs(psChild, pszURL);
}

/************************************************************************/
/*                          FindTreeByURL()                             */
/*                                                                      */
/*  Find a doc tree that is located at pszURL.                          */
/*  If not present in ppapsRoot, it updates it and ppapszResourceHREF.  */
/************************************************************************/

static CPLXMLNode *FindTreeByURL( CPLXMLNode ***ppapsRoot,
                                  char ***ppapszResourceHREF,
                                  const char *pszURL )

{
    if( *ppapsRoot == nullptr || ppapszResourceHREF == nullptr )
        return nullptr;

    // If found in ppapszResourceHREF.
    const int i = CSLFindString(*ppapszResourceHREF, pszURL);
    if( i >= 0 )
    {
        // Return corresponding psRoot.
        return (*ppapsRoot)[i];
    }

    CPLXMLNode *psSrcTree = nullptr;
    char *pszLocation = CPLStrdup(pszURL);
    // If it is part of filesystem.
    if( CPLCheckForFile( pszLocation, nullptr) )
    {
        // Filesystem.
        psSrcTree = CPLParseXMLFile(pszURL);
    }
    else if( CPLHTTPEnabled() )
    {
        // Web resource.
        CPLErrorReset();
        CPLHTTPResult *psResult = CPLHTTPFetch(pszURL, nullptr);
        if( psResult != nullptr )
        {
            if( psResult->nDataLen > 0 && CPLGetLastErrorNo() == 0)
                psSrcTree = CPLParseXMLString(reinterpret_cast<const char*>(psResult->pabyData));
            CPLHTTPDestroyResult( psResult );
        }
    }

    // Report error in case the resource cannot be retrieved.
    if( psSrcTree == nullptr )
        CPLError(CE_Failure, CPLE_NotSupported, "Could not access %s",
                 pszLocation);

    CPLFree(pszLocation);

/************************************************************************/
/*      In the external GML resource we will only need elements         */
/*      identified by a "gml:id". So trim them.                         */
/************************************************************************/
    CPLXMLNode *psSibling = psSrcTree;
    while( psSibling != nullptr )
    {
        TrimTree(psSibling);
        psSibling = psSibling->psNext;
    }

    // Update to lists.
    int nItems = CSLCount(*ppapszResourceHREF);
    *ppapszResourceHREF = CSLAddString(*ppapszResourceHREF, pszURL);
    *ppapsRoot = static_cast<CPLXMLNode **>(
        CPLRealloc(*ppapsRoot, (nItems + 2) * sizeof(CPLXMLNode *)));
    (*ppapsRoot)[nItems] = psSrcTree;
    (*ppapsRoot)[nItems + 1] = nullptr;

    // Return the tree.
    return (*ppapsRoot)[nItems];
}

/************************************************************************/
/*                           ResolveTree()                              */
/*  Resolves the xlinks in a node and its siblings                      */
/*  If any error is encountered or any element is skipped(papszSkip):   */
/*      If bStrict is TRUE, process is stopped and CE_Error is returned */
/*      If bStrict is FALSE, the process is continued but CE_Warning is */
/*       returned at the end.                                           */
/*  If everything goes fine, CE_None is returned.                       */
/************************************************************************/

static CPLErr Resolve( CPLXMLNode *psNode,
                       CPLXMLNode ***ppapsRoot,
                       char ***ppapszResourceHREF,
                       char **papszSkip,
                       const int bStrict,
                       int nDepth )

{
    // For each sibling.
    CPLXMLNode *psSibling = nullptr;
    CPLXMLNode *psResource = nullptr;
    CPLXMLNode *psTarget = nullptr;
    CPLErr eReturn = CE_None, eReturned;

    for( psSibling = psNode; psSibling != nullptr; psSibling = psSibling->psNext )
    {
        if( psSibling->eType != CXT_Element )
            continue;

        CPLXMLNode *psChild = psSibling->psChild;
        while( psChild != nullptr &&
               !( psChild->eType == CXT_Attribute &&
                  EQUAL(psChild->pszValue, "xlink:href") ) )
            psChild = psChild->psNext;

        // If a child has a "xlink:href" attribute.
        if( psChild != nullptr && psChild->psChild != nullptr )
        {
            if( CSLFindString(papszSkip, psSibling->pszValue) >= 0 )
            {
                // Skipping a specified element.
                eReturn = CE_Warning;
                continue;
            }

            const int nDepthCheck = 256;
            if( nDepth % nDepthCheck == 0 )
            {
                // A way to track progress.
                CPLDebug("GML",
                         "Resolving xlinks... (currently %s)",
                         psChild->psChild->pszValue);
            }

            char **papszTokens =
                CSLTokenizeString2(psChild->psChild->pszValue, "#",
                                   CSLT_ALLOWEMPTYTOKENS |
                                   CSLT_STRIPLEADSPACES |
                                   CSLT_STRIPENDSPACES);
            if( CSLCount(papszTokens) != 2 || papszTokens[1][0] == '\0' )
            {
                CPLError(bStrict ? CE_Failure : CE_Warning,
                         CPLE_NotSupported,
                         "Error parsing the href %s.%s",
                         psChild->psChild->pszValue,
                         bStrict ? "" : " Skipping...");
                CSLDestroy(papszTokens);
                if( bStrict )
                    return CE_Failure;
                eReturn = CE_Warning;
                continue;
            }

            // Look for the resource with that URL.
            psResource =
                FindTreeByURL(ppapsRoot, ppapszResourceHREF, papszTokens[0]);
            if( psResource == nullptr )
            {
                CSLDestroy(papszTokens);
                if( bStrict )
                    return CE_Failure;
                eReturn = CE_Warning;
                continue;
            }

            // Look for the element with the ID.
            psTarget = FindElementByID(psResource, papszTokens[1]);
            if( psTarget != nullptr )
            {
                // Remove the xlink:href attribute.
                CPLRemoveXMLChild(psSibling, psChild);
                CPLDestroyXMLNode(psChild);

                // Make a copy of psTarget.
                CPLXMLNode *psCopy =
                    CPLCreateXMLNode(nullptr, CXT_Element, psTarget->pszValue);
                psCopy->psChild = CPLCloneXMLTree(psTarget->psChild);
                RemoveIDs(psCopy);
                // Correct empty URLs in URL#id pairs.
                if( CPLStrnlen(papszTokens[0], 1) > 0 )
                {
                    CorrectURLs(psCopy, papszTokens[0]);
                }
                CPLAddXMLChild(psSibling, psCopy);
                CSLDestroy(papszTokens);
            }
            else
            {
                // Element not found.
                CSLDestroy(papszTokens);
                CPLError(bStrict ? CE_Failure : CE_Warning,
                         CPLE_ObjectNull,
                         "Couldn't find the element with id %s.",
                         psChild->psChild->pszValue);
                if( bStrict )
                    return CE_Failure;
                eReturn = CE_Warning;
            }
        }

        // Recurse with the first child.
        eReturned = Resolve(psSibling->psChild, ppapsRoot, ppapszResourceHREF,
                            papszSkip, bStrict, nDepth + 1);

        if( eReturned == CE_Failure )
            return CE_Failure;

        if( eReturned == CE_Warning )
            eReturn = CE_Warning;
    }
    return eReturn;
}

/************************************************************************/
/*                           ResolveXlinks()                            */
/*      Returns TRUE for success                                        */
/*    - Returns CE_None for success,                                    */
/*      CE_Warning if the resolved file is saved to a different file or */
/*      CE_Failure if it could not be saved at all.                     */
/*    - m_pszFilename will be set to the file the resolved file was     */
/*      saved to.                                                       */
/************************************************************************/

bool GMLReader::ResolveXlinks( const char *pszFile,
                               bool *pbOutIsTempFile,
                               char **papszSkip,
                               const bool bStrict )

{
    *pbOutIsTempFile = false;

    // Check if the original source file is set.
    if( m_pszFilename == nullptr )
    {
        CPLError(CE_Failure, CPLE_NotSupported,
                 "GML source file needs to be set first with "
                 "GMLReader::SetSourceFile().");
        return false;
    }

/* -------------------------------------------------------------------- */
/*      Load the raw XML file into a XML Node tree.                     */
/* -------------------------------------------------------------------- */
    CPLXMLNode **papsSrcTree =
        static_cast<CPLXMLNode **>(CPLCalloc(2, sizeof(CPLXMLNode *)));
    papsSrcTree[0] = CPLParseXMLFile(m_pszFilename);

    if( papsSrcTree[0] == nullptr )
    {
        CPLFree(papsSrcTree);
        return false;
    }

    // Make all the URLs absolute.
    CPLXMLNode *psSibling = nullptr;
    for( psSibling = papsSrcTree[0]; psSibling != nullptr;
         psSibling = psSibling->psNext )
        CorrectURLs(psSibling, m_pszFilename);

    // Setup resource data structure.
    char **papszResourceHREF = nullptr;
    // "" is the href of the original source file.
    papszResourceHREF = CSLAddString(papszResourceHREF, m_pszFilename);

    // Call resolver.
    const CPLErr eReturned = Resolve(papsSrcTree[0], &papsSrcTree,
                                     &papszResourceHREF, papszSkip, bStrict, 0);

    bool bReturn = true;
    if( eReturned != CE_Failure )
    {
        char *pszTmpName = nullptr;
        bool bTryWithTempFile = false;
        if( STARTS_WITH_CI(pszFile, "/vsitar/") ||
            STARTS_WITH_CI(pszFile, "/vsigzip/") ||
            STARTS_WITH_CI(pszFile, "/vsizip/") )
        {
            bTryWithTempFile = true;
        }
        else if( !CPLSerializeXMLTreeToFile(papsSrcTree[0], pszFile) )
        {
            CPLError(CE_Failure, CPLE_FileIO,
                     "Cannot serialize resolved file %s to %s.",
                     m_pszFilename, pszFile);
            bTryWithTempFile = true;
        }

        if (bTryWithTempFile)
        {
            pszTmpName = CPLStrdup(CPLGenerateTempFilename("ResolvedGML"));
            if( !CPLSerializeXMLTreeToFile(papsSrcTree[0], pszTmpName) )
            {
                CPLError(CE_Failure, CPLE_FileIO,
                         "Cannot serialize resolved file %s to %s either.",
                         m_pszFilename, pszTmpName);
                CPLFree(pszTmpName);
                bReturn = false;
            }
            else
            {
                // Set the source file to the resolved file.
                CPLFree(m_pszFilename);
                m_pszFilename = pszTmpName;
                *pbOutIsTempFile = true;
            }
        }
        else
        {
            // Set the source file to the resolved file.
            CPLFree(m_pszFilename);
            m_pszFilename = CPLStrdup(pszFile);
        }
    }
    else
    {
        bReturn = false;
    }

    const int nItems = CSLCount(papszResourceHREF);
    CSLDestroy(papszResourceHREF);
    for(int i = 0; i < nItems; i++)
        CPLDestroyXMLNode(papsSrcTree[i]);
    CPLFree(papsSrcTree);

    return bReturn;
}


text:
package com.intellij.internal.statistic.service.fus;

import com.intellij.internal.statistic.connect.StatServiceException;
import com.intellij.internal.statistic.service.ConfigurableStatisticsService;
import com.intellij.internal.statistic.service.fus.beans.FSContent;
import com.intellij.internal.statistic.service.fus.collectors.FUStatisticsAggregator;
import com.intellij.internal.statistic.service.fus.collectors.FUStatisticsPersistence;
import com.intellij.internal.statistic.service.fus.collectors.FUStatisticsStateService;
import com.intellij.openapi.application.ex.ApplicationManagerEx;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.util.io.HttpRequests;
import org.jetbrains.annotations.NotNull;

import java.net.HttpURLConnection;
import java.util.Set;

public class FUStatisticsService extends ConfigurableStatisticsService<FUStatisticsSettingsService> {
  private static final Logger LOG = Logger.getInstance("com.intellij.internal.statistic.service.whiteList.FUStatisticsService");

  private static final FUStatisticsSettingsService mySettingsService = FUStatisticsSettingsService.getInstance();
  private static final FUStatisticsAggregator myAggregator = FUStatisticsAggregator.create();

  @Override
  @NotNull
  protected String sendData() {
    String serviceUrl = mySettingsService.getServiceUrl();
    if (serviceUrl == null) {
      throw new StatServiceException("Unknown Statistics Server URL");
    }

    Set<String> approvedGroups = mySettingsService.getApprovedGroups();
    if (approvedGroups.isEmpty() && !ApplicationManagerEx.getApplicationEx().isInternal()) {
        throw new StatServiceException("There are no approved collectors or Statistics White List Service is unavailable.");
    }
    FSContent allDataFromCollectors = myAggregator.getUsageCollectorsData(approvedGroups);
    if (allDataFromCollectors == null) {
      throw new StatServiceException("There are no data from collectors to send");
    }

    try {
      String dataToSend = FUStatisticsStateService.create().getMergedDataToSend(allDataFromCollectors.asJsonString(), approvedGroups);
      if (dataToSend == null) {
        throw new StatServiceException("There are no data from collectors to send");
      }

      HttpRequests.post(serviceUrl, HttpRequests.JSON_CONTENT_TYPE)
                  .isReadResponseOnError(true)
                  .connect(request -> {
                    request.write(dataToSend);
                    if (LOG.isDebugEnabled()) {
                      String message = request.readString();
                      if (message.isEmpty()) {
                        LOG.debug(Integer.toString(((HttpURLConnection)request.getConnection()).getResponseCode()));
                      }
                      else {
                        LOG.debug(message);
                      }
                    }
                    return null;
                  });

      FUStatisticsPersistence.clearSessionPersistence(System.currentTimeMillis());
      FUStatisticsPersistence.clearLegacyStates();
      FUStatisticsPersistence.persistSentData(dataToSend);
      FUStatisticsPersistence.persistDataFromCollectors(allDataFromCollectors.asJsonString());

      return dataToSend;
    }
    catch (HttpRequests.HttpStatusException e) {
      String responseMessage = e.getMessage();
      LOG.info(responseMessage);
      throw new StatServiceException("Error during data sending. \n " + responseMessage);
    }
    catch (Exception e) {
      LOG.info(e);
      throw new StatServiceException("Error during data sending.", e);
    }
  }

  @Override
  public FUStatisticsSettingsService getConnectionService() {
    return mySettingsService;
  }
}

redpajama_set_name: RedPajamaGithub


text:
from __future__ import division
import numpy
import itertools
from cogent.core.tree import TreeBuilder
from cogent.phylo.tree_collection import ScoredTreeCollection
from cogent.util import parallel, checkpointing, progress_display as UI

__author__ = "Peter Maxwell"
__copyright__ = "Copyright 2007-2012, The Cogent Project"
__credits__ = ["Peter Maxwell"]
__license__ = "GPL"
__version__ = "1.5.3"
__maintainer__ = "Peter Maxwell"
__email__ = "pm67nz@gmail.com"
__status__ = "Production"

def ismallest(data, size):
    """There are many ways to get the k smallest items from an N sequence, and
    which one performs best depends on k, N and k/N.  This algorithm appears to
    beat anything heapq can do, and stays with a factor of 2 of sort() and
    min().  Is uses memory O(2*k) and so is particularly suitable for lazy
    application to large N.  It returns the smallest k sorted too."""
    limit = 2 * size
    data = iter(data)
    best = list(itertools.islice(data, limit))
    while True:
        best.sort()
        if len(best) <= size:
            break
        del best[size:]
        worst_of_best = best[-1]
        for item in data:
            if item < worst_of_best:
                best.append(item)
                if len(best) > limit:
                    break
    return best

# Trees are represented as "ancestry" matricies in which A[i,j] iff j is an
# ancestor of i.  For LS calculations the ancestry matrix is converted
# to a "paths" matrix or "split metric" in which S[p,j] iff the path between
# the pth pair of tips passes through edge j.  For ML calculations the
# ancestry matrix is converted back into an ordinary cogent tree object.

def tree2ancestry(tree, order=None):
    nodes = tree.unrooted().getEdgeVector()[:-1]
    if order is not None:
        lookup = dict([(k,i) for (i,k) in enumerate(order)])
        def _ordered_tips_first(n):
            if n.Children:
                return len(order)
            else:
                return lookup[n.Name]
        nodes.sort(key=_ordered_tips_first)

    n = len(nodes)
    A = numpy.zeros([n, n], int)
    seen = {}
    for (i, node) in enumerate(nodes):
        A[i, i] = 1
        seen[id(node)] = i
        for c in node.Children:
            A[:,i] |= A[:,seen[id(c)]]
    names = [n.Name for n in nodes if not n.Children]
    lengths = [n.Length for n in nodes]
    return (A, names, lengths)

def ancestry2tree(A, lengths, tip_names):
    """Convert edge x edge ancestry matrix to a cogent Tree object"""
    tips = {}
    tip = 0
    for i in range(len(A)):
        if numpy.sum(A[:,i]) == 1:
            tips[i] = tip_names[tip]
            tip += 1
    assert tip == len(tip_names)

    constructor = TreeBuilder().createEdge
    free = {}
    for i in numpy.argsort(numpy.sum(A, axis=0)):
        children = [j for j in range(len(A)) if A[j, i] and j != i]
        child_nodes = [free.pop(j) for j in children if j in free]
        if child_nodes:
            name = None
        else:
            name = tips[i]
        if lengths is None:
            params = {}
        else:
            params = {'length':lengths[i]}
        node = constructor(child_nodes, name, params)
        free[i] = node
    return constructor(free.values(), 'root', {})

def grown(B, split_edge):
    """Ancestry matrix 'B' with one extra leaf added at 'split_edge'.
    Row/column order within the matrix is independent of the topology it
    represents. The added leaf will be the last one in the matrix, which keeps
    the leaf node order the same as the order in which they are added, which is
    what is assumed by ancestry2tree and ancestry2paths"""
    n = len(B)
    A = numpy.zeros([n+2, n+2], int)
    A[:n, :n] = B
    (sibling, parent) = (n, n + 1)
    A[sibling] = A[parent] = A[split_edge]
    A[:,parent] = A[:,split_edge]
    A[sibling,split_edge] = 0
    A[parent, split_edge] = 0
    A[sibling,sibling] = 1
    A[parent,parent] = 1
    A[sibling,parent] = 1
    A[split_edge,parent] = 1
    return A

class TreeEvaluator(object):
    """Subclass must provide makeTreeScorer and result2output"""

    def results2output(self, results):
        return ScoredTreeCollection(results)

    def evaluateTopology(self, tree):
        """Optimal (score, tree) for the one topology 'tree'"""
        (ancestry, names, lengths) = tree2ancestry(tree)
        evaluate = self.makeTreeScorer(names)
        (err, lengths) = evaluate(ancestry)
        return self.result2output(err, ancestry, lengths, names)

    def evaluateTree(self, tree):
        """score for 'tree' with lengths as-is"""
        (ancestry, names, lengths) = tree2ancestry(tree)
        evaluate = self.makeTreeScorer(names)
        (err, result) = evaluate(ancestry, lengths=lengths)
        return err

    def _consistentNameOrder(self, fixed_names, ordered_names=None):
        """fixed_names followed by ordered_names without duplicates"""
        all_names = set(self.names)

        fixed_names_set = set(fixed_names)
        assert fixed_names_set.issubset(all_names)

        if ordered_names:
            assert set(ordered_names).issubset(all_names)
        else:
            ordered_names = self.names
        names = list(fixed_names) + [n for n in ordered_names
                if n not in fixed_names_set]
        return names

    @UI.display_wrap
    def trex(self, a=8, k=1000, start=None, order=None, return_all=False,
            filename=None, interval=None, ui=None):
        """TrexML policy for tree sampling - all trees up to size 'a' and
        then keep no more than 'k' best trees at each tree size.
        'order' is an optional list of tip names.
        'start' is an optional list of initial trees.  Each of the trees must
        contain the same tips.
        'filename' and 'interval' control checkpointing.

        Advanced step-wise addition algorithm
        M. J. Wolf, S. Easteal, M. Kahn, B. D. McKay, and L. S. Jermiin.
        Trexml: a maximum-likelihood approach for extensive tree-space
        exploration.
        Bioinformatics, 16(4):383 94, 2000."""

        checkpointer = checkpointing.Checkpointer(filename, interval)
        if checkpointer.available():
            (init_tree_size, fixed_names, trees) = checkpointer.load()
            names = self._consistentNameOrder(fixed_names, order)
        elif start is not None:
            if not isinstance(start, list):
                start = [start]
            fixed_names = start[0].getTipNames()
            names = self._consistentNameOrder(fixed_names, order)
            trees = []
            for tree in start:
                # check the start tree represents a subset of tips
                assert set(tree.getTipNames()) < set(self.names), \
                    "Starting tree names not a subset of the sequence names"

                (ancestry, fixed_names2, lengths) = tree2ancestry(
                        tree, order=fixed_names)
                assert fixed_names2 == fixed_names
                trees.append((None, None, ancestry))
            init_tree_size = len(fixed_names)
        else:
            trees = [(None, None, numpy.identity(3, int))]
            names = self._consistentNameOrder([], order)
            init_tree_size = 3

        tree_size = len(names)
        assert tree_size > 3
        if a > tree_size:
            a = tree_size
        if a < 4:
            a = 4

        # All trees of size a-1, no need to compare them
        for n in range(init_tree_size+1, a):
            trees2 = []
            for (err2, lengths2, ancestry) in trees:
                for split_edge in range(len(ancestry)):
                    ancestry2 = grown(ancestry, split_edge)
                    trees2.append((None, None, ancestry2))
            trees = trees2
            init_tree_size = n

        # Pre calculate how much work is to be done, for progress display
        tree_count = len(trees)
        total_work = 0
        work_done = [0] * (init_tree_size+1)
        for n in range(init_tree_size+1, tree_size+1):
            evals = tree_count * (n*2-5)
            total_work += evals * n
            tree_count = min(k, evals)
            work_done.append(total_work)

        # For each tree size, grow at each edge of each tree. Keep best k.
        for n in range(init_tree_size+1, tree_size+1):
            evaluate = self.makeTreeScorer(names[:n])

            def grown_tree(spec):
                (tree_ordinal, tree, split_edge) = spec
                (old_err, old_lengths, old_ancestry) = tree
                ancestry = grown(old_ancestry, split_edge)
                (err, lengths) = evaluate(ancestry)
                return (err, tree_ordinal, split_edge, lengths, ancestry)

            specs = [(i, tree, edge)
                        for (i,tree) in enumerate(trees)
                        for edge in range(n*2-5)]

            candidates = ui.imap(grown_tree, specs, noun=('%s leaf tree' % n),
                start=work_done[n-1]/total_work, end=work_done[n]/total_work)

            best = ismallest(candidates, k)

            trees = [(err, lengths, ancestry) for (err, parent_ordinal,
                    split_edge, lengths, ancestry) in best]

            checkpointer.record((n, names[:n], trees))

        results = (self.result2output(err, ancestry, lengths, names)
                    for (err, lengths, ancestry) in trees)
        if return_all:
            result = self.results2output(results)
        else:
            result = results.next()
        return result


text:
<?php

namespace Contributte\GopayInline\Api\Lists;

class RecurrenceState
{

	const REQUESTED = 'REQUESTED';
	const STARTED = 'STARTED';
	const STOPPED = 'STOPPED';

}


text:
package net.maizegenetics.dna.map;

/**
 * Container class for information on mapping position.

 * <p>
 * The mappingSource can be an identifier. Byte.MIN_VALUE means the tag doesn't exist (missing) in the mapping result. Other values means it exist in mapping result. The result could be either mapped or unmapped.
 *
 * Note: BWA doesn't provide mapping score, so the rank is just based on the order provided for multiple hits
 * Note: Currently, perfectMatch of PE is unknown (Byte.MIN_VALUE);
 *
 * @author edbuckler Fei Lu
 */
public class TagMappingInfoV3 {
    /** Chromosome as an integer, unknown = Integer.MIN_VALUE */
    public int chromosome=Integer.MIN_VALUE;  // 4 bytes
    /** Strand relative to reference genome. 1 = same sense as reference FASTA file.  -1 = opposite sense.  unknown = Byte.MIN_VALUE */
    public byte strand=Byte.MIN_VALUE;   // 1 byte
    /**Chromosomal position of the barcoded end of the tag, unknown = Integer.MIN_VALUE */
    public int startPosition=Integer.MIN_VALUE;  //   // 4 bytes
    /**Chromosomal position of the common adapter end of the tag (smaller than startPosition if tag matches minus strand), inclusive, unknown = Integer.MIN_VALUE */
    public int endPosition=Integer.MIN_VALUE;  //   // 4 bytes
    /**Number of diverging bp (edit distance) from reference, unknown = Byte.MIN_VALUE*/
    public byte divergence=Byte.MIN_VALUE;
    /**If the alignment is a perfect match to the reference, y = 1, n = 0, unknown = Byte.MIN_VALUE*/
    public byte perfectMatch = Byte.MIN_VALUE;
    /**Code of mappingSource.0: Bowtie2; 1: BWA; 2: BLAST; 3: BWAMEM; 4: PE one end; 5: PE the other end; 6: Genetic Mapping; missing = Byte.MIN_VALUE*/
    public byte mappingSource = Byte.MIN_VALUE;
    /**The rank of this mapping based on the scores from one aligner, starting from 0. If there are two 0, the rank of the third one is 1*/
    public byte mappingRank = Byte.MIN_VALUE;
    /**The mapping score of this mapping, unknown = Byte.MIN_VALUE*/
    public short mappingScore = Short.MIN_VALUE;
    /**Double cross-over probability Round(Log2(P)), unknown = Byte.MIN_VALUE */
    public byte dcoP=Byte.MIN_VALUE;
    /**Genetic mapping probability Round(Log2(P)), unknown= Byte.MIN_VALUE */
    public byte mapP=Byte.MIN_VALUE;  //Round(Log2(P)), unknown Byte.MIN_VALUE

    /**
     * MappingSource definition
     */
    public static enum Aligner {
        Bowtie2((byte)0, "Bowtie2"),
        BWA((byte)1, "BWA"),
        Blast((byte)2, "Blast"),
        BWAMEM((byte)3,"BWAMEM"),
        PEEnd1((byte)4, "PEEnd1"),
        PEEnd2((byte)5, "PEEnd2");
        private byte value;
        private String name;
        Aligner (byte mappingSource, String alignerName) {
            value = mappingSource;
            name = alignerName;
        }
        public byte getValue () {
            return value;
        }
        public String getName () {
            return name;
        }
        public static byte getValueFromName (String name) {
            if (name.equalsIgnoreCase(Bowtie2.name)) return Bowtie2.getValue();
            if (name.equalsIgnoreCase(BWA.name)) return BWA.getValue();
            if (name.equalsIgnoreCase(Blast.name)) return Blast.getValue();
            if (name.equalsIgnoreCase(BWAMEM.name)) return BWAMEM.getValue();
            if (name.equalsIgnoreCase(PEEnd1.name)) return PEEnd1.getValue();
            if (name.equalsIgnoreCase(PEEnd2.name)) return PEEnd2.getValue();
            return Byte.MIN_VALUE;
        }
        public static Aligner getAlignerFromName (String name) {
            if (name.equalsIgnoreCase(Bowtie2.name)) return Bowtie2;
            if (name.equalsIgnoreCase(BWA.name)) return BWA;
            if (name.equalsIgnoreCase(Blast.name)) return Blast;
            if (name.equalsIgnoreCase(BWAMEM.name)) return BWAMEM;
            if (name.equalsIgnoreCase(PEEnd1.name)) return PEEnd1;
            if (name.equalsIgnoreCase(PEEnd2.name)) return PEEnd2;
            return null;
        }
        public static Aligner getAlignerFromValue (byte value) {
            if (value == Bowtie2.getValue()) return Bowtie2;
            if (value == BWA.getValue()) return BWA;
            if (value == Blast.getValue()) return Blast;
            if (value == BWAMEM.getValue()) return BWAMEM;
            if (value == PEEnd1.getValue()) return PEEnd1;
            if (value == PEEnd2.getValue()) return PEEnd2;
            return null;
        }
    }

    public TagMappingInfoV3() {
    }

    public TagMappingInfoV3(int chromosome, byte strand, int startPosition, int endPosition, byte divergence, byte perfectMatch, byte mappingSource, short mappingScore) {
        this.chromosome=chromosome;
        this.strand=strand;
        this.startPosition=startPosition;
        this.endPosition=endPosition;
        this.divergence=divergence;
        this.perfectMatch = perfectMatch;
        this.mappingSource = mappingSource;
        this.mappingScore = mappingScore;
    }

    public TagMappingInfoV3(int chromosome, byte strand, int startPosition,
                int endPosition, byte divergence, byte perfectMatch, byte mappingSource, short mappingScore, byte[] variantPosOff, byte[] variantDef,
                byte dcoP, byte mapP) {
        this(chromosome, strand, startPosition, endPosition, divergence, perfectMatch, mappingSource, mappingScore);
        this.dcoP=dcoP;
        this.mapP=mapP;
    }

    public void setMappingRank (byte mappingRank) {
        this.mappingRank = mappingRank;
    }

    public void setMappingSource (byte mappingSource) {
        this.mappingSource = mappingSource;
    }
}


text:
(function() {
    "use strict";

    angular
        .module("app")
        .factory("AuthService", ["$firebaseAuth", "FIREBASE_URI", "$location", "locker",
            function ($firebaseAuth, FIREBASE_URI, $location, locker) {

                var ref = new Firebase(FIREBASE_URI)
                var auth = $firebaseAuth(ref);

                var service = this;

                service.login = function (email, password) {
                    return auth.$authWithPassword({
                        email: email,
                        password: password
                    });
                };

                service.register = function (email, password, first_name, last_name, zip_code) {
                    return auth.$createUser({
                        email: email,
                        password: password
                    }).then(function(authData) {
                        toastr.success("Registered successfully");
                        var profileRef = ref.child("users").child(authData.uid).child("profile");
                        profileRef.set({
                            email: email,
                            first_name: first_name,
                            last_name: last_name,
                            zip_code: zip_code
                        });
                        var email_to_keyRef = ref.child("emails_to_ids").child(emailToKey(email));
                        email_to_keyRef.set(authData.uid);
                    });
                };

                service.getAuth = function () {
                    return auth.$getAuth();
                };

                service.logout = function () {
                    auth.$unauth();
                    locker.forget("user");
                    locker.forget("currentUser");
                    $location.path("/login");
                };

                service.requireAuth = function () {
                    return auth.$requireAuth();
                };

                function emailToKey(emailAddress) {
                    return emailAddress.replace('.', ',');
                }

                return service;

            }]);
}());


text:
#ifndef _CLINK_MEDIA_MPEGFORMT_H_
#define _CLINK_MEDIA_MPEGFORMT_H_

#include <cybergarage/upnp/media/server/object/format/MovieFormat.h>

namespace CyberLink {

class MPEGFormat : public MovieFormat
{
	////////////////////////////////////////////////
	// Constroctor
	////////////////////////////////////////////////

public:

	MPEGFormat();
	MPEGFormat(CyberIO::File *file);

	////////////////////////////////////////////////
	// Abstract Methods
	////////////////////////////////////////////////

public:

	bool equals(CyberIO::File *file);

	FormatObject *createObject(CyberIO::File *file)
	{
		return new MPEGFormat(file);
	}

	const char *getMimeType()
	{
		return "video/mpeg";
	}

	int getAttributeList(CyberXML::AttributeList &attrList);
};

}

#endif


text:
The Nicira NVP Plugin
=====================

Introduction to the Nicira NVP Plugin
-------------------------------------

The Nicira NVP plugin adds Nicira NVP as one of the available SDN
implementations in CloudStack. With the plugin an exisiting Nicira NVP
setup can be used by CloudStack to implement isolated guest networks and
to provide additional services like routing and NAT.

Features of the Nicira NVP Plugin
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The following table lists the CloudStack network services provided by
the Nicira NVP Plugin.

+----------------------+----------------------+---------------+
| Network Service      | CloudStack version   | NVP version   |
+======================+======================+===============+
| Virtual Networking   | >= 4.0               | >= 2.2.1      |
+----------------------+----------------------+---------------+
| Source NAT           | >= 4.1               | >= 3.0.1      |
+----------------------+----------------------+---------------+
| Static NAT           | >= 4.1               | >= 3.0.1      |
+----------------------+----------------------+---------------+
| Port Forwarding      | >= 4.1               | >= 3.0.1      |
+----------------------+----------------------+---------------+

Table: Supported Services

.. note::   The Virtual Networking service was originally called 'Connectivity'
    in CloudStack 4.0

The following hypervisors are supported by the Nicira NVP Plugin.

+--------------+----------------------+
| Hypervisor   | CloudStack version   |
+==============+======================+
| XenServer    | >= 4.0               |
+--------------+----------------------+
| KVM          | >= 4.1               |
+--------------+----------------------+

Table: Supported Hypervisors

.. note::    Please refer to the Nicira NVP configuration guide on how to prepare
    the hypervisors for Nicira NVP integration.

Configuring the Nicira NVP Plugin
---------------------------------

Prerequisites
~~~~~~~~~~~~~

Before enabling the Nicira NVP plugin the NVP Controller needs to be
configured. Please review the NVP User Guide on how to do that.

Make sure you have the following information ready:

-  The IP address of the NVP Controller

-  The username to access the API

-  The password to access the API

-  The UUID of the Transport Zone that contains the hypervisors in this
   Zone

-  The UUID of the Gateway Service used to provide router and NAT
   services.

.. note::    The gateway service uuid is optional and is used for Layer 3
    services only (SourceNat, StaticNat and PortForwarding)

Zone Configuration
~~~~~~~~~~~~~~~~~~

CloudStack needs to have at least one physical network with the isolation
method set to "STT". This network should be enabled for the Guest
traffic type.

.. note::    The Guest traffic type should be configured with the traffic label
    that matches the name of the Integration Bridge on the hypervisor.
    See the Nicira NVP User Guide for more details on how to set this up
    in XenServer or KVM.

.. figure:: /_static/images/nvp-physical-network-stt.png
    :align: center
    :alt: a screenshot of a physical network with the STT isolation type

Enabling the service provider
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The Nicira NVP provider is disabled by default. Navigate to the "Network
Service Providers" configuration of the physical network with the STT
isolation type. Navigate to the Nicira NVP provider and press the
"Enable Provider" button.

.. note::    CloudStack 4.0 does not have the UI interface to configure the
    Nicira NVP plugin. Configuration needs to be done using the API
    directly.

.. figure:: /_static/images/nvp-physical-network-stt.png
    :align: center
    :alt: a screenshot of an enabled Nicira NVP provider

Device Management
~~~~~~~~~~~~~~~~~

In CloudStack a Nicira NVP setup is considered a "device" that can be added
and removed from a physical network. To complete the configuration of
the Nicira NVP plugin a device needs to be added to the physical
network. Press the "Add NVP Controller" button on the provider panel and
enter the configuration details.

.. figure:: /_static/images/nvp-physical-network-stt.png
    :align: center
    :alt: a screenshot of the device configuration popup.

Network Offerings
~~~~~~~~~~~~~~~~~

Using the Nicira NVP plugin requires a network offering with Virtual
Networking enabled and configured to use the NiciraNvp element. Typical
use cases combine services from the Virtual Router appliance and the
Nicira NVP plugin.

+----------------------+-----------------+
| Service              | Provider        |
+======================+=================+
| VPN                  | VirtualRouter   |
+----------------------+-----------------+
| DHCP                 | VirtualRouter   |
+----------------------+-----------------+
| DNS                  | VirtualRouter   |
+----------------------+-----------------+
| Firewall             | VirtualRouter   |
+----------------------+-----------------+
| Load Balancer        | VirtualRouter   |
+----------------------+-----------------+
| User Data            | VirtualRouter   |
+----------------------+-----------------+
| Source NAT           | VirtualRouter   |
+----------------------+-----------------+
| Static NAT           | VirtualRouter   |
+----------------------+-----------------+
| Post Forwarding      | VirtualRouter   |
+----------------------+-----------------+
| Virtual Networking   | NiciraNVP       |
+----------------------+-----------------+

Table: Isolated network offering with regular services from the Virtual
Router.

.. figure:: /_static/images/nvp-physical-network-stt.png
    :align: center
    :alt: a screenshot of a network offering.

.. note::    The tag in the network offering should be set to the name of the
    physical network with the NVP provider.

Isolated network with network services. The virtual router is still
required to provide network services like dns and dhcp.

+----------------------+-----------------+
| Service              | Provider        |
+======================+=================+
| DHCP                 | VirtualRouter   |
+----------------------+-----------------+
| DNS                  | VirtualRouter   |
+----------------------+-----------------+
| User Data            | VirtualRouter   |
+----------------------+-----------------+
| Source NAT           | NiciraNVP       |
+----------------------+-----------------+
| Static NAT           | NiciraNVP       |
+----------------------+-----------------+
| Post Forwarding      | NiciraNVP       |
+----------------------+-----------------+
| Virtual Networking   | NiciraNVP       |
+----------------------+-----------------+

Table: Isolated network offering with network services

Using the Nicira NVP plugin with VPC
------------------------------------

Supported VPC features
~~~~~~~~~~~~~~~~~~~~~~

The Nicira NVP plugin supports CloudStack VPC to a certain extent. Starting
with CloudStack version 4.1 VPCs can be deployed using NVP isolated
networks.

It is not possible to use a Nicira NVP Logical Router for as a VPC
Router

It is not possible to connect a private gateway using a Nicira NVP
Logical Switch

VPC Offering with Nicira NVP
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

To allow a VPC to use the Nicira NVP plugin to provision networks, a new
VPC offering needs to be created which allows the Virtual Networking
service to be implemented by NiciraNVP.

This is not currently possible with the UI. The API does provide the
proper calls to create a VPC offering with Virtual Networking enabled.
However due to a limitation in the 4.1 API it is not possible to select
the provider for this network service. To configure the VPC offering
with the NiciraNVP provider edit the database table
'vpc\_offering\_service\_map' and change the provider to NiciraNvp for
the service 'Connectivity'

It is also possible to update the default VPC offering by adding a row
to the 'vpc\_offering\_service\_map' with service 'Connectivity' and
provider 'NiciraNvp'

.. figure:: /_static/images/nvp-physical-network-stt.png
    :align: center
    :alt: a screenshot of the mysql table.

.. note::    When creating a new VPC offering please note that the UI does not
    allow you to select a VPC offering yet. The VPC needs to be created
    using the API with the offering UUID.

VPC Network Offerings
~~~~~~~~~~~~~~~~~~~~~

The VPC needs specific network offerings with the VPC flag enabled.
Otherwise these network offerings are identical to regular network
offerings. To allow VPC networks with a Nicira NVP isolated network the
offerings need to support the Virtual Networking service with the
NiciraNVP provider.

In a typical configuration two network offerings need to be created. One
with the loadbalancing service enabled and one without loadbalancing.

+----------------------+--------------------+
| Service              | Provider           |
+======================+====================+
| VPN                  | VpcVirtualRouter   |
+----------------------+--------------------+
| DHCP                 | VpcVirtualRouter   |
+----------------------+--------------------+
| DNS                  | VpcVirtualRouter   |
+----------------------+--------------------+
| Load Balancer        | VpcVirtualRouter   |
+----------------------+--------------------+
| User Data            | VpcVirtualRouter   |
+----------------------+--------------------+
| Source NAT           | VpcVirtualRouter   |
+----------------------+--------------------+
| Static NAT           | VpcVirtualRouter   |
+----------------------+--------------------+
| Post Forwarding      | VpcVirtualRouter   |
+----------------------+--------------------+
| NetworkACL           | VpcVirtualRouter   |
+----------------------+--------------------+
| Virtual Networking   | NiciraNVP          |
+----------------------+--------------------+

Table: VPC Network Offering with Loadbalancing

Troubleshooting the Nicira NVP Plugin
-------------------------------------

UUID References
~~~~~~~~~~~~~~~

The plugin maintains several references in the CloudStack database to items
created on the NVP Controller.

Every guest network that is created will have its broadcast type set to
Lswitch and if the network is in state "Implemented", the broadcast URI
will have the UUID of the Logical Switch that was created for this
network on the NVP Controller.

The Nics that are connected to one of the Logical Switches will have
their Logical Switch Port UUID listed in the nicira\_nvp\_nic\_map table

.. note::    All devices created on the NVP Controller will have a tag set to
    domain-account of the owner of the network, this string can be used
    to search for items in the NVP Controller.

Database tables
~~~~~~~~~~~~~~~

The following tables are added to the cloud database for the Nicira NVP
Plugin

+---------------------+--------------------------------------------------------------+
| id                  | auto incrementing id                                         |
+---------------------+--------------------------------------------------------------+
| logicalswitch       | uuid of the logical switch this port is connected to         |
+---------------------+--------------------------------------------------------------+
| logicalswitchport   | uuid of the logical switch port for this nic                 |
+---------------------+--------------------------------------------------------------+
| nic                 | the CloudStack uuid for this nic, reference to the nics table|
+---------------------+--------------------------------------------------------------+

Table: nicira\_nvp\_nic\_map

+-------------------------+-------------------------------------------------------------+
| id                      | auto incrementing id                                        |
+-------------------------+-------------------------------------------------------------+
| uuid                    | UUID identifying this device                                |
+-------------------------+-------------------------------------------------------------+
| physical\_network\_id   | the physical network this device is configured on           |
+-------------------------+-------------------------------------------------------------+
| provider\_name          | NiciraNVP                                                   |
+-------------------------+-------------------------------------------------------------+
| device\_name            | display name for this device                                |
+-------------------------+-------------------------------------------------------------+
| host\_id                | reference to the host table with the device configuration   |
+-------------------------+-------------------------------------------------------------+

Table: external\_nicira\_nvp\_devices

+-----------------------+----------------------------------------------+
| id                    | auto incrementing id                         |
+-----------------------+----------------------------------------------+
| logicalrouter\_uuid   | uuid of the logical router                   |
+-----------------------+----------------------------------------------+
| network\_id           | id of the network this router is linked to   |
+-----------------------+----------------------------------------------+

Table: nicira\_nvp\_router\_map

.. note::    nicira\_nvp\_router\_map is only available in CloudStack 4.1 and above

Revision History
----------------

0-0 Wed Oct 03 2012 Hugo Trippaers hugo@apache.org Documentation created
for 4.0.0-incubating version of the NVP Plugin 1-0 Wed May 22 2013 Hugo
Trippaers hugo@apache.org Documentation updated for CloudStack 4.1.0

.. | nvp-physical-network-stt.png: a screenshot of a physical network with the STT isolation type | image:: ./images/nvp-physical-network-stt.png
.. | nvp-physical-network-stt.png: a screenshot of an enabled Nicira NVP provider | image:: ./images/nvp-enable-provider.png
.. | nvp-physical-network-stt.png: a screenshot of the device configuration popup. | image:: ./images/nvp-add-controller.png
.. | nvp-physical-network-stt.png: a screenshot of a network offering. | image:: ./images/nvp-network-offering.png
.. | nvp-physical-network-stt.png: a screenshot of the mysql table. | image:: ./images/nvp-vpc-offering-edit.png


text:
<?php
namespace CodeOrders\V1\Rest\OauthAuthorizationCodes;

use ArrayObject;

class OauthAuthorizationCodesEntity extends ArrayObject
{
}


text:
#include "../common.h"

namespace Lua {

    /** Function prototype */
    Function::Function(StringObject * func_name, int line_defined_first, int line_defined_last, byte num_params,
                       byte is_vararg, byte max_stack_size,
                       InstructionList* code,
                       Container<ValueObject>* constants, Container<UpvalueDesc>* upvalues, std::vector<Function*>* protos):
            func_name(func_name),
            line_defined_first(line_defined_first),
            line_defined_last(line_defined_last),
            num_params(num_params),
            is_vararg(is_vararg),
            max_stack_size(max_stack_size),
            code(code),
            constants(constants),
            upvaluesdescs(upvalues),
            protos(protos)
    {}

    Function::~Function() {
        delete func_name;
        delete code;
        delete constants; // constants themselves are deleted by GC
        delete upvaluesdescs;

        for (std::vector<Function*>::iterator it = protos->begin(); it != protos->end(); ++it) {
            delete *it;
        }
        delete protos;
    }

    void Function::print() {
        printf("--- Function --------\n");
        if (func_name != NULL) {
            printf("Name: "); func_name->print();
        }
        printf("Lines: %i..%i\n", line_defined_first, line_defined_last);
        printf("Params: %i, vararg: %i, max stack: %i\n", num_params, is_vararg, max_stack_size);
        code->print();
        printf("Constants:\n");
        constants->print();
        printf("Upvalues:\n");
        upvaluesdescs->print();
        printf("Protos: %lu\n", protos->size());
        for (int i=0; i<protos->size(); i++) {
            (*protos)[i]->print();
        }
    }

    InstructionList* Function::getCode() const {
        return code;
    }
    byte Function::getMaxStackSize() const {
        return max_stack_size;
    }
}


text:
<?php
namespace Concrete\Controller\Dialog\Page\Add;

use Concrete\Core\Controller\Controller;
use Concrete\Core\Form\Service\Widget\DateTime;
use Concrete\Core\Page\EditResponse;
use Concrete\Core\Page\Template;
use Concrete\Core\Page\Type\Type;
use Concrete\Core\View\DialogView;
use Page;
use Permissions;

class Compose extends Controller
{
    protected $controllerActionPath = '/ccm/system/dialogs/page/add/compose';

    public function view($ptID, $cParentID)
    {
        $pagetype = Type::getByID($ptID);
        $e = $this->app->make('error');
        if (is_object($pagetype)) {
            $ptp = new Permissions($pagetype);
            if (!$ptp->canAddPageType()) {
                $e->add(t('You do not have permission to add a page of this type.'));
            }
        } else {
            $e->add(t('Invalid page type.'));
        }

        $parent = Page::getByID($cParentID);
        if (!is_object($parent) || $parent->isError()) {
            $e->add(t('Invalid parent page.'));
        }

        if (!$e->has()) {
            $this->view = new DialogView('/dialogs/page/add/compose');
            $this->set('parent', $parent);
            $this->set('pagetype', $pagetype);
        } else {
            $pr = new EditResponse();
            $pr->setError($e);
            $pr->outputJSON();
        }

        if (!$this->view) {
            throw new \Exception(t('Access Denied.'));
        }
    }

    public function submit()
    {
        $e = $this->app->make('error');
        $pagetype = Type::getByID($this->request->request->get('ptID'));
        if (is_object($pagetype)) {
            $configuredTarget = $pagetype->getPageTypePublishTargetObject();
            $cParentID = $configuredTarget->getPageTypePublishTargetConfiguredTargetParentPageID();
            if (!$cParentID) {
                $cParentID = $this->request->request->get('cParentID');
            }
        }
        $parent = Page::getByID($cParentID);

        $template = null;
        if ($this->request->request->get('ptComposerPageTemplateID')) {
            $template = Template::getByID($this->request->request->get('ptComposerPageTemplateID'));
        }
        if (!is_object($template)) {
            $template = $pagetype->getPageTypeDefaultPageTemplateObject();
        }

        if (is_object($pagetype)) {
            $validator = $pagetype->getPageTypeValidatorObject();
            $e->add($validator->validateCreateDraftRequest($template));
            $e->add($validator->validatePublishLocationRequest($parent));
            if ($this->request->request('addPageComposeAction') == 'publish') {
                $e->add($validator->validatePublishDraftRequest());
            }
        }
        $pr = new EditResponse();
        $pr->setError($e);

        if (!$e->has()) {
            $d = $pagetype->createDraft($template);
            $d->setPageDraftTargetParentPageID($cParentID);
            $saver = $pagetype->getPageTypeSaverObject();
            $saver->saveForm($d);
            if ($this->request->request('addPageComposeAction') == 'publish'
            || $this->request->request('addPageComposeAction') == 'schedule') {
                $publishDateTime = false;
                $publishEndDateTime = false;
                $keepOtherScheduling = false;
                if ($this->request->request->get('addPageComposeAction') == 'schedule') {
                    $dateTime = new DateTime();
                    $publishDateTime = $dateTime->translate('cvPublishDate');
                    $publishEndDateTime = $dateTime->translate('cvPublishEndDate');
                    if ($this->request->request->get('keepOtherScheduling')) {
                        $keepOtherScheduling = true;
                    }
                }

                $pagetype->publish($d, $publishDateTime, $publishEndDateTime, $keepOtherScheduling);

                $pr->setAdditionalDataAttribute('cParentID', $cParentID);
                $pr->setMessage(t('Page Added Successfully.'));
            } else {
                $pr->setRedirectURL($d->getCollectionLink(true));
            }
        }

        $pr->outputJSON();
    }
}


text:
@interface AVGOperation : FUNCOperation
//平均值
//msg 为 NSString(属性名称) or  PropertyCondition
//PropertyCondition  针对join
+(instancetype)Operation:(id)msg;
@end


text:
package org.oddjob.beancmpr.results;

import org.oddjob.arooa.reflect.PropertyAccessor;

/**
 * Allow for different {@link ResultBeanFactory}.
 *
 * @see BeanCreatingResultHandler
 *
 * @author rob
 *
 */
public interface ResultBeanFactoryBuilder {

	/**
	 * Build the factory.
	 *
	 * @param accessor
	 * @param xPropertyPrefix
	 * @param yPropertyPrefix

	 * @return Not Null.
	 */
	public ResultBeanFactory factoryFor(PropertyAccessor accessor,
			String xPropertyPrefix, String yPropertyPrefix);

}


text:
/* global window */

window.deprecationWorkflow = window.deprecationWorkflow || {};
window.deprecationWorkflow.config = {
  workflow: [
    { handler: 'silence', matchId: 'computed-property.volatile' },
    { handler: 'silence', matchId: 'computed-property.override' },
  ],
};


text:
"""The fetch commands."""

from ORCSchlange.command import BaseCommand
from ORCSchlange.orcid import API
import itertools
import pybtex.database
from ORCSchlange.bib import join_bibliography, write_html
import shutil
from ORCSchlange.config import Config
import os.path

class FetchReporeter(BaseCommand):
    """The class that contains all fetch commands."""

    def fetch(self):
        """Fetch data from public ORCID API"""
        self.debug("Read config")
        Config(self.args)
        if not Config().ready:
            if self.args.config == 1:
                self.error("No configuration found in db.")
            else:
                self.error("No valid json file.")
            return
        self.open()

        self.debug("Read orchids")
        orcs = self.db.get_orcids()

        self.close()

        self.debug("Open API connection")
        api = API()

        self.debug("Get all work summaries")
        alldocs = []
        for orc in orcs:
            docs = api.get_worksums(orc)
            alldocs += docs

        self.debug("Sort all work summaries")
        alldocs.sort()

        self.debug("Make entries uniques")
        uniqdocs = []
        for doc, _ in itertools.groupby(alldocs):
            uniqdocs.append(doc)

        works_api = dict()
        uniqdocs.sort(key=lambda x: x.orc)
        for key, docs in itertools.groupby(uniqdocs, key=lambda x: x.orc):
            works_api[key] = [str(x.id) for x in docs]

        self.debug("Get complete works")
        entries = pybtex.database.BibliographyData()

        for key in works_api:
            for ent in api.get_works(key, works_api[key]):
                join_bibliography(entries, ent)

        self.args.path = self.args.path if self.args.path.endswith("/") else self.args.path + "/"

        if self.args.bib:
            self.debug("Write bib in {path}{name}.bib".format(**vars(self.args)))
            entries.to_file(open("{path}{name}.bib".format(**vars(self.args)), "w"))
        if self.args.html:
            self.debug("Write html in {path}{name}.html".format(**vars(self.args)))
            write_html(entries, path="{path}{name}.html".format(**vars(self.args)))
        if self.args.jquery:
            jname = "jquery-3.2.1.min.js"
            self.debug("Copy jQuery to {path}{jname}".format(path=self.args.path, jname=jname))
            shutil.copyfile(os.path.dirname(__file__) + "/{jname}".format(jname=jname),
                            "{path}{jname}".format(path=self.args.path, jname=jname))


text:
package com.dd.bootstrap3.demo.components;

import com.dd.bootstrap.components.BSComponent;
import com.webobjects.appserver.WOContext;

public class Wrapper extends BSComponent {

	public Wrapper(WOContext context) {
        super(context);
    }

    @Override
    public boolean synchronizesVariablesWithBindings() {
    	return false;
    }
}


text:
package org.apache.spark.sql.connector.catalog;

import org.apache.spark.annotation.Evolving;
import org.apache.spark.sql.connector.expressions.Transform;
import org.apache.spark.sql.catalyst.analysis.NoSuchNamespaceException;
import org.apache.spark.sql.catalyst.analysis.NoSuchTableException;
import org.apache.spark.sql.catalyst.analysis.TableAlreadyExistsException;
import org.apache.spark.sql.errors.QueryCompilationErrors;
import org.apache.spark.sql.types.StructType;

import java.util.Map;

/**
 * Catalog methods for working with Tables.
 *

 * TableCatalog implementations may be case sensitive or case insensitive. Spark will pass
 * {@link Identifier table identifiers} without modification. Field names passed to
 * {@link #alterTable(Identifier, TableChange...)} will be normalized to match the case used in the
 * table schema when updating, renaming, or dropping existing columns when catalyst analysis is case
 * insensitive.
 *
 * @since 3.0.0
 */
@Evolving
public interface TableCatalog extends CatalogPlugin {

  /**
   * A reserved property to specify the location of the table. The files of the table
   * should be under this location.
   */
  String PROP_LOCATION = "location";

  /**
   * A reserved property to indicate that the table location is managed, not user-specified.
   * If this property is "true", SHOW CREATE TABLE will not generate the LOCATION clause.
   */
  String PROP_IS_MANAGED_LOCATION = "is_managed_location";

  /**
   * A reserved property to specify a table was created with EXTERNAL.
   */
  String PROP_EXTERNAL = "external";

  /**
   * A reserved property to specify the description of the table.
   */
  String PROP_COMMENT = "comment";

  /**
   * A reserved property to specify the provider of the table.
   */
  String PROP_PROVIDER = "provider";

  /**
   * A reserved property to specify the owner of the table.
   */
  String PROP_OWNER = "owner";

  /**
   * A prefix used to pass OPTIONS in table properties
   */
  String OPTION_PREFIX = "option.";

  /**
   * List the tables in a namespace from the catalog.
   *

   * If the catalog supports views, this must return identifiers for only tables and not views.
   *
   * @param namespace a multi-part namespace
   * @return an array of Identifiers for tables
   * @throws NoSuchNamespaceException If the namespace does not exist (optional).
   */
  Identifier[] listTables(String[] namespace) throws NoSuchNamespaceException;

  /**
   * Load table metadata by {@link Identifier identifier} from the catalog.
   *

   * If the catalog supports views and contains a view for the identifier and not a table, this
   * must throw {@link NoSuchTableException}.
   *
   * @param ident a table identifier
   * @return the table's metadata
   * @throws NoSuchTableException If the table doesn't exist or is a view
   */
  Table loadTable(Identifier ident) throws NoSuchTableException;

  /**
   * Load table metadata of a specific version by {@link Identifier identifier} from the catalog.
   *

   * If the catalog supports views and contains a view for the identifier and not a table, this
   * must throw {@link NoSuchTableException}.
   *
   * @param ident a table identifier
   * @param version version of the table
   * @return the table's metadata
   * @throws NoSuchTableException If the table doesn't exist or is a view
   */
  default Table loadTable(Identifier ident, String version) throws NoSuchTableException {
    throw QueryCompilationErrors.tableNotSupportTimeTravelError(ident);
  }

  /**
   * Load table metadata at a specific time by {@link Identifier identifier} from the catalog.
   *

   * If the catalog supports views and contains a view for the identifier and not a table, this
   * must throw {@link NoSuchTableException}.
   *
   * @param ident a table identifier
   * @param timestamp timestamp of the table, which is microseconds since 1970-01-01 00:00:00 UTC
   * @return the table's metadata
   * @throws NoSuchTableException If the table doesn't exist or is a view
   */
  default Table loadTable(Identifier ident, long timestamp) throws NoSuchTableException {
    throw QueryCompilationErrors.tableNotSupportTimeTravelError(ident);
  }

  /**
   * Invalidate cached table metadata for an {@link Identifier identifier}.
   *

   * If the table is already loaded or cached, drop cached data. If the table does not exist or is
   * not cached, do nothing. Calling this method should not query remote services.
   *
   * @param ident a table identifier
   */
  default void invalidateTable(Identifier ident) {
  }

  /**
   * Test whether a table exists using an {@link Identifier identifier} from the catalog.
   *

   * If the catalog supports views and contains a view for the identifier and not a table, this
   * must return false.
   *
   * @param ident a table identifier
   * @return true if the table exists, false otherwise
   */
  default boolean tableExists(Identifier ident) {
    try {
      return loadTable(ident) != null;
    } catch (NoSuchTableException e) {
      return false;
    }
  }

  /**
   * Create a table in the catalog.
   *
   * @param ident a table identifier
   * @param schema the schema of the new table, as a struct type
   * @param partitions transforms to use for partitioning data in the table
   * @param properties a string map of table properties
   * @return metadata for the new table
   * @throws TableAlreadyExistsException If a table or view already exists for the identifier
   * @throws UnsupportedOperationException If a requested partition transform is not supported
   * @throws NoSuchNamespaceException If the identifier namespace does not exist (optional)
   */
  Table createTable(
      Identifier ident,
      StructType schema,
      Transform[] partitions,
      Map<String, String> properties) throws TableAlreadyExistsException, NoSuchNamespaceException;

  /**
   * Apply a set of {@link TableChange changes} to a table in the catalog.
   *

   * Implementations may reject the requested changes. If any change is rejected, none of the
   * changes should be applied to the table.
   *

   * The requested changes must be applied in the order given.
   *

   * If the catalog supports views and contains a view for the identifier and not a table, this
   * must throw {@link NoSuchTableException}.
   *
   * @param ident a table identifier
   * @param changes changes to apply to the table
   * @return updated metadata for the table
   * @throws NoSuchTableException If the table doesn't exist or is a view
   * @throws IllegalArgumentException If any change is rejected by the implementation.
   */
  Table alterTable(
      Identifier ident,
      TableChange... changes) throws NoSuchTableException;

  /**
   * Drop a table in the catalog.
   *

   * If the catalog supports views and contains a view for the identifier and not a table, this
   * must not drop the view and must return false.
   *
   * @param ident a table identifier
   * @return true if a table was deleted, false if no table exists for the identifier
   */
  boolean dropTable(Identifier ident);

  /**
   * Drop a table in the catalog and completely remove its data by skipping a trash even if it is
   * supported.
   *

   * If the catalog supports views and contains a view for the identifier and not a table, this
   * must not drop the view and must return false.
   *

   * If the catalog supports to purge a table, this method should be overridden.
   * The default implementation throws {@link UnsupportedOperationException}.
   *
   * @param ident a table identifier
   * @return true if a table was deleted, false if no table exists for the identifier
   * @throws UnsupportedOperationException If table purging is not supported
   *
   * @since 3.1.0
   */
  default boolean purgeTable(Identifier ident) throws UnsupportedOperationException {
    throw new UnsupportedOperationException("Purge table is not supported.");
  }

  /**
   * Renames a table in the catalog.
   *

   * If the catalog supports views and contains a view for the old identifier and not a table, this
   * throws {@link NoSuchTableException}. Additionally, if the new identifier is a table or a view,
   * this throws {@link TableAlreadyExistsException}.
   *

   * If the catalog does not support table renames between namespaces, it throws
   * {@link UnsupportedOperationException}.
   *
   * @param oldIdent the table identifier of the existing table to rename
   * @param newIdent the new table identifier of the table
   * @throws NoSuchTableException If the table to rename doesn't exist or is a view
   * @throws TableAlreadyExistsException If the new table name already exists or is a view
   * @throws UnsupportedOperationException If the namespaces of old and new identifiers do not
   *                                       match (optional)
   */
  void renameTable(Identifier oldIdent, Identifier newIdent)
      throws NoSuchTableException, TableAlreadyExistsException;
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Coutourea rosmarini Castagne

### Remarks
null


text:
package pl.porannajava.javnysejm;

public abstract class AbstractInternalEntity extends AbstractEntity {

	public AbstractInternalEntity()
	{
		super();
	}

	@Override
	protected boolean hasId() {
		return false;
	}

}


text:
- ``writeToPackageDirectory(reason:)``

### Encoding and Decoding

- ``encode(to:)``


text:
<?php

require_once ($GLOBALS['HACKLIB_ROOT']);
if (!isset($GLOBALS['THRIFT_ROOT'])) {
  $GLOBALS['THRIFT_ROOT'] = __DIR__.'/../..';
}
require_once $GLOBALS['THRIFT_ROOT'].'/protocol/compact/TCompactProtocolAccelerated.php';
class TCompactProtocol extends TCompactProtocolAccelerated {
  public function __construct($trans) {
    parent::__construct($trans);
  }
}


text:
using System;
using StixGames;
using UnityEngine;

public class GrassPainter
{
	private const float EPSILON = 0.01f;

	public int Channel = 0;
	public int BrushMode = 0;
	public float Strength = 1;
	public float Size = 1;
	public float Softness = 0.5f;
	public float Spacing = 0.5f;
	public float Rotation = 0;

	/// <summary>
	/// The grass collider the brush will be applied to. Only set this when using ApplyBrush directly.
	/// </summary>
	public Collider GrassCollider;

	/// <summary>
	/// The density texture the brush will be applied to. Only set this when using ApplyBrush directly.
	/// </summary>
	public Texture2D Texture;

	public bool Draw(Ray ray)
	{
		RaycastHit hit;
		if (Physics.Raycast(ray, out hit))
		{
			GrassCollider = hit.collider;
			Texture = (Texture2D) hit.collider.GetComponent<Renderer>().material.mainTexture;

			ApplyBrush(hit.point);
			return true;
		}

		return false;
	}

	public void ApplyBrush(Vector3 hitPoint)
	{
		RaycastHit hit;
		Vector2 texForward, texRight;
		if (!GrassManipulationUtility.GetWorldToTextureSpaceMatrix(new Ray(hitPoint + Vector3.up * 1000, Vector3.down),
			EPSILON, GrassCollider, out hit, out texForward, out texRight))
		{
			return;
		}

		Vector2 texCoord = hit.textureCoord;

		//Convert the world space radius to a pixel radius in texture space. This requires square textures.
		int pixelRadius = (int)(Size * texForward.magnitude * Texture.width);

		//Calculate the pixel coordinates of the point where the raycast hit the texture.
		Vector2 mid = new Vector2(texCoord.x * Texture.width, texCoord.y * Texture.height);

		//Calculate the pixel area where the texture will be changed
		int targetStartX = (int)(mid.x - pixelRadius);
		int targetStartY = (int)(mid.y - pixelRadius);
		int startX = Mathf.Clamp(targetStartX, 0, Texture.width);
		int startY = Mathf.Clamp(targetStartY, 0, Texture.height);
		int width = Mathf.Min(targetStartX + pixelRadius * 2, Texture.width) - targetStartX;
		int height = Mathf.Min(targetStartY + pixelRadius * 2, Texture.height) - targetStartY;

		mid -= new Vector2(startX, startY);

		//Get pixels
		Color[] pixels = Texture.GetPixels(startX, startY, width, height);

		//Iterate trough all pixels
		for (int y = 0; y < height; y++)
		{
			for (int x = 0; x < width; x++)
			{
				int index = y * width + x;
				Vector2 uv = ((new Vector2(x, y) - mid) / pixelRadius) * 0.5f + new Vector2(0.5f, 0.5f);
				pixels[index] = ApplyBrushToPixel(pixels[index], uv);
			}
		}

		//Save pixels and apply them to the texture
		Texture.SetPixels(startX, startY, width, height, pixels);
		Texture.Apply();
	}

	private Color ApplyBrushToPixel(Color c, Vector2 v)
	{
		v -= new Vector2(0.5f, 0.5f);
		v *= 2;
		float distance = v.magnitude;

		//Calculate brush smoothness
		float value = SmoothStep(1, Mathf.Min(1 - Softness, 0.999f), distance);

		switch (BrushMode)
		{
			case 0:
				c = ChangeChannel(c, x => x + value * Strength);
				break;

			case 1:
				c = ChangeChannel(c, x => x - value * Strength);
				break;

			case 2:
				c = ChangeChannel(c, x => x * (1 - value) + Strength * value);
				break;
		}

		return c;
	}

	private Color ChangeChannel(Color c, Func<float, float> densityChange)
	{
		switch (Channel)
		{
			case 0:
				c.r = Mathf.Clamp01(densityChange(c.r));
				break;
			case 1:
				c.g = Mathf.Clamp01(densityChange(c.g));
				break;
			case 2:
				c.b = Mathf.Clamp01(densityChange(c.b));
				break;
			case 3:
				c.a = Mathf.Clamp01(densityChange(c.a));
				break;
			default:
				throw new InvalidOperationException("Channel number invalid");
		}
		return c;
	}

	private float SmoothStep(float edge0, float edge1, float x)
	{
		// Scale, bias and saturate x to 0..1 range
		x = Mathf.Clamp((x - edge0) / (edge1 - edge0), 0.0f, 1.0f);
		// Evaluate polynomial
		return x * x * (3 - 2 * x);
	}
}