text:
package com.szagurskii.patternedtextwatcher;

import android.text.Editable;
import android.text.TextWatcher;
import android.util.SparseArray;

import static com.szagurskii.patternedtextwatcher.Preconditions.checkInput;
import static com.szagurskii.patternedtextwatcher.Preconditions.checkPatternInInput;
import static com.szagurskii.patternedtextwatcher.Preconditions.checkPatternInput;

/**
 * A customizable text watcher which can be constructed via {@link Builder}.
 *
 * @author Savelii Zagurskii
 */
public class PatternedTextWatcher implements TextWatcher {

  static final String DEFAULT_CHAR = "#";

  private final int maxLength;
  private final char specialCharacter;

  /** Indexes of secondary characters (not inserted by user). */
  private final SparseArray<Character> patternCharactersByIndex;

  /** Indexes of symbols inserted by user. */
  private final SparseArray<Character> normalCharactersByIndex;

  private final boolean fillExtra;
  private final boolean deleteExtra;
  private final boolean saveInput;
  private final boolean respectPatternLength;
  private final boolean debug;

  private int firstIndexToCheck;
  private int lastIndexToCheck;

  private String lastText;
  private boolean enabled;
  private StringBuilder savedText;

  /**
   * Initialize {@link PatternedTextWatcher} with {@code pattern} and default parameters.
   * For advanced tweaking use {@link Builder}.
   *
   * @param pattern the pattern of the text watcher.
   */
  public PatternedTextWatcher(String pattern) {
    this(new Builder(pattern));
  }

  PatternedTextWatcher(Builder builder) {
    checkPatternInput(builder.pattern);
    checkInput(builder.specialChar, builder.saveInput, builder.fillExtraChars);
    checkPatternInInput(builder.pattern, builder.specialChar);

    String pattern = builder.pattern;
    this.fillExtra = builder.fillExtraChars;
    this.deleteExtra = builder.deleteExtraChars;
    this.saveInput = builder.saveInput;
    this.respectPatternLength = builder.respectPatternLength;
    this.debug = builder.debug;
    this.maxLength = pattern.length();
    this.specialCharacter = builder.specialChar.charAt(0);
    this.patternCharactersByIndex = new SparseArray<>();
    this.normalCharactersByIndex = new SparseArray<>();
    this.lastText = "";
    this.enabled = true;
    this.savedText = new StringBuilder();
    this.firstIndexToCheck = -1;
    this.lastIndexToCheck = -1;

    initializeIndexes(pattern);
  }

  private void initializeIndexes(String pattern) {
    for (int i = 0; i < pattern.length(); i++) {
      char c = pattern.charAt(i);

      // If current char is present in special characters that we must replace,
      // save it.
      if (specialCharacter == c) {
        normalCharactersByIndex.put(i, c);
      }
      // If current char is not present in special characters,
      // then we save current index and char that should be placed in the future into the string.
      else {
        if (firstIndexToCheck == -1)
          firstIndexToCheck = i;

        lastIndexToCheck = i;
        patternCharactersByIndex.put(i, c);
      }
    }
    if (firstIndexToCheck == -1) {
      // We don't have any chars to automatically insert.
      firstIndexToCheck = 0;
    }
    if (lastIndexToCheck <= 0) {
      // We don't have any chars to automatically insert.
      lastIndexToCheck = pattern.length();
    }
  }

  @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    LogUtils.logd("beforeTextChanged", s, debug);
  }

  @Override public void onTextChanged(CharSequence s, int start, int before, int count) {
    LogUtils.logd("onTextChanged", s, debug);
  }

  @Override public synchronized void afterTextChanged(Editable s) {
    LogUtils.logd("afterTextChanged", s, debug);

    if (isEnabled()) {
      final boolean isValidInLength = isValidInLength(s);
      StringBuilder sb = new StringBuilder(s);

      if (!isValidInLength) {
        if (sb.length() != 0) {
          // Delete all chars that exceed the limit.
          sb.delete(maxLength, sb.length());
        }
      }

      final boolean lastTextIsPresentIsSequence = sb.toString().startsWith(lastText);
      final boolean currentStringIsPresentIsSequence = lastText.startsWith(sb.toString());
      final int difference = sb.length() - lastText.length();
      final boolean batchInsert = difference > 1;
      final boolean batchDeletion = difference < -1;
      // Batch insert.
      if (batchInsert && lastTextIsPresentIsSequence) {
        if (saveInput) {
          // Text can be saved when it is saved from scratch.
          if (lastText.isEmpty()) {
            savedText.append(sb.toString());
          } else {
            // Attempt to append right string.
            savedText.append(StringUtils.difference(lastText, sb.toString()));
          }
        }
        insertCharactersIfNeeded(sb, lastText.length(), sb.length(), true);
      } else {
        if (batchDeletion) {
          if (saveInput) {
            // Delete all text if current string is empty.
            if (sb.length() == 0) {
              savedText.setLength(0);
            } else {
              // Attempt to append right string.
              savedText.delete(savedText.length() - StringUtils.difference(sb.toString(),
                  lastText).length() - 1, savedText.length());
            }
          }
          lastText = "";
          if (!validatePattern(sb)) {
            insertCharactersIfNeeded(sb, lastText.length(), sb.length(), true);
          }
        }

        // Determine if a character was added.
        if (s.length() > lastText.length()) {
          onCharacterAdded(sb, isValidInLength);
        } else if (s.length() < lastText.length()) {
          onCharacterDeleted(sb);
        }
      }

      // Check if the pattern is followed.
      if (!validatePattern(sb)) {
        insertCharactersIfNeeded(sb, firstIndexToCheck, lastIndexToCheck, false);
      }

      // Finalize the string by replacing the old object into a new one.
      checkIfReplaceIsNeeded(s, sb);
    }

    LogUtils.logd("Saved text", savedText.toString(), debug);
  }

  /**
   * Character was added.
   *
   * @param sb current string.
   */
  private void onCharacterAdded(StringBuilder sb, boolean isValidInLength) {
    // Check if the pattern has characters to replace in current index.
    Character possibleCharToInsert = patternCharactersByIndex.get(sb.length() - 1);

    // Append a pattern character if current index is not empty.
    if (possibleCharToInsert != null) {
      if (!possibleCharToInsert.equals(sb.charAt(sb.length() - 1))) {
        if (fillExtra) {
          // Insert pattern char.
          sb.insert(sb.length() - 1, possibleCharToInsert);

          // Insert pattern chars until they are over.
          while (patternCharactersByIndex.get(sb.length() - 1) != null) {
            sb.insert(sb.length() - 1, patternCharactersByIndex.get(sb.length() - 1));
          }
        } else {
          if (saveInput && isValidInLength) {
            savedText.append(sb.charAt(sb.length() - 1));
          }
          sb.setCharAt(sb.length() - 1, possibleCharToInsert);
        }
      }
    } else {
      if (saveInput && isValidInLength) {
        savedText.append(sb.charAt(sb.length() - 1));
      }
    }
    if (!areThereCharsLeftToReplace(sb))
      insertCharactersIfNeeded(sb, firstIndexToCheck, lastIndexToCheck, false);
  }

  /**
   * Character deleted.
   *
   * @param sb current string.
   */
  private void onCharacterDeleted(StringBuilder sb) {
    int currentLength = sb.length();
    if (saveInput) {
      int charactersDeletedCount = lastText.length() - sb.length();
      // Delete as many symbols as were deleted.
      for (int i = 0; i < charactersDeletedCount; i++) {
        savedText.deleteCharAt(savedText.length() - 1);
      }
    }
    if (deleteExtra) {
      // If the user deleted a pattern character.
      if (patternCharactersByIndex.get(lastText.length() - 1) != null) {
        deleteIfNextSymbolsArePatternCharacters(sb);

        // Then we delete the symbol, which was intended to be deleted initially.
        if (sb.length() != 0)
          sb.deleteCharAt(sb.length() - 1);

        deleteIfNextSymbolsArePatternCharacters(sb);
      }
      // If the user deleted a normal character.
      else {
        deleteIfNextSymbolsArePatternCharacters(sb);
      }
    }
    if (saveInput) {
      int charactersDeletedCount = currentLength - sb.length();
      // Delete as many symbols as were deleted.
      for (int i = 0; i < charactersDeletedCount; i++) {
        savedText.deleteCharAt(savedText.length() - 1);
      }
    }
  }

  /**
   * If next symbols are also pattern characters,
   * we need to delete them, too.
   *
   * @param sb current string.
   */
  private void deleteIfNextSymbolsArePatternCharacters(StringBuilder sb) {
    // If next symbols are also pattern characters,
    // we need to delete them, too.
    while (patternCharactersByIndex.get(sb.length() - 1) != null) {
      sb.deleteCharAt(sb.length() - 1);
    }
  }

  /**
   * Determine if there are chars left to replace with user input.
   *
   * @param sb current string.
   * @return {@code true} if there are chars left to replace. {@code false} otherwise.
   */
  private boolean areThereCharsLeftToReplace(StringBuilder sb) {
    if (normalCharactersByIndex.get(sb.length()) != null) {
      return true;
    }
    return false;
  }

  /**
   * Insert all missing character if needed.
   *
   * @param sb current string.
   */
  private void insertCharactersIfNeeded(StringBuilder sb, int firstIndexToCheck,
      int lastIndexToCheck, boolean batch) {
    if (sb.length() >= firstIndexToCheck && sb.length() - 1 <= lastIndexToCheck) {
      int i = firstIndexToCheck;

      while (i <= sb.length()) {
        // First check the length of current string.
        // If we exceed the max limit, we need to delete symbols.
        deleteOneLastCharIfLengthExceeds(sb);

        // Then we insert the next character if there is one.
        insertCharacterIfAvailable(sb, i, batch);

        i++;
      }
    }
  }

  /**
   * Insert the pattern character by the specified index if there is one.
   *
   * @param sb current string.
   * @param i  current index to look.
   */
  private void insertCharacterIfAvailable(StringBuilder sb, int i, boolean batch) {
    Character charToInsert = patternCharactersByIndex.get(i);
    if (charToInsert != null) {
      if (i < sb.length()) {
        if (batch) {
          Character normal = normalCharactersByIndex.get(i);
          if (normal == null) {
            insertDepending(sb, i, charToInsert);
          }
        } else {
          if (!charToInsert.equals(sb.charAt(i))) {
            insertDepending(sb, i, charToInsert);
          } else {
            Character normal = normalCharactersByIndex.get(i);
            if (normal == null) {
              sb.setCharAt(i, charToInsert);
            }
          }
        }
      } else {
        if (fillExtra) {
          sb.insert(i, charToInsert);
        }
      }
    }
  }

  /**
   * Insert the character depending on the {@link PatternedTextWatcher#fillExtra} parameter.
   *
   * @param sb           current string.
   * @param i            current index.
   * @param charToInsert char to insert.
   */
  private void insertDepending(StringBuilder sb, int i, Character charToInsert) {
    if (fillExtra) {
      sb.insert(i, charToInsert);
    } else {
      sb.setCharAt(i, charToInsert);
    }
  }

  /**
   * Check whether the Editable is empty or full.
   *
   * @param s the editable to check.
   * @return {@code false} if the {@code s} is empty or exceeds the maximum limit. {@code true}
   * otherwise.
   */
  private boolean isValidInLength(Editable s) {
    if (respectPatternLength && s.length() > maxLength)
      return false;
    return true;
  }

  /**
   * Check if current string was changed, so that editable should be also changed.
   *
   * @param s  the editable to change.
   * @param sb current string.
   */
  private void checkIfReplaceIsNeeded(Editable s, StringBuilder sb) {
    lastText = sb.toString();
    if (!s.toString().equals(lastText)) {
      s.replace(0, s.length(), sb);
    }
  }

  /**
   * Delete the last character if the length exceeds the maximum limit.
   *
   * @param sb current string.
   */
  private void deleteOneLastCharIfLengthExceeds(StringBuilder sb) {
    if (sb.length() > maxLength && respectPatternLength) {
      sb.delete(sb.length() - 1, sb.length());
    }
  }

  /**
   * Validate the pattern. Check so that all the patternCharactersByIndex were on their places.
   *
   * @param sb current string builder.
   * @return {@code true} if the pattern is followed correctly. {@code false} otherwise.
   */
  private boolean validatePattern(StringBuilder sb) {
    boolean patternValidated = true;
    for (int i = 0; i < patternCharactersByIndex.size(); i++) {
      Character character = patternCharactersByIndex.get(i);
      if (character != null && sb.length() > i && character != sb.charAt(i)) {
        LogUtils.logw("validatePattern",
            String.format("Assertion error! Expected \"%1$s\" in index \'%2$s\'." +
                "\nGot \"%3$s\".", character, i, sb.charAt(i)),
            debug);
        patternValidated = false;
      }
    }
    return patternValidated;
  }

  /**
   * Get the string as it is shown.
   *
   * @return string that is shown to the user.
   */
  public String getFormattedString() {
    return lastText;
  }

  /**
   *
Get the full string which was accumulated during the user's symbols addition.

   *
NOTE:

   * This works inly if you have set {@link Builder#saveAllInput(boolean)} to {@code true}
   * AND
   * {@link Builder#fillExtraCharactersAutomatically(boolean)} to {@code false}.
   *
   * @return the full string if the above criteria was met; {@link #getFormattedString()} otherwise.
   */
  public String getFullString() {
    if (saveInput)
      return savedText.toString();
    return getFormattedString();
  }

  /**
   * Get string only with characters which were replaced.
   *
   * @return clean string with inserted characters if you have set the
   * {@link Builder#respectPatternLength(boolean)}
   * to {@code true} (default).
   * {@link #getFormattedString()} otherwise.
   */
  public String getCleanString() {
    if (respectPatternLength) {
      StringBuilder cleanString = new StringBuilder();
      for (int i = 0; i < lastText.length(); i++) {
        if (normalCharactersByIndex.get(i) != null) {
          cleanString.append(lastText.charAt(i));
        }
      }
      return cleanString.toString();
    }
    return getFormattedString();
  }

  /**
   * Change the state of current TextWatcher.
   *
   * @param enabled {@code true} to enable text watching. {@code false} otherwise.
   */
  public void setEnabled(boolean enabled) {
    this.enabled = enabled;
  }

  /**
   * Determine if the TextWatcher is enabled and watches the text.
   *
   * @return {@code true} if enabled, {@code false} otherwise.
   */
  public boolean isEnabled() {
    return enabled;
  }

  /**
   * Determine if the TextWatcher is filling pattern characters automatically.
   *
   * @return {@code true} if fills automatically. {@code false} otherwise.
   */
  public boolean isFillingExtra() {
    return fillExtra;
  }

  /**
   * Determine if the TextWatcher is deleting extra characters automatically.
   *
   * @return {@code true} if deletes automatically. {@code false} otherwise.
   */
  public boolean isDeletingExtra() {
    return deleteExtra;
  }

  /**
   * Determine if the TextWatcher is saving input behind pattern characters.
   * This can be only done if automatic filling is turned off.
   *
   * @return {@code true} if saving input. {@code false} otherwise.
   */
  public boolean isSavingInput() {
    return saveInput;
  }

  /**
   * Determine if the TextWatcher is respecting pattern length.
   *
   * @return {@code true} if respecting. {@code false} otherwise.
   */
  public boolean isRespectingPatternLength() {
    return respectPatternLength;
  }

  /**
   * Determine if the debug logs are seen in logcat.
   *
   * @return {@code true} if debug logs can be seen in logcat. {@code false} otherwise.
   */
  public boolean isDebug() {
    return debug;
  }

  /**
   * Use {@link PatternedTextWatcher} builder to construct a TextWatcher
   * that will monitor your class that extends {@link android.widget.TextView}.
   */
  public static class Builder {
    String specialChar;
    String pattern;
    boolean fillExtraChars;
    boolean deleteExtraChars;
    boolean saveInput;
    boolean respectPatternLength;
    boolean debug;

    /**
     * Initialize a builder with {@code null} pattern definition.
     * The default {@code specialChar} is '#'.
     * You can set it via {@link Builder#specialChar(String)}.
     */
    public Builder() {
      this(null);
    }

    /**
     * Initialize builder with pattern definition.
     * The default {@code specialChar} is '#'.
     * You can set it via {@link Builder#specialChar(String)}.
     *
     * @param pattern the pattern to follow. Can't be null.
     */
    public Builder(String pattern) {
      this.pattern = pattern;
      this.specialChar = DEFAULT_CHAR;
      this.fillExtraChars = true;
      this.deleteExtraChars = true;
      this.saveInput = false;
      this.respectPatternLength = true;
      this.debug = false;
    }

    /**
     * Set the special char which is to be replaced instead of the user input.
     *
     * @param specialChar special char consisting of one or more
     * @return {@link Builder}
     */
    public Builder specialChar(String specialChar) {
      this.specialChar = specialChar;
      return this;
    }

    /**
     * Set the debug param in order to see the debug log in LogCat. Default is {@code false}.
     *
     * @param debug {@code true} to see debug log messages.
     * @return {@link Builder}
     */
    public Builder debug(boolean debug) {
      this.debug = debug;
      return this;
    }

    /**
     *
Set the pattern to follow.

     *
Example: {@code (###-###)}.

     *
     * @param pattern pattern to follow.
     * @return {@link Builder}
     */
    public Builder pattern(String pattern) {
      this.pattern = pattern;
      return this;
    }

    /**
     *
Fill extra characters automatically. Default is {@code true}.

     *
If you have a pattern with some characters that are not a part of the special
     * characters,
     * then this tweak will automatically insert these characters for the user.

     *
     * @param fillExtraChars whether you want the extra characters to be
     *                       inserted automatically.
     * @return {@link Builder}
     * @see Builder#deleteExtraCharactersAutomatically(boolean)
     * @see Builder#saveAllInput(boolean)
     */
    public Builder fillExtraCharactersAutomatically(boolean fillExtraChars) {
      this.fillExtraChars = fillExtraChars;
      return this;
    }

    /**
     * Delete extra characters automatically. Default is {@code true}.
     *
     * @param deleteExtraChars whether you want the extra characters to be
     *                         deleted automatically.
     * @return {@link Builder}
     * @see Builder#fillExtraCharactersAutomatically(boolean)
     * @see Builder#saveAllInput(boolean)
     */
    public Builder deleteExtraCharactersAutomatically(boolean deleteExtraChars) {
      this.deleteExtraChars = deleteExtraChars;
      return this;
    }

    /**
     * This tweak works ONLY if you have set the
     * {@link Builder#fillExtraCharactersAutomatically(boolean)} to {@code false},
     * otherwise it will throw {@link IllegalArgumentException} because values can't be saved
     * when the extra characters are inserted automatically.
     *
     * @param saveInput whether you want to save the input of characters hidden under other
     *                  characters.
     * @return {@link Builder}
     * @see Builder#fillExtraCharactersAutomatically(boolean)
     * @see Builder#deleteExtraCharactersAutomatically(boolean)
     */
    public Builder saveAllInput(boolean saveInput) {
      this.saveInput = saveInput;
      return this;
    }

    /**
     * Get the maximum string length from the pattern. Default is {@code true}.
     *
     * @param respectPatternLength whether you want to respect pattern length.
     * @return {@link Builder}
     */
    public Builder respectPatternLength(boolean respectPatternLength) {
      this.respectPatternLength = respectPatternLength;
      return this;
    }

    /**
     * Build the Patterned TextWatcher.
     *
     * @return a
     * {@link PatternedTextWatcher} which you can use for {@link android.widget.TextView}, {@link android.widget.EditText}, etc.
     */
    public PatternedTextWatcher build() {
      return new PatternedTextWatcher(this);
    }
  }
}


text:
package com.qc.you.socket.server.netty.handler;

import com.qc.you.socket.server.netty.ChannelRepository;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.net.SocketAddress;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

/**
 * Test for  SomethingServerHandler.java
 *
 * @author Jibeom Jung
 */
public class SomethingServerHandlerTest {

    private SomethingServerHandler somethingServerHandler;

    private ChannelHandlerContext channelHandlerContext;

    private Channel channel;

    private SocketAddress remoteAddress;

    @Before
    public void setUp() throws Exception {
        somethingServerHandler = new SomethingServerHandler();
        somethingServerHandler.setChannelRepository(new ChannelRepository());

        channelHandlerContext = mock(ChannelHandlerContext.class);
        channel = mock(Channel.class);
        remoteAddress = mock(SocketAddress.class);
    }

    @After
    public void tearDown() throws Exception {

    }

    @Test
    public void testChannelActive() throws Exception {
        when(channelHandlerContext.channel()).thenReturn(channel);
        when(channelHandlerContext.channel().remoteAddress()).thenReturn(remoteAddress);
        somethingServerHandler.channelActive(channelHandlerContext);
    }

    @Test
    public void testChannelRead() throws Exception {
        when(channelHandlerContext.channel()).thenReturn(channel);
        somethingServerHandler.channelRead(channelHandlerContext, "test message");
    }

    @Test
    public void testExceptionCaught() throws Exception {

    }
}

redpajama_set_name: RedPajamaGithub


text:
#ifndef PCL_FEATURES_IMPL_BOUNDARY_H_
#define PCL_FEATURES_IMPL_BOUNDARY_H_

#include <pcl/features/boundary.h>
#include <cfloat>

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointNT, typename PointOutT> bool
pcl::BoundaryEstimation<PointInT, PointNT, PointOutT>::isBoundaryPoint (
      const pcl::PointCloud<PointInT> &cloud, int q_idx,
      const std::vector<int> &indices,
      const Eigen::Vector4f &u, const Eigen::Vector4f &v,
      const float angle_threshold)
{
  return (isBoundaryPoint (cloud, cloud.points[q_idx], indices, u, v, angle_threshold));
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointNT, typename PointOutT> bool
pcl::BoundaryEstimation<PointInT, PointNT, PointOutT>::isBoundaryPoint (
      const pcl::PointCloud<PointInT> &cloud, const PointInT &q_point,
      const std::vector<int> &indices,
      const Eigen::Vector4f &u, const Eigen::Vector4f &v,
      const float angle_threshold)
{
  if (indices.size () < 3)
    return (false);

  if (!pcl_isfinite (q_point.x) || !pcl_isfinite (q_point.y) || !pcl_isfinite (q_point.z))
    return (false);

  // Compute the angles between each neighboring point and the query point itself
  std::vector<float> angles (indices.size ());
  float max_dif = FLT_MIN, dif;
  int cp = 0;

  for (size_t i = 0; i < indices.size (); ++i)
  {
    if (!pcl_isfinite (cloud.points[indices[i]].x) ||
        !pcl_isfinite (cloud.points[indices[i]].y) ||
        !pcl_isfinite (cloud.points[indices[i]].z))
      continue;

    Eigen::Vector4f delta = cloud.points[indices[i]].getVector4fMap () - q_point.getVector4fMap ();

    angles[cp++] = atan2f (v.dot (delta), u.dot (delta)); // the angles are fine between -PI and PI too
  }
  if (cp == 0)
    return (false);

  angles.resize (cp);
  std::sort (angles.begin (), angles.end ());

  // Compute the maximal angle difference between two consecutive angles
  for (size_t i = 0; i < angles.size () - 1; ++i)
  {
    dif = angles[i + 1] - angles[i];
    if (max_dif < dif)
      max_dif = dif;
  }
  // Get the angle difference between the last and the first
  dif = 2 * static_cast<float> (M_PI) - angles[angles.size () - 1] + angles[0];
  if (max_dif < dif)
    max_dif = dif;

  // Check results
  if (max_dif > angle_threshold)
    return (true);
  else
    return (false);
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointNT, typename PointOutT> void
pcl::BoundaryEstimation<PointInT, PointNT, PointOutT>::computeFeature (PointCloudOut &output)
{
  // Allocate enough space to hold the results
  // \note This resize is irrelevant for a radiusSearch ().
  std::vector<int> nn_indices (k_);
  std::vector<float> nn_dists (k_);

  Eigen::Vector4f u = Eigen::Vector4f::Zero (), v = Eigen::Vector4f::Zero ();

  output.is_dense = true;
  // Save a few cycles by not checking every point for NaN/Inf values if the cloud is set to dense
  if (input_->is_dense)
  {
    // Iterating over the entire index vector
    for (size_t idx = 0; idx < indices_->size (); ++idx)
    {
      if (this->searchForNeighbors ((*indices_)[idx], search_parameter_, nn_indices, nn_dists) == 0)
      {
        output.points[idx].boundary_point = std::numeric_limits<uint8_t>::quiet_NaN ();
        output.is_dense = false;
        continue;
      }

      // Obtain a coordinate system on the least-squares plane
      //v = normals_->points[(*indices_)[idx]].getNormalVector4fMap ().unitOrthogonal ();
      //u = normals_->points[(*indices_)[idx]].getNormalVector4fMap ().cross3 (v);
      getCoordinateSystemOnPlane (normals_->points[(*indices_)[idx]], u, v);

      // Estimate whether the point is lying on a boundary surface or not
      output.points[idx].boundary_point = isBoundaryPoint (*surface_, input_->points[(*indices_)[idx]], nn_indices, u, v, angle_threshold_);
    }
  }
  else
  {
    // Iterating over the entire index vector
    for (size_t idx = 0; idx < indices_->size (); ++idx)
    {
      if (!isFinite ((*input_)[(*indices_)[idx]]) ||
          this->searchForNeighbors ((*indices_)[idx], search_parameter_, nn_indices, nn_dists) == 0)
      {
        output.points[idx].boundary_point = std::numeric_limits<uint8_t>::quiet_NaN ();
        output.is_dense = false;
        continue;
      }

      // Obtain a coordinate system on the least-squares plane
      //v = normals_->points[(*indices_)[idx]].getNormalVector4fMap ().unitOrthogonal ();
      //u = normals_->points[(*indices_)[idx]].getNormalVector4fMap ().cross3 (v);
      getCoordinateSystemOnPlane (normals_->points[(*indices_)[idx]], u, v);

      // Estimate whether the point is lying on a boundary surface or not
      output.points[idx].boundary_point = isBoundaryPoint (*surface_, input_->points[(*indices_)[idx]], nn_indices, u, v, angle_threshold_);
    }
  }
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointNT> void
pcl::BoundaryEstimation<PointInT, PointNT, Eigen::MatrixXf>::computeFeatureEigen (pcl::PointCloud<Eigen::MatrixXf> &output)
{
  // Allocate enough space to hold the results
  // \note This resize is irrelevant for a radiusSearch ().
  std::vector<int> nn_indices (k_);
  std::vector<float> nn_dists (k_);

  Eigen::Vector4f u = Eigen::Vector4f::Zero (), v = Eigen::Vector4f::Zero ();

  output.is_dense = true;
  output.points.resize (indices_->size (), 1);
  // Save a few cycles by not checking every point for NaN/Inf values if the cloud is set to dense
  if (input_->is_dense)
  {
    // Iterating over the entire index vector
    for (size_t idx = 0; idx < indices_->size (); ++idx)
    {
      if (this->searchForNeighbors ((*indices_)[idx], search_parameter_, nn_indices, nn_dists) == 0)
      {
        output.points (idx, 0) = std::numeric_limits<float>::quiet_NaN ();
        output.is_dense = false;
        continue;
      }

      // Obtain a coordinate system on the least-squares plane
      //v = normals_->points[(*indices_)[idx]].getNormalVector4fMap ().unitOrthogonal ();
      //u = normals_->points[(*indices_)[idx]].getNormalVector4fMap ().cross3 (v);
      this->getCoordinateSystemOnPlane (normals_->points[(*indices_)[idx]], u, v);

      // Estimate whether the point is lying on a boundary surface or not
      output.points (idx, 0) = this->isBoundaryPoint (*surface_, input_->points[(*indices_)[idx]], nn_indices, u, v, angle_threshold_);
    }
  }
  else
  {
    // Iterating over the entire index vector
    for (size_t idx = 0; idx < indices_->size (); ++idx)
    {
      if (!isFinite ((*input_)[(*indices_)[idx]]) ||
          this->searchForNeighbors ((*indices_)[idx], search_parameter_, nn_indices, nn_dists) == 0)
      {
        output.points (idx, 0) = std::numeric_limits<float>::quiet_NaN ();
        output.is_dense = false;
        continue;
      }

      // Obtain a coordinate system on the least-squares plane
      //v = normals_->points[(*indices_)[idx]].getNormalVector4fMap ().unitOrthogonal ();
      //u = normals_->points[(*indices_)[idx]].getNormalVector4fMap ().cross3 (v);
      this->getCoordinateSystemOnPlane (normals_->points[(*indices_)[idx]], u, v);

      // Estimate whether the point is lying on a boundary surface or not
      output.points (idx, 0) = this->isBoundaryPoint (*surface_, input_->points[(*indices_)[idx]], nn_indices, u, v, angle_threshold_);
    }
  }
}

#define PCL_INSTANTIATE_BoundaryEstimation(PointInT,PointNT,PointOutT) template class PCL_EXPORTS pcl::BoundaryEstimation<PointInT, PointNT, PointOutT>;

#endif    // PCL_FEATURES_IMPL_BOUNDARY_H_


text:
package eu.impact_project.iif.ws.generic;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.eviware.soapui.impl.wsdl.WsdlOperation;
import com.eviware.soapui.impl.wsdl.WsdlRequest;
import com.eviware.soapui.impl.wsdl.WsdlSubmit;
import com.eviware.soapui.impl.wsdl.WsdlSubmitContext;
import com.eviware.soapui.model.iface.Attachment;
import com.eviware.soapui.model.iface.Response;
import com.eviware.soapui.model.iface.Request.SubmitException;

import eu.impact_project.iif.ws.generic.util.MyUtils;

/**
 * An executable operation with inputs and outputs
 *
 */
public class SoapOperation {

	private Logger logger = LoggerFactory.getLogger(SoapOperation.class);
	private static final int SOAP_REQUEST = 0;
	private static final int SOAP_RESPONSE = 1;

	private String name;
	private Map<String, SoapInput> inputs = new HashMap<String, SoapInput>();
	private Map<String, SoapOutput> outputs = new HashMap<String, SoapOutput>();

	private WsdlDocument wsdlDoc;
	private WsdlOperation operation;
	private String soapResponse;

	private Response wsdlResponse;

	/**
	 * Creates a new operation by reading the wsdl document
	 *
	 * @param name
	 *            of the operation
	 * @param wsdlDoc
	 *            contains info about the operation
	 * @throws IOException
	 */
	public SoapOperation(String name, WsdlDocument wsdlDoc) throws IOException {
		this.name = name;
		this.wsdlDoc = wsdlDoc;

		operation = wsdlDoc.getWsdlInterface().getOperationByName(name);

		Document defaultSoapDoc = MyUtils.toDocument(getDefaultRequest());
		parseSoap(defaultSoapDoc.getRootElement(), SOAP_REQUEST);
	}

	// creates either inputs or outputs while parsing the soap
	private void parseSoap(Element current, int soapType) throws IOException {
		if (current.getChildren().size() == 0 && !current.getText().equals("")) {
			if (soapType == SOAP_REQUEST) {
				SoapInput input = new SoapInput(current.getName(), wsdlDoc,
						this.name);
				inputs.put(current.getName(), input);
			} else if (soapType == SOAP_RESPONSE) {
				SoapOutput output = new SoapOutput(current.getName(),
						soapResponse);
				outputs.put(current.getName(), output);
			}
		} else {
			for (Object obj : current.getChildren()) {
				Element child = (Element) obj;
				parseSoap(child, soapType);
			}
		}
	}

	public String getName() {
		return name;
	}

	public List<SoapInput> getInputs() {
		return new ArrayList<SoapInput>(inputs.values());
	}

	public List<SoapOutput> getOutputs() {
		return new ArrayList<SoapOutput>(outputs.values());
	}

	public SoapInput getInput(String name) {
		return inputs.get(name);
	}

	/**
	 * Request message containing default values from the WSDL or question marks
	 * otherwise
	 *
	 * @return Default values
	 * @throws IOException
	 */
	public String getDefaultRequest() throws IOException {
		return wsdlDoc.generateRequest(name);
	}

	public String getDocumentation() throws IOException {
		String docu = wsdlDoc.getOperationDocumentation(name);
		return MyUtils.normalize(docu);
	}

	/**
	 * Sends the currently set inputs to the service
	 *
	 * @return Received outputs
	 * @throws IOException
	 */
	public List<SoapOutput> execute(String user, String pass) throws IOException {
		try {
			String request = getRequest();
			Properties props = new Properties();

			InputStream inConfig = this.getClass().getClassLoader().getResourceAsStream("config.properties");
			props.load(inConfig);

			String timeout = props.getProperty("timeout");

			inConfig.close();

			// prepare the request
			WsdlRequest wsdlRequest = operation.addNewRequest("req");
			wsdlRequest.setRequestContent(request);

			if ((user!=null && pass!=null) && (!user.equals("") && !pass.equals("")))
			{
				// Add WSSecurity parameters
				wsdlRequest.setWssPasswordType("PasswordText");
				wsdlRequest.setUsername(user);
				wsdlRequest.setPassword(pass);
				wsdlRequest.setWssTimeToLive("10000");
			}

			wsdlRequest.setTimeout(timeout);

			// send the request
			WsdlSubmit submit = (WsdlSubmit) wsdlRequest.submit(
					new WsdlSubmitContext(wsdlRequest), false);

			// get the response
			wsdlResponse = submit.getResponse();
			soapResponse = wsdlResponse.getContentAsString();

			InputStream soapStream = new ByteArrayInputStream(
					soapResponse.getBytes());
			SAXBuilder parser = new SAXBuilder();
			Document result = parser.build(soapStream);

			// create Output objects
			parseSoap(result.getRootElement(), SOAP_RESPONSE);

		} catch (SubmitException e) {
			throw new IOException("Problem while submitting the message.", e);
		} catch (JDOMException e) {
			throw new IOException(
					"Problem while parsing the SOAP request message.", e);
		}

		return new ArrayList<SoapOutput>(outputs.values());

	}

	/**
	 * Generates a SOAP message using the currently set input values
	 *
	 * @return Request message
	 * @throws IOException
	 */
	public String getRequest() throws IOException {
		Document request = MyUtils.toDocument(getDefaultRequest());

		Map<Element, List<Element>> additionalInputs = new HashMap<Element, List<Element>>();
		insertValues(request.getRootElement(), additionalInputs);

		for (Element parent : additionalInputs.keySet()) {
			List<Element> childNodes = additionalInputs.get(parent);
			parent.addContent(childNodes);
		}

		// store the XML document in a String
		XMLOutputter serializer = new XMLOutputter();
		ByteArrayOutputStream bout = new ByteArrayOutputStream();

		serializer.output(request, bout);
		String requestString = bout.toString();

		return requestString;
	}

	public String getResponse() {
		return soapResponse;
	}

	public List<SoapAttachment> getReceivedAttachments() {
		List<SoapAttachment> list = new ArrayList<SoapAttachment>();

		Attachment[] atts = wsdlResponse.getAttachments();
		for (Attachment att : atts) {
			try {
				SoapAttachment temp = new SoapAttachment(att.getInputStream(),
						att.getContentType());
				list.add(temp);
			} catch (Exception e) {
				logger.warn("Could not get the attachment '" + att.getName()
						+ "'");
			}
		}

		return list;
	}

	private void insertValues(Element current,
			Map<Element, List<Element>> additionalInputs) {

		if (inputs.get(current.getName()) != null) {
			SoapInput input = inputs.get(current.getName());
			String value = input.getValue();
			current.setText(value);

			// if there are several values
			List<Element> clones = new ArrayList<Element>();
			List<String> values = input.getValues();
			for (int i = 1; i < values.size(); i++) {
				Element clone = (Element) current.clone();
				clone.setText(values.get(i));
				clones.add(clone);
			}
			if (clones.size() > 0) {
				additionalInputs.put(current.getParentElement(), clones);
			}

			// recursive checking of all children
		} else {
			for (Object obj : current.getChildren()) {
				Element child = (Element) obj;
				insertValues(child, additionalInputs);
			}
		}

	}

}


text:
current_user=`whoami`
systembit=`getconf LONG_BIT`
current_dir=`pwd`
sudo_str=""

#help text, the script desc
#@param void
#@return void
function help_text() {
  cat <<EOF
${0} ver 1.0

options:
--protobuf      install protobuf in your system
--help          view the text, or just use -h
--full          intall unix odbc and mysql odbc driver
EOF
}

#print error message, red words
#@param string message
#@return void
function error_message() {
  local message=${1}
  echo -e "\e[0;31;1merror: ${message}\e[0m"
  exit 1
}

#print warning message, yellow words
#@param message
#@return string void
function warning_message() {
  local message=${1}
  echo -e "\e[0;33;1mwarning: ${message}\e[0m"
}

#print success message, yellow words
#@param message
#@return string void
function success_message() {
  local message=${1}
  echo -e "\e[0;32;1msuccess: ${message}\e[0m"
}

function check_privileges() {
  if [[ $current_user != "root" ]] ; then
    error_message "run this script need root privileges"
  fi
}

#install protobuf
#@param void
#@return void
function install_protobuf() {
  cd $current_dir
  chmod +x ./bin/*
  cp ./bin/* /usr/local/bin/ -r
  cp ./lib/* /usr/local/lib/ -r
  cp ./include/* /usr/local/include/ -r
  [[ 0 == $? ]] && success_message "install protobuf complete"
}

#the script main function, like c/c++
function main() {
  cmd=${1}
  cmd1=${2}
  if [[ "--sudo" == $cmd1 ]] ; then
    sudo_str="sudo"
  else
    check_privileges
  fi
  case "${cmd}" in
    --help ) help_text;;
    -h) help_text;;
    --protobuf) install_protobuf;;
    --full) install_protobuf;;
  esac
}
if [[ "" == ${@} ]] ; then
  error_message "${0}: no commond specified.You can use <${0} --help> "
                "get parameters for this script."
else
  main "${@}"
  exit 0
fi


text:
/**
 *
 */
package edu.ucdenver.ccp.nlp.pipelines.evaluation.craft.conceptmapper;

/*
 * #%L
 * Colorado Computational Pharmacology's NLP pipelines
 * 							module
 * %%
 * Copyright (C) 2014 - 2017 Regents of the University of Colorado
 * %%
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * 3. Neither the name of the Regents of the University of Colorado nor the names of its contributors
 *    may be used to endorse or promote products derived from this software without
 *    specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 * #L%
 */

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import edu.ucdenver.ccp.common.file.FileArchiveUtil;
import edu.ucdenver.ccp.common.io.ClassPathUtil;
import edu.ucdenver.ccp.common.string.StringConstants;
import edu.ucdenver.ccp.datasource.fileparsers.obo.OntologyUtil.SynonymType;
import edu.ucdenver.ccp.nlp.pipelines.conceptmapper.ConceptMapperDictionaryFileFactory;
import edu.ucdenver.ccp.nlp.pipelines.conceptmapper.ConceptMapperDictionaryFileFactory.DictionaryNamespace;
import edu.ucdenver.ccp.nlp.uima.collections.craft.CraftOntology;
import edu.ucdenver.ccp.nlp.wrapper.conceptmapper.dictionary.obo.DictionaryEntryModifier;
import edu.ucdenver.ccp.nlp.wrapper.conceptmapper.dictionary.obo.OboToDictionary.IncludeExt;

/**
 * This class builds Concept Mapper dictionaries using the ontologies that were
 * used to annotate the CRAFT corpus. These ontologies are available on the
 * classpath in the jar file that contains the XMI files storing the CRAFT
 * annotations.
 *
 * @author Colorado Computational Pharmacology, UC Denver;
 *         ccpsupport@ucdenver.edu
 *
 */
public class CraftOntologiesDictionaryFactory {

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

	public static final Map<DictionaryNamespace, String> namespacePathMap = new HashMap<DictionaryNamespace, String>() {
		{
			put(DictionaryNamespace.GO, CraftOntology.GO.oboFilePath());
			put(DictionaryNamespace.GO_CC, CraftOntology.GO.oboFilePath());
			put(DictionaryNamespace.GO_BP, CraftOntology.GO.oboFilePath());
			put(DictionaryNamespace.GO_MF, CraftOntology.GO.oboFilePath());
			put(DictionaryNamespace.FUNK_GO_CC, CraftOntology.GO.oboFilePath());
			put(DictionaryNamespace.FUNK_GO_BP, CraftOntology.GO.oboFilePath());
			put(DictionaryNamespace.FUNK_GO_MF, CraftOntology.GO.oboFilePath());
			put(DictionaryNamespace.CHEBI, CraftOntology.CHEBI.oboFilePath());
			put(DictionaryNamespace.CL, CraftOntology.CL.oboFilePath());
			put(DictionaryNamespace.NCBI_TAXON, CraftOntology.NCBI_TAXON.oboFilePath());
			put(DictionaryNamespace.PR, CraftOntology.PR.oboFilePath());
			put(DictionaryNamespace.SO, CraftOntology.SO.oboFilePath());
			put(DictionaryNamespace.UBERON, CraftOntology.UBERON.oboFilePath());
			put(DictionaryNamespace.MOP, CraftOntology.MOP.oboFilePath());
		}
	};

	/**
	 * Creates Concept Mapper dictionary files using archived ontologies (OBO
	 * files) that were used to annotate the CRAFT corpus. The ontology files
	 * are retrieved from the classpath.
	 *
	 * @param dictionaryNamespace
	 * @param outputDirectory
	 * @param cleanDictionaryFile
	 *            if true then any pre-existing dictionary files are deleted, if
	 *            false then pre-existing dictionaries are used
	 * @param dictId
	 * @param dictEntryModifier
	 * @param includeExt
	 * @return a reference to a newly created Concept Mapper dictionary file
	 * @throws IllegalArgumentException
	 *             if {@link DictionaryNamespace#EG} is used as input - this
	 *             dictionary is not supported
	 */
	public static File createDictionaryFile(DictionaryNamespace dictionaryNamespace, File outputDirectory,
			boolean cleanDictionaryFile, SynonymType synonymType, String dictId,
			DictionaryEntryModifier dictEntryModifier, IncludeExt includeExt) {
		long startTime = System.currentTimeMillis();
		try {
			if (dictionaryNamespace == DictionaryNamespace.EG) {
				throw new UnsupportedOperationException(
						"EntrezGene dictionary creation is not supported from the original EG data "
								+ "used to annotated CRAFT. That data was not archived since the "
								+ "NCBI Gene website was used extensively during annotation.");
			}

			String path = namespacePathMap.get(dictionaryNamespace);
			if (path == null) {
				throw new IllegalArgumentException(
						"Unknown concept mapper dictionary namespace: " + dictionaryNamespace.name());
			}
			File oboFile = copyOboFileFromClasspath(path, outputDirectory, cleanDictionaryFile);
			File dictionaryFile = ConceptMapperDictionaryFileFactory.createDictionaryFileFromOBO(dictionaryNamespace,
					oboFile, outputDirectory, cleanDictionaryFile, synonymType, dictId, dictEntryModifier, includeExt);
			logger.info("Dictionary creation complete. Elapsed time: "
					+ ((System.currentTimeMillis() - startTime) / 1000) + "s");
			return dictionaryFile;
		} catch (IOException e) {
			throw new RuntimeException("Error while constructing ConceptMapper dictionary.", e);
		}
	}

	/**
	 * Gets the gzipped OBO file from the classpath, copies it to the specified
	 * directory and unzips it. This occurs if cleanDictFile = true, or if the
	 * obo file does not exist locally.
	 *
	 * @param oboPath
	 *
	 * @param goOboPath
	 * @param outputDirectory
	 * @param cleanDictFile
	 *            if set to true then we re-download the obo file and re-build
	 *            the dictionary. If false, then the obo file is only downloaded
	 *            if it is not present.
	 * @return a reference to the unzipped OBO file
	 * @throws IOException
	 */
	private static File copyOboFileFromClasspath(String oboPath, File outputDirectory, boolean cleanDictFile)
			throws IOException {
		String resourceName = oboPath.substring(oboPath.lastIndexOf(StringConstants.FORWARD_SLASH) + 1);
		File resourceFile = FileArchiveUtil.getUnzippedFileReference(new File(outputDirectory, resourceName), null);
		if (!resourceFile.exists()) {
			logger.info("Clean dictionary flag set to true OR the OBO file does not exist locally. "
					+ "Downloading the OBO file from the classpath to: " + resourceFile.getAbsolutePath());
			File zippedOboFile = ClassPathUtil.copyClasspathResourceToDirectory(oboPath, outputDirectory);
			resourceFile = FileArchiveUtil.unzip(zippedOboFile, outputDirectory, null);
		}
		return resourceFile;
	}

	public static File getOboFile(DictionaryNamespace ns, File directory) {
		String path = namespacePathMap.get(ns);
		if (path == null) {
			throw new IllegalArgumentException("Unknown concept mapper dictionary namespace: " + ns.name());
		}
		String resourceName = path.substring(path.lastIndexOf(StringConstants.FORWARD_SLASH) + 1);
		return FileArchiveUtil.getUnzippedFileReference(new File(directory, resourceName), null);
	}

}


text:
"""
    sphinx.cmdline
    ~~~~~~~~~~~~~~

    sphinx-build command-line handling.

    :copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS.
    :license: BSD, see LICENSE for details.
"""

import sys
import warnings

from sphinx.cmd import build
from sphinx.deprecation import RemovedInSphinx30Warning

if False:
    # For type annotation
    import argparse  # NOQA
    from typing import Any, IO, List, Union  # NOQA
    from sphinx.application import Sphinx  # NOQA

def handle_exception(app, args, exception, stderr=sys.stderr):
    # type: (Sphinx, Any, Union[Exception, KeyboardInterrupt], IO) -> None
    warnings.warn('sphinx.cmdline module is deprecated. Use sphinx.cmd.build instead.',
                  RemovedInSphinx30Warning, stacklevel=2)
    build.handle_exception(app, args, exception, stderr)

def jobs_argument(value):
    # type: (str) -> int
    warnings.warn('sphinx.cmdline module is deprecated. Use sphinx.cmd.build instead.',
                  RemovedInSphinx30Warning, stacklevel=2)
    return build.jobs_argument(value)

def get_parser():
    # type: () -> argparse.ArgumentParser
    warnings.warn('sphinx.cmdline module is deprecated. Use sphinx.cmd.build instead.',
                  RemovedInSphinx30Warning, stacklevel=2)
    return build.get_parser()

def main(argv=sys.argv[1:]):
    # type: (List[str]) -> int
    warnings.warn('sphinx.cmdline module is deprecated. Use sphinx.cmd.build instead.',
                  RemovedInSphinx30Warning, stacklevel=2)
    return build.main(argv)


text:
class IOMemoryMapped
{
public:
    virtual uint8_t read(uint16_t addr) = 0;
    virtual void write(uint16_t addr, uint8_t value) = 0;
};

#endif


text:
content-area: about-detail
---
Floor Pro has over 30 years of experience in the industry.


text:
DOCUMENTATION = '''
---
module: win_oneget_source
version_added: "1.9"
short_description: Add a package source to the OneGet package manager
description:

options:
  name:
    description:
      - The desired package source name
    required: true
    default: null
    aliases: []
  provider:
    description:
      - The provider name for the new package source
    required: true
    default: null
    aliases: []
  location:
    description:
      - The location of the new package source
    required: true
    default: null
    aliases: []
author: Tal Auslander
'''

EXAMPLES = '''
# Playbook example
  - name: Add cloudshare-staging package source
    win_oneget_source:
      name: "aspnetrelease"
      provider: "NuGet"
      location: "https://www.myget.org/F/aspnetrelease"
'''


text:
Did your app just log an object to the dev tools console and you'd like to
interact with that object? It's not straightforward, but you can do it.

Assuming you already have dev tools opened to the _console_ tab, right click
on the value that has been logged to the console. Select the _Store as
Global Variable_ option. This will re-log the value assigning it to the
`temp1` variable.

You can now reference that object as `temp1` accessing its values and
calling functions.

You can even do this with multiple logged values, each subsequent one will
be assigned incrementing variable names: `temp2`, `temp3`, etc.

[source](https://stackoverflow.com/questions/15895579/access-last-logged-value-in-chrome-console)


text:
General information about the WiPy
==================================

No floating point support
-------------------------

Due to space reasons, there's no floating point support, and no math module. This
means that floating point numbers cannot be used anywhere in the code, and that
all divisions must be performed using '//' instead of '/'. Example::

    >>> r = 4 // 2  # this will work
    >>> r = 4 / 2   # this WON'T

Before applying power
---------------------

.. warning::

   The GPIO pins of the WiPy are NOT 5V tolerant, connecting them to voltages higer
   than 3.6V will cause irreparable damage to the board. ADC pins, when configured
   in analog mode cannot withstand voltages above 1.8V. Keep these considerations in
   mind when wiring your electronics.

WLAN default behaviour
----------------------

When the WiPy boots with the default factory configuration starts in Access Point
mode with ``ssid`` that starts with: ``wipy-wlan`` and ``key: www.wipy.io``.
Connect to this network and the WiPy will be reachable at ``192.168.1.1``. In order
to gain access to the interactive prompt, open a telnet session to that IP address on
the default port (23). You will be asked for credentials:
``login: micro`` and ``password: python``

.. _wipy_telnet:

Telnet REPL
-----------

Linux stock telnet works like a charm (also on OSX), but other tools like putty
work quite well too. The default credentials are: **user:** ``micro``, **password:** ``python``.
See :ref:`network.server <network.server>` for info on how to change the defaults.
For instance, on a linux shell (when connected to the WiPy in AP mode)::

   $ telnet 192.168.1.1

.. _wipy_filesystem:

Local file system and FTP access
--------------------------------

There is a small internal file system (a drive) on the WiPy, called ``/flash``,
which is stored within the external serial flash memory.  If a micro SD card
is hooked-up and mounted, it will be available as well.

When the WiPy starts up, it always boots from the ``boot.py`` located in the
``/flash`` file system.

The file system is accessible via the native FTP server running in the WiPy.
Open your FTP client of choice and connect to:

**url:** ``ftp://192.168.1.1``, **user:** ``micro``, **password:** ``python``

See :ref:`network.server <network.server>` for info on how to change the defaults.
The recommended clients are: Linux stock FTP (also in OSX), Filezilla and FireFTP.
For example, on a linux shell::

   $ ftp 192.168.1.1

The FTP server on the WiPy doesn't support active mode, only passive, therefore,
if using the native unix ftp client, just after logging in do::

    ftp> passive

Besides that, the FTP server only supports one data connection at a time. Check out
the Filezilla settings section below for more info.

FileZilla settings
------------------
Do not use the quick connect button, instead, open the site manager and create a new
configuration. In the ``General`` tab make sure that encryption is set to: ``Only use
plain FTP (insecure)``. In the Transfer Settings tab limit the max number of connections
to one, otherwise FileZilla will try to open a second command connection when retrieving
and saving files, and for simplicity and to reduce code size, only one command and one
data connections are possible. Other FTP clients might behave in a similar way.

.. _wipy_firmware_upgrade:

Upgrading the firmware Over The Air
-----------------------------------

OTA software updates can be performed through the FTP server. Upload the ``mcuimg.bin`` file
to: ``/flash/sys/mcuimg.bin`` it will take around 6s. You won't see the file being stored
inside ``/flash/sys/`` because it's actually saved bypassing the user file system, so it
ends up inside the internal **hidden** file system, but rest assured that it was successfully
transferred, and it has been signed with a MD5 checksum to verify its integrity. Now, reset
the WiPy by pressing the switch on the board, or by typing::

    >>> import machine
    >>> machine.reset()

Software updates can be found in: https://github.com/wipy/wipy/releases (**Binaries.zip**).
It's always recommended to update to the latest software, but make sure to
read the **release notes** before.

.. note::

   The ``bootloader.bin`` found inside ``Binaries.zip`` is there only for reference, it's not
   needed for the Over The Air update.

In order to check your software version, do::

   >>> import os
   >>> os.uname().release

If the version number is lower than the latest release found in
`the releases <https://github.com/wipy/wipy/releases>`_, go ahead and update your WiPy!

.. _wipy_boot_modes:

Boot modes and safe boot
------------------------

If you power up normally, or press the reset button, the WiPy will boot
into standard mode; the ``boot.py`` file will be executed first, then
``main.py`` will run.

You can override this boot sequence by pulling ``GP28`` **up** (connect
it to the 3v3 output pin) during reset. This procedure also allows going
back in time to old firmware versions. The WiPy can hold up to 3 different
firmware versions, which are: the factory firmware plus 2 user updates.

After reset, if ``GP28`` is held high, the heartbeat LED will start flashing
slowly, if after 3 seconds the pin is still being held high, the LED will start
blinking a bit faster and the WiPy will select the previous user update to boot.
If the previous user update is the desired firmware image, ``GP28`` must be
released before 3 more seconds elapse. If 3 seconds later the pin is still high,
the factory firmware will be selected, the LED will flash quickly for 1.5 seconds
and the WiPy will proceed to boot. The firmware selection mechanism is as follows:

**Safe Boot Pin** ``GP28`` **released during:**

+-------------------------+-------------------------+----------------------------+
| 1st 3 secs window       | 2nd 3 secs window       | Final 1.5 secs window      |
+=========================+=========================+============================+
| | Safe boot, *latest*   | | Safe boot, *previous* | | Safe boot, the *factory* |
| | firmware is selected  | | user update selected  | | firmware is selected     |
+-------------------------+-------------------------+----------------------------+

On all of the above 3 scenarios, safe boot mode is entered, meaning that
the execution of both ``boot.py`` and ``main.py`` is skipped. This is
useful to recover from crash situations caused by the user scripts. The selection
made during safe boot is not persistent, therefore after the next normal reset
the latest firmware will run again.

The heartbeat LED
------------------

By default the heartbeat LED flashes once every 4s to signal that the system is
alive. This can be overridden through the :mod:`wipy` module::

   >>> import wipy
   >>> wipy.heartbeat(False)

There are currently 2 kinds of errors that you might see:

1. If the heartbeat LED flashes quickly, then a Python script (eg ``main.py``)
   has an error.  Use the REPL to debug it.
2. If the heartbeat LED stays on, then there was a hard fault, you cannot
   recover from this, the only way out is to press the reset switch.


text:
package io.github.ibuildthecloud.dstack.spring.resource;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import io.github.ibuildthecloud.dstack.util.resource.ResourceLoader;

public class SpringResourceLoader implements ResourceLoader, ApplicationContextAware {

    private static final Logger log = LoggerFactory.getLogger(SpringResourceLoader.class);
    public static final String PREFIX = "classpath*:";

    PathMatchingResourcePatternResolver resolver;

    @Override
    public List<URL> getResources(String path) throws IOException {
        List<URL> result = new ArrayList<URL>();

        for ( Resource r : resolver.getResources(PREFIX + path) ) {
            if ( r.exists() ) {
                result.add(r.getURL());
            } else {
                log.debug("Skipping resource [{}]", r);
            }
        }

        return result;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        resolver = new PathMatchingResourcePatternResolver(applicationContext);
    }

    public PathMatchingResourcePatternResolver getResolver() {
        return resolver;
    }

    public void setResolver(PathMatchingResourcePatternResolver resolver) {
        this.resolver = resolver;
    }

}


text:
bool ChromeServiceRegistrarAndroid::Register(JNIEnv* env) {
  return RegisterNativesImpl(env);
}

// static
void ChromeServiceRegistrarAndroid::RegisterRenderFrameMojoServices(
    content::ServiceRegistry* registry) {
  Java_ChromeServiceRegistrar_registerRenderFrameMojoServices(
      base::android::AttachCurrentThread(),
      content::ServiceRegistryAndroid::Create(registry)->GetObj().obj(),
      base::android::GetApplicationContext());
}


text:
package org.takes.facets.fork;

import java.io.IOException;
import java.util.Arrays;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Test;
import org.takes.Request;
import org.takes.rq.RqFake;
import org.takes.rs.RsPrint;
import org.takes.rs.RsText;

/**
 * Test case for {@link RsFork}.
 * @author Yegor Bugayenko (yegor@teamed.io)
 * @version $Id$
 * @since 0.6
 */
public final class RsForkTest {

    /**
     * RsFork can route by the Accept header.
     * @throws IOException If some problem inside
     */
    @Test
    public void negotiatesContent() throws IOException {
        final Request req = new RqFake(
            Arrays.asList(
                "GET /hello.html",
                "Accept: text/xml; q=0.3, text/plain; q=0.1",
                "Accept: */*; q=0.05"
            ),
            ""
        );
        MatcherAssert.assertThat(
            new RsPrint(
                new RsFork(
                    req,
                    new FkTypes("text/plain", new RsText("it's a text")),
                    new FkTypes("image/*", new RsText("it's an image"))
                )
            ).printBody(),
            Matchers.endsWith("a text")
        );
    }

    /**
     * RsFork can route without Accept header.
     * @throws IOException If some problem inside
     */
    @Test
    public void negotiatesContentWithoutAccept() throws IOException {
        MatcherAssert.assertThat(
            new RsPrint(
                new RsFork(
                    new RqFake(),
                    new FkTypes("image/png", new RsText("a png"))
                )
            ).printBody(),
            Matchers.endsWith("png")
        );
    }

    /**
     * RsFork can route by the Accept header.
     * @throws IOException If some problem inside
     */
    @Test
    public void negotiatesContentWithComplexHeader() throws IOException {
        final Request req = new RqFake(
            Arrays.asList(
                "GET /hell-1o.html",
                "Accept: text/xml"
            ),
            ""
        );
        MatcherAssert.assertThat(
            new RsPrint(
                new RsFork(
                    req,
                    new FkTypes(
                        "application/xml,text/xml",
                        new RsText("how are you?")
                    )
                )
            ).printBody(),
            Matchers.endsWith("you?")
        );
    }

}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package soap;

import java.lang.reflect.Field;

/**
 *
 * @author mars
 */
public class SoapEncode {

    public <E> void soapEncode(E o) throws IllegalAccessException {
        Field[] fields = o.getClass().getFields();
        System.out.print("\n" + "<" + o + ">");
        for (int i = 0; i < fields.length; i++) {
            serialize(fields[i].get(o), fields[i].getName());
        }
    }

    public <E> void serialize(E obj, String string) {
        if (obj instanceof Object) {
            System.out.print("\n<" + obj + "xsi:type=\"xsd:string\">");
            System.out.print("</" + obj + ">\n");
        }
    }
    public static A obj = new A();

    public static class A {

        public B obj = new B();
    }

    public static class B {

        public int a = 6;
        public String b = new String("hello world");
    }

    public static void main(String[] args) throws IllegalAccessException {
        SoapEncode mySoapRequest = new SoapEncode();
        mySoapRequest.soapEncode(new B().b);
    }
}


text:
package org.apache.shardingsphere.sql.parser.sql.dialect.statement.opengauss.tcl;

import org.apache.shardingsphere.sql.parser.sql.common.statement.tcl.ReleaseSavepointStatement;
import org.apache.shardingsphere.sql.parser.sql.dialect.statement.opengauss.OpenGaussStatement;

/**
 * OpenGauss release savepoint statement.
 */
public final class OpenGaussReleaseSavepointStatement extends ReleaseSavepointStatement implements OpenGaussStatement {
}


text:
namespace blink {

class FrameSelectionTest : public EditingTestBase {
protected:
    void setSelection(const VisibleSelection&);
    FrameSelection& selection() const;
    const VisibleSelection& visibleSelectionInDOMTree() const { return selection().selection(); }
    const VisibleSelectionInFlatTree& visibleSelectionInFlatTree() const { return selection().selectionInFlatTree(); }

    Text* appendTextNode(const String& data);
    int layoutCount() const { return dummyPageHolder().frameView().layoutCount(); }

    bool shouldPaintCaretForTesting() const { return selection().shouldPaintCaretForTesting(); }
    bool isPreviousCaretDirtyForTesting() const { return selection().isPreviousCaretDirtyForTesting(); }

private:
    Persistent<Text> m_textNode;
};

void FrameSelectionTest::setSelection(const VisibleSelection& newSelection)
{
    dummyPageHolder().frame().selection().setSelection(newSelection);
}

FrameSelection& FrameSelectionTest::selection() const
{
    return dummyPageHolder().frame().selection();
}

Text* FrameSelectionTest::appendTextNode(const String& data)
{
    Text* text = document().createTextNode(data);
    document().body()->appendChild(text);
    return text;
}

TEST_F(FrameSelectionTest, SetValidSelection)
{
    Text* text = appendTextNode("Hello, World!");
    VisibleSelection validSelection(Position(text, 0), Position(text, 5));
    EXPECT_FALSE(validSelection.isNone());
    setSelection(validSelection);
    EXPECT_FALSE(selection().isNone());
}

TEST_F(FrameSelectionTest, SetInvalidSelection)
{
    // Create a new document without frame by using DOMImplementation.
    DocumentInit dummy;
    Document* documentWithoutFrame = Document::create();
    Element* body = HTMLBodyElement::create(*documentWithoutFrame);
    documentWithoutFrame->appendChild(body);
    Text* anotherText = documentWithoutFrame->createTextNode("Hello, another world");
    body->appendChild(anotherText);

    // Create a new VisibleSelection for the new document without frame and
    // update FrameSelection with the selection.
    VisibleSelection invalidSelection;
    invalidSelection.setWithoutValidation(Position(anotherText, 0), Position(anotherText, 5));
    setSelection(invalidSelection);

    EXPECT_TRUE(selection().isNone());
}

TEST_F(FrameSelectionTest, InvalidateCaretRect)
{
    Text* text = appendTextNode("Hello, World!");
    document().view()->updateAllLifecyclePhases();

    VisibleSelection validSelection(Position(text, 0), Position(text, 0));
    setSelection(validSelection);
    selection().setCaretRectNeedsUpdate();
    EXPECT_TRUE(selection().isCaretBoundsDirty());
    selection().invalidateCaretRect();
    EXPECT_FALSE(selection().isCaretBoundsDirty());

    document().body()->removeChild(text);
    document().updateStyleAndLayoutIgnorePendingStylesheets();
    selection().setCaretRectNeedsUpdate();
    EXPECT_TRUE(selection().isCaretBoundsDirty());
    selection().invalidateCaretRect();
    EXPECT_FALSE(selection().isCaretBoundsDirty());
}

TEST_F(FrameSelectionTest, PaintCaretShouldNotLayout)
{
    Text* text = appendTextNode("Hello, World!");
    document().view()->updateAllLifecyclePhases();

    document().body()->setContentEditable("true", ASSERT_NO_EXCEPTION);
    document().body()->focus();
    EXPECT_TRUE(document().body()->focused());

    VisibleSelection validSelection(Position(text, 0), Position(text, 0));
    selection().setCaretVisible(true);
    setSelection(validSelection);
    EXPECT_TRUE(selection().isCaret());
    EXPECT_TRUE(shouldPaintCaretForTesting());

    int startCount = layoutCount();
    {
        // To force layout in next updateLayout calling, widen view.
        FrameView& frameView = dummyPageHolder().frameView();
        IntRect frameRect = frameView.frameRect();
        frameRect.setWidth(frameRect.width() + 1);
        frameRect.setHeight(frameRect.height() + 1);
        dummyPageHolder().frameView().setFrameRect(frameRect);
    }
    OwnPtr<PaintController> paintController = PaintController::create();
    GraphicsContext context(*paintController);
    DrawingRecorder drawingRecorder(context, *dummyPageHolder().frameView().layoutView(), DisplayItem::Caret, LayoutRect::infiniteIntRect());
    selection().paintCaret(context, LayoutPoint());
    EXPECT_EQ(startCount, layoutCount());
}

TEST_F(FrameSelectionTest, InvalidatePreviousCaretAfterRemovingLastCharacter)
{
    Text* text = appendTextNode("Hello, World!");
    document().view()->updateAllLifecyclePhases();

    document().body()->setContentEditable("true", ASSERT_NO_EXCEPTION);
    document().body()->focus();
    EXPECT_TRUE(document().body()->focused());

    selection().setCaretVisible(true);
    EXPECT_TRUE(selection().isCaret());
    EXPECT_TRUE(shouldPaintCaretForTesting());

    // Simulate to type "Hello, World!".
    DisableCompositingQueryAsserts disabler;
    selection().moveTo(createVisiblePosition(selection().end(), selection().affinity()), NotUserTriggered);
    selection().setCaretRectNeedsUpdate();
    EXPECT_TRUE(selection().isCaretBoundsDirty());
    EXPECT_FALSE(isPreviousCaretDirtyForTesting());
    selection().invalidateCaretRect();
    EXPECT_FALSE(selection().isCaretBoundsDirty());
    EXPECT_TRUE(isPreviousCaretDirtyForTesting());

    // Simulate to remove all except for "H".
    text->replaceWholeText("H");
    selection().moveTo(createVisiblePosition(selection().end(), selection().affinity()), NotUserTriggered);
    selection().setCaretRectNeedsUpdate();
    EXPECT_TRUE(selection().isCaretBoundsDirty());
    // "H" remains so early previousCaret invalidation isn't needed.
    EXPECT_TRUE(isPreviousCaretDirtyForTesting());
    selection().invalidateCaretRect();
    EXPECT_FALSE(selection().isCaretBoundsDirty());
    EXPECT_TRUE(isPreviousCaretDirtyForTesting());

    // Simulate to remove the last character.
    document().body()->removeChild(text);
    // This line is the objective of this test.
    // As removing the last character, early previousCaret invalidation is executed.
    EXPECT_FALSE(isPreviousCaretDirtyForTesting());
    document().updateStyleAndLayoutIgnorePendingStylesheets();
    selection().setCaretRectNeedsUpdate();
    EXPECT_TRUE(selection().isCaretBoundsDirty());
    EXPECT_FALSE(isPreviousCaretDirtyForTesting());
    selection().invalidateCaretRect();
    EXPECT_FALSE(selection().isCaretBoundsDirty());
    EXPECT_TRUE(isPreviousCaretDirtyForTesting());
}

#define EXPECT_EQ_SELECTED_TEXT(text) \
    EXPECT_EQ(text, WebString(selection().selectedText()).utf8())

TEST_F(FrameSelectionTest, SelectWordAroundPosition)
{
    // "Foo Bar  Baz,"
    Text* text = appendTextNode("Foo Bar  Baz,");
    // "Fo|o Bar  Baz,"
    EXPECT_TRUE(selection().selectWordAroundPosition(createVisiblePosition(Position(text, 2))));
    EXPECT_EQ_SELECTED_TEXT("Foo");
    // "Foo| Bar  Baz,"
    EXPECT_TRUE(selection().selectWordAroundPosition(createVisiblePosition(Position(text, 3))));
    EXPECT_EQ_SELECTED_TEXT("Foo");
    // "Foo Bar | Baz,"
    EXPECT_FALSE(selection().selectWordAroundPosition(createVisiblePosition(Position(text, 13))));
    // "Foo Bar  Baz|,"
    EXPECT_TRUE(selection().selectWordAroundPosition(createVisiblePosition(Position(text, 22))));
    EXPECT_EQ_SELECTED_TEXT("Baz");
}

TEST_F(FrameSelectionTest, ModifyExtendWithFlatTree)
{
    setBodyContent("one");
    setShadowContent("two<content></content>", "host");
    Element* host = document().getElementById("host");
    Node* const two = FlatTreeTraversal::firstChild(*host);
    // Select "two" for selection in DOM tree
    // Select "twoone" for selection in Flat tree
    selection().setSelection(VisibleSelectionInFlatTree(PositionInFlatTree(host, 0), PositionInFlatTree(document().body(), 2)));
    selection().modify(FrameSelection::AlterationExtend, DirectionForward, WordGranularity);
    EXPECT_EQ(Position(two, 0), visibleSelectionInDOMTree().start());
    EXPECT_EQ(Position(two, 3), visibleSelectionInDOMTree().end());
    EXPECT_EQ(PositionInFlatTree(two, 0), visibleSelectionInFlatTree().start());
    EXPECT_EQ(PositionInFlatTree(two, 3), visibleSelectionInFlatTree().end());
}

TEST_F(FrameSelectionTest, MoveRangeSelectionTest)
{
    // "Foo Bar Baz,"
    Text* text = appendTextNode("Foo Bar Baz,");
    // Itinitializes with "Foo B|a>r Baz," (| means start and > means end).
    selection().setSelection(VisibleSelection(Position(text, 5), Position(text, 6)));
    EXPECT_EQ_SELECTED_TEXT("a");

    // "Foo B|ar B>az," with the Character granularity.
    selection().moveRangeSelection(createVisiblePosition(Position(text, 5)), createVisiblePosition(Position(text, 9)), CharacterGranularity);
    EXPECT_EQ_SELECTED_TEXT("ar B");
    // "Foo B|ar B>az," with the Word granularity.
    selection().moveRangeSelection(createVisiblePosition(Position(text, 5)), createVisiblePosition(Position(text, 9)), WordGranularity);
    EXPECT_EQ_SELECTED_TEXT("Bar Baz");
    // "Fo<o B|ar Baz," with the Character granularity.
    selection().moveRangeSelection(createVisiblePosition(Position(text, 5)), createVisiblePosition(Position(text, 2)), CharacterGranularity);
    EXPECT_EQ_SELECTED_TEXT("o B");
    // "Fo<o B|ar Baz," with the Word granularity.
    selection().moveRangeSelection(createVisiblePosition(Position(text, 5)), createVisiblePosition(Position(text, 2)), WordGranularity);
    EXPECT_EQ_SELECTED_TEXT("Foo Bar");
}

TEST_F(FrameSelectionTest, setNonDirectionalSelectionIfNeeded)
{
    const char* bodyContent = "top";
    const char* shadowContent = "bottom";
    setBodyContent(bodyContent);
    ShadowRoot* shadowRoot = setShadowContent(shadowContent, "host");

    Node* top = document().getElementById("top")->firstChild();
    Node* bottom = shadowRoot->getElementById("bottom")->firstChild();
    Node* host = document().getElementById("host");

    // top to bottom
    selection().setNonDirectionalSelectionIfNeeded(VisibleSelectionInFlatTree(PositionInFlatTree(top, 1), PositionInFlatTree(bottom, 3)), CharacterGranularity);
    EXPECT_EQ(Position(top, 1), visibleSelectionInDOMTree().base());
    EXPECT_EQ(Position::beforeNode(host), visibleSelectionInDOMTree().extent());
    EXPECT_EQ(Position(top, 1), visibleSelectionInDOMTree().start());
    EXPECT_EQ(Position(top, 3), visibleSelectionInDOMTree().end());

    EXPECT_EQ(PositionInFlatTree(top, 1), visibleSelectionInFlatTree().base());
    EXPECT_EQ(PositionInFlatTree(bottom, 3), visibleSelectionInFlatTree().extent());
    EXPECT_EQ(PositionInFlatTree(top, 1), visibleSelectionInFlatTree().start());
    EXPECT_EQ(PositionInFlatTree(bottom, 3), visibleSelectionInFlatTree().end());

    // bottom to top
    selection().setNonDirectionalSelectionIfNeeded(VisibleSelectionInFlatTree(PositionInFlatTree(bottom, 3), PositionInFlatTree(top, 1)), CharacterGranularity);
    EXPECT_EQ(Position(bottom, 3), visibleSelectionInDOMTree().base());
    EXPECT_EQ(Position::beforeNode(bottom->parentNode()), visibleSelectionInDOMTree().extent());
    EXPECT_EQ(Position(bottom, 0), visibleSelectionInDOMTree().start());
    EXPECT_EQ(Position(bottom, 3), visibleSelectionInDOMTree().end());

    EXPECT_EQ(PositionInFlatTree(bottom, 3), visibleSelectionInFlatTree().base());
    EXPECT_EQ(PositionInFlatTree(top, 1), visibleSelectionInFlatTree().extent());
    EXPECT_EQ(PositionInFlatTree(top, 1), visibleSelectionInFlatTree().start());
    EXPECT_EQ(PositionInFlatTree(bottom, 3), visibleSelectionInFlatTree().end());
}

TEST_F(FrameSelectionTest, SelectAllWithUnselectableRoot)
{
    Element* select = document().createElement("select", ASSERT_NO_EXCEPTION);
    document().replaceChild(select, document().documentElement());
    selection().selectAll();
    EXPECT_TRUE(selection().isNone()) << "Nothing should be selected if the content of the documentElement is not selctable.";
}

} // namespace blink


text:
using System;
using Amazon;
using Amazon.Runtime;

namespace Paramore.Brighter.Outbox.DynamoDB
{
    public class DynamoDbConfiguration
    {
        /// <summary>
        /// What AWS Credentials to use
        /// </summary>
        [Obsolete("This property is not being used")]
        public AWSCredentials Credentials { get; }
        /// <summary>
        /// Which AWS region
        /// </summary>
        [Obsolete("This property is not being used")]
        public RegionEndpoint Region { get; }
        /// <summary>
        /// The table that forms the Outbox
        /// </summary>
        public string TableName { get; set; }
        /// <summary>
        /// The name of local delivered status index
        /// </summary>
        public string DeliveredIndexName { get; }
        /// <summary>
        /// The name of the global secondary outstanding index
        /// </summary>
        public string OutstandingIndexName { get; set; }
        /// <summary>
        /// Timeout in milliseconds
        /// </summary>
        public int Timeout { get; }

        [Obsolete("Use the DynamoDbConfiguration without AWSCredentials and without RegionEndpoint")]
        public DynamoDbConfiguration(
            AWSCredentials credentials,
            RegionEndpoint region,
            string tableName = null,
            int timeout = 500)
        {
            Credentials = credentials;
            Region = region;
            TableName = tableName ?? "brighter_outbox";
            OutstandingIndexName = "Outstanding";
            DeliveredIndexName = "Delivered";
            Timeout = timeout;
        }

        public DynamoDbConfiguration(string tableName = null, int timeout = 500)
        {
            TableName = tableName ?? "brighter_outbox";
            OutstandingIndexName = "Outstanding";
            DeliveredIndexName = "Delivered";
            Timeout = timeout;
        }
    }
}


text:
// Copyright (c) 2017 James Skimming. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.

namespace Abioc
{
    using System;
    using System.Collections.Generic;

    /// <summary>
    /// The interface implemented by the generated class for the dependency injection container.
    /// </summary>
    public interface IContainer
    {
        /// <summary>
        /// Gets the service of type <paramref name="serviceType"/>.
        /// </summary>
        /// <param name="serviceType">The type of the service to get.</param>
        /// <returns>The service of type <paramref name="serviceType"/>.</returns>
        object GetService(Type serviceType);

        /// <summary>
        /// Gets the service of type <typeparamref name="TService"/>.
        /// </summary>
        /// <typeparam name="TService">The type of the service to get.</typeparam>
        /// <returns>The service of type <typeparamref name="TService"/>.</returns>
        TService GetService<TService>();

        /// <summary>
        /// Gets any services of the type <paramref name="serviceType"/>.
        /// </summary>
        /// <param name="serviceType">The type of the services to get.</param>
        /// <returns>Any services of the <paramref name="serviceType"/>.</returns>
        IEnumerable<object> GetServices(Type serviceType);

        /// <summary>
        /// Gets any services of the type <typeparamref name="TService"/>.
        /// </summary>
        /// <typeparam name="TService">The type of the service to get.</typeparam>
        /// <returns>Any services of the type  <typeparamref name="TService"/>.</returns>
        IEnumerable<TService> GetServices<TService>();
    }
}


text:
package org.apache.druid.data.input.avro;

import org.apache.druid.data.input.AvroStreamInputRowParserTest;
import org.apache.druid.data.input.SomeAvroDatum;
import org.junit.Assert;
import org.junit.Test;

public class AvroFlattenerMakerTest
{

  @Test
  public void getRootField()
  {
    final SomeAvroDatum record = AvroStreamInputRowParserTest.buildSomeAvroDatum();
    final AvroFlattenerMaker flattener = new AvroFlattenerMaker(false, false);

    Assert.assertEquals(
        record.getTimestamp(),
        flattener.getRootField(record, "timestamp")
    );
    Assert.assertEquals(
        record.getEventType(),
        flattener.getRootField(record, "eventType")
    );
    Assert.assertEquals(
        record.getId(),
        flattener.getRootField(record, "id")
    );
    Assert.assertEquals(
        record.getSomeOtherId(),
        flattener.getRootField(record, "someOtherId")
    );
    Assert.assertEquals(
        record.getIsValid(),
        flattener.getRootField(record, "isValid")
    );
    Assert.assertEquals(
        record.getSomeIntArray(),
        flattener.getRootField(record, "someIntArray")
    );
    Assert.assertEquals(
        record.getSomeStringArray(),
        flattener.getRootField(record, "someStringArray")
    );
    Assert.assertEquals(
        record.getSomeIntValueMap(),
        flattener.getRootField(record, "someIntValueMap")
    );
    Assert.assertEquals(
        record.getSomeStringValueMap(),
        flattener.getRootField(record, "someStringValueMap")
    );
    Assert.assertEquals(
        record.getSomeUnion(),
        flattener.getRootField(record, "someUnion")
    );
    Assert.assertEquals(
        record.getSomeNull(),
        flattener.getRootField(record, "someNull")
    );
    Assert.assertEquals(
        record.getSomeFixed(),
        flattener.getRootField(record, "someFixed")
    );
    Assert.assertEquals(
        // Casted to an array by transformValue
        record.getSomeBytes().array(),
        flattener.getRootField(record, "someBytes")
    );
    Assert.assertEquals(
        record.getSomeEnum(),
        flattener.getRootField(record, "someEnum")
    );
    Assert.assertEquals(
        record.getSomeRecord(),
        flattener.getRootField(record, "someRecord")
    );
    Assert.assertEquals(
        record.getSomeLong(),
        flattener.getRootField(record, "someLong")
    );
    Assert.assertEquals(
        record.getSomeInt(),
        flattener.getRootField(record, "someInt")
    );
    Assert.assertEquals(
        record.getSomeFloat(),
        flattener.getRootField(record, "someFloat")
    );
    Assert.assertEquals(
        record.getSomeRecordArray(),
        flattener.getRootField(record, "someRecordArray")
    );
  }

  @Test
  public void makeJsonPathExtractor()
  {
    final SomeAvroDatum record = AvroStreamInputRowParserTest.buildSomeAvroDatum();
    final AvroFlattenerMaker flattener = new AvroFlattenerMaker(false, false);

    Assert.assertEquals(
        record.getTimestamp(),
        flattener.makeJsonPathExtractor("$.timestamp").apply(record)
    );
    Assert.assertEquals(
        record.getEventType(),
        flattener.makeJsonPathExtractor("$.eventType").apply(record)
    );
    Assert.assertEquals(
        record.getId(),
        flattener.makeJsonPathExtractor("$.id").apply(record)
    );
    Assert.assertEquals(
        record.getSomeOtherId(),
        flattener.makeJsonPathExtractor("$.someOtherId").apply(record)
    );
    Assert.assertEquals(
        record.getIsValid(),
        flattener.makeJsonPathExtractor("$.isValid").apply(record)
    );
    Assert.assertEquals(
        record.getSomeIntArray(),
        flattener.makeJsonPathExtractor("$.someIntArray").apply(record)
    );
    Assert.assertEquals(
        record.getSomeStringArray(),
        flattener.makeJsonPathExtractor("$.someStringArray").apply(record)
    );
    Assert.assertEquals(
        record.getSomeIntValueMap(),
        flattener.makeJsonPathExtractor("$.someIntValueMap").apply(record)
    );
    Assert.assertEquals(
        record.getSomeStringValueMap(),
        flattener.makeJsonPathExtractor("$.someStringValueMap").apply(record)
    );
    Assert.assertEquals(
        record.getSomeUnion(),
        flattener.makeJsonPathExtractor("$.someUnion").apply(record)
    );
    Assert.assertEquals(
        record.getSomeNull(),
        flattener.makeJsonPathExtractor("$.someNull").apply(record)
    );
    Assert.assertEquals(
        record.getSomeFixed(),
        flattener.makeJsonPathExtractor("$.someFixed").apply(record)
    );
    Assert.assertEquals(
        // Casted to an array by transformValue
        record.getSomeBytes().array(),
        flattener.makeJsonPathExtractor("$.someBytes").apply(record)
    );
    Assert.assertEquals(
        record.getSomeEnum(),
        flattener.makeJsonPathExtractor("$.someEnum").apply(record)
    );
    Assert.assertEquals(
        record.getSomeRecord(),
        flattener.makeJsonPathExtractor("$.someRecord").apply(record)
    );
    Assert.assertEquals(
        record.getSomeLong(),
        flattener.makeJsonPathExtractor("$.someLong").apply(record)
    );
    Assert.assertEquals(
        record.getSomeInt(),
        flattener.makeJsonPathExtractor("$.someInt").apply(record)
    );
    Assert.assertEquals(
        record.getSomeFloat(),
        flattener.makeJsonPathExtractor("$.someFloat").apply(record)
    );
    Assert.assertEquals(
        record.getSomeRecordArray(),
        flattener.makeJsonPathExtractor("$.someRecordArray").apply(record)
    );
  }

  @Test(expected = UnsupportedOperationException.class)
  public void makeJsonQueryExtractor()
  {
    final SomeAvroDatum record = AvroStreamInputRowParserTest.buildSomeAvroDatum();
    final AvroFlattenerMaker flattener = new AvroFlattenerMaker(false, false);

    Assert.assertEquals(
        record.getTimestamp(),
        flattener.makeJsonQueryExtractor("$.timestamp").apply(record)
    );
  }
}


text:
namespace android_webview {

namespace internal {

class RequestInvokeGLTracker {
 public:
  RequestInvokeGLTracker();
  bool ShouldRequestOnNonUiThread(RenderThreadManager* state);
  bool ShouldRequestOnUiThread(RenderThreadManager* state);
  void ResetPending();
  void SetQueuedFunctorOnUi(RenderThreadManager* state);

 private:
  base::Lock lock_;
  RenderThreadManager* pending_ui_;
  RenderThreadManager* pending_non_ui_;
};

RequestInvokeGLTracker::RequestInvokeGLTracker()
    : pending_ui_(NULL), pending_non_ui_(NULL) {}

bool RequestInvokeGLTracker::ShouldRequestOnNonUiThread(
    RenderThreadManager* state) {
  base::AutoLock lock(lock_);
  if (pending_ui_ || pending_non_ui_)
    return false;
  pending_non_ui_ = state;
  return true;
}

bool RequestInvokeGLTracker::ShouldRequestOnUiThread(
    RenderThreadManager* state) {
  base::AutoLock lock(lock_);
  if (pending_non_ui_) {
    pending_non_ui_->ResetRequestInvokeGLCallback();
    pending_non_ui_ = NULL;
  }
  // At this time, we could have already called RequestInvokeGL on the UI
  // thread,
  // but the corresponding GL mode process hasn't happened yet. In this case,
  // don't schedule another requestInvokeGL on the UI thread.
  if (pending_ui_)
    return false;
  pending_ui_ = state;
  return true;
}

void RequestInvokeGLTracker::ResetPending() {
  base::AutoLock lock(lock_);
  pending_non_ui_ = NULL;
  pending_ui_ = NULL;
}

void RequestInvokeGLTracker::SetQueuedFunctorOnUi(RenderThreadManager* state) {
  base::AutoLock lock(lock_);
  DCHECK(state);
  pending_ui_ = state;
  pending_non_ui_ = NULL;
}

}  // namespace internal

namespace {

base::LazyInstance<internal::RequestInvokeGLTracker>
    g_request_invoke_gl_tracker = LAZY_INSTANCE_INITIALIZER;
}

RenderThreadManager::RenderThreadManager(
    RenderThreadManagerClient* client,
    const scoped_refptr<base::SingleThreadTaskRunner>& ui_loop)
    : ui_loop_(ui_loop),
      client_(client),
      compositor_frame_producer_(nullptr),
      renderer_manager_key_(GLViewRendererManager::GetInstance()->NullKey()),
      hardware_renderer_has_frame_(false),
      sync_on_draw_hardware_(base::CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kSyncOnDrawHardware)),
      inside_hardware_release_(false),
      weak_factory_on_ui_thread_(this) {
  DCHECK(ui_loop_->BelongsToCurrentThread());
  DCHECK(client_);
  ui_thread_weak_ptr_ = weak_factory_on_ui_thread_.GetWeakPtr();
  ResetRequestInvokeGLCallback();
}

RenderThreadManager::~RenderThreadManager() {
  DCHECK(ui_loop_->BelongsToCurrentThread());
  if (compositor_frame_producer_) {
    compositor_frame_producer_->RemoveCompositorFrameConsumer(this);
  }
  DCHECK(!hardware_renderer_.get());
}

void RenderThreadManager::ClientRequestInvokeGL(bool for_idle) {
  if (ui_loop_->BelongsToCurrentThread()) {
    if (!g_request_invoke_gl_tracker.Get().ShouldRequestOnUiThread(this))
      return;
    ClientRequestInvokeGLOnUI();
  } else {
    if (!g_request_invoke_gl_tracker.Get().ShouldRequestOnNonUiThread(this))
      return;
    base::Closure callback;
    {
      base::AutoLock lock(lock_);
      callback = request_draw_gl_closure_;
    }
    // 17ms is slightly longer than a frame, hoping that it will come
    // after the next frame so that the idle work is taken care off by
    // the next frame instead.
    ui_loop_->PostDelayedTask(
        FROM_HERE, callback,
        for_idle ? base::TimeDelta::FromMilliseconds(17) : base::TimeDelta());
  }
}

void RenderThreadManager::DidInvokeGLProcess() {
  g_request_invoke_gl_tracker.Get().ResetPending();
}

void RenderThreadManager::ResetRequestInvokeGLCallback() {
  DCHECK(ui_loop_->BelongsToCurrentThread());
  base::AutoLock lock(lock_);
  request_draw_gl_cancelable_closure_.Reset(base::Bind(
      &RenderThreadManager::ClientRequestInvokeGLOnUI, base::Unretained(this)));
  request_draw_gl_closure_ = request_draw_gl_cancelable_closure_.callback();
}

void RenderThreadManager::ClientRequestInvokeGLOnUI() {
  DCHECK(ui_loop_->BelongsToCurrentThread());
  ResetRequestInvokeGLCallback();
  g_request_invoke_gl_tracker.Get().SetQueuedFunctorOnUi(this);
  if (!client_->RequestInvokeGL(false)) {
    g_request_invoke_gl_tracker.Get().ResetPending();
    LOG(ERROR) << "Failed to request GL process. Deadlock likely";
  }
}

void RenderThreadManager::UpdateParentDrawConstraintsOnUI() {
  DCHECK(ui_loop_->BelongsToCurrentThread());
  if (compositor_frame_producer_) {
    compositor_frame_producer_->OnParentDrawConstraintsUpdated(this);
  }
}

void RenderThreadManager::SetScrollOffsetOnUI(gfx::Vector2d scroll_offset) {
  base::AutoLock lock(lock_);
  scroll_offset_ = scroll_offset;
}

gfx::Vector2d RenderThreadManager::GetScrollOffsetOnRT() {
  base::AutoLock lock(lock_);
  return scroll_offset_;
}

std::unique_ptr<ChildFrame> RenderThreadManager::SetFrameOnUI(
    std::unique_ptr<ChildFrame> new_frame) {
  DCHECK(new_frame);
  base::AutoLock lock(lock_);
  if (child_frames_.empty()) {
    child_frames_.emplace_back(std::move(new_frame));
    return nullptr;
  }
  std::unique_ptr<ChildFrame> uncommitted_frame;
  if (new_frame->frame) {
    // Optimization for synchronous path.
    // TODO(boliu): Remove when synchronous path is fully removed.
    DCHECK_LE(child_frames_.size(), 1u);
    if (!child_frames_.empty()) {
      uncommitted_frame = std::move(child_frames_.front());
      child_frames_.pop_front();
    }
    child_frames_.emplace_back(std::move(new_frame));
    return uncommitted_frame;
  }

  DCHECK_LE(child_frames_.size(), 2u);
  ChildFrameQueue pruned_frames =
      HardwareRenderer::WaitAndPruneFrameQueue(&child_frames_);
  DCHECK_LE(pruned_frames.size(), 1u);
  if (pruned_frames.size())
    uncommitted_frame = std::move(pruned_frames.front());
  child_frames_.emplace_back(std::move(new_frame));
  return uncommitted_frame;
}

ChildFrameQueue RenderThreadManager::PassFramesOnRT() {
  base::AutoLock lock(lock_);
  hardware_renderer_has_frame_ =
      hardware_renderer_has_frame_ || !child_frames_.empty();
  ChildFrameQueue returned_frames;
  returned_frames.swap(child_frames_);
  return returned_frames;
}

ChildFrameQueue RenderThreadManager::PassUncommittedFrameOnUI() {
  base::AutoLock lock(lock_);
  for (auto& frame_ptr : child_frames_)
    frame_ptr->WaitOnFutureIfNeeded();
  ChildFrameQueue returned_frames;
  returned_frames.swap(child_frames_);
  return returned_frames;
}

void RenderThreadManager::PostExternalDrawConstraintsToChildCompositorOnRT(
    const ParentCompositorDrawConstraints& parent_draw_constraints) {
  {
    base::AutoLock lock(lock_);
    parent_draw_constraints_ = parent_draw_constraints;
  }

  // No need to hold the lock_ during the post task.
  ui_loop_->PostTask(
      FROM_HERE,
      base::Bind(&RenderThreadManager::UpdateParentDrawConstraintsOnUI,
                 ui_thread_weak_ptr_));
}

ParentCompositorDrawConstraints
RenderThreadManager::GetParentDrawConstraintsOnUI() const {
  base::AutoLock lock(lock_);
  return parent_draw_constraints_;
}

void RenderThreadManager::SetInsideHardwareRelease(bool inside) {
  base::AutoLock lock(lock_);
  inside_hardware_release_ = inside;
}

bool RenderThreadManager::IsInsideHardwareRelease() const {
  base::AutoLock lock(lock_);
  return inside_hardware_release_;
}

RenderThreadManager::ReturnedResources::ReturnedResources()
    : compositor_frame_sink_id(0u) {}

RenderThreadManager::ReturnedResources::~ReturnedResources() {}

void RenderThreadManager::InsertReturnedResourcesOnRT(
    const cc::ReturnedResourceArray& resources,
    const CompositorID& compositor_id,
    uint32_t compositor_frame_sink_id) {
  base::AutoLock lock(lock_);
  ReturnedResources& returned_resources =
      returned_resources_map_[compositor_id];
  if (returned_resources.compositor_frame_sink_id != compositor_frame_sink_id) {
    returned_resources.resources.clear();
  }
  returned_resources.resources.insert(returned_resources.resources.end(),
                                      resources.begin(), resources.end());
  returned_resources.compositor_frame_sink_id = compositor_frame_sink_id;
}

void RenderThreadManager::SwapReturnedResourcesOnUI(
    ReturnedResourcesMap* returned_resource_map) {
  DCHECK(returned_resource_map->empty());
  base::AutoLock lock(lock_);
  returned_resource_map->swap(returned_resources_map_);
}

bool RenderThreadManager::ReturnedResourcesEmptyOnUI() const {
  base::AutoLock lock(lock_);
  return returned_resources_map_.empty();
}

void RenderThreadManager::DrawGL(AwDrawGLInfo* draw_info) {
  TRACE_EVENT0("android_webview", "DrawFunctor");
  if (draw_info->mode == AwDrawGLInfo::kModeSync) {
    TRACE_EVENT_INSTANT0("android_webview", "kModeSync",
                         TRACE_EVENT_SCOPE_THREAD);
    if (hardware_renderer_)
      hardware_renderer_->CommitFrame();
    return;
  }

  // kModeProcessNoContext should never happen because we tear down hardware
  // in onTrimMemory. However that guarantee is maintained outside of chromium
  // code. Not notifying shared state in kModeProcessNoContext can lead to
  // immediate deadlock, which is slightly more catastrophic than leaks or
  // corruption.
  if (draw_info->mode == AwDrawGLInfo::kModeProcess ||
      draw_info->mode == AwDrawGLInfo::kModeProcessNoContext) {
    DidInvokeGLProcess();
  }

  {
    GLViewRendererManager* manager = GLViewRendererManager::GetInstance();
    base::AutoLock lock(lock_);
    if (renderer_manager_key_ != manager->NullKey()) {
      manager->DidDrawGL(renderer_manager_key_);
    }
  }

  ScopedAppGLStateRestore state_restore(
      draw_info->mode == AwDrawGLInfo::kModeDraw
          ? ScopedAppGLStateRestore::MODE_DRAW
          : ScopedAppGLStateRestore::MODE_RESOURCE_MANAGEMENT);
  ScopedAllowGL allow_gl;
  if (!hardware_renderer_ && draw_info->mode == AwDrawGLInfo::kModeDraw &&
      !IsInsideHardwareRelease() && HasFrameForHardwareRendererOnRT()) {
    hardware_renderer_.reset(new HardwareRenderer(this));
    hardware_renderer_->CommitFrame();
  }

  if (draw_info->mode == AwDrawGLInfo::kModeProcessNoContext) {
    LOG(ERROR) << "Received unexpected kModeProcessNoContext";
  }

  if (IsInsideHardwareRelease()) {
    hardware_renderer_has_frame_ = false;
    hardware_renderer_.reset();
    // Flush the idle queue in tear down.
    DeferredGpuCommandService::GetInstance()->PerformAllIdleWork();
    return;
  }

  if (draw_info->mode != AwDrawGLInfo::kModeDraw) {
    if (draw_info->mode == AwDrawGLInfo::kModeProcess) {
      DeferredGpuCommandService::GetInstance()->PerformIdleWork(true);
    }
    return;
  }

  if (hardware_renderer_)
    hardware_renderer_->DrawGL(draw_info);
  DeferredGpuCommandService::GetInstance()->PerformIdleWork(false);
}

void RenderThreadManager::DeleteHardwareRendererOnUI() {
  DCHECK(ui_loop_->BelongsToCurrentThread());

  InsideHardwareReleaseReset auto_inside_hardware_release_reset(this);

  // If the WebView gets onTrimMemory >= MODERATE twice in a row, the 2nd
  // onTrimMemory will result in an unnecessary Render Thread InvokeGL call.
  bool hardware_initialized = HasFrameOnUI();
  if (hardware_initialized) {
    // The functor has only been attached to the view hierarchy if a compositor
    // frame has been generated. Thus, it should only be detached in this case.
    client_->DetachFunctorFromView();

    bool draw_functor_succeeded = client_->RequestInvokeGL(true);
    if (!draw_functor_succeeded) {
      LOG(ERROR) << "Unable to free GL resources. Has the Window leaked?";
      // Calling release on wrong thread intentionally.
      AwDrawGLInfo info;
      info.mode = AwDrawGLInfo::kModeProcess;
      DrawGL(&info);
    }
  }

  GLViewRendererManager* manager = GLViewRendererManager::GetInstance();

  {
    base::AutoLock lock(lock_);
    if (renderer_manager_key_ != manager->NullKey()) {
      manager->Remove(renderer_manager_key_);
      renderer_manager_key_ = manager->NullKey();
    }
  }

  if (hardware_initialized) {
    // Flush any invoke functors that's caused by ReleaseHardware.
    client_->RequestInvokeGL(true);
  }
}

void RenderThreadManager::SetCompositorFrameProducer(
    CompositorFrameProducer* compositor_frame_producer) {
  DCHECK(compositor_frame_producer == compositor_frame_producer_ ||
         compositor_frame_producer_ == nullptr ||
         compositor_frame_producer == nullptr);
  compositor_frame_producer_ = compositor_frame_producer;
}

bool RenderThreadManager::HasFrameOnUI() const {
  base::AutoLock lock(lock_);
  return hardware_renderer_has_frame_ || !child_frames_.empty();
}

bool RenderThreadManager::HasFrameForHardwareRendererOnRT() const {
  base::AutoLock lock(lock_);
  return !child_frames_.empty();
}

void RenderThreadManager::InitializeHardwareDrawIfNeededOnUI() {
  DCHECK(ui_loop_->BelongsToCurrentThread());
  GLViewRendererManager* manager = GLViewRendererManager::GetInstance();

  base::AutoLock lock(lock_);
  if (renderer_manager_key_ == manager->NullKey()) {
    renderer_manager_key_ = manager->PushBack(this);
  }
}

RenderThreadManager::InsideHardwareReleaseReset::InsideHardwareReleaseReset(
    RenderThreadManager* render_thread_manager)
    : render_thread_manager_(render_thread_manager) {
  DCHECK(!render_thread_manager_->IsInsideHardwareRelease());
  render_thread_manager_->SetInsideHardwareRelease(true);
}

RenderThreadManager::InsideHardwareReleaseReset::~InsideHardwareReleaseReset() {
  render_thread_manager_->SetInsideHardwareRelease(false);
}

}  // namespace android_webview


text:
package com.vmware.vim25;

/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/

public enum StorageDrsPodConfigInfoBehavior {
  manual ("manual"),
  automated ("automated");

  @SuppressWarnings("unused")
  private final String val;
  private StorageDrsPodConfigInfoBehavior(String val)
  {
    this.val = val;
  }
}