text:
#include "fennel/common/CommonPreamble.h"
#include "fennel/tuple/TupleAccessor.h"
#include "fennel/tuple/TupleDescriptor.h"
#include "fennel/tuple/TupleData.h"
#include "fennel/tuple/AttributeAccessorImpl.h"
#include "fennel/tuple/StoredTypeDescriptor.h"
#include <boost/lambda/bind.hpp>
#include <boost/lambda/construct.hpp>

FENNEL_BEGIN_CPPFILE("$Id$");

const bool TupleAccessor::BOOL_TRUE = true;

const bool TupleAccessor::BOOL_FALSE = false;

// NOTE jvs 11-Feb-2006: Set this to 1 to debug problems with
// TupleAccessor::setCurrentTupleBuf being passed invalid tuple images.
// Typical symptom is a Boost assertion failure in ~TupleAccessor when
// dynamic_bitset detects invalid bits set.  When this is set to 1, we write a
// magic number as a prefix every time a tuple is marshalled, and verify it
// when setCurrentTupleBuf is called.  CAUTION: do NOT check in changes with
// this set to 1!  Also realize that this affects on-disk storage, so if you
// run without it and generate a datafile, then run with it and read that
// datafile, you should expect an assertion failure.
#define DEBUG_TUPLE_ACCESS 0

/**
 * Matches net.sf.farrago.runtime.FennelTupleWriter.
 */
static const MagicNumber TUPLE_MAGIC_NUMBER = 0x9897ab509de7dcf5LL;

TupleAccessor::TupleAccessor() : alignment(TUPLE_ALIGN_NATIVE)
{
    pTupleBuf = NULL;
}

TupleAccessor::~TupleAccessor()
{
    clear();
}

void TupleAccessor::clear()
{
    using namespace boost::lambda;
    std::for_each(
        ppAttributeAccessors.begin(),
        ppAttributeAccessors.end(),
        bind(delete_ptr(),_1));
    ppAttributeAccessors.clear();
    pVarWidthAttrIndices.clear();
    marshalOrder.clear();
    pTupleBuf = NULL;
    bAlignedVar = false;
}

// TODO:  clean up template factory craziness below, and add network support
// for 64-bit types and UNICODE

// NOTE:  there's a small amount of code in Farrago which is sensitive to this
// algorithm, e.g. bit field ordering

void TupleAccessor::compute(
    TupleDescriptor const &tuple, TupleFormat formatInit, TupleAlign align)
{
    clear();
    format = formatInit;
    alignment = align;

    // these vectors keep track of the logical 0-based indices of the
    // attributes belonging to the various attribute storage classes
    VectorOfUint aligned8;
    VectorOfUint aligned4;
    VectorOfUint aligned2;
    VectorOfUint unalignedFixed;
    VectorOfUint unalignedVar;
    VectorOfUint alignedVar2;

    // special-case reference to the accessor for the first variable-width
    // attribute
    AttributeAccessor *pFirstVariableAccessor = NULL;

    // number of bit fields seen so far
    nBitFields = 0;

    // sum of max storage size for variable-width attributes seen so far
    uint cbVarDataMax = 0;

    // sum of total storage size seen so far; this is used as an accumulator
    // for assigning actual offsets
    cbMaxStorage = 0;

#if DEBUG_TUPLE_ACCESS
    cbMaxStorage += sizeof(MagicNumber);
#endif

    // first pass over all attributes in logical order:  collate them into
    // storage classes and precompute everything we can
    for (uint iAttr = 0; iAttr < tuple.size(); iAttr++) {
        AttributeAccessor *pNewAccessor;
        TupleAttributeDescriptor const &attr = tuple[iAttr];
        uint cbFixed = attr.pTypeDescriptor->getFixedByteCount();
        uint cbMin = attr.pTypeDescriptor->getMinByteCount(attr.cbStorage);
        if (cbFixed) {
            assert(cbFixed == attr.cbStorage);
            assert(cbFixed == cbMin);
        }
        bool bFixedWidth = (cbMin == attr.cbStorage);
        if (bFixedWidth && !attr.cbStorage) {
            if (!attr.pTypeDescriptor->getMinByteCount(1)) {
                // this is a "0-length variable-width" field masquerading
                // as a fixed-width field
                bFixedWidth = false;
            }
        }
        bool bNullable = attr.isNullable;
        uint nBits = (attr.pTypeDescriptor->getBitCount());
        assert(nBits <= 1);
        if (format == TUPLE_FORMAT_ALL_FIXED) {
            bFixedWidth = true;
            nBits = 0;
        }
        uint iAlign = attr.pTypeDescriptor->getAlignmentByteCount(
            attr.cbStorage);
        if (!bFixedWidth) {
            cbVarDataMax += attr.cbStorage;
            if (iAlign == 2) {
                alignedVar2.push_back(iAttr);
                bAlignedVar = true;
            } else {
                assert(iAlign == 1);
                unalignedVar.push_back(iAttr);
            }
            // We need to defer actual creation of the accessor until
            // after we've sorted out aligned from unaligned, so just
            // fill a placeholder into the array for now and
            // we'll overwrite it later.
            pNewAccessor = new VarOffsetAccessor<false>();
        } else if (nBits) {
            if (bNullable) {
                pNewAccessor = new NullableAccessor<BitAccessor>;
            } else {
                pNewAccessor = new BitAccessor;
            }
            pNewAccessor->iValueBit = nBitFields;
            nBitFields++;
        } else {
            assert((cbMin % iAlign) == 0);
            bool bArray =
                StandardTypeDescriptor::isArray(
                    StandardTypeDescriptorOrdinal(
                        attr.pTypeDescriptor->getOrdinal()));
            switch (iAlign) {
            case 2:
                if (bNullable) {
                    if ((format == TUPLE_FORMAT_NETWORK) && !bArray) {
                        pNewAccessor =
                            new NullableAccessor<FixedWidthNetworkAccessor16>;
                    } else {
                        pNewAccessor =
                            new NullableAccessor<FixedWidthAccessor>;
                    }
                } else {
                    if ((format == TUPLE_FORMAT_NETWORK) && !bArray) {
                        pNewAccessor = new FixedWidthNetworkAccessor16;
                    } else {
                        pNewAccessor = new FixedWidthAccessor;
                    }
                }
                break;
            case 4:
                if (bNullable) {
                    if (format == TUPLE_FORMAT_NETWORK) {
                        pNewAccessor =
                            new NullableAccessor<FixedWidthNetworkAccessor32>;
                    } else {
                        pNewAccessor =
                            new NullableAccessor<FixedWidthAccessor>;
                    }
                } else {
                    if (format == TUPLE_FORMAT_NETWORK) {
                        pNewAccessor = new FixedWidthNetworkAccessor32;
                    } else {
                        pNewAccessor = new FixedWidthAccessor;
                    }
                }
                break;
            case 8:
                if (bNullable) {
                    if (format == TUPLE_FORMAT_NETWORK) {
                        pNewAccessor =
                            new NullableAccessor<FixedWidthNetworkAccessor64>;
                    } else {
                        pNewAccessor =
                            new NullableAccessor<FixedWidthAccessor>;
                    }
                } else {
                    if (format == TUPLE_FORMAT_NETWORK) {
                        pNewAccessor = new FixedWidthNetworkAccessor64;
                    } else {
                        pNewAccessor = new FixedWidthAccessor;
                    }
                }
                break;
            default:
                if (bNullable) {
                    pNewAccessor = new NullableAccessor<FixedWidthAccessor>;
                } else {
                    pNewAccessor = new FixedWidthAccessor;
                }
                break;
            }
            switch (iAlign) {
            case 1:
                unalignedFixed.push_back(iAttr);
                break;
            case 2:
                aligned2.push_back(iAttr);
                break;
            case 4:
                aligned4.push_back(iAttr);
                break;
            case 8:
                aligned8.push_back(iAttr);
                break;
            default:
                permAssert(false);
            }
        }
        if (bNullable) {
            pNewAccessor->iNullBit = nBitFields;
            nBitFields++;
        }
        pNewAccessor->cbStorage = attr.cbStorage;
        ppAttributeAccessors.push_back(pNewAccessor);
    }
    bitFields.resize(nBitFields);

    // fill in variable-width attributes, since we had to defer them
    // above so that we could collect aligned ones before unaligned ones
    pVarWidthAttrIndices.resize(alignedVar2.size() + unalignedVar.size());
    std::copy(
        alignedVar2.begin(), alignedVar2.end(),
        pVarWidthAttrIndices.begin());
    std::copy(
        unalignedVar.begin(), unalignedVar.end(),
        pVarWidthAttrIndices.begin() + alignedVar2.size());
    for (uint i = 0; i < pVarWidthAttrIndices.size(); ++i) {
        uint iAttr = pVarWidthAttrIndices[i];
        TupleAttributeDescriptor const &attr = tuple[iAttr];
        bool bNullable = attr.isNullable;
        AttributeAccessor *pNewAccessor;
        if (pFirstVariableAccessor) {
            if (bNullable) {
                if (format == TUPLE_FORMAT_NETWORK) {
                    pNewAccessor =
                        new NullableAccessor< VarOffsetAccessor<true> >;
                } else {
                    pNewAccessor =
                        new NullableAccessor< VarOffsetAccessor<false> >;
                }
            } else {
                if (format == TUPLE_FORMAT_NETWORK) {
                    pNewAccessor = new VarOffsetAccessor<true>;
                } else {
                    pNewAccessor = new VarOffsetAccessor<false>;
                }
            }
        } else {
            if (bNullable) {
                if (format == TUPLE_FORMAT_NETWORK) {
                    pFirstVariableAccessor =
                        new NullableAccessor<
                        FixedOffsetVarWidthAccessor<true> >;
                } else {
                    pFirstVariableAccessor =
                        new NullableAccessor<
                        FixedOffsetVarWidthAccessor<false> >;
                }
            } else {
                if (format == TUPLE_FORMAT_NETWORK) {
                    pFirstVariableAccessor =
                        new FixedOffsetVarWidthAccessor<true>;
                } else {
                    pFirstVariableAccessor =
                        new FixedOffsetVarWidthAccessor<false>;
                }
            }
            pNewAccessor = pFirstVariableAccessor;
        }
        AttributeAccessor *pPlaceholder = ppAttributeAccessors[iAttr];
        pNewAccessor->cbStorage = attr.cbStorage;
        pNewAccessor->iNullBit = pPlaceholder->iNullBit;
        // overwrite placeholder
        ppAttributeAccessors[iAttr] = pNewAccessor;
        delete pPlaceholder;
    }

    // now, make a pass over each storage class, calculating actual offsets;
    // note that initFixedAccessors advances cbMaxStorage as a side-effect
    initFixedAccessors(tuple, aligned8);
    initFixedAccessors(tuple, aligned4);
    initFixedAccessors(tuple, aligned2);

    if (pFirstVariableAccessor) {
        iFirstVarEndIndirectOffset = cbMaxStorage;
    } else {
        iFirstVarEndIndirectOffset = MAXU;
    }

    for (uint i = 0; i < pVarWidthAttrIndices.size(); i++) {
        ppAttributeAccessors[pVarWidthAttrIndices[i]]->iEndIndirectOffset =
            cbMaxStorage;
        cbMaxStorage += sizeof(StoredValueOffset);
    }

    if (pFirstVariableAccessor) {
        iLastVarEndIndirectOffset = cbMaxStorage - sizeof(StoredValueOffset);
    } else {
        iLastVarEndIndirectOffset = MAXU;
    }

    initFixedAccessors(tuple, unalignedFixed);

    if (nBitFields) {
        iBitFieldOffset = cbMaxStorage;
    } else {
        iBitFieldOffset = MAXU;
    }
    cbMaxStorage += bytesForBits(nBitFields);
    if (pFirstVariableAccessor) {
        if (bAlignedVar) {
            // First variable-width value needs to be 2-byte aligned,
            // so add one byte of padding if necessary.
            if (cbMaxStorage & 1) {
                ++cbMaxStorage;
            }
        }
        pFirstVariableAccessor->iFixedOffset = cbMaxStorage;
        iFirstVarOffset = cbMaxStorage;
    } else {
        iFirstVarOffset = MAXU;
    }
    cbMinStorage = cbMaxStorage;
    cbMaxStorage += cbVarDataMax;

    // Avoid 0-byte tuples, because it's very hard to count something
    // that isn't there.  This bumps them up to 1-byte, which will get
    // further bumped up to the minimum alignment unit below.
    if (!cbMaxStorage) {
        cbMinStorage = 1;
        cbMaxStorage = 1;
    }

    // now round the entire row width up to the next alignment boundary;
    // this only affects the end of the row, which is why it is done
    // AFTER computing cbMaxStorage based on the unaligned cbMinStorage
    cbMinStorage = alignRoundUp(cbMinStorage, alignment);
    cbMaxStorage = alignRoundUp(cbMaxStorage, alignment);

    // if aligned variable-width fields are present, permute the marshalling
    // order so that they come before unaligned variable-width fields
    if (bAlignedVar) {
        // add all of the fixed-width attributes
        for (uint i = 0; i < tuple.size(); ++i) {
            AttributeAccessor const &accessor = getAttributeAccessor(i);
            if (isMAXU(accessor.iEndIndirectOffset)) {
                marshalOrder.push_back(i);
            }
        }
        uint nFixed = marshalOrder.size();
        assert(nFixed + pVarWidthAttrIndices.size() == tuple.size());
        marshalOrder.resize(tuple.size());
        // then all of the variable-width attributes, in the correct order
        std::copy(
            pVarWidthAttrIndices.begin(),
            pVarWidthAttrIndices.end(),
            marshalOrder.begin() + nFixed);
    }
}

void TupleAccessor::initFixedAccessors(
    TupleDescriptor const &tuple,VectorOfUint &v)
{
    for (uint i = 0; i < v.size(); i++) {
        uint iAttr = v[i];
        TupleAttributeDescriptor const &attr = tuple[iAttr];
        AttributeAccessor &accessor = *(ppAttributeAccessors[iAttr]);
        accessor.iFixedOffset = cbMaxStorage;
        cbMaxStorage += attr.cbStorage;
    }
}

uint TupleAccessor::getBufferByteCount(PConstBuffer pBuf) const
{
    if (isFixedWidth()) {
        return cbMaxStorage;
    } else {
        // variable-width tuple:  use the end of the last variable-width
        // attribute
        StoredValueOffset cb =
            *referenceIndirectOffset(
                const_cast<PBuffer>(pBuf),
                iLastVarEndIndirectOffset);
        if (format == TUPLE_FORMAT_NETWORK) {
            cb = ntohs(cb);
        }
        // round up for alignment padding
        return alignRoundUp(cb, alignment);
    }
}

uint TupleAccessor::getByteCount(TupleData const &tuple) const
{
    if (isFixedWidth()) {
        return cbMaxStorage;
    } else {
        // variable-width tuple:  add up all var-width fields
        uint cb = iFirstVarOffset;
        for (uint i = 0; i < pVarWidthAttrIndices.size(); ++i) {
            TupleDatum const &datum = tuple[pVarWidthAttrIndices[i]];
            if (datum.pData) {
                cb += datum.cbData;
            }
        }
        // round up for alignment padding
        return alignRoundUp(cb, alignment);
    }
}

bool TupleAccessor::isBufferSufficient(
    TupleData const &tuple,uint cbBuffer) const
{
    // fast optimistic check
    if (getMaxByteCount() <= cbBuffer) {
        return true;
    }
    // slower conservative check
    return getByteCount(tuple) <= cbBuffer;
}

void TupleAccessor::setCurrentTupleBuf(PConstBuffer pTupleBufInit, bool valid)
{
    assert(pTupleBufInit);
    pTupleBuf = pTupleBufInit;          // bind to buffer
    if (!isMAXU(iBitFieldOffset)) {
        // if buffer holds a valid marshalled tuple, load its bitFields
        if (valid) {
#if DEBUG_TUPLE_ACCESS
            assert(
                *reinterpret_cast<MagicNumber const *>(pTupleBuf)
                == TUPLE_MAGIC_NUMBER);
#endif
            // TODO:  trick dynamic_bitset to avoid copy
            boost::from_block_range(
                pTupleBuf + iBitFieldOffset,
                pTupleBuf + iBitFieldOffset + bitFields.num_blocks(),
                bitFields);
        }
    }
}

void TupleAccessor::resetCurrentTupleBuf()
{
    pTupleBuf = NULL;
}

void TupleAccessor::unmarshal(TupleData &tuple,uint iFirstDatum) const
{
    uint n = std::min(tuple.size() - iFirstDatum, ppAttributeAccessors.size());

    if ((format == TUPLE_FORMAT_NETWORK) || bAlignedVar) {
        // for TUPLE_FORMAT_NETWORK, unmarshal attributes individually
        for (uint i = 0; i < n; ++i) {
            getAttributeAccessor(i).unmarshalValue(
                *this,tuple[iFirstDatum + i]);
        }
        return;
    }

    // for other formats, we can go a little faster by avoiding per-attribute
    // call overhead

    uint iNextVarOffset = iFirstVarOffset;
    StoredValueOffset const *pNextVarEndOffset =
        referenceIndirectOffset(iFirstVarEndIndirectOffset);

    for (uint i = 0; i < n; i++) {
        TupleDatum &value = tuple[i + iFirstDatum];
        AttributeAccessor const &accessor = getAttributeAccessor(i);
        if (!isMAXU(accessor.iNullBit)) {
            if (bitFields[accessor.iNullBit]) {
                value.pData = NULL;
                if (!isMAXU(accessor.iEndIndirectOffset)) {
                    pNextVarEndOffset++;
                }
                continue;
            }
        }
        if (!isMAXU(accessor.iFixedOffset)) {
            value.pData = getCurrentTupleBuf() + accessor.iFixedOffset;
        } else if (isMAXU(accessor.iValueBit)) {
            value.pData = getCurrentTupleBuf() + iNextVarOffset;
        } else {
            static_cast<BitAccessor const &>(accessor).unmarshalValue(
                *this,value);
        }
        if (!isMAXU(accessor.iEndIndirectOffset)) {
            assert(
                pNextVarEndOffset
                == referenceIndirectOffset(accessor.iEndIndirectOffset));
            uint iEndOffset = *pNextVarEndOffset;
            pNextVarEndOffset++;
            value.cbData = iEndOffset - iNextVarOffset;
            iNextVarOffset = iEndOffset;
        }
        assert(value.cbData <= accessor.cbStorage);
    }
}

void TupleAccessor::marshal(TupleData const &tuple,PBuffer pTupleBufDest)
{
#if DEBUG_TUPLE_ACCESS
    *reinterpret_cast<MagicNumber *>(pTupleBufDest) = TUPLE_MAGIC_NUMBER;
#endif

    pTupleBuf = pTupleBufDest;

    uint iNextVarOffset = iFirstVarOffset;
    StoredValueOffset *pNextVarEndOffset =
        referenceIndirectOffset(pTupleBufDest, iFirstVarEndIndirectOffset);

    for (uint i = 0; i < tuple.size(); i++) {
        uint iAttr;
        if (bAlignedVar) {
            iAttr = marshalOrder[i];
        } else {
            iAttr = i;
        }
        TupleDatum const &value = tuple[iAttr];
        AttributeAccessor const &accessor = getAttributeAccessor(iAttr);
        if (!isMAXU(accessor.iNullBit)) {
            bitFields[accessor.iNullBit] = value.pData ? false : true;
        }
        if (value.pData) {
            if (isMAXU(accessor.iValueBit)) {
                uint iOffset;
                if (!isMAXU(accessor.iFixedOffset)) {
                    iOffset = accessor.iFixedOffset;
                } else {
                    iOffset = iNextVarOffset;
                }
                assert(value.cbData <= accessor.cbStorage);
                accessor.marshalValueData(
                    pTupleBufDest + iOffset,
                    value);
            } else {
                bitFields[accessor.iValueBit] =
                    *reinterpret_cast<bool const *>(value.pData);
            }
        } else {
            // if you hit this assert, most likely the result produced a null
            // but type derivation in SqlValidator derived a non-nullable
            // result type
            assert(!isMAXU(accessor.iNullBit));
        }
        if (!isMAXU(accessor.iEndIndirectOffset)) {
            assert(
                pNextVarEndOffset
                == referenceIndirectOffset(accessor.iEndIndirectOffset));
            if (value.pData) {
                iNextVarOffset += value.cbData;
            }
            // regardless of whether the value is null, we need to record the
            // end offset since it also marks the start of the next
            // non-null value
            if (format == TUPLE_FORMAT_NETWORK) {
                *pNextVarEndOffset =
                    htons(static_cast<StoredValueOffset>(iNextVarOffset));
            } else {
                *pNextVarEndOffset = iNextVarOffset;
            }
            pNextVarEndOffset++;
        }
    }
    if (!isMAXU(iBitFieldOffset)) {
        // TODO:  trick dynamic_bitset to avoid copy
        boost::to_block_range(
            bitFields,
            pTupleBufDest + iBitFieldOffset);
    }
}

FENNEL_END_CPPFILE("$Id$");

// End TupleAccessor.cpp


text:
package org.ixmas.machinelearning.tools.collection;

import com.google.common.collect.ForwardingSet;

import java.util.Collection;
import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;

public class LimitedSortedSet<T> extends ForwardingSet<T> {

    private TreeSet<T> m_sortedSet;
    private int m_limitedSize;
    private Comparator<T> m_comparator;

    public LimitedSortedSet(int limitedSize, Comparator<T> comparator) {
        m_limitedSize = limitedSize;
        m_comparator = comparator;
        m_sortedSet = new TreeSet<>(comparator);
    }

    @Override
    public boolean add(T element) {
        if (m_sortedSet.size() >= m_limitedSize) {
            if (m_comparator.compare(element, m_sortedSet.last()) > 0) {
                m_sortedSet.pollFirst();
                return super.add(element);
            }
            return false;
        }
        return super.add(element);
    }

    @Override
    public boolean addAll(Collection<? extends T> collection) {
        boolean hasChanged = false;
        for (T element : collection) {
            hasChanged |= m_sortedSet.add(element);
        }
        return hasChanged;
    }

    @Override
    protected Set<T> delegate() {
        return m_sortedSet;
    }

}

redpajama_set_name: RedPajamaGithub


text:
module GroupedScope
  module Arish
    module Associations
      module Builder
        class GroupedAssociation

          attr_reader :model, :ungrouped_name, :ungrouped_reflection, :grouped_name, :grouped_options

          def self.build(model, *association_names)
            association_names.each { |ungrouped_name| new(model, ungrouped_name).build }
          end

          def initialize(model, ungrouped_name)
            @model = model
            @ungrouped_name = ungrouped_name
            @ungrouped_reflection = find_ungrouped_reflection
            @grouped_name = :"grouped_scope_#{ungrouped_name}"
            @grouped_options = copy_ungrouped_reflection_options
          end

          def build
            model.send(ungrouped_reflection.macro, grouped_name, grouped_options).tap do |grouped_reflection|
              grouped_reflection.grouped_scope = true
              model.grouped_reflections = model.grouped_reflections.merge(ungrouped_name => grouped_reflection)
              define_grouped_scope_reader
            end
          end

          private

          def define_grouped_scope_reader
            model.send(:define_method, :group) do
              @group ||= GroupedScope::SelfGroupping.new(self)
            end
          end

          def find_ungrouped_reflection
            model.reflections[ungrouped_name]
          end

          def copy_ungrouped_reflection_options
            ungrouped_reflection.options.dup
          end

        end
      end
    end
  end
end


text:
package com.hubspot.singularity;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Optional;
import java.util.function.Function;

public class SingularityRequestWithState {
  private final SingularityRequest request;
  private final RequestState state;
  private final long timestamp;

  public static Function<SingularityRequestWithState, String> REQUEST_STATE_TO_REQUEST_ID = input ->
    input.getRequest().getId();

  public static String getRequestState(
    Optional<SingularityRequestWithState> maybeRequestWithState
  ) {
    if (maybeRequestWithState.isPresent()) {
      return maybeRequestWithState.get().getState().name();
    }
    return "MISSING";
  }

  public static boolean isActive(
    Optional<SingularityRequestWithState> maybeRequestWithState
  ) {
    return (
      maybeRequestWithState.isPresent() &&
      maybeRequestWithState.get().getState().isRunnable()
    );
  }

  @JsonCreator
  public SingularityRequestWithState(
    @JsonProperty("request") SingularityRequest request,
    @JsonProperty("state") RequestState state,
    @JsonProperty("timestamp") long timestamp
  ) {
    this.request = request;
    this.state = state;
    this.timestamp = timestamp;
  }

  public long getTimestamp() {
    return timestamp;
  }

  public RequestState getState() {
    return state;
  }

  public SingularityRequest getRequest() {
    return request;
  }

  @Override
  public String toString() {
    return (
      "SingularityRequestWithState{" +
      "request=" +
      request +
      ", state=" +
      state +
      ", timestamp=" +
      timestamp +
      '}'
    );
  }
}


text:
package br.com.hdev.bean;

import java.io.Serializable;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;

import br.com.hdev.dao.LogDAO;
import br.com.hdev.dao.impl.LogDAOImpl;
import br.com.hdev.entity.Log;
import br.com.hdev.exceptions.DBCommitException;
import br.com.hdev.singleton.EMFactorySingleton;

/**
 *
 * Classe que se comunica com a entidade Log, responsável pelo seu cadastro.
 *
 * @author HDEV
 *
 */
@ManagedBean
@RequestScoped
public class LogBean implements Serializable {

	private Log log;
	private LogDAO dao;

	private int id;

	@PostConstruct
	private void init() {
		EntityManager em = EMFactorySingleton.getInstance();
		log = new Log();
		dao = new LogDAOImpl(em);
	}

	public void cadastrar() {
		FacesMessage msg;

		try {
			dao.create(log);
			msg = new FacesMessage("Cadastrado com Sucesso !");
		} catch (DBCommitException e) {
			e.printStackTrace();
			msg = new FacesMessage("Erro ao Cadastrar");
		}
		FacesContext.getCurrentInstance().addMessage(null, msg);
	}

	public Log getLog() {
		return log;
	}

	public void setLog(Log log) {
		this.log = log;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

}


text:
#import <GoogleDataTransport/GDTCORTransport.h>

NS_ASSUME_NONNULL_BEGIN

/** A fake for GDTCORTransport that can be used in tests. */
@interface GDTCORTransportFake : GDTCORTransport

/** All log events that have been logged. */
@property(nonatomic, readonly) NSArray<GDTCOREvent *> *logEvents;

/** All logged events are cleared from memory, resetting the fake. */
- (void)reset;

@end

NS_ASSUME_NONNULL_END


text:
package javaemul.internal;

import java.util.Iterator;
import javaemul.internal.annotations.DoNotAutobox;
import jsinterop.annotations.JsFunction;
import jsinterop.annotations.JsMethod;
import jsinterop.annotations.JsPackage;
import jsinterop.annotations.JsProperty;
import jsinterop.annotations.JsType;

/** Provides utilities to perform operations on Arrays. */
public final class ArrayHelper {

  public static final int ARRAY_PROCESS_BATCH_SIZE = 10000;

  public static <T> T[] clone(T[] array) {
    Object result = asNativeArray(array).slice();
    return ArrayStamper.stampJavaTypeInfo(result, array);
  }

  public static <T> T[] clone(T[] array, int fromIndex, int toIndex) {
    Object result = unsafeClone(array, fromIndex, toIndex);
    // array.slice doesn't expand if toIndex > array.length
    setLength(result, toIndex - fromIndex);
    return ArrayStamper.stampJavaTypeInfo(result, array);
  }

  /**
   * Unlike clone, this method returns a copy of the array that is not type marked, nor size
   * guaranteed. This is only safe for temp arrays as returned array will not do any type checks.
   */
  public static Object[] unsafeClone(Object array, int fromIndex, int toIndex) {
    return asNativeArray(array).slice(fromIndex, toIndex);
  }

  public static <T> T[] createFrom(T[] array, int length) {
    return ArrayStamper.stampJavaTypeInfo(new NativeArray(length), array);
  }

  @JsMethod(name = "Array.isArray", namespace = JsPackage.GLOBAL)
  public static native boolean isArray(Object o);

  public static int getLength(Object array) {
    return asNativeArray(array).length;
  }

  public static void setLength(Object array, int length) {
    asNativeArray(array).length = length;
  }

  public static void push(Object array, @DoNotAutobox Object o) {
    asNativeArray(array).push(o);
  }

  /**
   * Sets an element of an array.
   *
   * <p>In GWT, the naive approach of checking or setting an element which may be out of bounds is
   * optimal. This method always returns the original value, or null for out of bounds.
   */
  public static <T> T setAt(T[] array, int index, T value) {
    T originalValue = array[index];
    array[index] = value;
    return originalValue;
  }

  public static void removeFrom(Object[] array, int index, int deleteCount) {
    asNativeArray(array).splice(index, deleteCount);
  }

  public static void insertTo(Object[] array, int index, Object value) {
    asNativeArray(array).splice(index, 0, value);
  }

  public static void insertTo(Object[] array, int index, Object[] values) {
    copy(values, 0, array, index, values.length, false);
  }

  public static void copy(Object array, int srcOfs, Object dest, int destOfs, int len) {
    copy(array, srcOfs, dest, destOfs, len, true);
  }

  private static void copy(
      Object src, int srcOfs, Object dest, int destOfs, int len, boolean overwrite) {

    if (len == 0) {
      return;
    }

    /*
     * Array.prototype.splice is not used directly to overcome the limits imposed to the number of
     * function parameters by browsers.
     */

    if (src == dest) {
      // copying to the same array, make a copy first
      src = unsafeClone(src, srcOfs, srcOfs + len);
      srcOfs = 0;
    }
    NativeArray destArray = asNativeArray(dest);
    for (int batchStart = srcOfs, end = srcOfs + len; batchStart < end;) {
      // increment in block
      int batchEnd = Math.min(batchStart + ARRAY_PROCESS_BATCH_SIZE, end);
      len = batchEnd - batchStart;
      Object[] spliceArgs = unsafeClone(src, batchStart, batchEnd);
      asNativeArray(spliceArgs).splice(0, 0, (double) destOfs, (double) (overwrite ? len : 0));
      getSpliceFunction().apply(destArray, spliceArgs);
      batchStart = batchEnd;
      destOfs += len;
    }
  }

  @JsType(isNative = true, name = "Function", namespace = JsPackage.GLOBAL)
  private static class NativeFunction {
    public native String apply(Object thisContext, Object[] argsArray);
  }

  @JsProperty(name = "Array.prototype.splice", namespace = JsPackage.GLOBAL)
  private static native NativeFunction getSpliceFunction();

  /** Compare function for sort. */
  @JsFunction
  public interface CompareFunction {
    double compare(Object d1, Object d2);
  }

  public static void sort(Object array, CompareFunction fn) {
    asNativeArray(array).sort(fn);
  }

  // TODO(b/234777938): Remove once the stdlib is in with their implementation of ArrayIterators.
  public static <T> Iterator<T> arrayIterator(T[] array) {
    return new ArrayIterator<>(array);
  }

  public static Iterator arrayIterator(byte[] array) {
    throw new UnsupportedOperationException();
  }

  public static Iterator arrayIterator(short[] array) {
    throw new UnsupportedOperationException();
  }

  public static Iterator arrayIterator(char[] array) {
    throw new UnsupportedOperationException();
  }

  public static IntArrayIterator arrayIterator(int[] array) {
    return new IntArrayIterator(array);
  }

  public static Iterator arrayIterator(long[] array) {
    throw new UnsupportedOperationException();
  }

  public static Iterator arrayIterator(float[] array) {
    throw new UnsupportedOperationException();
  }

  public static Iterator arrayIterator(double[] array) {
    throw new UnsupportedOperationException();
  }

  public static Iterator arrayIterator(boolean[] array) {
    throw new UnsupportedOperationException();
  }

  private static final class IntArrayIterator {
    private int index = 0;
    private int[] array;

    private IntArrayIterator(int[] array) {
      this.array = array;
    }

    public boolean hasNext() {
      return index < array.length;
    }

    public int next() {
      return array[index++];
    }
  }

  private static final class ArrayIterator<T> implements Iterator<T> {
    private int index = 0;
    private T[] array;

    private ArrayIterator(T[] array) {
      this.array = array;
    }

    @Override
    public boolean hasNext() {
      return index < array.length;
    }

    @Override
    public T next() {
      return array[index++];
    }
  }

  private static NativeArray asNativeArray(Object array) {
    return JsUtils.uncheckedCast(array);
  }

  @JsType(isNative = true, name = "Array", namespace = JsPackage.GLOBAL)
  private static class NativeArray {
    int length;

    NativeArray(int length) {}

    native void push(@DoNotAutobox Object item);

    native Object[] slice();

    native Object[] slice(int fromIndex, int toIndex);

    native void splice(int index, int deleteCount, Object... value);

    native <T> void sort(CompareFunction compareFunction);
  }

  private ArrayHelper() {}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Qt 4.8: submarine_p.h Example File (demos/sub-attaq/submarine_p.h)</title>
  <link rel="stylesheet" type="text/css" href="style/style.css" />

  <link rel="stylesheet" type="text/css" href="style/superfish.css" />
  <link rel="stylesheet" type="text/css" href="style/narrow.css" />

      Home

    Qt Reference Documentation

Qt HOME

DEV

          DOC

BLOG

Qt 4.8

ALL VERSIONS

API Lookup

Class index

Function index

Modules

Namespaces

Global Declarations

QML elements

Qt Topics

Programming with Qt

Device UIs & Qt Quick

UI Design with Qt

Supported Platforms

Qt and Key Technologies

How-To's and Best Practices

Examples

Examples

Tutorials

Demos

QML Examples

          Search index:

          <form id="qtdocsearch" action="" onsubmit="return false;">
            <fieldset>
              <input type="text" name="searchstring" id="pageType" value="" />

 Close

All | API | Articles | Examples

 results:

            </fieldset>
          </form>

            API Lookup

Class index

Function index

Modules

Namespaces

Global Declarations

QML elements

            Qt Topics

Programming with Qt

Device UIs & Qt Quick

UI Design with Qt

Supported Platforms

Qt and Key Technologies

How-To's and Best Practices

            Examples

Examples

Tutorials

Demos

QML Examples

Home

A

A

A

                Print

submarine_p.h Example File

demos/sub-attaq/submarine_p.h

 #ifndef SUBMARINE_P_H
 #define SUBMARINE_P_H

 //
 //  W A R N I N G
 //  -------------
 //
 // This file is not part of the Qt API.  It exists purely as an
 // implementation detail.  This header file may change from version to
 // version without notice, or even be removed.
 //
 // We mean it.
 //

 //Own
 #include "animationmanager.h"
 #include "submarine.h"
 #include "qanimationstate.h"

 //Qt
 #include <QtCore/QPropertyAnimation>
 #include <QtGui/QGraphicsScene>

 //This state is describing when the boat is moving right
 class MovementState : public QAnimationState
 {
 Q_OBJECT
 public:
     MovementState(SubMarine *submarine, QState *parent = 0) : QAnimationState(parent)
     {
         movementAnimation = new QPropertyAnimation(submarine, "pos");
         connect(movementAnimation,SIGNAL(valueChanged(const QVariant &)),this,SLOT(onAnimationMovementValueChanged(const QVariant &)));
         setAnimation(movementAnimation);
         AnimationManager::self()->registerAnimation(movementAnimation);
         this->submarine = submarine;
     }

 protected slots:
     void onAnimationMovementValueChanged(const QVariant &)
     {
         if (qrand() % 200 + 1 == 3)
             submarine->launchTorpedo(qrand() % 3 + 1);
     }

 protected:
     void onEntry(QEvent *e)
     {
         if (submarine->currentDirection() == SubMarine::Left) {
             movementAnimation->setEndValue(QPointF(0,submarine->y()));
             movementAnimation->setDuration(submarine->x()/submarine->currentSpeed()*12);
         }
         else /*if (submarine->currentDirection() == SubMarine::Right)*/ {
             movementAnimation->setEndValue(QPointF(submarine->scene()->width()-submarine->size().width(),submarine->y()));
             movementAnimation->setDuration((submarine->scene()->width()-submarine->size().width()-submarine->x())/submarine->currentSpeed()*12);
         }
         QAnimationState::onEntry(e);
     }

 private:
     SubMarine *submarine;
     QPropertyAnimation *movementAnimation;
 };

 //This state is describing when the boat is moving right
 class ReturnState : public QAnimationState
 {
 public:
     ReturnState(SubMarine *submarine, QState *parent = 0) : QAnimationState(parent)
     {
         returnAnimation = new QPropertyAnimation(submarine->rotation(), "angle");
         returnAnimation->setDuration(500);
         AnimationManager::self()->registerAnimation(returnAnimation);
         setAnimation(returnAnimation);
         this->submarine = submarine;
     }

 protected:
     void onEntry(QEvent *e)
     {
         returnAnimation->stop();
         returnAnimation->setEndValue(submarine->currentDirection() == SubMarine::Right ? 360. : 180.);
         QAnimationState::onEntry(e);
     }

     void onExit(QEvent *e)
     {
         submarine->currentDirection() == SubMarine::Right ? submarine->setCurrentDirection(SubMarine::Left) : submarine->setCurrentDirection(SubMarine::Right);
         QAnimationState::onExit(e);
     }

 private:
     SubMarine *submarine;
     QPropertyAnimation *returnAnimation;
 };

 #endif // SUBMARINE_P_H

      <acronym title="Copyright">©</acronym> 2013 Digia Plc and/or its
      subsidiaries. Documentation contributions included herein are the copyrights of
      their respective owners.

      The documentation provided herein is licensed under the terms of the
      GNU Free Documentation
      License version 1.3 as published by the Free Software Foundation.

      Documentation sources may be obtained from
      www.qt-project.org.

      Digia, Qt and their respective logos are trademarks of Digia Plc
      in Finland and/or other countries worldwide. All other trademarks are property
      of their respective owners. Privacy Policy


text:
<?php

namespace Amex\TriviaBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use \Symfony\Component\HttpFoundation\Request;

class EmailController extends Controller
{
    public function bienvenidaAction()
    {
        $request = $this->getRequest();
        $baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath().'/';
        return $this->render('AmexTriviaBundle:Email:bienvenida.html.twig',array('baseUrl'=>$baseurl));
    }
    public function mecanicaAction()
    {
        $request = $this->getRequest();
        $baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath().'/';
        return $this->render('AmexTriviaBundle:Email:mecanica.html.twig',array('baseUrl'=>$baseurl));
    }
    public function motivadorAction()
    {
        $request = $this->getRequest();
        $baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath().'/';
        return $this->render('AmexTriviaBundle:Email:motivador.html.twig',array('baseUrl'=>$baseurl));
    }
    public function ganadorDiaAction()
    {
        $request = $this->getRequest();
        $baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath().'/';
        return $this->render('AmexTriviaBundle:Email:ganadorDelDia.html.twig',array('baseUrl'=>$baseurl));
    }
    public function ganadorFinalAction()
    {
        $request = $this->getRequest();
        $baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath().'/';
        return $this->render('AmexTriviaBundle:Email:ganadorFinal.html.twig',array('baseUrl'=>$baseurl));
    }

}


text:
module Gitlab
  module Jira
    # Gitlab JIRA HTTP client to be used with jira-ruby gem, this subclasses JIRA::HTTPClient.
    # Uses Gitlab::HTTP to make requests to JIRA REST API.
    # The parent class implementation can be found at: https://github.com/sumoheavy/jira-ruby/blob/v1.7.0/lib/jira/http_client.rb
    class HttpClient < JIRA::HttpClient
      extend ::Gitlab::Utils::Override

      override :request
      def request(*args)
        result = make_request(*args)

        raise JIRA::HTTPError.new(result) unless result.response.is_a?(Net::HTTPSuccess)

        result
      end

      override :make_cookie_auth_request
      def make_cookie_auth_request
        body = {
          username: @options.delete(:username),
          password: @options.delete(:password)
        }.to_json

        make_request(:post, @options[:context_path] + '/rest/auth/1/session', body, 'Content-Type' => 'application/json')
      end

      override :make_request
      def make_request(http_method, path, body = '', headers = {})
        request_params = { headers: headers }
        request_params[:body] = body if body.present?
        request_params[:headers][:Cookie] = get_cookies if options[:use_cookies]
        request_params[:timeout] = options[:read_timeout] if options[:read_timeout]
        request_params[:base_uri] = uri.to_s
        request_params.merge!(auth_params)

        result = Gitlab::HTTP.public_send(http_method, path, **request_params) # rubocop:disable GitlabSecurity/PublicSend
        @authenticated = result.response.is_a?(Net::HTTPOK)
        store_cookies(result) if options[:use_cookies]

        result
      end

      def auth_params
        return {} unless @options[:username] && @options[:password]

        {
          basic_auth: {
            username: @options[:username],
            password: @options[:password]
          }
        }
      end

      private

      def get_cookies
        cookie_array = @cookies.values.map { |cookie| "#{cookie.name}=#{cookie.value[0]}" }
        cookie_array += Array(@options[:additional_cookies]) if @options.key?(:additional_cookies)
        cookie_array.join('; ') if cookie_array.any?
      end
    end
  end
end


text:
<?php
/**
 * Contains \jamesiarmes\PhpEws\Type\ConversationType.
 */

namespace jamesiarmes\PhpEws\Type;

use \jamesiarmes\PhpEws\Type;

/**
 * Represents a single conversation.
 *
 * @package php-ews\Type
 */
class ConversationType extends Type
{
    /**
     * Contains a collection of strings that identify the categories that are
     * applied to all conversation items in the current folder.
     *
     * @since Exchange 2010 SP1
     *
     * @var \jamesiarmes\PhpEws\ArrayType\ArrayOfStringsType
     */
    public $Categories;

    /**
     * Represents the identifier of a conversation.
     *
     * @since Exchange 2010 SP1
     *
     * @var \jamesiarmes\PhpEws\Type\ItemIdType
     */
    public $ConversationId;

    /**
     * Represents the conversation topic.
     *
     * This element is read-only.
     *
     * @since Exchange 2010 SP1
     *
     * @var string
     */
    public $ConversationTopic;

    /**
     * Contains the aggregated flag status for conversation items in the current
     * folder.
     *
     * @since Exchange 2010 SP1
     *
     * @var string
     *
     * @see \jamesiarmes\PhpEws\Enumeration\FlagStatusType
     */
    public $FlagStatus;

    /**
     * Contains the category list for all conversation items in a mailbox.
     *
     * @since Exchange 2010 SP1
     *
     * @var \jamesiarmes\PhpEws\ArrayType\ArrayOfStringsType
     */
    public $GlobalCategories;

    /**
     * Contains the aggregated flag status for all conversation items in a
     * mailbox.
     *
     * @since Exchange 2010 SP1
     *
     * @var string
     *
     * @see \jamesiarmes\PhpEws\Enumeration\FlagStatusType
     */
    public $GlobalFlagStatus;

    /**
     * Contains a value that indicates whether at least one conversation item in
     * a mailbox has an attachment.
     *
     * @since Exchange 2010 SP1
     *
     * @var boolean
     */
    public $GlobalHasAttachments;

    /**
     * Contains the aggregated importance for all conversation items in a
     * mailbox.
     *
     * @since Exchange 2010 SP1
     *
     * @var string
     *
     * @see \jamesiarmes\PhpEws\Enumeration\ImportanceChoicesType
     */
    public $GlobalImportance;

    /**
     * Contains a list of item classes that represents all the item classes of
     * the conversation items in a mailbox.
     *
     * @since Exchange 2010 SP1
     *
     * @var \jamesiarmes\PhpEws\ArrayType\ArrayOfItemClassType
     */
    public $GlobalItemClasses;

    /**
     * Contains the collection of item identifiers for all conversation items in
     * a mailbox.
     *
     * @since Exchange 2010 SP1
     *
     * @var \jamesiarmes\PhpEws\ArrayType\NonEmptyArrayOfBaseItemIdsType
     */
    public $GlobalItemIds;

    /**
     * Contains the delivery time of the message that was last received in this
     * conversation across all folders in the mailbox.
     *
     * @since Exchange 2010 SP1
     *
     * @var string
     *
     * @todo Make a DateTime object.
     */
    public $GlobalLastDeliveryTime;

    /**
     * Contains the total number of conversation items in the mailbox.
     *
     * @since Exchange 2010 SP1
     *
     * @var integer
     */
    public $GlobalMessageCount;

    /**
     * Contains the size of the conversation calculated from the size of all
     * conversation items in the mailbox.
     *
     * @since Exchange 2010 SP1
     *
     * @var integer
     */
    public $GlobalSize;

    /**
     * Contains the recipient list of a conversation aggregated across a
     * mailbox.
     *
     * This element is read-only.
     *
     * @since Exchange 2010 SP1
     *
     * @var \jamesiarmes\PhpEws\ArrayType\ArrayOfStringsType
     */
    public $GlobalUniqueRecipients;

    /**
     * Contains a list of all the senders of conversation items in the mailbox.
     *
     * @since Exchange 2010 SP1
     *
     * @var \jamesiarmes\PhpEws\ArrayType\ArrayOfStringsType
     */
    public $GlobalUniqueSenders;

    /**
     * Contains a list of all the people who have sent messages that are
     * currently unread in this conversation across all folders in the mailbox.
     *
     * @since Exchange 2010 SP1
     *
     * @var \jamesiarmes\PhpEws\ArrayType\ArrayOfStringsType
     */
    public $GlobalUniqueUnreadSenders;

    /**
     * Contains a count of all the unread conversation items in the mailbox.
     *
     * @since Exchange 2010 SP1
     *
     * @var integer
     */
    public $GlobalUnreadCount;

    /**
     * Contains a value that indicates whether at least one conversation item in
     * the current folder has an attachment.
     *
     * @since Exchange 2010 SP1
     *
     * @var boolean
     */
    public $HasAttachments;

    /**
     * Contains the aggregated importance for all conversation items in the
     * current folder.
     *
     * @since Exchange 2010 SP1
     *
     * @var string
     *
     * @see \jamesiarmes\PhpEws\Enumeration\ImportanceChoicesType
     */
    public $Importance;

    /**
     * Contains a list of item classes that represents all the item classes of
     * the conversation items in the current folder.
     *
     * @since Exchange 2010 SP1
     *
     * @var \jamesiarmes\PhpEws\ArrayType\ArrayOfItemClassType
     */
    public $ItemClasses;

    /**
     * Contains the collection of item identifiers for all conversation items in
     * the current folder.
     *
     * @since Exchange 2010 SP1
     *
     * @var \jamesiarmes\PhpEws\ArrayType\NonEmptyArrayOfBaseItemIdsType
     */
    public $ItemIds;

    /**
     * Contains the delivery time of the message that was last received in this
     * conversation in the current folder.
     *
     * @since Exchange 2010 SP1
     *
     * @var string
     *
     * @todo Make a DateTime object.
     */
    public $LastDeliveryTime;

    /**
     * Contains the total number of conversation items in the current folder.
     *
     * @since Exchange 2010 SP1
     *
     * @var integer
     */
    public $MessageCount;

    /**
     * Contains the conversation size calculated from the size of all
     * conversation items in the current folder.
     *
     * @since Exchange 2010 SP1
     *
     * @var integer
     */
    public $Size;

    /**
     * Contains the recipient list of a conversation aggregated from a
     * particular folder.
     *
     * This element is read-only.
     *
     * @since Exchange 2010 SP1
     *
     * @var \jamesiarmes\PhpEws\ArrayType\ArrayOfStringsType
     */
    public $UniqueRecipients;

    /**
     * Contains a list of all the senders of conversation items in the current
     * folder.
     *
     * This element is read-only.
     *
     * @since Exchange 2010 SP1
     *
     * @var \jamesiarmes\PhpEws\ArrayType\ArrayOfStringsType
     */
    public $UniqueSenders;

    /**
     * Contains a list of all the people who have sent messages that are
     * currently unread in this conversation in the current folder.
     *
     * This element is read-only.
     *
     * @since Exchange 2010 SP1
     *
     * @var \jamesiarmes\PhpEws\ArrayType\ArrayOfStringsType
     */
    public $UniqueUnreadSenders;

    /**
     * Contains the count of unread conversation items within a folder.
     *
     * @since Exchange 2010 SP1
     *
     * @var integer
     */
    public $UnreadCount;
}


text:
using System;

namespace stRrd.Core
{

	/// <summary>
	/// Class to represent internal RRD archive state for a single datasource.
	/// </summary>
	/// <remarks>Objects of this class are never manipulated directly, it's up to the RRDSharp
	/// framework to manage internal arcihve states.
	/// </remarks>
	public class ArcState : IRrdUpdatable
	{
		private Archive parentArc;

		private RrdDouble accumValue;
		private RrdLong nanSteps;

		/// <summary>
		///
		/// </summary>
		/// <param name="parentArc"></param>
		public ArcState(Archive parentArc)
		{
			this.parentArc = parentArc;
			if(RrdFile.RrdMode == RrdFile.MODE_CREATE)
			{
				// should initialize
				Header header = parentArc.ParentDb.Header;
				long step = header.Step;
				long lastUpdateTime = header.LastUpdateTime;
				long arcStep = parentArc.ArcStep;
				long nan = (Util.Normalize(lastUpdateTime, step) -
					Util.Normalize(lastUpdateTime, arcStep)) / step;
				accumValue = new RrdDouble(Double.NaN, this);
				nanSteps = new RrdLong(nan, this);
			}
			else
			{
				accumValue = new RrdDouble(this);
				nanSteps = new RrdLong(this);
			}

		}

		/// <summary>
		///
		/// </summary>
		public RrdFile RrdFile
		{
			get
			{
				return parentArc.ParentDb.RrdFile;
			}
		}

		/// <summary>
		///
		/// </summary>
		/// <returns></returns>
		public string Dump()
		{
			return "accumValue:" + accumValue.Get() + " nanSteps:" + nanSteps.Get() + "\n";
		}

		/// <summary>
		///
		/// </summary>
		public long NanSteps
		{
			get
			{
				return nanSteps.Get();
			}
			set
			{
				nanSteps.Set(value);
			}
		}

		/// <summary>
		///
		/// </summary>
		public double AccumValue
		{
			get
			{
				return accumValue.Get();
			}
			set
			{
				accumValue.Set(value);
			}
		}

		/// <summary>
		///
		/// </summary>
		public Archive Parent
		{
			get
			{
				return parentArc;
			}
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="other"></param>
		public void CopyStateTo(IRrdUpdatable other)
		{
			if(!(other is ArcState))
			{
				throw new RrdException("Cannot copy ArcState object to " + other.ToString());
			}
			ArcState arcState = (ArcState) other;
			arcState.accumValue.Set(accumValue.Get());
			arcState.nanSteps.Set(nanSteps.Get());
}

	}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Nova Hedwigia, Beih. 29: 229 (1969)

#### Original name
Stropharia aeruginosa var. neuquenensis M.M. Moser & Singer

### Remarks
null


text:
/**
 * @file
 * ClockedObject declaration and implementation.
 */

#ifndef __SIM_CLOCKED_OBJECT_HH__
#define __SIM_CLOCKED_OBJECT_HH__

#include "base/intmath.hh"
#include "base/misc.hh"
#include "params/ClockedObject.hh"
#include "sim/core.hh"
#include "sim/sim_object.hh"

/**
 * The ClockedObject class extends the SimObject with a clock and
 * accessor functions to relate ticks to the cycles of the object.
 */
class ClockedObject : public SimObject
{

  private:

    // the tick value of the next clock edge (>= curTick()) at the
    // time of the last call to update()
    mutable Tick tick;

    // The cycle counter value corresponding to the current value of
    // 'tick'
    mutable Cycles cycle;

    /**
     * Prevent inadvertent use of the copy constructor and assignment
     * operator by making them private.
     */
    ClockedObject(ClockedObject&);
    ClockedObject& operator=(ClockedObject&);

    /**
     *  Align cycle and tick to the next clock edge if not already done.
     */
    void update() const
    {
        // both tick and cycle are up-to-date and we are done, note
        // that the >= is important as it captures cases where tick
        // has already passed curTick()
        if (tick >= curTick())
            return;

        // optimise for the common case and see if the tick should be
        // advanced by a single clock period
        tick += clock;
        ++cycle;

        // see if we are done at this point
        if (tick >= curTick())
            return;

        // if not, we have to recalculate the cycle and tick, we
        // perform the calculations in terms of relative cycles to
        // allow changes to the clock period in the future
        Cycles elapsedCycles(divCeil(curTick() - tick, clock));
        cycle += elapsedCycles;
        tick += elapsedCycles * clock;
    }

    // Clock period in ticks
    Tick clock;

  protected:

    /**
     * Create a clocked object and set the clock based on the
     * parameters.
     */
    ClockedObject(const ClockedObjectParams* p) :
        SimObject(p), tick(0), cycle(0), clock(p->clock)
    {
        if (clock == 0) {
            fatal("%s has a clock period of zero\n", name());
        }
    }

    /**
     * Virtual destructor due to inheritance.
     */
    virtual ~ClockedObject() { }

    /**
     * Reset the object's clock using the current global tick value. Likely
     * to be used only when the global clock is reset. Currently, this done
     * only when Ruby is done warming up the memory system.
     */
    void resetClock() const
    {
        Cycles elapsedCycles(divCeil(curTick(), clock));
        cycle = elapsedCycles;
        tick = elapsedCycles * clock;
    }

  public:

    /**
     * Determine the tick when a cycle begins, by default the current
     * one, but the argument also enables the caller to determine a
     * future cycle.
     *
     * @param cycles The number of cycles into the future
     *
     * @return The tick when the clock edge occurs
     */
    inline Tick clockEdge(Cycles cycles = Cycles(0)) const
    {
        // align tick to the next clock edge
        update();

        // figure out when this future cycle is
        return tick + clock * cycles;
    }

    /**
     * Determine the current cycle, corresponding to a tick aligned to
     * a clock edge.
     *
     * @return The current cycle count
     */
    inline Cycles curCycle() const
    {
        // align cycle to the next clock edge.
        update();

        return cycle;
    }

    /**
     * Based on the clock of the object, determine the tick when the next
     * cycle begins, in other words, return the next clock edge.
     * (This can never be the current tick.)
     *
     * @return The tick when the next cycle starts
     */
    Tick nextCycle() const
    { return clockEdge(Cycles(1)); }

    inline uint64_t frequency() const { return SimClock::Frequency / clock; }

    inline Tick clockPeriod() const { return clock; }

    inline Cycles ticksToCycles(Tick t) const
    { return Cycles(t / clock); }

};

#endif //__SIM_CLOCKED_OBJECT_HH__


text:
package spark

import network.ConnectionManagerId
import org.scalatest.FunSuite
import org.scalatest.BeforeAndAfter
import org.scalatest.concurrent.Timeouts._
import org.scalatest.matchers.ShouldMatchers
import org.scalatest.prop.Checkers
import org.scalatest.time.{Span, Millis}
import org.scalacheck.Arbitrary._
import org.scalacheck.Gen
import org.scalacheck.Prop._
import org.eclipse.jetty.server.{Server, Request, Handler}

import com.google.common.io.Files

import scala.collection.mutable.ArrayBuffer

import SparkContext._
import storage.{GetBlock, BlockManagerWorker, StorageLevel}
import ui.JettyUtils

class NotSerializableClass
class NotSerializableExn(val notSer: NotSerializableClass) extends Throwable() {}

class DistributedSuite extends FunSuite with ShouldMatchers with BeforeAndAfter
  with LocalSparkContext {

  val clusterUrl = "local-cluster[2,1,512]"

  after {
    System.clearProperty("spark.reducer.maxMbInFlight")
    System.clearProperty("spark.storage.memoryFraction")
  }

  test("task throws not serializable exception") {
    // Ensures that executors do not crash when an exn is not serializable. If executors crash,
    // this test will hang. Correct behavior is that executors don't crash but fail tasks
    // and the scheduler throws a SparkException.

    // numSlaves must be less than numPartitions
    val numSlaves = 3
    val numPartitions = 10

    sc = new SparkContext("local-cluster[%s,1,512]".format(numSlaves), "test")
    val data = sc.parallelize(1 to 100, numPartitions).
      map(x => throw new NotSerializableExn(new NotSerializableClass))
    intercept[SparkException] {
      data.count()
    }
    resetSparkContext()
  }

  test("local-cluster format") {
    sc = new SparkContext("local-cluster[2,1,512]", "test")
    assert(sc.parallelize(1 to 2, 2).count() == 2)
    resetSparkContext()
    sc = new SparkContext("local-cluster[2 , 1 , 512]", "test")
    assert(sc.parallelize(1 to 2, 2).count() == 2)
    resetSparkContext()
    sc = new SparkContext("local-cluster[2, 1, 512]", "test")
    assert(sc.parallelize(1 to 2, 2).count() == 2)
    resetSparkContext()
    sc = new SparkContext("local-cluster[ 2, 1, 512 ]", "test")
    assert(sc.parallelize(1 to 2, 2).count() == 2)
    resetSparkContext()
  }

  test("simple groupByKey") {
    sc = new SparkContext(clusterUrl, "test")
    val pairs = sc.parallelize(Array((1, 1), (1, 2), (1, 3), (2, 1)), 5)
    val groups = pairs.groupByKey(5).collect()
    assert(groups.size === 2)
    val valuesFor1 = groups.find(_._1 == 1).get._2
    assert(valuesFor1.toList.sorted === List(1, 2, 3))
    val valuesFor2 = groups.find(_._1 == 2).get._2
    assert(valuesFor2.toList.sorted === List(1))
  }

  test("groupByKey where map output sizes exceed maxMbInFlight") {
    System.setProperty("spark.reducer.maxMbInFlight", "1")
    sc = new SparkContext(clusterUrl, "test")
    // This data should be around 20 MB, so even with 4 mappers and 2 reducers, each map output
    // file should be about 2.5 MB
    val pairs = sc.parallelize(1 to 2000, 4).map(x => (x % 16, new Array[Byte](10000)))
    val groups = pairs.groupByKey(2).map(x => (x._1, x._2.size)).collect()
    assert(groups.length === 16)
    assert(groups.map(_._2).sum === 2000)
    // Note that spark.reducer.maxMbInFlight will be cleared in the test suite's after{} block
  }

  test("accumulators") {
    sc = new SparkContext(clusterUrl, "test")
    val accum = sc.accumulator(0)
    sc.parallelize(1 to 10, 10).foreach(x => accum += x)
    assert(accum.value === 55)
  }

  test("broadcast variables") {
    sc = new SparkContext(clusterUrl, "test")
    val array = new Array[Int](100)
    val bv = sc.broadcast(array)
    array(2) = 3     // Change the array -- this should not be seen on workers
    val rdd = sc.parallelize(1 to 10, 10)
    val sum = rdd.map(x => bv.value.sum).reduce(_ + _)
    assert(sum === 0)
  }

  test("repeatedly failing task") {
    sc = new SparkContext(clusterUrl, "test")
    val accum = sc.accumulator(0)
    val thrown = intercept[SparkException] {
      sc.parallelize(1 to 10, 10).foreach(x => println(x / 0))
    }
    assert(thrown.getClass === classOf[SparkException])
    assert(thrown.getMessage.contains("more than 4 times"))
  }

  test("caching") {
    sc = new SparkContext(clusterUrl, "test")
    val data = sc.parallelize(1 to 1000, 10).cache()
    assert(data.count() === 1000)
    assert(data.count() === 1000)
    assert(data.count() === 1000)
  }

  test("caching on disk") {
    sc = new SparkContext(clusterUrl, "test")
    val data = sc.parallelize(1 to 1000, 10).persist(StorageLevel.DISK_ONLY)
    assert(data.count() === 1000)
    assert(data.count() === 1000)
    assert(data.count() === 1000)
  }

  test("caching in memory, replicated") {
    sc = new SparkContext(clusterUrl, "test")
    val data = sc.parallelize(1 to 1000, 10).persist(StorageLevel.MEMORY_ONLY_2)
    assert(data.count() === 1000)
    assert(data.count() === 1000)
    assert(data.count() === 1000)
  }

  test("caching in memory, serialized, replicated") {
    sc = new SparkContext(clusterUrl, "test")
    val data = sc.parallelize(1 to 1000, 10).persist(StorageLevel.MEMORY_ONLY_SER_2)
    assert(data.count() === 1000)
    assert(data.count() === 1000)
    assert(data.count() === 1000)
  }

  test("caching on disk, replicated") {
    sc = new SparkContext(clusterUrl, "test")
    val data = sc.parallelize(1 to 1000, 10).persist(StorageLevel.DISK_ONLY_2)
    assert(data.count() === 1000)
    assert(data.count() === 1000)
    assert(data.count() === 1000)
  }

  test("caching in memory and disk, replicated") {
    sc = new SparkContext(clusterUrl, "test")
    val data = sc.parallelize(1 to 1000, 10).persist(StorageLevel.MEMORY_AND_DISK_2)
    assert(data.count() === 1000)
    assert(data.count() === 1000)
    assert(data.count() === 1000)
  }

  test("caching in memory and disk, serialized, replicated") {
    sc = new SparkContext(clusterUrl, "test")
    val data = sc.parallelize(1 to 1000, 10).persist(StorageLevel.MEMORY_AND_DISK_SER_2)

    assert(data.count() === 1000)
    assert(data.count() === 1000)
    assert(data.count() === 1000)

    // Get all the locations of the first partition and try to fetch the partitions
    // from those locations.
    val blockIds = data.partitions.indices.map(index => "rdd_%d_%d".format(data.id, index)).toArray
    val blockId = blockIds(0)
    val blockManager = SparkEnv.get.blockManager
    blockManager.master.getLocations(blockId).foreach(id => {
      val bytes = BlockManagerWorker.syncGetBlock(
        GetBlock(blockId), ConnectionManagerId(id.host, id.port))
      val deserialized = blockManager.dataDeserialize(blockId, bytes).asInstanceOf[Iterator[Int]].toList
      assert(deserialized === (1 to 100).toList)
    })
  }

  test("compute without caching when no partitions fit in memory") {
    System.setProperty("spark.storage.memoryFraction", "0.0001")
    sc = new SparkContext(clusterUrl, "test")
    // data will be 4 million * 4 bytes = 16 MB in size, but our memoryFraction set the cache
    // to only 50 KB (0.0001 of 512 MB), so no partitions should fit in memory
    val data = sc.parallelize(1 to 4000000, 2).persist(StorageLevel.MEMORY_ONLY_SER)
    assert(data.count() === 4000000)
    assert(data.count() === 4000000)
    assert(data.count() === 4000000)
    System.clearProperty("spark.storage.memoryFraction")
  }

  test("compute when only some partitions fit in memory") {
    System.setProperty("spark.storage.memoryFraction", "0.01")
    sc = new SparkContext(clusterUrl, "test")
    // data will be 4 million * 4 bytes = 16 MB in size, but our memoryFraction set the cache
    // to only 5 MB (0.01 of 512 MB), so not all of it will fit in memory; we use 20 partitions
    // to make sure that *some* of them do fit though
    val data = sc.parallelize(1 to 4000000, 20).persist(StorageLevel.MEMORY_ONLY_SER)
    assert(data.count() === 4000000)
    assert(data.count() === 4000000)
    assert(data.count() === 4000000)
    System.clearProperty("spark.storage.memoryFraction")
  }

  test("passing environment variables to cluster") {
    sc = new SparkContext(clusterUrl, "test", null, Nil, Map("TEST_VAR" -> "TEST_VALUE"))
    val values = sc.parallelize(1 to 2, 2).map(x => System.getenv("TEST_VAR")).collect()
    assert(values.toSeq === Seq("TEST_VALUE", "TEST_VALUE"))
  }

  test("recover from node failures") {
    import DistributedSuite.{markNodeIfIdentity, failOnMarkedIdentity}
    DistributedSuite.amMaster = true
    sc = new SparkContext(clusterUrl, "test")
    val data = sc.parallelize(Seq(true, true), 2)
    assert(data.count === 2) // force executors to start
    assert(data.map(markNodeIfIdentity).collect.size === 2)
    assert(data.map(failOnMarkedIdentity).collect.size === 2)
  }

  test("recover from repeated node failures during shuffle-map") {
    import DistributedSuite.{markNodeIfIdentity, failOnMarkedIdentity}
    DistributedSuite.amMaster = true
    sc = new SparkContext(clusterUrl, "test")
    for (i <- 1 to 3) {
      val data = sc.parallelize(Seq(true, false), 2)
      assert(data.count === 2)
      assert(data.map(markNodeIfIdentity).collect.size === 2)
      assert(data.map(failOnMarkedIdentity).map(x => x -> x).groupByKey.count === 2)
    }
  }

  test("recover from repeated node failures during shuffle-reduce") {
    import DistributedSuite.{markNodeIfIdentity, failOnMarkedIdentity}
    DistributedSuite.amMaster = true
    sc = new SparkContext(clusterUrl, "test")
    for (i <- 1 to 3) {
      val data = sc.parallelize(Seq(true, true), 2)
      assert(data.count === 2)
      assert(data.map(markNodeIfIdentity).collect.size === 2)
      // This relies on mergeCombiners being used to perform the actual reduce for this
      // test to actually be testing what it claims.
      val grouped = data.map(x => x -> x).combineByKey(
                      x => x,
                      (x: Boolean, y: Boolean) => x,
                      (x: Boolean, y: Boolean) => failOnMarkedIdentity(x)
                    )
      assert(grouped.collect.size === 1)
    }
  }

  test("recover from node failures with replication") {
    import DistributedSuite.{markNodeIfIdentity, failOnMarkedIdentity}
    DistributedSuite.amMaster = true
    // Using more than two nodes so we don't have a symmetric communication pattern and might
    // cache a partially correct list of peers.
    sc = new SparkContext("local-cluster[3,1,512]", "test")
    for (i <- 1 to 3) {
      val data = sc.parallelize(Seq(true, false, false, false), 4)
      data.persist(StorageLevel.MEMORY_ONLY_2)

      assert(data.count === 4)
      assert(data.map(markNodeIfIdentity).collect.size === 4)
      assert(data.map(failOnMarkedIdentity).collect.size === 4)

      // Create a new replicated RDD to make sure that cached peer information doesn't cause
      // problems.
      val data2 = sc.parallelize(Seq(true, true), 2).persist(StorageLevel.MEMORY_ONLY_2)
      assert(data2.count === 2)
    }
  }

  test("unpersist RDDs") {
    DistributedSuite.amMaster = true
    sc = new SparkContext("local-cluster[3,1,512]", "test")
    val data = sc.parallelize(Seq(true, false, false, false), 4)
    data.persist(StorageLevel.MEMORY_ONLY_2)
    data.count
    assert(sc.persistentRdds.isEmpty === false)
    data.unpersist()
    assert(sc.persistentRdds.isEmpty === true)

    failAfter(Span(3000, Millis)) {
      try {
        while (! sc.getRDDStorageInfo.isEmpty) {
          Thread.sleep(200)
        }
      } catch {
        case _ => { Thread.sleep(10) }
          // Do nothing. We might see exceptions because block manager
          // is racing this thread to remove entries from the driver.
      }
    }
  }

  test("job should fail if TaskResult exceeds Akka frame size") {
    // We must use local-cluster mode since results are returned differently
    // when running under LocalScheduler:
    sc = new SparkContext("local-cluster[1,1,512]", "test")
    val akkaFrameSize =
      sc.env.actorSystem.settings.config.getBytes("akka.remote.netty.message-frame-size").toInt
    val rdd = sc.parallelize(Seq(1)).map{x => new Array[Byte](akkaFrameSize)}
    val exception = intercept[SparkException] {
      rdd.reduce((x, y) => x)
    }
    exception.getMessage should endWith("result exceeded Akka frame size")
  }
}

object DistributedSuite {
  // Indicates whether this JVM is marked for failure.
  var mark = false

  // Set by test to remember if we are in the driver program so we can assert
  // that we are not.
  var amMaster = false

  // Act like an identity function, but if the argument is true, set mark to true.
  def markNodeIfIdentity(item: Boolean): Boolean = {
    if (item) {
      assert(!amMaster)
      mark = true
    }
    item
  }

  // Act like an identity function, but if mark was set to true previously, fail,
  // crashing the entire JVM.
  def failOnMarkedIdentity(item: Boolean): Boolean = {
    if (mark) {
      System.exit(42)
    }
    item
  }
}


text:
// Copyright (c) the JPEG XL Project Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

#include "lib/jxl/color_management.h"

#include <stdint.h>
#include <stdio.h>

#include <algorithm>
#include <new>
#include <string>
#include <utility>

#include "lib/jxl/base/compiler_specific.h"
#include "lib/jxl/base/data_parallel.h"
#include "lib/jxl/base/file_io.h"
#include "lib/jxl/base/thread_pool_internal.h"
#include "lib/jxl/enc_color_management.h"
#include "lib/jxl/enc_xyb.h"
#include "lib/jxl/image_test_utils.h"
#include "lib/jxl/test_utils.h"
#include "lib/jxl/testdata.h"

namespace jxl {

std::ostream& operator<<(std::ostream& os, const CIExy& xy) {
  return os << "{x=" << xy.x << ", y=" << xy.y << "}";
}

std::ostream& operator<<(std::ostream& os, const PrimariesCIExy& primaries) {
  return os << "{r=" << primaries.r << ", g=" << primaries.g
            << ", b=" << primaries.b << "}";
}

namespace {

using ::testing::ElementsAre;
using ::testing::FloatNear;

// Small enough to be fast. If changed, must update Generate*.
static constexpr size_t kWidth = 16;

struct Globals {
  // TODO(deymo): Make this a const.
  static Globals* GetInstance() {
    static Globals ret;
    return &ret;
  }

 private:
  static constexpr size_t kNumThreads = 0;  // only have a single row.

  Globals() : pool(kNumThreads) {
    in_gray = GenerateGray();
    in_color = GenerateColor();
    out_gray = ImageF(kWidth, 1);
    out_color = ImageF(kWidth * 3, 1);

    c_native = ColorEncoding::LinearSRGB(/*is_gray=*/false);
    c_gray = ColorEncoding::LinearSRGB(/*is_gray=*/true);
  }

  static ImageF GenerateGray() {
    ImageF gray(kWidth, 1);
    float* JXL_RESTRICT row = gray.Row(0);
    // Increasing left to right
    for (uint32_t x = 0; x < kWidth; ++x) {
      row[x] = x * 1.0f / (kWidth - 1);  // [0, 1]
    }
    return gray;
  }

  static ImageF GenerateColor() {
    ImageF image(kWidth * 3, 1);
    float* JXL_RESTRICT interleaved = image.Row(0);
    std::fill(interleaved, interleaved + kWidth * 3, 0.0f);

    // [0, 4): neutral
    for (int32_t x = 0; x < 4; ++x) {
      interleaved[3 * x + 0] = x * 1.0f / 3;  // [0, 1]
      interleaved[3 * x + 2] = interleaved[3 * x + 1] = interleaved[3 * x + 0];
    }

    // [4, 13): pure RGB with low/medium/high saturation
    for (int32_t c = 0; c < 3; ++c) {
      interleaved[3 * (4 + c) + c] = 0.08f + c * 0.01f;
      interleaved[3 * (7 + c) + c] = 0.75f + c * 0.01f;
      interleaved[3 * (10 + c) + c] = 1.0f;
    }

    // [13, 16): impure, not quite saturated RGB
    interleaved[3 * 13 + 0] = 0.86f;
    interleaved[3 * 13 + 2] = interleaved[3 * 13 + 1] = 0.16f;
    interleaved[3 * 14 + 1] = 0.87f;
    interleaved[3 * 14 + 2] = interleaved[3 * 14 + 0] = 0.16f;
    interleaved[3 * 15 + 2] = 0.88f;
    interleaved[3 * 15 + 1] = interleaved[3 * 15 + 0] = 0.16f;

    return image;
  }

 public:
  ThreadPoolInternal pool;

  // ImageF so we can use VerifyRelativeError; all are interleaved RGB.
  ImageF in_gray;
  ImageF in_color;
  ImageF out_gray;
  ImageF out_color;
  ColorEncoding c_native;
  ColorEncoding c_gray;
};

class ColorManagementTest
    : public ::testing::TestWithParam<test::ColorEncodingDescriptor> {
 public:
  static void VerifySameFields(const ColorEncoding& c,
                               const ColorEncoding& c2) {
    ASSERT_EQ(c.rendering_intent, c2.rendering_intent);
    ASSERT_EQ(c.GetColorSpace(), c2.GetColorSpace());
    ASSERT_EQ(c.white_point, c2.white_point);
    if (c.HasPrimaries()) {
      ASSERT_EQ(c.primaries, c2.primaries);
    }
    ASSERT_TRUE(c.tf.IsSame(c2.tf));
  }

  // "Same" pixels after converting g->c_native -> c -> g->c_native.
  static void VerifyPixelRoundTrip(const ColorEncoding& c) {
    Globals* g = Globals::GetInstance();
    const ColorEncoding& c_native = c.IsGray() ? g->c_gray : g->c_native;
    const JxlCmsInterface& cms = GetJxlCms();
    ColorSpaceTransform xform_fwd(cms);
    ColorSpaceTransform xform_rev(cms);
    const float intensity_target =
        c.tf.IsHLG() ? 1000 : kDefaultIntensityTarget;
    ASSERT_TRUE(xform_fwd.Init(c_native, c, intensity_target, kWidth,
                               g->pool.NumThreads()));
    ASSERT_TRUE(xform_rev.Init(c, c_native, intensity_target, kWidth,
                               g->pool.NumThreads()));

    const size_t thread = 0;
    const ImageF& in = c.IsGray() ? g->in_gray : g->in_color;
    ImageF* JXL_RESTRICT out = c.IsGray() ? &g->out_gray : &g->out_color;
    ASSERT_TRUE(xform_fwd.Run(thread, in.Row(0), xform_fwd.BufDst(thread)));
    ASSERT_TRUE(xform_rev.Run(thread, xform_fwd.BufDst(thread), out->Row(0)));

#if JPEGXL_ENABLE_SKCMS
    double max_l1 = 7E-4;
    double max_rel = 4E-7;
#else
    double max_l1 = 5E-5;
    // Most are lower; reached 3E-7 with D60 AP0.
    double max_rel = 4E-7;
#endif
    if (c.IsGray()) max_rel = 2E-5;
    VerifyRelativeError(in, *out, max_l1, max_rel);
  }
};
JXL_GTEST_INSTANTIATE_TEST_SUITE_P(ColorManagementTestInstantiation,
                                   ColorManagementTest,
                                   ::testing::ValuesIn(test::AllEncodings()));

// Exercises the ColorManagement interface for ALL ColorEncoding synthesizable
// via enums.
TEST_P(ColorManagementTest, VerifyAllProfiles) {
  ColorEncoding c = ColorEncodingFromDescriptor(GetParam());
  printf("%s\n", Description(c).c_str());

  // Can create profile.
  ASSERT_TRUE(c.CreateICC());

  // Can set an equivalent ColorEncoding from the generated ICC profile.
  ColorEncoding c3;
  ASSERT_TRUE(c3.SetICC(PaddedBytes(c.ICC())));
  VerifySameFields(c, c3);

  VerifyPixelRoundTrip(c);
}

testing::Matcher<CIExy> CIExyIs(const double x, const double y) {
  static constexpr double kMaxError = 1e-4;
  return testing::AllOf(
      testing::Field(&CIExy::x, testing::DoubleNear(x, kMaxError)),
      testing::Field(&CIExy::y, testing::DoubleNear(y, kMaxError)));
}

testing::Matcher<PrimariesCIExy> PrimariesAre(
    const testing::Matcher<CIExy>& r, const testing::Matcher<CIExy>& g,
    const testing::Matcher<CIExy>& b) {
  return testing::AllOf(testing::Field(&PrimariesCIExy::r, r),
                        testing::Field(&PrimariesCIExy::g, g),
                        testing::Field(&PrimariesCIExy::b, b));
}

TEST_F(ColorManagementTest, sRGBChromaticity) {
  const ColorEncoding sRGB = ColorEncoding::SRGB();
  EXPECT_THAT(sRGB.GetWhitePoint(), CIExyIs(0.3127, 0.3290));
  EXPECT_THAT(sRGB.GetPrimaries(),
              PrimariesAre(CIExyIs(0.64, 0.33), CIExyIs(0.30, 0.60),
                           CIExyIs(0.15, 0.06)));
}

TEST_F(ColorManagementTest, D2700Chromaticity) {
  PaddedBytes icc = ReadTestData("jxl/color_management/sRGB-D2700.icc");
  ColorEncoding sRGB_D2700;
  ASSERT_TRUE(sRGB_D2700.SetICC(std::move(icc)));

  EXPECT_THAT(sRGB_D2700.GetWhitePoint(), CIExyIs(0.45986, 0.41060));
  // The illuminant-relative chromaticities of this profile's primaries are the
  // same as for sRGB. It is the PCS-relative chromaticities that would be
  // different.
  EXPECT_THAT(sRGB_D2700.GetPrimaries(),
              PrimariesAre(CIExyIs(0.64, 0.33), CIExyIs(0.30, 0.60),
                           CIExyIs(0.15, 0.06)));
}

TEST_F(ColorManagementTest, D2700ToSRGB) {
  PaddedBytes icc = ReadTestData("jxl/color_management/sRGB-D2700.icc");
  ColorEncoding sRGB_D2700;
  ASSERT_TRUE(sRGB_D2700.SetICC(std::move(icc)));

  ColorSpaceTransform transform(GetJxlCms());
  ASSERT_TRUE(transform.Init(sRGB_D2700, ColorEncoding::SRGB(),
                             kDefaultIntensityTarget, 1, 1));
  const float sRGB_D2700_values[3] = {0.863, 0.737, 0.490};
  float sRGB_values[3];
  ASSERT_TRUE(transform.Run(0, sRGB_D2700_values, sRGB_values));
  EXPECT_THAT(sRGB_values,
              ElementsAre(FloatNear(0.914, 1e-3), FloatNear(0.745, 1e-3),
                          FloatNear(0.601, 1e-3)));
}

TEST_F(ColorManagementTest, P3HlgTo2020Hlg) {
  ColorEncoding p3_hlg;
  p3_hlg.SetColorSpace(ColorSpace::kRGB);
  p3_hlg.white_point = WhitePoint::kD65;
  p3_hlg.primaries = Primaries::kP3;
  p3_hlg.tf.SetTransferFunction(TransferFunction::kHLG);
  ASSERT_TRUE(p3_hlg.CreateICC());

  ColorEncoding rec2020_hlg = p3_hlg;
  rec2020_hlg.primaries = Primaries::k2100;
  ASSERT_TRUE(rec2020_hlg.CreateICC());

  ColorSpaceTransform transform(GetJxlCms());
  ASSERT_TRUE(transform.Init(p3_hlg, rec2020_hlg, 1000, 1, 1));
  const float p3_hlg_values[3] = {0., 0.75, 0.};
  float rec2020_hlg_values[3];
  ASSERT_TRUE(transform.Run(0, p3_hlg_values, rec2020_hlg_values));
  EXPECT_THAT(rec2020_hlg_values,
              ElementsAre(FloatNear(0.3973, 1e-4), FloatNear(0.7382, 1e-4),
                          FloatNear(0.1183, 1e-4)));
}

TEST_F(ColorManagementTest, HlgOotf) {
  ColorEncoding p3_hlg;
  p3_hlg.SetColorSpace(ColorSpace::kRGB);
  p3_hlg.white_point = WhitePoint::kD65;
  p3_hlg.primaries = Primaries::kP3;
  p3_hlg.tf.SetTransferFunction(TransferFunction::kHLG);
  ASSERT_TRUE(p3_hlg.CreateICC());

  ColorSpaceTransform transform_to_1000(GetJxlCms());
  ASSERT_TRUE(
      transform_to_1000.Init(p3_hlg, ColorEncoding::LinearSRGB(), 1000, 1, 1));
  // HDR reference white: https://www.itu.int/pub/R-REP-BT.2408-4-2021
  float p3_hlg_values[3] = {0.75, 0.75, 0.75};
  float linear_srgb_values[3];
  ASSERT_TRUE(transform_to_1000.Run(0, p3_hlg_values, linear_srgb_values));
  // On a 1000-nit display, HDR reference white should be 203 cd/m² which is
  // 0.203 times the maximum.
  EXPECT_THAT(linear_srgb_values,
              ElementsAre(FloatNear(0.203, 1e-3), FloatNear(0.203, 1e-3),
                          FloatNear(0.203, 1e-3)));

  ColorSpaceTransform transform_to_400(GetJxlCms());
  ASSERT_TRUE(
      transform_to_400.Init(p3_hlg, ColorEncoding::LinearSRGB(), 400, 1, 1));
  ASSERT_TRUE(transform_to_400.Run(0, p3_hlg_values, linear_srgb_values));
  // On a 400-nit display, it should be 100 cd/m².
  EXPECT_THAT(linear_srgb_values,
              ElementsAre(FloatNear(0.250, 1e-3), FloatNear(0.250, 1e-3),
                          FloatNear(0.250, 1e-3)));

  p3_hlg_values[2] = 0.50;
  ASSERT_TRUE(transform_to_1000.Run(0, p3_hlg_values, linear_srgb_values));
  EXPECT_THAT(linear_srgb_values,
              ElementsAre(FloatNear(0.201, 1e-3), FloatNear(0.201, 1e-3),
                          FloatNear(0.050, 1e-3)));

  ColorSpaceTransform transform_from_400(GetJxlCms());
  ASSERT_TRUE(
      transform_from_400.Init(ColorEncoding::LinearSRGB(), p3_hlg, 400, 1, 1));
  linear_srgb_values[0] = linear_srgb_values[1] = linear_srgb_values[2] = 0.250;
  ASSERT_TRUE(transform_from_400.Run(0, linear_srgb_values, p3_hlg_values));
  EXPECT_THAT(p3_hlg_values,
              ElementsAre(FloatNear(0.75, 1e-3), FloatNear(0.75, 1e-3),
                          FloatNear(0.75, 1e-3)));

  ColorEncoding grayscale_hlg;
  grayscale_hlg.SetColorSpace(ColorSpace::kGray);
  grayscale_hlg.white_point = WhitePoint::kD65;
  grayscale_hlg.tf.SetTransferFunction(TransferFunction::kHLG);
  ASSERT_TRUE(grayscale_hlg.CreateICC());

  ColorSpaceTransform grayscale_transform(GetJxlCms());
  ASSERT_TRUE(grayscale_transform.Init(
      grayscale_hlg, ColorEncoding::LinearSRGB(/*is_gray=*/true), 1000, 1, 1));
  const float grayscale_hlg_value = 0.75;
  float linear_grayscale_value;
  ASSERT_TRUE(grayscale_transform.Run(0, &grayscale_hlg_value,
                                      &linear_grayscale_value));
  EXPECT_THAT(linear_grayscale_value, FloatNear(0.203, 1e-3));
}

TEST_F(ColorManagementTest, XYBProfile) {
  ColorEncoding c_xyb;
  c_xyb.SetColorSpace(ColorSpace::kXYB);
  c_xyb.rendering_intent = RenderingIntent::kPerceptual;
  ASSERT_TRUE(c_xyb.CreateICC());
  ColorEncoding c_native = ColorEncoding::LinearSRGB(false);

  static const size_t kGridDim = 17;
  static const size_t kNumColors = kGridDim * kGridDim * kGridDim;
  const JxlCmsInterface& cms = GetJxlCms();
  ColorSpaceTransform xform(cms);
  ASSERT_TRUE(
      xform.Init(c_xyb, c_native, kDefaultIntensityTarget, kNumColors, 1));

  ImageMetadata metadata;
  metadata.color_encoding = c_native;
  ImageBundle ib(&metadata);
  Image3F native(kNumColors, 1);
  float mul = 1.0f / (kGridDim - 1);
  for (size_t ir = 0, x = 0; ir < kGridDim; ++ir) {
    for (size_t ig = 0; ig < kGridDim; ++ig) {
      for (size_t ib = 0; ib < kGridDim; ++ib, ++x) {
        native.PlaneRow(0, 0)[x] = ir * mul;
        native.PlaneRow(1, 0)[x] = ig * mul;
        native.PlaneRow(2, 0)[x] = ib * mul;
      }
    }
  }
  ib.SetFromImage(std::move(native), c_native);
  const Image3F& in = *ib.color();
  Image3F opsin(kNumColors, 1);
  ToXYB(ib, nullptr, &opsin, cms, nullptr);

  Image3F opsin2 = CopyImage(opsin);
  ScaleXYB(&opsin2);

  float* src = xform.BufSrc(0);
  for (size_t i = 0; i < kNumColors; ++i) {
    for (size_t c = 0; c < 3; ++c) {
      src[3 * i + c] = opsin2.PlaneRow(c, 0)[i];
    }
  }

  float* dst = xform.BufDst(0);
  ASSERT_TRUE(xform.Run(0, src, dst));

  Image3F out(kNumColors, 1);
  for (size_t i = 0; i < kNumColors; ++i) {
    for (size_t c = 0; c < 3; ++c) {
      out.PlaneRow(c, 0)[i] = dst[3 * i + c];
    }
  }

  auto debug_print_color = [&](size_t i) {
    printf(
        "(%f, %f, %f) -> (%9.6f, %f, %f) -> (%f, %f, %f) -> "
        "(%9.6f, %9.6f, %9.6f)",
        in.PlaneRow(0, 0)[i], in.PlaneRow(1, 0)[i], in.PlaneRow(2, 0)[i],
        opsin.PlaneRow(0, 0)[i], opsin.PlaneRow(1, 0)[i],
        opsin.PlaneRow(2, 0)[i], opsin2.PlaneRow(0, 0)[i],
        opsin2.PlaneRow(1, 0)[i], opsin2.PlaneRow(2, 0)[i],
        out.PlaneRow(0, 0)[i], out.PlaneRow(1, 0)[i], out.PlaneRow(2, 0)[i]);
  };

  float max_err[3] = {};
  size_t max_err_i[3] = {};
  for (size_t i = 0; i < kNumColors; ++i) {
    for (size_t c = 0; c < 3; ++c) {
      // debug_print_color(i); printf("\n");
      float err = std::abs(in.PlaneRow(c, 0)[i] - out.PlaneRow(c, 0)[i]);
      if (err > max_err[c]) {
        max_err[c] = err;
        max_err_i[c] = i;
      }
    }
  }
  static float kMaxError[3] = {9e-4, 4e-4, 5e-4};
  printf("Maximum errors:\n");
  for (size_t c = 0; c < 3; ++c) {
    debug_print_color(max_err_i[c]);
    printf("    %f\n", max_err[c]);
    EXPECT_LT(max_err[c], kMaxError[c]);
  }
}

}  // namespace
}  // namespace jxl


text:
/* ==================================================================== */

/*** Includes. ***/

#include <apr_pools.h>
#include "svn_hash.h"
#include "svn_auth.h"
#include "svn_error.h"
#include "svn_utf.h"
#include "svn_config.h"
#include "svn_user.h"

/*-----------------------------------------------------------------------*/
/* File provider                                                         */
/*-----------------------------------------------------------------------*/

/* The key that will be stored on disk.  Serves the same role as similar
   constants in other providers. */
#define AUTHN_USERNAME_KEY "username"

/*** Username-only Provider ***/
static svn_error_t *
username_first_creds(void **credentials,
                     void **iter_baton,
                     void *provider_baton,
                     apr_hash_t *parameters,
                     const char *realmstring,
                     apr_pool_t *pool)
{
  const char *config_dir = svn_hash_gets(parameters,
                                         SVN_AUTH_PARAM_CONFIG_DIR);
  const char *username = svn_hash_gets(parameters,
                                       SVN_AUTH_PARAM_DEFAULT_USERNAME);
  svn_boolean_t may_save = !! username;
  svn_error_t *err;

  /* If we don't have a usename yet, try the auth cache */
  if (! username)
    {
      apr_hash_t *creds_hash = NULL;

      /* Try to load credentials from a file on disk, based on the
         realmstring.  Don't throw an error, though: if something went
         wrong reading the file, no big deal.  What really matters is that
         we failed to get the creds, so allow the auth system to try the
         next provider. */
      err = svn_config_read_auth_data(&creds_hash, SVN_AUTH_CRED_USERNAME,
                                      realmstring, config_dir, pool);
      svn_error_clear(err);
      if (! err && creds_hash)
        {
          svn_string_t *str = svn_hash_gets(creds_hash, AUTHN_USERNAME_KEY);
          if (str && str->data)
            username = str->data;
        }
    }

  /* If that failed, ask the OS for the username */
  if (! username)
    username = svn_user_get_name(pool);

  if (username)
    {
      svn_auth_cred_simple_t *creds = apr_pcalloc(pool, sizeof(*creds));
      creds->username = username;
      creds->may_save = may_save;
      *credentials = creds;
    }
  else
    *credentials = NULL;

  *iter_baton = NULL;

  return SVN_NO_ERROR;
}

static svn_error_t *
username_save_creds(svn_boolean_t *saved,
                    void *credentials,
                    void *provider_baton,
                    apr_hash_t *parameters,
                    const char *realmstring,
                    apr_pool_t *pool)
{
  svn_auth_cred_simple_t *creds = credentials;
  apr_hash_t *creds_hash = NULL;
  const char *config_dir;
  svn_error_t *err;

  *saved = FALSE;

  if (! creds->may_save)
    return SVN_NO_ERROR;

  config_dir = svn_hash_gets(parameters, SVN_AUTH_PARAM_CONFIG_DIR);

  /* Put the credentials in a hash and save it to disk */
  creds_hash = apr_hash_make(pool);
  svn_hash_sets(creds_hash, AUTHN_USERNAME_KEY,
                svn_string_create(creds->username, pool));
  err = svn_config_write_auth_data(creds_hash, SVN_AUTH_CRED_USERNAME,
                                   realmstring, config_dir, pool);
  svn_error_clear(err);
  *saved = ! err;

  return SVN_NO_ERROR;
}

static const svn_auth_provider_t username_provider = {
  SVN_AUTH_CRED_USERNAME,
  username_first_creds,
  NULL,
  username_save_creds
};

/* Public API */
void
svn_auth_get_username_provider(svn_auth_provider_object_t **provider,
                               apr_pool_t *pool)
{
  svn_auth_provider_object_t *po = apr_pcalloc(pool, sizeof(*po));

  po->vtable = &username_provider;
  *provider = po;
}

/*-----------------------------------------------------------------------*/
/* Prompt provider                                                       */
/*-----------------------------------------------------------------------*/

/* Baton type for username-only prompting. */
typedef struct username_prompt_provider_baton_t
{
  svn_auth_username_prompt_func_t prompt_func;
  void *prompt_baton;

  /* how many times to re-prompt after the first one fails */
  int retry_limit;
} username_prompt_provider_baton_t;

/* Iteration baton type for username-only prompting. */
typedef struct username_prompt_iter_baton_t
{
  /* how many times we've reprompted */
  int retries;

} username_prompt_iter_baton_t;

/*** Helper Functions ***/
static svn_error_t *
prompt_for_username_creds(svn_auth_cred_username_t **cred_p,
                          username_prompt_provider_baton_t *pb,
                          apr_hash_t *parameters,
                          const char *realmstring,
                          svn_boolean_t first_time,
                          svn_boolean_t may_save,
                          apr_pool_t *pool)
{
  const char *def_username = NULL;

  *cred_p = NULL;

  /* If we're allowed to check for default usernames, do so. */
  if (first_time)
    def_username = svn_hash_gets(parameters, SVN_AUTH_PARAM_DEFAULT_USERNAME);

  /* If we have defaults, just build the cred here and return it.
   *
   * ### I do wonder why this is here instead of in a separate
   * ### 'defaults' provider that would run before the prompt
   * ### provider... Hmmm.
   */
  if (def_username)
    {
      *cred_p = apr_palloc(pool, sizeof(**cred_p));
      (*cred_p)->username = apr_pstrdup(pool, def_username);
      (*cred_p)->may_save = TRUE;
    }
  else
    {
      SVN_ERR(pb->prompt_func(cred_p, pb->prompt_baton, realmstring,
                              may_save, pool));
    }

  return SVN_NO_ERROR;
}

/* Our first attempt will use any default username passed
   in, and prompt for the remaining stuff. */
static svn_error_t *
username_prompt_first_creds(void **credentials_p,
                            void **iter_baton,
                            void *provider_baton,
                            apr_hash_t *parameters,
                            const char *realmstring,
                            apr_pool_t *pool)
{
  username_prompt_provider_baton_t *pb = provider_baton;
  username_prompt_iter_baton_t *ibaton = apr_pcalloc(pool, sizeof(*ibaton));
  const char *no_auth_cache = svn_hash_gets(parameters,
                                            SVN_AUTH_PARAM_NO_AUTH_CACHE);

  SVN_ERR(prompt_for_username_creds
          ((svn_auth_cred_username_t **) credentials_p, pb,
           parameters, realmstring, TRUE, ! no_auth_cache, pool));

  ibaton->retries = 0;
  *iter_baton = ibaton;

  return SVN_NO_ERROR;
}

/* Subsequent attempts to fetch will ignore the default username
   value, and simply re-prompt for the username, up to a maximum of
   ib->pb->retry_limit. */
static svn_error_t *
username_prompt_next_creds(void **credentials_p,
                           void *iter_baton,
                           void *provider_baton,
                           apr_hash_t *parameters,
                           const char *realmstring,
                           apr_pool_t *pool)
{
  username_prompt_iter_baton_t *ib = iter_baton;
  username_prompt_provider_baton_t *pb = provider_baton;
  const char *no_auth_cache = svn_hash_gets(parameters,
                                            SVN_AUTH_PARAM_NO_AUTH_CACHE);

  if ((pb->retry_limit >= 0) && (ib->retries >= pb->retry_limit))
    {
      /* give up, go on to next provider. */
      *credentials_p = NULL;
      return SVN_NO_ERROR;
    }
  ib->retries++;

  return prompt_for_username_creds
         ((svn_auth_cred_username_t **) credentials_p, pb,
          parameters, realmstring, FALSE, ! no_auth_cache, pool);
}

static const svn_auth_provider_t username_prompt_provider = {
  SVN_AUTH_CRED_USERNAME,
  username_prompt_first_creds,
  username_prompt_next_creds,
  NULL,
};

/* Public API */
void
svn_auth_get_username_prompt_provider
  (svn_auth_provider_object_t **provider,
   svn_auth_username_prompt_func_t prompt_func,
   void *prompt_baton,
   int retry_limit,
   apr_pool_t *pool)
{
  svn_auth_provider_object_t *po = apr_pcalloc(pool, sizeof(*po));
  username_prompt_provider_baton_t *pb = apr_pcalloc(pool, sizeof(*pb));

  pb->prompt_func = prompt_func;
  pb->prompt_baton = prompt_baton;
  pb->retry_limit = retry_limit;

  po->vtable = &username_prompt_provider;
  po->provider_baton = pb;
  *provider = po;
}


text:
package org.jetbrains.plugins.groovy.codeInspection.threading;

import com.intellij.psi.*;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.groovy.codeInspection.BaseInspection;
import org.jetbrains.plugins.groovy.codeInspection.BaseInspectionVisitor;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrSynchronizedStatement;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral;

public class GroovySynchronizationOnVariableInitializedWithLiteralInspection extends BaseInspection {

  @Nls
  @NotNull
  public String getGroupDisplayName() {
    return THREADING_ISSUES;
  }

  @Nls
  @NotNull
  public String getDisplayName() {
    return "Synchronization on variable initialized with literal";
  }

  @Nullable
  protected String buildErrorString(Object... args) {
    return "Synchronization on variable '#ref', which was initialized with a literal #loc";

  }

  public BaseInspectionVisitor buildVisitor() {
    return new Visitor();
  }

  private static class Visitor extends BaseInspectionVisitor {
    public void visitSynchronizedStatement(GrSynchronizedStatement synchronizedStatement) {
      super.visitSynchronizedStatement(synchronizedStatement);
      final GrExpression lock = synchronizedStatement.getMonitor();
      if (lock == null || !(lock instanceof GrReferenceExpression)) {
        return;
      }
      final PsiElement referent = ((PsiReference) lock).resolve();
      if (referent instanceof GrVariable) {
        final GrVariable variable = (GrVariable) referent;
        final GrExpression initializer = variable.getInitializerGroovy();
        if (initializer == null) {
          return;
        }
        if (!(initializer instanceof GrLiteral)) {
          return;
        }
        registerError(lock);
      } else if (referent instanceof PsiVariable) {
        final PsiVariable variable = (PsiVariable) referent;
        final PsiExpression initializer = variable.getInitializer();
        if (initializer == null) {
          return;
        }
        if (!(initializer instanceof PsiLiteralExpression)) {
          return;
        }
        registerError(lock);
      }
    }

  }

}


text:
package com.intellij.execution.filters;

import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.OpenFileDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;

public final class OpenFileHyperlinkInfo implements FileHyperlinkInfo {

  private static final int UNDEFINED_OFFSET = -1;

  private final Project myProject;
  private final VirtualFile myFile;
  private final boolean myIncludeInOccurenceNavigation;
  private final int myDocumentLine;
  private final int myDocumentColumn;

  public OpenFileHyperlinkInfo(@NotNull OpenFileDescriptor descriptor) {
    this(descriptor.getProject(), descriptor.getFile(), descriptor.getLine(), descriptor.getColumn());
  }

  public OpenFileHyperlinkInfo(@NotNull Project project, @NotNull VirtualFile file, boolean includeInOccurenceNavigation,
                               int documentLine, int documentColumn) {
    myProject = project;
    myFile = file;
    myIncludeInOccurenceNavigation = includeInOccurenceNavigation;
    myDocumentLine = documentLine;
    myDocumentColumn = documentColumn;
  }

  public OpenFileHyperlinkInfo(@NotNull Project project, @NotNull final VirtualFile file, final int line) {
    this(project, file, line, 0);
  }

  public OpenFileHyperlinkInfo(@NotNull Project project, @NotNull VirtualFile file, int line, int column) {
    this(project, file, true, line, column);
  }

  @Override
  public OpenFileDescriptor getDescriptor() {
    if (!myFile.isValid()) {
      return null;
    }

    int line = myDocumentLine;
    FileDocumentManager.getInstance().getDocument(myFile); // need to load decompiler text
    LineNumbersMapping mapping = myFile.getUserData(LineNumbersMapping.LINE_NUMBERS_MAPPING_KEY);
    if (mapping != null) {
      line = mapping.bytecodeToSource(myDocumentLine + 1) - 1;
      if (line < 0) {
        line = myDocumentLine;
      }
    }

    int offset = calculateOffset(myFile, line, myDocumentColumn);
    if (offset != UNDEFINED_OFFSET) {
      return new OpenFileDescriptor(myProject, myFile, offset);
    }
    // although document position != logical position, it seems better than returning 'null'
    return new OpenFileDescriptor(myProject, myFile, line, myDocumentColumn);
  }

  @Override
  public void navigate(final Project project) {
    ApplicationManager.getApplication().runReadAction(() -> {
      OpenFileDescriptor descriptor = getDescriptor();
      if (descriptor != null) {
        FileEditorManager.getInstance(project).openTextEditor(descriptor, true);
      }
    });
  }

  @Override
  public boolean includeInOccurenceNavigation() {
    return myIncludeInOccurenceNavigation;
  }

  /**
   * Calculates an offset, that matches given line and column of the document.
   *
   * @param file           VirtualFile instance
   * @param documentLine   zero-based line of the document
   * @param documentColumn zero-based column of the document
   * @return calculated offset or UNDEFINED_OFFSET if it's impossible to calculate
   */
  private static int calculateOffset(@NotNull final VirtualFile file,
                                     final int documentLine, final int documentColumn) {
    return ApplicationManager.getApplication().runReadAction(new Computable<Integer>() {

      @Override
      public Integer compute() {
        Document document = FileDocumentManager.getInstance().getDocument(file);
        if (document != null) {
          int lineCount = document.getLineCount();
          if (0 <= documentLine && documentLine < lineCount) {
            int lineStartOffset = document.getLineStartOffset(documentLine);
            int lineEndOffset = document.getLineEndOffset(documentLine);
            int fixedColumn = Math.min(Math.max(documentColumn, 0), lineEndOffset - lineStartOffset);
            return lineStartOffset + fixedColumn;
          }
        }
        return UNDEFINED_OFFSET;
      }
    });
  }
}