text:
void CCounterAttackerStrikerIdleState::Execute(CPlayer* pPlayer)
{
	Position perIntersection;
	auto& pClosestPlayer = game_.GetClosestPlayer();
	float distanceFromBall = ball_.GetPosition().DistanceFrom(pPlayer->GetPosition());
	//ball is travelling and iterception is possible
	if (pPlayer->HasBall())
	{
		pPlayer->KickShort_Striker();
	}
	else if (distanceFromBall < 0.5)
	{
		pPlayer->TakePossession();
		pPlayer->ChangeState(CPlayerState::eCounterAttackerStrikerTakePossession);
	}
	else if (ball_.GetSpeed() > 0 &&
	    GetPerpendicularIntersection(ball_.GetPosition(), ball_.GetVirtualStationaryPosition(), pPlayer->GetPosition(), perIntersection))
	{
		//try to intercept ball
		pPlayer->MoveForBall();
		pPlayer->ChangeState(CPlayerState::eCounterAttackerStrikerInterceptBall);
	}
	else
	{
		//interseption not possible.
		if(pClosestPlayer->GetNumber() != pPlayer->GetNumber() && //not me
		   pClosestPlayer->IsOurTeamMember())					  // is our team
		{
			if (pPlayer->GetPosition().ApproxEqual(pPlayer->GetHomePosition(),POSITION_BIG_TOLERANCE))
			{
			pPlayer->SetHomePosition(pPlayer->GetRandomFreePosition_Striker());
			}

			pPlayer->MoveTo(pPlayer->GetHomePosition());
		}
		else if (ball_.IsFreeBall() && !pitch_.IsOurHalf(ball_.GetStationaryPosition()))
		{
			pPlayer->MoveTo(ball_.GetStationaryPosition());
		}
		else
		{
			if (pPlayer->GetPosition().ApproxEqual(pPlayer->GetHomePosition(),POSITION_BIG_TOLERANCE))
			{
			pPlayer->SetHomePosition(pPlayer->GetRandomFreePosition_Striker());
			}
			pPlayer->MoveTo(pPlayer->GetHomePosition());
		}

	}
}

void CCounterAttackerStrikerChaseBallState::Execute(CPlayer* pPlayer)
{
	auto& pClosestPlayer = game_.GetClosestPlayer();
	//ball in range take possession
	float distanceFromBall = ball_.GetPosition().DistanceFrom(pPlayer->GetPosition());
	if (pPlayer->HasBall())
	{
		pPlayer->KickShort_Striker();
	}
	else if (distanceFromBall < 0.5)
	{
		pPlayer->TakePossession();
		pPlayer->ChangeState(CPlayerState::eCounterAttackerStrikerTakePossession);
		return;
	}
	else if(pClosestPlayer->GetNumber() != pPlayer->GetNumber() && //not me
		   pClosestPlayer->IsOurTeamMember())					  // is our team
	{
			pPlayer->MoveTo(pPlayer->GetHomePosition());
			pPlayer->ChangeState(CPlayerState::eCounterAttackerStrikerIdle);
	}
	else if (ball_.GetSpeed() == 0 && ball_.IsFreeBall())
	{
		if (!pitch_.IsOurHalf(ball_.GetStationaryPosition()))
			pPlayer->MoveTo(ball_.GetStationaryPosition());
		else
		{
			pPlayer->MoveTo(pPlayer->GetHomePosition());
			pPlayer->ChangeState(CPlayerState::eCounterAttackerStrikerIdle);
		}
	}
	//lost possession
	else if (ball_.IsTheirTeamControlling() 			//their player in control of ball
			|| ball_.IsOurTeamControlling()
			) // not our team member
	{
		//lost possession. go home bitch
		pPlayer->MoveTo(pPlayer->GetHomePosition());
		pPlayer->ChangeState(CPlayerState::eCounterAttackerStrikerIdle);
	}

}

void CCounterAttackerStrikerInterceptBallState::Execute(CPlayer *pPlayer)
{
	//ball in range take possession
	float distanceFromBall = ball_.GetPosition().DistanceFrom(pPlayer->GetPosition());
	if (distanceFromBall < 0.5)
	{
		pPlayer->TakePossession();
		pPlayer->ChangeState(CPlayerState::eCounterAttackerStrikerTakePossession);
		return;
	}
	else if (ball_.GetSpeed() == 0 && ball_.IsFreeBall())
	{
		if (!pitch_.IsOurHalf(ball_.GetStationaryPosition()))
			pPlayer->MoveTo(ball_.GetStationaryPosition());
		else
		{
			pPlayer->MoveTo(pPlayer->GetHomePosition());
			pPlayer->ChangeState(CPlayerState::eCounterAttackerStrikerIdle);
		}
	}
	else if (ball_.IsTheirTeamControlling()  || ball_.IsOurTeamControlling()	//their player in control of ball
			 //game_.GetClosestPlayer()->IsTheirTeamMember()		//their player is closest
			) // not our team member
	{
		//lost possession. go home bitch
		pPlayer->MoveTo(pPlayer->GetHomePosition());
		pPlayer->ChangeState(CPlayerState::eCounterAttackerStrikerIdle);
	}
}

void CCounterAttackerStrikerTakePossessionState::Execute(CPlayer* pPlayer)
{
	//ball in range take possession
	if (pPlayer->HasBall())
	{
		pPlayer->KickShort_Striker();
	}
	else if (ball_.GetPosition().DistanceFrom(pPlayer->GetPosition()) < 0.5)
	{
		pPlayer->TakePossession();
		//pPlayer->ChangeState(CPlayerState::eCounterAttackerStrikerTakePossession);
	}
	//lost possession
	else if (ball_.IsTheirTeamControlling())//their player in control of ball
	{
		//lost possession. bitch go home
		pPlayer->MoveTo(pPlayer->GetHomePosition());
		pPlayer->ChangeState(CPlayerState::eCounterAttackerStrikerIdle);
	}
	else if (ball_.GetSpeed() == 0 && ball_.IsFreeBall())
	{
		if (!pitch_.IsOurHalf(ball_.GetStationaryPosition()))
			pPlayer->MoveTo(ball_.GetStationaryPosition());
		else
		{
			pPlayer->MoveTo(pPlayer->GetHomePosition());
			pPlayer->ChangeState(CPlayerState::eCounterAttackerStrikerIdle);
		}
	}
	else if (ball_.IsOurTeamControlling())//our player in control of ball
	{
		//lost possession. bitch go home
		pPlayer->MoveTo(pPlayer->GetHomePosition());
		pPlayer->ChangeState(CPlayerState::eCounterAttackerStrikerIdle);
	}
}

void CCounterAttackerStrikerShortKickState::Execute(CPlayer* pPlayer)
{
	float distanceFromBall = ball_.GetPosition().DistanceFrom(pPlayer->GetPosition());

	if (pPlayer->HasBall())
	{
		pPlayer->KickShort_Striker();
	}
	else if (distanceFromBall < 0.5)
	{
		pPlayer->TakePossession();
		pPlayer->ChangeState(CPlayerState::eCounterAttackerStrikerTakePossession);
	}
	else if (ball_.IsFreeBall())	// no owner
	{
		//pPlayer->MoveTo(ball_.GetStationaryPosition());
		if (!pitch_.IsOurHalf(ball_.GetStationaryPosition()))
			pPlayer->MoveTo(ball_.GetStationaryPosition());
		else
		{
			pPlayer->MoveTo(pPlayer->GetHomePosition());
			pPlayer->ChangeState(CPlayerState::eCounterAttackerStrikerIdle);
		}
	}
	//lost possession
	else if (ball_.IsTheirTeamControlling() 				//their player in control of ball
			 //game_.GetClosestPlayer()->IsTheirTeamMember()		//their player is closest
			) // not our team member
	{
		//lost possession. bitch go home
		pPlayer->MoveTo(pPlayer->GetHomePosition());
		pPlayer->ChangeState(CPlayerState::eCounterAttackerStrikerIdle);
	}
}

void CCounterAttackerZombieState::Execute(CPlayer *pPlayer)
{
	float distanceFromBall = ball_.GetPosition().DistanceFrom(pPlayer->GetPosition());

	if (pPlayer->HasBall())
	{
		pPlayer->Kick({ 50.0f, pPlayer->GetPosition().y_},100);
	}
	else if (distanceFromBall < 0.5)
	{
		pPlayer->TakePossession();
	}
}


text:
#pragma once

#include "mldb/core/value_function.h"
#include "mldb/plugins/html/ext/uap-cpp/UaParser.h"

namespace MLDB {

/*****************************************************************************/
/* USER AGENT PARSER FUNCTION CONFIG                                         */
/*****************************************************************************/

struct ParseUserAgentFunctionConfig {
    ParseUserAgentFunctionConfig()
        : regexFile("/opt/bin/useragent-regexes.yaml")
    {}

    std::string regexFile;
};

DECLARE_STRUCTURE_DESCRIPTION(ParseUserAgentFunctionConfig);

/*****************************************************************************/
/* USER AGENT PARSER FUNCTION                                                */
/*****************************************************************************/

struct UserAgentParserArgs  {
    ExpressionValue ua;
};

DECLARE_STRUCTURE_DESCRIPTION(UserAgentParserArgs);

struct UaDevice {
    ExpressionValue brand;
    ExpressionValue model;
};

struct UaSoftware {
    ExpressionValue family;
    ExpressionValue version;
};

struct ParsedUserAgent {
    UaDevice device;
    UaSoftware browser;
    UaSoftware os;
    ExpressionValue isSpider;
};

DECLARE_STRUCTURE_DESCRIPTION(ParsedUserAgent);

struct ParseUserAgentFunction: public ValueFunctionT<UserAgentParserArgs, ParsedUserAgent> {
    ParseUserAgentFunction(MldbEngine * owner,
                           PolyConfig config,
                           const std::function<bool (const Json::Value &)> & onProgress);

    virtual ParsedUserAgent call(UserAgentParserArgs input) const override;

    std::shared_ptr<UaParser::UserAgentParser> parser;

    ParseUserAgentFunctionConfig functionConfig;
};

} // namespace MLDB

redpajama_set_name: RedPajamaGithub


text:
import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';

import {
  NgbAccordion,
  NgbPanel,
  NgbPanelTitle,
  NgbPanelContent,
  NgbPanelHeader,
  NgbPanelToggle,
  NgbRefDirective
} from './accordion';

export {
  NgbAccordion,
  NgbPanel,
  NgbPanelTitle,
  NgbPanelContent,
  NgbPanelChangeEvent,
  NgbPanelHeader,
  NgbPanelHeaderContext,
  NgbPanelToggle
} from './accordion';
export {NgbAccordionConfig} from './accordion-config';

const NGB_ACCORDION_DIRECTIVES =
    [NgbAccordion, NgbPanel, NgbPanelTitle, NgbPanelContent, NgbPanelHeader, NgbPanelToggle];

@NgModule({
  declarations: [NgbRefDirective, ...NGB_ACCORDION_DIRECTIVES],
  exports: NGB_ACCORDION_DIRECTIVES,
  imports: [CommonModule]
})
export class NgbAccordionModule {
}


text:
package org.radargun.stressors;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.radargun.CacheWrapper;
import org.radargun.utils.Utils;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * On multiple threads executes put and get operations against the CacheWrapper, and returns the result as an Map.
 *
 * @author Mircea.Markus@jboss.com
 */
public class PutGetStressor extends AbstractCacheWrapperStressor {

   private static Log log = LogFactory.getLog(PutGetStressor.class);

   private int opsCountStatusLog = 5000;

   /**
    * total number of operation to be made against cache wrapper: reads + writes
    */
   private int numberOfRequests = 50000;

   /**
    * for each there will be created fixed number of keys. All the GETs and PUTs are performed on these keys only.
    */
   private int numberOfKeys = 100;

   /**
    * Each key will be a byte[] of this size.
    */
   private int sizeOfValue = 1000;

   /**
    * Out of the total number of operations, this defines the frequency of writes (percentage).
    */
   private int writePercentage = 20;

   /**
    * Negative values means duration is not enabled.
    */
   private long durationMillis = -1;

   /**
    * the number of threads that will work on this cache wrapper.
    */
   private int numOfThreads = 10;

   /**
    * This node's index in the Radargun cluster.  -1 is used for local benchmarks.
    */
   private int nodeIndex = -1;

   private int transactionSize = 1;

   private boolean useTransactions = false;

   private boolean commitTransactions = true;

   private AtomicInteger txCount = new AtomicInteger(0);

   private String keyGeneratorClass = StringKeyGenerator.class.getName();

   private KeyGenerator keyGenerator;

   private CacheWrapper cacheWrapper;
   private static Random r = new Random();
   private volatile long startNanos;
   private volatile CountDownLatch startPoint;
   private volatile StressorCompletion completion;

   public Map<String, String> stress(CacheWrapper wrapper) {
      this.cacheWrapper = wrapper;
      startNanos = System.nanoTime();
      log.info("Executing: " + this.toString());
      if (durationMillis > 0) {
         completion = new TimeStressorCompletion(durationMillis);
      } else {
         completion = new OperationCountCompletion(new AtomicInteger(numberOfRequests));
      }

      List<Stressor> stressors;
      try {
         stressors = executeOperations();
      } catch (Exception e) {
         throw new RuntimeException(e);
      }
      return processResults(stressors);
   }

   public void destroy() throws Exception {
      cacheWrapper.empty();
      cacheWrapper = null;
   }

   protected Map<String, String> processResults(List<Stressor> stressors) {
      long duration = 0;
      long transactionDuration = 0;
      int reads = 0;
      int writes = 0;
      int failures = 0;
      long readsDurations = 0;
      long writesDurations = 0;

      for (Stressor stressor : stressors) {
         duration += stressor.totalDuration();
         readsDurations += stressor.readDuration;
         writesDurations += stressor.writeDuration;
         transactionDuration += stressor.getTransactionsDuration();

         reads += stressor.reads;
         writes += stressor.writes;
         failures += stressor.nrFailures;
      }

      Map<String, String> results = new LinkedHashMap<String, String>();
      results.put("DURATION", str(duration));
      double requestPerSec = (reads + writes) / ((duration / numOfThreads) / 1000000000.0);
      results.put("REQ_PER_SEC", str(requestPerSec));
      results.put("READS_PER_SEC", str(reads / ((readsDurations / numOfThreads) / 1000000000.0)));
      results.put("WRITES_PER_SEC", str(writes / ((writesDurations / numOfThreads) / 1000000000.0)));
      results.put("READ_COUNT", str(reads));
      results.put("WRITE_COUNT", str(writes));
      results.put("FAILURES", str(failures));
      if (useTransactions) {
         double txPerSec = txCount.get() / ((transactionDuration / numOfThreads) / 1000.0);
         results.put("TX_PER_SEC", str(txPerSec));
      }
      log.info("Finished generating report. Nr of failed operations on this node is: " + failures +
                     ". Test duration is: " + Utils.getNanosDurationString(System.nanoTime() - startNanos));
      return results;
   }

   private List<Stressor> executeOperations() throws Exception {
      List<Stressor> stressors = new ArrayList<Stressor>(numOfThreads);
      startPoint = new CountDownLatch(1);
      for (int threadIndex = 0; threadIndex < numOfThreads; threadIndex++) {
         Stressor stressor = new Stressor(threadIndex);
         stressor.initialiseKeys();
         stressors.add(stressor);
         stressor.start();
      }
      log.info("Cache wrapper info is: " + cacheWrapper.getInfo());
      startPoint.countDown();
      log.info("Started " + stressors.size() + " stressor threads.");
      for (Stressor stressor : stressors) {
         stressor.join();
      }
      return stressors;
   }

   private boolean isLocalBenchmark() {
      return nodeIndex == -1;
   }

   protected class Stressor extends Thread {

      private ArrayList<Object> pooledKeys = new ArrayList<Object>(numberOfKeys);

      private int threadIndex;
      private int nrFailures;
      private long readDuration = 0;
      private long writeDuration = 0;
      private long transactionDuration = 0;
      private long reads;
      private long writes;
      private final String bucketId;
      boolean txNotCompleted = false;

      public Stressor(int threadIndex) {
         super("Stressor-" + threadIndex);
         this.threadIndex = threadIndex;
         this.bucketId = isLocalBenchmark() ? String.valueOf(threadIndex) : nodeIndex + "_" + threadIndex;
      }

      @Override
      public void run() {
         try {
            runInternal();
         } catch (Exception e) {
            log.error("Unexpected error in stressor!", e);
         }
      }

      private void runInternal() {
         int readPercentage = 100 - writePercentage;
         Random r = new Random();
         int randomAction;
         int randomKeyInt;
         try {
            startPoint.await();
            log.trace("Starting thread: " + getName());
         } catch (InterruptedException e) {
            log.warn(e);
         }

         int i = 0;
         while (completion.moreToRun()) {
            randomAction = r.nextInt(100);
            randomKeyInt = r.nextInt(numberOfKeys - 1);
            Object key = getKey(randomKeyInt);
            Object result = null;

            if (randomAction < readPercentage) {
               result = doRead(key, i);
            } else {
               String payload = generateRandomString(sizeOfValue);
               doWrite(key, payload, i);
            }

            i++;
            completion.logProgress(i, result, threadIndex);
         }

         if (txNotCompleted) {
            long start = System.nanoTime();
            completeTransaction(-1, true);
            transactionDuration += System.nanoTime() - start;
         }
      }

      private long startTx(int iteration) {
         long start = System.nanoTime();
         txNotCompleted = startTransaction(iteration);
         long txStartTime = 0;
         if (txNotCompleted) { //if a transaction has been started add the starting time
            txStartTime = System.nanoTime() - start;
            transactionDuration += txStartTime;
         }
         return txStartTime;
      }

      private long endTx(int iteration, long operationDuration) {
         transactionDuration += operationDuration;
         long start = System.nanoTime();
         //if we commit the transaction add the time needed for transaction commit as well
         long txEndTime = 0;
         if (completeTransaction(iteration, false)) {
            txEndTime = System.nanoTime() - start;
            txNotCompleted = false;
            transactionDuration += txEndTime;
         }
         return txEndTime;
      }

      private Object doRead(Object key, int iteration) {
         long txOverhead = 0;
         if (useTransactions) txOverhead = startTx(iteration);

         Object result = null;
         long start = System.nanoTime();
         try {
            result = cacheWrapper.get(bucketId, key);
         } catch (Exception e) {
            log.warn(e);
            nrFailures++;
         }
         long operationDuration = System.nanoTime() - start;

         if (useTransactions) txOverhead += endTx(iteration, operationDuration);
         readDuration += operationDuration;
         if (useTransactions) readDuration += txOverhead;
         reads++;
         return result;
      }

      private void doWrite(Object key, Object payload, int iteration) {
         long txOverhead = 0;
         if (useTransactions) txOverhead = startTx(iteration);

         long start = System.nanoTime();
         try {
            cacheWrapper.put(bucketId, key, payload);
         } catch (Exception e) {
            log.warn(e);
            nrFailures++;
         }
         long operationDuration = System.nanoTime() - start;

         if (useTransactions) txOverhead += endTx(iteration, operationDuration);
         writeDuration += operationDuration;
         if (useTransactions) writeDuration += txOverhead;
         writes++;
      }

      public long totalDuration() {
         return readDuration + writeDuration;
      }

      public void initialiseKeys() {
         for (int keyIndex = 0; keyIndex < numberOfKeys; keyIndex++) {
            try {
               Object key;
               if (isLocalBenchmark()) {
                  key = getKeyGenerator().generateKey(threadIndex, keyIndex);
               } else {
                  key = getKeyGenerator().generateKey(nodeIndex, threadIndex, keyIndex);
               }
               pooledKeys.add(key);
               cacheWrapper.put(this.bucketId, key, generateRandomString(sizeOfValue));
            } catch (Throwable e) {
               log.warn("Error while initializing the session: ", e);
            }
         }
      }

      public Object getKey(int keyIndex) {
         return pooledKeys.get(keyIndex);
      }

      public long getTransactionsDuration() {
         return transactionDuration;
      }
   }

   private boolean startTransaction(int i) {
      if ((i % transactionSize) == 0) {
         cacheWrapper.startTransaction(false);
         return true;
      }
      return false;
   }

   private boolean completeTransaction(int i, boolean force) {
      if ((((i + 1) % transactionSize) == 0) || force) {
         try {
            cacheWrapper.endTransaction(commitTransactions);
         } catch (Exception e) {
            log.error("Issues committing the transaction", e);
            throw new RuntimeException(e);
         }
         txCount.incrementAndGet();
         return true;
      }
      return false;
   }

   private String str(Object o) {
      return String.valueOf(o);
   }

   public void setNumberOfRequests(int numberOfRequests) {
      this.numberOfRequests = numberOfRequests;
   }

   public void setNumberOfAttributes(int numberOfKeys) {
      this.numberOfKeys = numberOfKeys;
   }

   public void setSizeOfAnAttribute(int sizeOfValue) {
      this.sizeOfValue = sizeOfValue;
   }

   public void setNumOfThreads(int numOfThreads) {
      this.numOfThreads = numOfThreads;
   }

   public void setWritePercentage(int writePercentage) {
      this.writePercentage = writePercentage;
   }

   public void setOpsCountStatusLog(int opsCountStatusLog) {
      this.opsCountStatusLog = opsCountStatusLog;
   }

   private static String generateRandomString(int size) {
      // each char is 2 bytes
      StringBuilder sb = new StringBuilder();
      for (int i = 0; i < size / 2; i++) sb.append((char) (64 + r.nextInt(26)));
      return sb.toString();
   }

   public int getNodeIndex() {
      return nodeIndex;
   }

   public void setNodeIndex(int nodeIndex) {
      this.nodeIndex = nodeIndex;
   }

   public String getKeyGeneratorClass() {
      return keyGeneratorClass;
   }

   public void setKeyGeneratorClass(String keyGeneratorClass) {
      this.keyGeneratorClass = keyGeneratorClass;
      instantiateGenerator(keyGeneratorClass);
   }

   private void instantiateGenerator(String keyGeneratorClass) {
      keyGenerator = (KeyGenerator) Utils.instantiate(keyGeneratorClass);
   }

   public KeyGenerator getKeyGenerator() {
      if (keyGenerator == null) instantiateGenerator(keyGeneratorClass);
      return keyGenerator;
   }

   public int getTransactionSize() {
      return transactionSize;
   }

   public void setTransactionSize(int transactionSize) {
      this.transactionSize = transactionSize;
   }

   public boolean isUseTransactions() {
      return useTransactions;
   }

   public void setUseTransactions(boolean useTransactions) {
      this.useTransactions = useTransactions;
   }

   public boolean isCommitTransactions() {
      return commitTransactions;
   }

   public void setCommitTransactions(boolean commitTransactions) {
      this.commitTransactions = commitTransactions;
   }

   public long getDurationMillis() {
      return durationMillis;
   }

   public void setDurationMillis(long durationMillis) {
      this.durationMillis = durationMillis;
   }

   public void setDuration(String duration) {
      this.durationMillis = Utils.string2Millis(duration);
   }

   abstract class StressorCompletion {

      abstract boolean moreToRun();

      public void logProgress(int i, Object result, int threadIndex) {
         if (shoulLogBasedOnOpCount(i)) {
            avoidJit(result);
            logRemainingTime(i, threadIndex);
         }
      }

      protected boolean shoulLogBasedOnOpCount(int i) {
         return (i + 1) % opsCountStatusLog == 0;
      }

      protected void logRemainingTime(int i, int threadIndex) {
         double elapsedNanos = System.nanoTime() - startNanos;
         double estimatedTotal = ((double) (numberOfRequests / numOfThreads) / (double) i) * elapsedNanos;
         double estimatedRemaining = estimatedTotal - elapsedNanos;
         if (log.isTraceEnabled()) {
            log.trace("i=" + i + ", elapsedTime=" + elapsedNanos);
         }
         log.info("Thread index '" + threadIndex + "' executed " + (i + 1) + " operations. Elapsed time: " +
                        Utils.getNanosDurationString((long) elapsedNanos) + ". Estimated remaining: " + Utils.getNanosDurationString((long) estimatedRemaining) +
                        ". Estimated total: " + Utils.getNanosDurationString((long) estimatedTotal));
      }

      protected void avoidJit(Object result) {
         //this line was added just to make sure JIT doesn't skip call to cacheWrapper.get
         if (result != null && System.identityHashCode(result) == result.hashCode()) System.out.print("");
      }
   }

   class OperationCountCompletion extends StressorCompletion {

      private final AtomicInteger requestsLeft;

      OperationCountCompletion(AtomicInteger requestsLeft) {
         this.requestsLeft = requestsLeft;
      }

      @Override
      public boolean moreToRun() {
         return requestsLeft.getAndDecrement() > -1;
      }
   }

   class TimeStressorCompletion extends StressorCompletion {

      private volatile long startTime;

      private final long durationMillis;

      private volatile long lastPrint = -1;

      TimeStressorCompletion(long durationMillis) {
         this.durationMillis = durationMillis;
         startTime = nowMillis();
      }

      @Override
      boolean moreToRun() {
         return nowMillis() <= startTime + durationMillis;
      }

      public void logProgress(int i, Object result, int threadIndex) {
         long nowMillis = nowMillis();

         //make sure this info is not printed more frequently than 20 secs
         int logFrequency = 20;
         if (lastPrint > 0 && (getSecondsSinceLastPrint(nowMillis) < logFrequency)) return; {
            synchronized (this) {
               if (getSecondsSinceLastPrint(nowMillis) < logFrequency) return;
               avoidJit(result);

               lastPrint = nowMillis;
               long elapsedMillis = nowMillis - startTime;

               //make sure negative durations are not printed
               long remaining = Math.max(0, (startTime + durationMillis) - nowMillis);

               log.info("Number of ops executed so far: " + i + ". Elapsed time: " + Utils.getMillisDurationString(elapsedMillis) + ". Remaining: " + Utils.getMillisDurationString(remaining) +
                              ". Total: " + Utils.getMillisDurationString(durationMillis));
            }
         }
      }

      private long getSecondsSinceLastPrint(long nowMillis) {
         return TimeUnit.MILLISECONDS.toSeconds(nowMillis - lastPrint);
      }

      private long nowMillis() {
         return TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
      }
   }

   @Override
   public String toString() {
      return "PutGetStressor{" +
            "opsCountStatusLog=" + opsCountStatusLog +
            ", numberOfRequests=" + numberOfRequests +
            ", numberOfKeys=" + numberOfKeys +
            ", sizeOfValue=" + sizeOfValue +
            ", writePercentage=" + writePercentage +
            ", numOfThreads=" + numOfThreads +
            ", cacheWrapper=" + cacheWrapper +
            ", nodeIndex=" + nodeIndex +
            ", useTransactions=" + useTransactions +
            ", transactionSize=" + transactionSize +
            ", commitTransactions=" + commitTransactions +
            ", durationMillis=" + durationMillis +
            "}";
   }
}


text:
import * as React from "react";
import * as PropTypes from "prop-types";

import ContentDialog, { ContentDialogProps } from "react-uwp/ContentDialog";
import Toggle from "react-uwp/Toggle";

export interface SimpleExampleState {
  showDialog?: boolean;
  showStatusBarDialog?: boolean;
}

const wrapperStyle: React.CSSProperties = {
  margin: "10px 0"
};
export default class SimpleExample extends React.Component<{}, SimpleExampleState> {
  static contextTypes = { theme: PropTypes.object };
  context: { theme: ReactUWP.ThemeType };
  state: SimpleExampleState = {
    showDialog: false,
    showStatusBarDialog: false
  };

  handleToggle = (showDialog: boolean) => {
    this.setState({ showDialog });
  }

  handleToggleStatusBar = (showStatusBarDialog: boolean) => {
    this.setState({ showStatusBarDialog });
  }

  toggleShowDialog = (showDialog?: any) => {
    if (typeof showDialog === "boolean") {
      if (showDialog !== this.state.showDialog) {
        this.setState({ showDialog });
      }
    } else {
      this.setState((prevState, prevProps) => ({
        showDialog: !prevState.showDialog
      }));
    }
  }

  toggleShowStatusBarDialog = (showStatusBarDialog?: any) => {
    if (typeof showStatusBarDialog === "boolean") {
      if (showStatusBarDialog !== this.state.showStatusBarDialog) {
        this.setState({ showStatusBarDialog });
      }
    } else {
      this.setState((prevState, prevProps) => ({
        showStatusBarDialog: !prevState.showStatusBarDialog
      }));
    }
  }

  render() {
    const { showDialog, showStatusBarDialog } = this.state;
    const props: ContentDialogProps = {
      title: "Delete file permanently?",
      content: "If you delete this file, you won't be able to recover it. Do you want to delete it?"
    };
    const statusBarProps: ContentDialogProps = {
      statusBarTitle: "Status Bar",
      showCloseButton: true,
      ...props
    };
    return (

          <Toggle
            checked={showStatusBarDialog}
            label="Toggle Show StatusBarDialog"
            onToggle={this.handleToggleStatusBar}
            defaultToggled={showStatusBarDialog}
          />
          <ContentDialog
            {...statusBarProps}
            defaultShow={showStatusBarDialog}
            primaryButtonAction={this.toggleShowStatusBarDialog}
            closeButtonAction={this.toggleShowStatusBarDialog}
            onCloseDialog={() => {
              this.setState({ showStatusBarDialog: false });
            }}
          />

          <Toggle
            checked={showDialog}
            label="Toggle Show ContentDialog"
            onToggle={this.handleToggle}
            defaultToggled={showDialog}
          />
          <ContentDialog
            {...props}
            defaultShow={showDialog}
            primaryButtonAction={this.toggleShowDialog}
            secondaryButtonAction={this.toggleShowDialog}
            closeButtonAction={this.toggleShowDialog}
            primaryButtonText="Sure"
            secondaryButtonText={null}
            onCloseDialog={() => {
              this.setState({ showDialog: false });
            }}
          />

    );
  }
}


text:
from wtforms.widgets import TextArea

class BigTextArea(TextArea):
    def __init__(self, *args, **kwargs):
        super(BigTextArea, self).__init__()
        self.rows = kwargs.get('rows')
        self.cols = kwargs.get('cols')
        self.css_cls = kwargs.get('css_cls')
        self.style_ = kwargs.get('style_')

    def __call__(self, field, **kwargs):
        c = kwargs.pop('class', '') or kwargs.pop('class_', '')
        kwargs['class'] = u'%s %s' % (self.css_cls, c)
        kwargs['rows'] = self.rows
        kwargs['cols'] = self.cols
        kwargs['style'] = self.style_
        return super(BigTextArea, self).__call__(field, **kwargs)


text:
<?php

/**
 * (c) 2011 - ∞ Vespolina Project http://www.vespolina-project.org
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Vespolina\Tests\Product\Manager;

use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;

use Vespolina\Entity\Channel\Channel;
use Vespolina\Entity\Product\Product;
use Vespolina\Product\Manager\ProductManager;

/**
 * @author Richard D Shank <develop@zestic.com>
 */
class ProductManagerTest extends \PHPUnit_Framework_TestCase
{
    /** @var $mgr \Vespolina\Product\Manager\ProductManager */
    protected $mgr;

    protected function setUp()
    {
        $this->mgr = $this->createProductManager();
    }

    public function testAddProductHandler()
    {
        $handler = $this->createProductHandler('test');
        $this->mgr->addProductHandler($handler);

        $this->assertSame($handler, $this->mgr->getProductHandler('test'), 'a handler should be returned by type');
        $this->assertTrue(is_array($this->mgr->getProductHandlers()));
        $this->assertContains($handler, $this->mgr->getProductHandlers(), 'return all of the handlers');

        $handler2 = $this->createProductHandler('test2');
        $this->mgr->addProductHandler($handler2);
        $this->assertContains($handler2, $this->mgr->getProductHandlers(), 'return all of the handlers');
        $this->assertCount(2, $this->mgr->getProductHandlers());

        $this->mgr->removeProductHandler('test2');
        $this->assertCount(1, $this->mgr->getProductHandlers(), 'there should now only be one handler');

        $this->mgr->removeProductHandler('test');
        $this->assertEmpty($this->mgr->getProductHandlers(), 'there should be no handlers after test has been removed');
    }

    public function testCreateProduct()
    {
        $handler = $this->createProductHandler('test');
        $this->mgr->addProductHandler($handler);

        $this->assertInstanceOf('Vespolina\Entity\Product\ProductInterface', $this->mgr->createProduct('test'));
    }

    public function testCreateMerchandise()
    {
        $handler = $this->createProductHandler('test');
        $this->mgr->addProductHandler($handler);
        $product = $this->mgr->createProduct('test');

        $this->mgr->addMerchandiseHandler($this->getMock(
            'Vespolina\Product\Handler\MerchandiseHandler', null ,  array('Vespolina\Entity\Product\Merchandise')));

        $channel = new Channel();
        $channel->setName('webshop1');
        $this->assertInstanceOf('Vespolina\Entity\Product\MerchandiseInterface', $this->mgr->createMerchandise($product, $channel));
    }

    public function testSearchForProductByIdentifier()
    {
        $this->markTestIncomplete(
            'This test has not been implemented yet.'
        );

        // search by identifier should return a product set up with the specific information for that identifier
        // full results flag returns the full data set for the product
    }

    public function testSetProductSKU()
    {
        $mgr = $this->createProductManager();
        $product = new Product();
        $sku = 'ABC12345';
        $mgr->setProductSKU($product, $sku);

        $identifiers = $product->getIdentifiers();
        $this->assertCount(1, $identifiers);
        $identifier = array_shift($identifiers);
        $this->assertInstanceOf('Vespolina\Entity\Identifier\SKUIdentifier', $identifier);
        $this->assertSame($sku, $identifier->getCode());
    }

    public function testCreateOption()
    {
        $this->markTestIncomplete(
            'This test has not been implemented yet.'
        );

        $mgr = $this->createProductManager('Vespolina\ProductBundle\Model\Identifier\Identifier');

        $option = $mgr->createOption('CoLoR', 'BlAcK');

        $this->assertInstanceOf(
            'Vespolina\ProductBundle\Model\Option\OptionInterface',
            $option,
            'an Option instance should be created'
        );

        $this->assertEquals(
            'CoLoR',
            $option->getType(),
            'make sure the type of the option is stored correctly'
        );

        $this->assertEquals(
            'BlAcK',
            $option->getValue(),
            'make sure the value of the option is stored correctly'
        );
    }

    public function testCreateAttribute()
    {
        $label = $this->mgr->createAttribute('label', 'Joat Music');

        $this->assertSame('label', $label->getType(), 'the type should be copied');
        $this->assertSame('Joat Music', $label->getName(), 'the name should be copied');
    }

    public function testAddAttributeToProduct()
    {
        $product = $this->mgr->createProduct();
        $label = $this->mgr->createAttribute('label', 'Joat Music');
        $this->mgr->addAttributeToProduct($product, $label);
        $this->assertCount(1, $product->getAttributes(), 'the attribute should be added');
        $this->assertSame($label, $product->getAttribute('label'), 'the original attribute should be returned');

        $format = array('format' => 'mp3');
        $this->mgr->addAttributeToProduct($product, $format);
        $this->assertCount(2, $product->getAttributes(), 'an array has been passed in should be added as an attribute');

        $formatAttribute = $product->getAttribute('format');
        $this->assertInstanceOf('Vespolina\Entity\Product\AttributeInterface', $formatAttribute, 'the array should be turned into an Attribute object');
        $this->assertSame('format', $formatAttribute->getType(), 'the type should be copied');
        $this->assertSame('mp3', $formatAttribute->getName(), 'the name should be copied');

        $attribute = 'genre';
        $value = 'rock';
        $this->mgr->addAttributeToProduct($product, $attribute, $value);
        $this->assertCount(3, $product->getAttributes(), 'an array has been passed in should be added as an attribute');

        $formatAttribute = $product->getAttribute('genre');
        $this->assertInstanceOf('Vespolina\Entity\Product\AttributeInterface', $formatAttribute, 'the array should be turned into an Attribute object');
        $this->assertSame('genre', $formatAttribute->getType(), 'the type should be copied');
        $this->assertSame('rock', $formatAttribute->getName(), 'the name should be copied');
    }

    public function testGetImageManager()
    {
        $this->markTestIncomplete(
            'This test has not been implemented yet.'
        );
        $mgr = $this->createProductManager($mediaManager);

        $this->assertSame($mediaManager, $mgr->getMediaManager());

        $this->setExpectedException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException');
        $mgr = $this->createProductManager('Vespolina\ProductBundle\Model\Identifier\IdIdentifier');
        $mgr->getMediaManager();
    }

    public function testSearchForProductByAttribute()
    {
        // search by identifier should return a product set up with the specific information for that identifier
        // full results flag returns the full data set for the product
    }

    public function testSearchForProductByAttributeType()
    {
        // search by identifier should return a product set up with the specific information for that identifier
        // full results flag returns the full data set for the product
    }

    protected function createProductHandler($type, $productClass = 'Vespolina\Entity\Product\Product')
    {
        $productHandler = $this->getMock(
            'Vespolina\Product\Handler\ProductHandler',
            array('createProduct', 'getType'),
            array(),
            '',
            false
        );
        $productHandler->expects($this->any())
            ->method('createProduct')
            ->will($this->returnValue(new Product()));
        $productHandler->expects($this->any())
            ->method('getType')
            ->will($this->returnValue($type));

        return $productHandler;
    }

    protected function createProductManager()
    {
        $productGateway = $this->getMockBuilder('Vespolina\Product\Gateway\ProductGateway')
            ->disableOriginalConstructor()
            ->getMock()
        ;
        $mgr = new ProductManager($productGateway, array(
            'merchandiseClass' => 'Vespolina\Entity\Product\Merchandise',
            'attributeClass' => 'Vespolina\Entity\Product\Attribute',
            'optionClass' => 'Vespolina\Entity\Product\Option',
            'productClass' => 'Vespolina\Entity\Product\Product',
        ));

        return $mgr;
    }
}


text:
FROM nodesource/trusty:5.3.0

MAINTAINER Khoa Nguyen <hi@khoanguyen.me>

ENV DEBIAN_FRONTEND noninteractive
ENV DEBCONF_NONINTERACTIVE_SEEN true

RUN apt-get -y update
RUN apt-get install -y -q software-properties-common
RUN curl https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add -
RUN echo "deb http://dl.google.com/linux/chrome/deb/ stable main" > /etc/apt/sources.list.d/google.list
RUN apt-get update -y
RUN apt-get install -y -q \
  firefox \
  google-chrome-stable \
  Xvfb
RUN apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

ADD xvfb.sh /etc/init.d/xvfb
ADD entrypoint.sh /entrypoint.sh

ENV DISPLAY :99.0
ENV CHROME_BIN /usr/bin/google-chrome
ENV FIREFOX_BIN /usr/bin/firefox

ENTRYPOINT ["/entrypoint.sh"]


text:
namespace {

char g_test_xml[] =
    "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
    "<?my_instruction my_value?>\n"
    "<!DOCTYPE my_document SYSTEM \"example.dtd\" [\n"
    "    <!ENTITY EA \"EA Value\">\n"
    "    <!ENTITY EB \"EB Value\">\n"
    "]>\n"
    "<ns:obj xmlns:ns=\"http://www.example.org/ns\">\n"
    "  <ns:objA>value A</ns:objA>\n"
    "  \n"
    "  <ns:objB>\n"
    "    <ns:objB_1>value B1</ns:objB_1>\n"
    "    <ns:objB_2><![CDATA[some
 data]]></ns:objB_2>\n"
    "    <ns:objB_3>&EB;</ns:objB_3>\n"
    "    <ns:objB_4>this is mixed content &EA;</ns:objB_4>\n"
    "  </ns:objB>\n"
    "  <ns:objC ns:attr1=\"value C1\" ns:attr2=\"value C2\"/><ns:objD>"
    "</ns:objD>\n"
    "</ns:obj>\n";

}  // namespace

// Test XML reading
TEST(XmlReaderTest, Read) {
  // Create the stream reader.
  CefRefPtr<CefStreamReader> stream(
      CefStreamReader::CreateForData(g_test_xml, sizeof(g_test_xml) - 1));
  ASSERT_TRUE(stream.get() != NULL);

  // Create the XML reader.
  CefRefPtr<CefXmlReader> reader(
      CefXmlReader::Create(stream, XML_ENCODING_NONE,
      "http://www.example.org/example.xml"));
  ASSERT_TRUE(reader.get() != NULL);

  // Move to the processing instruction node.
  ASSERT_TRUE(reader->MoveToNextNode());
  ASSERT_EQ(reader->GetDepth(), 0);
  ASSERT_EQ(reader->GetType(), XML_NODE_PROCESSING_INSTRUCTION);
  ASSERT_EQ(reader->GetLocalName(), "my_instruction");
  ASSERT_EQ(reader->GetQualifiedName(), "my_instruction");
  ASSERT_TRUE(reader->HasValue());
  ASSERT_EQ(reader->GetValue(), "my_value");

  // Move to the DOCTYPE node.
  ASSERT_TRUE(reader->MoveToNextNode());
  ASSERT_EQ(reader->GetDepth(), 0);
  ASSERT_EQ(reader->GetType(), XML_NODE_DOCUMENT_TYPE);
  ASSERT_EQ(reader->GetLocalName(), "my_document");
  ASSERT_EQ(reader->GetQualifiedName(), "my_document");
  ASSERT_FALSE(reader->HasValue());

  // Move to ns:obj element start node.
  ASSERT_TRUE(reader->MoveToNextNode());
  ASSERT_EQ(reader->GetDepth(), 0);
  ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_START);
  ASSERT_EQ(reader->GetLocalName(), "obj");
  ASSERT_EQ(reader->GetPrefix(), "ns");
  ASSERT_EQ(reader->GetQualifiedName(), "ns:obj");
  ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns");
  ASSERT_TRUE(reader->HasAttributes());
  ASSERT_EQ(reader->GetAttributeCount(), (size_t)1);
  ASSERT_EQ(reader->GetAttribute(0), "http://www.example.org/ns");
  ASSERT_EQ(reader->GetAttribute("xmlns:ns"), "http://www.example.org/ns");
  ASSERT_EQ(reader->GetAttribute("ns", "http://www.w3.org/2000/xmlns/"),
      "http://www.example.org/ns");

  // Move to the whitespace node.
  ASSERT_TRUE(reader->MoveToNextNode());
  ASSERT_EQ(reader->GetType(), XML_NODE_WHITESPACE);

  // Move to the ns:objA element start node.
  ASSERT_TRUE(reader->MoveToNextNode());
  ASSERT_EQ(reader->GetDepth(), 1);
  ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_START);
  ASSERT_EQ(reader->GetLocalName(), "objA");
  ASSERT_EQ(reader->GetPrefix(), "ns");
  ASSERT_EQ(reader->GetQualifiedName(), "ns:objA");
  ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns");
  ASSERT_FALSE(reader->IsEmptyElement());
  ASSERT_FALSE(reader->HasAttributes());
  ASSERT_FALSE(reader->HasValue());

  // Move to the ns:objA value node.
  ASSERT_TRUE(reader->MoveToNextNode());
  ASSERT_EQ(reader->GetDepth(), 2);
  ASSERT_EQ(reader->GetType(), XML_NODE_TEXT);
  ASSERT_EQ(reader->GetLocalName(), "#text");
  ASSERT_EQ(reader->GetQualifiedName(), "#text");
  ASSERT_TRUE(reader->HasValue());
  ASSERT_EQ(reader->GetValue(), "value A");

  // Move to the ns:objA element ending node.
  ASSERT_TRUE(reader->MoveToNextNode());
  ASSERT_EQ(reader->GetDepth(), 1);
  ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_END);
  ASSERT_EQ(reader->GetLocalName(), "objA");
  ASSERT_EQ(reader->GetPrefix(), "ns");
  ASSERT_EQ(reader->GetQualifiedName(), "ns:objA");
  ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns");
  ASSERT_FALSE(reader->IsEmptyElement());
  ASSERT_FALSE(reader->HasAttributes());
  ASSERT_FALSE(reader->HasValue());

  // Move to the whitespace node.
  ASSERT_TRUE(reader->MoveToNextNode());
  ASSERT_EQ(reader->GetDepth(), 1);
  ASSERT_EQ(reader->GetType(), XML_NODE_WHITESPACE);

  // Move to the comment node.
  ASSERT_TRUE(reader->MoveToNextNode());
  ASSERT_EQ(reader->GetDepth(), 1);
  ASSERT_EQ(reader->GetType(), XML_NODE_COMMENT);
  ASSERT_EQ(reader->GetLocalName(), "#comment");
  ASSERT_EQ(reader->GetQualifiedName(), "#comment");
  ASSERT_TRUE(reader->HasValue());
  ASSERT_EQ(reader->GetValue(), " my comment ");

  // Move to the whitespace node.
  ASSERT_TRUE(reader->MoveToNextNode());
  ASSERT_EQ(reader->GetType(), XML_NODE_WHITESPACE);

  // Move to the ns:objB element start node.
  ASSERT_TRUE(reader->MoveToNextNode());
  ASSERT_EQ(reader->GetDepth(), 1);
  ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_START);
  ASSERT_EQ(reader->GetLocalName(), "objB");
  ASSERT_EQ(reader->GetPrefix(), "ns");
  ASSERT_EQ(reader->GetQualifiedName(), "ns:objB");
  ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns");
  ASSERT_FALSE(reader->IsEmptyElement());
  ASSERT_FALSE(reader->HasAttributes());
  ASSERT_FALSE(reader->HasValue());

  // Move to the whitespace node.
  ASSERT_TRUE(reader->MoveToNextNode());
  ASSERT_EQ(reader->GetType(), XML_NODE_WHITESPACE);

  // Move to the ns:objB_1 element start node.
  ASSERT_TRUE(reader->MoveToNextNode());
  ASSERT_EQ(reader->GetDepth(), 2);
  ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_START);
  ASSERT_EQ(reader->GetLocalName(), "objB_1");
  ASSERT_EQ(reader->GetPrefix(), "ns");
  ASSERT_EQ(reader->GetQualifiedName(), "ns:objB_1");
  ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns");
  ASSERT_FALSE(reader->IsEmptyElement());
  ASSERT_FALSE(reader->HasAttributes());
  ASSERT_FALSE(reader->HasValue());

  // Move to the ns:objB_1 value node.
  ASSERT_TRUE(reader->MoveToNextNode());
  ASSERT_EQ(reader->GetDepth(), 3);
  ASSERT_EQ(reader->GetType(), XML_NODE_TEXT);
  ASSERT_TRUE(reader->HasValue());
  ASSERT_EQ(reader->GetValue(), "value B1");

  // Move to the ns:objB_1 element ending node.
  ASSERT_TRUE(reader->MoveToNextNode());
  ASSERT_EQ(reader->GetDepth(), 2);
  ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_END);
  ASSERT_EQ(reader->GetLocalName(), "objB_1");
  ASSERT_EQ(reader->GetPrefix(), "ns");
  ASSERT_EQ(reader->GetQualifiedName(), "ns:objB_1");
  ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns");
  ASSERT_FALSE(reader->IsEmptyElement());
  ASSERT_FALSE(reader->HasAttributes());
  ASSERT_FALSE(reader->HasValue());

  // Move to the whitespace node.
  ASSERT_TRUE(reader->MoveToNextNode());
  ASSERT_EQ(reader->GetType(), XML_NODE_WHITESPACE);

  // Move to the ns:objB_2 element start node.
  ASSERT_TRUE(reader->MoveToNextNode());
  ASSERT_EQ(reader->GetDepth(), 2);
  ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_START);
  ASSERT_EQ(reader->GetLocalName(), "objB_2");
  ASSERT_EQ(reader->GetPrefix(), "ns");
  ASSERT_EQ(reader->GetQualifiedName(), "ns:objB_2");
  ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns");
  ASSERT_FALSE(reader->IsEmptyElement());
  ASSERT_FALSE(reader->HasAttributes());
  ASSERT_FALSE(reader->HasValue());

  // Move to the ns:objB_2 value node.
  ASSERT_TRUE(reader->MoveToNextNode());
  ASSERT_EQ(reader->GetDepth(), 3);
  ASSERT_EQ(reader->GetType(), XML_NODE_CDATA);
  ASSERT_TRUE(reader->HasValue());
  ASSERT_EQ(reader->GetValue(), "some
 data");

  // Move to the ns:objB_2 element ending node.
  ASSERT_TRUE(reader->MoveToNextNode());
  ASSERT_EQ(reader->GetDepth(), 2);
  ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_END);
  ASSERT_EQ(reader->GetLocalName(), "objB_2");
  ASSERT_EQ(reader->GetPrefix(), "ns");
  ASSERT_EQ(reader->GetQualifiedName(), "ns:objB_2");
  ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns");
  ASSERT_FALSE(reader->IsEmptyElement());
  ASSERT_FALSE(reader->HasAttributes());
  ASSERT_FALSE(reader->HasValue());

  // Move to the whitespace node.
  ASSERT_TRUE(reader->MoveToNextNode());
  ASSERT_EQ(reader->GetType(), XML_NODE_WHITESPACE);

  // Move to the ns:objB_3 element start node.
  ASSERT_TRUE(reader->MoveToNextNode());
  ASSERT_EQ(reader->GetDepth(), 2);
  ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_START);
  ASSERT_EQ(reader->GetLocalName(), "objB_3");
  ASSERT_EQ(reader->GetPrefix(), "ns");
  ASSERT_EQ(reader->GetQualifiedName(), "ns:objB_3");
  ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns");
  ASSERT_FALSE(reader->IsEmptyElement());
  ASSERT_FALSE(reader->HasAttributes());
  ASSERT_FALSE(reader->HasValue());

  // Move to the EB entity reference node.
  ASSERT_TRUE(reader->MoveToNextNode());
  ASSERT_EQ(reader->GetDepth(), 3);
  ASSERT_EQ(reader->GetType(), XML_NODE_ENTITY_REFERENCE);
  ASSERT_EQ(reader->GetLocalName(), "EB");
  ASSERT_EQ(reader->GetQualifiedName(), "EB");
  ASSERT_TRUE(reader->HasValue());
  ASSERT_EQ(reader->GetValue(), "EB Value");

  // Move to the ns:objB_3 element ending node.
  ASSERT_TRUE(reader->MoveToNextNode());
  ASSERT_EQ(reader->GetDepth(), 2);
  ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_END);
  ASSERT_EQ(reader->GetLocalName(), "objB_3");
  ASSERT_EQ(reader->GetPrefix(), "ns");
  ASSERT_EQ(reader->GetQualifiedName(), "ns:objB_3");
  ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns");
  ASSERT_FALSE(reader->IsEmptyElement());
  ASSERT_FALSE(reader->HasAttributes());
  ASSERT_FALSE(reader->HasValue());

  // Move to the whitespace node.
  ASSERT_TRUE(reader->MoveToNextNode());
  ASSERT_EQ(reader->GetType(), XML_NODE_WHITESPACE);

  // Move to the ns:objB_4 element start node.
  ASSERT_TRUE(reader->MoveToNextNode());
  ASSERT_EQ(reader->GetDepth(), 2);
  ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_START);
  ASSERT_EQ(reader->GetLocalName(), "objB_4");
  ASSERT_EQ(reader->GetPrefix(), "ns");
  ASSERT_EQ(reader->GetQualifiedName(), "ns:objB_4");
  ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns");
  ASSERT_FALSE(reader->IsEmptyElement());
  ASSERT_FALSE(reader->HasAttributes());
  ASSERT_FALSE(reader->HasValue());
  ASSERT_EQ(reader->GetInnerXml(), "this is mixed content &EA;");
  ASSERT_EQ(reader->GetOuterXml(),
      "<ns:objB_4 xmlns:ns=\"http://www.example.org/ns\">"
      "this is mixed content &EA;</ns:objB_4>");

  // Move to the  element node.
  ASSERT_TRUE(reader->MoveToNextNode());
  ASSERT_EQ(reader->GetDepth(), 3);
  ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_START);
  ASSERT_EQ(reader->GetLocalName(), "b");
  ASSERT_EQ(reader->GetQualifiedName(), "b");
  ASSERT_FALSE(reader->IsEmptyElement());
  ASSERT_FALSE(reader->HasAttributes());
  ASSERT_FALSE(reader->HasValue());

  // Move to the text node.
  ASSERT_TRUE(reader->MoveToNextNode());
  ASSERT_EQ(reader->GetDepth(), 4);
  ASSERT_EQ(reader->GetType(), XML_NODE_TEXT);
  ASSERT_EQ(reader->GetLocalName(), "#text");
  ASSERT_EQ(reader->GetQualifiedName(), "#text");
  ASSERT_TRUE(reader->HasValue());
  ASSERT_EQ(reader->GetValue(), "this is");

  // Move to the  element node.
  ASSERT_TRUE(reader->MoveToNextNode());
  ASSERT_EQ(reader->GetDepth(), 3);
  ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_END);
  ASSERT_EQ(reader->GetLocalName(), "b");
  ASSERT_EQ(reader->GetQualifiedName(), "b");

  // Move to the text node.
  ASSERT_TRUE(reader->MoveToNextNode());
  ASSERT_EQ(reader->GetDepth(), 3);
  ASSERT_EQ(reader->GetType(), XML_NODE_TEXT);
  ASSERT_EQ(reader->GetLocalName(), "#text");
  ASSERT_EQ(reader->GetQualifiedName(), "#text");
  ASSERT_TRUE(reader->HasValue());
  ASSERT_EQ(reader->GetValue(), " mixed content ");

  // Move to the EA entity reference node.
  ASSERT_TRUE(reader->MoveToNextNode());
  ASSERT_EQ(reader->GetDepth(), 3);
  ASSERT_EQ(reader->GetType(), XML_NODE_ENTITY_REFERENCE);
  ASSERT_EQ(reader->GetLocalName(), "EA");
  ASSERT_EQ(reader->GetQualifiedName(), "EA");
  ASSERT_TRUE(reader->HasValue());
  ASSERT_EQ(reader->GetValue(), "EA Value");

  // Move to the ns:objB_4 element ending node.
  ASSERT_TRUE(reader->MoveToNextNode());
  ASSERT_EQ(reader->GetDepth(), 2);
  ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_END);
  ASSERT_EQ(reader->GetLocalName(), "objB_4");
  ASSERT_EQ(reader->GetPrefix(), "ns");
  ASSERT_EQ(reader->GetQualifiedName(), "ns:objB_4");
  ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns");
  ASSERT_FALSE(reader->IsEmptyElement());
  ASSERT_FALSE(reader->HasAttributes());
  ASSERT_FALSE(reader->HasValue());

  // Move to the whitespace node.
  ASSERT_TRUE(reader->MoveToNextNode());
  ASSERT_EQ(reader->GetType(), XML_NODE_WHITESPACE);

  // Move to the ns:objB element ending node.
  ASSERT_TRUE(reader->MoveToNextNode());
  ASSERT_EQ(reader->GetDepth(), 1);
  ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_END);
  ASSERT_EQ(reader->GetLocalName(), "objB");
  ASSERT_EQ(reader->GetPrefix(), "ns");
  ASSERT_EQ(reader->GetQualifiedName(), "ns:objB");
  ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns");
  ASSERT_FALSE(reader->IsEmptyElement());
  ASSERT_FALSE(reader->HasAttributes());
  ASSERT_FALSE(reader->HasValue());

  // Move to the whitespace node.
  ASSERT_TRUE(reader->MoveToNextNode());
  ASSERT_EQ(reader->GetType(), XML_NODE_WHITESPACE);

  // Move to the ns:objC element start node.
  ASSERT_TRUE(reader->MoveToNextNode());
  ASSERT_EQ(reader->GetDepth(), 1);
  ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_START);
  ASSERT_EQ(reader->GetLocalName(), "objC");
  ASSERT_EQ(reader->GetPrefix(), "ns");
  ASSERT_EQ(reader->GetQualifiedName(), "ns:objC");
  ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns");
  ASSERT_TRUE(reader->IsEmptyElement());
  ASSERT_TRUE(reader->HasAttributes());
  ASSERT_FALSE(reader->HasValue());
  ASSERT_EQ(reader->GetAttributeCount(), (size_t)2);
  ASSERT_EQ(reader->GetAttribute(0), "value C1");
  ASSERT_EQ(reader->GetAttribute("ns:attr1"), "value C1");
  ASSERT_EQ(reader->GetAttribute("attr1", "http://www.example.org/ns"),
      "value C1");
  ASSERT_EQ(reader->GetAttribute(1), "value C2");
  ASSERT_EQ(reader->GetAttribute("ns:attr2"), "value C2");
  ASSERT_EQ(reader->GetAttribute("attr2", "http://www.example.org/ns"),
      "value C2");

  // Move to the ns:attr1 attribute.
  ASSERT_TRUE(reader->MoveToFirstAttribute());
  ASSERT_EQ(reader->GetDepth(), 2);
  ASSERT_EQ(reader->GetType(), XML_NODE_ATTRIBUTE);
  ASSERT_EQ(reader->GetLocalName(), "attr1");
  ASSERT_EQ(reader->GetPrefix(), "ns");
  ASSERT_EQ(reader->GetQualifiedName(), "ns:attr1");
  ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns");
  ASSERT_TRUE(reader->HasValue());
  ASSERT_FALSE(reader->IsEmptyElement());
  ASSERT_FALSE(reader->HasAttributes());
  ASSERT_EQ(reader->GetValue(), "value C1");

  // Move to the ns:attr2 attribute.
  ASSERT_TRUE(reader->MoveToNextAttribute());
  ASSERT_EQ(reader->GetDepth(), 2);
  ASSERT_EQ(reader->GetType(), XML_NODE_ATTRIBUTE);
  ASSERT_EQ(reader->GetLocalName(), "attr2");
  ASSERT_EQ(reader->GetPrefix(), "ns");
  ASSERT_EQ(reader->GetQualifiedName(), "ns:attr2");
  ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns");
  ASSERT_TRUE(reader->HasValue());
  ASSERT_FALSE(reader->IsEmptyElement());
  ASSERT_FALSE(reader->HasAttributes());
  ASSERT_EQ(reader->GetValue(), "value C2");

  // No more attributes.
  ASSERT_FALSE(reader->MoveToNextAttribute());

  // Return to the ns:objC element start node.
  ASSERT_TRUE(reader->MoveToCarryingElement());
  ASSERT_EQ(reader->GetDepth(), 1);
  ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_START);
  ASSERT_EQ(reader->GetQualifiedName(), "ns:objC");

  // Move to the ns:attr1 attribute.
  ASSERT_TRUE(reader->MoveToAttribute(0));
  ASSERT_EQ(reader->GetDepth(), 2);
  ASSERT_EQ(reader->GetType(), XML_NODE_ATTRIBUTE);
  ASSERT_EQ(reader->GetLocalName(), "attr1");
  ASSERT_EQ(reader->GetPrefix(), "ns");
  ASSERT_EQ(reader->GetQualifiedName(), "ns:attr1");
  ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns");
  ASSERT_TRUE(reader->HasValue());
  ASSERT_FALSE(reader->IsEmptyElement());
  ASSERT_FALSE(reader->HasAttributes());
  ASSERT_EQ(reader->GetValue(), "value C1");

  // Return to the ns:objC element start node.
  ASSERT_TRUE(reader->MoveToCarryingElement());
  ASSERT_EQ(reader->GetDepth(), 1);
  ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_START);
  ASSERT_EQ(reader->GetQualifiedName(), "ns:objC");

  // Move to the ns:attr2 attribute.
  ASSERT_TRUE(reader->MoveToAttribute("ns:attr2"));
  ASSERT_EQ(reader->GetDepth(), 2);
  ASSERT_EQ(reader->GetType(), XML_NODE_ATTRIBUTE);
  ASSERT_EQ(reader->GetLocalName(), "attr2");
  ASSERT_EQ(reader->GetPrefix(), "ns");
  ASSERT_EQ(reader->GetQualifiedName(), "ns:attr2");
  ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns");
  ASSERT_TRUE(reader->HasValue());
  ASSERT_FALSE(reader->IsEmptyElement());
  ASSERT_FALSE(reader->HasAttributes());
  ASSERT_EQ(reader->GetValue(), "value C2");

  // Move to the ns:attr1 attribute without returning to the ns:objC element.
  ASSERT_TRUE(reader->MoveToAttribute("attr1", "http://www.example.org/ns"));
  ASSERT_EQ(reader->GetDepth(), 2);
  ASSERT_EQ(reader->GetType(), XML_NODE_ATTRIBUTE);
  ASSERT_EQ(reader->GetLocalName(), "attr1");
  ASSERT_EQ(reader->GetPrefix(), "ns");
  ASSERT_EQ(reader->GetQualifiedName(), "ns:attr1");
  ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns");
  ASSERT_TRUE(reader->HasValue());
  ASSERT_FALSE(reader->IsEmptyElement());
  ASSERT_FALSE(reader->HasAttributes());
  ASSERT_EQ(reader->GetValue(), "value C1");

  // Move to the ns:objD element start node.
  ASSERT_TRUE(reader->MoveToNextNode());
  ASSERT_EQ(reader->GetDepth(), 1);
  ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_START);
  ASSERT_EQ(reader->GetLocalName(), "objD");
  ASSERT_EQ(reader->GetPrefix(), "ns");
  ASSERT_EQ(reader->GetQualifiedName(), "ns:objD");
  ASSERT_FALSE(reader->IsEmptyElement());
  ASSERT_FALSE(reader->HasAttributes());
  ASSERT_FALSE(reader->HasValue());

  // Move to the ns:objD element end node.
  ASSERT_TRUE(reader->MoveToNextNode());
  ASSERT_EQ(reader->GetDepth(), 1);
  ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_END);
  ASSERT_EQ(reader->GetLocalName(), "objD");
  ASSERT_EQ(reader->GetPrefix(), "ns");
  ASSERT_EQ(reader->GetQualifiedName(), "ns:objD");
  ASSERT_FALSE(reader->IsEmptyElement());
  ASSERT_FALSE(reader->HasAttributes());
  ASSERT_FALSE(reader->HasValue());

  // Move to the whitespace node without returning to the ns:objC element.
  ASSERT_TRUE(reader->MoveToNextNode());
  ASSERT_EQ(reader->GetType(), XML_NODE_WHITESPACE);

  // Move to ns:obj element ending node.
  ASSERT_TRUE(reader->MoveToNextNode());
  ASSERT_EQ(reader->GetDepth(), 0);
  ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_END);
  ASSERT_EQ(reader->GetLocalName(), "obj");
  ASSERT_EQ(reader->GetPrefix(), "ns");
  ASSERT_EQ(reader->GetQualifiedName(), "ns:obj");
  ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns");
  ASSERT_FALSE(reader->IsEmptyElement());
  ASSERT_TRUE(reader->HasAttributes());
  ASSERT_FALSE(reader->HasValue());
  // Strangely, the end node will report if the starting node has attributes
  // but will not provide access to them.
  ASSERT_TRUE(reader->HasAttributes());
  ASSERT_EQ(reader->GetAttributeCount(), (size_t)0);

  // And we're done.
  ASSERT_FALSE(reader->MoveToNextNode());

  ASSERT_TRUE(reader->Close());
}

// Test XML read error handling.
TEST(XmlReaderTest, ReadError) {
  char test_str[] =
    "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
    "<!ATTRIBUTE foo bar>\n";

  // Create the stream reader.
  CefRefPtr<CefStreamReader> stream(
      CefStreamReader::CreateForData(test_str, sizeof(test_str) - 1));
  ASSERT_TRUE(stream.get() != NULL);

  // Create the XML reader.
  CefRefPtr<CefXmlReader> reader(
      CefXmlReader::Create(stream, XML_ENCODING_NONE,
      "http://www.example.org/example.xml"));
  ASSERT_TRUE(reader.get() != NULL);

  // Move to the processing instruction node and generate parser error.
  ASSERT_FALSE(reader->MoveToNextNode());
  ASSERT_TRUE(reader->HasError());
}

// Test XmlObject load behavior.
TEST(XmlReaderTest, ObjectLoad) {
  // Create the stream reader.
  CefRefPtr<CefStreamReader> stream(
      CefStreamReader::CreateForData(g_test_xml, sizeof(g_test_xml) - 1));
  ASSERT_TRUE(stream.get() != NULL);

  // Create the XML reader.
  CefRefPtr<CefXmlObject> object(new CefXmlObject("object"));
  ASSERT_TRUE(object->Load(stream, XML_ENCODING_NONE,
      "http://www.example.org/example.xml", NULL));

  ASSERT_FALSE(object->HasAttributes());
  ASSERT_TRUE(object->HasChildren());
  ASSERT_EQ(object->GetChildCount(), (size_t)1);

  CefRefPtr<CefXmlObject> obj(object->FindChild("ns:obj"));
  ASSERT_TRUE(obj.get());
  ASSERT_TRUE(obj->HasChildren());
  ASSERT_EQ(obj->GetChildCount(), (size_t)4);

  CefRefPtr<CefXmlObject> obj_child(obj->FindChild("ns:objC"));
  ASSERT_TRUE(obj_child.get());
  ASSERT_EQ(obj_child->GetName(), "ns:objC");
  ASSERT_FALSE(obj_child->HasChildren());
  ASSERT_FALSE(obj_child->HasValue());
  ASSERT_TRUE(obj_child->HasAttributes());

  CefXmlObject::ObjectVector obj_children;
  ASSERT_EQ(obj->GetChildren(obj_children), (size_t)4);
  ASSERT_EQ(obj_children.size(), (size_t)4);

  CefXmlObject::ObjectVector::const_iterator it = obj_children.begin();
  for (int ct = 0; it != obj_children.end(); ++it, ++ct) {
    obj_child = *it;
    ASSERT_TRUE(obj_child.get());
    if (ct == 0) {
      // ns:objA
      ASSERT_EQ(obj_child->GetName(), "ns:objA");
      ASSERT_FALSE(obj_child->HasChildren());
      ASSERT_TRUE(obj_child->HasValue());
      ASSERT_FALSE(obj_child->HasAttributes());
      ASSERT_EQ(obj_child->GetValue(), "value A");
    } else if (ct == 1) {
      // ns:objB
      ASSERT_EQ(obj_child->GetName(), "ns:objB");
      ASSERT_TRUE(obj_child->HasChildren());
      ASSERT_FALSE(obj_child->HasValue());
      ASSERT_FALSE(obj_child->HasAttributes());
      ASSERT_EQ(obj_child->GetChildCount(), (size_t)4);
      obj_child = obj_child->FindChild("ns:objB_4");
      ASSERT_TRUE(obj_child.get());
      ASSERT_TRUE(obj_child->HasValue());
      ASSERT_EQ(obj_child->GetValue(),
          "this is mixed content EA Value");
    } else if (ct == 2) {
      // ns:objC
      ASSERT_EQ(obj_child->GetName(), "ns:objC");
      ASSERT_FALSE(obj_child->HasChildren());
      ASSERT_FALSE(obj_child->HasValue());
      ASSERT_TRUE(obj_child->HasAttributes());

      CefXmlObject::AttributeMap attribs;
      ASSERT_EQ(obj_child->GetAttributes(attribs), (size_t)2);
      ASSERT_EQ(attribs.size(), (size_t)2);
      ASSERT_EQ(attribs["ns:attr1"], "value C1");
      ASSERT_EQ(attribs["ns:attr2"], "value C2");

      ASSERT_EQ(obj_child->GetAttributeCount(), (size_t)2);
      ASSERT_TRUE(obj_child->HasAttribute("ns:attr1"));
      ASSERT_EQ(obj_child->GetAttributeValue("ns:attr1"), "value C1");
      ASSERT_TRUE(obj_child->HasAttribute("ns:attr2"));
      ASSERT_EQ(obj_child->GetAttributeValue("ns:attr2"), "value C2");
    } else if (ct == 3) {
      // ns:objD
      ASSERT_EQ(obj_child->GetName(), "ns:objD");
      ASSERT_FALSE(obj_child->HasChildren());
      ASSERT_FALSE(obj_child->HasValue());
      ASSERT_FALSE(obj_child->HasAttributes());
    }
  }
}

// Test XmlObject load error handling behavior.
TEST(XmlReaderTest, ObjectLoadError) {
  // Test start/end tag mismatch error.
  {
    char error_xml[] = "<obj>\n<foo>\n</obj>\n</foo>";

    // Create the stream reader.
    CefRefPtr<CefStreamReader> stream(
        CefStreamReader::CreateForData(error_xml, sizeof(error_xml) - 1));
    ASSERT_TRUE(stream.get() != NULL);

    CefString error_str;

    // Create the XML reader.
    CefRefPtr<CefXmlObject> object(new CefXmlObject("object"));
    ASSERT_FALSE(object->Load(stream, XML_ENCODING_NONE,
        "http://www.example.org/example.xml", &error_str));
    ASSERT_EQ(error_str,
        "Opening and ending tag mismatch: foo line 2 and obj, line 3");
  }

  // Test value following child error.
  {
    char error_xml[] = "<obj>\n<foo>\n</foo>disallowed value\n</obj>";

    // Create the stream reader.
    CefRefPtr<CefStreamReader> stream(
        CefStreamReader::CreateForData(error_xml, sizeof(error_xml) - 1));
    ASSERT_TRUE(stream.get() != NULL);

    CefString error_str;

    // Create the XML reader.
    CefRefPtr<CefXmlObject> object(new CefXmlObject("object"));
    ASSERT_FALSE(object->Load(stream, XML_ENCODING_NONE,
        "http://www.example.org/example.xml", &error_str));
    ASSERT_EQ(error_str,
        "Value following child element, line 4");
  }
}


text:
package org.apache.flink.runtime.taskexecutor.slot;

import org.apache.flink.api.common.JobID;
import org.apache.flink.runtime.clusterframework.types.AllocationID;
import org.apache.flink.runtime.clusterframework.types.ResourceProfile;
import org.apache.flink.runtime.clusterframework.types.SlotID;

import java.util.Objects;

/** Model to save local slot allocation info. */
public class SlotAllocationSnapshot implements java.io.Serializable {

    private static final long serialVersionUID = 1L;

    private final SlotID slotID;
    private final JobID jobId;
    private final String jobTargetAddress;
    private final AllocationID allocationId;
    private final ResourceProfile resourceProfile;

    public SlotAllocationSnapshot(
            SlotID slotID,
            JobID jobId,
            String jobTargetAddress,
            AllocationID allocationId,
            ResourceProfile resourceProfile) {
        this.slotID = slotID;
        this.jobId = jobId;
        this.jobTargetAddress = jobTargetAddress;
        this.allocationId = allocationId;
        this.resourceProfile = resourceProfile;
    }

    public SlotID getSlotID() {
        return slotID;
    }

    public JobID getJobId() {
        return jobId;
    }

    public String getJobTargetAddress() {
        return jobTargetAddress;
    }

    public AllocationID getAllocationId() {
        return allocationId;
    }

    public ResourceProfile getResourceProfile() {
        return resourceProfile;
    }

    public int getSlotIndex() {
        return slotID.getSlotNumber();
    }

    @Override
    public String toString() {
        return "SlotAllocationSnapshot{"
                + "slotID="
                + slotID
                + ", jobId="
                + jobId
                + ", jobTargetAddress='"
                + jobTargetAddress
                + '\''
                + ", allocationId="
                + allocationId
                + ", resourceProfile="
                + resourceProfile
                + '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        SlotAllocationSnapshot that = (SlotAllocationSnapshot) o;
        return slotID.equals(that.slotID)
                && jobId.equals(that.jobId)
                && jobTargetAddress.equals(that.jobTargetAddress)
                && allocationId.equals(that.allocationId)
                && resourceProfile.equals(that.resourceProfile);
    }

    @Override
    public int hashCode() {
        return Objects.hash(slotID, jobId, jobTargetAddress, allocationId, resourceProfile);
    }
}


text:
package com.example.tests;

public class ContactData implements Comparable<ContactData>{
	private String firstName;
	private String lastName;
	private String address;
	private String homePhone;
	private String mobilePhone;
	private String officePhone;
	private String email;
	private String email2;
	private String bday;
	private String bmonth;
	private String byear;
	private String newGroup;
	private String address2;
	private String phone2;

	public ContactData(String firstName, String lastName, String address, String homePhone, String mobilePhone,
			String officePhone, String email, String email2, String bday, String bmonth, String byear, String newGroup,
			String address2, String phone2) {
		this.firstName = firstName;
		this.lastName = lastName;
		this.address = address;
		this.homePhone = homePhone;
		this.mobilePhone = mobilePhone;
		this.officePhone = officePhone;
		this.email = email;
		this.email2 = email2;
		this.bday = bday;
		this.bmonth = bmonth;
		this.byear = byear;
		this.newGroup = newGroup;
		this.address2 = address2;
		this.phone2 = phone2;
	}

	public ContactData(){
	}

	// -------------- getters

	public String getFirstName() {
		return firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public String getAddress() {
		return address;
	}

	public String getHomePhone() {
		return homePhone;
	}

	public String getMobilePhone() {
		return mobilePhone;
	}

	public String getOfficePhone() {
		return officePhone;
	}

	public String getEmail() {
		return email;
	}

	public String getEmail2() {
		return email2;
	}

	public String getBday() {
		return bday;
	}

	public String getBmonth() {
		return bmonth;
	}

	public String getByear() {
		return byear;
	}

	public String getNewGroup() {
		return newGroup;
	}

	public String getAddress2() {
		return address2;
	}

	public String getPhone2() {
		return phone2;
	}

	// ------------ setters

	public ContactData withFirstName(String firstName) {
		this.firstName = firstName;
		return this;
	}

	public ContactData withLastName(String lastName) {
		this.lastName = lastName;
		return this;
	}

	public ContactData withAddress(String address) {
		this.address = address;
		return this;
	}

	public ContactData withHomePhone(String homePhone) {
		this.homePhone = homePhone;
		return this;
	}

	public ContactData withMobilePhone(String mobilePhone) {
		this.mobilePhone = mobilePhone;
		return this;
	}

	public ContactData withOfficePhone(String officePhone) {
		this.officePhone = officePhone;
		return this;
	}

	public ContactData withEmail(String email) {
		this.email = email;
		return this;
	}

	public ContactData withEmail2(String email2) {
		this.email2 = email2;
		return this;
	}

	public ContactData withBday(String bday) {
		this.bday = bday;
		return this;
	}

	public ContactData withbmonth(String bmonth) {
		this.bmonth = bmonth;
		return this;
	}

	public ContactData withbyear(String byear) {
		this.byear = byear;
		return this;
	}

	public ContactData withNewGroup(String newGroup) {
		this.newGroup = newGroup;
		return this;
	}

	public ContactData withAddress2(String address2) {
		this.address2 = address2;
		return this;
	}

	public ContactData withPhone2(String phone2) {
		this.phone2 = phone2;
		return this;
	}

	@Override
	public int compareTo(ContactData other) {
		int compareTo = this.lastName.toLowerCase().compareTo(other.lastName.toLowerCase());
			if (compareTo == 0){
				return this.firstName.toLowerCase().compareTo(other.firstName.toLowerCase());
			} else {
				return compareTo;
			}
	}

	@Override
	public String toString() {
		return "Contact [" + firstName + " " + lastName + "]";
	}

	@Override
	public int hashCode() {
	//	final int prime = 31;
		int result = 1;
	//	result = prime * result + ((firstName == null) ? 0 : firstName.hashCode());
	//	result = prime * result + ((lastName == null) ? 0 : lastName.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		ContactData other = (ContactData) obj;
		if (firstName == null) {
			if (other.firstName != null)
				return false;
		} else if (!firstName.equals(other.firstName))
			return false;
		if (lastName == null) {
			if (other.lastName != null)
				return false;
		} else if (!lastName.equals(other.lastName))
			return false;
		return true;
	}
}


text:
using System;
using System.Collections.Generic;

namespace Frontenac.Blueprints.Util.Wrappers.Event.Listener
{
    /// <summary>
    ///     Event that fires when a vertex is added to a graph.
    /// </summary>
    public class VertexAddedEvent : IEvent
    {
        private readonly IVertex _vertex;

        public VertexAddedEvent(IVertex vertex)
        {
            if (vertex == null)
                throw new ArgumentNullException(nameof(vertex));

            _vertex = vertex;
        }

        public void FireEvent(IEnumerator<IGraphChangedListener> eventListeners)
        {
            EventContract.ValidateFireEvent(eventListeners);

            while (eventListeners.MoveNext())
            {
                eventListeners.Current.VertexAdded(_vertex);
            }
        }
    }
}


text:
package org.yaml.snakeyaml.immutable;

/**
 * No constructors with 1 argument. These immutable objects are not supported.
 */
public class Code3 {
    private final String name;
    private final Integer code;

    public Code3(String name, Integer code) {
        this.code = code;
        this.name = name;
    }

    public String getData() {
        return name + code;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof Code3) {
            Code3 code = (Code3) obj;
            return code.equals(code.code);
        } else {
            return false;
        }
    }

    @Override
    public int hashCode() {
        return code.hashCode();
    }

    @Override
    public String toString() {
        return "<Code3 data=" + getData() + ">";
    }
}


text:
/**
 * Created by Caciano on 2/27/2017.
 */

var mongoose = require("mongoose");
var Schema = mongoose.Schema;
mongoose.Promise = global.Promise;

var schema = new Schema
({
    imagePath: {type: String, required: true},
    title: {type: String, required: true},
    description: {type: String, required: true},
    price: {type: Number, required: true},
});

module.exports = mongoose.model("Product", schema);


text:
<?php

class SigninForm extends sfVoForm
{
  public function configure()
  {
    $this->setWidgets(array(
      'username' => new sfWidgetFormInputText(array()),
      'password' => new sfWidgetFormInputText(array('type' => 'password')),
      'remember' => new sfWidgetFormInputCheckbox(array(), array()),
    ));
	$this->widgetSchema->setLabels(array(
  	  'username'    => 'Email',
	  'password'    => sfContext::getInstance()->getI18N()->__('Password', array(), 'notices'),
	  'remember'    => sfContext::getInstance()->getI18N()->__('Recordar', array(), 'notices'),
	));
        $this->setValidators(array(
      'username'   => new sfValidatorEmail(array('required' => true), sfVoForm::getEmailMessages()),
      'password' => new sfValidatorPassword(array('required' => true), sfVoForm::getStringMessages()),
      'remember' => new sfValidatorBoolean(),
    ));

    //$this->validatorSchema->setPostValidator(new sfGuardValidatorUser(array(), sfVoForm::getUserMessages()));

    $this->widgetSchema->setNameFormat('signin[%s]');
  }

  public function addPostValidation() {
  	$this->validatorSchema->setPostValidator(new sfGuardValidatorUser(array(), sfVoForm::getUserMessages()));
  }
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Chung-kuo Ti Chen-chun, [Fungi of China] 762 (1963)

#### Original name
Xerotus nigrita Lév.

### Remarks
null


text:
<?xml version="1.0" encoding="UTF-8"?>

<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
-->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.apache.maven</groupId>
    <artifactId>maven</artifactId>
    <version>3.4.0-SNAPSHOT</version>
  </parent>

  <artifactId>maven-aether-provider</artifactId>

  <name>Maven Aether Provider</name>
  <description>Extensions to Aether for utilizing Maven POM and repository metadata.</description>

  <dependencies>
    <dependency>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-model</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-model-builder</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-repository-metadata</artifactId>
    </dependency>
    <dependency>
      <groupId>org.eclipse.aether</groupId>
      <artifactId>aether-api</artifactId>
    </dependency>
    <dependency>
      <groupId>org.eclipse.aether</groupId>
      <artifactId>aether-spi</artifactId>
    </dependency>
    <dependency>
      <groupId>org.eclipse.aether</groupId>
      <artifactId>aether-util</artifactId>
    </dependency>
    <dependency>
      <groupId>org.eclipse.aether</groupId>
      <artifactId>aether-impl</artifactId>
    </dependency>
    <dependency>
      <groupId>org.codehaus.plexus</groupId>
      <artifactId>plexus-component-annotations</artifactId>
    </dependency>
    <dependency>
      <groupId>org.codehaus.plexus</groupId>
      <artifactId>plexus-utils</artifactId>
    </dependency>
    <dependency>
      <groupId>org.eclipse.sisu</groupId>
      <artifactId>org.eclipse.sisu.plexus</artifactId>
    </dependency>
    <dependency>
      <groupId>com.google.inject</groupId>
      <artifactId>guice</artifactId>
      <classifier>no_aop</classifier>
      <optional>true</optional>
      <exclusions>
        <exclusion>
          <groupId>aopalliance</groupId>
          <artifactId>aopalliance</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
    </dependency>
    <!-- Testing -->
    <dependency>
      <groupId>org.eclipse.aether</groupId>
      <artifactId>aether-connector-basic</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.eclipse.aether</groupId>
      <artifactId>aether-transport-wagon</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.maven.wagon</groupId>
      <artifactId>wagon-file</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-core</artifactId>
      <version>1.10.19</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.codehaus.plexus</groupId>
        <artifactId>plexus-component-metadata</artifactId>
      </plugin>
    </plugins>
  </build>

</project>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>ovs all: IPv6ExtHdr Struct Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

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

ovs all

Main Page

Related Pages

Namespaces

Data Structures

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Data Structures

Data Structure Index

Class Hierarchy

Data Fields

Data Fields

IPv6ExtHdr Struct Reference

#include <NetProto.h>

Data Fields

UINT8 	nextHeader

UINT8 	hdrExtLen

UINT16 	optPad1

UINT32 	optPad2

Field Documentation

          UINT8 IPv6ExtHdr::hdrExtLen

          UINT8 IPv6ExtHdr::nextHeader

          UINT16 IPv6ExtHdr::optPad1

          UINT32 IPv6ExtHdr::optPad2

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

/home/vladn/git/ovs/datapath-windows/ovsext/NetProto.h

IPv6ExtHdr

Generated on Wed Sep 9 2015 19:08:08 for ovs all by

     1.8.9.1


text:
import numpy as np

import unittest
import paddle
import paddle.fluid as fluid
from paddle.fluid.dygraph.jit import declarative

def dyfunc_tensor_shape_1(x):
    x = fluid.dygraph.to_variable(x)
    res = fluid.layers.reshape(x, shape=x.shape)
    return res

def dyfunc_tensor_shape_2(x):
    x = paddle.to_tensor(x)
    shape = x.shape
    shape2 = shape
    res = paddle.reshape(x, shape2)
    return res

def dyfunc_tensor_shape_3(x):
    # Transform y.shape but run y.shape actually because y is not Tensor
    x = fluid.dygraph.to_variable(x)
    y = np.ones(5)
    res = fluid.layers.reshape(x, shape=y.shape)
    return res

def dyfunc_tensor_shape_4(x):
    x = fluid.dygraph.to_variable(x)
    res = fluid.layers.reshape(x, shape=(-1, x.shape[0], len(x.shape)))
    return res

def dyfunc_tensor_shape_5(x):
    # `res = fluid.layers.reshape(x, shape=(-1, s))` to
    # `res = fluid.layers.reshape(x, shape=(-1,
    #           paddle.jit.dy2static.convert_var_shape(x)[0]))`
    x = fluid.dygraph.to_variable(x)
    s = x.shape[0]
    res = fluid.layers.reshape(x, shape=(-1, s))
    return res

def dyfunc_tensor_shape_6(x):
    # `res = fluid.layers.reshape(x, shape=(-1, s))` to
    # `res = fluid.layers.reshape(x, shape=(-1,
    #           paddle.jit.dy2static.convert_var_shape(x)[0:]))`
    x = fluid.dygraph.to_variable(x)
    s = x.shape[0:]
    res = fluid.layers.reshape(x, shape=s)
    return res

def dyfunc_tuple_shape_1(x):
    x = paddle.to_tensor(x)
    a, b = x.shape
    res = paddle.reshape(x, shape=(b, a))
    return res

def dyfunc_tuple_shape_2(x):
    x = paddle.to_tensor(x)
    shape = x.shape
    a, b = shape
    res = paddle.reshape(x, shape=(b, a))
    return res

def dyfunc_tuple_shape_3(x):
    x = paddle.to_tensor(x)
    a, b = paddle.shape(x)
    res = paddle.reshape(x, shape=(b, a))
    return res

def dyfunc_paddle_shape_api(x):
    x = paddle.to_tensor(x)
    # paddle.shape will not be converted.
    a = paddle.shape(x)[0]
    # alias api will also not be converted.
    alias_old_api = paddle.fluid.layers
    b = alias_old_api.shape(x)[1]
    res = paddle.reshape(x, shape=(b, a))
    return res

def dyfunc_with_if_1(x):
    x = fluid.dygraph.to_variable(x)
    res = fluid.layers.reshape(x, [-1, 1])
    x_shape_0 = x.shape[0]
    if x_shape_0 < 1:
        # `res.shape[0]` is transformed into
        #   `paddle.jit.dy2static.convert_var_shape(res)[0]`
        if res.shape[0] > 1:
            res = fluid.layers.fill_constant(
                value=2, shape=x.shape, dtype="int32"
            )
        else:
            res = fluid.layers.fill_constant(
                value=3, shape=x.shape, dtype="int32"
            )
    return res

def dyfunc_with_if_2(x):
    x = fluid.dygraph.to_variable(x)
    # `len(x.shape)` will not be transformed because x.shape is not used by Paddle api.
    if len(x.shape) < 1:
        res = x
    else:
        res = fluid.layers.fill_constant(value=8, shape=x.shape, dtype="int32")

    return res

def dyfunc_with_for_1(x):
    x = fluid.dygraph.to_variable(x)
    res = fluid.layers.fill_constant(value=0, shape=[1], dtype="int32")
    # `x.shape[0]` is transformed into `paddle.jit.dy2static.convert_var_shape(x)[0]`
    for i in range(x.shape[0]):
        res += 1
    return res

def dyfunc_with_for_2(x):
    x = fluid.dygraph.to_variable(x)
    x_shape_0 = x.shape[0]
    res = fluid.layers.fill_constant(value=0, shape=[1], dtype="int32")

    # `x_shape_0` is transformed into `paddle.jit.dy2static.convert_var_shape(x)[0]`
    for i in range(x_shape_0):
        res += 1
    return res

def dyfunc_with_for_3(x):
    x = fluid.dygraph.to_variable(x)
    res = fluid.layers.fill_constant(value=0, shape=[1], dtype="int32")
    # `len(x.shape)` is not transformed.
    for i in range(len(x.shape)):
        res += 1

    return res

def dyfunc_with_while_1(x):
    x = fluid.dygraph.to_variable(x)
    res = fluid.layers.fill_constant(value=0, shape=[1], dtype="int32")
    # `x.shape[0]` is transformed into `paddle.jit.dy2static.convert_var_shape(x)[0]`
    i = 1
    while i < x.shape[0]:
        res += 1
        i = i + 2
    return res

def dyfunc_with_while_2(x):
    x = fluid.dygraph.to_variable(x)
    x_shape_0 = x.shape[0]
    res = fluid.layers.fill_constant(value=0, shape=[1], dtype="int32")
    i = 1
    # `x_shape_0` is transformed into `paddle.jit.dy2static.convert_var_shape(x)[0]`
    while i < x_shape_0:
        res += 1
        i = i + 2
    return res

def dyfunc_with_while_3(x):
    x = fluid.dygraph.to_variable(x)
    x_shape = x.shape
    res = fluid.layers.fill_constant(value=0, shape=[1], dtype="int32")
    i = 1

    # `len(x.shape)` is not transformed.
    while len(x_shape) > i:
        res += 1
        i += 1
    return res

def dyfunc_with_while_4(x):
    x = paddle.to_tensor(x)
    y = np.ones(5)
    y_shape_0 = y.shape[0]
    i = 1

    # Transform y_shape_0 but run y.shape[0] actually because y is not Tensor
    while y_shape_0 > i:
        x += 1
        i += 1
    return x

def dyfunc_change_shape_after_assign(x):
    x = paddle.to_tensor(x)
    a, b = x.shape
    x = paddle.reshape(x, shape=(-1, 1))
    res = paddle.reshape(x, shape=(b, a))
    return res

def dyfunc_len_paddle_shape():
    x = paddle.to_tensor([1, 2, 3])
    if len(paddle.shape(x)) > 0:
        print(x)

def dyfunc_dict_assign_shape():
    x = paddle.to_tensor([1, 2])
    a = {}
    a['shape'] = x.shape[0]

# 1. Basic tests without control flow
class TestTensorShapeBasic(unittest.TestCase):
    def setUp(self):
        self.input = np.ones(5).astype("int32")
        self.place = (
            fluid.CUDAPlace(0)
            if fluid.is_compiled_with_cuda()
            else fluid.CPUPlace()
        )
        self._set_input_spec()
        self._set_expected_op_num()
        self.init_test_func()

    def init_test_func(self):
        self.dygraph_func = dyfunc_tensor_shape_1

    def _set_input_spec(self):
        self.input_spec = [paddle.static.InputSpec(shape=[5], dtype="int32")]

    def _run(self, to_static):
        with fluid.dygraph.guard():
            if to_static:
                res = declarative(self.dygraph_func)(self.input).numpy()
            else:
                res = self.dygraph_func(self.input).numpy()
            return res

    def get_dygraph_output(self):
        return self._run(to_static=False)

    def get_static_output(self):
        return self._run(to_static=True)

    def test_transformed_static_result(self):
        static_res = self.get_static_output()
        dygraph_res = self.get_dygraph_output()
        np.testing.assert_allclose(dygraph_res, static_res, rtol=1e-05)

    def _set_expected_op_num(self):
        self.expected_op_num = 2
        self.expected_shape_op_num = 0
        self.expected_slice_op_num = 0

    def _compute_op_num(self, program):
        self.op_num = sum([len(block.ops) for block in program.blocks])
        self.shape_op_num = 0
        self.slice_op_num = 0

        for block in program.blocks:
            self.shape_op_num += len(
                [op for op in block.ops if op.type == "shape"]
            )
            self.slice_op_num += len(
                [op for op in block.ops if op.type == "slice"]
            )

    def test_op_num(self):
        static_layer = paddle.jit.to_static(self.dygraph_func, self.input_spec)
        program = static_layer.main_program
        self._compute_op_num(program)
        self.assertEqual(self.op_num, self.expected_op_num)
        self.assertEqual(self.shape_op_num, self.expected_shape_op_num)
        self.assertEqual(self.slice_op_num, self.expected_slice_op_num)

class TestTensorShapeBasic2(TestTensorShapeBasic):
    def init_test_func(self):
        self.dygraph_func = dyfunc_tensor_shape_2

    def _set_expected_op_num(self):
        self.expected_op_num = 1
        self.expected_shape_op_num = 0
        self.expected_slice_op_num = 0

class TestTensorShapeBasic3(TestTensorShapeBasic):
    def init_test_func(self):
        self.dygraph_func = dyfunc_tensor_shape_3

class TestTensorShapeBasic4(TestTensorShapeBasic):
    def init_test_func(self):
        self.dygraph_func = dyfunc_tensor_shape_4

class TestTensorShapeBasic5(TestTensorShapeBasic):
    def init_test_func(self):
        self.dygraph_func = dyfunc_tensor_shape_5

    def _set_expected_op_num(self):
        self.expected_op_num = 2
        self.expected_shape_op_num = 0
        self.expected_slice_op_num = 0

class TestTensorShapeBasic6(TestTensorShapeBasic):
    def init_test_func(self):
        self.dygraph_func = dyfunc_tensor_shape_6

    def _set_expected_op_num(self):
        self.expected_op_num = 2
        self.expected_shape_op_num = 0
        self.expected_slice_op_num = 0

class TestTupleShape1(TestTensorShapeBasic):
    def init_test_func(self):
        self.input = np.ones((5, 7)).astype("int32")
        self.input_spec = [
            paddle.static.InputSpec(shape=[-1, -1], dtype="int32")
        ]
        self.dygraph_func = dyfunc_tuple_shape_1

    def _set_expected_op_num(self):
        self.expected_op_num = 4
        self.expected_shape_op_num = 1
        self.expected_slice_op_num = 2

class TestTupleShape2(TestTensorShapeBasic):
    def init_test_func(self):
        self.input = np.ones((5, 7)).astype("int32")
        self.input_spec = [
            paddle.static.InputSpec(shape=[-1, 7], dtype="int32")
        ]
        self.dygraph_func = dyfunc_tuple_shape_2

    def _set_expected_op_num(self):
        self.expected_op_num = 4
        self.expected_shape_op_num = 1
        self.expected_slice_op_num = 1

class TestTupleShape3(TestTensorShapeBasic):
    def init_test_func(self):
        self.input = np.ones((5, 7)).astype("int32")
        self.input_spec = [paddle.static.InputSpec(shape=[5, 7], dtype="int32")]
        self.dygraph_func = dyfunc_tuple_shape_3

    def _set_expected_op_num(self):
        self.expected_op_num = 4
        self.expected_shape_op_num = 1
        self.expected_slice_op_num = 2

class TestPaddleShapeApi(TestTensorShapeBasic):
    def init_test_func(self):
        self.input = np.ones((5, 7)).astype("int32")
        self.input_spec = [paddle.static.InputSpec(shape=[5, 7], dtype="int32")]
        self.dygraph_func = dyfunc_paddle_shape_api

    def _set_expected_op_num(self):
        self.expected_op_num = 5
        self.expected_shape_op_num = 2
        self.expected_slice_op_num = 2

# 2. Tests with control flow if
class TestTensorShapeInIf1(TestTensorShapeBasic):
    def init_test_func(self):
        self.dygraph_func = dyfunc_with_if_1

    def _set_expected_op_num(self):
        self.expected_op_num = 2
        self.expected_shape_op_num = 0
        self.expected_slice_op_num = 0

class TestTensorShapeInIf2(TestTensorShapeBasic):
    def init_test_func(self):
        self.dygraph_func = dyfunc_with_if_2

    def _set_expected_op_num(self):
        self.expected_op_num = 2
        self.expected_shape_op_num = 0
        self.expected_slice_op_num = 0

# 3. Tests with control flow for loop
class TestTensorShapeInFor1(TestTensorShapeBasic):
    def init_test_func(self):
        self.dygraph_func = dyfunc_with_for_1

    def _set_expected_op_num(self):
        self.expected_op_num = 7
        self.expected_shape_op_num = 0
        self.expected_slice_op_num = 0

class TestTensorShapeInFor2(TestTensorShapeInFor1):
    def init_test_func(self):
        self.dygraph_func = dyfunc_with_for_2

    def _set_expected_op_num(self):
        self.expected_op_num = 7
        self.expected_shape_op_num = 0
        self.expected_slice_op_num = 0

class TestTensorShapeInFor3(TestTensorShapeInFor1):
    def init_test_func(self):
        self.dygraph_func = dyfunc_with_for_3

    def _set_expected_op_num(self):
        self.expected_op_num = 3
        self.expected_shape_op_num = 0
        self.expected_slice_op_num = 0

# 4. Tests with control flow while loop
class TestTensorShapeInWhile1(TestTensorShapeInFor1):
    def init_test_func(self):
        self.dygraph_func = dyfunc_with_while_1

    def _set_expected_op_num(self):
        self.expected_op_num = 4
        self.expected_shape_op_num = 0
        self.expected_slice_op_num = 0

class TestTensorShapeInWhile2(TestTensorShapeInFor1):
    def init_test_func(self):
        self.dygraph_func = dyfunc_with_while_2

    def _set_expected_op_num(self):
        self.expected_op_num = 4
        self.expected_shape_op_num = 0
        self.expected_slice_op_num = 0

class TestTensorShapeInWhile3(TestTensorShapeBasic):
    def init_test_func(self):
        self.dygraph_func = dyfunc_with_while_3

    def _set_expected_op_num(self):
        self.expected_op_num = 2
        self.expected_shape_op_num = 0
        self.expected_slice_op_num = 0

class TestTensorShapeInWhile4(TestTensorShapeBasic):
    def init_test_func(self):
        self.dygraph_func = dyfunc_with_while_4

    def _set_expected_op_num(self):
        self.expected_op_num = 4
        self.expected_shape_op_num = 0
        self.expected_slice_op_num = 0

# 5. Test op num for negetive dim
class TestOpNumBasicWithTensorShape(unittest.TestCase):
    def setUp(self):
        self._set_input_spec()
        self._set_test_func()
        self._set_expected_op_num()

    def _set_input_spec(self):
        self.input_spec = [
            paddle.static.InputSpec(shape=[-1, 5], dtype="int32")
        ]

    def _set_test_func(self):
        self.dygraph_func = dyfunc_tensor_shape_1

    def _set_expected_op_num(self):
        self.expected_op_num = 5
        self.expected_shape_op_num = 1
        self.expected_slice_op_num = 1

    def _compute_op_num(self, program):
        self.op_num = sum([len(block.ops) for block in program.blocks])
        self.shape_op_num = 0
        self.slice_op_num = 0

        for block in program.blocks:
            self.shape_op_num += len(
                [op for op in block.ops if op.type == "shape"]
            )
            self.slice_op_num += len(
                [op for op in block.ops if op.type == "slice"]
            )

    def test_op_num(self):
        static_layer = paddle.jit.to_static(self.dygraph_func, self.input_spec)
        program = static_layer.main_program

        self._compute_op_num(program)
        self.assertEqual(self.op_num, self.expected_op_num)
        self.assertEqual(self.shape_op_num, self.expected_shape_op_num)
        self.assertEqual(self.slice_op_num, self.expected_slice_op_num)

class TestOpNumBasicWithTensorShape4(TestOpNumBasicWithTensorShape):
    def _set_test_func(self):
        self.dygraph_func = dyfunc_tensor_shape_4

    def _set_expected_op_num(self):
        self.expected_op_num = 8
        self.expected_shape_op_num = 2
        self.expected_slice_op_num = 2

class TestOpNumWithTensorShapeTuple1(TestOpNumBasicWithTensorShape):
    def _set_test_func(self):
        self.dygraph_func = dyfunc_tuple_shape_1

    def _set_expected_op_num(self):
        self.expected_op_num = 4
        self.expected_shape_op_num = 1
        self.expected_slice_op_num = 1

class TestOpNumWithTensorShapeInIf1(TestOpNumBasicWithTensorShape):
    def _set_test_func(self):
        self.dygraph_func = dyfunc_with_if_1

    def _set_expected_op_num(self):
        self.expected_op_num = 32
        self.expected_shape_op_num = 4
        self.expected_slice_op_num = 4

class TestOpNumWithTensorShapeInFor1(TestOpNumBasicWithTensorShape):
    def _set_test_func(self):
        self.dygraph_func = dyfunc_with_for_1

    def _set_expected_op_num(self):
        self.expected_op_num = 29
        self.expected_shape_op_num = 2
        self.expected_slice_op_num = 3

class TestOpNumWithTensorShapeInWhile1(TestOpNumBasicWithTensorShape):
    def _set_test_func(self):
        self.dygraph_func = dyfunc_with_while_1

    def _set_expected_op_num(self):
        self.expected_op_num = 21
        self.expected_shape_op_num = 3
        self.expected_slice_op_num = 3

class TestChangeShapeAfterAssign(TestTensorShapeBasic):
    def init_test_func(self):
        self.input = np.ones((2, 3)).astype("int32")
        self.input_spec = [
            paddle.static.InputSpec(shape=[-1, 3], dtype="int32")
        ]
        self.dygraph_func = dyfunc_change_shape_after_assign

    def _set_expected_op_num(self):
        self.expected_op_num = 5
        self.expected_shape_op_num = 1
        self.expected_slice_op_num = 1

def dyfunc_with_static_convert_var_shape(x):
    # Note: this will create `batch_size__static_convert_var_shape_suffix_0` firstly.
    batch_size = x.shape[0]
    if len(x.shape) < 1:
        res = x
    else:
        # Test for correctly to find `batch_size__static_convert_var_shape_suffix_0` in
        # deeply nested scope.
        res = fluid.layers.fill_constant(
            value=8, shape=[batch_size], dtype="int32"
        )

    return res

class TestFindStatiConvertVarShapeSuffixVar(unittest.TestCase):
    def test(self):
        x_spec = paddle.static.InputSpec(shape=[None, 10])
        func = paddle.jit.to_static(dyfunc_with_if_2, input_spec=[x_spec])
        # Call this function to trigger program translation.
        func.concrete_program

if __name__ == '__main__':
    unittest.main()