text:
#ifndef THREAD_H
#define THREAD_H

#include "super_block.h"
#include "super_block_path.h"
#include <vector>
#include <ostream>

extern FILE *stat_fp;
extern boolean statistics;

class thread : public super_block_path
{
public:
    enum thread_type{
        SPECULATIVE,
        NONSPECULATIVE,
        LOOP
    };

private:
    int s_count;                            /*spawn count*/
    tnle* spawned_pos;                      /*spawn position*/
    cfg_block* spawned_block;               /*cfg block which contains spawn position*/
    tree_node_list* pslice;                 /*pre-compute slice*/
    label_sym *cqip_pos_num;                /*control quasi-independent point*/
    cfg_block* cqip_block;                  /*cfg block which contains cqip position*/
    tnle* cqip_pos;                         /*cqip position*/
    std::vector<tnle *> spawn_poss;         /*vector of thread's spawn position*/
    thread_type thread_kind;                /*current thread type(speculative or nonspeculative)*/

public:
    thread();
    ~thread();
    void set_spawn_count(int n);
    int spawn_count();
    void inc_spawn_count();
    void set_spawn_info(cfg_block *spawn_block, tree_node_list *pslice,
                        label_sym *cqip_pos_num);
    void set_spawned_pos(tnle *spawn_pos);
    tnle* get_spawned_pos();

    void set_thread_type(thread_type type) {thread_kind = type;};
    thread_type get_thread_type() {return thread_kind;}

    void set_cqip_pos(tnle *cqip_pos);
    tnle* get_cqip_pos();

    void set_spawned_block(cfg_block *cb){spawned_block = cb;}
    void setSpawnBlock(tnle* spawn_pos);
    cfg_block* get_spawned_block();
    void set_cqip_block(cfg_block *cb) {cqip_block = cb;}
    cfg_block* get_cqip_block();

    tree_node_list* get_pslice() {return pslice;}
    void add_spawn_pos(tnle *spawn_pos);

    bool reach_any_spawn_pos(tnle *spawn_pos);

    void write_spawn_info();

public:		//addbykeyming 20141231
    static thread * create_new_thread(super_block * first);
    void finish_construction(thread* future_thread);
    super_block *find_pslice_path(super_block * spawn_sblock,super_block * cqip_sblock);
    void fillPslice(super_block *pslice_path);
 /**
  * Print out some key information of the thread object. These methods are used to debug or log the information.
  */
public:
    void printSpawnPosition(std::ostream &os)const;
    void printSuperBlocks(std::ostream &os)const;
};
#endif


text:
package embl.ebi.variation.eva.vcfdump;

import embl.ebi.variation.eva.vcfdump.cellbasewsclient.CellbaseWSClient;
import htsjdk.variant.variantcontext.Allele;
import htsjdk.variant.variantcontext.Genotype;
import htsjdk.variant.variantcontext.VariantContext;
import htsjdk.variant.vcf.VCFHeader;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.opencb.biodata.models.feature.Region;
import org.opencb.biodata.models.variant.*;
import org.opencb.datastore.core.QueryOptions;
import org.opencb.opencga.lib.common.Config;
import org.opencb.opencga.storage.core.StorageManagerException;
import org.opencb.opencga.storage.core.StorageManagerFactory;
import org.opencb.opencga.storage.core.variant.VariantStorageManager;
import org.opencb.opencga.storage.core.variant.adaptors.VariantDBAdaptor;
import org.opencb.opencga.storage.core.variant.adaptors.VariantDBIterator;
import org.opencb.opencga.storage.core.variant.adaptors.VariantSourceDBAdaptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.util.*;

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

/**
 * Created by jmmut on 2015-10-29.
 *
 * @author Jose Miguel Mut Lopez <jmmut@ebi.ac.uk>
 */
public class VariantExporterTest {

    private static final Logger logger = LoggerFactory.getLogger(VariantExporterTest.class);

    @Rule
    public ExpectedException thrown = ExpectedException.none();
    private static CellbaseWSClient cellBaseClient;
    private static VariantStorageManager variantStorageManager;
    private static VariantDBAdaptor variantDBAdaptor;
    private static VariantSourceDBAdaptor variantSourceDBAdaptor;

    /**
     * Clears and populates the Mongo collection used during the tests.
     *
     * @throws java.io.IOException
     * @throws java.lang.InterruptedException
     */
    @BeforeClass
    public static void setUpClass() throws IOException, InterruptedException, URISyntaxException, IllegalAccessException, ClassNotFoundException, InstantiationException, StorageManagerException {
        VariantExporterTestDB.cleanDBs();
        VariantExporterTestDB.fillDB();

        Config.setOpenCGAHome(System.getenv("OPENCGA_HOME") != null ? System.getenv("OPENCGA_HOME") : "/opt/opencga");
        cellBaseClient = new CellbaseWSClient("hsapiens");
        logger.info("using cellbase: " + cellBaseClient.getUrl() + " version " + cellBaseClient.getVersion());
        variantStorageManager = StorageManagerFactory.getVariantStorageManager();
        variantDBAdaptor = variantStorageManager.getDBAdaptor(VariantExporterTestDB.DB_NAME, null);
        variantSourceDBAdaptor = variantDBAdaptor.getVariantSourceDBAdaptor();
    }

    /**
     * Clears and populates the Mongo collection used during the tests.
     *
     * @throws UnknownHostException
     */
    @AfterClass
    public static void tearDownClass() throws UnknownHostException {
        VariantExporterTestDB.cleanDBs();
    }

    @Test
    public void getSources() {
        VariantExporter variantExporter = new VariantExporter(null);

        // one study
        String study7Id = "7";
        List<String> studies = Collections.singletonList(study7Id);
        Map<String, VariantSource> sources = variantExporter.getSources(variantSourceDBAdaptor, studies);
        assertEquals(1, sources.size());
        VariantSource file = sources.get(study7Id);
        assertEquals(study7Id, file.getStudyId());
        assertEquals("6", file.getFileId());

        // two studies
        String study8Id = "8";
        studies = Arrays.asList(study7Id, study8Id);
        sources = variantExporter.getSources(variantSourceDBAdaptor, studies);
        assertEquals(2, sources.size());
        file = sources.get(study7Id);
        assertEquals(study7Id, file.getStudyId());
        assertEquals("6", file.getFileId());
        assertEquals(2504, file.getSamples().size());
        file = sources.get(study8Id);
        assertEquals(study8Id, file.getStudyId());
        assertEquals("5", file.getFileId());
        assertEquals(2504, file.getSamples().size());

        // one study not in database
        studies = Arrays.asList("2");
        sources = variantExporter.getSources(variantSourceDBAdaptor, studies);
        assertEquals(0, sources.size());

        // empty study filter
        studies = new ArrayList<>();
        sources = variantExporter.getSources(variantSourceDBAdaptor, studies);
        assertEquals(0, sources.size());
    }

    @Test
    public void getVcfHeaders() throws IOException {
        VariantExporter variantExporter = new VariantExporter(null);
        String study7Id = "7";
        String study8Id = "8";
        List<String> studies = Arrays.asList(study7Id, study8Id);
        Map<String, VariantSource> sources = variantExporter.getSources(variantSourceDBAdaptor, studies);

        Map<String, VCFHeader> headers = variantExporter.getVcfHeaders(sources);
        VCFHeader header = headers.get(study7Id);
        assertEquals(2504, header.getSampleNamesInOrder().size());
        assertTrue(header.hasGenotypingData());
        header = headers.get(study8Id);
        assertEquals(2504, header.getSampleNamesInOrder().size());
        assertTrue(header.hasGenotypingData());
    }

    @Test
    public void testExportOneStudy() throws Exception {
        List<String> studies = Collections.singletonList("7");
        String region = "20:61000-69000";
        QueryOptions query = new QueryOptions();
        Map<String, List<VariantContext>> exportedVariants = exportAndCheck(query, studies, region);
        checkExportedVariants(query, studies, exportedVariants);
    }

    @Test
    public void testExportTwoStudies() throws Exception {
        List<String> studies = Arrays.asList("7", "8");
        String region = "20:71000-79000";
        // TODO Both studies have 219 variants in the region... check if we can choose some region with different number of variants
        QueryOptions query = new QueryOptions();
        Map<String, List<VariantContext>> exportedVariants = exportAndCheck(query, studies, region);
        checkExportedVariants(query, studies, exportedVariants);
    }

    // TODO: review this test
//    @Test
//    public void textExportWithFilter() {
//        QueryOptions queryOptions = new QueryOptions();
//        // TODO: this test should fail, is not exporting all variants
//        queryOptions.put(VariantDBAdaptor.ID, "rs544625796");
 //      //     query.put(VariantDBAdaptor.REFERENCE, "A");
//        List<String> studies = Collections.singletonList("7");
//        String region = "20:61000-69000";
//        eMap<String, List<VariantContext>> exportedVariants = xportAndCheck(queryOptions, studies, region);
//        checkExportedVariants
//                // annot-ct=SO%3A0001583
//
//    }

    @Test
    public void testMissingCellbase() throws Exception {
        String studyId = "studyId";
        final VariantSource variantSource = createTestVariantSource(studyId);
        VariantFactory factory = new VariantVcfFactory();

        List<String> studies = Collections.singletonList(studyId);

        // test multiallelic. these first conversions should NOT fail, as they doesn't need the src
        String multiallelicLine = "1\t1000\tid\tC\tA,T\t100\tPASS\t.\tGT\t0|0\t0|0\t0|1\t1|1\t1|2\t0|1";
        List<Variant> variants = factory.create(variantSource, multiallelicLine);
        assertEquals(2, variants.size());
        removeSrc(variants);    // <---- this is the key point of the test

        VariantExporter variantExporter = new VariantExporter(null);
        Map<String, VariantContext> variantContext = variantExporter.convertBiodataVariantToVariantContext(variants.get(0), studies, null);

        List<String> alleles = Arrays.asList("C", "A", ".");
        assertEqualGenotypes(variants.get(0), variantContext.get(studyId), alleles);

        variantContext = variantExporter.convertBiodataVariantToVariantContext(variants.get(1), studies, null);
        alleles = Arrays.asList("C", "T", ".");
        assertEqualGenotypes(variants.get(1), variantContext.get(studyId), alleles);

        // test multiallelic + indel
        String multiallelicIndelLine = "1\t1000\tid\tC\tCA,T\t100\tPASS\t.\tGT\t0|0\t0|0\t0|1\t1|1\t1|2\t0|1";
        variants = factory.create(variantSource, multiallelicIndelLine);
        assertEquals(2, variants.size());
        removeSrc(variants);    // <---- this is the key point of the test

        variantContext = variantExporter.convertBiodataVariantToVariantContext(variants.get(1), studies, null);
        alleles = Arrays.asList("C", "T", ".");
        assertEqualGenotypes(variants.get(1), variantContext.get(studyId), alleles);

        // the next exception is the only one that should throw
        thrown.expect(IllegalArgumentException.class);
        variantExporter.convertBiodataVariantToVariantContext(variants.get(0), studies, null);

    }

    @Test
    public void testGetVariantContextFromVariant() throws Exception {
        String studyId = "studyId";
        final VariantSource variantSource = createTestVariantSource(studyId);
        VariantFactory factory = new VariantVcfFactory();

        List<String> studyIds = Collections.singletonList(studyId);

        // test multiallelic
        String multiallelicLine = "1\t1000\tid\tC\tA,T\t100\tPASS\t.\tGT\t0|0\t0|0\t0|1\t1|1\t1|2\t0|1";
        List<Variant> variants = factory.create(variantSource, multiallelicLine);
        assertEquals(2, variants.size());

        VariantExporter variantExporter = new VariantExporter(cellBaseClient);
        Map<String, VariantContext> variantContext = variantExporter.convertBiodataVariantToVariantContext(variants.get(0), studyIds, null);

        List<String> alleles = Arrays.asList("C", "A", ".");
        assertEqualGenotypes(variants.get(0), variantContext.get(studyId), alleles);

        variantContext = variantExporter.convertBiodataVariantToVariantContext(variants.get(1), studyIds, null);
        alleles = Arrays.asList("C", "T", ".");
        assertEqualGenotypes(variants.get(1), variantContext.get(studyId), alleles);

        // test indel
        String indelLine = "1\t1000\tid\tN\tNA\t100\tPASS\t.\tGT\t0|0\t0|0\t0|1\t1|1\t1|0\t0|1";
        variants = factory.create(variantSource, indelLine);

        variantContext = variantExporter.convertBiodataVariantToVariantContext(variants.get(0), studyIds, null);
        alleles = Arrays.asList("N", "NA");
        assertEqualGenotypes(variants.get(0), variantContext.get(studyId), alleles);

        // test multiallelic + indel
        String multiallelicIndelLine = "1\t1000\tid\tN\tNA,T\t100\tPASS\t.\tGT\t0|0\t0|0\t0|1\t1|1\t1|2\t0|1";
        variants = factory.create(variantSource, multiallelicIndelLine);
        assertEquals(2, variants.size());

        variantContext = variantExporter.convertBiodataVariantToVariantContext(variants.get(0), studyIds, null);
        alleles = Arrays.asList("N", "NA", ".");
        assertEqualGenotypes(variants.get(0), variantContext.get(studyId), alleles);

        variantContext = variantExporter.convertBiodataVariantToVariantContext(variants.get(1), studyIds, null);
        alleles = Arrays.asList("N", "T", ".");
        assertEqualGenotypes(variants.get(1), variantContext.get(studyId), alleles);

    }

    private Map<String, List<VariantContext>> exportAndCheck(QueryOptions query, List<String> studies, String region) {
        VariantExporter variantExporter = new VariantExporter(cellBaseClient);
        query.put(VariantDBAdaptor.STUDIES, studies);
        query.add(VariantDBAdaptor.REGION, region);

        VariantDBIterator iterator = variantDBAdaptor.iterator(query);
        Map<String, List<VariantContext>> exportedVariants = variantExporter.export(iterator, new Region(region), studies);
        assertEquals(0, variantExporter.getFailedVariants());
        return exportedVariants;
    }

    private void checkExportedVariants(QueryOptions query, List<String> studies, Map<String, List<VariantContext>> exportedVariants) {
        // checks
        assertEquals(studies.size(), exportedVariants.keySet().size());

        for (String study : studies) {
            compareExportedVariantsWithDatabaseOnes(query, exportedVariants, study);
        }
    }

    private void compareExportedVariantsWithDatabaseOnes(QueryOptions query, Map<String, List<VariantContext>> exportedVariants, String study) {
        VariantDBIterator iterator;
        query.put(VariantDBAdaptor.STUDIES, Collections.singletonList(study));
        long iteratorSize = 0;
        iterator = variantDBAdaptor.iterator(query);
        while (iterator.hasNext()) {
            Variant variant = iterator.next();
            assertTrue(variantInExportedVariantsCollection(variant, exportedVariants.get(study)));
            iteratorSize++;
        }
        int studyExportedVariants = exportedVariants.get(study).size();
        logger.info("{} variants exported for study {}", studyExportedVariants, study);
        assertEquals(iteratorSize, studyExportedVariants);
    }

    private VariantSource createTestVariantSource(String studyId) {
        final VariantSource variantSource = new VariantSource("name", "fileId", studyId, "studyName");
        List<String> samples = new ArrayList<>();
        for (int i = 0; i < 6; i++) {
            samples.add("s"+i);
        }
        variantSource.setSamples(samples);
        return variantSource;
    }

    private void removeSrc(List<Variant> variants) {
        for (Variant variant : variants) {
            for (VariantSourceEntry variantSourceEntry : variant.getSourceEntries().values()) {
                variantSourceEntry.getAttributes().remove("src");
            }
        }
    }

    private void assertEqualGenotypes(Variant variant, VariantContext variantContext, List<String> alleles) {
        for (Map.Entry<String, Map<String, String>> data : variant.getSourceEntries().values().iterator().next().getSamplesData().entrySet()) {
            Genotype genotype = variantContext.getGenotype(data.getKey());
            String gt = data.getValue().get("GT");
            org.opencb.biodata.models.feature.Genotype biodataGenotype = new org.opencb.biodata.models.feature.Genotype(gt, alleles.get(0), alleles.get(1));
            assertEquals(Allele.create(alleles.get(biodataGenotype.getAllele(0)), biodataGenotype.isAlleleRef(0)),
                    genotype.getAllele(0));
            assertEquals(Allele.create(alleles.get(biodataGenotype.getAllele(1)), biodataGenotype.isAlleleRef(1)),
                    genotype.getAllele(1));
        }
    }

    private static boolean variantInExportedVariantsCollection(Variant variant, List<VariantContext> exportedVariants) {
        if (exportedVariants.stream().anyMatch(v -> sameVariant(variant, v))) {
            return true;
        }

        return false;
    }

    private static boolean sameVariant(Variant v1, VariantContext v2) {
        if (v2.getContig().equals(v1.getChromosome()) && v2.getStart() == v1.getStart()) {
            if (v1.getReference().equals("")) {
                // insertion
                return v2.getAlternateAlleles().contains(Allele.create(v2.getReference().getBaseString() + v1.getAlternate()));
            } else if (v1.getAlternate().equals("")) {
                // deletion
                return v2.getAlternateAlleles().stream().anyMatch(alt -> v2.getReference().getBaseString().equals(alt.getBaseString() + v1.getReference()));
            } else {
                return v1.getReference().equals(v2.getReference().getBaseString()) && v2.getAlternateAlleles().contains(Allele.create(v1.getAlternate()));
            }
        }
        return false;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.ovirt.engine.ui.userportal.section.login.view;

import org.ovirt.engine.ui.common.idhandler.ElementIdHandler;
import org.ovirt.engine.ui.common.idhandler.WithElementId;
import org.ovirt.engine.ui.common.view.AbstractLoginPopupView;
import org.ovirt.engine.ui.common.widget.Align;
import org.ovirt.engine.ui.common.widget.dialog.PopupNativeKeyPressHandler;
import org.ovirt.engine.ui.common.widget.dialog.SimpleDialogButton;
import org.ovirt.engine.ui.common.widget.dialog.SimplePopupPanel;
import org.ovirt.engine.ui.common.widget.editor.EntityModelCheckBoxEditor;
import org.ovirt.engine.ui.common.widget.editor.EntityModelPasswordBoxEditor;
import org.ovirt.engine.ui.common.widget.editor.EntityModelTextBoxEditor;
import org.ovirt.engine.ui.common.widget.editor.ListModelListBoxEditor;
import org.ovirt.engine.ui.uicommonweb.models.userportal.UserPortalLoginModel;
import org.ovirt.engine.ui.userportal.ApplicationConstants;
import org.ovirt.engine.ui.userportal.ApplicationMessages;
import org.ovirt.engine.ui.userportal.ApplicationResources;
import org.ovirt.engine.ui.userportal.section.login.presenter.LoginPopupPresenterWidget;

import com.google.gwt.core.client.GWT;
import com.google.gwt.editor.client.SimpleBeanEditorDriver;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.DecoratedPopupPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Panel;
import com.google.inject.Inject;

public class LoginPopupView extends AbstractLoginPopupView implements LoginPopupPresenterWidget.ViewDef {

    interface Driver extends SimpleBeanEditorDriver<UserPortalLoginModel, LoginPopupView> {
        Driver driver = GWT.create(Driver.class);
    }

    interface ViewUiBinder extends UiBinder<DecoratedPopupPanel, LoginPopupView> {
        ViewUiBinder uiBinder = GWT.create(ViewUiBinder.class);
    }

    interface ViewIdHandler extends ElementIdHandler<LoginPopupView> {
        ViewIdHandler idHandler = GWT.create(ViewIdHandler.class);
    }

    @UiField
    SimplePopupPanel popup;

    @UiField
    @Path("userName.entity")
    @WithElementId("userName")
    EntityModelTextBoxEditor userNameEditor;

    @UiField
    @Path("password.entity")
    @WithElementId("password")
    EntityModelPasswordBoxEditor passwordEditor;

    @UiField
    @Path("domain.selectedItem")
    @WithElementId("domain")
    ListModelListBoxEditor<Object> domainEditor;

    @UiField
    @WithElementId
    SimpleDialogButton loginButton;

    @UiField
    @Ignore
    Label errorMessage;

    @UiField(provided = true)
    @Path("isAutoConnect.entity")
    @WithElementId
    EntityModelCheckBoxEditor connectAutomatically;

    @UiField
    @Ignore
    Panel errorMessagePanel;

    @Inject
    public LoginPopupView(EventBus eventBus,
            ApplicationResources resources,
            ApplicationConstants constants,
            ApplicationMessages messages) {
        super(eventBus, resources);

        connectAutomatically = new EntityModelCheckBoxEditor(Align.RIGHT);
        initWidget(ViewUiBinder.uiBinder.createAndBindUi(this));
        asWidget().setGlassEnabled(false);
        localize(constants);

        errorMessagePanel.setVisible(false);
        passwordEditor.setAutoComplete("off"); //$NON-NLS-1$
        Driver.driver.initialize(this);
        ViewIdHandler.idHandler.generateAndSetIds(this);
    }

    void localize(ApplicationConstants constants) {
        userNameEditor.setLabel(constants.loginFormUserNameLabel());
        passwordEditor.setLabel(constants.loginFormPasswordLabel());
        domainEditor.setLabel(constants.loginFormDomainLabel());
        connectAutomatically.setLabel(constants.loginFormConnectAutomaticallyLabel());
        loginButton.setText(constants.loginButtonLabel());
    }

    @Override
    public void edit(UserPortalLoginModel object) {
        Driver.driver.edit(object);
    }

    @Override
    public UserPortalLoginModel flush() {
        return Driver.driver.flush();
    }

    @Override
    public void resetAndFocus() {
        userNameEditor.asValueBox().selectAll();
        userNameEditor.asValueBox().setFocus(true);
        clearErrorMessage();
    }

    @Override
    public void setErrorMessage(String text) {
        errorMessage.setText(text);
        errorMessage.setVisible(text != null);

        if (errorMessage.isVisible()) {
            errorMessagePanel.setVisible(true);
        }
    }

    @Override
    public void clearErrorMessage() {
        setErrorMessage(null);
    }

    @Override
    public HasClickHandlers getLoginButton() {
        return loginButton;
    }

    @Override
    public void setPopupKeyPressHandler(PopupNativeKeyPressHandler keyPressHandler) {
        popup.setKeyPressHandler(keyPressHandler);
    }

}


text:
package resourceapply

import (
	"context"
	"crypto/sha256"
	"encoding/json"
	"fmt"

	"k8s.io/klog/v2"

	appsv1 "k8s.io/api/apps/v1"
	apierrors "k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/util/uuid"
	appsclientv1 "k8s.io/client-go/kubernetes/typed/apps/v1"

	"github.com/openshift/library-go/pkg/operator/events"
	"github.com/openshift/library-go/pkg/operator/resource/resourcemerge"
)

// The Apply<type> methods in this file ensure that a resource is created or updated to match
// the form provided by the caller.
//
// If the resource does not yet exist, it will be created.
//
// If the resource exists, the metadata of the required resource will be merged with the
// existing resource and an update will be performed if the spec and metadata differ between
// the required and existing resources. To be reliable, the input of the required spec from
// the operator should be stable. It does not need to set all fields, since some fields are
// defaulted server-side.  Detection of spec drift from intent by other actors is determined
// by generation, not by spec comparison.
//
// To ensure an update in response to state external to the resource spec, the caller should
// set an annotation representing that external state e.g.
//
//   `myoperator.openshift.io/config-resource-version: <resourceVersion>`
//
// An update will be performed if:
//
// - The required resource metadata differs from that of the existing resource.
//   - The difference will be detected by comparing the name, namespace, labels and
//   annotations of the 2 resources.
//
// - The generation expected by the operator differs from generation of the existing
// resource.
//   - This is the likely result of an actor other than the operator updating a resource
//   managed by the operator.
//
// - The spec of the required resource differs from the spec of the existing resource.
//   - The difference will be detected via metadata comparison since the hash of the
//   resource's spec will be set as an annotation prior to comparison.

const specHashAnnotation = "operator.openshift.io/spec-hash"

// SetSpecHashAnnotation computes the hash of the provided spec and sets an annotation of the
// hash on the provided ObjectMeta. This method is used internally by Apply<type> methods, and
// is exposed to support testing with fake clients that need to know the mutated form of the
// resource resulting from an Apply<type> call.
func SetSpecHashAnnotation(objMeta *metav1.ObjectMeta, spec interface{}) error {
	jsonBytes, err := json.Marshal(spec)
	if err != nil {
		return err
	}
	specHash := fmt.Sprintf("%x", sha256.Sum256(jsonBytes))
	if objMeta.Annotations == nil {
		objMeta.Annotations = map[string]string{}
	}
	objMeta.Annotations[specHashAnnotation] = specHash
	return nil
}

// ApplyDeployment ensures the form of the specified deployment is present in the API. If it
// does not exist, it will be created. If it does exist, the metadata of the required
// deployment will be merged with the existing deployment and an update performed if the
// deployment spec and metadata differ from the previously required spec and metadata. For
// further detail, check the top-level comment.
//
// NOTE: The previous implementation of this method was renamed to
// ApplyDeploymentWithForce. If are reading this in response to a compile error due to the
// change in signature, you have the following options:
//
// - Update the calling code to rely on the spec comparison provided by the new
// implementation. If the code in question was specifying the force parameter to ensure
// rollout in response to changes in resources external to the deployment, it will need to be
// revised to set that external state as an annotation e.g.
//
//   myoperator.openshift.io/my-resource: <resourceVersion>
//
// - Update the call to use ApplyDeploymentWithForce. This is available as a temporary measure
// but the method is deprecated and will be removed in 4.6.
func ApplyDeployment(ctx context.Context, client appsclientv1.DeploymentsGetter, recorder events.Recorder,
	requiredOriginal *appsv1.Deployment, expectedGeneration int64) (*appsv1.Deployment, bool, error) {

	required := requiredOriginal.DeepCopy()
	err := SetSpecHashAnnotation(&required.ObjectMeta, required.Spec)
	if err != nil {
		return nil, false, err
	}

	return ApplyDeploymentWithForce(ctx, client, recorder, required, expectedGeneration, false)
}

// ApplyDeploymentWithForce merges objectmeta and requires matching generation. It returns the final Object, whether any change as made, and an error.
//
// DEPRECATED - This method will be removed in 4.6 and callers will need to migrate to ApplyDeployment before then.
func ApplyDeploymentWithForce(ctx context.Context, client appsclientv1.DeploymentsGetter, recorder events.Recorder, requiredOriginal *appsv1.Deployment, expectedGeneration int64,
	forceRollout bool) (*appsv1.Deployment, bool, error) {

	required := requiredOriginal.DeepCopy()
	if required.Annotations == nil {
		required.Annotations = map[string]string{}
	}
	if _, ok := required.Annotations[specHashAnnotation]; !ok {
		// If the spec hash annotation is not present, the caller expects the
		// pull-spec annotation to be applied.
		required.Annotations["operator.openshift.io/pull-spec"] = required.Spec.Template.Spec.Containers[0].Image
	}
	existing, err := client.Deployments(required.Namespace).Get(ctx, required.Name, metav1.GetOptions{})
	if apierrors.IsNotFound(err) {
		actual, err := client.Deployments(required.Namespace).Create(ctx, required, metav1.CreateOptions{})
		reportCreateEvent(recorder, required, err)
		return actual, true, err
	}
	if err != nil {
		return nil, false, err
	}

	modified := resourcemerge.BoolPtr(false)
	existingCopy := existing.DeepCopy()

	resourcemerge.EnsureObjectMeta(modified, &existingCopy.ObjectMeta, required.ObjectMeta)
	// there was no change to metadata, the generation was right, and we weren't asked for force the deployment
	if !*modified && existingCopy.ObjectMeta.Generation == expectedGeneration && !forceRollout {
		return existingCopy, false, nil
	}

	// at this point we know that we're going to perform a write.  We're just trying to get the object correct
	toWrite := existingCopy // shallow copy so the code reads easier
	toWrite.Spec = *required.Spec.DeepCopy()
	if forceRollout {
		// forces a deployment
		forceString := string(uuid.NewUUID())
		if toWrite.Annotations == nil {
			toWrite.Annotations = map[string]string{}
		}
		if toWrite.Spec.Template.Annotations == nil {
			toWrite.Spec.Template.Annotations = map[string]string{}
		}
		toWrite.Annotations["operator.openshift.io/force"] = forceString
		toWrite.Spec.Template.Annotations["operator.openshift.io/force"] = forceString
	}

	if klog.V(4).Enabled() {
		klog.Infof("Deployment %q changes: %v", required.Namespace+"/"+required.Name, JSONPatchNoError(existing, toWrite))
	}

	actual, err := client.Deployments(required.Namespace).Update(ctx, toWrite, metav1.UpdateOptions{})
	reportUpdateEvent(recorder, required, err)
	return actual, true, err
}

// ApplyDaemonSet ensures the form of the specified daemonset is present in the API. If it
// does not exist, it will be created. If it does exist, the metadata of the required
// daemonset will be merged with the existing daemonset and an update performed if the
// daemonset spec and metadata differ from the previously required spec and metadata. For
// further detail, check the top-level comment.
//
// NOTE: The previous implementation of this method was renamed to ApplyDaemonSetWithForce. If
// are reading this in response to a compile error due to the change in signature, you have
// the following options:
//
// - Update the calling code to rely on the spec comparison provided by the new
// implementation. If the code in question was specifying the force parameter to ensure
// rollout in response to changes in resources external to the daemonset, it will need to be
// revised to set that external state as an annotation e.g.
//
//   myoperator.openshift.io/my-resource: <resourceVersion>
//
// - Update the call to use ApplyDaemonSetWithForce. This is available as a temporary measure
// but the method is deprecated and will be removed in 4.6.
func ApplyDaemonSet(ctx context.Context, client appsclientv1.DaemonSetsGetter, recorder events.Recorder,
	requiredOriginal *appsv1.DaemonSet, expectedGeneration int64) (*appsv1.DaemonSet, bool, error) {

	required := requiredOriginal.DeepCopy()
	err := SetSpecHashAnnotation(&required.ObjectMeta, required.Spec)
	if err != nil {
		return nil, false, err
	}

	return ApplyDaemonSetWithForce(ctx, client, recorder, required, expectedGeneration, false)
}

// ApplyDaemonSetWithForce merges objectmeta and requires matching generation. It returns the final Object, whether any change as made, and an error
// DEPRECATED - This method will be removed in 4.6 and callers will need to migrate to ApplyDaemonSet before then.
func ApplyDaemonSetWithForce(ctx context.Context, client appsclientv1.DaemonSetsGetter, recorder events.Recorder, requiredOriginal *appsv1.DaemonSet, expectedGeneration int64, forceRollout bool) (*appsv1.DaemonSet, bool, error) {
	required := requiredOriginal.DeepCopy()
	if required.Annotations == nil {
		required.Annotations = map[string]string{}
	}
	if _, ok := required.Annotations[specHashAnnotation]; !ok {
		// If the spec hash annotation is not present, the caller expects the
		// pull-spec annotation to be applied.
		required.Annotations["operator.openshift.io/pull-spec"] = required.Spec.Template.Spec.Containers[0].Image
	}
	existing, err := client.DaemonSets(required.Namespace).Get(ctx, required.Name, metav1.GetOptions{})
	if apierrors.IsNotFound(err) {
		actual, err := client.DaemonSets(required.Namespace).Create(ctx, required, metav1.CreateOptions{})
		reportCreateEvent(recorder, required, err)
		return actual, true, err
	}
	if err != nil {
		return nil, false, err
	}

	modified := resourcemerge.BoolPtr(false)
	existingCopy := existing.DeepCopy()

	resourcemerge.EnsureObjectMeta(modified, &existingCopy.ObjectMeta, required.ObjectMeta)
	// there was no change to metadata, the generation was right, and we weren't asked for force the deployment
	if !*modified && existingCopy.ObjectMeta.Generation == expectedGeneration && !forceRollout {
		return existingCopy, false, nil
	}

	// at this point we know that we're going to perform a write.  We're just trying to get the object correct
	toWrite := existingCopy // shallow copy so the code reads easier
	toWrite.Spec = *required.Spec.DeepCopy()
	if forceRollout {
		// forces a deployment
		forceString := string(uuid.NewUUID())
		if toWrite.Annotations == nil {
			toWrite.Annotations = map[string]string{}
		}
		if toWrite.Spec.Template.Annotations == nil {
			toWrite.Spec.Template.Annotations = map[string]string{}
		}
		toWrite.Annotations["operator.openshift.io/force"] = forceString
		toWrite.Spec.Template.Annotations["operator.openshift.io/force"] = forceString
	}

	if klog.V(4).Enabled() {
		klog.Infof("DaemonSet %q changes: %v", required.Namespace+"/"+required.Name, JSONPatchNoError(existing, toWrite))
	}
	actual, err := client.DaemonSets(required.Namespace).Update(ctx, toWrite, metav1.UpdateOptions{})
	reportUpdateEvent(recorder, required, err)
	return actual, true, err
}


text:
/*
 * 04/07/2005
 *
 * RTextAreaBase.java - The base class for an RTextArea.
 *
 * This library is distributed under a modified BSD license.  See the included
 * RSyntaxTextArea.License.txt file for details.
 */
package org.fife.ui.rtextarea;

import java.awt.AWTEvent;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.ComponentEvent;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JTextArea;
import javax.swing.event.CaretEvent;
import javax.swing.plaf.ColorUIResource;
import javax.swing.plaf.TextUI;
import javax.swing.text.AbstractDocument;
import javax.swing.text.BadLocationException;
import javax.swing.text.Caret;
import javax.swing.text.StyleContext;

/**
 * This is the base class for RTextArea; basically it's just an
 * extension of javax.swing.JTextArea adding a bunch of properties.
 *

 *
 * This class is only supposed to be overridden by RTextArea.
 *
 * @author Robert Futrell
 * @version 0.8
 */
abstract class RTextAreaBase extends JTextArea {

	public static final String BACKGROUND_IMAGE_PROPERTY			= "background.image";
	public static final String CURRENT_LINE_HIGHLIGHT_COLOR_PROPERTY	= "RTA.currentLineHighlightColor";
	public static final String CURRENT_LINE_HIGHLIGHT_FADE_PROPERTY	= "RTA.currentLineHighlightFade";
	public static final String HIGHLIGHT_CURRENT_LINE_PROPERTY		= "RTA.currentLineHighlight";
	public static final String ROUNDED_SELECTION_PROPERTY			= "RTA.roundedSelection";

	private boolean tabsEmulatedWithSpaces;		// If true, tabs will be expanded to spaces.

	private boolean highlightCurrentLine;		// If true, the current line is highlighted.
	private Color currentLineColor;			// The color used to highlight the current line.
	private boolean marginLineEnabled;			// If true, paint a "margin line."
	private Color marginLineColor;			// The color used to paint the margin line.
	private int marginLineX;				// The x-location of the margin line.
	private int marginSizeInChars;			// How many 'm' widths the margin line is over.
	private boolean fadeCurrentLineHighlight;	// "Fade effect" for current line highlight.
	private boolean roundedSelectionEdges;
	private int previousCaretY;
int currentCaretY;							// Used to know when to rehighlight current line.

	private BackgroundPainterStrategy backgroundPainter;	// Paints the background.

	private RTAMouseListener mouseListener;

	private static final Color DEFAULT_CARET_COLOR				= new ColorUIResource(255,51,51);
	private static final Color DEFAULT_CURRENT_LINE_HIGHLIGHT_COLOR	= new Color(255,255,170);
	private static final Color DEFAULT_MARGIN_LINE_COLOR			= new Color(255,224,224);
	private static final int DEFAULT_TAB_SIZE					= 4;
	private static final int DEFAULT_MARGIN_LINE_POSITION			= 80;

	/**
	 * Constructor.
	 */
	public RTextAreaBase() {
		init();
	}

	/**
	 * Constructor.
	 *
	 * @param doc The document for the editor.
	 */
	public RTextAreaBase(AbstractDocument doc) {
		super(doc);
		init();
	}

	/**
	 * Constructor.
	 *
	 * @param text The initial text to display.
	 */
	public RTextAreaBase(String text) {
		// Don't call super(text) to avoid NPE due to our funky RTextAreaUI...
		init();
		setText(text);
	}

	/**
	 * Constructor.
	 *
	 * @param rows The number of rows to display.
	 * @param cols The number of columns to display.
	 * @throws IllegalArgumentException If either rows or
	 *         cols is negative.
	 */
	public RTextAreaBase(int rows, int cols) {
		super(rows, cols);
		init();
	}

	/**
	 * Constructor.
	 *
	 * @param text The initial text to display.
	 * @param rows The number of rows to display.
	 * @param cols The number of columns to display.
	 * @throws IllegalArgumentException If either rows or
	 *         cols is negative.
	 */
	public RTextAreaBase(String text, int rows, int cols) {
		// Don't call this super() due to NPE from our funky RTextAreaUI...
		//super(text, rows, cols);
		super(rows, cols);
		init();
		setText(text);
	}

	/**
	 * Constructor.
	 *
	 * @param doc The document for the editor.
	 * @param text The initial text to display.
	 * @param rows The number of rows to display.
	 * @param cols The number of columns to display.
	 * @throws IllegalArgumentException If either rows or
	 *         cols is negative.
	 */
	public RTextAreaBase(AbstractDocument doc, String text, int rows,
							int cols) {
		// Don't call super() with text due to NPE from our funky RTextAreaUI...
		super(doc, null/*text*/, rows, cols);
		init();
		setText(text);
	}

	/**
	 * Adds listeners that listen for changes to the current line, so we can
	 * update our "current line highlight."  This is needed only because of an
	 * apparent difference between the JRE 1.4.2 and 1.5.0 (needed on 1.4.2,
	 * not needed on 1.5.0).
	 */
	private void addCurrentLineHighlightListeners() {
		boolean add = true;
		MouseMotionListener[] mouseMotionListeners = getMouseMotionListeners();
		for (int i=0; i<mouseMotionListeners.length; i++) {
			if (mouseMotionListeners[i]==mouseListener) {
				add = false;
				break;
			}
		}
		if (add==true) {
			//System.err.println("Adding mouse motion listener!");
			addMouseMotionListener(mouseListener);
		}
		MouseListener[] mouseListeners = getMouseListeners();
		for (int i=0; i<mouseListeners.length; i++) {
			if (mouseListeners[i]==mouseListener) {
				add = false;
				break;
			}
		}
		if (add==true) {
			//System.err.println("Adding mouse listener!");
			addMouseListener(mouseListener);
		}
	}

	/*
	 * TODO: Figure out why RTextArea doesn't work with RTL orientation!
	 */
//	public void applyComponentOrientation(ComponentOrientation orientation) {
//		super.applyComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
//	}

	/**
	 * Converts all instances of a number of spaces equal to a tab size
	 * into a tab in this text area.
	 *
	 * @see #convertTabsToSpaces
	 * @see #getTabsEmulated
	 * @see #setTabsEmulated
	 */
	public void convertSpacesToTabs() {

		// FIXME:  This is inefficient and will yield an OutOfMemoryError if
		// done on a large document.  We should scan 1 line at a time and
		// replace; it'll be slower but safer.

		int caretPosition = getCaretPosition();
		int tabSize = getTabSize();
		String tabInSpaces = "";
		for (int i=0; i<tabSize; i++)
			tabInSpaces += " ";
		String text = getText();
		setText(text.replaceAll(tabInSpaces, "\t"));
		int newDocumentLength = getDocument().getLength();

		// Place the caret back in its proper position.
		if (caretPosition<newDocumentLength)
			setCaretPosition(caretPosition);
		else
			setCaretPosition(newDocumentLength-1);

	}

	/**
	 * Converts all instances of a tab into a number of spaces equivalent
	 * to a tab in this text area.
	 *
	 * @see #convertSpacesToTabs
	 * @see #getTabsEmulated
	 * @see #setTabsEmulated
	 */
	public void convertTabsToSpaces() {

		// FIXME:  This is inefficient and will yield an OutOfMemoryError if
		// done on a large document.  We should scan 1 line at a time and
		// replace; it'll be slower but safer.

		int caretPosition = getCaretPosition();
		int tabSize = getTabSize();
		StringBuilder tabInSpaces = new StringBuilder();
		for (int i=0; i<tabSize; i++)
			tabInSpaces.append(' ');
		String text = getText();
		setText(text.replaceAll("\t", tabInSpaces.toString()));

		// Put caret back at same place in document.
		setCaretPosition(caretPosition);

	}

	/**
	 * Returns the caret event/mouse listener for RTextAreas.
	 *
	 * @return The caret event/mouse listener.
	 */
	protected abstract RTAMouseListener createMouseListener();

	/**
	 * Returns the a real UI to install on this text component.  Subclasses
	 * can override this method to return an extended version of
	 * RTextAreaUI.
	 *
	 * @return The UI.
	 */
	protected abstract RTextAreaUI createRTextAreaUI();

	/**
	 * Forces the current line highlight to be repainted.  This hack is
	 * necessary for those situations when the view (appearance) changes
	 * but the caret's location hasn't (and thus the current line highlight
	 * coordinates won't get changed).  Examples of this are when
	 * word wrap is toggled and when syntax styles are changed in an
	 * RSyntaxTextArea.
	 */
	protected void forceCurrentLineHighlightRepaint() {
		// Check isShowing() to prevent BadLocationException
		// in constructor if linewrap is set to true.
		if (isShowing()) {
			// Changing previousCaretY makes us sure to get a repaint.
			previousCaretY = -1;
			// Trick it into checking for the need to repaint by firing
			// a false caret event.
			fireCaretUpdate(mouseListener);
		}
	}

	/**
	 * Returns the java.awt.Color used as the background color for
	 * this text area.  If a java.awt.Image image is currently
	 * being used instead, null is returned.
	 *
	 * @return The current background color, or null if an image
	 *         is currently the background.
	 */
	@Override
	public final Color getBackground() {
		Object bg = getBackgroundObject();
		return (bg instanceof Color) ? (Color)bg : null;
	}

	/**
	 * Returns the image currently used for the background.
	 * If the current background is currently a java.awt.Color and
	 * not a java.awt.Image, then null is returned.
	 *
	 * @return A java.awt.Image used for the background, or
	 *         null if the background is not an image.
	 * @see #setBackgroundImage
	 */
	public final Image getBackgroundImage() {
		Object bg = getBackgroundObject();
		return (bg instanceof Image) ? (Image)bg : null;
	}

	/**
	 * Returns the Object representing the background for all
	 * documents in this tabbed pane; either a java.awt.Color or a
	 * java.lang.Image containing the image used as the background
	 * for this text area.
	 *
	 * @return The Object used for the background.
	 * @see #setBackgroundObject(Object newBackground)
	 */
	public final Object getBackgroundObject() {
		if (backgroundPainter==null)
			return null;
		return (backgroundPainter instanceof ImageBackgroundPainterStrategy) ?
			(Object)((ImageBackgroundPainterStrategy)backgroundPainter).
					getMasterImage() :
			(Object)((ColorBackgroundPainterStrategy)backgroundPainter).
					getColor();
	}

	/**
	 * Gets the line number that the caret is on.
	 *
	 * @return The zero-based line number that the caret is on.
	 */
	public final int getCaretLineNumber() {
		try {
			return getLineOfOffset(getCaretPosition());
		} catch (BadLocationException ble) {
			return 0; // Never happens
		}
	}

	/**
	 * Gets the position from the beginning of the current line that the caret
	 * is on.
	 *
	 * @return The zero-based position from the beginning of the current line
	 *         that the caret is on.
	 */
	public final int getCaretOffsetFromLineStart() {
		try {
			int pos = getCaretPosition();
			return pos - getLineStartOffset(getLineOfOffset(pos));
		} catch (BadLocationException ble) {
			return 0; // Never happens
		}
	}

	/**
	 * Returns the color being used to highlight the current line.  Note that
	 * if highlighting the current line is turned off, you will not be seeing
	 * this highlight.
	 *
	 * @return The color being used to highlight the current line.
	 * @see #getHighlightCurrentLine()
	 * @see #setHighlightCurrentLine(boolean)
	 * @see #setCurrentLineHighlightColor
	 */
	public Color getCurrentLineHighlightColor() {
		return currentLineColor;
	}

	/**
	 * Returns the default caret color.
	 *
	 * @return The default caret color.
	 */
	public static final Color getDefaultCaretColor() {
		return DEFAULT_CARET_COLOR;
	}

	/**
	 * Returns the "default" color for highlighting the current line.  Note
	 * that this color was chosen only because it looks nice (to me) against a
	 * white background.
	 *
	 * @return The default color for highlighting the current line.
	 */
	public static final Color getDefaultCurrentLineHighlightColor() {
		return DEFAULT_CURRENT_LINE_HIGHLIGHT_COLOR;
	}

	/**
	 * Returns the default font for text areas.
	 *
	 * @return The default font.
	 */
	public static final Font getDefaultFont() {

		// Use StyleContext to get a composite font for better Asian language
		// support; see Sun bug S282887.
		StyleContext sc = StyleContext.getDefaultStyleContext();
		Font font = null;

		if (isOSX()) {
			// Snow Leopard (1.6) uses Menlo as default monospaced font,
			// pre-Snow Leopard used Monaco.
			font = sc.getFont("Menlo", Font.PLAIN, 12);
			if (!"Menlo".equals(font.getFamily())) {
				font = sc.getFont("Monaco", Font.PLAIN, 12);
				if (!"Monaco".equals(font.getFamily())) { // Shouldn't happen
					font = sc.getFont("Monospaced", Font.PLAIN, 13);
				}
			}
		}
		else {
			// Consolas added in Vista, used by VS2010+.
			font = sc.getFont("Consolas", Font.PLAIN, 13);
			if (!"Consolas".equals(font.getFamily())) {
				font = sc.getFont("Monospaced", Font.PLAIN, 13);
			}
		}

		//System.out.println(font.getFamily() + ", " + font.getName());
		return font;

	}

	/**
	 * Returns the default foreground color for text in this text area.
	 *
	 * @return The default foreground color.
	 */
	public static final Color getDefaultForeground() {
		return Color.BLACK;
	}

	/**
	 * Returns the default color for the margin line.
	 *
	 * @return The default margin line color.
	 * @see #getMarginLineColor()
	 * @see #setMarginLineColor(Color)
	 */
	public static final Color getDefaultMarginLineColor() {
		return DEFAULT_MARGIN_LINE_COLOR;
	}

	/**
	 * Returns the default margin line position.
	 *
	 * @return The default margin line position.
	 * @see #getMarginLinePosition
	 * @see #setMarginLinePosition
	 */
	public static final int getDefaultMarginLinePosition() {
		return DEFAULT_MARGIN_LINE_POSITION;
	}

	/**
	 * Returns the default tab size, in spaces.
	 *
	 * @return The default tab size.
	 */
	public static final int getDefaultTabSize() {
		return DEFAULT_TAB_SIZE;
	}

	/**
	 * Returns whether the current line highlight is faded.
	 *
	 * @return Whether the current line highlight is faded.
	 * @see #setFadeCurrentLineHighlight
	 */
	public boolean getFadeCurrentLineHighlight() {
		return fadeCurrentLineHighlight;
	}

	/**
	 * Returns whether or not the current line is highlighted.
	 *
	 * @return Whether or the current line is highlighted.
	 * @see #setHighlightCurrentLine(boolean)
	 * @see #getCurrentLineHighlightColor
	 * @see #setCurrentLineHighlightColor
	 */
	public boolean getHighlightCurrentLine() {
		return highlightCurrentLine;
	}

	/**
	 * Returns the offset of the last character of the line that the caret is
	 * on.
	 *
	 * @return The last offset of the line that the caret is currently on.
	 */
	public final int getLineEndOffsetOfCurrentLine() {
		try {
			return getLineEndOffset(getCaretLineNumber());
		} catch (BadLocationException ble) {
			return 0; // Never happens
		}
	}

	/**
	 * Returns the height of a line of text in this text area.
	 *
	 * @return The height of a line of text.
	 */
	public int getLineHeight() {
		return getRowHeight();
	}

	/**
	 * Returns the offset of the first character of the line that the caret is
	 * on.
	 *
	 * @return The first offset of the line that the caret is currently on.
	 */
	public final int getLineStartOffsetOfCurrentLine() {
		try {
			return getLineStartOffset(getCaretLineNumber());
		} catch (BadLocationException ble) {
			return 0; // Never happens
		}
	}

	/**
	 * Returns the color used to paint the margin line.
	 *
	 * @return The margin line color.
	 * @see #setMarginLineColor(Color)
	 */
	public Color getMarginLineColor() {
		return marginLineColor;
	}

	/**
	 * Returns the margin line position (in pixels) from the left-hand side of
	 * the text area.
	 *
	 * @return The margin line position.
	 * @see #getDefaultMarginLinePosition
	 * @see #setMarginLinePosition
	 */
	public int getMarginLinePixelLocation() {
		return marginLineX;
	}

	/**
	 * Returns the margin line position (which is the number of 'm' widths in
	 * the current font the margin line is over).
	 *
	 * @return The margin line position.
	 * @see #getDefaultMarginLinePosition
	 * @see #setMarginLinePosition
	 */
	public int getMarginLinePosition() {
		return marginSizeInChars;
	}

	/**
	 * Returns whether selection edges are rounded in this text area.
	 *
	 * @return Whether selection edges are rounded.
	 * @see #setRoundedSelectionEdges(boolean)
	 */
	public boolean getRoundedSelectionEdges() {
		return roundedSelectionEdges;
	}

	/**
	 * Returns whether or not tabs are emulated with spaces (i.e., "soft"
	 * tabs).
	 *
	 * @return true if tabs are emulated with spaces;
	 *         false if they aren't.
	 * @see #setTabsEmulated
	 */
	public boolean getTabsEmulated() {
		return tabsEmulatedWithSpaces;
	}

	/**
	 * Initializes this text area.
	 */
	protected void init() {

		// Sets the UI.  Note that setUI() is overridden in RTextArea to only
		// update the popup menu; this method must be called to set the real
		// UI.  This is done because the look and feel of an RTextArea is
		// independent of the installed Java look and feels.
		setRTextAreaUI(createRTextAreaUI());

		// So we get notified when the component is resized.
		enableEvents(AWTEvent.COMPONENT_EVENT_MASK|AWTEvent.KEY_EVENT_MASK);

		// Defaults for various properties.
		setHighlightCurrentLine(true);
		setCurrentLineHighlightColor(getDefaultCurrentLineHighlightColor());
		setMarginLineEnabled(false);
		setMarginLineColor(getDefaultMarginLineColor());
		setMarginLinePosition(getDefaultMarginLinePosition());
		setBackgroundObject(Color.WHITE);
		setWrapStyleWord(true);// We only support wrapping at word boundaries.
		setTabSize(5);
		setForeground(Color.BLACK);
		setTabsEmulated(false);

		// Stuff needed by the caret listener below.
		previousCaretY = currentCaretY = getInsets().top;

		// Stuff to highlight the current line.
		mouseListener = createMouseListener();
		// Also acts as a focus listener so we can update our shared actions
		// (cut, copy, etc. on the popup menu).
		addFocusListener(mouseListener);
		addCurrentLineHighlightListeners();

	}

	/**
	 * Returns whether or not the margin line is being painted.
	 *
	 * @return Whether or not the margin line is being painted.
	 * @see #setMarginLineEnabled
	 */
	public boolean isMarginLineEnabled() {
		return marginLineEnabled;
	}

	/**
	 * Returns whether the OS we're running on is OS X.
	 *
	 * @return Whether the OS we're running on is OS X.
	 */
	public static boolean isOSX() {
		// Recommended at:
		// http://developer.apple.com/mac/library/technotes/tn2002/tn2110.html
		String osName = System.getProperty("os.name").toLowerCase();
		return osName.startsWith("mac os x");
	}

	/**
	 * Paints the text area.
	 *
	 * @param g The graphics context with which to paint.
	 */
	@Override
	protected void paintComponent(Graphics g) {

		//long startTime = System.currentTimeMillis();

		backgroundPainter.paint(g, getVisibleRect());

		// Paint the main part of the text area.
		TextUI ui = getUI();
		if (ui != null) {
			// Not allowed to modify g, so make a copy.
			Graphics scratchGraphics = g.create();
			try {
				ui.update(scratchGraphics, this);
			} finally {
				scratchGraphics.dispose();
			}
		}

		//long endTime = System.currentTimeMillis();
		//System.err.println(endTime-startTime);

	}

	/**
	 * Updates the current line highlight location.
	 */
	protected void possiblyUpdateCurrentLineHighlightLocation() {

		int width = getWidth();
		int lineHeight = getLineHeight();
		int dot = getCaretPosition();

		// If we're wrapping lines we need to check the actual y-coordinate
		// of the caret, not just the line number, since a single logical
		// line can span multiple physical lines.
		if (getLineWrap()) {
			try {
				Rectangle temp = modelToView(dot);
				if (temp!=null) {
					currentCaretY = temp.y;
				}
			} catch (BadLocationException ble) {
				ble.printStackTrace(); // Should never happen.
			}
		}

		// No line wrap - we can simply check the line number (quicker).
		else {
//			Document doc = getDocument();
//			if (doc!=null) {
//				Element map = doc.getDefaultRootElement();
//				int caretLine = map.getElementIndex(dot);
//				Rectangle alloc = ((RTextAreaUI)getUI()).
//											getVisibleEditorRect();
//				if (alloc!=null)
//					currentCaretY = alloc.y + caretLine*lineHeight;
//			}
// Modified for code folding requirements
try {
	Rectangle temp = modelToView(dot);
	if (temp!=null) {
		currentCaretY = temp.y;
	}
} catch (BadLocationException ble) {
	ble.printStackTrace(); // Should never happen.
}
		}

		// Repaint current line (to fill in entire highlight), and old line
		// (to erase entire old highlight) if necessary.  Always repaint
		// current line in case selection is added or removed.
		repaint(0,currentCaretY, width,lineHeight);
		if (previousCaretY!=currentCaretY) {
			repaint(0,previousCaretY, width,lineHeight);
		}

		previousCaretY = currentCaretY;

	}

	/**
	 * Overridden so we can tell when the text area is resized and update the
	 * current-line highlight, if necessary (i.e., if it is enabled and if
	 * lineWrap is enabled.
	 *
	 * @param e The component event about to be sent to all registered
	 *        ComponentListeners.
	 */
	@Override
	protected void processComponentEvent(ComponentEvent e) {

		// In line wrap mode, resizing the text area means that the caret's
		// "line" could change - not to a different logical line, but a
		// different physical one.  So, here we force a repaint of the current
		// line's highlight if necessary.
		if (e.getID()==ComponentEvent.COMPONENT_RESIZED &&
				getLineWrap()==true && getHighlightCurrentLine()) {
			previousCaretY = -1;  // So we are sure to repaint.
			fireCaretUpdate(mouseListener);
		}

		super.processComponentEvent(e);

	}

	/**
	 * Sets the background color of this text editor.  Note that this is
	 * equivalent to calling setBackgroundObject(bg).
	 *
	 * NOTE:  the opaque property is set to true when the
	 * background is set to a color (by this method).  When an image is used
	 * for the background, opaque is set to false.  This is because
	 * we perform better when setOpaque is true, but if we use an
	 * image for the background when opaque is true, we get on-screen
	 * garbage when the user scrolls via the arrow keys.  Thus we
	 * need setOpaque to be false in that case.

	 * You never have to change the opaque property yourself; it is always done
	 * for you.
	 *
	 * @param bg The color to use as the background color.
	 */
	@Override
	public void setBackground(Color bg) {
		Object oldBG = getBackgroundObject();
		if (oldBG instanceof Color) { // Just change color of strategy.
			((ColorBackgroundPainterStrategy)backgroundPainter).
						setColor(bg);
		}
		else { // Was an image painter...
			backgroundPainter = new ColorBackgroundPainterStrategy(bg);
		}
		setOpaque(true);
		firePropertyChange("background", oldBG, bg);
		repaint();
	}

	/**
	 * Sets this image as the background image.  This method fires a
	 * property change event of type {@link #BACKGROUND_IMAGE_PROPERTY}.

	 *
	 * NOTE:  the opaque property is set to true when the
	 * background is set to a color.  When an image is used for the
	 * background (by this method), opaque is set to false.  This is because
	 * we perform better when setOpaque is true, but if we use an
	 * image for the background when opaque is true, we get on-screen
	 * garbage when the user scrolls via the arrow keys.  Thus we
	 * need setOpaque to be false in that case.

	 * You never have to change the opaque property yourself; it is always done
	 * for you.
	 *
	 * @param image The image to use as this text area's background.
	 * @see #getBackgroundImage
	 */
	public void setBackgroundImage(Image image) {
		Object oldBG = getBackgroundObject();
		if (oldBG instanceof Image) { // Just change image being displayed.
			((ImageBackgroundPainterStrategy)backgroundPainter).
					setImage(image);
		}
		else { // Was a color strategy...
			ImageBackgroundPainterStrategy strategy =
				new BufferedImageBackgroundPainterStrategy(this);
			strategy.setImage(image);
			backgroundPainter = strategy;
		}
		setOpaque(false);
		firePropertyChange(BACKGROUND_IMAGE_PROPERTY, oldBG, image);
		repaint();
	}

	/**
	 * Makes the background into this Object.
	 *
	 * @param newBackground The java.awt.Color or
	 *        java.awt.Image object. If newBackground
	 *        is not either of these, the background is set to plain white.
	 */
	public void setBackgroundObject(Object newBackground) {
		if (newBackground instanceof Color) {
			setBackground((Color)newBackground);
		}
		else if (newBackground instanceof Image) {
			setBackgroundImage((Image)newBackground);
		}
		else {
			setBackground(Color.WHITE);
		}

	}

	/*
	 * TODO: Figure out why RTextArea doesn't work with RTL (e.g. Arabic)
	 * and fix it!
	 */
//	public void setComponentOrientation(ComponentOrientation o) {
//		if (!o.isLeftToRight()) {
//			o = ComponentOrientation.LEFT_TO_RIGHT;
//		}
//		super.setComponentOrientation(o);
//	}

	/**
	 * Sets the color to use to highlight the current line.  Note that if
	 * highlighting the current line is turned off, you will not be able to
	 * see this highlight.  This method fires a property change of type
	 * {@link #CURRENT_LINE_HIGHLIGHT_COLOR_PROPERTY}.
	 *
	 * @param color The color to use to highlight the current line.
	 * @throws NullPointerException if color is null.
	 * @see #getHighlightCurrentLine()
	 * @see #setHighlightCurrentLine(boolean)
	 * @see #getCurrentLineHighlightColor
	 */
	public void setCurrentLineHighlightColor(Color color) {
		if (color==null)
			throw new NullPointerException();
		if (!color.equals(currentLineColor)) {
			Color old = currentLineColor;
			currentLineColor = color;
			firePropertyChange(CURRENT_LINE_HIGHLIGHT_COLOR_PROPERTY,
							old, color);
		}
	}

	/**
	 * Sets whether the current line highlight should have a "fade" effect.
	 * This method fires a property change event of type
	 * CURRENT_LINE_HIGHLIGHT_FADE_PROPERTY.
	 *
	 * @param fade Whether the fade effect should be enabled.
	 * @see #getFadeCurrentLineHighlight
	 */
	public void setFadeCurrentLineHighlight(boolean fade) {
		if (fade!=fadeCurrentLineHighlight) {
			fadeCurrentLineHighlight = fade;
			if (getHighlightCurrentLine())
				forceCurrentLineHighlightRepaint();
			firePropertyChange(CURRENT_LINE_HIGHLIGHT_FADE_PROPERTY,
							!fade, fade);
		}
	}

	/**
	 * Sets the font for this text area.  This is overridden only so that we
	 * can update the size of the "current line highlight" and the location of
	 * the "margin line," if necessary.
	 *
	 * @param font The font to use for this text component.
	 */
	@Override
	public void setFont(Font font) {
		super.setFont(font);
		updateMarginLineX();
		if (highlightCurrentLine)
			possiblyUpdateCurrentLineHighlightLocation();
	}

	/**
	 * Sets whether or not the current line is highlighted.  This method
	 * fires a property change of type {@link #HIGHLIGHT_CURRENT_LINE_PROPERTY}.
	 *
	 * @param highlight Whether or not to highlight the current line.
	 * @see #getHighlightCurrentLine()
	 * @see #getCurrentLineHighlightColor
	 * @see #setCurrentLineHighlightColor
	 */
	public void setHighlightCurrentLine(boolean highlight) {
		if (highlight!=highlightCurrentLine) {
			highlightCurrentLine = highlight;
			firePropertyChange(HIGHLIGHT_CURRENT_LINE_PROPERTY,
							!highlight, highlight);
			repaint(); // Repaint entire width of line.
		}
	}

	/**
	 * Sets whether or not word wrap is enabled.  This is overridden so that
	 * the "current line highlight" gets updated if it needs to be.
	 *
	 * @param wrap Whether or not word wrap should be enabled.
	 */
	@Override
	public void setLineWrap(boolean wrap) {
		super.setLineWrap(wrap);
		forceCurrentLineHighlightRepaint();
	}

	/**
	 * Overridden to update the current line highlight location.
	 *
	 * @param insets The new insets.
	 */
	@Override
	public void setMargin(Insets insets) {
		Insets old = getInsets();
		int oldTop = old!=null ? old.top : 0;
		int newTop = insets!=null ? insets.top : 0;
		if (oldTop!=newTop) {
			// The entire editor will be automatically repainted if it is
			// visible, so no need to call repaint() or forceCurrentLine...().
			previousCaretY = currentCaretY = newTop;
		}
		super.setMargin(insets);
	}

	/**
	 * Sets the color used to paint the margin line.
	 *
	 * @param color The new margin line color.
	 * @see #getDefaultMarginLineColor()
	 * @see #getMarginLineColor()
	 */
	public void setMarginLineColor(Color color) {
		marginLineColor = color;
		if (marginLineEnabled) {
			Rectangle visibleRect = getVisibleRect();
			repaint(marginLineX,visibleRect.y, 1,visibleRect.height);
		}
	}

	/**
	 * Enables or disables the margin line.
	 *
	 * @param enabled Whether or not the margin line should be enabled.
	 * @see #isMarginLineEnabled
	 */
	public void setMarginLineEnabled(boolean enabled) {
		if (enabled!=marginLineEnabled) {
			marginLineEnabled = enabled;
			if (marginLineEnabled) {
				Rectangle visibleRect = getVisibleRect();
				repaint(marginLineX,visibleRect.y, 1,visibleRect.height);
			}
		}
	}

	/**
	 * Sets the number of 'm' widths the margin line is over.
	 *
	 * @param size The margin size.
	 * #see #getDefaultMarginLinePosition
	 * @see #getMarginLinePosition
	 */
	public void setMarginLinePosition(int size) {
		marginSizeInChars = size;
		if (marginLineEnabled) {
			Rectangle visibleRect = getVisibleRect();
			repaint(marginLineX,visibleRect.y, 1,visibleRect.height);
			updateMarginLineX();
			repaint(marginLineX,visibleRect.y, 1,visibleRect.height);
		}
	}

	/**
	 * Sets whether the edges of selections are rounded in this text area.
	 * This method fires a property change of type
	 * {@link #ROUNDED_SELECTION_PROPERTY}.
	 *
	 * @param rounded Whether selection edges should be rounded.
	 * @see #getRoundedSelectionEdges()
	 */
	public void setRoundedSelectionEdges(boolean rounded) {
		if (roundedSelectionEdges!=rounded) {
			roundedSelectionEdges = rounded;
			Caret c = getCaret();
			if (c instanceof ConfigurableCaret) {
				((ConfigurableCaret)c).setRoundedSelectionEdges(rounded);
				if (c.getDot()!=c.getMark()) { // e.g., there's is a selection
					repaint();
				}
			}
			firePropertyChange(ROUNDED_SELECTION_PROPERTY, !rounded,
											rounded);
		}
	}

	/**
	 * Sets the UI for this RTextArea.  Note that, for instances
	 * of RTextArea, setUI only updates the popup
	 * menu; this is because RTextAreas' look and feels are
	 * independent of the Java Look and Feel.  This method is here so
	 * subclasses can set a UI (subclass of RTextAreaUI) if they
	 * have to.
	 *
	 * @param ui The new UI.
	 * @see #setUI
	 */
	protected void setRTextAreaUI(RTextAreaUI ui) {

		super.setUI(ui);

		// Workaround as setUI makes the text area opaque, even if we don't
		// want it to be.
		setOpaque(getBackgroundObject() instanceof Color);

	}

	/**
	 * Changes whether or not tabs should be emulated with spaces (i.e., soft
	 * tabs).  Note that this affects all tabs inserted AFTER this call, not
	 * tabs already in the document.  For that, see
	 * {@link #convertTabsToSpaces} and {@link #convertSpacesToTabs}.
	 *
	 * @param areEmulated Whether or not tabs should be emulated with spaces.
	 * @see #convertSpacesToTabs
	 * @see #convertTabsToSpaces
	 * @see #getTabsEmulated
	 */
	public void setTabsEmulated(boolean areEmulated) {
		tabsEmulatedWithSpaces = areEmulated;
	}

	/**
	 * Workaround, since in JDK1.4 it appears that setTabSize()
	 * doesn't work for a JTextArea unless you use the constructor
	 * specifying the number of rows and columns...

	 * Sets the number of characters to expand tabs to. This will be multiplied
	 * by the maximum advance for variable width fonts. A PropertyChange event
	 * ("tabSize") is fired when the tab size changes.
	 *
	 * @param size Number of characters to expand to.
	 */
	@Override
	public void setTabSize(int size) {
		super.setTabSize(size);
		boolean b = getLineWrap();
		setLineWrap(!b);
		setLineWrap(b);
	}

	/**
	 * This is here so subclasses such as RSyntaxTextArea that
	 * have multiple fonts can define exactly what it means, for example, for
	 * the margin line to be "80 characters" over.
	 */
	protected void updateMarginLineX() {
		marginLineX = getFontMetrics(getFont()).charWidth('m') *
												marginSizeInChars;
	}

	/**
	 * Returns the y-coordinate of the specified line.
	 *
	 * @param line The line number.
	 * @return The y-coordinate of the top of the line, or -1 if
	 *         this text area doesn't yet have a positive size or the line is
	 *         hidden (i.e. from folding).
	 * @throws BadLocationException If line isn't a valid line
	 *         number for this document.
	 */
	public int yForLine(int line) throws BadLocationException {
		return ((RTextAreaUI)getUI()).yForLine(line);
	}

	/**
	 * Returns the y-coordinate of the line containing an offset.
	 *
	 * @param offs The offset info the document.
	 * @return The y-coordinate of the top of the offset, or -1 if
	 *         this text area doesn't yet have a positive size or the line is
	 *         hidden (i.e. from folding).
	 * @throws BadLocationException If offs isn't a valid offset
	 *         into the document.
	 */
	public int yForLineContaining(int offs) throws BadLocationException {
		return ((RTextAreaUI)getUI()).yForLineContaining(offs);
	}

	protected class RTAMouseListener extends CaretEvent implements
					MouseListener, MouseMotionListener, FocusListener {

		RTAMouseListener(RTextAreaBase textArea) {
			super(textArea);
		}

		public void focusGained(FocusEvent e) {}
		public void focusLost(FocusEvent e) {}
		public void mouseDragged(MouseEvent e) {}
		public void mouseMoved(MouseEvent e) {}
		public void mouseClicked(MouseEvent e) {}
		public void mousePressed(MouseEvent e) {}
		public void mouseReleased(MouseEvent e) {}
		public void mouseEntered(MouseEvent e) {}
		public void mouseExited(MouseEvent e) {}

		@Override
		public int getDot() {
			return dot;
		}

		@Override
		public int getMark() {
			return mark;
		}

		protected int dot;
		protected int mark;

	}

}


text:
namespace treeDiM.StackBuilder.TechnologyBSA_ASPNET
{
    public class LayerDataShort
    {
        public LayerDataShort(string name, int layerIndex, bool hasInterlayer)
        {
            Name = name;
            LayerIndex = layerIndex;
            HasInterlayer = hasInterlayer;
        }
        public string Name { get; set; }
        public int LayerIndex { get; set; }
        public bool HasInterlayer { get; set; }
    }
}


text:
package MyXDR

import (
  "bytes"
  "encoding"
  "io"
  "fmt"

  "github.com/stellar/go-xdr/xdr3"
)

// XdrFilesSHA256 is the SHA256 hashes of source files.
var XdrFilesSHA256 = map[string]string{
  "spec/fixtures/generator/nesting.x": "5537949272c11f1bd09cf613a3751668b5018d686a1c2aaa3baa91183ca18f6a",
}

type xdrType interface {
  xdrType()
}

type decoderFrom interface {
  DecodeFrom(d *xdr.Decoder) (int, error)
}

// Unmarshal reads an xdr element from `r` into `v`.
func Unmarshal(r io.Reader, v interface{}) (int, error) {
  if decodable, ok := v.(decoderFrom); ok {
    d := xdr.NewDecoder(r)
    return decodable.DecodeFrom(d)
  }
  // delegate to xdr package's Unmarshal
	return xdr.Unmarshal(r, v)
}

// Marshal writes an xdr element `v` into `w`.
func Marshal(w io.Writer, v interface{}) (int, error) {
  if _, ok := v.(xdrType); ok {
    if bm, ok := v.(encoding.BinaryMarshaler); ok {
      b, err := bm.MarshalBinary()
      if err != nil {
        return 0, err
      }
      return w.Write(b)
    }
  }
  // delegate to xdr package's Marshal
  return xdr.Marshal(w, v)
}

// UnionKey is an XDR Enum defines as:
//
//   enum UnionKey {
//      ONE = 1,
//      TWO = 2,
//      OFFER = 3
//    };
//
type UnionKey int32
const (
  UnionKeyOne UnionKey = 1
  UnionKeyTwo UnionKey = 2
  UnionKeyOffer UnionKey = 3
)
var unionKeyMap = map[int32]string{
  1: "UnionKeyOne",
  2: "UnionKeyTwo",
  3: "UnionKeyOffer",
}

// ValidEnum validates a proposed value for this enum.  Implements
// the Enum interface for UnionKey
func (e UnionKey) ValidEnum(v int32) bool {
  _, ok := unionKeyMap[v]
  return ok
}
// String returns the name of `e`
func (e UnionKey) String() string {
  name, _ := unionKeyMap[int32(e)]
  return name
}

// EncodeTo encodes this value using the Encoder.
func (e UnionKey) EncodeTo(enc *xdr.Encoder) error {
  if _, ok := unionKeyMap[int32(e)]; !ok {
    return fmt.Errorf("'%d' is not a valid UnionKey enum value", e)
  }
  _, err := enc.EncodeInt(int32(e))
  return err
}
var _ decoderFrom = (*UnionKey)(nil)
// DecodeFrom decodes this value using the Decoder.
func (e *UnionKey) DecodeFrom(d *xdr.Decoder) (int, error) {
  v, n, err := d.DecodeInt()
  if err != nil {
    return n, fmt.Errorf("decoding UnionKey: %s", err)
  }
  if _, ok := unionKeyMap[v]; !ok {
    return n, fmt.Errorf("'%d' is not a valid UnionKey enum value", v)
  }
  *e = UnionKey(v)
  return n, nil
}
// MarshalBinary implements encoding.BinaryMarshaler.
func (s UnionKey) MarshalBinary() ([]byte, error) {
  b := bytes.Buffer{}
  e := xdr.NewEncoder(&b)
  err := s.EncodeTo(e)
  return b.Bytes(), err
}

// UnmarshalBinary implements encoding.BinaryUnmarshaler.
func (s *UnionKey) UnmarshalBinary(inp []byte) error {
  r := bytes.NewReader(inp)
  d := xdr.NewDecoder(r)
  _, err := s.DecodeFrom(d)
  return err
}

var (
  _ encoding.BinaryMarshaler   = (*UnionKey)(nil)
  _ encoding.BinaryUnmarshaler = (*UnionKey)(nil)
)

// xdrType signals that this type is an type representing
// representing XDR values defined by this package.
func (s UnionKey) xdrType() {}

var _ xdrType = (*UnionKey)(nil)

// Foo is an XDR Typedef defines as:
//
//   typedef int Foo;
//
type Foo int32

// EncodeTo encodes this value using the Encoder.
func (s Foo) EncodeTo(e *xdr.Encoder) error {
  var err error
if _, err = e.EncodeInt(int32(s)); err != nil {
  return err
}
  return nil
}

var _ decoderFrom = (*Foo)(nil)
// DecodeFrom decodes this value using the Decoder.
func (s *Foo) DecodeFrom(d *xdr.Decoder) (int, error) {
  var err error
  var n, nTmp int
  var v int32
  v, nTmp, err = d.DecodeInt()
n += nTmp
if err != nil {
  return n, fmt.Errorf("decoding Int: %s", err)
}
  *s = Foo(v)
  return n, nil
}

// MarshalBinary implements encoding.BinaryMarshaler.
func (s Foo) MarshalBinary() ([]byte, error) {
  b := bytes.Buffer{}
  e := xdr.NewEncoder(&b)
  err := s.EncodeTo(e)
  return b.Bytes(), err
}

// UnmarshalBinary implements encoding.BinaryUnmarshaler.
func (s *Foo) UnmarshalBinary(inp []byte) error {
  r := bytes.NewReader(inp)
  d := xdr.NewDecoder(r)
  _, err := s.DecodeFrom(d)
  return err
}

var (
  _ encoding.BinaryMarshaler   = (*Foo)(nil)
  _ encoding.BinaryUnmarshaler = (*Foo)(nil)
)

// xdrType signals that this type is an type representing
// representing XDR values defined by this package.
func (s Foo) xdrType() {}

var _ xdrType = (*Foo)(nil)

// MyUnionOne is an XDR NestedStruct defines as:
//
//   struct {
//                int someInt;
//            }
//
type MyUnionOne struct {
  SomeInt int32
}

// EncodeTo encodes this value using the Encoder.
func (s *MyUnionOne) EncodeTo(e *xdr.Encoder) error {
  var err error
if _, err = e.EncodeInt(int32(s.SomeInt)); err != nil {
  return err
}
  return nil
}

var _ decoderFrom = (*MyUnionOne)(nil)
// DecodeFrom decodes this value using the Decoder.
func (s *MyUnionOne) DecodeFrom(d *xdr.Decoder) (int, error) {
  var err error
  var n, nTmp int
  s.SomeInt, nTmp, err = d.DecodeInt()
n += nTmp
if err != nil {
  return n, fmt.Errorf("decoding Int: %s", err)
}
  return n, nil
}

// MarshalBinary implements encoding.BinaryMarshaler.
func (s MyUnionOne) MarshalBinary() ([]byte, error) {
  b := bytes.Buffer{}
  e := xdr.NewEncoder(&b)
  err := s.EncodeTo(e)
  return b.Bytes(), err
}

// UnmarshalBinary implements encoding.BinaryUnmarshaler.
func (s *MyUnionOne) UnmarshalBinary(inp []byte) error {
  r := bytes.NewReader(inp)
  d := xdr.NewDecoder(r)
  _, err := s.DecodeFrom(d)
  return err
}

var (
  _ encoding.BinaryMarshaler   = (*MyUnionOne)(nil)
  _ encoding.BinaryUnmarshaler = (*MyUnionOne)(nil)
)

// xdrType signals that this type is an type representing
// representing XDR values defined by this package.
func (s MyUnionOne) xdrType() {}

var _ xdrType = (*MyUnionOne)(nil)

// MyUnionTwo is an XDR NestedStruct defines as:
//
//   struct {
//                int someInt;
//                Foo foo;
//            }
//
type MyUnionTwo struct {
  SomeInt int32
  Foo Foo
}

// EncodeTo encodes this value using the Encoder.
func (s *MyUnionTwo) EncodeTo(e *xdr.Encoder) error {
  var err error
if _, err = e.EncodeInt(int32(s.SomeInt)); err != nil {
  return err
}
if   err = s.Foo.EncodeTo(e); err != nil {
  return err
}
  return nil
}

var _ decoderFrom = (*MyUnionTwo)(nil)
// DecodeFrom decodes this value using the Decoder.
func (s *MyUnionTwo) DecodeFrom(d *xdr.Decoder) (int, error) {
  var err error
  var n, nTmp int
  s.SomeInt, nTmp, err = d.DecodeInt()
n += nTmp
if err != nil {
  return n, fmt.Errorf("decoding Int: %s", err)
}
  nTmp, err = s.Foo.DecodeFrom(d)
n += nTmp
if err != nil {
  return n, fmt.Errorf("decoding Foo: %s", err)
}
  return n, nil
}

// MarshalBinary implements encoding.BinaryMarshaler.
func (s MyUnionTwo) MarshalBinary() ([]byte, error) {
  b := bytes.Buffer{}
  e := xdr.NewEncoder(&b)
  err := s.EncodeTo(e)
  return b.Bytes(), err
}

// UnmarshalBinary implements encoding.BinaryUnmarshaler.
func (s *MyUnionTwo) UnmarshalBinary(inp []byte) error {
  r := bytes.NewReader(inp)
  d := xdr.NewDecoder(r)
  _, err := s.DecodeFrom(d)
  return err
}

var (
  _ encoding.BinaryMarshaler   = (*MyUnionTwo)(nil)
  _ encoding.BinaryUnmarshaler = (*MyUnionTwo)(nil)
)

// xdrType signals that this type is an type representing
// representing XDR values defined by this package.
func (s MyUnionTwo) xdrType() {}

var _ xdrType = (*MyUnionTwo)(nil)

// MyUnion is an XDR Union defines as:
//
//   union MyUnion switch (UnionKey type)
//    {
//        case ONE:
//            struct {
//                int someInt;
//            } one;
//
//        case TWO:
//            struct {
//                int someInt;
//                Foo foo;
//            } two;
//
//        case OFFER:
//            void;
//    };
//
type MyUnion struct{
  Type UnionKey
  One *MyUnionOne
  Two *MyUnionTwo
}

// SwitchFieldName returns the field name in which this union's
// discriminant is stored
func (u MyUnion) SwitchFieldName() string {
  return "Type"
}

// ArmForSwitch returns which field name should be used for storing
// the value for an instance of MyUnion
func (u MyUnion) ArmForSwitch(sw int32) (string, bool) {
switch UnionKey(sw) {
    case UnionKeyOne:
      return "One", true
    case UnionKeyTwo:
      return "Two", true
    case UnionKeyOffer:
      return "", true
}
return "-", false
}

// NewMyUnion creates a new  MyUnion.
func NewMyUnion(aType UnionKey, value interface{}) (result MyUnion, err error) {
  result.Type = aType
switch UnionKey(aType) {
    case UnionKeyOne:
                  tv, ok := value.(MyUnionOne)
            if !ok {
              err = fmt.Errorf("invalid value, must be MyUnionOne")
              return
            }
            result.One = &tv
    case UnionKeyTwo:
                  tv, ok := value.(MyUnionTwo)
            if !ok {
              err = fmt.Errorf("invalid value, must be MyUnionTwo")
              return
            }
            result.Two = &tv
    case UnionKeyOffer:
      // void
}
  return
}
// MustOne retrieves the One value from the union,
// panicing if the value is not set.
func (u MyUnion) MustOne() MyUnionOne {
  val, ok := u.GetOne()

  if !ok {
    panic("arm One is not set")
  }

  return val
}

// GetOne retrieves the One value from the union,
// returning ok if the union's switch indicated the value is valid.
func (u MyUnion) GetOne() (result MyUnionOne, ok bool) {
  armName, _ := u.ArmForSwitch(int32(u.Type))

  if armName == "One" {
    result = *u.One
    ok = true
  }

  return
}
// MustTwo retrieves the Two value from the union,
// panicing if the value is not set.
func (u MyUnion) MustTwo() MyUnionTwo {
  val, ok := u.GetTwo()

  if !ok {
    panic("arm Two is not set")
  }

  return val
}

// GetTwo retrieves the Two value from the union,
// returning ok if the union's switch indicated the value is valid.
func (u MyUnion) GetTwo() (result MyUnionTwo, ok bool) {
  armName, _ := u.ArmForSwitch(int32(u.Type))

  if armName == "Two" {
    result = *u.Two
    ok = true
  }

  return
}

// EncodeTo encodes this value using the Encoder.
func (u MyUnion) EncodeTo(e *xdr.Encoder) error {
  var err error
if   err = u.Type.EncodeTo(e); err != nil {
  return err
}
switch UnionKey(u.Type) {
    case UnionKeyOne:
      if err = (*u.One).EncodeTo(e); err != nil {
  return err
}
return nil
    case UnionKeyTwo:
      if err = (*u.Two).EncodeTo(e); err != nil {
  return err
}
return nil
    case UnionKeyOffer:
      // Void
return nil
}
  return fmt.Errorf("Type (UnionKey) switch value '%d' is not valid for union MyUnion", u.Type)
}

var _ decoderFrom = (*MyUnion)(nil)
// DecodeFrom decodes this value using the Decoder.
func (u *MyUnion) DecodeFrom(d *xdr.Decoder) (int, error) {
  var err error
  var n, nTmp int
  nTmp, err = u.Type.DecodeFrom(d)
n += nTmp
if err != nil {
  return n, fmt.Errorf("decoding UnionKey: %s", err)
}
switch UnionKey(u.Type) {
    case UnionKeyOne:
        u.One = new(MyUnionOne)
  nTmp, err = (*u.One).DecodeFrom(d)
n += nTmp
if err != nil {
  return n, fmt.Errorf("decoding MyUnionOne: %s", err)
}
  return n, nil
    case UnionKeyTwo:
        u.Two = new(MyUnionTwo)
  nTmp, err = (*u.Two).DecodeFrom(d)
n += nTmp
if err != nil {
  return n, fmt.Errorf("decoding MyUnionTwo: %s", err)
}
  return n, nil
    case UnionKeyOffer:
      // Void
  return n, nil
}
  return n, fmt.Errorf("union MyUnion has invalid Type (UnionKey) switch value '%d'", u.Type)
}

// MarshalBinary implements encoding.BinaryMarshaler.
func (s MyUnion) MarshalBinary() ([]byte, error) {
  b := bytes.Buffer{}
  e := xdr.NewEncoder(&b)
  err := s.EncodeTo(e)
  return b.Bytes(), err
}

// UnmarshalBinary implements encoding.BinaryUnmarshaler.
func (s *MyUnion) UnmarshalBinary(inp []byte) error {
  r := bytes.NewReader(inp)
  d := xdr.NewDecoder(r)
  _, err := s.DecodeFrom(d)
  return err
}

var (
  _ encoding.BinaryMarshaler   = (*MyUnion)(nil)
  _ encoding.BinaryUnmarshaler = (*MyUnion)(nil)
)

// xdrType signals that this type is an type representing
// representing XDR values defined by this package.
func (s MyUnion) xdrType() {}

var _ xdrType = (*MyUnion)(nil)

        var fmtTest = fmt.Sprint("this is a dummy usage of fmt")


text:
package org.tbag

import sbt._
import java.lang.String
import java.io.File

class BuildSbtFile(baseDir: File, currentRef: ProjectRef, scope: Settings[Scope], otherLibDependencies: Seq[String] = Seq()) {

  def write(settingKeys: SettingKey[String]*) = {
    assertDoesNotExist()
    val newBuildSettings = (settingKeys map {
      (settingKey: SettingKey[String]) => (settingKey, getNewValueFromUserFor(settingKey))
    }).toMap

    val content = (settingKeys map {
      (settingKey: SettingKey[String]) => """%s := "%s"""".format(settingName(settingKey), newBuildSettings.get(settingKey).getOrElse(""))
    } mkString "\n\n") + libDependenciesBuildSbtString

    IO.write(new File(baseDir, "build.sbt"), content)
    println("Generated build file")
    newBuildSettings
  }

  private def settingName(settingKey: SettingKey[String]) = {
    settingKey.key.label match {
      case "scala-version" => "scalaVersion"
      case s => s
    }
  }

  private def assertDoesNotExist() {
    val buildSbtFile: File = new File(baseDir, "build.sbt")
    if (buildSbtFile.exists()) sys.error(
      "\nbuild.sbt file already exists for this project at path %s" format buildSbtFile.getParent
    )
  }

  private def currentValueFor(settingKey: SettingKey[String]): String = {
    (settingKey in currentRef get scope).getOrElse("")
  }

  private def getNewValueFromUserFor(settingKey: SettingKey[String]): String = {
    val currentValue: String = currentValueFor(settingKey)
    SimpleReader.readLine(settingKey.key + "[" + currentValue + "]: ") match {
      case Some("") => currentValue
      case Some(s) => s
      case None => currentValue
    }
  }

  val libraryDependencies = otherLibDependencies ++ Seq(
    """"org.scalatest" %% "scalatest" % "2.1.6" % "test""""
  )

  val libDependenciesBuildSbtString =
    """
      |
      |libraryDependencies ++= Seq(
    %s
      |)""".format((libraryDependencies map ("|    " + _)).mkString(",\n")).stripMargin
}

object BuildSbtFile {
  def simpleBuildSbtFile(sbtStuff: SbtStuff) = {
    new BuildSbtFile(sbtStuff.baseDir, sbtStuff.projectRef, sbtStuff.scopeSettings)
  }

  def webBuildSbtFile(sbtStuff: SbtStuff) = {
    val unfilteredLibs = Seq(
      """"net.databinder" %% "unfiltered-filter" % "0.7.1" % "compile"""",
      """"net.databinder" %% "unfiltered-jetty" % "0.7.1" % "compile"""",
      """"org.eclipse.jetty.orbit" % "javax.servlet" % "2.5.0.v201103041518" % "compile""""
    )
    new BuildSbtFile(sbtStuff.baseDir, sbtStuff.projectRef, sbtStuff.scopeSettings, unfilteredLibs)
  }

  def liftwebBuildSbtFile(sbtStuff: SbtStuff) = {
    val liftAndJettyLibs = Seq(
      """"net.liftweb" %% "lift-webkit" % "2.5" % "compile"""",
      """"org.eclipse.jetty" % "jetty-webapp" % "8.1.15.v20140411" % "compile""""
    )
    new BuildSbtFile(sbtStuff.baseDir, sbtStuff.projectRef, sbtStuff.scopeSettings, liftAndJettyLibs)
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project>
  <property name="jnlp.title"    value="JST TranslucentPopupMenu" />
  <property name="jnlp.Name"     value="TranslucentPopupMenu" />
  <property name="jnlp.name"     value="translucentpopupmenu" />
  <property name="jnlp.codebase" value="https://ateraimemo.com/swing/translucentpopupmenu/" />
  <property name="jnlp.homepage" value="https://ateraimemo.com/Swing/TranslucentPopupMenu.html" />
</project>


text:
#import "PLStructs.h"
#import "PLTransition.h"
#import "PLHotspot.h"

@protocol PLIView;

@protocol PLViewDelegate

@optional

#pragma mark -
#pragma mark touch methods

-(void)view:(UIView<PLIView> *)pView touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
-(void)view:(UIView<PLIView> *)pView touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
-(void)view:(UIView<PLIView> *)pView touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;

-(BOOL)view:(UIView<PLIView> *)pView shouldBeginTouching:(NSSet *)touches withEvent:(UIEvent *)event;
-(void)view:(UIView<PLIView> *)pView didBeginTouching:(NSSet *)touches withEvent:(UIEvent *)event;
-(BOOL)view:(UIView<PLIView> *)pView shouldTouch:(NSSet *)touches withEvent:(UIEvent *)event;
-(void)view:(UIView<PLIView> *)pView didTouch:(NSSet *)touches withEvent:(UIEvent *)event;
-(BOOL)view:(UIView<PLIView> *)pView shouldEndTouching:(NSSet *)touches withEvent:(UIEvent *)event;
-(void)view:(UIView<PLIView> *)pView didEndTouching:(NSSet *)touches withEvent:(UIEvent *)event;

#pragma mark -
#pragma mark accelerometer methods

-(BOOL)view:(UIView<PLIView> *)pView shouldAccelerate:(UIAcceleration *)acceleration withAccelerometer:(UIAccelerometer *)accelerometer;
-(void)view:(UIView<PLIView> *)pView didAccelerate:(UIAcceleration *)acceleration withAccelerometer:(UIAccelerometer *)accelerometer;

#pragma mark -
#pragma mark inertia methods

-(BOOL)view:(UIView<PLIView> *)pView shouldBeginInertia:(CGPoint)starPoint endPoint:(CGPoint)endPoint;
-(void)view:(UIView<PLIView> *)pView didBeginInertia:(CGPoint)starPoint endPoint:(CGPoint)endPoint;
-(BOOL)view:(UIView<PLIView> *)pView shouldRunInertia:(CGPoint)starPoint endPoint:(CGPoint)endPoint;
-(void)view:(UIView<PLIView> *)pView didRunInertia:(CGPoint)starPoint endPoint:(CGPoint)endPoint;
-(void)view:(UIView<PLIView> *)pView didEndInertia:(CGPoint)starPoint endPoint:(CGPoint)endPoint;

#pragma mark -
#pragma mark reset methods

-(BOOL)viewShouldReset:(UIView<PLIView> *)pView;
-(void)viewDidReset:(UIView<PLIView> *)pView;

#pragma mark -
#pragma mark zooming methods

-(BOOL)viewShouldBeginZooming:(UIView<PLIView> *)pView;
-(void)view:(UIView<PLIView> *)pView didBeginZooming:(CGPoint)starPoint endPoint:(CGPoint)endPoint;
-(BOOL)view:(UIView<PLIView> *)pView shouldRunZooming:(float)distance isZoomIn:(BOOL)isZoomIn isZoomOut:(BOOL)isZoomOut;
-(void)view:(UIView<PLIView> *)pView didRunZooming:(float)distance isZoomIn:(BOOL)isZoomIn isZoomOut:(BOOL)isZoomOut;
-(void)view:(UIView<PLIView> *)pView didEndZooming:(float)distance isZoomIn:(BOOL)isZoomIn isZoomOut:(BOOL)isZoomOut;

#pragma mark -
#pragma mark moving methods

-(BOOL)view:(UIView<PLIView> *)pView shouldBeginMoving:(CGPoint)starPoint endPoint:(CGPoint)endPoint;
-(void)view:(UIView<PLIView> *)pView didBeginMoving:(CGPoint)starPoint endPoint:(CGPoint)endPoint;
-(BOOL)view:(UIView<PLIView> *)pView shouldRunMoving:(CGPoint)starPoint endPoint:(CGPoint)endPoint;
-(void)view:(UIView<PLIView> *)pView didRunMoving:(CGPoint)starPoint endPoint:(CGPoint)endPoint;
-(void)view:(UIView<PLIView> *)pView didEndMoving:(CGPoint)starPoint endPoint:(CGPoint)endPoint;

#pragma mark -
#pragma mark scrolling methods

-(BOOL)view:(UIView<PLIView> *)pView shouldBeingScrolling:(CGPoint)starPoint endPoint:(CGPoint)endPoint;
-(void)view:(UIView<PLIView> *)pView didBeginScrolling:(CGPoint)starPoint endPoint:(CGPoint)endPoint;
-(BOOL)view:(UIView<PLIView> *)pView shouldScroll:(CGPoint)starPoint endPoint:(CGPoint)endPoint;
-(void)view:(UIView<PLIView> *)pView didScroll:(CGPoint)starPoint endPoint:(CGPoint)endPoint;
-(void)view:(UIView<PLIView> *)pView didEndScrolling:(CGPoint)starPoint endPoint:(CGPoint)endPoint;

#pragma mark -
#pragma mark transition methods

-(void)view:(UIView<PLIView> *)pView didBeginTransition:(PLTransition *)transition;
-(void)view:(UIView<PLIView> *)pView didProcessTransition:(PLTransition *)transition progressPercentage:(NSUInteger)progressPercentage;
-(void)view:(UIView<PLIView> *)pView didEndTransition:(PLTransition *)transition;

#pragma mark -
#pragma mark camera methods

-(BOOL)view:(UIView<PLIView> *)pView didRotateCamera:(PLCamera *)camera rotation:(PLRotation)rotation;

#pragma mark -
#pragma mark hotspot methods

-(void)view:(UIView<PLIView> *)pView didOverHotspot:(PLHotspot *)hotspot screenPoint:(CGPoint)point scene3DPoint:(PLPosition)position;
-(void)view:(UIView<PLIView> *)pView didOutHotspot:(PLHotspot *)hotspot screenPoint:(CGPoint)point scene3DPoint:(PLPosition)position;
-(void)view:(UIView<PLIView> *)pView didClickHotspot:(PLHotspot *)hotspot screenPoint:(CGPoint)point scene3DPoint:(PLPosition)position;

@end


text:
<?php

namespace MusicDiff\Helper;

use MusicDiff\Collection\CollectionInterface;
use MusicDiff\Collection\Converter\ArrayConverter;

class DiffCollection
{
    /**
     * Leave elements that are not present in the first collection.
     * Artists are taken from the first collection only.
     * @param CollectionInterface $coll1
     * @param CollectionInterface $coll2
     * @return CollectionInterface
     */
    public function calculateDiff(CollectionInterface $coll1, CollectionInterface $coll2): CollectionInterface
    {
        $arrayConverter = new ArrayConverter();

        $coll1Array = $resultArray = $arrayConverter->fromCollection($coll1);
        $coll2Array = $arrayConverter->fromCollection($coll2);

        foreach ($coll1Array as $origArtistKey => $origArtist) {
            $resultArray[$origArtistKey]['albums'] = [];

            foreach ($coll2Array as $artist) {
                if (strtolower($origArtist['name']) !== strtolower($artist['name'])) {
                    continue;
                }

                // Albums.
                $albumNames = array_map(function ($val) {
                    return strtolower($val['name']);
                }, $origArtist['albums']);

                foreach ($artist['albums'] as $album) {
                    if (!in_array(strtolower($album['name']), $albumNames)) {
                        $resultArray[$origArtistKey]['albums'][] = $album;
                    }
                }

            }
        }
        return $arrayConverter->toCollection($resultArray);
    }
}


text:
* Added *SPRITE-IP* to *assay_term_name* enum
* Added *CUT&Tag* to *assay_term_name* enum
* Added *Capture Hi-C* and *single-nucleus RNA-seq* to *assay_term_name* enum
* Added *GRO-cap*, *GRO-seq*, and *long read single-cell RNA-seq* to *assay_term_name* enum;  *single-nucleus RNA-seq* and *genotyping by high throughput sequencing assay* were removed and remapped to *single-cell RNA sequencing assay* and *whole genome sequencing assay* respectively
* Removed *single-cell ATAC-seq* from *assay_term_name* enum and remapped to *single-nucleus ATAC-seq*
* Added *LC/MS label-free quantitative proteomics*, *LC-MS/MS isobaric label quantitative proteomics*, and *Ribo-seq* to *assay_term_name* enum. *assay_term_name* enum *Capture Hi-C* was changed to *capture Hi-C*
* Added *genomic perturbation followed by RT-qPCR* to *assay_term_name* enum.
* Added *seqFISH* to *assay_term_name* enum.

### Schema version 2

* The following properties were removed from the schema and will be reported in an attachment:
  - 3prime_overlapping_ncrna
  - IG_C_gene
  - IG_C_pseudogene
  - IG_D_gene
  - IG_J_gene
  - IG_J_pseudogene
  - IG_V_gene
  - IG_V_pseudogene
  - Mt_tRNA
  - TEC
  - TR_C_gene
  - TR_D_gene
  - TR_J_gene
  - TR_J_pseudogene
  - TR_V_gene
  - TR_V_pseudogene
  - bidirectional_promoter_lncrna
  - lincRNA
  - macro_lncRNA
  - misc_RNA
  - polymorphic_pseudogene
  - processed_pseudogene
  - pseudogene
  - tRNAscan
  - transcribed_processed_pseudogene
  - transcribed_unitary_pseudogene
  - transcribed_unprocessed_pseudogene
  - transcript_id_not_found
  - translated_unprocessed_pseudogene
  - unitary_pseudogene
  - unprocessed_pseudogene
  - vaultRNA

### Minor changes since schema version 1

* *quality_metric_of* was set to have a minimum of 1.


text:
NOTE: This plugin is no longer under active development.  See BigWarps instead.

SmallWarps is a simple warps plugin designed for PvE minecraft servers.  It allows players to warp to their bed or the world spawn, and mods can create and use named warps.  Returning to death point is also supported, and players can teleport request each other.

Commands:
* /spawn - warp to spawn
* /home - warp to spawn bed
* /back - return to previous warp point or death point

* /tpa - request to teleport
* /tpaccept - accept a teleport request
* /tpdeny - deny a teleport request
* /tpcancel - cancel a teleport request

* /mkwarp - create a mod warp
* /rmwarp - remove a warp
* /warp - warp to a mod warp
* /lswarps - list mod warps

* /tp - passthrough to vanilla tp, but records player position for /back

Curious as to why this readme looks so bad?  So am I.  Look at the source then compare to how it renders, and you'll be even more confused.


text:
<!DOCTYPE HTML>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name='HandheldFriendly' content='True'>
<meta name='MobileOptimized' content='480'>
<meta name='format-detection' content='telephone=no'>
<meta name='viewport' content='initial-scale=1.0,width=device-width, minimum-scale=1.0, maximum-scale=1.0'>
<meta http-equiv='cleartype' content='on'>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="copyright" content="(C) 版权 2005"/>
<meta name="DC.rights.owner" content="(C) 版权 2005"/>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7"/>
<meta name="DC.Type" content="topic"/>
<meta name="DC.Title" content="Why can't my phone open some audio clips or videos?"/>
<meta name="DC.Relation" scheme="URI" content="../index.html"/>
<meta name="DC.Format" content="XHTML"/>
<meta name="DC.Identifier" content="topic_play_media_fail"/>
<meta name="DC.Language" content="zh-cn"/>
<link rel="stylesheet" type="text/css" href="../css/commonltr.css"/>
<link rel="stylesheet" type="text/css" href="../css/my.css"/>
<title>Why can't my phone open some audio clips or videos?</title>

    <link rel="stylesheet" type="text/css" href="css/my.css"/>

            Why can't my phone open some audio clips or videos?

Your phone may not support the file format. Supported video and
audio formats include MP3, WAV, OGG, MID, AMR, MP4, and 3GP.

The file may be corrupted. Download another copy
of the file and try opening it again.

The file may be copyright-protected. Obtain a non copyright-protected
version of the file.


text:
package org.apache.druid.query.movingaverage.averagers;

import org.junit.Assert;
import org.junit.Test;

import java.util.Collections;
import java.util.HashMap;

public class LongMeanNoNullAveragerTest
{
  @Test
  public void testComputeResult()
  {
    BaseAverager<Number, Double> avg = new LongMeanNoNullAverager(3, "test", "field", 1);

    Assert.assertEquals(Double.NaN, avg.computeResult(), 0.0);

    avg.addElement(Collections.singletonMap("field", 3L), new HashMap<>());
    Assert.assertEquals(3.0, avg.computeResult(), 0.0);

    avg.addElement(Collections.singletonMap("field", 3L), new HashMap<>());
    Assert.assertEquals(3.0, avg.computeResult(), 0.0);

    avg.addElement(Collections.singletonMap("field", 0), new HashMap<>());
    Assert.assertEquals(2.0, avg.computeResult(), 0.0);

    avg.addElement(Collections.singletonMap("field", 2L), new HashMap<>());
    avg.addElement(Collections.singletonMap("field", 2L), new HashMap<>());
    avg.addElement(Collections.singletonMap("field", 2L), new HashMap<>());
    Assert.assertEquals(2.0, avg.computeResult(), 0.0);

    avg.skip();
    Assert.assertEquals(2.0, avg.computeResult(), 0.0);
  }

}


text:
package com.kneelawk.stree.core.infoProviders;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

import com.kneelawk.stree.core.ListSTreeNode;
import com.kneelawk.stree.core.STreeNode;

public class ListSTreeNodeInfoProvider implements STreeInfoProvider {

	public static final ListSTreeNodeInfoProvider INSTANCE = new ListSTreeNodeInfoProvider();

	protected ListSTreeNodeInfoProvider() {
	}

	@Override
	public void write(STreeNode objectToWrite, DataOutput streamToWriteTo)
			throws IOException {
		ListSTreeNode node = (ListSTreeNode) objectToWrite;
		streamToWriteTo.writeInt(node.size());
		for (int i = 0; i < node.size(); i++) {
			STreeNode.writeSTreeNode(node.get(i), streamToWriteTo);
		}
	}

	@Override
	public ListSTreeNode read(DataInput streamToReadFrom) throws IOException {
		ListSTreeNode node = new ListSTreeNode();
		int size = streamToReadFrom.readInt();
		for (int i = 0; i < size; i++) {
			node.add(STreeNode.readSTreeNode(streamToReadFrom));
		}
		return node;
	}

	@Override
	public byte getSTreeID() {
		return 2;
	}

}