text:
package com.innavace.ds;

import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: sstacha
 * Date: 6/21/13
 * Time: 12:17 PM
 * Handles basic data conversions from string to another type
 */
public class Convert {
    public static Logger log = Logger.getLogger(Convert.class);
    private static final String HEXES = "0123456789ABCDEF";

    // ---------------------------------------------------------- toDate -
    /**
     *  Attempts to parse a String to a java.util.Date
     *  datatype.
     *
     *@param	text_date		generic string to be converted to Date
     *@param    parser          how to format the date
     *@return				    Date value converted
     */
    public static synchronized Date parseDate(String text_date, SimpleDateFormat parser)
    {
        Date theDate = null;
        //log.debug("date string is: " + text_date);
        if (parser != null)
        {
            log.debug("format mask is: " + parser.toPattern());
            try {theDate = parser.parse(text_date);}
            catch (Exception ex) { log.debug("exception when attempting to convert: " + ex.getMessage()); }
        }
        return theDate;
    }
    public static synchronized Date parseDate(String text_date, DateFormat parser)
    {
        Date theDate = null;
        //log.finest("date string is: " + text_date);
        if (parser != null)
        {
            try {theDate = parser.parse(text_date);}
            catch (Exception ex) { log.debug("exception when attempting to convert: " + ex.getMessage()); }
        }
        return theDate;
    }

    // ---------------------------------------------------------- toDate -
    /**
     *  Converts an Object to a java.util.Date
     *  datatype.
     *
     *@param	object		generic object to be converted to Date
     *@return				Date value converted
     */
    public static synchronized Date toDate(Object object)
    {
        //log.finest("converting to a date...");
        Date value = null;
        String string = "";
        SimpleDateFormat sdf = new SimpleDateFormat();
        //DateFormat df = null;

        if (object != null)
        {
            if (object instanceof Date)
                return (Date)object;

            if (object instanceof String)
            {
                //log.finest("object is a string...");
                // try and make it a date type if we have a value
                if (((String)object).length() > 0)
                {
                    string = (String)object;
                    //log.finest("starting string is: " + string);

                    // try the basic formats first
                    if (value == null)
                        value = parseDate(string, DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT));
                    if (value == null)
                        value = parseDate(string, DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT));
                    if (value == null)
                        value = parseDate(string, DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.SHORT));
                    if (value == null)
                        value = parseDate(string, DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL));
                    // try some of the common custom formats: NOTE: try in most specific to least specific to prevent errors
                    sdf.applyPattern("EEE MMM d HH:mm:ss z yyyy");
                    if (value == null)
                        value = parseDate(string, sdf);
                    sdf.applyPattern("yyyy-MMM-dd'T'HH:mm:ss.SZ");
                    if (value == null)
                        value = parseDate(string, sdf);
                    sdf.applyPattern("yyyy-MM-dd'T'HH:mm:ss.SZ");
                    if (value == null)
                        value = parseDate(string, sdf);
                    sdf.applyPattern("yyyyMMMdd'T'HH:mm:ss.SZ");
                    if (value == null)
                        value = parseDate(string, sdf);
                    sdf.applyPattern("yyyyMMdd'T'HH:mm:ss.SZ");
                    if (value == null)
                        value = parseDate(string, sdf);
                    sdf.applyPattern("yyyyMMMdd'T'HHmmss.SZ");
                    if (value == null)
                        value = parseDate(string, sdf);
                    sdf.applyPattern("yyyyMMdd'T'HHmmss.SZ");
                    if (value == null)
                        value = parseDate(string, sdf);
                    sdf.applyPattern("yyyy-MMM-dd HH:mm:ss.SZ");
                    if (value == null)
                        value = parseDate(string, sdf);
                    sdf.applyPattern("yyyy-MM-dd HH:mm:ss.SZ");
                    if (value == null)
                        value = parseDate(string, sdf);
                    sdf.applyPattern("yyyy-MMM-dd'T'HH:mm:ssZ");
                    if (value == null)
                        value = parseDate(string, sdf);
                    sdf.applyPattern("yyyy-MM-dd'T'HH:mm:ssZ");
                    if (value == null)
                        value = parseDate(string, sdf);
                    sdf.applyPattern("yyyyMMMdd'T'HH:mm:ssZ");
                    if (value == null)
                        value = parseDate(string, sdf);
                    sdf.applyPattern("yyyyMMdd'T'HH:mm:ssZ");
                    if (value == null)
                        value = parseDate(string, sdf);
                    sdf.applyPattern("yyyyMMMdd'T'HHmmssZ");
                    if (value == null)
                        value = parseDate(string, sdf);
                    sdf.applyPattern("yyyyMMdd'T'HHmmssZ");
                    if (value == null)
                        value = parseDate(string, sdf);
                    sdf.applyPattern("yyyy-MMM-dd HH:mm:ssZ");
                    if (value == null)
                        value = parseDate(string, sdf);
                    sdf.applyPattern("yyyy-MM-dd HH:mm:ssZ");
                    if (value == null)
                        value = parseDate(string, sdf);
                    sdf.applyPattern("yyyy-MMM-dd'T'HH:mm:ss.S");
                    if (value == null)
                        value = parseDate(string, sdf);
                    sdf.applyPattern("yyyy-MM-dd'T'HH:mm:ss.S");
                    if (value == null)
                        value = parseDate(string, sdf);
                    sdf.applyPattern("yyyyMMdd'T'HH:mm:ss.S");
                    if (value == null)
                        value = parseDate(string, sdf);
                    sdf.applyPattern("yyyyMMMdd'T'HH:mm:ss.S");
                    if (value == null)
                        value = parseDate(string, sdf);
                    sdf.applyPattern("yyyyMMdd'T'HHmmss.S");
                    if (value == null)
                        value = parseDate(string, sdf);
                    sdf.applyPattern("yyyy-MMM-dd HH:mm:ss.S");
                    if (value == null)
                        value = parseDate(string, sdf);
                    sdf.applyPattern("yyyy-MM-dd HH:mm:ss.S");
                    if (value == null)
                        value = parseDate(string, sdf);
                    sdf.applyPattern("yyyy-MM-dd'T'HH:mm:ss");
                    if (value == null)
                        value = parseDate(string, sdf);
                    sdf.applyPattern("yyyy-MMM-dd'T'HH:mm:ss");
                    if (value == null)
                        value = parseDate(string, sdf);
                    sdf.applyPattern("yyyyMMdd'T'HH:mm:ss");
                    if (value == null)
                        value = parseDate(string, sdf);
                    sdf.applyPattern("yyyyMMMdd'T'HHmmss");
                    if (value == null)
                        value = parseDate(string, sdf);
                    sdf.applyPattern("yyyyMMdd'T'HHmmss");
                    if (value == null)
                        value = parseDate(string, sdf);
                    sdf.applyPattern("yyyy-MMM-dd HH:mm:ss");
                    if (value == null)
                        value = parseDate(string, sdf);
                    sdf.applyPattern("yyyy-MM-dd HH:mm:ss");
                    if (value == null)
                        value = parseDate(string, sdf);
                    sdf.applyPattern("dd-MMM-yyyy HH:mm:ss");
                    if (value == null)
                        value = parseDate(string, sdf);
                    sdf.applyPattern("dd-MMM-yyyy");
                    if (value == null)
                        value = parseDate(string, sdf);
                    sdf.applyPattern("dd MMM yyyy");
                    if (value == null)
                        value = parseDate(string, sdf);
                    sdf.applyPattern("dd/MM/yyyy");
                    if (value == null)
                        value = parseDate(string, sdf);
                    sdf.applyPattern("dd/MM/yy");
                    if (value == null)
                        value = parseDate(string, sdf);
                    sdf.applyPattern("d/MM/yyyy HH:mm:ss a");
                    if (value == null)
                        value = parseDate(string, sdf);
                    sdf.applyPattern("d/MM/yyyy HH:mm:ss");
                    if (value == null)
                        value = parseDate(string, sdf);
                    sdf.applyPattern("d/MM/yyyy");
                    if (value == null)
                        value = parseDate(string, sdf);
                    sdf.applyPattern("d/M/yyyy");
                    if (value == null)
                        value = parseDate(string, sdf);
                    sdf.applyPattern("d/M/yy");
                    if (value == null)
                        value = parseDate(string, sdf);
                    sdf.applyPattern("dd.MM.yyyy");
                    if (value == null)
                        value = parseDate(string, sdf);
                    sdf.applyPattern("dd.MM.yy");
                    if (value == null)
                        value = parseDate(string, sdf);
                    sdf.applyPattern("d.MM.yyyy");
                    if (value == null)
                        value = parseDate(string, sdf);
                    sdf.applyPattern("d.M.yyyy");
                    if (value == null)
                        value = parseDate(string, sdf);
                    sdf.applyPattern("d.M.yy");
                    if (value == null)
                        value = parseDate(string, sdf);
                    sdf.applyPattern("yyy.MM.dd");
                    if (value == null)
                        value = parseDate(string, sdf);
                    sdf.applyPattern("yyyy-MM-dd");
                    if (value == null)
                        value = parseDate(string, sdf);
                    sdf.applyPattern("yyyyMMdd");
                    if (value == null)
                        value = parseDate(string, sdf);
                    if (value == null)
                        log.debug("attempted to parse date string but didn't find a match!");
                }
            }

            if (object instanceof Number)
            {
                try
                {
                    log.debug("attempting to convert to long");
                    long long_value = ((Number)object).longValue();
                    value = new Date(long_value);
                }
                catch (Exception ex)
                {
                    log.error("Exception occured converting Number <"	+ object.toString()	+ "> to a Date");
                }
            }
        }

        return value;
    }

    // ---------------------------------------------------------- toBool -
    /**
    *  Converts to a boolean value.
    *
    *@param	object		generic object to be converted to int
    *@return			boolean value converted
    */
    public static synchronized boolean toBool(Object object)
    {
        boolean value = false;
        boolean set = false;
        String string;

        int integer;

        log.debug("attempting to convert generic object to a boolean value...");
        log.debug("object: " + object);

        if (object != null)
        {
            if (object instanceof String)
            {
                log.debug("is instance of String...");
                // try and make it an integer type if we have a value
                if (((String)object).length() > 0)
                {
                    string = (String)object;
                    try
                    {
                        if (string.equalsIgnoreCase("YES") || string.equalsIgnoreCase("TRUE") || string.equalsIgnoreCase("Y") || string.equalsIgnoreCase("T"))
                        {
                            value = true;
                            set = true;
                        }
                        if (string.equalsIgnoreCase("NO") || string.equalsIgnoreCase("FALSE") || string.equalsIgnoreCase("N") || string.equalsIgnoreCase("F"))
                        {
                            value = false;
                            set = true;
                        }
                        // note: setting the object back to an integer will cause the number part next to fire
                        if (!set)
                            object = new Integer((String)object);
                    }
                    catch (NumberFormatException nfe)
                    {
                        log.error("Exception occured converting String <"	+ object.toString()	+ "> to boolean");
                    }
                }
            }
            if (object instanceof Boolean)
            {
                log.debug("is instance of Boolean...");
                value = ((Boolean)object).booleanValue();
            }
            // any integer not 0 is true...
            if (object instanceof Number)
            {
                log.debug("is instance of Number...");
                try
                {
                    integer = ((Number)object).intValue();
                    if (integer != 0)
                        value = true;
                }
                catch (Exception ex)
                {
                    log.error("Exception occured converting Number <"	+ object.toString()	+ "> to integer");
                }
            }
        }
        return value;
    }

    // ----------------------------------------------------------- toLong -
    /**
    *  Converts to a Long value.
    *
    *@param	object		generic object to be converted to Long
    *@return			Long value converted
    */
    public static Long toLong(Object object)
    {
        return new Long(toLng(object));
    }

    // ----------------------------------------------------------- toLng -
    /**
    *  Converts to a long value.
    *
    *@param	object		generic object to be converted to long
    *@return			long value converted
    */
    public static synchronized long toLng(Object object)
    {
        long value = 0L;

        if (object != null)
        {
            if (object instanceof String)
            {
                // try and make it an integer type if we have a value
                if (((String)object).length() > 0)
                {
                    try
                    {
                        value = Long.parseLong((String)object);
                    }
                    catch (NumberFormatException nfe)
                    {
                        log.error("Exception occured converting String <"	+ object.toString()	+ "> to long");
                    }
                }
            }
            if (object instanceof Number)
            {
                try
                {
                    value = ((Number)object).longValue();
                }
                catch (Exception ex)
                {
                    log.error("Exception occured converting Number <"	+ object.toString()	+ "> to long");
                }
            }
        }
        return value;
    }

    // ----------------------------------------------------------- toInteger -
    /**
    *  Converts to a Integer value.
    *
    *@param	object		generic object to be converted to int
    *@return			Integer value converted
    */
    public static Integer toInteger(Object object)
    {
        return new Integer(toInt(object));
    }
    // ----------------------------------------------------------- toInt -
    public static synchronized int toInt(boolean value)
    {
        if (value)
            return 1;
        else
            return 0;
    }

    // ----------------------------------------------------------- toInt -
    /**
    *  Converts to a int value
    *
    *@param	object		generic object to be converted to int
    *@return			int value converted
    */
    public static synchronized int toInt(Object object)
    {
        int integer = 0;

        if (object != null)
        {
            if (object instanceof String)
            {
                //removing spaces
                String strToUse =   ((String)object).trim();
                // try and make it an integer type if we have a value
                if (strToUse.length() > 0)
                {
                    try
                    {
                        // try first to check for a true / false and convert
                        if (strToUse.equalsIgnoreCase("TRUE"))
                            integer = 1;
                        else if (strToUse.equalsIgnoreCase("FALSE"))
                            integer = 0;
                        else
                            integer = Integer.parseInt(strToUse);
                    }
                    catch (NumberFormatException nfe)
                    {
                        log.error("Exception occured converting String <"	+ object.toString()	+ "> to integer");
                    }
                }
            }
            if (object instanceof Number)
            {
                try
                {
                    integer = ((Number)object).intValue();
                }
                catch (Exception ex)
                {
                    log.error("Exception occured converting Number <"	+ object.toString()	+ "> to integer");
                }
            }
        }
        return integer;
    }

    // ----------------------------------------------------------- toDouble -
    /**
    *  Converts to a Double value.
    *
    *@param	object		generic object to be converted to Double
    *@return			Double value converted
    */
    public static synchronized Double toDouble(Object object)
    {
        return new Double(toDbl(object));
    }

    // ----------------------------------------------------------- toDbl -
    /**
    *  Converts to a double value
    *
    *@param	object		generic object to be converted to double
    *@return			double value converted
    */
    public static synchronized double toDbl(Object object)
    {
        double dbl = 0.0;

        if (object != null)
        {
            if (object instanceof String)
            {
                // try and make it an integer type if we have a value
                if (((String)object).length() > 0)
                {
                    try
                    {
                        dbl = Double.parseDouble((String)object);
                    }
                    catch (NumberFormatException nfe)
                    {
                        log.error("Exception occured converting String <"	+ object.toString()	+ "> to double");
                    }
                }
            }
            if (object instanceof Number)
            {
                try
                {
                    dbl = ((Number)object).doubleValue();
                }
                catch (Exception ex)
                {
                    log.error("Exception occured converting Number <"	+ object.toString()	+ "> to double");
                }
            }
        }
        return dbl;
    }

	// ----------------------------------------------------------- toFloat -
	/**
	*  Converts to a Float value.
	*
	*@param	object		generic object to be converted to Float
	*@return			Float value converted
	*/
	public static synchronized Float toFloat(Object object)
	{
	    return new Float(toFlt(object));
	}

	// ----------------------------------------------------------- toFlt -
	/**
	*  Converts to a float value
	*
	*@param	object		generic object to be converted to float
	*@return			float value converted
	*/
	public static synchronized float toFlt(Object object)
	{
	    float value = 0;

	    if (object != null)
	    {
	        if (object instanceof String)
	        {
	            // try and make it an integer type if we have a value
	            if (((String)object).length() > 0)
	            {
	                try
	                {
	                    value = Float.parseFloat((String)object);
	                }
	                catch (NumberFormatException nfe)
	                {
	                    log.error("Exception occured converting String <"	+ object.toString()	+ "> to float");
	                }
	            }
	        }
	        if (object instanceof Number)
	        {
	            try
	            {
	                value = ((Number)object).floatValue();
	            }
	            catch (Exception ex)
	            {
	                log.error("Exception occured converting Number <"	+ object.toString()	+ "> to float");
	            }
	        }
	    }
	    return value;
	}

	// ----------------------------------------------------------- toShort -
	/**
	*  Converts to a Short value.
	*
	*@param	object		generic object to be converted to Short
	*@return			Short value converted
	*/
	public static synchronized Short toShort(Object object)
	{
	    return new Short(toSht(object));
	}

	// ----------------------------------------------------------- toSht -
	/**
	*  Converts to a short value
	*
	*@param	object		generic object to be converted to float
	*@return			float value converted
	*/
	public static synchronized short toSht(Object object)
	{
	    short value = 0;

	    if (object != null)
	    {
	        if (object instanceof String)
	        {
	            // try and make it an integer type if we have a value
	            if (((String)object).length() > 0)
	            {
	                try
	                {
	                    value = Short.parseShort((String)object);
	                }
	                catch (NumberFormatException nfe)
	                {
	                    log.error("Exception occured converting String <"	+ object.toString()	+ "> to short");
	                }
	            }
	        }
	        if (object instanceof Number)
	        {
	            try
	            {
	                value = ((Number)object).shortValue();
	            }
	            catch (Exception ex)
	            {
	                log.error("Exception occured converting Number <"	+ object.toString()	+ "> to short");
	            }
	        }
	    }
	    return value;
	}

	// ----------------------------------------------------------- toBigDecimal -
	/**
	*  Converts to a BigDecimal value.
	*
	*@param	object		generic object to be converted to Long
	*@return			Long value converted
	*/

	public static synchronized BigDecimal toBigDecimal(Object object) {return Convert.toBigDecimal(object, false);}
	public static synchronized BigDecimal toBigDecimal(Object object, boolean returnNulls)
	{
		if (object == null)
		{
			if (returnNulls)
				return null;
			else
				return new BigDecimal(0);
		}

		if (object instanceof Number)
		{
			if (object instanceof BigInteger)
				return new BigDecimal((BigInteger)object);
			if (object instanceof Double)
				return new BigDecimal((Double)object);
			if (object instanceof Long)
				return new BigDecimal((Long)object);
			if (object instanceof Integer)
				return new BigDecimal((Integer)object);
			if (object instanceof Float)
				return new BigDecimal((Float)object);
			if (object instanceof Short)
				return new BigDecimal((Short)object);
		}
	    return new BigDecimal(object.toString());
	}

    // -------------------------------------------------------- toString -
    /**
    *  Converts to a String value
    *
    * @param	object			generic object to be converted to string
    * @return         		string value converted
    */

    public static synchronized String toString(Object object)
    {
        return toString(object, false);
    }

    public static synchronized String toParameter(Date date) {return toString(date, "yyyy-MM-dd'T'HH:mm:ss.SZ");}
    public static synchronized String toString(Date date)  {return toString(date, "dd-MMM-yyyy");}
    public static synchronized String toString(Date date, String format)
    {
        String dateString = "";
        if (date != null)
        {
            SimpleDateFormat custom_format = new SimpleDateFormat(format);
            dateString = custom_format.format(date);
        }
        return dateString;
    }
    /**
     * Converts two Date objects to a string representation of the date range using the following rules:
     *   If date2 is null or date1 == date2:                 "1 Aug 2003"
     *   If date1 and date2 have the same month and year:    "1 - 5 Aug 2003"
     *   If date1 and date2 have the same year:              "1 Aug - 6 Sep 2003"
     *   If date1 and date2 are completely different:        "1 Aug 2002 - 7 Sep 2003"
     * @param date1 the start date
     * @param date2 the end date
     * @return a String representation of the date range
     */
    public static synchronized String toDateRange(Date date1, Date date2) {
        if(date1 != null) {
            Calendar c1 = new GregorianCalendar();
            c1.setTime(date1);
            c1 = new GregorianCalendar(c1.get(Calendar.YEAR), c1.get(Calendar.MONTH), c1.get(Calendar.DATE));
            if(date2 == null) {
                return toString(c1.getTime(), "d MMM yyyy");
            }
            else {
                Calendar c2 = new GregorianCalendar();
                c2.setTime(date2);
                c2 = new GregorianCalendar(c2.get(Calendar.YEAR), c2.get(Calendar.MONTH), c2.get(Calendar.DATE));
                if(c1.getTime().compareTo(c2.getTime()) == 0) {
                    return toString(c1.getTime(), "d MMM yyyy");
                }
                else if(c1.get(Calendar.MONTH) == c2.get(Calendar.MONTH) && c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR)) {
                    return toString(c1.getTime(), "d") + " - " + toString(c2.getTime(), "d MMM yyyy");
                }
                else {
                    if(c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR)) {
                        return toString(c1.getTime(), "d MMM") + " - " + toString(c2.getTime(), "d MMM yyyy");
                    }
                    else {
                        return toString(c1.getTime(), "d MMM yyyy") + " - " + toString(c2.getTime(), "d MMM YYYY");
                    }
                }
            }
        }
        return "";
    }
    public static synchronized String toDatabaseString(String string)
    {
        // escape all sql special chars for a value in a sql statement
        string = Convert.toString(string);
        return replace(string, "'", "''", "''");
    }
    public static synchronized String toDatabaseString(Date date)
    {
        if (date == null)
            return "NULL";
        SimpleDateFormat custom_format = new SimpleDateFormat("yyyy-MM-dd H:mm:ss");
        StringBuffer sql_date = new StringBuffer("{ts '");
        sql_date.append(custom_format.format(date)).append("'}");
        return sql_date.toString();
    }
    /**
     * @param object          Any object to convert to string
     * @param returnNulls     by default returns an empty string; true will return null
     *
     * @return string value   the string value converted
     */
    public static synchronized String toString(Object object, boolean returnNulls)
    {
        String string = "";

        if ((returnNulls) && (object == null))
            string = null;
        if (object != null)
        {
            if (object instanceof String)
                string = (String)object;
            else if (object instanceof java.util.Date)
            {
                Date date = (Date)object;
                SimpleDateFormat custom_format = new SimpleDateFormat("dd-MMM-yyyy");
                string = custom_format.format(date);
            }
            else
            {
                try
                {
                    string = object.toString();
                }
                catch (Exception ex)
                {
                    log.error("Exception occurred converting object to string");
                }
            }
        }
        return string;
    }
    public static synchronized String toDatabaseString(Collection list, String delimeter)
    {
        return toDatabaseString(list, delimeter, "");
    }
    public static synchronized String toDatabaseString(Object obj, String text_qualifier)
    {
        StringBuffer string = new StringBuffer();

        if (obj == null)
            string.append("NULL");
        else if (obj instanceof Date)
            string.append(Convert.toDatabaseString((Date)obj));
        else if (obj instanceof Boolean)
        {
            boolean bool = ((Boolean)obj).booleanValue();
            if (bool)
                string.append("1");
            else
                string.append("0");
        }
        else if (obj instanceof String)
        {
            // sas 01.03.12 - don't want to add quotes to hex strings for byte fields.
            // todo : later use an annotation instead of this assumption that everything starting with 0x is hex
            if (((String)obj).toUpperCase().trim().startsWith("0X"))
                string.append(Convert.toDatabaseString((String)obj));
            else
                string.append(text_qualifier).append(Convert.toDatabaseString((String)obj)).append(text_qualifier);
        }
        else if (Convert.isNumeric(Convert.toString(obj)))
            string.append(Convert.toString(obj));
        else
            string.append(text_qualifier).append(Convert.toDatabaseString(Convert.toString(obj))).append(text_qualifier);

        return string.toString();
    }
    public static synchronized String toDatabaseString(Collection list, String delimeter, String text_qualifier)
    {
        Iterator iterator;
        StringBuffer string = new StringBuffer();
        if (text_qualifier == null)
            text_qualifier = "";

        if (list != null && delimeter != null)
        {
            iterator = list.iterator();

            while (iterator.hasNext())
            {
                Object obj = iterator.next();

                if (string.length() > 0)
                    string.append(delimeter);
                string.append(toDatabaseString(obj, text_qualifier));
            }
        }
        return string.toString();
    }

    public static synchronized String toDebugString(Object _pojo)
    {
        Class dataClass = _pojo.getClass();
        StringBuffer data = new StringBuffer(100);
        data.append("\n");
        if (!dataClass.getName().equalsIgnoreCase("java.lang.Object"))
            data.append("---------- ").append(dataClass.getSimpleName()).append(" ----------\n");

        while ((dataClass != null) && (dataClass != Object.class))
        {
            Field fieldList[] = dataClass.getDeclaredFields();
            AccessibleObject.setAccessible(fieldList, true);
            StringBuffer fldstr = new StringBuffer(50);
            for (Field fld : fieldList)
            {
//                String typeclass = fld.getType().getName();
//                if (isValidType(fld.getType()))
//                {
                //data += "(" + typeclass + ")";
                fldstr.setLength(0);
                fldstr.append(fld.getName()).append(" = ");
                try
                {
                    if (fld.get(_pojo) != null && fld.get(_pojo).toString() != null && fld.get(_pojo).toString().length() > 0)
                        fldstr.append(fld.get(_pojo));
                }
                catch (IllegalAccessException iae)
                {
                    fldstr.append("????");
                }
                data.append(fldstr).append("\n");
//                }
//                else
//                    if (verbose)
//                        log.debug("(" + typeclass + ") " + fld.getName() + " skipped...");
            }
            dataClass = dataClass.getSuperclass();
        }
        data.append("-----------------------------------\n");
        return data.toString();
    }

    /**
     * @param 	list			list of items to be concated to a string
     * @return String containing a comma separated values from the collection
     */
    public static synchronized String toString(Collection list)
    {
        return toString(list, ", ", null);
    }
    /**
     * @param 	list			list of items to be concated to a string
     * @param	delimeter		string to use as the delimeter separate the list if items
     *
     * @return String containing a comma separated values from the collection
     **/
    public static synchronized String toString(Collection list, String delimeter)
    {
        return toString(list, delimeter, null);
    }
    public static synchronized String toString(Collection list, String delimeter, String text_qualifier)
    {
        Iterator iterator = null;
        String string = "";

        // todo: replace the string functions with a stringbuffer for the appending and return the toString()
        if (list != null && delimeter != null)
        {
            iterator = list.iterator();
            //iterator = list.listIterator();
            while (iterator.hasNext())
            {
                Object obj = iterator.next();
                if (string.length() > 0)
                    string += delimeter;
                if ((obj instanceof String) && (text_qualifier != null))
                    string += text_qualifier + Convert.toString(obj) + text_qualifier;
                else
                    string += Convert.toString(obj);
            }
        }
        return string;

    }
    /**
    *  parses a string to a list of strings given a delimiter.
    *
    * NOTE: will handle if 2 separators and return an empty value
    * Example: ,,2,3 will return 2 empty strings for index 1 & 2
    * then values 2 and 3 as a string for index 3 & 4.
    *
    *@param	string		the original string.
    *@param	delimeter	the delimter to separate strings on
    *@return			list of string values
    */
    // ------------------------------------------------------- toList -
    public static synchronized List<String> toList(String string, String delimeter)
    {
        // NOTE: tokenizer didn't work so doing the string manips myself
        int pos_start = 0;
        int pos_stop = 0;
        List<String> paramlist = new ArrayList<String>();

        if (string != null && delimeter != null)
        {
            while ((pos_stop = string.indexOf(delimeter, pos_start)) != -1)
            {
                if (pos_stop == 0)
                    paramlist.add("");
                else
                    paramlist.add(string.substring(pos_start, pos_stop));
                pos_start = pos_stop + delimeter.length();
            }
            if (pos_start != string.length())
                paramlist.add(string.substring(pos_start).trim());
        }
        return paramlist;

    }
    // -------------------------------------------------------- isNumeric -
    /**
     *  check if string contains only numbers
     *
     *@param	object		object to check
     *@return				if is numeric value
     */
    public static synchronized boolean isNumeric(Object object)
    {
        boolean is_digits = false;
        boolean has_decimal = false;

        String string = "";

        if (object == null)
            return false;
        // NOTE: byte, int, long, doubble, etc. all derive from number
        //		which by nature must be numeric
        if (object instanceof Number)
            return true;
        // try and convert everything else to a string and evaluate
        string = toString(object);
        if (string.length() > 0)
        {
            is_digits = true;
            char[] chars = string.toCharArray();
            for (int x = 0; x < chars.length; x++)
            {
                if (x == 0 && chars[x] == '-')
                    continue;
                if (!Character.isDigit(chars[x]))
                {
                    // we allow 1 and only 1 decimal
                    if ((Character.toString(chars[x])).equalsIgnoreCase("."))
                    {
                        if (has_decimal)
                        {
                            is_digits = false;
                            break;
                        }
                        else
                            has_decimal = true;
                    }
                    else
                    {
                        is_digits = false;
                        break;
                    }
                }
            }
        }
        return is_digits;
    }

	/**
	 * Round a float value to a specified number of decimal
	 * places.
	 *
	 * @param val the value to be rounded.
	 * @param places the number of decimal places to round to.
	 * @return val rounded to places decimal places.
	 */
	public static synchronized float round(float val, int places)
	{
		BigDecimal bd = new BigDecimal(Float.toString(val));
		bd = bd.setScale(places,BigDecimal.ROUND_HALF_UP);
		return bd.floatValue();
	}

    /**
     * Round a double value to a specified number of decimal
     * places.
     *
     * @param val the value to be rounded.
     * @param places the number of decimal places to round to.
     * @return val rounded to places decimal places.
     */
    public static synchronized double round(double val, int places)
    {
      // see the Javadoc about why we use a String in the constructor
      // http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigDecimal.html#BigDecimal(double)
      BigDecimal bd = new BigDecimal(Double.toString(val));
	  return round(bd, places);
    }

	public static synchronized double round(BigDecimal bd, int places)
	{
		bd = bd.setScale(places,BigDecimal.ROUND_HALF_UP);
		return bd.doubleValue();
	}

	/**
	 * Rounds the double value to the speicified decimal points and returns that number of decimal
	 * points as a String.  For example: 4 to 2 places would return 4.00
	 *
	 * @param val : the double value to set the number of decimal digits for
	 * @param places : the number of decimal digits to set
	 * @return String containing the right number of digits for the number
	 */
    public static synchronized String toString(double val, int places)
    {

        NumberFormat nf = NumberFormat.getNumberInstance(Locale.US);
		nf.setMaximumFractionDigits(places);
		nf.setMinimumFractionDigits(places);
        return nf.format(val);
    }

	/**
	 * Rounds the long value to the speicified decimal points and returns that number of decimal
	 * points as a String.  For example: 4 to 2 places would return 4.00
	 *
	 * @param val : the long value to set the number of decimal digits for
	 * @param places : the number of decimal digits to set
	 * @return String containing the right number of digits for the number
	 */
    public static synchronized String toString(long val, int places)
    {

        NumberFormat nf = NumberFormat.getNumberInstance(Locale.US);
		nf.setMaximumFractionDigits(places);
		nf.setMinimumFractionDigits(places);
        return nf.format(val);
    }

	public static synchronized String toHTML(String string)
	{
		string = Convert.toString(string);
		string = Convert.replace(string, "\n", "
");
		return string;
	}

    public static synchronized String toSHA1(String key, String value) {
        try {
            // Get an hmac_sha1 key from the raw key bytes
            byte[] keyBytes = key.getBytes();
            SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");

            // Get an hmac_sha1 Mac instance and initialize with the signing key
            Mac mac = Mac.getInstance("HmacSHA1");
            mac.init(signingKey);

            // Compute the hmac on input data bytes
            byte[] rawHmac = mac.doFinal(value.getBytes());

            //  Covert array of Hex bytes to a String
            return toHexString(rawHmac);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    public static synchronized String toHexString( byte [] raw ) {
        if ( raw == null ) {
            return null;
        }
        final StringBuilder hex = new StringBuilder( 2 * raw.length );
        for ( final byte b : raw ) {
            hex.append(HEXES.charAt((b & 0xF0) >> 4))
                .append(HEXES.charAt((b & 0x0F)));
        }
        return hex.toString();
    }
    // --------------------------------------------------------- replace -
     /**
      * Replaces all occurances of the specified sub-string to find with the
      * specified sub-string to replace with.
      *
      * @return The modified string.
      * @param	string			 The original string.
      * @param	replaceString The string to replace.
      * @param	substring			 The string to replace with.
      */
    public static synchronized String replace(String string, String replaceString, String substring)
    {
        return replace(string, replaceString, substring, null);
    }
    public static synchronized String replace(String string, String replaceString, String substring, String omit_string)
    {
	    int pos_start = 0;
	    int pos_stop;
        StringBuilder sb = new StringBuilder();

	    if (string == null)
	        string = "";
	    if (replaceString == null)
	        replaceString = "";
	    if (substring == null)
	        substring = "";
	    if (omit_string == null)
	        omit_string = "";
	    if (string.length() > 0 && replaceString.length() > 0)
	    {
	        while ((pos_stop = string.indexOf(replaceString, pos_start)) >= 0)
	        {
	            sb.append(string.substring(pos_start, pos_stop));
	            // we might have an omitted value
	            if (omit_string.length() > 0)
	            {
	                if (string.startsWith(omit_string, pos_stop))
	                {
	                    // omitted value: prepend the original string and move start to stop + omitstring length
	                    sb.append(omit_string);
	                    pos_start = pos_stop + omit_string.length();
	                    continue;
	                }
	            }
	            sb.append(substring);
	            pos_start = pos_stop + replaceString.length();
	        }
	        sb.append(string.substring(pos_start));
	    }
	    return sb.toString();
    }

    public static void main(String[] args)
    {
        DOMConfigurator.configure("/configs/log4j.xml");
//        System.out.println("Convert.round to 2 decimal points: " + Convert.round(20.1289,2));
//        System.out.println("Convert.round to 2 decimal points: " + Convert.round(20.0000,2));
//        System.out.println("Convert.rounding to 2 decimal points: " + Convert.round(20.1289,2));
//        System.out.println("Convert.rounding to 2 decimal points: " + Convert.round(20.0000,2));
//	    System.out.println("Rounded: " +  Convert.round((6666558899L * .001), 3));
//	    System.out.println("File Size: "+ Convert.toString((6666558899L * .001), 2) + "K");
//	    System.out.println("As Price $" + Convert.toString(55899, 2));
//        System.out.println("toInt" + Convert.toInteger("1019              ")+"good");
//        Date convertedDate = Convert.toDate("2014-02-28 00:00:00");
//        Date convertedDate = Convert.toDate("2014-02-28T00:00:00");
//        Date convertedDate = Convert.toDate("2014-02-28T00:00:00-06");
//        Date convertedDate = Convert.toDate("2014-02-28T00:00:00Z");
        Date convertedDate = Convert.toDate("2013-04-01 07:30:00");
        //Date convertedDate = Convert.toDate("20140228T000000.000-06");
        System.out.println(convertedDate);
    }

    // calls to database string with the default ' for character wrapping
    public static String toSQLString(Object object)
    {
        return toDatabaseString(object, "'");
    }

}


A Lovely remodeled 3bed/2bath Mid Century home with a two story guest cottage (ADU) tucked below the foothills with sweeping mountain views! The Main House features black granite kitchen countertops enhanced with stainless steel appliances and a farm sink. The dining and bedrooms have grayed refinished hardwood floors, vaulted ceilings, Custom barnwood walls, gas fireplace. This home has been expanded to include a self contained master suite with french doors that open out to a private deck that makes you feel as if you are in the canopy of the trees. Under the master suite is the Rec Room/Office/Bonus Rm. This home is the ultimate dual living/extended family set up. Located on a very quiet Cul-de-sac street with very little traffic and just around the corner to Monte Vista Elementary.


Share a video remixing a scene from your favorite commercial, music video or movie to stand a chance to win FREE CREDIT this week. Add the hashtag #reSkit and #skitsapp to each entry.
This week, we're changing up the rules. We will not be selecting winners solely by the number of likes. Instead, we will be looking for the funniest and most interesting videos.
Make sure you tell us where the scene you are remixing comes from.


text:
Q: How to add event listeners to an array of objects I have an array of objects (specifically easelJS images) - something like this:
var imageArray = new Array;
gShape  = new createjs.Shape();
// shape is something
imageArray.push(gShape);

What I want to do is have an event listener instead of:
gShape.addEventListener("click", function() {alert"stuff"});

I want the program to know specifically which region is clicked so that I can send an alert box in the following way:
imageArray[index].addEventListener("click", function(){
    alert " you clicked region number " + index}

A: Something like this should work:
for (var i = 0 ; i < imageArray.length ; ++i) {
    function(index) {
        imageArray[index].addEventListener("click", function() {
            alert ("You clicked region number: " + index");
        });
    } ( i);
}

The reason it works is because it creates a closure that holds the value of index that will be shown in the alert message. Each time through the loop creates another closure holding another value of index.

A: Sure. You can just use a closure to save the index of that iteration. Otherwise there are shared by the same function scope and will give you the value of the same iteration. Creating a separate function for each will save the state of that inside the function.
var imageArray = new Array;
gShape = new createjs.Shape();
 // shape is something
 imageArray.push(gShape); // Dumped all the objects

for (var i = 0; i < imageArray.length; i++) {
   (function(index) {
        imageArray[index].addEventListener("click", function() {
           console.log("you clicked region number " + index);
         })
   })(i);
}

or better
 for(var i = 0; i < imageArray.length; i++) {
       imageArray[i].addEventListener("click", bindClick(i));
 }

 function bindClick(i) {
    return function() {
        console.log("you clicked region number " + i);
    };
 }

ES6 to the rescue
let imageArray = [];
gShape = new createjs.Shape();
// shape is something
imageArray.push(gShape); // Dumped all the objects

for (let i = 0; i < imageArray.length; i++) {
  imageArray[i].addEventListener("click", function() {
    console.log("you clicked region number " + i);
  });
}

Using the let keyword creates a block scoping for the variable in iteration and will have the correct index when the event handler is invoked.

A: //gShape must be an array of HTMLElement
gShape.forEach(element => element.addEventListener("click", function () {
    // this, refers to the current element.
    alert ("You clicked region number: " + this.getAttribute('data-region'));
}));

A: Sure, a closure is the solution, but since he's got Ext loaded he might as well use it and get some very readable code. The index is passed as the second argument to Ext.Array.each (aliased to Ext.each).
Ext.each(imageArray, function(gShape, index) {
    gShape.addEventListener("click", function() {
        alert("You clicked region number " + index);
    });
});

A: This is what I'm using for div id's:
var array = ['all', 'what', 'you', 'want'];

function fName () {
    for (var i = 0; i < array.length; i++)
    document.getElementById(array[i]).addEventListener('click', eventFunction);
};

Good Luck!

A: A simple way to do this, is by calling a querySelectorAll() on all
the elements and using a loop to iterate and execute a function with the data of that specific array index once the EventListener is
triggered by the element clicked.
Snippet

Retrieving the id attribute of the clicked element

document.querySelectorAll('li').forEach(element => {
  element.addEventListener('click', () => {
    console.log(element.getAttribute('id'))
  })
})
li{cursor:pointer}

One

Two

Three

Four

redpajama_set_name: RedPajamaStackExchange


text:
Drawing Room Confessions
DRC Radio
THE BLIND MAN1
Evelyn Fishburn2
Juan Lucas Aisemberg3
Griselda Pollock4
Robrecht Vanderbeeken5
Falke Pisano6
Laure Prouvost7
David Lamelas8
Penelope Curtis9
Julian Assange10
Will McLean11
Nick Collett12
Helen Marten13
1. The Blind Man follows with a series of questions posed by an interviewer whose identity is concealed from the player. The Blind Man was an ephemeral publication founded in New York in 1917 by Marcel Duchamp, Beatrice Webb, and Henri-Pierre Roché. The magazine invited contributors to publish whatever they wanted, proclaiming on the front cover of the inaugural issue, "The second issue of The Blind Man will appear as soon as YOU have sent sufficient material for it".
2. Evelyn Fishburn is Professor Emeritus of Latin American Literary Studies at London Metropolitan University and holds an honorary senior research position at University College London. She has worked extensively on the Argentine writer Jorge Luis Borges.
3. Juan Lucas Aisemberg is a viola player with the Deutsche Opera Berlin and various chamber music ensembles. He is also dedicated to tango, jazz and other forms of popular music as a performer and as the founder of several groups.
4. Griselda Pollock is Professor of Social and Critical Histories of Art in the Department of Fine Art at the University of Leeds, England. Her main research interests are gender, race and class in the formations of modernism in late nineteenth-century Europe and America; the history of women in the visual arts, with a current project focusing on femininity, representation and modernity 1928-1968; and contemporary visual arts by women.
5. Robrecht Vanderbeeken is a philosopher currently doing post-doctoral research at University College Ghent on performance, fine art and the cultural-philosophical implications of technological evolutions. He has published widely on subjects ranging from metaphysics to aesthetics, and is a visiting lecturer at the Higher Institute of Fine Arts, Sint-Lucas Art Academy, Ghent University, Transmedia, and Brunel University London.
6. Dutch artist Falke Pisano is a long-time collaborator of Benoît Maire. Her work, based on immersive research, fluctuates between concrete and abstract, object-based and performative, often centered on a deconstruction of linguistic structures.
7. Laure Prouvost is an artist born in France, now living and working in London, who creates multi-media environments that often invoke loose narratives centred around a single event. Her work has been shown at Tate Britain, ICA (London), Serpentine Gallery, and the Sculpture Centre (New York). She is the recipient of the 2011 Max Mara Art Prize for Women.
8. David Lamelas is an artist born in Argentina. He lives in Los Angeles, Buenos Aires, and London.
9. Penelope Curtis is a British art historian, writer, and curator. The author of Sculpture 1900-1945: After Rodin (OUP, 1999) and Patio and Pavilion: The Place of Sculpture in Modern Architecture (Ridinghouse, 2007), she became Director of Tate Britain in 2010.
10. Julian Assange is known as the editor-in-chief and founder of WikiLeaks. Since November 2010, Assange has been subject to a European arrest warrant in response to a request by the Swedish police. In June 2012, he was granted diplomatic asylum by the Ecuadorean government and has been living inside the Embassy of Ecuador in London ever since.
11. Will McLean is the son of Bruce McLean and a practicing architect. For over a decade, he has organised public lectures on the technological development of architecture. He lectures at Westminster University.
12. Nick Collett is a British director and writer who specialises in comedy.
13. The sculptures and images by London-based artist Helen Marten proliferate with models and motifs which define the physical and linguistic limits of everyday life. Her work is invested with a strong sense of materiality, and recent exhibitions include the 55th Venice Biennale, Sadie Coles HQ and Museum Fridericianum.

redpajama_set_name: RedPajamaCommonCrawl


Are You Really a Type-A Doer Like Martha?
, I started reading with a superior attitude.
That described me to perfection. As I read the book, I realized that I had relegated Jesus to the living room. That's where we spend time together each morning. But when I close the covers of my journal, I jump up ready to wrangle the day in my own way. Often times leaving Jesus as I run around getting things done.
The root of the Martha attitude lies in feeling as if we have something to prove.
Katie divides the book up into four parts to show the reader how to claim one's identity in Christ. The first section—Striving—helps the reader understand some of the psychology behind those who relish to-do lists and getting things done. Our need to do things just might come from a hired-help mentality.
Each chapter ends with a little checklist and space to write down responses to what the reader learns. The author also includes Bible verses the reader can look up at the end of each chapter for further study. The end of each section has a self-assessment for readers.
The second section—Sitting—shows the reader how to grab hold of our true, beloved daughter identity. Once we leave behind the hired-help mentality, we must replace it with a new paradigm. The author points out that Jesus loves us even when we mess up (even if we mess up royally). As a beloved daughter, we can leave the stress of striving behind us.
Standing—the third section—helps the reader understand that 'We can rest because perfection is not up to us; perfection is in us, and His name is Jesus.' Katie dedicates the last section of the book to a study guide for group or individual study. I appreciate that she bakes everything into one book and makes it possible for readers to grab a group of friends and dive right in.
I challenge you to grab a copy and discover for yourself whether you're a Mary or a Martha, or a combination of both. All of us have much to learn about ourselves from studying how Martha and Mary interacted with Jesus.
Anita, reading only good things about Katie's book. Tempting but so much to do with this move!!!
Thanks so much for this post, Anita!


The Village of Swansea is pleased to announce the adoption of the Property Maintenance Code on September 21, 2015, Ordinance 1728. The adoption of this code puts in place a Property Inspection Program and Occupancy Permit Program for all residential properties/dwellings in the Village of Swansea. The program will consist of a required premises inspection conducted by the Village of Swansea and the issuance of an Occupancy Permit from the Village of Swansea. The scope of this program is to promote and to protect the public health, safety and general welfare of the people in all existing residential structures by establishing minimum requirements related to the safety, maintenance, sanitation, and other elements necessary for occupancy of a residential structure.
Beginning December 1, 2015, all residential structures will be required to have an inspection performed and passed, before an occupancy permit can be issued. This includes all rental properties, as well as all owner-occupied properties. Currently-occupied dwellings are not required to schedule an inspection until time of tenant/occupant change, or sale of property. All inspections will be performed by the Village of Swansea Building & Zoning Department. All Occupancy Permits will be issued by the Village of Swansea upon passing the inspection. Please click for the Occupancy Inspection Checklist as a reference of items that will be included in the inspection. For the Property Maintenance Code click here.
We welcome this program to ensure the safety and well- being of all Village residents. Please contact our office with any questions regarding this program.
the required inspection with the Village of Swansea.
during that period, even if the occupancy changes.
Occupancy Permit, please call 618-234-0044.
• Applicants will be required to list the names and ages of all tenants/occupants.
• Occupancy Permit Fee of $30.00 is to be paid at the time of application.
Letter from landlord/agent listing names and ages of tenant/occupants.
name and assume financial responsibility for all such utilities.
The temporary permit shall not authorize any person to occupy the premises.
A temporary permit shall expire upon the issuance of a certificate of occupancy for the premises.


text:
Q: Filter Records by query on relations in Laravel I need to get only those users that have role name "Team Leader".
user table : role_id
role_table : role_name

For example:
   $role = Role::where('name', 'Team Leader')->first();
   $team_leaders = User::where('role_id',$role->id)->get();

How can I do this directly with query on relationship?

A: IN User model you should add relation method 'role'
class User extends Authenticatable
{

   public function role()
   {
     return $this->belongsTo(Role::class, 'role_id');
   }

}

And then you can do:
User::whereHas('role', function ($query) {
    $query->where('role_name', '=', 'Team Leader');
})->get();

A: You can define one to many relationship,
In your Role model,
class Role extends Model
{
   public function users()
   {
     return $this->hasMany(User::class, 'role_id');
   }

}

in your User Model,
class User extends Authenticatable
{

   public function role()
   {
     return $this->belongsTo(Role::class, 'role_id');
   }

}

Now you can get the users list of team leader,
$role = Role::where('name', 'Team Leader')->first();
$team_leaders = $role->users;

Further more information you can see: https://laravel.com/docs/5.7/eloquent-relationships#one-to-many

A: One way of doing this is through Query Scopes.
For example:
public function scopeTeamLeader($query)
{
    $role = Role::whereName('Team Leader')->first();

    return $query->where('role_id', $role->id);
}

To query Users who are then also Team Leaders, you can do something like this
User::latest()
    ->TeamLeader()
    ->get();

I would also probably define some class constants in my 'App\Role' class.
For example.
class Role
{
    const TEAM_LEADER = 1;
}

The following could then be cleaned up like this:
public function scopeTeamLeader($query)
{
    return $query->where('role_id', Role::TEAM_LEADER);
}

Obviously, that's just a personal preference and would not be applicable everywhere, but I think it really improves readability and also reduces your scope by 1 query :)


text:
Titus Curtilius Mancia (fl. 55-56) est un homme politique de l'Empire romain.

Biographie
Il est consul suffect en 55 et légat d'Auguste propréteur exercitus en Germanie inférieure en 56.

Sa fille Curtilia Mancia s'est mariée avec Sextus Curvius Lucanus.

Bibliographie

Consul de l'Empire romain
Date de naissance incertaine (Ier siècle)

redpajama_set_name: RedPajamaWikipedia