text:
package nz.co.gregs.dbvolution.internal.properties;

import static nz.co.gregs.dbvolution.internal.properties.PropertyMatchers.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import java.sql.SQLException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import nz.co.gregs.dbvolution.DBRow;
import nz.co.gregs.dbvolution.annotations.DBAdaptType;
import nz.co.gregs.dbvolution.annotations.DBColumn;
import nz.co.gregs.dbvolution.datatypes.DBDate;
import nz.co.gregs.dbvolution.datatypes.DBInteger;
import nz.co.gregs.dbvolution.datatypes.DBNumber;
import nz.co.gregs.dbvolution.datatypes.DBString;
import nz.co.gregs.dbvolution.datatypes.DBTypeAdaptor;
import nz.co.gregs.dbvolution.datatypes.QueryableDatatype;
import nz.co.gregs.dbvolution.exceptions.InvalidDeclaredTypeException;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

/**
 * Focuses on low-level functionality of type adaptors. End-to-end confirmation
 * that it works when querying an actual database is in {@link TypeAdaptorTest}.
 */
@SuppressWarnings({"serial", "unused"})
public class PropertyTypeHandlerTest {

	@Rule
	public ExpectedException thrown = ExpectedException.none();

	@Test
	public void errorsOnConstructionGivenValidTypeAdaptorWithWrongExplicitDBvType() {
		class MyClass extends DBRow {

			@DBColumn
			@DBAdaptType(value = StringLongAdaptor.class, type = DBString.class)
			public DBString field = new DBString();
		}

		thrown.expect(InvalidDeclaredTypeException.class);
		thrown.expectMessage("internal Long type is not compatible");
		new PropertyTypeHandler(propertyOf(MyClass.class, "field"), false);
	}

	@Test
	public void errorsOnConstructionGivenTypeAdaptorWithWrongExternalType() {
		class MyClass extends DBRow {

			@DBColumn
			@DBAdaptType(value = LongStringAdaptor.class)
			public DBString field = new DBString();
		}

		thrown.expect(InvalidDeclaredTypeException.class);
		thrown.expectMessage("external Long type is not compatible");
		new PropertyTypeHandler(propertyOf(MyClass.class, "field"), false);
	}

	@Test
	public void errorsOnConstructionGivenInvalidAdaptorWithNonSimpleFirstType() {
		class MyClass extends DBRow {

			@DBColumn
			@DBAdaptType(value = DBStringIntegerAdaptor.class, type = DBInteger.class)
			public DBString field = new DBString();
		}

		thrown.expect(InvalidDeclaredTypeException.class);
		thrown.expectMessage("external type must not");
		new PropertyTypeHandler(propertyOf(MyClass.class, "field"), false);
	}

	@Test
	public void errorsOnConstructionGivenInvalidAdaptorWithNonSimpleSecondType() {
		class MyClass extends DBRow {

			@DBColumn
			@DBAdaptType(value = IntegerDBIntegerAdaptor.class, type = DBInteger.class)
			public DBString field = new DBString();
		}

		thrown.expect(InvalidDeclaredTypeException.class);
		thrown.expectMessage("internal type must not");
		new PropertyTypeHandler(propertyOf(MyClass.class, "field"), false);
	}

	@Test(expected = InvalidDeclaredTypeException.class)
	public void errorsOnConstructionGivenInterfaceTypeAdaptor() {
		class MyClass extends DBRow {

			@DBColumn
			@DBAdaptType(value = AdaptorInterface.class, type = DBInteger.class)
			public DBInteger field;
		}

		new PropertyTypeHandler(propertyOf(MyClass.class, "field"), false);
	}

	@Test
	public void errorsOnConstructionGivenTypeAdaptorWithAbstractExplicitType() {
		class MyClass extends DBRow {

			@DBColumn
			@DBAdaptType(value = IntegerLongAdaptor.class, type = QueryableDatatype.class)
			public Integer field;
		}

		thrown.expect(InvalidDeclaredTypeException.class);
		thrown.expectMessage("must be");
		thrown.expectMessage("concrete");
		new PropertyTypeHandler(propertyOf(MyClass.class, "field"), false);
	}

	@Test
	public void acceptsOnConstructionGivenValidTypeAdaptorWithImplicitDBvType() {
		class MyClass extends DBRow {

			@DBColumn
			@DBAdaptType(value = IntegerLongAdaptor.class)
			public Integer field;
		}

		PropertyTypeHandler propertyHandler = new PropertyTypeHandler(propertyOf(MyClass.class, "field"), false);
		assertThat(propertyHandler, is(not(nullValue())));
	}

	@Test
	public void acceptsOnConstructionGivenValidTypeAdaptorWithCorrectExplicitDBvType() {
		class MyClass extends DBRow {

			@DBColumn
			@DBAdaptType(value = IntegerLongAdaptor.class, type = DBInteger.class)
			public Integer field;
		}

		PropertyTypeHandler propertyHandler = new PropertyTypeHandler(propertyOf(MyClass.class, "field"), false);
		assertThat(propertyHandler, is(not(nullValue())));
	}

	@Test
	public void acceptsOnConstructionGivenValidTypeAdaptorWithExternalSimpleTypeUpcast() {
		class MyClass extends DBRow {

			@DBColumn
			@DBAdaptType(value = IntegerStringAdaptor.class)
			public Long field;
		}

		PropertyTypeHandler propertyHandler = new PropertyTypeHandler(propertyOf(MyClass.class, "field"), false);
		assertThat(propertyHandler, is(not(nullValue())));
	}

	@Test
	public void acceptsOnConstructionGivenValidTypeAdaptorWithExternalSimpleTypeDowncast() {
		class MyClass extends DBRow {

			@DBColumn
			@DBAdaptType(value = LongStringAdaptor.class)
			public Integer field;
		}

		PropertyTypeHandler propertyHandler = new PropertyTypeHandler(propertyOf(MyClass.class, "field"), false);
		assertThat(propertyHandler, is(not(nullValue())));
	}

	@Test
	public void acceptsOnConstructionGivenValidTypeAdaptorWithInternalSimpleTypeUpcast() {
		class MyClass extends DBRow {

			@DBColumn
			@DBAdaptType(value = StringIntegerAdaptor.class)
			public String field;
		}

		PropertyTypeHandler propertyHandler = new PropertyTypeHandler(propertyOf(MyClass.class, "field"), false);
		assertThat(propertyHandler, is(not(nullValue())));
	}

	@Test
	public void infersDBIntegerGivenStringLongAdaptorOnDBStringField() {
		class MyClass extends DBRow {

			@DBAdaptType(value = StringLongAdaptor.class)
			@DBColumn
			public DBString field = new DBString("23");
		}

		PropertyTypeHandler propertyHandler = propertyHandlerOf(MyClass.class, "field");
		QueryableDatatype qdt = propertyHandler.getJavaPropertyAsQueryableDatatype(new MyClass());
		assertThat(propertyHandler.getQueryableDatatypeClass(), is((Object) DBInteger.class));
		assertThat(qdt, is(instanceOf(DBInteger.class)));
		assertThat(qdt.getValue(), is(instanceOf(Long.class)));
		propertyHandler.setJavaPropertyAsQueryableDatatype(new MyClass(), new DBInteger(42));
	}

	@Test
	public void infersDBIntegerGivenStringLongAdaptorOnStringField() {
		class MyClass extends DBRow {

			@DBAdaptType(value = StringLongAdaptor.class)
			@DBColumn
			public String field = "23";
		}

		PropertyTypeHandler propertyHandler = propertyHandlerOf(MyClass.class, "field");
		QueryableDatatype qdt = propertyHandler.getJavaPropertyAsQueryableDatatype(new MyClass());
		assertThat(propertyHandler.getQueryableDatatypeClass(), is((Object) DBInteger.class));
		assertThat(qdt, is(instanceOf(DBInteger.class)));
		assertThat(qdt.getValue(), is(instanceOf(Long.class)));
		propertyHandler.setJavaPropertyAsQueryableDatatype(new MyClass(), new DBInteger(42));
	}

	@Test
	public void infersDBIntegerGivenStringIntegerAdaptorOnDBStringField() {
		class MyClass extends DBRow {

			@DBAdaptType(value = StringIntegerAdaptor.class)
			@DBColumn
			public DBString field = new DBString("23");
		}

		PropertyTypeHandler propertyHandler = propertyHandlerOf(MyClass.class, "field");
		QueryableDatatype qdt = propertyHandler.getJavaPropertyAsQueryableDatatype(new MyClass());
		assertThat(propertyHandler.getQueryableDatatypeClass(), is((Object) DBInteger.class));
		assertThat(qdt, is(instanceOf(DBInteger.class)));
		assertThat(qdt.getValue(), is(instanceOf(Long.class)));
		propertyHandler.setJavaPropertyAsQueryableDatatype(new MyClass(), new DBInteger(42));
	}

	@Test
	public void infersDBIntegerGivenStringIntegerAdaptorOnStringField() {
		class MyClass extends DBRow {

			@DBAdaptType(value = StringIntegerAdaptor.class)
			@DBColumn
			public String field = "23";
		}

		PropertyTypeHandler propertyHandler = propertyHandlerOf(MyClass.class, "field");
		QueryableDatatype qdt = propertyHandler.getJavaPropertyAsQueryableDatatype(new MyClass());
		assertThat(propertyHandler.getQueryableDatatypeClass(), is((Object) DBInteger.class));
		assertThat(qdt, is(instanceOf(DBInteger.class)));
		assertThat(qdt.getValue(), is(instanceOf(Long.class)));
		propertyHandler.setJavaPropertyAsQueryableDatatype(new MyClass(), new DBInteger(42));
	}

	@Test
	public void infersDBStringGivenLongStringAdaptorOnDBIntegerField() {
		class MyClass extends DBRow {

			@DBAdaptType(value = LongStringAdaptor.class)
			@DBColumn
			public DBInteger field = new DBInteger(23);
		}

		PropertyTypeHandler propertyHandler = propertyHandlerOf(MyClass.class, "field");
		QueryableDatatype qdt = propertyHandler.getJavaPropertyAsQueryableDatatype(new MyClass());
		assertThat(propertyHandler.getQueryableDatatypeClass(), is((Object) DBString.class));
		assertThat(qdt, is(instanceOf(DBString.class)));
		assertThat(qdt.getValue(), is(instanceOf(String.class)));
		propertyHandler.setJavaPropertyAsQueryableDatatype(new MyClass(), new DBString("42"));
	}

	@Test
	public void infersDBStringGivenLongStringAdaptorOnLongField() {
		class MyClass extends DBRow {

			@DBAdaptType(value = LongStringAdaptor.class)
			@DBColumn
			public Long field = 23L;
		}

		PropertyTypeHandler propertyHandler = propertyHandlerOf(MyClass.class, "field");
		QueryableDatatype qdt = propertyHandler.getJavaPropertyAsQueryableDatatype(new MyClass());
		assertThat(propertyHandler.getQueryableDatatypeClass(), is((Object) DBString.class));
		assertThat(qdt, is(instanceOf(DBString.class)));
		assertThat(qdt.getValue(), is(instanceOf(String.class)));
		propertyHandler.setJavaPropertyAsQueryableDatatype(new MyClass(), new DBString("42"));
	}

	@Test
	public void infersDBStringGivenLongStringAdaptorOnIntegerField() {
		class MyClass extends DBRow {

			@DBAdaptType(value = LongStringAdaptor.class)
			@DBColumn
			public Integer field = 23;
		}

		PropertyTypeHandler propertyHandler = propertyHandlerOf(MyClass.class, "field");
		QueryableDatatype qdt = propertyHandler.getJavaPropertyAsQueryableDatatype(new MyClass());
		assertThat(propertyHandler.getQueryableDatatypeClass(), is((Object) DBString.class));
		assertThat(qdt, is(instanceOf(DBString.class)));
		assertThat(qdt.getValue(), is(instanceOf(String.class)));
		propertyHandler.setJavaPropertyAsQueryableDatatype(new MyClass(), new DBString("42"));
	}

	@Test
	public void infersDBStringGivenIntegerStringAdaptorOnLongField() {
		class MyClass extends DBRow {

			@DBAdaptType(value = IntegerStringAdaptor.class)
			@DBColumn
			public Long field = 23L;
		}

		PropertyTypeHandler propertyHandler = propertyHandlerOf(MyClass.class, "field");
		QueryableDatatype qdt = propertyHandler.getJavaPropertyAsQueryableDatatype(new MyClass());
		assertThat(propertyHandler.getQueryableDatatypeClass(), is((Object) DBString.class));
		assertThat(qdt, is(instanceOf(DBString.class)));
		assertThat(qdt.getValue(), is(instanceOf(String.class)));
		propertyHandler.setJavaPropertyAsQueryableDatatype(new MyClass(), new DBString("42"));
	}

	@Test
	public void infersLongGivenDateLongAdaptor() {
		class MyClass extends DBRow {

			@DBAdaptType(value = DateLongAdaptor.class)
			@DBColumn
			public DBDate field = new DBDate(new Date());
		}

		PropertyTypeHandler propertyHandler = propertyHandlerOf(MyClass.class, "field");
		QueryableDatatype qdt = propertyHandler.getJavaPropertyAsQueryableDatatype(new MyClass());
		assertThat(propertyHandler.getQueryableDatatypeClass(), is((Object) DBInteger.class));
		assertThat(qdt, is(instanceOf(DBInteger.class)));
		assertThat(qdt.getValue(), is(instanceOf(Long.class)));
		propertyHandler.setJavaPropertyAsQueryableDatatype(new MyClass(), new DBInteger(42));
	}

	@Test
	public void infersDBDateGivenIntegerStringAdaptor() {
		class MyClass extends DBRow {

			@DBAdaptType(value = LongDateAdaptor.class)
			@DBColumn
			public Long field = 2013L;
		}

		PropertyTypeHandler propertyHandler = propertyHandlerOf(MyClass.class, "field");
		QueryableDatatype qdt = propertyHandler.getJavaPropertyAsQueryableDatatype(new MyClass());
		assertThat(propertyHandler.getQueryableDatatypeClass(), is((Object) DBDate.class));
		assertThat(qdt, is(instanceOf(DBDate.class)));
		assertThat(qdt.getValue(), is(instanceOf(Date.class)));
		propertyHandler.setJavaPropertyAsQueryableDatatype(new MyClass(), new DBDate(new Date()));
	}

	@Test
	public void acceptsDBIntegerGivenIntegerAdaptorAndExplicitType() {
		class MyClass extends DBRow {

			@DBAdaptType(value = StringIntegerAdaptor.class, type = DBInteger.class)
			@DBColumn
			public String field = "23";
		}

		PropertyTypeHandler propertyHandler = propertyHandlerOf(MyClass.class, "field");
		QueryableDatatype qdt = propertyHandler.getJavaPropertyAsQueryableDatatype(new MyClass());
		assertThat(propertyHandler.getQueryableDatatypeClass(), is((Object) DBInteger.class));
		assertThat(qdt, is(instanceOf(DBInteger.class)));
		assertThat(qdt.getValue(), is(instanceOf(Long.class)));
	}

	// Obsolete since DBInteger is now a separate type
//	@Test
//	public void acceptsDBNumberGivenIntegerAdaptorAndExplicitType() {
//		class MyClass extends DBRow {
//			@DBAdaptType(value=StringIntegerAdaptor.class, type=DBNumber.class)
//			@DBColumn
//			public String field = "23";
//		}
//
//		PropertyTypeHandler propertyHandler = propertyHandlerOf(MyClass.class, "field");
//		QueryableDatatype qdt = propertyHandler.getJavaPropertyAsQueryableDatatype(new MyClass());
//		assertThat(propertyHandler.getQueryableDatatypeClass(), is((Object) DBNumber.class));
//		assertThat(qdt, is(instanceOf(DBNumber.class)));
//		assertThat(qdt.getValue(), is(instanceOf(Double.class)));
//	}
	@Test
	public void getsQDTValueGivenValidFieldAndNoTypeAdaptor() {
		class MyClass extends DBRow {

			@DBColumn
			public DBInteger field = new DBInteger();
		}

		MyClass myObj = new MyClass();
		myObj.field.setValue(23);

		PropertyTypeHandler propertyHandler = propertyHandlerOf(MyClass.class, "field");
		DBInteger qdt = (DBInteger) propertyHandler.getJavaPropertyAsQueryableDatatype(myObj);
		assertThat(qdt.getValue().intValue(), is(23));
	}

	@Test
	public void getsUnchangedQDTInstanceGivenValidFieldAndNoTypeAdaptor() {
		class MyClass extends DBRow {

			@DBColumn
			public DBInteger field = new DBInteger();
		}

		MyClass myObj = new MyClass();

		PropertyTypeHandler propertyHandler = propertyHandlerOf(MyClass.class, "field");
		DBInteger qdt = (DBInteger) propertyHandler.getJavaPropertyAsQueryableDatatype(myObj);
		assertThat(qdt == myObj.field, is(true));
	}

	@Test
	public void getsNullQDTValueGivenValidNullQDTFieldAndNoTypeAdaptor() {
		class MyClass extends DBRow {

			@DBColumn
			public DBInteger field = null;
		}

		MyClass myObj = new MyClass();

		PropertyTypeHandler propertyHandler = propertyHandlerOf(MyClass.class, "field");
		DBInteger qdt = (DBInteger) propertyHandler.getJavaPropertyAsQueryableDatatype(myObj);
		assertThat(qdt, is(nullValue()));
	}

	@Test
	public void getsNullAdaptedQDTValueGivenNullQDTFieldAndTypeAdaptor() {
		class MyClass extends DBRow {

			@DBColumn
			@DBAdaptType(value = LongStringAdaptor.class)
			public DBInteger field = null;
		}

		MyClass myObj = new MyClass();

		PropertyTypeHandler propertyHandler = propertyHandlerOf(MyClass.class, "field");
		QueryableDatatype qdt = propertyHandler.getJavaPropertyAsQueryableDatatype(myObj);
		assertThat(qdt, is(nullValue()));
	}

	@Test
	public void getsIsNullAdaptedQDTValueGivenNullSimpleFieldAndTypeAdaptor() {
		class MyClass extends DBRow {

			@DBColumn
			@DBAdaptType(value = LongStringAdaptor.class)
			public Long field = null;
		}

		MyClass myObj = new MyClass();

		PropertyTypeHandler propertyHandler = propertyHandlerOf(MyClass.class, "field");
		QueryableDatatype qdt = propertyHandler.getJavaPropertyAsQueryableDatatype(myObj);
		assertThat(qdt, is(not(nullValue())));
		assertThat(qdt.isNull(), is(true));
	}

	@Test
	public void getsCorrectInternalValueTypeGivenIntegerStringAdaptorOnDBIntegerField() {
		class MyClass extends DBRow {

			@DBAdaptType(value = LongStringAdaptor.class)
			@DBColumn
			public DBInteger field = new DBInteger();
		}

		PropertyTypeHandler propertyHandler = propertyHandlerOf(MyClass.class, "field");
		QueryableDatatype qdt = propertyHandler.getJavaPropertyAsQueryableDatatype(new MyClass());
		assertThat(qdt, is(instanceOf(DBString.class)));
	}

	@Test
	public void getsCorrectInternalValueGivenLongStringAdaptorOnDBIntegerField() {
		class MyClass extends DBRow {

			@DBAdaptType(value = LongStringAdaptor.class)
			@DBColumn
			public DBInteger field = new DBInteger();
		}

		MyClass myObj = new MyClass();
		myObj.field.setValue(23);

		PropertyTypeHandler propertyHandler = propertyHandlerOf(MyClass.class, "field");
		DBString qdt = (DBString) propertyHandler.getJavaPropertyAsQueryableDatatype(myObj);

		assertThat(qdt.stringValue(), is("23"));
	}

	@Test
	public void getsSameInstanceOnConsecutiveReadsGivenAdaptorWhenUsingSameHandler() {
		class MyClass extends DBRow {

			@DBAdaptType(value = LongStringAdaptor.class)
			@DBColumn
			public DBInteger field = new DBInteger();
		}

		MyClass myObj = new MyClass();
		PropertyTypeHandler propertyHandler = propertyHandlerOf(MyClass.class, "field");
		DBString qdt1 = (DBString) propertyHandler.getJavaPropertyAsQueryableDatatype(myObj);
		DBString qdt2 = (DBString) propertyHandler.getJavaPropertyAsQueryableDatatype(myObj);
		DBString qdt3 = (DBString) propertyHandler.getJavaPropertyAsQueryableDatatype(myObj);

		assertThat(qdt2 == qdt1, is(true));
		assertThat(qdt3 == qdt1, is(true));
	}

	@Test
	public void getsDifferentInstanceOnConsecutiveReadsAndWritesGivenAdaptorWhenUsingSameHandler() {
		class MyClass extends DBRow {

			@DBAdaptType(value = LongStringAdaptor.class)
			@DBColumn
			public DBInteger field = new DBInteger();
		}

		MyClass myObj = new MyClass();
		PropertyTypeHandler propertyHandler = propertyHandlerOf(MyClass.class, "field");
		DBString qdt1 = (DBString) propertyHandler.getJavaPropertyAsQueryableDatatype(myObj);

		propertyHandler.setJavaPropertyAsQueryableDatatype(myObj, new DBString());
		DBString qdt2 = (DBString) propertyHandler.getJavaPropertyAsQueryableDatatype(myObj);

		propertyHandler.setJavaPropertyAsQueryableDatatype(myObj, new DBString());
		DBString qdt3 = (DBString) propertyHandler.getJavaPropertyAsQueryableDatatype(myObj);

		assertThat(qdt2 == qdt1, is(false));
		assertThat(qdt3 == qdt1, is(false));
		assertThat(qdt3 == qdt2, is(false));
	}

	@Test
	public void setsFieldValueGivenValidFieldAndNoTypeAdaptor() {
		class MyClass extends DBRow {

			@DBColumn
			public DBInteger field = new DBInteger();
		}

		MyClass myObj = new MyClass();
		PropertyTypeHandler propertyHandler = propertyHandlerOf(MyClass.class, "field");

		DBInteger qdt = new DBInteger();
		qdt.setValue(23);
		propertyHandler.setJavaPropertyAsQueryableDatatype(myObj, qdt);

		assertThat(myObj.field.getValue().intValue(), is(23));
	}

	@Test
	public void setsFieldValueGivenValidFieldAndTypeAdaptor() {
		class MyClass extends DBRow {

			@DBColumn
			@DBAdaptType(StringLongAdaptor.class)
			public DBString field = new DBString();
		}

		MyClass myObj = new MyClass();
		PropertyTypeHandler propertyHandler = propertyHandlerOf(MyClass.class, "field");

		DBInteger qdt = new DBInteger();
		qdt.setValue(23);
		propertyHandler.setJavaPropertyAsQueryableDatatype(myObj, qdt);

		assertThat(myObj.field.stringValue(), is("23"));
	}

	@Test
	public void setsUnchangedFieldReferenceGivenValidObjectAndNoTypeAdaptor() {
		class MyClass extends DBRow {

			@DBColumn
			public DBInteger field = new DBInteger();
		}

		MyClass myObj = new MyClass();
		PropertyTypeHandler propertyHandler = propertyHandlerOf(MyClass.class, "field");

		DBInteger qdt = new DBInteger();
		propertyHandler.setJavaPropertyAsQueryableDatatype(myObj, qdt);

		assertThat(myObj.field == qdt, is(true));
	}

	@Test
	public void setsQDTFieldNullGivenNullQDTAndNoTypeAdaptor() {
		class MyClass extends DBRow {

			@DBColumn
			public DBInteger field = new DBInteger();
		}

		MyClass myObj = new MyClass();
		PropertyTypeHandler propertyHandler = propertyHandlerOf(MyClass.class, "field");

		propertyHandler.setJavaPropertyAsQueryableDatatype(myObj, null);
		assertThat(myObj.field, is(nullValue()));
	}

	@Test
	public void setsQDTFieldNullGivenNullQDTAndTypeAdaptor() {
		class MyClass extends DBRow {

			@DBColumn
			@DBAdaptType(value = IntegerStringAdaptor.class)
			public DBInteger field = new DBInteger();
		}

		MyClass myObj = new MyClass();
		PropertyTypeHandler propertyHandler = propertyHandlerOf(MyClass.class, "field");

		propertyHandler.setJavaPropertyAsQueryableDatatype(myObj, null);
		assertThat(myObj.field, is(nullValue()));
	}

	@Test
	public void setsAsDBIntegerWithLongGivenLongAdaptor() {
		class MyClass extends DBRow {

			@DBAdaptType(value = StringLongAdaptor.class)
			@DBColumn
			public DBString field = new DBString();
		}

		MyClass obj = new MyClass();
		PropertyTypeHandler propertyHandler = propertyHandlerOf(MyClass.class, "field");
		propertyHandler.setJavaPropertyAsQueryableDatatype(obj, new DBInteger(42L));
		assertThat(obj.field.getValue(), is((Object) "42"));
	}

	@Test
	public void setsAsDBIntegerWithIntegerGivenLongAdaptor() {
		class MyClass extends DBRow {

			@DBAdaptType(value = StringLongAdaptor.class)
			@DBColumn
			public DBString field = new DBString();
		}

		MyClass obj = new MyClass();
		PropertyTypeHandler propertyHandler = propertyHandlerOf(MyClass.class, "field");
		propertyHandler.setJavaPropertyAsQueryableDatatype(obj, new DBInteger(42));
		assertThat(obj.field.getValue(), is((Object) "42"));
	}

//	@Test
//	public void setsAsDBNumberWithIntegerGivenLongAdaptor() {
//		class MyClass extends DBRow {
//			@DBAdaptType(value=StringLongAdaptor.class, type=DBNumber.class)
//			@DBColumn
//			public DBString field = new DBString();
//		}
//
//		MyClass obj = new MyClass();
//		PropertyTypeHandler propertyHandler = propertyHandlerOf(MyClass.class, "field");
//		propertyHandler.setJavaPropertyAsQueryableDatatype(obj, new DBNumber(42));
//		assertThat(obj.field.getValue(), is((Object)"42"));
//	}
//	@Test
//	public void doesSomethingSensibleWhenSettingDBNumberAsDBIntegerWithLongGivenLongAdaptor() {
//		class MyClass extends DBRow {
//			@DBAdaptType(value=StringLongAdaptor.class, type=DBNumber.class)
//			@DBColumn
//			public DBString field = new DBString();
//		}
//
//		thrown.expect(ClassCastException.class);
//
//		MyClass obj = new MyClass();
//		PropertyTypeHandler propertyHandler = propertyHandlerOf(MyClass.class, "field");
//		propertyHandler.setJavaPropertyAsQueryableDatatype(obj, new DBInteger(42L));
//		//assertThat(obj.field.getValue(), is((Object)"42"));
//	}
//	@Test
//	public void doesSomethingSensibleWhenSettingDBNumberAsDBIntegerWithIntegerGivenLongAdaptor() {
//		class MyClass extends DBRow {
//			@DBAdaptType(value=StringLongAdaptor.class, type=DBNumber.class)
//			@DBColumn
//			public DBString field = new DBString();
//		}
//
//		thrown.expect(ClassCastException.class);
//
//		MyClass obj = new MyClass();
//		PropertyTypeHandler propertyHandler = propertyHandlerOf(MyClass.class, "field");
//		propertyHandler.setJavaPropertyAsQueryableDatatype(obj, new DBInteger(42));
//		//assertThat(obj.field.getValue(), is((Object)"42"));
//	}

	private PropertyTypeHandler propertyHandlerOf(Class<?> clazz, String javaPropertyName) {
		return new PropertyTypeHandler(propertyOf(clazz, javaPropertyName), false);
	}

	private JavaProperty propertyOf(Class<?> clazz, String javaPropertyName) {
		List<JavaProperty> properties = new JavaPropertyFinder().getPropertiesOf(clazz);
		JavaProperty property = itemOf(properties, that(hasJavaPropertyName(javaPropertyName)));
		if (property == null) {
			throw new IllegalArgumentException("No public property found with java name '" + javaPropertyName + "'");
		}
		return property;
	}

	public static class IntegerStringAdaptor implements DBTypeAdaptor<Integer, String> {

		@Override
		public Integer fromDatabaseValue(String dbvValue) {
			if (dbvValue != null) {
				return Integer.parseInt(dbvValue);
			}
			return null;
		}

		@Override
		public String toDatabaseValue(Integer objectValue) {
			if (objectValue != null) {
				return objectValue.toString();
			}
			return null;
		}
	}

	public static class StringIntegerAdaptor implements DBTypeAdaptor<String, Integer> {

		@Override
		public String fromDatabaseValue(Integer dbvValue) {
			if (dbvValue != null) {
				return dbvValue.toString();
			}
			return null;
		}

		@Override
		public Integer toDatabaseValue(String objectValue) {
			if (objectValue != null) {
				return Integer.parseInt(objectValue);
			}
			return null;
		}
	}

	public static class LongStringAdaptor implements DBTypeAdaptor<Long, String> {

		@Override
		public Long fromDatabaseValue(String dbvValue) {
			if (dbvValue != null) {
				return Long.parseLong(dbvValue);
			}
			return null;
		}

		@Override
		public String toDatabaseValue(Long objectValue) {
			if (objectValue != null) {
				return objectValue.toString();
			}
			return null;
		}
	}

	public static class StringLongAdaptor implements DBTypeAdaptor<String, Long> {

		@Override
		public String fromDatabaseValue(Long dbvValue) {
			if (dbvValue != null) {
				return dbvValue.toString();
			}
			return null;
		}

		@Override
		public Long toDatabaseValue(String objectValue) {
			if (objectValue != null) {
				return Long.parseLong(objectValue);
			}
			return null;
		}
	}

	public static class DateLongAdaptor implements DBTypeAdaptor<Date, Long> {

		@Override
		public Date fromDatabaseValue(Long dbvValue) {
			if (dbvValue != null) {
				Calendar c = Calendar.getInstance();
				c.clear();
				c.set(Calendar.YEAR, dbvValue.intValue());
				return c.getTime();
			}
			return null;
		}

		@Override
		public Long toDatabaseValue(Date objectValue) {
			Calendar c = Calendar.getInstance();
			c.setTime(objectValue);
			return (long) c.get(Calendar.YEAR);
		}
	}

	public static class LongDateAdaptor implements DBTypeAdaptor<Long, Date> {

		@Override
		public Long fromDatabaseValue(Date dbvValue) {
			Calendar c = Calendar.getInstance();
			c.setTime(dbvValue);
			return (long) c.get(Calendar.YEAR);
		}

		@Override
		public Date toDatabaseValue(Long objectValue) {
			if (objectValue != null) {
				Calendar c = Calendar.getInstance();
				c.clear();
				c.set(Calendar.YEAR, objectValue.intValue());
				return c.getTime();
			}
			return null;
		}
	}

	public static class IntegerLongAdaptor implements DBTypeAdaptor<Integer, Long> {

		@Override
		public Integer fromDatabaseValue(Long dbvValue) {
			return null;
		}

		@Override
		public Long toDatabaseValue(Integer objectValue) {
			return null;
		}
	}

	public static class IntegerDBIntegerAdaptor implements DBTypeAdaptor<Integer, DBInteger> {

		@Override
		public Integer fromDatabaseValue(DBInteger dbvValue) {
			return null;
		}

		@Override
		public DBInteger toDatabaseValue(Integer objectValue) {
			return null;
		}
	}

	public static class DBStringIntegerAdaptor implements DBTypeAdaptor<DBString, Integer> {

		@Override
		public DBString fromDatabaseValue(Integer dbvValue) {
			return null;
		}

		@Override
		public Integer toDatabaseValue(DBString objectValue) {
			return null;
		}
	}

	public static interface AdaptorInterface extends DBTypeAdaptor<Object, QueryableDatatype> {
		// empty
	}
}


text:
// Copyright 2018-2022, University of Colorado Boulder

/**
 * Displays 'NO REAL ROOTS', used when a quadratic has no real roots.
 *
 * @author Chris Malley (PixelZoom, Inc.)
 */

import DerivedProperty from '../../../../axon/js/DerivedProperty.js';
import Bounds2 from '../../../../dot/js/Bounds2.js';
import merge from '../../../../phet-core/js/merge.js';
import { Node, Rectangle, Text } from '../../../../scenery/js/imports.js';
import Tandem from '../../../../tandem/js/Tandem.js';
import BooleanIO from '../../../../tandem/js/types/BooleanIO.js';
import GQColors from '../../common/GQColors.js';
import GQConstants from '../../common/GQConstants.js';
import graphingQuadratics from '../../graphingQuadratics.js';
import GraphingQuadraticsStrings from '../../GraphingQuadraticsStrings.js';

// const
const Y_OFFSET = 2; // min offset from vertex, determined empirically

class NoRealRootsNode extends Node {

  /**
   * @param {BooleanProperty} rootsVisibleProperty
   * @param {BooleanProperty} vertexVisibleProperty
   * @param {BooleanProperty} coordinatesVisibleProperty
   * @param {Property.<Quadratic>} quadraticProperty - the interactive quadratic
   * @param {ModelViewTransform2} modelViewTransform
   * @param {Object} [options]
   */
  constructor( rootsVisibleProperty, vertexVisibleProperty, coordinatesVisibleProperty,
               quadraticProperty, modelViewTransform, options ) {

    options = merge( {

      // Node options
      maxWidth: 200, // determined empirically

      // phet-io
      tandem: Tandem.REQUIRED,
      phetioDocumentation: 'displays NO REAL ROOTS when the interactive quadratic has no real roots'
    }, options );

    const textNode = new Text( GraphingQuadraticsStrings.noRealRoots, {
      font: GQConstants.NO_REAL_ROOTS_FONT,
      fill: 'white'
    } );

    const backgroundNode = new Rectangle( textNode.bounds.dilatedXY( 5, 1 ), {
      fill: GQColors.ROOTS,
      opacity: 0.75,
      cornerRadius: 4,
      center: textNode.center
    } );

    assert && assert( !options.children, 'NoRealRootsNode sets children' );
    options.children = [ backgroundNode, textNode ];

    // visibility of this Node
    assert && assert( !options.visibleProperty, 'NoRealRootsNode sets visibleProperty' );
    options.visibleProperty = new DerivedProperty(
      [ rootsVisibleProperty, quadraticProperty ],
      ( rootsVisible, quadratic ) =>
        rootsVisible && // the Roots checkbox is checked
        !!( quadratic.roots && quadratic.roots.length === 0 ), // the interactive quadratic has no roots
      {
        tandem: options.tandem.createTandem( 'visibleProperty' ),
        phetioValueType: BooleanIO
      } );

    super( options );

    // Part of the graph where 'NO REAL ROOTS' may overlap with vertex coordinates, when 'NO REAL ROOTS' is
    // typically centered at the origin. Width is based on maxWidth, height was determined empirically.
    // See https://github.com/phetsims/graphing-quadratics/issues/88
    const vertexOverlapBounds = new Bounds2(
      modelViewTransform.viewToModelDeltaX( -0.6 * options.maxWidth ), -Y_OFFSET,
      modelViewTransform.viewToModelDeltaX( 0.6 * options.maxWidth ), Y_OFFSET );

    // The center of this Node, typically at the origin, except when that would overlap the vertex's coordinates.
    // In that case, position above or below the x axis, depending on which way the parabola opens.
    // See https://github.com/phetsims/graphing-quadratics/issues/88
    const centerProperty = new DerivedProperty(
      [ vertexVisibleProperty, coordinatesVisibleProperty, quadraticProperty ],
      ( vertexVisible, coordinatesVisible, quadratic ) => {
        if ( vertexVisible && // the Vertex checkbox is checked
             coordinatesVisible && // the Coordinates checkbox is checked
             ( quadratic.roots && quadratic.roots.length === 0 ) && // no roots
             // vertex is in a position where its coordinates will overlap
             ( quadratic.vertex && vertexOverlapBounds.containsPoint( quadratic.vertex ) ) ) {
          // center above or below the x axis, y offset determined empirically
          const y = quadratic.vertex.y + ( quadratic.a > 0 ? -Y_OFFSET : Y_OFFSET );
          return modelViewTransform.modelToViewXY( 0, y );
        }
        else {
          // center at the origin
          return modelViewTransform.modelToViewXY( 0, 0 );
        }
      }
    );
    centerProperty.linkAttribute( this, 'center' );
  }
}

graphingQuadratics.register( 'NoRealRootsNode', NoRealRootsNode );
export default NoRealRootsNode;

redpajama_set_name: RedPajamaGithub


text:
package org.drools.core.command.runtime.rule;

import org.drools.core.command.impl.GenericCommand;
import org.drools.core.command.impl.KnowledgeCommandContext;
import org.kie.api.event.rule.RuleRuntimeEventListener;
import org.kie.api.runtime.KieSession;
import org.kie.internal.command.Context;

import java.util.Collection;

public class GetRuleRuntimeEventListenersCommand
    implements
    GenericCommand<Collection<RuleRuntimeEventListener>> {

    public Collection<RuleRuntimeEventListener> execute(Context context) {
        KieSession ksession = ((KnowledgeCommandContext) context).getKieSession();
        return ksession.getRuleRuntimeEventListeners();
    }

    public String toString() {
        return "session.getRuleRuntimeEventListeners();";
    }
}


text:
You can edit Slot

Are you sure you want to delete?

{{$ctrl.timeslot.date.value}} - {{$ctrl.timeslot.date.key}}

                            Time Slot :

                            <input type="text" disabled ng-model="$ctrl.timeslot.time" class="form-controls">

                            Availability Count :

                            <input autofocus type="text" ng-model="$ctrl.timeslot.availabilityCount" class="form-controls">

                    <button type="button" ng-click="$ctrl.cancel()" class="btn btn-sm btn-default">Cancel</button>
                    <button ng-show="!$ctrl.enableDel" type="button" ng-click="$ctrl.save()" class="btn btn-sm btn-success">Save</button>
                    <button ng-show="$ctrl.enableDel" type="button" ng-click="$ctrl.save()" class="btn btn-sm btn-danger">Delete</button>


text:
@implementation UIColor (Extension)
+ (UIColor*) budgetPurple
{
	return [UIColor colorWithRed:92.0f/255.0f green:64.0f/255.0f blue:124.0f/255.0f alpha:1.0f];
}

+ (UIColor*) budgetGreen
{
	return [UIColor colorWithRed:130.0f/255.0f green:179.0f/255.0f blue:74.0f/255.0f alpha:1.0f];
}

+ (UIColor*) budgetOrange
{
	return [UIColor colorWithRed:235.0f/255.0f green:116.0f/255.0f blue:62.0f/255.0f alpha:1.0f];
}

+ (UIColor*) budgetTurquoise
{
	return [UIColor colorWithRed:123.0f/255.0f green:181.0f/255.0f blue:123.0f/255.0f alpha:1.0f];
}

+ (UIColor*) budgetYellow
{
	return [UIColor colorWithRed:236.0f/255.0f green:160.0f/255.0f blue:47.0f/255.0f alpha:1.0f];
}

+ (UIColor*) budgetTeal
{
	return [UIColor colorWithRed:32.0f/255.0f green:137.0f/255.0f blue:164.0f/255.0f alpha:1.0f];
}

+ (UIColor*) budgetRed
{
	return [UIColor colorWithRed:161.0f/255.0f green:56.0f/255.0f blue:53.0/255.0f alpha:1.0f];
}

+ (UIColor*) budgetBlack
{
	return [UIColor colorWithRed:19.0f/255.0f green:19.0f/255.0f blue:19.0f/255.0f alpha:1.0f];
}

+ (UIColor*) budgetLightGray
{
	return [UIColor colorWithRed:150.0f/255.0f green:150.0f/255.0f blue:150.0f/255.0f alpha:1.0f];
}

// Takes a UIColor, returns an NSData
+ (NSData*)transfomedValue:(UIColor*)value {
    UIColor *color = value;
    const CGFloat *components = CGColorGetComponents(color.CGColor);
    NSString *colorAsString = [NSString stringWithFormat:@"%f,%f,%f,%f", components[0], components[1], components[2], components[3]];
    return [colorAsString dataUsingEncoding:NSUTF8StringEncoding];
}

// Takes an NSData, returns a UIColor
+ (UIColor*)reverseTransformedValue:(NSData*)value {
    NSString *colorAsString = [[NSString alloc] initWithData:value encoding:NSUTF8StringEncoding];
    NSArray *components = [colorAsString componentsSeparatedByString:@","];
    CGFloat r = [[components objectAtIndex:0] floatValue];
    CGFloat g = [[components objectAtIndex:1] floatValue];
    CGFloat b = [[components objectAtIndex:2] floatValue];
    CGFloat a = [[components objectAtIndex:3] floatValue];
    return [UIColor colorWithRed:r green:g blue:b alpha:a];
}
@end


text:
/* dtkComposerNodeFactoryView.h ---
 *
 * Author: Thibaud Kloczko
 * Created: Thu Apr 11 10:38:29 2013 (+0200)
 * Version:
 * Last-Updated: ven. janv.  9 10:13:20 2015 (+0100)
 *           By: Thibaud Kloczko
 *     Update #: 8
 */

/* Change Log:
 *
 */

#pragma once

#include "dtkComposerExport.h"

#include <QtCore>
#include <QtWidgets>

class dtkComposerFactory;
class dtkComposerNodeFactoryViewPrivate;
class dtkComposerSceneNode;
class dtkWidgetsItemView;
class dtkWidgetsTagCloud;
class dtkWidgetsTagCloudScope;
class dtkWidgetsTagCloudView;

class DTKCOMPOSER_EXPORT dtkComposerNodeFactoryView : public QWidget
{
    Q_OBJECT

public:
     dtkComposerNodeFactoryView(QWidget *parent = 0);
    ~dtkComposerNodeFactoryView(void);

public slots:
    void onShowNodeDocumentation(dtkComposerSceneNode *node);

public:
    void addNote(void);

public:
    void setFactory(dtkComposerFactory *factory);

public:
    void setDark(void);

public:
    dtkWidgetsTagCloud      *cloudView(void) const;
    dtkWidgetsTagCloudView   *itemView(void) const;
    dtkWidgetsTagCloudScope *scopeView(void) const;

private:
    dtkComposerNodeFactoryViewPrivate *d;
};


text:
package org.brackit.server.metadata.pathSynopsis.manager;

import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.brackit.server.metadata.pathSynopsis.NsMapping;
import org.brackit.server.metadata.pathSynopsis.PSNode;
import org.brackit.server.tx.Tx;
import org.brackit.xquery.atomic.QNm;
import org.brackit.xquery.util.path.Path;
import org.brackit.xquery.util.path.PathException;
import org.brackit.xquery.xdm.DocumentException;
import org.brackit.xquery.xdm.Kind;
import org.brackit.xquery.xdm.type.ElementType;
import org.brackit.xquery.xdm.type.NodeType;
import org.brackit.xquery.xdm.type.TextType;

/**
 * Realizes the path synopsis as a tree.
 *
 * A path synopsis is a collection of path classes of an xml collection. It is
 * organized as multiple trees counting the number of the same classes in each
 * node. A path class is a collection of the same types of parent-child related
 * xml nodes. The names of the xml nodes (attributes respectively) are stored as
 * ids referencing the actual names. These can be resolved in the vocabulary
 * manager.
 *
 * Every node has a pcr.
 *
 * @author Martin Meiringer
 * @author Karsten Schmidt
 * @author Matthias Burkhart
 * @author Sebastian Baechle
 */
public class PathSynopsis {

	// insert new nodes as children of this node
	private PathSynopsisNode[] roots;

	// maps pcrs to the corresponding nodes
	private PathSynopsisNode[] pcrTable;

	// pcr count
	private int pcr = 0;

	// max pcr stored on disk. Needed for optimized storage of the path synopsis
	// nodes at transaction commit
	private int maxStoredPCR = 0;

	private int psIdxNo = -1;

	// needs to be cleared when a path is added or removed !!
	private HashMap<Path<QNm>, Set<Integer>> pathCache = new HashMap<Path<QNm>, Set<Integer>>();

	protected final Map<QNm, ArrayList<PSNode>> map;

	public PathSynopsis(int idxNo) {
		this.psIdxNo = idxNo;
		this.roots = new PathSynopsisNode[1];
		this.pcrTable = new PathSynopsisNode[20];
		this.map = new HashMap<QNm, ArrayList<PSNode>>();
	}

	public PathSynopsisNode getNewNode(int pcr, QNm name, int uriVocID,
			int prefixVocID, int localNameVocID, byte kind,
			NsMapping nsMapping, PathSynopsisNode parent) {
		pathCache.clear();

		if (nsMapping != null) {
			nsMapping.finalize();
		}
		PathSynopsisNode psN = new PathSynopsisNode(uriVocID, prefixVocID,
				localNameVocID, pcr, name, kind, nsMapping, parent, this);

		if (pcr > this.pcr) {
			this.pcr++;
		}

		while (pcr >= pcrTable.length) {
			PathSynopsisNode[] newPcrs = new PathSynopsisNode[(pcrTable.length * 3) / 2 + 1];
			System.arraycopy(pcrTable, 0, newPcrs, 0, pcrTable.length);
			pcrTable = newPcrs;
		}
		pcrTable[pcr] = psN;

		if (parent == null) {
			int i = 0;
			while ((i < roots.length) && (roots[i] != null)) {
				i++;
			}

			if (i == roots.length) {
				PathSynopsisNode[] newRoots = new PathSynopsisNode[(roots.length * 3) / 2 + 1];
				System.arraycopy(roots, 0, newRoots, 0, roots.length);
				roots = newRoots;
			}

			roots[i] = psN;
		}

		ArrayList<PSNode> list = map.get(name);
		if (list == null) {
			list = new ArrayList<PSNode>(4);
			map.put(name, list);
		}
		list.add(psN);

		return psN;
	}

	public BitSet match(QNm name, int minLevel) {
		ArrayList<PSNode> list = map.get(name);
		if (list == null) {
			return new BitSet(0);
		}
		BitSet matches = new BitSet();
		for (PSNode psn : list) {
			if (psn.getLevel() > minLevel) {
				matches.set(psn.getPCR());
			}
		}
		return matches;
	}

	public BitSet matchChildPath(NodeType[] type, int pcr) {
		BitSet matches = new BitSet();
		PathSynopsisNode n = getNodeByPcr(pcr);
		matchChildPath(matches, n, type, 0);
		return matches;
	}

	public static void main(String[] args) throws Exception {
		PathSynopsis ps = new PathSynopsis(1);
		PathSynopsisNode a = ps.getNewNode(new QNm("a"), -1, -1, -1, Kind.ELEMENT.ID, null, null, 0);
		PathSynopsisNode b = ps.getNewNode(new QNm("b"), -1, -1, -1, Kind.ELEMENT.ID, null, a, 0);
		PathSynopsisNode c = ps.getNewNode(new QNm("c"), -1, -1, -1, Kind.ELEMENT.ID, null, b, 0);
		PathSynopsisNode d = ps.getNewNode(new QNm("d"), -1, -1, -1, Kind.ELEMENT.ID, null, c, 0);
		PathSynopsisNode e = ps.getNewNode(new QNm("e"), -1, -1, -1, Kind.ELEMENT.ID, null, d, 0);
		PathSynopsisNode f = ps.getNewNode(new QNm("f"), -1, -1, -1, Kind.ELEMENT.ID, null, d, 0);
		PathSynopsisNode g = ps.getNewNode(new QNm("g"), -1, -1, -1, Kind.ATTRIBUTE.ID, null, d, 0);
		NodeType[] path = {new ElementType(new QNm("b")), new ElementType(new QNm("c")), new ElementType(new QNm("d"))};
		System.out.println(ps.matchChildPath(path, a.getPCR()));
	}

	private void matchChildPath(BitSet matches, PathSynopsisNode n,
			NodeType[] type, int step) {
		if ((type[step].getNodeKind() != null) && (type[step].getNodeKind() != Kind.ELEMENT)) {
			if (n != null) {
				matches.set(n.getPCR());
			}
			return;
		}
		PathSynopsisNode[] children = (n != null) ? n.children : roots;
		QNm name = type[step].getQName();
		for (PathSynopsisNode c : children) {
			if ((name == null) || (c.name.atomicCmp(name) == 0)) {
				if (++step == type.length) {
					addAll(matches, c);
				} else {
					matches.set(c.getPCR());
					matchChildPath(matches, c, type, step);
				}
				return;
			}
		}
	}

	private void addAll(BitSet matches, PathSynopsisNode n) {
		matches.set(n.getPCR());
		for (PathSynopsisNode c : n.children) {
			addAll(matches, c);
		}
	}

	public PathSynopsisNode getNewNode(QNm name, int uriVocID, int prefixVocID,
			int localNameVocID, byte kind, NsMapping nsMapping,
			PathSynopsisNode parent, int count) {
		return getNewNode(++pcr, name, uriVocID, prefixVocID, localNameVocID,
				kind, nsMapping, parent);
	}

	public PathSynopsisNode getNodeByPcr(int pcr) {
		return ((pcr <= this.pcr) && (pcr > 0)) ? pcrTable[pcr] : null;
	}

	public Set<Integer> getPCRsForPath(Tx transaction, Path<QNm> path)
			throws DocumentException {
		try {
			Set<Integer> pcrSet = pathCache.get(path);

			if (pcrSet != null) {
				return pcrSet;
			}

			pcrSet = new HashSet<Integer>();

			boolean isAttributePattern = path.isAttribute();
			int pathLength = path.getLength();

			for (int i = 1; i <= pcr; i++) {
				PathSynopsisNode node = pcrTable[i];

				if (node == null) {
					continue;
				}

				if (node.getLevel() < pathLength) {
					continue;
				}

				if (isAttributePattern ^ (node.getKind() == Kind.ATTRIBUTE.ID)) {
					continue;
				}

				if (path.matches(node.getPath())) {
					pcrSet.add(node.getPCR());
				}
			}
			pathCache.put(path, pcrSet);
			return pcrSet;
		} catch (PathException e) {
			throw new DocumentException(e);
		}
	}

	public int[] getPCRsForChildPath(Tx transaction, Path<QNm> path)
			throws DocumentException {
		try {
			// assert: path only consists of childsteps

			int pathLength = path.getLength();

			int[] pathPCRs = new int[pathLength];
			for (int i = 0; i < pathPCRs.length; i++) {
				pathPCRs[i] = -1;
			}

			// decompose path
			List<Path<QNm>> paths = new ArrayList<Path<QNm>>(pathLength);
			paths.add(path);
			for (int i = 1; i < pathLength; i++) {
				path = path.leading();
				paths.add(path);
			}
			Collections.reverse(paths);

			// path lookup in cache
			for (int i = 0; i < pathPCRs.length; i++) {
				Set<Integer> pcrSet = pathCache.get(paths.get(i));

				if (pcrSet != null) {
					for (int pcr : pcrSet) {
						pathPCRs[i] = pcr;
					}
				}
			}

			for (int i = 1; i <= pcr; i++) {
				PathSynopsisNode node = pcrTable[i];

				if (node == null) {
					continue;
				}

				for (int j = 0; j < pathPCRs.length; j++) {
					if (pathPCRs[j] == -1) {
						// PCR not already fetched

						if (paths.get(j).matches(node.getPath())) {
							pathPCRs[j] = node.getPCR();
						}
					}
				}
			}

			for (int j = 0; j < pathPCRs.length; j++) {
				if (pathPCRs[j] != -1) {
					// PCR successfully fetched
					Set<Integer> s = new HashSet<Integer>();
					s.add(pathPCRs[j]);
					pathCache.put(paths.get(j), s);
				}
			}

			return pathPCRs;
		} catch (PathException e) {
			throw new DocumentException(e);
		}
	}

	@Override
	public String toString() {
		StringBuilder buffer = new StringBuilder(
				"path synopsis (Format [PCR:VocID:Count] ):");
		for (PathSynopsisNode root : roots) {
			if (root != null) {
				ArrayList<StringBuffer> levelBuffers = new ArrayList<StringBuffer>();
				printNode(root, levelBuffers);
				for (StringBuffer buf : levelBuffers) {
					buffer.append("\n");
					buffer.append(buf);
				}
			}
		}
		buffer.append("\n Max PCR=" + this.pcr);
		return buffer.toString();
	}

	private void printNode(PathSynopsisNode node,
			ArrayList<StringBuffer> levelBuffers) {
		if (levelBuffers.size() - 1 <= node.getLevel()) {
			levelBuffers.add(new StringBuffer());
		}

		for (PathSynopsisNode child : node.getChildren()) {
			printNode(child, levelBuffers);
		}

		StringBuffer buf = levelBuffers.get(node.getLevel() - 1);
		String str = String
				.format("[%s:%s]  ",
						node.getPCR(),
						((node.getKind() == Kind.ATTRIBUTE.ID) ? "@" : "")
								+ String.format("(%s,%s,%s)",
										node.getURIVocID(),
										node.getPrefixVocID(),
										node.getLocalNameVocID()));
		buf.append(str);

		if (levelBuffers.size() - 1 > node.getLevel()) // child level exists
		{
			int indent = levelBuffers.get(node.getLevel() + 1).length()
					- buf.length();
			for (int i = indent + 2; i > 0; i--)
				buf.append(" ");
		}
	}

	public PathSynopsisNode[] getRoots() {
		int i = 0;
		while ((i < roots.length) && (roots[i] != null)) {
			i++;
		}
		PathSynopsisNode[] clone = new PathSynopsisNode[i];
		System.arraycopy(roots, 0, clone, 0, i);
		return clone;
	}

	public void setPcr(int pcr) {
		this.pcr = pcr;
	}

	public void setIndexNumber(int idxNo) {
		this.psIdxNo = idxNo;
	}

	public int getIndexNumber() {
		return psIdxNo;
	}

	public int getMaxStoredPCR() {
		return maxStoredPCR;
	}

	public void setMaxStoredPCR(int maxStoredPCR) {
		this.maxStoredPCR = maxStoredPCR;
	}

	public int getMaxPCR() {
		return pcr;
	}

	public void clearCache() {
		this.pathCache.clear();
	}
}


text:
import WebGLConstants from "./WebGLConstants.js";

/**
 * Winding order defines the order of vertices for a triangle to be considered front-facing.
 *
 * @enum {Number}
 */
const WindingOrder = {
  /**
   * Vertices are in clockwise order.
   *
   * @type {Number}
   * @constant
   */
  CLOCKWISE: WebGLConstants.CW,

  /**
   * Vertices are in counter-clockwise order.
   *
   * @type {Number}
   * @constant
   */
  COUNTER_CLOCKWISE: WebGLConstants.CCW,
};

/**
 * @private
 */
WindingOrder.validate = function (windingOrder) {
  return (
    windingOrder === WindingOrder.CLOCKWISE ||
    windingOrder === WindingOrder.COUNTER_CLOCKWISE
  );
};

export default Object.freeze(WindingOrder);


text:
package io.netty.handler.timeout;

import org.junit.Test;

import static io.netty.handler.timeout.IdleStateEvent.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasToString;

public class IdleStateEventTest {
    @Test
    public void testHumanReadableToString() {
        assertThat(FIRST_READER_IDLE_STATE_EVENT, hasToString("IdleStateEvent(READER_IDLE, first)"));
        assertThat(READER_IDLE_STATE_EVENT, hasToString("IdleStateEvent(READER_IDLE)"));
        assertThat(FIRST_WRITER_IDLE_STATE_EVENT, hasToString("IdleStateEvent(WRITER_IDLE, first)"));
        assertThat(WRITER_IDLE_STATE_EVENT, hasToString("IdleStateEvent(WRITER_IDLE)"));
        assertThat(FIRST_ALL_IDLE_STATE_EVENT, hasToString("IdleStateEvent(ALL_IDLE, first)"));
        assertThat(ALL_IDLE_STATE_EVENT, hasToString("IdleStateEvent(ALL_IDLE)"));
    }
}


text:
package net.violet.mynabaztag.form;

import java.util.ArrayList;
import java.util.List;

import net.violet.platform.dataobjects.MusicData;
import net.violet.platform.util.StringShop;

public final class MySrvSoundForm extends AbstractForm {

	private static final long serialVersionUID = 1L;

	private int user_id;
	private int user_main;
	private int langUser;
	private long srvSound_id;

	private String name = StringShop.EMPTY_STRING;

	private List<MusicData> sonList = new ArrayList<MusicData>();

	public int getLangUser() {
		return this.langUser;
	}

	public void setLangUser(int langUser) {
		this.langUser = langUser;
	}

	public List<MusicData> getSonList() {
		return this.sonList;
	}

	public void setSonList(List<MusicData> sonList) {
		this.sonList = sonList;
	}

	public int getUser_id() {
		return this.user_id;
	}

	public void setUser_id(int user_id) {
		this.user_id = user_id;
	}

	public int getUser_main() {
		return this.user_main;
	}

	public void setUser_main(int user_main) {
		this.user_main = user_main;
	}

	public String getName() {
		return this.name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public long getSrvSound_id() {
		return this.srvSound_id;
	}

	public void setSrvSound_id(long music_id) {
		this.srvSound_id = music_id;
	}

}


text:
package com.supyuan.jfinal.component.oauth.util;

import com.supyuan.util.Config;

/**
 * Oauth 授权
 */
public class OathConfig {

	public static String getValue(String key) {
		return Config.getStr(key);
	}
}


text:
from irc3.testing import BotTestCase
from irc3.testing import MagicMock
from irc3.plugins import cron
from irc3.compat import asyncio

class MyCron:

    def __init__(self, bot):
        self.bot = bot

    @cron.cron('* * * * * *')
    def method(self):
        return self.bot

@cron.cron('* * * * * *')
@asyncio.coroutine
def function(bot):
    return bot

class TestCron(BotTestCase):

    config = dict(includes=['irc3.plugins.cron'])

    def test_add_remove_cron(self):
        bot = self.callFTU()
        plugin = bot.get_plugin(cron.Crons)
        plugin.connection_made()
        callback = MagicMock()
        c = bot.add_cron('* * * * *', callback)
        assert c.handle is not None
        assert len(plugin) == 1
        assert not callback.called
        plugin.remove_cron(c)
        assert len(plugin) == 0

    def test_connection_made(self):
        bot = self.callFTU()
        bot.include(__name__)
        plugin = bot.get_plugin(cron.Crons)
        assert not plugin.started
        plugin.connection_made()
        assert plugin.started

    def test_reload(self):
        bot = self.callFTU()
        bot.include(__name__)
        plugin = bot.get_plugin(cron.Crons)
        assert len(plugin) == 2
        plugin.before_reload()
        assert len(plugin) == 0
        assert not plugin.started
        plugin.after_reload()
        assert plugin.started

    def test_callable(self):
        loop = asyncio.new_event_loop()
        bot = self.callFTU(loop=loop)
        bot.include(__name__)
        plugin = bot.get_plugin(cron.Crons)

        results = []

        f = asyncio.Future(loop=loop)

        def complete(future):
            results.append(future.result())
            if len(results) == 2:
                f.set_result(results)

        for c in plugin:
            asyncio.ensure_future(
                c.next(), loop=loop).add_done_callback(complete)

        loop.run_until_complete(f)
        assert results == [bot, bot]


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.ServiceModel;
using System.ServiceModel.Channels;

namespace AxoCover.Common.Extensions
{
  public static class NetworkingExtensions
  {
    public static readonly TimeSpan NetworkTimeout = TimeSpan.MaxValue;
    public static readonly TimeSpan SessionTimeout = TimeSpan.MaxValue;

    public static Binding GetServiceBinding(CommunicationProtocol protocol)
    {
      switch(protocol)
      {
        case CommunicationProtocol.Tcp:
          return GetTcpBinding();
        case CommunicationProtocol.MemoryPipe:
          return GetMemoryTypeBinding();
        default:
          throw new NotImplementedException();
      }
    }

    private static NetTcpBinding GetTcpBinding()
    {
      var binding = new NetTcpBinding(SecurityMode.None)
      {
        MaxReceivedMessageSize = int.MaxValue,
        ReceiveTimeout = TimeSpan.MaxValue,
        SendTimeout = NetworkTimeout,
        OpenTimeout = NetworkTimeout,
        CloseTimeout = NetworkTimeout
      };
      binding.ReliableSession.Enabled = true;
      binding.ReliableSession.InactivityTimeout = SessionTimeout;
      binding.ReliableSession.Ordered = true;
      return binding;
    }

    private static Binding GetMemoryTypeBinding()
    {
      var binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None)
      {
        MaxReceivedMessageSize = int.MaxValue,
        ReceiveTimeout = TimeSpan.MaxValue,
        SendTimeout = NetworkTimeout,
        OpenTimeout = NetworkTimeout,
        CloseTimeout = NetworkTimeout
      };
      return binding;
    }

    public static Uri GetServiceAddress(CommunicationProtocol protocol)
    {
      switch (protocol)
      {
        case CommunicationProtocol.Tcp:
          return GetTcpAddress();
        case CommunicationProtocol.MemoryPipe:
          return GetMemoryTypeAddress();
        default:
          throw new NotImplementedException();
      }
    }

    private static Uri GetTcpAddress(int minPort = 49152, int maxPort = IPEndPoint.MaxPort)
    {
      var ipProperties = IPGlobalProperties.GetIPGlobalProperties();

      var usedPorts = new List<int>();
      usedPorts.AddRange(ipProperties
        .GetActiveTcpConnections()
        .Select(p => p.LocalEndPoint.Port));
      usedPorts.AddRange(ipProperties
        .GetActiveTcpListeners()
        .Select(p => p.Port));

      var random = new Random();
      var portCount = maxPort - minPort;
      var portToTest = random.Next(minPort, maxPort);
      for (var portIndex = 0; portIndex < portCount; portIndex++, portToTest++)
      {
        if (portToTest > maxPort)
        {
          portToTest = minPort;
        }

        if (usedPorts.Contains(portToTest)) continue;

        try
        {
          var tcpListener = new TcpListener(IPAddress.Loopback, portToTest);
          tcpListener.Start();
          tcpListener.Stop();
          return new Uri($"net.tcp://{IPAddress.Loopback}:{portToTest}");
        }
        catch
        {

        }
      }

      throw new Exception("All ports in the specified segment are in use.");
    }

    private static Uri GetMemoryTypeAddress()
    {
      return new Uri($"net.pipe://localhost/axoCover-runner/" + Guid.NewGuid().ToString());
    }
  }
}


text:
using System;
using System.Diagnostics;

namespace Roslyn.VisualStudio.Test.Utilities.InProcess
{
    internal class VisualStudio_InProc : InProcComponent
    {
        private VisualStudio_InProc() { }

        public static VisualStudio_InProc Create()
        {
            return new VisualStudio_InProc();
        }

        new public void WaitForApplicationIdle()
        {
            InProcComponent.WaitForApplicationIdle();
        }

        new public void WaitForSystemIdle()
        {
            InProcComponent.WaitForSystemIdle();
        }

        new public bool IsCommandAvailable(string commandName)
        {
            return InProcComponent.IsCommandAvailable(commandName);
        }

        new public void ExecuteCommand(string commandName, string args = "")
        {
            InProcComponent.ExecuteCommand(commandName, args);
        }

        public void ActivateMainWindow()
        {
            InvokeOnUIThread(() =>
            {
                var dte = GetDTE();

                var activeVisualStudioWindow = (IntPtr)dte.ActiveWindow.HWnd;
                Debug.WriteLine($"DTE.ActiveWindow.HWnd = {activeVisualStudioWindow}");

                if (activeVisualStudioWindow == IntPtr.Zero)
                {
                    activeVisualStudioWindow = (IntPtr)dte.MainWindow.HWnd;
                    Debug.WriteLine($"DTE.MainWindow.HWnd = {activeVisualStudioWindow}");
                }

                IntegrationHelper.SetForegroundWindow(activeVisualStudioWindow);
            });
        }

        public void Quit()
        {
            GetDTE().Quit();
        }
    }
}


text:
var gulp = require('gulp');
var autoprefixer = require('gulp-autoprefixer');


text:
using System;
using System.ComponentModel;
using System.Windows;
using System.Xml;
using System.Xml.Serialization;

namespace SharpLib.Docking
{
    [Serializable]
    public abstract class LayoutElement : DependencyObject, ILayoutElement
    {
        #region Константы

        /// <summary>
        /// Название поля XML
        /// </summary>
        internal const string XML_INTERNAL_DESC = "InternalDescription";

        /// <summary>
        /// Название поля XML
        /// </summary>
        internal const string XML_LAST_ACTIVATION_TIME_STAMP = "LastActivationTimeStamp";

        #endregion

        #region Поля

        [NonSerialized]
        private ILayoutContainer _parent;

        [NonSerialized]
        private ILayoutRoot _root;

        #endregion

        #region Свойства

        /// <summary>
        /// Тестовое описание (для внутреннего использования в отладке)
        /// </summary>
        [XmlIgnore]
        public string InternalDesc { get; set; }

        [XmlIgnore]
        public ILayoutContainer Parent
        {
            get { return _parent; }
            set
            {
                if (_parent != value)
                {
                    var oldValue = _parent;
                    var oldRoot = _root;
                    RaisePropertyChanging("Parent");
                    OnParentChanging(oldValue, value);
                    _parent = value;
                    OnParentChanged(oldValue, value);

                    _root = Root;
                    if (oldRoot != _root)
                    {
                        OnRootChanged(oldRoot, _root);
                    }

                    RaisePropertyChanged("Parent");

                    var root = Root as LayoutRoot;
                    if (root != null)
                    {
                        root.FireLayoutUpdated();
                    }
                }
            }
        }

        public ILayoutRoot Root
        {
            get
            {
                var parent = Parent;

                while (parent != null && (!(parent is ILayoutRoot)))
                {
                    parent = parent.Parent;
                }

                return parent as ILayoutRoot;
            }
        }

        #endregion

        #region События

        [field: NonSerialized]
        [field: XmlIgnore]
        public event PropertyChangedEventHandler PropertyChanged;

        [field: NonSerialized]
        [field: XmlIgnore]
        public event PropertyChangingEventHandler PropertyChanging;

        #endregion

        #region Конструктор

        internal LayoutElement()
        {
        }

        #endregion

        #region Методы

        protected virtual void OnParentChanging(ILayoutContainer oldValue, ILayoutContainer newValue)
        {
        }

        protected virtual void OnParentChanged(ILayoutContainer oldValue, ILayoutContainer newValue)
        {
        }

        protected virtual void OnRootChanged(ILayoutRoot oldRoot, ILayoutRoot newRoot)
        {
            if (oldRoot != null)
            {
                ((LayoutRoot)oldRoot).OnLayoutElementRemoved(this);
            }
            if (newRoot != null)
            {
                ((LayoutRoot)newRoot).OnLayoutElementAdded(this);
            }
        }

        protected virtual void RaisePropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        protected virtual void RaisePropertyChanging(string propertyName)
        {
            if (PropertyChanging != null)
            {
                PropertyChanging(this, new PropertyChangingEventArgs(propertyName));
            }
        }

        public virtual void ConsoleDump(int tab)
        {
            // Trace.Write(new string(' ', tab * 4));
            // Trace.WriteLine(ToString());
        }

        /// <summary>
        /// Текстовое представление объекта
        /// </summary>
        public override string ToString()
        {
            if (InternalDesc.IsValid())
            {
                return string.Format("{0} ({1})", InternalDesc, base.ToString());
            }

            return base.ToString();
        }

        /// <summary>
        /// Сохранине в Xml параметра "Description"
        /// </summary>
        protected void WriteXmlInternalDesc(XmlWriter writer)
        {
            if (InternalDesc.IsValid())
            {
                writer.WriteAttributeString(XML_INTERNAL_DESC, InternalDesc);
            }
        }

        /// <summary>
        /// Чтение из Xml параметра "Description"
        /// </summary>
        protected void ReadXmlInternalDesc(XmlReader reader)
        {
            if (reader.MoveToAttribute(XML_INTERNAL_DESC))
            {
                InternalDesc = reader.Value;
            }
        }

        #endregion
    }
}


text:
exports.up = async knex => {
  await knex.schema.alterTable('search_job', table => {
    table.datetime('tweetsStart')
    table.datetime('tweetsEnd')
  })
}

exports.down = async knex => {
  return knex.schema.alterTable('search_job', table => {
    table.dropColumn('tweetsStart')
    table.dropColumn('tweetsEnd')
  })
}


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model common\models\SearchActiveRecordLog */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin([
        'action' => ['index'],
        'method' => 'get',
    ]); ?>

    <?= $form->field($model, 'id') ?>

    <?= $form->field($model, 'action') ?>

    <?= $form->field($model, 'model') ?>

    <?= $form->field($model, 'idModel') ?>

    <?= $form->field($model, 'field') ?>

    <?php // echo $form->field($model, 'From') ?>

    <?php // echo $form->field($model, 'To') ?>

    <?php // echo $form->field($model, 'creationdate') ?>

    <?php // echo $form->field($model, 'userid') ?>

        <?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
        <?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>

    <?php ActiveForm::end(); ?>


text:
A Tooltip is useful to show information on hover in any kind of component. We have a component that can be used as a **decorator** for any kind of component. You just have to take into account that the overflow in the component should be visible.

<!-- example -->
```jsx
import Button from 'react-toolbox/lib/button';
import Tooltip from 'react-toolbox/lib/tooltip';

const TooltipButton = Tooltip(Button);
const TooltipInput = Tooltip(Input);

const TooltipTest = () => (
  <div>
    <TooltipButton label='Bookmark' icon='bookmark' raised primary tooltip='Bookmark Tooltip' tooltipDelay={1000} />
    <TooltipButton icon='add' floating accent tooltip='Floating Tooltip' />
    <TooltipInput tooltip='lorem ipsum...' />
  </div>
);
```

## Properties

In any component you decorate with the Tooltip you'd get some additional props:

| Name      | Type      | Default         | Description|
|:-----|:-----|:-----|:-----|
| `tooltip`     | `String`  |  | The text string to use for the tooltip.|
| `tooltipDelay`     | `Number`  |  | Amount of time in miliseconds spent before the tooltip is visible.|
| `tooltipHideOnClick`     | `Boolean`  | `true` | If true, the Tooltip hides after a click in the host component. |


text:
<?php

namespace Doctrine\SkeletonMapper\Hydrator;

/**
 * Base class for object hydrators to extend from.
 *
 * @author Jonathan H. Wage <jonwage@gmail.com>
 */
abstract class ObjectHydrator implements ObjectHydratorInterface
{
}


text:
package mysql

import (
	// "crypto/md5"
	"fmt"

	"database/sql"
	_ "github.com/go-sql-driver/mysql"

	"go-bro/broker"
	"go-bro/config"
	"go-bro/service/common"
)

type MysqlService struct {
	db   sql.DB
	conf config.ServiceConfig
}

func New(conf config.ServiceConfig) *MysqlService {

	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/", conf.Username, conf.Password, conf.Host, conf.Port)
	conn, err := sql.Open("mysql", dsn)
	defer conn.Close()

	if err != nil {
		panic(err.Error())
	}

	// connectError := conn.Ping()
	// if connectError != nil {
	// 	panic("Could not connect: " + connectError.Error())
	// }

	return &MysqlService{db: *conn, conf: conf}
}

func (s MysqlService) Create(serviceInstance string, req broker.ServiceRequest, planConfig config.PlanConfig) error {

	// connection.execute("CREATE DATABASE IF NOT EXISTS #{connection.quote_table_name(database_name)}")
	sql := fmt.Sprintf("CREATE DATABASE `%s`", serviceInstance)
	_, err := s.db.Exec(sql)
	return err
}

func (s MysqlService) Destroy(serviceInstance string) error {

	_, err := s.db.Exec(fmt.Sprintf("DROP DATABASE `%s`", serviceInstance))
	return err
}

func (s MysqlService) Bind(serviceInstance string, bindID string, req broker.BindRequest, planConfig config.PlanConfig) (resp broker.BindResponse, err error) {

	cred := broker.BindCredentials{Host: s.conf.Host, Port: s.conf.Port}

	// md5Sum := md5.Sum([]byte(bindID))
	// cred.Username = fmt.Sprintf("%x", md5Sum[0:8]) //Mysql supports username <= 16 chars.

	cred.Username = bindID[0:16] //Mysql supports username <= 16 chars.
	cred.Password = utils.Rand_str(16)
	cred.Database = serviceInstance
	cred.Uri = fmt.Sprintf("mysql://%s:%s@%s:%d/%s", cred.Username, cred.Password, cred.Host, cred.Port, cred.Database)

	resp = broker.BindResponse{Credentials: cred}

	sql := fmt.Sprintf("CREATE USER '%s'@'%%' IDENTIFIED BY '%s'", cred.Username, cred.Password)
	_, err = s.db.Exec(sql)
	if err != nil {
		return
	}

	sql = fmt.Sprintf("GRANT ALL ON `%s`.* TO '%s'@'%%' WITH MAX_USER_CONNECTIONS %d", cred.Database, cred.Username, planConfig.Concurrency)
	_, err = s.db.Exec(sql)
	if err != nil {
		return
	}

	_, err = s.db.Exec("FLUSH PRIVILEGES")
	return

	return broker.BindResponse{}, nil
}

func (s MysqlService) Unbind(serviceInstance string, bindID string) error {

	sql := fmt.Sprintf("DROP USER '%s'", bindID[0:16])
	_, err := s.db.Exec(sql)
	if err != nil {
		return err
	}

	_, err = s.db.Exec("FLUSH PRIVILEGES")
	return err
}