text:
package org.gearvrf.mixedreality.arcore;

import android.app.Activity;
import android.graphics.Bitmap;
import android.opengl.Matrix;
import android.util.DisplayMetrics;
import android.view.Surface;

import com.google.ar.core.Anchor;
import com.google.ar.core.ArCoreApk;
import com.google.ar.core.AugmentedImage;
import com.google.ar.core.AugmentedImageDatabase;
import com.google.ar.core.Camera;
import com.google.ar.core.Config;
import com.google.ar.core.Frame;
import com.google.ar.core.HitResult;
import com.google.ar.core.Plane;
import com.google.ar.core.Pose;
import com.google.ar.core.Session;
import com.google.ar.core.TrackingState;
import com.google.ar.core.exceptions.CameraNotAvailableException;
import com.google.ar.core.exceptions.UnavailableApkTooOldException;
import com.google.ar.core.exceptions.UnavailableArcoreNotInstalledException;
import com.google.ar.core.exceptions.UnavailableSdkTooOldException;
import com.google.ar.core.exceptions.UnavailableUserDeclinedInstallationException;

import org.gearvrf.GVRCameraRig;
import org.gearvrf.GVRContext;
import org.gearvrf.GVRDrawFrameListener;
import org.gearvrf.GVRExternalImage;
import org.gearvrf.GVRMaterial;
import org.gearvrf.GVRMesh;
import org.gearvrf.GVRMeshCollider;
import org.gearvrf.GVRPerspectiveCamera;
import org.gearvrf.GVRPicker;
import org.gearvrf.GVRRenderData;
import org.gearvrf.GVRScene;
import org.gearvrf.GVRSceneObject;
import org.gearvrf.GVRTexture;
import org.gearvrf.mixedreality.CameraPermissionHelper;
import org.gearvrf.mixedreality.GVRAnchor;
import org.gearvrf.mixedreality.GVRHitResult;
import org.gearvrf.mixedreality.GVRLightEstimate;
import org.gearvrf.mixedreality.GVRMarker;
import org.gearvrf.mixedreality.GVRPlane;
import org.gearvrf.mixedreality.IAnchorEvents;
import org.gearvrf.mixedreality.IPlaneEvents;
import org.gearvrf.mixedreality.MRCommon;
import org.gearvrf.utility.Log;
import org.joml.Math;
import org.joml.Matrix4f;
import org.joml.Quaternionf;
import org.joml.Vector2f;
import org.joml.Vector3f;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ARCoreSession extends MRCommon {
    private static float AR2VR_SCALE = 100.0f;

    private Session mSession;
    private boolean mInstallRequested;
    private Config mConfig;

    private GVRScene mVRScene;
    private GVRSceneObject mARPassThroughObject;
    private Frame mLastARFrame;
    private Frame arFrame;
    private ARCoreHandler mARCoreHandler;
    private boolean mEnableCloudAnchor;
    private Vector2f mScreenToCamera = new Vector2f(1, 1);

    /* From AR to GVR space matrices */
    private float[] mGVRCamMatrix = new float[16];

    private Vector3f mDisplayGeometry;

    private float mScreenDepth;

    private ARCoreHelper mArCoreHelper;

    private final Map<Anchor, CloudAnchorCallback> pendingAnchors = new HashMap<>();

    public ARCoreSession(GVRScene scene, boolean enableCloudAnchor) {
        super(scene.getGVRContext());
        mSession = null;
        mLastARFrame = null;
        mVRScene = scene;
        mArCoreHelper = new ARCoreHelper(scene.getGVRContext(), this);
        mEnableCloudAnchor = enableCloudAnchor;
    }

    @Override
    public float getARToVRScale() { return AR2VR_SCALE; }

    @Override
    public float getScreenDepth()
    {
        return mScreenDepth;
    }

    @Override
    protected void onResume() {

        Log.d(TAG, "onResumeAR");

        if (mSession == null) {

            if (!checkARCoreAndCamera()) {
                return;
            }

            // Create default config and check if supported.
            mConfig = new Config(mSession);
            if (mEnableCloudAnchor) {
                mConfig.setCloudAnchorMode(Config.CloudAnchorMode.ENABLED);
            }
            mConfig.setUpdateMode(Config.UpdateMode.LATEST_CAMERA_IMAGE);
            ArCoreApk arCoreApk = ArCoreApk.getInstance();
            ArCoreApk.Availability availability = arCoreApk.checkAvailability(mGVRContext.getContext());
            if (availability == ArCoreApk.Availability.UNSUPPORTED_DEVICE_NOT_CAPABLE) {
                showSnackbarMessage("This device does not support AR", true);
            }
            mSession.configure(mConfig);
        }

        showLoadingMessage();

        try {
            mSession.resume();
        } catch (CameraNotAvailableException e) {
            e.printStackTrace();
        }

        mGVRContext.runOnGlThread(new Runnable() {
            @Override
            public void run() {
                try {
                    onInitARCoreSession(mGVRContext);
                } catch (CameraNotAvailableException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void onPause() {
        Log.d(TAG, "onPause");

        if (mSession != null) {
            mSession.pause();
        }
    }

    private boolean checkARCoreAndCamera() {
        Activity activity = mGVRContext.getApplication().getActivity();
        Exception exception = null;
        String message = null;
        try {
            switch (ArCoreApk.getInstance().requestInstall(activity, !mInstallRequested)) {
                case INSTALL_REQUESTED:
                    mInstallRequested = true;
                    return false;
                case INSTALLED:
                    break;
            }

            // ARCore requires camera permissions to operate. If we did not yet obtain runtime
            // permission on Android M and above, now is a good time to ask the user for it.
            if (!CameraPermissionHelper.hasCameraPermission(activity)) {
                CameraPermissionHelper.requestCameraPermission(activity);
                return false;
            }

            mSession = new Session(/* context= */ activity);
        } catch (UnavailableArcoreNotInstalledException
                | UnavailableUserDeclinedInstallationException e) {
            message = "Please install ARCore";
            exception = e;
        } catch (UnavailableApkTooOldException e) {
            message = "Please update ARCore";
            exception = e;
        } catch (UnavailableSdkTooOldException e) {
            message = "Please update this app";
            exception = e;
        } catch (Exception e) {
            message = "This device does not support AR";
            exception = e;
        }

        if (message != null) {
            showSnackbarMessage(message, true);
            android.util.Log.e(TAG, "Exception creating session", exception);
            return false;
        }

        return true;
    }

    private void showSnackbarMessage(String message, boolean finishOnDismiss) {
        Log.d(TAG, message);
        if (finishOnDismiss) {
            //FIXME: finish();
        }
    }

    private void showLoadingMessage() {
        showSnackbarMessage("Searching for surfaces...", false);
    }

    private void onInitARCoreSession(GVRContext gvrContext) throws CameraNotAvailableException {
        final GVRExternalImage image = new GVRExternalImage(gvrContext);
        final GVRTexture passThroughTexture = new GVRTexture(image);

        mSession.setCameraTextureName(passThroughTexture.getId());

        configDisplayAspectRatio(mGVRContext.getActivity());

        mLastARFrame = mSession.update();
        final GVRCameraRig cameraRig = mVRScene.getMainCameraRig();

        mDisplayGeometry = configDisplayGeometry(mLastARFrame.getCamera(), cameraRig);
        mSession.setDisplayGeometry(Surface.ROTATION_90,
                (int) mDisplayGeometry.x, (int) mDisplayGeometry.y);

        final GVRMesh mesh = GVRMesh.createQuad(mGVRContext, "float3 a_position float2 a_texcoord",
                mDisplayGeometry.x, mDisplayGeometry.y);

        final FloatBuffer texCoords = mesh.getTexCoordsAsFloatBuffer();
        final int capacity = texCoords.capacity();
        final int FLOAT_SIZE = 4;

        ByteBuffer bbTexCoordsTransformed = ByteBuffer.allocateDirect(capacity * FLOAT_SIZE);
        bbTexCoordsTransformed.order(ByteOrder.nativeOrder());

        FloatBuffer quadTexCoordTransformed = bbTexCoordsTransformed.asFloatBuffer();

        mLastARFrame.transformDisplayUvCoords(texCoords, quadTexCoordTransformed);

        float[] uv = new float[capacity];
        quadTexCoordTransformed.get(uv);

        mesh.setTexCoords(uv);

        /* To render texture from phone's camera */
        mARPassThroughObject = new GVRSceneObject(gvrContext, mesh,
                passThroughTexture, GVRMaterial.GVRShaderType.OES.ID);

        mARPassThroughObject.getRenderData().setRenderingOrder(GVRRenderData.GVRRenderingOrder.BACKGROUND);
        mARPassThroughObject.getRenderData().setDepthTest(false);
        mARPassThroughObject.getTransform().setPosition(0, 0, mDisplayGeometry.z);
        mARPassThroughObject.attachComponent(new GVRMeshCollider(gvrContext, true));
        mARPassThroughObject.setName("ARPassThrough");
        mVRScene.getMainCameraRig().addChildObject(mARPassThroughObject);

        /* AR main loop */
        mARCoreHandler = new ARCoreHandler();
        gvrContext.registerDrawFrameListener(mARCoreHandler);
        syncARCamToVRCam(mLastARFrame.getCamera(), cameraRig);
        gvrContext.getEventManager().sendEvent(this,
                IPlaneEvents.class,
                "onStartPlaneDetection",
                this);
    }

    public class ARCoreHandler implements GVRDrawFrameListener {
        @Override
        public void onDrawFrame(float v) {
            try {
                arFrame = mSession.update();
            } catch (CameraNotAvailableException e) {
                e.printStackTrace();
                mGVRContext.unregisterDrawFrameListener(this);
                mGVRContext.getEventManager().sendEvent(this,
                        IPlaneEvents.class,
                        "onStopPlaneDetection",
                        this);
                return;
            }

            Camera arCamera = arFrame.getCamera();

            if (arFrame.getTimestamp() == mLastARFrame.getTimestamp()) {
                // FIXME: ARCore works at 30fps.
                return;
            }

            mArCoreHelper.setCamera(arCamera);

            syncARCamToVRCam(arCamera, mVRScene.getMainCameraRig());

            if (arCamera.getTrackingState() != TrackingState.TRACKING) {
                return;
            }

            mArCoreHelper.updatePlanes(mSession.getAllTrackables(Plane.class), AR2VR_SCALE);

            mArCoreHelper.updateAugmentedImages(arFrame.getUpdatedTrackables(AugmentedImage.class));

            mArCoreHelper.updateAnchors(AR2VR_SCALE);

            updateCloudAnchors(arFrame.getUpdatedAnchors());

            mLastARFrame = arFrame;
        }
    }

    private void syncARCamToVRCam(Camera arCamera, GVRCameraRig cameraRig) {
        float x = mGVRCamMatrix[12];
        float y = mGVRCamMatrix[13];
        float z = mGVRCamMatrix[14];

        arCamera.getDisplayOrientedPose().toMatrix(mGVRCamMatrix, 0);

        // FIXME: This is a workaround because the AR camera's pose is changing its
        // position values even if it is stopped! To avoid the scene looks trembling
        mGVRCamMatrix[12] = (mGVRCamMatrix[12] * AR2VR_SCALE + x) * 0.5f;
        mGVRCamMatrix[13] = (mGVRCamMatrix[13] * AR2VR_SCALE + y) * 0.5f;
        mGVRCamMatrix[14] = (mGVRCamMatrix[14] * AR2VR_SCALE + z) * 0.5f;

        cameraRig.getTransform().setModelMatrix(mGVRCamMatrix);
    }

    private void configDisplayAspectRatio(Activity activity) {
        final DisplayMetrics metrics = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
        mScreenToCamera.x = metrics.widthPixels;
        mScreenToCamera.y = metrics.heightPixels;
        mSession.setDisplayGeometry(Surface.ROTATION_90, metrics.widthPixels, metrics.heightPixels);
    }

    private Vector3f configDisplayGeometry(Camera arCamera, GVRCameraRig cameraRig) {
        GVRPerspectiveCamera centerCamera = cameraRig.getCenterCamera();
        float near = centerCamera.getNearClippingDistance();
        float far = centerCamera.getFarClippingDistance();

        // Get phones' cam projection matrix.
        float[] m = new float[16];
        arCamera.getProjectionMatrix(m, 0, near, far);
        Matrix4f projmtx = new Matrix4f();
        projmtx.set(m);

        float aspectRatio = projmtx.m11() / projmtx.m00();
        float arCamFOV = projmtx.perspectiveFov();
        float tanfov =  (float) Math.tan(arCamFOV * 0.5f);
        float quadDistance = far - 1;
        float quadHeight = quadDistance * tanfov * 2;
        float quadWidth = quadHeight * aspectRatio;

        // Use the same fov from AR to VR Camera as default value.
        float vrFov = (float) Math.toDegrees(arCamFOV);
        setVRCameraFov(cameraRig, vrFov);

        // VR Camera will be updated by AR pose, not by internal sensors.
        cameraRig.getHeadTransform().setRotation(1, 0, 0, 0);
        cameraRig.setCameraRigType(GVRCameraRig.GVRCameraRigType.Freeze.ID);

        android.util.Log.d(TAG, "ARCore configured to: passthrough[w: "
                + quadWidth + ", h: " + quadHeight +", z: " + quadDistance
                + "], cam fov: " +vrFov + ", aspect ratio: " + aspectRatio);
        mScreenToCamera.x = quadWidth / mScreenToCamera.x;    // map [0, ScreenSize] to [-Display, +Display]
        mScreenToCamera.y = quadHeight / mScreenToCamera.y;
        mScreenDepth = quadHeight / tanfov;
        return new Vector3f(quadWidth, quadHeight, -quadDistance);
    }

    private static void setVRCameraFov(GVRCameraRig camRig, float degreesFov) {
        camRig.getCenterCamera().setFovY(degreesFov);
        ((GVRPerspectiveCamera)camRig.getLeftCamera()).setFovY(degreesFov);
        ((GVRPerspectiveCamera)camRig.getRightCamera()).setFovY(degreesFov);
    }

    @Override
    protected GVRSceneObject onGetPassThroughObject() {
        return mARPassThroughObject;
    }

    @Override
    protected ArrayList<GVRPlane> onGetAllPlanes() {
        return mArCoreHelper.getAllPlanes();
    }

    @Override
    protected GVRAnchor onCreateAnchor(float[] pose) {
        final float[] translation = new float[3];
        final float[] rotation = new float[4];
        final float[] arPose = pose.clone();

        gvr2ar(arPose);

        convertMatrixPoseToVector(arPose, translation, rotation);

        Anchor anchor = mSession.createAnchor(new Pose(translation, rotation));
        return mArCoreHelper.createAnchor(anchor, AR2VR_SCALE);
    }

    @Override
    protected void onUpdateAnchorPose(GVRAnchor anchor, float[] pose) {
        final float[] translation = new float[3];
        final float[] rotation = new float[4];
        final float[] arPose = pose.clone();

        gvr2ar(arPose);

        convertMatrixPoseToVector(arPose, translation, rotation);

        Anchor arAnchor = mSession.createAnchor(new Pose(translation, rotation));
        mArCoreHelper.updateAnchorPose((ARCoreAnchor) anchor, arAnchor);
    }

    @Override
    protected void onRemoveAnchor(GVRAnchor anchor) {
        mArCoreHelper.removeAnchor((ARCoreAnchor) anchor);
    }

    /**
     * This method hosts an anchor. The {@code listener} will be invoked when the results are
     * available.
     */
    @Override
    synchronized protected void onHostAnchor(GVRAnchor anchor, CloudAnchorCallback cb) {
        Anchor newAnchor = mSession.hostCloudAnchor(((ARCoreAnchor) anchor).getAnchorAR());
        pendingAnchors.put(newAnchor, cb);
    }

    /**
     * This method resolves an anchor. The {@link IAnchorEvents} will be invoked when the results are
     * available.
     */
    synchronized protected void onResolveCloudAnchor(String anchorId, CloudAnchorCallback cb) {
        Anchor newAnchor = mSession.resolveCloudAnchor(anchorId);
        pendingAnchors.put(newAnchor, cb);
    }

    /**
     * Should be called with the updated anchors available after a {@link Session#update()} call.
     */
    synchronized void updateCloudAnchors(Collection<Anchor> updatedAnchors) {
        for (Anchor anchor : updatedAnchors) {
            if (pendingAnchors.containsKey(anchor)) {
                Anchor.CloudAnchorState cloudState = anchor.getCloudAnchorState();
                if (isReturnableState(cloudState)) {
                    CloudAnchorCallback cb = pendingAnchors.get(anchor);
                    pendingAnchors.remove(anchor);
                    GVRAnchor newAnchor = mArCoreHelper.createAnchor(anchor, AR2VR_SCALE);
                    cb.onCloudUpdate(newAnchor);
                }
            }
        }
    }

    /**
     * Used to clear any currently registered listeners, so they wont be called again.
     */
    synchronized void clearListeners() {
        pendingAnchors.clear();
    }

    private static boolean isReturnableState(Anchor.CloudAnchorState cloudState) {
        switch (cloudState) {
            case NONE:
            case TASK_IN_PROGRESS:
                return false;
            default:
                return true;
        }
    }

    @Override
    protected void onSetEnableCloudAnchor(boolean enableCloudAnchor) {
        mEnableCloudAnchor = enableCloudAnchor;
    }

    @Override
    protected GVRHitResult onHitTest(GVRPicker.GVRPickedObject collision) {
        Vector2f tapPosition = convertToDisplayGeometrySpace(collision.hitLocation[0], collision.hitLocation[1]);
        List<HitResult> hitResult = arFrame.hitTest(tapPosition.x, tapPosition.y);

        return mArCoreHelper.hitTest(hitResult, AR2VR_SCALE);
    }

    @Override
    protected GVRHitResult onHitTest(float x, float y) {
        x *= mScreenToCamera.x;
        y *= mScreenToCamera.y;
        List<HitResult> hitResult = arFrame.hitTest(x, y);
        return mArCoreHelper.hitTest(hitResult, AR2VR_SCALE);
    }

    @Override
    protected GVRLightEstimate onGetLightEstimate() {
        return mArCoreHelper.getLightEstimate(arFrame.getLightEstimate());
    }

    @Override
    protected void onSetMarker(Bitmap image) {
        ArrayList<Bitmap> imagesList = new ArrayList<>();
        imagesList.add(image);
        onSetMarkers(imagesList);
    }

    @Override
    protected void onSetMarkers(ArrayList<Bitmap> imagesList) {
        AugmentedImageDatabase augmentedImageDatabase = new AugmentedImageDatabase(mSession);
        for (Bitmap image : imagesList) {
            augmentedImageDatabase.addImage("image_name", image);
        }

        mConfig.setAugmentedImageDatabase(augmentedImageDatabase);
        mSession.configure(mConfig);
    }

    @Override
    protected ArrayList<GVRMarker> onGetAllMarkers() {
        return mArCoreHelper.getAllMarkers();
    }

    @Override
    protected float[] onMakeInterpolated(float[] poseA, float[] poseB, float t) {
        float[] translation = new float[3];
        float[] rotation = new float[4];
        float[] newMatrixPose = new float[16];

        convertMatrixPoseToVector(poseA, translation, rotation);
        Pose ARPoseA = new Pose(translation, rotation);

        convertMatrixPoseToVector(poseB, translation, rotation);
        Pose ARPoseB = new Pose(translation, rotation);

        Pose newPose = Pose.makeInterpolated(ARPoseA, ARPoseB, t);
        newPose.toMatrix(newMatrixPose, 0);

        return newMatrixPose;
    }

    private Vector2f convertToDisplayGeometrySpace(float x, float y) {
        final float hitX = x + 0.5f * mDisplayGeometry.x;
        final float hitY = 0.5f * mDisplayGeometry.y - y;

        return new Vector2f(hitX, hitY);
    }

    static void gvr2ar(float[] transformModelMatrix) {
        Matrix.scaleM(transformModelMatrix, 0, 1/AR2VR_SCALE, 1/AR2VR_SCALE, 1/AR2VR_SCALE);

        transformModelMatrix[12] /= AR2VR_SCALE;
        transformModelMatrix[13] /= AR2VR_SCALE;
        transformModelMatrix[14] /= AR2VR_SCALE;
    }

    static void convertMatrixPoseToVector(float[] pose, float[] translation, float[] rotation) {
        Vector3f vectorTranslation = new Vector3f();
        Quaternionf quaternionRotation = new Quaternionf();
        Matrix4f matrixPose = new Matrix4f();

        matrixPose.set(pose);

        matrixPose.getTranslation(vectorTranslation);
        translation[0] = vectorTranslation.x;
        translation[1] = vectorTranslation.y;
        translation[2] = vectorTranslation.z;

        matrixPose.getNormalizedRotation(quaternionRotation);
        rotation[0] = quaternionRotation.x;
        rotation[1] = quaternionRotation.y;
        rotation[2] = quaternionRotation.z;
        rotation[3] = quaternionRotation.w;
    }
}


text:
Apache Portable Runtime Libevent Bridge Thread Support
======================================================

Full native threading is available on supported platforms (typically via
pthreads, but there is some rudimentary support for windows threading). At a
minimum, *BOTH* the APR and libevent *MUST* be configured for thread support
in order for AEB to compile correctly and be usable in a multithreaded
application.

AEB will attempt to enable thread support by default when configure is first
run but will emit a warning and disable thread support if the above conditions
are not met or something else goes wrong. This can be forced by passing
``--enable-threads`` or ``--disable-threads`` to configure.

##Using AEB Threads##

* All threading primitives should generally be accessed through the APR,
  although certain basic operations will work correctly as long as pthreads is
  underlying all libraries.

* Generally speaking, event-based I/O is vastly more efficient than
  multithreaded or multiprocess I/O as its quite easy to induce significant
  amounts of unintentional contention between threads (and processes come with
  a lot of overhead). That being said, there are cases when a small number of
  threads can be beneficial such as when multi-core or multi-cpu systems are
  dedicated to a single network intensive task. Additionally, it may make
  sense to have a single I/O thread processing events and hand actually cpu
  intensive work off to a pool of worker threads (such as via APR's
  ``apr_thread_pool_t``). In either case, you should attempt to minimize the
  interaction between different threads and different events as much as
  possible -- the best models will always be those where the events created by
  a thread are never handled by any other thread. (Of course, in case you
  really don't want to do that, keep reading ...)

* A private memory pool is created for each thread when ``aeb_event_create()``
  or ``aeb_event_loop()`` is first called. This pool is destroyed when the
  thread or application exits. During its lifetime this pool is used for only
  one task: to allocate a single ``event_base`` which is the coordinating data
  structure used by libevent during the various I/O loops. This has a number
  of critical side effects:

 1. Calling ``aeb_event_add()``, ``aeb_event_remove()``, ``aeb_event_loop()``
    or similar *ONLY* effects the current thread. When an event is initially
    allocated it is indirectly associated with the currently running thread;
    this means that if you hand off an event to a different thread such as ...

````  C
    static void *other_thread(apr_thread_t *t, void *data)
    {
       aeb_event_t *event = (aeb_event_t*)data;

       aeb_event_add(event);
       aeb_event_loop(NULL);
       ...
    }
````

   Then the event will **NEVER** be processed and no callbacks will occur
   (unless the thread that created it also calls ``aeb_event_add()`` and
   ``aeb_event_loop()``).

2. You can move an event to a different thread after creation. Once this is
   done calls to ``aeb_event_add()`` will effect the new thread's event handling
   rather than the thread that created it.

   Keep in mind that this *ONLY* switches the ``event_base``, not the memory
   pool the event was allocated from. Fortunately however, should the
   allocating pool be destroyed the event will automatically be removed from
   the base it is assigned to regardless of which thread "owns" what.

   Example of moving an event to our thread:

````  C
    static void *io_thread(apr_thread_t *t, void *data)
    {
       aeb_event_t *event = (aeb_event_t*)data;

       aeb_event_thread_assign(event,t);
       aeb_event_add(event);
       aeb_event_loop(NULL);
       ...
    }
````

    Note that it is not necessary to call ``aeb_event_remove()`` before moving
    it to a different thread and in some cases it is also not necessary to call
    ``aeb_event_add()`` although it's generally safest to do so (it's a noop if
    already added). ``aeb_event_thread_assign()`` will automatically remove it
    from the previous thread's ``event_base`` and add it to the new one (it's
    never automatically added to the new one unless it had been previously
    added to the old).

 3. There is currently no way to determine who "owns" an event, although you
    can call ``aeb_event_thread_assign()`` with ``NULL`` as the second
    argument as shorthard for assigning it to the current running thread.
    Keep in mind that this "ownership" has nothing to do with memory
    allocation or creation but only about which thread created the
    ``event_base`` currently assigned to the event.

 4. It's possible to use events as a form of inter-thread RPC, although there
    are much better ways of accomplishing this sort of thing. Consider:

  a. One dispatch thread running:

````  C
     /* globally available dispatch thread */
     static apr_thread_t *dispatch_thread = NULL;

     static void *dispatch_thread_start(apr_thread_t *t, void *data)
     {
       dispatch_thread = t;
       aeb_event_loop(NULL);
     }
````

  b. To execute a particular callback function inside the dispatch thread:

````  C
     static void call_dispatch_thread(apr_pool_t *p,
                                   aeb_event_callback_fn func,
                                   int misc)
     {
       aeb_event_t *ev;

       aeb_event_create(p,func,&ev);
       aeb_event_thread_assign(e,dispatch_thread);
       aeb_event_add(ev);
       aeb_event_trigger(ev,misc);
     }
````

 c. This **won't** necessarily _immediately_ execute the callback function,
    but it will be scheduled for handling whenever the dispatch thread is both
    running ane examining all pending events from its event loop.

 d. When performing a trick like this it's important to watch out for memory
    leaks or allocation conflicts. In the above example the event should be
    considered "owned" by the dispatch thread *and* the memory pool must not
    be destroyed until it can be assured that the dispatch thread won't be in
    the middle of handling the event While it would be fine to destroy the
    pool if the event had been added but wasn't pending (calling
    aeb_event_trigger() always makes it immediately pending), there are
    potential race conditions that need to be considered so it's generally
    best to handle allocation in such a way that the "receiving" thread can
    take care of it however it sees fit.

redpajama_set_name: RedPajamaGithub


text:
\section{src/Tridiagonal\_\-Matrix.h File Reference}
\label{Tridiagonal__Matrix_8h}\index{src/Tridiagonal_Matrix.h@{src/Tridiagonal\_\-Matrix.h}}
{\tt \#include $<$Eigen/Dense$>$}\par

Include dependency graph for Tridiagonal\_\-Matrix.h:

This graph shows which files directly or indirectly include this file:\subsection*{Classes}
\begin{CompactItemize}
\item
class \bf{Tridiagonal\_\-Matrix}
\begin{CompactList}\small\item\em \doxyref{Tridiagonal\_\-Matrix}{p.}{classTridiagonal__Matrix} is the class for storing tridiagonal matrices. \item\end{CompactList}\end{CompactItemize}


text:
using System.Collections.Generic;
using Azure.Core;

namespace Azure.ResourceManager.Resources.Models
{
    /// <summary> List of policy definitions. </summary>
    public partial class PolicyDefinitionListResult
    {
        /// <summary> Initializes a new instance of PolicyDefinitionListResult. </summary>
        internal PolicyDefinitionListResult()
        {
            Value = new ChangeTrackingList<PolicyDefinition>();
        }

        /// <summary> Initializes a new instance of PolicyDefinitionListResult. </summary>
        /// <param name="value"> An array of policy definitions. </param>
        /// <param name="nextLink"> The URL to use for getting the next set of results. </param>
        internal PolicyDefinitionListResult(IReadOnlyList<PolicyDefinition> value, string nextLink)
        {
            Value = value;
            NextLink = nextLink;
        }

        /// <summary> An array of policy definitions. </summary>
        public IReadOnlyList<PolicyDefinition> Value { get; }
        /// <summary> The URL to use for getting the next set of results. </summary>
        public string NextLink { get; }
    }
}


text:
<?php

namespace Jade\Nodes;

class When extends Node
{
    public $expr;
    public $block;

    public function __construct($expr, $block)
    {
        $this->expr = $expr;
        $this->block = $block;
    }
}


text:
from google.cloud import logging_v2

async def sample_delete_view():
    # Create a client
    client = logging_v2.ConfigServiceV2AsyncClient()

    # Initialize request argument(s)
    request = logging_v2.DeleteViewRequest(
        name="name_value",
    )

    # Make the request
    await client.delete_view(request=request)

# [END logging_v2_generated_ConfigServiceV2_DeleteView_async]


text:
package org.odlabs.wiquery.ui.core;

import org.odlabs.wiquery.core.resources.WiQueryJavaScriptResourceReference;
import org.odlabs.wiquery.core.ui.ICoreUIJavaScriptResourceReference;

/**
 * $Id: CoreUIJavaScriptResourceReference.java 1145 2011-08-02 08:57:23Z
 * hielke.hoeve@gmail.com $
 * <p>
 * References the core jQuery UI library.
 * </p>
 *
 * @author Lionel Armanet
 * @since 0.5
 */
public class CoreUIJavaScriptResourceReference extends WiQueryJavaScriptResourceReference implements
		ICoreUIJavaScriptResourceReference
{
	private static final long serialVersionUID = 4585057795574929263L;

	private static CoreUIJavaScriptResourceReference instance =
		new CoreUIJavaScriptResourceReference();

	public static CoreUIJavaScriptResourceReference get()
	{
		return instance;
	}

	/**
	 * Builds a new instance of {@link CoreUIJavaScriptResourceReference}.
	 */
	private CoreUIJavaScriptResourceReference()
	{
		super(CoreUIJavaScriptResourceReference.class, "jquery.ui.core.js");
	}
}


text:
sap.ui.define([], function() {
	"use strict";

	var Utils = {};

	Utils.getPersistencyKey = function(oControl) {
		if (oControl) {
			var oVMControl = oControl.getVariantManagement && oControl.getVariantManagement() || oControl;
			if (oVMControl.getPersonalizableControlPersistencyKey) {
				return oVMControl.getPersonalizableControlPersistencyKey();
			}
			return oVMControl.getPersistencyKey && oVMControl.getPersistencyKey();
		}
	};

	return Utils;
});


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

    if (typeof define === 'function' && define.amd) {
        // AMD
        define(['jquery'], function ($) {
            return factory($, window, document);
        });
    }
    else if (typeof exports === 'object') {
        // CommonJS
        module.exports = function (root, $) {
            if (!root) {
                root = window;
            }

            if (!$) {
                $ = typeof window !== 'undefined' ?
                    require('jquery') :
                    require('jquery')(root);
            }

            return factory($, root, root.document);
        };
    }
    else {
        // Browser
        factory(jQuery, window, document);
    }
}

(function ($, window, document) {
    $.fn.dataTable.render.moment = function (from, to, locale) {
        // Argument shifting
        if (arguments.length === 1) {
            locale = 'en';
            to = from;
            from = 'YYYY-MM-DD';
        }
        else if (arguments.length === 2) {
            locale = 'en';
        }

        return function (d, type, row) {
            var moment = require('moment');
            var m = moment(d, from, locale, true);

            // Order and type get a number value from Moment, everything else
            // sees the rendered value
            return m.format(type === 'sort' || type === 'type' ? 'x' : to);
        };
    };
}));


text:
namespace net {
class URLRequestContextGetter;
}

namespace gcm {

// Unregistration request is used to revoke registration IDs for applications
// that were uninstalled and should no longer receive GCM messages. In case an
// attempt to unregister fails, it will retry using the backoff policy.
// TODO(fgorski): Consider sharing code with RegistrationRequest if possible.
class GCM_EXPORT UnregistrationRequest : public net::URLFetcherDelegate {
 public:
  // Callback completing the unregistration request.
  typedef base::Callback<void(bool success)> UnregistrationCallback;

  // Details of the of the Unregistration Request. All parameters are mandatory.
  struct GCM_EXPORT RequestInfo {
    RequestInfo(uint64 android_id,
                uint64 security_token,
                const std::string& app_id);
    ~RequestInfo();

    // Android ID of the device.
    uint64 android_id;
    // Security token of the device.
    uint64 security_token;
    // Application ID.
    std::string app_id;
  };

  // Creates an instance of UnregistrationRequest. |callback| will be called
  // once registration has been revoked or there has been an error that makes
  // further retries pointless.
  UnregistrationRequest(
      const RequestInfo& request_info,
      const net::BackoffEntry::Policy& backoff_policy,
      const UnregistrationCallback& callback,
      scoped_refptr<net::URLRequestContextGetter> request_context_getter);
  virtual ~UnregistrationRequest();

  // Starts an unregistration request.
  void Start();

  // URLFetcherDelegate implementation.
  virtual void OnURLFetchComplete(const net::URLFetcher* source) OVERRIDE;

 private:
  // Schedules a retry attempt and informs the backoff of previous request's
  // failure, when |update_backoff| is true.
  void RetryWithBackoff(bool update_backoff);

  UnregistrationCallback callback_;
  RequestInfo request_info_;

  net::BackoffEntry backoff_entry_;
  scoped_refptr<net::URLRequestContextGetter> request_context_getter_;
  scoped_ptr<net::URLFetcher> url_fetcher_;

  base::WeakPtrFactory<UnregistrationRequest> weak_ptr_factory_;

  DISALLOW_COPY_AND_ASSIGN(UnregistrationRequest);
};

}  // namespace gcm

#endif  // GOOGLE_APIS_GCM_ENGINE_UNREGISTRATION_REQUEST_H_


text:
#ifndef FAULTINJECTOR_H
#define FAULTINJECTOR_H

#include "pg_config_manual.h"

#define FAULTINJECTOR_MAX_SLOTS	16

/*
 *
 */
typedef enum FaultInjectorIdentifier_e {
	FaultInjectorIdNotSpecified=0,

	FaultInjectorIdAll,
		/*
		 * affects all faults injected
		 *		*) remove all faults injected from the segment
		 *		*) display status for all faults injected
		 */
	Postmaster,

	PgControl,

	PgXlog,

	StartPrepareTx,

	FaultBeforePendingDeleteRelationEntry,

	FaultBeforePendingDeleteDatabaseEntry,

	FaultBeforePendingDeleteTablespaceEntry,

	FaultBeforePendingDeleteFilespaceEntry,

	FileRepConsumer,

	FileRepConsumerVerification,

	FileRepChangeTrackingCompacting,

	FileRepSender,

	FileRepReceiver,

	FileRepFlush,

	FileRepResync,

	FileRepResyncInProgress,

	FileRepResyncWorker,

	FileRepResyncWorkerRead,

	FileRepTransitionToInResyncMirrorReCreate,

	FileRepTransitionToInResyncMarkReCreated,

	FileRepTransitionToInResyncMarkCompleted,

	FileRepTransitionToInSyncBegin,

	FileRepTransitionToInSync,

	FileRepTransitionToInSyncBeforeCheckpoint,

	FileRepTransitionToInSyncMarkCompleted,

	FileRepTransitionToChangeTracking,
	FileRepIsOperationCompleted,
	FileRepImmediateShutdownRequested,

	Checkpoint,

	ChangeTrackingCompactingReport,

	ChangeTrackingDisable,

	TransactionAbortAfterDistributedPrepared,

	TransactionCommitPass1FromCreatePendingToCreated,

	TransactionCommitPass1FromDropInMemoryToDropPending,

	TransactionCommitPass1FromAbortingCreateNeededToAbortingCreate,

	TransactionAbortPass1FromCreatePendingToAbortingCreate,

	TransactionAbortPass1FromAbortingCreateNeededToAbortingCreate,

	TransactionCommitPass2FromDropInMemoryToDropPending,

	TransactionCommitPass2FromAbortingCreateNeededToAbortingCreate,

	TransactionAbortPass2FromCreatePendingToAbortingCreate,

	TransactionAbortPass2FromAbortingCreateNeededToAbortingCreate,

	FinishPreparedTransactionCommitPass1FromCreatePendingToCreated,

	FinishPreparedTransactionCommitPass2FromCreatePendingToCreated,
		/* commit: create pending => created */

	FinishPreparedTransactionAbortPass1FromCreatePendingToAbortingCreate,
	FinishPreparedTransactionAbortPass2FromCreatePendingToAbortingCreate,
		/* abort: create pending => aborting create */

	FinishPreparedTransactionCommitPass1FromDropInMemoryToDropPending,

	FinishPreparedTransactionCommitPass2FromDropInMemoryToDropPending,
		/* commit: drop in memory => drop pending */

	FinishPreparedTransactionCommitPass1AbortingCreateNeeded,

	FinishPreparedTransactionCommitPass2AbortingCreateNeeded,
		/* commit: create pending => created */

	FinishPreparedTransactionAbortPass1AbortingCreateNeeded,

	FinishPreparedTransactionAbortPass2AbortingCreateNeeded,
		/* abort: create pending => aborting create */

	FileRepVerification,
		/* trigger filerep verification for testing */

	TwoPhaseTransactionCommitPrepared,

	TwoPhaseTransactionAbortPrepared,

	DtmBroadcastPrepare,

	DtmBroadcastCommitPrepared,

	DtmBroadcastAbortPrepared,

	DtmXLogDistributedCommit,

	DtmInit,

        EndPreparedTwoPhaseSleep,
	       /* sleep after creating two phase files */

	SegmentTransitionRequest,

	SegmentProbeResponse,

	SubtransactionFlushToFile,
	SubtransactionReadFromFile,
	SubtransactionRelease,
	SubtransactionRollback,
	LocalTmRecordTransactionCommit,

	MallocFailure,
	AbortTransactionFail,
	WorkfileCreationFail,

	UpdateCommittedEofInPersistentTable,

	ExecSimpleQueryEndCommand,
	MultiExecHashLargeVmem,

	ExecSortBeforeSorting,
	ExecSortMKSortMergeRuns,
	ExecShareInputNext,
	BaseBackupPostCreateCheckpoint,

	CompactionBeforeSegmentFileDropPhase,
	CompactionBeforeCleanupPhase,

	AppendOnlyInsert,
	AppendOnlyDelete,
	AppendOnlyUpdate,

	ReindexDB,
	ReindexRelation,

	FaultDuringExecDynamicTableScan,

	FaultInBackgroundWriterMain,

	CdbCopyStartAfterDispatch,

	RepairFragEnd,
	VacuumFullBeforeTruncate,
	VacuumFullAfterTruncate,
	VacuumRelationEndOfFirstRound,

	RebuildPTDB,

	ProcArray_Add,

	FaultExecHashJoinNewBatch,

	FtsWaitForShutdown,

	RunawayCleanup,

	OptTaskAllocateStringBuffer,
	OptRelcacheTranslatorCatalogAccess,

	/* INSERT has to be done before that line */
	FaultInjectorIdMax,

} FaultInjectorIdentifier_e;

/*
 * NB: This list needs to be kept in sync with:
 * - FaultInjectorTypeEnumToString
 * - the help message in clsInjectFault.py
 */
typedef enum FaultInjectorType_e {
	FaultInjectorTypeNotSpecified=0,

	FaultInjectorTypeSleep,

	FaultInjectorTypeFault,

	FaultInjectorTypeFatal,

	FaultInjectorTypePanic,

	FaultInjectorTypeError,

	FaultInjectorTypeInfiniteLoop,

	FaultInjectorTypeDataCorruption,

	FaultInjectorTypeSuspend,

	FaultInjectorTypeResume,

	FaultInjectorTypeSkip,

	FaultInjectorTypeMemoryFull,

	FaultInjectorTypeReset,

	FaultInjectorTypeStatus,

	FaultInjectorTypeSegv,

	FaultInjectorTypeInterrupt,

	FaultInjectorTypeFinishPending,

	FaultInjectorTypeCheckpointAndPanic,

	/* INSERT has to be done before that line */
	FaultInjectorTypeMax,

} FaultInjectorType_e;

/*
 *
 */
typedef enum DDLStatement_e {
	DDLNotSpecified=0,

	CreateDatabase,
	DropDatabase,

	CreateTable,
	DropTable,

	CreateIndex,
	AlterIndex,
	ReIndex,
	DropIndex,

	CreateFilespaces,
	DropFilespaces,

	CreateTablespaces,
	DropTablespaces,

	Truncate,

	Vacuum,

	/* INSERT has to be done before that line */
	DDLMax,
} DDLStatement_e;

/*
 *
 */
typedef enum FaultInjectorState_e {
	FaultInjectorStateNotInitialized=0,

	FaultInjectorStateWaiting,
		/* Request is waiting to be injected */

	FaultInjectorStateTriggered,
		/* Fault is injected */

	FaultInjectorStateCompleted,
		/* Fault was injected and completed successfully */

	FaultInjectorStateFailed,
		/* Fault was NOT injected */

} FaultInjectorState_e;

/*
 *
 */
typedef struct FaultInjectorEntry_s {

	FaultInjectorIdentifier_e	faultInjectorIdentifier;

	FaultInjectorType_e		faultInjectorType;

	int						sleepTime;
		/* in seconds, in use if fault injection type is sleep */

	DDLStatement_e			ddlStatement;

	char					databaseName[NAMEDATALEN];

	char					tableName[NAMEDATALEN];

	volatile	int			occurrence;

	volatile	FaultInjectorState_e	faultInjectorState;
		/* the state of the fault injection */
	char					bufOutput[2500];

} FaultInjectorEntry_s;

extern FaultInjectorType_e	FaultInjectorTypeStringToEnum(
									char*		faultTypeString);

extern	FaultInjectorIdentifier_e FaultInjectorIdentifierStringToEnum(
									char*			faultName);

extern DDLStatement_e FaultInjectorDDLStringToEnum(
									char*	ddlString);

extern Size FaultInjector_ShmemSize(void);

extern void FaultInjector_ShmemInit(void);

extern FaultInjectorType_e FaultInjector_InjectFaultIfSet(
							   FaultInjectorIdentifier_e identifier,
							   DDLStatement_e			 ddlStatement,
							   const char*				 databaseName,
							   const char*				 tableName);

extern int FaultInjector_SetFaultInjection(
							FaultInjectorEntry_s	*entry);

extern bool FaultInjector_IsFaultInjected(
							FaultInjectorIdentifier_e identifier);

#ifdef FAULT_INJECTOR
#define SIMPLE_FAULT_INJECTOR(FaultName) \
	FaultInjector_InjectFaultIfSet(FaultName, DDLNotSpecified, "", "")

#else
#define SIMPLE_FAULT_INJECTOR(FaultName)
#endif

#endif	/* FAULTINJECTOR_H */


text:
package uk.ac.imperial.doc.gpa.fsm;

import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import uk.ac.imperial.doc.gpepa.representation.components.AbstractPrefix;
import uk.ac.imperial.doc.gpepa.representation.components.ComponentId;
import uk.ac.imperial.doc.gpepa.representation.components.PEPAComponent;
import uk.ac.imperial.doc.igpepa.representation.components.ImmediatePrefix;
import uk.ac.imperial.doc.igpepa.representation.components.iChoice;
import uk.ac.imperial.doc.igpepa.representation.components.iPassivePrefix;
import uk.ac.imperial.doc.jexpressions.expressions.DoubleExpression;

import com.google.common.collect.Multimap;

public class NFAStateToPEPA
{
	// modifies the states branching from the starting state
	// (including the starting state)
	public static Map<String,PEPAComponent> HybridDFAtoPEPA
		(NFAState startingState, String naming)
	{

		startingState.setName (naming);

		Set<NFAState> renamed = new HashSet<NFAState> ();
		renamed.add (startingState);

		Map<String, PEPAComponent> ret = HybridDFAtoPEPAI (startingState, naming,
			new HashSet<NFAState> (), renamed);

		return ret;
	}

	private static Map<String,PEPAComponent> HybridDFAtoPEPAI (NFAState startingState, String naming,
		 Set<NFAState> visited, Set<NFAState> renamed)
	{

		Map<String,PEPAComponent> ret = new HashMap<String, PEPAComponent>();
		visited.add (startingState);

		Collection<NFAState> derivedStates = new HashSet<NFAState> ();
		Multimap<ITransition, NFAState> transitions
			= startingState.getTransitions ();
		List<AbstractPrefix> choices = new LinkedList<AbstractPrefix>();
		for (ITransition transition : transitions.keySet ())
		{
			Collection<NFAState> nextStates = transitions.get (transition);
            for (NFAState nextState : nextStates)
            {
                if (!renamed.contains (nextState))
                {
                    nextState.setName(naming + (renamed.size()));
                    renamed.add (nextState);
                }

                AbstractPrefix choice;
                if (transition instanceof SignalTransition) {
                	choice = new ImmediatePrefix(transition.toString(),
                			 new DoubleExpression(1.0), new ComponentId(nextState.toString())
                			);
                } else {
                	choice = new iPassivePrefix(transition.toString(),
                			null, new DoubleExpression(1.0), new ComponentId(nextState.toString()),
                			new LinkedList<ImmediatePrefix>());
                }

                choices.add(choice);
                derivedStates.add (nextState);
            }
		}
		ret.put(startingState.toString(), new iChoice(choices));

		for (NFAState state : derivedStates)
		{
			if (!visited.contains (state))
			{
				Map<String,PEPAComponent> newComponents = HybridDFAtoPEPAI
					(state, naming, visited, renamed);

				ret.putAll(newComponents);
			}
		}

		return ret;
	}
}


text:
package org.apache.beam.sdk.util;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotSame;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.List;
import org.apache.beam.sdk.coders.AtomicCoder;
import org.apache.beam.sdk.coders.Coder;
import org.apache.beam.sdk.coders.CoderException;
import org.apache.beam.sdk.testing.InterceptingUrlClassLoader;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Charsets;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableList;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Tests for {@link SerializableUtils}. */
@RunWith(JUnit4.class)
public class SerializableUtilsTest {
  @Rule public ExpectedException expectedException = ExpectedException.none();

  /** A class that is serializable by Java. */
  private static class SerializableByJava implements Serializable {
    final String stringValue;
    final int intValue;

    public SerializableByJava(String stringValue, int intValue) {
      this.stringValue = stringValue;
      this.intValue = intValue;
    }
  }

  @Test
  public void customClassLoader() throws Exception {
    // define a classloader with test-classes in it
    final ClassLoader testLoader = Thread.currentThread().getContextClassLoader();
    final ClassLoader loader = new InterceptingUrlClassLoader(testLoader, Foo.class.getName());
    final Class<?> source = loader.loadClass(Foo.class.getName());
    assertNotSame(source.getClassLoader(), Foo.class.getClassLoader());

    // validate if the caller set the classloader that it works well
    final Serializable customLoaderSourceInstance =
        Serializable.class.cast(source.getConstructor().newInstance());
    final Thread thread = Thread.currentThread();
    thread.setContextClassLoader(loader);
    try {
      assertSerializationClassLoader(loader, customLoaderSourceInstance);
    } finally {
      thread.setContextClassLoader(testLoader);
    }

    // now let beam be a little be more fancy and try to ensure it by itself from the incoming value
    assertSerializationClassLoader(loader, customLoaderSourceInstance);
  }

  @Test
  public void testTranscode() {
    String stringValue = "hi bob";
    int intValue = 42;

    SerializableByJava testObject = new SerializableByJava(stringValue, intValue);
    SerializableByJava testCopy = SerializableUtils.ensureSerializable(testObject);

    assertEquals(stringValue, testCopy.stringValue);
    assertEquals(intValue, testCopy.intValue);
  }

  @Test
  public void testDeserializationError() {
    expectedException.expect(IllegalArgumentException.class);
    expectedException.expectMessage("unable to deserialize a bogus string");
    SerializableUtils.deserializeFromByteArray(
        "this isn't legal".getBytes(Charsets.UTF_8), "a bogus string");
  }

  /** A class that is not serializable by Java. */
  private static class UnserializableByJava implements Serializable {
    @SuppressWarnings("unused")
    private Object unserializableField = new Object();
  }

  @Test
  public void testSerializationError() {
    expectedException.expect(IllegalArgumentException.class);
    expectedException.expectMessage("unable to serialize");
    SerializableUtils.serializeToByteArray(new UnserializableByJava());
  }

  /** A {@link Coder} that is not serializable by Java. */
  private static class UnserializableCoderByJava extends AtomicCoder<Object> {
    private final Object unserializableField = new Object();

    @Override
    public void encode(Object value, OutputStream outStream) throws CoderException, IOException {}

    @Override
    public Object decode(InputStream inStream) throws CoderException, IOException {
      return unserializableField;
    }

    @Override
    public List<? extends Coder<?>> getCoderArguments() {
      return ImmutableList.of();
    }

    @Override
    public void verifyDeterministic() throws NonDeterministicException {}
  }

  @Test
  public void testEnsureSerializableWithUnserializableCoderByJava() {
    expectedException.expect(IllegalArgumentException.class);
    expectedException.expectMessage("unable to serialize");
    SerializableUtils.ensureSerializable(new UnserializableCoderByJava());
  }

  private void assertSerializationClassLoader(
      final ClassLoader loader, final Serializable customLoaderSourceInstance) {
    final Serializable copy = SerializableUtils.ensureSerializable(customLoaderSourceInstance);
    assertEquals(loader, copy.getClass().getClassLoader());
    assertEquals(
        copy.getClass().getClassLoader(), customLoaderSourceInstance.getClass().getClassLoader());
  }

  /**
   * a sample class to test framework serialization, {@see SerializableUtilsTest#customClassLoader}.
   */
  public static class Foo implements Serializable {}
}


text:
import gettext

from flask_bombril.form_validators.utils import raise_with_stop
from flask_bombril.r import R

class Length(object):
    def __init__(self, min_length=-1, max_length=-1, message=None, stop=True):
        assert min_length >= -1 and max_length >= -1
        assert min_length != -1 or max_length != -1
        assert max_length == -1 or min_length <= max_length
        self.min = min_length
        self.max = max_length
        self.message = message
        self.stop = stop

    def __call__(self, form, field):
        if callable(self.message):
            self.message = self.message()

        l = field.data and len(field.data) or 0
        if l < self.min or self.max != -1 and l > self.max:
            message = self.message
            if message is None:
                if self.max == -1:
                    message = gettext.ngettext(
                        R.string.validators.field_min_length_singular,
                        R.string.validators.field_min_length_plural,
                        self.min) % dict(min_length=self.min)
                elif self.min == -1:
                    message = gettext.ngettext(
                        R.string.validators.field_max_length_singular,
                        R.string.validators.field_max_length_plural,
                        self.max) % dict(max_length=self.max)
                else:
                    message = R.string.validators.field_length_range % dict(min_length=self.min, max_length=self.max)

            raise_with_stop(self, message=message)


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

/**
 * Package containing classes used for representing secrets, deleted secrets and their attributes in
 * Azure Key Vault.
 */
package com.azure.security.keyvault.secrets.models;


text:
package org.jbehave.examples.core.urls;

import static java.util.Arrays.asList;
import static org.jbehave.core.io.CodeLocations.codeLocationFromURL;
import static org.jbehave.core.reporters.Format.CONSOLE;
import static org.jbehave.core.reporters.Format.HTML;
import static org.jbehave.core.reporters.Format.TXT;
import static org.jbehave.core.reporters.Format.XML;

import java.util.List;

import org.jbehave.core.configuration.Configuration;
import org.jbehave.core.io.LoadFromURL;
import org.jbehave.core.reporters.StoryReporterBuilder;
import org.jbehave.examples.core.CoreStories;

/**
 *

 * Example of how multiple remote stories can be run via JUnit.
 *

 *

 * Stories are specified as remote URLs and correspondingly the {@link LoadFromURL}
 * story loader is configured and the story paths are looked up as remote URLs.
 * It extends CoreStories simply for convenience, in order to avoid
 * duplicating common configuration.
 *

 */
public class RemoteCoreStories extends CoreStories {

    @Override
    public Configuration configuration() {
        return super.configuration()
               .useStoryLoader(new LoadFromURL())
               .useStoryReporterBuilder(
                       new StoryReporterBuilder()
                           .withCodeLocation(codeLocationFromURL("http://jbehave.org/reference/examples/stories/"))
                           .withDefaultFormats()
                           .withFormats(CONSOLE, TXT, HTML, XML));
    }

    @Override
    public List<String> storyPaths() {
        // Specify story paths as remote URLs
        String codeLocation = codeLocationFromURL("http://jbehave.org/reference/examples/stories/")
                .toExternalForm();
        return asList(codeLocation + "and_step.story");
    }

}


text:
/* Vector emulation for C */

#ifndef VECTOR_EMULATION_H
#define VECTOR_EMULATION_H

#include "basic_types.h"
#include "vector_emulation/vector_types.h"
#include "vector_emulation/vector_operators.h"
#include "vector_emulation/vector_literals.h"
#include "vector_emulation/vector_convert.h"
#include "vector_emulation/vector_elements.h"

#endif


text:
"""Unit tests for Part Views (see views.py)"""

from django.urls import reverse

from InvenTree.helpers import InvenTreeTestCase

from .models import Part

class PartViewTestCase(InvenTreeTestCase):
    """Base class for unit testing the various Part views"""

    fixtures = [
        'category',
        'part',
        'bom',
        'location',
        'company',
        'supplier_part',
    ]

    roles = 'all'
    superuser = True

class PartListTest(PartViewTestCase):
    """Unit tests for the PartList view"""

    def test_part_index(self):
        """Test that the PartIndex page returns successfully"""
        response = self.client.get(reverse('part-index'))
        self.assertEqual(response.status_code, 200)

        keys = response.context.keys()
        self.assertIn('csrf_token', keys)
        self.assertIn('parts', keys)
        self.assertIn('user', keys)

class PartDetailTest(PartViewTestCase):
    """Unit tests for the PartDetail view"""

    def test_part_detail(self):
        """Test that we can retrieve a part detail page."""
        pk = 1

        response = self.client.get(reverse('part-detail', args=(pk,)))
        self.assertEqual(response.status_code, 200)

        part = Part.objects.get(pk=pk)

        keys = response.context.keys()

        self.assertIn('part', keys)
        self.assertIn('category', keys)

        self.assertEqual(response.context['part'].pk, pk)
        self.assertEqual(response.context['category'], part.category)

    def test_part_detail_from_ipn(self):
        """Test that we can retrieve a part detail page from part IPN:

        - if no part with matching IPN -> return part index
        - if unique IPN match -> return part detail page
        - if multiple IPN matches -> return part index
        """
        ipn_test = 'PART-000000-AA'
        pk = 1

        def test_ipn_match(index_result=False, detail_result=False):
            """Helper function for matching IPN detail view"""
            index_redirect = False
            detail_redirect = False

            response = self.client.get(reverse('part-detail-from-ipn', args=(ipn_test,)))

            # Check for PartIndex redirect
            try:
                if response.url == '/part/':
                    index_redirect = True
            except AttributeError:
                pass

            # Check for PartDetail redirect
            try:
                if response.context['part'].pk == pk:
                    detail_redirect = True
            except TypeError:
                pass

            self.assertEqual(index_result, index_redirect)
            self.assertEqual(detail_result, detail_redirect)

        # Test no match
        test_ipn_match(index_result=True, detail_result=False)

        # Test unique match
        part = Part.objects.get(pk=pk)
        part.IPN = ipn_test
        part.save()

        test_ipn_match(index_result=False, detail_result=True)

        # Test multiple matches
        part = Part.objects.get(pk=pk + 1)
        part.IPN = ipn_test
        part.save()

        test_ipn_match(index_result=True, detail_result=False)

    def test_bom_download(self):
        """Test downloading a BOM for a valid part."""
        response = self.client.get(reverse('bom-download', args=(1,)), HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEqual(response.status_code, 200)
        self.assertIn('streaming_content', dir(response))

class PartQRTest(PartViewTestCase):
    """Tests for the Part QR Code AJAX view."""

    def test_html_redirect(self):
        """A HTML request for a QR code should be redirected (use an AJAX request instead)"""
        response = self.client.get(reverse('part-qr', args=(1,)))
        self.assertEqual(response.status_code, 302)

    def test_valid_part(self):
        """Test QR code response for a Part"""
        response = self.client.get(reverse('part-qr', args=(1,)), HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEqual(response.status_code, 200)

        data = str(response.content)

        self.assertIn('Part QR Code', data)
        self.assertIn('<img src=', data)

    def test_invalid_part(self):
        """Test response for an invalid Part ID value"""
        response = self.client.get(reverse('part-qr', args=(9999,)), HTTP_X_REQUESTED_WITH='XMLHttpRequest')

        self.assertEqual(response.status_code, 200)


text:
Django Google Contact Importer
==============================

This application wraps Google Contact API, using AuthSub, and provides easy
access to contacts of a Google user. Its primary usage is for writing
"Invite Your Friends" like functionality.

Installation:

* Install gdata.py_
* Install ElementTree_
* Put dgci folder somewhere in PYTHONPATH
* Add dgci to settings.py under INSTALLED_APPS
* (r'^dgci/', include('dgci.urls')), into urls.py

Usage:

* Point user to /dgci/start/?next=YourURL

It will store the addressbook into requset.session["dgci_contact_feed"] and
then redirect users to YourURL once addressbook has been imported.

Some examples of how to work with dgci_contact_feed_ object.

Enjoy!

.. _gdata.py: http://code.google.com/p/gdata-python-client/downloads/list
.. _ElementTree: http://pypi.python.org/pypi/elementtree/
.. _dgci_contact_feed: http://code.google.com/apis/contacts/docs/1.0/developers_guide_python.html#Retrieving


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

<TITLE>
RandomConnection (ANJI API)
</TITLE>

<META NAME="keywords" CONTENT="com.anji.nn.RandomConnection class">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

com.anji.nn

Class RandomConnection

java.lang.Object
  com.anji.nn.RandomConnection

All Implemented Interfaces:
Connection

public class RandomConnection
extends java.lang.Object
implements Connection

Author:

Philip Tucker

Field Summary

Fields inherited from interface com.anji.nn.Connection

XML_TAG

Method Summary

 long
cost()

static RandomConnection
getInstance()

 double
read()

 void
setRand(java.util.Random aRand)

 java.lang.String
toXml()

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Method Detail

setRand

public void setRand(java.util.Random aRand)

Parameters:
aRand - new random generator

getInstance

public static RandomConnection getInstance()

Returns:
singleton instance

read

public double read()

Specified by:
read in interface Connection

Returns:
double value carried on this connection from incoming neuron
See Also:
Connection.read()

toXml

public java.lang.String toXml()

Specified by:
toXml in interface Connection

Returns:
String representation of object
See Also:
Connection.toXml()

cost

public long cost()

Specified by:
cost in interface Connection

Returns:
number corresponding to cost of activation in resources
See Also:
Connection.cost()

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
<?php

/**
 * @category    Oink
 * @package     Oink_Oink
 */
class Oink_Oink_Model_Mysql4_Order
        extends Mage_Core_Model_Mysql4_Abstract
{

    /**
     * Serializeable field: additional_information
     *
     * @var array
     */
    protected $_serializableFields   = array(
        'additional_information' => array(null, array())
    );
    /**
     * Initialize connection and define main table
     *
     */
    protected function _construct()
    {
        $this->_init('oink/order', 'oink_order_id');
    }

}

?>


text:
#ifndef configment_debug_h_20130321
#define configment_debug_h_20130321

#include<iostream>
#include<vector>
#include<string>
#include<typeinfo>
#include<exception>

#include <configment/enum.h>

namespace configment
{

// DebugInfo
struct DebugInfo
{
    static bool		_visible;
    str_type		_filename;
    int_type		_line_number;
    DebugInfo(const str_type & filename, const int_type & line_number) :
		_filename(filename),
		_line_number(line_number)
    {
    }
    static void set_visible(bool show=true);
    static bool get_visible();
    str_type where(bool visible) const;
    str_type where() const;
};

std::ostream & operator << (std::ostream & os, const DebugInfo & di);

#define DEBUG_INFO	(configment::DebugInfo(__FILE__, __LINE__))

} // namespace configment
#endif // #define configment_debug_h_20130321


text:
module Watir
  class Element

    #
    # Refresh the page until the element is present.
    #
    # @example
    #   browser.button(:id => 'foo').refresh_until_present
    #
    # @param [Fixnum] timeout seconds to wait before timing out
    #
    # @see Watir::WaitWithRefresh
    # @see Watir::Element#present?
    #

    def refresh_until_present(timeout = 30)
      message = "waiting for #{@selector.inspect} to become present"
      Watir::WaitWithRefresh.refresh_until(browser, timeout, message) { present? }
    end

    #
    # Refresh the page while the element is present.
    #
    # @example
    #   browser.button(:id => 'foo').refresh_while_present
    #
    # @param [Integer] timeout seconds to wait before timing out
    #
    # @see Watir::WaitWithRefresh
    # @see Watir::Element#present?
    #

    def refresh_while_present(timeout = 30)
      message = "waiting for #{@selector.inspect} to disappear"
      Watir::WaitWithRefresh.refresh_while(browser, timeout, message) { present? }
    end

    #
    # Refreshes the page until the element is present.
    #
    # @example
    #   browser.button(:id => 'foo').when_present_after_refresh.click
    #   browser.div(:id => 'bar').when_present_after_refresh { |div| ... }
    #   browser.p(:id => 'baz').when_present_after_refresh(60).text
    #
    # @param [Fixnum] timeout seconds to wait before timing out
    #
    # @see Watir::WaitWithRefresh
    # @see Watir::Element#present?
    #

    def when_present_after_refresh(timeout = 30)
      message = "waiting for #{@selector.inspect} to become present"

      if block_given?
        Watir::WaitWithRefresh.refresh_until(browser, timeout, message) { present? }
        yield self
      else
        WhenPresentAfterRefreshDecorator.new(self, timeout, message)
      end
    end

  end # Element

  #
  # Wraps an Element so that any subsequent method calls are
  # put on hold until the element is present (exists and is visible) on the page.
  #

  class WhenPresentAfterRefreshDecorator
    def initialize(element, timeout, message = nil)
      @element = element
      @timeout = timeout
      @message = message
    end

    def respond_to?(*args)
      @element.respond_to?(*args)
    end

    def method_missing(m, *args, &block)
      unless @element.respond_to?(m)
        raise NoMethodError, "undefined method `#{m}' for #{@element.inspect}:#{@element.class}"
      end

      Watir::WaitWithRefresh.refresh_until(@element.browser, @timeout, @message) { @element.present? }

      @element.__send__(m, *args, &block)
    end
  end # WhenPresentAfterRefreshDecorator
end # Watir


text:
package com.amazonaws.services.codedeploy.model.transform;

import java.util.List;
import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.codedeploy.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * DeploymentGroupInfoMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class DeploymentGroupInfoMarshaller {

    private static final MarshallingInfo<String> APPLICATIONNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("applicationName").build();
    private static final MarshallingInfo<String> DEPLOYMENTGROUPID_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("deploymentGroupId").build();
    private static final MarshallingInfo<String> DEPLOYMENTGROUPNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("deploymentGroupName").build();
    private static final MarshallingInfo<String> DEPLOYMENTCONFIGNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("deploymentConfigName").build();
    private static final MarshallingInfo<List> EC2TAGFILTERS_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("ec2TagFilters").build();
    private static final MarshallingInfo<List> ONPREMISESINSTANCETAGFILTERS_BINDING = MarshallingInfo.builder(MarshallingType.LIST)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("onPremisesInstanceTagFilters").build();
    private static final MarshallingInfo<List> AUTOSCALINGGROUPS_BINDING = MarshallingInfo.builder(MarshallingType.LIST)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("autoScalingGroups").build();
    private static final MarshallingInfo<String> SERVICEROLEARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("serviceRoleArn").build();
    private static final MarshallingInfo<StructuredPojo> TARGETREVISION_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("targetRevision").build();
    private static final MarshallingInfo<List> TRIGGERCONFIGURATIONS_BINDING = MarshallingInfo.builder(MarshallingType.LIST)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("triggerConfigurations").build();
    private static final MarshallingInfo<StructuredPojo> ALARMCONFIGURATION_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("alarmConfiguration").build();
    private static final MarshallingInfo<StructuredPojo> AUTOROLLBACKCONFIGURATION_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("autoRollbackConfiguration").build();
    private static final MarshallingInfo<StructuredPojo> DEPLOYMENTSTYLE_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("deploymentStyle").build();
    private static final MarshallingInfo<StructuredPojo> BLUEGREENDEPLOYMENTCONFIGURATION_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("blueGreenDeploymentConfiguration").build();
    private static final MarshallingInfo<StructuredPojo> LOADBALANCERINFO_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("loadBalancerInfo").build();
    private static final MarshallingInfo<StructuredPojo> LASTSUCCESSFULDEPLOYMENT_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("lastSuccessfulDeployment").build();
    private static final MarshallingInfo<StructuredPojo> LASTATTEMPTEDDEPLOYMENT_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("lastAttemptedDeployment").build();
    private static final MarshallingInfo<StructuredPojo> EC2TAGSET_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ec2TagSet").build();
    private static final MarshallingInfo<StructuredPojo> ONPREMISESTAGSET_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("onPremisesTagSet").build();
    private static final MarshallingInfo<String> COMPUTEPLATFORM_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("computePlatform").build();
    private static final MarshallingInfo<List> ECSSERVICES_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("ecsServices").build();

    private static final DeploymentGroupInfoMarshaller instance = new DeploymentGroupInfoMarshaller();

    public static DeploymentGroupInfoMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(DeploymentGroupInfo deploymentGroupInfo, ProtocolMarshaller protocolMarshaller) {

        if (deploymentGroupInfo == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(deploymentGroupInfo.getApplicationName(), APPLICATIONNAME_BINDING);
            protocolMarshaller.marshall(deploymentGroupInfo.getDeploymentGroupId(), DEPLOYMENTGROUPID_BINDING);
            protocolMarshaller.marshall(deploymentGroupInfo.getDeploymentGroupName(), DEPLOYMENTGROUPNAME_BINDING);
            protocolMarshaller.marshall(deploymentGroupInfo.getDeploymentConfigName(), DEPLOYMENTCONFIGNAME_BINDING);
            protocolMarshaller.marshall(deploymentGroupInfo.getEc2TagFilters(), EC2TAGFILTERS_BINDING);
            protocolMarshaller.marshall(deploymentGroupInfo.getOnPremisesInstanceTagFilters(), ONPREMISESINSTANCETAGFILTERS_BINDING);
            protocolMarshaller.marshall(deploymentGroupInfo.getAutoScalingGroups(), AUTOSCALINGGROUPS_BINDING);
            protocolMarshaller.marshall(deploymentGroupInfo.getServiceRoleArn(), SERVICEROLEARN_BINDING);
            protocolMarshaller.marshall(deploymentGroupInfo.getTargetRevision(), TARGETREVISION_BINDING);
            protocolMarshaller.marshall(deploymentGroupInfo.getTriggerConfigurations(), TRIGGERCONFIGURATIONS_BINDING);
            protocolMarshaller.marshall(deploymentGroupInfo.getAlarmConfiguration(), ALARMCONFIGURATION_BINDING);
            protocolMarshaller.marshall(deploymentGroupInfo.getAutoRollbackConfiguration(), AUTOROLLBACKCONFIGURATION_BINDING);
            protocolMarshaller.marshall(deploymentGroupInfo.getDeploymentStyle(), DEPLOYMENTSTYLE_BINDING);
            protocolMarshaller.marshall(deploymentGroupInfo.getBlueGreenDeploymentConfiguration(), BLUEGREENDEPLOYMENTCONFIGURATION_BINDING);
            protocolMarshaller.marshall(deploymentGroupInfo.getLoadBalancerInfo(), LOADBALANCERINFO_BINDING);
            protocolMarshaller.marshall(deploymentGroupInfo.getLastSuccessfulDeployment(), LASTSUCCESSFULDEPLOYMENT_BINDING);
            protocolMarshaller.marshall(deploymentGroupInfo.getLastAttemptedDeployment(), LASTATTEMPTEDDEPLOYMENT_BINDING);
            protocolMarshaller.marshall(deploymentGroupInfo.getEc2TagSet(), EC2TAGSET_BINDING);
            protocolMarshaller.marshall(deploymentGroupInfo.getOnPremisesTagSet(), ONPREMISESTAGSET_BINDING);
            protocolMarshaller.marshall(deploymentGroupInfo.getComputePlatform(), COMPUTEPLATFORM_BINDING);
            protocolMarshaller.marshall(deploymentGroupInfo.getEcsServices(), ECSSERVICES_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
package org.compass.sample.petclinic;

/**
 *
 * @author Juergen Hoeller
 *
 */

public class Specialty extends NamedEntity {

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ShopSystem.Data.Repositories;
using ShopSystem.Models.EntityModels;
using System.Data.Entity;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;

namespace ShopSystem.Data.UnitOfWork
{
    public class ShopSystemData : IShopSystemData
    {
        private readonly DbContext dbContext;

        private readonly IDictionary<Type, object> repositorues;

        private IUserStore<ApplicationUser> userStore;

        public ShopSystemData()
            : this(new ShopSystemContext())
        {
        }

        public ShopSystemData(DbContext context)
        {
            this.dbContext = context;
            this.repositorues = new Dictionary<Type, object>();
        }

        public IRepository<ApplicationUser> Users
        {
            get
            {
                return this.GetRepository<ApplicationUser>();
            }
        }

        public IRepository<Laptop> Laptops
        {
            get
            {
                return this.GetRepository<Laptop>();
            }
        }

        public IRepository<Monitor> Monitors
        {
            get
            {
                return this.GetRepository<Monitor>();
            }
        }

        public IUserStore<ApplicationUser> UserStore
        {
            get
            {
                if (this.userStore == null)
                {
                    this.userStore = new UserStore<ApplicationUser>(this.dbContext);
                }

                return this.userStore;
            }
        }

        public IRepository<Accessor> Accessories
        {
            get
            {
                return this.GetRepository<Accessor>();
            }
        }

        public void SaveChanges()
        {
            this.dbContext.SaveChanges();
        }

        private IRepository<T> GetRepository<T>() where T : class
        {
            if (! this.repositorues.ContainsKey(typeof(T)))
            {
                var type = typeof(GenericEfRepository<T>);
                this.repositorues.Add(typeof(T),
                Activator.CreateInstance(type, this.dbContext));
            }

            return (IRepository<T>)this.repositorues[typeof(T)];
        }
    }
}


text:
// Copyright (c) Christof Senn. All rights reserved. See license.txt in the project root for license information.

namespace Aqua.Tests.Serialization.Dynamic.DynamicObject
{
    using Aqua.Dynamic;
    using Shouldly;
    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.Linq;
    using System.Reflection;
    using Xunit;
    using TypeInfo = Aqua.TypeSystem.TypeInfo;

    public abstract class When_serializing_dynamic_object
    {
        public class With_newtonsoft_json_serializer : When_serializing_dynamic_object
        {
            public With_newtonsoft_json_serializer()
                : base(NewtonsoftJsonSerializationHelper.Clone)
            {
            }
        }

        public class With_system_text_json_serializer : When_serializing_dynamic_object
        {
            public With_system_text_json_serializer()
                : base(SystemTextJsonSerializationHelper.Clone)
            {
            }
        }

        public class With_data_contract_serializer : When_serializing_dynamic_object
        {
            public With_data_contract_serializer()
                : base(DataContractSerializationHelper.Clone)
            {
            }
        }

        public class With_binary_formatter : When_serializing_dynamic_object
        {
            public With_binary_formatter()
                : base(BinarySerializationHelper.Clone)
            {
            }
        }

#if NETFRAMEWORK
        public class With_net_data_contract_serializer : When_serializing_dynamic_object
        {
            public With_net_data_contract_serializer()
                : base(NetDataContractSerializationHelper.Clone)
            {
            }
        }
#endif // NETFRAMEWORK

        public class With_protobuf_net_serializer : When_serializing_dynamic_object
        {
            public With_protobuf_net_serializer()
                : base(ProtobufNetSerializationHelper.Clone)
            {
            }
        }

        public class With_xml_serializer : When_serializing_dynamic_object
        {
            public With_xml_serializer()
                : base(XmlSerializationHelper.Serialize)
            {
            }
        }

        private class A<T>
        {
            public T Value { get; set; }
        }

        private const BindingFlags PrivateInstance = BindingFlags.NonPublic | BindingFlags.Instance;

        private readonly Func<DynamicObject, DynamicObject> _serialize;

        protected When_serializing_dynamic_object(Func<DynamicObject, DynamicObject> serialize)
        {
            _serialize = serialize;
        }

        [SkippableTheory]
        [MemberData(nameof(TestData.TestValues), MemberType = typeof(TestData))]
        [MemberData(nameof(TestData.TestValueArrays), MemberType = typeof(TestData))]
        [MemberData(nameof(TestData.TestValueLists), MemberType = typeof(TestData))]
        public void Should_serialize_value(Type type, object value, CultureInfo culture)
        {
            if (this.TestIs<With_protobuf_net_serializer>())
            {
                ProtobufNetSerializationHelper.SkipUnsupportedDataType(type, value);
            }

            if (this.TestIs<With_system_text_json_serializer>())
            {
                SystemTextJsonSerializationHelper.SkipUnsupportedDataType(type, value);
            }

#if NET5_0_OR_GREATER
            Skip.If(type.Is<Half>(), "Half type serialization is not supported.");
#endif // NET5_0_OR_GREATER
            Skip.If(this.TestIs<With_xml_serializer>(), "XmlSerializer has limited type support.");

            using var cultureContext = culture.CreateContext();

            var result = Serialize(type, value);
            result.ShouldBe(value, $"type: {type.FullName}");
        }

        [SkippableTheory]
        [MemberData(nameof(TestData.TestValues), MemberType = typeof(TestData))]
        [MemberData(nameof(TestData.TestValueArrays), MemberType = typeof(TestData))]
        [MemberData(nameof(TestData.TestValueLists), MemberType = typeof(TestData))]
        public void Should_serialize_value_when_using_string_formatting(Type type, object value, CultureInfo culture)
        {
            if (this.TestIs<With_protobuf_net_serializer>())
            {
                ProtobufNetSerializationHelper.SkipUnsupportedDataType(type, value);
            }

            if (this.TestIs<With_system_text_json_serializer>())
            {
                SystemTextJsonSerializationHelper.SkipUnsupportedDataType(type, value);
            }

            Skip.If(this.TestIs<With_xml_serializer>() && type.Is<char>(), "Only characters which are valid in xml may be supported by XmlSerializer.");

            using var cultureContext = culture.CreateContext();

            var result = Serialize(type, value, formatValuesAsStrings: true);
            result.ShouldBe(value, $"type: {type.FullName}");
        }

        [SkippableTheory]
        [MemberData(nameof(TestData.TestValues), MemberType = typeof(TestData))]
        [MemberData(nameof(TestData.TestValueArrays), MemberType = typeof(TestData))]
        [MemberData(nameof(TestData.TestValueLists), MemberType = typeof(TestData))]
        public void Should_serialize_value_as_property(Type type, object value, CultureInfo culture)
        {
            if (this.TestIs<With_protobuf_net_serializer>())
            {
                ProtobufNetSerializationHelper.SkipUnsupportedDataType(type, value);
            }

            if (this.TestIs<With_system_text_json_serializer>())
            {
                SystemTextJsonSerializationHelper.SkipUnsupportedDataType(type, value);
            }

#if NET5_0_OR_GREATER
            Skip.If(type.Is<Half>(), "Half type serialization is not supported.");
#endif // NET5_0_OR_GREATER
            Skip.If(this.TestIs<With_xml_serializer>(), "XmlSerializer has limited type support.");

            using var cultureContext = culture.CreateContext();

            var result = SerializeAsProperty(type, value);
            result.ShouldBe(value, $"type: {type.FullName}");
        }

        [SkippableTheory]
        [MemberData(nameof(TestData.TestValues), MemberType = typeof(TestData))]
        [MemberData(nameof(TestData.TestValueArrays), MemberType = typeof(TestData))]
        [MemberData(nameof(TestData.TestValueLists), MemberType = typeof(TestData))]
        public void Should_serialize_value_as_property_when_using_string_formatting(Type type, object value, CultureInfo culture)
        {
            Skip.If(this.TestIs<With_xml_serializer>() && type.Is<char>(), "Only characters which are valid in xml may be supported by XmlSerializer.");

            using var cultureContext = culture.CreateContext();

            var result = SerializeAsProperty(type, value, formatValuesAsStrings: true);
            result.ShouldBe(value, $"type: {type.FullName}  ({value})");
        }

        [Fact]
        public void Should_serialize_array_as_property()
        {
            var value = new[] { new TestData.RecordType { Value = "test" } };
            var result = SerializeAsProperty(value.GetType(), value);
            result
                .ShouldBeOfType<TestData.RecordType[]>()
                .ShouldHaveSingleItem()
                .Value.ShouldBe("test");
        }

        [Fact]
        public void Should_serialize_array()
        {
            var value = new[] { new TestData.RecordType { Value = "test" } };
            var result = Serialize(value.GetType(), value);
            result
                .ShouldBeOfType<TestData.RecordType[]>()
                .ShouldHaveSingleItem()
                .Value.ShouldBe("test");
        }

        [Fact]
        public void Should_serialize_empty_array_as_property()
        {
            var value = new TestData.RecordType[0];
            var result = SerializeAsProperty(value.GetType(), value);
            result.ShouldBe(value);
        }

        [Fact]
        public void Should_serialize_empty_array()
        {
            var value = new TestData.RecordType[0];
            var result = Serialize(value.GetType(), value);
            result.ShouldBe(value);
        }

        [Fact]
        public void Should_serialize_null_array()
        {
            var type = typeof(TestData.RecordType[]);
            var result = Serialize(type, null);
            result.ShouldBeNull();
        }

        [Fact]
        public void Should_serialize_null_array_as_property()
        {
            var type = typeof(TestData.RecordType[]);
            var result = SerializeAsProperty(type, null);
            result.ShouldBeNull();
        }

        [SkippableFact]
        public void Should_serialize_DateTimeOffset_as_property()
        {
            Skip.If(this.TestIs<With_protobuf_net_serializer>(), "DateTimeOffset is not supported by XmlSerializer.");
            Skip.If(this.TestIs<With_xml_serializer>(), "DateTimeOffset is not supported by XmlSerializer.");

            var value = new DateTimeOffset(2, 1, 2, 10, 0, 0, 300, new TimeSpan(1, 30, 0));
            var result = SerializeAsProperty(value.GetType(), value);
            result.ShouldBe(value);
        }

        [Fact]
        public void Should_serialize_DateTimeOffset_as_property_when_using_string_formatting()
        {
            var value = new DateTimeOffset(2, 1, 2, 10, 0, 0, 300, new TimeSpan(1, 30, 0));
            var result = SerializeAsProperty(value.GetType(), value, formatValuesAsStrings: true);
            result.ShouldBe(value);
        }

        [Fact]
        public void Should_serialize_DateTimeOffset_as_property_when_using_string_formatting2()
        {
            var mapperSettings = new DynamicObjectMapperSettings { FormatNativeTypesAsString = true };
            var mapper = new DynamicObjectMapper(mapperSettings);

            var dto1 = new DateTimeOffset(2, 1, 2, 10, 0, 0, 300, new TimeSpan(1, 30, 0));
            var dtoDynamic = mapper.MapObject(dto1);
            var dto2 = mapper.Map<DateTimeOffset>(dtoDynamic);

            dto2.ShouldBe(dto1);
        }

        [Fact]
        public void List_of_int_should_serialize()
        {
            var source = new List<int> { 1, 11 };

            var result = Serialize(source);

            result.ShouldNotBeSameAs(source);
            result.SequenceShouldBeEqual(source);
        }

        [Fact]
        public void List_of_nullable_int_should_serialize()
        {
            var source = new List<int?> { null, 1, 11 };

            var result = Serialize(source);

            result.ShouldNotBeSameAs(source);
            result.SequenceShouldBeEqual(source);
        }

        [Fact]
        public void List_of_nullable_int_should_serialize_as_ienumerable()
        {
            var source = new List<int?> { null, 1, 11 };

            var result = Serialize<IEnumerable<int?>>(source);

            result.ShouldNotBeSameAs(source);
            result.SequenceShouldBeEqual(source);
        }

        [Fact]
        public void Array_of_int_should_serialize()
        {
            var source = new[] { 1, 11 };

            var result = Serialize(source);

            result.ShouldNotBeSameAs(source);
            result.SequenceShouldBeEqual(source);
        }

        [Fact]
        public void Array_of_nullable_int_should_serialize()
        {
            var source = new int?[] { null, 1, 11 };

            var result = Serialize(source);

            result.ShouldNotBeSameAs(source);
            result.SequenceShouldBeEqual(source);
        }

        [Fact]
        public void Three_dimensional_array_of_nullable_int_should_serialize()
        {
#pragma warning disable SA1500 // Braces for multi-line statements should not share line
            var array = new int?[,,]
            {
                {
                    { null, 8, 1, 1, 1 }, { 1, 8, 1, 1, 1 }, { 11, 8, 1, 1, 1 },
                    { 8, null, 1, 1, 1 }, { 8, 1, 1, 1, 1 }, { 8, 11, 1, 1, 1 },
                },
                {
                    { null, 4, 1, 1, 1 }, { 1, 4, 1, 1, 1 }, { 11, 4, 1, 1, 1 },
                    { null, 4, 1, 1, 1 }, { 1, 4, 1, 1, 1 }, { 11, 4, 1, 1, 1 },
                },
            };
#pragma warning restore SA1500 // Braces for multi-line statements should not share line

            var result = Serialize<int?[,,], int?[]>(array);
            result.Length.ShouldBe(60);
        }

        [Fact]
        public void Array_of_char_should_serialize()
        {
            var source = new[] { 'h', 'e', 'l', 'l', 'o' };

            var result = Serialize(source);

            result.ShouldNotBeSameAs(source);
            result.SequenceShouldBeEqual(source);
        }

        [Fact]
        public void Nested_anonymous_type_with_nullable_int_property_should_serialize()
        {
            int? i = 1;
            sbyte? b1 = -2;
            byte b2 = 2;
            Should.NotThrow(() => Serialize(new { B = b1, N = new { I = i, B = b2 } }));
        }

        [Fact]
        public void Float_as_string_should_serialize()
        {
            var result = Serialize<float, float>(0.1F, formatValuesAsStrings: true);
            result.ShouldBe(0.1F);
        }

        [Fact]
        public void Custom_reference_type_should_serialize()
        {
            var source = new A<int> { Value = 1 };

            var result = Serialize(source);

            result.Value.ShouldBe(1);
        }

        [Fact]
        public void Custom_reference_type_array_should_serialize()
        {
            var source = new[]
            {
                new A<int> { Value = 1 },
                new A<int> { Value = 2 },
            };

            var result = Serialize(source);

            result.SequenceShouldBeEqual(source, (x, y) => x.Value == y.Value);
        }

        [Fact]
        public void Custom_reference_type_with_property_of_custom_reference_type_array_should_serialize()
        {
            var source = new A<A<int>[]>
            {
                Value = new[]
                {
                    new A<int> { Value = 1 },
                    new A<int> { Value = 2 },
                },
            };

            var result = Serialize(source);

            result.Value.SequenceShouldBeEqual(source.Value, (x, y) => x.Value == y.Value);
        }

        [Fact]
        public void List_of_custom_reference_type_with_property_of_custom_reference_type_array_should_serialize()
        {
            var source = new List<A<A<int>[]>>
            {
                new A<A<int>[]>
                {
                    Value = new[]
                    {
                        new A<int> { Value = 1 },
                        new A<int> { Value = 2 },
                    },
                },
                new A<A<int>[]>
                {
                    Value = new[]
                    {
                        new A<int> { Value = 3 },
                    },
                },
            };

            var result = Serialize(source);

            result.SequenceShouldBeEqual(
                source,
                (x, y) => x.Value.SequenceEqual(
                    y.Value,
                    (x, y) => x.Value == y.Value));
        }

        private object SerializeAsProperty(Type propertyTape, object propertyValue, bool setTypeFromGenericArgument = true, bool formatValuesAsStrings = false)
        {
            var method = typeof(When_serializing_dynamic_object)
              .GetMethods(PrivateInstance)
              .Single(x => x.Name == nameof(SerializeAsProperty) && x.IsGenericMethod && x.GetGenericArguments().Length == 1);
            return method.MakeGenericMethod(propertyTape).Invoke(this, new[] { propertyValue, setTypeFromGenericArgument, formatValuesAsStrings });
        }

        private T SerializeAsProperty<T>(T value, bool setTypeFromGenericArgument = true, bool formatValuesAsStrings = false)
            => Serialize<A<T>, A<T>>(new A<T> { Value = value }, setTypeFromGenericArgument, formatValuesAsStrings).Value;

        private object Serialize(Type type, object value, bool setTypeFromGenericArgument = true, bool formatValuesAsStrings = false)
        {
            var method = typeof(When_serializing_dynamic_object)
                .GetMethods(PrivateInstance)
                .Single(x => x.Name == nameof(Serialize) && x.IsGenericMethod && x.GetGenericArguments().Length == 1 && x.GetParameters().Length == 3);
            return method.MakeGenericMethod(type).Invoke(this, new[] { value, setTypeFromGenericArgument, formatValuesAsStrings });
        }

        private T Serialize<T>(T value, bool setTypeFromGenericArgument, bool formatValuesAsStrings)
            => Serialize<T, T>(value, setTypeFromGenericArgument, formatValuesAsStrings);

        private TResult Serialize<TSource, TResult>(TSource value, bool setTypeFromGenericArgument = true, bool formatValuesAsStrings = false)
        {
            var settings = new DynamicObjectMapperSettings { FormatNativeTypesAsString = formatValuesAsStrings };
            var dynamicObject = new DynamicObjectMapper(settings).MapObject(value);
            if (dynamicObject is not null && setTypeFromGenericArgument)
            {
                dynamicObject.Type = new TypeInfo(typeof(TSource), false, false);
            }

            var serializedDynamicObject = _serialize(dynamicObject);

            var resurectedValue = new DynamicObjectMapper().Map<TResult>(serializedDynamicObject);
            return resurectedValue;
        }

        private T Serialize<T>(T source)
        {
            var dynamicSourceObject = DynamicObject.Create(source);

            var dynamicSourceResult = _serialize(dynamicSourceObject);

            dynamicSourceResult.ShouldNotBeSameAs(dynamicSourceObject);

            var result = dynamicSourceResult.CreateObject();

            result.ShouldNotBeSameAs(source);
            result.ShouldBeOfType(source.GetType());
            return result.ShouldBeAssignableTo<T>();
        }
    }
}