text:
<?php

namespace Dvsa\Mot\Behat\Support\Data;

use Dvsa\Mot\Behat\Support\Api\MotTest;
use Dvsa\Mot\Behat\Support\Api\Session\AuthenticatedUser;
use Dvsa\Mot\Behat\Support\Data\Params\MotTestParams;
use Dvsa\Mot\Behat\Support\Helper\TestSupportHelper;
use Dvsa\Mot\Behat\Support\Data\Collection\SharedDataCollection;
use Dvsa\Mot\Behat\Support\Data\Params\SiteParams;
use Dvsa\Mot\Behat\Support\Response;
use DvsaCommon\Dto\Common\MotTestDto;
use DvsaCommon\Dto\Common\MotTestTypeDto;
use DvsaCommon\Dto\Person\PersonDto;
use DvsaCommon\Dto\Site\SiteDto;
use DvsaCommon\Dto\Vehicle\VehicleDto;
use DvsaCommon\Enum\VehicleClassCode;
use DvsaCommon\Utility\DtoHydrator;

abstract class AbstractMotTestData extends AbstractData
{
    protected $motTest;
    private $brakeTestResultData;
    private $odometerReadingData;
    private $reasonForRejectionData;
    protected $testSupportHelper;

    protected $motCollection;

    public function __construct(
        UserData $userData,
        MotTest $motTest,
        BrakeTestResultData $brakeTestResultData,
        OdometerReadingData $odometerReadingData,
        ReasonForRejectionData $reasonForRejectionData,
        TestSupportHelper $testSupportHelper
    ) {
        parent::__construct($userData);

        $this->motTest = $motTest;
        $this->brakeTestResultData = $brakeTestResultData;
        $this->odometerReadingData = $odometerReadingData;
        $this->reasonForRejectionData = $reasonForRejectionData;
        $this->testSupportHelper = $testSupportHelper;
        $this->motCollection = SharedDataCollection::get(MotTestDto::class);
    }

    public function passMotTestWithDefaultBrakeTestAndMeterReading(MotTestDto $mot)
    {
        $this->addBrakeTestDecelerometerClass($mot);
        $this->addMeterReading($mot);

        return $this->passMotTest($mot);
    }

    public function passMotTest(MotTestDto $mot)
    {
        $tester = $this->getTester($mot);
        $response = $this->motTest->passed($tester->getAccessToken(), $mot->getMotTestNumber());

        $mot = $this->hydrateResponseToDto($response);
        $this->motCollection->add($mot, $mot->getMotTestNumber());

        return $mot;
    }

    public function passMotTestWithAdvisory(MotTestDto $mot, $rfrId)
    {
        $this->reasonForRejectionData->addAdvisory($mot, $rfrId);

        return $this->passMotTestWithDefaultBrakeTestAndMeterReading($mot);
    }

    public function failMotTestWithAdvisory(MotTestDto $mot, $rfrId)
    {
        $this->reasonForRejectionData->addAdvisory($mot, $rfrId);

        return $this->failMotTestWithDefaultBrakeTestAndMeterReading($mot);
    }

    public function failMotTestWithDefaultBrakeTestAndMeterReading(MotTestDto $mot, $rfrId = null)
    {
        $this->addBrakeTestDecelerometerClass($mot);
        $this->addMeterReading($mot);

        if ($rfrId === null) {
            return $this->failMotTestWithDefaultRfr($mot);
        }

        return $this->failMotTestWithRfr($mot, $rfrId);
    }

    public function failMotTestWithRfr(MotTestDto $mot, $rfrId)
    {
        $this->reasonForRejectionData->addFailure($mot, $rfrId);

        return $this->failMotTest($mot);
    }

    public function failMotTestWithDefaultRfr(MotTestDto $mot)
    {
        $this->reasonForRejectionData->addDefaultFailure($mot);

        return $this->failMotTest($mot);
    }

    public function failMotTest(MotTestDto $mot)
    {
        $tester = $this->getTester($mot);
        $response = $this->motTest->failed($tester->getAccessToken(), $mot->getMotTestNumber());

        $mot = $this->hydrateResponseToDto($response);

        $this->motCollection->add($mot, $mot->getMotTestNumber());

        return $mot;
    }

    public function createFailedMotTestWithRfr(MotTestDto $mot, $rfrId)
    {
        return $this->failMotTestWithManyRfrs($mot, [$rfrId]);
    }

    public function failMotTestWithManyRfrs(MotTestDto $mot, array $rfrs)
    {
        $tester = $this->getTester($mot);

        $this->addBrakeTestDecelerometerClass($mot);
        $this->addMeterReading($mot);

        foreach ($rfrs as $id) {
            $this->reasonForRejectionData->addFailure($mot, $id);
        }

        $response = $this->motTest->failed($tester->getAccessToken(), $mot->getMotTestNumber());

        $mot = $this->hydrateResponseToDto($response);

        $this->motCollection->add($mot, $mot->getMotTestNumber());

        return $mot;
    }

    public function failMotTestWithPrs(MotTestDto $mot, $rfrId = null)
    {
        $tester = $this->getTester($mot);

        $this->addBrakeTestDecelerometerClass($mot);
        $this->addMeterReading($mot);

        if ($rfrId === null) {
            $this->reasonForRejectionData->addDefaultPrs($mot);
        } else {
            $this->reasonForRejectionData->addPrs($mot, $rfrId);
        }

        $response = $this->motTest->passed($tester->getAccessToken(), $mot->getMotTestNumber());

        $mot = $this->hydrateResponseToDto($response);
        $this->motCollection->add($mot, $mot->getMotTestNumber());

        return $mot;
    }

    public function failMotTestWithPrsAlreadyAdded(MotTestDto $mot)
    {
        $tester = $this->getTester($mot);

        $response = $this->motTest->passed($tester->getAccessToken(), $mot->getMotTestNumber());

        $mot = $this->hydrateResponseToDto($response);
        $this->motCollection->add($mot, $mot->getMotTestNumber());

        return $mot;
    }

    public function abandonMotTestByUser(MotTestDto $mot, AuthenticatedUser $user, $cancelReasonId = 23)
    {
        $response = $this->motTest->abandon($user->getAccessToken(), $mot->getMotTestNumber(), $cancelReasonId);

        $mot = $this->hydrateResponseToDto($response);
        $this->motCollection->add($mot, $mot->getMotTestNumber());

        return $mot;
    }

    public function abandonMotTest(MotTestDto $mot, $cancelReasonId = 23)
    {
        $tester = $this->getTester($mot);

        $this->abandonMotTestByUser($mot, $tester, $cancelReasonId);

        return $mot;
    }

    public function abortMotTestByUser(MotTestDto $mot, AuthenticatedUser $user)
    {
        return $this->abandonMotTestByUser($mot, $user, 5);
    }

    public function abortMotTest(MotTestDto $mot)
    {
        return $this->abandonMotTest($mot, 5);
    }

    public function abortMotTestByVE(MotTestDto $mot, AuthenticatedUser $user)
    {
        $response = $this->motTest->abortTestByVE($user->getAccessToken(), $mot->getMotTestNumber());
        $mot = $this->hydrateResponseToDto($response);
        $this->motCollection->add($mot, $mot->getMotTestNumber());

        return $mot;
    }

    protected function addBrakeTestDecelerometerClass(MotTestDto $motTest)
    {
        if ($motTest->getVehicleClass()->getCode() < VehicleClassCode::CLASS_3) {
            $this->brakeTestResultData->addDefaultBrakeTestDecelerometerClass1To2($motTest);
        } else {
            $this->brakeTestResultData->addBrakeTestDecelerometerClass3To7($motTest);
        }
    }

    protected function addMeterReading(MotTestDto $motTest)
    {
        $this->odometerReadingData->addDefaultMeterReading($motTest);
    }

    public function updateLatestMotTestWithNewDvlaVehicleDetails($id, array $data)
    {
        $service = $this->testSupportHelper->getMotService();
        $service->updateLatest($id, $data);
    }

    /**
     * @param int $vehicleId
     *
     * @return int
     */
    public function getLatestMotTestIdForVehicle($vehicleId)
    {
        $service = $this->testSupportHelper->getMotService();
        $mot = $service->getLatestTest($vehicleId);

        return $mot[MotTestParams::ID];
    }

    /**
     * @param MotTestDto $mot
     *
     * @return AuthenticatedUser
     */
    protected function getTester(MotTestDto $mot)
    {
        return $this
            ->userData
            ->get($mot->getTester()->getUsername());
    }

    private function hydrateResponseToDto(Response $response)
    {
        /** @var MotTestDto $dto */
        $dto = DtoHydrator::jsonToDto($response->getBody()->getData());

        return $dto;
    }

    public function get($motTestNumber)
    {
        return $this->motCollection->get($motTestNumber);
    }

    public function tryGet($motTestNumber)
    {
        return $this->motCollection->tryGet($motTestNumber);
    }

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

    public function fetchMotTestData(AuthenticatedUser $user, $motTestNumber)
    {
        $response = $this->motTest->getMotData($user->getAccessToken(), $motTestNumber);

        $mot = $this->hydrateResponseToDto($response);
        $this->motCollection->add($mot, $mot->getMotTestNumber());

        return $mot;
    }

    public function getInProgressTestByUser(AuthenticatedUser $requestor, AuthenticatedUser $tester)
    {
        $motTestNumber = $this->motTest->getInProgressTestId($requestor->getAccessToken(), $tester->getUserId());

        return $this->fetchMotTestData($requestor, $motTestNumber);
    }

    public function getInProgressTest(AuthenticatedUser $user)
    {
        return $this->getInProgressTestByUser($user, $user);
    }

    /**
     * @param $vehicleId
     * @param AuthenticatedUser $tester
     *
     * @return MotTestDto[]
     */
    public function getTestHistory($vehicleId, AuthenticatedUser $tester)
    {
        $response = $this->motTest->getTestHistory($tester->getAccessToken(), $vehicleId);
        $history = [];

        foreach ($response->getBody()->getData() as $datum) {
            $history[] = DtoHydrator::jsonToDto($datum);
        }

        return $history;
    }

    /**
     * @return Response
     */
    public function getLastResponse()
    {
        return $this->motTest->getLastResponse();
    }

    /**
     * @param AuthenticatedUser $tester
     * @param VehicleDto        $vehicle
     * @param int               $motTestNumber
     * @param string            $motTestType
     * @param SiteDto|null      $site
     *
     * @return MotTestDto
     */
    protected function mapToMotTestDto(
        AuthenticatedUser $tester,
        VehicleDto $vehicle,
        $motTestNumber,
        $motTestType,
        SiteDto $site = null
    ) {
        $personDto = new PersonDto();
        $personDto
            ->setId($tester->getUserId())
            ->setUsername($tester->getUsername());

        $typeDto = new MotTestTypeDto();
        $typeDto->setCode($motTestType);

        $vts = [];
        if ($site !== null) {
            $vts = [
                SiteParams::NAME => $site->getName(),
                'address' => [],
                SiteParams::SITE_NUMBER => $site->getSiteNumber(),
            ];
        }

        $dto = new MotTestDto();
        $dto
            ->setMotTestNumber($motTestNumber)
            ->setTester($personDto)
            ->setVehicle($vehicle)
            ->setVehicleClass($vehicle->getVehicleClass())
            ->setTestType($typeDto)
            ->setVehicleTestingStation($vts);

        return $dto;
    }
}


text:
package org.katlas.JavaKh.rows;

import org.katlas.JavaKh.utils.RedBlackIntegerTree;

public class RedBlackIntegerMap<F> extends RedBlackIntegerTree<F> implements MatrixRow<F> {

	/**
	 *
	 */
	private static final long serialVersionUID = 5885667469881867107L;

	public void compact() {

	}

	public void putLast(int key, F f) {
		put(key, f);
	}

	@Override
	public void put(int key, F value) {
		if(value == null) {
			remove(key);
		} else {
			super.put(key, value);
		}
	}

}

redpajama_set_name: RedPajamaGithub


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

namespace Ploeh.Samples.HelloDI.CommandLine
{
    public class SecureMessageWriter : IMessageWriter
    {
        private readonly IMessageWriter writer;

        public SecureMessageWriter(IMessageWriter writer)
        {
            if (writer == null)
            {
                throw new ArgumentNullException("writer");
            }

            this.writer = writer;
        }

        public void Write(string message)
        {
            if (Thread.CurrentPrincipal.Identity
                .IsAuthenticated)
            {
                this.writer.Write(message);
            }
        }
    }
}


text:
class InfrastructureTaskFormatter
  def call(severity, time, progname, msg)
    "#{time.strftime('%Y-%m-%d %H:%M:%S')} #{msg.strip}\n"
  end
end

class InfrastructureTaskLogger
  @@mutex = Mutex.new
  @@infrastructures_logger = Logger.new("#{Rails.root}/log/infrastructures.log", 5, 1024*1024*100)
  @@infrastructures_logger.formatter = InfrastructureTaskFormatter.new

  def self.logger
    @@mutex.synchronize do
      @@infrastructures_logger
    end
  end

  def initialize(infrastructure_name, job_record=nil)
    if job_record
      @log_format = Proc.new do |message|
        "[#{infrastructure_name}][Exp: #{job_record.experiment_id}][SiM: #{job_record.id}][Res: #{job_record.resource_id}] - #{message}"
      end
    else
      @log_format = Proc.new do |message|
        "[#{infrastructure_name}] - #{message}"
      end
    end
  end

  def method_missing(method_name, *args, &block)
    if %w(info debug warn error).include? method_name.to_s
      InfrastructureTaskLogger.logger.send(method_name.to_s, @log_format.call(args[0], block))
    else
      super(method_name, *args, &block)
    end
  end
end


text:
package org.march.server;

import org.march.server.endpoint.*;
import org.march.data.Resource;
import org.march.data.ResourceConnector;
import org.march.sync.endpoint.ChangeSet;
import org.march.sync.endpoint.UpdateException;
import org.march.sync.master.DuplicateRegistrationException;
import org.march.sync.master.Master;
import org.march.sync.master.MasterException;
import org.march.sync.master.MasterState;
import org.march.sync.transform.Transformer;

import java.util.*;

public class Server {

    private ResourceConnector resourceConnector;

    private Map<String, Transformer> transformers;

    private Map<String, Master> masters;

    private Map<UUID, MessageEndpoint> routes;

    public Server(){
        this.transformers = Collections.synchronizedMap(new HashMap<>());

        this.masters = Collections.synchronizedMap(new HashMap<>());

        this.routes = Collections.synchronizedMap(new HashMap<>());

    }

    public void start(){
        //todo: change state
        // start scheduler thread maintenance
    }

    public void stop(){
        //overkill
    }

    public void addClient(MessageEndpoint messageEndpoint){
        // todo: check state

        MessageListener messageListener = new MessageListener() {
            @Override
            public void receive(Message message) {
                Server.this.receive(messageEndpoint, message);
            }
        };

        messageEndpoint.setMessageListener(messageListener);
    }

    public void removeClient(MessageEndpoint messageEndpoint){
        messageEndpoint.setMessageListener(null);

        //todo: look for all know routes for replicas, remove routes and unregister replicas from master
        //todo: else throw server exception
    }

    public void addTransformer(String schema, Transformer transformer){
        transformers.put(schema, transformer);
    }

    public void removeTransformer(String schema){
        transformers.remove(schema);
    }

    public ResourceConnector getResourceConnector() {
        return resourceConnector;
    }

    public void setResourceConnector(ResourceConnector resourceConnector) {
        this.resourceConnector = resourceConnector;
    }

    private void receive(MessageEndpoint endpoint, Message message){
        if(message instanceof UpdateMessage){
            receive(endpoint, (UpdateMessage)message);
        } else if (message instanceof ReplicateMessage){
            receive(endpoint, (ReplicateMessage)message);
        }
    }

    private void receive(MessageEndpoint endpoint, UpdateMessage updateMessage){
        String scope = updateMessage.getScope();
        Master master = masters.get(scope);
        try {
            AbstractUpdateEndpoint updateEndpoint = (AbstractUpdateEndpoint)master.getEndpoint();
            updateEndpoint.receive(updateMessage.getReplicaName(), updateMessage.getChangeSet());
        } catch (UpdateException e) {
            endpoint.send(
                    new ErrorMessage(
                            updateMessage.getReplicaName(),
                            String.format("Cannot delegate update for replica '%s'.", updateMessage.getReplicaName()),
                            ErrorCode.INTERNAL_SERVER_ERROR));
        }
    }

    private void receive(MessageEndpoint endpoint, ReplicateMessage replicateMessage){
        Master master = null;

        synchronized (masters) {
            if (masters.containsKey(replicateMessage.getScope()) &&
                    masters.get(replicateMessage.getScope()).getState() != MasterState.ACTIVE) {

                // todo: sort out when this situation could occur
                endpoint.send(new ErrorMessage(replicateMessage.getReplicaName(), "Master not active.", ErrorCode.METHOD_NOT_ALLOWED));

            } else if (!masters.containsKey(replicateMessage.getScope())) {

                String scope = replicateMessage.getScope();
                Resource resource = resourceConnector.get(scope);
                if (resource == null) {
                    endpoint.send(
                            new ErrorMessage(
                                    replicateMessage.getReplicaName(),
                                    String.format("Resource '%s' not found.", replicateMessage.getScope()),
                                    ErrorCode.RESOURCE_NOT_FOUND));

                }

                Transformer transformer = transformers.get(resource.getType());
                if (transformer == null) {
                    endpoint.send(
                            new ErrorMessage(
                                    replicateMessage.getReplicaName(),
                                    String.format("No transformer for operations on '%s' found.", replicateMessage.getScope()),
                                    ErrorCode.UNSUPPORTED_MEDIA_TYPE));
                }

                master = new Master(new AbstractUpdateEndpoint() {
                    @Override
                    public void send(UUID replicaName, ChangeSet changeSet) throws UpdateException {
                        MessageEndpoint channel = Server.this.routes.get(replicaName);
                        channel.send(new UpdateMessage(scope, replicaName, changeSet));
                    }
                });

                masters.put(scope, master);

                try {
                    master.activate(resource, transformer);
                } catch (DuplicateRegistrationException e) {
                    endpoint.send(
                            new ErrorMessage(
                                    replicateMessage.getReplicaName(),
                                    String.format("Replica already registered '%s'.", replicateMessage.getScope()),
                                    ErrorCode.DUPLICATE_REGISTRATION));
                } catch (MasterException e) {
                    endpoint.send(
                            new ErrorMessage(
                                    replicateMessage.getReplicaName(),
                                    String.format("Cannot initialize replication master for '%s'.", replicateMessage.getScope()),
                                    ErrorCode.INTERNAL_SERVER_ERROR));
                }
            }
        }

        this.routes.put(replicateMessage.getReplicaName(), endpoint);

        try {
            master.register(replicateMessage.getReplicaName());
        } catch (MasterException e) {
            endpoint.send(
                    new ErrorMessage(
                            replicateMessage.getReplicaName(),
                            String.format("Failed to register replica for '%s'.", replicateMessage.getScope()),
                            ErrorCode.INTERNAL_SERVER_ERROR));
        }
    }

    private void receive(MessageEndpoint endpoint, ErrorMessage errorMessage){
        //todo: something smart
    }

}


text:
#ifdef HAVE_UNISTD_H
  #include <unistd.h>
#endif
// Qt includes
#include <QDebug>
#include <QFileInfo>
#include <QMainWindow>
#include <QMessageBox>
#include <QStandardItem>
#include <QXmlStreamWriter>
#include <QErrorMessage>

// QtPropertyBrowser includes
#include <QtVariantPropertyManager>
#include <QtVariantProperty>

#include <QNetworkAccessManager>
#include <QUrl>
#include <QNetworkReply>
#include <QNetworkRequest>

// Visomics includes
#include "voAnalysis.h"
#include "voAnalysisDriver.h"
#include "voApplication.h"
#include "voDataModel.h"
#include "voDataModelItem.h"
#include "voInputFileDataObject.h"
#include "voIOManager.h"
#include "voRegistry.h"
#include "voUtils.h"
#include "vtkExtendedTable.h"

// VTK includes
#include <vtkDelimitedTextReader.h>
#include <vtkDelimitedTextWriter.h>
#include <vtkDoubleArray.h>
#include <vtkGenericDataObjectWriter.h>
#include <vtkNew.h>
#include <vtkSmartPointer.h>
#include <vtkStringArray.h>
#include <vtkTable.h>
#include <vtkMultiNewickTreeReader.h>
#include <vtkNewickTreeReader.h>
#include <vtkMultiPieceDataSet.h>
#include <vtkGraphLayoutView.h>
#include <vtkTree.h>

// --------------------------------------------------------------------------
voIOManager::voIOManager()
{
}

// --------------------------------------------------------------------------
voIOManager::~voIOManager()
{
}

// --------------------------------------------------------------------------
bool voIOManager::readCSVFileIntoTable(const QString& fileName, vtkTable * outputTable, const voDelimitedTextImportSettings& settings, const bool haveHeaders)
{
  if (!outputTable)
    {
    return false;
    }

  vtkNew<vtkDelimitedTextReader> reader;
  reader->SetFileName(fileName.toLatin1());

  // Configure reader
  reader->SetFieldDelimiterCharacters(
        settings.value(voDelimitedTextImportSettings::FieldDelimiterCharacters).toString().toLatin1());
  reader->SetMergeConsecutiveDelimiters(
        settings.value(voDelimitedTextImportSettings::MergeConsecutiveDelimiters).toBool());
  reader->SetStringDelimiter(
        settings.value(voDelimitedTextImportSettings::StringDelimiter).toChar().toLatin1());
  reader->SetUseStringDelimiter(
        settings.value(voDelimitedTextImportSettings::UseStringDelimiter).toBool());
  reader->SetHaveHeaders(haveHeaders);
  reader->DetectNumericColumnsOn();

  // Read data
  reader->Update();

  outputTable->ShallowCopy(reader->GetOutput());

  return true;
}

// --------------------------------------------------------------------------
bool voIOManager::readCSVFileIntoExtendedTable(const QString& fileName,
                                               vtkExtendedTable *outputTable,
                                               const voDelimitedTextImportSettings& settings)
{
  if (!outputTable)
    {
    return false;
    }

  vtkNew<vtkTable> dataTable;
  vtkNew<vtkTable> inputToExtendedTable;
  Self::readCSVFileIntoTable(fileName, dataTable.GetPointer(), settings, true);
  Self::readCSVFileIntoTable(fileName, inputToExtendedTable.GetPointer(), settings, false);
  Self::fillExtendedTable(inputToExtendedTable.GetPointer(), outputTable, settings);

  bool transpose = settings.value(voDelimitedTextImportSettings::Transpose).toBool();
  if (transpose)
    {
    voUtils::transposeTable(dataTable.GetPointer(), voUtils::Headers);
    }

  outputTable->SetInputDataTable(dataTable.GetPointer());

  return true;
}

// --------------------------------------------------------------------------
bool voIOManager::writeTableToCVSFile(vtkTable* table, const QString& fileName)
{
  if (!table)
    {
    return false;
    }

  vtkNew<vtkDelimitedTextWriter> writer;

  voDelimitedTextImportSettings settings;

  // Configure writer
  writer->SetFieldDelimiter(
        settings.value(voDelimitedTextImportSettings::FieldDelimiterCharacters).toString().toLatin1());
  writer->SetStringDelimiter(
        QString(settings.value(voDelimitedTextImportSettings::StringDelimiter).toChar()).toLatin1());
  writer->SetUseStringDelimiter(
        settings.value(voDelimitedTextImportSettings::UseStringDelimiter).toBool());

  writer->SetFileName(fileName.toLatin1());

  writer->SetInputData(table);
  writer->Update();

  return true;
}

// --------------------------------------------------------------------------
void voIOManager::fillExtendedTable(vtkTable* sourceTable, vtkExtendedTable* destTable,
                                    const voDelimitedTextImportSettings& settings)
{
  // vtkExtendedTable settings
  bool transpose = settings.value(voDelimitedTextImportSettings::Transpose).toBool();
  if (transpose)
    {
    voUtils::transposeTable(sourceTable);
    }

  int numberOfRowMetaDataTypes =
      settings.value(voDelimitedTextImportSettings::NumberOfRowMetaDataTypes).toInt();
  int numberOfColumnMetaDataTypes =
      settings.value(voDelimitedTextImportSettings::NumberOfColumnMetaDataTypes).toInt();

  Q_ASSERT(numberOfColumnMetaDataTypes <= sourceTable->GetNumberOfRows());

  //sourceTable->Dump();

  // ColumnMetaData
  vtkNew<vtkTable> columnMetaData;
  for (int cid = numberOfRowMetaDataTypes; cid < sourceTable->GetNumberOfColumns(); ++cid)
    {
    vtkStringArray * column = vtkStringArray::SafeDownCast(sourceTable->GetColumn(cid));
    Q_ASSERT(column);
    for (int rid = 0; rid < numberOfColumnMetaDataTypes; ++rid)
      {
      vtkSmartPointer<vtkStringArray> newColumn;
      if (cid == numberOfRowMetaDataTypes)
        {
        newColumn = vtkSmartPointer<vtkStringArray>::New();
        newColumn->SetNumberOfValues(sourceTable->GetNumberOfColumns() - numberOfRowMetaDataTypes);
        columnMetaData->AddColumn(newColumn);
        }
      else
        {
        newColumn = vtkStringArray::SafeDownCast(columnMetaData->GetColumn(rid));
        }
      Q_ASSERT(newColumn);
      vtkStdString value = column->GetValue(rid);
      newColumn->SetValue(cid - numberOfRowMetaDataTypes, value);
      }
    }

  //columnMetaData->Dump();

  // ColumnMetaDataLabels
  vtkNew<vtkStringArray> columnMetaDataLabels;
  if (numberOfRowMetaDataTypes > 0) // If there are no row metadata types, there is no room for column metadata labels
    {
    for (int rid = 0; rid < numberOfColumnMetaDataTypes; rid++)
      {
      columnMetaDataLabels->InsertNextValue(sourceTable->GetValue(rid, 0).ToString());
      }
    }

  // RowMetaData
  vtkNew<vtkTable> rowMetaData;
  Q_ASSERT(numberOfRowMetaDataTypes <= sourceTable->GetNumberOfColumns());
  for (int cid = 0; cid < numberOfRowMetaDataTypes; ++cid)
    {
    vtkStringArray * column = vtkStringArray::SafeDownCast(sourceTable->GetColumn(cid));
    Q_ASSERT(column);
    for (int rid = numberOfColumnMetaDataTypes; rid < column->GetNumberOfValues(); ++rid)
      {
      vtkSmartPointer<vtkStringArray> newColumn;
      if (rid == numberOfColumnMetaDataTypes)
        {
        newColumn = vtkSmartPointer<vtkStringArray>::New();
        newColumn->SetNumberOfValues(sourceTable->GetNumberOfRows() - numberOfColumnMetaDataTypes);
        rowMetaData->AddColumn(newColumn);
        }
      else
        {
        newColumn = vtkStringArray::SafeDownCast(rowMetaData->GetColumn(cid));
        }
      Q_ASSERT(newColumn);
      vtkStdString value = column->GetValue(rid);
      newColumn->SetValue(rid - numberOfColumnMetaDataTypes, value);
      }
    }

  //rowMetaData->Dump();

  // RowMetaDataLabels
  vtkNew<vtkStringArray> rowMetaDataLabels;
  if (numberOfColumnMetaDataTypes > 0) // If there are no column metadata types, there is no room for row metadata labels
    {
    for (int cid = 0; cid < numberOfRowMetaDataTypes; cid++)
      {
      rowMetaDataLabels->InsertNextValue(sourceTable->GetValue(0, cid).ToString());
      }
    }

  // Data
  vtkNew<vtkTable> data;
  for (int cid = numberOfRowMetaDataTypes; cid < sourceTable->GetNumberOfColumns(); ++cid)
    {
    vtkStringArray * column = vtkStringArray::SafeDownCast(sourceTable->GetColumn(cid));
    Q_ASSERT(column);

    // determine whether this column contains numerical or categorical data.
    vtkNew<vtkDoubleArray> doubleColumn;
    vtkNew<vtkStringArray> stringColumn;
    vtkStdString value = column->GetValue(numberOfColumnMetaDataTypes);
    bool dataIsNumerical = false;
    vtkVariant(value).ToDouble(&dataIsNumerical);
    if (dataIsNumerical)
      {
      doubleColumn->SetNumberOfValues(
        sourceTable->GetNumberOfRows() - numberOfColumnMetaDataTypes);
      data->AddColumn(doubleColumn.GetPointer());
      }
    else
      {
      stringColumn->SetNumberOfValues(
        sourceTable->GetNumberOfRows() - numberOfColumnMetaDataTypes);
      data->AddColumn(stringColumn.GetPointer());
      }

    for (int rid = numberOfColumnMetaDataTypes; rid < column->GetNumberOfValues(); ++rid)
      {
      vtkStdString value = column->GetValue(rid);
      if (dataIsNumerical)
        {
        // Convert to numeric
        bool ok = false;
        double doubleValue = vtkVariant(value).ToDouble(&ok);
        if (!ok)
          {
          qCritical() << "Data at column" << cid << "and row" << rid << "is not a numeric value !"
                      << " - Defaulting to 0";
          doubleValue = 0;
          }
        doubleColumn->SetValue(rid - numberOfColumnMetaDataTypes, doubleValue);
        }
      else
        {
        stringColumn->SetValue(rid - numberOfColumnMetaDataTypes, value);
        }
      }
    }

  // ColumnMetaDataTypeOfInterest
  int columnMetaDataTypeOfInterest =
      settings.value(voDelimitedTextImportSettings::ColumnMetaDataTypeOfInterest).toInt();

  // RowMetaDataTypeOfInterest
  int rowMetaDataTypeOfInterest =
      settings.value(voDelimitedTextImportSettings::RowMetaDataTypeOfInterest).toInt();

  destTable->SetColumnMetaDataTable(columnMetaData.GetPointer());
  destTable->SetRowMetaDataTable(rowMetaData.GetPointer());
  destTable->SetData(data.GetPointer());
  destTable->SetColumnMetaDataTypeOfInterest(columnMetaDataTypeOfInterest);
  destTable->SetRowMetaDataTypeOfInterest(rowMetaDataTypeOfInterest);
  destTable->SetColumnMetaDataLabels(columnMetaDataLabels.GetPointer());
  destTable->SetRowMetaDataLabels(rowMetaDataLabels.GetPointer());

  // Set column names
  voUtils::setTableColumnNames(destTable->GetData(), destTable->GetColumnMetaDataOfInterestAsString());

  // NormalizationMethod
  QString normalizationMethod =
      settings.value(voDelimitedTextImportSettings::NormalizationMethod).toString();

  // Normalize
  if (voApplication::application())
    {
    voApplication::application()->normalizerRegistry()->apply(
          normalizationMethod, destTable->GetData(), settings);
    }
}

// --------------------------------------------------------------------------
void voIOManager::openCSVFile(const QString& fileName, const voDelimitedTextImportSettings& settings)
{
  vtkNew<vtkExtendedTable> extendedTable;
  Self::readCSVFileIntoExtendedTable(fileName, extendedTable.GetPointer(),
                                     settings);
  voInputFileDataObject * dataObject =
      new voInputFileDataObject(fileName, extendedTable.GetPointer());

  tableSettings.insert(dataObject, const_cast<voDelimitedTextImportSettings&>(settings));

  voDataModel * model = voApplication::application()->dataModel();
  voDataModelItem * newItem = model->addDataObject(dataObject);
  newItem->setRawViewType("voExtendedTableView");

  // Select added item
  model->setSelected(newItem);
}

// --------------------------------------------------------------------------
void voIOManager::loadPhyloTreeDataSet(const QString& fileName)
{
  // load the phylo tree data set file
  vtkSmartPointer<vtkMultiNewickTreeReader> reader =
        vtkSmartPointer<vtkMultiNewickTreeReader>::New();

  reader->SetFileName(fileName.toStdString().c_str());
  vtkMultiPieceDataSet * forest = reader->GetOutput();
  reader->Update();

  voDataModel * model = voApplication::application()->dataModel();

  if (forest->GetNumberOfPieces() == 1)
     { //single tree
     vtkTree * tree =  vtkTree::SafeDownCast( forest->GetPieceAsDataObject(0));
     voInputFileDataObject * dataObject =
       new voInputFileDataObject(fileName, tree);
     voDataModelItem * newItem = model->addDataObject(dataObject);
     newItem->setRawViewType("voTreeHeatmapView");

     model->setSelected(newItem);
     }
  else
     {//multiple trees --forest
     voDataObject * emptyDataObject = new voDataObject(QFileInfo(fileName).baseName(),NULL);
     voDataModelItem * newForestItem = model->addDataObject(emptyDataObject);
     for (unsigned int i = 0; i < forest->GetNumberOfPieces(); i++)
       {
       vtkTree * tree =  vtkTree::SafeDownCast( forest->GetPieceAsDataObject(i));
       QString displayName = QString("tree-%1").arg(QString::number(i));
       voInputFileDataObject * dataObject = new voInputFileDataObject(displayName, tree);
       voDataModelItem * treeItem = model->addDataObjectAsChild(dataObject, newForestItem);
       treeItem->setRawViewType("voTreeHeatmapView");

       newForestItem->addChildItem(treeItem);
       }
     model->setSelected(newForestItem);
     }
}

// --------------------------------------------------------------------------
void voIOManager::loadPhyloTreeDataSet(const QString& fileName,
  const QString & tableFileName, const voDelimitedTextImportSettings& settings )
{
  // load the phylo tree
  vtkSmartPointer<vtkMultiNewickTreeReader> reader =
        vtkSmartPointer<vtkMultiNewickTreeReader>::New();
  reader->SetFileName(fileName.toStdString().c_str());
  vtkMultiPieceDataSet * forest = reader->GetOutput();
  reader->Update();

  // load the associated table data
  vtkNew<vtkExtendedTable> extendedTable;
  Self::readCSVFileIntoExtendedTable(tableFileName, extendedTable.GetPointer(),
                                     settings);
  voInputFileDataObject * tableObject = new voInputFileDataObject(
    tableFileName, extendedTable.GetPointer());

  tableSettings.insert(tableObject,
                       const_cast<voDelimitedTextImportSettings&>(settings));

  //single tree
  if (forest->GetNumberOfPieces() == 1)
    {
    vtkTree * tree =  vtkTree::SafeDownCast( forest->GetPieceAsDataObject(0));

    voInputFileDataObject * treeObject =
      new voInputFileDataObject(fileName, tree);

    this->createTreeHeatmapItem(
      "TreeHeatmap",
      dynamic_cast<voDataObject*>(treeObject),
      dynamic_cast<voDataObject*>(tableObject));
    }

  // multiple trees
  else
    {
    QList<voDataObject *> treeObjects;
    for (unsigned int i = 0; i < forest->GetNumberOfPieces(); i++)
      {
      vtkTree * tree =  vtkTree::SafeDownCast( forest->GetPieceAsDataObject(i));
      QString displayName = QString("tree-%1").arg(QString::number(i));
      voDataObject * treeObject = new voDataObject(displayName, tree);
      treeObjects << treeObject;
      }

    this->createTreeHeatmapItem("TreeHeatmap", treeObjects,
                                dynamic_cast<voDataObject*>(tableObject));
    }
}

// --------------------------------------------------------------------------
void voIOManager::createTreeHeatmapItem(QString name,
                                        voDataModelItem * parent,
                                        voDataObject * treeObject,
                                        voDataObject * tableObject)
{
  voDataModel * model = voApplication::application()->dataModel();

  // create a new item for our TreeHeatmap
  voDataObject * emptyDataObject = new voDataObject(name, NULL);
  voDataModelItem * newItem;
  if (parent)
    {
    newItem = model->addDataObjectAsChild(emptyDataObject,parent);
    }
  else
    {
    newItem = model->addDataObject(emptyDataObject);
    }

  // create a DataModelItem for our tree
  voDataModelItem * treeItem = model->addDataObjectAsChild(treeObject, newItem);
  treeItem->setType(voDataModelItem::InputType);
  treeItem->setRawViewType("voTreeHeatmapView");
  newItem->addChildItem(treeItem);

  // do the same for our table
  voDataModelItem * tableItem = model->addDataObjectAsChild(tableObject, newItem);
  tableItem->setType(voDataModelItem::InputType);
  tableItem->setRawViewType("voExtendedTableView");
  newItem->addChildItem(tableItem);

  // set up the visualization of the new TreeHeatmap
  newItem->setRawViewType("voTreeHeatmapView");
  newItem->setType(voDataModelItem::InputType);

  model->setSelected(newItem);
}

// --------------------------------------------------------------------------
void voIOManager::createTreeHeatmapItem(QString name,
                                        voDataObject * treeObject,
                                        voDataObject * tableObject)
{
  createTreeHeatmapItem(name,NULL,treeObject,tableObject);
}

// --------------------------------------------------------------------------
void voIOManager::createTreeHeatmapItem(QString name,
                                        QList<voDataObject *> treeObjects,
                                        voDataObject * tableObject)
{
  voDataModel * model = voApplication::application()->dataModel();

  // create a new item for our TreeHeatmap
  voDataObject * emptyDataObject = new voDataObject(name, NULL);
  voDataModelItem * newItem = model->addDataObject(emptyDataObject);

  // create a DataModelItem for each of our trees
  for (int i = 0; i < treeObjects.size(); ++i)
    {
    voDataObject * treeObject = treeObjects[i];
    voDataModelItem * treeItem = model->addDataObjectAsChild(treeObject, newItem);
    treeItem->setRawViewType("voTreeHeatmapView");
    newItem->addChildItem(treeItem);
    }

  // do the same for our table
  voDataModelItem * tableItem = model->addDataObjectAsChild(tableObject, newItem);
  tableItem->setType(voDataModelItem::InputType);
  tableItem->setRawViewType("voExtendedTableView");
  newItem->addChildItem(tableItem);

  // set up the visualization of the new TreeHeatmap
  newItem->setRawViewType("voTreeHeatmapView");
  newItem->setType(voDataModelItem::InputType);

  model->setSelected(newItem);
}

// --------------------------------------------------------------------------
bool voIOManager::writeDataObjectToFile(vtkDataObject * dataObject, const QString& fileName)
{
  if (!dataObject)
    {
    return false;
    }

  vtkNew<vtkGenericDataObjectWriter> dataWriter;
  dataWriter->SetFileName(fileName.toLatin1());
  dataWriter->SetInputData(dataObject);
  dataWriter->Update();

  return true;
}

// --------------------------------------------------------------------------
void voIOManager::saveWorkflowToFile(const QString& fileName)
{
  QFile file(fileName);
  if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
  {
    qCritical() << "Could not open " << fileName << " for writing!";
    return;
  }

  QXmlStreamWriter stream(&file);
  stream.setAutoFormatting(true);
  stream.writeStartDocument();
  stream.writeStartElement("workflow");

  QStandardItem *parent = NULL;
  this->writeItemToXML(parent, &stream);
  this->writeAnalysesToXML(&stream);

  stream.writeEndElement(); //workflow
  stream.writeEndDocument();
}

// --------------------------------------------------------------------------
void voIOManager::writeItemToXML(QStandardItem* parent,
                                 QXmlStreamWriter *stream)
{
  voDataModel * dataModel = voApplication::application()->dataModel();

  if (!parent)
    {
    parent = dataModel->invisibleRootItem();
    }

  for (int row = 0; row < dataModel->rowCount(parent->index()); ++row)
    {
    for (int col = 0; col < dataModel->columnCount(parent->index()); ++col)
      {
      voDataModelItem *item =
        dynamic_cast<voDataModelItem*>(
        dataModel->itemFromIndex(dataModel->index(row, col, parent->index())));

      if (item->data(voDataModelItem::IsAnalysisContainerRole).toBool())
        {
        continue; // we record analyses later during a separate step.
        }

      else if (item->type() == voDataModelItem::InputType)
        {
        // Only record top-level input.  Child input objects are saved
        // with their parents.
        if (parent != dataModel->invisibleRootItem())
          {
          if (dataModel->hasChildren(item->index()))
            {
            this->writeItemToXML(item, stream);
            }
          continue;
          }

        if (item->rawViewType() == "voTreeHeatmapView")
          {
          if (item->text().contains("TreeHeatmap"))
            {
            this->writeTreeHeatmapToXML(item, stream);
            }
          else
            {
            this->writeInputToXML("Tree", item, stream);
            }
          }
        else if(item->rawViewType() == "voExtendedTableView" ||
                item->rawViewType() == "voTableView")
          {
          this->writeInputToXML("Table", item, stream);
          }
        }

      if (dataModel->hasChildren(item->index()))
        {
        this->writeItemToXML(item, stream);
        }
      }
    }
}

// --------------------------------------------------------------------------
void voIOManager::writeAnalysesToXML(QXmlStreamWriter *stream)
{
  voDataModel * dataModel = voApplication::application()->dataModel();
  const QList<voDataModelItem *> analyses = dataModel->analyses();
  foreach (voDataModelItem *item, analyses)
    {
    this->writeAnalysisToXML(item, stream);
    }
}

// --------------------------------------------------------------------------
void voIOManager::writeAnalysisToXML(voDataModelItem *item,
                                     QXmlStreamWriter *stream)
{
  stream->writeStartElement("analysis");

  voAnalysis *analysis = reinterpret_cast<voAnalysis*>(
        item->data(voDataModelItem::AnalysisVoidStarRole).value<void*>());
  QString analysisName = analysis->objectName();
  stream->writeAttribute("type", analysisName);

  voDataModelItem *parentItem =
    dynamic_cast<voDataModelItem*>(item->parent());
  stream->writeStartElement("parent");
  stream->writeCharacters(parentItem->text());
  stream->writeEndElement(); // parent

  QSet<QtProperty*> properties = analysis->propertyManager()->properties();
  stream->writeStartElement("parameters");
  foreach (QtProperty* property, properties)
    {
    QtVariantProperty* variantProperty =
      dynamic_cast<QtVariantProperty*>(property);
    if (!variantProperty ||
        variantProperty->propertyType() ==
        QtVariantPropertyManager::groupTypeId())
      {
      continue;
      }
    stream->writeStartElement("parameter");
    stream->writeAttribute("name", variantProperty->propertyId());
    stream->writeAttribute("type", QString::number(variantProperty->propertyType()));
    stream->writeCharacters(variantProperty->value().toString());
    stream->writeEndElement(); // parameter
    }
  stream->writeEndElement(); // parameters
  stream->writeEndElement(); // analysis
}

// --------------------------------------------------------------------------
void voIOManager::writeTreeHeatmapToXML(voDataModelItem *item,
                                        QXmlStreamWriter *stream)
{
  stream->writeStartElement("input");
  stream->writeAttribute("type", "TreeHeatmap");
  // Children are saved as rows (not columns)
  for (int i = 0; i < item->rowCount(); ++i)
    {
    voDataModelItem *childItem =
      dynamic_cast<voDataModelItem*>(item->child(i));
    voInputFileDataObject *inputObject =
      dynamic_cast<voInputFileDataObject*>(childItem->dataObject());
    if (!inputObject)
      {
      continue;
      }
    stream->writeStartElement("input");
    if(childItem->rawViewType() == "voExtendedTableView" ||
       childItem->rawViewType() == "voTableView")
      {
      stream->writeAttribute("type", "Table");
      this->writeTableSettingsToXML(childItem, stream);
      }
    else
      {
      stream->writeAttribute("type", "Tree");
      }
    stream->writeStartElement("filename");
    stream->writeCharacters(inputObject->fileName());
    stream->writeEndElement(); // filename
    stream->writeEndElement(); // tree or table input
    }
  stream->writeEndElement(); // tree heatmap input
}

// --------------------------------------------------------------------------
void voIOManager::writeInputToXML(const QString& type, voDataModelItem *item,
                                  QXmlStreamWriter *stream)
{
  stream->writeStartElement("input");
  stream->writeAttribute("type", type);
  voInputFileDataObject *inputObject =
    dynamic_cast<voInputFileDataObject*>(item->dataObject());
  if (!inputObject)
    {
    qCritical() << "Could not resolve " << item->rawViewType()
                << " as an input data file!";
    stream->writeEndElement(); // input
    return;
    }
  if (type == "Table")
    {
    this->writeTableSettingsToXML(item, stream);
    }
  stream->writeStartElement("filename");
  stream->writeCharacters(inputObject->fileName());
  stream->writeEndElement(); // filename
  stream->writeEndElement(); // input
}

// --------------------------------------------------------------------------
void voIOManager::writeTableSettingsToXML(voDataModelItem *item,
                                          QXmlStreamWriter *stream)
{
  voInputFileDataObject *tableObject =
    dynamic_cast<voInputFileDataObject*>(item->dataObject());
  if (!tableObject)
    {
    qCritical() << "Could not resolve " << item->text() << " as an input data file";
    return;
    }

  if (!this->tableSettings.contains(tableObject))
    {
    qCritical() << "No settings are stored for table " << item->text();
    return;
    }

  voDelimitedTextImportSettings settings =
    this->tableSettings.value(tableObject);

  stream->writeStartElement("table_reader_settings");

  stream->writeStartElement("setting");
  stream->writeAttribute("name", "FieldDelimiterCharacters");
  stream->writeCharacters(settings.value(
    voDelimitedTextImportSettings::FieldDelimiterCharacters).toString());
  stream->writeEndElement();

  stream->writeStartElement("setting");
  stream->writeAttribute("name", "MergeConsecutiveDelimiters");
  stream->writeCharacters(settings.value(
    voDelimitedTextImportSettings::MergeConsecutiveDelimiters).toString());
  stream->writeEndElement();

  stream->writeStartElement("setting");
  stream->writeAttribute("name", "StringDelimiter");
  stream->writeCharacters(settings.value(
    voDelimitedTextImportSettings::StringDelimiter).toString());
  stream->writeEndElement();

  stream->writeStartElement("setting");
  stream->writeAttribute("name", "UseStringDelimiter");
  stream->writeCharacters(settings.value(
    voDelimitedTextImportSettings::UseStringDelimiter).toString());
  stream->writeEndElement();

  stream->writeStartElement("setting");
  stream->writeAttribute("name", "Transpose");
  stream->writeCharacters(settings.value(
    voDelimitedTextImportSettings::Transpose).toString());
  stream->writeEndElement();

  stream->writeStartElement("setting");
  stream->writeAttribute("name", "NumberOfColumnMetaDataTypes");
  stream->writeCharacters(settings.value(
    voDelimitedTextImportSettings::NumberOfColumnMetaDataTypes).toString());
  stream->writeEndElement();

  stream->writeStartElement("setting");
  stream->writeAttribute("name", "ColumnMetaDataTypeOfInterest");
  stream->writeCharacters(settings.value(
    voDelimitedTextImportSettings::ColumnMetaDataTypeOfInterest).toString());
  stream->writeEndElement();

  stream->writeStartElement("setting");
  stream->writeAttribute("name", "NumberOfRowMetaDataTypes");
  stream->writeCharacters(settings.value(
    voDelimitedTextImportSettings::NumberOfRowMetaDataTypes).toString());
  stream->writeEndElement();

  stream->writeStartElement("setting");
  stream->writeAttribute("name", "RowMetaDataTypeOfInterest");
  stream->writeCharacters(settings.value(
    voDelimitedTextImportSettings::RowMetaDataTypeOfInterest).toString());
  stream->writeEndElement();

  stream->writeEndElement(); // table_reader_settings
}

// --------------------------------------------------------------------------
void voIOManager::loadWorkflowFromFile(const QString& fileName)
{
  QFile file(fileName);
  if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
  {
    qCritical() << "Could not open " << fileName << " for reading!";
    return;
  }

  QXmlStreamReader stream(&file);
  this->loadWorkflow(&stream);
}

// --------------------------------------------------------------------------
void voIOManager::loadTreeFromOpenTreeDB(const QString& hostURL,
                                         const QString& ottolID,
                                         const QString& maxDepth)
{// download tree from opentreeoflife neo4j database
  QUrl url(hostURL);

  QNetworkRequest request;
  request.setUrl(url);
  request.setHeader(QNetworkRequest::ContentTypeHeader,"Application/json"); //Required!

  QNetworkAccessManager *manager = new QNetworkAccessManager();

  QNetworkReply *reply = manager->post(request,QString("{\"ottolID\":\"%1\", \"maxDepth\": %2}").arg(ottolID,maxDepth).toLatin1());

  QEventLoop loop;
  QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
  loop.exec();

  // a newick tree is returned as the response
  /* here is an example:
  "{
  "tree" : "(Homo_sapiens_ssp_Denisova:1.0E-22,Homo_sapiens_neanderthalensis:1.0E-22)Homo_sapiens"
   }"
  */
  QByteArray replyBytes =  reply->readAll();
  if (replyBytes.contains("tree") )
    {
    //trim the response to be a newicktree string
    replyBytes.remove(0,14);//remove the header charactors  "{\n\"tree\" : \""
    replyBytes.replace(QString("\"\n}"),QByteArray(";"));//tail

    char * singleTreeBuffer = replyBytes.data();

    vtkNew<vtkNewickTreeReader> treeReader;
    vtkSmartPointer<vtkTree> tree = vtkSmartPointer<vtkTree>::New();
    treeReader->ReadNewickTree(singleTreeBuffer, *tree);

    //load the tree to the GUI
    voDataModel * model = voApplication::application()->dataModel();
    voInputFileDataObject * dataObject =
      new voInputFileDataObject("OpenTreeOfLife", tree);
    voDataModelItem * newItem = model->addDataObject(dataObject);
    newItem->setRawViewType("voTreeHeatmapView");

    model->setSelected(newItem);
    }
  else
    {//error
    qDebug()<< replyBytes;
    QErrorMessage errorMessage;
    errorMessage.showMessage("Failed to load the tree from OpenTreeOfLife database!");
    errorMessage.exec();
    }
}

// --------------------------------------------------------------------------
void voIOManager::loadWorkflow(QXmlStreamReader *stream)
{
  voDataModel * model = voApplication::application()->dataModel();
  model->clear();
  model->setColumnCount(1);

  while (!stream->atEnd())
    {
    QString attribute = "";
    stream->readNext();
    if (stream->isStartElement())
      {
      QString name = stream->name().toString();
      if (name == "input")
        {
        QStringRef type = stream->attributes().value("type");
        if (type == "")
          {
          qCritical() << "empty type attribute encountered!";
          }
        else if (type == "TreeHeatmap")
          {
          this->loadTreeHeatmapFromXML(stream);
          }
        else if (type == "Tree")
          {
          this->loadTreeFromXML(stream);
          }
        else if (type == "Table")
          {
          this->loadTableFromXML(stream);
          }
        }
      else if(name == "analysis")
        {
        this->loadAnalysisFromXML(stream);
        }
      }
    }
  if (stream->hasError())
    {
    // do error handling
    }
}

// --------------------------------------------------------------------------
void voIOManager::loadTreeHeatmapFromXML(QXmlStreamReader *stream)
{
  stream->readNextStartElement();  // input (tree)
  QString name = stream->name().toString();
  if (name != "input")
    {
    qCritical() << "expected input, found " << name;
    return;
    }
  QString treeFile = this->readTreeFileNameFromXML(stream);
  if (treeFile == "")
    {
    qCritical() << "tree filename is empty string";
    return;
    }

  stream->readNext(); // </filename>
  stream->readNext(); // </input>

  stream->readNextStartElement(); // <input>
  name = stream->name().toString();
  if (name != "input")
    {
    qCritical() << "expected input, found " << name;
    return;
    }
  QStringRef type = stream->attributes().value("type");
  if (type != "Table")
    {
    qCritical() << "expected Table, found " << type;
    return;
    }

  QString tableFile;
  voDelimitedTextImportSettings settings =
    this->readTableFromXML(stream, &tableFile);
 if (tableFile == "")
   {
   qCritical() << "tree filename is empty string";
   return;
   }

  this->loadPhyloTreeDataSet(treeFile, tableFile, settings);
}

// --------------------------------------------------------------------------
void voIOManager::loadTreeFromXML(QXmlStreamReader *stream)
{
  QString fileName = this->readTreeFileNameFromXML(stream);
 if (fileName == "")
   {
   qCritical() << "tree filename is empty string";
   return;
   }
  this->loadPhyloTreeDataSet(fileName);
}

// --------------------------------------------------------------------------
void voIOManager::loadTableFromXML(QXmlStreamReader *stream)
{
  QString fileName;
  voDelimitedTextImportSettings settings =
    this->readTableFromXML(stream, &fileName);
 if (fileName == "")
   {
   qCritical() << "table filename is empty string";
   return;
   }
  this->openCSVFile(fileName, settings);
}

// --------------------------------------------------------------------------
QString voIOManager::readTreeFileNameFromXML(QXmlStreamReader *stream)
{
  QStringRef type = stream->attributes().value("type");
  if (type != "Tree")
    {
    qCritical() << "expected Tree, found " << type;
    return "";
    }

  stream->readNextStartElement();  // filename of Tree
  QString name = stream->name().toString();
  if (name != "filename")
    {
    qCritical() << "expecting filename, found " << name;
    return "";
    }

 return stream->readElementText();
}

// --------------------------------------------------------------------------
voDelimitedTextImportSettings voIOManager::readTableFromXML(
  QXmlStreamReader *stream, QString *fileName)
{
  voDelimitedTextImportSettings settings;
  stream->readNextStartElement();
  QString name = stream->name().toString();
  if (name != "table_reader_settings")
    {
    qCritical() << "expected table_reader_settings, found " << name;
    return settings;
    }

  // read table settings
  stream->readNext();
  stream->readNextStartElement();
  name = stream->name().toString();
  while (name != "table_reader_settings" && !stream->atEnd())
    {
    if (name != "setting")
      {
      qCritical() << "expected setting, found " << name;
      return settings;
      }

    QStringRef settingType = stream->attributes().value("name");
    QString value = stream->readElementText();
    if (settingType == "FieldDelimiterCharacters") // QString
      {
      settings.insert(voDelimitedTextImportSettings::FieldDelimiterCharacters,
                      value);
      }
    else if ("MergeConsecutiveDelimiters") // bool
      {
      bool b = false;
      if (value == "true")
        {
        b = true;
        }
      settings.insert(voDelimitedTextImportSettings::MergeConsecutiveDelimiters,
                      b);
      }
    else if ("StringDelimiter") // char
      {
      settings.insert(voDelimitedTextImportSettings::StringDelimiter,
                      value.at(0).toAscii());
      }
    else if ("UseStringDelimiter") // bool
      {
      bool b = false;
      if (value == "true")
        {
        b = true;
        }
      settings.insert(voDelimitedTextImportSettings::UseStringDelimiter,
                      b);
      }
    else if ("Transpose") // bool
      {
      bool b = false;
      if (value == "true")
        {
        b = true;
        }
      settings.insert(voDelimitedTextImportSettings::Transpose,
                      b);
      }
    else if ("NumberOfColumnMetaDataTypes") // int
      {
      settings.insert(voDelimitedTextImportSettings::NumberOfColumnMetaDataTypes,
                      value.toInt());
      }
    else if ("ColumnMetaDataTypeOfInterest") // int
      {
      settings.insert(voDelimitedTextImportSettings::ColumnMetaDataTypeOfInterest,
                      value.toInt());
      }
    else if ("NumberOfRowMetaDataTypes") // int
      {
      settings.insert(voDelimitedTextImportSettings::NumberOfRowMetaDataTypes,
                      value.toInt());
      }
    else if ("RowMetaDataTypeOfInterest") // int
      {
      settings.insert(voDelimitedTextImportSettings::RowMetaDataTypeOfInterest,
                      value.toInt());
      }
    else if ("NormalizationMethod") // QString
      {
      settings.insert(voDelimitedTextImportSettings::NormalizationMethod,
                      value);
      }
    else
      {
      qWarning() << "unhandled table setting encountered: " << settingType;
      }
    stream->readNextStartElement();
    name = stream->name().toString();
    }
  // end settings

  stream->readNextStartElement();
  name = stream->name().toString();
  if (name != "filename")
    {
    qCritical() << "expected filename, found " << name;
    return settings;
    }

 *fileName = stream->readElementText();
 return settings;
}

// --------------------------------------------------------------------------
void voIOManager::loadAnalysisFromXML(QXmlStreamReader *stream)
{
  QString type = stream->attributes().value("type").toString();
  type.remove(QChar('"'));

  stream->readNextStartElement();
  QString name = stream->name().toString();
  if (name != "parent")
    {
    qCritical() << "expected parent, found " << name;
    return;
    }
  QString parent = stream->readElementText();

  stream->readNextStartElement();
  name = stream->name().toString();
  if (name != "parameters")
    {
    qCritical() << "expected parameters, found " << name;
    }

  QHash<QString, QVariant> parameters;

  stream->readNextStartElement();
  name = stream->name().toString();
  while (name != "parameters" && !stream->atEnd())
    {
    if (name != "parameter")
      {
      qCritical() << "expected parameter, found " << name;
      return;
      }

    QString parameterName = stream->attributes().value("name").toString();
    QString parameterValue = stream->readElementText();
    parameters.insert(parameterName, QVariant(parameterValue));
    stream->readNextStartElement();
    name = stream->name().toString();
    }

  voDataModel * model = voApplication::application()->dataModel();
  voDataModelItem *inputTarget = model->findItemWithText(parent);
  QList<voDataModelItem*> inputTargets;
  inputTargets << inputTarget;

  voAnalysisDriver *driver = voApplication::application()->analysisDriver();
  driver->runAnalysis(type, inputTargets, parameters);
}

// --------------------------------------------------------------------------
void voIOManager::convertTableToExtended(vtkTable *table,
                                         vtkExtendedTable *extendedTable)
{
  extendedTable->SetInputDataTable(table);
  // column meta data: the names of each array in the input table
  vtkNew<vtkTable> columnMetaData;
  vtkNew<vtkStringArray> columnNames;
  for(int i = 1; i < table->GetNumberOfColumns(); ++i)
    {
    columnNames->InsertNextValue(table->GetColumn(i)->GetName());
    }
  columnMetaData->AddColumn(columnNames.GetPointer());
  extendedTable->SetColumnMetaDataTable(columnMetaData.GetPointer());

  // row meta data: the first column of the input table
  vtkNew<vtkTable> rowMetaData;
  rowMetaData->AddColumn(table->GetColumn(0));
  extendedTable->SetRowMetaDataTable(rowMetaData.GetPointer());

  // "data": all of the columns of the input table, except for the first
  vtkNew<vtkTable> data;
  for (int i = 1; i < table->GetNumberOfColumns(); ++i)
    {
    data->AddColumn(table->GetColumn(i));
    }
  extendedTable->SetData(data.GetPointer());

  extendedTable->SetColumnMetaDataTypeOfInterest(0);
  extendedTable->SetRowMetaDataTypeOfInterest(0);

  vtkNew<vtkStringArray> columnMetaDataLabels;
  columnMetaDataLabels->InsertNextValue(table->GetValue(0, 0).ToString());
  extendedTable->SetColumnMetaDataLabels(columnMetaDataLabels.GetPointer());

  vtkNew<vtkStringArray> rowMetaDataLabels;
  rowMetaDataLabels->InsertNextValue(table->GetValue(0, 0).ToString());
  extendedTable->SetRowMetaDataLabels(rowMetaDataLabels.GetPointer());

  // Set column names
  voUtils::setTableColumnNames(extendedTable->GetData(),
    extendedTable->GetColumnMetaDataOfInterestAsString());
}


text:
#ifndef THREAD_CONTEXT_WINDOWS_H
#define THREAD_CONTEXT_WINDOWS_H

#if defined(_WIN32) || defined(_WIN64)
#include <Windows.h>

#include "../public/PromisePublicAPIs.h"

namespace ThreadContextImpl {
  namespace Windows {
    namespace Details {
      using Task = std::function<void()>;

      static void InvokeFunction(void *context) {
        std::unique_ptr<Task> function{ static_cast<Task *>(context) };
        (*function)();
      }
    } // Details

    class ThreadPoolContext : public Promise2::ThreadContext {
    public:
      static ThreadContext *New() {
        return new ThreadPoolContext;
      }

    protected:
      ThreadPoolContext() = default;

    public:
      virtual ~ThreadPoolContext() = default;

    public:
      virtual void scheduleToRun(std::function<void()>&& task) override {
        ::QueueUserWorkItem(Details::InvokeFunction, new Details::Task{ std::move(task) }, 0);
      }

    private:
      ThreadPoolContext(const ThreadPoolContext& ) = delete;
      ThreadPoolContext& operator = (const ThreadPoolContext& ) = delete;
    };
  } // Windows
}

#endif // windows

#endif // THREAD_CONTEXT_WINDOWS_H


text:
package org.apache.shardingsphere.transaction;

import com.google.common.base.Preconditions;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.underlying.common.database.type.DatabaseType;
import org.apache.shardingsphere.transaction.core.ResourceDataSource;
import org.apache.shardingsphere.transaction.core.TransactionType;
import org.apache.shardingsphere.transaction.spi.ShardingTransactionManager;

import javax.sql.DataSource;
import java.util.Collection;
import java.util.EnumMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.ServiceLoader;

/**
 * Sharding transaction manager engine.
 */
@Slf4j
public final class ShardingTransactionManagerEngine {

    private final Map<TransactionType, ShardingTransactionManager> transactionManagerMap = new EnumMap<>(TransactionType.class);

    public ShardingTransactionManagerEngine() {
        loadShardingTransactionManager();
    }

    private void loadShardingTransactionManager() {
        for (ShardingTransactionManager each : ServiceLoader.load(ShardingTransactionManager.class)) {
            if (transactionManagerMap.containsKey(each.getTransactionType())) {
                log.warn("Find more than one {} transaction manager implementation class, use `{}` now",
                    each.getTransactionType(), transactionManagerMap.get(each.getTransactionType()).getClass().getName());
                continue;
            }
            transactionManagerMap.put(each.getTransactionType(), each);
        }
    }

    /**
     * Initialize sharding transaction managers.
     *
     * @param databaseType database type
     * @param dataSourceMap data source map
     */
    public void init(final DatabaseType databaseType, final Map<String, DataSource> dataSourceMap) {
        for (Entry<TransactionType, ShardingTransactionManager> entry : transactionManagerMap.entrySet()) {
            entry.getValue().init(databaseType, getResourceDataSources(dataSourceMap));
        }
    }

    private Collection<ResourceDataSource> getResourceDataSources(final Map<String, DataSource> dataSourceMap) {
        List<ResourceDataSource> result = new LinkedList<>();
        for (Map.Entry<String, DataSource> entry : dataSourceMap.entrySet()) {
            result.add(new ResourceDataSource(entry.getKey(), entry.getValue()));
        }
        return result;
    }

    /**
     * Get sharding transaction manager.
     *
     * @param transactionType transaction type
     * @return sharding transaction manager
     */
    public ShardingTransactionManager getTransactionManager(final TransactionType transactionType) {
        ShardingTransactionManager result = transactionManagerMap.get(transactionType);
        if (TransactionType.LOCAL != transactionType) {
            Preconditions.checkNotNull(result, "Cannot find transaction manager of [%s]", transactionType);
        }
        return result;
    }

    /**
     * Close sharding transaction managers.
     *
     * @throws Exception exception
     */
    public void close() throws Exception {
        for (Entry<TransactionType, ShardingTransactionManager> entry : transactionManagerMap.entrySet()) {
            entry.getValue().close();
        }
    }
}


text:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject.js';
import { Subject } from 'rxjs/Subject';
import { CityInfo } from '../../interfaces';
import { Coordinats } from '../../interfaces';
@Injectable()

export class EventService {
    private newCityEvent: Subject<CityInfo> = new BehaviorSubject<CityInfo>(null);

    private locationEvent: Subject<Coordinats> = new Subject<Coordinats>();

    newCityEvent$ = this.newCityEvent.asObservable();
    locationEvent$ = this.locationEvent.asObservable();
    constructor() { }

    public triggerEvent(value: CityInfo): void {
        this.newCityEvent.next(value);
    }

    public triggerlocationEvent(value: Coordinats): void {
        this.locationEvent.next(value);
    }
}


text:
ENV['RACK_ENV'] = 'test'

begin
  require 'rack'
rescue LoadError
  require 'rubygems'
  require 'rack'
end

testdir = File.dirname(__FILE__)
$LOAD_PATH.unshift(testdir) unless $LOAD_PATH.include?(testdir)

libdir = File.dirname(File.dirname(__FILE__)) + '/lib'
$LOAD_PATH.unshift(libdir) unless $LOAD_PATH.include?(libdir)

require 'test/unit'
require 'rack/accept'

class Test::Unit::TestCase
  attr_reader :context
  attr_reader :response

  def status
    @response && @response.status
  end

  def request(env={}, method='GET', uri='/')
    @context = Rack::Accept.new(fake_app)
    yield @context if block_given?
    mock_request = Rack::MockRequest.new(@context)
    @response = mock_request.request(method.to_s.upcase, uri, env)
    @response
  end

  def fake_app(status=200, headers={}, body=[])
    lambda {|env| Rack::Response.new(body, status, headers).finish }
  end
end


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

namespace Azure.ResourceManager.Resources.Models
{
    /// <summary> List of resource providers. </summary>
    internal partial class ProviderListResult
    {
        /// <summary> Initializes a new instance of ProviderListResult. </summary>
        internal ProviderListResult()
        {
            Value = new ChangeTrackingList<ProviderData>();
        }

        /// <summary> Initializes a new instance of ProviderListResult. </summary>
        /// <param name="value"> An array of resource providers. </param>
        /// <param name="nextLink"> The URL to use for getting the next set of results. </param>
        internal ProviderListResult(IReadOnlyList<ProviderData> value, string nextLink)
        {
            Value = value;
            NextLink = nextLink;
        }

        /// <summary> An array of resource providers. </summary>
        public IReadOnlyList<ProviderData> Value { get; }
        /// <summary> The URL to use for getting the next set of results. </summary>
        public string NextLink { get; }
    }
}


text:
package com.zaubersoftware.gnip4j.api.stats;

/**
 * Modifable {@link StreamStats}.
 *
 * @author Juan F. Codagnone
 * @since May 26, 2011
 */
public interface ModifiableStreamStats extends StreamStats {

    /** updates the number of succesful reconnections */
    void incrementNumberOfSuccessfulReconnections();

    /** updates the number of connections attemps */
    void incrementNumberOfReconnectionsAttempt();

    /** updates the number of  transfered activities */
    void incrementTransferedActivities();

    /** updates the number of  transfered bytes */
    void incrementTransferedBytes();

}


text:
package org.quartz.examples.example3;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.SchedulerMetaData;
import org.quartz.impl.StdSchedulerFactory;

/**
 * This Example will demonstrate all of the basics of scheduling capabilities of
 * Quartz using Cron Triggers.
 *
 * @author Bill Kratzer
 */
public class CronTriggerExample {

    public void run() throws Exception {
        Logger log = LoggerFactory.getLogger(CronTriggerExample.class);

        log.info("------- Initializing -------------------");

        // First we must get a reference to a scheduler
        SchedulerFactory sf = new StdSchedulerFactory();
        Scheduler sched = sf.getScheduler();

        log.info("------- Initialization Complete --------");

        log.info("------- Scheduling Jobs ----------------");

        // jobs can be scheduled before sched.start() has been called

        // job 1 will run every 20 seconds
        JobDetail job = new JobDetail("job1", "group1", SimpleJob.class);
        CronTrigger trigger = new CronTrigger("trigger1", "group1", "job1",
                "group1", "0/20 * * * * ?");
        sched.addJob(job, true);
        Date ft = sched.scheduleJob(trigger);
        log.info(job.getFullName() + " has been scheduled to run at: " + ft
                + " and repeat based on expression: "
                + trigger.getCronExpression());

        // job 2 will run every other minute (at 15 seconds past the minute)
        job = new JobDetail("job2", "group1", SimpleJob.class);
        trigger = new CronTrigger("trigger2", "group1", "job2", "group1",
                "15 0/2 * * * ?");
        sched.addJob(job, true);
        ft = sched.scheduleJob(trigger);
        log.info(job.getFullName() + " has been scheduled to run at: " + ft
                + " and repeat based on expression: "
                + trigger.getCronExpression());

        // job 3 will run every other minute but only between 8am and 5pm
        job = new JobDetail("job3", "group1", SimpleJob.class);
        trigger = new CronTrigger("trigger3", "group1", "job3", "group1",
                "0 0/2 8-17 * * ?");
        sched.addJob(job, true);
        ft = sched.scheduleJob(trigger);
        log.info(job.getFullName() + " has been scheduled to run at: " + ft
                + " and repeat based on expression: "
                + trigger.getCronExpression());

        // job 4 will run every three minutes but only between 5pm and 11pm
        job = new JobDetail("job4", "group1", SimpleJob.class);
        trigger = new CronTrigger("trigger4", "group1", "job4", "group1",
                "0 0/3 17-23 * * ?");
        sched.addJob(job, true);
        ft = sched.scheduleJob(trigger);
        log.info(job.getFullName() + " has been scheduled to run at: " + ft
                + " and repeat based on expression: "
                + trigger.getCronExpression());

        // job 5 will run at 10am on the 1st and 15th days of the month
        job = new JobDetail("job5", "group1", SimpleJob.class);
        trigger = new CronTrigger("trigger5", "group1", "job5", "group1",
                "0 0 10am 1,15 * ?");
        sched.addJob(job, true);
        ft = sched.scheduleJob(trigger);
        log.info(job.getFullName() + " has been scheduled to run at: " + ft
                + " and repeat based on expression: "
                + trigger.getCronExpression());

        // job 6 will run every 30 seconds but only on Weekdays (Monday through
        // Friday)
        job = new JobDetail("job6", "group1", SimpleJob.class);
        trigger = new CronTrigger("trigger6", "group1", "job6", "group1",
                "0,30 * * ? * MON-FRI");
        sched.addJob(job, true);
        ft = sched.scheduleJob(trigger);
        log.info(job.getFullName() + " has been scheduled to run at: " + ft
                + " and repeat based on expression: "
                + trigger.getCronExpression());

        // job 7 will run every 30 seconds but only on Weekends (Saturday and
        // Sunday)
        job = new JobDetail("job7", "group1", SimpleJob.class);
        trigger = new CronTrigger("trigger7", "group1", "job7", "group1",
                "0,30 * * ? * SAT,SUN");
        sched.addJob(job, true);
        ft = sched.scheduleJob(trigger);
        log.info(job.getFullName() + " has been scheduled to run at: " + ft
                + " and repeat based on expression: "
                + trigger.getCronExpression());

        log.info("------- Starting Scheduler ----------------");

        // All of the jobs have been added to the scheduler, but none of the
        // jobs
        // will run until the scheduler has been started
        sched.start();

        log.info("------- Started Scheduler -----------------");

        log.info("------- Waiting five minutes... ------------");
        try {
            // wait five minutes to show jobs
            Thread.sleep(300L * 1000L);
            // executing...
        } catch (Exception e) {
        }

        log.info("------- Shutting Down ---------------------");

        sched.shutdown(true);

        log.info("------- Shutdown Complete -----------------");

        SchedulerMetaData metaData = sched.getMetaData();
        log.info("Executed " + metaData.getNumberOfJobsExecuted() + " jobs.");

    }

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

        CronTriggerExample example = new CronTriggerExample();
        example.run();
    }

}


text:
@implementation NSString (OKCategory)

- (BOOL)ok_isNull {
    if (!self || [self isKindOfClass:[NSNull class]] || [self ok_isEmptyAfterTrim]) {
        return YES;
    }
    return NO;
}

- (BOOL)ok_isEmpty {
    return (!self || !self.length);
}

- (BOOL)ok_isEmptyAfterTrim {
    return [[self ok_trimmingWhitespaceAndNewlines] isEqualToString:@""];
}

- (BOOL)ok_isStartsWithACapitalLetter {

    unichar firstCharacter = [self characterAtIndex:0];
    return [[NSCharacterSet uppercaseLetterCharacterSet]
            characterIsMember:firstCharacter];
}

- (NSUInteger)ok_countNumberOfWords {
    NSScanner *scanner = [NSScanner scannerWithString:self];
    NSCharacterSet *whiteSpace = [NSCharacterSet whitespaceAndNewlineCharacterSet];

    NSUInteger count = 0;
    while ([scanner scanUpToCharactersFromSet:whiteSpace intoString:nil]) {
        count++;
    }

    return count;
}

- (NSString *)ok_reverseString {

    NSMutableString *reversedString = [NSMutableString stringWithCapacity:[self length]];

    [self enumerateSubstringsInRange:NSMakeRange(0, [self length])
                             options:(NSStringEnumerationReverse | NSStringEnumerationByComposedCharacterSequences)
                          usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
         [reversedString appendString:substring];
     }];
    return reversedString;
}

- (NSString *)ok_removeSubString:(NSString *)subString {
    if ([self ok_containsString:subString]) {
        NSRange range = [self rangeOfString:subString];
        return [self stringByReplacingCharactersInRange:range withString:@""];
    }
    return self;
}

- (BOOL)ok_containsOnlyLetters {
    NSCharacterSet *letterCharacterset = [[NSCharacterSet letterCharacterSet] invertedSet];
    return ([self rangeOfCharacterFromSet:letterCharacterset].location == NSNotFound);
}

- (BOOL)ok_containsOnlyNumbers {
    NSCharacterSet *numbersCharacterSet = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet];
    return ([self rangeOfCharacterFromSet:numbersCharacterSet].location == NSNotFound);
}

- (BOOL)ok_containsOnlyNumbersAndLetters {
    NSCharacterSet *numAndLetterCharSet = [[NSCharacterSet alphanumericCharacterSet] invertedSet];
    return ([self rangeOfCharacterFromSet:numAndLetterCharSet].location == NSNotFound);
}

- (CGFloat)ok_widthWithFont:(UIFont *)font containerHeight:(CGFloat)containerHeight {
    return [self ok_sizeWithFont:font containerSize:CGSizeMake(containerHeight, CGFLOAT_MAX)].width;
}

- (CGFloat)ok_heightWithFont:(UIFont *)font containerWidth:(CGFloat)containerWidth {
    return [self ok_sizeWithFont:font containerSize:CGSizeMake(containerWidth, CGFLOAT_MAX)].height;
}

- (CGSize)ok_sizeWithFont:(UIFont *)font containerSize:(CGSize)containerSize {

    UIFont *textFont = font ? : [UIFont systemFontOfSize:[UIFont systemFontSize]];

    CGSize textSize = CGSizeZero;

#if __IPHONE_OS_VERSION_MIN_REQUIRED < 70000
    if ([self respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)]) {
        NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
        paragraph.lineBreakMode = NSLineBreakByWordWrapping;
        NSDictionary *attributes = @{NSFontAttributeName: textFont,
                                     NSParagraphStyleAttributeName: paragraph};
        textSize = [self boundingRectWithSize:containerSize
                                      options:(NSStringDrawingUsesLineFragmentOrigin |
                                               NSStringDrawingUsesFontLeading |
                                               NSStringDrawingTruncatesLastVisibleLine)
                                   attributes:attributes
                                      context:nil].size;
    } else {
        textSize = [self sizeWithFont:textFont
                    constrainedToSize:containerSize
                        lineBreakMode:NSLineBreakByWordWrapping];
    }
#else
    NSDictionary *attributes = @{NSFontAttributeName: textFont,
                                 NSParagraphStyleAttributeName: [NSParagraphStyle defaultParagraphStyle]};

    textSize = [self boundingRectWithSize:containerSize
                                  options:(NSStringDrawingUsesLineFragmentOrigin |
                                           NSStringDrawingUsesFontLeading |
                                           NSStringDrawingTruncatesLastVisibleLine)
                               attributes:attributes
                                  context:nil].size;
#endif
    return CGSizeMake(ceil(textSize.width), ceil(textSize.height));
}

@end

@implementation NSString (OKCategory_SafeAccess)

- (BOOL)ok_containsString:(NSString *)string {

    if (string.length == 0) {
        return NO;
    }

    if (__IPHONE_OS_VERSION_MIN_REQUIRED < 80000) {
        NSRange range = [self rangeOfString:string];
        return range.location == NSNotFound ? NO : YES;
    } else {
        return [self containsString:string];
    }
}

- (NSString *)ok_substringWithRange:(NSRange)range {
    if (range.location > self.length || range.length == 0) {
        return self;
    } else if ((range.location + range.length) > self.length) {
        return self;
    }

    return [self substringWithRange:range];
}

@end

@implementation NSString (OKCategory_Trims)

- (NSString *)ok_trimmingWhitespace {
    return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}

- (NSString *)ok_trimmingWhitespaceAndNewlines {
    return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

- (NSString *)ok_stringByStrippingHTML {
    return [self stringByReplacingOccurrencesOfString:@"<[^>]+>" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, self.length)];
}

- (NSString *)ok_stringByRemovingScriptsAndStrippingHTML {
    NSMutableString *mString = [self mutableCopy];
    NSError *error;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"<script[^>]*>[\\w\\W]*</script>" options:NSRegularExpressionCaseInsensitive error:&error];
    NSArray *matches = [regex matchesInString:mString options:NSMatchingReportProgress range:NSMakeRange(0, [mString length])];
    for (NSTextCheckingResult *match in [matches reverseObjectEnumerator]) {
        [mString replaceCharactersInRange:match.range withString:@""];
    }
    return [mString ok_stringByStrippingHTML];
}

@end

@implementation NSString (OKCategory_Base64)

#pragma mark - URL Encoding and Decoding
- (NSString *)ok_URLEncode {
    return [self ok_URLEncodeUsingEncoding:NSUTF8StringEncoding];
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
- (NSString *)ok_URLEncodeUsingEncoding:(NSStringEncoding)encoding {
    return (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
                                                                                (__bridge CFStringRef)self,
                                                                                NULL,
                                                                                (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",
                                                                                CFStringConvertNSStringEncodingToEncoding(encoding));
}

- (NSString *)ok_URLDecode {
    return [self ok_URLDecodeUsingEncoding:NSUTF8StringEncoding];
}

- (NSString *)ok_URLDecodeUsingEncoding:(NSStringEncoding)encoding {
    return (__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL,
                                                                                (__bridge CFStringRef)self,
                                                                                CFSTR(""),
                                                                                CFStringConvertNSStringEncodingToEncoding(encoding));
}

#pragma clang diagnostic pop

+ (NSString *)ok_stringWithBase64EncodedString:(NSString *)string {
    NSData *data = [NSData ok_dataWithBase64EncodedString:string];
    if (data) {
        return [[self alloc] initWithData:data encoding:NSUTF8StringEncoding];
    }
    return nil;
}

- (NSString *)ok_base64EncodedStringWithWrapWidth:(NSUInteger)wrapWidth {
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    return [data ok_base64EncodedStringWithWrapWidth:wrapWidth];
}

- (NSString *)ok_base64EncodedString {
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    return [data ok_base64EncodedString];
}

- (NSString *)ok_base64DecodedString {
    return [NSString ok_stringWithBase64EncodedString:self];
}

- (NSData *)ok_base64DecodedData {
    return [NSData ok_dataWithBase64EncodedString:self];
}

@end

#pragma mark OKCategory_Encrypt

@implementation NSString (OKCategory_Encrypt)

- (NSString *)ok_MD5
{
    NSData * value;

    value = [NSData dataWithBytes:[self UTF8String] length:[self length]];
    return [value ok_MD5Encryption];
}

@end


text:
 Customer Inquiry

    <pagination boundary-links="true" total-items="TotalCustomers" items-per-page="PageSize" ng-change="pageChanged()" ng-model="CurrentPageNumber" class="pagination-lg" previous-text="Prev" next-text="Next" first-text="First" last-text="Last"></pagination>

        <alert ng-repeat="alert in alerts" type="{{alert.type}}" close="closeAlert($index)">

</alert>


text:
import os
import sys

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_settings")

def nose_collector():
    import nose
    return nose.collector()

if __name__ == "__main__":
    from django.core.management import execute_from_command_line
    execute_from_command_line(sys.argv)


text:
#region License

// --------------------------------------------------------------------------------------------------------------------
// <copyright file="SerializeHelper.cs">
//  Copyright 2015 Benjamin S. Ramey
//
//  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.
// </copyright>
// <created>03/25/2015 4:41 PM</created>
// <updated>03/31/2015 12:55 PM by Ben Ramey</updated>
// --------------------------------------------------------------------------------------------------------------------

#endregion

#region Usings

using System;
using System.Collections.Generic;
using System.Linq;
using NServiceBus.Serializers.Json;

#endregion

namespace GoodlyFere.NServiceBus.EntityFramework.Support
{
    internal static class SerializeHelper
    {
        private static readonly JsonMessageSerializer Serializer = new JsonMessageSerializer(null);

        internal static Dictionary<string, string> ToDictionary(this string str)
        {
            if (String.IsNullOrEmpty(str))
            {
                return new Dictionary<string, string>();
            }

            return (Dictionary<string, string>)Serializer.DeserializeObject(str, typeof(Dictionary<string, string>));
        }

        internal static string ToDictionaryString(this Dictionary<string, string> dictionary)
        {
            if (dictionary != null && dictionary.Count > 0)
            {
                return Serializer.SerializeObject(dictionary);
            }

            return null;
        }
    }
}


text:
For a full list of releases, see github.

## 1.3.7 / 2021-02-17

* Upgrade junit to 4.13.1, xerces to 2.12.0
* Publish releases to Maven Central
  (previous releases are in Conjars)
* Sign jars
* Change maven groupId from "eigenbase" to "net.hydromatic"
* Upgrade to eigenbase-xom 1.3.6.

## 1.3.6 / 2014-01-13

* Upgrade to eigenbase-xom 1.3.4.

## 1.3.5 / 2014-01-08

* Add release notes and history.
* Make ant an optional dependency for the OSGI bundle.
* Enable oraclejdk8 in Travis CI.

## 1.3.4 / 2013-12-06

* Oops, need conjars repository for dependencies.

## 1.3.3 / 2013-12-06

* Switch to conjars as distribution repository.
* Enable maven-release-plugin.
* Changes made to POM to make the packaged jar a valid OSGI bundle.
* Enable Travis CI.
* Remove Intellij files from git.
* Remove files that can be generated from pom.
* Add content to README.
* Publish sources & javadoc.
* Migrate from DynamoBI.

## Origins

ResGen was derived from the
MonRG utility in the Mondrian project (an open-source OLAP server).
Next, it was part of the Eigenbase project (hence the name).
Now it is a standalone library, maintained by Julian Hyde, and hosted at
github.


text:
@interface PodsDummy_Pods_RWKit_Example : NSObject
@end
@implementation PodsDummy_Pods_RWKit_Example
@end


text:
Nebula Test
===========

![Support Status](https://img.shields.io/badge/nebula-active-green.svg)
[![Maven Central](https://img.shields.io/maven-central/v/com.netflix.nebula/nebula-test)](https://maven-badges.herokuapp.com/maven-central/com.netflix.nebula/nebula-test)
![Build](https://github.com/nebula-plugins/nebula-test/actions/workflows/nebula.yml/badge.svg)
[![Apache 2.0](https://img.shields.io/github/license/nebula-plugins/nebula-test.svg)](http://www.apache.org/licenses/LICENSE-2.0)

Classes specific to testing a Gradle project, leveraging [Spock](http://spockframework.org)

# Documentation

The project wiki contains the [full documentation](https://github.com/nebula-plugins/nebula-test/wiki) for the library.

LICENSE
=======

Copyright 2014-2021 Netflix, 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.


text:
Manual Inquiry

		                          Dashboard

		                         Manual Inquiry

				<form role="form" method="post" action="<?php echo base_url()."index.php/SalesAdmin/manualinq/"?>">

<?php echo $this->session->flashdata('msg'); ?>

                                First Name
                                <input class="form-control" name="fname">

                                Last Name
                                <input class="form-control" name="lname">

                                Company
                                <input class="form-control" name="company">

                                Position in Company
                                <input class="form-control" name="pos">

                                Address
                                <input class="form-control" name="address">

                                City
                                <input class="form-control" name="city">

                                Zip Code
                                <input class="form-control" name="zip">

                                Phone
                                <input class="form-control" name="phone">

                                Fax
                                <input class="form-control" name="fax">

                                Email
                                <input class="form-control" name="email" type="email">

                                Number Employee
                                <input class="form-control" name="employee">

                                Message
                                <textarea class="form-control" rows="3" name="message"></textarea>

                            <button type="submit" class="btn btn-default">Submit</button>

                        </form>


text:
- http://wiki.summercode.com/how_to_disable_mobile_backups_on_lion
```
sudo tmutil disablelocal
```

## Change default shell ##
- http://stackoverflow.com/questions/453236/how-can-i-set-fish-shell-as-my-default-shell-on-mac

- Add `/usr/local/bin/fish` to `/etc/shells`
- chsh -s /usr/local/bin/fish