text:
package ch.difty.scipamato.core.entity.search;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import ch.difty.scipamato.common.entity.FieldEnumType;
import ch.difty.scipamato.core.entity.IdScipamatoEntity;
import ch.difty.scipamato.core.entity.PaperSlimFilter;

/**
 * The {@link SearchOrder} is the entry point for the entire (complex) search,
 * containing one or combining several {@link SearchCondition}s
 *
 * @author u.joss
 */
@Getter
@Setter
@EqualsAndHashCode(callSuper = true, exclude = { "showExcluded" })
public class SearchOrder extends IdScipamatoEntity<Long> implements PaperSlimFilter {

    private static final long serialVersionUID = 1L;

    static final int    DISPL_VALUE_THRESHOLD = 100;
    static final String DISPL_VALUE_ELLIPSIS  = "...";
    static final int    DISPL_VALUE_CUTOFF    = DISPL_VALUE_THRESHOLD - DISPL_VALUE_ELLIPSIS.length();

    private static final String JOIN_DELIMITER = "; OR ";

    private String  name;
    private int     owner;
    private boolean global;

    private final List<SearchCondition> searchConditions = new ArrayList<>();
    private final List<Long>            excludedPaperIds = new ArrayList<>();

    // this will not get persisted
    private boolean showExcluded = false;

    public enum SearchOrderFields implements FieldEnumType {
        NAME("name"),
        OWNER("owner"),
        GLOBAL("global"),
        CONDITIONS("searchConditions"),
        EXCLUDED_PAPER_IDS("excludedPaperIds"),
        SHOW_EXCLUDED("showExcluded");

        private final String name;

        SearchOrderFields(final String name) {
            this.name = name;
        }

        @NotNull
        @Override
        public String getFieldName() {
            return name;
        }
    }

    public SearchOrder() {
        // default constructor
    }

    public SearchOrder(@Nullable final List<SearchCondition> searchConditions) {
        setSearchConditions(searchConditions);
    }

    public SearchOrder(final long id, @Nullable final String name, final int owner, final boolean global,
        @Nullable final List<SearchCondition> searchConditions, @Nullable final List<Long> excludedPaperIds) {
        setId(id);
        setName(name);
        setOwner(owner);
        setGlobal(global);
        setSearchConditions(searchConditions);
        setExcludedPaperIds(excludedPaperIds);
    }

    private void setSearchConditions(final List<SearchCondition> searchConditions) {
        if (searchConditions != null) {
            this.searchConditions.clear();
            this.searchConditions.addAll(searchConditions);
        }
    }

    /**
     * Add a new instance of a {@link SearchCondition}.
     *
     * @param searchCondition
     *     to be added.
     */
    public void add(@Nullable final SearchCondition searchCondition) {
        if (searchCondition != null && !searchConditions.contains(searchCondition))
            searchConditions.add(searchCondition);
    }

    /**
     * Removes the specified {@link SearchCondition} - if not null and present.
     *
     * @param searchCondition
     *     the condition to remove
     */
    public void remove(@Nullable final SearchCondition searchCondition) {
        if (searchCondition != null) {
            searchConditions.remove(searchCondition);
        }
    }

    @NotNull
    public List<Long> getExcludedPaperIds() {
        return excludedPaperIds;
    }

    public void setExcludedPaperIds(@Nullable final List<Long> excludedPaperIds) {
        if (excludedPaperIds != null) {
            this.excludedPaperIds.clear();
            this.excludedPaperIds.addAll(excludedPaperIds);
        }
    }

    /**
     * Add a new paper id for exclusion.
     *
     * @param paperId
     *     paper id to be added to exclusions
     */
    public void addExclusionOfPaperWithId(final long paperId) {
        if (!excludedPaperIds.contains(paperId))
            excludedPaperIds.add(paperId);
    }

    /**
     * Removes the specified paperId from the list of exclusions.
     *
     * @param paperId
     *     the id to remove from exclusions
     */
    public void removeExclusionOfPaperWithId(final long paperId) {
        excludedPaperIds.remove(paperId);
    }

    public String getFullDisplayValue() {
        final StringBuilder sb = part1(false);
        part2(sb);
        return sb.toString();
    }

    @NotNull
    private StringBuilder part1(final boolean truncate) {
        final StringBuilder sb = new StringBuilder();
        if (getName() != null) {
            sb
                .append(getName())
                .append(": ");
        }
        sb.append(searchConditions
            .stream()
            .map(SearchCondition::getDisplayValue)
            .collect(Collectors.joining(JOIN_DELIMITER)));
        if (sb.length() == 0)
            sb.append("--");

        if (truncate && sb.length() > DISPL_VALUE_THRESHOLD) {
            sb.delete(DISPL_VALUE_CUTOFF, sb.length());
            sb.append(DISPL_VALUE_ELLIPSIS);
        }
        return sb;
    }

    private void part2(final StringBuilder sb) {
        sb
            .append(" (")
            .append(getId())
            .append(")");
        if (isGlobal())
            sb.append("*");
    }

    @NotNull
    public String getDisplayValue() {
        final StringBuilder sb = part1(true);
        part2(sb);
        return sb.toString();
    }
}


text:
#ifndef __ASM_BUGS_H
#define __ASM_BUGS_H

#define check_bugs() cpu_check_bugs()

#endif

redpajama_set_name: RedPajamaGithub


text:
'use strict';

module.exports = function (app) {
  // User Routes
  var users = require('../controllers/users.server.controller');
  var machine = require('../controllers/machine.server.controller');

  // Setting up the users profile api
  app.route('/api/users/me').get(users.me);
  app.route('/api/users').put(users.update);
  app.route('/api/users/accounts').delete(users.removeOAuthProvider);
  app.route('/api/users/password').post(users.changePassword);
  app.route('/api/users/picture').post(users.changeProfilePicture);

  app.route('/api/machines/getUserMachine/:userId').get(machine.getUserMachines);

  app.route('/api/machines/getMachines/:machineId').get(machine.getMachines);
  app.route('/api/machines/getTableData/:tbMachineId').get(machine.getTableData);
  app.route('/api/machinesData/getDataByYear/:dIdYear').get(machine.getDataByYear);
  app.route('/api/machinesData/getDataByMonth/:dIdMonth/:year').get(machine.getDataByMonth);
  app.route('/api/machinesData/getDataByDay/:dIdDay/:year/:month').get(machine.getDataByDay);
  app.route('/api/machinesData/getDataByHour/:dIdHour/:year/:month/:day').get(machine.getDataByHour);
  app.route('/api/machinesData/getAvgFlowByHour/:dIdFlow/:year/:month/:day').get(machine.getAvgFlowByHour);

  app.route('/api/machinesData/getAverageWaterIn/:dIdIn').get(machine.getAverageWaterIn);
  app.route('/api/machinesData/getAverageWaterOut/:dIdOut').get(machine.getAverageWaterOut);
  app.route('/api/machinesData/getAverageWaterDelTemp/:dIdDel').get(machine.getAverageWaterDelTemp);

  app.route('/api/machinesData/getAverageFlowLive/:dIdInLive').get(machine.getAverageFlowLive);
  app.route('/api/machinesData/getAveragePowerLive/:dIdOutLive').get(machine.getAveragePowerLive);
  app.route('/api/machinesData/getAverageWaterDelTempLive/:dIdDelLive').get(machine.getAverageWaterDelTempLive);

  app.route('/api/machinesData/getGaugeValue/:dIdGauge').get(machine.getGaugeValue);

  app.route('/api/machinesData/:dId/:fromDate/:toDate').get(machine.getToFromDataTable);

  //app.route('/api/reportHistoric/send').post(machine.sendReport);

  app.route('/api/machinesData/liveData/:idLive').get(machine.getLiveData);

  // Finish by binding the user middleware
  app.param('idLive',machine.getLiveData);
  app.param('dIdGauge',machine.getGaugeValue);
  app.param('userId', machine.getUserMachines);
  app.param('tbMachineId', machine.getTableData);
  app.param('machineId', machine.getMachines);
  app.param('dIdYear', machine.getDataByYear);
  app.param('dIdMonth', machine.getDataByMonth);
  app.param('year', machine.getDataByMonth);
  app.param('dIdDay', machine.getDataByDay);
  app.param('dIdHour', machine.getDataByHour);
  app.param('dIdFlow', machine.getAvgFlowByHour);

  app.param('dIdIn', machine.getAverageWaterIn);
  app.param('dIdOut', machine.getAverageWaterOut);
  app.param('dIdDel', machine.getAverageWaterDelTemp);

  app.param('dIdInLive', machine.getAverageFlowLive);
  app.param('dIdOutLive', machine.getAveragePowerLive);
  app.param('dIdDelLive', machine.getAverageWaterDelTempLive);
};


text:
namespace cms
{

	namespace test
	{

		class CommandParserTests : public ::testing::Test
		{

		public:
			void SetUp()
			{
				dealerManager = DealerManagerPtr(new DealerManager());
				parser = boost::shared_ptr<CommandParser>(new CommandParser(dealerManager));
			}

			void TearDown()
			{
				parser = boost::shared_ptr<CommandParser>();
				dealerManager = DealerManagerPtr();
			}

		protected:
			DealerManagerPtr dealerManager;
			boost::shared_ptr<CommandParser> parser;

		};

		TEST_F(CommandParserTests, ParseInvalidCommands)
		{
			// Empty string
			EXPECT_THROW(parser->parse(""), ParseException);
			// String which exceeds maximum length
			std::string validCommandButTooLong =
			"DB LIST " + std::string(MAX_COMMAND_LENGTH, ' ');
			EXPECT_THROW(parser->parse(validCommandButTooLong), ParseException);
			// Gibberish
			EXPECT_THROW(parser->parse("sotu58h7=h3jfhgr"), ParseException);
			// Just dealer ID
			EXPECT_THROW(parser->parse("RBS"), ParseException);
			// Dealer ID and command type (invalid dealer)
			EXPECT_THROW(parser->parse("NOTREALDEALER LIST"), ParseException);
			// Dealer ID and command type (invalid type)
			EXPECT_THROW(parser->parse("RBS HAHA"), ParseException);
			// Dealer ID and command type (valid type, not enough arguments)
			// NOTE: CHECK command should have at least one argument
			EXPECT_THROW(parser->parse("RBS CHECK"), ParseException);
			// NOTE: POST command should have at least four arguments
			EXPECT_THROW(parser->parse("RBS POST BUY GOLD"), ParseException);
		}

		TEST_F(CommandParserTests, ParseAggress)
		{
			CommandPtr command;
			boost::shared_ptr<AggressCommand> aggressCommand;

			// One aggression (with invalid order ID)
			EXPECT_THROW(parser->parse("RBS AGGRESS FOO 200"), CMSException);
			// One aggression (with invalid amount to buy/sell)
			EXPECT_THROW(parser->parse("RBS AGGRESS 1 -200"), CMSException);
			EXPECT_THROW(parser->parse("RBS AGGRESS 0 0"), CMSException);
			EXPECT_THROW(parser->parse("RBS AGGRESS 0 FOO"), CMSException);
			// One aggression (valid)
			command = parser->parse("RBS AGGRESS 1 200");
			EXPECT_EQ(command->type(), "AGGRESS");
			EXPECT_EQ(command->dealerID(), "RBS");
			aggressCommand = boost::dynamic_pointer_cast<AggressCommand>(command);
			ASSERT_FALSE(aggressCommand == boost::shared_ptr<AggressCommand>());
			ASSERT_EQ(1, aggressCommand->allOrdersToAggress().size());
			EXPECT_EQ(1, aggressCommand->allOrdersToAggress()[0].first);
			EXPECT_EQ(200, aggressCommand->allOrdersToAggress()[0].second);
			// Odd number of arguments (trailing argument)
			// The trailing argument should just be ignored!
			command = parser->parse("RBS AGGRESS 1 200 3");
			EXPECT_EQ(command->type(), "AGGRESS");
			EXPECT_EQ(command->dealerID(), "RBS");
			aggressCommand = boost::dynamic_pointer_cast<AggressCommand>(command);
			ASSERT_FALSE(aggressCommand == boost::shared_ptr<AggressCommand>());
			ASSERT_EQ(1, aggressCommand->allOrdersToAggress().size());
			EXPECT_EQ(1, aggressCommand->allOrdersToAggress()[0].first);
			EXPECT_EQ(200, aggressCommand->allOrdersToAggress()[0].second);
			// Multiple aggressions
			command = parser->parse("RBS AGGRESS 1 200 3 5000");
			EXPECT_EQ(command->type(), "AGGRESS");
			EXPECT_EQ(command->dealerID(), "RBS");
			aggressCommand = boost::dynamic_pointer_cast<AggressCommand>(command);
			ASSERT_FALSE(aggressCommand == boost::shared_ptr<AggressCommand>());
			ASSERT_EQ(2, aggressCommand->allOrdersToAggress().size());
			EXPECT_EQ(1, aggressCommand->allOrdersToAggress()[0].first);
			EXPECT_EQ(200, aggressCommand->allOrdersToAggress()[0].second);
			EXPECT_EQ(3, aggressCommand->allOrdersToAggress()[1].first);
			EXPECT_EQ(5000, aggressCommand->allOrdersToAggress()[1].second);
		}

		TEST_F(CommandParserTests, ParseCheck)
		{
			// Non-integer argument
			EXPECT_THROW(parser->parse("RBS CHECK NDFFGH"), CMSException);
			// Integer argument
			CommandPtr command = parser->parse("RBS CHECK 2");
			EXPECT_EQ("RBS", command->dealerID());
			EXPECT_EQ("CHECK", command->type());
			boost::shared_ptr<CheckCommand> checkCommand =
				boost::dynamic_pointer_cast<CheckCommand>(command);
			// Ensure downcast was successful
			ASSERT_FALSE(checkCommand == boost::shared_ptr<CheckCommand>());
			EXPECT_EQ(2, checkCommand->orderID());
		}

		TEST_F(CommandParserTests, ParseList)
		{
			CommandPtr command;
			boost::shared_ptr<ListCommand> listCommand;

			// No arguments
			command = parser->parse("RBS LIST");
			EXPECT_EQ("RBS", command->dealerID());
			EXPECT_EQ("LIST", command->type());
			listCommand = boost::dynamic_pointer_cast<ListCommand>(command);
			ASSERT_FALSE(listCommand == boost::shared_ptr<ListCommand>());
			EXPECT_EQ(COMMODITY_UNKNOWN, listCommand->commodityFilter());
			EXPECT_EQ("", listCommand->dealerIDFilter());

			// Commodity filter (unknown commodity)
			EXPECT_THROW(parser->parse("RBS LIST HAHA"), CMSException);

			// Commodity filter (valid commodity)
			command = parser->parse("RBS LIST GOLD");
			EXPECT_EQ("RBS", command->dealerID());
			EXPECT_EQ("LIST", command->type());
			listCommand = boost::dynamic_pointer_cast<ListCommand>(command);
			ASSERT_FALSE(listCommand == boost::shared_ptr<ListCommand>());
			EXPECT_EQ(COMMODITY_GOLD, listCommand->commodityFilter());
			EXPECT_EQ("", listCommand->dealerIDFilter());

			// Commodity + dealer filter (unknown dealer)
			EXPECT_THROW(parser->parse("RBS LIST GOLD HAHA"), CMSException);

			// Commodity + dealer filter (valid dealer)
			command = parser->parse("RBS LIST GOLD DB");
			EXPECT_EQ("RBS", command->dealerID());
			EXPECT_EQ("LIST", command->type());
			listCommand = boost::dynamic_pointer_cast<ListCommand>(command);
			ASSERT_FALSE(listCommand == boost::shared_ptr<ListCommand>());
			EXPECT_EQ(COMMODITY_GOLD, listCommand->commodityFilter());
			EXPECT_EQ("DB", listCommand->dealerIDFilter());
		}

		TEST_F(CommandParserTests, ParsePost)
		{
			// Invalid side
			EXPECT_THROW(parser->parse("RBS POST FOO GOLD 2000 44.4"), CMSException);
			// Invalid commodity
			EXPECT_THROW(parser->parse("RBS POST BUY FOO 2000 44.4"), CMSException);
			// Invalid amount
			EXPECT_THROW(parser->parse("RBS POST BUY GOLD -2000 44.4"), CMSException);
			EXPECT_THROW(parser->parse("RBS POST BUY GOLD 0 44.4"), CMSException);
			EXPECT_THROW(parser->parse("RBS POST BUY GOLD FOO 44.4"), CMSException);
			// Invalid price
			EXPECT_THROW(parser->parse("RBS POST BUY GOLD 2000 44.4.4"), CMSException);
			EXPECT_THROW(parser->parse("RBS POST BUY GOLD 2000 FOO"), CMSException);

			// Valid arguments
			CommandPtr command = parser->parse("RBS POST BUY GOLD 2000 44.4");
			EXPECT_EQ("RBS", command->dealerID());
			EXPECT_EQ("POST", command->type());
			boost::shared_ptr<PostCommand> postCommand =
				boost::dynamic_pointer_cast<PostCommand>(command);
			const Order& orderToPost = postCommand->order();
			EXPECT_EQ(SIDE_BUY, orderToPost.side());
			EXPECT_EQ(COMMODITY_GOLD, orderToPost.commodity());
			EXPECT_EQ(2000, orderToPost.amount());
			EXPECT_EQ(44.4, orderToPost.price());
		}

		TEST_F(CommandParserTests, ParseRevoke)
		{
			// Non-integer argument
			EXPECT_THROW(parser->parse("RBS REVOKE NDFFGH"), CMSException);
			// Integer argument
			CommandPtr command = parser->parse("RBS REVOKE 2");
			EXPECT_EQ("RBS", command->dealerID());
			EXPECT_EQ("REVOKE", command->type());
			boost::shared_ptr<RevokeCommand> revokeCommand =
				boost::dynamic_pointer_cast<RevokeCommand>(command);
			// Ensure downcast was successful
			ASSERT_FALSE(revokeCommand == boost::shared_ptr<RevokeCommand>());
			EXPECT_EQ(2, revokeCommand->orderID());
		}

	}

}

#endif


text:
Homework: Conditional statements
================================

### [Submit homework in bgcoder](http://bgcoder.com/Contests/358/JavaScript-Fundamentals-05-Conditional-Statements)

### Problem List

1. [Exchange if greater](./01.ExchangeIfGreater)
1. [Multiplication Sign](./02.MultiplicationSign)
1. [The biggest of Three](./03.TheBiggestOfThree)
1. [Sort 3 numbers](./04.Sort3Numbers)
1. [Digit as word](./05.DigitAsWord)
1. [Quadratic equation](./06.QuadraticEquation)
1. [The biggest of five numbers](./07.TheBiggestOfFiveNumbers)
1. [Number as words](./08.NumberAsWords)


text:
package com.google.cloud.domains.v1.samples;

// [START domains_v1_generated_Domains_SearchDomains_async]
import com.google.api.core.ApiFuture;
import com.google.cloud.domains.v1.DomainsClient;
import com.google.cloud.domains.v1.LocationName;
import com.google.cloud.domains.v1.SearchDomainsRequest;
import com.google.cloud.domains.v1.SearchDomainsResponse;

public class AsyncSearchDomains {

  public static void main(String[] args) throws Exception {
    asyncSearchDomains();
  }

  public static void asyncSearchDomains() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (DomainsClient domainsClient = DomainsClient.create()) {
      SearchDomainsRequest request =
          SearchDomainsRequest.newBuilder()
              .setQuery("query107944136")
              .setLocation(LocationName.of("[PROJECT]", "[LOCATION]").toString())
              .build();
      ApiFuture<SearchDomainsResponse> future =
          domainsClient.searchDomainsCallable().futureCall(request);
      // Do something.
      SearchDomainsResponse response = future.get();
    }
  }
}
// [END domains_v1_generated_Domains_SearchDomains_async]


text:
package varys.framework.client

import akka.actor._
import akka.actor.Terminated
import akka.pattern.ask
import akka.pattern.AskTimeoutException
import akka.remote.{RemotingLifecycleEvent, DisassociatedEvent}

import java.io._
import java.net._
import java.util.concurrent.ConcurrentHashMap

import scala.collection.mutable.HashMap
import scala.collection.JavaConversions._
import scala.concurrent.duration._
import scala.concurrent.{Await, ExecutionContext}

import varys.{Logging, Utils, VarysException}
import varys.framework._
import varys.framework.master.{Master, CoflowInfo}
import varys.framework.slave.Slave
import varys.util._

class VarysClient(
    clientName: String,
    masterUrl: String,
    listener: ClientListener = null)
  extends Logging {

  val INTERNAL_ASK_TIMEOUT_MS: Int =
    System.getProperty("varys.client.internalAskTimeoutMillis", "5000").toInt
  val RATE_UPDATE_FREQ = System.getProperty("varys.client.rateUpdateIntervalMillis", "100").toLong
  val SHORT_FLOW_BYTES = System.getProperty("varys.client.shortFlowMB", "0").toLong * 1048576
  val NIC_BPS = 1024 * 1048576

  var actorSystem: ActorSystem = null

  var masterActor: ActorRef = null
  val clientRegisterLock = new Object

  var slaveId: String = null
  var slaveUrl: String = null
  var slaveActor: ActorRef = null

  var clientId: String = null
  var clientActor: ActorRef = null

  // ExecutionContext for Futures
  implicit val futureExecContext = ExecutionContext.fromExecutor(Utils.newDaemonCachedThreadPool())

  var regStartTime = 0L

  val flowToTIS = new ConcurrentHashMap[DataIdentifier, ThrottledInputStream]()
  // TODO: Currently using flowToBitPerSec inside synchronized blocks. Might consider replacing with
  // an appropriate data structure; e.g., Collections.synchronizedMap.
  val flowToBitPerSec = new ConcurrentHashMap[DataIdentifier, Double]()
  val flowToObject = new HashMap[DataIdentifier, Array[Byte]]

  val serverThreadName = "ServerThread for Client@" + Utils.localHostName()
  var dataServer = new DataServer(0, serverThreadName, flowToObject)
  dataServer.start()

  var clientHost = Utils.localHostName()
  var clientCommPort = dataServer.getCommPort

  class ClientActor extends Actor with Logging {
    var masterAddress: Address = null

    // To avoid calling listener.disconnected() multiple times
    var alreadyDisconnected = false

    override def preStart() {
      logInfo("Connecting to master " + masterUrl)
      regStartTime = now
      try {
        masterActor = AkkaUtils.getActorRef(Master.toAkkaUrl(masterUrl), context)
        masterAddress = masterActor.path.address
        masterActor ! RegisterClient(clientName, clientHost, clientCommPort)
        context.system.eventStream.subscribe(self, classOf[RemotingLifecycleEvent])
      } catch {
        case e: Exception =>
          logError("Failed to connect to master", e)
          markDisconnected()
          context.stop(self)
      }
    }

    @throws(classOf[VarysException])
    def masterDisconnected() {
      // TODO: It would be nice to try to reconnect to the master, but just shut down for now.
      // (Note that if reconnecting we would also need to assign IDs differently.)
      val connToMasterFailedMsg = "Connection to master failed; stopping client"
      logWarning(connToMasterFailedMsg)
      markDisconnected()
      context.stop(self)
      throw new VarysException(connToMasterFailedMsg)
    }

    override def receive = {

      case RegisteredClient(clientId_, slaveId_, slaveUrl_) =>
        clientId = clientId_
        slaveId = slaveId_
        slaveUrl = slaveUrl_
        slaveActor = AkkaUtils.getActorRef(Slave.toAkkaUrl(slaveUrl), context)
        if (listener != null) {
          listener.connected(clientId)
        }
        clientRegisterLock.synchronized { clientRegisterLock.notifyAll() }  // Ready to go!
        logInfo("Registered to master in " +  (now - regStartTime) +
          " milliseconds. Local slave url = " + slaveUrl)

        // Thread to periodically uodate the rates of all existing ThrottledInputStreams
        context.system.scheduler.schedule(0.millis, RATE_UPDATE_FREQ.millis) {
          flowToBitPerSec.synchronized {
            flowToBitPerSec.foreach { kv => {
              // kv (key = FlowId, value = Rate)
              if (flowToTIS.containsKey(kv._1))
                flowToTIS.get(kv._1).setNewRate(kv._2)
              }
            }
          }
        }

      case Terminated(actor_) if actor_ == masterActor =>
        masterDisconnected()

      case e: DisassociatedEvent if e.remoteAddress == masterAddress =>
        masterDisconnected()

      case StopClient =>
        markDisconnected()
        sender ! true
        context.stop(self)

      case UpdatedRates(newRates) =>
        logInfo("Received updated shares")
        flowToBitPerSec.synchronized {
          for ((dataId, newBitPerSec) <- newRates) {
            logTrace(dataId + " ==> " + newBitPerSec + " bps")
            flowToBitPerSec.put(dataId, newBitPerSec)
          }
        }

      case RejectedCoflow(coflowId, rejectMessage) =>
        logDebug("Coflow " + coflowId + " has been rejected! " + rejectMessage)

        // Let the client know
        if (listener != null) {
          listener.coflowRejected(coflowId, rejectMessage)
        }

        // Close ongoing streams, if any. This will raise exceptions in getOne()
        // and go back to the application.
        // TODO: Find a more elegant solution.
        flowToTIS.foreach { kv => {
          // kv (key = dataId, value = TIS)
          if (kv._1.coflowId == coflowId)
            kv._2.close()
          }
        }

        // Free local resources
        freeLocalResources(coflowId)
    }

    /**
     * Notify the listener that we disconnected, if we hadn't already done so before.
     */
    def markDisconnected() {
      if (!alreadyDisconnected) {
        if (listener != null) {
          listener.disconnected()
        }
        alreadyDisconnected = true
      }
    }

  }

  private def now() = System.currentTimeMillis

  def start() {
    // Just launch an actor; it will call back into the listener.
    val (actorSystem_, _) = AkkaUtils.createActorSystem("varysClient", Utils.localIpAddress, 0)
    actorSystem = actorSystem_
    clientActor = actorSystem.actorOf(Props(new ClientActor))
  }

  def stop() {
    if (clientActor != null) {
      try {
        val timeout = INTERNAL_ASK_TIMEOUT_MS.millis
        val future = clientActor.ask(StopClient)(timeout)
        Await.result(future, timeout)
      } catch {
        case e: AskTimeoutException =>  // Ignore it, maybe master went away
      }
      clientActor = null
    }
    dataServer.stop()
  }

  def awaitTermination() {
    actorSystem.awaitTermination()
  }

  // Wait until the client has been registered
  private def waitForRegistration = {
    while (clientId == null) {
      clientRegisterLock.synchronized {
        clientRegisterLock.wait()
        clientRegisterLock.notifyAll()
      }
    }
  }

  def registerCoflow(coflowDesc: CoflowDescription): String = {
    waitForRegistration

    // Register with the master
    val RegisteredCoflow(coflowId) = AkkaUtils.askActorWithReply[RegisteredCoflow](masterActor,
      RegisterCoflow(clientId, coflowDesc))

    // Let the local slave know
    AkkaUtils.tellActor(slaveActor, RegisteredCoflow(coflowId))

    coflowId
  }

  def unregisterCoflow(coflowId: String) {
    waitForRegistration

    // Let the master know
    AkkaUtils.tellActor(masterActor, UnregisterCoflow(coflowId))

    // Update local slave
    AkkaUtils.tellActor(slaveActor, UnregisterCoflow(coflowId))

    // Free local resources
    freeLocalResources(coflowId)
  }

  private def freeLocalResources(coflowId: String) {
    flowToTIS.retain((dataId, _) => dataId.coflowId != coflowId)
    flowToBitPerSec.synchronized {
      flowToBitPerSec.retain((dataId, _) => dataId.coflowId != coflowId)
    }
    flowToObject.retain((dataId, _) => dataId.coflowId != coflowId)
  }

  /**
   * Makes data available for retrieval, and notifies local slave, which will register it with the
   * master.
   * Non-blocking call.
   */
  private def handlePut(flowDesc: FlowDescription, serialObj: Array[Byte] = null) {
    waitForRegistration

    val st = now

    // Notify the slave, which will notify the master
    AkkaUtils.tellActor(slaveActor, AddFlow(flowDesc))

    logInfo("Registered " + flowDesc + " in " + (now - st) + " milliseconds")

    // Keep a reference to the object to be served when asked for.
    if (flowDesc.dataType == DataType.INMEMORY) {
      assert(serialObj != null)
      flowToObject(flowDesc.dataId) = serialObj
    }
  }

  /**
   * Makes multiple pieces of data available for retrieval, and notifies local slave, which will
   * register it with the master.
   * Non-blocking call.
   * FIXME: Handles only DataType.FAKE right now.
   */
  private def handlePutMultiple(
      flowDescs: Array[FlowDescription],
      coflowId: String,
      dataType: DataType.DataType) {

    if (dataType != DataType.FAKE) {
      val tmpM = "handlePutMultiple currently supports only DataType.FAKE"
      logWarning(tmpM)
      throw new VarysException(tmpM)
    }

    waitForRegistration

    val st = now

    // Notify the slave, which will notify the master
    AkkaUtils.tellActor(slaveActor, AddFlows(flowDescs, coflowId, dataType))

    logInfo("Registered Array[FlowDescription] in " + (now - st) + " milliseconds")
  }

  /**
   * Puts any data structure
   */
  def putObject[T: Manifest](
      objId: String,
      obj: T,
      coflowId: String,
      size: Long,
      numReceivers: Int) {

    // TODO: Figure out class name
    val className = "UnknownType"
    val desc =
      new ObjectDescription(
        objId,
        className,
        coflowId,
        DataType.INMEMORY,
        size,
        numReceivers,
        clientHost,
        clientCommPort)

    val serialObj = Utils.serialize[T](obj)
    handlePut(desc, serialObj)
  }

  /**
   * Puts a complete local file
   */
  def putFile(fileId: String, pathToFile: String, coflowId: String, size: Long, numReceivers: Int) {
    putFile(fileId, pathToFile, coflowId, 0, size, numReceivers)
  }

  /**
   * Puts a range of local file
   */
  def putFile(
      fileId: String,
      pathToFile: String,
      coflowId: String,
      offset: Long,
      size: Long,
      numReceivers: Int) {

    val desc =
      new FileDescription(
        fileId,
        pathToFile,
        coflowId,
        DataType.ONDISK,
        offset,
        size,
        numReceivers,
        clientHost,
        clientCommPort)

    handlePut(desc)
  }

  /**
   * Emulates the process without having to actually put anything
   */
  def putFake(blockId: String, coflowId: String, size: Long, numReceivers: Int) {
    val desc =
      new FlowDescription(
        blockId,
        coflowId,
        DataType.FAKE,
        size,
        numReceivers,
        clientHost,
        clientCommPort)

    handlePut(desc)
  }

  /**
   * Puts multiple blocks at the same time of same size and same number of receivers
   * blocks => (blockId, blockSize, numReceivers)
   */
  def putFakeMultiple(blocks: Array[(String, Long, Int)], coflowId: String) {
    val descs =
      blocks.map(blk =>
        new FlowDescription(
          blk._1,
          coflowId,
          DataType.FAKE,
          blk._2,
          blk._3,
          clientHost,
          clientCommPort))

    handlePutMultiple(descs, coflowId, DataType.FAKE)
  }

  /**
   * Performs exactly one get operation
   */
  @throws(classOf[VarysException])
  private def getOne(flowDesc: FlowDescription): (FlowDescription, Array[Byte]) = {
    var st = now
    val sock = new Socket(flowDesc.originHost, flowDesc.originCommPort)
    val oos = new ObjectOutputStream(new BufferedOutputStream(sock.getOutputStream))
    oos.flush

    // Don't wait for scheduling for 'SHORT' flows
    val tisRate = if (flowDesc.sizeInBytes > SHORT_FLOW_BYTES) 0.0 else NIC_BPS

    val tis = new ThrottledInputStream(sock.getInputStream, clientName, tisRate)
    flowToTIS.put(flowDesc.dataId, tis)
    // logTrace("Created socket and " + tis + " for " + flowDesc + " in " + (now - st) +
    //   " milliseconds")

    oos.writeObject(GetRequest(flowDesc))
    oos.flush

    var retVal: Array[Byte] = null

    st = now
    // Specially handle DataType.FAKE
    if (flowDesc.dataType == DataType.FAKE) {
      val buf = new Array[Byte](65536)
      var bytesReceived = 0L
      while (bytesReceived < flowDesc.sizeInBytes) {
        val n = tis.read(buf)
        // logInfo("Received " + n + " bytes of " + flowDesc.sizeInBytes)
        if (n == -1) {
          logError("EOF reached after " + bytesReceived + " bytes")
          throw new VarysException("Too few bytes received")
        } else {
          bytesReceived += n
        }
      }
    } else {
      val ois = new ObjectInputStream(tis)
      val resp = ois.readObject.asInstanceOf[Option[Array[Byte]]]
      resp match {
        case Some(byteArr) => {
          logInfo("Received response of " + byteArr.length + " bytes")

          flowDesc.dataType match {
            case DataType.ONDISK => {
              retVal = byteArr
            }

            case DataType.INMEMORY => {
              retVal = byteArr
            }

            case _ => {
              logError("Invalid DataType!")
              throw new VarysException("Invalid DataType!")
            }
          }
        }
        case None => {
          logError("Nothing received!")
          throw new VarysException("Invalid DataType!")
        }
      }
    }
    logTrace("Received " + flowDesc.sizeInBytes + " bytes for " + flowDesc + " in " + (now - st) +
      " milliseconds")

    // Close everything
    flowToTIS.remove(flowDesc.dataId)
    tis.close
    sock.close

    (flowDesc, retVal)
  }

  /**
   * Notifies the master and the slave. But everything is done in the client
   * Blocking call.
   */
  @throws(classOf[VarysException])
  private def handleGet(
      blockId: String,
      dataType: DataType.DataType,
      coflowId: String): Array[Byte] = {

    waitForRegistration

    var st = now

    // Notify master and retrieve the FlowDescription in response
    var flowDesc: FlowDescription = null

    val gotFlowDesc = AkkaUtils.askActorWithReply[Option[GotFlowDesc]](masterActor,
      GetFlow(blockId, coflowId, clientId, slaveId))
    gotFlowDesc match {
      case Some(GotFlowDesc(x)) => flowDesc = x
      case None => {
        val tmpM = "Failed to receive FlowDescription for " + blockId + " of coflow " + coflowId
        logWarning(tmpM)
        // TODO: Define proper VarysExceptions
        throw new VarysException(tmpM)
      }
    }
    logInfo("Received " + flowDesc + " for " + blockId + " of coflow " + coflowId + " in " +
      (now - st) + " milliseconds")

    // Notify local slave
    AkkaUtils.tellActor(slaveActor, GetFlow(blockId, coflowId, clientId, slaveId, flowDesc))

    // Get it!
    val (origFlowDesc, retVal) = getOne(flowDesc)
    // Notify flow completion
    masterActor ! FlowProgress(
      origFlowDesc.id,
      origFlowDesc.coflowId,
      origFlowDesc.sizeInBytes,
      true)

    retVal
  }

  /**
   * Notifies the master and the slave. But everything is done in the client
   * Blocking call.
   * FIXME: Handles only DataType.FAKE right now.
   */
  @throws(classOf[VarysException])
  private def handleGetMultiple(
      blockIds: Array[String],
      dataType: DataType.DataType,
      coflowId: String) {

    if (dataType != DataType.FAKE) {
      val tmpM = "handleGetMultiple currently supports only DataType.FAKE"
      logWarning(tmpM)
      throw new VarysException(tmpM)
    }

    waitForRegistration

    var st = now

    // Notify master and retrieve the FlowDescription in response
    var flowDescs: Array[FlowDescription] = null

    val gotFlowDescs = AkkaUtils.askActorWithReply[Option[GotFlowDescs]](
      masterActor,
      GetFlows(blockIds, coflowId, clientId, slaveId))

    gotFlowDescs match {
      case Some(GotFlowDescs(x)) => flowDescs = x
      case None => {
        val tmpM = "Failed to receive FlowDescriptions for " + blockIds.size + " flows of coflow " +
          coflowId
        logWarning(tmpM)
        // TODO: Define proper VarysExceptions
        throw new VarysException(tmpM)
      }
    }
    logInfo("Received " + flowDescs.size + " flowDescs " + " of coflow " + coflowId + " in " +
      (now - st) + " milliseconds")

    // Notify local slave
    AkkaUtils.tellActor(slaveActor, GetFlows(blockIds, coflowId, clientId, slaveId, flowDescs))

    // Get 'em!
    val recvLock = new Object()
    var recvFinished = 0

    for (flowDesc <- flowDescs) {
      new Thread("Receive thread for " + flowDesc) {
        override def run() {
          val (origFlowDesc, retVal) = getOne(flowDesc)
          // Notify flow completion
          masterActor ! FlowProgress(
            origFlowDesc.id,
            origFlowDesc.coflowId,
            origFlowDesc.sizeInBytes,
            true)

          recvLock.synchronized {
            recvFinished += 1
            recvLock.notifyAll()
          }
        }
      }.start()
    }

    recvLock.synchronized {
      while (recvFinished < flowDescs.size) {
        recvLock.wait()
      }
    }

    // val futureList = Future.traverse(flowDescs.toList)(fd => Future(getOne(fd)))
    // futureList.onComplete {
    //   case Right(arrayOfFlowDesc_Res) => {
    //     arrayOfFlowDesc_Res.foreach { x =>
    //       val (origFlowDesc, res) = x
    //       masterActor ! FlowProgress(
    //         origFlowDesc.id,
    //         origFlowDesc.coflowId,
    //         origFlowDesc.sizeInBytes,
    //         true)
    //     }
    //   }
    //   case Left(vex) => throw vex
    // }
  }

  /**
   * Retrieves data from any of the feasible locations.
   */
  @throws(classOf[VarysException])
  def getObject[T](objectId: String, coflowId: String): T = {
    val resp = handleGet(objectId, DataType.INMEMORY, coflowId)
    Utils.deserialize[T](resp)
  }

  /**
   * Gets a file
   */
  @throws(classOf[VarysException])
  def getFile(fileId: String, coflowId: String): Array[Byte] = {
    handleGet(fileId, DataType.ONDISK, coflowId)
  }

  /**
   * Paired get() for putFake. Doesn't return anything, but emulates the retrieval process.
   */
  @throws(classOf[VarysException])
  def getFake(blockId: String, coflowId: String) {
    handleGet(blockId, DataType.FAKE, coflowId)
  }

  /**
   * Paired get() for putFakeMultiple. Doesn't return anything, but emulates the retrieval process.
   */
  @throws(classOf[VarysException])
  def getFakeMultiple(blockIds: Array[String], coflowId: String) {
    handleGetMultiple(blockIds, DataType.FAKE, coflowId)
  }

  def deleteFlow(flowId: String, coflowId: String) {
    // TODO: Do something!
    // AkkaUtils.tellActor(slaveActor, DeleteFlow(flowId, coflowId))
  }

  /**
   * Receive 'howMany' machines with the lowest incoming usage
   */
  def getBestRxMachines(howMany: Int, adjustBytes: Long): Array[String] = {
    val BestRxMachines(bestRxMachines) = AkkaUtils.askActorWithReply[BestRxMachines](
      masterActor,
      RequestBestRxMachines(howMany, adjustBytes))
    bestRxMachines
  }

  /**
   * Receive the machine with the lowest incoming usage
   */
  def getBestRxMachine(adjustBytes: Long): String = {
    val BestRxMachines(bestRxMachines) = AkkaUtils.askActorWithReply[BestRxMachines](
      masterActor,
      RequestBestRxMachines(1, adjustBytes))
    bestRxMachines(0)
  }

  /**
   * Receive 'howMany' machines with the lowest outgoing usage
   */
  def getTxMachines(howMany: Int, adjustBytes: Long): Array[String] = {
    val BestTxMachines(bestTxMachines) = AkkaUtils.askActorWithReply[BestTxMachines](
      masterActor,
      RequestBestTxMachines(howMany, adjustBytes))
    bestTxMachines
  }

  /**
   * Receive the machine with the lowest outgoing usage
   */
  def getBestTxMachine(adjustBytes: Long): String = {
    val BestTxMachines(bestTxMachines) = AkkaUtils.askActorWithReply[BestTxMachines](
      masterActor,
      RequestBestTxMachines(1, adjustBytes))
    bestTxMachines(0)
  }
}


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

	<title>quadrantFactory unit tests</title>

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

QUnit example

test markup, will be hidden


text:
Accelerator Physics, Beam Dynamics: Tune Spread Calculation with Laslett Formula for TWISS Files

Command line tool for calculation of direct space charge tune spread in Gaussian beams.
Uses MAD-X Twiss files.


text:
package test;

import static org.junit.Assert.*;

import org.junit.Test;

import seedu.task.commons.exceptions.IllegalValueException;
import seedu.task.model.item.Price;
import seedu.task.model.item.PriceChange;

public class PriceTest {

	@Test
    public void price_check() throws IllegalValueException {
        Price d1 = new Price("23.00");
        Price d2 = new Price("23");

        assertEquals(d1,d2);
        assertEquals(d1,d1);

        try {
        	Price d4 = new Price("23.12345");
        } catch (IllegalValueException e) {
        	assertEquals(e.getMessage(), Price.MESSAGE_PRICE_CONSTRAINTS);
        }

    }

	@Test
	public void price_change_check() throws IllegalValueException {
		PriceChange c1 = new PriceChange("+23.00");
		PriceChange c2 = new PriceChange("-0.001");

		try {
        	PriceChange c4 = new PriceChange("23.12345");
        } catch (IllegalValueException e) {
        	assertEquals(e.getMessage(), PriceChange.MESSAGE_PRICE_CHANGE_CONSTRAINTS);
        }

		assertTrue(c1.isSignPositive());

	}

}


text: Local Classes in C


text:
using System;
using System.Collections;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text;
using OpenADK.Library;
using OpenADK.Library.Infra;
using OpenADK.Library.Log;

namespace Library.Examples.Chameleon
{
    /// <summary>
    /// Summary description for ChamelonObjectLogger.
    /// </summary>
    public class ObjectLogger : IQueryResults, ISubscriber, IMessagingListener
    {
        private string fDir;

        /// <summary>
        /// Tracks the current response number
        /// </summary>
        private int fResponseOrdinal = 1;

        private Chameleon fAgent;
        private IDictionary fRefIdTracker = new Hashtable();

        public ObjectLogger( Chameleon agent )
        {
            fAgent = agent;
            fDir = Path.Combine( agent.HomeDir, "Chameleon" ) + "\\";
            if ( fAgent.Properties.GetProperty( "chameleon.autoClearLog", false ) )
            {
                try
                {
                    DirectoryInfo inf = new DirectoryInfo( fDir );
                    if ( inf.Exists )
                    {
                        inf.Delete( true );
                    }
                }
                catch ( Exception ex )
                {
                    Adk.Log.Error( "Error clearing the log files", ex );
                }
            }
        }

        public void OnQueryResults( IDataObjectInputStream data,
                                    SIF_Error error,
                                    IZone zone,
                                    IMessageInfo info )
        {
            SifMessageInfo smi = (SifMessageInfo) info;
            if ( error != null )
            {
                Adk.Log.Warn( "Received Error Response: " + error.SIF_Desc );
            }
            else
            {
                string debug =
                    string.Format
                        ( "Received Response for {0} from zone: {1}. Packet {2} of {3}",
                          data.ObjectType, zone.ZoneId, smi.PacketNumber,
                          smi.MorePackets ? smi.PacketNumber + "+" : smi.PacketNumber + " (FINAL)" );
                zone.Log.Info( debug );
                zone.ServerLog.Log
                    ( LogLevel.INFO, debug, null, "1003", LogEntryCodes.CATEGORY_SUCCESS,
                      LogEntryCodes.CODE_SUCCESS, smi, null );
                bool logToconsole = fAgent.getChameleonProperty( zone, "logConsole", false );
                if ( fAgent.getChameleonProperty( zone, "logResponses", true ) )
                {
                    Log
                        ( fDir + Path.DirectorySeparatorChar + zone.ZoneId +
                          Path.DirectorySeparatorChar + "Responses\\" + data.ObjectType.Name + "\\" +
                          data.ObjectType.Name + DateTime.Now.ToFileTime().ToString() + ".xml", data,
                          smi, logToconsole );
                }
            }
        }

        public void OnEvent( Event evnt,
                             IZone zone,
                             IMessageInfo info )
        {
            bool logToconsole = fAgent.getChameleonProperty( zone, "logConsole", false );
            SifMessageInfo smi = (SifMessageInfo) info;
            string debug =
                string.Format
                    ( "Received {0} Event from {1} in Zone: {2}", evnt.ActionString, smi.SourceId,
                      zone.ZoneId );
            zone.ServerLog.Log
                ( LogLevel.INFO, debug, null, "1003", LogEntryCodes.CATEGORY_SUCCESS,
                  LogEntryCodes.CODE_SUCCESS, smi, null );
            Adk.Log.Info( debug );
            Log
                ( fDir + Path.DirectorySeparatorChar + zone.ZoneId + Path.DirectorySeparatorChar +
                  "Events\\" + evnt.ObjectType.Name + "\\" + evnt.ObjectType.Name +
                  DateTime.Now.ToFileTime().ToString() + ".xml", evnt.Data, smi, logToconsole );
        }

        private void Log( string fileName,
                          IDataObjectInputStream input,
                          SifMessageInfo info,
                          bool logToConsole )
        {
            try
            {
                // Ensure that the directory is there
                FileInfo file = new FileInfo( fileName );
                file.Directory.Create();
                int numObjects = 0;

                using ( Stream outStream = File.OpenWrite( fileName ) )
                {
                    using ( TextWriter twriter = new StreamWriter( outStream, Encoding.UTF8 ) )
                    {
                        twriter.WriteLine( "<SIF_ObjectData>" );
                        twriter.Flush();
                        SifWriter writer = new SifWriter( twriter );
                        SifWriter consoleWriter = null;
                        if ( logToConsole )
                        {
                            consoleWriter = new SifWriter( Console.Out );
                        }

                        SifDataObject o;
                        while ( (o = input.ReadDataObject()) != null )
                        {
                            numObjects++;
                            Track( o );
                            writer.Write( o );
                            if ( logToConsole )
                            {
                                consoleWriter.Write( o );
                                Console.WriteLine();
                            }
                        }
                        writer.Flush();
                        if ( logToConsole )
                        {
                            consoleWriter.Flush();
                        }
                        twriter.WriteLine( "</SIF_ObjectData>" );
                    }

                    outStream.Close();

                    Console.WriteLine
                        ( "Received {0} objects for {1}, Packet# {2}", numObjects,
                          input.ObjectType.Name, info.PacketNumber );
                }
            }
            catch ( Exception ex )
            {
                Adk.Log.Error( ex.Message, ex );
            }
        }

        private void Track( SifDataObject o )
        {
            try
            {
                if ( fRefIdTracker.Contains( o.RefId ) )
                {
                    using (
                        Stream outStream =
                            File.OpenWrite
                                ( "Duplicate " + o.RefId + "-" + o.ElementDef.Name + "-" +
                                  DateTime.Now.ToFileTime().ToString() + ".xml" ) )
                    {
                        using ( TextWriter wr = new StreamWriter( outStream ) )
                        {
                            wr.WriteLine
                                ( String.Format( "Duplicate Object with Refid: {0}", o.RefId ) );
                            wr.WriteLine
                                ( "Original:" + ((SifDataObject) fRefIdTracker[o.RefId]).ToXml() );
                            wr.WriteLine( "New:" + o.ToXml() );
                        }
                    }
                }
                else
                {
                    fRefIdTracker.Add( o.RefId, o );
                }
            }
            catch ( Exception ex )
            {
                Console.WriteLine( ex.Message );
                Adk.Log.Warn( ex.Message, ex );
            }
        }

        public void OnQueryPending( IMessageInfo info,
                                    IZone zone )
        {
            Adk.Log.Info
                ( string.Format
                      ( "Requested {0} from zone: {1}",
                        ((SifMessageInfo) info).SIFRequestObjectType.Name, zone.ZoneId ) );
        }

        [MethodImpl( MethodImplOptions.Synchronized )]
        public MessagingReturnCode OnMessageReceived( SifMessageType messageType,
                                                      StringBuilder message )
        {
            return MessagingReturnCode.Process;
        }

        public void OnMessageProcessed( SifMessageType messageType,
                                        IMessageInfo info )
        {
            string fileName = null;
            SifMessageInfo smi = (SifMessageInfo) info;
            if ( messageType == SifMessageType.SIF_Response )
            {
                // Log Query responses in the standard OpenADK Message tracing format
                //N-ObjectType-ZoneID-SourceID-PacketNum|"error".txt
                fileName =
                    string.Format
                        ( "{0:00000}-{1}-{2}-{3}-{4}.txt", fResponseOrdinal++,
                          smi.SIFRequestObjectType.Name, smi.Zone.ZoneId, smi.SourceId,
                          smi.PacketNumber );
            }
            else if ( messageType == SifMessageType.SIF_Event )
            {
                fileName =
                    string.Format
                        ( "{0:00000}-{1}-{2}-{3}-SIF_Event.txt", fResponseOrdinal++, "ChangeThis",
                          smi.Zone.ZoneId, smi.SourceId );
            }
            if ( fileName != null )
            {
                try
                {
                    FileInfo file = new FileInfo( fDir + "\\Raw\\" + fileName );
                    file.Directory.Create();
                    using (
                        StreamWriter writer = new StreamWriter( file.FullName, true, Encoding.UTF8 )
                        )
                    {
                        writer.Write( smi.Message );
                        writer.Close();
                    }
                }
                catch ( Exception ex )
                {
                    Adk.Log.Warn( ex.Message, ex );
                }
            }
        }

        public bool OnSendingMessage( SifMessageType messageType,
                                      IMessageInfo info,
                                      StringBuilder message )
        {
            return true;
        }

        public void OnMessageSent( SifMessageType messageType,
                                   IMessageInfo info,
                                   object receipt )
        {
        }
    }
}


text:
package org.uberfire.annotations.processors;

import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.SimplePanel;
import org.uberfire.backend.vfs.Path;
import org.uberfire.client.annotations.WorkbenchEditor;
import org.uberfire.client.annotations.WorkbenchPartTitle;
import org.uberfire.client.annotations.WorkbenchPartView;
import org.uberfire.client.mvp.MyTestType;
import org.uberfire.lifecycle.OnStartup;
import org.uberfire.mvp.PlaceRequest;

@WorkbenchEditor(identifier = "test13", supportedTypes = { MyTestType.class })
public class WorkbenchEditorTest13 {

    @WorkbenchPartView
    public IsWidget getView() {
        return new SimplePanel();
    }

    @WorkbenchPartTitle
    public String getTitle() {
        return "title";
    }

    @OnStartup
    public void onStartup(final PlaceRequest place,
                        final Path path) {
    }

}


text:
package com.hazelcast.spi.impl.sequence;

import com.hazelcast.util.concurrent.BackoffIdleStrategy;
import com.hazelcast.util.concurrent.IdleStrategy;

import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicLongArray;

import static com.hazelcast.nio.Bits.CACHE_LINE_LENGTH;
import static com.hazelcast.nio.Bits.LONG_SIZE_IN_BYTES;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.NANOSECONDS;

/**
 * A {@link CallIdSequence} that provides backpressure by taking
 * the number of in-flight operations into account when before creating a new call-id.
 *

 * It is possible to temporarily create more concurrent invocations than the declared capacity due to:
 *

 *
system operations

 *
the racy nature of checking if space is available and getting the next sequence.

 *

 * The latter cause is not a problem since the capacity is exceeded temporarily and it isn't sustainable.
 * So perhaps there are a few threads that at the same time see that the there is space and do a next.
 * But any following invocation needs to wait till there is is capacity.
 */
public final class CallIdSequenceWithBackpressure implements CallIdSequence {
    static final int MAX_DELAY_MS = 500;
    private static final IdleStrategy IDLER = new BackoffIdleStrategy(
            0, 0, MILLISECONDS.toNanos(1), MILLISECONDS.toNanos(MAX_DELAY_MS));
    private static final int INDEX_HEAD = 7;
    private static final int INDEX_TAIL = 15;

    // instead of using 2 AtomicLongs, we use an array if width of 3 cache lines to prevent any false sharing.
    private final AtomicLongArray longs = new AtomicLongArray(3 * CACHE_LINE_LENGTH / LONG_SIZE_IN_BYTES);

    private final int maxConcurrentInvocations;
    private final long backoffTimeoutNanos;

    public CallIdSequenceWithBackpressure(int maxConcurrentInvocations, long backoffTimeoutMs) {
        this.maxConcurrentInvocations = maxConcurrentInvocations;
        this.backoffTimeoutNanos = MILLISECONDS.toNanos(backoffTimeoutMs);
    }

    @Override
    public long getLastCallId() {
        return longs.get(INDEX_HEAD);
    }

    @Override
    public int getMaxConcurrentInvocations() {
        return maxConcurrentInvocations;
    }

    @Override
    public long next() throws TimeoutException {
        if (!hasSpace()) {
            waitForSpace();
        }
        return forceNext();
    }

    @Override
    public void complete() {
        long newTail = longs.incrementAndGet(INDEX_TAIL);
        assert newTail <= longs.get(INDEX_HEAD);
    }

    public long forceNext() {
        return longs.incrementAndGet(INDEX_HEAD);
    }

    long getTail() {
        return longs.get(INDEX_TAIL);
    }

    private boolean hasSpace() {
        return longs.get(INDEX_HEAD) - longs.get(INDEX_TAIL) < maxConcurrentInvocations;
    }

    private void waitForSpace() throws TimeoutException {
        long deadline = System.nanoTime() + backoffTimeoutNanos;
        for (long idleCount = 0; ; idleCount++) {
            if (System.nanoTime() >= deadline) {
                throw new TimeoutException(String.format("Timed out trying to acquire another call ID."
                        + " maxConcurrentInvocations = %d, backoffTimeout = %d", maxConcurrentInvocations,
                        NANOSECONDS.toMillis(backoffTimeoutNanos)));
            }
            IDLER.idle(idleCount);
            if (hasSpace()) {
                return;
            }
        }
    }
}


text:
/*  ******************************
  Module - Video
  Author: Jack Lukic

  This is a video playlist and video embed plugin which helps
  provide helpers for adding embed code for vimeo and youtube and
  abstracting event handlers for each library

******************************  */

;(function ($, window, document, undefined) {

module.exports = function(parameters) {
  var _module = module;

  var
    $allModules     = $(this),

    moduleSelector  = $allModules.selector || '',

    time            = new Date().getTime(),
    performance     = [],

    query           = arguments[0],
    methodInvoked   = (typeof query == 'string'),
    queryArguments  = [].slice.call(arguments, 1),

    returnedValue
  ;

  $allModules
    .each(function() {
      var
        settings        = ( $.isPlainObject(parameters) )
          ? $.extend(true, {}, _module.exports.settings, parameters)
          : $.extend({}, _module.exports.settings),

        selector        = settings.selector,
        className       = settings.className,
        error           = settings.error,
        metadata        = settings.metadata,
        namespace       = settings.namespace,

        eventNamespace  = '.' + namespace,
        moduleNamespace = 'module-' + namespace,

        $module         = $(this),
        $placeholder    = $module.find(selector.placeholder),
        $playButton     = $module.find(selector.playButton),
        $embed          = $module.find(selector.embed),

        element         = this,
        instance        = $module.data(moduleNamespace),
        module
      ;

      module = {

        initialize: function() {
          module.debug('Initializing video');
          $placeholder
            .on('click' + eventNamespace, module.play)
          ;
          $playButton
            .on('click' + eventNamespace, module.play)
          ;
          module.instantiate();
        },

        instantiate: function() {
          module.verbose('Storing instance of module', module);
          instance = module;
          $module
            .data(moduleNamespace, module)
          ;
        },

        destroy: function() {
          module.verbose('Destroying previous instance of video');
          $module
            .removeData(moduleNamespace)
            .off(eventNamespace)
          ;
          $placeholder
            .off(eventNamespace)
          ;
          $playButton
            .off(eventNamespace)
          ;
        },

        // sets new video
        change: function(source, id, url) {
          module.debug('Changing video to ', source, id, url);
          $module
            .data(metadata.source, source)
            .data(metadata.id, id)
            .data(metadata.url, url)
          ;
          settings.onChange();
        },

        // clears video embed
        reset: function() {
          module.debug('Clearing video embed and showing placeholder');
          $module
            .removeClass(className.active)
          ;
          $embed
            .html(' ')
          ;
          $placeholder
            .show()
          ;
          settings.onReset();
        },

        // plays current video
        play: function() {
          module.debug('Playing video');
          var
            source = $module.data(metadata.source) || false,
            url    = $module.data(metadata.url)    || false,
            id     = $module.data(metadata.id)     || false
          ;
          $embed
            .html( module.generate.html(source, id, url) )
          ;
          $module
            .addClass(className.active)
          ;
          settings.onPlay();
        },

        generate: {
          // generates iframe html
          html: function(source, id, url) {
            module.debug('Generating embed html');
            var
              width = (settings.width == 'auto')
                ? $module.width()
                : settings.width,
              height = (settings.height == 'auto')
                ? $module.height()
                : settings.height,
              html
            ;
            if(source && id) {
              if(source == 'vimeo') {
                html = ''
                  + ''
                ;
              }
              else if(source == 'youtube') {
                html = ''
                  + ''
                ;
              }
            }
            else if(url) {
              html = ''
                + ''
              ;
            }
            else {
              module.error(error.noVideo);
            }
            return html;
          },

          // generate url parameters
          url: function(source) {
            var
              api      = (settings.api)
                ? 1
                : 0,
              autoplay = (settings.autoplay)
                ? 1
                : 0,
              hd       = (settings.hd)
                ? 1
                : 0,
              showUI   = (settings.showUI)
                ? 1
                : 0,
              // opposite used for some params
              hideUI   = !(settings.showUI)
                ? 1
                : 0,
              url = ''
            ;
            if(source == 'vimeo') {
              url = ''
                +      'api='      + api
                + '&title='    + showUI
                + '&byline='   + showUI
                + '&portrait=' + showUI
                + '&autoplay=' + autoplay
              ;
              if(settings.color) {
                url += '&color=' + settings.color;
              }
            }
            if(source == 'ustream') {
              url = ''
                + 'autoplay=' + autoplay
              ;
              if(settings.color) {
                url += '&color=' + settings.color;
              }
            }
            else if(source == 'youtube') {
              url = ''
                +      'enablejsapi=' + api
                + '&autoplay='    + autoplay
                + '&autohide='    + hideUI
                + '&hq='          + hd
                + '&modestbranding=1'
              ;
              if(settings.color) {
                url += '&color=' + settings.color;
              }
            }
            return url;
          }
        },

        setting: function(name, value) {
          if( $.isPlainObject(name) ) {
            $.extend(true, settings, name);
          }
          else if(value !== undefined) {
            settings[name] = value;
          }
          else {
            return settings[name];
          }
        },
        internal: function(name, value) {
          if( $.isPlainObject(name) ) {
            $.extend(true, module, name);
          }
          else if(value !== undefined) {
            module[name] = value;
          }
          else {
            return module[name];
          }
        },
        debug: function() {
          if(settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.debug.apply(console, arguments);
            }
          }
        },
        verbose: function() {
          if(settings.verbose && settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.verbose.apply(console, arguments);
            }
          }
        },
        error: function() {
          module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
          module.error.apply(console, arguments);
        },
        performance: {
          log: function(message) {
            var
              currentTime,
              executionTime,
              previousTime
            ;
            if(settings.performance) {
              currentTime   = new Date().getTime();
              previousTime  = time || currentTime;
              executionTime = currentTime - previousTime;
              time          = currentTime;
              performance.push({
                'Element'        : element,
                'Name'           : message[0],
                'Arguments'      : [].slice.call(message, 1) || '',
                'Execution Time' : executionTime
              });
            }
            clearTimeout(module.performance.timer);
            module.performance.timer = setTimeout(module.performance.display, 100);
          },
          display: function() {
            var
              title = settings.name + ':',
              totalTime = 0
            ;
            time = false;
            clearTimeout(module.performance.timer);
            $.each(performance, function(index, data) {
              totalTime += data['Execution Time'];
            });
            title += ' ' + totalTime + 'ms';
            if(moduleSelector) {
              title += ' \'' + moduleSelector + '\'';
            }
            if($allModules.size() > 1) {
              title += ' ' + '(' + $allModules.size() + ')';
            }
            if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
              console.groupCollapsed(title);
              if(console.table) {
                console.table(performance);
              }
              else {
                $.each(performance, function(index, data) {
                  console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
                });
              }
              console.groupEnd();
            }
            performance = [];
          }
        },
        invoke: function(query, passedArguments, context) {
          var
            object = instance,
            maxDepth,
            found,
            response
          ;
          passedArguments = passedArguments || queryArguments;
          context         = element         || context;
          if(typeof query == 'string' && object !== undefined) {
            query    = query.split(/[\. ]/);
            maxDepth = query.length - 1;
            $.each(query, function(depth, value) {
              var camelCaseValue = (depth != maxDepth)
                ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
                : query
              ;
              if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
                object = object[camelCaseValue];
              }
              else if( object[camelCaseValue] !== undefined ) {
                found = object[camelCaseValue];
                return false;
              }
              else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
                object = object[value];
              }
              else if( object[value] !== undefined ) {
                found = object[value];
                return false;
              }
              else {
                return false;
              }
            });
          }
          if ( $.isFunction( found ) ) {
            response = found.apply(context, passedArguments);
          }
          else if(found !== undefined) {
            response = found;
          }
          if($.isArray(returnedValue)) {
            returnedValue.push(response);
          }
          else if(returnedValue !== undefined) {
            returnedValue = [returnedValue, response];
          }
          else if(response !== undefined) {
            returnedValue = response;
          }
          return found;
        }
      };

      if(methodInvoked) {
        if(instance === undefined) {
          module.initialize();
        }
        module.invoke(query);
      }
      else {
        if(instance !== undefined) {
          module.destroy();
        }
        module.initialize();
      }
    })
  ;
  return (returnedValue !== undefined)
    ? returnedValue
    : this
  ;
};

module.exports.settings = {

  name        : 'Video',
  namespace   : 'video',

  debug       : false,
  verbose     : true,
  performance : true,

  metadata    : {
    source : 'source',
    id     : 'id',
    url    : 'url'
  },

  onPlay   : function(){},
  onReset  : function(){},
  onChange : function(){},

  // callbacks not coded yet (needs to use jsapi)
  onPause  : function() {},
  onStop   : function() {},

  width    : 'auto',
  height   : 'auto',

  autoplay : false,
  color    : '#442359',
  hd       : true,
  showUI   : false,
  api      : true,

  error      : {
    noVideo     : 'No video specified',
    method      : 'The method you called is not defined'
  },

  className   : {
    active      : 'active'
  },

  selector    : {
    embed       : '.embed',
    placeholder : '.placeholder',
    playButton  : '.play'
  }
};

})( require("jquery"), window , document );


text:
<?php

namespace backend\controllers;

use Yii;
use backend\models\assignment\Assignment;
use backend\models\assignment\AssignmentSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;

/**
 * AssignmentController implements the CRUD actions for Assignment model.
 */
class AssignmentController extends Controller
{
    public function behaviors()
    {
        return [
	        'access' => [
	            'class' => AccessControl::className(),
	            'rules' => [
	                [
	                    'allow' => true,
	                	'actions' => ['view', 'index',],
	                    'roles' => ['manager'],
	                ],
	            	[
	            		'allow' => true,
	            		'actions' => ['create', 'update', 'view', 'index', 'delete'],
	            		'roles' => ['admin'],
	            	],
	            ],
	        ],
	    ];
    }

    /**
     * Lists all Assignment models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new AssignmentSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Assignment model.
     * @param string $item_name
     * @param string $user_id
     * @return mixed
     */
    public function actionView($item_name, $user_id)
    {
        return $this->render('view', [
            'model' => $this->findModel($item_name, $user_id),
        ]);
    }

    /**
     * Creates a new Assignment model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Assignment();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'item_name' => $model->item_name, 'user_id' => $model->user_id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Assignment model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $item_name
     * @param string $user_id
     * @return mixed
     */
    public function actionUpdate($item_name, $user_id)
    {
        $model = $this->findModel($item_name, $user_id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'item_name' => $model->item_name, 'user_id' => $model->user_id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Assignment model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $item_name
     * @param string $user_id
     * @return mixed
     */
    public function actionDelete($item_name, $user_id)
    {
        $this->findModel($item_name, $user_id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Assignment model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $item_name
     * @param string $user_id
     * @return Assignment the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($item_name, $user_id)
    {
        if (($model = Assignment::findOne(['item_name' => $item_name, 'user_id' => $user_id])) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}


text:
#ifndef CHARACTERTASKSIT_H
#define CHARACTERTASKSIT_H

#include "CharacterTask.h"

class CharacterTaskSit : public CharacterTask {
public:
	CharacterTaskSit();
	virtual ~CharacterTaskSit();

	virtual std::vector<CharacterTaskCondition*> getPrerequisites()const ;
	virtual bool fulfills(const CharacterTaskCondition* condition) const;
	virtual CharacterTaskSit* newWhichFulfills(const CharacterTaskCondition* condition) const;

	virtual bool process(CharacterState& state, irr::f32 tpf);
	virtual bool isCompleted(const CharacterState& state) const;

};

#endif // CHARACTERTASKSIT_H


text:
<?php

namespace Galileo\SettingBundle\Lib\Model\ValueObject;

class Value
{
    private $value;

    public function __construct($value)
    {
        $this->value = $value;
    }

    public static function fromString($string)
    {
        return new Value($string);
    }

    public function value()
    {
        return $this->value;
    }

    public function equalsTo(Value $value)
    {
        return $this->value === $value->value;
    }
}


text:
"use strict";

var _dexie = require("../../dexie");
var _worker = require("../../worker");
var _fakeIndexeddb = require("fake-indexeddb");
var storage = (0, _dexie.getRxStorageDexie)({
  indexedDB: _fakeIndexeddb.indexedDB,
  IDBKeyRange: _fakeIndexeddb.IDBKeyRange
});
(0, _worker.wrappedWorkerRxStorage)({
  storage: storage
});
//# sourceMappingURL=dexie-memory.worker.js.map


text:
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *     Copyright 2012-2020 Couchbase, Inc.
 *
 *   Licensed 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.
 */
#include "config.h"
#include "iotests.h"

class ArithmeticUnitTest : public MockUnitTest
{
};

static lcb_uint64_t arithm_val;

extern "C" {
static void arithmetic_incr_callback(lcb_INSTANCE *, lcb_CALLBACK_TYPE, const lcb_RESPCOUNTER *resp)
{
    ASSERT_EQ(LCB_SUCCESS, lcb_respcounter_status(resp));

    const char *key;
    size_t nkey;
    lcb_respcounter_key(resp, &key, &nkey);
    ASSERT_EQ(7, nkey);
    ASSERT_EQ(0, memcmp(key, "counter", 7));

    uint64_t value;
    lcb_respcounter_value(resp, &value);
    ASSERT_EQ(arithm_val + 1, value);
    arithm_val = value;
}

static void arithmetic_decr_callback(lcb_INSTANCE *, lcb_CALLBACK_TYPE, const lcb_RESPCOUNTER *resp)
{
    ASSERT_EQ(LCB_SUCCESS, lcb_respcounter_status(resp));

    const char *key;
    size_t nkey;
    lcb_respcounter_key(resp, &key, &nkey);
    ASSERT_EQ(7, nkey);
    ASSERT_EQ(0, memcmp(key, "counter", 7));

    uint64_t value;
    lcb_respcounter_value(resp, &value);
    ASSERT_EQ(arithm_val - 1, value);
    arithm_val = value;
}

static void arithmetic_create_callback(lcb_INSTANCE *, lcb_CALLBACK_TYPE, const lcb_RESPCOUNTER *resp)
{
    ASSERT_EQ(LCB_SUCCESS, lcb_respcounter_status(resp));

    const char *key;
    size_t nkey;
    lcb_respcounter_key(resp, &key, &nkey);
    ASSERT_EQ(9, nkey);
    ASSERT_EQ(0, memcmp(key, "mycounter", 9));

    uint64_t value;
    lcb_respcounter_value(resp, &value);
    ASSERT_EQ(0xdeadbeef, value);
}
}

/**
 * Common function to bootstrap an arithmetic key and set the expected/last
 * value counter.
 */
static void initArithmeticKey(lcb_INSTANCE *instance, std::string key, lcb_uint64_t value)
{
    std::stringstream ss;
    ss << value;
    storeKey(instance, key, ss.str());
    arithm_val = value;
}

/**
 * @test Arithmetic (incr)
 * @pre initialize a global variable @c arithm_val to 0.
 * Schedule 10 arithmetic operations. The arithmetic callback should check
 * that the current value is one greater than @c arithm_val. Then set
 * @c arithm_val to the current value.
 *
 * @post The callback's assertions succeed (see precondition)
 */
TEST_F(ArithmeticUnitTest, testIncr)
{
    lcb_INSTANCE *instance;
    HandleWrap hw;
    createConnection(hw, &instance);
    (void)lcb_install_callback(instance, LCB_CALLBACK_COUNTER, (lcb_RESPCALLBACK)arithmetic_incr_callback);

    initArithmeticKey(instance, "counter", 0);

    for (int ii = 0; ii < 10; ++ii) {
        lcb_CMDCOUNTER *cmd;
        lcb_cmdcounter_create(&cmd);
        lcb_cmdcounter_key(cmd, "counter", 7);
        lcb_cmdcounter_delta(cmd, 1);
        lcb_counter(instance, NULL, cmd);
        lcb_cmdcounter_destroy(cmd);
        lcb_wait(instance, LCB_WAIT_DEFAULT);
    }
}

/**
 * @test Arithmetic (Decr)
 *
 * @pre Initialize the @c arithm_val to @c 100. Decrement the key 10 times.
 *
 * @post See @ref testIncr for expectations
 */
TEST_F(ArithmeticUnitTest, testDecr)
{
    lcb_INSTANCE *instance;
    HandleWrap hw;
    createConnection(hw, &instance);
    (void)lcb_install_callback(instance, LCB_CALLBACK_COUNTER, (lcb_RESPCALLBACK)arithmetic_decr_callback);

    initArithmeticKey(instance, "counter", 100);

    for (int ii = 0; ii < 10; ++ii) {
        lcb_CMDCOUNTER *cmd;
        lcb_cmdcounter_create(&cmd);
        lcb_cmdcounter_key(cmd, "counter", 7);
        lcb_cmdcounter_delta(cmd, -1);
        lcb_counter(instance, NULL, cmd);
        lcb_cmdcounter_destroy(cmd);
        lcb_wait(instance, LCB_WAIT_DEFAULT);
    }
}

/**
 * @test Arithmetic (Creation)
 * @pre Perform an arithmetic operation on a non-existent key. The increment
 * offset is @c 0x77 and the default value is @c 0xdeadbeef
 *
 * @post Value upon getting the key is @c 0xdeadbeef
 */
TEST_F(ArithmeticUnitTest, testArithmeticCreate)
{
    lcb_INSTANCE *instance;
    HandleWrap hw;
    createConnection(hw, &instance);

    removeKey(instance, "mycounter");
    (void)lcb_install_callback(instance, LCB_CALLBACK_COUNTER, (lcb_RESPCALLBACK)arithmetic_create_callback);
    lcb_CMDCOUNTER *cmd;
    lcb_cmdcounter_create(&cmd);
    lcb_cmdcounter_key(cmd, "mycounter", 9);
    lcb_cmdcounter_initial(cmd, 0xdeadbeef);
    lcb_cmdcounter_delta(cmd, 0x77);
    lcb_counter(instance, NULL, cmd);
    lcb_cmdcounter_destroy(cmd);
    lcb_wait(instance, LCB_WAIT_DEFAULT);
}


text:
namespace std
{
  typedef short type_t;
  template class basic_ifstream<type_t, char_traits<type_t> >;
} // test


text:
install_package()
{
    print_info COMPONENT "Installing packages '${@}'..."

    translate_packages packages $@

    if [ -n "$packages" ]; then
        pact install "${packages}"
    fi
}

update_system()
{
    print_info COMPONENT "Updating system..."

    pact update
}


text:
<h2>Самое необходимое приложение для будущих и настоящих Келинок </h2>

{% include subscription.html %}


text:
package com.socialize.entity;

/**
 * @author Jason Polites
 *
 */
public class Stats extends SocializeObject {

	private static final long serialVersionUID = 1276943832489224622L;

	private Integer views;
	private Integer likes;
	private Integer comments;
	private Integer shares;

	public Integer getViews() {
		return views;
	}
	public void setViews(Integer views) {
		this.views = views;
	}
	public Integer getLikes() {
		return likes;
	}
	public void setLikes(Integer likes) {
		this.likes = likes;
	}
	public Integer getComments() {
		return comments;
	}
	public void setComments(Integer comments) {
		this.comments = comments;
	}
	public Integer getShares() {
		return shares;
	}
	public void setShares(Integer shares) {
		this.shares = shares;
	}
	@Override
	public int hashCode() {
		return super.hashCode();
	}

	@Override
	public boolean equals(Object obj) {
		return super.equals(obj);
	}
}


text:
#include "qdesigner_formwindow.h"
#include "qdesigner_workbench.h"
#include "formwindowbase_p.h"

// sdk
#include <QtDesigner/QDesignerFormWindowInterface>
#include <QtDesigner/QDesignerFormEditorInterface>
#include <QtDesigner/QDesignerPropertySheetExtension>
#include <QtDesigner/QDesignerPropertyEditorInterface>
#include <QtDesigner/QDesignerFormWindowManagerInterface>
#include <QtDesigner/QDesignerTaskMenuExtension>
#include <QtDesigner/QExtensionManager>

#include <QtCore/QEvent>
#include <QtCore/QFile>

#include <QtGui/QAction>
#include <QtGui/QCloseEvent>
#include <QtGui/QFileDialog>
#include <QtGui/QMessageBox>
#include <QtGui/QPushButton>
#include <QtGui/QVBoxLayout>
#include <QtGui/QUndoCommand>
#include <QtGui/QWindowStateChangeEvent>

QT_BEGIN_NAMESPACE

QDesignerFormWindow::QDesignerFormWindow(QDesignerFormWindowInterface *editor, QDesignerWorkbench *workbench, QWidget *parent, Qt::WindowFlags flags)
    : QWidget(parent, flags),
      m_editor(editor),
      m_workbench(workbench),
      m_action(new QAction(this)),
      m_initialized(false),
      m_windowTitleInitialized(false)
{
    Q_ASSERT(workbench);

    setMaximumSize(0xFFF, 0xFFF);
    QDesignerFormEditorInterface *core = workbench->core();

    if (m_editor) {
        m_editor->setParent(this);
    } else {
        m_editor = core->formWindowManager()->createFormWindow(this);
    }

    QVBoxLayout *l = new QVBoxLayout(this);
    l->setMargin(0);
    l->addWidget(m_editor);

    m_action->setCheckable(true);

    connect(m_editor->commandHistory(), SIGNAL(indexChanged(int)), this, SLOT(updateChanged()));
    connect(m_editor, SIGNAL(geometryChanged()), this, SLOT(geometryChanged()));
    qdesigner_internal::FormWindowBase::setupDefaultAction(m_editor);
}

QDesignerFormWindow::~QDesignerFormWindow()
{
    if (workbench())
        workbench()->removeFormWindow(this);
}

QAction *QDesignerFormWindow::action() const
{
    return m_action;
}

void QDesignerFormWindow::changeEvent(QEvent *e)
{
    switch (e->type()) {
        case QEvent::WindowTitleChange:
            m_action->setText(windowTitle().remove(QLatin1String("[*]")));
            break;
        case QEvent::WindowIconChange:
            m_action->setIcon(windowIcon());
            break;
    case QEvent::WindowStateChange: {
        const  QWindowStateChangeEvent *wsce =  static_cast<const QWindowStateChangeEvent *>(e);
        const bool wasMinimized = Qt::WindowMinimized & wsce->oldState();
        const bool isMinimizedNow = isMinimized();
        if (wasMinimized != isMinimizedNow )
            emit minimizationStateChanged(m_editor, isMinimizedNow);
    }
        break;
        default:
            break;
    }
    QWidget::changeEvent(e);
}

QRect QDesignerFormWindow::geometryHint() const
{
    const QPoint point(0, 0);
    // If we have a container, we want to be just as big.
    // QMdiSubWindow attempts to resize its children to sizeHint() when switching user interface modes.
    if (QWidget *mainContainer = m_editor->mainContainer())
        return QRect(point, mainContainer->size());

    return QRect(point, sizeHint());
}

QDesignerFormWindowInterface *QDesignerFormWindow::editor() const
{
    return m_editor;
}

QDesignerWorkbench *QDesignerFormWindow::workbench() const
{
    return m_workbench;
}

void QDesignerFormWindow::firstShow()
{
    // Set up handling of file name changes and set initial title.
    if (!m_windowTitleInitialized) {
        m_windowTitleInitialized = true;
        if (m_editor) {
            connect(m_editor, SIGNAL(fileNameChanged(QString)), this, SLOT(updateWindowTitle(QString)));
            updateWindowTitle(m_editor->fileName());
            updateChanged();
        }
    }
    show();
}

int QDesignerFormWindow::getNumberOfUntitledWindows() const
{
    const int totalWindows = m_workbench->formWindowCount();
    if (!totalWindows)
        return 0;

    int maxUntitled = 0;
    // Find the number of untitled windows excluding ourselves.
    // Do not fall for 'untitled.ui', match with modified place holder.
    // This will cause some problems with i18n, but for now I need the string to be "static"
    QRegExp rx(QLatin1String("untitled( (\\d+))?\\[\\*\\]"));
    for (int i = 0; i < totalWindows; ++i) {
        QDesignerFormWindow *fw =  m_workbench->formWindow(i);
        if (fw != this) {
            const QString title = m_workbench->formWindow(i)->windowTitle();
            if (rx.indexIn(title) != -1) {
                if (maxUntitled == 0)
                    ++maxUntitled;
                if (rx.captureCount() > 1) {
                    const QString numberCapture = rx.cap(2);
                    if (!numberCapture.isEmpty())
                        maxUntitled = qMax(numberCapture.toInt(), maxUntitled);
                }
            }
        }
    }
    return maxUntitled;
}

void QDesignerFormWindow::updateWindowTitle(const QString &fileName)
{
    if (!m_windowTitleInitialized) {
        m_windowTitleInitialized = true;
        if (m_editor)
            connect(m_editor, SIGNAL(fileNameChanged(QString)), this, SLOT(updateWindowTitle(QString)));
    }

    QString fileNameTitle;
    if (fileName.isEmpty()) {
        fileNameTitle = QLatin1String("untitled");
        if (const int maxUntitled = getNumberOfUntitledWindows()) {
            fileNameTitle += QLatin1Char(' ');
            fileNameTitle += QString::number(maxUntitled + 1);
        }
    } else {
        fileNameTitle = QFileInfo(fileName).fileName();
    }

    if (const QWidget *mc = m_editor->mainContainer()) {
        setWindowIcon(mc->windowIcon());
        setWindowTitle(tr("%1 - %2[*]").arg(mc->windowTitle()).arg(fileNameTitle));
    } else {
        setWindowTitle(fileNameTitle);
    }
}

void QDesignerFormWindow::closeEvent(QCloseEvent *ev)
{
    if (m_editor->isDirty()) {
        raise();
        QMessageBox box(QMessageBox::Information, tr("Save Form?"),
                tr("Do you want to save the changes to this document before closing?"),
                QMessageBox::Discard | QMessageBox::Cancel | QMessageBox::Save, m_editor);
        box.setInformativeText(tr("If you don't save, your changes will be lost."));
        box.setWindowModality(Qt::WindowModal);
        static_cast<QPushButton *>(box.button(QMessageBox::Save))->setDefault(true);

        switch (box.exec()) {
            case QMessageBox::Save: {
                bool ok = workbench()->saveForm(m_editor);
                ev->setAccepted(ok);
                m_editor->setDirty(!ok);
                break;
            }
            case QMessageBox::Discard:
                m_editor->setDirty(false); // Not really necessary, but stops problems if we get close again.
                ev->accept();
                break;
            case QMessageBox::Cancel:
                ev->ignore();
                break;
        }
    }
}

void QDesignerFormWindow::updateChanged()
{
    // Sometimes called after form window destruction.
    if (m_editor) {
        setWindowModified(m_editor->isDirty());
        updateWindowTitle(m_editor->fileName());
    }
}

void QDesignerFormWindow::resizeEvent(QResizeEvent *rev)
{
    if(m_initialized) {
        m_editor->setDirty(true);
        setWindowModified(true);
    }

    m_initialized = true;
    QWidget::resizeEvent(rev);
}

void QDesignerFormWindow::geometryChanged()
{
    // If the form window changes, re-update the geometry of the current widget in the property editor.
    // Note that in the case of layouts, non-maincontainer widgets must also be updated,
    // so, do not do it for the main container only
    const QDesignerFormEditorInterface *core = m_editor->core();
    QObject *object = core->propertyEditor()->object();
    if (object == 0 || !object->isWidgetType())
        return;
    static const QString geometryProperty = QLatin1String("geometry");
    const QDesignerPropertySheetExtension *sheet = qt_extension<QDesignerPropertySheetExtension*>(core->extensionManager(), object);
    const int geometryIndex = sheet->indexOf(geometryProperty);
    if (geometryIndex == -1)
        return;
    core->propertyEditor()->setPropertyValue(geometryProperty, sheet->property(geometryIndex));
}

QT_END_NAMESPACE


text:
/*************************************************************************/
/*  code_editor.h                                                        */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#ifndef CODE_EDITOR_H
#define CODE_EDITOR_H

#include "editor/editor_plugin.h"
#include "scene/gui/check_box.h"
#include "scene/gui/check_button.h"
#include "scene/gui/dialogs.h"
#include "scene/gui/line_edit.h"
#include "scene/gui/text_edit.h"
#include "scene/gui/tool_button.h"
#include "scene/main/timer.h"

class GotoLineDialog : public ConfirmationDialog {
	GDCLASS(GotoLineDialog, ConfirmationDialog);

	Label *line_label;
	LineEdit *line;

	TextEdit *text_editor;

	virtual void ok_pressed();

public:
	void popup_find_line(TextEdit *p_edit);
	int get_line() const;

	GotoLineDialog();
};

class FindReplaceBar : public HBoxContainer {
	GDCLASS(FindReplaceBar, HBoxContainer);

	LineEdit *search_text;
	Label *matches_label;
	ToolButton *find_prev;
	ToolButton *find_next;
	CheckBox *case_sensitive;
	CheckBox *whole_words;
	TextureButton *hide_button;

	LineEdit *replace_text;
	Button *replace;
	Button *replace_all;
	CheckBox *selection_only;

	VBoxContainer *vbc_lineedit;
	HBoxContainer *hbc_button_replace;
	HBoxContainer *hbc_option_replace;

	TextEdit *text_edit;

	int result_line;
	int result_col;
	int results_count;

	bool replace_all_mode;
	bool preserve_cursor;

	void _get_search_from(int &r_line, int &r_col);
	void _update_results_count();
	void _update_matches_label();

	void _show_search(bool p_focus_replace = false, bool p_show_only = false);
	void _hide_bar();

	void _editor_text_changed();
	void _search_options_changed(bool p_pressed);
	void _search_text_changed(const String &p_text);
	void _search_text_entered(const String &p_text);
	void _replace_text_entered(const String &p_text);

protected:
	void _notification(int p_what);
	void _unhandled_input(const Ref<InputEvent> &p_event);

	bool _search(uint32_t p_flags, int p_from_line, int p_from_col);

	void _replace();
	void _replace_all();

	static void _bind_methods();

public:
	String get_search_text() const;
	String get_replace_text() const;

	bool is_case_sensitive() const;
	bool is_whole_words() const;
	bool is_selection_only() const;
	void set_error(const String &p_label);

	void set_text_edit(TextEdit *p_text_edit);

	void popup_search(bool p_show_only = false);
	void popup_replace();

	bool search_current();
	bool search_prev();
	bool search_next();

	FindReplaceBar();
};

typedef void (*CodeTextEditorCodeCompleteFunc)(void *p_ud, const String &p_code, List<ScriptCodeCompletionOption> *r_options, bool &r_forced);

class CodeTextEditor : public VBoxContainer {
	GDCLASS(CodeTextEditor, VBoxContainer);

	TextEdit *text_editor;
	FindReplaceBar *find_replace_bar;
	HBoxContainer *status_bar;

	ToolButton *toggle_scripts_button;
	ToolButton *warning_button;
	Label *warning_count_label;

	Label *line_and_col_txt;

	Label *info;
	Timer *idle;
	Timer *code_complete_timer;

	Timer *font_resize_timer;
	int font_resize_val;
	real_t font_size;

	Label *error;
	int error_line;
	int error_column;

	void _on_settings_change();

	void _update_font();
	void _complete_request();
	Ref<Texture> _get_completion_icon(const ScriptCodeCompletionOption &p_option);
	void _font_resize_timeout();
	bool _add_font_size(int p_delta);

	void _input(const Ref<InputEvent> &event);
	void _text_editor_gui_input(const Ref<InputEvent> &p_event);
	void _zoom_in();
	void _zoom_out();
	void _zoom_changed();
	void _reset_zoom();

	CodeTextEditorCodeCompleteFunc code_complete_func;
	void *code_complete_ud;

	void _warning_label_gui_input(const Ref<InputEvent> &p_event);
	void _warning_button_pressed();
	void _set_show_warnings_panel(bool p_show);
	void _error_pressed(const Ref<InputEvent> &p_event);

	void _delete_line(int p_line);
	void _toggle_scripts_pressed();

protected:
	virtual void _load_theme_settings() {}
	virtual void _validate_script() {}
	virtual void _code_complete_script(const String &p_code, List<ScriptCodeCompletionOption> *r_options) {}

	void _text_changed_idle_timeout();
	void _code_complete_timer_timeout();
	void _text_changed();
	void _line_col_changed();
	void _notification(int);
	static void _bind_methods();

	bool is_warnings_panel_opened;

public:
	void trim_trailing_whitespace();
	void insert_final_newline();

	void convert_indent_to_spaces();
	void convert_indent_to_tabs();

	enum CaseStyle {
		UPPER,
		LOWER,
		CAPITALIZE,
	};
	void convert_case(CaseStyle p_case);

	void move_lines_up();
	void move_lines_down();
	void delete_lines();
	void duplicate_selection();

	/// Toggle inline comment on currently selected lines, or on current line if nothing is selected,
	/// by adding or removing comment delimiter
	void toggle_inline_comment(const String &delimiter);

	void goto_line(int p_line);
	void goto_line_selection(int p_line, int p_begin, int p_end);
	void goto_line_centered(int p_line);
	void set_executing_line(int p_line);
	void clear_executing_line();

	Variant get_edit_state();
	void set_edit_state(const Variant &p_state);

	void set_warning_nb(int p_warning_nb);

	void update_editor_settings();
	void set_error(const String &p_error);
	void set_error_pos(int p_line, int p_column);
	void update_line_and_column() { _line_col_changed(); }
	TextEdit *get_text_edit() { return text_editor; }
	FindReplaceBar *get_find_replace_bar() { return find_replace_bar; }
	virtual void apply_code() {}
	void goto_error();

	void toggle_bookmark();
	void goto_next_bookmark();
	void goto_prev_bookmark();
	void remove_all_bookmarks();

	void set_code_complete_func(CodeTextEditorCodeCompleteFunc p_code_complete_func, void *p_ud);

	void validate_script();

	void show_toggle_scripts_button();
	void update_toggle_scripts_button();

	CodeTextEditor();
};

#endif // CODE_EDITOR_H


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

namespace Xceed.Wpf.DataGrid
{
  public enum CommitMode
  {
    PageReleasedFromMemory = 0,
    EditCommitted = 1
  }
}


text: this is a test Node.js project.


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Class CompetitionCore
   | CodeJam </title>
    <meta name="viewport" content="width=device-width">
    <meta name="title" content="Class CompetitionCore
   | CodeJam ">
    <meta name="generator" content="docfx 2.23.1.0">

    <link rel="shortcut icon" href="../../favicon.ico">
    <link rel="stylesheet" href="../../styles/docfx.vendor.css">
    <link rel="stylesheet" href="../../styles/docfx.css">
    <link rel="stylesheet" href="../../styles/main.css">
    <meta property="docfx:navrel" content="../../toc.html">
    <meta property="docfx:tocrel" content="toc.html">
    <meta property="docfx:rel" content="../../">

              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
                Toggle navigation

              </button>

              <form class="navbar-form navbar-right" role="search" id="search">

                  <input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">

              </form>

          Show / Hide Table of Contents

Class CompetitionCore

Helpers for performance testing infrastructure.

Inheritance

System.Object

CompetitionCore

Inherited Members

      System.Object.ToString()

      System.Object.Equals(System.Object)

      System.Object.Equals(System.Object, System.Object)

      System.Object.ReferenceEquals(System.Object, System.Object)

      System.Object.GetHashCode()

      System.Object.GetType()

      System.Object.MemberwiseClone()

Namespace: CodeJam.PerfTests.Running.Core

Assembly: CodeJam.PerfTests.dll

Syntax

public static class CompetitionCore

Fields

    |
    Improve this Doc

    View Source

RunState

Run state slot.

Declaration

public static readonly RunState<CompetitionState> RunState

Field Value

        Type
        Description

        RunState<CompetitionState>

                    Improve this Doc

                    View Source

              Back to top

            Copyright � 2015-2017


text:
<?xml version="1.0" encoding="UTF-8"?>
<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">
    <parent>
        <artifactId>breezee-pcm</artifactId>
        <groupId>com.breezee</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.breezee</groupId>
    <artifactId>breezee-pcm-service</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>com.breezee</groupId>
            <artifactId>breezee-pcm-api</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>com.breezee</groupId>
            <artifactId>breezee-oms-api</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
    </dependencies>

    <build>
        <finalName>pcmService</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>


text:
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
           xmlns:tools="http://schemas.android.com/tools"
           android:id="@+id/color_indicator"
           android:layout_width="36dp"
           android:layout_height="36dp"
           tools:ignore="ContentDescription"/>


text:
Featured Video

We're improving our products and making lending more efficient for the entire rural housing market.