text:
package net.bytebuddy.implementation;

import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.description.type.TypeList;
import net.bytebuddy.dynamic.scaffold.InstrumentedType;
import net.bytebuddy.implementation.bytecode.ByteCodeAppender;
import net.bytebuddy.implementation.bytecode.StackManipulation;
import net.bytebuddy.implementation.bytecode.member.MethodReturn;
import net.bytebuddy.implementation.bytecode.member.MethodVariableAccess;
import org.objectweb.asm.MethodVisitor;

import java.util.*;

import static net.bytebuddy.utility.ByteBuddyCommons.isInterface;
import static net.bytebuddy.utility.ByteBuddyCommons.nonNull;
import static net.bytebuddy.utility.ByteBuddyCommons.toList;

/**
 * This {@link Implementation} invokes a default method for the methods it instruments.
 * A default method is potentially ambiguous if a method of identical signature is defined in several interfaces.
 * For this reason, this implementation allows for the specification of prioritized interfaces whose default
 * methods, if a method of equivalent signature is defined for a specific interface. All prioritized interfaces are
 * searched for default methods in the order of their specification. If no prioritized interface defines a default method
 * of equivalent signature to the given instrumented method, any non-prioritized interface is searched for a suitable
 * default method. If exactly one of those interfaces defines a suitable default method, this method is invoked.
 * If no method or more than one method is identified as a suitable default method, an exception is thrown.
 *

 * When it comes to default methods, the Java programming language specifies stronger requirements for the
 * legitimacy of invoking a default method than the Java runtime. The Java compiler requires a method to be
 * the most specific method in its defining type's type hierarchy, i.e. the method must not be overridden by another
 * interface or class type. Additionally, the method must be invokable from an interface type which is directly
 * implemented by the instrumented type. The Java runtime only requires the second condition to be fulfilled which
 * is why this implementation only checks the later condition, as well.
 */
public class DefaultMethodCall implements Implementation {

    /**
     * A list of prioritized interfaces in the order in which a method should be attempted to be called.
     */
    private final List<TypeDescription> prioritizedInterfaces;

    /**
     * Creates a new {@link net.bytebuddy.implementation.DefaultMethodCall} implementation for a given list of
     * prioritized interfaces.
     *
     * @param prioritizedInterfaces A list of prioritized interfaces in the order in which a method should be attempted to
     *                              be called.
     */
    protected DefaultMethodCall(List<TypeDescription> prioritizedInterfaces) {
        for (TypeDescription typeDescription : prioritizedInterfaces) {
            isInterface(typeDescription);
        }
        this.prioritizedInterfaces = prioritizedInterfaces;
    }

    /**
     * Creates a {@link net.bytebuddy.implementation.DefaultMethodCall} implementation which searches the given list
     * of interface types for a suitable default method in their order. If no such prioritized interface is suitable,
     * because it is either not defined on the instrumented type or because it does not define a suitable default method,
     * any remaining interface is searched for a suitable default method. If no or more than one method defines a
     * suitable default method, an exception is thrown.
     *
     * @param prioritizedInterface A list of prioritized default method interfaces in their prioritization order.
     * @return An implementation which calls an instrumented method's compatible default method that considers the given
     * interfaces to be prioritized in their order.
     */
    public static Implementation prioritize(Class<?>... prioritizedInterface) {
        return prioritize(new TypeList.ForLoadedType(nonNull(prioritizedInterface)));
    }

    /**
     * Creates a {@link net.bytebuddy.implementation.DefaultMethodCall} implementation which searches the given list
     * of interface types for a suitable default method in their order. If no such prioritized interface is suitable,
     * because it is either not defined on the instrumented type or because it does not define a suitable default method,
     * any remaining interface is searched for a suitable default method. If no or more than one method defines a
     * suitable default method, an exception is thrown.
     *
     * @param prioritizedInterface A list of prioritized default method interfaces in their prioritization order.
     * @return An implementation which calls an instrumented method's compatible default method that considers the given
     * interfaces to be prioritized in their order.
     */
    public static Implementation prioritize(Iterable<? extends Class<?>> prioritizedInterface) {
        return prioritize(new TypeList.ForLoadedType(toList(prioritizedInterface)));
    }

    /**
     * Creates a {@link net.bytebuddy.implementation.DefaultMethodCall} implementation which searches the given list
     * of interface types for a suitable default method in their order. If no such prioritized interface is suitable,
     * because it is either not defined on the instrumented type or because it does not define a suitable default method,
     * any remaining interface is searched for a suitable default method. If no or more than one method defines a
     * suitable default method, an exception is thrown.
     *
     * @param prioritizedInterface A list of prioritized default method interfaces in their prioritization order.
     * @return An implementation which calls an instrumented method's compatible default method that considers the given
     * interfaces to be prioritized in their order.
     */
    public static Implementation prioritize(TypeDescription... prioritizedInterface) {
        return prioritize(Arrays.asList(nonNull(prioritizedInterface)));
    }

    /**
     * Creates a {@link net.bytebuddy.implementation.DefaultMethodCall} implementation which searches the given list
     * of interface types for a suitable default method in their order. If no such prioritized interface is suitable,
     * because it is either not defined on the instrumented type or because it does not define a suitable default method,
     * any remaining interface is searched for a suitable default method. If no or more than one method defines a
     * suitable default method, an exception is thrown.
     *
     * @param prioritizedInterfaces A collection of prioritized default method interfaces in their prioritization order.
     * @return An implementation which calls an instrumented method's compatible default method that considers the given
     * interfaces to be prioritized in their order.
     */
    public static Implementation prioritize(Collection<? extends TypeDescription> prioritizedInterfaces) {
        return new DefaultMethodCall(new ArrayList<TypeDescription>(nonNull(prioritizedInterfaces)));
    }

    /**
     * Creates a {@link net.bytebuddy.implementation.DefaultMethodCall} implementation without prioritizing any
     * interface. Instead, any interface that is defined for a given type is searched for a suitable default method. If
     * exactly one interface defines a suitable default method, this method is invoked from the instrumented method.
     * Otherwise, an exception is thrown.
     *
     * @return An implementation which calls an instrumented method's compatible default method if such a method
     * is unambiguous.
     */
    public static Implementation unambiguousOnly() {
        return new DefaultMethodCall(Collections.<TypeDescription>emptyList());
    }

    @Override
    public InstrumentedType prepare(InstrumentedType instrumentedType) {
        return instrumentedType;
    }

    @Override
    public ByteCodeAppender appender(Target implementationTarget) {
        return new Appender(implementationTarget, filterRelevant(implementationTarget.getTypeDescription()));
    }

    /**
     * Filters the relevant prioritized interfaces for a given type, i.e. finds the types that are
     * directly declared on a given instrumented type.
     *
     * @param typeDescription The instrumented type for which the prioritized interfaces are to be filtered.
     * @return A list of prioritized interfaces that are additionally implemented by the given type.
     */
    private List<TypeDescription> filterRelevant(TypeDescription typeDescription) {
        List<TypeDescription> filtered = new ArrayList<TypeDescription>(prioritizedInterfaces.size());
        Set<TypeDescription> relevant = new HashSet<TypeDescription>(typeDescription.getInterfaces());
        for (TypeDescription prioritizedInterface : prioritizedInterfaces) {
            if (relevant.remove(prioritizedInterface)) {
                filtered.add(prioritizedInterface);
            }
        }
        return filtered;
    }

    @Override
    public boolean equals(Object other) {
        return this == other || !(other == null || getClass() != other.getClass())
                && prioritizedInterfaces.equals(((DefaultMethodCall) other).prioritizedInterfaces);
    }

    @Override
    public int hashCode() {
        return prioritizedInterfaces.hashCode();
    }

    @Override
    public String toString() {
        return "DefaultMethodCall{prioritizedInterfaces=" + prioritizedInterfaces + '}';
    }

    /**
     * The appender for implementing a {@link net.bytebuddy.implementation.DefaultMethodCall}.
     */
    protected static class Appender implements ByteCodeAppender {

        /**
         * The implementation target of this appender.
         */
        private final Target implementationTarget;

        /**
         * The relevant prioritized interfaces to be considered by this appender.
         */
        private final List<TypeDescription> prioritizedInterfaces;

        /**
         * The relevant non-prioritized interfaces to be considered by this appender.
         */
        private final Set<TypeDescription> nonPrioritizedInterfaces;

        /**
         * Creates a new appender for implementing a {@link net.bytebuddy.implementation.DefaultMethodCall}.
         *
         * @param implementationTarget  The implementation target of this appender.
         * @param prioritizedInterfaces The relevant prioritized interfaces to be considered by this appender.
         */
        protected Appender(Target implementationTarget, List<TypeDescription> prioritizedInterfaces) {
            this.implementationTarget = implementationTarget;
            this.prioritizedInterfaces = prioritizedInterfaces;
            this.nonPrioritizedInterfaces = new HashSet<TypeDescription>(implementationTarget.getTypeDescription().getInterfaces());
            nonPrioritizedInterfaces.removeAll(prioritizedInterfaces);
        }

        @Override
        public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) {
            StackManipulation defaultMethodInvocation = locateDefault(instrumentedMethod);
            if (!defaultMethodInvocation.isValid()) {
                throw new IllegalStateException("Cannot invoke default method on " + instrumentedMethod);
            }
            StackManipulation.Size stackSize = new StackManipulation.Compound(
                    MethodVariableAccess.loadThisReferenceAndArguments(instrumentedMethod),
                    defaultMethodInvocation,
                    MethodReturn.returning(instrumentedMethod.getReturnType())
            ).apply(methodVisitor, implementationContext);
            return new Size(stackSize.getMaximalSize(), instrumentedMethod.getStackSize());
        }

        /**
         * Locates a special method invocation to be invoked from a given method.
         *
         * @param methodDescription The method that is currently instrumented.
         * @return A potentially illegal stack manipulation representing the default method invocation for the
         * given method.
         */
        private StackManipulation locateDefault(MethodDescription methodDescription) {
            String uniqueMethodSignature = methodDescription.getUniqueSignature();
            SpecialMethodInvocation specialMethodInvocation = SpecialMethodInvocation.Illegal.INSTANCE;
            for (TypeDescription typeDescription : prioritizedInterfaces) {
                specialMethodInvocation = implementationTarget.invokeDefault(typeDescription, uniqueMethodSignature);
                if (specialMethodInvocation.isValid()) {
                    return specialMethodInvocation;
                }
            }
            for (TypeDescription typeDescription : nonPrioritizedInterfaces) {
                SpecialMethodInvocation other = implementationTarget.invokeDefault(typeDescription, uniqueMethodSignature);
                if (specialMethodInvocation.isValid() && other.isValid()) {
                    throw new IllegalStateException(methodDescription + " has an ambiguous default method with "
                            + other.getMethodDescription() + " and " + specialMethodInvocation.getMethodDescription());
                }
                specialMethodInvocation = other;
            }
            return specialMethodInvocation;
        }

        @Override
        public boolean equals(Object other) {
            return this == other || !(other == null || getClass() != other.getClass())
                    && prioritizedInterfaces.equals(((Appender) other).prioritizedInterfaces)
                    && implementationTarget.equals(((Appender) other).implementationTarget);
        }

        @Override
        public int hashCode() {
            return 31 * implementationTarget.hashCode() + prioritizedInterfaces.hashCode();
        }

        @Override
        public String toString() {
            return "DefaultMethodCall.Appender{" +
                    "implementationTarget=" + implementationTarget +
                    ", prioritizedInterfaces=" + prioritizedInterfaces +
                    ", nonPrioritizedInterfaces=" + nonPrioritizedInterfaces +
                    '}';
        }
    }
}


text:
package jatoo.imager;

import java.awt.event.ActionEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.swing.AbstractAction;
import javax.swing.JFrame;

import jatoo.image.ImageMemoryCache;
import jatoo.image.ImageThumbnails;
import jatoo.image.ImageUtils;
import jatoo.ui.ImageLoaderOldV1;
import jatoo.ui.UIUtils;

@SuppressWarnings("serial")
public class JaTooImager extends JFrame {

  private static final int RESIZE_MOUSE_WHEEL_WIDTH_RATIO = (int) (UIUtils.getScreenWidth() * 0.01f);
  private static final int RESIZE_MOUSE_WHEEL_HEIGHT_RATIO = (int) (UIUtils.getScreenHeight() * 0.01f);

  static {
    UIUtils.setSystemLookAndFeel();
    // UITheme2.setTheme(JaTooImager.class);
  }

  public static void main(String[] args) throws Exception {
    // new JaTooImagerViewer(new File("src\\test\\resources\\image.jpg"));
    new JaTooImager(new File("d:\\OneDrive - PSS Prosoft Solutions\\Cristi - Personal\\Photos\\Share\\2013.10.21 - USA\\FB\\IMG_20131024_085105.jpg"));
  }

  private ImageMemoryCache imagesMemoryCache = new ImageMemoryCache();
  private ImageMemoryCache iconsMemoryCache = new ImageMemoryCache();

  private ImageThumbnails thumbnails = new ImageThumbnails();

  private List<File> files;
  private int filesIndex;

  private JaTooImagerCanvas canvas;

  private ImageLoaderOldV1 imageLoader;

  public JaTooImager(File file) throws Exception {

    //
    // files

    files = new ArrayList<>(Arrays.asList(file.getParentFile().listFiles(new FileFilter() {
      public boolean accept(File file) {
        return file.isFile();
      }
    })));
    filesIndex = files.indexOf(file);

    //
    // canvas

    canvas = new JaTooImagerCanvas();

    canvas.addMouseWheelListener(new ResizeMouseWheelListener());

    UIUtils.forwardDragAsMove(canvas, this);
    UIUtils.disableDecorations(JaTooImager.this);

    UIUtils.setActionForEscapeKeyStroke(canvas, new AbstractAction() {
      public void actionPerformed(ActionEvent e) {
        JaTooImager.this.setVisible(false);
        JaTooImager.this.dispose();
      }
    });

    UIUtils.setActionForLeftKeyStroke(canvas, new AbstractAction() {
      public void actionPerformed(ActionEvent e) {

        filesIndex--;
        if (filesIndex < 0) {
          filesIndex = files.size() - 1;
        }

        showImage(files.get(filesIndex));
      }
    });

    UIUtils.setActionForRightKeyStroke(canvas, new AbstractAction() {
      public void actionPerformed(ActionEvent e) {

        synchronized (files) {

          filesIndex++;
          if (filesIndex >= files.size()) {
            filesIndex = 0;
          }

          showImage(files.get(filesIndex));
        }
      }
    });

    setContentPane(canvas);

    //
    // frame

    setTitle(file.getName());
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    UIUtils.centerWindowOnScreen(this, 0, 25, 25);
    setVisible(true);

    //
    // show the image

    showImage(file);
  }

  private void showImage(final File file) {

    //
    // first of all check the image in the memory cache

    BufferedImage imageCached = imagesMemoryCache.get(file);

    if (imageCached != null) {

      if (imageLoader != null) {
        imageLoader.forceStop();
      }

      showImage(file, imageCached, true);

      return;
    }

    //
    // start a new image loader
    // but only after the previous one is stopped

    canvas.showLoader();

    if (imageLoader != null) {
      imageLoader.forceStop();
    }

    imageLoader = new ImageLoaderOldV1(file) {

      @Override
      protected void onLoaderStart(File file, boolean isForceStop) {

        //
        // get the thumbnail, but only if there is one already created
        // will be created with the image already loaded

        BufferedImage thumbnail = thumbnails.get(file, 32, 32, false, true, ImageUtils.FORMAT.JPG);

        if (thumbnail != null) {
          showImage(file, thumbnail, false);
        } else {
          showImage(file, null, false);
        }
      }

      @Override
      protected void onImageLoaded(File file, BufferedImage image) {

        //
        // - show the image
        // - update the cache
        // - force the creation of the thumbnail

        showImage(file, image, false);

        imagesMemoryCache.put(file, image);
        thumbnails.get(file, image, 32, 32, true, true, ImageUtils.FORMAT.JPG);
      }

      @Override
      protected void onLoaderStop(File file, boolean isForceStop) {

        //
        // don't hide the loading indicator on a force stop
        // it means that a new loading operation started

        if (!isForceStop) {
          canvas.hideLoader();
        }
      }
    };
  }

  private void showImage(final File file, final BufferedImage image, final boolean hideLoader) {

    canvas.setImage(image);

    if (image == null) {
      setIconImage(null);
    }

    else {

      BufferedImage icon = iconsMemoryCache.get(file);

      if (icon == null) {
        icon = thumbnails.get(file, 32, 32, true, false, ImageUtils.FORMAT.JPG);
        iconsMemoryCache.put(file, icon);
      }

      setIconImage(icon);
    }

    if (hideLoader) {
      canvas.hideLoader();
    }
  }

  private class ResizeMouseWheelListener implements MouseWheelListener {

    @Override
    public void mouseWheelMoved(MouseWheelEvent e) {

      final int widthRatio, heightRatio;

      if (e.getPreciseWheelRotation() > 0) {
        widthRatio = -RESIZE_MOUSE_WHEEL_WIDTH_RATIO;
        heightRatio = -RESIZE_MOUSE_WHEEL_HEIGHT_RATIO;
      }

      else {
        widthRatio = +RESIZE_MOUSE_WHEEL_WIDTH_RATIO;
        heightRatio = +RESIZE_MOUSE_WHEEL_HEIGHT_RATIO;
      }

      setSize(getWidth() + widthRatio, getHeight() + heightRatio);
    }
  }

}

redpajama_set_name: RedPajamaGithub


text:
#ifndef DESTRUCTIBLE_ASSET_PROXY_H
#define DESTRUCTIBLE_ASSET_PROXY_H

#include "ModuleDestructible.h"
#include "NxDestructibleAsset.h"
#include "DestructibleAsset.h"
#include "PsUserAllocated.h"
#include "authoring/Fracturing.h"
#include "PsShare.h"
#include "ApexAuthorableObject.h"
#include "ApexAssetAuthoring.h"

#include "PsArray.h"
#include "NxParameterized.h"

#include "ApexRWLockable.h"
#include "ReadCheck.h"
#include "WriteCheck.h"

#pragma warning(disable: 4355) // 'this' : used in base member initialization list

namespace physx
{
namespace apex
{
namespace destructible
{

class DestructibleAssetProxy : public NxDestructibleAsset, public NxApexResource, public physx::UserAllocated, public ApexRWLockable
{
public:
	APEX_RW_LOCKABLE_BOILERPLATE

	DestructibleAsset impl;

	DestructibleAssetProxy(ModuleDestructible* module, NxResourceList& list, const char* name) :
		impl(module, this, name)
	{
		list.add(*this);
	}

	DestructibleAssetProxy(ModuleDestructible* module, NxResourceList& list, NxParameterized::Interface* params, const char* name) :
		impl(module, this, params, name)
	{
		list.add(*this);
	}

	~DestructibleAssetProxy()
	{
	}

	physx::PxBounds3 getChunkActorLocalBounds(physx::PxU32 chunkIndex) const
	{
		NX_READ_ZONE();
		return impl.getChunkActorLocalBounds(chunkIndex);
	}

	const NxParameterized::Interface* getAssetNxParameterized() const
	{
		NX_READ_ZONE();
		return impl.getAssetNxParameterized();
	}

	/**
	* \brief Releases the ApexAsset but returns the NxParameterized::Interface and *ownership* to the caller.
	*/
	virtual NxParameterized::Interface* releaseAndReturnNxParameterizedInterface(void)
	{
		NxParameterized::Interface* ret = impl.acquireNxParameterizedInterface();
		release();
		return ret;
	}

	virtual void releaseDestructibleActor(NxDestructibleActor& actor)
	{
		NX_WRITE_ZONE();
		impl.releaseDestructibleActor(actor);
	}
	virtual NxDestructibleParameters getDestructibleParameters() const
	{
		return impl.getParameters();
	}
	virtual NxDestructibleInitParameters getDestructibleInitParameters() const
	{
		return impl.getInitParameters();
	}
	virtual physx::PxU32 getChunkCount() const
	{
		return impl.getChunkCount();
	}
	virtual physx::PxU32 getDepthCount() const
	{
		NX_READ_ZONE();
		return impl.getDepthCount();
	}
	virtual NxRenderMeshAsset* getRenderMeshAsset() const
	{
		NX_READ_ZONE();
		return impl.getRenderMeshAsset();
	}
	virtual bool setRenderMeshAsset(NxRenderMeshAsset* renderMeshAsset)
	{
		NX_WRITE_ZONE();
		return impl.setRenderMeshAsset(renderMeshAsset);
	}
	virtual physx::PxU32 getScatterMeshAssetCount() const
	{
		NX_READ_ZONE();
		return impl.getScatterMeshAssetCount();
	}
	virtual NxRenderMeshAsset* const * getScatterMeshAssets() const
	{
		NX_READ_ZONE();
		return impl.getScatterMeshAssets();
	}
	virtual physx::PxU32 getInstancedChunkMeshCount() const
	{
		NX_READ_ZONE();
		return impl.getInstancedChunkMeshCount();
	}
	virtual const char* getCrumbleEmitterName() const
	{
		NX_READ_ZONE();
		return impl.getCrumbleEmitterName();
	}
	virtual const char* getDustEmitterName() const
	{
		NX_READ_ZONE();
		return impl.getDustEmitterName();
	}
	virtual const char* getFracturePatternName() const
	{
		return impl.getFracturePatternName();
	}
	virtual void getStats(NxDestructibleAssetStats& stats) const
	{
		NX_READ_ZONE();
		impl.getStats(stats);
	}

	virtual void cacheChunkOverlapsUpToDepth(physx::PxI32 depth = -1)
	{
		NX_WRITE_ZONE();
		impl.cacheChunkOverlapsUpToDepth(depth);
	}

	virtual void clearChunkOverlaps(physx::PxI32 depth = -1, bool keepCachedFlag = false)
	{
		impl.clearChunkOverlaps(depth, keepCachedFlag);
	}

	virtual void addChunkOverlaps(NxIntPair* supportGraphEdges, PxU32 numSupportGraphEdges)
	{
		impl.addChunkOverlaps(supportGraphEdges, numSupportGraphEdges);
	}

	virtual void removeChunkOverlaps(NxIntPair* supportGraphEdges, PxU32 numSupportGraphEdges, bool keepCachedFlagIfEmpty)
	{
		impl.removeChunkOverlaps(supportGraphEdges, numSupportGraphEdges, keepCachedFlagIfEmpty);
	}

	virtual physx::PxU32 getCachedOverlapCountAtDepth(physx::PxU32 depth) const
	{
		NX_READ_ZONE();
		CachedOverlapsNS::IntPair_DynamicArray1D_Type* pairArray = impl.getOverlapsAtDepth(depth, false);
		return physx::PxU32(pairArray != NULL ? pairArray->arraySizes[0] : 0);
	}

	virtual const NxIntPair* getCachedOverlapsAtDepth(physx::PxU32 depth) const
	{
		NX_READ_ZONE();
		CachedOverlapsNS::IntPair_DynamicArray1D_Type* pairArray = impl.getOverlapsAtDepth(depth, false);
		PX_ASSERT(sizeof(NxIntPair) == pairArray->elementSize);
		return pairArray != NULL ? (const NxIntPair*)pairArray->buf : NULL;
	}

	NxParameterized::Interface* getDefaultActorDesc()
	{
		return impl.getDefaultActorDesc();
	}

	NxParameterized::Interface* getDefaultAssetPreviewDesc()
	{
		return impl.getDefaultAssetPreviewDesc();
	}

	virtual NxApexActor* createApexActor(const NxParameterized::Interface& parms, NxApexScene& apexScene)
	{
		return impl.createApexActor(parms, apexScene);
	}

	virtual NxDestructibleActor* createDestructibleActorFromDeserializedState(NxParameterized::Interface* parms, NxApexScene& apexScene)
	{
		NX_WRITE_ZONE();
		return impl.createDestructibleActorFromDeserializedState(parms, apexScene);
	}

	virtual NxApexAssetPreview* createApexAssetPreview(const NxParameterized::Interface& params, NxApexAssetPreviewScene* /*previewScene*/)
	{
		return impl.createApexAssetPreview(params, NULL);
	}

	virtual bool isValidForActorCreation(const ::NxParameterized::Interface& parms, NxApexScene& apexScene) const
	{
		return impl.isValidForActorCreation(parms, apexScene);
	}

	virtual bool isDirty() const
	{
		return false;
	}

	virtual physx::PxVec3 getChunkPositionOffset(physx::PxU32 chunkIndex) const
	{
		NX_READ_ZONE();
		return impl.getChunkPositionOffset(chunkIndex);
	}

	virtual physx::PxVec2 getChunkUVOffset(physx::PxU32 chunkIndex) const
	{
		NX_READ_ZONE();
		return impl.getChunkUVOffset(chunkIndex);
	}

	virtual physx::PxU32 getChunkFlags(physx::PxU32 chunkIndex) const
	{
		NX_READ_ZONE();
		return impl.getChunkFlags(chunkIndex);
	}

	virtual physx::PxU16 getChunkDepth(physx::PxU32 chunkIndex) const
	{
		NX_READ_ZONE();
		return impl.getChunkDepth(chunkIndex);
	}

	virtual physx::PxI32 getChunkParentIndex(physx::PxU32 chunkIndex) const
	{
		NX_READ_ZONE();
		const physx::PxU16 chunkParentIndex = impl.getChunkParentIndex(chunkIndex);
		return chunkParentIndex != DestructibleAsset::InvalidChunkIndex ? (physx::PxI32)chunkParentIndex : -1;
	}

	virtual physx::PxU32 getPartIndex(physx::PxU32 chunkIndex) const
	{
		NX_READ_ZONE();
		return impl.getPartIndex(chunkIndex);
	}

	virtual physx::PxU32 getPartConvexHullCount(const physx::PxU32 partIndex) const
	{
		NX_READ_ZONE();
		return impl.getPartHullIndexStop(partIndex) - impl.getPartHullIndexStart(partIndex);
	}

	virtual NxParameterized::Interface** getPartConvexHullArray(const physx::PxU32 partIndex) const
	{
		NX_READ_ZONE();
		return impl.getConvexHullParameters(impl.getPartHullIndexStart(partIndex));
	}

	physx::PxU32 getActorTransformCount() const
	{
		NX_READ_ZONE();
		return impl.getActorTransformCount();
	}
	const physx::PxMat44* getActorTransforms() const
	{
		NX_READ_ZONE();
		return impl.getActorTransforms();
	}

	void applyTransformation(const physx::PxMat44& transformation, physx::PxF32 scale)
	{
		NX_WRITE_ZONE();
		impl.applyTransformation(transformation, scale);
	}
	void applyTransformation(const physx::PxMat44& transformation)
	{
		NX_WRITE_ZONE();
		impl.applyTransformation(transformation);
	}

	virtual bool rebuildCollisionGeometry(physx::PxU32 partIndex, const NxDestructibleGeometryDesc& geometryDesc)
	{
		NX_WRITE_ZONE();
		return impl.rebuildCollisionGeometry(partIndex, geometryDesc);
	}

	// NxApexInterface methods
	virtual void release()
	{
		NX_WRITE_ZONE();
		impl.getOwner()->mSdk->releaseAsset(*this);
	}
	virtual void destroy()
	{
		impl.cleanup();
		delete this;
	}

	// NxApexAsset methods
	virtual const char* getName() const
	{
		NX_READ_ZONE();
		return impl.getName();
	}
	static const char* 		getClassName()
	{
		return NX_DESTRUCTIBLE_AUTHORING_TYPE_NAME;
	}
	virtual NxAuthObjTypeID	getObjTypeID() const
	{
		return impl.getObjTypeID();
	}
	virtual const char* getObjTypeName() const
	{
		return impl.getObjTypeName();
	}
	virtual physx::PxU32 forceLoadAssets()
	{
		return impl.forceLoadAssets();
	}

	// NxApexResource methods
	virtual void	setListIndex(NxResourceList& list, physx::PxU32 index)
	{
		impl.m_listIndex = index;
		impl.m_list = &list;
	}
	virtual physx::PxU32	getListIndex() const
	{
		return impl.m_listIndex;
	}

	friend class DestructibleActor;
};

#ifndef WITHOUT_APEX_AUTHORING
class DestructibleAssetAuthoringProxy : public NxDestructibleAssetAuthoring, public NxApexResource, public ApexAssetAuthoring, public physx::UserAllocated, public ApexRWLockable
{
public:
	APEX_RW_LOCKABLE_BOILERPLATE

	DestructibleAssetAuthoring impl;

	DestructibleAssetAuthoringProxy(ModuleDestructible* module, NxResourceList& list) :
		impl(module, NULL, "DestructibleAuthoring")
	{
		list.add(*this);
	}

	DestructibleAssetAuthoringProxy(ModuleDestructible* module, NxResourceList& list, const char* name) :
		impl(module, NULL, name)
	{
		list.add(*this);
	}

	DestructibleAssetAuthoringProxy(ModuleDestructible* module, NxResourceList& list, NxParameterized::Interface* params, const char* name) :
		impl(module, NULL, params, name)
	{
		list.add(*this);
	}

	virtual ~DestructibleAssetAuthoringProxy()
	{
	}

	// NxDestructibleAssetAuthoring methods

	virtual NxExplicitHierarchicalMesh& getExplicitHierarchicalMesh()
	{
		return impl.hMesh;
	}

	virtual NxExplicitHierarchicalMesh& getCoreExplicitHierarchicalMesh()
	{
		return impl.hMeshCore;
	}

	virtual NxCutoutSet&	getCutoutSet()
	{
		return impl.cutoutSet;
	}

	virtual physx::PxU32					partitionMeshByIslands
	(
		physx::NxExplicitRenderTriangle* mesh,
		physx::PxU32 meshTriangleCount,
	    physx::PxU32* meshPartition,
	    physx::PxU32 meshPartitionMaxCount,
		physx::PxF32 padding
	)
	{
		return ::FractureTools::partitionMeshByIslands(mesh, meshTriangleCount, meshPartition, meshPartitionMaxCount, padding);
	}

	virtual bool	setRootMesh
	(
	    const NxExplicitRenderTriangle* meshTriangles,
	    physx::PxU32 meshTriangleCount,
	    const NxExplicitSubmeshData* submeshData,
	    physx::PxU32 submeshCount,
	    physx::PxU32* meshPartition = NULL,
	    physx::PxU32 meshPartitionCount = 0,
		physx::PxI32* parentIndices = NULL,
		physx::PxU32 parentIndexCount = 0
	)
	{
		return ::FractureTools::buildExplicitHierarchicalMesh(impl.hMesh, meshTriangles, meshTriangleCount, submeshData, submeshCount, meshPartition, meshPartitionCount, parentIndices, parentIndexCount);
	}

	virtual bool	importRenderMeshAssetToRootMesh(const physx::NxRenderMeshAsset& renderMeshAsset, physx::PxU32 maxRootDepth = PX_MAX_U32)
	{
		return ::FractureTools::buildExplicitHierarchicalMeshFromRenderMeshAsset(impl.hMesh, renderMeshAsset, maxRootDepth);
	}

	virtual bool	importDestructibleAssetToRootMesh(const NxDestructibleAsset& destructibleAsset, physx::PxU32 maxRootDepth = PX_MAX_U32)
	{
		return ::FractureTools::buildExplicitHierarchicalMeshFromDestructibleAsset(impl.hMesh, destructibleAsset, maxRootDepth);
	}

	virtual bool	setCoreMesh
	(
	    const NxExplicitRenderTriangle* meshTriangles,
	    physx::PxU32 meshTriangleCount,
	    const NxExplicitSubmeshData* submeshData,
	    physx::PxU32 submeshCount,
	    physx::PxU32* meshPartition = NULL,
	    physx::PxU32 meshPartitionCount = 0
	)
	{
		return ::FractureTools::buildExplicitHierarchicalMesh(impl.hMeshCore, meshTriangles, meshTriangleCount, submeshData, submeshCount, meshPartition, meshPartitionCount);
	}

	virtual bool buildExplicitHierarchicalMesh
	(
		NxExplicitHierarchicalMesh& hMesh,
		const NxExplicitRenderTriangle* meshTriangles,
		physx::PxU32 meshTriangleCount,
		const NxExplicitSubmeshData* submeshData,
		physx::PxU32 submeshCount,
		physx::PxU32* meshPartition = NULL,
		physx::PxU32 meshPartitionCount = 0,
		physx::PxI32* parentIndices = NULL,
		physx::PxU32 parentIndexCount = 0
	)
	{
		return ::FractureTools::buildExplicitHierarchicalMesh(hMesh, meshTriangles, meshTriangleCount, submeshData, submeshCount, meshPartition, meshPartitionCount, parentIndices, parentIndexCount);
	}

	virtual bool	createHierarchicallySplitMesh
	(
	    const NxMeshProcessingParameters& meshProcessingParams,
	    const NxFractureSliceDesc& desc,
	    const NxCollisionDesc& collisionDesc,
	    bool exportCoreMesh,
		physx::PxI32 coreMeshImprintSubmeshIndex,
	    physx::PxU32 randomSeed,
	    IProgressListener& progressListener,
	    volatile bool* cancel = NULL
	)
	{
		return ::FractureTools::createHierarchicallySplitMesh(impl.hMesh, impl.hMeshCore, exportCoreMesh, coreMeshImprintSubmeshIndex,
		        meshProcessingParams, desc, collisionDesc, randomSeed, progressListener, cancel);
	}

	virtual bool	createVoronoiSplitMesh
	(
		const ::FractureTools::NxMeshProcessingParameters& meshProcessingParams,
		const ::FractureTools::NxFractureVoronoiDesc& desc,
		const NxCollisionDesc& collisionDesc,
		bool exportCoreMesh,
		physx::PxI32 coreMeshImprintSubmeshIndex,
		physx::PxU32 randomSeed,
		IProgressListener& progressListener,
		volatile bool* cancel = NULL
	)
	{
		return ::FractureTools::createVoronoiSplitMesh(impl.hMesh, impl.hMeshCore, exportCoreMesh, coreMeshImprintSubmeshIndex,
				meshProcessingParams, desc, collisionDesc, randomSeed, progressListener, cancel);
	}

	virtual bool	hierarchicallySplitChunk
	(
		physx::PxU32 chunkIndex,
	    const ::FractureTools::NxMeshProcessingParameters& meshProcessingParams,
	    const ::FractureTools::NxFractureSliceDesc& desc,
	    const physx::NxCollisionDesc& collisionDesc,
	    physx::PxU32* randomSeed,
	    IProgressListener& progressListener,
	    volatile bool* cancel = NULL
	)
	{
		return ::FractureTools::hierarchicallySplitChunk(impl.hMesh, chunkIndex, meshProcessingParams, desc, collisionDesc, randomSeed, progressListener, cancel);
	}

	virtual bool	voronoiSplitChunk
		(
		physx::PxU32 chunkIndex,
		const ::FractureTools::NxMeshProcessingParameters& meshProcessingParams,
		const ::FractureTools::NxFractureVoronoiDesc& desc,
		const physx::NxCollisionDesc& collisionDesc,
		physx::PxU32* randomSeed,
		IProgressListener& progressListener,
		volatile bool* cancel = NULL
		)
	{
		return ::FractureTools::voronoiSplitChunk(impl.hMesh, chunkIndex, meshProcessingParams, desc, collisionDesc, randomSeed, progressListener, cancel);
	}

	virtual bool	createChippedMesh
	(
	    const NxMeshProcessingParameters& meshProcessingParams,
	    const NxFractureCutoutDesc& desc,
	    const NxCutoutSet& iCutoutSet,
	    const NxFractureSliceDesc& sliceDesc,
		const physx::NxFractureVoronoiDesc& voronoiDesc,
	    const physx::NxCollisionDesc& collisionDesc,
	    physx::PxU32 randomSeed,
	    IProgressListener& progressListener,
	    volatile bool* cancel = NULL
	)
	{
		return ::FractureTools::createChippedMesh(impl.hMesh, meshProcessingParams, desc, iCutoutSet, sliceDesc, voronoiDesc, collisionDesc, randomSeed, progressListener, cancel);
	}

	virtual void	buildCutoutSet
	(
	    const physx::PxU8* pixelBuffer,
	    physx::PxU32 bufferWidth,
	    physx::PxU32 bufferHeight,
	    physx::PxF32 snapThreshold,
		bool periodic
	)
	{
		::FractureTools::buildCutoutSet(impl.cutoutSet, pixelBuffer, bufferWidth, bufferHeight, snapThreshold, periodic);
	}

	virtual bool	calculateCutoutUVMapping(physx::PxMat33& mapping, const physx::NxExplicitRenderTriangle& triangle)
	{
		return ::FractureTools::calculateCutoutUVMapping(triangle, mapping);
	}

	virtual bool	calculateCutoutUVMapping(physx::PxMat33& mapping, const physx::PxVec3& targetDirection)
	{
		return ::FractureTools::calculateCutoutUVMapping(impl.hMesh, targetDirection, mapping);
	}

	virtual physx::PxU32	createVoronoiSitesInsideMesh
	(
		physx::PxVec3* siteBuffer,
		physx::PxU32* siteChunkIndices,
		physx::PxU32 siteCount,
		physx::PxU32* randomSeed,
		physx::PxU32* microgridSize,
		IProgressListener& progressListener,
		physx::PxU32 chunkIndex = 0xFFFFFFFF
	)
	{
		return ::FractureTools::createVoronoiSitesInsideMesh(impl.hMesh, siteBuffer, siteChunkIndices, siteCount, randomSeed, microgridSize, progressListener, chunkIndex);
	}

	physx::PxU32	createScatterMeshSites
	(
		physx::PxU8*						meshIndices,
		physx::PxMat44*						relativeTransforms,
		physx::PxU32*						chunkMeshStarts,
		physx::PxU32						scatterMeshInstancesBufferSize,
		physx::PxU32						targetChunkCount,
		const physx::PxU16*					targetChunkIndices,
		physx::PxU32*						randomSeed,
		physx::PxU32						scatterMeshAssetCount,
		physx::NxRenderMeshAsset**			scatterMeshAssets,
		const physx::PxU32*					minCount,
		const physx::PxU32*					maxCount,
		const physx::PxF32*					minScales,
		const physx::PxF32*					maxScales,
		const physx::PxF32*					maxAngles
	)
	{
		return ::FractureTools::createScatterMeshSites(meshIndices, relativeTransforms, chunkMeshStarts, scatterMeshInstancesBufferSize, impl.hMesh, targetChunkCount, targetChunkIndices,
													 randomSeed, scatterMeshAssetCount, scatterMeshAssets, minCount, maxCount, minScales, maxScales, maxAngles);
	}

	virtual void	visualizeVoronoiCells
	(
		physx::NxApexRenderDebug& debugRender,
		const physx::PxVec3* sites,
		physx::PxU32 siteCount,
		const physx::PxU32* cellColors,
		physx::PxU32 cellColorCount,
		const physx::PxBounds3& bounds,
		physx::PxU32 cellIndex = 0xFFFFFFFF
	)
	{
		::FractureTools::visualizeVoronoiCells(debugRender, sites, siteCount, cellColors, cellColorCount, bounds, cellIndex);
	}

	virtual void	setBSPTolerances
	(
		physx::PxF32 linearTolerance,
		physx::PxF32 angularTolerance,
		physx::PxF32 baseTolerance,
		physx::PxF32 clipTolerance,
		physx::PxF32 cleaningTolerance
	)
	{
		::FractureTools::setBSPTolerances(linearTolerance, angularTolerance, baseTolerance, clipTolerance, cleaningTolerance);
	}

	virtual void	setBSPBuildParameters
	(
		physx::PxF32 logAreaSigmaThreshold,
		physx::PxU32 testSetSize,
		physx::PxF32 splitWeight,
		physx::PxF32 imbalanceWeight
	)
	{
		::FractureTools::setBSPBuildParameters(logAreaSigmaThreshold, testSetSize, splitWeight, imbalanceWeight);
	}

	virtual NxExplicitHierarchicalMesh::NxConvexHull*	createExplicitHierarchicalMeshConvexHull()
	{
		return ::FractureTools::createExplicitHierarchicalMeshConvexHull();
	}

	virtual physx::PxU32 buildSliceMesh(const NxExplicitRenderTriangle*& mesh, const ::FractureTools::NxNoiseParameters& noiseParameters, const physx::PxPlane& slicePlane, physx::PxU32 randomSeed)
	{
		if( ::FractureTools::buildSliceMesh(impl.intersectMesh, impl.hMesh, slicePlane, noiseParameters, randomSeed) )
		{
			mesh = impl.intersectMesh.m_triangles.begin();
			return impl.intersectMesh.m_triangles.size();
		}

		mesh = NULL;
		return 0;
	}

	virtual void setChunkOverlapsCacheDepth(physx::PxI32 depth = -1)
	{
		impl.setChunkOverlapsCacheDepth(depth);
	}
	virtual NxRenderMeshAsset* getRenderMeshAsset() const
	{
		return impl.getRenderMeshAsset();
	}
	virtual bool setRenderMeshAsset(NxRenderMeshAsset* renderMeshAsset)
	{
		return impl.setRenderMeshAsset(renderMeshAsset);
	}
	virtual bool setScatterMeshAssets(NxRenderMeshAsset** scatterMeshAssetArray, physx::PxU32 scatterMeshAssetArraySize)
	{
		return impl.setScatterMeshAssets(scatterMeshAssetArray, scatterMeshAssetArraySize);
	}
	virtual physx::PxU32 getScatterMeshAssetCount() const
	{
		return impl.getScatterMeshAssetCount();
	}
	virtual NxRenderMeshAsset* const * getScatterMeshAssets() const
	{
		return impl.getScatterMeshAssets();
	}
	virtual physx::PxU32 getInstancedChunkMeshCount() const
	{
		return impl.getInstancedChunkMeshCount();
	}
	virtual void setDestructibleParameters(const NxDestructibleParameters& parameters)
	{
		impl.setParameters(parameters);
	}
	virtual NxDestructibleParameters getDestructibleParameters() const
	{
		NX_READ_ZONE();
		return impl.getParameters();
	}
	virtual void setDestructibleInitParameters(const NxDestructibleInitParameters& parameters)
	{
		impl.setInitParameters(parameters);
	}
	virtual NxDestructibleInitParameters	getDestructibleInitParameters() const
	{
		NX_READ_ZONE();
		return impl.getInitParameters();
	}
	virtual void setCrumbleEmitterName(const char* name)
	{
		impl.setCrumbleEmitterName(name);
	}
	virtual void setDustEmitterName(const char* name)
	{
		impl.setDustEmitterName(name);
	}
	virtual void setFracturePatternName(const char* name)
	{
		impl.setFracturePatternName(name);
	}
	virtual void cookChunks(const NxDestructibleAssetCookingDesc& cookingDesc, bool cacheOverlaps, PxU32* chunkIndexMapUser2Apex, PxU32* chunkIndexMapApex2User, PxU32 chunkIndexMapCount)
	{
		impl.cookChunks(cookingDesc, cacheOverlaps, chunkIndexMapApex2User, chunkIndexMapUser2Apex, chunkIndexMapCount);
	}
	virtual void serializeFractureToolState(physx::PxFileBuf& stream, physx::NxExplicitHierarchicalMesh::NxEmbedding& embedding) const
	{
		impl.serializeFractureToolState(stream, embedding);
	}
	virtual void deserializeFractureToolState(physx::PxFileBuf& stream, physx::NxExplicitHierarchicalMesh::NxEmbedding& embedding)
	{
		impl.deserializeFractureToolState(stream, embedding);
	}
	virtual physx::PxU32 getChunkCount() const
	{
		NX_READ_ZONE();
		return impl.getChunkCount();
	}
	virtual physx::PxU32 getDepthCount() const
	{
		return impl.getDepthCount();
	}
	virtual physx::PxU32 getChunkChildCount(physx::PxU32 chunkIndex) const
	{
		return impl.getChunkChildCount(chunkIndex);
	}
	virtual physx::PxI32 getChunkChild(physx::PxU32 chunkIndex, physx::PxU32 childIndex) const
	{
		return impl.getChunkChild(chunkIndex, childIndex);
	}
	virtual physx::PxVec3 getChunkPositionOffset(physx::PxU32 chunkIndex) const
	{
		return impl.getChunkPositionOffset(chunkIndex);
	}
	virtual physx::PxVec2 getChunkUVOffset(physx::PxU32 chunkIndex) const
	{
		return impl.getChunkUVOffset(chunkIndex);
	}
	virtual physx::PxU32 getPartIndex(physx::PxU32 chunkIndex) const
	{
		return impl.getPartIndex(chunkIndex);
	}
	virtual void trimCollisionGeometry(const physx::PxU32* partIndices, physx::PxU32 partIndexCount, physx::PxF32 maxTrimFraction = 0.2f)
	{
		impl.trimCollisionGeometry(partIndices, partIndexCount, maxTrimFraction);
	}
	virtual physx::PxF32 getImpactVelocityThreshold() const
	{
		return impl.getImpactVelocityThreshold();
	}
	void setImpactVelocityThreshold(physx::PxF32 threshold)
	{
		impl.setImpactVelocityThreshold(threshold);
	}
	virtual physx::PxF32 getFractureImpulseScale() const
	{
		return impl.getFractureImpulseScale();
	}
	void setFractureImpulseScale(physx::PxF32 scale)
	{
		impl.setFractureImpulseScale(scale);
	}
	virtual void getStats(NxDestructibleAssetStats& stats) const
	{
		impl.getStats(stats);
	}

	virtual void cacheChunkOverlapsUpToDepth(physx::PxI32 depth = -1)
	{
		impl.cacheChunkOverlapsUpToDepth(depth);
	}

	virtual void clearChunkOverlaps(physx::PxI32 depth = -1, bool keepCachedFlag = false)
	{
		impl.clearChunkOverlaps(depth, keepCachedFlag);
	}

	virtual void addChunkOverlaps(NxIntPair* supportGraphEdges, PxU32 numSupportGraphEdges)
	{
		impl.addChunkOverlaps(supportGraphEdges, numSupportGraphEdges);
	}

	virtual void removeChunkOverlaps(NxIntPair* supportGraphEdges, PxU32 numSupportGraphEdges, bool keepCachedFlagIfEmpty)
	{
		impl.removeChunkOverlaps(supportGraphEdges, numSupportGraphEdges, keepCachedFlagIfEmpty);
	}

	virtual physx::PxU32 getCachedOverlapCountAtDepth(physx::PxU32 depth)
	{
		CachedOverlapsNS::IntPair_DynamicArray1D_Type* pairArray = impl.getOverlapsAtDepth(depth, false);
		return physx::PxU32(pairArray != NULL ? pairArray->arraySizes[0] : 0);
	}

	virtual const NxIntPair* getCachedOverlapsAtDepth(physx::PxU32 depth)
	{
		CachedOverlapsNS::IntPair_DynamicArray1D_Type* pairArray = impl.getOverlapsAtDepth(depth, false);
		PX_ASSERT(sizeof(NxIntPair) == pairArray->elementSize);
		return pairArray != NULL ? (const NxIntPair*)pairArray->buf : NULL;
	}
	virtual void setNeighborPadding(physx::PxF32 neighborPadding)
	{
		impl.setNeighborPadding(neighborPadding);
	}
	virtual physx::PxF32 getNeighborPadding() const
	{
		return impl.getNeighborPadding();
	}
	void applyTransformation(const physx::PxMat44& transformation, physx::PxF32 scale)
	{
		impl.applyTransformation(transformation, scale);
	}
	void applyTransformation(const physx::PxMat44& transformation)
	{
		impl.applyTransformation(transformation);
	}

	bool setPlatformMaxDepth(NxPlatformTag platform, physx::PxU32 maxDepth)
	{
		return impl.setPlatformMaxDepth(platform, maxDepth);
	}

	bool removePlatformMaxDepth(NxPlatformTag platform)
	{
		return impl.removePlatformMaxDepth(platform);
	}

	// NxApexAssetAuthoring methods

	const char* getName(void) const
	{
		return impl.getName();
	}

	const char* getObjTypeName() const
	{
		return impl.getObjTypeName();
	}

	virtual bool prepareForPlatform(physx::apex::NxPlatformTag platformTag)
	{
		return impl.prepareForPlatform(platformTag);
	}

	void setToolString(const char* toolName, const char* toolVersion, PxU32 toolChangelist)
	{
		ApexAssetAuthoring::setToolString(toolName, toolVersion, toolChangelist);
	}

	void setToolString(const char* toolString)
	{
		impl.setToolString(toolString);
	}

	physx::PxU32 getActorTransformCount() const
	{
		return impl.getActorTransformCount();
	}

	const physx::PxMat44* getActorTransforms() const
	{
		return impl.getActorTransforms();
	}

	void appendActorTransforms(const physx::PxMat44* transforms, physx::PxU32 transformCount)
	{
		impl.appendActorTransforms(transforms, transformCount);
	}

	void clearActorTransforms()
	{
		impl.clearActorTransforms();
	}

	NxParameterized::Interface* getNxParameterized() const
	{
		return (NxParameterized::Interface*)impl.getAssetNxParameterized();
	}

	/**
	* \brief Releases the ApexAsset but returns the NxParameterized::Interface and *ownership* to the caller.
	*/
	virtual NxParameterized::Interface* releaseAndReturnNxParameterizedInterface(void)
	{
		NxParameterized::Interface* ret = impl.acquireNxParameterizedInterface();
		release();
		return ret;
	}

	// NxApexResource methods
	virtual void	setListIndex(NxResourceList& list, physx::PxU32 index)
	{
		impl.m_listIndex = index;
		impl.m_list = &list;
	}
	virtual physx::PxU32	getListIndex() const
	{
		return impl.m_listIndex;
	}

	// NxApexInterface methods
	virtual void release()
	{
		impl.getOwner()->mSdk->releaseAssetAuthoring(*this);
	}
	virtual void destroy()
	{
		impl.cleanup();
		delete this;
	}
};
#endif

}
}
} // end namespace physx::apex

#endif // DESTRUCTIBLE_ASSET_PROXY_H


text:
namespace ash::cros_healthd::connectivity {

class ContextImpl : public Context {
 public:
  ContextImpl(std::unique_ptr<LocalState> local_state,
              std::unique_ptr<RemoteState> remote_state)
      : local_state_(std::move(local_state)),
        remote_state_(std::move(remote_state)) {}
  ContextImpl(const ContextImpl&) = delete;
  ContextImpl& operator=(const ContextImpl&) = delete;
  virtual ~ContextImpl() = default;

 public:
  LocalState* local_state() override { return local_state_.get(); }
  RemoteState* remote_state() override { return remote_state_.get(); }

 private:
  std::unique_ptr<LocalState> local_state_;
  std::unique_ptr<RemoteState> remote_state_;
};

std::unique_ptr<Context> Context::Create(
    std::unique_ptr<LocalState> local_state,
    std::unique_ptr<RemoteState> remote_state) {
  return std::make_unique<ContextImpl>(std::move(local_state),
                                       std::move(remote_state));
}

}  // namespace ash::cros_healthd::connectivity


text:
<?xml version="1.0"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
    <display-name>RestWithCXF</display-name>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>WEB-INF/cxf.xml</param-value>
    </context-param>
    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
    <servlet>
        <servlet-name>CXFServlet</servlet-name>
        <servlet-class>
            org.apache.cxf.transport.servlet.CXFServlet
        </servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>CXFServlet</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
</web-app>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/1999/REC-html401-19991224/strict.dtd">

	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<title>Message de {shop_name}</title>

Hola {firstname} {lastname},

Programa de Patrocinio

Le informamos de que usted acaba de obtener una orden de compra después de su remisión.

Aquí está su número de comprobante: {voucher_num}, de un total de {voucher_amount} euros.
Copia y pega este código en la canasta de tu próxima compra antes de ajustar el orden.

{shop_name} dirigida por PrestaShop™


text:
#import "ABI42_0_0RNCPicker.h"

#import <ABI42_0_0React/ABI42_0_0RCTConvert.h>
#import <ABI42_0_0React/ABI42_0_0RCTUtils.h>

@interface ABI42_0_0RNCPicker() <UIPickerViewDataSource, UIPickerViewDelegate>
@end

@implementation ABI42_0_0RNCPicker

- (instancetype)initWithFrame:(CGRect)frame
{
  if ((self = [super initWithFrame:frame])) {
    _color = [UIColor blackColor];
    _font = [UIFont systemFontOfSize:21]; // TODO: selected title default should be 23.5
    _selectedIndex = NSNotFound;
    _textAlign = NSTextAlignmentCenter;
    self.delegate = self;
    self.dataSource = self;
    [self selectRow:0 inComponent:0 animated:YES]; // Workaround for missing selection indicator lines (see https://stackoverflow.com/questions/39564660/uipickerview-selection-indicator-not-visible-in-ios10)
  }
  return self;
}

ABI42_0_0RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:(NSCoder *)aDecoder)

- (void)setItems:(NSArray<NSDictionary *> *)items
{
  _items = [items copy];
  [self setNeedsLayout];
}

- (void)setSelectedIndex:(NSInteger)selectedIndex
{
  if (_selectedIndex != selectedIndex) {
    BOOL animated = _selectedIndex != NSNotFound; // Don't animate the initial value
    _selectedIndex = selectedIndex;
    dispatch_async(dispatch_get_main_queue(), ^{
      [self selectRow:selectedIndex inComponent:0 animated:animated];
    });
  }
}

#pragma mark - UIPickerViewDataSource protocol

- (NSInteger)numberOfComponentsInPickerView:(__unused UIPickerView *)pickerView
{
  return 1;
}

- (NSInteger)pickerView:(__unused UIPickerView *)pickerView
numberOfRowsInComponent:(__unused NSInteger)component
{
  return _items.count;
}

#pragma mark - UIPickerViewDelegate methods

- (NSString *)pickerView:(__unused UIPickerView *)pickerView
             titleForRow:(NSInteger)row
            forComponent:(__unused NSInteger)component
{
  return [ABI42_0_0RCTConvert NSString:_items[row][@"label"]];
}

- (CGFloat)pickerView:(__unused UIPickerView *)pickerView rowHeightForComponent:(NSInteger)__unused component {
  return _font.pointSize + 19;
}

- (UIView *)pickerView:(UIPickerView *)pickerView
            viewForRow:(NSInteger)row
          forComponent:(NSInteger)component
           reusingView:(UILabel *)label
{
  if (!label) {
    label = [[UILabel alloc] initWithFrame:(CGRect){
      CGPointZero,
      {
        [pickerView rowSizeForComponent:component].width,
        [pickerView rowSizeForComponent:component].height,
      }
    }];
  }

  label.font = _font;

  label.textColor = [ABI42_0_0RCTConvert UIColor:_items[row][@"textColor"]] ?: _color;

  label.textAlignment = _textAlign;
  label.text = [self pickerView:pickerView titleForRow:row forComponent:component];
  label.accessibilityIdentifier = _items[row][@"testID"];
  return label;
}

- (void)pickerView:(__unused UIPickerView *)pickerView
      didSelectRow:(NSInteger)row inComponent:(__unused NSInteger)component
{
  _selectedIndex = row;
  if (_onChange && _items.count > (NSUInteger)row) {
    _onChange(@{
      @"newIndex": @(row),
      @"newValue": ABI42_0_0RCTNullIfNil(_items[row][@"value"]),
    });
  }
}

@end


text:
package com.example.hahaha.musicplayer.feature.play.control;

import android.os.Bundle;
import android.util.Log;
import com.example.hahaha.musicplayer.feature.base.BasePresenter;
import com.example.hahaha.musicplayer.feature.play.PlayActivity;
import com.example.hahaha.musicplayer.model.entity.internal.PlayStateInfo;
import com.example.hahaha.musicplayer.model.entity.internal.PositionInfo;
import com.example.hahaha.musicplayer.model.enumeration.PlayOrder;
import com.example.hahaha.musicplayer.service.proxy.MusicManagerProxy;
import com.example.hahaha.musicplayer.tools.PlayOrderTools;
import com.example.hahaha.musicplayer.widget.ComSubscriber;

public class PlayControlPresenter extends BasePresenter<PlayControlFragment> {
  private MusicManagerProxy mMusicManager;
  private ComSubscriber<PositionInfo> mPositionListener;
  private ComSubscriber<PlayStateInfo> mSongChangeListener;
  private int mDuration;
  private int mPlayOrder;

  @Override protected void onCreate(Bundle savedState) {
    super.onCreate(savedState);
    mPlayOrder = PlayOrder.NORMAL;
    mMusicManager = MusicManagerProxy.getInstance();
    initPositionStub();
    mSongChangeListener = new ComSubscriber<PlayStateInfo>() {
      @Override public void onChange(PlayStateInfo playStateInfo) {
        if (playStateInfo == null) return;
        PlayControlFragment fragment = getView();
        if (fragment == null) return;
        Log.d("xyz", "playstate change playorder = "+String.valueOf(playStateInfo.getPlayOrder()));
        fragment.setPlayOrder(PlayOrderTools.getDrawableRes(playStateInfo.getPlayOrder()));
        fragment.setIsPlaying(playStateInfo.isPlaying());
      }
    };
  }

  private void initPositionStub() {
    mPositionListener = new ComSubscriber<PositionInfo>() {
      @Override public void onChange(PositionInfo positionInfo) {
        mDuration = positionInfo.getDuration();
        PlayControlFragment fragment = getView();
        if (fragment == null) return;
        int progress = positionInfo.getCurrentTime() * 100 / mDuration;
        fragment.setProgress(progress, positionInfo.getCurrentTime(), mDuration);
      }
    };
  }

  @Override protected void onTakeView(PlayControlFragment playControlFragment) {
    super.onTakeView(playControlFragment);
    mMusicManager.addPositionListener(mPositionListener);
    mMusicManager.addSongChangeListener(mSongChangeListener);
  }

  @Override protected void onDropView() {
    super.onDropView();
    mMusicManager.removePositionListener(mPositionListener);
    mMusicManager.removeSongChangeListener(mSongChangeListener);
  }

  void setProgress(int progress) {
    int position = progress * mDuration / 100;
    mMusicManager.setPosition(position);
  }

  void playOrderClick() {
    Log.d("xyz", "play order click "+String.valueOf(mPlayOrder));
    switch (mPlayOrder) {
      case PlayOrder.NORMAL: mPlayOrder = PlayOrder.RANDOM; break;
      case PlayOrder.RANDOM: mPlayOrder = PlayOrder.SINGLE; break;
      case PlayOrder.SINGLE: mPlayOrder = PlayOrder.NORMAL; break;
    }
    Log.d("xyz", "after play order click "+String.valueOf(mPlayOrder));
    mMusicManager.setPlayOrder(mPlayOrder);
  }

  void prevSong() {
    mMusicManager.playPrevious();
  }

  void nextSong() {
    mMusicManager.playNext();
  }

  void playPause() {
    mMusicManager.playOrPause();
  }
}


text:
package com.martinchamarro.lazystorage;

import android.content.Context;

import com.martinchamarro.lazystorage.internal.database.Database;
import com.martinchamarro.lazystorage.internal.database.DatabaseImpl;
import com.martinchamarro.lazystorage.internal.exception.LazyStorageException;
import com.martinchamarro.lazystorage.utils.Logger;

import java.util.List;

/**
 *
 * This class is the point of access of the library.
 * All the methods of the class work synchronously, so it's necessary to call them
 * in background using a Thread, an AsyncTask or other thread implementation.
 *
 */
public final class LazyStorage {

    private static final String TAG = LazyStorage.class.getSimpleName();

    private Database database;

    public LazyStorage(Context context) {
        database = new DatabaseImpl(context);
    }

    /**
     * Saves an object to the database.
     * Uses an IdProvider to get the object id by reflection.
     *
     * @param object to save
     */
    public void save(Object object) {
        try {
            database.save(object);
        } catch (LazyStorageException e) {
            Logger.e(TAG, e);
        }
    }

    /**
     * Saves an object to the database.
     * Doesn't use reflection to get the id of the object.
     *
     * @param id of the object to save
     * @param object to save in the database
     */
    public void save(Object id, Object object) {
        try {
            database.save(id, object);
        } catch (LazyStorageException e) {
            Logger.e(TAG, e);
        }
    }

    /**
     * Saves a list of objects to the database.
     *
     * @param objects to save
     * @param <T>
     */
    public <T> void saveAll(List<T> objects) {
        try {
            database.saveAll(objects);
        } catch (LazyStorageException e) {
            Logger.e(TAG, e);
        }
    }

    /**
     * Loads an object from the database.
     *
     * @param id of the object to load
     * @param classOfT of the object to load
     * @param <T>
     * @return the object to load or null if the object doesn't exist or
     * there is some problem converting the saved data to an object.
     */
    public <T> T load(Object id, Class<T> classOfT) {
        T result = null;
        try {
            result = database.load(id, classOfT);
        } catch (LazyStorageException e) {
            Logger.e(TAG, e);
        }
        return result;
    }

    /**
     * Loads all the objects of the given class.
     *
     * @param classOfT is the class of the objects to load
     * @param <T>
     * @return a list of objects of the given class or an empty list if
     * there aren't objects of this class or there is a problem loading them.
     */
    public <T> List<T> loadAll(Class<T> classOfT) {
        List<T> result = null;
        try {
            result = database.loadAll(classOfT);
        } catch (LazyStorageException e) {
            Logger.e(TAG, e);
        }
        return result;
    }

    /**
     * Deletes from the database the object with the given id and the given class.
     *
     * @param id of the object to delete
     * @param classOfT of the object to delete
     * @param <T>
     */
    public <T> void delete(Object id, Class<T> classOfT) {
        try {
            database.delete(id, classOfT);
        } catch (LazyStorageException e) {
            Logger.e(TAG, e);
        }
    }

    /**
     * Deletes all the existing objects of the given class.
     *
     * @param classOfT of the all the objects to delete
     * @param <T>
     */
    public <T> void deleteAll(Class<T> classOfT) {
        try {
            database.deleteAll(classOfT);
        } catch (LazyStorageException e) {
            Logger.e(TAG, e);
        }
    }

    /**
     * Deletes all the given objects from the database.
     *
     * @param objects is the list of objects to delete
     * @param <T>
     */
    public <T> void deleteAll(List<T> objects) {
        try {
            database.deleteAll(objects);
        } catch (LazyStorageException e) {
            Logger.e(TAG, e);
        }
    }

    /**
     * Deletes all the content of the database.
     */
    public void invalidate() {
        try {
            database.invalidate();
        } catch (LazyStorageException e) {
            Logger.e(TAG, e);
        }
    }

    /**
     * Enables the log of the library that is disabled by default.
     */
    public void enableLogging() {
        Logger.enable();
    }
}


text:
#ifndef MINPRDPNGCONF_H
#define MINPRDPNGCONF_H

/* To include pngusr.h set -DPNG_USER_CONFIG in CPPFLAGS */

/* List options to turn off features of the build that do not
 * affect the API (so are not recorded in pnglibconf.h)
 */

#define PNG_ALIGN_TYPE PNG_ALIGN_NONE

#endif /* MINPRDPNGCONF_H */


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Trans. & Proc. Roy. Soc. S. Australia 43: 272 (1919)

#### Original name
Cantharellus corrugatus Cleland & Cheel

### Remarks
null


text:
package com.facebook.buck.features.apple.projectV2;

import com.facebook.buck.core.util.immutables.BuckStyleValueWithBuilder;
import org.immutables.value.Value;

/** Options for how {@link ProjectGenerator} generates Xcode projects. */
@BuckStyleValueWithBuilder
public interface ProjectGeneratorOptions {
  /** Use short BuildTarget name instead of full name for targets */
  @Value.Default
  default boolean shouldUseShortNamesForTargets() {
    return false;
  }

  /** Create schemes for each project's contained build and test targets. */
  @Value.Default
  default boolean shouldGenerateProjectSchemes() {
    return false;
  }

  /** Generate read-only project files */
  @Value.Default
  default boolean shouldGenerateReadOnlyFiles() {
    return false;
  }

  /** Include tests that test root targets in the scheme */
  @Value.Default
  default boolean shouldIncludeTests() {
    return false;
  }

  /** Include dependencies tests in the scheme */
  @Value.Default
  default boolean shouldIncludeDependenciesTests() {
    return false;
  }

  /** Generate an umbrella header for modular targets without one for use in a modulemap */
  @Value.Default
  default boolean shouldGenerateMissingUmbrellaHeader() {
    return false;
  }

  /** Add linker flags to OTHER_LDFLAGS to force load of libraries with link_whole = true */
  @Value.Default
  default boolean shouldForceLoadLinkWholeLibraries() {
    return false;
  }

  /** Add linker flags to OTHER_LDFLAGS for libraries rather than to the library build phase */
  @Value.Default
  default boolean shouldAddLinkedLibrariesAsFlags() {
    return false;
  }

  /** Add system swift library linker flags */
  @Value.Default
  default boolean shouldLinkSystemSwift() {
    return true;
  }

  static Builder builder() {
    return new Builder();
  }

  class Builder extends ImmutableProjectGeneratorOptions.Builder {}
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Casework | Design Studio</title>
<meta name="robots" content="index, follow" />
<meta http-equiv="imagetoolbar" content="no" />
<meta name="keywords" content="" />
<meta name="description" content="" />

<link rel="stylesheet" type="text/css" href="css/style.css" media="screen" />

首页

幻灯片

缩略图

展示

完整描述的展示

2列

3列

4列

分页展示

详细展示

快速查看

博客

简介

列表

特色

Typography & Shortcodes

Columns & Pricing Table

JavaScript Additions

页面布局

页面右侧栏

页面左侧栏

全宽页面

半宽页面

图像显示概述

联系

Blog / Join the conversation

Vestibulum adipiscing commodo tellus volutpat

                        Posted by Admin on March 28, 2012 in Web Design | 12 comments

Proin fermentum libero ac lectus commodo non congue velit. Nulla pellentesque, lacus commodo gravida, dui enim convallis lectus, a ullamcorper lorem massa leo. Integer enim sit amet justo tristique consectetur sit amet vitae eros. Mauris magna diam bibendum egestas.

                        Read More

Pellentesque magna luctus maecenas

                        Posted by Admin on March 19, 2012 in Photography | 4 comments

Maecenas non mauris diam. Vestibulum scelerisque quis risus ornare sodales aliquam nunc tellus placerat. Mauris lectus est, vestibulum eu imperdiet in, aliquet a velit. Donec auctor tortor vitae lorem porta non viverra. Etiam malesuada lobortis ipsum, sodales eros mollis sit amet.

                        Read More

Euismod vitae viverra quis eu massa condimentum

                        Posted by Admin on March 15, 2012 in Graphic Design | 23 comments

Nullam iaculis odio turpis tristique accumsan metus venenatis. Suspendisse vel arcu quam. Proin dignissim cursus tellus, non accumsan turpis elementum sit amet. Quisque eu neque sem. Praesent lacinia lectus a ante volutpat feugiat. Donec feugiat sem ut sem mollis feugiat.

                        Read More

Quisque gravida aliquet sapien

                        Posted by Admin on March 11, 2012 in Branding | 10 comments

Praesent malesuada dictum lacus congue. Ut ultrices ligula et tortor iaculis pulvinar. Sed fringilla tellus elit ut eleifend mattis. In sed lectus dui convallis a pellentesque. Etiam erat purus, accumsan eget gravida, feugiat eget lacus. Nullam non auctor purus sit amet blandit adipiscing, neque libero pulvinar dolor.

                        Read More

                    Page 1 of 5

1

2

3

4

5

                    <form id="search" method="post" action="#">
                        <fieldset>
                        <input class="search-field" type="text" name="search_string" id="search_string" value="站内搜索" onfocus="if (this.value == '站内搜索') {this.value = '';}" onblur="if (this.value == '') {this.value = '站内搜索';}" />

                        </fieldset>
                    </form>

Blog Categories

Photography / 9

Arts & Crafts / 12

Typography / 15

Web Design / 34

Branding / 27

Graphic Design / 6

Creativity / 11

Miscellaneous / 20

Popular Posts

Vestibulum adipiscing commodo tellus volutpat

Pellentesque magna luctus maecenas

Euismod vitae viverra quis eu massa condimentum

Quisque gravida aliquet sapien

Archive Records

April 2012 / 6

March 2012 / 17

February 2012 / 22

January 2012 / 18

December 2011 / 6

November 2011 / 31

Photostream

订阅

Subscribe to our newsletter today! Receive updates, tips, support and inspiration once a month.

                    <form id="sub_form" method="post" action="#">
                        <fieldset>
                            <input class="subscribe-field" type="text" name="sub_email" id="sub_email" value="Subscribe via Email" onfocus="if (this.value == 'Subscribe via Email') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Subscribe via Email';}"  />

                        </fieldset>
                    </form>

As well subscribe to our RSS Feed

最新文章

Vestibulum adipiscing commodo tellus volutpat

                    March 28, 2012 | 12 comments

Pellentesque magna luctus maecenas

                    March 19, 2012 | 4 comments

Euismod vitae viverra quis eu massa condimentum

                    March 15, 2012 | 23 comments

Quisque gravida aliquet sapien

                    March 11, 2012 | 10 comments

联系方式

                Street Road 12/34, City Town, Country State
                +1 (123) 456-7890
                info@yourstudioname.com
                Send email via contact form

			© 2014. All Rights Reserved.


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycol. Writ. 7: 1336 (1925)

#### Original name
Stereum adnatum Lloyd

### Remarks
null


text:
import networkx as nx
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import numpy as np
import textwrap
import pydot
import random, string

def drawGraph(data2Draw,current,trues,pos):

    if drawActive == False:
        return ""

    text = str("Now we delete:"+textwrap.fill(str(current), 40)+"\n\n\n\nTrues: "+textwrap.fill(str(trues), 40))
    #print (text)
    #return
    width = 10
    height = 15
    plt.figure(figsize=(width, height))
    dx = nx.DiGraph()
    dx = nx.nx.complete_multipartite_graph(1,2,3,4)
    dx.add_nodes_from(data2Draw['members'])
    dx.add_edges_from(data2Draw['edges'])
    if pos == 0:
        pos = nx.random_layout(dx,2,4)
    nx.draw_networkx_labels(dx, pos, data2Draw['labels'], font_size=16)
    nx.draw_networkx_nodes(dx, pos, nodelist=data2Draw['members'], node_color='r',node_size=700)
    nx.draw_networkx_nodes(
        dx, pos, nodelist=data2Draw['name'], node_color='y', node_shape='s', node_size=1300, linewidths=10)
    nx.draw_networkx_edges(
        dx, pos, edgelist=data2Draw['edges'], edge_color='b', arrows=True)

    red_patch = mpatches.Patch(color='red', label='Members')
    yellow_patch = mpatches.Patch(color='y', label='Lamdas')

    plt.legend(handles=[red_patch,yellow_patch], loc=1)
    plt.annotate(text,xy=(1.05,0.5),xycoords='axes fraction', fontsize=14)
    plt.show()
    return pos
def mergeDict(dictA, dictB):
    for m in dictB.keys():
        if m not in dictA.keys():
            dictA[m] = dictB[m]
        dictA[m] = (dictA[m])
    return dictA

def mergeData(data1, data2):
    allData = {}
    allData['labels'] = mergeDict(data1['labels'], data2['labels'])
    allData['edges'] = data1['edges'] | data2['edges']
    allData['members'] = data1['members'] | data2['members']
    allData['name'] = list(set().union(data1['name'],[data2['name']]))
    return allData

def getData(sentence):
    leftMembers = sentence['leftMembers']
    name = sentence['name']
    rightMembers = sentence['rightMembers']
    labels = {}
    edges = []
    for m in leftMembers:
        labels[m] = m
        edges.append((m, name))
    for m in rightMembers:
        labels[m] = m
        edges.append((name, m))
    labels[name] = name
#     if len (rightMembers) == 0:
#         leftMembers = []
    return ({'labels':  (labels), 'edges': set(edges),
             'members': set(leftMembers) | set(rightMembers), 'name': name})
def drawGraph2(data2Draw):
    graph = pydot.Dot(graph_type='graph')
    pyNodes = {}
    for n in set(data2Draw['members']):
        pyNodes[n] = pydot.Node(n, fillcolor='r')
    for n in set(data2Draw['names']):
        pyNodes[n] = pydot.Node(n, fillcolor="b", shape='box')
    for edge in set(data2Draw['edges']):
        graph.add_edge(pydot.Edge(edge[0], edge[1], label='a', color='r'))
    graph.write_png('ojj.png')

def findIndependetMembers(data,val):
    if val == 0:
        independentMember = {key: 0 for key in set(data['name'])}
    else:
        independentMember = {key: 0 for key in set(data['members'])}

    for k in data['edges']:
        if k[1] in independentMember:
            independentMember[k[1]] += 1
    return [l for l in independentMember.keys() if independentMember[l]==0]

def updateGraph(dataToProcess, trues, pos):
    dataToProcess, lamdasDeleted = removeLambda(dataToProcess, trues, pos)
    dataToProcess, membersDeleted = removeMember(dataToProcess, trues, pos)

    return dataToProcess, membersDeleted

def removeLambda(dataToProcess, trues, pos):
    toDelete = findIndependetMembers(dataToProcess,0)
    for e in [l for l in dataToProcess['edges'] if l[0] in toDelete]:
        dataToProcess['edges'].remove(e)
    for e in toDelete:
        del dataToProcess['labels'][e]
        dataToProcess['name'].remove(e)

    drawGraph(dataToProcess,toDelete,trues, pos)
    return dataToProcess, toDelete

def removeMember(dataToProcess,trues,pos):
    toDelete = findIndependetMembers(dataToProcess,1)
    for e in [l for l in dataToProcess['edges'] if l[0] in toDelete]:
        dataToProcess['edges'].remove(e)
    for e in toDelete:
        del dataToProcess['labels'][e]
        dataToProcess['members'].remove(e)
    drawGraph(dataToProcess,toDelete,trues , pos)
    return dataToProcess, toDelete

def updateSentencesAndGetTrues(sentences, membersToDelete):
    retValue = []
    for m in membersToDelete:
        for s in sentences:
            if [m] == s['rightMembers']:
                retValue.append(m)
                s['edges'] = []
                continue;
            if m in s['leftMembers']:
                del s
                continue
            if m in s['rightMembers']:
                s['rightMembers'].remove(m)
    return set(retValue), sentences

def convertJson2Theory(sentences):
    [print (l['name']+':'+str(l['leftMembers'])+'->'+str(l['rightMembers'])) for l in sentences]

def generateRandomSentences(num,lenght,members,size):
    retValue = []
    for i in range(num):
        val = {}
        lengthR = lengthL = 0
        while lengthL == 0 & lengthR == 0:
            lengthR = int (random_num(lenght))
            lengthL = int (random_num(lenght))
        val = {}
        val['name']= 'L' +str(i)
        val['leftMembers']=[]
        for j in range(lengthL):
            val['leftMembers'].append(randomword(members,size))
        val['rightMembers']=[]
        for j in range(lengthR):
            val['rightMembers'].append(randomword(members,size))
        retValue.append(val)
    return retValue

def random_num(length):
    return random.randint(0, length)

def randomword(members,length):
    return ''.join(random.choice(string.ascii_lowercase[:members]) for i in range(length))
def readFile(filename):
    f = open(filename,'r').read().replace(':[',';').replace(']->[',';').replace(']','').replace("'",'').replace(" ",'')
    allS = f.split('\n')
    listSentences = []
    for i in allS:
        ele = {}
        t = i.split(';')
        ele ['name']=t[0]
        if t[1] == '':
            ele['leftMembers'] = []
        else:
            ele['leftMembers'] = t[1].split(',')
        if t[2] == '':
            ele['rightMembers'] = []
        else:
            ele['rightMembers'] = t[2].split(',')
        listSentences.append(ele)
    return listSentences
def insert_newlines(string, every=64):
    return '\n'.join(string[i:i+every] for i in range(0, len(string), every))
def main(theory):
    convertJson2Theory(theory)
    trues = []
    deletedMembers = []
    data = {'name':[],'edges':set(),'members':set(),'labels':{}}
    for oS in theory:
        data = mergeData(data, getData(oS))
    sentences = theory
    pos = ""
    pos = drawGraph(data,deletedMembers,trues, 0)
    #drawGraph2(data)
    lastState = []
    curState = [len(data['name']),len(data['edges']),len(data['members'])]

    while lastState != curState:
        lastState = curState
        data,membersDeleted = updateGraph(data,trues, pos)
        curT, sentences = updateSentencesAndGetTrues(sentences, membersDeleted)
        curState = [len(data['name']),len(data['edges']),len(data['members'])]
        if len(curT)>0:
            trues+=curT
    trues+=data['members']
    drawGraph(data,[''],trues,pos)
    plt.clf()
    print ('Trues:')
    print (trues)
    print ('--------Finished--------')

#%%
theory = [
    {'leftMembers': [], 'name': ('L1'), 'rightMembers': ['a', 'b']},
    {'leftMembers': ['b'], 'name': ('L2'), 'rightMembers': ['a']},
    {'leftMembers': [], 'name': ('L3'), 'rightMembers': ['a', 'c']},
    {'leftMembers': ['a'], 'name': ('L4'), 'rightMembers': ['d', 'e', 'f']},
    {'leftMembers': ['e'], 'name': ('L5'), 'rightMembers': ['f']},
    {'leftMembers': ['f'], 'name': ('L6'), 'rightMembers': ['e']},
]
drawActive = True
main(theory)
#%%
drawActive = True
theory = readFile('example 1.txt')
main(theory)
#%%
drawActive = False
for i in range(100):
    print ('-------------------------')
    print ("Running N-", i)
    main(generateRandomSentences(10,2,15,1))


text:
#include <common.h>
#include <nand.h>
#include <asm/io.h>
#include <asm/arch/hardware.h>
#include <asm/arch/emif_defs.h>
#include <asm/arch/nand_defs.h>
#include <asm/arch/davinci_misc.h>
#include <net.h>
#include <netdev.h>
#ifdef CONFIG_DAVINCI_MMC
#include <mmc.h>
#include <asm/arch/sdmmc_defs.h>
#endif

DECLARE_GLOBAL_DATA_PTR;

/*
 * With the DM355 EVM, u-boot is *always* a third stage loader,
 * unless a JTAG debugger handles the first two stages:
 *
 *   - 1st stage is ROM Boot Loader (RBL), which searches for a
 *     second stage loader in one of three places based on SW7:
 *     NAND (with MMC/SD fallback), MMC/SD, or UART.
 *
 *   - 2nd stage is User Boot Loader (UBL), using at most 30KB
 *     of on-chip SRAM, responsible for lowlevel init, and for
 *     loading the third stage loader into DRAM.
 *
 *   - 3rd stage, that's us!
 */

int board_init(void)
{
	gd->bd->bi_arch_number = MACH_TYPE_DAVINCI_DM355_EVM;
	gd->bd->bi_boot_params = PHYS_SDRAM_1 + 0x100;

	/* We expect the UBL to have handled "lowlevel init", which
	 * involves setting up at least:
	 *  - clocks
	 *      + PLL1 (for ARM and peripherals) and PLL2 (for DDR)
	 *      + clock divisors for those PLLs
	 *      + LPSC_DDR module enabled
	 *      + LPSC_TIMER0 module (still) enabled
	 *  - EMIF
	 *      + DDR init and timings
	 *      + AEMIF timings (for NAND and DM9000)
	 *  - pinmux
	 *
	 * Some of that is repeated here, mostly as a precaution.
	 */

	/* AEMIF:  Some "address" lines are available as GPIOs.  A3..A13
	 * could be too if we used A12 as a GPIO during NAND chipselect
	 * (and Linux did too), letting us control the LED on A7/GPIO61.
	 */
	REG(PINMUX2) = 0x0c08;

	/* UART0 may still be in SyncReset if we didn't boot from UART */
	davinci_enable_uart0();

	/* EDMA may be in SyncReset too; turn it on, Linux won't (yet) */
	lpsc_on(DAVINCI_LPSC_TPCC);
	lpsc_on(DAVINCI_LPSC_TPTC0);
	lpsc_on(DAVINCI_LPSC_TPTC1);

	return 0;
}

#ifdef CONFIG_DRIVER_DM9000
int board_eth_init(bd_t *bis)
{
	return dm9000_initialize(bis);
}
#endif

#ifdef CONFIG_NAND_DAVINCI

static void nand_dm355evm_select_chip(struct mtd_info *mtd, int chip)
{
	struct nand_chip	*this = mtd->priv;
	unsigned long		wbase = (unsigned long) this->IO_ADDR_W;
	unsigned long		rbase = (unsigned long) this->IO_ADDR_R;

	if (chip == 1) {
		__set_bit(14, &wbase);
		__set_bit(14, &rbase);
	} else {
		__clear_bit(14, &wbase);
		__clear_bit(14, &rbase);
	}
	this->IO_ADDR_W = (void *)wbase;
	this->IO_ADDR_R = (void *)rbase;
}

int board_nand_init(struct nand_chip *nand)
{
	davinci_nand_init(nand);
	nand->select_chip = nand_dm355evm_select_chip;
	return 0;
}

#endif

#ifdef CONFIG_DAVINCI_MMC
static struct davinci_mmc mmc_sd0 = {
	.reg_base	= (struct davinci_mmc_regs *)DAVINCI_MMC_SD0_BASE,
	.input_clk	= 108000000,
	.host_caps	= MMC_MODE_4BIT,
	.voltages	= MMC_VDD_32_33 | MMC_VDD_33_34,
	.version	= MMC_CTLR_VERSION_1,
};

#ifdef CONFIG_DAVINCI_MMC_SD1
static struct davinci_mmc mmc_sd1 = {
	.reg_base	= (struct davinci_mmc_regs *)DAVINCI_MMC_SD1_BASE,
	.input_clk	= 108000000,
	.host_caps	= MMC_MODE_4BIT,
	.voltages	= MMC_VDD_32_33 | MMC_VDD_33_34,
	.version	= MMC_CTLR_VERSION_1,
};
#endif

int board_mmc_init(bd_t *bis)
{
	int err;

	/* Add slot-0 to mmc subsystem */
	err = davinci_mmc_init(bis, &mmc_sd0);
	if (err)
		return err;

#ifdef CONFIG_DAVINCI_MMC_SD1
	/* Add slot-1 to mmc subsystem */
	err = davinci_mmc_init(bis, &mmc_sd1);
#endif

	return err;
}
#endif