text:
package com.intellij.openapi.roots.ui.configuration.projectRoot.daemon;

import com.intellij.openapi.actionSystem.DataContext;

import javax.annotation.Nonnull;

/**
 * @author nik
 */
public abstract class ConfigurationErrorQuickFix {
  private final String myActionName;

  protected ConfigurationErrorQuickFix(String actionName) {
    myActionName = actionName;
  }

  public String getActionName() {
    return myActionName;
  }

  public abstract void performFix(@Nonnull DataContext dataContext);
}


text:
package cn.sxx.thinkinginjava.chap15.coffee;

public class Mocha extends Coffee {

}

redpajama_set_name: RedPajamaGithub


text:
import { GuideService } from './../../guide/guide.service';
import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { FormGroup } from '@angular/forms';
import { Trip } from '../../trips/trip';
import { TripsService } from '../../trips/trips.service';
import { UiNotificationsService } from '../../common/ui-notifications.service';
import { MessageSeverity } from '../../common/message-severity.enum';
import { City } from '../../cities/city';
import { CitiesService } from '../../cities/cities.service';
import { Country } from '../../countries/country';
import { CountriesService } from '../../countries/countries.service';
import { ConfirmationService } from 'primeng/components/common/confirmationservice';

@Component({
  selector: 'app-dashboard-trips',
  templateUrl: './dashboard-trips.component.html',
  styleUrls: ['./dashboard-trips.component.css']
})
export class DashboardTripsComponent implements OnInit {

  newTripMode: boolean;
  newTripForm: FormGroup;
  trips: Trip[];
  cities: string[];
  countries: string[];
  invalidCountry: boolean;
  isGuide: boolean;

  constructor(private formBuilder: FormBuilder,
    private tripService: TripsService,
    private uiNotificationService: UiNotificationsService,
    private citiesService: CitiesService,
    private countriesService: CountriesService,
    private confirmationService: ConfirmationService,
    private guideService: GuideService) {

  }

  ngOnInit() {
    this.buildForm();
    this.getTripsForUser();
    this.checkIfIsGuide();
  }

  private searchCities(event) {
    this.citiesService.getForAutocomplete(event.query, this.newTripForm.value.country).subscribe(data => {
      this.cities = data;
    });
  }

  private searchCountries(event) {
    this.countriesService.getForAutocomplete(event.query).subscribe(result => {
      this.countries = result;
    },
      error => {
        this.uiNotificationService.addSingleMessage(MessageSeverity.Error, error.message, "");
      })
  }

  private getTripsForUser() {
    this.tripService.getTripsForUser().subscribe(result => {
      this.trips = result;
    },
      error => {
        this.uiNotificationService.addSingleMessage(MessageSeverity.Error, error.message, "");
      });
  }

  private buildForm() {

    this.invalidCountry = true;
    this.newTripMode = false;

    this.newTripForm = this.formBuilder.group({
      tripName: [null, [Validators.required]],
      tripDescription: [null, [Validators.required]],
      available: [null, null],
      city: [null, [Validators.required]],
      country: [null, [Validators.required]]
    });

  }

  private createNewTrip() {
    if (!this.newTripForm.valid) {
      this.uiNotificationService.addSingleMessage(MessageSeverity.Error, "Form is invalid", "");
      return;
    }

    let formValue = this.newTripForm.value;
    let trip = new Trip(formValue.tripName, formValue.tripDescription, formValue.available, formValue.country, formValue.city);

    this.tripService.addNewTrip(trip).subscribe(result => {
      this.uiNotificationService.addSingleMessage(MessageSeverity.Success, "You have created new trip!", "Have fun while meeting new people");
      this.toggleTripMode();
    },
      error => {
        this.uiNotificationService.addSingleMessage(MessageSeverity.Error, error.message, "");
      });
  }

  private delete(trip: Trip) {

    this.tripService.delete(trip).subscribe(result => {
      this.uiNotificationService.addSingleMessage(MessageSeverity.Info, "You have deleted trip!", "We are not content. Not at all!");
      this.getTripsForUser();
    },
    error => {
      this.uiNotificationService.addErrorMessage(error.message);
    });
  }

  private update(trip: Trip) {
    this.confirmationService.confirm({
      message: "Are you sure that you want to perform this action?",
      accept: () => {
        this.tripService.update(trip).subscribe(result => {

          this.uiNotificationService.addSingleMessage(MessageSeverity.Info, "You have updated trip!");

          this.toggleEditMode(trip);
          this.getTripsForUser();
        },
        error => {
          this.uiNotificationService.addErrorMessage(error.message);
        });
      }
    });
  }

  private becomeGuide() {
    this.confirmationService.confirm({
      message: "Are you sure that you want to become a guide?",
      accept: () => {
        this.guideService.becomeGuide().subscribe(result => {
          this.uiNotificationService.addSuccessMessage("You have become a guide!", "Do not hesitate to add some guided trips just now.");
          this.isGuide = true;
        },
        error => {
            this.uiNotificationService.addErrorMessage(error.message);
        });
      }
    });
  }

  private toggleEditMode(trip: Trip) {
    trip.EditMode = !trip.EditMode;
  }

  private toggleTripMode() {
    this.newTripMode = !this.newTripMode;
    this.resetForm();
  }

  private updateCountryValidation(){
    this.invalidCountry = false;
  }

  private resetForm() {
    this.newTripForm.reset();
  }

  private checkIfIsGuide() {
    this.guideService.checkIfIsGuide().subscribe(result => {
      this.isGuide = result;
    },
    error => {
        this.uiNotificationService.addErrorMessage(error.message);
    });
  }
}


text:
package net.savantly.sprout.domain.home;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration(value = "defaultHomePageConfiguration")
public class HomePageConfiguration {

	@Bean
	@ConditionalOnMissingBean
	public HomePageApi defaultHomePageApi() {
		return new DefaultHomePageApi();
	}
}


text:
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef WIN32
#include <unistd.h>
#else
#include <process.h>
#define snprintf sprintf_s
#endif

#include <mosquitto.h>

static char **topics = NULL;
static int topic_count = 0;
static int topic_qos = 0;
static char *username = NULL;
static char *password = NULL;
int verbose = 0;

void my_message_callback(void *obj, const struct mosquitto_message *message)
{
	if(verbose){
		if(message->payloadlen){
			printf("%s %s\n", message->topic, message->payload);
		}else{
			printf("%s (null)\n", message->topic);
		}
		fflush(stdout);
	}else{
		if(message->payloadlen){
			printf("%s\n", message->payload);
			fflush(stdout);
		}
	}
}

void my_connect_callback(void *obj, int result)
{
	struct mosquitto *mosq = obj;

	int i;
	if(!result){
		for(i=0; i<topic_count; i++){
			mosquitto_subscribe(mosq, NULL, topics[i], topic_qos);
		}
	}else{
		switch(result){
			case 1:
				fprintf(stderr, "Connection Refused: unacceptable protocol version\n");
				break;
			case 2:
				fprintf(stderr, "Connection Refused: identifier rejected\n");
				break;
			case 3:
				fprintf(stderr, "Connection Refused: broker unavailable\n");
				break;
			case 4:
				fprintf(stderr, "Connection Refused: bad user name or password\n");
				break;
			case 5:
				fprintf(stderr, "Connection Refused: not authorised\n");
				break;
			default:
				fprintf(stderr, "Connection Refused: unknown reason\n");
				break;
		}
	}
}

void my_subscribe_callback(void *obj, uint16_t mid, int qos_count, const uint8_t *granted_qos)
{
	int i;

	printf("Subscribed (mid: %d): %d", mid, granted_qos[0]);
	for(i=1; i<qos_count; i++){
		printf(", %d", granted_qos[i]);
	}
	printf("\n");
}

void print_usage(void)
{
	printf("mosquitto_sub is a simple mqtt client that will subscribe to a single topic and print all messages it receives.\n\n");
	printf("Usage: mosquitto_sub [-c] [-i id] [-k keepalive] [-p port] [-q qos] [-v] -t topic ...\n");
	printf("                     [-u username [--pw password]]\n");
	printf("                     [--will-topic [--will-payload payload] [--will-qos qos] [--will-retain]]\n\n");
	printf(" -c : disable 'clean session' (store subscription and pending messages when client disconnects).\n");
	printf(" -d : enable debug messages.\n");
	printf(" -h : mqtt host to connect to. Defaults to localhost.\n");
	printf(" -i : id to use for this client. Defaults to mosquitto_sub_ appended with the process id.\n");
	printf(" -k : keep alive in seconds for this client. Defaults to 60.\n");
	printf(" -p : network port to connect to. Defaults to 1883.\n");
	printf(" -q : quality of service level to use for the subscription. Defaults to 0.\n");
	printf(" -t : mqtt topic to subscribe to. May be repeated multiple times.\n");
	printf(" -u : provide a username (requires MQTT 3.1 broker)\n");
	printf(" -v : print published messages verbosely.\n");
	printf(" --pw : provide a password (requires MQTT 3.1 broker)\n");
	printf(" --will-payload : payload for the client Will, which is sent by the broker in case of\n");
	printf("                  unexpected disconnection. If not given and will-topic is set, a zero\n");
	printf("                  length message will be sent.\n");
	printf(" --will-qos : QoS level for the client Will.\n");
	printf(" --will-retain : if given, make the client Will retained.\n");
	printf(" --will-topic : the topic on which to publish the client Will.\n");
}

int main(int argc, char *argv[])
{
	char id[30];
	int i;
	char *host = "localhost";
	int port = 1883;
	int keepalive = 60;
	bool clean_session = true;
	bool debug = false;
	struct mosquitto *mosq = NULL;

	uint8_t *will_payload = NULL;
	long will_payloadlen = 0;
	int will_qos = 0;
	bool will_retain = false;
	char *will_topic = NULL;

	snprintf(id, 30, "mosquitto_sub_%d", getpid());

	for(i=1; i<argc; i++){
		if(!strcmp(argv[i], "-p") || !strcmp(argv[i], "--port")){
			if(i==argc-1){
				fprintf(stderr, "Error: -p argument given but no port specified.\n\n");
				print_usage();
				return 1;
			}else{
				port = atoi(argv[i+1]);
				if(port<1 || port>65535){
					fprintf(stderr, "Error: Invalid port given: %d\n", port);
					print_usage();
					return 1;
				}
			}
			i++;
		}else if(!strcmp(argv[i], "-c") || !strcmp(argv[i], "--disable-clean-session")){
			clean_session = false;
		}else if(!strcmp(argv[i], "-d") || !strcmp(argv[i], "--debug")){
			debug = true;
		}else if(!strcmp(argv[i], "-h") || !strcmp(argv[i], "--host")){
			if(i==argc-1){
				fprintf(stderr, "Error: -h argument given but no host specified.\n\n");
				print_usage();
				return 1;
			}else{
				host = argv[i+1];
			}
			i++;
		}else if(!strcmp(argv[i], "-i") || !strcmp(argv[i], "--id")){
			if(i==argc-1){
				fprintf(stderr, "Error: -i argument given but no id specified.\n\n");
				print_usage();
				return 1;
			}else{
				memset(id, 0, 30);
				snprintf(id, 29, "%s", argv[i+1]);
			}
			i++;
		}else if(!strcmp(argv[i], "-k") || !strcmp(argv[i], "--keepalive")){
			if(i==argc-1){
				fprintf(stderr, "Error: -k argument given but no keepalive specified.\n\n");
				print_usage();
				return 1;
			}else{
				keepalive = atoi(argv[i+1]);
				if(keepalive>65535){
					fprintf(stderr, "Error: Invalid keepalive given: %d\n", keepalive);
					print_usage();
					return 1;
				}
			}
			i++;
		}else if(!strcmp(argv[i], "-q") || !strcmp(argv[i], "--qos")){
			if(i==argc-1){
				fprintf(stderr, "Error: -q argument given but no QoS specified.\n\n");
				print_usage();
				return 1;
			}else{
				topic_qos = atoi(argv[i+1]);
				if(topic_qos<0 || topic_qos>2){
					fprintf(stderr, "Error: Invalid QoS given: %d\n", topic_qos);
					print_usage();
					return 1;
				}
			}
			i++;
		}else if(!strcmp(argv[i], "-t") || !strcmp(argv[i], "--topic")){
			if(i==argc-1){
				fprintf(stderr, "Error: -t argument given but no topic specified.\n\n");
				print_usage();
				return 1;
			}else{
				topic_count++;
				topics = realloc(topics, topic_count*sizeof(char *));
				topics[topic_count-1] = argv[i+1];
			}
			i++;
		}else if(!strcmp(argv[i], "-u") || !strcmp(argv[i], "--username")){
			if(i==argc-1){
				fprintf(stderr, "Error: -u argument given but no username specified.\n\n");
				print_usage();
				return 1;
			}else{
				username = argv[i+1];
			}
			i++;
		}else if(!strcmp(argv[i], "-v") || !strcmp(argv[i], "--verbose")){
			verbose = 1;
		}else if(!strcmp(argv[i], "--pw")){
			if(i==argc-1){
				fprintf(stderr, "Error: --pw argument given but no password specified.\n\n");
				print_usage();
				return 1;
			}else{
				password = argv[i+1];
			}
			i++;
		}else if(!strcmp(argv[i], "--will-payload")){
			if(i==argc-1){
				fprintf(stderr, "Error: --will-payload argument given but no will payload specified.\n\n");
				print_usage();
				return 1;
			}else{
				will_payload = (uint8_t *)argv[i+1];
				will_payloadlen = strlen((char *)will_payload);
			}
			i++;
		}else if(!strcmp(argv[i], "--will-qos")){
			if(i==argc-1){
				fprintf(stderr, "Error: --will-qos argument given but no will QoS specified.\n\n");
				print_usage();
				return 1;
			}else{
				will_qos = atoi(argv[i+1]);
				if(will_qos < 0 || will_qos > 2){
					fprintf(stderr, "Error: Invalid will QoS %d.\n\n", will_qos);
					return 1;
				}
			}
			i++;
		}else if(!strcmp(argv[i], "--will-retain")){
			will_retain = true;
		}else if(!strcmp(argv[i], "--will-topic")){
			if(i==argc-1){
				fprintf(stderr, "Error: --will-topic argument given but no will topic specified.\n\n");
				print_usage();
				return 1;
			}else{
				will_topic = argv[i+1];
			}
			i++;
		}else{
			fprintf(stderr, "Error: Unknown option '%s'.\n",argv[i]);
			print_usage();
			return 1;
		}
	}
	if(topic_count == 0){
		fprintf(stderr, "Error: You must specify a topic to subscribe to.\n");
		print_usage();
		return 1;
	}
	if(will_payload && !will_topic){
		fprintf(stderr, "Error: Will payload given, but no will topic given.\n");
		print_usage();
		return 1;
	}
	if(will_retain && !will_topic){
		fprintf(stderr, "Error: Will retain given, but no will topic given.\n");
		print_usage();
		return 1;
	}
	if(password && !username){
		fprintf(stderr, "Warning: Not using password since username not set.\n");
	}
	mosquitto_lib_init();
	mosq = mosquitto_new(id, NULL);
	if(!mosq){
		fprintf(stderr, "Error: Out of memory.\n");
		return 1;
	}
	if(debug){
		mosquitto_log_init(mosq, MOSQ_LOG_DEBUG | MOSQ_LOG_ERR | MOSQ_LOG_WARNING
				| MOSQ_LOG_NOTICE | MOSQ_LOG_INFO, MOSQ_LOG_STDERR);
	}
	if(will_topic && mosquitto_will_set(mosq, true, will_topic, will_payloadlen, will_payload, will_qos, will_retain)){
		fprintf(stderr, "Error: Problem setting will.\n");
		return 1;
	}
	if(username && mosquitto_username_pw_set(mosq, username, password)){
		fprintf(stderr, "Error: Problem setting username and password.\n");
		return 1;
	}
	mosquitto_connect_callback_set(mosq, my_connect_callback);
	mosquitto_message_callback_set(mosq, my_message_callback);
	if(debug){
		mosquitto_subscribe_callback_set(mosq, my_subscribe_callback);
	}

	if(mosquitto_connect(mosq, host, port, keepalive, clean_session)){
		fprintf(stderr, "Unable to connect.\n");
		return 1;
	}

	while(!mosquitto_loop(mosq, -1)){
	}
	mosquitto_destroy(mosq);
	mosquitto_lib_cleanup();

	return 0;
}


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

<ui-menu xmlns="http://www.efaps.org/xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://www.efaps.org/xsd http://www.efaps.org/xsd/eFaps_1.0.xsd">
    <uuid>bfd25c10-8e62-43b4-94c3-71db43573289</uuid>
    <file-application>eFapsApp-Products</file-application>
    <definition>
        <version-expression>(version==latest)</version-expression>
        <name>Products_ProductStandartTree_Image</name>
        <access>
            <role>Products_Admin</role>
            <role>Products_Modifier</role>
            <role>Products_Reader</role>
        </access>
        <target>
            <menu>Products_ProductTree_Image_Menu</menu>

Products_Product2ImageTable

            <evaluate program="org.efaps.esjp.common.uitable.MultiPrint">
                <property name="Type">Products_Product2ImageAbstract</property>
                <property name="LinkFrom">ProductAbstractLink</property>
            </evaluate>
            <trigger program="org.efaps.esjp.admin.access.AccessCheck4UI"
                name="Products_ProductMaterialMyDesk.UI_ACCESSCHECK"
                method="configCheck"
                event="UI_ACCESSCHECK">

                <property name="SystemConfig">e53cd705-e463-47dc-a400-4ace4ed72071</property>
                <property name="AttributeExists">org.efaps.products.Standart.Image</property>
            </trigger>
        </target>

        <property name="Target">content</property>
        <property name="TargetMode">view</property>
        <property name="TargetShowCheckBoxes">true</property>
    </definition>
</ui-menu>


text:
<?php
/**
 * WorkflowActivityStateEnum.php
 * 2013 Petr Dvorak, petr-dvorak.cz / 14.4.13 16:40
 */

namespace ITILSimulator\Runtime\Workflow;

/**
 * Enumeration of available workflow activity states
 * @package ITILSimulator\Runtime\Workflow
 */
class WorkflowActivityStateEnum
{
	const WAITING = 1;
	const RUNNING = 2;
	const FINISHED = 3;
	const CANCELLED = 4;
}


text:
@class JavaLangShort;

@interface OrgBouncycastleUtilShorts : NSObject

#pragma mark Public

- (instancetype)init;

+ (JavaLangShort *)valueOfWithShort:(jshort)value;

@end

J2OBJC_EMPTY_STATIC_INIT(OrgBouncycastleUtilShorts)

FOUNDATION_EXPORT JavaLangShort *OrgBouncycastleUtilShorts_valueOfWithShort_(jshort value);

FOUNDATION_EXPORT void OrgBouncycastleUtilShorts_init(OrgBouncycastleUtilShorts *self);

FOUNDATION_EXPORT OrgBouncycastleUtilShorts *new_OrgBouncycastleUtilShorts_init() NS_RETURNS_RETAINED;

J2OBJC_TYPE_LITERAL_HEADER(OrgBouncycastleUtilShorts)

#endif // _OrgBouncycastleUtilShorts_H_


text:
@import UIKit;
#import "DXAppDelegate.h"

int main(int argc, char * argv[])
{
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([DXAppDelegate class]));
    }
}


text:
using namespace Gaffer;

/// \todo If we expose ValuePlug::HashProcess and ValuePlug::ComputeProcess
/// then we can use the types defined there directly.
static IECore::InternedString g_hashType( "computeNode:hash" );
static IECore::InternedString g_computeType( "computeNode:compute" );
static PerformanceMonitor::Statistics g_emptyStatistics;

//////////////////////////////////////////////////////////////////////////
// PerformanceMonitor::Statistics
//////////////////////////////////////////////////////////////////////////

PerformanceMonitor::Statistics::Statistics( size_t hashCount, size_t computeCount, boost::chrono::nanoseconds hashDuration, boost::chrono::nanoseconds computeDuration )
	:	hashCount( hashCount ), computeCount( computeCount ), hashDuration( hashDuration ), computeDuration( computeDuration )
{
}

PerformanceMonitor::Statistics & PerformanceMonitor::Statistics::operator += ( const Statistics &rhs )
{
	hashCount += rhs.hashCount;
	computeCount += rhs.computeCount;
	hashDuration += rhs.hashDuration;
	computeDuration += rhs.computeDuration;
	return *this;
}

bool PerformanceMonitor::Statistics::operator == ( const Statistics &rhs )
{
	return
		hashCount == rhs.hashCount &&
		computeCount == rhs.computeCount &&
		hashDuration == rhs.hashDuration &&
		computeDuration == rhs.computeDuration
	;
}

bool PerformanceMonitor::Statistics::operator != ( const Statistics &rhs )
{
	return !( *this == rhs );
}

//////////////////////////////////////////////////////////////////////////
// PerformanceMonitor
//////////////////////////////////////////////////////////////////////////

PerformanceMonitor::PerformanceMonitor()
{
}

PerformanceMonitor::~PerformanceMonitor()
{
}

const PerformanceMonitor::StatisticsMap &PerformanceMonitor::allStatistics() const
{
	collate();
	return m_statistics;
}

const PerformanceMonitor::Statistics &PerformanceMonitor::plugStatistics( const Plug *plug ) const
{
	collate();
	StatisticsMap::const_iterator it = m_statistics.find( plug );
	if( it == m_statistics.end() )
	{
		return g_emptyStatistics;
	}
	return it->second;
}

void PerformanceMonitor::processStarted( const Process *process )
{
	const IECore::InternedString type = process->type();
	if( type != g_hashType && type != g_computeType )
	{
		return;
	}

	ThreadData &threadData = m_threadData.local();

	boost::chrono::high_resolution_clock::time_point now = boost::chrono::high_resolution_clock::now();
	if( !threadData.durationStack.empty() )
	{
		*(threadData.durationStack.top()) += now - threadData.then;
	}
	threadData.then = now;

	Statistics &s = threadData.statistics[process->plug()];
	if( type == g_hashType )
	{
		s.hashCount++;
		threadData.durationStack.push( &s.hashDuration );
	}
	else
	{
		s.computeCount++;
		threadData.durationStack.push( &s.computeDuration );
	}
}

void PerformanceMonitor::processFinished( const Process *process )
{
	const IECore::InternedString type = process->type();
	if( type != g_hashType && type != g_computeType )
	{
		return;
	}

	ThreadData &threadData = m_threadData.local();
	boost::chrono::high_resolution_clock::time_point now = boost::chrono::high_resolution_clock::now();
	*(threadData.durationStack.top()) += now - threadData.then;
	threadData.durationStack.pop();
	threadData.then = now;
}

void PerformanceMonitor::collate() const
{
	tbb::enumerable_thread_specific<ThreadData, tbb::cache_aligned_allocator<ThreadData>, tbb::ets_key_per_instance>::iterator it, eIt;
	for( it = m_threadData.begin(), eIt = m_threadData.end(); it != eIt; ++it )
	{
		StatisticsMap &m = it->statistics;
		for( StatisticsMap::const_iterator mIt = m.begin(), meIt = m.end(); mIt != meIt; ++mIt )
		{
			m_statistics[mIt->first] += mIt->second;
		}
		m.clear();
	}
}


text:
package org.jabref.shared;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.jabref.model.entry.BibEntry;
import org.jabref.shared.exception.InvalidDBMSConnectionPropertiesException;
import org.jabref.shared.exception.OfflineLockException;
import org.jabref.testutils.category.DatabaseTest;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;

@DatabaseTest
public class DBMSProcessorTest {

    private DBMSConnection dbmsConnection;
    private DBMSProcessor dbmsProcessor;

    @Parameter
    public DBMSType dbmsType;

    @BeforeEach
    public void setUp() throws SQLException, InvalidDBMSConnectionPropertiesException {
        dbmsConnection = TestConnector.getTestDBMSConnection(dbmsType);
        dbmsProcessor = DBMSProcessor.getProcessorInstance(dbmsConnection);
        dbmsProcessor.setupSharedDatabase();
    }

    @Parameters(name = "Test with {0} database system")
    public static Collection<DBMSType> getTestingDatabaseSystems() {
        return TestManager.getDBMSTypeTestParameter();
    }

    @Test
    public void testCheckBaseIntegrity() throws SQLException {
        assertTrue(dbmsProcessor.checkBaseIntegrity());
        clear();
        assertFalse(dbmsProcessor.checkBaseIntegrity());
    }

    @Test
    public void testSetUpSharedDatabase() throws SQLException {
        clear();
        dbmsProcessor.setupSharedDatabase();
        assertTrue(dbmsProcessor.checkBaseIntegrity());
    }

    @Test
    public void testInsertEntry() throws SQLException {
        BibEntry expectedEntry = getBibEntryExample();

        dbmsProcessor.insertEntry(expectedEntry);

        BibEntry emptyEntry = new BibEntry();
        emptyEntry.getSharedBibEntryData().setSharedID(1);
        dbmsProcessor.insertEntry(emptyEntry); // does not insert, due to same sharedID.

        Map<String, String> actualFieldMap = new HashMap<>();

        try (ResultSet entryResultSet = selectFrom("ENTRY")) {
            assertTrue(entryResultSet.next());
            assertEquals(1, entryResultSet.getInt("SHARED_ID"));
            assertEquals("inproceedings", entryResultSet.getString("TYPE"));
            assertEquals(1, entryResultSet.getInt("VERSION"));
            assertFalse(entryResultSet.next());

            try (ResultSet fieldResultSet = selectFrom("FIELD")) {
                while (fieldResultSet.next()) {
                    actualFieldMap.put(fieldResultSet.getString("NAME"), fieldResultSet.getString("VALUE"));
                }
            }
        }

        Map<String, String> expectedFieldMap = expectedEntry.getFieldMap();

        assertEquals(expectedFieldMap, actualFieldMap);
    }

    @Test
    public void testUpdateEntry() throws OfflineLockException, SQLException {
        BibEntry expectedEntry = getBibEntryExample();

        dbmsProcessor.insertEntry(expectedEntry);

        expectedEntry.setType("book");
        expectedEntry.setField("author", "Michael J and Hutchings");
        expectedEntry.setField("customField", "custom value");
        expectedEntry.clearField("booktitle");

        dbmsProcessor.updateEntry(expectedEntry);

        Optional<BibEntry> actualEntryOptional = dbmsProcessor
                .getSharedEntry(expectedEntry.getSharedBibEntryData().getSharedID());

        assertEquals(expectedEntry, actualEntryOptional.get());
    }

    @Test
    public void testUpdateNewerEntry() throws OfflineLockException, SQLException {
        BibEntry bibEntry = getBibEntryExample();

        dbmsProcessor.insertEntry(bibEntry);

        //simulate older version
        bibEntry.getSharedBibEntryData().setVersion(0);
        bibEntry.setField("year", "1993");

        assertThrows(OfflineLockException.class, () -> dbmsProcessor.updateEntry(bibEntry));
    }

    @Test
    public void testUpdateEqualEntry() throws OfflineLockException, SQLException {
        BibEntry expectedBibEntry = getBibEntryExample();

        dbmsProcessor.insertEntry(expectedBibEntry);
        //simulate older version
        expectedBibEntry.getSharedBibEntryData().setVersion(0);
        dbmsProcessor.updateEntry(expectedBibEntry);

        Optional<BibEntry> actualBibEntryOptional = dbmsProcessor
                .getSharedEntry(expectedBibEntry.getSharedBibEntryData().getSharedID());

        assertEquals(expectedBibEntry, actualBibEntryOptional.get());
    }

    @Test
    public void testRemoveEntry() throws SQLException {
        BibEntry bibEntry = getBibEntryExample();
        dbmsProcessor.insertEntry(bibEntry);
        dbmsProcessor.removeEntry(bibEntry);

        try (ResultSet resultSet = selectFrom("ENTRY")) {
            assertFalse(resultSet.next());
        }
    }

    @Test
    public void testGetSharedEntries() {
        BibEntry bibEntry = getBibEntryExampleWithEmptyFields();

        dbmsProcessor.insertEntry(bibEntry);

        List<BibEntry> expectedEntries = Arrays.asList(bibEntry);
        List<BibEntry> actualEntries = dbmsProcessor.getSharedEntries();

        assertEquals(expectedEntries, actualEntries);
    }

    @Test
    public void testGetSharedEntry() {
        BibEntry expectedBibEntry = getBibEntryExampleWithEmptyFields();

        dbmsProcessor.insertEntry(expectedBibEntry);

        Optional<BibEntry> actualBibEntryOptional = dbmsProcessor
                .getSharedEntry(expectedBibEntry.getSharedBibEntryData().getSharedID());

        assertEquals(expectedBibEntry, actualBibEntryOptional.get());
    }

    @Test
    public void testGetNotExistingSharedEntry() {
        Optional<BibEntry> actualBibEntryOptional = dbmsProcessor.getSharedEntry(1);
        assertFalse(actualBibEntryOptional.isPresent());
    }

    @Test
    public void testGetSharedIDVersionMapping() throws OfflineLockException, SQLException {
        BibEntry firstEntry = getBibEntryExample();
        BibEntry secondEntry = getBibEntryExample();

        dbmsProcessor.insertEntry(firstEntry);
        dbmsProcessor.insertEntry(secondEntry);
        dbmsProcessor.updateEntry(secondEntry);

        Map<Integer, Integer> expectedIDVersionMap = new HashMap<>();
        expectedIDVersionMap.put(firstEntry.getSharedBibEntryData().getSharedID(), 1);
        expectedIDVersionMap.put(secondEntry.getSharedBibEntryData().getSharedID(), 2);

        Map<Integer, Integer> actualIDVersionMap = dbmsProcessor.getSharedIDVersionMapping();

        assertEquals(expectedIDVersionMap, actualIDVersionMap);
    }

    @Test
    public void testGetSharedMetaData() {
        insertMetaData("databaseType", "bibtex;");
        insertMetaData("protectedFlag", "true;");
        insertMetaData("saveActions", "enabled;\nauthor[capitalize,html_to_latex]\ntitle[title_case]\n;");
        insertMetaData("saveOrderConfig", "specified;author;false;title;false;year;true;");

        Map<String, String> expectedMetaData = getMetaDataExample();
        Map<String, String> actualMetaData = dbmsProcessor.getSharedMetaData();

        assertEquals(expectedMetaData, actualMetaData);
    }

    @Test
    public void testSetSharedMetaData() throws SQLException {
        Map<String, String> expectedMetaData = getMetaDataExample();
        dbmsProcessor.setSharedMetaData(expectedMetaData);

        Map<String, String> actualMetaData = dbmsProcessor.getSharedMetaData();

        assertEquals(expectedMetaData, actualMetaData);
    }

    private Map<String, String> getMetaDataExample() {
        Map<String, String> expectedMetaData = new HashMap<>();

        expectedMetaData.put("databaseType", "bibtex;");
        expectedMetaData.put("protectedFlag", "true;");
        expectedMetaData.put("saveActions", "enabled;\nauthor[capitalize,html_to_latex]\ntitle[title_case]\n;");
        expectedMetaData.put("saveOrderConfig", "specified;author;false;title;false;year;true;");

        return expectedMetaData;
    }

    private BibEntry getBibEntryExampleWithEmptyFields() {
        BibEntry bibEntry = new BibEntry();
        bibEntry.setField("author", "Author");
        bibEntry.setField("title", "");
        bibEntry.setField("year", "");
        bibEntry.getSharedBibEntryData().setSharedID(1);
        return bibEntry;
    }

    private BibEntry getBibEntryExample() {
        BibEntry bibEntry = new BibEntry();
        bibEntry.setType("inproceedings");
        bibEntry.setField("author", "Wirthlin, Michael J and Hutchings, Brad L and Gilson, Kent L");
        bibEntry.setField("title", "The nano processor: a low resource reconfigurable processor");
        bibEntry.setField("booktitle", "FPGAs for Custom Computing Machines, 1994. Proceedings. IEEE Workshop on");
        bibEntry.setField("year", "1994");
        bibEntry.setCiteKey("nanoproc1994");
        return bibEntry;
    }

    private ResultSet selectFrom(String table) {
        try {
            return dbmsConnection.getConnection().createStatement().executeQuery("SELECT * FROM " + escape(table));
        } catch (SQLException e) {
            fail(e.getMessage());
            return null;
        }
    }

    // Oracle does not support multiple tuple insertion in one INSERT INTO command.
    // Therefore this function was defined to improve the readability and to keep the code short.
    private void insertMetaData(String key, String value) {
        try {
            dbmsConnection.getConnection().createStatement().executeUpdate("INSERT INTO " + escape("METADATA") + "("
                    + escape("KEY") + ", " + escape("VALUE") + ") VALUES("
                    + escapeValue(key) + ", " + escapeValue(value) + ")");
        } catch (SQLException e) {
            fail(e.getMessage());
        }
    }

    private String escape(String expression) {
        return dbmsProcessor.escape(expression);
    }

    private String escapeValue(String value) {
        return "'" + value + "'";
    }

    @AfterEach
    public void clear() throws SQLException {
        TestManager.clearTables(dbmsConnection);
    }
}


text:
layout: frontmatter
title: Ambient Intelligence 2015
active: Home
---

					The course aims at
					describing the field of Ambient Intelligence (AmI), outlining its
					multi-disciplinary nature and its technology and application areas.
					The evolution of consumer electronic technologies, of wireless
					networks, of sensors and the ability to represent and process
					knowledge and data on a large scale, nowadays allow the conception
					of intelligent environments able to handle, in an optimal way,
					energy-related variables, comfort, safety and user interaction.
					Such scenarios spur a variety of solutions, ranging from smart
					homes to smart buildings, from smart cities to smart transportation
					systems. Special emphasis, on the course, will be devoted to
					design-related aspects and on the overall hardware-software
					architectures, besides reviewing the involved technologies. This
					will enable the conception and realization of reusable and
					interoperable solutions. The course will include some seminars
					given by industry experts.

Skills

Writing system specifications and high-level design of an
					ambient intelligence system, starting from its functional and
					behavioral requirements. Realization of intelligent scenarios over
					real smart environments.

Knowledge

Technologies involved in the design and realization of
					intelligent environments, at the various architectural levels
					(sensors, domotic networks, wireless sensor networks, residential
					gateways, stream data processing, big data analysis, user
					interfaces). Application of user-driven design methodologies.

Engagement

Students are required to engage in design and implementation
					of real-world intelligent environments. They are required to
					team-up around project ideas individually proposed and socially
					ranked. Teams are composed by 3 students on average, and select the
					project to carry-on throughout the course. Final outcomes are
					publicly reachable (see below for current projects).

					Learn more about the course by visiting http://bit.ly/polito-ami.

					Video lectures are freely available on a dedicated YouTube playlist and on the teaching portal of the Politecnico di Torino.

		{% assign projects = site.categories.projects | sort: 'title' %} {%for post in projects %} {% assign odd = forloop.index0 | modulo:2 %}
		{%if odd == 0 %}

					{{ post.title }} {%if post.acronym %} ({{post.acronym}}) {% endif %}

					{{ post.content}} Read more...

		{% else %}

					{{ post.title }} {%if post.acronym %} ({{post.acronym}}) {% endif %}

					{{ post.content}} Read more...

		{% endif %} {% endfor %}

Other projects

			{% assign projects = site.categories.other-projects | sort: 'title' %}
			{% for post in projects %} {% assign odd = forloop.index0 | modulo:2 %}

			{%if odd == 0 %}

						{{ post.title }} {%if post.acronym %} ({{post.acronym}}) {% endif %}

						{{ post.content}} Read more...

			{% else %}

						{{ post.title }} {%if post.acronym %} ({{post.acronym}}) {% endif %}

						{{ post.content}} Read more...

			{% endif %} {% endfor %}


text:
"""Data Retriever Excel Functions

This module contains optional functions for importing data from Excel.

"""

class Excel:
    """Excel class to handle excel values"""

    @staticmethod
    def empty_cell(cell):
        """Test if excel cell is empty or contains only whitespace."""
        if cell.ctype == 0:
            return True
        if str(cell.value).strip() == "":
            return True
        return False

    @staticmethod
    def cell_value(cell):
        """Return string value of an excel spreadsheet cell."""
        if (cell.value).__class__.__name__ == 'unicode':
            return (str(cell.value).encode()).strip()
        return str(cell.value).strip()


text:
package org.ots.app.conf;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@EnableAutoConfiguration
@Configuration
@ComponentScan({"org.ots.app.*"})
public class BootWebConfig{

}


text:
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>SPKO</title>
    <link href="<?php echo base_url('asset/js/plugins/datatables/extensions/Buttons/css/buttons.dataTables.min.css'); ?>" rel="stylesheet">
    <!-- PACE LOAD BAR PLUGIN - This creates the subtle load bar effect at the top of the page. -->
    <link href="<?php echo base_url('asset/css/plugins/pace/pace.css'); ?>" rel="stylesheet">
    <script src="<?php echo base_url('asset/js/plugins/pace/pace.js'); ?>"></script>

    <!-- GLOBAL STYLES - Include these on every page. -->
    <link href="<?php echo base_url('asset/css/plugins/bootstrap/css/bootstrap.min.css'); ?>" rel="stylesheet">
    <!-- <link href='http://fonts.googleapis.com/css?family=Ubuntu:300,400,500,700,300italic,400italic,500italic,700italic' rel="stylesheet" type="text/css">
    <link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel="stylesheet" type="text/css"> -->
    <script src="<?php echo base_url('asset/js/jquery.min.js'); ?>"></script>
    <link href="<?php echo base_url('asset/icons/font-awesome/css/font-awesome.min.css'); ?>" rel="stylesheet">

    <!-- PAGE LEVEL PLUGIN STYLES -->

    <!-- THEME STYLES - Include these on every page. -->
    <link href="<?php echo base_url('asset/css/style.css'); ?>" rel="stylesheet">
    <link href="<?php echo base_url('asset/css/plugins.css'); ?>" rel="stylesheet">

    <!-- THEME DEMO STYLES - Use these styles for reference if needed. Otherwise they can be deleted. -->
    <link href="<?php echo base_url('asset/css/demo.css'); ?>" rel="stylesheet">
    <!-- JQUERY -->

    <!-- DataTables -->
    <link href="<?php echo base_url('asset/css/plugins/datatables/datatables.css'); ?>" rel="stylesheet">
    <script src="<?php echo base_url('asset/js/plugins/datatables/jquery.dataTables.js'); ?>"></script>
    <script src="<?php echo base_url('asset/js/plugins/datatables/dataTables.bootstrap4.js'); ?>"></script>

    <!--[if lt IE 9]>
      <script src="js/html5shiv.js"></script>
      <script src="js/respond.min.js"></script>
    <![endif]-->


text:
Ajouter un contrôle<?= $data['promo'] ? ' de promo' : '' ?>

        <form method="post"
            action="<?= base_url('Process_Control/add' . ($data['promo'] ? '/promo' : '')) ?>">

                        <input type="text" id="name" name="name"/>
                        Libellé

                        <select name="typeId" id="typeId">
                            <?php
                            foreach ($data['controlTypes'] as $controlType)
                            { ?>
                                <option value="<?= $controlType->idControlType ?>"
                                    <?= $data['promo'] && $controlType->idControlType == 1 ? 'selected' : '' ?>
                                    ><?= $controlType->controlTypeName ?>
                                </option>
                                <?php
                            }
                            ?>
                        </select>
                        Type de Controle

                        <input type="number" id="coefficient" name="coefficient" step="0.5" min="0" value="1"/>
                        Coefficient

                        <input type="number" id="divisor" name="divisor" min="1" value="20"/>
                        Diviseur

                        <?php if ($data['promo'] === false)
                        { ?>
                            <select name="educationId" id="educationId">
                                <?php
                                foreach ($data['select'] as $education)
                                { ?>
                                    <option value="<?= $education->idEducation ?>"
                                        ><?= $education->groupName . $education->courseType . ' en ' . $education->subjectName ?>
                                    </option>
                                    <?php
                                } ?>
                            </select>
                            Groupe
                            <?php
                        } else { ?>
                            <select name="subjectId" id="subjectId">
                                <?php
                                foreach ($data['select'] as $subject)
                                { ?>
                                    <option value="<?= $subject->idSubject ?>"
                                        ><?= $subject->subjectCode . ' - ' . $subject->subjectName ?>
                                    </option>
                                    <?php
                                } ?>
                            </select>
                            Matière
                            <?php
                        } ?>

                        <input type="text" id="date" name="date"
                               class="datepicker" value="<?= date('d/m/Y') ?>"/>
                        Date du controle

                <button type="submit" class="btn-flat waves-effect">Ajouter</button>
                <a class="btn-flat" href="<?= site_url('Control') ?>">Annuler

        </form>

Type de contrôle incompatibles

                Vous avez changer de type de DS, et le type choisi est
                incompatible avec la page de création de DS actuelle.

Voulez-vous être redirigé vers la page de création adaptée ?

            Oui
            Non


text:
package org.gradle.model.internal.manage.schema.extract;

import org.gradle.internal.Cast;
import org.gradle.model.internal.core.DefaultModelViewState;
import org.gradle.model.internal.core.ModelPath;
import org.gradle.model.internal.core.ModelView;
import org.gradle.model.internal.core.MutableModelNode;
import org.gradle.model.internal.core.rule.describe.ModelRuleDescriptor;
import org.gradle.model.internal.type.ModelType;

import java.util.Collection;

public abstract class ScalarCollectionModelView<E, C extends Collection<E>> implements ModelView<C> {
    protected final ModelPath path;
    protected final ModelType<E> elementType;
    protected final ModelType<C> type;
    protected final MutableModelNode modelNode;
    protected final boolean overwritable;
    protected final DefaultModelViewState state;

    public ScalarCollectionModelView(ModelPath path, ModelType<C> type, ModelType<E> elementType, MutableModelNode modelNode, ModelRuleDescriptor descriptor, boolean overwritable, boolean mutable) {
        this.path = path;
        this.type = type;
        this.elementType = elementType;
        this.modelNode = modelNode;
        this.overwritable = overwritable;
        this.state = new DefaultModelViewState(path, type, descriptor, mutable, false);
    }

    @Override
    public ModelPath getPath() {
        return path;
    }

    @Override
    public ModelType<C> getType() {
        return type;
    }

    private Collection<E> getBackingValue() {
        return Cast.uncheckedCast(modelNode.getPrivateData(Collection.class));
    }

    private void setBackingValue(Collection<E> values) {
        if (state.isCanMutate()) {
            modelNode.setPrivateData(Collection.class, values);
        }
    }

    protected abstract C toMutationSafe(Collection<?> backingCollection);

    @Override
    public C getInstance() {
        Collection<?> delegate = getBackingValue();
        if (delegate == null) {
            if (overwritable || state.isCanMutate()) {
                // if the collection is a read-only property, it must be initialized first (it will never be null)
                // if the collection is *not* read-only, then we will initialize it only if the collection is the
                // subject of a rule, that is to say that it can be mutated. This may look strange, if a read-write
                // collection is null to initialize it to an empty list, but this is how the specs define reaw-write
                // collections of scalar types.
                delegate = initializeEmptyCollection();
            }
        }
        return delegate == null ? null : toMutationSafe(delegate);
    }

    private Collection<E> initializeEmptyCollection() {
        Collection<E> delegate = initialValue();
        setBackingValue(delegate);
        return delegate;
    }

    @Override
    public void close() {
        C instance = getInstance();
        state.closer().execute(instance);
    }

    protected abstract C initialValue();

    @SuppressWarnings("unchecked")
    public Object setValue(Object values) {
        state.assertCanMutate();
        if (values == null) {
            setBackingValue(null);
            return null;
        } else {
            Collection<E> objects = initializeEmptyCollection();
            objects.addAll((Collection<? extends E>) values);
            return objects;
        }
    }
}


text:
package org.olap4j;

import org.olap4j.impl.Olap4jUtil;
import org.olap4j.metadata.*;
import org.olap4j.test.TestContext;

import junit.framework.TestCase;

import java.sql.*;
import java.util.*;

/**
 * Unit test for olap4j metadata methods.
 */
public class MetadataTest extends TestCase {
    private TestContext testContext = TestContext.instance();
    private TestContext.Tester tester = testContext.getTester();
    private static final String NL = System.getProperty("line.separator");

    private Connection connection;
    private String catalogName;
    private OlapConnection olapConnection;
    private OlapDatabaseMetaData olapDatabaseMetaData;
    private final String propertyNamePattern = null;
    private final String dataSourceName = "xx";

    private static final List<String> CUBE_COLUMN_NAMES = Arrays.asList(
        "CATALOG_NAME", "SCHEMA_NAME", "CUBE_NAME", "CUBE_TYPE", "CUBE_GUID",
        "CREATED_ON", "LAST_SCHEMA_UPDATE", "SCHEMA_UPDATED_BY",
        "LAST_DATA_UPDATE", "DATA_UPDATED_BY", "IS_DRILLTHROUGH_ENABLED",
        "IS_WRITE_ENABLED", "IS_LINKABLE", "IS_SQL_ENABLED", "DESCRIPTION");
    private static final List<String> LITERALS_COLUMN_NAMES = Arrays.asList(
        "LITERAL_NAME", "LITERAL_VALUE", "LITERAL_INVALID_CHARS",
        "LITERAL_INVALID_STARTING_CHARS", "LITERAL_MAX_LENGTH");
    private static final List<String> SETS_COLUMN_NAMES = Arrays.asList(
        "CATALOG_NAME", "SCHEMA_NAME", "CUBE_NAME", "SET_NAME", "SCOPE");
    private static final List<String> PROPERTIES_COLUMN_NAMES = Arrays.asList(
        "CATALOG_NAME", "SCHEMA_NAME", "CUBE_NAME", "DIMENSION_UNIQUE_NAME",
        "HIERARCHY_UNIQUE_NAME", "LEVEL_UNIQUE_NAME", "MEMBER_UNIQUE_NAME",
        "PROPERTY_NAME", "PROPERTY_CAPTION", "PROPERTY_TYPE", "DATA_TYPE",
        "PROPERTY_CONTENT_TYPE", "DESCRIPTION");
    private static final List<String> MEMBERS_COLUMN_NAMES = Arrays.asList(
        "CATALOG_NAME", "SCHEMA_NAME", "CUBE_NAME", "DIMENSION_UNIQUE_NAME",
        "HIERARCHY_UNIQUE_NAME", "LEVEL_UNIQUE_NAME", "LEVEL_NUMBER",
        "MEMBER_ORDINAL", "MEMBER_NAME", "MEMBER_UNIQUE_NAME", "MEMBER_TYPE",
        "MEMBER_GUID", "MEMBER_CAPTION", "CHILDREN_CARDINALITY", "PARENT_LEVEL",
        "PARENT_UNIQUE_NAME", "PARENT_COUNT", "TREE_OP", "DEPTH");
    private static final List<String> MEASURES_COLUMN_NAMES = Arrays.asList(
        "CATALOG_NAME", "SCHEMA_NAME", "CUBE_NAME", "MEASURE_NAME",
        "MEASURE_UNIQUE_NAME", "MEASURE_CAPTION", "MEASURE_GUID",
        "MEASURE_AGGREGATOR", "DATA_TYPE", "MEASURE_IS_VISIBLE", "LEVELS_LIST",
        "DESCRIPTION");
    private static final List<String> LEVELS_COLUMN_NAMES = Arrays.asList(
        "CATALOG_NAME", "SCHEMA_NAME", "CUBE_NAME", "DIMENSION_UNIQUE_NAME",
        "HIERARCHY_UNIQUE_NAME", "LEVEL_NAME", "LEVEL_UNIQUE_NAME",
        "LEVEL_GUID", "LEVEL_CAPTION", "LEVEL_NUMBER", "LEVEL_CARDINALITY",
        "LEVEL_TYPE", "CUSTOM_ROLLUP_SETTINGS", "LEVEL_UNIQUE_SETTINGS",
        "LEVEL_IS_VISIBLE", "DESCRIPTION");
    private static final List<String> HIERARCHIES_COLUMN_NAMES = Arrays.asList(
        "CATALOG_NAME", "SCHEMA_NAME", "CUBE_NAME", "DIMENSION_UNIQUE_NAME",
        "HIERARCHY_NAME", "HIERARCHY_UNIQUE_NAME", "HIERARCHY_GUID",
        "HIERARCHY_CAPTION", "DIMENSION_TYPE", "HIERARCHY_CARDINALITY",
        "DEFAULT_MEMBER", "ALL_MEMBER", "DESCRIPTION", "STRUCTURE",
        "IS_VIRTUAL", "IS_READWRITE", "DIMENSION_UNIQUE_SETTINGS",
        "DIMENSION_IS_VISIBLE", "HIERARCHY_IS_VISIBLE", "HIERARCHY_ORDINAL",
        "DIMENSION_IS_SHARED", "PARENT_CHILD");
    private static final List<String> FUNCTIONS_COLUMN_NAMES = Arrays.asList(
        "FUNCTION_NAME", "DESCRIPTION", "PARAMETER_LIST", "RETURN_TYPE",
        "ORIGIN", "INTERFACE_NAME", "LIBRARY_NAME", "CAPTION");
    private static final List<String> DIMENSIONS_COLUMN_NAMES = Arrays.asList(
        "CATALOG_NAME", "SCHEMA_NAME", "CUBE_NAME", "DIMENSION_NAME",
        "DIMENSION_UNIQUE_NAME", "DIMENSION_GUID", "DIMENSION_CAPTION",
        "DIMENSION_ORDINAL", "DIMENSION_TYPE", "DIMENSION_CARDINALITY",
        "DEFAULT_HIERARCHY", "DESCRIPTION", "IS_VIRTUAL", "IS_READWRITE",
        "DIMENSION_UNIQUE_SETTINGS", "DIMENSION_MASTER_UNIQUE_NAME",
        "DIMENSION_IS_VISIBLE");
    private static final List<String> DATABASE_PROPERTIES_COLUMN_NAMES =
        Arrays.asList(
            "PROPERTY_NAME", "PROPERTY_DESCRIPTION", "PROPERTY_TYPE",
            "PROPERTY_ACCESS_TYPE", "IS_REQUIRED", "PROPERTY_VALUE");
    private static final List<String> DATASOURCES_COLUMN_NAMES = Arrays.asList(
        "DATA_SOURCE_NAME", "DATA_SOURCE_DESCRIPTION", "URL",
        "DATA_SOURCE_INFO", "PROVIDER_NAME", "PROVIDER_TYPE",
        "AUTHENTICATION_MODE");
    private static final List<String> CATALOGS_COLUMN_NAMES = Arrays.asList(
        "TABLE_CAT");
    private static final List<String> SCHEMAS_COLUMN_NAMES = Arrays.asList(
        "TABLE_SCHEM", "TABLE_CAT");
    private static final List<String> ACTIONS_COLUMN_NAMES = Arrays.asList(
        "CATALOG_NAME", "SCHEMA_NAME", "CUBE_NAME", "ACTION_NAME", "COORDINATE",
        "COORDINATE_TYPE");

    public MetadataTest() throws SQLException {
    }

    protected void setUp() throws SQLException {
        connection = tester.createConnection();
        catalogName = connection.getCatalog();
        olapConnection =
            tester.getWrapper().unwrap(connection, OlapConnection.class);
        olapDatabaseMetaData  = olapConnection.getMetaData();
    }

    protected void tearDown() throws Exception {
        if (connection != null && !connection.isClosed()) {
            connection.close();
            connection = null;
        }
        connection = null;
        olapConnection = null;
        olapDatabaseMetaData = null;
        testContext = null;
        tester = null;
    }

    // ~ Helper methods ----------

    private void assertContains(String seek, String s) {
        if (s.indexOf(seek) < 0) {
            fail("expected to find '" + seek + "' in '" + s + "'");
        }
    }

    private void assertContainsLine(String partial, String seek, String s) {
        if (partial == null) {
            partial = seek;
        }
        int i = s.indexOf(partial);
        if (i < 0) {
            fail("expected to find '" + seek + "' in '" + s + "'");
        }
        int start = i;
        while (start > 0
               && s.charAt(start - 1) != 0x0D
               && s.charAt(start - 1) != 0x0A)
        {
            --start;
        }
        int end = i;
        while (end < s.length()
               && s.charAt(end) != 0x0D
               && s.charAt(end) != 0x0A)
        {
            ++end;
        }
        String line = s.substring(start, end);
        assertEquals(seek, line);
    }

    private void assertNotContains(String seek, String s) {
        if (s.indexOf(seek) >= 0) {
            fail("expected not to find '" + seek + "' in '" + s + "'");
        }
    }

    private int linecount(String s) {
        int i = 0;
        int count = 0;
        while (i < s.length()) {
            int nl = s.indexOf('\n', i);
            if (nl < 0) {
                break;
            }
            i = nl + 1;
            ++count;
        }
        return count;
    }

    // ~ Tests follow -------------

    public void testDatabaseMetaData() throws SQLException {
        assertEquals("" + catalogName + "", catalogName);

        DatabaseMetaData databaseMetaData = connection.getMetaData();
        switch (tester.getFlavor()) {
        case XMLA:
        case REMOTE_XMLA:
            // FIXME: implement getDatabaseXxxVersion in XMLA driver
            break;
        default:
            assertTrue(databaseMetaData.getDatabaseMajorVersion() > 0);
            assertTrue(databaseMetaData.getDatabaseMinorVersion() >= 0);
//            assertTrue(databaseMetaData.getDatabaseProductName() != null);
            assertTrue(databaseMetaData.getDatabaseProductVersion() != null);
            break;
        }
        assertTrue(databaseMetaData.getDriverName() != null);
        assertTrue(databaseMetaData.getDriverVersion() != null);

        // mondrian-specific
        switch (tester.getFlavor()) {
        case MONDRIAN:
            assertTrue(databaseMetaData.isReadOnly());
            assertNull(databaseMetaData.getUserName());
            assertNotNull(databaseMetaData.getURL());
            break;
        }

        // unwrap connection; may or may not be the same object as connection;
        // check extended methods

        // also unwrap metadata from regular connection
        assertTrue(
            ((OlapWrapper) databaseMetaData).isWrapperFor(
                OlapDatabaseMetaData.class));
        assertFalse(
            ((OlapWrapper) databaseMetaData).isWrapperFor(
                OlapStatement.class));
        OlapDatabaseMetaData olapDatabaseMetaData1 =
            ((OlapWrapper) databaseMetaData).unwrap(
                OlapDatabaseMetaData.class);
        assertTrue(
            olapDatabaseMetaData1.getDriverName().equals(
                olapDatabaseMetaData.getDriverName()));
        switch (tester.getFlavor()) {
        case XMLA:
        case REMOTE_XMLA:
            // FIXME: implement getDatabaseXxxVersion in XMLA driver
            break;
        default:
            assertTrue(
                olapDatabaseMetaData1.getDatabaseProductVersion().equals(
                    olapDatabaseMetaData.getDatabaseProductVersion()));
        }
    }

    public void testSchemas() throws OlapException {
        // check schema auto detection
        final Schema schema1 = olapConnection.getOlapSchema();
        assertEquals(
            "Failed to auto detect the schema.",
            schema1.getName(),
            "FoodMart");
        switch (tester.getFlavor()) {
        case MONDRIAN:
            // Setting a correct schema should work.
            olapConnection.setSchema("FoodMart");
            // setting a null schema should be ignored
            olapConnection.setSchema(null);
            // setting a non existent schema should be ignored
            olapConnection.setSchema("Chunky Bacon");
            break;
        case XMLA:
        case REMOTE_XMLA:
            // Setting a correct schema should work.
            olapConnection.setSchema(catalogName);
            // setting a null schema should fail
            try {
                olapConnection.setSchema(null);
                fail();
            } catch (OlapException e) {
                // no op.
            }
            // setting a non existent schema should fail
            try {
                olapConnection.setSchema("Chunky Bacon");
                fail();
            } catch (OlapException e) {
                // no op.
            }
            break;
        default:
            fail("Unknown tester flavor.");
        }
    }

    public void testCatalogs() throws SQLException {
        final Catalog catalog = olapConnection.getOlapCatalog();
        assertEquals(
            "Failed to auto detect the catalog.",
            catalog.getName(),
            "FoodMart");

        switch (tester.getFlavor()) {
        case MONDRIAN:
            // Setting a correct catalog should work.
            olapConnection.setCatalog("FoodMart");
            // setting a null catalog should be ignored
            olapConnection.setCatalog(null);
            // setting a non existent catalog should be ignored
            olapConnection.setCatalog("Chunky Bacon");
            break;
        case XMLA:
        case REMOTE_XMLA:
            // Setting a correct catalog should work.
            olapConnection.setCatalog(catalogName);
            // setting a null catalog should fail
            try {
                olapConnection.setCatalog(null);
                fail();
            } catch (OlapException e) {
                // no op.
            }
            // setting a non existent catalog should fail
            try {
                olapConnection.setCatalog("Chunky Bacon");
                fail();
            } catch (OlapException e) {
                // no op.
            }
            break;
        default:
            fail("Unknown tester flavor.");
        }
    }

    public void testDatabases() throws SQLException {
        final Database database = olapConnection.getOlapDatabase();
        assertTrue(
            "Failed to auto detect the database.",
            database.getName()
                .equals("Provider=Mondrian;DataSource=MondrianFoodMart;")
            || database.getName()
                .equals("FoodMart"));

        switch (tester.getFlavor()) {
        case MONDRIAN:
            // Setting a correct database should work.
            olapConnection.setDatabase("FoodMart");
            // setting a null database should be ignored
            olapConnection.setDatabase(null);
            // setting a non existent database should be ignored
            olapConnection.setDatabase("Chunky Bacon");
            break;
        case XMLA:
            // Setting a correct database should work.
            olapConnection.setDatabase(
                "FoodMart");
            // setting a null database should fail
            try {
                olapConnection.setDatabase(null);
                fail();
            } catch (OlapException e) {
                // no op.
            }
            // setting a non existent database should fail
            try {
                olapConnection.setDatabase("Chunky Bacon");
                fail();
            } catch (OlapException e) {
                // no op.
            }
            break;
        case REMOTE_XMLA:
            // Setting a correct database should work.
            olapConnection.setDatabase(
                "Provider=Mondrian;DataSource=MondrianFoodMart;");
            // setting a null database should fail
            try {
                olapConnection.setDatabase(null);
                fail();
            } catch (OlapException e) {
                // no op.
            }
            // setting a non existent database should fail
            try {
                olapConnection.setDatabase("Chunky Bacon");
                fail();
            } catch (OlapException e) {
                // no op.
            }
            break;
        default:
            fail("Unknown tester flavor.");
        }
    }

    public void testDatabaseMetaDataGetActions() throws SQLException {
        String s = checkResultSet(
            olapDatabaseMetaData.getActions(
                catalogName, null, null, null),
            ACTIONS_COLUMN_NAMES);
        assertEquals("", s); // mondrian has no actions
    }

    public void testDatabaseMetaDataGetDatasources() throws SQLException {
        String s = checkResultSet(
            olapDatabaseMetaData.getDatabases(),
            DATASOURCES_COLUMN_NAMES);
        switch (tester.getFlavor()) {
        case MONDRIAN:
            TestContext.assertEqualsVerbose(
                "DATA_SOURCE_NAME=FoodMart,"
                + " DATA_SOURCE_DESCRIPTION=null,"
                + " URL=null,"
                + " DATA_SOURCE_INFO=FoodMart,"
                + " PROVIDER_NAME=Mondrian,"
                + " PROVIDER_TYPE=MDP,"
                + " AUTHENTICATION_MODE=Unauthenticated\n",
                s);
            break;
        case REMOTE_XMLA:
            // This can be anything, depending on the remote server.
            break;
        case XMLA:
            TestContext.assertEqualsVerbose(
                "DATA_SOURCE_NAME=FoodMart,"
                + " DATA_SOURCE_DESCRIPTION=Mondrian FoodMart data source,"
                + " URL=http://localhost:8080/mondrian/xmla,"
                + " DATA_SOURCE_INFO=FoodMart,"
                + " PROVIDER_NAME=Mondrian,"
                + " PROVIDER_TYPE=MDP,"
                + " AUTHENTICATION_MODE=Unauthenticated\n",
                s);
            break;
        }
    }

    public void testDatabaseMetaDataGetCatalogs() throws SQLException {
        String s = checkResultSet(
            olapDatabaseMetaData.getCatalogs(),
            CATALOGS_COLUMN_NAMES);
        final String expected;
        switch (tester.getFlavor()) {
        case XMLA:
            // XMLA test uses dummy duplicate catalog to make sure that we
            // get all catalogs
            expected =
                "TABLE_CAT=" + catalogName + "\n"
                + "TABLE_CAT=" + catalogName + "2\n";
            break;
        case REMOTE_XMLA:
        default:
            expected = "TABLE_CAT=" + catalogName + "\n";
            break;
        }
        TestContext.assertEqualsVerbose(expected, s);
    }

    public void testDatabaseMetaDataGetSchemas() throws SQLException {
        String s = checkResultSet(
            olapDatabaseMetaData.getSchemas(),
            SCHEMAS_COLUMN_NAMES);
        final String expected;
        switch (tester.getFlavor()) {
        case XMLA:
            // XMLA test uses dummy duplicate schema to make sure that we
            // get all schemas
            expected =
                "TABLE_SCHEM=FoodMart, TABLE_CAT=" + catalogName + "\n"
                + "TABLE_SCHEM=FoodMart, TABLE_CAT=" + catalogName + "2\n";
            break;
        case REMOTE_XMLA:
        default:
            expected = "TABLE_SCHEM=FoodMart, TABLE_CAT=" + catalogName + "\n";
            break;
        }
        TestContext.assertEqualsVerbose(expected, s);
    }

    public void testDatabaseMetaDataGetLiterals() throws SQLException {
        String s = checkResultSet(
            olapDatabaseMetaData.getLiterals(),
            LITERALS_COLUMN_NAMES);
        assertContains("LITERAL_NAME=DBLITERAL_QUOTE, LITERAL_VALUE=[, ", s);
    }

    public void testDatabaseMetaDataGetDatabaseProperties()
        throws SQLException
    {
        String s = checkResultSet(
            olapDatabaseMetaData.getDatabaseProperties(
                dataSourceName, propertyNamePattern),
            DATABASE_PROPERTIES_COLUMN_NAMES);
        assertContains("PROPERTY_NAME=ProviderName, ", s);
    }

    public void testDatabaseMetaDataGetProperties() throws SQLException {
        String s = checkResultSet(
            olapDatabaseMetaData.getProperties(
                catalogName, null, null, null, null, null, null, null),
            PROPERTIES_COLUMN_NAMES);
        assertContains(
            "CATALOG_NAME=" + catalogName
            + ", SCHEMA_NAME=FoodMart, CUBE_NAME=Warehouse and Sales, DIMENSION_UNIQUE_NAME=[Store], HIERARCHY_UNIQUE_NAME=[Store].[Store], LEVEL_UNIQUE_NAME=[Store].[Store].[Store Name], MEMBER_UNIQUE_NAME=null, PROPERTY_NAME=Frozen Sqft, PROPERTY_CAPTION=Frozen Sqft, PROPERTY_TYPE=1, DATA_TYPE=5, PROPERTY_CONTENT_TYPE=0, DESCRIPTION=Warehouse and Sales Cube - Store Hierarchy - Store Name Level - Frozen Sqft Property",
            s);
        assertEquals(s, 66, linecount(s));

        s = checkResultSet(
            olapDatabaseMetaData.getProperties(
                catalogName, "FoodMart", "Sales",
                null, null, "[Store].[Store].[Store Name]",
                null, null),
            PROPERTIES_COLUMN_NAMES);
        assertContains(
            "CATALOG_NAME=" + catalogName
            + ", SCHEMA_NAME=FoodMart, CUBE_NAME=Sales, DIMENSION_UNIQUE_NAME=[Store], HIERARCHY_UNIQUE_NAME=[Store].[Store], LEVEL_UNIQUE_NAME=[Store].[Store].[Store Name], MEMBER_UNIQUE_NAME=null, PROPERTY_NAME=Has coffee bar, PROPERTY_CAPTION=Has coffee bar, PROPERTY_TYPE=1, DATA_TYPE=130, PROPERTY_CONTENT_TYPE=0, DESCRIPTION=Sales Cube - Store Hierarchy - Store Name Level - Has coffee bar Property",
            s);
        assertNotContains(
            "CATALOG_NAME=" + catalogName
            + ", SCHEMA_NAME=FoodMart, CUBE_NAME=Warehouse and Sales, ",
            s);
        assertEquals(8, linecount(s));
    }

    public void testDatabaseMetaDataGetMdxKeywords() throws SQLException {
        String keywords = olapDatabaseMetaData.getMdxKeywords();
        assertNotNull(keywords);
        assertContains(",From,", keywords);
    }

    public void testDatabaseMetaDataGetCubes() throws SQLException {
        String s = checkResultSet(
            olapDatabaseMetaData.getCubes(
                catalogName,
                null,
                null),
            CUBE_COLUMN_NAMES);
        assertContains(
            "CATALOG_NAME=" + catalogName
            + ", SCHEMA_NAME=FoodMart, CUBE_NAME=Sales, ",
            s);
        final int lineCount = linecount(s);

        // Null catalog specified in metadata request, but connection has a
        // catalog. Should return all cubes, ignoring the connection's catalog.
        olapDatabaseMetaData.getConnection().setCatalog(catalogName);
        s = checkResultSet(
            olapDatabaseMetaData.getCubes(
                null,
                null,
                null),
            CUBE_COLUMN_NAMES);
        assertContains(
            "CATALOG_NAME=" + catalogName
            + ", SCHEMA_NAME=FoodMart, CUBE_NAME=Sales, ",
            s);
        final int lineCount3 = linecount(s);
        if (tester.getFlavor() == TestContext.Tester.Flavor.XMLA) {
            assertEquals(lineCount * 2, lineCount3);
        }
        s = checkResultSet(
            olapDatabaseMetaData.getCubes(
                "FoodMart",
                "FoodMart",
                "Sales"),
            CUBE_COLUMN_NAMES);
        switch (testContext.getTester().getFlavor()) {
        case MONDRIAN:
            assertTrue(s.contains(", IS_DRILLTHROUGH_ENABLED=true"));
            break;
        case XMLA:
        case REMOTE_XMLA:
            assertTrue(s.contains(", IS_DRILLTHROUGH_ENABLED=false"));
            assertFalse(s.contains(", IS_DRILLTHROUGH_ENABLED=true"));
            break;
        default:
            throw new RuntimeException("Unknown tester type.");
        }

        // If we ask for 'Warehouse and Sales' cube we should get it, but
        // nothing else.
        s = checkResultSet(
            olapDatabaseMetaData.getCubes(
                catalogName,
                null,
                "Warehouse and Sales"),
            CUBE_COLUMN_NAMES);
        assertContains(", CUBE_NAME=Warehouse and Sales,", s);
        assertNotContains(", CUBE_NAME=Warehouse,", s);

        // If we ask for a pattern, should get multiple hits.
        s = checkResultSet(
            olapDatabaseMetaData.getCubes(
                catalogName,
                null,
                "Warehouse%"),
            CUBE_COLUMN_NAMES);
        assertTrue(s.contains(", CUBE_NAME=Warehouse and Sales"));
        assertTrue(s.contains(", CUBE_NAME=Warehouse"));
        assertFalse(s.contains(", CUBE_NAME=Sales"));
    }

    public void testDatabaseMetaDataGetDimensions() throws SQLException {
        String s = checkResultSet(
            olapDatabaseMetaData.getDimensions(
                catalogName, null, null, null),
            DIMENSIONS_COLUMN_NAMES);
        assertContains(
            "CATALOG_NAME=" + catalogName
            + ", SCHEMA_NAME=FoodMart, CUBE_NAME=Sales, DIMENSION_NAME=Education Level, DIMENSION_UNIQUE_NAME=[Education Level], DIMENSION_GUID=null, DIMENSION_CAPTION=Education Level, DIMENSION_ORDINAL=9, DIMENSION_TYPE=3, DIMENSION_CARDINALITY=6, DEFAULT_HIERARCHY=[Education Level], DESCRIPTION=Sales Cube - Education Level Dimension, IS_VIRTUAL=false, IS_READWRITE=false, DIMENSION_UNIQUE_SETTINGS=0, DIMENSION_MASTER_UNIQUE_NAME=null, DIMENSION_IS_VISIBLE=true",
            s);
        assertEquals(62, linecount(s));
    }

    public void testDatabaseMetaDataGetFunctions() throws SQLException {
        String s = checkResultSet(
            olapDatabaseMetaData.getOlapFunctions(null),
            FUNCTIONS_COLUMN_NAMES);
        assertContains(
            "FUNCTION_NAME=Name, DESCRIPTION=Returns the name of a member., PARAMETER_LIST=Member, RETURN_TYPE=8, ORIGIN=1, INTERFACE_NAME=, LIBRARY_NAME=null, CAPTION=Name",
            s);
        // Mondrian has 361 functions (as of 2008/1/23)
        final int functionCount = linecount(s);
        assertTrue(functionCount + " functions", functionCount > 360);

        // Mondrian has 13 variants of the Ascendants and Descendants functions
        s = checkResultSet(
            olapDatabaseMetaData.getOlapFunctions("%scendants"),
            FUNCTIONS_COLUMN_NAMES);
        assertEquals(s, 13, linecount(s));
    }

    public void testDatabaseMetaDataGetHierarchies() throws SQLException {
        String s = checkResultSet(
            olapDatabaseMetaData.getHierarchies(
                catalogName, null, null, null, null),
            HIERARCHIES_COLUMN_NAMES);
        assertContains(
            "CATALOG_NAME=" + catalogName
            + ", SCHEMA_NAME=FoodMart, CUBE_NAME=HR, DIMENSION_UNIQUE_NAME=[Employees], HIERARCHY_NAME=Employees, HIERARCHY_UNIQUE_NAME=[Employees].[Employees], HIERARCHY_GUID=null, HIERARCHY_CAPTION=Employees, DIMENSION_TYPE=3, HIERARCHY_CARDINALITY=1156, DEFAULT_MEMBER=[Employees].[Employees].[All Employees], ALL_MEMBER=[Employees].[Employees].[All Employees], DESCRIPTION=HR Cube - Employees Hierarchy, STRUCTURE=0, IS_VIRTUAL=false, IS_READWRITE=false, DIMENSION_UNIQUE_SETTINGS=0, DIMENSION_IS_VISIBLE=true, HIERARCHY_IS_VISIBLE=true, HIERARCHY_ORDINAL=7, DIMENSION_IS_SHARED=true, PARENT_CHILD=true",
            s);

        s = checkResultSet(
            olapDatabaseMetaData.getHierarchies(
                catalogName, null, "Sales", null, "Store"),
            HIERARCHIES_COLUMN_NAMES);
        TestContext.assertEqualsVerbose(
            "CATALOG_NAME=" + catalogName
            + ", SCHEMA_NAME=FoodMart, CUBE_NAME=Sales, DIMENSION_UNIQUE_NAME=[Store], HIERARCHY_NAME=Store, HIERARCHY_UNIQUE_NAME=[Store].[Store], HIERARCHY_GUID=null, HIERARCHY_CAPTION=Store, DIMENSION_TYPE=3, HIERARCHY_CARDINALITY=63, DEFAULT_MEMBER=[Store].[Store].[All Stores], ALL_MEMBER=[Store].[Store].[All Stores], DESCRIPTION=Sales Cube - Store Hierarchy, STRUCTURE=0, IS_VIRTUAL=false, IS_READWRITE=false, DIMENSION_UNIQUE_SETTINGS=0, DIMENSION_IS_VISIBLE=true, HIERARCHY_IS_VISIBLE=true, HIERARCHY_ORDINAL=1, DIMENSION_IS_SHARED=true, PARENT_CHILD=false\n",
            s);

        // With dimension unique name (bug 2527862).
        s = checkResultSet(
            olapDatabaseMetaData.getHierarchies(
                catalogName, null, "Sales", "[Store]", null),
            HIERARCHIES_COLUMN_NAMES);
        TestContext.assertEqualsVerbose(
            "CATALOG_NAME=" + catalogName
            + ", SCHEMA_NAME=FoodMart, CUBE_NAME=Sales, DIMENSION_UNIQUE_NAME=[Store], HIERARCHY_NAME=Store, HIERARCHY_UNIQUE_NAME=[Store].[Store], HIERARCHY_GUID=null, HIERARCHY_CAPTION=Store, DIMENSION_TYPE=3, HIERARCHY_CARDINALITY=63, DEFAULT_MEMBER=[Store].[Store].[All Stores], ALL_MEMBER=[Store].[Store].[All Stores], DESCRIPTION=Sales Cube - Store Hierarchy, STRUCTURE=0, IS_VIRTUAL=false, IS_READWRITE=false, DIMENSION_UNIQUE_SETTINGS=0, DIMENSION_IS_VISIBLE=true, HIERARCHY_IS_VISIBLE=true, HIERARCHY_ORDINAL=1, DIMENSION_IS_SHARED=true, PARENT_CHILD=false\n",
            s);
    }

    public void testDatabaseMetaDataGetLevels() throws SQLException {
        String s = checkResultSet(
            olapDatabaseMetaData.getLevels(
                catalogName, null, null, null, null, null),
            LEVELS_COLUMN_NAMES);
        assertContains(
            "CATALOG_NAME=FoodMart, SCHEMA_NAME=FoodMart, CUBE_NAME=Sales, DIMENSION_UNIQUE_NAME=[Measures], HIERARCHY_UNIQUE_NAME=[Measures], LEVEL_NAME=MeasuresLevel, LEVEL_UNIQUE_NAME=[Measures].[MeasuresLevel], LEVEL_GUID=null, LEVEL_CAPTION=MeasuresLevel, LEVEL_NUMBER=0, LEVEL_CARDINALITY=9, LEVEL_TYPE=0, CUSTOM_ROLLUP_SETTINGS=0, LEVEL_UNIQUE_SETTINGS=1, LEVEL_IS_VISIBLE=true, DESCRIPTION=Sales Cube - Measures Hierarchy - MeasuresLevel Level",
            s);

        s = checkResultSet(
            olapDatabaseMetaData.getLevels(
                catalogName, null, "Sales", null, "[Store].[Store]", null),
            LEVELS_COLUMN_NAMES);
        assertEquals(s, 5, linecount(s));
    }

    public void testDatabaseMetaDataGetLiterals2() throws SQLException {
        String s = checkResultSet(
            olapDatabaseMetaData.getLiterals(),
            LITERALS_COLUMN_NAMES);
        assertContains(
            "LITERAL_NAME=DBLITERAL_QUOTE, LITERAL_VALUE=[, LITERAL_INVALID_CHARS=null, LITERAL_INVALID_STARTING_CHARS=null, LITERAL_MAX_LENGTH=-1",
            s);
        assertEquals(17, linecount(s));
    }

    public void testDatabaseMetaDataGetMeasures() throws SQLException {
        String s = checkResultSet(
            olapDatabaseMetaData.getMeasures(
                catalogName, null, null, null, null),
            MEASURES_COLUMN_NAMES);
        assertContains(
            "CATALOG_NAME=" + catalogName
            + ", SCHEMA_NAME=FoodMart, CUBE_NAME=Sales, MEASURE_NAME=Profit, MEASURE_UNIQUE_NAME=[Measures].[Profit], MEASURE_CAPTION=Profit, MEASURE_GUID=null, MEASURE_AGGREGATOR=127, DATA_TYPE=130, MEASURE_IS_VISIBLE=true, LEVELS_LIST=null, DESCRIPTION=Sales Cube - Profit Member",
            s);

        // wildcard match
        s = checkResultSet(
            olapDatabaseMetaData.getMeasures(
                catalogName, null, "Sales", "%Sales", null),
            MEASURES_COLUMN_NAMES);
        assertEquals(s, 3, linecount(s));

        // wildcard match
        s = checkResultSet(
            olapDatabaseMetaData.getMeasures(
                catalogName, null, "Sales", null, "[Measures].[Unit Sales]"),
            MEASURES_COLUMN_NAMES);
        assertEquals(s, 1, linecount(s));
    }

    public void testDatabaseMetaDataGetMembers() throws SQLException {
        String s = checkResultSet(
            olapDatabaseMetaData.getMembers(
                catalogName, "FoodMart", "Sales", null, "[Gender].[Gender]",
                null, null, null),
            MEMBERS_COLUMN_NAMES);
        TestContext.assertEqualsVerbose(
            "CATALOG_NAME=" + catalogName
            + ", SCHEMA_NAME=FoodMart, CUBE_NAME=Sales, DIMENSION_UNIQUE_NAME=[Gender], HIERARCHY_UNIQUE_NAME=[Gender].[Gender], LEVEL_UNIQUE_NAME=[Gender].[Gender].[(All)], LEVEL_NUMBER=0, MEMBER_ORDINAL=0, MEMBER_NAME=All Gender, MEMBER_UNIQUE_NAME=[Gender].[Gender].[All Gender], MEMBER_TYPE=2, MEMBER_GUID=null, MEMBER_CAPTION=All Gender, CHILDREN_CARDINALITY=2, PARENT_LEVEL=0, PARENT_UNIQUE_NAME=null, PARENT_COUNT=0, TREE_OP=null, DEPTH=0\n"
            + "CATALOG_NAME=" + catalogName
            + ", SCHEMA_NAME=FoodMart, CUBE_NAME=Sales, DIMENSION_UNIQUE_NAME=[Gender], HIERARCHY_UNIQUE_NAME=[Gender].[Gender], LEVEL_UNIQUE_NAME=[Gender].[Gender].[Gender], LEVEL_NUMBER=1, MEMBER_ORDINAL=1, MEMBER_NAME=F, MEMBER_UNIQUE_NAME=[Gender].[Gender].[F], MEMBER_TYPE=1, MEMBER_GUID=null, MEMBER_CAPTION=F, CHILDREN_CARDINALITY=0, PARENT_LEVEL=0, PARENT_UNIQUE_NAME=[Gender].[Gender].[All Gender], PARENT_COUNT=1, TREE_OP=null, DEPTH=1\n"
            + "CATALOG_NAME=" + catalogName
            + ", SCHEMA_NAME=FoodMart, CUBE_NAME=Sales, DIMENSION_UNIQUE_NAME=[Gender], HIERARCHY_UNIQUE_NAME=[Gender].[Gender], LEVEL_UNIQUE_NAME=[Gender].[Gender].[Gender], LEVEL_NUMBER=1, MEMBER_ORDINAL=2, MEMBER_NAME=M, MEMBER_UNIQUE_NAME=[Gender].[Gender].[M], MEMBER_TYPE=1, MEMBER_GUID=null, MEMBER_CAPTION=M, CHILDREN_CARDINALITY=0, PARENT_LEVEL=0, PARENT_UNIQUE_NAME=[Gender].[Gender].[All Gender], PARENT_COUNT=1, TREE_OP=null, DEPTH=1\n",
            s);

        // by member unique name
        s = checkResultSet(
            olapDatabaseMetaData.getMembers(
                catalogName, "FoodMart", "Sales", null, null, null,
                "[Time].[Time].[1997].[Q2].[4]", null),
            MEMBERS_COLUMN_NAMES);
        TestContext.assertEqualsVerbose(
            "CATALOG_NAME=" + catalogName
            + ", SCHEMA_NAME=FoodMart, CUBE_NAME=Sales, DIMENSION_UNIQUE_NAME=[Time], HIERARCHY_UNIQUE_NAME=[Time].[Time], LEVEL_UNIQUE_NAME=[Time].[Time].[Month], LEVEL_NUMBER=2, MEMBER_ORDINAL=6, MEMBER_NAME=4, MEMBER_UNIQUE_NAME=[Time].[Time].[1997].[Q2].[4], MEMBER_TYPE=1, MEMBER_GUID=null, MEMBER_CAPTION=4, CHILDREN_CARDINALITY=0, PARENT_LEVEL=1, PARENT_UNIQUE_NAME=[Time].[Time].[1997].[Q2], PARENT_COUNT=1, TREE_OP=null, DEPTH=2\n",
            s);

        // with treeop
        s = checkResultSet(
            olapDatabaseMetaData.getMembers(
                catalogName, "FoodMart", "Sales", null, null, null,
                "[Customers].[Customers].[USA].[CA]",
                Olap4jUtil.enumSetOf(
                    Member.TreeOp.ANCESTORS, Member.TreeOp.SIBLINGS)),
            MEMBERS_COLUMN_NAMES);
        switch (tester.getFlavor()) {
        case MONDRIAN:
            // TODO: fix mondrian driver so that members are returned sorted
            // by level depth
            TestContext.assertEqualsVerbose(
                "CATALOG_NAME=" + catalogName
                + ", SCHEMA_NAME=FoodMart, CUBE_NAME=Sales, DIMENSION_UNIQUE_NAME=[Customers], HIERARCHY_UNIQUE_NAME=[Customers].[Customers], LEVEL_UNIQUE_NAME=[Customers].[Customers].[State Province], LEVEL_NUMBER=2, MEMBER_ORDINAL=7235, MEMBER_NAME=OR, MEMBER_UNIQUE_NAME=[Customers].[Customers].[USA].[OR], MEMBER_TYPE=1, MEMBER_GUID=null, MEMBER_CAPTION=OR, CHILDREN_CARDINALITY=11, PARENT_LEVEL=1, PARENT_UNIQUE_NAME=[Customers].[Customers].[USA], PARENT_COUNT=1, TREE_OP=null, DEPTH=2\n"
                + "CATALOG_NAME=" + catalogName
                + ", SCHEMA_NAME=FoodMart, CUBE_NAME=Sales, DIMENSION_UNIQUE_NAME=[Customers], HIERARCHY_UNIQUE_NAME=[Customers].[Customers], LEVEL_UNIQUE_NAME=[Customers].[Customers].[State Province], LEVEL_NUMBER=2, MEMBER_ORDINAL=8298, MEMBER_NAME=WA, MEMBER_UNIQUE_NAME=[Customers].[Customers].[USA].[WA], MEMBER_TYPE=1, MEMBER_GUID=null, MEMBER_CAPTION=WA, CHILDREN_CARDINALITY=22, PARENT_LEVEL=1, PARENT_UNIQUE_NAME=[Customers].[Customers].[USA], PARENT_COUNT=1, TREE_OP=null, DEPTH=2\n"
                + "CATALOG_NAME=" + catalogName
                + ", SCHEMA_NAME=FoodMart, CUBE_NAME=Sales, DIMENSION_UNIQUE_NAME=[Customers], HIERARCHY_UNIQUE_NAME=[Customers].[Customers], LEVEL_UNIQUE_NAME=[Customers].[Customers].[Country], LEVEL_NUMBER=1, MEMBER_ORDINAL=2966, MEMBER_NAME=USA, MEMBER_UNIQUE_NAME=[Customers].[Customers].[USA], MEMBER_TYPE=1, MEMBER_GUID=null, MEMBER_CAPTION=USA, CHILDREN_CARDINALITY=3, PARENT_LEVEL=0, PARENT_UNIQUE_NAME=[Customers].[Customers].[All Customers], PARENT_COUNT=1, TREE_OP=null, DEPTH=1\n"
                + "CATALOG_NAME=" + catalogName
                + ", SCHEMA_NAME=FoodMart, CUBE_NAME=Sales, DIMENSION_UNIQUE_NAME=[Customers], HIERARCHY_UNIQUE_NAME=[Customers].[Customers], LEVEL_UNIQUE_NAME=[Customers].[Customers].[(All)], LEVEL_NUMBER=0, MEMBER_ORDINAL=0, MEMBER_NAME=All Customers, MEMBER_UNIQUE_NAME=[Customers].[Customers].[All Customers], MEMBER_TYPE=2, MEMBER_GUID=null, MEMBER_CAPTION=All Customers, CHILDREN_CARDINALITY=3, PARENT_LEVEL=0, PARENT_UNIQUE_NAME=null, PARENT_COUNT=0, TREE_OP=null, DEPTH=0\n",
                s);
            break;
        default:
            TestContext.assertEqualsVerbose(
                "CATALOG_NAME=" + catalogName
                + ", SCHEMA_NAME=FoodMart, CUBE_NAME=Sales, DIMENSION_UNIQUE_NAME=[Customers], HIERARCHY_UNIQUE_NAME=[Customers].[Customers], LEVEL_UNIQUE_NAME=[Customers].[Customers].[(All)], LEVEL_NUMBER=0, MEMBER_ORDINAL=0, MEMBER_NAME=All Customers, MEMBER_UNIQUE_NAME=[Customers].[Customers].[All Customers], MEMBER_TYPE=2, MEMBER_GUID=null, MEMBER_CAPTION=All Customers, CHILDREN_CARDINALITY=3, PARENT_LEVEL=0, PARENT_UNIQUE_NAME=null, PARENT_COUNT=0, TREE_OP=null, DEPTH=0\n"
                + "CATALOG_NAME=" + catalogName
                + ", SCHEMA_NAME=FoodMart, CUBE_NAME=Sales, DIMENSION_UNIQUE_NAME=[Customers], HIERARCHY_UNIQUE_NAME=[Customers].[Customers], LEVEL_UNIQUE_NAME=[Customers].[Customers].[Country], LEVEL_NUMBER=1, MEMBER_ORDINAL=2966, MEMBER_NAME=USA, MEMBER_UNIQUE_NAME=[Customers].[Customers].[USA], MEMBER_TYPE=1, MEMBER_GUID=null, MEMBER_CAPTION=USA, CHILDREN_CARDINALITY=3, PARENT_LEVEL=0, PARENT_UNIQUE_NAME=[Customers].[Customers].[All Customers], PARENT_COUNT=1, TREE_OP=null, DEPTH=1\n"
                + "CATALOG_NAME=" + catalogName
                + ", SCHEMA_NAME=FoodMart, CUBE_NAME=Sales, DIMENSION_UNIQUE_NAME=[Customers], HIERARCHY_UNIQUE_NAME=[Customers].[Customers], LEVEL_UNIQUE_NAME=[Customers].[Customers].[State Province], LEVEL_NUMBER=2, MEMBER_ORDINAL=7235, MEMBER_NAME=OR, MEMBER_UNIQUE_NAME=[Customers].[Customers].[USA].[OR], MEMBER_TYPE=1, MEMBER_GUID=null, MEMBER_CAPTION=OR, CHILDREN_CARDINALITY=11, PARENT_LEVEL=1, PARENT_UNIQUE_NAME=[Customers].[Customers].[USA], PARENT_COUNT=1, TREE_OP=null, DEPTH=2\n"
                + "CATALOG_NAME=" + catalogName
                + ", SCHEMA_NAME=FoodMart, CUBE_NAME=Sales, DIMENSION_UNIQUE_NAME=[Customers], HIERARCHY_UNIQUE_NAME=[Customers].[Customers], LEVEL_UNIQUE_NAME=[Customers].[Customers].[State Province], LEVEL_NUMBER=2, MEMBER_ORDINAL=8298, MEMBER_NAME=WA, MEMBER_UNIQUE_NAME=[Customers].[Customers].[USA].[WA], MEMBER_TYPE=1, MEMBER_GUID=null, MEMBER_CAPTION=WA, CHILDREN_CARDINALITY=22, PARENT_LEVEL=1, PARENT_UNIQUE_NAME=[Customers].[Customers].[USA], PARENT_COUNT=1, TREE_OP=null, DEPTH=2\n",
                s);
            break;
        }
    }

    public void testDatabaseMetaDataGetSets() throws SQLException {
        String s = checkResultSet(
            olapDatabaseMetaData.getSets(
                catalogName, null, null, null),
            SETS_COLUMN_NAMES);
        TestContext.assertEqualsVerbose(
            "CATALOG_NAME=" + catalogName
            + ", SCHEMA_NAME=FoodMart, CUBE_NAME=Warehouse, SET_NAME=[Top Sellers], SCOPE=1\n"
            + "CATALOG_NAME=" + catalogName
            + ", SCHEMA_NAME=FoodMart, CUBE_NAME=Warehouse and Sales, SET_NAME=[Top Sellers], SCOPE=1\n",
            s);

        s = checkResultSet(
            olapDatabaseMetaData.getSets(
                catalogName, null, null, "non existent set"),
            SETS_COLUMN_NAMES);
        TestContext.assertEqualsVerbose("", s);
    }

    // todo: More tests required for other methods on DatabaseMetaData

    private String checkResultSet(
        ResultSet resultSet,
        List<String> columnNames) throws SQLException
    {
        ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
        final int columnCount = resultSetMetaData.getColumnCount();
        List<String> rsColumnNames = new ArrayList<String>();
        if (columnNames != null) {
            for (int k = 0; k < columnCount; k++) {
                rsColumnNames.add(
                    resultSetMetaData.getColumnName(k + 1));
            }

            final HashSet<String> set = new HashSet<String>(columnNames);
            set.removeAll(rsColumnNames);
            assertTrue("Expected columns not found: " + set, set.isEmpty());
        }
        assertNotNull(resultSet);
        int k = 0;
        StringBuilder buf = new StringBuilder();
        while (resultSet.next()) {
            ++k;
            for (int i = 0; i < columnCount; i++) {
                if (i > 0) {
                    buf.append(", ");
                }
                String s = resultSet.getString(i + 1);
                buf.append(resultSetMetaData.getColumnName(i + 1))
                    .append('=')
                    .append(s);
            }
            buf.append(NL);
        }
        assertTrue(k >= 0);
        assertTrue(resultSet.isAfterLast());
        return buf.toString();
    }
}

// End MetadataTest.java


text:
NSString * const OSKActivityOption_ExcludedTypes = @"OSKActivityOption_ExcludedTypes";
NSString * const OSKActivityOption_BespokeActivities = @"OSKActivityOption_BespokeActivities";
NSString * const OSKActivityOption_RequireOperations = @"OSKActivityOption_RequireOperations";

// ACTIVITY TYPES
NSString * const OSKActivityType_iOS_Twitter = @"OSKActivityType_iOS_Twitter";
NSString * const OSKActivityType_iOS_Facebook = @"OSKActivityType_iOS_Facebook";
NSString * const OSKActivityType_iOS_Safari = @"OSKActivityType_iOS_Safari";
NSString * const OSKActivityType_iOS_SMS = @"OSKActivityType_iOS_SMS";
NSString * const OSKActivityType_iOS_Email = @"OSKActivityType_iOS_Email";
NSString * const OSKActivityType_iOS_CopyToPasteboard = @"OSKActivityType_iOS_CopyToPasteboard";
NSString * const OSKActivityType_iOS_AirDrop = @"OSKActivityType_iOS_AirDrop";
NSString * const OSKActivityType_iOS_ReadingList = @"OSKActivityType_iOS_ReadingList";
NSString * const OSKActivityType_iOS_SaveToCameraRoll = @"OSKActivityType_iOS_SaveToCameraRoll";
NSString * const OSKActivityType_API_AppDotNet = @"OSKActivityType_API_AppDotNet";
NSString * const OSKActivityType_API_500Pixels = @"OSKActivityType_API_500Pixels";
NSString * const OSKActivityType_API_Instapaper = @"OSKActivityType_API_Instapaper";
NSString * const OSKActivityType_API_Readability = @"OSKActivityType_API_Readability";
NSString * const OSKActivityType_API_Pocket = @"OSKActivityType_API_Pocket";
NSString * const OSKActivityType_API_Pinboard = @"OSKActivityType_API_Pinboard";
NSString * const OSKActivityType_API_GooglePlus = @"OSKActivityType_API_GooglePlus";
NSString * const OSKActivityType_URLScheme_Instagram = @"OSKActivityType_URLScheme_Instagram";
NSString * const OSKActivityType_URLScheme_Riposte = @"OSKActivityType_URLScheme_Riposte";
NSString * const OSKActivityType_URLScheme_Tweetbot = @"OSKActivityType_URLScheme_Tweetbot";
NSString * const OSKActivityType_URLScheme_1Password_Search = @"OSKActivityType_URLScheme_1Password_Search";
NSString * const OSKActivityType_URLScheme_1Password_Browser = @"OSKActivityType_URLScheme_1Password_Browser";
NSString * const OSKActivityType_URLScheme_Chrome = @"OSKActivityType_URLScheme_Chrome";
NSString * const OSKActivityType_URLScheme_Omnifocus = @"OSKActivityType_URLScheme_Omnifocus";
NSString * const OSKActivityType_URLScheme_Things = @"OSKActivityType_URLScheme_Things";
NSString * const OSKActivityType_URLScheme_Drafts = @"OSKActivityType_URLScheme_Drafts";
NSString * const OSKActivityType_SDK_Pocket = @"OSKActivityType_SDK_Pocket";

@interface OSKActivity ()

@property (strong, nonatomic, readonly) OSKActivitiesManager *manager;
@property (strong, nonatomic, readwrite) OSKShareableContentItem *contentItem;

@end

@implementation OSKActivity

@synthesize manager = _manager;

#pragma mark - Initialization

- (instancetype)initWithContentItem:(OSKShareableContentItem *)item {
    self = [super init];
    if (self) {
        _contentItem = item;
    }
    return self;
}

#pragma mark - Do Not Override

+ (OSKApplicationCredential *)applicationCredential {
    return [[OSKActivitiesManager sharedInstance] applicationCredentialForActivityType:[self activityType]];
}

- (OSKActivitiesManager *)manager {
    if (_manager == nil) {
        _manager = [OSKActivitiesManager sharedInstance];
    }
    return _manager;
}

- (BOOL)requiresPurchase {
    return [self.manager activityTypeRequiresPurchase:[self.class activityType]];
}

- (BOOL)isAlreadyPurchased {
    return [self.manager activityTypeIsPurchased:[self.class activityType]];
}

#pragma mark - Methods for Subclasses

+ (NSString *)supportedContentItemType {
    NSAssert(NO, @"OSKActivity subclasses must override `supportedContentItemType` without calling super.");
    return nil;
}

+ (BOOL)isAvailable {
    NSAssert(NO, @"OSKActivity subclasses must override `isAvailable` without calling super.");
    return NO;
}

+ (NSString *)activityType {
    NSAssert(NO, @"OSKActivity subclasses must override `activityType` without calling super.");
    return nil;
}

+ (NSString *)activityName {
    NSAssert(NO, @"OSKActivity subclasses must override `activityName` without calling super.");
    return nil;
}

+ (UIImage *)iconForIdiom:(UIUserInterfaceIdiom)idiom {
    NSAssert(NO, @"OSKActivity subclasses must override `iconForIdiom:` without calling super.");
    return nil;
}

+ (UIImage *)settingsIcon {
    // Optional
    return nil;
}

+ (OSKAuthenticationMethod)authenticationMethod {
    NSAssert(NO, @"OSKActivity subclasses must override `authenticationMethod` without calling super.");
    return OSKAuthenticationMethod_None;
}

+ (BOOL)requiresApplicationCredential {
    NSAssert(NO, @"OSKActivity subclasses must override `requiresApplicationCredential` without calling super.");
    return NO;
}

+ (OSKPublishingMethod)publishingMethod {
    NSAssert(NO, @"OSKActivity subclasses must override `usesPublishingViewController` without calling super.");
    return OSKPublishingMethod_None;
}

- (BOOL)isReadyToPerform {
    NSAssert(NO, @"OSKActivity subclasses must override `isReadyToPerform` without calling super.");
    return NO;
}

- (void)performActivity:(OSKActivityCompletionHandler)completion {
    NSAssert(NO, @"OSKActivity subclasses must override `performActivity:` without calling super.");
}

+ (BOOL)canPerformViaOperation {
    NSAssert(NO, @"OSKActivity subclasses must override `canPerformViaOperation` without calling super.");
    return NO;
}

- (OSKActivityOperation *)operationForActivityWithCompletion:(OSKActivityCompletionHandler)completion {
    NSAssert(NO, @"OSKActivity subclasses must override `operationForActivityWithCompletion:` without calling super.");
    return nil;
}

@end


text:
module Main where
    reverseList x = reverseResult(reverseTuple(x, []))

    reverseTuple ([], reverse) = ([], reverse)
    reverseTuple (h:t, reverse) = reverseTuple(t, h:reverse)

    reverseResult (original, reverse) = reverse


text: A project I made to help people learn to ruby.