text:
package org.dcm4chex.cdw.mbean;

import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BandedSampleModel;
import java.awt.image.BufferedImage;
import java.awt.image.IndexColorModel;
import java.awt.image.Raster;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.stream.FileImageInputStream;
import javax.imageio.stream.ImageInputStream;

import org.dcm4che.data.Dataset;
import org.dcm4che.data.DcmElement;
import org.dcm4che.data.DcmObjectFactory;
import org.dcm4che.data.FileMetaInfo;
import org.dcm4che.dict.Tags;
import org.dcm4che.dict.UIDs;
import org.dcm4che.imageio.plugins.DcmMetadata;
import org.dcm4che.media.DirBuilderFactory;
import org.dcm4che.media.DirReader;
import org.dcm4che.media.DirRecord;
import org.dcm4che.media.DirWriter;
import org.dcm4che.util.MD5Utils;
import org.dcm4che.util.UIDGenerator;
import org.dcm4cheri.util.StringUtils;
import org.dcm4chex.cdw.common.ExecutionStatusInfo;
import org.dcm4chex.cdw.common.Flag;
import org.dcm4chex.cdw.common.MediaCreationException;
import org.dcm4chex.cdw.common.MediaCreationRequest;
import org.dcm4chex.cdw.common.SpoolDirDelegate;
import org.jboss.logging.Logger;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 * @author gunter.zeilinter@tiani.com
 * @version $Revision: 4289 $ $Date: 2006-05-18 06:35:00 +0800 (周四, 18 5月 2006) $
 * @since 29.06.2004
 *
 */
class FilesetBuilder {

    private static final String EXT_MD5 = ".MD5";

    private static final String MD5_SUMS = "MD5_SUMS";

    private static final String DICOM = "DICOM";

    private static final String IHE_PDI = "IHE_PDI";

    private static final char[] HEX_DIGIT = { '0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

    private static final UIDGenerator uidgen = UIDGenerator.getInstance();

    private static final DcmObjectFactory dof = DcmObjectFactory.getInstance();

    private static final DirBuilderFactory dbf = DirBuilderFactory
            .getInstance();

    private final MediaComposerService service;

    private final SpoolDirDelegate spoolDir;

    private final DirRecordFactory recFact;

    private final MediaCreationRequest rq;

    private final Dataset attrs;

    private final Logger log;

    private final boolean debug;

    private final ImageReader reader;

    private final boolean preserveInstances;

    private final String nonDICOM;

    private final boolean viewer;

    private final boolean web;

    private final boolean md5sums;

    private final boolean icons;

    private final boolean indexFile;

    private BufferedImage imageBI;

    private BufferedImage jpegBI;

    private BufferedImage iconBI;

    private byte[] iconPixelData;

    private final FilesetComponent fsRoot = FilesetComponent
            .makeRootFilesetComponent();

    private final Dataset recFilter = dof.newDataset();

    private final byte[] bbuf;

    private static String toHex(int val) {
        char[] ch8 = new char[8];
        for (int i = 8; --i >= 0; val >>= 4)
            ch8[i] = HEX_DIGIT[val & 0xf];

        return String.valueOf(ch8);
    }

    private static String[] makeFileIDs(String pid, String suid, String seruid,
            String iuid) {
        return new String[] { DICOM, toHex(pid.hashCode()),
                toHex(suid.hashCode()), toHex(seruid.hashCode()),
                toHex(iuid.hashCode()),};
    }

    private static final class Pair {

        final DirRecord rec;

        final FilesetComponent comp;

        Pair(DirRecord rec, FilesetComponent comp) {
            this.rec = rec;
            this.comp = comp;
        }
    }

    public FilesetBuilder(MediaComposerService service,
            MediaCreationRequest rq, Dataset attrs) {
        this.service = service;
        this.spoolDir = service.getSpoolDir();
        this.recFact = service.getDirRecordFactory();
        this.log = service.getLog();
        this.debug = log.isDebugEnabled();
        this.reader = service.getImageReader();
        this.rq = rq;
        this.attrs = attrs;
        this.preserveInstances = Flag.isYES(attrs
                .getString(Tags.PreserveCompositeInstancesAfterMediaCreation))
                && !service.isArchiveHighWater();
        this.viewer = Flag.isYES(attrs
                .getString(Tags.IncludeDisplayApplication));
        this.nonDICOM = attrs.getString(Tags.IncludeNonDICOMObjects, "NO");
        this.web = service.includeWeb(nonDICOM);
        this.md5sums = service.includeMd5Sums(nonDICOM);
        this.indexFile = service.indexFile(nonDICOM);
        this.icons = service.createIcons(nonDICOM);
        this.bbuf = new byte[service.getBufferSize()];
    }

    final byte[] getBuffer() {
        return bbuf;
    }

    final boolean isWeb() {
        return web;
    }

    final boolean isMd5Sums() {
        return md5sums;
    }

    final boolean isViewer() {
        return viewer;
    }

    final boolean isIndexFile() {
        return indexFile;
    }

    public void buildFileset() throws MediaCreationException {
        try {
            File rootDir = mkRootDir(spoolDir, false);
            rq.setFilesetDir(rootDir);
            File readmeFile = new File(rootDir, service
                    .getFileSetDescriptorFile());
            DirWriter dirWriter = dbf.newDirWriter(rq.getDicomDirFile(),
                    rootDir.getName(),
                    rq.getFilesetID(),
                    readmeFile,
                    service.getCharsetOfFileSetDescriptorFile(),
                    null);
            HashMap patRecs = new HashMap();
            HashMap styRecs = new HashMap();
            HashMap serRecs = new HashMap();
            try {
                DcmElement refSOPs = attrs.get(Tags.RefSOPSeq);
                for (int i = 0, n = refSOPs.countItems(); i < n; ++i) {
                    addFile(rootDir,
                            refSOPs.getItem(i),
                            dirWriter,
                            patRecs,
                            styRecs,
                            serRecs);
                }

            } finally {
                try {
                    dirWriter.close();
                } catch (Exception ignore) {
                }
                spoolDir.register(rq.getDicomDirFile());
            }
        } catch (Throwable e) {
            log.error("buildFileset failed:", e);
            throw new MediaCreationException(ExecutionStatusInfo.PROC_FAILURE,
                    e);
        }
    }

    public long sizeOfDicomContent() {
        return fsRoot.size();
    }

    private void addFile(File rootDir, Dataset item, DirWriter dirWriter,
            HashMap patRecs, HashMap styRecs, HashMap serRecs)
            throws IOException, MediaCreationException {
        String iuid = item.getString(Tags.RefSOPInstanceUID);
        String cuid = item.getString(Tags.RefSOPClassUID);
        File src = spoolDir.getInstanceFile(iuid);
        if (debug)
            log.debug("M-READ " + src);
        ImageInputStream in = new FileImageInputStream(src);
        String[] fileIDs;
        try {
            reader.setInput(in);
            DcmMetadata metadata = (DcmMetadata) reader.getStreamMetadata();
            Dataset ds = metadata.getDataset();
            FileMetaInfo fmi = ds.getFileMetaInfo();
            String tsuid = fmi.getTransferSyntaxUID();

            String suid = ds.getString(Tags.StudyInstanceUID);
            String seruid = ds.getString(Tags.SeriesInstanceUID);
            String pid = ds.getString(Tags.PatientID);
            if (pid == null) {
                pid = suid;
                ds.putLO(Tags.PatientID, suid);
                log.info("Missing Patient ID in instance[uid=" + iuid +
                        "] - use Study Instance UID " + pid + " as Patient ID");
            }
            String sid = ds.getString(Tags.StudyID);
            if (sid == null) {
                sid = Integer.toString(suid.hashCode());
                ds.putSH(Tags.StudyID, sid);
                log.info("Missing Study ID in instance[uid=" + iuid +
                        "] - use hash of Study Instance UID " + sid + " as Study ID");
            }
            // ensure TYPE 2 Attributes in DICOMDIR record
            if (ds.vm(Tags.AccessionNumber) == -1) {
                ds.putLO(Tags.AccessionNumber);
            }
            if (ds.vm(Tags.StudyDescription) == -1) {
                ds.putLO(Tags.StudyDescription);
            }
            if (ds.vm(Tags.PatientName) == -1) {
                ds.putLO(Tags.PatientName);
            }

            fileIDs = makeFileIDs(pid, suid, seruid, iuid);
            Pair serRec = (Pair) serRecs.get(seruid);
            if (serRec == null) {
                Pair styRec = (Pair) styRecs.get(suid);
                if (styRec == null) {
                    Pair patRec = (Pair) patRecs.get(pid);
                    if (patRec == null) {
                        patRec = new Pair(dirWriter.add(null,
                                DirRecord.PATIENT,
                                recFact.makeRecord(DirRecord.PATIENT, ds)),
                                FilesetComponent
                                        .makePatientFilesetComponent(ds,
                                                toFilePath(fileIDs, 2)));
                        patRecs.put(pid, patRec);
                        fsRoot.addChild(patRec.comp);
                    }
                    styRec = new Pair(dirWriter.add(patRec.rec,
                            DirRecord.STUDY,
                            recFact.makeRecord(DirRecord.STUDY, ds)),
                            FilesetComponent.makeStudyFilesetComponent(ds,
                                    toFilePath(fileIDs, 3)));
                    styRecs.put(suid, styRec);
                    patRec.comp.addChild(styRec.comp);
                }
                serRec = new Pair(dirWriter.add(styRec.rec,
                        DirRecord.SERIES,
                        recFact.makeRecord(DirRecord.SERIES, ds)),
                        FilesetComponent.makeSeriesFilesetComponent(ds,
                                toFilePath(fileIDs, 4)));
                serRecs.put(seruid, serRec);
                styRec.comp.addChild(serRec.comp);
            }
            FilesetComponent comp = FilesetComponent
                    .makeInstanceFilesetComponent(ds, toFilePath(fileIDs, 5));
            comp.incSize(src.length());
            serRec.comp.addChild(comp);
            String recType = DirBuilderFactory.getRecordType(cuid);
            Dataset rec = recFact.makeRecord(recType, ds);

            if (DirRecord.IMAGE.equals(recType)) {
                Dataset iconItem = item.getItem(Tags.IconImageSeq);
                if (iconItem == null && icons)
                    try {
                        iconItem = mkIconItem(ds,
                                !UIDs.ImplicitVRLittleEndian.equals(tsuid) &&
                                !UIDs.ExplicitVRLittleEndian.equals(tsuid));
                    } catch (Exception e) {
                        log.warn("Failed to generate icon from " + src,
                                e);
                    }
                if (iconItem != null)
                        rec.putSQ(Tags.IconImageSeq).addItem(iconItem);
                if (web) {
                     try {
                        fileIDs[0] = IHE_PDI;
                        File jpegDir = new File(rq.getFilesetDir(),
                                StringUtils.toString(fileIDs,
                                        File.separatorChar));
                        fileIDs[0] = DICOM;
                        mkJpegs(jpegDir);
                    } catch (Exception e) {
                        log.warn("Failed to generate jpeg from " + src, e);
                    }
                }
            }
            dirWriter.add(serRec.rec, recType, rec, fileIDs, cuid, iuid, tsuid);
            if (debug)
                service.logMemoryUsage();
        } finally {
            try {
                in.close();
            } catch (IOException ignore) {
            }
        }

        File dest = new File(rootDir, StringUtils.toString(fileIDs,
                File.separatorChar));
        mkParentDir(dest);
        if (preserveInstances) {
            spoolDir.copy(src, dest, bbuf);
            if (md5sums)
                    spoolDir.copy(MD5Utils.makeMD5File(src), MD5Utils
                            .makeMD5File(dest), bbuf);
        } else {
            spoolDir.move(src, dest);
            File md5src = MD5Utils.makeMD5File(src);
            if (md5sums)
                spoolDir.move(md5src, MD5Utils.makeMD5File(dest));
            else
                spoolDir.delete(md5src);
        }
    }

    private String toFilePath(String[] fileIDs, int n) {
        StringBuffer sb = new StringBuffer(fileIDs[0]);
        for (int i = 1; i < n; ++i)
            sb.append(File.separatorChar).append(fileIDs[i]);
        return sb.toString();
    }

    private void mkJpegs(File dir) throws IOException {
        dir.mkdirs();
        int w0 = reader.getWidth(0);
        int h0 = reader.getHeight(0);
        float ratio = reader.getAspectRatio(0);
        int w = Math.min(w0, service.getJpegWidth());
        int h = Math.min(h0, service.getJpegHeight());
        w = (int) Math.min(w, h * ratio);
        h = (int) Math.min(h, w / ratio);
        if (debug)
                log.debug("create jpegs[w=" + w + ",h=" + h + "] from image[w="
                        + w0 + ",h=" + h0 + "]");
        ImageReadParam param = reader.getDefaultReadParam();
        imageBI = checkReusable(imageBI, w0, h0);
        AffineTransformOp scaleOp = null;
        if (w != w0 || h != h0) {
            jpegBI = checkReusable(jpegBI, w, h);
            AffineTransform scale = AffineTransform.getScaleInstance((double) w
                    / w0, (double) h / h0);
            scaleOp = new AffineTransformOp(scale,
                    AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
        }
        BufferedImage bi;
        for (int frame = 0, n = reader.getNumImages(false); frame < n; ++frame) {
            param.setDestination(imageBI);
            bi = imageBI = reader.read(frame, param);
            if (scaleOp != null) {
                // workaround for ImagingLib.filter(this, bi, dst) == null
                // if bi.getSampleModel() instanceof BandedSampleModel
                if (imageBI.getSampleModel() instanceof BandedSampleModel) {
                    log.debug("convert RGB plane to RGB pixel");
                    BufferedImage newbi = convertBI(imageBI,
                            BufferedImage.TYPE_INT_RGB);
                    imageBI.flush();
                    imageBI = newbi;
                    jpegBI = null;
                }
                bi = jpegBI = scaleOp.filter(imageBI, jpegBI);
                imageBI.flush();
            }
            File dest = new File(dir, "" + (frame + 1) + ".JPG");
            OutputStream out = new BufferedOutputStream(new FileOutputStream(
                    dest));
            try {
                JPEGImageEncoder enc = JPEGCodec.createJPEGEncoder(out);
                enc.encode(bi);
            } finally {
                out.close();
            }
            bi.flush();
        }
    }

    private BufferedImage convertBI(BufferedImage src, int imageType) {
        BufferedImage dst = new BufferedImage(src.getWidth(), src.getHeight(),
                imageType);
        Graphics2D big = dst.createGraphics();
        try {
            big.drawImage(src, 0, 0, null);
        } finally {
            big.dispose();
        }
        return dst;
    }

    private Dataset mkIconItem(Dataset ds, boolean decompress) throws IOException {
        int frame = ds.getInt(Tags.RepresentativeFrameNumber, 1) - 1;
        frame = Math.max(0, frame);
        frame = Math.min(frame, ds.getInt(Tags.NumberOfFrames, 1) - 1);

        int w0 = reader.getWidth(0);
        int h0 = reader.getHeight(0);
        float ratio = reader.getAspectRatio(0);
        int w = Math.min(w0, service.getIconWidth());
        int h = Math.min(h0, service.getIconHeight());
        w = (int) Math.min(w, h * ratio);
        h = (int) Math.min(h, w / ratio);
        int xSubsampling = (w0 - 1) / w + 1;
        int ySubsampling = (h0 - 1) / h + 1;
        w = (w0 - 1) / xSubsampling + 1;
        h = (h0 - 1) / ySubsampling + 1;
        if (debug)
                log.debug("create icon[w=" + w + ",h=" + h + "] from image[w="
                        + w0 + ",h=" + h0 + "]");
        ImageReadParam param = reader.getDefaultReadParam();
        iconBI = checkReusable(iconBI, w, h);
        if (!decompress) {
	        param.setSourceSubsampling(xSubsampling, ySubsampling, 0, 0);
	        param.setDestination(iconBI);
	        iconBI = reader.read(frame, param);
        } else {
	        param.setDestination(checkReusable(imageBI, w0, h0));
            imageBI = reader.read(frame, param);
            AffineTransform scale = AffineTransform.getScaleInstance((double) w
                    / w0, (double) h / h0);
            AffineTransformOp scaleOp = new AffineTransformOp(scale,
                    AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
            // workaround for ImagingLib.filter(this, bi, dst) == null
            // if bi.getSampleModel() instanceof BandedSampleModel
            if (imageBI.getSampleModel() instanceof BandedSampleModel) {
                log.debug("convert RGB plane to RGB pixel");
                BufferedImage newbi = convertBI(imageBI,
                        BufferedImage.TYPE_INT_RGB);
                imageBI.flush();
                imageBI = newbi;
                iconBI = null;
            }
            iconBI = scaleOp.filter(imageBI, iconBI);
            imageBI.flush();
        }
        if (w != iconBI.getWidth() || h != iconBI.getHeight()) {
            log.warn("created icon with unexpected dimension[w="
                    + iconBI.getWidth() + ",h=" + iconBI.getHeight()
                    + "] instead [w=" + w + ",h=" + h + "] from image[w=" + w0
                    + ",h=" + h0 + "]");
            w = iconBI.getWidth();
            h = iconBI.getHeight();
        }
        String pmi = ds.getString(Tags.PhotometricInterpretation);
        BufferedImage bi = iconBI;
        if ("RGB".equals(pmi)) {
            bi = convertBI(iconBI, BufferedImage.TYPE_BYTE_INDEXED);
            pmi = "PALETTE COLOR";
        }

        /*
         File dest = new File(ds.getString(Tags.SOPInstanceUID) + ".JPG");
         OutputStream out = new BufferedOutputStream(new FileOutputStream(
         dest));
         try {
         JPEGImageEncoder enc = JPEGCodec.createJPEGEncoder(out);
         enc.encode(bi);
         } finally {
         out.close();
         }
         */

        if (iconPixelData == null || iconPixelData.length != w * h)
                iconPixelData = new byte[w * h];
        Dataset iconItem = dof.newDataset();

        if ("PALETTE COLOR".equals(pmi)) {
            IndexColorModel cm = (IndexColorModel) bi.getColorModel();
            int[] lutDesc = { cm.getMapSize(), 0, 8};
            byte[] r = new byte[lutDesc[0]];
            byte[] g = new byte[lutDesc[0]];
            byte[] b = new byte[lutDesc[0]];
            cm.getReds(r);
            cm.getGreens(g);
            cm.getBlues(b);
            iconItem.putUS(Tags.RedPaletteColorLUTDescriptor, lutDesc);
            iconItem.putUS(Tags.GreenPaletteColorLUTDescriptor, lutDesc);
            iconItem.putUS(Tags.BluePaletteColorLUTDescriptor, lutDesc);
            iconItem.putOW(Tags.RedPaletteColorLUTData, ByteBuffer.wrap(r)
                    .order(ByteOrder.LITTLE_ENDIAN));
            iconItem.putOW(Tags.GreenPaletteColorLUTData, ByteBuffer.wrap(g)
                    .order(ByteOrder.LITTLE_ENDIAN));
            iconItem.putOW(Tags.BluePaletteColorLUTData, ByteBuffer.wrap(b)
                    .order(ByteOrder.LITTLE_ENDIAN));

            Raster raster = bi.getRaster();
            for (int y = 0, i = 0; y < h; ++y)
                for (int x = 0; x < w; ++x, ++i)
                    iconPixelData[i] = (byte) raster.getSample(x, y, 0);
        } else {
            pmi = "MONOCHROME2";
            for (int y = 0, i = 0; y < h; ++y)
                for (int x = 0; x < w; ++x, ++i)
                    iconPixelData[i] = (byte) bi.getRGB(x, y);
        }
        iconItem.putCS(Tags.PhotometricInterpretation, pmi);
        iconItem.putUS(Tags.Rows, h);
        iconItem.putUS(Tags.Columns, w);
        iconItem.putUS(Tags.SamplesPerPixel, 1);
        iconItem.putUS(Tags.BitsAllocated, 8);
        iconItem.putUS(Tags.BitsStored, 8);
        iconItem.putUS(Tags.HighBit, 7);
        iconItem.putOB(Tags.PixelData, iconPixelData);
        return iconItem;
    }

    private BufferedImage checkReusable(BufferedImage bi, int w, int h)
            throws IOException {
        if (bi == null || bi.getWidth() != w || bi.getHeight() != h)
                return null;
        ImageTypeSpecifier t1 = reader.getRawImageType(0);
        ImageTypeSpecifier t2 = ImageTypeSpecifier.createFromRenderedImage(bi);
        if (!t1.equals(t2)) return null;
        if (debug) log.debug("Reuse BufferedImage[w=" + w + ",h=" + h + "]");
        return bi;
    }

    private File mkRootDir(SpoolDirDelegate spoolDir, boolean newuid)
            throws IOException {
        String uid = newuid ? null : attrs
                .getString(Tags.StorageMediaFileSetUID);
        if (uid == null) uid = uidgen.createUID();

        File d;
        while ((d = spoolDir.getMediaFilesetRootDir(uid)).exists()) {
            log.warn("Duplicate file set UID:" + uid + " - generate new uid");
            uid = uidgen.createUID();
        }
        if (!d.mkdir()) throw new IOException("Failed to mkdir " + d);
        return d;
    }

    public ArrayList splitMedia(long freeSizeFirst, long freeSizeOther,
            DicomDirDOM dom) throws MediaCreationException, IOException {
        File ddFile = rq.getDicomDirFile();
        ArrayList fsList = new ArrayList();
        split(fsRoot, freeSizeFirst, freeSizeOther, fsList);
        rq.setVolsetSize(fsList.size());
        String fsIDPrefix = getFilesetIDPrefix();
        File oldDDFile = new File(rq.getFilesetDir(), "DICOMDIR.old");
        ddFile.renameTo(oldDDFile);
        DirReader dirReader = dbf.newDirReader(oldDDFile);
        ArrayList rqList = new ArrayList();
        try {
            for (int i = 0, n = fsList.size(); i < n; ++i) {
                FilesetComponent comp = (FilesetComponent) fsList.get(i);
                File rootDir = rq.getFilesetDir();
                MediaCreationRequest newrq = rq;
                if (i > 0) {
                    rootDir = mkRootDir(spoolDir, true);
                    moveComponents(comp.childs(), rootDir);
                    newrq = new MediaCreationRequest(rq);
                    newrq.setFilesetDir(rootDir);
                    newrq.setVolsetSeqno(i + 1);
                    if (dom != null)
                        setVolsetSeqno(comp.childs(), i + 1, dom);
                }
                rqList.add(newrq);
                if (fsIDPrefix != null)
                        newrq.setFilesetID(fsIDPrefix + (i + 1));
                File newReadmeFile = new File(rootDir, service
                        .getFileSetDescriptorFile());
                DirWriter dirWriter = dbf.newDirWriter(newrq.getDicomDirFile(),
                        rootDir.getName(),
                        newrq.getFilesetID(),
                        newReadmeFile,
                        service.getCharsetOfFileSetDescriptorFile(),
                        null);
                try {
                    copyPatientDirRecords(comp.root().childs(),
                            dirWriter,
                            dirReader);
                } finally {
                    try {
                        dirWriter.close();
                    } catch (Exception ignore) {
                    }
                    spoolDir.register(newrq.getDicomDirFile());
                }
            }
        } finally {
            dirReader.close();
            spoolDir.delete(oldDDFile);
        }
        return rqList;
    }

    private void setVolsetSeqno(List comps, int seqNo, DicomDirDOM dom) {
        for (int i = 0, n = comps.size(); i < n; ++i) {
            FilesetComponent comp = (FilesetComponent) comps.get(i);
            switch (comp.level()) {
            case FilesetComponent.PATIENT:
                dom.setPatientSeqNo(comp.id(), seqNo);
                break;
            case FilesetComponent.STUDY:
                dom.setStudySeqNo(comp.parent().id(), comp.id(), seqNo);
                break;
            case FilesetComponent.SERIES:
                dom.setSeriesSeqNo(comp.parent().parent().id(), comp.parent()
                        .id(), comp.id(), seqNo);
                break;
            case FilesetComponent.INSTANCE:
                dom.setInstanceSeqNo(comp.parent().parent().parent().id(),
                        comp.parent().parent().id(),
                        comp.parent().id(),
                        comp.id(),
                        seqNo);
                break;
            }
        }
    }

    private void split(FilesetComponent src, long freeSizeFirst,
            long freeSizeOther, ArrayList fsList) throws MediaCreationException {
        if (debug) log.debug("split " + src);
        List childs = src.childs();
        while (!childs.isEmpty()) {
            FilesetComponent comp = src
                    .takeChilds(fsList.isEmpty() ? freeSizeFirst
                            : freeSizeOther);
            if (comp.isEmpty()) {
                if (src.level() == FilesetComponent.SERIES)
                        throw new MediaCreationException(
                                ExecutionStatusInfo.INST_OVERSIZED, "Instance "
                                        + ((FilesetComponent) childs.get(0))
                                                .id()
                                        + " does not fit on media");
                break;
            }
            fsList.add(comp);
            if (debug)
                    log.debug(" into " + comp + " on Media #" + fsList.size());
        }
        for (int i = 0, n = childs.size(); i < n; ++i)
            split((FilesetComponent) childs.get(i),
                    freeSizeFirst,
                    freeSizeOther,
                    fsList);
    }

    private String getFilesetIDPrefix() {
        if (rq.getFilesetID().length() == 0) return null;
        String prefix = rq.getFilesetID() + '_';
        int maxSuffixLen = String.valueOf(rq.getVolsetSize()).length();
        return prefix
                .substring(0, Math.min(prefix.length(), 16 - maxSuffixLen));
    }

    private void moveComponents(List comps, File newRootDir) throws IOException {
        for (int i = 0, n = comps.size(); i < n; ++i) {
            FilesetComponent comp = (FilesetComponent) comps.get(i);
            moveComponent(comp.getFilePath(), newRootDir);
        }
    }

    private void moveComponent(String filepath, File newRootDir) throws IOException {
        File src = new File(rq.getFilesetDir(), filepath);
        if (!src.exists()) return;
        File dest = new File(newRootDir, filepath);
        mkParentDir(dest);
        src.renameTo(dest);
        // purge empty directories
        File dir = src.getParentFile();
        while (dir.delete()) dir = src.getParentFile();
    }

    private boolean mkParentDir(File dest) throws IOException {
        File parent = dest.getParentFile();
        if (parent.exists()) return false;
        if (!parent.mkdirs())
                throw new IOException("Failed to mkdirs " + parent);
        return true;
    }

    private void copyPatientDirRecords(List pats, DirWriter dirWriter,
            DirReader dirReader) throws IOException {
        for (int i = 0, n = pats.size(); i < n; ++i) {
            FilesetComponent pat = (FilesetComponent) pats.get(i);
            recFilter.clear();
            recFilter.putLO(Tags.PatientID, pat.id());
            DirRecord srcPatRec = dirReader.getFirstRecordBy(null,
                    recFilter,
                    false);
            DirRecord dstPatRec = dirWriter.add(null,
                    srcPatRec.getType(),
                    srcPatRec.getDataset());
            copyStudyDirRecords(pat.childs(), dirWriter, srcPatRec, dstPatRec);
        }
    }

    private void copyStudyDirRecords(List stys, DirWriter dirWriter,
            DirRecord srcPatRec, DirRecord dstPatRec) throws IOException {
        for (int i = 0, n = stys.size(); i < n; ++i) {
            FilesetComponent sty = (FilesetComponent) stys.get(i);
            recFilter.clear();
            recFilter.putUI(Tags.StudyInstanceUID, sty.id());
            DirRecord srcRec = srcPatRec
                    .getFirstChildBy(null, recFilter, false);
            DirRecord dstRec = dirWriter.add(dstPatRec,
                    srcRec.getType(),
                    srcRec.getDataset());
            copySeriesDirRecords(sty.childs(), dirWriter, srcRec, dstRec);
        }
    }

    private void copySeriesDirRecords(List sers, DirWriter dirWriter,
            DirRecord srcStyRec, DirRecord dstStyRec) throws IOException {
        for (int i = 0, n = sers.size(); i < n; ++i) {
            FilesetComponent ser = (FilesetComponent) sers.get(i);
            recFilter.clear();
            recFilter.putUI(Tags.SeriesInstanceUID, ser.id());
            DirRecord srcRec = srcStyRec
                    .getFirstChildBy(null, recFilter, false);
            DirRecord dstRec = dirWriter.add(dstStyRec,
                    srcRec.getType(),
                    srcRec.getDataset());
            copyInstanceDirRecords(ser.childs(), dirWriter, srcRec, dstRec);
        }
    }

    private void copyInstanceDirRecords(List insts, DirWriter dirWriter,
            DirRecord srcSerRec, DirRecord dstSerRec) throws IOException {
        for (int i = 0, n = insts.size(); i < n; ++i) {
            FilesetComponent inst = (FilesetComponent) insts.get(i);
            recFilter.clear();
            recFilter.putUI(Tags.SOPInstanceUID, inst.id());
            DirRecord srcRec = srcSerRec
                    .getFirstChildBy(null, recFilter, false);
            Dataset ds = srcRec.getDataset();
            DirRecord dstRec = dirWriter.add(dstSerRec,
                    srcRec.getType(),
                    ds,
                    ds.getStrings(Tags.RefFileID),
                    ds.getString(Tags.RefSOPClassUIDInFile),
                    ds.getString(Tags.RefSOPInstanceUIDInFile),
                    ds.getString(Tags.RefSOPTransferSyntaxUIDInFile));
        }
    }

    void createMd5Sums(MediaCreationRequest rq) throws MediaCreationException {
        if (!md5sums) return;
        try {
            char[] cbuf = new char[32];
            MessageDigest digest = MessageDigest.getInstance("MD5");
            File rootDir = rq.getFilesetDir();
            String[] subDirs = rootDir.list();
            File md5sums = new File(rootDir, MD5_SUMS);
            int strip = rootDir.toURI().toString().length();
            log.info("Start Creating MD5 sums for " + rq);
            Writer out = new BufferedWriter(new FileWriter(md5sums));
            try {
                for (int i = 0; i < subDirs.length; i++) {
                    writeMd5Sums(out,
                            new File(rootDir, subDirs[i]),
                            strip,
                            digest,
                            cbuf);
                }
            } finally {
                try {
                    out.close();
                } catch (Exception ignore) {
                }
                spoolDir.register(md5sums);
            }
        } catch (Exception e) {
            throw new MediaCreationException(ExecutionStatusInfo.PROC_FAILURE,
                    e);
        }
        log.info("Finished Creating MD5 sums for " + rq);
    }

    private void writeMd5Sums(Writer out, File fileOrDir, int strip,
            MessageDigest digest, char[] cbuf) throws IOException {
        if (fileOrDir.isDirectory()) {
            String[] files = fileOrDir.list();
            for (int i = 0; i < files.length; i++) {
                String f = files[i];
                writeMd5Sums(out, new File(fileOrDir, f), strip, digest, cbuf);
            }
        } else {
            String fname = fileOrDir.getName();
            if (fname.endsWith(EXT_MD5)) return;
            File md5file = new File(fileOrDir.getParent(), fname + EXT_MD5);
            if (md5file.exists()) {
                Reader in = new FileReader(md5file);
                try {
                    in.read(cbuf);
                } finally {
                    in.close();
                }
                spoolDir.delete(md5file);
            } else {
                MD5Utils.md5sum(fileOrDir, cbuf, digest, bbuf);
            }
            out.write(cbuf);
            out.write(' ');
            out.write(' ');
            String uri = fileOrDir.toURI().toString();
            out.write(uri, strip, uri.length() - strip);
            out.write('\r');
            out.write('\n');
        }

    }

}


text:
package spawn

import (
	"encoding/gob"
	"fmt"
	"os"
	"os/exec"
)

// The childProcess struct combines several objects used to handle a spawned
// child process.
type childProcess struct {
	*actor       // input/output pipe of child process.
	*exec.Cmd    // command to start/stop process.
	*gob.Encoder // encoder to write on the child's input pipe.
	*gob.Decoder // decoder to read from the child's output pipe.
}

// newChildProcess creates a new child process, but doesn't start it yet.
func newChildProcess() *childProcess {
	act := newActor()
	cmd := exec.Command(os.Args[0])

	// Show the output of our child processes on the dispatcher's terminal.
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

	// To make a long story short: Go's multithreaded nature forbids using
	// plain fork. So we have to use fork + exec instead. This starts
	// a completely new process. We use an envirnment variable to tell this
	// process that it is a child, not a dispatcher. To allow communication,
	// we pass the already created pipes as ExtraFiles to the new process.
	// The child process inherits these ExtraFiles as already open files.
	cmd.Env = os.Environ()
	cmd.Env = append(cmd.Env, "SPAWN_WORKER=yes")

	// Child receives the same command-line arguments as the dispatcher.
	cmd.Args = os.Args

	// Child inherites these file descriptors as already opened files.
	cmd.ExtraFiles = make([]*os.File, 0, 8)
	cmd.ExtraFiles = append(cmd.ExtraFiles, self.getFiles()...)
	cmd.ExtraFiles = append(cmd.ExtraFiles, act.getFiles()...)

	// Encoder is used to send tasks to child processes.
	// Decoder is used to receive finished tasks from child processes.
	enc := gob.NewEncoder(act.input.writeEnd)
	dec := gob.NewDecoder(act.output.readEnd)

	return &childProcess{act, cmd, enc, dec}
}

// Closes pipes and kill process.
func (p *childProcess) kill() {
	p.actor.close()
	p.Process.Kill()
}

func runDispatcher(n int) {
	pool := make(map[int]*childProcess)
	for i := 0; i < n; i++ {
		proc := newChildProcess()
		proc.Start()
		pool[proc.Process.Pid] = proc
	}

	// tasksSent: number of tasks sent to our childs
	// tasksDone: number of finished tasks returned from our childs
	tasksSent := 0
	tasksDone := 0

	// Idle channel contains the pids of idle child processes.
	Idle := make(chan int, n)

	// Goroutine which reads pids from the process' input pipe.
	// Whenever a child process finishes a task, it writes its pid to our
	// input pipe and the processed task to its own output pipe. We read the
	// pids here, lookup the corresponding child process and read the processed
	// task from the child process' output pipe.
	go func() {
		var pid int

		dec := gob.NewDecoder(self.input.readEnd)
		for {
			err := dec.Decode(&pid)
			if err != nil {
				fmt.Println(err)
				break
			}

			// If our process pool doesn't contain the pid we just read,
			// something went terribly wrong.
			proc, ok := pool[pid]
			if !ok {
				panic("Received unkown Pid.")
			}

			proc.Decoder.DecodeValue(taskVal)
			Result <- taskVal.Interface()
			Idle <- pid
			tasksDone++
		}
		close(Idle)
	}()

	// Goroutine dispatch() sends tasks over the Task channel. We distribute
	// them among our child processes.
	go dispatch()

	// Goroutine which receives tasks from dispatch() and distributes each
	// task to an idle child process. For every received task it waits till it
	// receives a pid on the Idle channel and sends the task to the
	// corresponding child process. After distributing all tasks, it waits
	// for all results and finally kills the child processes.
	go func() {
		for task := range Task {
			pid := <-Idle

			// The pids we receive from Idle should always exist in our
			// process pool
			pool[pid].Encode(task)
			tasksSent++
		}

		// We distributed all tasks. Now we wait until we received all results.
		for tasksDone < tasksSent {
			<-Idle
		}

		// Workers don't terminate on their own. They just block on a read, so
		// we have to kill them now.
		for _, proc := range pool {
			proc.kill()
		}
		close(Result)
	}()

	// Ready, set, go! Start distributing tasks.
	for pid := range pool {
		Idle <- pid
	}
}

redpajama_set_name: RedPajamaGithub


text:
//
//
using System;
using RestSharp;
using RestSharp.Authenticators;
using System.Collections.Generic;
using Newtonsoft.Json;

using System.Text.RegularExpressions;

namespace org.restcomm.connect.sdk.dotnet
{//
    public partial class Account
    {

        public NumberFilter SearchPhoneNumbers(string IsoCountryCode)
        {

            RestClient client = new RestClient(baseurl + "Accounts/" + Properties.sid + "/AvailablePhoneNumbers/" + IsoCountryCode + "/Local.json");

            client.Authenticator = new HttpBasicAuthenticator(Properties.sid, Properties.auth_token);
            RestRequest req = new RestRequest(Method.GET);//cant figure out correct method for it . get and post wont work
            return new NumberFilter(client, req);

        }

    }
    public class NumberFilter
    {
        private RestClient Client;
        private RestRequest Request;

        public NumberFilter(RestClient client, RestRequest request)
        {
            Client = client;
            Request = request;
        }
        public void AddSearchParameter(string ParameterName, string ParameterValue)
        {
            Request.AddQueryParameter(ParameterName, ParameterValue);
        }

        public List<PhoneNumber> Search()
        {

            IRestResponse res = Client.Execute(Request);

            var content = res.Content;

            content = Regex.Replace(content, @"[^\u0000-\u007F]+", string.Empty);

          var  Propertieslist = JsonConvert.DeserializeObject<List<numberProperties>>(content);

            List<PhoneNumber> phonenumberlist = new List<PhoneNumber>();
                foreach(numberProperties property in Propertieslist)
            {
                phonenumberlist.Add(new PhoneNumber(property));
            }
            return phonenumberlist;

        }

    }
    public class PhoneNumber
    {

        public numberProperties Properties;

        public PhoneNumber(numberProperties properties)
        {
            Properties = properties;
        }

    }
}


text:
'''The endpoints server.'''
__author__ = 'Sebastian Boyd', 'Alexander Otavka'
__copyright__ = 'Copyright (C) 2015 DHS Developers Club'

import datetime
import urllib, urllib2, cookielib, sys, re
import hashlib, hmac

import endpoints
from protorpc import message_types, remote
from google.appengine.api import urlfetch

#from libs.endpoints_proto_datastore.ndb import EndpointsModel

from bs4 import BeautifulSoup

import models
from messages import (LoginHAC, ClassesHAC, AssigmentHAC, ClassHAC, GradeHAC)

WEB_CLIENT_ID = '981058069504-rjcfv5tc2msk8qvmu42uedqetforee0t.apps.googleusercontent.com'
ANDROID_CLIENT_ID = ''
IOS_CLIENT_ID = ''
ANDROID_AUDIENCE = ANDROID_CLIENT_ID

def verify_email(api_key, token, timestamp, signature):
    return signature == hmac.new(
                             key=api_key,
                             msg='{}{}'.format(timestamp, token),
                             digestmod=hashlib.sha256).hexdigest()

def get_grades(username, password):
    cj = cookielib.CookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
    database = '10'
    login_data = urllib.urlencode({'Database' : database, 'LogOnDetails.UserName' : username, 'LogOnDetails.Password' : password})
    opener.open('https://home.tamdistrict.org/HomeAccess/Account/LogOn', login_data, 15)
    if [cookie for cookie in cj if cookie.name == ".AuthCookie"] == []:
        login_status = ClassesHAC.LoginStatus.LOGIN_ERROR
    else:
        login_status = ClassesHAC.LoginStatus.OK
    resp = opener.open('https://home.tamdistrict.org/HomeAccess/Content/Student/Assignments.aspx', None, 15)
    html = resp.read()
    html = html.decode('utf8', 'ignore')
    soup = BeautifulSoup(html)
    charts = soup.find_all('table')
    classes_list = []
    for classroom_soup in soup.find_all("div", { "class" : "AssignmentClass"}):
        class_title = classroom_soup.find_all("div", class_="sg-header sg-header-square")[0].find_all("a")[0].string.strip()
        assignment_list = []
        try:
            for tr in classroom_soup.find("table", class_="sg-asp-table").find_all("tr", class_="sg-asp-table-data-row"):
                td = tr.find_all("td")
                due = td[0].string
                assigned = td[1].string
                assigment_title = td[2].find_all("a")[0].string.strip()
                assignment_category = td[3].string.strip()
                score_my = td[4].string.strip()
                score_total = td[5].string.strip()
                assignment = AssigmentHAC(title=assigment_title, category=assignment_category,
                                                date_assigned=assigned, date_due=due,
                                                score=score_my, max_score=score_total)
                assignment_list.append(assignment)
        except:
            continue
        grade_list = []
        for tr in classroom_soup.find("div", class_="sg-view-quick sg-clearfix").find("table", class_="sg-asp-table").find_all("tr", class_="sg-asp-table-data-row"):
            td = tr.find_all("td")
            length = len(td)
            grade_items_docs = ["grade_category", "points", "max_points", "percent", "weight", "weighted_points"]
            grade_items = []
            for t in td:
                grade_items.append(t.string.strip())
            while len(grade_items) < 6:
                grade_items.append('')
            grade = GradeHAC(category=grade_items[0], weight=grade_items[4], score=grade_items[1],
                            max_score=grade_items[2], percent=grade_items[3],
                            weighted_points=grade_items[5])
            grade_list.append(grade)
        grade_str = classroom_soup.find("span", id=re.compile("plnMain_rptAssigmnetsByCourse_lblOverallAverage_\d")).string
        p = re.compile(r'\(([^\)]+)\)')
        grade_percent = re.sub(r'\([^)]*\)', '', grade_str).strip()
        try:
            grade_letter = p.search(grade_str).group(1)
        except:
            grade_letter = ''
        print("done")
        classes_list.append(ClassHAC(assignments=assignment_list, title=class_title, grade_table=grade_list, grade_percent=grade_percent, grade_letter=grade_letter))
    response = {'classes': classes_list, "status": login_status}
    return response

def search_classrooms(query, classrooms):
    if query == None: query = ''
    if query == '': return False
    query_list = query.split()
    def match_count(classroom):
        queryed_properties = (classroom.title)
        match_count = 0
        for string in queryed_properties:
            for query in query_list:
                if query.lower() in string.lower():
                    match_count += 1
        return match_count

    # Sort the list of classrooms, then take best result
    sorted_classrooms = sorted((-match_count(c), c) for c in classrooms)
    if len(sorted_classrooms) == 0:
        return False
    else:
        classroom = sorted_classrooms[0]
    return classroom

def send_mail(sender, to, subject, text, html=None, campaign=None):
        api_key = 'REDACTED'
        url = 'https://api.mailgun.net/v3/sebastianboyd.com'
        deadline = 5
        payload = {}
        payload['from'] = sender
        payload['to'] = to
        payload['subject'] = subject
        payload['text'] = text
        if html:
            payload['html'] = html
        if campaign:
            payload['o:campaign'] = campaign
        encoded_payload = urllib.urlencode(payload)
        base64string = base64.encodestring('api:' + api_key).replace('\n', '')
        headers = {}
        headers['Authorization'] = "Basic %s" % base64string
        result = urlfetch.fetch(url, deadline=deadline, payload=encoded_payload, method=urlfetch.POST, headers=headers)
        return result

@endpoints.api(name='homeaccessclient', version='v1')
class HomeAccessClientApi(remote.Service):
    @endpoints.method(LoginHAC, ClassesHAC, name='login',
                      allowed_client_ids=[WEB_CLIENT_ID, endpoints.API_EXPLORER_CLIENT_ID])
    def login(self, request):
        response = get_grades(request.username, request.password)
        return ClassesHAC(classes=response["classes"], status=response["login_status"])

    # Text Message refers to text based communication; sms, email
    @endpoints.method(TextMessage, ClassesHAC, name='incomingtextrequest')
    def incomingtextrequest(self, request):
        mailgun_api_key = ''
        wit_token = 'WQPZ2RUGURGQSQKZNVLDPTGBISP7QZ35'
        if varify_email(api_key, request.token, request.imestamp, request.signature):
            return # Add failure code
        wit_request = urllib2.Request("https://api.wit.ai/message?v=20150731&q=" + request.stripped-text,
                                  headers={"Authorization": "Bearer " + wit_token})
        contents = json.loads(urllib2.urlopen(wit_request).read())
        query = contents["outcomes"][0]["entities"]["search_query"][0]["value"]
        grades = get_grades(username, password)
        if grades["status"] == ClassesHAC.LoginStatus.OK:
            classroom = search_classrooms(query, grades["classes"])
            if classroom:
                send_mail("<Grades> grades@txt.sebastianboyd.com", , )
application = endpoints.api_server([HomeAccessClientApi])


text:
import ApplicationSerializer from './application';

export default class <%= singular.className %>Serializer extends ApplicationSerializer {

  attributes = [];

  relationships = {};

}


text:
<?php
/**
 * @author Tiago Mazzarollo <tmazza@email.com>
 */

use PHPUnit\Framework\TestCase;
use Tarsius\Tarsius;

class TarsiusTest extends TestCase
{
    public function testConfig()
    {
        Tarsius::config([
            'threshold' => 140,
        ]);

        $this->assertEquals(140, Tarsius::$threshold);
    }
}


text:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:vh="http://vedaxml.com/soap/header/v-header-v1-9.xsd" xmlns:wsa="http://www.w3.org/2005/08/addressing" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <soapenv:Header>
      <wsa:MessageID>141029-V5S29-05MXN</wsa:MessageID>
      <wsa:RelatesTo>urn:example.com:123456789</wsa:RelatesTo>
      <wsa:To>http://www.w3.org/2005/08/addressing/anonymous</wsa:To>
      <wsa:From>
         <wsa:Address>https://ctaau.vedaxml.com:8443/cta/sys2/company-enquiry-v3-2</wsa:Address>
      </wsa:From>
      <wsa:Action>http://vedaxml.com/companyEnquiry/ServiceResult</wsa:Action>
   </soapenv:Header>
   <SOAP-ENV:Body xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
      <SOAP-ENV:Fault>
         <faultcode>SOAP-ENV:SERVER</faultcode>
         <faultstring>System Error</faultstring>
         <detail>
            <VEDA:error xmlns:VEDA="http://vedaxml.com/vxml2/veda-error-response-v1.0">
               <VEDA:code>030</VEDA:code>
               <VEDA:description>ASIC Org Extract Gateway Unavailable</VEDA:description>
            </VEDA:error>
         </detail>
      </SOAP-ENV:Fault>
   </SOAP-ENV:Body>
</soapenv:Envelope>


text:
PRIVATE_HEADER
--------------

Specify private header files in a FRAMEWORK shared library target.

Shared library targets marked with the FRAMEWORK property generate
frameworks on OS X and normal shared libraries on other platforms.
This property may be set to a list of header files to be placed in the
PrivateHeaders directory inside the framework folder.  On non-Apple
platforms these headers may be installed using the PRIVATE_HEADER
option to the install(TARGETS) command.


text:
package org.killbill.billing.plugin.analytics.dao.model;

import java.util.UUID;

import javax.annotation.Nullable;

import org.killbill.billing.account.api.Account;
import org.killbill.billing.util.audit.AuditLog;
import org.killbill.billing.util.tag.Tag;
import org.killbill.billing.util.tag.TagDefinition;

public class BusinessInvoiceTagModelDao extends BusinessTagModelDao {

    private UUID invoiceId;

    public BusinessInvoiceTagModelDao() { /* When reading from the database */ }

    public BusinessInvoiceTagModelDao(final Account account,
                                      final Long accountRecordId,
                                      final Tag tag,
                                      final Long tagRecordId,
                                      final TagDefinition tagDefinition,
                                      @Nullable final AuditLog creationAuditLog,
                                      final Long tenantRecordId,
                                      @Nullable final ReportGroup reportGroup) {
        super(account,
              accountRecordId,
              tag,
              tagRecordId,
              tagDefinition,
              creationAuditLog,
              tenantRecordId,
              reportGroup);
        this.invoiceId = tag.getObjectId();
    }

    @Override
    public String getTableName() {
        return INVOICE_TAGS_TABLE_NAME;
    }

    public UUID getInvoiceId() {
        return invoiceId;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder();
        sb.append("BusinessInvoiceTagModelDao");
        sb.append("{invoiceId=").append(invoiceId);
        sb.append('}');
        return sb.toString();
    }

    @Override
    public boolean equals(final Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        if (!super.equals(o)) {
            return false;
        }

        final BusinessInvoiceTagModelDao that = (BusinessInvoiceTagModelDao) o;

        if (invoiceId != null ? !invoiceId.equals(that.invoiceId) : that.invoiceId != null) {
            return false;
        }

        return true;
    }

    @Override
    public int hashCode() {
        int result = super.hashCode();
        result = 31 * result + (invoiceId != null ? invoiceId.hashCode() : 0);
        return result;
    }
}


text:
<!DOCTYPE html>
<meta charset="utf-8">
<title>CSS Flexbox Test: flex-grow - positive number(fill all space)</title>
<link rel="author" title="Intel" href="http://www.intel.com">
<link rel="author" title="Shiyou Tan" href="mailto:shiyoux.tan@intel.com">
<link rel="help" title="7.3.1. The 'flex-grow' property" href="http://www.w3.org/TR/css-flexbox-1/#propdef-flex-grow">
<link rel="match" href="../reference/ref-filled-green-100px-square.xht">
<meta name="flags" content="">
<meta name="assert" content="Test checks that all space of flex container will be filled when there is only one flex item and 'flex-grow' set any positive number.">

Test passes if there is a filled green square and no red.


text:
"""Support for Abode Security System binary sensors."""
from typing import cast

from abodepy.devices.binary_sensor import AbodeBinarySensor as ABBinarySensor
import abodepy.helpers.constants as CONST

from homeassistant.components.binary_sensor import (
    BinarySensorDeviceClass,
    BinarySensorEntity,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback

from . import AbodeDevice, AbodeSystem
from .const import DOMAIN

async def async_setup_entry(
    hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None:
    """Set up Abode binary sensor devices."""
    data: AbodeSystem = hass.data[DOMAIN]

    device_types = [
        CONST.TYPE_CONNECTIVITY,
        CONST.TYPE_MOISTURE,
        CONST.TYPE_MOTION,
        CONST.TYPE_OCCUPANCY,
        CONST.TYPE_OPENING,
    ]

    async_add_entities(
        AbodeBinarySensor(data, device)
        for device in data.abode.get_devices(generic_type=device_types)
    )

class AbodeBinarySensor(AbodeDevice, BinarySensorEntity):
    """A binary sensor implementation for Abode device."""

    _device: ABBinarySensor

    @property
    def is_on(self) -> bool:
        """Return True if the binary sensor is on."""
        return cast(bool, self._device.is_on)

    @property
    def device_class(self) -> str:
        """Return the class of the binary sensor."""
        if self._device.get_value("is_window") == "1":
            return BinarySensorDeviceClass.WINDOW
        return cast(str, self._device.generic_type)


text:
#include <pcl/gpu/kinfu/color_volume.h>
#include <pcl/gpu/kinfu/tsdf_volume.h>
#include "internal.h"
#include <algorithm>
#include <Eigen/Core>

using namespace pcl;
using namespace pcl::gpu;
using namespace Eigen;
using pcl::device::device_cast;

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

pcl::gpu::ColorVolume::ColorVolume(const TsdfVolume& tsdf, int max_weight) : resolution_(tsdf.getResolution()), volume_size_(tsdf.getSize()), max_weight_(1)
{
  max_weight_ = max_weight < 0 ? max_weight_ : max_weight;
  max_weight_ = max_weight_ > 255 ? 255 : max_weight_;

  int volume_x = resolution_(0);
  int volume_y = resolution_(1);
  int volume_z = resolution_(2);

  color_volume_.create (volume_y * volume_z, volume_x);
  reset();
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

pcl::gpu::ColorVolume::~ColorVolume()
{

}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void
pcl::gpu::ColorVolume::reset()
{
  device::initColorVolume(color_volume_);
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

int
pcl::gpu::ColorVolume::getMaxWeight() const
{
  return max_weight_;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

DeviceArray2D<int>
pcl::gpu::ColorVolume::data() const
{
  return color_volume_;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::gpu::ColorVolume::fetchColors (const DeviceArray<PointType>& cloud, DeviceArray<RGB>& colors) const
{
  colors.create(cloud.size());
  device::exctractColors(color_volume_, device_cast<const float3> (volume_size_), cloud, (uchar4*)colors.ptr()/*bgra*/);
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////


text:
<?php
$this->breadcrumbs=array(
	'Search'=>array('search'),
	'Results',
);
?>

Search results

<?php $this->widget('bootstrap.widgets.TbListView',array(
	'dataProvider'=>$dataProvider,
	'itemView'=>'_view',
)); ?>


text:
#pragma once
#include <aws/sdb/SimpleDB_EXPORTS.h>
#include <aws/sdb/SimpleDBRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/sdb/model/DeletableItem.h>

namespace Aws
{
namespace SimpleDB
{
namespace Model
{

  /**
   */
  class AWS_SIMPLEDB_API BatchDeleteAttributesRequest : public SimpleDBRequest
  {
  public:
    BatchDeleteAttributesRequest();
    Aws::String SerializePayload() const override;

    /**
     * The name of the domain in which the attributes are being deleted.
     */
    inline const Aws::String& GetDomainName() const{ return m_domainName; }

    /**
     * The name of the domain in which the attributes are being deleted.
     */
    inline void SetDomainName(const Aws::String& value) { m_domainNameHasBeenSet = true; m_domainName = value; }

    /**
     * The name of the domain in which the attributes are being deleted.
     */
    inline void SetDomainName(Aws::String&& value) { m_domainNameHasBeenSet = true; m_domainName = value; }

    /**
     * The name of the domain in which the attributes are being deleted.
     */
    inline void SetDomainName(const char* value) { m_domainNameHasBeenSet = true; m_domainName.assign(value); }

    /**
     * The name of the domain in which the attributes are being deleted.
     */
    inline BatchDeleteAttributesRequest& WithDomainName(const Aws::String& value) { SetDomainName(value); return *this;}

    /**
     * The name of the domain in which the attributes are being deleted.
     */
    inline BatchDeleteAttributesRequest& WithDomainName(Aws::String&& value) { SetDomainName(value); return *this;}

    /**
     * The name of the domain in which the attributes are being deleted.
     */
    inline BatchDeleteAttributesRequest& WithDomainName(const char* value) { SetDomainName(value); return *this;}

    /**
     * A list of items on which to perform the operation.
     */
    inline const Aws::Vector<DeletableItem>& GetItems() const{ return m_items; }

    /**
     * A list of items on which to perform the operation.
     */
    inline void SetItems(const Aws::Vector<DeletableItem>& value) { m_itemsHasBeenSet = true; m_items = value; }

    /**
     * A list of items on which to perform the operation.
     */
    inline void SetItems(Aws::Vector<DeletableItem>&& value) { m_itemsHasBeenSet = true; m_items = value; }

    /**
     * A list of items on which to perform the operation.
     */
    inline BatchDeleteAttributesRequest& WithItems(const Aws::Vector<DeletableItem>& value) { SetItems(value); return *this;}

    /**
     * A list of items on which to perform the operation.
     */
    inline BatchDeleteAttributesRequest& WithItems(Aws::Vector<DeletableItem>&& value) { SetItems(value); return *this;}

    /**
     * A list of items on which to perform the operation.
     */
    inline BatchDeleteAttributesRequest& AddItems(const DeletableItem& value) { m_itemsHasBeenSet = true; m_items.push_back(value); return *this; }

    /**
     * A list of items on which to perform the operation.
     */
    inline BatchDeleteAttributesRequest& AddItems(DeletableItem&& value) { m_itemsHasBeenSet = true; m_items.push_back(value); return *this; }

  private:
    Aws::String m_domainName;
    bool m_domainNameHasBeenSet;
    Aws::Vector<DeletableItem> m_items;
    bool m_itemsHasBeenSet;
  };

} // namespace Model
} // namespace SimpleDB
} // namespace Aws


text:
//************************************
// Begin defining a new symbol
//************************************
(function (CS) {
	'use strict';
	// Specify the symbol definition
	var myCustomSymbolDefinition = {
		// Specify the unique name for this symbol; this instructs PI Vision to also
		// look for HTML template and configuration template files called sym-<typeName>-template.html and sym-<typeName>-config.html
		typeName: 'HTML5video',
		// Specify the user-friendly name of the symbol that will appear in PI Vision
		displayName: 'HTML5 video',
		// Specify the number of data sources for this symbol
		datasourceBehavior: CS.Extensibility.Enums.DatasourceBehaviors.Single,
		// Specify the location of an image file to use as the icon for this symbol
		iconUrl: '/Scripts/app/editor/symbols/ext/Icons/HTML5video.png',
		visObjectType: symbolVis,
		// Specify default configuration for this symbol
		getDefaultConfig: function () {
			return {
				// Specify the data shape type (for symbols that update with new data)
				DataShape: 'Value',
				// Specify the default height and width of this symbol
				Height: 300,
				Width: 600,
				// Specify the value of custom configuration options; see the "configure" section below
				videoSourcePath: "",
				showControls: true,
                enableAutoplay: false,
				enableLoop: true,
                enableRefresh: false,
				refreshIntervalSeconds: 60,
				useDataItemAsVideoSource: false
			};
		},
		// By including this, you're specifying that you want to allow configuration options for this symbol
        configOptions: function () {
            return [{
				// Add a title that will appear when the user right-clicks a symbol
				title: 'Format Symbol',
				// Supply a unique name for this configuration setting, so it can be reused, if needed
                mode: 'format'
            }];
        }
		// Specify the name of the function that will be called to initialize the symbol
		//init: myCustomSymbolInitFunction
	};

	//************************************
	// Function called to initialize the symbol
	//************************************
	//function myCustomSymbolInitFunction(scope, elem) {
	function symbolVis() { }
    CS.deriveVisualizationFromBase(symbolVis);
	symbolVis.prototype.init = function (scope, elem) {
		// Specify which function to call when a data update or configuration change occurs
		this.onDataUpdate = myCustomDataUpdateFunction;
		this.onConfigChange = myCustomConfigurationChangeFunction;

		// Locate the div that will contain the symbol, using its id, which is "container" by default
		var symbolContainerElement = elem.find('#container')[0];
        // Use random functions to generate a new unique id for this symbol, to make it unique among all other custom symbols
		var newUniqueIDString = "myCustomSymbol_" + Math.random().toString(36).substr(2, 16);
		// Write that new unique ID back to overwrite the old id
        symbolContainerElement.id = newUniqueIDString;
		// Create a timer variable to be used for refreshes
		var myTimer;

        //************************************
		// When a data update occurs...
		//************************************
		function myCustomDataUpdateFunction(data) {
			// If there is indeed new data in the update
            //console.log("New data received: ", data);
			if (data !== null && data.Value) {
				// Check for an error
				if (data.ErrorDescription) {
					console.log(data.ErrorDescription);
				}
				// If the custom visualization hasn't been made yet... create the custom visualization!
				// Custom code begins here:
				// -----------------------------------------------------------------------------------------
				// Get the data item value
                if (data.Value) {
					scope.dataItemValue = data.Value;
				}
				// Use the data item as the source, or not
				if (scope.config.useDataItemAsVideoSource) {
					scope.config.videoSourcePath = scope.dataItemValue;
				}
			}

		}
		//************************************
		// Function that is called when custom configuration changes are made
		//************************************
        // Initialize a variable to hold the timer interval
        var OLDrefreshIntervalSeconds = scope.config.refreshIntervalSeconds;
		function myCustomConfigurationChangeFunction() {
			// Use the data item as the source, or not
			if (scope.config.useDataItemAsVideoSource) {
				scope.config.videoSourcePath = scope.dataItemValue;
			}
            // If a change is detected, update the path, controls setting, and auto-play setting
            if (symbolContainerElement.src !== scope.config.videoSourcePath) {
                symbolContainerElement.src = scope.config.videoSourcePath;
            }
            if (symbolContainerElement.controls !== scope.config.showControls) {
                symbolContainerElement.controls = scope.config.showControls;
            }
            if (symbolContainerElement.autoplay !== scope.config.enableAutoplay) {
                symbolContainerElement.autoplay = scope.config.enableAutoplay;
            }
            if (symbolContainerElement.loop !== scope.config.enableLoop) {
                symbolContainerElement.loop = scope.config.enableLoop;
            }
            // If the "enable refresh check-box
            if (!scope.config.enableRefresh) {
                window.clearTimeout(myTimer);
            } else {
                // In this case, the timer is enabled!
                // If a change is detected, update the refresh interval
                if (OLDrefreshIntervalSeconds !== scope.config.refreshIntervalSeconds) {
                    OLDrefreshIntervalSeconds = scope.config.refreshIntervalSeconds;
                    // Since the interval has changed, stop the timer, then start it
                    window.clearTimeout(myTimer);
                    startMyTimerIfEnabled();
                }
            }
		}

        //************************************
        // Function called by the timer to refresh the video feed
        //************************************
        function refreshVideoSource() {
            // Refresh the video source when the timer elapses, then restart the timer
            symbolContainerElement.src = "";
            symbolContainerElement.src = scope.config.videoSourcePath;
			startMyTimerIfEnabled();

        }

        //************************************
        // Function that starts the timer anew, only if it is currently enabled
        //************************************
		function startMyTimerIfEnabled() {
			// If enabled, start a new timer, using the specified  timer interval (only allow an interval over 0 seconds)
            if (scope.config.enableRefresh && scope.config.refreshIntervalSeconds > 0) {
                myTimer = setTimeout(refreshVideoSource, scope.config.refreshIntervalSeconds * 1000);
            }
		}

		// Specify which function to call when a data update or configuration change occurs
		//return { configChange: myCustomConfigurationChangeFunction };
	};
	// Register this custom symbol definition with PI Vision
	CS.symbolCatalog.register(myCustomSymbolDefinition);

})(window.PIVisualization);


text:
package org.apache.jackrabbit.core.query.lucene;

import org.apache.jackrabbit.core.SessionImpl;
import org.apache.jackrabbit.core.nodetype.NodeTypeImpl;
import org.apache.jackrabbit.core.query.PropertyTypeRegistry;
import org.apache.jackrabbit.core.session.SessionContext;
import org.apache.jackrabbit.spi.Name;
import org.apache.jackrabbit.spi.Path;
import org.apache.jackrabbit.spi.QPropertyDefinition;
import org.apache.jackrabbit.spi.commons.name.NameConstants;
import org.apache.jackrabbit.spi.commons.name.NameFactoryImpl;
import org.apache.jackrabbit.spi.commons.nodetype.PropertyDefinitionImpl;
import org.apache.jackrabbit.spi.commons.query.AndQueryNode;
import org.apache.jackrabbit.spi.commons.query.DefaultQueryNodeVisitor;
import org.apache.jackrabbit.spi.commons.query.LocationStepQueryNode;
import org.apache.jackrabbit.spi.commons.query.NodeTypeQueryNode;
import org.apache.jackrabbit.spi.commons.query.OrderQueryNode;
import org.apache.jackrabbit.spi.commons.query.QueryNodeFactory;
import org.apache.jackrabbit.spi.commons.query.QueryParser;
import org.apache.jackrabbit.spi.commons.query.QueryRootNode;
import org.apache.jackrabbit.spi.commons.query.qom.ColumnImpl;
import org.apache.lucene.search.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.jcr.RepositoryException;
import javax.jcr.Workspace;
import javax.jcr.nodetype.PropertyDefinition;
import javax.jcr.query.InvalidQueryException;
import javax.jcr.query.QueryResult;
import javax.jcr.query.qom.QueryObjectModelFactory;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Implements the {@link org.apache.jackrabbit.core.query.ExecutableQuery}
 * interface.
 */
public class QueryImpl extends AbstractQueryImpl {

    /**
     * The logger instance for this class
     */
    private static final Logger log = LoggerFactory.getLogger(QueryImpl.class);

    /**
     * The default selector name 's'.
     */
    public static final Name DEFAULT_SELECTOR_NAME = NameFactoryImpl.getInstance().create("", "s");

    /**
     * The root node of the query tree
     */
    protected final QueryRootNode root;

    /**
     * Creates a new query instance from a query string.
     *
     * @param sessionContext component context of the current session
     * @param index     the search index.
     * @param propReg   the property type registry.
     * @param statement the query statement.
     * @param language  the syntax of the query statement.
     * @param factory   the query node factory.
     * @throws InvalidQueryException if the query statement is invalid according
     *                               to the specified language.
     */
    public QueryImpl(
            SessionContext sessionContext, SearchIndex index,
            PropertyTypeRegistry propReg, String statement, String language,
            QueryNodeFactory factory) throws InvalidQueryException {
        super(sessionContext, index, propReg);
        // parse query according to language
        // build query tree using the passed factory
        this.root = QueryParser.parse(
                statement, language, sessionContext, factory);
    }

    /**
     * Executes this query and returns a {@link QueryResult}.
     *
     * @param offset the offset in the total result set
     * @param limit the maximum result size
     * @return a QueryResult
     * @throws RepositoryException if an error occurs
     */
    public QueryResult execute(long offset, long limit) throws RepositoryException {
        if (log.isDebugEnabled()) {
            log.debug("Executing query: \n" + root.dump());
        }

        // build lucene query
        Query query = LuceneQueryBuilder.createQuery(
                root, sessionContext.getSessionImpl(),
                index.getContext().getItemStateManager(),
                index.getNamespaceMappings(), index.getTextAnalyzer(),
                propReg, index.getSynonymProvider(),
                index.getIndexFormatVersion(),
                cache);

        OrderQueryNode orderNode = root.getOrderNode();

        OrderQueryNode.OrderSpec[] orderSpecs;
        if (orderNode != null) {
            orderSpecs = orderNode.getOrderSpecs();
        } else {
            orderSpecs = new OrderQueryNode.OrderSpec[0];
        }
        Path[] orderProperties = new Path[orderSpecs.length];
        boolean[] ascSpecs = new boolean[orderSpecs.length];
        String[] orderFuncs = new String[orderSpecs.length];
        for (int i = 0; i < orderSpecs.length; i++) {
            orderProperties[i] = orderSpecs[i].getPropertyPath();
            ascSpecs[i] = orderSpecs[i].isAscending();
            orderFuncs[i] = orderSpecs[i].getFunction();
        }

        return new SingleColumnQueryResult(
                index, sessionContext, this, query,
                new SpellSuggestion(index.getSpellChecker(), root),
                getColumns(), orderProperties, ascSpecs, orderFuncs,
                orderProperties.length == 0 && getRespectDocumentOrder(),
                offset, limit);
    }

    /**
     * Returns the columns for this query.
     *
     * @return array of columns.
     * @throws RepositoryException if an error occurs.
     */
    protected ColumnImpl[] getColumns() throws RepositoryException {
        SessionImpl session = sessionContext.getSessionImpl();
        QueryObjectModelFactory qomFactory =
            session.getWorkspace().getQueryManager().getQOMFactory();
        // get columns
        Map<Name, ColumnImpl> columns = new LinkedHashMap<Name, ColumnImpl>();
        for (Name name : root.getSelectProperties()) {
            String pn = sessionContext.getJCRName(name);
            ColumnImpl col = (ColumnImpl) qomFactory.column(
                    sessionContext.getJCRName(DEFAULT_SELECTOR_NAME), pn, pn);
            columns.put(name, col);
        }
        if (columns.size() == 0) {
            // use node type constraint
            LocationStepQueryNode[] steps = root.getLocationNode().getPathSteps();
            final Name[] ntName = new Name[1];
            steps[steps.length - 1].acceptOperands(new DefaultQueryNodeVisitor() {

                public Object visit(AndQueryNode node, Object data) throws RepositoryException {
                    return node.acceptOperands(this, data);
                }

                public Object visit(NodeTypeQueryNode node, Object data) {
                    ntName[0] = node.getValue();
                    return data;
                }
            }, null);
            if (ntName[0] == null) {
                ntName[0] = NameConstants.NT_BASE;
            }
            NodeTypeImpl nt = session.getNodeTypeManager().getNodeType(ntName[0]);
            PropertyDefinition[] propDefs = nt.getPropertyDefinitions();
            for (PropertyDefinition pd : propDefs) {
                QPropertyDefinition propDef = ((PropertyDefinitionImpl) pd).unwrap();
                if (!propDef.definesResidual() && !propDef.isMultiple()) {
                    columns.put(propDef.getName(), columnForName(propDef.getName()));
                }
            }
        }

        // add jcr:path and jcr:score if not selected already
        if (!columns.containsKey(NameConstants.JCR_PATH)) {
            columns.put(NameConstants.JCR_PATH, columnForName(NameConstants.JCR_PATH));
        }
        if (!columns.containsKey(NameConstants.JCR_SCORE)) {
            columns.put(NameConstants.JCR_SCORE, columnForName(NameConstants.JCR_SCORE));
        }

        return columns.values().toArray(new ColumnImpl[columns.size()]);
    }

    /**
     * Returns true if this query node needs items under
     * /jcr:system to be queried.
     *
     * @return true if this query node needs content under
     *         /jcr:system to be queried; false otherwise.
     */
    public boolean needsSystemTree() {
        return this.root.needsSystemTree();
    }

    /**
     * Returns a column for the given property name and the default selector
     * name.
     *
     * @param propertyName the name of the property as well as the column.
     * @return a column.
     * @throws RepositoryException if an error occurs while creating the column.
     */
    protected ColumnImpl columnForName(Name propertyName) throws RepositoryException {
        Workspace workspace = sessionContext.getSessionImpl().getWorkspace();
        QueryObjectModelFactory qomFactory =
            workspace.getQueryManager().getQOMFactory();
        String name = sessionContext.getJCRName(propertyName);
        return (ColumnImpl) qomFactory.column(
                sessionContext.getJCRName(DEFAULT_SELECTOR_NAME), name, name);
    }
}


text:
package proto

import (
	protoV2 "google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/runtime/protoiface"
)

// Size returns the size in bytes of the wire-format encoding of m.
func Size(m Message) int {
	if m == nil {
		return 0
	}
	mi := MessageV2(m)
	return protoV2.Size(mi)
}

// Marshal returns the wire-format encoding of m.
func Marshal(m Message) ([]byte, error) {
	b, err := marshalAppend(nil, m, false)
	if b == nil {
		b = zeroBytes
	}
	return b, err
}

var zeroBytes = make([]byte, 0, 0)

func marshalAppend(buf []byte, m Message, deterministic bool) ([]byte, error) {
	if m == nil {
		return nil, ErrNil
	}
	mi := MessageV2(m)
	nbuf, err := protoV2.MarshalOptions{
		Deterministic: deterministic,
		AllowPartial:  true,
	}.MarshalAppend(buf, mi)
	if err != nil {
		return buf, err
	}
	if len(buf) == len(nbuf) {
		if !mi.ProtoReflect().IsValid() {
			return buf, ErrNil
		}
	}
	return nbuf, checkRequiredNotSet(mi)
}

// Unmarshal parses a wire-format message in b and places the decoded results in m.
//
// Unmarshal resets m before starting to unmarshal, so any existing data in m is always
// removed. Use UnmarshalMerge to preserve and append to existing data.
func Unmarshal(b []byte, m Message) error {
	m.Reset()
	return UnmarshalMerge(b, m)
}

// UnmarshalMerge parses a wire-format message in b and places the decoded results in m.
func UnmarshalMerge(b []byte, m Message) error {
	mi := MessageV2(m)
	out, err := protoV2.UnmarshalOptions{
		AllowPartial: true,
		Merge:        true,
	}.UnmarshalState(protoiface.UnmarshalInput{
		Buf:     b,
		Message: mi.ProtoReflect(),
	})
	if err != nil {
		return err
	}
	if out.Flags&protoiface.UnmarshalInitialized > 0 {
		return nil
	}
	return checkRequiredNotSet(mi)
}


text:
'use strict';

function Game(console, players) {
    this.console = console;
    this.players = players;
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>WPILIB: BCGOptions_struct Struct Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css">
<link href="doxygen.css" rel="stylesheet" type="text/css">

Main Page

Related Pages

Classes

Files

Class List

Class Hierarchy

Class Members

BCGOptions_struct Struct Reference
#include <nivision.h>

List of all members.

Public Attributes

float 	brightness

float 	contrast

float 	gamma

Detailed Description

Definition at line 3285 of file nivision.h.

Member Data Documentation

          float BCGOptions_struct::brightness

Definition at line 3286 of file nivision.h.

          float BCGOptions_struct::contrast

Definition at line 3287 of file nivision.h.

          float BCGOptions_struct::gamma

Definition at line 3288 of file nivision.h.

The documentation for this struct was generated from the following file:

nivision.h

<address style="text-align: right;">Generated on Wed Feb 9 11:20:46 2011 for WPILIB by

 1.5.8 </address>


text:
#Requires -Version 3.0

<#
  Get-SPClientGroup.ps1

  Copyright (c) 2017 karamem0

  This software is released under the MIT License.
  https://github.com/karamem0/SPClient/blob/master/LICENSE
#>

function Get-SPClientGroup {

<#
.SYNOPSIS
  Gets one or more groups.
.DESCRIPTION
  The Get-SPClientGroup function lists all site groups or retrieves the specified site group.
  If not specified filterable parameter, returns site all groups.
  Otherwise, returns a group which matches the parameter.
.PARAMETER ClientContext
  Indicates the client context. If not specified, uses a default context.
.PARAMETER NoEnumerate
  If specified, suppresses enumeration in output.
.PARAMETER Identity
  Indicates the group ID.
.PARAMETER Name
  Indicates the group name.
.PARAMETER Retrieval
  Indicates the data retrieval expression.
.EXAMPLE
  Get-SPClientGroup
.EXAMPLE
  Get-SPClientGroup -Identity 7
.EXAMPLE
  Get-SPClientGroup -Name "Custom Group"
.EXAMPLE
  Get-SPClientGroup -Retrieval "Title"
.INPUTS
  None
.OUTPUTS
  Microsoft.SharePoint.Client.Group[]
.LINK
  https://github.com/karamem0/SPClient/blob/master/doc/Get-SPClientGroup.md
#>

    [CmdletBinding(DefaultParameterSetName = 'All')]
    param (
        [Parameter(Mandatory = $false)]
        [Microsoft.SharePoint.Client.ClientContext]
        $ClientContext = $SPClient.ClientContext,
        [Parameter(Mandatory = $false, ParameterSetName = 'All')]
        [switch]
        $NoEnumerate,
        [Parameter(Mandatory = $true, ParameterSetName = 'Identity')]
        [Alias('Id')]
        [int]
        $Identity,
        [Parameter(Mandatory = $true, ParameterSetName = 'Name')]
        [Alias('Title')]
        [string]
        $Name,
        [Parameter(Mandatory = $false)]
        [string]
        $Retrieval
    )

    process {
        if ($ClientContext -eq $null) {
            throw "Cannot bind argument to parameter 'ClientContext' because it is null."
        }
        $ClientObjectCollection = $ClientContext.Site.RootWeb.SiteGroups
        if ($PSCmdlet.ParameterSetName -eq 'All') {
            Invoke-ClientContextLoad `
                -ClientContext $ClientContext `
                -ClientObject $ClientObjectCollection `
                -Retrieval $Retrieval
            Write-Output $ClientObjectCollection -NoEnumerate:$NoEnumerate
        }
        if ($PSCmdlet.ParameterSetName -eq 'Identity') {
            $PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
                $ClientContext, `
                $ClientObjectCollection.Path, `
                'GetById', `
                [object[]]$Identity)
            $ClientObject = New-Object Microsoft.SharePoint.Client.Group($ClientContext, $PathMethod)
            Invoke-ClientContextLoad `
                -ClientContext $ClientContext `
                -ClientObject $ClientObject `
                -Retrieval $Retrieval
            Write-Output $ClientObject
            trap {
                throw 'The specified group could not be found.'
            }
        }
        if ($PSCmdlet.ParameterSetName -eq 'Name') {
            $PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
                $ClientContext, `
                $ClientObjectCollection.Path, `
                'GetByName', `
                [object[]]$Name)
            $ClientObject = New-Object Microsoft.SharePoint.Client.Group($ClientContext, $PathMethod)
            Invoke-ClientContextLoad `
                -ClientContext $ClientContext `
                -ClientObject $ClientObject `
                -Retrieval $Retrieval
            Write-Output $ClientObject
            trap {
                throw 'The specified group could not be found.'
            }
        }
    }

}


text:
import Ember from 'ember';
import config from './config/environment';

var Router = Ember.Router.extend({
  location: config.locationType
});

Router.map(function() {
  this.route('basics');
  this.route('examples', function() {
    this.route('step-one');
    this.route('step-two');
  });
  this.route('scenarios', function() {
    this.route('multiple-tethers');
    this.route('component-in-tether');
    this.route('nested-tethers');
  });
});

export default Router;


text:
import * as vscode from 'vscode';
import * as child_process from 'child_process';
import * as path from 'path';

function wait(ms: number): Promise<void> {
	return new Promise(r => setTimeout(r, ms));
}

export function activate(context: vscode.ExtensionContext): any {
	context.subscriptions.push(vscode.commands.registerCommand('vscode-notebook-tests.createNewNotebook', async () => {
		const workspacePath = vscode.workspace.workspaceFolders![0].uri.fsPath;
		const notebookPath = path.join(workspacePath, 'test.smoke-nb');
		child_process.execSync('echo \'\' > ' + notebookPath);
		await wait(500);
		await vscode.commands.executeCommand('vscode.open', vscode.Uri.file(notebookPath));
	}));

	context.subscriptions.push(vscode.workspace.registerNotebookContentProvider('notebookSmokeTest', {
		openNotebook: async (_resource: vscode.Uri) => {
			const dto: vscode.NotebookData = {
				metadata: {},
				cells: [
					{
						value: 'code()',
						languageId: 'typescript',
						kind: vscode.NotebookCellKind.Code,
						outputs: [],
						metadata: { custom: { testCellMetadata: 123 } }
					},
					{
						value: 'Markdown Cell',
						languageId: 'markdown',
						kind: vscode.NotebookCellKind.Markup,
						outputs: [],
						metadata: { custom: { testCellMetadata: 123 } }
					}
				]
			};

			return dto;
		},
		saveNotebook: async (_document: vscode.NotebookDocument, _cancellation: vscode.CancellationToken) => {
			return;
		},
		saveNotebookAs: async (_targetResource: vscode.Uri, _document: vscode.NotebookDocument, _cancellation: vscode.CancellationToken) => {
			return;
		},
		backupNotebook: async (_document: vscode.NotebookDocument, _context: vscode.NotebookDocumentBackupContext, _cancellation: vscode.CancellationToken) => {
			return {
				id: '1',
				delete: () => { }
			};
		}
	}));

	const controller = vscode.notebooks.createNotebookController(
		'notebookSmokeTest',
		'notebookSmokeTest',
		'notebookSmokeTest'
	);

	controller.executeHandler = (cells) => {
		for (const cell of cells) {
			const task = controller.createNotebookCellExecution(cell);
			task.start();
			task.replaceOutput([new vscode.NotebookCellOutput([
				vscode.NotebookCellOutputItem.text('test output', 'text/html')
			])]);
			task.end(true);
		}
	};

	context.subscriptions.push(controller);

	context.subscriptions.push(vscode.commands.registerCommand('vscode-notebook-tests.debugAction', async (cell: vscode.NotebookCell) => {
		if (cell) {
			const edit = new vscode.WorkspaceEdit();
			const fullRange = new vscode.Range(0, 0, cell.document.lineCount - 1, cell.document.lineAt(cell.document.lineCount - 1).range.end.character);
			edit.replace(cell.document.uri, fullRange, 'test');
			await vscode.workspace.applyEdit(edit);
		} else {
			throw new Error('Cell not set correctly');
		}
	}));
}


text:
===========
pyprototypr
===========

About
=====

**pyprototypr** is a simple Python utility for fast creation of elements needed for prototype board or card games or other creative endevours requiring regular, simple output.

**pyprototypr** is *not* a graphic design program, nor even at the level of a tool such as nanDeck (see http://www.nand.it/nandeck/), which allows for fairly complex designs.

Concept
=======

The program should be reasonably simple, quick and useful.

* **Simple** in that name and shortcuts make sense; defaults are sensible; common things are easy
* **Quick** in that commands should be simple and easy things should take a few lines
* **Useful** for common prototypes but not at the level of complex graphic design

The assumption is that a user of this tool wants to rapidly develop a prototype in digital form, and is expecting to iterate over numerous versions in the course of a design process.  For that purpose, a clean and simple layout is better than getting bogged down in the intricacies of, for example, graduated shading or intricate interdependant layouts.

The underlying availability of Python means that more complex scenarios can, if needs be, be catered for by a programmer.

Elements
========

========== ========== ========
Primitives Shapes     Elements
========== ========== ========
color      line       card
position   hex        grid
place      circle     image
size       rectangle  deck
 -         oval       tile
 -         polygon    text
========== ========== ========

All elements have defaults; sizes are based on 1cm (one centimeter) as a default; the default foreground color is black and the default background color is white.

Sizes
=====

Some sizes are predefined for convenience:

* iles - catan, bluemooncity
* Cards - poker, tarot
* Hexes - AH, SPI, Catan
* Paper - A4, Letter
* Labels_Avery

Keywords
========

* type []
* offset []
* x []
* y []
* width []
* height []
* size []
*  []
*  []
*  []


text:
id: 582
title: 'Past	Forward: A Heritage Blogging and Social Media Workshop'
date: 2012-07-09T12:53:36+00:00
author_name: Adrianna Tan
layout: post
guid: http://popagandhi.com/?p=582
permalink: /2012/07/pastforward-a-heritage-blogging-and-social-media-workshop/
dsq_thread_id:
  -
crisp_persona_post_view_count:
  - 102
categories:
  - Events
  - Singapore
---
My friend [Yu-Mei](http://blog.toomanythoughts.org/) is putting together a blogging and social media workshop as part of [HeritageFest](http://www.heritagefest.sg/en/), a NHB event.

I'll be speaking with Rosenah Omar at 3pm, on a panel moderated by [Notabilia](http://notabilia.wordpress.com/), although I do wish I could split myself and attend the panel on 1960s music at the same time! Here's the schedule for the day, and here's the [Facebook event page](https://www.facebook.com/events/243987645704984/). Hope to see you there!

**Programme:**

**2:00 p.m.**

_Going Past Forward: The art of blogging or writing online about Singapore heritage_

1) [Lam Chun See](http://goodmorningyesterday.blogspot.com/)

2) [Ivan Chew](http://ramblinglibrarian.blogspot.com/), [Singapore Memory Project](http://www.iremember.sg/)

3) Dan Koh, [POSKOD.SG](http://poskod.sg/)

**2:45 p.m.**

Tea break

**3:00 p.m.**

_Blog What You Know: The Heritage of Everyday Life_

1) [Adrianna Tan](http://www.popagandhi.com/)

2) [Rosenah Omar](http://nenalingsblog.blogspot.com/)

OR

**3:00 p.m.**

_Not Just Nostalgia: Music of the 1960s_

1) [Andy Lim](http://singapore60smusic.blogspot.com/)

2) [Georgiana Glass](http://hamsterguppies.wordpress.com/) (and at [Mod-ified music](http://modcentric.blogspot.com/))

**3:45 p.m.**

_A Picture's Worth a Thousand Words_

1) [Char Lee](http://2ndshot.blogspot.com/)

2) [Zakaria Zainal](http://zakariazainal.com/)

OR

**3:45 p.m.**

_Balik Kampung: Blogging about Your Neighbourhood_

1) [Victor Yue](http://bullockcartwater.blogspot.com/)

2) [Kwek Li Yong](http://myqueenstown.blogspot.com/)

**4:30 p.m.**

END

**4:45 p.m.**

Special tour (optional): Victor Yue's Chinatown or Kwek Li Yong's Queenstown