text:
<?php

namespace Bakkerij\Bundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Bakkerij\Bundle\Entity\Product;
use Bakkerij\Bundle\Entity\Address;
use Bakkerij\Bundle\Entity\Bestelling;
use Bakkerij\Bundle\Form\AddressType;

class BestellingController extends Controller {

    public function facture() {

        $em = $this->getDoctrine()->getManager();
        $generator = $this->container->get('security.secure_random');
        $session = $this->getRequest()->getSession();
        $address = $session->get('address');
        $panier = $session->get('panier');
        $commande = array();
        $totalHT = 0;
        $totalTTC = 0;

        $facturation = $em->getRepository('BakkerijBundle:Address')->find($address['facturation']);
        $livraison = $em->getRepository('BakkerijBundle:Address')->find($address['livraison']);
        $products = $em->getRepository('BakkerijBundle:Product')->findArray(array_keys($session->get('panier')));

        foreach ($products as $product) {
            $prixHT = ($product->getPrijs() * $panier[$product->getId()]);
            $prixTTC = $prixHT + ($product->getPrijs() * $panier[$product->getId()] * 0.21);
            $totalHT += $prixHT;
            $totalTTC += $prixTTC;

            $tvaapayer = round($prixTTC - $prixHT, 2);
            $commande['produit'][$product->getId()] = array('reference' => $product->getNaam(),
                'quantite' => $panier[$product->getId()],
                'prixHT' => round($product->getPrijs(), 2),
                'prixTTC' => round($product->getPrijs() / 0.21, 2));
        }
        $commande['livraison'] = array('prenom' => $livraison->getVoornaam(),
            'nom' => $livraison->getNaam(),
            'telephone' => $livraison->getPhone(),
            'address' => $livraison->getAddress(),
            'pc' => $livraison->getPc(),
            'ville' => $livraison->getStad(),
            'pays' => $livraison->getLand(),
            'complement' => $livraison->getComplement());

        $commande['facturation'] = array('prenom' => $facturation->getVoornaam(),
            'nom' => $facturation->getNaam(),
            'telephone' => $facturation->getPhone(),
            'address' => $facturation->getAddress(),
            'pc' => $facturation->getPc(),
            'ville' => $facturation->getStad(),
            'pays' => $facturation->getLand(),
            'complement' => $facturation->getComplement());

        $commande['prixHT'] = round($totalHT, 2);
        $commande['prixTTC'] = round($totalTTC, 2);
        $commande['token'] = bin2hex($generator->nextBytes(20));
        return $commande;
    }

    public function prepareCommandeAction() {
        $session = $this->getRequest()->getSession();
        $em = $this->getDoctrine()->getManager();

        if (!$session->has('commande'))
            $commande = new Bestelling();
        else
            $commande = $em->getRepository('BakkerijBundle:Bestelling')->find($session->get('commande'));

        $commande->setDatum(new \DateTime());
        $commande->setUsers($this->container->get('security.context')->getToken()->getUser());
        $commande->setValider(0);
        $commande->setReference(0);
        $commande->setBestelproducten($this->facture());

        //echo $prepareCommande->getContent();

        if (!$session->has('commande')) {
            $em->persist($commande);
            $session->set('commande', $commande);
        }

        $em->flush();
        return new Response($commande->getId());
    }

    // API paimenet
    public function validationCommandeAction($id) {
        $em = $this->getDoctrine()->getManager();
        $commande = $em->getRepository('BakkerijBundle:Bestelling')->find($id);

        if (!$commande || $commande->getValider() == 1)
           throw $this->createNotFoundException('La commande n\'existe pas');

        $commande->setValider(1);
        $commande->setReference($this->container->get('setNewReference')->reference()); // Service
        $em->flush();

        $session = $this->getRequest()->getSession();
        $session->remove('address');
        $session->remove('livraison');
        $session->remove('facturation');
        $session->remove('panier');
        $session->remove('commande');

        $this->get('session')->getFlashBag()->add('Success', 'Commande OK');
        return $this->redirect($this->generateUrl('factures'));
    }

}


text:
/* MACHINE GENERATED FILE, DO NOT EDIT */

#include <jni.h>
#include "extgl.h"

typedef void (APIENTRY *glProgramNamedParameter4fNVPROC) (GLuint id, GLsizei length, const GLubyte * name, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
typedef void (APIENTRY *glProgramNamedParameter4dNVPROC) (GLuint id, GLsizei length, const GLubyte * name, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
typedef void (APIENTRY *glGetProgramNamedParameterfvNVPROC) (GLuint id, GLsizei length, const GLubyte * name, GLfloat * params);
typedef void (APIENTRY *glGetProgramNamedParameterdvNVPROC) (GLuint id, GLsizei length, const GLubyte * name, GLdouble * params);

JNIEXPORT void JNICALL Java_org_lwjgl_opengl_NVFragmentProgram_nglProgramNamedParameter4fNV(JNIEnv *env, jclass clazz, jint id, jint length, jlong name, jfloat x, jfloat y, jfloat z, jfloat w, jlong function_pointer) {
	const GLubyte *name_address = (const GLubyte *)(intptr_t)name;
	glProgramNamedParameter4fNVPROC glProgramNamedParameter4fNV = (glProgramNamedParameter4fNVPROC)((intptr_t)function_pointer);
	glProgramNamedParameter4fNV(id, length, name_address, x, y, z, w);
}

JNIEXPORT void JNICALL Java_org_lwjgl_opengl_NVFragmentProgram_nglProgramNamedParameter4dNV(JNIEnv *env, jclass clazz, jint id, jint length, jlong name, jdouble x, jdouble y, jdouble z, jdouble w, jlong function_pointer) {
	const GLubyte *name_address = (const GLubyte *)(intptr_t)name;
	glProgramNamedParameter4dNVPROC glProgramNamedParameter4dNV = (glProgramNamedParameter4dNVPROC)((intptr_t)function_pointer);
	glProgramNamedParameter4dNV(id, length, name_address, x, y, z, w);
}

JNIEXPORT void JNICALL Java_org_lwjgl_opengl_NVFragmentProgram_nglGetProgramNamedParameterfvNV(JNIEnv *env, jclass clazz, jint id, jint length, jlong name, jlong params, jlong function_pointer) {
	const GLubyte *name_address = (const GLubyte *)(intptr_t)name;
	GLfloat *params_address = (GLfloat *)(intptr_t)params;
	glGetProgramNamedParameterfvNVPROC glGetProgramNamedParameterfvNV = (glGetProgramNamedParameterfvNVPROC)((intptr_t)function_pointer);
	glGetProgramNamedParameterfvNV(id, length, name_address, params_address);
}

JNIEXPORT void JNICALL Java_org_lwjgl_opengl_NVFragmentProgram_nglGetProgramNamedParameterdvNV(JNIEnv *env, jclass clazz, jint id, jint length, jlong name, jlong params, jlong function_pointer) {
	const GLubyte *name_address = (const GLubyte *)(intptr_t)name;
	GLdouble *params_address = (GLdouble *)(intptr_t)params;
	glGetProgramNamedParameterdvNVPROC glGetProgramNamedParameterdvNV = (glGetProgramNamedParameterdvNVPROC)((intptr_t)function_pointer);
	glGetProgramNamedParameterdvNV(id, length, name_address, params_address);
}

redpajama_set_name: RedPajamaGithub


text:
package com.tom_roush.pdfbox.pdmodel.graphics.image;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.Log;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.SoftReference;
import java.util.Arrays;
import java.util.List;

import com.tom_roush.pdfbox.cos.COSArray;
import com.tom_roush.pdfbox.cos.COSBase;
import com.tom_roush.pdfbox.cos.COSDictionary;
import com.tom_roush.pdfbox.cos.COSInputStream;
import com.tom_roush.pdfbox.cos.COSName;
import com.tom_roush.pdfbox.cos.COSObject;
import com.tom_roush.pdfbox.cos.COSStream;
import com.tom_roush.pdfbox.filter.DecodeOptions;
import com.tom_roush.pdfbox.filter.DecodeResult;
import com.tom_roush.pdfbox.io.IOUtils;
import com.tom_roush.pdfbox.pdmodel.PDDocument;
import com.tom_roush.pdfbox.pdmodel.PDResources;
import com.tom_roush.pdfbox.pdmodel.common.PDMetadata;
import com.tom_roush.pdfbox.pdmodel.common.PDStream;
import com.tom_roush.pdfbox.pdmodel.documentinterchange.markedcontent.PDPropertyList;
import com.tom_roush.pdfbox.pdmodel.graphics.PDXObject;
import com.tom_roush.pdfbox.pdmodel.graphics.color.PDColorSpace;
import com.tom_roush.pdfbox.pdmodel.graphics.color.PDDeviceGray;
import com.tom_roush.pdfbox.util.filetypedetector.FileType;
import com.tom_roush.pdfbox.util.filetypedetector.FileTypeDetector;

/**
 * An Image XObject.
 *
 * @author John Hewson
 * @author Ben Litchfield
 */
public final class PDImageXObject extends PDXObject implements PDImage
{
    private SoftReference<Bitmap> cachedImage;
    private PDColorSpace colorSpace;

    // initialize to MAX_VALUE as we prefer lower subsampling when keeping/replacing cache.
    private int cachedImageSubsampling = Integer.MAX_VALUE;

    /**
     * current resource dictionary (has color spaces)
     */
    private final PDResources resources;

    /**
     * Creates an Image XObject in the given document. This constructor is for internal PDFBox use
     * and is not for PDF generation. Users who want to create images should look at {@link #createFromFileByExtension(File, PDDocument)
     * }.
     *
     * @param document the current document
     * @throws java.io.IOException if there is an error creating the XObject.
     */
    public PDImageXObject(PDDocument document) throws IOException
    {
        this(new PDStream(document), null);
    }

    /**
     * Creates an Image XObject in the given document using the given filtered stream. This
     * constructor is for internal PDFBox use and is not for PDF generation. Users who want to
     * create images should look at {@link #createFromFileByExtension(File, PDDocument) }.
     *
     * @param document the current document
     * @param encodedStream an encoded stream of image data
     * @param cosFilter the filter or a COSArray of filters
     * @param width the image width
     * @param height the image height
     * @param bitsPerComponent the bits per component
     * @param initColorSpace the color space
     * @throws IOException if there is an error creating the XObject.
     */
    public PDImageXObject(PDDocument document, InputStream encodedStream,
        COSBase cosFilter, int width, int height, int bitsPerComponent,
        PDColorSpace initColorSpace) throws IOException
    {
        super(createRawStream(document, encodedStream), COSName.IMAGE);
        getCOSObject().setItem(COSName.FILTER, cosFilter);
        resources = null;
        colorSpace = null;
        setBitsPerComponent(bitsPerComponent);
        setWidth(width);
        setHeight(height);
        setColorSpace(initColorSpace);
    }

    /**
     * Creates an Image XObject with the given stream as its contents and current color spaces. This
     * constructor is for internal PDFBox use and is not for PDF generation. Users who want to
     * create images should look at {@link #createFromFileByExtension(File, PDDocument) }.
     *
     * @param stream the XObject stream to read
     * @param resources the current resources
     * @throws java.io.IOException if there is an error creating the XObject.
     */
    public PDImageXObject(PDStream stream, PDResources resources) throws IOException
    {
        super(stream, COSName.IMAGE);
        this.resources = resources;
        List<COSName> filters = stream.getFilters();
        // JPX would be decode twice in rending. here is no need. just to ensure no parameters is missing.
        if (filters != null && !filters.isEmpty() && COSName.JPX_DECODE.equals(filters.get(filters.size() - 1)))
        {
            // skip decode jpx is no parameters is missing. see PDFBOX-5375 PDFBOX-3340
            List<COSName> requireKeys = Arrays.asList(COSName.WIDTH, COSName.HEIGHT, COSName.COLORSPACE);
            boolean needDecode = false;
            COSStream cos = stream.getCOSObject();
            for (COSName k : requireKeys)
            {
                if (!cos.containsKey(k))
                {
                    needDecode = true;
                    break;
                }
            }
            if (!needDecode)
            {
                return;
            }
            COSInputStream is = null;
            try
            {
                is = stream.createInputStream();
                DecodeResult decodeResult = is.getDecodeResult();
                stream.getCOSObject().addAll(decodeResult.getParameters());
                // getJPXColorSpace would be null in most cases
                this.colorSpace = decodeResult.getJPXColorSpace();
            }
            finally
            {
                IOUtils.closeQuietly(is);
            }
        }
    }

    /**
     * Creates a thumbnail Image XObject from the given COSBase and name.
     * @param cosStream the COS stream
     * @return an XObject
     * @throws IOException if there is an error creating the XObject.
     */
    public static PDImageXObject createThumbnail(COSStream cosStream) throws IOException
    {
        // thumbnails are special, any non-null subtype is treated as being "Image"
        PDStream pdStream = new PDStream(cosStream);
        return new PDImageXObject(pdStream, null);
    }

    /**
     * Creates a COS stream from raw (encoded) data.
     */
    private static COSStream createRawStream(PDDocument document, InputStream rawInput)
        throws IOException
    {
        COSStream stream = document.getDocument().createCOSStream();
        OutputStream output = null;
        try
        {
            output = stream.createRawOutputStream();
            IOUtils.copy(rawInput, output);
        }
        finally
        {
            if (output != null)
            {
                output.close();
            }
        }
        return stream;
    }

    /**
     * Create a PDImageXObject from an image file, see {@link #createFromFileByExtension(File, PDDocument)} for
     * more details.
     *
     * @param imagePath the image file path.
     * @param doc the document that shall use this PDImageXObject.
     * @return a PDImageXObject.
     * @throws IOException if there is an error when reading the file or creating the
     * PDImageXObject, or if the image type is not supported.
     */
    public static PDImageXObject createFromFile(String imagePath, PDDocument doc) throws IOException
    {
        return createFromFileByExtension(new File(imagePath), doc);
    }

    /**
     * Create a PDImageXObject from an image file. The file format is determined by the file name
     * suffix. The following suffixes are supported: JPG, JPEG, TIF, TIFF, GIF, BMP and PNG. This is
     * a convenience method that calls {@link JPEGFactory#createFromStream},
     * {@link CCITTFactory#createFromFile} or {@link BitmapFactory#decodeFile} combined with
     * {@link LosslessFactory#createFromImage}. (The later can also be used to create a
     * PDImageXObject from a Bitmap). Starting with 2.0.18, this call will create an image
     * directly from a PNG file without decoding it (when possible), which is faster. However the
     * result size depends on the compression skill of the software that created the PNG file. If
     * file size or bandwidth are important to you or to your clients, then create your PNG files
     * with a tool that has implemented the
     * Zopfli
     * algorithm, or use the two-step process mentioned above.
     *
     * @param file the image file.
     * @param doc the document that shall use this PDImageXObject.
     * @return a PDImageXObject.
     * @throws IOException if there is an error when reading the file or creating the
     * PDImageXObject.
     * @throws IllegalArgumentException if the image type is not supported.
     */
    public static PDImageXObject createFromFileByExtension(File file, PDDocument doc) throws IOException
    {
        String name = file.getName();
        int dot = name.lastIndexOf('.');
        if (dot == -1)
        {
            throw new IllegalArgumentException("Image type not supported: " + name);
        }
        String ext = name.substring(dot + 1).toLowerCase();
        if ("jpg".equals(ext) || "jpeg".equals(ext))
        {
            FileInputStream fis = null;
            try
            {
                fis = new FileInputStream(file);
                return JPEGFactory.createFromStream(doc, fis);
            }
            finally
            {
                IOUtils.closeQuietly(fis);
            }
        }
        if ("tif".equals(ext) || "tiff".equals(ext))
        {
            try
            {
                return CCITTFactory.createFromFile(doc, file);
            }
            catch (IOException ex)
            {
                Log.d("PdfBox-Android", "Reading as TIFF failed, setting fileType to PNG", ex);
                // Plan B: try reading with ImageIO
                // common exception:
                // First image in tiff is not CCITT T4 or T6 compressed
                ext = "png";
            }
        }
        if ("gif".equals(ext) || "bmp".equals(ext) || "png".equals(ext))
        {
            Bitmap bim = BitmapFactory.decodeFile(file.getPath());
            return LosslessFactory.createFromImage(doc, bim);
        }
        throw new IllegalArgumentException("Image type not supported: " + name);
    }

    /**
     * Create a PDImageXObject from an image file. The file format is determined by the file
     * content. The following file types are supported: JPG, JPEG, TIF, TIFF, GIF, BMP and PNG. This
     * is a convenience method that calls {@link JPEGFactory#createFromStream},
     * {@link CCITTFactory#createFromFile} or {@link BitmapFactory#decodeFile} combined with
     * {@link LosslessFactory#createFromImage}. (The later can also be used to create a
     * PDImageXObject from a Bitmap). Starting with 2.0.18, this call will create an image
     * directly from a png file without decoding it (when possible), which is faster. However the
     * result size depends on the compression skill of the software that created the PNG file. If
     * file size or bandwidth are important to you or to your clients, then create your PNG files
     * with a tool that has implemented the
     * Zopfli
     * algorithm, or use the two-step process mentioned above.
     *
     * @param file the image file.
     * @param doc the document that shall use this PDImageXObject.
     * @return a PDImageXObject.
     * @throws IOException if there is an error when reading the file or creating the
     * PDImageXObject.
     * @throws IllegalArgumentException if the image type is not supported.
     */
    public static PDImageXObject createFromFileByContent(File file, PDDocument doc) throws IOException
    {
        FileInputStream fileInputStream = null;
        BufferedInputStream bufferedInputStream = null;
        FileType fileType = null;
        try
        {
            fileInputStream = new FileInputStream(file);
            bufferedInputStream = new BufferedInputStream(fileInputStream);
            fileType = FileTypeDetector.detectFileType(bufferedInputStream);
        }
        catch (IOException e)
        {
            throw new IOException("Could not determine file type: " + file.getName(), e);
        }
        finally
        {
            IOUtils.closeQuietly(fileInputStream);
            IOUtils.closeQuietly(bufferedInputStream);
        }
        if (fileType == null)
        {
            throw new IllegalArgumentException("Image type not supported: " + file.getName());
        }

        if (fileType.equals(FileType.JPEG))
        {
            FileInputStream fis = new FileInputStream(file);
            PDImageXObject imageXObject = JPEGFactory.createFromStream(doc, fis);
            fis.close();
            return imageXObject;
        }
        if (fileType.equals(FileType.TIFF))
        {
            try
            {
                return CCITTFactory.createFromFile(doc, file);
            }
            catch (IOException ex)
            {
                Log.d("PdfBox-Android", "Reading as TIFF failed, setting fileType to PNG", ex);
                // Plan B: try reading with ImageIO
                // common exception:
                // First image in tiff is not CCITT T4 or T6 compressed
                fileType = FileType.PNG;
            }
        }
        if (fileType.equals(FileType.BMP) || fileType.equals(FileType.GIF) || fileType.equals(FileType.PNG))
        {
            Bitmap bim = BitmapFactory.decodeFile(file.getPath());
            return LosslessFactory.createFromImage(doc, bim);
        }
        throw new IllegalArgumentException("Image type " + fileType + " not supported: " + file.getName());
    }

    /**
     * Create a PDImageXObject from bytes of an image file. The file format is determined by the
     * file content. The following file types are supported: JPG, JPEG, TIF, TIFF, GIF, BMP and PNG.
     * This is a convenience method that calls {@link JPEGFactory#createFromByteArray},
     * {@link CCITTFactory#createFromFile} or {@link BitmapFactory#decodeFile} combined with
     * {@link LosslessFactory#createFromImage}. (The later can also be used to create a
     * PDImageXObject from a Bitmap). Starting with 2.0.18, this call will create an image
     * directly from a PNG file without decoding it (when possible), which is faster. However the
     * result size depends on the compression skill of the software that created the PNG file. If
     * file size or bandwidth are important to you or to your clients, then create your PNG files
     * with a tool that has implemented the
     * Zopfli
     * algorithm, or use the two-step process mentioned above.
     *
     * @param byteArray bytes from an image file.
     * @param document the document that shall use this PDImageXObject.
     * @param name name of image file for exception messages, can be null.
     * @return a PDImageXObject.
     * @throws IOException if there is an error when reading the file or creating the
     * PDImageXObject.
     * @throws IllegalArgumentException if the image type is not supported.
     */
    public static PDImageXObject createFromByteArray(PDDocument document, byte[] byteArray, String name) throws IOException
    {
        FileType fileType;
        try
        {
            fileType = FileTypeDetector.detectFileType(byteArray);
        }
        catch (IOException e)
        {
            throw new IOException("Could not determine file type: " + name, e);
        }
        if (fileType == null)
        {
            throw new IllegalArgumentException("Image type not supported: " + name);
        }

        if (fileType.equals(FileType.JPEG))
        {
            return JPEGFactory.createFromByteArray(document, byteArray);
        }
//        if (fileType.equals(FileType.PNG)) TODO: PdfBox-Android
        if (fileType.equals(FileType.TIFF))
        {
            try
            {
                return CCITTFactory.createFromByteArray(document, byteArray);
            }
            catch (IOException ex)
            {
                Log.d("PdfBox-Android", "Reading as TIFF failed, setting fileType to PNG", ex);
                // Plan B: try reading with ImageIO
                // common exception:
                // First image in tiff is not CCITT T4 or T6 compressed
                fileType = FileType.PNG;
            }
        }
        if (fileType.equals(FileType.BMP) || fileType.equals(FileType.GIF) || fileType.equals(FileType.PNG))
        {
            ByteArrayInputStream bais = new ByteArrayInputStream(byteArray);
            Bitmap bim = BitmapFactory.decodeStream(bais);
            return LosslessFactory.createFromImage(document, bim);
        }
        throw new IllegalArgumentException("Image type " + fileType + " not supported: " + name);
    }

    /**
     * Returns the metadata associated with this XObject, or null if there is none.
     * @return the metadata associated with this object.
     */
    public PDMetadata getMetadata()
    {
        COSStream cosStream = getCOSObject().getCOSStream(COSName.METADATA);
        if (cosStream != null)
        {
            return new PDMetadata(cosStream);
        }
        return null;
    }

    /**
     * Sets the metadata associated with this XObject, or null if there is none.
     * @param meta the metadata associated with this object
     */
    public void setMetadata(PDMetadata meta)
    {
        getCOSObject().setItem(COSName.METADATA, meta);
    }

    /**
     * Returns the key of this XObject in the structural parent tree.
     *
     * @return this object's key the structural parent tree or -1 if there isn't any.
     */
    public int getStructParent()
    {
        return getCOSObject().getInt(COSName.STRUCT_PARENT);
    }

    /**
     * Sets the key of this XObject in the structural parent tree.
     * @param key the new key for this XObject
     */
    public void setStructParent(int key)
    {
        getCOSObject().setInt(COSName.STRUCT_PARENT, key);
    }

    /**
     * {@inheritDoc}
     * The returned images are cached via a SoftReference.
     */
    @Override
    public Bitmap getImage() throws IOException
    {
        return getImage(null, 1);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Bitmap getImage(Rect region, int subsampling) throws IOException
    {
        if (region == null && subsampling == cachedImageSubsampling && cachedImage != null)
        {
            Bitmap cached = cachedImage.get();
            if (cached != null)
            {
                return cached;
            }
        }

        // get RGB image w/o reference because applyMask might modify it, take long time and a lot of memory.
        final Bitmap image;
        final PDImageXObject softMask = getSoftMask();
        final PDImageXObject mask = getMask();
        // soft mask (overrides explicit mask)
        if (softMask != null)
        {
            image = applyMask(SampledImageReader.getRGBImage(this, region, subsampling, getColorKeyMask()),
                softMask.getOpaqueImage(), softMask.getInterpolate(), true, extractMatte(softMask));
        }
        // explicit mask - to be applied only if /ImageMask true
        else if (mask != null && mask.isStencil())
        {
            image = applyMask(SampledImageReader.getRGBImage(this, region, subsampling, getColorKeyMask()),
                mask.getOpaqueImage(), mask.getInterpolate(), false, null);
        }
        else
        {
            image = SampledImageReader.getRGBImage(this, region, subsampling, getColorKeyMask());
        }

        if (region == null && subsampling <= cachedImageSubsampling)
        {
            // only cache full-image renders, and prefer lower subsampling frequency, as lower
            // subsampling means higher quality and longer render times.
            cachedImageSubsampling = subsampling;
            cachedImage = new SoftReference<Bitmap>(image);
        }

        return image;
    }

    /**
     * Extract the matte color from a softmask.
     *
     * @param softMask
     * @return the matte color.
     * @throws IOException if the color conversion fails.
     */
    private float[] extractMatte(PDImageXObject softMask) throws IOException
    {
        COSBase base = softMask.getCOSObject().getItem(COSName.MATTE);
        float[] matte = null;
        if (base instanceof COSArray)
        {
            // PDFBOX-4267: process /Matte
            // see PDF specification 1.7, 11.6.5.3 Soft-Mask Images
            matte = ((COSArray) base).toFloatArray();
            // convert to RGB
            if (matte.length < getColorSpace().getNumberOfComponents())
            {
                Log.e("PdfBox-Android", "Image /Matte entry not long enough for colorspace, skipped");
                return null;
            }
            matte = getColorSpace().toRGB(matte);
        }
        return matte;
    }

    /**
     * {@inheritDoc}
     * The returned images are not cached.
     */
    @Override
    public Bitmap getStencilImage(Paint paint) throws IOException
    {
        if (!isStencil())
        {
            throw new IllegalStateException("Image is not a stencil");
        }
        return SampledImageReader.getStencilImage(this, paint);
    }

    /**
     * Returns an RGB buffered image containing the opaque image stream without any masks applied.
     * If this Image XObject is a mask then the buffered image will contain the raw mask.
     * @return the image without any masks applied
     * @throws IOException if the image cannot be read
     */
    public Bitmap getOpaqueImage() throws IOException
    {
        return SampledImageReader.getRGBImage(this, null);
    }

    /**
     * @param image The image to apply the mask to as alpha channel.
     * @param mask A mask image in 8 bit Gray. Even for a stencil mask image due to
     * {@link #getOpaqueImage()} and {@link SampledImageReader}'s {@code from1Bit()} special
     * handling of DeviceGray.
     * @param interpolateMask interpolation flag of the mask image.
     * @param isSoft {@code true} if a soft mask. If not stencil mask, then alpha will be inverted
     * by this method.
     * @param matte an optional RGB matte if a soft mask.
     * @return an ARGB image (can be the altered original image)
     */
    private Bitmap applyMask(Bitmap image, Bitmap mask, boolean interpolateMask,
        boolean isSoft, float[] matte)
    {
        if (mask == null)
        {
            return image;
        }

        final int width = Math.max(image.getWidth(), mask.getWidth());
        final int height = Math.max(image.getHeight(), mask.getHeight());

        // scale mask to fit image, or image to fit mask, whichever is larger.
        // also make sure that mask is 8 bit gray and image is ARGB as this
        // is what needs to be returned.
        if (mask.getWidth() < width || mask.getHeight() < height)
        {
            mask = scaleImage(mask, width, height, interpolateMask);
        }
        if (mask.getConfig() != Bitmap.Config.ALPHA_8 || !image.isMutable())
        {
            mask = mask.copy(Bitmap.Config.ALPHA_8, true);
        }

        if (image.getWidth() < width || image.getHeight() < height)
        {
            image = scaleImage(image, width, height, getInterpolate());
        }
        if (image.getConfig() != Bitmap.Config.ARGB_8888 || !image.isMutable())
        {
            image = image.copy(Bitmap.Config.ARGB_8888, true);
        }
        int[] pixels = new int[width];
        int[] maskPixels = new int[width];

        // compose alpha into ARGB image, either:
        // - very fast by direct bit combination if not a soft mask and a 8 bit alpha source.
        // - fast by letting the sample model do a bulk band operation if no matte is set.
        // - slow and complex by matte calculations on individual pixel components.
        if (!isSoft && image.getByteCount() == mask.getByteCount())
        {
            for (int y = 0; y < height; y++)
            {
                image.getPixels(pixels, 0, width, 0, y, width, 1);
                mask.getPixels(maskPixels, 0, width, 0, y, width, 1);
                for (int i = 0, c = width; c > 0; i++, c--)
                {
                    pixels[i] = pixels[i] & 0xffffff | ~maskPixels[i] & 0xff000000;
                }
                image.setPixels(pixels, 0, width, 0, y, width, 1);
            }
        }
        else if (matte == null)
        {
            for (int y = 0; y < height; y++)
            {
                image.getPixels(pixels, 0, width, 0, y, width, 1);
                mask.getPixels(maskPixels, 0, width, 0, y, width, 1);
                for (int x = 0; x < width; x++)
                {
                    if (!isSoft)
                    {
                        maskPixels[x] ^= -1;
                    }
                    pixels[x] = pixels[x] & 0xffffff | maskPixels[x] & 0xff000000;
                }
                image.setPixels(pixels, 0, width, 0, y, width, 1);
            }
        }
        else
        {
            // Original code is to clamp component and alpha to [0f, 1f] as matte is,
            // and later expand to [0; 255] again (with rounding).
            // component = 255f * ((component / 255f - matte) / (alpha / 255f) + matte)
            //           = (255 * component - 255 * 255f * matte) / alpha + 255f * matte
            // There is a clearly visible factor 255 for most components in above formula,
            // i.e. max value is 255 * 255: 16 bits + sign.
            // Let's use faster fixed point integer arithmetics with Q16.15,
            // introducing neglible errors (0.001%).
            // Note: For "correct" rounding we increase the final matte value (m0h, m1h, m2h) by
            // a half an integer.
            final int fraction = 15;
            final int factor = 255 << fraction;
            final int m0 = Math.round(factor * matte[0]) * 255;
            final int m1 = Math.round(factor * matte[1]) * 255;
            final int m2 = Math.round(factor * matte[2]) * 255;
            final int m0h = m0 / 255 + (1 << fraction - 1);
            final int m1h = m1 / 255 + (1 << fraction - 1);
            final int m2h = m2 / 255 + (1 << fraction - 1);
            for (int y = 0; y < height; y++)
            {
                image.getPixels(pixels, 0, width, 0, y, width, 1);
                mask.getPixels(maskPixels, 0, width, 0, y, width, 1);
                for (int x = 0; x < width; x++)
                {
                    int a = Color.alpha(maskPixels[x]);
                    if (a == 0)
                    {
                        pixels[x] = pixels[x] & 0xffffff;
                        continue;
                    }
                    int rgb = pixels[x];
                    int r = Color.red(rgb);
                    int g = Color.green(rgb);
                    int b = Color.blue(rgb);
                    r = clampColor(((r * factor - m0) / a + m0h) >> fraction);
                    g = clampColor(((g * factor - m1) / a + m1h) >> fraction);
                    b = clampColor(((b * factor - m2) / a + m2h) >> fraction);
                    pixels[x] = Color.argb(a, r, g, b);
                }
                image.setPixels(pixels, 0, width, 0, y, width, 1);
            }
        }
        return image;
    }

    private static int clampColor(int color)
    {
        return color < 0 ? 0 : color > 255 ? 255 : color;
    }

    /**
     * High-quality image scaling.
     */
    private Bitmap scaleImage(Bitmap image, int width, int height, boolean interpolate)
    {
        return Bitmap.createScaledBitmap(image, width, height, !interpolate);
    }

    /**
     * Returns the Mask Image XObject associated with this image, or null if there is none.
     * @return Mask Image XObject
     * @throws java.io.IOException
     */
    public PDImageXObject getMask() throws IOException
    {
        COSBase mask = getCOSObject().getDictionaryObject(COSName.MASK);
        if (mask instanceof COSArray)
        {
            // color key mask, no explicit mask to return
            return null;
        }
        else
        {
            COSStream cosStream = getCOSObject().getCOSStream(COSName.MASK);
            if (cosStream != null)
            {
                // always DeviceGray
                return new PDImageXObject(new PDStream(cosStream), null);
            }
            return null;
        }
    }

    /**
     * Returns the color key mask array associated with this image, or null if there is none.
     * @return Mask Image XObject
     */
    public COSArray getColorKeyMask()
    {
        COSBase mask = getCOSObject().getDictionaryObject(COSName.MASK);
        if (mask instanceof COSArray)
        {
            return (COSArray)mask;
        }
        return null;
    }

    /**
     * Returns the Soft Mask Image XObject associated with this image, or null if there is none.
     * @return the SMask Image XObject, or null.
     * @throws java.io.IOException
     */
    public PDImageXObject getSoftMask() throws IOException
    {
        COSStream cosStream = getCOSObject().getCOSStream(COSName.SMASK);
        if (cosStream != null)
        {
            // always DeviceGray
            return new PDImageXObject(new PDStream(cosStream), null);
        }
        return null;
    }

    @Override
    public int getBitsPerComponent()
    {
        if (isStencil())
        {
            return 1;
        }
        else
        {
            return getCOSObject().getInt(COSName.BITS_PER_COMPONENT, COSName.BPC);
        }
    }

    @Override
    public void setBitsPerComponent(int bpc)
    {
        getCOSObject().setInt(COSName.BITS_PER_COMPONENT, bpc);
    }

    @Override
    public PDColorSpace getColorSpace() throws IOException
    {
        if (colorSpace == null)
        {
            COSBase cosBase = getCOSObject().getItem(COSName.COLORSPACE, COSName.CS);
            if (cosBase != null)
            {
                COSObject indirect = null;
                if (cosBase instanceof COSObject &&
                    resources != null && resources.getResourceCache() != null)
                {
                    // PDFBOX-4022: use the resource cache because several images
                    // might have the same colorspace indirect object.
                    indirect = (COSObject) cosBase;
                    colorSpace = resources.getResourceCache().getColorSpace(indirect);
                    if (colorSpace != null)
                    {
                        return colorSpace;
                    }
                }
                colorSpace = PDColorSpace.create(cosBase, resources);
                if (indirect != null)
                {
                    resources.getResourceCache().put(indirect, colorSpace);
                }
            }
            else if (isStencil())
            {
                // stencil mask color space must be gray, it is often missing
                return PDDeviceGray.INSTANCE;
            }
            else
            {
                // an image without a color space is always broken
                throw new IOException("could not determine color space");
            }
        }
        return colorSpace;
    }

    @Override
    public InputStream createInputStream() throws IOException
    {
        return getStream().createInputStream();
    }

    @Override
    public InputStream createInputStream(DecodeOptions options) throws IOException
    {
        return getStream().createInputStream(options);
    }

    @Override
    public InputStream createInputStream(List<String> stopFilters) throws IOException
    {
        return getStream().createInputStream(stopFilters);
    }

    @Override
    public boolean isEmpty()
    {
        return getStream().getCOSObject().getLength() == 0;
    }

    @Override
    public void setColorSpace(PDColorSpace cs)
    {
        getCOSObject().setItem(COSName.COLORSPACE, cs != null ? cs.getCOSObject() : null);
        colorSpace = null;
        cachedImage = null;
    }

    @Override
    public int getHeight()
    {
        return getCOSObject().getInt(COSName.HEIGHT);
    }

    @Override
    public void setHeight(int h)
    {
        getCOSObject().setInt(COSName.HEIGHT, h);
    }

    @Override
    public int getWidth()
    {
        return getCOSObject().getInt(COSName.WIDTH);
    }

    @Override
    public void setWidth(int w)
    {
        getCOSObject().setInt(COSName.WIDTH, w);
    }

    @Override
    public boolean getInterpolate()
    {
        return getCOSObject().getBoolean(COSName.INTERPOLATE, false);
    }

    @Override
    public void setInterpolate(boolean value)
    {
        getCOSObject().setBoolean(COSName.INTERPOLATE, value);
    }

    @Override
    public void setDecode(COSArray decode)
    {
        getCOSObject().setItem(COSName.DECODE, decode);
    }

    @Override
    public COSArray getDecode()
    {
        COSBase decode = getCOSObject().getDictionaryObject(COSName.DECODE);
        if (decode instanceof COSArray)
        {
            return (COSArray) decode;
        }
        return null;
    }

    @Override
    public boolean isStencil()
    {
        return getCOSObject().getBoolean(COSName.IMAGE_MASK, false);
    }

    @Override
    public void setStencil(boolean isStencil)
    {
        getCOSObject().setBoolean(COSName.IMAGE_MASK, isStencil);
    }

    /**
     * This will get the suffix for this image type, e.g. jpg/png.
     * @return The image suffix or null if not available.
     */
    @Override
    public String getSuffix()
    {
        List<COSName> filters = getStream().getFilters();

        if (filters == null)
        {
            return "png";
        }
        else if (filters.contains(COSName.DCT_DECODE))
        {
            return "jpg";
        }
        else if (filters.contains(COSName.JPX_DECODE))
        {
            return "jpx";
        }
        else if (filters.contains(COSName.CCITTFAX_DECODE))
        {
            return "tiff";
        }
        else if (filters.contains(COSName.FLATE_DECODE)
            || filters.contains(COSName.LZW_DECODE)
            || filters.contains(COSName.RUN_LENGTH_DECODE))
        {
            return "png";
        }
        else if (filters.contains(COSName.JBIG2_DECODE))
        {
            return "jb2";
        }
        else
        {
            Log.w("PdfBox-Android", "getSuffix() returns null, filters: " + filters);
            return null;
        }
    }

    /**
     * This will get the optional content group or optional content membership dictionary.
     *
     * @return The optional content group or optional content membership dictionary or null if there
     * is none.
     */
    public PDPropertyList getOptionalContent()
    {
        COSBase base = getCOSObject().getDictionaryObject(COSName.OC);
        if (base instanceof COSDictionary)
        {
            return PDPropertyList.create((COSDictionary) base);
        }
        return null;
    }

    /**
     * Sets the optional content group or optional content membership dictionary.
     *
     * @param oc The optional content group or optional content membership dictionary.
     */
    public void setOptionalContent(PDPropertyList oc)
    {
        getCOSObject().setItem(COSName.OC, oc);
    }
}


text:
using Base.Test
using Calculus
using ForwardDiff
using ForwardDiff:
        GradientNumber,
        HessianNumber,
        value,
        grad,
        hess,
        npartials,
        isconstant,
        gradnum

floatrange = .01:.01:.99
intrange = 1:10
N = 4
T = Float64
C = NTuple{N,T}
hessveclen = ForwardDiff.halfhesslen(N)

test_val = rand(floatrange)
test_partials = tuple(rand(floatrange, N)...)
test_hessvec = rand(floatrange, hessveclen)
test_grad = GradientNumber(test_val, test_partials)
test_hess = HessianNumber(test_grad, test_hessvec)

######################
# Accessor Functions #
######################
@test value(test_hess) == test_val
@test grad(test_hess) == test_partials
@test hess(test_hess) == test_hessvec

for i in 1:N
    @test grad(test_hess, i) == test_partials[i]
end

for i in 1:hessveclen
    @test hess(test_hess, i) == test_hessvec[i]
end

@test npartials(test_hess) == npartials(typeof(test_hess)) == N

##################################
# Value Representation Functions #
##################################
@test eps(test_hess) == eps(test_val)
@test eps(typeof(test_hess)) == eps(T)

hess_zero = HessianNumber(zero(test_grad), map(zero, test_hessvec))
hess_one = HessianNumber(one(test_grad), map(zero, test_hessvec))

@test zero(test_hess) == hess_zero
@test zero(typeof(test_hess)) == hess_zero

@test one(test_hess) == hess_one
@test one(typeof(test_hess)) == hess_one

#########################################
# Conversion/Promotion/Hashing/Equality #
#########################################
int_val = round(Int, test_val)
int_partials = map(x -> round(Int, x), test_partials)
int_hessvec = map(x -> round(Int, x), test_hessvec)

float_val = float(int_val)
float_partials = map(float, int_partials)
float_hessvec= map(float, int_hessvec)

int_hess = HessianNumber(GradientNumber(int_val, int_partials), int_hessvec)
float_hess = HessianNumber(GradientNumber(float_val, float_partials), float_hessvec)
const_hess = HessianNumber{N,T,C}(float_val)

@test convert(typeof(test_hess), test_hess) == test_hess
@test convert(HessianNumber, test_hess) == test_hess
@test convert(HessianNumber{N,T,C}, int_hess) == float_hess
@test convert(HessianNumber{3,T,NTuple{3,T}}, 1) == HessianNumber{3,T,NTuple{3,T}}(1.0)
@test convert(T, HessianNumber(GradientNumber(1, tuple(0, 0)))) == 1.0

@test float(int_hess) == float_hess

IntHess = HessianNumber{N,Int,NTuple{N,Int}}
FloatHess = HessianNumber{N,Float64,NTuple{N,Float64}}

@test promote_type(IntHess, IntHess) == IntHess
@test promote_type(FloatHess, IntHess) == FloatHess
@test promote_type(IntHess, Float64) == FloatHess
@test promote_type(FloatHess, Int) == FloatHess

@test hash(int_hess) == hash(float_hess)
@test hash(const_hess) == hash(float_val)

@test int_hess == float_hess
@test float_val == const_hess
@test const_hess == float_val

@test isequal(int_hess, float_hess)
@test isequal(float_val, const_hess)
@test isequal(const_hess, float_val)

@test copy(test_hess) == test_hess

####################
# is____ Functions #
####################
@test isnan(test_hess) == isnan(test_val)
@test isnan(HessianNumber{N,T,C}(NaN))

not_const_hess = HessianNumber(GradientNumber(one(T), map(one, test_partials)))
@test !(isconstant(not_const_hess))
@test !(isreal(not_const_hess))
@test isconstant(const_hess) && isreal(const_hess)
@test isconstant(zero(not_const_hess)) && isreal(zero(not_const_hess))

inf_hess = HessianNumber{N,T,C}(Inf)
@test isfinite(test_hess) == isfinite(test_val)
@test !isfinite(inf_hess)

@test isinf(inf_hess)
@test !(isinf(test_hess))

@test isless(test_hess-1, test_hess)
@test test_hess-1 < test_hess
@test test_hess > test_hess-1

@test isless(test_val-1, test_hess)
@test test_val-1 < test_hess
@test test_hess > test_val-1

@test isless(test_hess, test_val+1)
@test test_hess < test_val+1
@test test_val+1 > test_hess

#######
# I/O #
#######
io = IOBuffer()
write(io, test_hess)
seekstart(io)

@test read(io, typeof(test_hess)) == test_hess

close(io)

##############
# Math tests #
##############
rand_val = rand(floatrange)
rand_partials = map(x -> rand(floatrange), test_partials)
rand_hessvec = map(x -> rand(floatrange), test_hessvec)
rand_grad = GradientNumber(rand_val, rand_partials)
rand_hess = HessianNumber(rand_grad, rand_hessvec)

# Addition/Subtraction #
#----------------------#
@test rand_hess + test_hess == HessianNumber(rand_grad + test_grad, rand_hessvec + test_hessvec)
@test rand_hess + test_hess == test_hess + rand_hess
@test rand_hess - test_hess == HessianNumber(rand_grad - test_grad, rand_hessvec - test_hessvec)

@test rand_val + test_hess == HessianNumber(rand_val + test_grad, test_hessvec)
@test rand_val + test_hess == test_hess + rand_val
@test rand_val - test_hess == HessianNumber(rand_val - test_grad, -test_hessvec)
@test test_hess - rand_val == HessianNumber(test_grad - rand_val, test_hessvec)

@test -test_hess == HessianNumber(-test_grad, -test_hessvec)

# Multiplication/Division #
#-------------------------#
function hess_approx_eq(a::HessianNumber, b::HessianNumber)
    eps = 1e-9
    try
        @test_approx_eq_eps value(a) value(b) eps
        @test_approx_eq_eps collect(grad(a)) collect(grad(b)) eps
        @test_approx_eq_eps hess(a) hess(b) eps
    catch err
        error("Failure: HessianNumber a and HessianNumber b should be equal.\n Error: $err\n rand_hess = $rand_hess\n test_hess = $test_hess")
    end
end

@test gradnum(rand_hess * test_hess) == rand_grad * test_grad

@test rand_val * test_hess == HessianNumber(rand_val * test_grad, rand_val * test_hessvec)
@test test_hess * rand_val == rand_val * test_hess

@test test_hess * true == test_hess
@test true * test_hess == test_hess * true
@test test_hess * false == zero(test_hess)
@test false * test_hess == test_hess * false

hess_approx_eq(rand_hess, rand_hess * (test_hess/test_hess))
hess_approx_eq(rand_hess, test_hess * (rand_hess/test_hess))
hess_approx_eq(rand_hess, (rand_hess * test_hess)/test_hess)
hess_approx_eq(test_hess, (rand_hess * test_hess)/rand_hess)

hess_approx_eq(2 * test_hess, test_hess + test_hess)
hess_approx_eq(test_hess * inv(test_hess), one(test_hess))

hess_approx_eq(rand_val / test_hess, rand_val * inv(test_hess))
hess_approx_eq(rand_val / test_hess, rand_val * 1/test_hess)
hess_approx_eq(rand_hess / test_hess, rand_hess * inv(test_hess))
hess_approx_eq(rand_hess / test_hess, rand_hess * 1/test_hess)
hess_approx_eq(test_hess / test_hess, one(test_hess))

@test test_hess / rand_val == HessianNumber(test_grad / rand_val, test_hessvec / rand_val)

# Exponentiation #
#----------------#
hess_approx_eq(test_hess^rand_hess, exp(rand_hess * log(test_hess)))
hess_approx_eq(test_hess^rand_val, exp(rand_val * log(test_hess)))
hess_approx_eq(rand_val^test_hess, exp(test_hess * log(rand_val)))

# Special Cases #
#---------------#
@test abs(test_hess) == test_hess
@test abs(-test_hess) == test_hess
hess_approx_eq(abs2(test_hess), test_hess*test_hess)

atan2_hess = atan2(test_hess, rand_hess)
atanyx_hess = atan(test_hess/rand_hess)

@test value(atan2_hess) == atan2(test_val, rand_val)
@test_approx_eq collect(grad(atan2_hess)) collect(grad(atanyx_hess))
@test_approx_eq hess(atan2_hess) hess(atanyx_hess)

# Unary functions/API usage testing #
#-----------------------------------#
N = 6
testout = Array(Float64, N, N)

function hess_deriv_ij(f_expr, x::Vector, i, j)
    var_syms = [:a, :b, :c, :l, :m, :r]
    diff_expr = differentiate(f_expr, var_syms[j])
    diff_expr = differentiate(diff_expr, var_syms[i])
    @eval begin
        a,b,c,l,m,r = $x
        return $diff_expr
    end
end

function hess_test_result(f_expr, x::Vector)
    return [hess_deriv_ij(f_expr, x, i, j) for i in 1:N, j in 1:N]
end

function hess_test_x(fsym, N)
    randrange = .01:.01:.99

    needs_modification = (:acosh, :acoth)
    if fsym in needs_modification
        randrange += 1
    end

    return rand(randrange, N)
end

chunk_sizes = (ForwardDiff.default_chunk_size, 2, Int(N/2), N)

for fsym in ForwardDiff.auto_defined_unary_hess_funcs
    testexpr = :($(fsym)(a) + $(fsym)(b) - $(fsym)(c) * $(fsym)(l) - $(fsym)(m) + $(fsym)(r))

    @eval function testf(x::Vector)
        a,b,c,l,m,r = x
        return $testexpr
    end

    for chunk in chunk_sizes
        try
            testx = hess_test_x(fsym, N)
            val_result = testf(testx)
            grad_result = ForwardDiff.gradient(testf, testx)
            hess_result = hess_test_result(testexpr, testx)

            # Non-AllResults
            test_hess = (testout) -> @test_approx_eq testout hess_result

            ForwardDiff.hessian!(testout, testf, testx; chunk_size=chunk)
            test_hess(testout)

            test_hess(ForwardDiff.hessian(testf, testx; chunk_size=chunk))

            hessf! = ForwardDiff.hessian(testf; mutates=true, chunk_size=chunk)
            testout = similar(testout)
            hessf!(testout, testx)
            test_hess(testout)

            hessf = ForwardDiff.hessian(testf; mutates=false, chunk_size=chunk)
            test_hess(hessf(testx))

            # AllResults
            test_all_results = (testout, results) -> begin
                @test_approx_eq ForwardDiff.value(results) val_result
                @test_approx_eq ForwardDiff.gradient(results) grad_result
                test_hess(ForwardDiff.hessian(results))
                test_hess(testout)
            end

            testout = similar(testout)
            results = ForwardDiff.hessian!(testout, testf, testx, AllResults; chunk_size=chunk)
            test_all_results(testout, results[2])

            testout = similar(testout)
            testout, results2 = ForwardDiff.hessian(testf, testx, AllResults; chunk_size=chunk)
            test_all_results(testout, results2)

            hessf! = ForwardDiff.hessian(testf, AllResults; mutates=true, chunk_size=chunk)
            testout = similar(testout)
            results3 = hessf!(testout, testx)
            test_all_results(testout, results3[2])

            hessf = ForwardDiff.hessian(testf, AllResults; mutates=false, chunk_size=chunk)
            testout = similar(testout)
            testout, results4 = hessf(testx)
            test_all_results(testout, results4)
        catch err
            warn("Failure when testing Hessians involving $fsym with chunk_size=$chunk:")
            throw(err)
        end
    end
end


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>User Management API: Select Language</title>
    <meta name="description" content="This site provides all the documentation you need to configure and use the User Management APIs for your organization.">

    <link rel="stylesheet" href="/assets/main.css">
    <link rel="canonical" href="/">

        User Management

Select language

English

User Management

User Management

The User Management API allows clients to manage their users and product entitlements.


text:
package com.sqap.base;

import org.junit.Before;
import org.junit.Rule;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.restdocs.JUnitRestDocumentation;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;

@RunWith(SpringRunner.class)
@WebAppConfiguration
@SpringBootTest
public class MockMvcTest {
    protected MockMvc mockMvc;

    @Rule
    public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation("target/generated-snippets");

    @Autowired
    protected WebApplicationContext context;

    @Before
    public void setup() {
        this.mockMvc =   MockMvcBuilders
                .webAppContextSetup(context)
                .apply(documentationConfiguration(this.restDocumentation))
                .alwaysDo(print())
                .build();
    }

}


text:
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

using FluentMigrator.Infrastructure;
using FluentMigrator.Model;
using FluentMigrator.Validation;

namespace FluentMigrator.Expressions
{
    /// <summary>
    /// The implementation of interfaces to alter a column
    /// </summary>
    public class AlterColumnExpression
        : MigrationExpressionBase,
          ISchemaExpression,
          IValidationChildren
    {
        /// <inheritdoc />
        public virtual string SchemaName { get; set; }

        /// <summary>
        /// Gets or sets the table name
        /// </summary>
        [Required(ErrorMessageResourceType = typeof(ErrorMessages), ErrorMessageResourceName = nameof(ErrorMessages.TableNameCannotBeNullOrEmpty))]
        public virtual string TableName { get; set; }

        /// <summary>
        /// Gets or sets the column definition
        /// </summary>
        public virtual ColumnDefinition Column { get; set; }
            = new ColumnDefinition() { ModificationType = ColumnModificationType.Alter };

        /// <inheritdoc />
        public override void ExecuteWith(IMigrationProcessor processor)
        {
            Column.TableName = TableName;
            processor.Process(this);
        }

        /// <inheritdoc />
        public override string ToString()
        {
            var typeName = Column.Type == null ? Column.CustomType : Column.Type.ToString();
            return base.ToString() + TableName + " " + Column.Name + " " + typeName;
        }

        /// <inheritdoc />
        IEnumerable<object> IValidationChildren.Children
        {
            get { yield return Column; }
        }
    }
}


text:
import os
import requests # pip install requests

# The authentication key (API Key).
# Get your own by registering at https://app.pdf.co
API_KEY = "******************************************"

# Base URL for PDF.co Web API requests
BASE_URL = "https://api.pdf.co/v1"

# Source PDF file
SourceFile = ".\\sample.pdf"

def main(args = None):
    uploadedFileUrl = uploadFile(SourceFile)
    if (uploadedFileUrl != None):
        getInfoFromPDF(uploadedFileUrl)

def getInfoFromPDF(uploadedFileUrl):
    """Get Information using PDF.co Web API"""

    # Prepare requests params as JSON
    # See documentation: https://apidocs.pdf.co
    parameters = {}
    parameters["url"] = uploadedFileUrl

    # Prepare URL for 'PDF Info' API request
    url = "{}/pdf/info".format(BASE_URL)

    # Execute request and get response as JSON
    response = requests.post(url, data=parameters, headers={ "x-api-key": API_KEY })
    if (response.status_code == 200):
        json = response.json()

        if json["error"] == False:
            # Display information
            print(json["info"])
        else:
            # Show service reported error
            print(json["message"])
    else:
        print(f"Request error: {response.status_code} {response.reason}")

def uploadFile(fileName):
    """Uploads file to the cloud"""

    # 1. RETRIEVE PRESIGNED URL TO UPLOAD FILE.

    # Prepare URL for 'Get Presigned URL' API request
    url = "{}/file/upload/get-presigned-url?contenttype=application/octet-stream&name={}".format(
        BASE_URL, os.path.basename(fileName))

    # Execute request and get response as JSON
    response = requests.get(url, headers={ "x-api-key": API_KEY })
    if (response.status_code == 200):
        json = response.json()

        if json["error"] == False:
            # URL to use for file upload
            uploadUrl = json["presignedUrl"]
            # URL for future reference
            uploadedFileUrl = json["url"]

            # 2. UPLOAD FILE TO CLOUD.
            with open(fileName, 'rb') as file:
                requests.put(uploadUrl, data=file, headers={ "x-api-key": API_KEY, "content-type": "application/octet-stream" })

            return uploadedFileUrl
        else:
            # Show service reported error
            print(json["message"])
    else:
        print(f"Request error: {response.status_code} {response.reason}")

    return None

if __name__ == '__main__':
    main()


text:
@interface ZWHSettingTableView ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic, strong) UISwitch *swi;          //

@end

@implementation ZWHSettingTableView

- (instancetype)initWithFrame:(CGRect)frame {

    if (self = [super initWithFrame:frame]) {
        [self tableView];
    }
    return self;
}

- (UITableView *)tableView {
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:self.bounds style:UITableViewStylePlain];

        _tableView.delegate = self;
        _tableView.dataSource = self;

        _tableView.bounces = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

        _tableView.tableFooterView = [[UIView alloc] init];

        _tableView.showsHorizontalScrollIndicator = YES;
        _tableView.indicatorStyle = UIScrollViewIndicatorStyleBlack;
        [self addSubview:_tableView];

        self.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    }
    return _tableView;
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.titleArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (kIsIpad) {
        return kIpadCellHeight;
    }
    else {
        return kSettingCellHeight;
    }
}

#pragma mark - UITableViewDataDelegate

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    ZWHSettingCell *cell = [[ZWHSettingCell alloc] init];

    cell.lable.text = self.titleArr[indexPath.row];
    cell.lable.textColor = kBlackColor;
    if (kIsIpad) {
        cell.lable.font = FontSize(19);
    }
    else {
        cell.lable.font = FontSize(15);
    }

    cell.lable.highlightedTextColor = kWhiteColor;
    cell.lable.textAlignment = NSTextAlignmentLeft;

    if (indexPath.row == 4) {

        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.accessoryType = UITableViewCellAccessoryNone;
        UISwitch *swi = [[UISwitch alloc] init];
        BOOL ret = [[kUserDefaults objectForKey:kClearScreen] boolValue];
        swi.on = ret;
        [swi addTarget:self action:@selector(swithAction) forControlEvents:UIControlEventValueChanged];
        if (kIsIpad) {
            swi.frame = CGRectMake(kWidth / 2 - 1 - 51 - 15, (kIpadCellHeight - 31)*0.5, 51, 31);
        }
        else {
            swi.frame = CGRectMake(kWidth / 2 - 1 - 51 - 15, (kSettingCellHeight - 31)*0.5, 51, 31);
        }

        [cell.contentView addSubview:swi];
        _swi = swi;
    }
    else if (indexPath.row == 5) {
        cell.accessoryType = UITableViewCellAccessoryNone;
        UISwitch *swi = [[UISwitch alloc] init];
        swi.on = [[kUserDefaults objectForKey:@"flyModel"] boolValue];
        [swi addTarget:self action:@selector(changeModel:) forControlEvents:UIControlEventValueChanged];
        swi.frame = CGRectMake(kWidth / 2 - 1 - 51 - 15, (kSettingCellHeight - 31)*0.5, 51, 31);
        [cell.contentView addSubview:swi];
    }

    else {
        if (_accessoryType == UITableViewCellAccessoryNone) {
        }
        else {
            cell.appearIndicator = YES;
        }
        cell.selectedBackgroundView = [[UIView alloc] initWithFrame:cell.frame];
        cell.selectedBackgroundView.backgroundColor = [UIColor greenColor];

    }

    return cell;
}

- (void)swithAction {

    if (self.swi.isOn) {
        [kUserDefaults setObject:@1 forKey:kClearScreen];
        [kUserDefaults synchronize];
    }
    else {
        [kUserDefaults setObject:@0 forKey:kClearScreen];
        [kUserDefaults synchronize];
    }
}

-(void)changeModel:(UISwitch *)swi
{
    if (swi.on) {
        [kUserDefaults setObject:@1 forKey:@"flyModel"];
    }
    else {
        [kUserDefaults setObject:@0 forKey:@"flyModel"];
    }
    if (_delegate) {
        [_delegate changeFlyModel:swi.on];
    }
    [kUserDefaults synchronize];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 4) {
        return;
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if ([self.delegate respondsToSelector:@selector(didSelectRowAtIndexPath:)]) {
        [self.delegate didSelectRowAtIndexPath:indexPath];
    }
}

- (void)dealloc {

}
@end


text:
import { buildCard } from './CardNode';
import { convertCardToHTML } from './cardToHTML';
import { markdownToHTML } from './utils/markdownUtils';

export function markdownToHTMLCard(markdown: string) {
  const html = markdownToHTML(markdown);
  return convertCardToHTML(buildCard(html));
}


text:
import sys

infile = open(sys.argv[1], "r")
outfile = open(sys.argv[2], "w")

infile.readline()
infile.readline()
infile.readline()
infile.readline()
infile.readline()
infile.readline()
infile.readline()
for x in range(0,23):
	tempstr = infile.readline()
	newstr = tempstr[-2]
	newstr = tempstr[0:len(tempstr)-2]
	outfile.write(newstr+"\n");
tempstr = infile.readline()
outfile.write(tempstr)


text:
<?php
/**
 * This file defines Builder Layouts and Layout Parts
 *
 * Themify_Builder_Layouts class register post type for Layouts and Layout Parts
 * Custom metabox, shortcode, and load layout / layout part.
 *
 *
 * @package    Themify_Builder
 * @subpackage Themify_Builder/classes
 */

/**
 * The Builder Layouts class.
 *
 * This class register post type for Layouts and Layout Parts
 * Custom metabox, shortcode, and load layout / layout part.
 *
 *
 * @package    Themify_Builder
 * @subpackage Themify_Builder/classes
 * @author     Themify
 */
class Themify_Builder_Layouts {

	/**
	 * Post Type Layout Object.
	 *
	 * @access public
	 * @var object $layout.
	 */
	public $layout;

	/**
	 * Post Type Layout Part Object.
	 *
	 * @access public
	 * @var object $layout_part.
	 */
	public $layout_part;

	/**
	 * Store registered layout / part post types.
	 *
	 * @access public
	 * @var array $post_types.
	 */
	public $post_types = array();

	/**
	 * Constructor
	 *
	 * @access public
	 */
	public function __construct() {
		$this->register_layout();

		// Builder write panel
		add_filter( 'themify_do_metaboxes', array( $this, 'layout_write_panels' ), 11 );
		add_filter( 'themify_post_types', array( $this, 'extend_post_types' ) );
		add_action( 'add_meta_boxes_tbuilder_layout_part', array( $this, 'custom_meta_boxes' ) );

		add_action( 'wp_ajax_tfb_load_layout', array( $this, 'load_layout_ajaxify' ), 10 );
		add_action( 'wp_ajax_tfb_set_layout', array( $this, 'set_layout_ajaxify' ), 10 );
		add_action( 'wp_ajax_tfb_append_layout', array( $this, 'append_layout_ajaxify' ), 10 );
		add_action( 'wp_ajax_tfb_custom_layout_form', array( $this, 'custom_layout_form_ajaxify' ), 10 );
		add_action( 'wp_ajax_tfb_save_custom_layout', array( $this, 'save_custom_layout_ajaxify' ), 10 );

		add_filter( 'template_include', array( $this, 'template_singular_layout' ) );

		add_shortcode( 'themify_layout_part', array( $this, 'layout_part_shortcode' ) );

		// Quick Edit Links
		add_filter( 'post_row_actions', array( $this, 'row_actions' ) );
		add_filter( 'page_row_actions', array( $this, 'row_actions' ) );
		add_action( 'admin_init', array( $this, 'duplicate_action' ) );

		add_action( 'admin_init', array( $this, 'cleanup_builtin_layouts' ) );
		add_filter( 'themify_builder_post_types_support', array( $this, 'add_builder_support' ) );
	}

	/**
	 * Register Layout and Layout Part Custom Post Type
	 *
	 * @access public
	 */
	public function register_layout() {
		if ( ! class_exists( 'CPT' ) ) {
			include_once THEMIFY_BUILDER_LIBRARIES_DIR . '/' . 'CPT.php';
		}

		// create a template custom post type
		$this->layout = new CPT( array(
			'post_type_name' => 'tbuilder_layout',
			'singular' => __('Layout', 'themify'),
			'plural' => __('Layouts', 'themify')
		), array(
			'supports' => array('title', 'thumbnail'),
			'exclude_from_search' => true,
			'show_in_nav_menus' => false,
			'show_in_menu' => false,
			'public' => true
		));

		// define the columns to appear on the admin edit screen
		$this->layout->columns(array(
			'cb' => '<input type="checkbox" />',
			'title' => __('Title', 'themify'),
			'thumbnail' => __('Thumbnail', 'themify'),
			'author' => __('Author', 'themify'),
			'date' => __('Date', 'themify')
		));

		// populate the thumbnail column
		$this->layout->populate_column('thumbnail', array( $this, 'populate_column_layout_thumbnail' ) );

		// use "pages" icon for post type
		$this->layout->menu_icon('dashicons-admin-page');

		// create a template custom post type
		$this->layout_part = new CPT( array(
			'post_type_name' => 'tbuilder_layout_part',
			'singular' => __('Layout Part', 'themify'),
			'plural' => __('Layout Parts', 'themify'),
			'slug' => 'tbuilder-layout-part'
		), array(
			'supports' => array('title', 'thumbnail'),
			'exclude_from_search' => true,
			'show_in_nav_menus' => false,
			'show_in_menu' => false,
			'public' => true
		));

		// define the columns to appear on the admin edit screen
		$this->layout_part->columns(array(
			'cb' => '<input type="checkbox" />',
			'title' => __('Title', 'themify'),
			'shortcode' => __('Shortcode', 'themify'),
			'author' => __('Author', 'themify'),
			'date' => __('Date', 'themify')
		));

		// populate the thumbnail column
		$this->layout_part->populate_column('shortcode', array( $this, 'populate_column_layout_part_shortcode' ) );

		// use "pages" icon for post type
		$this->layout_part->menu_icon('dashicons-screenoptions');

		$this->set_post_type_var( $this->layout->post_type_name );
		$this->set_post_type_var( $this->layout_part->post_type_name );

		add_post_type_support( $this->layout->post_type_name, 'revisions' );
		add_post_type_support( $this->layout_part->post_type_name, 'revisions' );
	}

	/**
	 * Set the post type variable.
	 *
	 * @access public
	 * @param string $name
	 */
	public function set_post_type_var( $name ) {
		array_push( $this->post_types, $name );
	}

	/**
	 * Custom column thumbnail.
	 *
	 * @access public
	 * @param array $column
	 * @param object $post
	 */
	public function populate_column_layout_thumbnail( $column, $post ) {
		echo get_the_post_thumbnail( $post->ID, 'thumbnail');
	}

	/**
	 * Custom column for shortcode.
	 *
	 * @access public
	 * @param array $column
	 * @param object $post
	 */
	public function populate_column_layout_part_shortcode( $column, $post ) {
		echo sprintf( '[themify_layout_part id=%d]', $post->ID );
		echo '
';
		echo sprintf( '[themify_layout_part slug=%s]', $post->post_name );
	}

	/**
	 * Metabox Panel
	 *
	 * @access public
	 * @param $meta_boxes
	 * @return array
	 */
	public function layout_write_panels( $meta_boxes ) {
		global $pagenow;

		if ( ! in_array( $pagenow, array( 'post-new.php', 'post.php' ) ) ) {
			return $meta_boxes;
		}

		$meta_settings = array(
			array(
				'name' 		=> 'post_image',
				'title' 	=> __('Layout Thumbnail', 'themify'),
				'description' => '',
				'type' 		=> 'image',
				'meta'		=> array()
			)
		);

		$all_meta_boxes = array();
		$all_meta_boxes[] = apply_filters( 'layout_write_panels_meta_boxes', array(
			'name'		=> __( 'Settings', 'themify' ),
			'id' 		=> 'layout-settings-builder',
			'options'	=> $meta_settings,
			'pages'    	=> $this->layout->post_type_name
		) );
		return array_merge( $meta_boxes, $all_meta_boxes);
	}

	/**
	 * Includes this custom post to array of cpts managed by Themify
	 *
	 * @access public
	 * @param Array $types
	 * @return Array
	 */
	public function extend_post_types( $types ) {
		$cpts = array( $this->layout->post_type_name, $this->layout_part->post_type_name );
		return array_merge( $types, $cpts );
	}

	/**
	 * Add meta boxes to layout and/or layout part screens.
	 *
	 * @access public
	 * @param object $post
	 */
	public function custom_meta_boxes( $post ) {
		add_meta_box( 'layout-part-info', __( 'Using this Layout Part', 'themify' ), array( $this, 'layout_part_info' ), $this->layout_part->post_type_name, 'side', 'default' );
	}

	/**
	 * Displays information about this layout part.
	 *
	 * @access public
	 */
	public function layout_part_info() {
		$layout_part = get_post();
		echo '
' . __( 'To display this Layout Part, insert this shortcode:', 'themify' ) . '

		<input type="text" readonly="readonly" class="widefat" onclick="this.select()" value="' . esc_attr( '[themify_layout_part id="' . $layout_part->ID . '"]' ) . '" />';
		if ( ! empty( $layout_part->post_name ) ) {
			echo '<input type="text" readonly="readonly" class="widefat" onclick="this.select()" value="' . esc_attr( '[themify_layout_part slug="' . $layout_part->post_name . '"]' ) . '" />';
		}
		echo '
';
	}

	/**
	 * Load list of available Templates
	 *
	 * @access public
	 */
	public function load_layout_ajaxify() {
		global $post;

		check_ajax_referer( 'tfb_load_nonce', 'nonce' );

		$layouts = array(
			'core' => array(),
			'parallax' => array(),
			'custom' => array(),
			'theme' => array(),
		);

		// user-created layouts
		$posts = new WP_Query( array(
			'post_type' => $this->layout->post_type_name,
			'posts_per_page' => -1,
			'orderby' => 'title',
			'order' => 'ASC',
		));
		if( $posts->have_posts() ) : while( $posts->have_posts() ) : $posts->the_post();
			$layouts['custom'][] = array(
				'title' => get_the_title(),
				'slug' => $post->post_name,
				'thumbnail' => has_post_thumbnail() ? get_the_post_thumbnail(null, 'thumbnail', array( 150, 150 ) ) : sprintf( '', 'http://placehold.it/150x150' ),
			);
		endwhile; endif;
		wp_reset_postdata();

		// builtin layouts
		$data = include( THEMIFY_BUILDER_INCLUDES_DIR . '/data/layouts.php' );
		if( ! empty ( $data ) ) {
			foreach( $data as $layout ) {
				$group = isset( $layout['group'] ) ? $layout['group'] : 'core';
				$layouts[$group][] = array(
					'title' => $layout['title'],
					'slug' => $layout['data'],
					'thumbnail' => sprintf( '', sprintf( $layout['thumb'], THEMIFY_BUILDER_URI . '/includes/data' ) ),
				);
			}
		}

		if( is_file( get_template_directory() . '/builder-layouts/layouts.php' ) ) {
			$theme_layouts = include( get_template_directory() . '/builder-layouts/layouts.php' );
			foreach( $theme_layouts as $layout ) {
				$group = isset( $layout['group'] ) ? $layout['group'] : 'theme';
				$layouts[$group][] = array(
					'title' => $layout['title'],
					'slug' => $layout['data'],
					'thumbnail' => sprintf( '', sprintf( $layout['thumb'], get_template_directory_uri() . '/builder-layouts' ) ),
				);
			}
		}

		include_once THEMIFY_BUILDER_INCLUDES_DIR . '/themify-builder-layout-lists.php';
		die();
	}

	/**
	 * Custom layout for Template / Template Part Builder Editor.
	 *
	 * @access public
	 */
	public function template_singular_layout( $original_template ) {
		if ( is_singular( array( $this->layout->post_type_name, $this->layout_part->post_type_name ) ) ) {
			$templatefilename = 'template-builder-editor.php';

			$return_template = locate_template(
				array(
					trailingslashit( 'themify-builder/templates' ) . $templatefilename
				)
			);

			// Get default template
			if ( ! $return_template )
				$return_template = THEMIFY_BUILDER_TEMPLATES_DIR . '/' . $templatefilename;

			return $return_template;
		} else {
			return $original_template;
		}
	}

	/**
	 * Set template to current active builder.
	 *
	 * @access public
	 */
	public function set_layout_ajaxify() {
		global $ThemifyBuilder;
		check_ajax_referer( 'tfb_load_nonce', 'nonce' );
		$template_slug = $_POST['layout_slug'];
		$current_builder_id = (int) $_POST['current_builder_id'];
		$layout_group = $_POST['layout_group'];
		$builder_data = '';
		$response = array();

		if( $layout_group == 'core' || $layout_group == 'theme' ) {
			if( $layout_group == 'core' ) {
				$file = THEMIFY_BUILDER_INCLUDES_DIR . '/data/' . $template_slug;
			} elseif( $layout_group == 'theme' ) {
				$file = get_template_directory() . '/builder-layouts/' . $template_slug;
			}
			if( is_file( $file ) ) {
				$cache_dir = themify_get_cache_dir();
				$extract_file = $cache_dir['path'] . basename( $template_slug );
				WP_Filesystem();
				$extract_action = unzip_file( $file, $extract_file );
				/* extract the file */
				if( is_wp_error( $extract_action ) ) {
					$response['msg'] = $extract_action->get_error_message();
				} else {
					$extract_file = $cache_dir['path'] . basename( $template_slug ) . '/builder_data_export.txt';
					/* use include to read the file, seems safer than wp_filesystem */
					ob_start();
					include $extract_file;
					$builder_data = ob_get_clean();
				}
			} else {
				$response['msg'] = __( 'Layout does not exist.', 'themify' );
			}
		} else {
			$args = array(
				'name' => $template_slug,
				'post_type' => $this->layout->post_type_name,
				'post_status' => 'publish',
				'numberposts' => 1
			);
			$template = get_posts( $args );
			if ( $template ) {
				$builder_data = $ThemifyBuilder->get_builder_data( $template[0]->ID );
				$builder_data = json_encode( $builder_data );
			} else {
				$response['msg'] = __('Requested layout not found.', 'themify');
			}
		}

		if ( ! empty( $builder_data ) ) {
			$GLOBALS['ThemifyBuilder_Data_Manager']->save_data( $builder_data, $current_builder_id );
			$response['status'] = 'success';
			$response['msg'] = '';
		} else {
			$response['status'] = 'failed';
			if( ! isset( $response['msg'] ) ) {
				$response['msg'] = __('Something went wrong', 'themify');
			}
		}

		do_action( 'themify_builder_layout_loaded', compact( 'template_slug', 'current_builder_id', 'layout_group', 'builder_data' ) );

		wp_send_json( $response );
		die();
	}

	/**
	 * Append template to current active builder.
	 *
	 * @access public
	 */
	public function append_layout_ajaxify() {
		global $ThemifyBuilder;
		check_ajax_referer( 'tfb_load_nonce', 'nonce' );
		$template_slug = $_POST['layout_slug'];
		$current_builder_id = (int) $_POST['current_builder_id'];
		$layout_group = $_POST['layout_group'];
		$builder_data = '';
		$response = array();

		if( $layout_group == 'core' || $layout_group == 'theme' ) {
			if( $layout_group == 'core' ) {
				$file = THEMIFY_BUILDER_INCLUDES_DIR . '/data/' . $template_slug;
			} elseif( $layout_group == 'theme' ) {
				$file = get_template_directory() . '/builder-layouts/' . $template_slug;
			}
			if( is_file( $file ) ) {
				$cache_dir = themify_get_cache_dir();
				$extract_file = $cache_dir['path'] . basename( $template_slug );
				WP_Filesystem();
				$extract_action = unzip_file( $file, $extract_file );
				/* extract the file */
				if( is_wp_error( $extract_action ) ) {
					$response['msg'] = $extract_action->get_error_message();
				} else {
					$extract_file = $cache_dir['path'] . basename( $template_slug ) . '/builder_data_export.txt';
					/* use include to read the file, seems safer than wp_filesystem */
					ob_start();
					include $extract_file;
					$builder_data = ob_get_clean();
				}
			} else {
				$response['msg'] = __( 'Layout does not exist.', 'themify' );
			}
		} else {
			$args = array(
				'name' => $template_slug,
				'post_type' => $this->layout->post_type_name,
				'post_status' => 'publish',
				'numberposts' => 1
			);
			$template = get_posts( $args );
			if ( $template ) {
				$builder_data = $ThemifyBuilder->get_builder_data( $template[0]->ID );
			} else {
				$response['msg'] = __('Requested layout not found.', 'themify');
			}
		}

		if ( ! empty( $builder_data ) ) {
			$oldPostData = $GLOBALS['ThemifyBuilder_Data_Manager']->get_data( $current_builder_id );
			$newBuilderData = $oldPostData;
			$count = count( $newBuilderData );
			$json_data = json_decode($builder_data,true);
			if($json_data){
				$builder_data = stripslashes_deep($json_data);
			}
			foreach ($builder_data as $data ) {
				$data['row_order'] = $count;
				$newBuilderData[] = $data;
				$count++;
			}
			$builder_data = json_encode( $newBuilderData );
			$GLOBALS['ThemifyBuilder_Data_Manager']->save_data( $builder_data, $current_builder_id );
			$response['status'] = 'success';
			$response['msg'] = '';
		} else {
			$response['status'] = 'failed';
			if( ! isset( $response['msg'] ) ) {
				$response['msg'] = __('Something went wrong', 'themify');
			}
		}

		do_action( 'themify_builder_layout_appended', compact( 'template_slug', 'current_builder_id', 'layout_group', 'builder_data' ) );

		wp_send_json( $response );
		die();
	}

	/**
	 * Layout Part Shortcode
	 *
	 * @access public
	 * @param array $atts
	 * @return string
	 */
	public function layout_part_shortcode( $atts ) {
		global $ThemifyBuilder;
		extract( shortcode_atts( array(
			'id' => '',
			'slug' => ''
		), $atts ));

		$args = array(
			'post_type' => $this->layout_part->post_type_name,
			'post_status' => 'publish',
			'numberposts' => 1
		);
		if ( ! empty( $slug ) ) $args['name'] = $slug;
		if ( ! empty( $id ) ) $args['p'] = $id;
		$template = get_posts( $args );
		$output = '';

		if ( $template ) {
			$builder_data = $ThemifyBuilder->get_builder_data( $template[0]->ID );

			if ( ! empty( $builder_data ) ) {
				$output = $ThemifyBuilder->retrieve_template( 'builder-layout-part-output.php', array( 'builder_output' => $builder_data, 'builder_id' => $template[0]->ID ), '', '', false );
			}
		}

		return $output;
	}

	/**
	 * Render Layout Form in lightbox
	 *
	 * @access public
	 */
	public function custom_layout_form_ajaxify() {
		check_ajax_referer( 'tfb_load_nonce', 'nonce' );
		$postid = (int) $_POST['postid'];

		$fields = array(
			array(
				'id' => 'layout_img_field',
				'type' => 'image',
				'label' => __('Image Preview', 'themify'),
				'class' => 'xlarge'
			),
			array(
				'id' => 'layout_title_field',
				'type' => 'text',
				'label' => __('Title', 'themify')
			)
		);

		include_once THEMIFY_BUILDER_INCLUDES_DIR . '/themify-builder-save-layout-form.php';
		die();
	}

	/**
	 * Save as Layout
	 *
	 * @access public
	 */
	public function save_custom_layout_ajaxify() {
		check_ajax_referer( 'tfb_load_nonce', 'nonce' );
		global $ThemifyBuilder;
		$data = array();
		$response = array(
			'status' => 'failed',
			'msg' => __('Something went wrong', 'themify')
		);

		if ( isset( $_POST['form_data'] ) )
			parse_str( $_POST['form_data'], $data );

		if ( isset( $data['postid'] ) && ! empty( $data['postid'] ) ) {
			$template = get_post( $data['postid'] );
			$title = isset( $data['layout_title_field'] ) && ! empty( $data['layout_title_field'] ) ? sanitize_text_field( $data['layout_title_field'] ) : $template->post_title . ' Layout';
			$builder_data = $ThemifyBuilder->get_builder_data( $template->ID );
			if ( ! empty( $builder_data ) ) {
				$new_id = wp_insert_post(array(
					'post_status' => 'publish',
					'post_type' => $this->layout->post_type_name,
					'post_author' => $template->post_author,
					'post_title' => $title,
				));

				$GLOBALS['ThemifyBuilder_Data_Manager']->save_data( $builder_data, $new_id );

				// Set image as Featured Image
				if ( isset( $data['layout_img_field_attach_id'] ) && ! empty( $data['layout_img_field_attach_id'] ) )
					set_post_thumbnail( $new_id, $data['layout_img_field_attach_id'] );

				$response['status'] = 'success';
				$response['msg'] = '';
			}
		}

		wp_send_json( $response );
	}

	/**
	 * Add custom link actions in post / page rows
	 *
	 * @access public
	 * @param array $actions
	 * @return array
	 */
	public function row_actions( $actions ) {
		global $post;
		$builder_link = sprintf( '%s', esc_url( get_permalink( $post->ID ) . '#builder_active' ), __('Themify Builder', 'themify' ));
		if ( ( $this->layout->post_type_name == get_post_type() ) || ( $this->layout_part->post_type_name == get_post_type() ) ) {
			$actions['themify-builder-duplicate'] = sprintf( '%s', wp_nonce_url( admin_url( 'post.php?post=' . $post->ID . '&action=duplicate_tbuilder' ), 'duplicate_themify_builder' ), __('Duplicate', 'themify') );
			$actions['themify-builder'] = $builder_link;
		} else {
			// print builder links on another post types
			$registered_post_types = themify_post_types();
			if ( in_array( get_post_type(), $registered_post_types ) )
				$actions['themify-builder'] = $builder_link;
		}

		return $actions;
	}

	/**
	 * Duplicate Post in Admin Edit page.
	 *
	 * @access public
	 */
	public function duplicate_action() {
		if ( isset( $_GET['action'] ) && 'duplicate_tbuilder' == $_GET['action'] && wp_verify_nonce($_GET['_wpnonce'], 'duplicate_themify_builder') ) {
			global $themifyBuilderDuplicate;
			$postid = (int) $_GET['post'];
			$layout = get_post( $postid );

			$new_id = $themifyBuilderDuplicate->duplicate( $layout );
			delete_post_meta( $new_id, '_themify_builder_prebuilt_layout' );

			wp_redirect( admin_url( 'edit.php?post_type=' . get_post_type( $postid ) ) );
			exit;
		}
	}

	/**
	 * Get layouts cache dir.
	 *
	 * @access public
	 * @return array
	 */
	static public function get_cache_dir() {
		$upload_dir = wp_upload_dir();

		$dir_info = array(
			'path'   => $upload_dir['basedir'] . '/themify-builder/',
			'url'    => $upload_dir['baseurl'] . '/themify-builder/'
		);

		if( ! file_exists( $dir_info['path'] ) ) {
			wp_mkdir_p( $dir_info['path'] );
		}

		return $dir_info;
	}

	/**
	 * Add Builder support to Layout and Layout Part post types.
	 *
	 * @access public
	 * @since 2.4.8
	 */
	public function add_builder_support( $post_types ) {
		$post_types['tbuilder_layout'] = 'tbuilder_layout';
		$post_types['tbuilder_layout_part'] = 'tbuilder_layout_part';

		return $post_types;
	}

	/**
	 * Runs once and removes the builtin layout posts as no longer needed
	 *
	 * @access public
	 * @since 1.5.1
	 */
	public function cleanup_builtin_layouts() {
		global $post;
		if( get_option( 'themify_builder_cleanup_builtin_layouts' ) == 'yes' )
			return;

		$posts = new WP_Query( array(
			'post_type' => $this->layout->post_type_name,
			'posts_per_page' => -1,
			'orderby' => 'title',
			'order' => 'ASC',
			'meta_key' => '_themify_builder_prebuilt_layout',
			'meta_value' => 'yes'
		));
		if( $posts->have_posts() ) : while( $posts->have_posts() ) : $posts->the_post();
			wp_delete_post( $post->ID, true );
		endwhile; endif;
		wp_reset_postdata();

		update_option( 'themify_builder_cleanup_builtin_layouts', 'yes' );
	}
}


text:
//
// This source code implements specifications defined by the Java
// Community Process. In order to remain compliant with the specification
// DO NOT add / change / or delete method signatures!
//

package javax.transaction.xa;

/**
 * @version $Rev$ $Date$
 */
public interface XAResource {
    int TMENDRSCAN = 8388608;
    int TMFAIL = 536870912;
    int TMJOIN = 2097152;
    int TMNOFLAGS = 0;
    int TMONEPHASE = 1073741824;
    int TMRESUME = 134217728;
    int TMSTARTRSCAN = 16777216;
    int TMSUCCESS = 67108864;
    int TMSUSPEND = 33554432;
    int XA_RDONLY = 3;
    int XA_OK = 0;

    void commit(Xid xid, boolean onePhase) throws XAException;

    void end(Xid xid, int flags) throws XAException;

    void forget(Xid xid) throws XAException;

    int getTransactionTimeout() throws XAException;

    boolean isSameRM(XAResource xaResource) throws XAException;

    int prepare(Xid xid) throws XAException;

    Xid[] recover(int flag) throws XAException;

    void rollback(Xid xid) throws XAException;

    boolean setTransactionTimeout(int seconds) throws XAException;

    void start(Xid xid, int flags) throws XAException;
}


text:
package org.hbird.business.navigation.orekit;

import org.apache.camel.model.ProcessorDefinition;
import org.hbird.business.api.ICatalogue;
import org.hbird.business.api.IDataAccess;
import org.hbird.business.api.IPublisher;
import org.hbird.business.core.SoftwareComponentDriver;
import org.hbird.business.navigation.PredictionComponent;
import org.hbird.business.navigation.configuration.ContactPredictionConfiguration;
import org.hbird.business.navigation.processors.GroundStationResolver;
import org.hbird.business.navigation.processors.SatelliteResolver;
import org.hbird.business.navigation.processors.TimeRangeCalulator;
import org.hbird.business.navigation.processors.TleResolver;
import org.hbird.business.navigation.processors.orekit.AzimuthCalculator;
import org.hbird.business.navigation.processors.orekit.ContactDataExtractor;
import org.hbird.business.navigation.processors.orekit.ContactPredictionRequestCreator;
import org.hbird.business.navigation.processors.orekit.DopplerCalculator;
import org.hbird.business.navigation.processors.orekit.EclipseCalculator;
import org.hbird.business.navigation.processors.orekit.ElevationCalculator;
import org.hbird.business.navigation.processors.orekit.LocationContactEventExtractor;
import org.hbird.business.navigation.processors.orekit.OrekitContactPredictor;
import org.hbird.business.navigation.processors.orekit.RangeCalculator;
import org.hbird.business.navigation.processors.orekit.SignalDelayCalculator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 *
 */
public class ContactPredictionDriver extends SoftwareComponentDriver<PredictionComponent> {

    private static final Logger LOG = LoggerFactory.getLogger(ContactPredictionDriver.class);

    protected IDataAccess dao;
    protected ICatalogue catalogue;

    @Autowired
    public ContactPredictionDriver(IDataAccess dao, ICatalogue catalogue, IPublisher publisher) {
    	super(publisher);

    	this.dao = dao;
    	this.catalogue = catalogue;
    }

    /**
     * @see org.hbird.business.core.SoftwareComponentDriver#doConfigure()
     */
    @Override
    protected void doConfigure() {

        // setup from component
        PredictionComponent component = entity;
        ContactPredictionConfiguration config = (ContactPredictionConfiguration) component.getConfiguration();

        // dependencies
        String componentId = component.getID();
        IPropagatorProvider propagatorProvider = new TlePropagatorProvider();
        IFrameProvider frameProvider = new Cirf2000FrameProvider();
        long predictionInterval = config.getPredictionInterval();
        double calculationStep = config.getDetailsCalculationStep() / 1000D; // from millis to seconds

        // processors
        ContactPredictionRequestCreator requestCreator = new ContactPredictionRequestCreator(config);
        SatelliteResolver satelliteResolver = new SatelliteResolver(dao);
        TleResolver tleResolver = new TleResolver(dao);
        GroundStationResolver gsResolver = new GroundStationResolver(dao, catalogue);
        TimeRangeCalulator timeRangeCalculator = new TimeRangeCalulator();
        OrekitContactPredictor predictor = new OrekitContactPredictor(componentId, propagatorProvider, publisher, frameProvider);
        ContactDataExtractor dataExtractor = new ContactDataExtractor();
        LocationContactEventExtractor eventExtractor = new LocationContactEventExtractor();

        AzimuthCalculator azimuthCalculator = new AzimuthCalculator();
        ElevationCalculator elevationCalculator = new ElevationCalculator(calculationStep);
        DopplerCalculator dopplerCalculator = new DopplerCalculator();
        RangeCalculator rangeCalculator = new RangeCalculator(calculationStep);
        SignalDelayCalculator signalDelayCalculator = new SignalDelayCalculator();
        EclipseCalculator eclipseCalculator = new EclipseCalculator();
        // TODO - 30.05.2013, kimmell - missing signal loss calculator

        LOG.info("Starting {}; using '{}' and '{}' with interval {} ms", new Object[] { getClass().getSimpleName(),
                propagatorProvider.getClass().getSimpleName(), frameProvider.getClass().getSimpleName(), predictionInterval });

        // actual route
        // @formatter:off
        ProcessorDefinition<?> route = from(addTimer(componentId, predictionInterval)) // execute using timer
                .bean(requestCreator)               // create request object
                .bean(satelliteResolver)            // resolve satellite
                .bean(tleResolver)                  // resolve TLE for the satellite
                .bean(gsResolver)                   // resolve ground stations from IDs
                .bean(timeRangeCalculator)          // calculate time ranges
                .bean(predictor)                    // predict the contacts
                .bean(dataExtractor)                // extract ContactData objects
                .split(body())                      // process each contact data object separately
                    .bean(azimuthCalculator)        // calculate azimuth
                    .bean(elevationCalculator)      // calculate elevation
                    .bean(dopplerCalculator)        // calculate Doppler
                    .bean(rangeCalculator)          // calculate range
                    .bean(signalDelayCalculator)    // calculate signal delay
                    .bean(eclipseCalculator)        // calculate eclipse
                    .bean(eventExtractor)           // extract LocationContactEvent objects
                    .to("log:org.hbird.prediction.contact.stats?level=DEBUG&groupInterval=60000&groupDelay=60000&groupActiveOnly=false");
        // @formatter:on

        route.bean(publisher, "publish");
    }
}


text:
package nl.exl.doomidgamesarchive.idgamesdb;

import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.ForeignKey;
import androidx.room.PrimaryKey;

@Entity(
    tableName = "images",
    foreignKeys = @ForeignKey(
        entity = File.class,
        parentColumns = "id",
        childColumns = "file_id"
    )
)
public class Image {
    @PrimaryKey
    @ColumnInfo(
        name = "id"
    )
    public int id;

    @ColumnInfo(
        name = "file_id",
        index = true
    )
    public int fileId;

    @ColumnInfo(
        name = "path"
    )
    public String path;

    @ColumnInfo(
        name = "width"
    )
    public int width;

    @ColumnInfo(
        name = "height"
    )
    public int height;

    @ColumnInfo(
        name = "color"
    )
    public int color;
}


text:
<?php
// Get the PHP helper library from https://twilio.com/docs/libraries/php
require_once "/path/to/vendor/autoload.php"; // Loads the library
use Twilio\Rest\Client;

// Your Account Sid and Auth Token from twilio.com/console
// To set up environmental variables, see http://twil.io/secure
$apiKeySid = getenv('TWILIO_API_KEY');
$apiKeySecret = "your_auth_api_key_secret";
$client = new Client($apiKeySid, $apiKeySecret);

$recordingSid = "RTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$uri = "https://video.twilio.com/v1/Recordings/$recordingSid/Media";
$response = $client->request("GET", $uri);
$mediaLocation = $response->getContent()["redirect_to"];

$media_content = file_get_contents($mediaLocation);
print_r($media_content);


text:
function remove_valid_names() {
  sed '
    # Xcode-generated asset files
    /Assets.xcassets/ d

    # Files without spaces
    /^[^ ]*$/ d
  '
}

count=$(git ls-files | remove_valid_names | wc -l | xargs)

if [[ ${count} != 0 ]]; then
  echo 'ERROR: Spaces in filenames are not permitted in this repo. Please fix.'
  echo ''

  git ls-files | remove_valid_names
  exit 1
fi


text:
/**
 * SearchForBooks.java
 *
 * This file was auto-generated from WSDL
 * by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
 */

package be.library;

public class SearchForBooks  implements java.io.Serializable {
    private java.lang.String query;

    public SearchForBooks() {
    }

    public SearchForBooks(
           java.lang.String query) {
           this.query = query;
    }

    /**
     * Gets the query value for this SearchForBooks.
     *
     * @return query
     */
    public java.lang.String getQuery() {
        return query;
    }

    /**
     * Sets the query value for this SearchForBooks.
     *
     * @param query
     */
    public void setQuery(java.lang.String query) {
        this.query = query;
    }

    private java.lang.Object __equalsCalc = null;
    public synchronized boolean equals(java.lang.Object obj) {
        if (!(obj instanceof SearchForBooks)) return false;
        SearchForBooks other = (SearchForBooks) obj;
        if (obj == null) return false;
        if (this == obj) return true;
        if (__equalsCalc != null) {
            return (__equalsCalc == obj);
        }
        __equalsCalc = obj;
        boolean _equals;
        _equals = true &&
            ((this.query==null && other.getQuery()==null) ||
             (this.query!=null &&
              this.query.equals(other.getQuery())));
        __equalsCalc = null;
        return _equals;
    }

    private boolean __hashCodeCalc = false;
    public synchronized int hashCode() {
        if (__hashCodeCalc) {
            return 0;
        }
        __hashCodeCalc = true;
        int _hashCode = 1;
        if (getQuery() != null) {
            _hashCode += getQuery().hashCode();
        }
        __hashCodeCalc = false;
        return _hashCode;
    }

    // Type metadata
    private static org.apache.axis.description.TypeDesc typeDesc =
        new org.apache.axis.description.TypeDesc(SearchForBooks.class, true);

    static {
        typeDesc.setXmlType(new javax.xml.namespace.QName("http://library.be", ">searchForBooks"));
        org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("query");
        elemField.setXmlName(new javax.xml.namespace.QName("http://library.be", "query"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
    }

    /**
     * Return type metadata object
     */
    public static org.apache.axis.description.TypeDesc getTypeDesc() {
        return typeDesc;
    }

    /**
     * Get Custom Serializer
     */
    public static org.apache.axis.encoding.Serializer getSerializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanSerializer(
            _javaType, _xmlType, typeDesc);
    }

    /**
     * Get Custom Deserializer
     */
    public static org.apache.axis.encoding.Deserializer getDeserializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanDeserializer(
            _javaType, _xmlType, typeDesc);
    }

}