text:
bool GLGlobalState::_initializationAvailable = false;

void GLGlobalState::applyChanges(GL* gl, GLGlobalState& currentState) const {

  INativeGL* nativeGL = gl->getNative();

  // Depth Test
  if (_depthTest != currentState._depthTest) {
    if (_depthTest) {
      nativeGL->enable(GLStage::depthTest());
    }
    else {
      nativeGL->disable(GLStage::depthTest());
    }
    currentState._depthTest = _depthTest;
  }

  // Blending
  if (_blend != currentState._blend) {
    if (_blend) {
      nativeGL->enable(GLStage::blend());
    }
    else {
      nativeGL->disable(GLStage::blend());
    }
    currentState._blend = _blend;
  }

  // Cull Face
  if (_cullFace != currentState._cullFace) {
    currentState._cullFace = _cullFace;
    if (_cullFace) {
      nativeGL->enable(GLStage::cullFace());
      if (_culledFace != currentState._culledFace) {
        nativeGL->cullFace(_culledFace);
        currentState._culledFace = _culledFace;
      }
    }
    else {
      nativeGL->disable(GLStage::cullFace());
    }
  }

  if (_lineWidth != currentState._lineWidth) {
    nativeGL->lineWidth(_lineWidth);
    currentState._lineWidth = _lineWidth;
  }

  //Polygon Offset
  if (_polygonOffsetFill != currentState._polygonOffsetFill) {
    currentState._polygonOffsetFill = _polygonOffsetFill;
    if (_polygonOffsetFill) {
      nativeGL->enable(GLStage::polygonOffsetFill());

      if (_polygonOffsetFactor != currentState._polygonOffsetFactor ||
          _polygonOffsetUnits != currentState._polygonOffsetUnits) {
        nativeGL->polygonOffset(_polygonOffsetFactor, _polygonOffsetUnits);

        currentState._polygonOffsetUnits = _polygonOffsetUnits;
        currentState._polygonOffsetFactor = _polygonOffsetFactor;
      }
    }
    else {
      nativeGL->disable(GLStage::polygonOffsetFill());
    }
  }

  //Blending Factors
  if (_blendDFactor != currentState._blendDFactor || _blendSFactor != currentState._blendSFactor) {
    nativeGL->blendFunc(_blendSFactor, _blendDFactor);
    currentState._blendDFactor = _blendDFactor;
    currentState._blendSFactor = _blendSFactor;
  }

  //Texture (After blending factors)

  for (int i = 0; i < MAX_N_TEXTURES; i++) {

    if (_boundTextureId[i] != NULL) {
      if (currentState._boundTextureId[i] == NULL ||
          !_boundTextureId[i]->isEquals(currentState._boundTextureId[i])) {
        nativeGL->setActiveTexture(i);
        nativeGL->bindTexture(GLTextureType::texture2D(), _boundTextureId[i]);

        currentState._boundTextureId[i] = _boundTextureId[i];
      }
      //else {
      //  ILogger::instance()->logInfo("Texture already bound.\n");
      //}
    }
  }

  if (_pixelStoreIAlignmentUnpack != -1 && _pixelStoreIAlignmentUnpack != currentState._pixelStoreIAlignmentUnpack) {
    nativeGL->pixelStorei(GLAlignment::unpack(), _pixelStoreIAlignmentUnpack);
    currentState._pixelStoreIAlignmentUnpack = _pixelStoreIAlignmentUnpack;
  }

  if (_pixelStoreIAlignmentUnpack != -1 && _pixelStoreIAlignmentUnpack != currentState._pixelStoreIAlignmentUnpack) {
    nativeGL->pixelStorei(GLAlignment::unpack(), _pixelStoreIAlignmentUnpack);
    currentState._pixelStoreIAlignmentUnpack = _pixelStoreIAlignmentUnpack;
  }

  if (_clearColorR != currentState._clearColorR ||
      _clearColorG != currentState._clearColorG ||
      _clearColorB != currentState._clearColorB ||
      _clearColorA != currentState._clearColorA) {
    nativeGL->clearColor(_clearColorR, _clearColorG, _clearColorB, _clearColorA);
    currentState._clearColorR = _clearColorR;
    currentState._clearColorG = _clearColorG;
    currentState._clearColorB = _clearColorB;
    currentState._clearColorA = _clearColorA;
  }

}

redpajama_set_name: RedPajamaGithub


text:
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.groovy.lang.psi.dataFlow.types;

import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiType;
import com.intellij.psi.util.CachedValueProvider.Result;
import com.intellij.psi.util.CachedValuesManager;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.groovy.codeInspection.utils.ControlFlowUtils;
import org.jetbrains.plugins.groovy.lang.lexer.TokenSets;
import org.jetbrains.plugins.groovy.lang.psi.GrControlFlowOwner;
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyReference;
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.GrListOrMap;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.*;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrIndexProperty;
import org.jetbrains.plugins.groovy.lang.psi.controlFlow.Instruction;
import org.jetbrains.plugins.groovy.lang.psi.controlFlow.ReadWriteVariableInstruction;
import org.jetbrains.plugins.groovy.lang.psi.controlFlow.VariableDescriptor;
import org.jetbrains.plugins.groovy.lang.psi.controlFlow.impl.ControlFlowBuilder;
import org.jetbrains.plugins.groovy.lang.psi.controlFlow.impl.GroovyControlFlow;
import org.jetbrains.plugins.groovy.lang.psi.dataFlow.DFAEngine;
import org.jetbrains.plugins.groovy.lang.psi.dataFlow.DFAType;
import org.jetbrains.plugins.groovy.lang.psi.dataFlow.reachingDefs.DefinitionMap;
import org.jetbrains.plugins.groovy.lang.psi.dataFlow.reachingDefs.ReachingDefinitionsDfaInstance;
import org.jetbrains.plugins.groovy.lang.psi.dataFlow.reachingDefs.ReachingDefinitionsSemilattice;
import org.jetbrains.plugins.groovy.lang.psi.impl.InferenceContext;
import org.jetbrains.plugins.groovy.lang.psi.impl.PartialContext;

import java.util.List;
import java.util.Map;
import java.util.function.Supplier;

import static com.intellij.psi.util.PsiModificationTracker.MODIFICATION_COUNT;
import static org.jetbrains.plugins.groovy.lang.psi.controlFlow.impl.FunctionalExpressionFlowUtil.isFlatDFAAllowed;
import static org.jetbrains.plugins.groovy.lang.psi.controlFlow.impl.VariableDescriptorFactory.createDescriptor;
import static org.jetbrains.plugins.groovy.lang.psi.dataFlow.types.NestedContextKt.checkNestedContext;
import static org.jetbrains.plugins.groovy.lang.psi.util.CompileStaticUtil.isCompileStatic;
import static org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil.skipParentheses;
import static org.jetbrains.plugins.groovy.lang.typing.TuplesKt.getMultiAssignmentType;

/**
 * @author ven
 */
@SuppressWarnings("UtilityClassWithoutPrivateConstructor")
public final class TypeInferenceHelper {
  private static final Logger LOG = Logger.getInstance(TypeInferenceHelper.class);

  private static final ThreadLocal<InferenceContext> ourInferenceContext = new ThreadLocal<>();

  static <T> T doInference(@NotNull Map<VariableDescriptor, DFAType> bindings, @NotNull Supplier<? extends T> computation) {
    if (ApplicationManager.getApplication().isUnitTestMode()) {
      checkNestedContext();
    }
    return withContext(new PartialContext(bindings), computation);
  }

  private static <T> T withContext(@NotNull InferenceContext context, @NotNull Supplier<? extends T> computation) {
    InferenceContext previous = ourInferenceContext.get();
    ourInferenceContext.set(context);
    try {
      return computation.get();
    }
    finally {
      ourInferenceContext.set(previous);
    }
  }

  @NotNull
  @Contract(pure = true)
  public static InferenceContext getCurrentContext() {
    InferenceContext context = ourInferenceContext.get();
    return context != null ? context : getTopContext();
  }

  public static <T> T inTopContext(@NotNull Supplier<? extends T> computation) {
    return withContext(getTopContext(), computation);
  }

  @NotNull
  @Contract(pure = true)
  public static InferenceContext getTopContext() {
    return InferenceContext.TOP_CONTEXT;
  }

  @Nullable
  public static PsiType getInferredType(@NotNull final GrReferenceExpression refExpr) {
    final GrControlFlowOwner scope = isFlatDFAAllowed() ? ControlFlowUtils.getTopmostOwner(refExpr) : ControlFlowUtils.findControlFlowOwner(refExpr);
    if (scope == null) return null;

    final GroovyReference rValueReference = refExpr.getRValueReference();
    PsiElement resolve = rValueReference == null ? null : rValueReference.resolve();
    boolean mixinOnly = resolve instanceof GrField && isCompileStatic(refExpr);

    final VariableDescriptor descriptor = createDescriptor(refExpr);
    if (descriptor == null) return null;

    final ReadWriteVariableInstruction rwInstruction = ControlFlowUtils.findRWInstruction(refExpr, getFlatControlFlow(scope).getFlow());
    if (rwInstruction == null) return null;

    final InferenceCache cache = getInferenceCache(scope);

    int descriptorIndex = cache.getGroovyFlow().getIndex(descriptor);
    if (descriptorIndex == 0) return null;

    return cache.getInferredType(descriptorIndex, rwInstruction, mixinOnly);
  }

  @Nullable
  public static PsiType getInferredType(int descriptor, Instruction instruction, GrControlFlowOwner scope) {
    InferenceCache cache = getInferenceCache(scope);
    return cache.getInferredType(descriptor, instruction, false);
  }

  @Nullable
  public static PsiType getVariableTypeInContext(@Nullable PsiElement context, @NotNull GrVariable variable) {
    if (context == null) return variable.getType();
    final GrControlFlowOwner scope = isFlatDFAAllowed() ? ControlFlowUtils.getTopmostOwner(ControlFlowUtils.findControlFlowOwner(context))
                                                        : ControlFlowUtils.findControlFlowOwner(context);
    if (scope == null) return null;

    final Instruction nearest = ControlFlowUtils.findNearestInstruction(context, scope.getControlFlow());
    if (nearest == null) return null;
    boolean mixinOnly = variable instanceof GrField && isCompileStatic(scope);

    final InferenceCache cache = getInferenceCache(scope);
    final VariableDescriptor descriptor = createDescriptor(variable);
    int descriptorIndex = cache.getGroovyFlow().getIndex(descriptor);
    if (descriptorIndex == 0) {
      if (variable instanceof GrField) {
        // variable is not used anywhere in the scope, therefore it is enough to return its declared type
        return variable.getDeclaredType();
      } else {
        return null;
      }
    }

    final PsiType inferredType = cache.getInferredType(descriptorIndex, nearest, mixinOnly);
    return inferredType != null ? inferredType : variable.getType();
  }

  public static boolean isTooComplexTooAnalyze(@NotNull GrControlFlowOwner scope) {
    return getInferenceCache(scope).isTooComplexToAnalyze();
  }

  @NotNull
  static InferenceCache getInferenceCache(@NotNull final GrControlFlowOwner scope) {
    if (isFlatDFAAllowed() && ControlFlowUtils.getTopmostOwner(scope) != scope) {
      LOG.error("Flat DFA inconsistency: scope is " + scope + ", but topmost owner is " + ControlFlowUtils.getTopmostOwner(scope));
    }
    return CachedValuesManager.getCachedValue(scope, () -> Result.create(new InferenceCache(scope), MODIFICATION_COUNT));
  }

  public static GroovyControlFlow getFlatControlFlow(@NotNull final GrControlFlowOwner scope) {
    if (isFlatDFAAllowed()) {
      return CachedValuesManager.getCachedValue(scope, () -> Result.create(ControlFlowBuilder.buildFlatControlFlow(scope), MODIFICATION_COUNT));
    } else {
      return ControlFlowUtils.getGroovyControlFlow(scope);
    }
  }

  @Nullable
  static List<DefinitionMap> getDefUseMaps(@NotNull GroovyControlFlow flow) {
    final ReachingDefinitionsDfaInstance dfaInstance = new TypesReachingDefinitionsInstance();
    final ReachingDefinitionsSemilattice lattice = new ReachingDefinitionsSemilattice();
    final DFAEngine<DefinitionMap> engine = new DFAEngine<>(flow.getFlow(), dfaInstance, lattice);
    List<@Nullable DefinitionMap> maps = engine.performDFAWithTimeout();
    if (maps == null) {
      return null;
    }
    return ContainerUtil.map(maps, it -> it == null ? DefinitionMap.NEUTRAL : it);
  }

  @Nullable
  public static PsiType getInitializerType(final PsiElement element) {
    if (element instanceof GrReferenceExpression && ((GrReferenceExpression)element).getQualifierExpression() == null) {
      return getInitializerTypeFor(element);
    }

    if (element instanceof GrVariable) {
      return ((GrVariable)element).getTypeGroovy();
    }

    return null;
  }

  @Nullable
  public static PsiType getInitializerTypeFor(PsiElement element) {
    final PsiElement parent = skipParentheses(element.getParent(), true);
    if (parent instanceof GrAssignmentExpression) {
      if (element instanceof GrIndexProperty) {
        final GrExpression rvalue = ((GrAssignmentExpression)parent).getRValue();
        return rvalue != null
               ? rvalue.getType()
               : null; //don't try to infer assignment type in case of index property because of infinite recursion (example: a[2]+=4)
      }
      return ((GrAssignmentExpression)parent).getType();
    }

    if (parent instanceof GrTuple) {
      GrTuple list = (GrTuple)parent;
      GrTupleAssignmentExpression assignment = list.getParent();
      if (assignment != null) {
        final GrExpression rValue = assignment.getRValue();
        if (rValue != null) {
          int idx = list.indexOf(element);
          if (idx >= 0) {
            return getMultiAssignmentType(rValue, idx);
          }
        }
      }
    }
    if (parent instanceof GrUnaryExpression) {
      GrUnaryExpression unary = (GrUnaryExpression)parent;
      if (TokenSets.POSTFIX_UNARY_OP_SET.contains(unary.getOperationTokenType())) {
        return unary.getOperationType();
      }
    }

    return null;
  }

  @Nullable
  public static GrExpression getInitializerFor(GrExpression lValue) {
    final PsiElement parent = lValue.getParent();
    if (parent instanceof GrAssignmentExpression) return ((GrAssignmentExpression)parent).getRValue();
    if (parent instanceof GrTuple) {
      final int i = ((GrTuple)parent).indexOf(lValue);
      final GrTupleAssignmentExpression grandParent = ((GrTuple)parent).getParent();
      LOG.assertTrue(grandParent != null);

      final GrExpression rValue = grandParent.getRValue();
      if (rValue instanceof GrListOrMap && !((GrListOrMap)rValue).isMap()) {
        final GrExpression[] initializers = ((GrListOrMap)rValue).getInitializers();
        if (i < initializers.length) return initializers[i];
      }
    }

    return null;
  }

  public static boolean isSimpleEnoughForAugmenting(Instruction @NotNull [] flow) {
    // in large flows there are a lot of variables, so minor inability to infer type for a parameter should not be noticeable.
    // on the other side, people may omit types of parameters in short methods, so augmenting may be useful there
    return flow.length < 20;
  }
}


text:
require 'spec_helper'

hiera_config = 'spec/fixtures/hiera/hiera.yaml'

describe 'one::oned::config' do
  OS_FACTS.each do |f|
    context "On #{f[:operatingsystem]} #{f[:operatingsystemmajrelease]}" do
      let(:facts) { f }
      let(:hiera_config) { hiera_config }
      let(:pre_condition) { 'include one' }

      context 'general' do
        it { should contain_class('one::oned::config') }
        it { should contain_file('/etc/one/oned.conf') \
                    .with_ensure('file')\
                    .with_owner('root') \
                    .with_mode('0640')
        }
        it { should contain_file('/etc/one/sched.conf') \
                    .with_ensure('file')\
                    .with_owner('root') \
                    .with_mode('0640')
        }
        it { should contain_file('/usr/share/one/hooks') \
                    .with_ensure('directory') \
                    .with_mode('0750')
        }
        it { should contain_file('/usr/share/one').with_ensure('directory') }
      end

      context 'with mysql backend and create_backup_dir default' do
        let(:params) { {
            :backend => 'mysql',
            :backup_script_path => '/var/lib/one/bin/one_db_backup.sh',
            :backup_dir => '/srv/backup'
        } }
        it { should contain_file('/srv/backup') }
        it { should contain_file('/var/lib/one/bin/one_db_backup.sh') }
        it { should contain_cron('one_db_backup') }
      end

      context 'with mysql backend and create_backup_dir eq NO' do
        let(:params) { {
            :backend => 'mysql',
            :backup_script_path => '/var/lib/one/bin/one_db_backup.sh',
            :backup_dir => '/srv/backup',
            :create_backup_dir => 'NO'
        } }
        it { should_not contain_file('/srv/backup') }
        it { should contain_file('/var/lib/one/bin/one_db_backup.sh') }
        it { should contain_cron('one_db_backup') }
      end

      context 'without kvm driver emulator settings' do
        it { should_not contain_ini_setting('set_kvm_driver_emulator') }
      end

      context 'with kvm driver emulator settings' do
        let(:params) { {
            :kvm_driver_emulator => '/usr/bin/foobar/kvm-bogus'
        } }
        it { should contain_ini_setting('set_kvm_driver_emulator').with_value('/usr/bin/foobar/kvm-bogus') }
      end

      context 'without kvm driver nic settings' do
        it { should_not contain_ini_setting('set_kvm_driver_nic') }
      end

      context 'with kvm driver nic settings' do
        let(:params) { {
            :kvm_driver_nic_attrs => '[ filter="clean-traffic", model="bogus" ]'
        } }
        it { should contain_ini_setting('set_kvm_driver_nic').with_value('[ filter="clean-traffic", model="bogus" ]') }
      end
    end
  end
end


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

<TITLE>
com.numericalmethod.suanshu.stats.timeseries.multivariate (SuanShu 1.3.1 API Documentation)
</TITLE>

<META NAME="date" CONTENT="2011-04-26">

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

      Overview
    Package
      Class
      Tree
      Index
      Help

                SuanShu, a Java numerical and statistical library

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes

Package com.numericalmethod.suanshu.stats.timeseries.multivariate

Interface Summary

MultiVariateTimeSeries<T>
A multivariate time series is a sequence of vectors indexed by some notion of time.

Class Summary

GenericTimeTimeSeries<T extends Comparable<T>>
This is an implementation of a multivariate time series indexed by some notion of time.

MultiVariateTimeSeries.Entry<T>
the <tt>TimeSeries.Entry</tt> for a multivariate time series

MultiVariateTimeSeries.Iterator<E extends MultiVariateTimeSeries.Entry<?>>
the <tt>Iterator</tt> to read a multivariate time series

      Overview
    Package
      Class
      Tree
      Index
      Help

                SuanShu, a Java numerical and statistical library

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes

                Copyright © 2011 Numerical Method Inc. Ltd. All Rights Reserved.


text:
package info.guardianproject.otr.app.im.service;

import info.guardianproject.otr.IOtrKeyManager;
import info.guardianproject.otr.OtrAndroidKeyManagerImpl;
import info.guardianproject.otr.OtrChatManager;
import info.guardianproject.otr.OtrDebugLogger;
import info.guardianproject.otr.app.im.IConnectionCreationListener;
import info.guardianproject.otr.app.im.IImConnection;
import info.guardianproject.otr.app.im.IRemoteImService;
import info.guardianproject.otr.app.im.ImService;
import info.guardianproject.otr.app.im.R;
import info.guardianproject.otr.app.im.app.DummyActivity;
import info.guardianproject.otr.app.im.app.ImApp;
import info.guardianproject.otr.app.im.app.ImPluginHelper;
import info.guardianproject.otr.app.im.app.NetworkConnectivityListener.State;
import info.guardianproject.otr.app.im.app.NewChatActivity;
import info.guardianproject.otr.app.im.engine.ConnectionFactory;
import info.guardianproject.otr.app.im.engine.ImConnection;
import info.guardianproject.otr.app.im.engine.ImException;
import info.guardianproject.otr.app.im.plugin.ImPluginInfo;
import info.guardianproject.otr.app.im.provider.Imps;
import info.guardianproject.util.Debug;
import info.guardianproject.util.LogCleaner;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import net.java.otr4j.OtrEngineListener;
import net.java.otr4j.OtrKeyManager;
import net.java.otr4j.OtrKeyManagerListener;
import net.java.otr4j.OtrPolicy;
import net.java.otr4j.session.SessionID;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;

public class RemoteImService extends Service implements OtrEngineListener, ImService {

    private static final String PREV_CONNECTIONS_TRAIL_TAG = "prev_connections";
    private static final String CONNECTIONS_TRAIL_TAG = "connections";
    private static final String LAST_SWIPE_TRAIL_TAG = "last_swipe";
    private static final String SERVICE_DESTROY_TRAIL_TAG = "service_destroy";
    private static final String PREV_SERVICE_CREATE_TRAIL_TAG = "prev_service_create";
    private static final String SERVICE_CREATE_TRAIL_KEY = "service_create";
    private static final String[] ACCOUNT_PROJECTION = { Imps.Account._ID, Imps.Account.PROVIDER,
                                                        Imps.Account.USERNAME,
                                                        Imps.Account.PASSWORD, };
    // TODO why aren't these Imps.Account.* values?
    private static final int ACCOUNT_ID_COLUMN = 0;
    private static final int ACCOUNT_PROVIDER_COLUMN = 1;
    private static final int ACCOUNT_USERNAME_COLUMN = 2;
    private static final int ACCOUNT_PASSOWRD_COLUMN = 3;

    private static final int EVENT_SHOW_TOAST = 100;

    private StatusBarNotifier mStatusBarNotifier;
    private Handler mServiceHandler;
    private int mNetworkType;
    private boolean mNeedCheckAutoLogin;

    //private SettingsMonitor mSettingsMonitor;
    private OtrChatManager mOtrChatManager;

    private ImPluginHelper mPluginHelper;
    private Hashtable<String, ImConnectionAdapter> mConnections;

    private Imps.ProviderSettings.QueryMap mGlobalSettings;
    private Handler mHandler;

    final RemoteCallbackList<IConnectionCreationListener> mRemoteListeners = new RemoteCallbackList<IConnectionCreationListener>();
    public long mHeartbeatInterval;
    private WakeLock mWakeLock;
    private State mNetworkState;

    private static final String TAG = "GB.ImService";

    public long getHeartbeatInterval() {
        return mHeartbeatInterval;
    }

    public static void debug(String msg) {
        LogCleaner.debug(TAG, msg);
    }

    public static void debug(String msg, Exception e) {
        LogCleaner.error(TAG, msg, e);
    }

    private synchronized void initOtr() {
        int otrPolicy = convertPolicy();

        if (mOtrChatManager == null) {

            try {
                OtrKeyManager otrKeyManager = OtrAndroidKeyManagerImpl.getInstance(this);

                if (otrKeyManager != null)
                {
                    // TODO OTRCHAT add support for more than one connection type (this is a kludge)
                    mOtrChatManager = OtrChatManager.getInstance(otrPolicy, this, otrKeyManager);
                    mOtrChatManager.addOtrEngineListener(this);

                    otrKeyManager.addListener(new OtrKeyManagerListener() {
                        public void verificationStatusChanged(SessionID session) {
                            boolean isVerified = mOtrChatManager.getKeyManager().isVerified(session);
                            String msg = session + ": verification status=" + isVerified;

                            OtrDebugLogger.log(msg);

                        }

                        public void remoteVerifiedUs(SessionID session) {
                            String msg = session + ": remote verified us";
                            OtrDebugLogger.log(msg);

                            showToast(getString(R.string.remote_verified_us),Toast.LENGTH_SHORT);
                         //   if (!isRemoteKeyVerified(session))
                           //     showWarning(session, mContext.getApplicationContext().getString(R.string.remote_verified_us));
                        }
                    });
                }
                else
                {
                    throw new RuntimeException("could not instantiate OTR manager");
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else {
            mOtrChatManager.setPolicy(otrPolicy);
        }
    }

    private int convertPolicy() {
        int otrPolicy = OtrPolicy.OPPORTUNISTIC;

        String otrModeSelect = getGlobalSettings().getOtrMode();

        if (otrModeSelect.equals("auto")) {
            otrPolicy = OtrPolicy.OPPORTUNISTIC;
        } else if (otrModeSelect.equals("disabled")) {
            otrPolicy = OtrPolicy.NEVER;

        } else if (otrModeSelect.equals("force")) {
            otrPolicy = OtrPolicy.OTRL_POLICY_ALWAYS;

        } else if (otrModeSelect.equals("requested")) {
            otrPolicy = OtrPolicy.OTRL_POLICY_MANUAL;
        }
        return otrPolicy;
    }

    private Imps.ProviderSettings.QueryMap getGlobalSettings() {
        if (mGlobalSettings == null) {

            ContentResolver contentResolver = getContentResolver();

            Cursor cursor = contentResolver.query(Imps.ProviderSettings.CONTENT_URI,new String[] {Imps.ProviderSettings.NAME, Imps.ProviderSettings.VALUE},Imps.ProviderSettings.PROVIDER + "=?",new String[] { Long.toString(Imps.ProviderSettings.PROVIDER_ID_FOR_GLOBAL_SETTINGS)},null);

            if (cursor == null)
                return null;

            mGlobalSettings = new Imps.ProviderSettings.QueryMap(cursor, contentResolver, Imps.ProviderSettings.PROVIDER_ID_FOR_GLOBAL_SETTINGS, true, mHandler);
        }

        return mGlobalSettings;
    }

    @Override
    public void onCreate() {
        debug("ImService started");
        final String prev = Debug.getTrail(this, SERVICE_CREATE_TRAIL_KEY);
        if (prev != null)
            Debug.recordTrail(this, PREV_SERVICE_CREATE_TRAIL_TAG, prev);
        Debug.recordTrail(this, SERVICE_CREATE_TRAIL_KEY, new Date());
        final String prevConnections = Debug.getTrail(this, CONNECTIONS_TRAIL_TAG);
        if (prevConnections != null)
            Debug.recordTrail(this, PREV_CONNECTIONS_TRAIL_TAG, prevConnections);
        Debug.recordTrail(this, CONNECTIONS_TRAIL_TAG, "0");

        mConnections = new Hashtable<String, ImConnectionAdapter>();
        mHandler = new Handler();

        Debug.onServiceStart();

        PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
        mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "IM_WAKELOCK");

        // Clear all account statii to logged-out, since we just got started and we don't want
        // leftovers from any previous crash.
        clearConnectionStatii();

        mStatusBarNotifier = new StatusBarNotifier(this);
        mServiceHandler = new ServiceHandler();

        //mSettingsMonitor = new SettingsMonitor();

        /*
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
        registerReceiver(mSettingsMonitor, intentFilter);
        */

      //  setBackgroundData(ImApp.getApplication().isNetworkAvailableAndConnected());

        mPluginHelper = ImPluginHelper.getInstance(this);
        mPluginHelper.loadAvailablePlugins();

        // Have the heartbeat start autoLogin, unless onStart turns this off
        mNeedCheckAutoLogin = true;

        HeartbeatService.startBeating(getApplicationContext());
    }

    private void startForegroundCompat() {
        Notification notification = new Notification(R.drawable.notify_chatsecure, getString(R.string.app_name),
                System.currentTimeMillis());
        Intent notificationIntent = new Intent(this, NewChatActivity.class);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent launchIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);
        notification.setLatestEventInfo(getApplicationContext(),
                getString(R.string.app_name),
                getString(R.string.app_unlocked),
                launchIntent);

        stopForeground(true);
        startForeground(1000, notification);
    }

    public void sendHeartbeat() {
        Debug.onHeartbeat();
        try {
            if (mNeedCheckAutoLogin && mNetworkState != State.NOT_CONNECTED) {
                debug("autoLogin from heartbeat");
                mNeedCheckAutoLogin = false;
                autoLogin();
            }

            for (ImConnectionAdapter conn : mConnections.values())
            {
                conn.sendHeartbeat();
            }
        } finally {
            return;
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        if (intent != null && HeartbeatService.HEARTBEAT_ACTION.equals(intent.getAction())) {
          //  Log.d(TAG, "HEARTBEAT");
            try {
                mWakeLock.acquire();
                sendHeartbeat();
            } finally {
                mWakeLock.release();
            }
            return START_STICKY;
        }

        if (intent != null && HeartbeatService.NETWORK_STATE_ACTION.equals(intent.getAction())) {
            NetworkInfo networkInfo = (NetworkInfo) intent
                    .getParcelableExtra(HeartbeatService.NETWORK_INFO_EXTRA);
            State networkState = State.values()[intent.getIntExtra(HeartbeatService.NETWORK_STATE_EXTRA, 0)];
            // TODO(miron) wakelock?

            networkStateChanged(networkInfo, networkState);
            return START_STICKY;
        }

        if (intent != null && intent.hasExtra(ImServiceConstants.EXTRA_CHECK_AUTO_LOGIN))
            mNeedCheckAutoLogin = intent.getBooleanExtra(ImServiceConstants.EXTRA_CHECK_AUTO_LOGIN,
                false);
        else
            mNeedCheckAutoLogin = true;

        debug("ImService.onStart, checkAutoLogin=" + mNeedCheckAutoLogin + " intent =" + intent
              + " startId =" + startId);

        // Check and login accounts if network is ready, otherwise it's checked
        // when the network becomes available.
        if (mNeedCheckAutoLogin && mNetworkState != State.NOT_CONNECTED) {
            mNeedCheckAutoLogin = false;
            autoLogin();
        }

        return START_STICKY;
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
    }

    private void clearConnectionStatii() {
        ContentResolver cr = getContentResolver();
        ContentValues values = new ContentValues(2);

        values.put(Imps.AccountStatus.PRESENCE_STATUS, Imps.Presence.OFFLINE);
        values.put(Imps.AccountStatus.CONNECTION_STATUS, Imps.ConnectionStatus.OFFLINE);

        try
        {
            //insert on the "account_status" uri actually replaces the existing value
            cr.update(Imps.AccountStatus.CONTENT_URI, values, null, null);
        }
        catch (Exception e)
        {
            //this can throw NPE on restart sometimes if database has not been unlocked
            debug("database is not unlocked yet. caught NPE from mDbHelper in ImpsProvider");
        }
    }

    private void autoLogin() {
        // Try empty passphrase.  We can't autologin if this fails.
        if (!Imps.setEmptyPassphrase(this, true)) {
            debug("Cannot autologin with non-empty passphrase");
            return;
        }

        if (!mConnections.isEmpty()) {
            // This can happen because the UI process may be restarted and may think that we need
            // to autologin, while we (the Service process) are already up.
            debug("Got autoLogin request, but we have one or more connections");
            return;
        }

        debug("Scanning accounts and login automatically");

        ContentResolver resolver = getContentResolver();

        String where = Imps.Account.KEEP_SIGNED_IN + "=1 AND " + Imps.Account.ACTIVE + "=1";
        Cursor cursor = resolver.query(Imps.Account.CONTENT_URI, ACCOUNT_PROJECTION, where, null,
                null);
        if (cursor == null) {
            Log.w(TAG, "Can't query account!");
            return;
        }
        while (cursor.moveToNext()) {
            long accountId = cursor.getLong(ACCOUNT_ID_COLUMN);
            long providerId = cursor.getLong(ACCOUNT_PROVIDER_COLUMN);
            IImConnection conn = createConnection(providerId, accountId);

            try
            {
                if (conn.getState() != ImConnection.LOGGED_IN)
                {
                    try {
                        conn.login(null, true, true);
                    } catch (RemoteException e) {
                        Log.w(TAG, "Logging error while automatically login!");
                    }
                }
            }
            catch (Exception e){
                Log.d(ImApp.LOG_TAG,"error auto logging into ImConnection",e);
            }
        }
        cursor.close();
    }

    private Map<String, String> loadProviderSettings(long providerId) {
        ContentResolver cr = getContentResolver();
        Map<String, String> settings = Imps.ProviderSettings.queryProviderSettings(cr, providerId);

//        NetworkInfo networkInfo = mNetworkConnectivityListener.getNetworkInfo();
        // Insert a fake msisdn on emulator. We don't need this on device
        // because the mobile network will take care of it.
        //        if ("1".equals(SystemProperties.get("ro.kernel.qemu"))) {
        /*
        if (false) {
            settings.put(ImpsConfigNames.MSISDN, "15555218135");
        } else if (networkInfo != null
                && networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            if (!TextUtils.isEmpty(settings.get(ImpsConfigNames.SMS_ADDR))) {
                // Send authentication through sms if SMS data channel is
                // supported and WiFi is used.
                settings.put(ImpsConfigNames.SMS_AUTH, "true");
                settings.put(ImpsConfigNames.SECURE_LOGIN, "false");
            } else {
                // Wi-Fi network won't insert a MSISDN, we should get from the SIM
                // card. Assume we can always get the correct MSISDN from SIM, otherwise,
                // the sign in would fail and an error message should be shown to warn
                // the user to contact their operator.
                String msisdn = ""; // TODO TelephonyManager.getDefault().getLine1Number();
                if (TextUtils.isEmpty(msisdn)) {
                    Log.w(TAG, "Can not read MSISDN from SIM, use a fake one."
                         + " SMS related feature won't work.");
                    msisdn = "15555218135";
                }
                settings.put(ImpsConfigNames.MSISDN, msisdn);
            }
        }*/

        return settings;
    }

    @Override
    public void onDestroy() {
        Debug.recordTrail(this, SERVICE_DESTROY_TRAIL_TAG, new Date());

        HeartbeatService.stopBeating(getApplicationContext());

        Log.w(TAG, "ImService stopped.");
        for (ImConnectionAdapter conn : mConnections.values()) {
            conn.logout();
        }

        if (mUseForeground)
            stopForeground(true);

        if (mGlobalSettings != null)
            mGlobalSettings.close();

    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    public void showToast(CharSequence text, int duration) {
        Message msg = Message.obtain(mServiceHandler, EVENT_SHOW_TOAST, duration, 0, text);
        msg.sendToTarget();
    }

    public StatusBarNotifier getStatusBarNotifier() {
        return mStatusBarNotifier;
    }

    public OtrChatManager getOtrChatManager() {
        initOtr() ;
        return mOtrChatManager;
    }

    public void scheduleReconnect(long delay) {
        if (!isNetworkAvailable()) {
            // Don't schedule reconnect if no network available. We will try to
            // reconnect when network state become CONNECTED.
            return;
        }
        mServiceHandler.postDelayed(new Runnable() {
            public void run() {
                reestablishConnections();
            }
        }, delay);
    }

    IImConnection createConnection(final long providerId, final long accountId) {
        final IImConnection[] results = new IImConnection[1];
        Debug.wrapExceptions(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                results[0] = do_createConnection(providerId, accountId);
            }
        });
        return results[0];
    }

    private boolean mUseForeground = false;

    IImConnection do_createConnection(long providerId, long accountId) {

        if (mConnections.size() == 0)
        {
            mUseForeground = getGlobalSettings().getUseForegroundPriority();

            if (mUseForeground)
                startForegroundCompat();
        }

        Map<String, String> settings = loadProviderSettings(providerId);
        ConnectionFactory factory = ConnectionFactory.getInstance();
        try {
            ImConnection conn = factory.createConnection(settings, this);
            conn.initUser(providerId, accountId);
            ImConnectionAdapter imConnectionAdapter =
                    new ImConnectionAdapter(providerId, accountId, conn, this);

            ContentResolver contentResolver = getContentResolver();

            Cursor cursor = contentResolver.query(Imps.ProviderSettings.CONTENT_URI,new String[] {Imps.ProviderSettings.NAME, Imps.ProviderSettings.VALUE},Imps.ProviderSettings.PROVIDER + "=?",new String[] { Long.toString(providerId)},null);

            if (cursor == null)
                throw new ImException ("unable to query the provider settings");

            Imps.ProviderSettings.QueryMap providerSettings = new Imps.ProviderSettings.QueryMap(
                    cursor, contentResolver, providerId, false, null);
            String userName = Imps.Account.getUserName(contentResolver, accountId);
            String domain = providerSettings.getDomain();
            providerSettings.close();

            mConnections.put(userName + '@' + domain,imConnectionAdapter);
            Debug.recordTrail(this, CONNECTIONS_TRAIL_TAG, "" + mConnections.size());

            final int N = mRemoteListeners.beginBroadcast();
            for (int i = 0; i < N; i++) {
                IConnectionCreationListener listener = mRemoteListeners.getBroadcastItem(i);
                try {
                    listener.onConnectionCreated(imConnectionAdapter);
                } catch (RemoteException e) {
                    // The RemoteCallbackList will take care of removing the
                    // dead listeners.
                }
            }

            mRemoteListeners.finishBroadcast();

            return imConnectionAdapter;
        } catch (ImException e) {
            debug("Error creating connection", e);
            return null;
        }
    }

    void removeConnection(ImConnectionAdapter connection) {

        mConnections.remove(connection);

        if (mConnections.size() == 0)
            if (getGlobalSettings().getUseForegroundPriority())
                stopForeground(true);
    }

    boolean isNetworkAvailable ()
    {
        return mNetworkState == State.CONNECTED;
    }

    void networkStateChanged(NetworkInfo networkInfo, State networkState) {
        mNetworkState = networkState;

        debug("networkStateChanged:" + mNetworkState);

        int oldType = mNetworkType;
        mNetworkType = networkInfo != null ? networkInfo.getType() : -1;

        // Notify the connection that network type has changed. Note that this
        // only work for connected connections, we need to reestablish if it's
        // suspended.
        if (mNetworkType != oldType && isNetworkAvailable()) {
            for (ImConnectionAdapter conn : mConnections.values()) {
                conn.networkTypeChanged();
            }
        }

        NetworkInfo.State state = networkInfo != null ? networkInfo.getState() : NetworkInfo.State.DISCONNECTED;
        switch (state) {
        case CONNECTED:
            if (mNeedCheckAutoLogin) {
                mNeedCheckAutoLogin = false;
                autoLogin();
                break;
            }
            reestablishConnections();
            break;

        case DISCONNECTED:
            if (!isNetworkAvailable()) {
                suspendConnections();
            }
            break;
            // TODO(miron) what about DISCONNECTING?
        default:
            break;
        }
    }

    // package private for inner class access
    void reestablishConnections() {
        if (!isNetworkAvailable()) {
            return;
        }

        for (ImConnectionAdapter conn : mConnections.values()) {
            int connState = conn.getState();
            if (connState == ImConnection.SUSPENDED) {
                conn.reestablishSession();
            }
        }

    }

    private void suspendConnections() {
        for (ImConnectionAdapter conn : mConnections.values()) {
            if (conn.getState() != ImConnection.LOGGED_IN) {
                continue;
            }
            conn.suspend();

        }

    }

    public ImConnectionAdapter getConnection(String username) {
       return mConnections.get(username);
    }

    private final IRemoteImService.Stub mBinder = new IRemoteImService.Stub() {

        @Override
        public List<ImPluginInfo> getAllPlugins() {
            return new ArrayList<ImPluginInfo>(mPluginHelper.getPluginsInfo());
        }

        @Override
        public void addConnectionCreatedListener(IConnectionCreationListener listener) {
            if (listener != null) {
                mRemoteListeners.register(listener);
            }
        }

        @Override
        public void removeConnectionCreatedListener(IConnectionCreationListener listener) {
            if (listener != null) {
                mRemoteListeners.unregister(listener);
            }
        }

        @Override
        public IImConnection createConnection(long providerId, long accountId) {
            return RemoteImService.this.createConnection(providerId, accountId);
        }

        @Override
        public List getActiveConnections() {
            ArrayList<IBinder> result = new ArrayList<IBinder>(mConnections.size());
            for (IImConnection conn : mConnections.values()) {
                result.add(conn.asBinder());
            }
            return result;
        }

        @Override
        public void dismissNotifications(long providerId) {
            mStatusBarNotifier.dismissNotifications(providerId);
        }

        @Override
        public void dismissChatNotification(long providerId, String username) {
            mStatusBarNotifier.dismissChatNotification(providerId, username);
        }

        @Override
        public boolean unlockOtrStore (String password)
        {
            OtrAndroidKeyManagerImpl.setKeyStorePassword(password);
            return true;
        }

        @Override
        public IOtrKeyManager getOtrKeyManager()
        {

            try
            {
                OtrAndroidKeyManagerImpl keyMgr = OtrAndroidKeyManagerImpl.getInstance(RemoteImService.this);

                return keyMgr;
            }
            catch (IOException re)
            {
                throw new RuntimeException("Could not open OTR Key Manager store");
            }

        }

        @Override
        public void setKillProcessOnStop (boolean killProcessOnStop)
        {
            mKillProcessOnStop = killProcessOnStop;
        }

        @Override
        public void enableDebugLogging (boolean debug)
        {
            Debug.DEBUG_ENABLED = debug;
        }
    };

    private boolean mKillProcessOnStop = false;

    /*
     //the concept of "background data is deprecated from Android
     // the only thing that matters is checking if Network is available and connected
    private final class SettingsMonitor extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED.equals(action)) {
                ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
                setBackgroundData(manager.getBackgroundDataSetting());
                handleBackgroundDataSettingChange();
            }
        }
    }
    */
    private final class ServiceHandler extends Handler {
        public ServiceHandler() {
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case EVENT_SHOW_TOAST:
                Toast.makeText(RemoteImService.this, (CharSequence) msg.obj, msg.arg1).show();
                break;

            default:
            }
        }
    }

    @Override
    public void sessionStatusChanged(SessionID sessionID) {

        //this method does nothing!
    }

    public void onTaskRemoved(Intent rootIntent) {
        Debug.recordTrail(this, LAST_SWIPE_TRAIL_TAG, new Date());
        Intent intent = new Intent(this, DummyActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
    }
}


text:
package ch.ninecode.np

/**
 * Parser for Customer3_NetworkParameters command line operation.
 */
@SuppressWarnings(Array("org.wartremover.warts.NonUnitStatements"))
class Customer3OptionsParser (options: NetworkParametersOptions) extends NetworkParametersOptionsParser(options)
{
    opt[String]("csv")
        .valueName("<CSV file>")
        .action((x, c) => c.copy(available_power_csv = x))
        .text(s"csv file of available power at station data [${options.available_power_csv}]")
}


text:
<?php
namespace TYPO3\Flow\Tests\Unit\Aop\Advice;

/**
 * Testcase for the Abstract Method Interceptor Builder
 *
 */
class AroundAdviceTest extends \TYPO3\Flow\Tests\UnitTestCase
{
    /**
     * @test
     * @return void
     */
    public function invokeInvokesTheAdviceIfTheRuntimeEvaluatorReturnsTrue()
    {
        $mockJoinPoint = $this->createMock(\TYPO3\Flow\Aop\JoinPointInterface::class);

        $mockAspect = $this->createMock(Fixtures\SomeClass::class);
        $mockAspect->expects($this->once())->method('someMethod')->with($mockJoinPoint)->will($this->returnValue('result'));

        $mockObjectManager = $this->createMock(\TYPO3\Flow\Object\ObjectManagerInterface::class);
        $mockObjectManager->expects($this->once())->method('get')->with('aspectObjectName')->will($this->returnValue($mockAspect));

        $advice = new \TYPO3\Flow\Aop\Advice\AroundAdvice('aspectObjectName', 'someMethod', $mockObjectManager, function (\TYPO3\Flow\Aop\JoinPointInterface $joinPoint) {
            if ($joinPoint !== null) {
                return true;
            }
        });
        $result = $advice->invoke($mockJoinPoint);

        $this->assertEquals($result, 'result', 'The around advice did not return the result value as expected.');
    }

    /**
     * @test
     * @return void
     */
    public function invokeDoesNotInvokeTheAdviceIfTheRuntimeEvaluatorReturnsFalse()
    {
        $mockAdviceChain = $this->getMockBuilder(\TYPO3\Flow\Aop\Advice\AdviceChain::class)->disableOriginalConstructor()->getMock();
        $mockAdviceChain->expects($this->once())->method('proceed')->will($this->returnValue('result'));

        $mockJoinPoint = $this->createMock(\TYPO3\Flow\Aop\JoinPointInterface::class);
        $mockJoinPoint->expects($this->any())->method('getAdviceChain')->will($this->returnValue($mockAdviceChain));

        $mockAspect = $this->createMock(Fixtures\SomeClass::class);
        $mockAspect->expects($this->never())->method('someMethod');

        $mockObjectManager = $this->createMock(\TYPO3\Flow\Object\ObjectManagerInterface::class);
        $mockObjectManager->expects($this->any())->method('get')->will($this->returnValue($mockAspect));

        $advice = new \TYPO3\Flow\Aop\Advice\AroundAdvice('aspectObjectName', 'someMethod', $mockObjectManager, function (\TYPO3\Flow\Aop\JoinPointInterface $joinPoint) {
            if ($joinPoint !== null) {
                return false;
            }
        });
        $result = $advice->invoke($mockJoinPoint);

        $this->assertEquals($result, 'result', 'The around advice did not return the result value as expected.');
    }
}


text:
package org.killbill.billing.invoice.tree;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.killbill.billing.invoice.api.InvoiceItem;
import org.killbill.billing.invoice.api.InvoiceItemType;

import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;

/**
 * Tree of invoice items for a given account.
 *

 *
It contains a map of <tt>SubscriptionItemTree</tt> and the logic is executed independently for all items
 * associated to a given subscription. That also means that invoice item adjustment which cross subscriptions
 * can't be correctly handled when they compete with other forms of adjustments.
 *

 *
The class is not thread safe, there is no such use case today, and there is a lifecyle to respect:
 *

 *
Add existing invoice items
 *
Build the tree,
 *
Merge the proposed list
 *
Retrieves final list
 *

 */
public class AccountItemTree {

    private final UUID accountId;
    private final UUID targetInvoiceId;
    private final Map<UUID, SubscriptionItemTree> subscriptionItemTree;
    private final List<InvoiceItem> allExistingItems;
    private List<InvoiceItem> pendingItemAdj;

    private boolean isBuilt;

    public AccountItemTree(final UUID accountId, final UUID targetInvoiceId) {
        this.accountId = accountId;
        this.targetInvoiceId = targetInvoiceId;
        this.subscriptionItemTree = new HashMap<UUID, SubscriptionItemTree>();
        this.isBuilt = false;
        this.allExistingItems = new LinkedList<InvoiceItem>();
        this.pendingItemAdj = new LinkedList<InvoiceItem>();
    }

    /**
     * build the subscription trees after they have been populated with existing items on disk
     */
    public void build() {
        Preconditions.checkState(!isBuilt);

        if (pendingItemAdj.size() > 0) {
            for (InvoiceItem item : pendingItemAdj) {
                addExistingItem(item, true);
            }
            pendingItemAdj.clear();
        }
        for (SubscriptionItemTree tree : subscriptionItemTree.values()) {
            tree.build();
        }
        isBuilt = true;
    }

    /**
     * Populate tree from existing items on disk
     *
     * @param existingItem an item read on disk
     */
    public void addExistingItem(final InvoiceItem existingItem) {
        addExistingItem(existingItem, false);
    }

    private void addExistingItem(final InvoiceItem existingItem, final boolean failOnMissingSubscription) {
        Preconditions.checkState(!isBuilt);

        // Only used to retrieve the original item for linked items
        allExistingItems.add(existingItem);

        switch (existingItem.getInvoiceItemType()) {
            case EXTERNAL_CHARGE:
            case TAX:
            case CBA_ADJ:
            case CREDIT_ADJ:
            case REFUND_ADJ:
            case USAGE:
                return;

            case RECURRING:
            case REPAIR_ADJ:
            case FIXED:
            case ITEM_ADJ:
                break;

            default:
                Preconditions.checkState(false, "Unknown invoice item type " + existingItem.getInvoiceItemType());

        }

        if (existingItem.getInvoiceItemType() == InvoiceItemType.ITEM_ADJ) {
            final InvoiceItem linkedInvoiceItem = getLinkedInvoiceItem(existingItem, allExistingItems);
            if (linkedInvoiceItem != null &&
                linkedInvoiceItem.getInvoiceItemType() != InvoiceItemType.RECURRING &&
                linkedInvoiceItem.getInvoiceItemType() != InvoiceItemType.FIXED) {
                // We only care about adjustments for recurring and fixed items when building the tree
                // (we assume that REPAIR_ADJ and ITEM_ADJ items cannot be adjusted)
                return;
            }
        }

        final UUID subscriptionId = getSubscriptionId(existingItem, allExistingItems);
        Preconditions.checkState(subscriptionId != null || !failOnMissingSubscription, "Missing subscription id");

        if (subscriptionId == null && existingItem.getInvoiceItemType() == InvoiceItemType.ITEM_ADJ) {
            pendingItemAdj.add(existingItem);
            return;
        }

        if (!subscriptionItemTree.containsKey(subscriptionId)) {
            subscriptionItemTree.put(subscriptionId, new SubscriptionItemTree(subscriptionId, targetInvoiceId));
        }
        final SubscriptionItemTree tree = subscriptionItemTree.get(subscriptionId);
        tree.addItem(existingItem);
    }

    /**
     * Rebuild the new tree by merging current on-disk existing view with new proposed list.
     *
     * @param proposedItems list of proposed item that should be merged with current existing view
     */
    public void mergeWithProposedItems(final List<InvoiceItem> proposedItems) {

        build();
        for (SubscriptionItemTree tree : subscriptionItemTree.values()) {
            tree.flatten(true);
        }

        for (InvoiceItem item : proposedItems) {
            final UUID subscriptionId = getSubscriptionId(item, null);
            SubscriptionItemTree tree = subscriptionItemTree.get(subscriptionId);
            if (tree == null) {
                tree = new SubscriptionItemTree(subscriptionId, targetInvoiceId);
                subscriptionItemTree.put(subscriptionId, tree);
            }
            tree.mergeProposedItem(item);
        }

        for (SubscriptionItemTree tree : subscriptionItemTree.values()) {
            tree.buildForMerge();
        }
    }

    /**
     * @return the resulting list of items that should be written to disk
     */
    public List<InvoiceItem> getResultingItemList() {
        final List<InvoiceItem> result = new ArrayList<InvoiceItem>();
        for (SubscriptionItemTree tree : subscriptionItemTree.values()) {
            final List<InvoiceItem> simplifiedView = tree.getView();
            if (simplifiedView.size() > 0) {
                result.addAll(simplifiedView);
            }
        }
        return result;
    }

    public UUID getAccountId() {
        return accountId;
    }

    private UUID getSubscriptionId(final InvoiceItem item, final List<InvoiceItem> allItems) {
        if (item.getInvoiceItemType() == InvoiceItemType.RECURRING ||
            item.getInvoiceItemType() == InvoiceItemType.FIXED) {
            return item.getSubscriptionId();
        } else {
            final InvoiceItem linkedItem = getLinkedInvoiceItem(item, allItems);
            return linkedItem != null ? linkedItem.getSubscriptionId() : null;
        }
    }

    private InvoiceItem getLinkedInvoiceItem(final InvoiceItem item, final Iterable<InvoiceItem> allItems) {
        return Iterables.tryFind(allItems, new Predicate<InvoiceItem>() {
            @Override
            public boolean apply(final InvoiceItem input) {
                return input.getId().equals(item.getLinkedItemId());
            }
        }).orNull();
    }
}


text:
#ifndef AUTOBOOST_PREDEF_COMPILER_DIAB_H
#define AUTOBOOST_PREDEF_COMPILER_DIAB_H

#include <autoboost/predef/version_number.h>
#include <autoboost/predef/make.h>

/*`
[heading `AUTOBOOST_COMP_DIAB`]

[@http://www.windriver.com/products/development_suite/wind_river_compiler/ Diab C/C++] compiler.
Version number available as major, minor, and patch.

[table
    [[__predef_symbol__] [__predef_version__]]

    [[`__DCC__`] [__predef_detection__]]

    [[`__VERSION_NUMBER__`] [V.R.P]]
    ]
 */

#define AUTOBOOST_COMP_DIAB AUTOBOOST_VERSION_NUMBER_NOT_AVAILABLE

#if defined(__DCC__)
#   define AUTOBOOST_COMP_DIAB_DETECTION AUTOBOOST_PREDEF_MAKE_10_VRPP(__VERSION_NUMBER__)
#endif

#ifdef AUTOBOOST_COMP_DIAB_DETECTION
#   if defined(AUTOBOOST_PREDEF_DETAIL_COMP_DETECTED)
#       define AUTOBOOST_COMP_DIAB_EMULATED AUTOBOOST_COMP_DIAB_DETECTION
#   else
#       undef AUTOBOOST_COMP_DIAB
#       define AUTOBOOST_COMP_DIAB AUTOBOOST_COMP_DIAB_DETECTION
#   endif
#   define AUTOBOOST_COMP_DIAB_AVAILABLE
#   include <autoboost/predef/detail/comp_detected.h>
#endif

#define AUTOBOOST_COMP_DIAB_NAME "Diab C/C++"

#include <autoboost/predef/detail/test.h>
AUTOBOOST_PREDEF_DECLARE_TEST(AUTOBOOST_COMP_DIAB,AUTOBOOST_COMP_DIAB_NAME)

#ifdef AUTOBOOST_COMP_DIAB_EMULATED
#include <autoboost/predef/detail/test.h>
AUTOBOOST_PREDEF_DECLARE_TEST(AUTOBOOST_COMP_DIAB_EMULATED,AUTOBOOST_COMP_DIAB_NAME)
#endif

#endif


text:
<?php

/** @Entity @Table(name="news_post") */
class Model_News_Post {
  /** @Id @Column(type="integer") @GeneratedValue(strategy="AUTO") */
  protected $id;
  /** @Column(type="string", length="255") */
  protected $name;
  /** @Column(type="integer") */
  protected $time;
  /** @OneToOne(targetEntity="Model_Auth_User") */
  protected $user;
  /** @Column(type="string", length="65535") */
  protected $content;
  /**
  * @ManyToMany(targetEntity="Model_News_Category", inversedBy="posts")
  * @JoinTable(name="news_post_category", joinColumns={@JoinColumn(name="category_id", referencedColumnName="id")}, inverseJoinColumns={@JoinColumn(name="post_id", referencedColumnName="id")})
  */
  protected $categories = array();
  /**
  * @ManyToMany(targetEntity="Model_News_Tag", inversedBy="posts")
  * @JoinTable(name="news_post_tag", joinColumns={@JoinColumn(name="tag_id", referencedColumnName="id")}, inverseJoinColumns={@JoinColumn(name="post_id", referencedColumnName="id")})
  */
  protected $tags = array();

  public function get_id() { return $this->id; }
  public function set_id($id) { if (is_integer($id)) { $this->id = $id; return true; } return false; }
  public function get_name() { return $this->name; }
  public function set_name($name) { if (is_string($name)) { $this->name = $name; return true; } return false; }
  public function get_time() { return $this->time; }
  public function set_time($time) { if (is_integer($time)) { $this->time = $time; return true; } return false; }
  public function get_user() { return $this->user; }
  public function set_user($user) { if (is_a('Model_Auth_User', $user)) { $this->user = $user; return true; } return false; }
  public function get_content() { return $this->content; }
  public function set_content($content) { if (is_string($content)) { $this->content = $content; return true; } return false; }
  public function get_categories() { return $this->categories; }
  public function get_tags() { return $this->tags; }
}

?>


text:
layout: brief
issue: 2018
category: brief
order: 1
title: Preparing for recession
colors:
    background: "#f7edde"
    tag: "#84cbd8"
tags:
    - Economics
---
<figure>
{% asset 2018/carl-walsh.jpg @magick:resize=380 alt:"Carl Walsh" class:"right" %}
<figcaption>Distinguished professor of economics Carl Walsh speaks on monetary policy at Norges Bank, the central bank of Norway. Credit: Courtesy of Carl Walsh.</figcaption>
</figure>

During the 2008 financial crisis, the Federal Reserve reinvigorated the economy by slashing its benchmark interest rate to zero. Today, as the economy continues to rebound, interest rates are climbing.

But due to shifts in the global economy—in particular, the emergence of China—economists expect slower growth and interest rates to remain low overall. If there's another financial crisis, inflation will again plummet, taking interest rates down with it.

With rates already low, the Fed won't be able to cut them further to spur spending. "When interest rates hit an effective lower bound, monetary policy is constrained in its ability to help stabilize the economy," said [**Carl Walsh**](https://economics.ucsc.edu/faculty/singleton.php?&singleton=true&cruz_id=walshc), distinguished professor of economics.

Other safeguards may be needed. Walsh and other economists are evaluating whether central banks should move away from current policies that work to maintain a certain inflation rate. They could instead aim to keep general prices at a certain level or promise to keep future interest rates low. Such forward guidance policies are discussed in a new chapter in the recently published fourth edition of Walsh's textbook, [*Monetary Theory and Policy*](https://mitpress.mit.edu/books/monetary-theory-and-policy-fourth-edition).

If and when another recession hits, investors would expect these price-level targeting policies to bump prices—and inflation—back up, Walsh said. The anticipation of higher inflation coupled with rock-bottom interest rates would incentivize people to borrow and spend, thus stabilizing the economy.

*—[Marcus Woo](https://about.me/marcus_woo)*


text:
using System.Collections.Generic;
namespace BizHawk.Client.ApiHawk
{
	public interface IMovie : IExternalApi
	{
		bool StartsFromSavestate();
		bool StartsFromSaveram();
		string Filename();
		Dictionary<string, dynamic> GetInput(int frame);
		string GetInputAsMnemonic(int frame);
		bool GetReadOnly();
		ulong GetRerecordCount();
		bool GetRerecordCounting();
		bool IsLoaded();
		double Length();
		string Mode();
		void Save(string filename = "");
		void SetReadOnly(bool readOnly);
		void SetRerecordCount(double count);
		void SetRerecordCounting(bool counting);
		void Stop();
		double GetFps();
		Dictionary<string, string> GetHeader();
		List<string> GetComments();
		List<string> GetSubtitles();
	}
}


text:
<?php
// $Id: calendar-week-multiple-node.tpl.php,v 1.1.2.5 2010/11/21 13:19:37 karens Exp $
/**
 * @file
 * Template to display a summary of the days items as a calendar week node.
 *
 * @see template_preprocess_calendar_week_multiple_node.
 */
?>
<div class="view-item view-item-<?php print $view->name ?>">
  <div class="<?php print $curday; ?> calendar weekview">
    <?php foreach ($types as $type): ?>
      <?php if ($view->date_info->style_max_items_behavior != 'more'): ?>
        <?php print theme('calendar_stripe_stripe', $type); ?>
      <?php endif; ?>
    <?php endforeach; ?>
    <div class="view-item <?php print views_css_safe('view-item-'. $view->name) ?>">
      <?php if ($view->date_info->style_max_items_behavior != 'more'): ?>

          <?php print l(t('Click to see all @count events', array('@count' => $count)), $link) ?>

    <?php else: ?>

<?php print l(t('more'), $link) ?>»

    <?php endif; ?>


text:
using System;
using System.Windows.Forms;

namespace xClient.Core.MouseKeyHook
{
    /// <summary>
    ///     Provides all mouse events.
    /// </summary>
    public interface IMouseEvents
    {
        /// <summary>
        ///     Occurs when the mouse pointer is moved.
        /// </summary>
        event MouseEventHandler MouseMove;

        /// <summary>
        ///     Occurs when the mouse pointer is moved.
        /// </summary>
        /// <remarks>
        ///     This event provides extended arguments of type <see cref="MouseEventArgs" /> enabling you to
        ///     suppress further processing of mouse movement in other applications.
        /// </remarks>
        event EventHandler<MouseEventExtArgs> MouseMoveExt;

        /// <summary>
        ///     Occurs when a click was performed by the mouse.
        /// </summary>
        event MouseEventHandler MouseClick;

        /// <summary>
        ///     Occurs when the mouse a mouse button is pressed.
        /// </summary>
        event MouseEventHandler MouseDown;

        /// <summary>
        ///     Occurs when the mouse a mouse button is pressed.
        /// </summary>
        /// <remarks>
        ///     This event provides extended arguments of type <see cref="MouseEventArgs" /> enabling you to
        ///     suppress further processing of mouse click in other applications.
        /// </remarks>
        event EventHandler<MouseEventExtArgs> MouseDownExt;

        /// <summary>
        ///     Occurs when a mouse button is released.
        /// </summary>
        event MouseEventHandler MouseUp;

        /// <summary>
        /// Occurs when a mouse button is released.
        /// </summary>
        /// <remarks>
        ///     This event provides extended arguments of type <see cref="MouseEventArgs" /> enabling you to
        ///     suppress further processing of mouse click in other applications.
        /// </remarks>
        event EventHandler<MouseEventExtArgs> MouseUpExt;

        /// <summary>
        ///     Occurs when the mouse wheel moves.
        /// </summary>
        event MouseEventHandler MouseWheel;

        /// <summary>
        ///     Occurs when a mouse button is double-clicked.
        /// </summary>
        event MouseEventHandler MouseDoubleClick;
    }
}


text:
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_EDITING_VISIBLE_UNITS_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_EDITING_VISIBLE_UNITS_H_

#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/editing/editing_boundary.h"
#include "third_party/blink/renderer/core/editing/forward.h"
#include "third_party/blink/renderer/platform/geometry/layout_rect.h"
#include "third_party/blink/renderer/platform/text/text_direction.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_uchar.h"

namespace gfx {
class Point;
class Rect;
}

namespace blink {

class LayoutObject;
class Node;
class LocalFrame;

// |WordSide| is used as a parameter of |StartOfWordPosition()| and
// |EndOfWord()| to control a returning position when they are called for a
// position before word boundary.
enum WordSide {
  kNextWordIfOnBoundary = false,
  kPreviousWordIfOnBoundary = true
};

enum class PlatformWordBehavior { kWordSkipSpaces, kWordDontSkipSpaces };
enum class SentenceTrailingSpaceBehavior { kIncludeSpace, kOmitSpace };

// offset functions on Node
CORE_EXPORT int CaretMinOffset(const Node*);
CORE_EXPORT int CaretMaxOffset(const Node*);

// Position
// mostForward/BackwardCaretPosition are used for moving back and forth between
// visually equivalent candidates.
// For example, for the text node "foo     bar" where whitespace is
// collapsible, there are two candidates that map to the VisiblePosition
// between 'b' and the space, after first space and before last space.
//
// mostBackwardCaretPosition returns the left candidate and also returs
// [boundary, 0] for any of the positions from [boundary, 0] to the first
// candidate in boundary, where
// endsOfNodeAreVisuallyDistinctPositions(boundary) is true.
//
// mostForwardCaretPosition() returns the right one and also returns the
// last position in the last atomic node in boundary for all of the positions
// in boundary after the last candidate, where
// endsOfNodeAreVisuallyDistinctPositions(boundary).
CORE_EXPORT Position MostBackwardCaretPosition(
    const Position&,
    EditingBoundaryCrossingRule = kCannotCrossEditingBoundary);
CORE_EXPORT PositionInFlatTree MostBackwardCaretPosition(
    const PositionInFlatTree&,
    EditingBoundaryCrossingRule = kCannotCrossEditingBoundary);
CORE_EXPORT Position MostForwardCaretPosition(
    const Position&,
    EditingBoundaryCrossingRule = kCannotCrossEditingBoundary);
CORE_EXPORT PositionInFlatTree MostForwardCaretPosition(
    const PositionInFlatTree&,
    EditingBoundaryCrossingRule = kCannotCrossEditingBoundary);

CORE_EXPORT bool IsVisuallyEquivalentCandidate(const Position&);
CORE_EXPORT bool IsVisuallyEquivalentCandidate(const PositionInFlatTree&);

// Whether or not [node, 0] and [node, lastOffsetForEditing(node)] are their own
// VisiblePositions.
// If true, adjacent candidates are visually distinct.
CORE_EXPORT bool EndsOfNodeAreVisuallyDistinctPositions(const Node*);

CORE_EXPORT Position CanonicalPositionOf(const Position&);
CORE_EXPORT PositionInFlatTree CanonicalPositionOf(const PositionInFlatTree&);

CORE_EXPORT UChar32 CharacterAfter(const VisiblePosition&);
CORE_EXPORT UChar32 CharacterAfter(const VisiblePositionInFlatTree&);
CORE_EXPORT UChar32 CharacterBefore(const VisiblePosition&);
CORE_EXPORT UChar32 CharacterBefore(const VisiblePositionInFlatTree&);

CORE_EXPORT VisiblePosition
NextPositionOf(const Position&,
               EditingBoundaryCrossingRule = kCanCrossEditingBoundary);
CORE_EXPORT VisiblePosition
NextPositionOf(const VisiblePosition&,
               EditingBoundaryCrossingRule = kCanCrossEditingBoundary);
CORE_EXPORT VisiblePositionInFlatTree
NextPositionOf(const VisiblePositionInFlatTree&,
               EditingBoundaryCrossingRule = kCanCrossEditingBoundary);
CORE_EXPORT VisiblePosition
PreviousPositionOf(const VisiblePosition&,
                   EditingBoundaryCrossingRule = kCanCrossEditingBoundary);
CORE_EXPORT VisiblePositionInFlatTree
PreviousPositionOf(const VisiblePositionInFlatTree&,
                   EditingBoundaryCrossingRule = kCanCrossEditingBoundary);

// words
CORE_EXPORT Position StartOfWordPosition(const Position&,
                                         WordSide = kNextWordIfOnBoundary);
CORE_EXPORT PositionInFlatTree
StartOfWordPosition(const PositionInFlatTree&,
                    WordSide = kNextWordIfOnBoundary);
CORE_EXPORT Position EndOfWordPosition(const Position&,
                                       WordSide = kNextWordIfOnBoundary);
CORE_EXPORT PositionInFlatTree
EndOfWordPosition(const PositionInFlatTree&, WordSide = kNextWordIfOnBoundary);
CORE_EXPORT PositionWithAffinity PreviousWordPosition(const Position&);
CORE_EXPORT PositionInFlatTreeWithAffinity
PreviousWordPosition(const PositionInFlatTree&);
CORE_EXPORT PositionWithAffinity NextWordPosition(
    const Position&,
    PlatformWordBehavior = PlatformWordBehavior::kWordDontSkipSpaces);
CORE_EXPORT PositionInFlatTreeWithAffinity NextWordPosition(
    const PositionInFlatTree&,
    PlatformWordBehavior = PlatformWordBehavior::kWordDontSkipSpaces);
bool IsWordBreak(UChar);

// sentences
CORE_EXPORT Position StartOfSentencePosition(const Position&);
CORE_EXPORT PositionInFlatTree
StartOfSentencePosition(const PositionInFlatTree&);
CORE_EXPORT PositionWithAffinity
EndOfSentence(const Position&,
              SentenceTrailingSpaceBehavior =
                  SentenceTrailingSpaceBehavior::kIncludeSpace);
CORE_EXPORT PositionInFlatTreeWithAffinity
EndOfSentence(const PositionInFlatTree&,
              SentenceTrailingSpaceBehavior =
                  SentenceTrailingSpaceBehavior::kIncludeSpace);
CORE_EXPORT VisiblePosition
EndOfSentence(const VisiblePosition&,
              SentenceTrailingSpaceBehavior =
                  SentenceTrailingSpaceBehavior::kIncludeSpace);
CORE_EXPORT VisiblePositionInFlatTree
EndOfSentence(const VisiblePositionInFlatTree&,
              SentenceTrailingSpaceBehavior =
                  SentenceTrailingSpaceBehavior::kIncludeSpace);
PositionInFlatTree PreviousSentencePosition(const PositionInFlatTree&);
PositionInFlatTree NextSentencePosition(const PositionInFlatTree&);
EphemeralRange ExpandEndToSentenceBoundary(const EphemeralRange&);
EphemeralRange ExpandRangeToSentenceBoundary(const EphemeralRange&);

// lines
// TODO(yosin) Return values of |VisiblePosition| version of |startOfLine()|
// with shadow tree isn't defined well. We should not use it for shadow tree.
CORE_EXPORT VisiblePosition StartOfLine(const VisiblePosition&);
CORE_EXPORT VisiblePositionInFlatTree
StartOfLine(const VisiblePositionInFlatTree&);
CORE_EXPORT PositionWithAffinity StartOfLine(const PositionWithAffinity&);
CORE_EXPORT PositionInFlatTreeWithAffinity
StartOfLine(const PositionInFlatTreeWithAffinity&);
CORE_EXPORT PositionWithAffinity EndOfLine(const PositionWithAffinity&);
CORE_EXPORT PositionInFlatTreeWithAffinity
EndOfLine(const PositionInFlatTreeWithAffinity&);
CORE_EXPORT bool InSameLine(const VisiblePosition&, const VisiblePosition&);
CORE_EXPORT bool InSameLine(const VisiblePositionInFlatTree&,
                            const VisiblePositionInFlatTree&);
CORE_EXPORT bool InSameLine(const PositionWithAffinity&,
                            const PositionWithAffinity&);
CORE_EXPORT bool InSameLine(const PositionInFlatTreeWithAffinity&,
                            const PositionInFlatTreeWithAffinity&);
CORE_EXPORT bool IsStartOfLine(const VisiblePosition&);
CORE_EXPORT bool IsStartOfLine(const VisiblePositionInFlatTree&);
CORE_EXPORT bool IsEndOfLine(const VisiblePosition&);
CORE_EXPORT bool IsEndOfLine(const VisiblePositionInFlatTree&);
// TODO(yosin) Return values of |VisiblePosition| version of
// |logicalStartOfLine()| with shadow tree isn't defined well. We should not use
// it for shadow tree.
CORE_EXPORT VisiblePosition LogicalStartOfLine(const VisiblePosition&);
CORE_EXPORT VisiblePositionInFlatTree
LogicalStartOfLine(const VisiblePositionInFlatTree&);
// TODO(yosin) Return values of |VisiblePosition| version of
// |logicalEndOfLine()| with shadow tree isn't defined well. We should not use
// it for shadow tree.
CORE_EXPORT VisiblePosition LogicalEndOfLine(const VisiblePosition&);
CORE_EXPORT VisiblePositionInFlatTree
LogicalEndOfLine(const VisiblePositionInFlatTree&);
CORE_EXPORT bool IsLogicalEndOfLine(const VisiblePosition&);
CORE_EXPORT bool IsLogicalEndOfLine(const VisiblePositionInFlatTree&);

// paragraphs (perhaps a misnomer, can be divided by line break elements)
// TODO(yosin) Since return value of |startOfParagraph()| with |VisiblePosition|
// isn't defined well on flat tree, we should not use it for a position in
// flat tree.
CORE_EXPORT VisiblePosition
StartOfParagraph(const VisiblePosition&,
                 EditingBoundaryCrossingRule = kCannotCrossEditingBoundary);
CORE_EXPORT VisiblePositionInFlatTree
StartOfParagraph(const VisiblePositionInFlatTree&,
                 EditingBoundaryCrossingRule = kCannotCrossEditingBoundary);
CORE_EXPORT VisiblePosition
EndOfParagraph(const VisiblePosition&,
               EditingBoundaryCrossingRule = kCannotCrossEditingBoundary);
CORE_EXPORT VisiblePositionInFlatTree
EndOfParagraph(const VisiblePositionInFlatTree&,
               EditingBoundaryCrossingRule = kCannotCrossEditingBoundary);
CORE_EXPORT VisiblePosition StartOfNextParagraph(const VisiblePosition&);
CORE_EXPORT bool IsStartOfParagraph(
    const VisiblePosition&,
    EditingBoundaryCrossingRule = kCannotCrossEditingBoundary);
CORE_EXPORT bool IsStartOfParagraph(const VisiblePositionInFlatTree&);
CORE_EXPORT bool IsEndOfParagraph(
    const VisiblePosition&,
    EditingBoundaryCrossingRule = kCannotCrossEditingBoundary);
CORE_EXPORT bool IsEndOfParagraph(const VisiblePositionInFlatTree&);
bool InSameParagraph(const VisiblePosition&,
                     const VisiblePosition&,
                     EditingBoundaryCrossingRule = kCannotCrossEditingBoundary);
EphemeralRange ExpandToParagraphBoundary(const EphemeralRange&);

// document
CORE_EXPORT Position StartOfDocument(const Position&);
CORE_EXPORT PositionInFlatTree StartOfDocument(const PositionInFlatTree&);
CORE_EXPORT VisiblePosition EndOfDocument(const VisiblePosition&);
CORE_EXPORT VisiblePositionInFlatTree
EndOfDocument(const VisiblePositionInFlatTree&);
bool IsStartOfDocument(const VisiblePosition&);
bool IsEndOfDocument(const VisiblePosition&);

// editable content
PositionInFlatTree StartOfEditableContent(const PositionInFlatTree&);
PositionInFlatTree EndOfEditableContent(const PositionInFlatTree&);
CORE_EXPORT bool IsEndOfEditableOrNonEditableContent(const VisiblePosition&);
CORE_EXPORT bool IsEndOfEditableOrNonEditableContent(
    const VisiblePositionInFlatTree&);

bool HasRenderedNonAnonymousDescendantsWithHeight(const LayoutObject*);

// TODO(editing-dev): We should move this functions to somewhere else.
// Returns a hit-tested PositionWithAffinity for the given point in
// contents-space coordinates.
CORE_EXPORT PositionWithAffinity
PositionForContentsPointRespectingEditingBoundary(const gfx::Point&,
                                                  LocalFrame*);

CORE_EXPORT bool RendersInDifferentPosition(const Position&, const Position&);

CORE_EXPORT Position SkipWhitespace(const Position&);
CORE_EXPORT PositionInFlatTree SkipWhitespace(const PositionInFlatTree&);

CORE_EXPORT gfx::Rect ComputeTextRect(const EphemeralRange&);
gfx::Rect ComputeTextRect(const EphemeralRangeInFlatTree&);
gfx::RectF ComputeTextRectF(const EphemeralRange&);

// |FirstRectForRange| requires up-to-date layout.
gfx::Rect FirstRectForRange(const EphemeralRange&);

CORE_EXPORT PositionWithAffinity
AdjustForwardPositionToAvoidCrossingEditingBoundaries(
    const PositionWithAffinity&,
    const Position&);

PositionInFlatTreeWithAffinity
AdjustForwardPositionToAvoidCrossingEditingBoundaries(
    const PositionInFlatTreeWithAffinity&,
    const PositionInFlatTree&);

PositionWithAffinity AdjustBackwardPositionToAvoidCrossingEditingBoundaries(
    const PositionWithAffinity&,
    const Position&);

PositionInFlatTreeWithAffinity
AdjustBackwardPositionToAvoidCrossingEditingBoundaries(
    const PositionInFlatTreeWithAffinity&,
    const PositionInFlatTree&);

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_CORE_EDITING_VISIBLE_UNITS_H_


text:
/**Testing package "document".*/
package ru.job4j.profession.document;