| repo_name
				 stringlengths 7 104 | file_path
				 stringlengths 13 198 | context
				 stringlengths 67 7.15k | import_statement
				 stringlengths 16 4.43k | code
				 stringlengths 40 6.98k | prompt
				 stringlengths 227 8.27k | next_line
				 stringlengths 8 795 | 
|---|---|---|---|---|---|---|
| 
	dkpro/dkpro-statistics | 
	dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/visualization/UnitizingMatrixPrinter.java | 
	// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/unitizing/IUnitizingAnnotationStudy.java
// public interface IUnitizingAnnotationStudy
//     extends IAnnotationStudy
// {
// 
//     // -- Units --
// 
//     /** Allows iterating all annotation units of this study. */
//     Collection<IUnitizingAnnotationUnit> getUnits();
// 
//     // -- Continuum --
// 
//     // @Deprecated
//     // public int getSectionCount();
//     //
//     // @Deprecated
//     // public Iterable<Integer> getSectionBoundaries();
// 
//     /**
//      * Returns the begin of the continuum (i.e., the first offset that is considered valid for
//      * annotation units).
//      */
//     long getContinuumBegin();
// 
//     /**
//      * Returns the length of the continuum (i.e., the last possible right delimiter of an annotation
//      * unit).
//      */
//     long getContinuumLength();
// 
//     /**
//      * Returns the number of units rated by the given rater.
//      */
//     long getUnitCount(int aRaterIdx);
// 
//     // TODO: public void addSectionBoundary(long position);
// 
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/unitizing/IUnitizingAnnotationUnit.java
// public interface IUnitizingAnnotationUnit
//     extends IAnnotationUnit, Comparable<IUnitizingAnnotationUnit>
// {
// 
//     /**
//      * Returns the offset of the annotation unit (i.e., the start position of the identified
//      * segment).
//      */
//     public long getOffset();
// 
//     /**
//      * Returns the length of the annotation unit (i.e., the difference between the end and start
//      * position of the identified segment).
//      */
//     public long getLength();
// 
//     /**
//      * Returns the right delimiter of the annotation unit (i.e., the end position of the identified
//      * segment). The method is a shorthand for {@link #getOffset()} + {@link #getLength()}.
//      */
//     public long getEndOffset();
// 
// }
 | 
	import java.io.PrintStream;
import java.util.Objects;
import org.dkpro.statistics.agreement.unitizing.IUnitizingAnnotationStudy;
import org.dkpro.statistics.agreement.unitizing.IUnitizingAnnotationUnit; | 
	/*
 * Copyright 2014
 * Ubiquitous Knowledge Processing (UKP) Lab
 * Technische Universität Darmstadt
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.dkpro.statistics.agreement.visualization;
/**
 * Plain-text visualization for unitizing studies. The visualization prints the annotation units of
 * two raters in a matrix form - similar to the matrices used by Krippendorff (1995: p. 62). This
 * type of visualization can be used for comparing the boundaries of the units identified by a pair
 * of raters. By defining a {@link PrintStream}, it is possible to display a study on the console or
 * to write the results to a text file.<br>
 * <br>
 * References:
 * <ul>
 * <li>Krippendorff, K.: On the reliability of unitizing contiguous data. Sociological Methodology
 * 25:47–76, 1995.</li>
 * </ul>
 * 
 * @see IUnitizingAnnotationStudy
 * @author Christian M. Meyer
 */
public class UnitizingMatrixPrinter
{
    /**
     * Print a plain-text representation of the given unitizing study. A matrix can only be printed
     * for two of the raters and for (non-overlapping) units coded with the same category.
     */ | 
	// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/unitizing/IUnitizingAnnotationStudy.java
// public interface IUnitizingAnnotationStudy
//     extends IAnnotationStudy
// {
// 
//     // -- Units --
// 
//     /** Allows iterating all annotation units of this study. */
//     Collection<IUnitizingAnnotationUnit> getUnits();
// 
//     // -- Continuum --
// 
//     // @Deprecated
//     // public int getSectionCount();
//     //
//     // @Deprecated
//     // public Iterable<Integer> getSectionBoundaries();
// 
//     /**
//      * Returns the begin of the continuum (i.e., the first offset that is considered valid for
//      * annotation units).
//      */
//     long getContinuumBegin();
// 
//     /**
//      * Returns the length of the continuum (i.e., the last possible right delimiter of an annotation
//      * unit).
//      */
//     long getContinuumLength();
// 
//     /**
//      * Returns the number of units rated by the given rater.
//      */
//     long getUnitCount(int aRaterIdx);
// 
//     // TODO: public void addSectionBoundary(long position);
// 
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/unitizing/IUnitizingAnnotationUnit.java
// public interface IUnitizingAnnotationUnit
//     extends IAnnotationUnit, Comparable<IUnitizingAnnotationUnit>
// {
// 
//     /**
//      * Returns the offset of the annotation unit (i.e., the start position of the identified
//      * segment).
//      */
//     public long getOffset();
// 
//     /**
//      * Returns the length of the annotation unit (i.e., the difference between the end and start
//      * position of the identified segment).
//      */
//     public long getLength();
// 
//     /**
//      * Returns the right delimiter of the annotation unit (i.e., the end position of the identified
//      * segment). The method is a shorthand for {@link #getOffset()} + {@link #getLength()}.
//      */
//     public long getEndOffset();
// 
// }
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/visualization/UnitizingMatrixPrinter.java
import java.io.PrintStream;
import java.util.Objects;
import org.dkpro.statistics.agreement.unitizing.IUnitizingAnnotationStudy;
import org.dkpro.statistics.agreement.unitizing.IUnitizingAnnotationUnit;
/*
 * Copyright 2014
 * Ubiquitous Knowledge Processing (UKP) Lab
 * Technische Universität Darmstadt
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.dkpro.statistics.agreement.visualization;
/**
 * Plain-text visualization for unitizing studies. The visualization prints the annotation units of
 * two raters in a matrix form - similar to the matrices used by Krippendorff (1995: p. 62). This
 * type of visualization can be used for comparing the boundaries of the units identified by a pair
 * of raters. By defining a {@link PrintStream}, it is possible to display a study on the console or
 * to write the results to a text file.<br>
 * <br>
 * References:
 * <ul>
 * <li>Krippendorff, K.: On the reliability of unitizing contiguous data. Sociological Methodology
 * 25:47–76, 1995.</li>
 * </ul>
 * 
 * @see IUnitizingAnnotationStudy
 * @author Christian M. Meyer
 */
public class UnitizingMatrixPrinter
{
    /**
     * Print a plain-text representation of the given unitizing study. A matrix can only be printed
     * for two of the raters and for (non-overlapping) units coded with the same category.
     */ | 
	    public void print(final PrintStream out, final IUnitizingAnnotationStudy study, | 
| 
	dkpro/dkpro-statistics | 
	dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/visualization/UnitizingMatrixPrinter.java | 
	// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/unitizing/IUnitizingAnnotationStudy.java
// public interface IUnitizingAnnotationStudy
//     extends IAnnotationStudy
// {
// 
//     // -- Units --
// 
//     /** Allows iterating all annotation units of this study. */
//     Collection<IUnitizingAnnotationUnit> getUnits();
// 
//     // -- Continuum --
// 
//     // @Deprecated
//     // public int getSectionCount();
//     //
//     // @Deprecated
//     // public Iterable<Integer> getSectionBoundaries();
// 
//     /**
//      * Returns the begin of the continuum (i.e., the first offset that is considered valid for
//      * annotation units).
//      */
//     long getContinuumBegin();
// 
//     /**
//      * Returns the length of the continuum (i.e., the last possible right delimiter of an annotation
//      * unit).
//      */
//     long getContinuumLength();
// 
//     /**
//      * Returns the number of units rated by the given rater.
//      */
//     long getUnitCount(int aRaterIdx);
// 
//     // TODO: public void addSectionBoundary(long position);
// 
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/unitizing/IUnitizingAnnotationUnit.java
// public interface IUnitizingAnnotationUnit
//     extends IAnnotationUnit, Comparable<IUnitizingAnnotationUnit>
// {
// 
//     /**
//      * Returns the offset of the annotation unit (i.e., the start position of the identified
//      * segment).
//      */
//     public long getOffset();
// 
//     /**
//      * Returns the length of the annotation unit (i.e., the difference between the end and start
//      * position of the identified segment).
//      */
//     public long getLength();
// 
//     /**
//      * Returns the right delimiter of the annotation unit (i.e., the end position of the identified
//      * segment). The method is a shorthand for {@link #getOffset()} + {@link #getLength()}.
//      */
//     public long getEndOffset();
// 
// }
 | 
	import java.io.PrintStream;
import java.util.Objects;
import org.dkpro.statistics.agreement.unitizing.IUnitizingAnnotationStudy;
import org.dkpro.statistics.agreement.unitizing.IUnitizingAnnotationUnit; | 
	            for (int j = 0; j <= L; j++) {
                scale[i][j] = ' ';
            }
        }
        for (int i = 0; i <= L; i++) {
            int idx = 0;
            long pos = B + i;
            do {
                long lastDigit = pos % 10;
                scale[idx++][i] = (char) (lastDigit + '0');
                if (lastDigit == 0 || i == 0 || i == L) {
                    pos = pos / 10;
                }
                else {
                    break;
                }
            }
            while (pos > 0);
        }
        for (int j = digits - 1; j >= 0; j--) {
            out.print(digitSpace);
            out.print("  ");
            out.println(scale[j]);
        }
        // Rater 1.
        char[] annotations1 = new char[(int) L];
        for (int i = 0; i < L; i++) {
            annotations1[i] = ' ';
        } | 
	// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/unitizing/IUnitizingAnnotationStudy.java
// public interface IUnitizingAnnotationStudy
//     extends IAnnotationStudy
// {
// 
//     // -- Units --
// 
//     /** Allows iterating all annotation units of this study. */
//     Collection<IUnitizingAnnotationUnit> getUnits();
// 
//     // -- Continuum --
// 
//     // @Deprecated
//     // public int getSectionCount();
//     //
//     // @Deprecated
//     // public Iterable<Integer> getSectionBoundaries();
// 
//     /**
//      * Returns the begin of the continuum (i.e., the first offset that is considered valid for
//      * annotation units).
//      */
//     long getContinuumBegin();
// 
//     /**
//      * Returns the length of the continuum (i.e., the last possible right delimiter of an annotation
//      * unit).
//      */
//     long getContinuumLength();
// 
//     /**
//      * Returns the number of units rated by the given rater.
//      */
//     long getUnitCount(int aRaterIdx);
// 
//     // TODO: public void addSectionBoundary(long position);
// 
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/unitizing/IUnitizingAnnotationUnit.java
// public interface IUnitizingAnnotationUnit
//     extends IAnnotationUnit, Comparable<IUnitizingAnnotationUnit>
// {
// 
//     /**
//      * Returns the offset of the annotation unit (i.e., the start position of the identified
//      * segment).
//      */
//     public long getOffset();
// 
//     /**
//      * Returns the length of the annotation unit (i.e., the difference between the end and start
//      * position of the identified segment).
//      */
//     public long getLength();
// 
//     /**
//      * Returns the right delimiter of the annotation unit (i.e., the end position of the identified
//      * segment). The method is a shorthand for {@link #getOffset()} + {@link #getLength()}.
//      */
//     public long getEndOffset();
// 
// }
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/visualization/UnitizingMatrixPrinter.java
import java.io.PrintStream;
import java.util.Objects;
import org.dkpro.statistics.agreement.unitizing.IUnitizingAnnotationStudy;
import org.dkpro.statistics.agreement.unitizing.IUnitizingAnnotationUnit;
            for (int j = 0; j <= L; j++) {
                scale[i][j] = ' ';
            }
        }
        for (int i = 0; i <= L; i++) {
            int idx = 0;
            long pos = B + i;
            do {
                long lastDigit = pos % 10;
                scale[idx++][i] = (char) (lastDigit + '0');
                if (lastDigit == 0 || i == 0 || i == L) {
                    pos = pos / 10;
                }
                else {
                    break;
                }
            }
            while (pos > 0);
        }
        for (int j = digits - 1; j >= 0; j--) {
            out.print(digitSpace);
            out.print("  ");
            out.println(scale[j]);
        }
        // Rater 1.
        char[] annotations1 = new char[(int) L];
        for (int i = 0; i < L; i++) {
            annotations1[i] = ' ';
        } | 
	        for (IUnitizingAnnotationUnit unit : study.getUnits()) { | 
| 
	dkpro/dkpro-statistics | 
	dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/CodingAnnotationItem.java | 
	// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationUnit.java
// public interface IAnnotationUnit
//     extends Serializable
// {
//     /**
//      * Returns the index of the rater who coded this unit (in case of a coding study) or defined the
//      * boundaries of this unit (in case of a unitizing study). The first rater has index 0.
//      */
//     public int getRaterIdx();
// 
//     /**
//      * Returns the category assigned to this unit by one of the raters. The category might be null
//      * if, and only if, the unit represents a missing value (in case of a coding study) or a gap (in
//      * case of a unitizing study).
//      */
//     public Object getCategory();
// }
 | 
	import java.util.ArrayList;
import java.util.List;
import org.dkpro.statistics.agreement.IAnnotationUnit; | 
	/*
 * Copyright 2014
 * Ubiquitous Knowledge Processing (UKP) Lab
 * Technische Universität Darmstadt
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.dkpro.statistics.agreement.coding;
/**
 * Default implementation of {@link ICodingAnnotationItem} holding the set of annotation units for
 * this item (i.e., the categories assigned to this item by all raters). When using the default
 * implementation, it is recommended to use {@link CodingAnnotationStudy#addItem(Object...)} instead
 * of instantiating this type.
 * 
 * @see CodingAnnotationStudy
 * @see ICodingAnnotationItem
 * @author Christian M. Meyer
 */
public class CodingAnnotationItem
    implements ICodingAnnotationItem
{
    private static final long serialVersionUID = 3447650373912260846L;
     | 
	// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationUnit.java
// public interface IAnnotationUnit
//     extends Serializable
// {
//     /**
//      * Returns the index of the rater who coded this unit (in case of a coding study) or defined the
//      * boundaries of this unit (in case of a unitizing study). The first rater has index 0.
//      */
//     public int getRaterIdx();
// 
//     /**
//      * Returns the category assigned to this unit by one of the raters. The category might be null
//      * if, and only if, the unit represents a missing value (in case of a coding study) or a gap (in
//      * case of a unitizing study).
//      */
//     public Object getCategory();
// }
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/CodingAnnotationItem.java
import java.util.ArrayList;
import java.util.List;
import org.dkpro.statistics.agreement.IAnnotationUnit;
/*
 * Copyright 2014
 * Ubiquitous Knowledge Processing (UKP) Lab
 * Technische Universität Darmstadt
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.dkpro.statistics.agreement.coding;
/**
 * Default implementation of {@link ICodingAnnotationItem} holding the set of annotation units for
 * this item (i.e., the categories assigned to this item by all raters). When using the default
 * implementation, it is recommended to use {@link CodingAnnotationStudy#addItem(Object...)} instead
 * of instantiating this type.
 * 
 * @see CodingAnnotationStudy
 * @see ICodingAnnotationItem
 * @author Christian M. Meyer
 */
public class CodingAnnotationItem
    implements ICodingAnnotationItem
{
    private static final long serialVersionUID = 3447650373912260846L;
     | 
	    protected List<IAnnotationUnit> units; | 
| 
	dkpro/dkpro-statistics | 
	dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/WeightedKappaAgreement.java | 
	// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IChanceCorrectedDisagreement.java
// public interface IChanceCorrectedDisagreement
//     extends IAgreementMeasure
// {
//     /**
//      * Returns the observed disagreement of an annotation study. The observed disagreement is
//      * basically the proportion of annotation units that the raters disagree on divided by the
//      * number of units in the given study.
//      */
//     public double calculateObservedDisagreement();
// 
//     /**
//      * Returns the expected disagreement of an annotation study. The expected disagreement is the
//      * proportion of disagreement that would be expected by chance alone. The expected disagreement
//      * should be equal to the observed disagreement if each rater makes a random decision for each
//      * unit.
//      */
//     public double calculateExpectedDisagreement();
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IDistanceFunction.java
// public interface IDistanceFunction
// {
// 
//     /**
//      * Returns a distance value for the given pair of categories used within the given annotation
//      * study. Normally, the measure should return a distance of 0 if, and only if, the two
//      * categories are equal and a positive number otherwise.
//      */
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2);
// 
// }
 | 
	import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Map;
import java.util.Map.Entry;
import org.dkpro.statistics.agreement.IChanceCorrectedDisagreement;
import org.dkpro.statistics.agreement.distance.IDistanceFunction; | 
	/*
 * Copyright 2014
 * Ubiquitous Knowledge Processing (UKP) Lab
 * Technische Universität Darmstadt
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.dkpro.statistics.agreement.coding;
/**
 * Generalization of Cohen's (1960) kappa-measure for calculating a chance-corrected inter-rater
 * agreement for multiple raters with arbitrary distance/weighting functions. Before an inter-rater
 * agreement can be calculated, an {@link IDistanceFunction} instance needs to be assigned.<br>
 * <br>
 * References:
 * <ul>
 * <li>Cohen, J.: A Coefficient of Agreement for Nominal Scales. Educational and Psychological
 * Measurement 20(1):37-46, Beverly Hills, CA: Sage Publications, 1960.
 * <li>Cohen, J.: Weighted kappa: Nominal scale agreement with provision for scaled disagreement or
 * partial credit. Psychological Bulletin 70(4):213-220, Washington, DC: American Psychological
 * Association, 1968.
 * <li>Artstein, R. & Poesio, M.: Inter-Coder Agreement for Computational Linguistics.
 * Computational Linguistics 34(4):555-596, Cambridge, MA: The MIT Press, 2008.
 * </ul>
 * 
 * @author Christian M. Meyer
 */
public class WeightedKappaAgreement
    extends WeightedAgreement | 
	// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IChanceCorrectedDisagreement.java
// public interface IChanceCorrectedDisagreement
//     extends IAgreementMeasure
// {
//     /**
//      * Returns the observed disagreement of an annotation study. The observed disagreement is
//      * basically the proportion of annotation units that the raters disagree on divided by the
//      * number of units in the given study.
//      */
//     public double calculateObservedDisagreement();
// 
//     /**
//      * Returns the expected disagreement of an annotation study. The expected disagreement is the
//      * proportion of disagreement that would be expected by chance alone. The expected disagreement
//      * should be equal to the observed disagreement if each rater makes a random decision for each
//      * unit.
//      */
//     public double calculateExpectedDisagreement();
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IDistanceFunction.java
// public interface IDistanceFunction
// {
// 
//     /**
//      * Returns a distance value for the given pair of categories used within the given annotation
//      * study. Normally, the measure should return a distance of 0 if, and only if, the two
//      * categories are equal and a positive number otherwise.
//      */
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2);
// 
// }
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/WeightedKappaAgreement.java
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Map;
import java.util.Map.Entry;
import org.dkpro.statistics.agreement.IChanceCorrectedDisagreement;
import org.dkpro.statistics.agreement.distance.IDistanceFunction;
/*
 * Copyright 2014
 * Ubiquitous Knowledge Processing (UKP) Lab
 * Technische Universität Darmstadt
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.dkpro.statistics.agreement.coding;
/**
 * Generalization of Cohen's (1960) kappa-measure for calculating a chance-corrected inter-rater
 * agreement for multiple raters with arbitrary distance/weighting functions. Before an inter-rater
 * agreement can be calculated, an {@link IDistanceFunction} instance needs to be assigned.<br>
 * <br>
 * References:
 * <ul>
 * <li>Cohen, J.: A Coefficient of Agreement for Nominal Scales. Educational and Psychological
 * Measurement 20(1):37-46, Beverly Hills, CA: Sage Publications, 1960.
 * <li>Cohen, J.: Weighted kappa: Nominal scale agreement with provision for scaled disagreement or
 * partial credit. Psychological Bulletin 70(4):213-220, Washington, DC: American Psychological
 * Association, 1968.
 * <li>Artstein, R. & Poesio, M.: Inter-Coder Agreement for Computational Linguistics.
 * Computational Linguistics 34(4):555-596, Cambridge, MA: The MIT Press, 2008.
 * </ul>
 * 
 * @author Christian M. Meyer
 */
public class WeightedKappaAgreement
    extends WeightedAgreement | 
	    implements IChanceCorrectedDisagreement | 
| 
	dkpro/dkpro-statistics | 
	dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/WeightedKappaAgreement.java | 
	// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IChanceCorrectedDisagreement.java
// public interface IChanceCorrectedDisagreement
//     extends IAgreementMeasure
// {
//     /**
//      * Returns the observed disagreement of an annotation study. The observed disagreement is
//      * basically the proportion of annotation units that the raters disagree on divided by the
//      * number of units in the given study.
//      */
//     public double calculateObservedDisagreement();
// 
//     /**
//      * Returns the expected disagreement of an annotation study. The expected disagreement is the
//      * proportion of disagreement that would be expected by chance alone. The expected disagreement
//      * should be equal to the observed disagreement if each rater makes a random decision for each
//      * unit.
//      */
//     public double calculateExpectedDisagreement();
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IDistanceFunction.java
// public interface IDistanceFunction
// {
// 
//     /**
//      * Returns a distance value for the given pair of categories used within the given annotation
//      * study. Normally, the measure should return a distance of 0 if, and only if, the two
//      * categories are equal and a positive number otherwise.
//      */
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2);
// 
// }
 | 
	import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Map;
import java.util.Map.Entry;
import org.dkpro.statistics.agreement.IChanceCorrectedDisagreement;
import org.dkpro.statistics.agreement.distance.IDistanceFunction; | 
	/*
 * Copyright 2014
 * Ubiquitous Knowledge Processing (UKP) Lab
 * Technische Universität Darmstadt
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.dkpro.statistics.agreement.coding;
/**
 * Generalization of Cohen's (1960) kappa-measure for calculating a chance-corrected inter-rater
 * agreement for multiple raters with arbitrary distance/weighting functions. Before an inter-rater
 * agreement can be calculated, an {@link IDistanceFunction} instance needs to be assigned.<br>
 * <br>
 * References:
 * <ul>
 * <li>Cohen, J.: A Coefficient of Agreement for Nominal Scales. Educational and Psychological
 * Measurement 20(1):37-46, Beverly Hills, CA: Sage Publications, 1960.
 * <li>Cohen, J.: Weighted kappa: Nominal scale agreement with provision for scaled disagreement or
 * partial credit. Psychological Bulletin 70(4):213-220, Washington, DC: American Psychological
 * Association, 1968.
 * <li>Artstein, R. & Poesio, M.: Inter-Coder Agreement for Computational Linguistics.
 * Computational Linguistics 34(4):555-596, Cambridge, MA: The MIT Press, 2008.
 * </ul>
 * 
 * @author Christian M. Meyer
 */
public class WeightedKappaAgreement
    extends WeightedAgreement
    implements IChanceCorrectedDisagreement
{
    /**
     * Initializes the instance for the given annotation study. The study should never be null.
     */
    public WeightedKappaAgreement(final ICodingAnnotationStudy study, | 
	// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IChanceCorrectedDisagreement.java
// public interface IChanceCorrectedDisagreement
//     extends IAgreementMeasure
// {
//     /**
//      * Returns the observed disagreement of an annotation study. The observed disagreement is
//      * basically the proportion of annotation units that the raters disagree on divided by the
//      * number of units in the given study.
//      */
//     public double calculateObservedDisagreement();
// 
//     /**
//      * Returns the expected disagreement of an annotation study. The expected disagreement is the
//      * proportion of disagreement that would be expected by chance alone. The expected disagreement
//      * should be equal to the observed disagreement if each rater makes a random decision for each
//      * unit.
//      */
//     public double calculateExpectedDisagreement();
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IDistanceFunction.java
// public interface IDistanceFunction
// {
// 
//     /**
//      * Returns a distance value for the given pair of categories used within the given annotation
//      * study. Normally, the measure should return a distance of 0 if, and only if, the two
//      * categories are equal and a positive number otherwise.
//      */
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2);
// 
// }
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/WeightedKappaAgreement.java
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Map;
import java.util.Map.Entry;
import org.dkpro.statistics.agreement.IChanceCorrectedDisagreement;
import org.dkpro.statistics.agreement.distance.IDistanceFunction;
/*
 * Copyright 2014
 * Ubiquitous Knowledge Processing (UKP) Lab
 * Technische Universität Darmstadt
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.dkpro.statistics.agreement.coding;
/**
 * Generalization of Cohen's (1960) kappa-measure for calculating a chance-corrected inter-rater
 * agreement for multiple raters with arbitrary distance/weighting functions. Before an inter-rater
 * agreement can be calculated, an {@link IDistanceFunction} instance needs to be assigned.<br>
 * <br>
 * References:
 * <ul>
 * <li>Cohen, J.: A Coefficient of Agreement for Nominal Scales. Educational and Psychological
 * Measurement 20(1):37-46, Beverly Hills, CA: Sage Publications, 1960.
 * <li>Cohen, J.: Weighted kappa: Nominal scale agreement with provision for scaled disagreement or
 * partial credit. Psychological Bulletin 70(4):213-220, Washington, DC: American Psychological
 * Association, 1968.
 * <li>Artstein, R. & Poesio, M.: Inter-Coder Agreement for Computational Linguistics.
 * Computational Linguistics 34(4):555-596, Cambridge, MA: The MIT Press, 2008.
 * </ul>
 * 
 * @author Christian M. Meyer
 */
public class WeightedKappaAgreement
    extends WeightedAgreement
    implements IChanceCorrectedDisagreement
{
    /**
     * Initializes the instance for the given annotation study. The study should never be null.
     */
    public WeightedKappaAgreement(final ICodingAnnotationStudy study, | 
	            final IDistanceFunction distanceFunction) | 
| 
	dkpro/dkpro-statistics | 
	dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/ICodingAnnotationItem.java | 
	// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationItem.java
// public interface IAnnotationItem extends Serializable
// {
// 
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationUnit.java
// public interface IAnnotationUnit
//     extends Serializable
// {
//     /**
//      * Returns the index of the rater who coded this unit (in case of a coding study) or defined the
//      * boundaries of this unit (in case of a unitizing study). The first rater has index 0.
//      */
//     public int getRaterIdx();
// 
//     /**
//      * Returns the category assigned to this unit by one of the raters. The category might be null
//      * if, and only if, the unit represents a missing value (in case of a coding study) or a gap (in
//      * case of a unitizing study).
//      */
//     public Object getCategory();
// }
 | 
	import org.dkpro.statistics.agreement.IAnnotationItem;
import org.dkpro.statistics.agreement.IAnnotationUnit; | 
	/*
 * Copyright 2014
 * Ubiquitous Knowledge Processing (UKP) Lab
 * Technische Universität Darmstadt
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.dkpro.statistics.agreement.coding;
/**
 * Represents a single annotation item of an {@link ICodingAnnotationStudy}. In coding tasks,
 * annotation items are fixed, and each rater is asked to code each item. The category assigned by a
 * certain rater is represented as annotation units. Thus, an annotation item of a coding study
 * consists of multiple annotation units.
 * 
 * @see IAnnotationUnit
 * @see ICodingAnnotationStudy
 * @author Christian M. Meyer
 */
public interface ICodingAnnotationItem
    extends IAnnotationItem
{
    /**
     * Returns the annotation unit of the rater with the specified index. That is, the object
     * holding the category assigned to the item by the specified rater.
     */ | 
	// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationItem.java
// public interface IAnnotationItem extends Serializable
// {
// 
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationUnit.java
// public interface IAnnotationUnit
//     extends Serializable
// {
//     /**
//      * Returns the index of the rater who coded this unit (in case of a coding study) or defined the
//      * boundaries of this unit (in case of a unitizing study). The first rater has index 0.
//      */
//     public int getRaterIdx();
// 
//     /**
//      * Returns the category assigned to this unit by one of the raters. The category might be null
//      * if, and only if, the unit represents a missing value (in case of a coding study) or a gap (in
//      * case of a unitizing study).
//      */
//     public Object getCategory();
// }
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/ICodingAnnotationItem.java
import org.dkpro.statistics.agreement.IAnnotationItem;
import org.dkpro.statistics.agreement.IAnnotationUnit;
/*
 * Copyright 2014
 * Ubiquitous Knowledge Processing (UKP) Lab
 * Technische Universität Darmstadt
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.dkpro.statistics.agreement.coding;
/**
 * Represents a single annotation item of an {@link ICodingAnnotationStudy}. In coding tasks,
 * annotation items are fixed, and each rater is asked to code each item. The category assigned by a
 * certain rater is represented as annotation units. Thus, an annotation item of a coding study
 * consists of multiple annotation units.
 * 
 * @see IAnnotationUnit
 * @see ICodingAnnotationStudy
 * @author Christian M. Meyer
 */
public interface ICodingAnnotationItem
    extends IAnnotationItem
{
    /**
     * Returns the annotation unit of the rater with the specified index. That is, the object
     * holding the category assigned to the item by the specified rater.
     */ | 
	    public IAnnotationUnit getUnit(int raterIdx); | 
| 
	dkpro/dkpro-statistics | 
	dkpro-statistics-agreement/src/test/java/org/dkpro/statistics/agreement/coding/Krippendorff2004Test.java | 
	// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IDistanceFunction.java
// public interface IDistanceFunction
// {
// 
//     /**
//      * Returns a distance value for the given pair of categories used within the given annotation
//      * study. Normally, the measure should return a distance of 0 if, and only if, the two
//      * categories are equal and a positive number otherwise.
//      */
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2);
// 
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IntervalDistanceFunction.java
// public class IntervalDistanceFunction
//     implements IDistanceFunction
// {
// 
//     @Override
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2)
//     {
//         if (category1 instanceof Integer && category2 instanceof Integer) {
//             return (((Integer) category1) - ((Integer) category2))
//                     * (((Integer) category1) - ((Integer) category2));
//         }
// 
//         if (category1 instanceof Double && category2 instanceof Double) {
//             return (((Double) category1) - ((Double) category2))
//                     * (((Double) category1) - ((Double) category2));
//         }
// 
//         return (category1.equals(category2) ? 0.0 : 1.0);
//     }
// 
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/NominalDistanceFunction.java
// public class NominalDistanceFunction
//     implements IDistanceFunction
// {
// 
//     @Override
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2)
//     {
//         return (category1.equals(category2) ? 0.0 : 1.0);
//     }
// 
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/OrdinalDistanceFunction.java
// public class OrdinalDistanceFunction
//     implements IDistanceFunction
// {
// 
//     @Override
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2)
//     {
//         if (category1 instanceof Integer && category2 instanceof Integer) {
//             if (category1.equals(category2)) {
//                 return 0.0;
//             }
// 
//             // TODO: Provide generic method for the annotation study w/ potential use for unitizing
//             // tasks!
//             Map<Object, Integer> nk = CodingAnnotationStudy
//                     .countTotalAnnotationsPerCategory((ICodingAnnotationStudy) study);
//             Integer v;
// 
//             double result = 0.0;
//             v = nk.get(category1);
//             if (v != null) {
//                 result += ((double) v) / 2.0;
//             }
//             v = nk.get(category2);
//             if (v != null) {
//                 result += ((double) v) / 2.0;
//             }
// 
//             int cat1 = (Integer) category1;
//             int cat2 = (Integer) category2;
//             int minCat = (cat1 < cat2 ? cat1 : cat2);
//             int maxCat = (cat1 < cat2 ? cat2 : cat1);
//             for (int i = minCat + 1; i < maxCat; i++) {
//                 v = nk.get(i);
//                 if (v != null) {
//                     result += v;
//                 }
//             }
//             return result * result;
//         }
// 
//         return (category1.equals(category2) ? 0.0 : 1.0);
//     }
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/RatioDistanceFunction.java
// public class RatioDistanceFunction
//     implements IDistanceFunction
// {
// 
//     @Override
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2)
//     {
//         if (category1 instanceof Integer && category2 instanceof Integer
//                 && (((Integer) category1) + ((Integer) category2) > 0.0)) {
//             double result = (((Integer) category1) - ((Integer) category2))
//                     / (double) (((Integer) category1) + ((Integer) category2));
//             return result * result;
//         }
// 
//         if (category1 instanceof Double && category2 instanceof Double
//                 && (((Double) category1) + ((Double) category2) > 0.0)) {
//             double result = (((Double) category1) - ((Double) category2))
//                     / (((Double) category1) + ((Double) category2));
//             return result * result;
//         }
// 
//         return (category1.equals(category2) ? 0.0 : 1.0);
//     }
// 
// }
 | 
	import org.dkpro.statistics.agreement.distance.IDistanceFunction;
import org.dkpro.statistics.agreement.distance.IntervalDistanceFunction;
import org.dkpro.statistics.agreement.distance.NominalDistanceFunction;
import org.dkpro.statistics.agreement.distance.OrdinalDistanceFunction;
import org.dkpro.statistics.agreement.distance.RatioDistanceFunction;
import junit.framework.TestCase; | 
	/*
 * Copyright 2014
 * Ubiquitous Knowledge Processing (UKP) Lab
 * Technische Universität Darmstadt
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.dkpro.statistics.agreement.coding;
/**
 * Tests based on Krippendorff (2004) for measuring {@link KrippendorffAlphaAgreement}.<br>
 * <br>
 * References:
 * <ul>
 * <li>Krippendorff, K.: Content Analysis: An Introduction to Its Methodology. Thousand Oaks, CA:
 * Sage Publications, 2004.</li>
 * </ul>
 * 
 * @author Christian M. Meyer
 */
public class Krippendorff2004Test
    extends TestCase
{
    
    public void testDichotomy()
    {
        ICodingAnnotationStudy study = createExample1();
        PercentageAgreement pa = new PercentageAgreement(study);
        assertEquals(0.600, pa.calculateAgreement(), 0.001);
        KrippendorffAlphaAgreement alpha = new KrippendorffAlphaAgreement(study, | 
	// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IDistanceFunction.java
// public interface IDistanceFunction
// {
// 
//     /**
//      * Returns a distance value for the given pair of categories used within the given annotation
//      * study. Normally, the measure should return a distance of 0 if, and only if, the two
//      * categories are equal and a positive number otherwise.
//      */
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2);
// 
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IntervalDistanceFunction.java
// public class IntervalDistanceFunction
//     implements IDistanceFunction
// {
// 
//     @Override
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2)
//     {
//         if (category1 instanceof Integer && category2 instanceof Integer) {
//             return (((Integer) category1) - ((Integer) category2))
//                     * (((Integer) category1) - ((Integer) category2));
//         }
// 
//         if (category1 instanceof Double && category2 instanceof Double) {
//             return (((Double) category1) - ((Double) category2))
//                     * (((Double) category1) - ((Double) category2));
//         }
// 
//         return (category1.equals(category2) ? 0.0 : 1.0);
//     }
// 
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/NominalDistanceFunction.java
// public class NominalDistanceFunction
//     implements IDistanceFunction
// {
// 
//     @Override
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2)
//     {
//         return (category1.equals(category2) ? 0.0 : 1.0);
//     }
// 
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/OrdinalDistanceFunction.java
// public class OrdinalDistanceFunction
//     implements IDistanceFunction
// {
// 
//     @Override
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2)
//     {
//         if (category1 instanceof Integer && category2 instanceof Integer) {
//             if (category1.equals(category2)) {
//                 return 0.0;
//             }
// 
//             // TODO: Provide generic method for the annotation study w/ potential use for unitizing
//             // tasks!
//             Map<Object, Integer> nk = CodingAnnotationStudy
//                     .countTotalAnnotationsPerCategory((ICodingAnnotationStudy) study);
//             Integer v;
// 
//             double result = 0.0;
//             v = nk.get(category1);
//             if (v != null) {
//                 result += ((double) v) / 2.0;
//             }
//             v = nk.get(category2);
//             if (v != null) {
//                 result += ((double) v) / 2.0;
//             }
// 
//             int cat1 = (Integer) category1;
//             int cat2 = (Integer) category2;
//             int minCat = (cat1 < cat2 ? cat1 : cat2);
//             int maxCat = (cat1 < cat2 ? cat2 : cat1);
//             for (int i = minCat + 1; i < maxCat; i++) {
//                 v = nk.get(i);
//                 if (v != null) {
//                     result += v;
//                 }
//             }
//             return result * result;
//         }
// 
//         return (category1.equals(category2) ? 0.0 : 1.0);
//     }
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/RatioDistanceFunction.java
// public class RatioDistanceFunction
//     implements IDistanceFunction
// {
// 
//     @Override
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2)
//     {
//         if (category1 instanceof Integer && category2 instanceof Integer
//                 && (((Integer) category1) + ((Integer) category2) > 0.0)) {
//             double result = (((Integer) category1) - ((Integer) category2))
//                     / (double) (((Integer) category1) + ((Integer) category2));
//             return result * result;
//         }
// 
//         if (category1 instanceof Double && category2 instanceof Double
//                 && (((Double) category1) + ((Double) category2) > 0.0)) {
//             double result = (((Double) category1) - ((Double) category2))
//                     / (((Double) category1) + ((Double) category2));
//             return result * result;
//         }
// 
//         return (category1.equals(category2) ? 0.0 : 1.0);
//     }
// 
// }
// Path: dkpro-statistics-agreement/src/test/java/org/dkpro/statistics/agreement/coding/Krippendorff2004Test.java
import org.dkpro.statistics.agreement.distance.IDistanceFunction;
import org.dkpro.statistics.agreement.distance.IntervalDistanceFunction;
import org.dkpro.statistics.agreement.distance.NominalDistanceFunction;
import org.dkpro.statistics.agreement.distance.OrdinalDistanceFunction;
import org.dkpro.statistics.agreement.distance.RatioDistanceFunction;
import junit.framework.TestCase;
/*
 * Copyright 2014
 * Ubiquitous Knowledge Processing (UKP) Lab
 * Technische Universität Darmstadt
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.dkpro.statistics.agreement.coding;
/**
 * Tests based on Krippendorff (2004) for measuring {@link KrippendorffAlphaAgreement}.<br>
 * <br>
 * References:
 * <ul>
 * <li>Krippendorff, K.: Content Analysis: An Introduction to Its Methodology. Thousand Oaks, CA:
 * Sage Publications, 2004.</li>
 * </ul>
 * 
 * @author Christian M. Meyer
 */
public class Krippendorff2004Test
    extends TestCase
{
    
    public void testDichotomy()
    {
        ICodingAnnotationStudy study = createExample1();
        PercentageAgreement pa = new PercentageAgreement(study);
        assertEquals(0.600, pa.calculateAgreement(), 0.001);
        KrippendorffAlphaAgreement alpha = new KrippendorffAlphaAgreement(study, | 
	                new NominalDistanceFunction()); | 
| 
	dkpro/dkpro-statistics | 
	dkpro-statistics-agreement/src/test/java/org/dkpro/statistics/agreement/coding/Krippendorff2004Test.java | 
	// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IDistanceFunction.java
// public interface IDistanceFunction
// {
// 
//     /**
//      * Returns a distance value for the given pair of categories used within the given annotation
//      * study. Normally, the measure should return a distance of 0 if, and only if, the two
//      * categories are equal and a positive number otherwise.
//      */
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2);
// 
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IntervalDistanceFunction.java
// public class IntervalDistanceFunction
//     implements IDistanceFunction
// {
// 
//     @Override
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2)
//     {
//         if (category1 instanceof Integer && category2 instanceof Integer) {
//             return (((Integer) category1) - ((Integer) category2))
//                     * (((Integer) category1) - ((Integer) category2));
//         }
// 
//         if (category1 instanceof Double && category2 instanceof Double) {
//             return (((Double) category1) - ((Double) category2))
//                     * (((Double) category1) - ((Double) category2));
//         }
// 
//         return (category1.equals(category2) ? 0.0 : 1.0);
//     }
// 
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/NominalDistanceFunction.java
// public class NominalDistanceFunction
//     implements IDistanceFunction
// {
// 
//     @Override
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2)
//     {
//         return (category1.equals(category2) ? 0.0 : 1.0);
//     }
// 
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/OrdinalDistanceFunction.java
// public class OrdinalDistanceFunction
//     implements IDistanceFunction
// {
// 
//     @Override
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2)
//     {
//         if (category1 instanceof Integer && category2 instanceof Integer) {
//             if (category1.equals(category2)) {
//                 return 0.0;
//             }
// 
//             // TODO: Provide generic method for the annotation study w/ potential use for unitizing
//             // tasks!
//             Map<Object, Integer> nk = CodingAnnotationStudy
//                     .countTotalAnnotationsPerCategory((ICodingAnnotationStudy) study);
//             Integer v;
// 
//             double result = 0.0;
//             v = nk.get(category1);
//             if (v != null) {
//                 result += ((double) v) / 2.0;
//             }
//             v = nk.get(category2);
//             if (v != null) {
//                 result += ((double) v) / 2.0;
//             }
// 
//             int cat1 = (Integer) category1;
//             int cat2 = (Integer) category2;
//             int minCat = (cat1 < cat2 ? cat1 : cat2);
//             int maxCat = (cat1 < cat2 ? cat2 : cat1);
//             for (int i = minCat + 1; i < maxCat; i++) {
//                 v = nk.get(i);
//                 if (v != null) {
//                     result += v;
//                 }
//             }
//             return result * result;
//         }
// 
//         return (category1.equals(category2) ? 0.0 : 1.0);
//     }
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/RatioDistanceFunction.java
// public class RatioDistanceFunction
//     implements IDistanceFunction
// {
// 
//     @Override
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2)
//     {
//         if (category1 instanceof Integer && category2 instanceof Integer
//                 && (((Integer) category1) + ((Integer) category2) > 0.0)) {
//             double result = (((Integer) category1) - ((Integer) category2))
//                     / (double) (((Integer) category1) + ((Integer) category2));
//             return result * result;
//         }
// 
//         if (category1 instanceof Double && category2 instanceof Double
//                 && (((Double) category1) + ((Double) category2) > 0.0)) {
//             double result = (((Double) category1) - ((Double) category2))
//                     / (((Double) category1) + ((Double) category2));
//             return result * result;
//         }
// 
//         return (category1.equals(category2) ? 0.0 : 1.0);
//     }
// 
// }
 | 
	import org.dkpro.statistics.agreement.distance.IDistanceFunction;
import org.dkpro.statistics.agreement.distance.IntervalDistanceFunction;
import org.dkpro.statistics.agreement.distance.NominalDistanceFunction;
import org.dkpro.statistics.agreement.distance.OrdinalDistanceFunction;
import org.dkpro.statistics.agreement.distance.RatioDistanceFunction;
import junit.framework.TestCase; | 
	        PercentageAgreement pa = new PercentageAgreement(study);
        assertEquals(0.833, pa.calculateAgreement(), 0.001);
        KrippendorffAlphaAgreement alpha = new KrippendorffAlphaAgreement(study,
                new NominalDistanceFunction());
        assertEquals(0.1667, alpha.calculateObservedDisagreement(), 0.001);
        assertEquals(0.6268, alpha.calculateExpectedDisagreement(), 0.001);
        assertEquals(0.734, alpha.calculateAgreement(), 0.001);
    }
    
    public void testMultipleRatersMissingValues()
    {
        ICodingAnnotationStudy study = createExample3();
        PercentageAgreement pa = new PercentageAgreement(study);
        assertEquals(0.800, pa.calculateAgreement(), 0.001);
        KrippendorffAlphaAgreement alpha = new KrippendorffAlphaAgreement(study,
                new NominalDistanceFunction());
        assertEquals(0.200, alpha.calculateObservedDisagreement(), 0.001);
        assertEquals(0.779, alpha.calculateExpectedDisagreement(), 0.001);
        assertEquals(0.743, alpha.calculateAgreement(), 0.001);
    }
    
    public void testOrdinalMetric()
    {
        CodingAnnotationStudy study = createExample3a(0);
 | 
	// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IDistanceFunction.java
// public interface IDistanceFunction
// {
// 
//     /**
//      * Returns a distance value for the given pair of categories used within the given annotation
//      * study. Normally, the measure should return a distance of 0 if, and only if, the two
//      * categories are equal and a positive number otherwise.
//      */
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2);
// 
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IntervalDistanceFunction.java
// public class IntervalDistanceFunction
//     implements IDistanceFunction
// {
// 
//     @Override
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2)
//     {
//         if (category1 instanceof Integer && category2 instanceof Integer) {
//             return (((Integer) category1) - ((Integer) category2))
//                     * (((Integer) category1) - ((Integer) category2));
//         }
// 
//         if (category1 instanceof Double && category2 instanceof Double) {
//             return (((Double) category1) - ((Double) category2))
//                     * (((Double) category1) - ((Double) category2));
//         }
// 
//         return (category1.equals(category2) ? 0.0 : 1.0);
//     }
// 
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/NominalDistanceFunction.java
// public class NominalDistanceFunction
//     implements IDistanceFunction
// {
// 
//     @Override
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2)
//     {
//         return (category1.equals(category2) ? 0.0 : 1.0);
//     }
// 
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/OrdinalDistanceFunction.java
// public class OrdinalDistanceFunction
//     implements IDistanceFunction
// {
// 
//     @Override
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2)
//     {
//         if (category1 instanceof Integer && category2 instanceof Integer) {
//             if (category1.equals(category2)) {
//                 return 0.0;
//             }
// 
//             // TODO: Provide generic method for the annotation study w/ potential use for unitizing
//             // tasks!
//             Map<Object, Integer> nk = CodingAnnotationStudy
//                     .countTotalAnnotationsPerCategory((ICodingAnnotationStudy) study);
//             Integer v;
// 
//             double result = 0.0;
//             v = nk.get(category1);
//             if (v != null) {
//                 result += ((double) v) / 2.0;
//             }
//             v = nk.get(category2);
//             if (v != null) {
//                 result += ((double) v) / 2.0;
//             }
// 
//             int cat1 = (Integer) category1;
//             int cat2 = (Integer) category2;
//             int minCat = (cat1 < cat2 ? cat1 : cat2);
//             int maxCat = (cat1 < cat2 ? cat2 : cat1);
//             for (int i = minCat + 1; i < maxCat; i++) {
//                 v = nk.get(i);
//                 if (v != null) {
//                     result += v;
//                 }
//             }
//             return result * result;
//         }
// 
//         return (category1.equals(category2) ? 0.0 : 1.0);
//     }
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/RatioDistanceFunction.java
// public class RatioDistanceFunction
//     implements IDistanceFunction
// {
// 
//     @Override
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2)
//     {
//         if (category1 instanceof Integer && category2 instanceof Integer
//                 && (((Integer) category1) + ((Integer) category2) > 0.0)) {
//             double result = (((Integer) category1) - ((Integer) category2))
//                     / (double) (((Integer) category1) + ((Integer) category2));
//             return result * result;
//         }
// 
//         if (category1 instanceof Double && category2 instanceof Double
//                 && (((Double) category1) + ((Double) category2) > 0.0)) {
//             double result = (((Double) category1) - ((Double) category2))
//                     / (((Double) category1) + ((Double) category2));
//             return result * result;
//         }
// 
//         return (category1.equals(category2) ? 0.0 : 1.0);
//     }
// 
// }
// Path: dkpro-statistics-agreement/src/test/java/org/dkpro/statistics/agreement/coding/Krippendorff2004Test.java
import org.dkpro.statistics.agreement.distance.IDistanceFunction;
import org.dkpro.statistics.agreement.distance.IntervalDistanceFunction;
import org.dkpro.statistics.agreement.distance.NominalDistanceFunction;
import org.dkpro.statistics.agreement.distance.OrdinalDistanceFunction;
import org.dkpro.statistics.agreement.distance.RatioDistanceFunction;
import junit.framework.TestCase;
        PercentageAgreement pa = new PercentageAgreement(study);
        assertEquals(0.833, pa.calculateAgreement(), 0.001);
        KrippendorffAlphaAgreement alpha = new KrippendorffAlphaAgreement(study,
                new NominalDistanceFunction());
        assertEquals(0.1667, alpha.calculateObservedDisagreement(), 0.001);
        assertEquals(0.6268, alpha.calculateExpectedDisagreement(), 0.001);
        assertEquals(0.734, alpha.calculateAgreement(), 0.001);
    }
    
    public void testMultipleRatersMissingValues()
    {
        ICodingAnnotationStudy study = createExample3();
        PercentageAgreement pa = new PercentageAgreement(study);
        assertEquals(0.800, pa.calculateAgreement(), 0.001);
        KrippendorffAlphaAgreement alpha = new KrippendorffAlphaAgreement(study,
                new NominalDistanceFunction());
        assertEquals(0.200, alpha.calculateObservedDisagreement(), 0.001);
        assertEquals(0.779, alpha.calculateExpectedDisagreement(), 0.001);
        assertEquals(0.743, alpha.calculateAgreement(), 0.001);
    }
    
    public void testOrdinalMetric()
    {
        CodingAnnotationStudy study = createExample3a(0);
 | 
	        IDistanceFunction distFunc = new OrdinalDistanceFunction(); | 
| 
	dkpro/dkpro-statistics | 
	dkpro-statistics-agreement/src/test/java/org/dkpro/statistics/agreement/coding/Krippendorff2004Test.java | 
	// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IDistanceFunction.java
// public interface IDistanceFunction
// {
// 
//     /**
//      * Returns a distance value for the given pair of categories used within the given annotation
//      * study. Normally, the measure should return a distance of 0 if, and only if, the two
//      * categories are equal and a positive number otherwise.
//      */
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2);
// 
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IntervalDistanceFunction.java
// public class IntervalDistanceFunction
//     implements IDistanceFunction
// {
// 
//     @Override
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2)
//     {
//         if (category1 instanceof Integer && category2 instanceof Integer) {
//             return (((Integer) category1) - ((Integer) category2))
//                     * (((Integer) category1) - ((Integer) category2));
//         }
// 
//         if (category1 instanceof Double && category2 instanceof Double) {
//             return (((Double) category1) - ((Double) category2))
//                     * (((Double) category1) - ((Double) category2));
//         }
// 
//         return (category1.equals(category2) ? 0.0 : 1.0);
//     }
// 
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/NominalDistanceFunction.java
// public class NominalDistanceFunction
//     implements IDistanceFunction
// {
// 
//     @Override
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2)
//     {
//         return (category1.equals(category2) ? 0.0 : 1.0);
//     }
// 
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/OrdinalDistanceFunction.java
// public class OrdinalDistanceFunction
//     implements IDistanceFunction
// {
// 
//     @Override
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2)
//     {
//         if (category1 instanceof Integer && category2 instanceof Integer) {
//             if (category1.equals(category2)) {
//                 return 0.0;
//             }
// 
//             // TODO: Provide generic method for the annotation study w/ potential use for unitizing
//             // tasks!
//             Map<Object, Integer> nk = CodingAnnotationStudy
//                     .countTotalAnnotationsPerCategory((ICodingAnnotationStudy) study);
//             Integer v;
// 
//             double result = 0.0;
//             v = nk.get(category1);
//             if (v != null) {
//                 result += ((double) v) / 2.0;
//             }
//             v = nk.get(category2);
//             if (v != null) {
//                 result += ((double) v) / 2.0;
//             }
// 
//             int cat1 = (Integer) category1;
//             int cat2 = (Integer) category2;
//             int minCat = (cat1 < cat2 ? cat1 : cat2);
//             int maxCat = (cat1 < cat2 ? cat2 : cat1);
//             for (int i = minCat + 1; i < maxCat; i++) {
//                 v = nk.get(i);
//                 if (v != null) {
//                     result += v;
//                 }
//             }
//             return result * result;
//         }
// 
//         return (category1.equals(category2) ? 0.0 : 1.0);
//     }
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/RatioDistanceFunction.java
// public class RatioDistanceFunction
//     implements IDistanceFunction
// {
// 
//     @Override
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2)
//     {
//         if (category1 instanceof Integer && category2 instanceof Integer
//                 && (((Integer) category1) + ((Integer) category2) > 0.0)) {
//             double result = (((Integer) category1) - ((Integer) category2))
//                     / (double) (((Integer) category1) + ((Integer) category2));
//             return result * result;
//         }
// 
//         if (category1 instanceof Double && category2 instanceof Double
//                 && (((Double) category1) + ((Double) category2) > 0.0)) {
//             double result = (((Double) category1) - ((Double) category2))
//                     / (((Double) category1) + ((Double) category2));
//             return result * result;
//         }
// 
//         return (category1.equals(category2) ? 0.0 : 1.0);
//     }
// 
// }
 | 
	import org.dkpro.statistics.agreement.distance.IDistanceFunction;
import org.dkpro.statistics.agreement.distance.IntervalDistanceFunction;
import org.dkpro.statistics.agreement.distance.NominalDistanceFunction;
import org.dkpro.statistics.agreement.distance.OrdinalDistanceFunction;
import org.dkpro.statistics.agreement.distance.RatioDistanceFunction;
import junit.framework.TestCase; | 
	        PercentageAgreement pa = new PercentageAgreement(study);
        assertEquals(0.833, pa.calculateAgreement(), 0.001);
        KrippendorffAlphaAgreement alpha = new KrippendorffAlphaAgreement(study,
                new NominalDistanceFunction());
        assertEquals(0.1667, alpha.calculateObservedDisagreement(), 0.001);
        assertEquals(0.6268, alpha.calculateExpectedDisagreement(), 0.001);
        assertEquals(0.734, alpha.calculateAgreement(), 0.001);
    }
    
    public void testMultipleRatersMissingValues()
    {
        ICodingAnnotationStudy study = createExample3();
        PercentageAgreement pa = new PercentageAgreement(study);
        assertEquals(0.800, pa.calculateAgreement(), 0.001);
        KrippendorffAlphaAgreement alpha = new KrippendorffAlphaAgreement(study,
                new NominalDistanceFunction());
        assertEquals(0.200, alpha.calculateObservedDisagreement(), 0.001);
        assertEquals(0.779, alpha.calculateExpectedDisagreement(), 0.001);
        assertEquals(0.743, alpha.calculateAgreement(), 0.001);
    }
    
    public void testOrdinalMetric()
    {
        CodingAnnotationStudy study = createExample3a(0);
 | 
	// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IDistanceFunction.java
// public interface IDistanceFunction
// {
// 
//     /**
//      * Returns a distance value for the given pair of categories used within the given annotation
//      * study. Normally, the measure should return a distance of 0 if, and only if, the two
//      * categories are equal and a positive number otherwise.
//      */
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2);
// 
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IntervalDistanceFunction.java
// public class IntervalDistanceFunction
//     implements IDistanceFunction
// {
// 
//     @Override
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2)
//     {
//         if (category1 instanceof Integer && category2 instanceof Integer) {
//             return (((Integer) category1) - ((Integer) category2))
//                     * (((Integer) category1) - ((Integer) category2));
//         }
// 
//         if (category1 instanceof Double && category2 instanceof Double) {
//             return (((Double) category1) - ((Double) category2))
//                     * (((Double) category1) - ((Double) category2));
//         }
// 
//         return (category1.equals(category2) ? 0.0 : 1.0);
//     }
// 
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/NominalDistanceFunction.java
// public class NominalDistanceFunction
//     implements IDistanceFunction
// {
// 
//     @Override
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2)
//     {
//         return (category1.equals(category2) ? 0.0 : 1.0);
//     }
// 
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/OrdinalDistanceFunction.java
// public class OrdinalDistanceFunction
//     implements IDistanceFunction
// {
// 
//     @Override
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2)
//     {
//         if (category1 instanceof Integer && category2 instanceof Integer) {
//             if (category1.equals(category2)) {
//                 return 0.0;
//             }
// 
//             // TODO: Provide generic method for the annotation study w/ potential use for unitizing
//             // tasks!
//             Map<Object, Integer> nk = CodingAnnotationStudy
//                     .countTotalAnnotationsPerCategory((ICodingAnnotationStudy) study);
//             Integer v;
// 
//             double result = 0.0;
//             v = nk.get(category1);
//             if (v != null) {
//                 result += ((double) v) / 2.0;
//             }
//             v = nk.get(category2);
//             if (v != null) {
//                 result += ((double) v) / 2.0;
//             }
// 
//             int cat1 = (Integer) category1;
//             int cat2 = (Integer) category2;
//             int minCat = (cat1 < cat2 ? cat1 : cat2);
//             int maxCat = (cat1 < cat2 ? cat2 : cat1);
//             for (int i = minCat + 1; i < maxCat; i++) {
//                 v = nk.get(i);
//                 if (v != null) {
//                     result += v;
//                 }
//             }
//             return result * result;
//         }
// 
//         return (category1.equals(category2) ? 0.0 : 1.0);
//     }
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/RatioDistanceFunction.java
// public class RatioDistanceFunction
//     implements IDistanceFunction
// {
// 
//     @Override
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2)
//     {
//         if (category1 instanceof Integer && category2 instanceof Integer
//                 && (((Integer) category1) + ((Integer) category2) > 0.0)) {
//             double result = (((Integer) category1) - ((Integer) category2))
//                     / (double) (((Integer) category1) + ((Integer) category2));
//             return result * result;
//         }
// 
//         if (category1 instanceof Double && category2 instanceof Double
//                 && (((Double) category1) + ((Double) category2) > 0.0)) {
//             double result = (((Double) category1) - ((Double) category2))
//                     / (((Double) category1) + ((Double) category2));
//             return result * result;
//         }
// 
//         return (category1.equals(category2) ? 0.0 : 1.0);
//     }
// 
// }
// Path: dkpro-statistics-agreement/src/test/java/org/dkpro/statistics/agreement/coding/Krippendorff2004Test.java
import org.dkpro.statistics.agreement.distance.IDistanceFunction;
import org.dkpro.statistics.agreement.distance.IntervalDistanceFunction;
import org.dkpro.statistics.agreement.distance.NominalDistanceFunction;
import org.dkpro.statistics.agreement.distance.OrdinalDistanceFunction;
import org.dkpro.statistics.agreement.distance.RatioDistanceFunction;
import junit.framework.TestCase;
        PercentageAgreement pa = new PercentageAgreement(study);
        assertEquals(0.833, pa.calculateAgreement(), 0.001);
        KrippendorffAlphaAgreement alpha = new KrippendorffAlphaAgreement(study,
                new NominalDistanceFunction());
        assertEquals(0.1667, alpha.calculateObservedDisagreement(), 0.001);
        assertEquals(0.6268, alpha.calculateExpectedDisagreement(), 0.001);
        assertEquals(0.734, alpha.calculateAgreement(), 0.001);
    }
    
    public void testMultipleRatersMissingValues()
    {
        ICodingAnnotationStudy study = createExample3();
        PercentageAgreement pa = new PercentageAgreement(study);
        assertEquals(0.800, pa.calculateAgreement(), 0.001);
        KrippendorffAlphaAgreement alpha = new KrippendorffAlphaAgreement(study,
                new NominalDistanceFunction());
        assertEquals(0.200, alpha.calculateObservedDisagreement(), 0.001);
        assertEquals(0.779, alpha.calculateExpectedDisagreement(), 0.001);
        assertEquals(0.743, alpha.calculateAgreement(), 0.001);
    }
    
    public void testOrdinalMetric()
    {
        CodingAnnotationStudy study = createExample3a(0);
 | 
	        IDistanceFunction distFunc = new OrdinalDistanceFunction(); | 
| 
	dkpro/dkpro-statistics | 
	dkpro-statistics-agreement/src/test/java/org/dkpro/statistics/agreement/coding/Krippendorff2004Test.java | 
	// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IDistanceFunction.java
// public interface IDistanceFunction
// {
// 
//     /**
//      * Returns a distance value for the given pair of categories used within the given annotation
//      * study. Normally, the measure should return a distance of 0 if, and only if, the two
//      * categories are equal and a positive number otherwise.
//      */
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2);
// 
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IntervalDistanceFunction.java
// public class IntervalDistanceFunction
//     implements IDistanceFunction
// {
// 
//     @Override
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2)
//     {
//         if (category1 instanceof Integer && category2 instanceof Integer) {
//             return (((Integer) category1) - ((Integer) category2))
//                     * (((Integer) category1) - ((Integer) category2));
//         }
// 
//         if (category1 instanceof Double && category2 instanceof Double) {
//             return (((Double) category1) - ((Double) category2))
//                     * (((Double) category1) - ((Double) category2));
//         }
// 
//         return (category1.equals(category2) ? 0.0 : 1.0);
//     }
// 
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/NominalDistanceFunction.java
// public class NominalDistanceFunction
//     implements IDistanceFunction
// {
// 
//     @Override
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2)
//     {
//         return (category1.equals(category2) ? 0.0 : 1.0);
//     }
// 
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/OrdinalDistanceFunction.java
// public class OrdinalDistanceFunction
//     implements IDistanceFunction
// {
// 
//     @Override
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2)
//     {
//         if (category1 instanceof Integer && category2 instanceof Integer) {
//             if (category1.equals(category2)) {
//                 return 0.0;
//             }
// 
//             // TODO: Provide generic method for the annotation study w/ potential use for unitizing
//             // tasks!
//             Map<Object, Integer> nk = CodingAnnotationStudy
//                     .countTotalAnnotationsPerCategory((ICodingAnnotationStudy) study);
//             Integer v;
// 
//             double result = 0.0;
//             v = nk.get(category1);
//             if (v != null) {
//                 result += ((double) v) / 2.0;
//             }
//             v = nk.get(category2);
//             if (v != null) {
//                 result += ((double) v) / 2.0;
//             }
// 
//             int cat1 = (Integer) category1;
//             int cat2 = (Integer) category2;
//             int minCat = (cat1 < cat2 ? cat1 : cat2);
//             int maxCat = (cat1 < cat2 ? cat2 : cat1);
//             for (int i = minCat + 1; i < maxCat; i++) {
//                 v = nk.get(i);
//                 if (v != null) {
//                     result += v;
//                 }
//             }
//             return result * result;
//         }
// 
//         return (category1.equals(category2) ? 0.0 : 1.0);
//     }
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/RatioDistanceFunction.java
// public class RatioDistanceFunction
//     implements IDistanceFunction
// {
// 
//     @Override
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2)
//     {
//         if (category1 instanceof Integer && category2 instanceof Integer
//                 && (((Integer) category1) + ((Integer) category2) > 0.0)) {
//             double result = (((Integer) category1) - ((Integer) category2))
//                     / (double) (((Integer) category1) + ((Integer) category2));
//             return result * result;
//         }
// 
//         if (category1 instanceof Double && category2 instanceof Double
//                 && (((Double) category1) + ((Double) category2) > 0.0)) {
//             double result = (((Double) category1) - ((Double) category2))
//                     / (((Double) category1) + ((Double) category2));
//             return result * result;
//         }
// 
//         return (category1.equals(category2) ? 0.0 : 1.0);
//     }
// 
// }
 | 
	import org.dkpro.statistics.agreement.distance.IDistanceFunction;
import org.dkpro.statistics.agreement.distance.IntervalDistanceFunction;
import org.dkpro.statistics.agreement.distance.NominalDistanceFunction;
import org.dkpro.statistics.agreement.distance.OrdinalDistanceFunction;
import org.dkpro.statistics.agreement.distance.RatioDistanceFunction;
import junit.framework.TestCase; | 
	        CodingAnnotationStudy study = createExample3a(0);
        IDistanceFunction distFunc = new OrdinalDistanceFunction();
        final double[][] EXPECTED = new double[][]{
                {  0.0, 11.0, 22.5, 30.0, 32.5, 34.0 },
                { 11.0,  0.0, 11.5, 19.0, 21.5, 23.0 },
                { 22.5, 11.5,  0.0,  7.5, 10.0, 11.5 },
                { 30.0, 19.0,  7.5,  0.0,  2.5,  4.0 },
                { 32.5, 21.5, 10.0,  2.5,  0.0,  1.5 },
                { 34.0, 23.0, 11.5,  4.0,  1.5,  0.0 }
        }; 
        int i = 0;
        int j = 0;
        for (Object category1 : study.getCategories()) {
            for (Object category2 : study.getCategories()) {
                assertEquals("item " + category1 + "," + category2, EXPECTED[i][j] * EXPECTED[i][j],
                        distFunc.measureDistance(study, category1, category2), 0.001);
                j++;
            }
            i++;
            j = 0;
        }
    }
    
    public void testIntervallMetric()
    {
        CodingAnnotationStudy study = createExample3a(-2);
 | 
	// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IDistanceFunction.java
// public interface IDistanceFunction
// {
// 
//     /**
//      * Returns a distance value for the given pair of categories used within the given annotation
//      * study. Normally, the measure should return a distance of 0 if, and only if, the two
//      * categories are equal and a positive number otherwise.
//      */
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2);
// 
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IntervalDistanceFunction.java
// public class IntervalDistanceFunction
//     implements IDistanceFunction
// {
// 
//     @Override
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2)
//     {
//         if (category1 instanceof Integer && category2 instanceof Integer) {
//             return (((Integer) category1) - ((Integer) category2))
//                     * (((Integer) category1) - ((Integer) category2));
//         }
// 
//         if (category1 instanceof Double && category2 instanceof Double) {
//             return (((Double) category1) - ((Double) category2))
//                     * (((Double) category1) - ((Double) category2));
//         }
// 
//         return (category1.equals(category2) ? 0.0 : 1.0);
//     }
// 
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/NominalDistanceFunction.java
// public class NominalDistanceFunction
//     implements IDistanceFunction
// {
// 
//     @Override
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2)
//     {
//         return (category1.equals(category2) ? 0.0 : 1.0);
//     }
// 
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/OrdinalDistanceFunction.java
// public class OrdinalDistanceFunction
//     implements IDistanceFunction
// {
// 
//     @Override
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2)
//     {
//         if (category1 instanceof Integer && category2 instanceof Integer) {
//             if (category1.equals(category2)) {
//                 return 0.0;
//             }
// 
//             // TODO: Provide generic method for the annotation study w/ potential use for unitizing
//             // tasks!
//             Map<Object, Integer> nk = CodingAnnotationStudy
//                     .countTotalAnnotationsPerCategory((ICodingAnnotationStudy) study);
//             Integer v;
// 
//             double result = 0.0;
//             v = nk.get(category1);
//             if (v != null) {
//                 result += ((double) v) / 2.0;
//             }
//             v = nk.get(category2);
//             if (v != null) {
//                 result += ((double) v) / 2.0;
//             }
// 
//             int cat1 = (Integer) category1;
//             int cat2 = (Integer) category2;
//             int minCat = (cat1 < cat2 ? cat1 : cat2);
//             int maxCat = (cat1 < cat2 ? cat2 : cat1);
//             for (int i = minCat + 1; i < maxCat; i++) {
//                 v = nk.get(i);
//                 if (v != null) {
//                     result += v;
//                 }
//             }
//             return result * result;
//         }
// 
//         return (category1.equals(category2) ? 0.0 : 1.0);
//     }
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/RatioDistanceFunction.java
// public class RatioDistanceFunction
//     implements IDistanceFunction
// {
// 
//     @Override
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2)
//     {
//         if (category1 instanceof Integer && category2 instanceof Integer
//                 && (((Integer) category1) + ((Integer) category2) > 0.0)) {
//             double result = (((Integer) category1) - ((Integer) category2))
//                     / (double) (((Integer) category1) + ((Integer) category2));
//             return result * result;
//         }
// 
//         if (category1 instanceof Double && category2 instanceof Double
//                 && (((Double) category1) + ((Double) category2) > 0.0)) {
//             double result = (((Double) category1) - ((Double) category2))
//                     / (((Double) category1) + ((Double) category2));
//             return result * result;
//         }
// 
//         return (category1.equals(category2) ? 0.0 : 1.0);
//     }
// 
// }
// Path: dkpro-statistics-agreement/src/test/java/org/dkpro/statistics/agreement/coding/Krippendorff2004Test.java
import org.dkpro.statistics.agreement.distance.IDistanceFunction;
import org.dkpro.statistics.agreement.distance.IntervalDistanceFunction;
import org.dkpro.statistics.agreement.distance.NominalDistanceFunction;
import org.dkpro.statistics.agreement.distance.OrdinalDistanceFunction;
import org.dkpro.statistics.agreement.distance.RatioDistanceFunction;
import junit.framework.TestCase;
        CodingAnnotationStudy study = createExample3a(0);
        IDistanceFunction distFunc = new OrdinalDistanceFunction();
        final double[][] EXPECTED = new double[][]{
                {  0.0, 11.0, 22.5, 30.0, 32.5, 34.0 },
                { 11.0,  0.0, 11.5, 19.0, 21.5, 23.0 },
                { 22.5, 11.5,  0.0,  7.5, 10.0, 11.5 },
                { 30.0, 19.0,  7.5,  0.0,  2.5,  4.0 },
                { 32.5, 21.5, 10.0,  2.5,  0.0,  1.5 },
                { 34.0, 23.0, 11.5,  4.0,  1.5,  0.0 }
        }; 
        int i = 0;
        int j = 0;
        for (Object category1 : study.getCategories()) {
            for (Object category2 : study.getCategories()) {
                assertEquals("item " + category1 + "," + category2, EXPECTED[i][j] * EXPECTED[i][j],
                        distFunc.measureDistance(study, category1, category2), 0.001);
                j++;
            }
            i++;
            j = 0;
        }
    }
    
    public void testIntervallMetric()
    {
        CodingAnnotationStudy study = createExample3a(-2);
 | 
	        IDistanceFunction distFunc = new IntervalDistanceFunction(); | 
| 
	dkpro/dkpro-statistics | 
	dkpro-statistics-agreement/src/test/java/org/dkpro/statistics/agreement/coding/Krippendorff2004Test.java | 
	// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IDistanceFunction.java
// public interface IDistanceFunction
// {
// 
//     /**
//      * Returns a distance value for the given pair of categories used within the given annotation
//      * study. Normally, the measure should return a distance of 0 if, and only if, the two
//      * categories are equal and a positive number otherwise.
//      */
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2);
// 
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IntervalDistanceFunction.java
// public class IntervalDistanceFunction
//     implements IDistanceFunction
// {
// 
//     @Override
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2)
//     {
//         if (category1 instanceof Integer && category2 instanceof Integer) {
//             return (((Integer) category1) - ((Integer) category2))
//                     * (((Integer) category1) - ((Integer) category2));
//         }
// 
//         if (category1 instanceof Double && category2 instanceof Double) {
//             return (((Double) category1) - ((Double) category2))
//                     * (((Double) category1) - ((Double) category2));
//         }
// 
//         return (category1.equals(category2) ? 0.0 : 1.0);
//     }
// 
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/NominalDistanceFunction.java
// public class NominalDistanceFunction
//     implements IDistanceFunction
// {
// 
//     @Override
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2)
//     {
//         return (category1.equals(category2) ? 0.0 : 1.0);
//     }
// 
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/OrdinalDistanceFunction.java
// public class OrdinalDistanceFunction
//     implements IDistanceFunction
// {
// 
//     @Override
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2)
//     {
//         if (category1 instanceof Integer && category2 instanceof Integer) {
//             if (category1.equals(category2)) {
//                 return 0.0;
//             }
// 
//             // TODO: Provide generic method for the annotation study w/ potential use for unitizing
//             // tasks!
//             Map<Object, Integer> nk = CodingAnnotationStudy
//                     .countTotalAnnotationsPerCategory((ICodingAnnotationStudy) study);
//             Integer v;
// 
//             double result = 0.0;
//             v = nk.get(category1);
//             if (v != null) {
//                 result += ((double) v) / 2.0;
//             }
//             v = nk.get(category2);
//             if (v != null) {
//                 result += ((double) v) / 2.0;
//             }
// 
//             int cat1 = (Integer) category1;
//             int cat2 = (Integer) category2;
//             int minCat = (cat1 < cat2 ? cat1 : cat2);
//             int maxCat = (cat1 < cat2 ? cat2 : cat1);
//             for (int i = minCat + 1; i < maxCat; i++) {
//                 v = nk.get(i);
//                 if (v != null) {
//                     result += v;
//                 }
//             }
//             return result * result;
//         }
// 
//         return (category1.equals(category2) ? 0.0 : 1.0);
//     }
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/RatioDistanceFunction.java
// public class RatioDistanceFunction
//     implements IDistanceFunction
// {
// 
//     @Override
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2)
//     {
//         if (category1 instanceof Integer && category2 instanceof Integer
//                 && (((Integer) category1) + ((Integer) category2) > 0.0)) {
//             double result = (((Integer) category1) - ((Integer) category2))
//                     / (double) (((Integer) category1) + ((Integer) category2));
//             return result * result;
//         }
// 
//         if (category1 instanceof Double && category2 instanceof Double
//                 && (((Double) category1) + ((Double) category2) > 0.0)) {
//             double result = (((Double) category1) - ((Double) category2))
//                     / (((Double) category1) + ((Double) category2));
//             return result * result;
//         }
// 
//         return (category1.equals(category2) ? 0.0 : 1.0);
//     }
// 
// }
 | 
	import org.dkpro.statistics.agreement.distance.IDistanceFunction;
import org.dkpro.statistics.agreement.distance.IntervalDistanceFunction;
import org.dkpro.statistics.agreement.distance.NominalDistanceFunction;
import org.dkpro.statistics.agreement.distance.OrdinalDistanceFunction;
import org.dkpro.statistics.agreement.distance.RatioDistanceFunction;
import junit.framework.TestCase; | 
	        CodingAnnotationStudy study = createExample3a(-2);
        IDistanceFunction distFunc = new IntervalDistanceFunction();
        final double[][] EXPECTED = new double[][]{
                {  0.0,  1.0,  2.0,  3.0,  4.0,  5.0 },
                {  1.0,  0.0,  1.0,  2.0,  3.0,  4.0 },
                {  2.0,  1.0,  0.0,  1.0,  2.0,  3.0 },
                {  3.0,  2.0,  1.0,  0.0,  1.0,  2.0 },
                {  4.0,  3.0,  2.0,  1.0,  0.0,  1.0 },
                {  5.0,  4.0,  3.0,  2.0,  1.0,  0.0 }
        };
        int i = 0;
        int j = 0;
        for (Object category1 : study.getCategories()) {
            for (Object category2 : study.getCategories()) {
                assertEquals("item " + category1 + "," + category2, EXPECTED[i][j] * EXPECTED[i][j],
                        distFunc.measureDistance(study, category1, category2), 0.001);
                j++;
            }
            i++;
            j = 0;
        }
    }
    
    public void testRatioMetric()
    {
        CodingAnnotationStudy study = createExample3a(-1);
 | 
	// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IDistanceFunction.java
// public interface IDistanceFunction
// {
// 
//     /**
//      * Returns a distance value for the given pair of categories used within the given annotation
//      * study. Normally, the measure should return a distance of 0 if, and only if, the two
//      * categories are equal and a positive number otherwise.
//      */
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2);
// 
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/IntervalDistanceFunction.java
// public class IntervalDistanceFunction
//     implements IDistanceFunction
// {
// 
//     @Override
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2)
//     {
//         if (category1 instanceof Integer && category2 instanceof Integer) {
//             return (((Integer) category1) - ((Integer) category2))
//                     * (((Integer) category1) - ((Integer) category2));
//         }
// 
//         if (category1 instanceof Double && category2 instanceof Double) {
//             return (((Double) category1) - ((Double) category2))
//                     * (((Double) category1) - ((Double) category2));
//         }
// 
//         return (category1.equals(category2) ? 0.0 : 1.0);
//     }
// 
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/NominalDistanceFunction.java
// public class NominalDistanceFunction
//     implements IDistanceFunction
// {
// 
//     @Override
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2)
//     {
//         return (category1.equals(category2) ? 0.0 : 1.0);
//     }
// 
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/OrdinalDistanceFunction.java
// public class OrdinalDistanceFunction
//     implements IDistanceFunction
// {
// 
//     @Override
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2)
//     {
//         if (category1 instanceof Integer && category2 instanceof Integer) {
//             if (category1.equals(category2)) {
//                 return 0.0;
//             }
// 
//             // TODO: Provide generic method for the annotation study w/ potential use for unitizing
//             // tasks!
//             Map<Object, Integer> nk = CodingAnnotationStudy
//                     .countTotalAnnotationsPerCategory((ICodingAnnotationStudy) study);
//             Integer v;
// 
//             double result = 0.0;
//             v = nk.get(category1);
//             if (v != null) {
//                 result += ((double) v) / 2.0;
//             }
//             v = nk.get(category2);
//             if (v != null) {
//                 result += ((double) v) / 2.0;
//             }
// 
//             int cat1 = (Integer) category1;
//             int cat2 = (Integer) category2;
//             int minCat = (cat1 < cat2 ? cat1 : cat2);
//             int maxCat = (cat1 < cat2 ? cat2 : cat1);
//             for (int i = minCat + 1; i < maxCat; i++) {
//                 v = nk.get(i);
//                 if (v != null) {
//                     result += v;
//                 }
//             }
//             return result * result;
//         }
// 
//         return (category1.equals(category2) ? 0.0 : 1.0);
//     }
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/distance/RatioDistanceFunction.java
// public class RatioDistanceFunction
//     implements IDistanceFunction
// {
// 
//     @Override
//     public double measureDistance(final IAnnotationStudy study, final Object category1,
//             final Object category2)
//     {
//         if (category1 instanceof Integer && category2 instanceof Integer
//                 && (((Integer) category1) + ((Integer) category2) > 0.0)) {
//             double result = (((Integer) category1) - ((Integer) category2))
//                     / (double) (((Integer) category1) + ((Integer) category2));
//             return result * result;
//         }
// 
//         if (category1 instanceof Double && category2 instanceof Double
//                 && (((Double) category1) + ((Double) category2) > 0.0)) {
//             double result = (((Double) category1) - ((Double) category2))
//                     / (((Double) category1) + ((Double) category2));
//             return result * result;
//         }
// 
//         return (category1.equals(category2) ? 0.0 : 1.0);
//     }
// 
// }
// Path: dkpro-statistics-agreement/src/test/java/org/dkpro/statistics/agreement/coding/Krippendorff2004Test.java
import org.dkpro.statistics.agreement.distance.IDistanceFunction;
import org.dkpro.statistics.agreement.distance.IntervalDistanceFunction;
import org.dkpro.statistics.agreement.distance.NominalDistanceFunction;
import org.dkpro.statistics.agreement.distance.OrdinalDistanceFunction;
import org.dkpro.statistics.agreement.distance.RatioDistanceFunction;
import junit.framework.TestCase;
        CodingAnnotationStudy study = createExample3a(-2);
        IDistanceFunction distFunc = new IntervalDistanceFunction();
        final double[][] EXPECTED = new double[][]{
                {  0.0,  1.0,  2.0,  3.0,  4.0,  5.0 },
                {  1.0,  0.0,  1.0,  2.0,  3.0,  4.0 },
                {  2.0,  1.0,  0.0,  1.0,  2.0,  3.0 },
                {  3.0,  2.0,  1.0,  0.0,  1.0,  2.0 },
                {  4.0,  3.0,  2.0,  1.0,  0.0,  1.0 },
                {  5.0,  4.0,  3.0,  2.0,  1.0,  0.0 }
        };
        int i = 0;
        int j = 0;
        for (Object category1 : study.getCategories()) {
            for (Object category2 : study.getCategories()) {
                assertEquals("item " + category1 + "," + category2, EXPECTED[i][j] * EXPECTED[i][j],
                        distFunc.measureDistance(study, category1, category2), 0.001);
                j++;
            }
            i++;
            j = 0;
        }
    }
    
    public void testRatioMetric()
    {
        CodingAnnotationStudy study = createExample3a(-1);
 | 
	        IDistanceFunction distFunc = new RatioDistanceFunction(); | 
| 
	dkpro/dkpro-statistics | 
	dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/CohenKappaAgreement.java | 
	// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationUnit.java
// public interface IAnnotationUnit
//     extends Serializable
// {
//     /**
//      * Returns the index of the rater who coded this unit (in case of a coding study) or defined the
//      * boundaries of this unit (in case of a unitizing study). The first rater has index 0.
//      */
//     public int getRaterIdx();
// 
//     /**
//      * Returns the category assigned to this unit by one of the raters. The category might be null
//      * if, and only if, the unit represents a missing value (in case of a coding study) or a gap (in
//      * case of a unitizing study).
//      */
//     public Object getCategory();
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/ICategorySpecificAgreement.java
// public interface ICategorySpecificAgreement
// {
//     /**
//      * Calculates the inter-rater agreement for the given category.
//      * 
//      * @see ICategorySpecificAgreement
//      */
//     /*
//      * TODO @throws NullPointerException if the study is null or the given category is null.
//      * 
//      * @throws ArrayIndexOutOfBoundsException if the study does not contain the given category.
//      * 
//      * @throws ArithmeticException if the study does not contain annotations for the given category.
//      */
//     public double calculateCategoryAgreement(final Object category);
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IChanceCorrectedAgreement.java
// public interface IChanceCorrectedAgreement
//     extends IAgreementMeasure
// {
//     /**
//      * Returns the observed agreement of an annotation study. The observed agreement is basically
//      * the proportion of annotation units that the raters agree on divided by the number of units in
//      * the given study.
//      */
//     public double calculateObservedAgreement();
// 
//     /**
//      * Returns the expected agreement of an annotation study. The expected agreement is the
//      * proportion of agreement that would be expected by chance alone. The expected agreement should
//      * be equal to the observed agreement if each rater makes a random decision for each unit.
//      */
//     public double calculateExpectedAgreement();
// }
 | 
	import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Map;
import org.dkpro.statistics.agreement.IAnnotationUnit;
import org.dkpro.statistics.agreement.ICategorySpecificAgreement;
import org.dkpro.statistics.agreement.IChanceCorrectedAgreement; | 
	/*
 * Copyright 2014
 * Ubiquitous Knowledge Processing (UKP) Lab
 * Technische Universität Darmstadt
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.dkpro.statistics.agreement.coding;
/**
 * Implementation of Cohen's kappa (1960) for calculating a chance-corrected inter-rater agreement
 * for two raters. The measure assumes a different probability distribution for all raters.<br>
 * <br>
 * References:
 * <ul>
 * <li>Artstein, R. & Poesio, M.: Inter-Coder Agreement for Computational Linguistics.
 * Computational Linguistics 34(4):555-596, 2008.</li>
 * <li>Cohen, J.: A Coefficient of Agreement for Nominal Scales. Educational and Psychological
 * Measurement 20(1):37-46, 1960.</li>
 * </ul>
 * 
 * @author Christian M. Meyer
 */
public class CohenKappaAgreement
    extends CodingAgreementMeasure | 
	// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationUnit.java
// public interface IAnnotationUnit
//     extends Serializable
// {
//     /**
//      * Returns the index of the rater who coded this unit (in case of a coding study) or defined the
//      * boundaries of this unit (in case of a unitizing study). The first rater has index 0.
//      */
//     public int getRaterIdx();
// 
//     /**
//      * Returns the category assigned to this unit by one of the raters. The category might be null
//      * if, and only if, the unit represents a missing value (in case of a coding study) or a gap (in
//      * case of a unitizing study).
//      */
//     public Object getCategory();
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/ICategorySpecificAgreement.java
// public interface ICategorySpecificAgreement
// {
//     /**
//      * Calculates the inter-rater agreement for the given category.
//      * 
//      * @see ICategorySpecificAgreement
//      */
//     /*
//      * TODO @throws NullPointerException if the study is null or the given category is null.
//      * 
//      * @throws ArrayIndexOutOfBoundsException if the study does not contain the given category.
//      * 
//      * @throws ArithmeticException if the study does not contain annotations for the given category.
//      */
//     public double calculateCategoryAgreement(final Object category);
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IChanceCorrectedAgreement.java
// public interface IChanceCorrectedAgreement
//     extends IAgreementMeasure
// {
//     /**
//      * Returns the observed agreement of an annotation study. The observed agreement is basically
//      * the proportion of annotation units that the raters agree on divided by the number of units in
//      * the given study.
//      */
//     public double calculateObservedAgreement();
// 
//     /**
//      * Returns the expected agreement of an annotation study. The expected agreement is the
//      * proportion of agreement that would be expected by chance alone. The expected agreement should
//      * be equal to the observed agreement if each rater makes a random decision for each unit.
//      */
//     public double calculateExpectedAgreement();
// }
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/CohenKappaAgreement.java
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Map;
import org.dkpro.statistics.agreement.IAnnotationUnit;
import org.dkpro.statistics.agreement.ICategorySpecificAgreement;
import org.dkpro.statistics.agreement.IChanceCorrectedAgreement;
/*
 * Copyright 2014
 * Ubiquitous Knowledge Processing (UKP) Lab
 * Technische Universität Darmstadt
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.dkpro.statistics.agreement.coding;
/**
 * Implementation of Cohen's kappa (1960) for calculating a chance-corrected inter-rater agreement
 * for two raters. The measure assumes a different probability distribution for all raters.<br>
 * <br>
 * References:
 * <ul>
 * <li>Artstein, R. & Poesio, M.: Inter-Coder Agreement for Computational Linguistics.
 * Computational Linguistics 34(4):555-596, 2008.</li>
 * <li>Cohen, J.: A Coefficient of Agreement for Nominal Scales. Educational and Psychological
 * Measurement 20(1):37-46, 1960.</li>
 * </ul>
 * 
 * @author Christian M. Meyer
 */
public class CohenKappaAgreement
    extends CodingAgreementMeasure | 
	    implements IChanceCorrectedAgreement, ICategorySpecificAgreement | 
| 
	dkpro/dkpro-statistics | 
	dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/CohenKappaAgreement.java | 
	// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationUnit.java
// public interface IAnnotationUnit
//     extends Serializable
// {
//     /**
//      * Returns the index of the rater who coded this unit (in case of a coding study) or defined the
//      * boundaries of this unit (in case of a unitizing study). The first rater has index 0.
//      */
//     public int getRaterIdx();
// 
//     /**
//      * Returns the category assigned to this unit by one of the raters. The category might be null
//      * if, and only if, the unit represents a missing value (in case of a coding study) or a gap (in
//      * case of a unitizing study).
//      */
//     public Object getCategory();
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/ICategorySpecificAgreement.java
// public interface ICategorySpecificAgreement
// {
//     /**
//      * Calculates the inter-rater agreement for the given category.
//      * 
//      * @see ICategorySpecificAgreement
//      */
//     /*
//      * TODO @throws NullPointerException if the study is null or the given category is null.
//      * 
//      * @throws ArrayIndexOutOfBoundsException if the study does not contain the given category.
//      * 
//      * @throws ArithmeticException if the study does not contain annotations for the given category.
//      */
//     public double calculateCategoryAgreement(final Object category);
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IChanceCorrectedAgreement.java
// public interface IChanceCorrectedAgreement
//     extends IAgreementMeasure
// {
//     /**
//      * Returns the observed agreement of an annotation study. The observed agreement is basically
//      * the proportion of annotation units that the raters agree on divided by the number of units in
//      * the given study.
//      */
//     public double calculateObservedAgreement();
// 
//     /**
//      * Returns the expected agreement of an annotation study. The expected agreement is the
//      * proportion of agreement that would be expected by chance alone. The expected agreement should
//      * be equal to the observed agreement if each rater makes a random decision for each unit.
//      */
//     public double calculateExpectedAgreement();
// }
 | 
	import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Map;
import org.dkpro.statistics.agreement.IAnnotationUnit;
import org.dkpro.statistics.agreement.ICategorySpecificAgreement;
import org.dkpro.statistics.agreement.IChanceCorrectedAgreement; | 
	/*
 * Copyright 2014
 * Ubiquitous Knowledge Processing (UKP) Lab
 * Technische Universität Darmstadt
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.dkpro.statistics.agreement.coding;
/**
 * Implementation of Cohen's kappa (1960) for calculating a chance-corrected inter-rater agreement
 * for two raters. The measure assumes a different probability distribution for all raters.<br>
 * <br>
 * References:
 * <ul>
 * <li>Artstein, R. & Poesio, M.: Inter-Coder Agreement for Computational Linguistics.
 * Computational Linguistics 34(4):555-596, 2008.</li>
 * <li>Cohen, J.: A Coefficient of Agreement for Nominal Scales. Educational and Psychological
 * Measurement 20(1):37-46, 1960.</li>
 * </ul>
 * 
 * @author Christian M. Meyer
 */
public class CohenKappaAgreement
    extends CodingAgreementMeasure | 
	// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationUnit.java
// public interface IAnnotationUnit
//     extends Serializable
// {
//     /**
//      * Returns the index of the rater who coded this unit (in case of a coding study) or defined the
//      * boundaries of this unit (in case of a unitizing study). The first rater has index 0.
//      */
//     public int getRaterIdx();
// 
//     /**
//      * Returns the category assigned to this unit by one of the raters. The category might be null
//      * if, and only if, the unit represents a missing value (in case of a coding study) or a gap (in
//      * case of a unitizing study).
//      */
//     public Object getCategory();
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/ICategorySpecificAgreement.java
// public interface ICategorySpecificAgreement
// {
//     /**
//      * Calculates the inter-rater agreement for the given category.
//      * 
//      * @see ICategorySpecificAgreement
//      */
//     /*
//      * TODO @throws NullPointerException if the study is null or the given category is null.
//      * 
//      * @throws ArrayIndexOutOfBoundsException if the study does not contain the given category.
//      * 
//      * @throws ArithmeticException if the study does not contain annotations for the given category.
//      */
//     public double calculateCategoryAgreement(final Object category);
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IChanceCorrectedAgreement.java
// public interface IChanceCorrectedAgreement
//     extends IAgreementMeasure
// {
//     /**
//      * Returns the observed agreement of an annotation study. The observed agreement is basically
//      * the proportion of annotation units that the raters agree on divided by the number of units in
//      * the given study.
//      */
//     public double calculateObservedAgreement();
// 
//     /**
//      * Returns the expected agreement of an annotation study. The expected agreement is the
//      * proportion of agreement that would be expected by chance alone. The expected agreement should
//      * be equal to the observed agreement if each rater makes a random decision for each unit.
//      */
//     public double calculateExpectedAgreement();
// }
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/CohenKappaAgreement.java
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Map;
import org.dkpro.statistics.agreement.IAnnotationUnit;
import org.dkpro.statistics.agreement.ICategorySpecificAgreement;
import org.dkpro.statistics.agreement.IChanceCorrectedAgreement;
/*
 * Copyright 2014
 * Ubiquitous Knowledge Processing (UKP) Lab
 * Technische Universität Darmstadt
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.dkpro.statistics.agreement.coding;
/**
 * Implementation of Cohen's kappa (1960) for calculating a chance-corrected inter-rater agreement
 * for two raters. The measure assumes a different probability distribution for all raters.<br>
 * <br>
 * References:
 * <ul>
 * <li>Artstein, R. & Poesio, M.: Inter-Coder Agreement for Computational Linguistics.
 * Computational Linguistics 34(4):555-596, 2008.</li>
 * <li>Cohen, J.: A Coefficient of Agreement for Nominal Scales. Educational and Psychological
 * Measurement 20(1):37-46, 1960.</li>
 * </ul>
 * 
 * @author Christian M. Meyer
 */
public class CohenKappaAgreement
    extends CodingAgreementMeasure | 
	    implements IChanceCorrectedAgreement, ICategorySpecificAgreement | 
| 
	dkpro/dkpro-statistics | 
	dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/CohenKappaAgreement.java | 
	// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationUnit.java
// public interface IAnnotationUnit
//     extends Serializable
// {
//     /**
//      * Returns the index of the rater who coded this unit (in case of a coding study) or defined the
//      * boundaries of this unit (in case of a unitizing study). The first rater has index 0.
//      */
//     public int getRaterIdx();
// 
//     /**
//      * Returns the category assigned to this unit by one of the raters. The category might be null
//      * if, and only if, the unit represents a missing value (in case of a coding study) or a gap (in
//      * case of a unitizing study).
//      */
//     public Object getCategory();
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/ICategorySpecificAgreement.java
// public interface ICategorySpecificAgreement
// {
//     /**
//      * Calculates the inter-rater agreement for the given category.
//      * 
//      * @see ICategorySpecificAgreement
//      */
//     /*
//      * TODO @throws NullPointerException if the study is null or the given category is null.
//      * 
//      * @throws ArrayIndexOutOfBoundsException if the study does not contain the given category.
//      * 
//      * @throws ArithmeticException if the study does not contain annotations for the given category.
//      */
//     public double calculateCategoryAgreement(final Object category);
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IChanceCorrectedAgreement.java
// public interface IChanceCorrectedAgreement
//     extends IAgreementMeasure
// {
//     /**
//      * Returns the observed agreement of an annotation study. The observed agreement is basically
//      * the proportion of annotation units that the raters agree on divided by the number of units in
//      * the given study.
//      */
//     public double calculateObservedAgreement();
// 
//     /**
//      * Returns the expected agreement of an annotation study. The expected agreement is the
//      * proportion of agreement that would be expected by chance alone. The expected agreement should
//      * be equal to the observed agreement if each rater makes a random decision for each unit.
//      */
//     public double calculateExpectedAgreement();
// }
 | 
	import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Map;
import org.dkpro.statistics.agreement.IAnnotationUnit;
import org.dkpro.statistics.agreement.ICategorySpecificAgreement;
import org.dkpro.statistics.agreement.IChanceCorrectedAgreement; | 
	    /*
     * Calculates the inter-rater agreement for the given annotation category based on the object's
     * annotation study that has been passed to the class constructor.
     * 
     * @throws NullPointerException if the study is null or the given category is null.
     * 
     * @throws ArrayIndexOutOfBoundsException if the study does not contain the given category.
     * 
     * @throws ArithmeticException if the study does not contain annotations for the given category.
     */
    // Attention: This follows Agresti (1992)!
    // Artstein&Poesio have a different definition!
    @Override
    public double calculateCategoryAgreement(final Object category)
    {
        // N = # subjects = #items -> index i
        // n = # ratings/subject = #raters
        // k = # categories -> index j
        // n_ij = # raters that annotated item i as category j
        //
        // k_j = (P_j - p_j) / (1 - p_j)
        // P_j = (sum( n_ij^2 ) - N n p_j) / (N n (n-1) p_j )
        // p_j = 1/Nn sum n_ij
        int N = study.getItemCount();
        int n = study.getRaterCount();
        int sum_nij = 0;
        int sum_nij_2 = 0;
        for (ICodingAnnotationItem item : study.getItems()) {
            int nij = 0; | 
	// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IAnnotationUnit.java
// public interface IAnnotationUnit
//     extends Serializable
// {
//     /**
//      * Returns the index of the rater who coded this unit (in case of a coding study) or defined the
//      * boundaries of this unit (in case of a unitizing study). The first rater has index 0.
//      */
//     public int getRaterIdx();
// 
//     /**
//      * Returns the category assigned to this unit by one of the raters. The category might be null
//      * if, and only if, the unit represents a missing value (in case of a coding study) or a gap (in
//      * case of a unitizing study).
//      */
//     public Object getCategory();
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/ICategorySpecificAgreement.java
// public interface ICategorySpecificAgreement
// {
//     /**
//      * Calculates the inter-rater agreement for the given category.
//      * 
//      * @see ICategorySpecificAgreement
//      */
//     /*
//      * TODO @throws NullPointerException if the study is null or the given category is null.
//      * 
//      * @throws ArrayIndexOutOfBoundsException if the study does not contain the given category.
//      * 
//      * @throws ArithmeticException if the study does not contain annotations for the given category.
//      */
//     public double calculateCategoryAgreement(final Object category);
// }
// 
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/IChanceCorrectedAgreement.java
// public interface IChanceCorrectedAgreement
//     extends IAgreementMeasure
// {
//     /**
//      * Returns the observed agreement of an annotation study. The observed agreement is basically
//      * the proportion of annotation units that the raters agree on divided by the number of units in
//      * the given study.
//      */
//     public double calculateObservedAgreement();
// 
//     /**
//      * Returns the expected agreement of an annotation study. The expected agreement is the
//      * proportion of agreement that would be expected by chance alone. The expected agreement should
//      * be equal to the observed agreement if each rater makes a random decision for each unit.
//      */
//     public double calculateExpectedAgreement();
// }
// Path: dkpro-statistics-agreement/src/main/java/org/dkpro/statistics/agreement/coding/CohenKappaAgreement.java
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Map;
import org.dkpro.statistics.agreement.IAnnotationUnit;
import org.dkpro.statistics.agreement.ICategorySpecificAgreement;
import org.dkpro.statistics.agreement.IChanceCorrectedAgreement;
    /*
     * Calculates the inter-rater agreement for the given annotation category based on the object's
     * annotation study that has been passed to the class constructor.
     * 
     * @throws NullPointerException if the study is null or the given category is null.
     * 
     * @throws ArrayIndexOutOfBoundsException if the study does not contain the given category.
     * 
     * @throws ArithmeticException if the study does not contain annotations for the given category.
     */
    // Attention: This follows Agresti (1992)!
    // Artstein&Poesio have a different definition!
    @Override
    public double calculateCategoryAgreement(final Object category)
    {
        // N = # subjects = #items -> index i
        // n = # ratings/subject = #raters
        // k = # categories -> index j
        // n_ij = # raters that annotated item i as category j
        //
        // k_j = (P_j - p_j) / (1 - p_j)
        // P_j = (sum( n_ij^2 ) - N n p_j) / (N n (n-1) p_j )
        // p_j = 1/Nn sum n_ij
        int N = study.getItemCount();
        int n = study.getRaterCount();
        int sum_nij = 0;
        int sum_nij_2 = 0;
        for (ICodingAnnotationItem item : study.getItems()) {
            int nij = 0; | 
	            for (IAnnotationUnit unit : item.getUnits()) { | 
| 
	orgzly/org-java | 
	src/test/java/com/orgzly/org/OrgPropertiesTest.java | 
	// Path: src/main/java/com/orgzly/org/parser/OrgParsedFile.java
// public class OrgParsedFile { // TODO: Extend OrgFile instead?
//     private OrgFile file;
// 
//     private List<OrgNodeInList> headsInList;
// 
//     public OrgParsedFile() {
//         headsInList = new ArrayList<>();
//     }
// 
//     public OrgFile getFile() {
//         return file;
//     }
// 
//     public void setFile(OrgFile file) {
//         this.file = file;
//     }
// 
//     public List<OrgNodeInList> getHeadsInList() {
//         return headsInList;
//     }
// 
//     public void addHead(OrgNodeInList nodeInList) {
//         headsInList.add(nodeInList);
//     }
// 
//     public String toString() {
//         return toString(OrgParserSettings.getBasic());
//     }
// 
//     public String toString(OrgParserSettings settings) {
//         StringBuilder str = new StringBuilder();
// 
//         OrgParserWriter parserWriter = new OrgParserWriter(settings);
// 
//         str.append(parserWriter.whiteSpacedFilePreface(file.getPreface()));
// 
//         for (OrgNodeInList nodeInList : headsInList) {
//             str.append(parserWriter.whiteSpacedHead(nodeInList, file.getSettings().isIndented()));
//         }
// 
//         return str.toString();
//     }
// }
 | 
	import com.orgzly.org.parser.OrgParsedFile;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException; | 
	        Assert.assertEquals("BAR", properties.getAll().get(0).getValue());
        Assert.assertEquals("LAST_REPEAT", properties.getAll().get(1).getName());
        Assert.assertEquals("[2009-10-19 Mon 00:40]", properties.getAll().get(1).getValue());
    }
    @Test
    public void setReplacesExistingValue() {
        OrgProperties properties = new OrgProperties();
        properties.put("LAST_REPEAT", "[2009-10-19 Mon 00:30]");
        properties.put("LAST_REPEAT", "[2009-10-19 Mon 00:35]");
        properties.put("FOO", "BAR");
        properties.set("LAST_REPEAT", "[2009-10-19 Mon 00:40]");
        Assert.assertEquals(2, properties.size());
        Assert.assertEquals("LAST_REPEAT", properties.getAll().get(0).getName());
        Assert.assertEquals("[2009-10-19 Mon 00:40]", properties.getAll().get(0).getValue());
        Assert.assertEquals("FOO", properties.getAll().get(1).getName());
        Assert.assertEquals("BAR", properties.getAll().get(1).getValue());
    }
    @Test
    public void indented() throws IOException {
        String fileContent =
                "** TODO Note\n" +
                        ":PROPERTIES:\n" +
                        "   :STYLE:    habit\n" +
                        "   :LAST_REPEAT: [2009-10-19 Mon 00:36]\n" +
                        "   :END:";
 | 
	// Path: src/main/java/com/orgzly/org/parser/OrgParsedFile.java
// public class OrgParsedFile { // TODO: Extend OrgFile instead?
//     private OrgFile file;
// 
//     private List<OrgNodeInList> headsInList;
// 
//     public OrgParsedFile() {
//         headsInList = new ArrayList<>();
//     }
// 
//     public OrgFile getFile() {
//         return file;
//     }
// 
//     public void setFile(OrgFile file) {
//         this.file = file;
//     }
// 
//     public List<OrgNodeInList> getHeadsInList() {
//         return headsInList;
//     }
// 
//     public void addHead(OrgNodeInList nodeInList) {
//         headsInList.add(nodeInList);
//     }
// 
//     public String toString() {
//         return toString(OrgParserSettings.getBasic());
//     }
// 
//     public String toString(OrgParserSettings settings) {
//         StringBuilder str = new StringBuilder();
// 
//         OrgParserWriter parserWriter = new OrgParserWriter(settings);
// 
//         str.append(parserWriter.whiteSpacedFilePreface(file.getPreface()));
// 
//         for (OrgNodeInList nodeInList : headsInList) {
//             str.append(parserWriter.whiteSpacedHead(nodeInList, file.getSettings().isIndented()));
//         }
// 
//         return str.toString();
//     }
// }
// Path: src/test/java/com/orgzly/org/OrgPropertiesTest.java
import com.orgzly.org.parser.OrgParsedFile;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
        Assert.assertEquals("BAR", properties.getAll().get(0).getValue());
        Assert.assertEquals("LAST_REPEAT", properties.getAll().get(1).getName());
        Assert.assertEquals("[2009-10-19 Mon 00:40]", properties.getAll().get(1).getValue());
    }
    @Test
    public void setReplacesExistingValue() {
        OrgProperties properties = new OrgProperties();
        properties.put("LAST_REPEAT", "[2009-10-19 Mon 00:30]");
        properties.put("LAST_REPEAT", "[2009-10-19 Mon 00:35]");
        properties.put("FOO", "BAR");
        properties.set("LAST_REPEAT", "[2009-10-19 Mon 00:40]");
        Assert.assertEquals(2, properties.size());
        Assert.assertEquals("LAST_REPEAT", properties.getAll().get(0).getName());
        Assert.assertEquals("[2009-10-19 Mon 00:40]", properties.getAll().get(0).getValue());
        Assert.assertEquals("FOO", properties.getAll().get(1).getName());
        Assert.assertEquals("BAR", properties.getAll().get(1).getValue());
    }
    @Test
    public void indented() throws IOException {
        String fileContent =
                "** TODO Note\n" +
                        ":PROPERTIES:\n" +
                        "   :STYLE:    habit\n" +
                        "   :LAST_REPEAT: [2009-10-19 Mon 00:36]\n" +
                        "   :END:";
 | 
	        OrgParsedFile file = parserBuilder.setInput(fileContent).build().parse(); | 
| 
	orgzly/org-java | 
	src/main/java/com/orgzly/org/parser/OrgDomyParser.java | 
	// Path: src/main/java/com/orgzly/org/OrgFile.java
// public class OrgFile {
// 
//     /** In-buffer settings. */
//     private OrgFileSettings settings;
// 
//     /** Text before the first heading. */
//     private String preface;
// 
//     public OrgFile() {
// 	}
// 
//     public OrgFileSettings getSettings() {
//         if (settings == null) {
//             settings = new OrgFileSettings();
//         }
//         return settings;
//     }
// 
//     /**
//      * @return Text before first {@link OrgHead} in the file.
//      */
//     public String getPreface() {
//         return preface != null ? preface : "";
//     }
// 
//     public void setPreface(String str) {
//         preface = str;
//     }
// 
//     public String toString() {
// 		return OrgFile.class.getSimpleName() + "[" + preface.length() + "]";
// 	}
// }
 | 
	import com.orgzly.org.OrgFile;
import java.io.IOException;
import java.io.Reader; | 
	package com.orgzly.org.parser;
/**
 * Parse complete input and return it as {@link OrgParsedFile}.
 */
class OrgDomyParser extends OrgParser {
    private Reader reader;
    public OrgDomyParser(OrgParserSettings settings, Reader reader) {
        this.settings = settings;
        this.reader = reader;
    }
    @Override
    public OrgParsedFile parse() throws IOException {
        final OrgParsedFile parsedFile = new OrgParsedFile();
        OrgParser parser = new Builder(settings)
                .setInput(reader)
                .setListener(new OrgSaxyParserListener() {
                    @Override
                    public void onHead(OrgNodeInList nodeInList) throws IOException {
                        parsedFile.addHead(nodeInList);
                    }
                    @Override | 
	// Path: src/main/java/com/orgzly/org/OrgFile.java
// public class OrgFile {
// 
//     /** In-buffer settings. */
//     private OrgFileSettings settings;
// 
//     /** Text before the first heading. */
//     private String preface;
// 
//     public OrgFile() {
// 	}
// 
//     public OrgFileSettings getSettings() {
//         if (settings == null) {
//             settings = new OrgFileSettings();
//         }
//         return settings;
//     }
// 
//     /**
//      * @return Text before first {@link OrgHead} in the file.
//      */
//     public String getPreface() {
//         return preface != null ? preface : "";
//     }
// 
//     public void setPreface(String str) {
//         preface = str;
//     }
// 
//     public String toString() {
// 		return OrgFile.class.getSimpleName() + "[" + preface.length() + "]";
// 	}
// }
// Path: src/main/java/com/orgzly/org/parser/OrgDomyParser.java
import com.orgzly.org.OrgFile;
import java.io.IOException;
import java.io.Reader;
package com.orgzly.org.parser;
/**
 * Parse complete input and return it as {@link OrgParsedFile}.
 */
class OrgDomyParser extends OrgParser {
    private Reader reader;
    public OrgDomyParser(OrgParserSettings settings, Reader reader) {
        this.settings = settings;
        this.reader = reader;
    }
    @Override
    public OrgParsedFile parse() throws IOException {
        final OrgParsedFile parsedFile = new OrgParsedFile();
        OrgParser parser = new Builder(settings)
                .setInput(reader)
                .setListener(new OrgSaxyParserListener() {
                    @Override
                    public void onHead(OrgNodeInList nodeInList) throws IOException {
                        parsedFile.addHead(nodeInList);
                    }
                    @Override | 
	                    public void onFile(OrgFile file) throws IOException { | 
| 
	orgzly/org-java | 
	src/main/java/com/orgzly/org/utils/ArrayListSpaceSeparated.java | 
	// Path: src/main/java/com/orgzly/org/OrgStringUtils.java
// public class OrgStringUtils {
//     public static String trimLines(String str) {
//         return str.replaceFirst("\n+[\\s]*$", "").replaceFirst("^[\\s]*\n", "");
//     }
// 
//     public static boolean isEmpty(String s) {
//         return s == null || s.length() == 0;
//     }
// 
//     public static String join(Collection set, String d) {
//         StringBuilder result = new StringBuilder();
// 
//         int i = 0;
//         for (Object str: set) {
//             result.append(str);
// 
//             if (i++ < set.size() - 1) { /* Not last. */
//                 result.append(d);
//             }
//         }
// 
//         return result.toString();
//     }
// 
// 
// 
//     public static int stringWidth(String str) {
//         int total = 0;
// 
//         for (int i = 0; i < str.length(); ) {
//             int cp = str.codePointAt(i);
// 
//             int width = codePointWidth(cp);
// 
//             // System.out.printf("Code point %c width: %d\n", cp, width);
// 
//             total += width;
// 
//             i += Character.charCount(cp);
//         }
// 
//         return total;
//     }
// 
//     private static int codePointWidth(int cp) {
//         return EastAsianWidth.CP.contains(cp) ? 2 : 1;
//     }
// }
 | 
	import com.orgzly.org.OrgStringUtils;
import java.util.ArrayList; | 
	package com.orgzly.org.utils;
public class ArrayListSpaceSeparated extends ArrayList<String> {
    private static final String DELIMITER = " ";
    public ArrayListSpaceSeparated() {
        super();
    }
    public ArrayListSpaceSeparated(String str) {
        for (String s: str.split(DELIMITER)) {
            String st = s.trim();
            if (st.length() > 0) {
                add(st);
            }
        }
    }
    public String toString() { | 
	// Path: src/main/java/com/orgzly/org/OrgStringUtils.java
// public class OrgStringUtils {
//     public static String trimLines(String str) {
//         return str.replaceFirst("\n+[\\s]*$", "").replaceFirst("^[\\s]*\n", "");
//     }
// 
//     public static boolean isEmpty(String s) {
//         return s == null || s.length() == 0;
//     }
// 
//     public static String join(Collection set, String d) {
//         StringBuilder result = new StringBuilder();
// 
//         int i = 0;
//         for (Object str: set) {
//             result.append(str);
// 
//             if (i++ < set.size() - 1) { /* Not last. */
//                 result.append(d);
//             }
//         }
// 
//         return result.toString();
//     }
// 
// 
// 
//     public static int stringWidth(String str) {
//         int total = 0;
// 
//         for (int i = 0; i < str.length(); ) {
//             int cp = str.codePointAt(i);
// 
//             int width = codePointWidth(cp);
// 
//             // System.out.printf("Code point %c width: %d\n", cp, width);
// 
//             total += width;
// 
//             i += Character.charCount(cp);
//         }
// 
//         return total;
//     }
// 
//     private static int codePointWidth(int cp) {
//         return EastAsianWidth.CP.contains(cp) ? 2 : 1;
//     }
// }
// Path: src/main/java/com/orgzly/org/utils/ArrayListSpaceSeparated.java
import com.orgzly.org.OrgStringUtils;
import java.util.ArrayList;
package com.orgzly.org.utils;
public class ArrayListSpaceSeparated extends ArrayList<String> {
    private static final String DELIMITER = " ";
    public ArrayListSpaceSeparated() {
        super();
    }
    public ArrayListSpaceSeparated(String str) {
        for (String s: str.split(DELIMITER)) {
            String st = s.trim();
            if (st.length() > 0) {
                add(st);
            }
        }
    }
    public String toString() { | 
	        return OrgStringUtils.join(this, DELIMITER); | 
| 
	orgzly/org-java | 
	src/main/java/com/orgzly/org/datetime/OrgDelay.java | 
	// Path: src/main/java/com/orgzly/org/OrgPatterns.java
// public class OrgPatterns {
//     // org-ts-regexp-both
//     private static final String DT = "(([\\[<])[0-9]{4,}-[0-9]{2}-[0-9]{2} ?[^]\r\n>]*?[]>])";
// 
//     // org-tsr-regexp-both
//     private static final String DT_OR_RANGE = "(" + DT + "(--?-?" + DT + ")?)";
// 
//     public static final Pattern DT_OR_RANGE_P = Pattern.compile(OrgPatterns.DT_OR_RANGE);
// 
//     //  org-repeat-re
//     public static final Pattern REPEAT_P = Pattern.compile(
//             "[0-9]{4,}-[0-9][0-9]-[0-9][0-9] [^>\n]*?([.+]?\\+[0-9]+[hdwmy](/[0-9]+[hdwmy])?)");
// 
//     public static final Pattern TIME_DELAY_P = Pattern.compile("([-]{1,2}+)([0-9]+)([hdwmy])");
// 
//     public static final Pattern REPEATER = Pattern.compile(
//             "(([.+]?\\+)([0-9]+)([hdwmy]))(/([0-9]+)([hdwmy]))?");
// 
//     // org-ts-regexp0
//     public static final Pattern DT_MAYBE_WITH_TIME_P = Pattern.compile(
//             "(([0-9]{4,})-([0-9]{2})-([0-9]{2})( +[^]+0-9>\r\n -]+)?( +([0-9]{1,2}):([0-9]{2}))?)");
// 
//     /*
//      * Time of day with optional end-time.
//      * From org-get-compact-tod.
//      */
//     public static final Pattern TIME_OF_DAY_P = Pattern.compile(
//             "(([012]?[0-9]):([0-5][0-9]))(-(([012]?[0-9]):([0-5][0-9])))?");
// 
//     public static final Pattern PLANNING_TIMES_P = Pattern.compile(
//             "(SCHEDULED:|CLOSED:|DEADLINE:) *" + DT_OR_RANGE);
// 
//     public static final Pattern HEAD_P = Pattern.compile("^([*]+)\\s+(.*)\\s*$");
//     public static final Pattern HEAD_PRIORITY_P = Pattern.compile("^\\s*\\[#([A-Z])](.*)");
//     public static final Pattern HEAD_TAGS_P = Pattern.compile("^(.*)\\s+:(\\S+):\\s*$");
// 
//     // org-property-re
//     public static final Pattern PROPERTY = Pattern.compile("^[ \\t]*:(\\S+):(|[ \\t]+.*?[ \\t]*)$");
// 
//     /*
//     https://orgmode.org/manual/In_002dbuffer-settings.html
// 
//     "In-buffer settings start with ‘#+’, followed by a keyword, a colon,
//     and then a word for each setting. Org accepts multiple settings on the same line.
//     Org also accepts multiple lines for a keyword."
// 
//     Here we don't allow multiple settings per line for now.
//      */
//     public static final Pattern KEYWORD_VALUE = Pattern.compile("^#\\+([A-Za-z0-9_]+):\\s*(.*?)\\s*$");
// }
 | 
	import com.orgzly.org.OrgPatterns;
import java.util.regex.Matcher; | 
	package com.orgzly.org.datetime;
/**
 * Delay for scheduled time.
 *
 * FIXME: Also used as a warning period for deadline time.
 *
 * http://orgmode.org/manual/Deadlines-and-scheduling.html
 */
public class OrgDelay extends OrgInterval {
    public enum Type {
        ALL,         //  -
        FIRST_ONLY   //  --
    }
    private Type type;
    public static OrgDelay parse(String str) {
        OrgDelay delay = new OrgDelay();
 | 
	// Path: src/main/java/com/orgzly/org/OrgPatterns.java
// public class OrgPatterns {
//     // org-ts-regexp-both
//     private static final String DT = "(([\\[<])[0-9]{4,}-[0-9]{2}-[0-9]{2} ?[^]\r\n>]*?[]>])";
// 
//     // org-tsr-regexp-both
//     private static final String DT_OR_RANGE = "(" + DT + "(--?-?" + DT + ")?)";
// 
//     public static final Pattern DT_OR_RANGE_P = Pattern.compile(OrgPatterns.DT_OR_RANGE);
// 
//     //  org-repeat-re
//     public static final Pattern REPEAT_P = Pattern.compile(
//             "[0-9]{4,}-[0-9][0-9]-[0-9][0-9] [^>\n]*?([.+]?\\+[0-9]+[hdwmy](/[0-9]+[hdwmy])?)");
// 
//     public static final Pattern TIME_DELAY_P = Pattern.compile("([-]{1,2}+)([0-9]+)([hdwmy])");
// 
//     public static final Pattern REPEATER = Pattern.compile(
//             "(([.+]?\\+)([0-9]+)([hdwmy]))(/([0-9]+)([hdwmy]))?");
// 
//     // org-ts-regexp0
//     public static final Pattern DT_MAYBE_WITH_TIME_P = Pattern.compile(
//             "(([0-9]{4,})-([0-9]{2})-([0-9]{2})( +[^]+0-9>\r\n -]+)?( +([0-9]{1,2}):([0-9]{2}))?)");
// 
//     /*
//      * Time of day with optional end-time.
//      * From org-get-compact-tod.
//      */
//     public static final Pattern TIME_OF_DAY_P = Pattern.compile(
//             "(([012]?[0-9]):([0-5][0-9]))(-(([012]?[0-9]):([0-5][0-9])))?");
// 
//     public static final Pattern PLANNING_TIMES_P = Pattern.compile(
//             "(SCHEDULED:|CLOSED:|DEADLINE:) *" + DT_OR_RANGE);
// 
//     public static final Pattern HEAD_P = Pattern.compile("^([*]+)\\s+(.*)\\s*$");
//     public static final Pattern HEAD_PRIORITY_P = Pattern.compile("^\\s*\\[#([A-Z])](.*)");
//     public static final Pattern HEAD_TAGS_P = Pattern.compile("^(.*)\\s+:(\\S+):\\s*$");
// 
//     // org-property-re
//     public static final Pattern PROPERTY = Pattern.compile("^[ \\t]*:(\\S+):(|[ \\t]+.*?[ \\t]*)$");
// 
//     /*
//     https://orgmode.org/manual/In_002dbuffer-settings.html
// 
//     "In-buffer settings start with ‘#+’, followed by a keyword, a colon,
//     and then a word for each setting. Org accepts multiple settings on the same line.
//     Org also accepts multiple lines for a keyword."
// 
//     Here we don't allow multiple settings per line for now.
//      */
//     public static final Pattern KEYWORD_VALUE = Pattern.compile("^#\\+([A-Za-z0-9_]+):\\s*(.*?)\\s*$");
// }
// Path: src/main/java/com/orgzly/org/datetime/OrgDelay.java
import com.orgzly.org.OrgPatterns;
import java.util.regex.Matcher;
package com.orgzly.org.datetime;
/**
 * Delay for scheduled time.
 *
 * FIXME: Also used as a warning period for deadline time.
 *
 * http://orgmode.org/manual/Deadlines-and-scheduling.html
 */
public class OrgDelay extends OrgInterval {
    public enum Type {
        ALL,         //  -
        FIRST_ONLY   //  --
    }
    private Type type;
    public static OrgDelay parse(String str) {
        OrgDelay delay = new OrgDelay();
 | 
	        Matcher m = OrgPatterns.TIME_DELAY_P.matcher(str); | 
| 
	orgzly/org-java | 
	src/main/java/com/orgzly/org/OrgHead.java | 
	// Path: src/main/java/com/orgzly/org/datetime/OrgRange.java
// public class OrgRange {
//     private OrgDateTime startTime;
//     private OrgDateTime endTime;
// 
//     public static OrgRange parseOrNull(String str) {
//         if (OrgStringUtils.isEmpty(str)) {
//             return null;
//         }
// 
//         return parse(str);
//     }
// 
//     public static OrgRange parse(String str) {
//         if (str == null) {
//             throw new IllegalArgumentException("OrgRange cannot be created from null string");
//         }
// 
//         if (str.length() == 0) {
//             throw new IllegalArgumentException("OrgRange cannot be created from null string");
//         }
// 
//         OrgRange t = new OrgRange();
// 
//         Matcher m = OrgPatterns.DT_OR_RANGE_P.matcher(str);
// 
//         if (m.find()) {
// //            for (int i = 0; i < m.groupCount() + 1; i++) {
// //                System.out.println("group(" + i + ") " + m.group(i));
// //            }
// 
//             if (m.groupCount() == 6 && m.group(6) != null) { // Range - two timestamps
//                 t.startTime = OrgDateTime.parse(m.group(2));
//                 t.endTime = OrgDateTime.parse(m.group(5));
// 
//             } else { // Single timestamp
//                 t.startTime = OrgDateTime.parse(m.group(2));
//                 t.endTime = null;
//             }
// 
//             return t;
// 
//         } else {
//             throw new IllegalArgumentException(
//                     "String " + str +
//                     " cannot be parsed as OrgRange using pattern " + OrgPatterns.DT_OR_RANGE_P);
//         }
//     }
// 
//     // TODO: Rename to parse, rename other methods to getInstance, add *orThrow methods if needed
//     public static OrgRange doParse(String str) {
//         try {
//             // Make sure both OrgDateTime are actually parsed.
//             // This is pretty bad, clean these classes.
//             OrgRange range = OrgRange.parse(str);
//             range.startTime.getCalendar();
//             if (range.endTime != null) {
//                 range.endTime.getCalendar();
//             }
//             return range;
//         } catch (Exception e) {
//             return null;
//         }
//     }
// 
//     private OrgRange() {
//     }
// 
//     public OrgRange(OrgRange orgRange) {
//         this.startTime = new OrgDateTime(orgRange.getStartTime());
// 
//         if (orgRange.getEndTime() != null) {
//             this.endTime = new OrgDateTime(orgRange.getEndTime());
//         }
//     }
// 
//     public OrgRange(OrgDateTime fromTime) {
//         this(fromTime, null);
//     }
// 
//     public OrgRange(OrgDateTime fromTime, OrgDateTime endTime) {
//         if (fromTime == null) {
//             throw new IllegalArgumentException("OrgRange cannot be created from null OrgDateTime");
//         }
// 
//         this.startTime = fromTime;
//         this.endTime = endTime;
//     }
// 
//     public OrgDateTime getStartTime() {
//         return startTime;
//     }
// 
//     /**
//      * @return last time of the range, can be {@code null}
//      */
//     @Nullable
//     public OrgDateTime getEndTime() {
//         return endTime;
//     }
// 
//     public boolean isSet() {
//         return startTime != null;
//     }
// 
//     public String toString() {
//         StringBuilder s = new StringBuilder();
// 
//         s.append(startTime);
// 
//         if (endTime != null) {
//             s.append("--");
//             s.append(endTime);
//         }
// 
//         return s.toString();
//     }
// 
//     public String toStringWithoutBrackets() {
//         StringBuilder s = new StringBuilder();
// 
//         s.append(startTime.toStringWithoutBrackets());
// 
//         if (endTime != null) {
//             s.append("--");
//             s.append(endTime.toStringWithoutBrackets());
//         }
// 
//         return s.toString();
//     }
// 
//     public boolean shift() {
//         return shift(Calendar.getInstance());
//     }
// 
//     /**
//      * Shifts both timestamps by their repeater intervals.
//      *
//      * @param now current time
//      * @return {@code true} if shift was performed
//      */
//     public boolean shift(Calendar now) {
//         boolean shifted = false;
// 
//         if (startTime != null) {
//             if (startTime.shift(now)) {
//                 shifted = true;
//             }
//         }
// 
//         if (endTime != null) {
//             if (endTime.shift(now)) {
//                 shifted = true;
//             }
//         }
// 
//         return shifted;
//     }
// }
 | 
	import com.orgzly.org.datetime.OrgRange;
import java.util.ArrayList;
import java.util.List; | 
	package com.orgzly.org;
/**
 * Heading with text below it.
 *
 * Does not contain any coordinates (position within the outline), not even a level.
 */
public class OrgHead {
    private String title;
    private List<String> tags;
    private String state;
    private String priority;
 | 
	// Path: src/main/java/com/orgzly/org/datetime/OrgRange.java
// public class OrgRange {
//     private OrgDateTime startTime;
//     private OrgDateTime endTime;
// 
//     public static OrgRange parseOrNull(String str) {
//         if (OrgStringUtils.isEmpty(str)) {
//             return null;
//         }
// 
//         return parse(str);
//     }
// 
//     public static OrgRange parse(String str) {
//         if (str == null) {
//             throw new IllegalArgumentException("OrgRange cannot be created from null string");
//         }
// 
//         if (str.length() == 0) {
//             throw new IllegalArgumentException("OrgRange cannot be created from null string");
//         }
// 
//         OrgRange t = new OrgRange();
// 
//         Matcher m = OrgPatterns.DT_OR_RANGE_P.matcher(str);
// 
//         if (m.find()) {
// //            for (int i = 0; i < m.groupCount() + 1; i++) {
// //                System.out.println("group(" + i + ") " + m.group(i));
// //            }
// 
//             if (m.groupCount() == 6 && m.group(6) != null) { // Range - two timestamps
//                 t.startTime = OrgDateTime.parse(m.group(2));
//                 t.endTime = OrgDateTime.parse(m.group(5));
// 
//             } else { // Single timestamp
//                 t.startTime = OrgDateTime.parse(m.group(2));
//                 t.endTime = null;
//             }
// 
//             return t;
// 
//         } else {
//             throw new IllegalArgumentException(
//                     "String " + str +
//                     " cannot be parsed as OrgRange using pattern " + OrgPatterns.DT_OR_RANGE_P);
//         }
//     }
// 
//     // TODO: Rename to parse, rename other methods to getInstance, add *orThrow methods if needed
//     public static OrgRange doParse(String str) {
//         try {
//             // Make sure both OrgDateTime are actually parsed.
//             // This is pretty bad, clean these classes.
//             OrgRange range = OrgRange.parse(str);
//             range.startTime.getCalendar();
//             if (range.endTime != null) {
//                 range.endTime.getCalendar();
//             }
//             return range;
//         } catch (Exception e) {
//             return null;
//         }
//     }
// 
//     private OrgRange() {
//     }
// 
//     public OrgRange(OrgRange orgRange) {
//         this.startTime = new OrgDateTime(orgRange.getStartTime());
// 
//         if (orgRange.getEndTime() != null) {
//             this.endTime = new OrgDateTime(orgRange.getEndTime());
//         }
//     }
// 
//     public OrgRange(OrgDateTime fromTime) {
//         this(fromTime, null);
//     }
// 
//     public OrgRange(OrgDateTime fromTime, OrgDateTime endTime) {
//         if (fromTime == null) {
//             throw new IllegalArgumentException("OrgRange cannot be created from null OrgDateTime");
//         }
// 
//         this.startTime = fromTime;
//         this.endTime = endTime;
//     }
// 
//     public OrgDateTime getStartTime() {
//         return startTime;
//     }
// 
//     /**
//      * @return last time of the range, can be {@code null}
//      */
//     @Nullable
//     public OrgDateTime getEndTime() {
//         return endTime;
//     }
// 
//     public boolean isSet() {
//         return startTime != null;
//     }
// 
//     public String toString() {
//         StringBuilder s = new StringBuilder();
// 
//         s.append(startTime);
// 
//         if (endTime != null) {
//             s.append("--");
//             s.append(endTime);
//         }
// 
//         return s.toString();
//     }
// 
//     public String toStringWithoutBrackets() {
//         StringBuilder s = new StringBuilder();
// 
//         s.append(startTime.toStringWithoutBrackets());
// 
//         if (endTime != null) {
//             s.append("--");
//             s.append(endTime.toStringWithoutBrackets());
//         }
// 
//         return s.toString();
//     }
// 
//     public boolean shift() {
//         return shift(Calendar.getInstance());
//     }
// 
//     /**
//      * Shifts both timestamps by their repeater intervals.
//      *
//      * @param now current time
//      * @return {@code true} if shift was performed
//      */
//     public boolean shift(Calendar now) {
//         boolean shifted = false;
// 
//         if (startTime != null) {
//             if (startTime.shift(now)) {
//                 shifted = true;
//             }
//         }
// 
//         if (endTime != null) {
//             if (endTime.shift(now)) {
//                 shifted = true;
//             }
//         }
// 
//         return shifted;
//     }
// }
// Path: src/main/java/com/orgzly/org/OrgHead.java
import com.orgzly.org.datetime.OrgRange;
import java.util.ArrayList;
import java.util.List;
package com.orgzly.org;
/**
 * Heading with text below it.
 *
 * Does not contain any coordinates (position within the outline), not even a level.
 */
public class OrgHead {
    private String title;
    private List<String> tags;
    private String state;
    private String priority;
 | 
	    private OrgRange scheduled; | 
| 
	orgzly/org-java | 
	src/main/java/com/orgzly/org/datetime/OrgRange.java | 
	// Path: src/main/java/com/orgzly/org/OrgPatterns.java
// public class OrgPatterns {
//     // org-ts-regexp-both
//     private static final String DT = "(([\\[<])[0-9]{4,}-[0-9]{2}-[0-9]{2} ?[^]\r\n>]*?[]>])";
// 
//     // org-tsr-regexp-both
//     private static final String DT_OR_RANGE = "(" + DT + "(--?-?" + DT + ")?)";
// 
//     public static final Pattern DT_OR_RANGE_P = Pattern.compile(OrgPatterns.DT_OR_RANGE);
// 
//     //  org-repeat-re
//     public static final Pattern REPEAT_P = Pattern.compile(
//             "[0-9]{4,}-[0-9][0-9]-[0-9][0-9] [^>\n]*?([.+]?\\+[0-9]+[hdwmy](/[0-9]+[hdwmy])?)");
// 
//     public static final Pattern TIME_DELAY_P = Pattern.compile("([-]{1,2}+)([0-9]+)([hdwmy])");
// 
//     public static final Pattern REPEATER = Pattern.compile(
//             "(([.+]?\\+)([0-9]+)([hdwmy]))(/([0-9]+)([hdwmy]))?");
// 
//     // org-ts-regexp0
//     public static final Pattern DT_MAYBE_WITH_TIME_P = Pattern.compile(
//             "(([0-9]{4,})-([0-9]{2})-([0-9]{2})( +[^]+0-9>\r\n -]+)?( +([0-9]{1,2}):([0-9]{2}))?)");
// 
//     /*
//      * Time of day with optional end-time.
//      * From org-get-compact-tod.
//      */
//     public static final Pattern TIME_OF_DAY_P = Pattern.compile(
//             "(([012]?[0-9]):([0-5][0-9]))(-(([012]?[0-9]):([0-5][0-9])))?");
// 
//     public static final Pattern PLANNING_TIMES_P = Pattern.compile(
//             "(SCHEDULED:|CLOSED:|DEADLINE:) *" + DT_OR_RANGE);
// 
//     public static final Pattern HEAD_P = Pattern.compile("^([*]+)\\s+(.*)\\s*$");
//     public static final Pattern HEAD_PRIORITY_P = Pattern.compile("^\\s*\\[#([A-Z])](.*)");
//     public static final Pattern HEAD_TAGS_P = Pattern.compile("^(.*)\\s+:(\\S+):\\s*$");
// 
//     // org-property-re
//     public static final Pattern PROPERTY = Pattern.compile("^[ \\t]*:(\\S+):(|[ \\t]+.*?[ \\t]*)$");
// 
//     /*
//     https://orgmode.org/manual/In_002dbuffer-settings.html
// 
//     "In-buffer settings start with ‘#+’, followed by a keyword, a colon,
//     and then a word for each setting. Org accepts multiple settings on the same line.
//     Org also accepts multiple lines for a keyword."
// 
//     Here we don't allow multiple settings per line for now.
//      */
//     public static final Pattern KEYWORD_VALUE = Pattern.compile("^#\\+([A-Za-z0-9_]+):\\s*(.*?)\\s*$");
// }
// 
// Path: src/main/java/com/orgzly/org/OrgStringUtils.java
// public class OrgStringUtils {
//     public static String trimLines(String str) {
//         return str.replaceFirst("\n+[\\s]*$", "").replaceFirst("^[\\s]*\n", "");
//     }
// 
//     public static boolean isEmpty(String s) {
//         return s == null || s.length() == 0;
//     }
// 
//     public static String join(Collection set, String d) {
//         StringBuilder result = new StringBuilder();
// 
//         int i = 0;
//         for (Object str: set) {
//             result.append(str);
// 
//             if (i++ < set.size() - 1) { /* Not last. */
//                 result.append(d);
//             }
//         }
// 
//         return result.toString();
//     }
// 
// 
// 
//     public static int stringWidth(String str) {
//         int total = 0;
// 
//         for (int i = 0; i < str.length(); ) {
//             int cp = str.codePointAt(i);
// 
//             int width = codePointWidth(cp);
// 
//             // System.out.printf("Code point %c width: %d\n", cp, width);
// 
//             total += width;
// 
//             i += Character.charCount(cp);
//         }
// 
//         return total;
//     }
// 
//     private static int codePointWidth(int cp) {
//         return EastAsianWidth.CP.contains(cp) ? 2 : 1;
//     }
// }
 | 
	import com.orgzly.org.OrgPatterns;
import com.orgzly.org.OrgStringUtils;
import org.jetbrains.annotations.Nullable;
import java.util.Calendar;
import java.util.regex.Matcher; | 
	package com.orgzly.org.datetime;
/**
 * Org mode range.
 *
 * For example {@literal <2004-08-23 Mon>} or {@literal <2004-08-23 Mon>--<2004-08-26 Thu>}.
 */
public class OrgRange {
    private OrgDateTime startTime;
    private OrgDateTime endTime;
    public static OrgRange parseOrNull(String str) { | 
	// Path: src/main/java/com/orgzly/org/OrgPatterns.java
// public class OrgPatterns {
//     // org-ts-regexp-both
//     private static final String DT = "(([\\[<])[0-9]{4,}-[0-9]{2}-[0-9]{2} ?[^]\r\n>]*?[]>])";
// 
//     // org-tsr-regexp-both
//     private static final String DT_OR_RANGE = "(" + DT + "(--?-?" + DT + ")?)";
// 
//     public static final Pattern DT_OR_RANGE_P = Pattern.compile(OrgPatterns.DT_OR_RANGE);
// 
//     //  org-repeat-re
//     public static final Pattern REPEAT_P = Pattern.compile(
//             "[0-9]{4,}-[0-9][0-9]-[0-9][0-9] [^>\n]*?([.+]?\\+[0-9]+[hdwmy](/[0-9]+[hdwmy])?)");
// 
//     public static final Pattern TIME_DELAY_P = Pattern.compile("([-]{1,2}+)([0-9]+)([hdwmy])");
// 
//     public static final Pattern REPEATER = Pattern.compile(
//             "(([.+]?\\+)([0-9]+)([hdwmy]))(/([0-9]+)([hdwmy]))?");
// 
//     // org-ts-regexp0
//     public static final Pattern DT_MAYBE_WITH_TIME_P = Pattern.compile(
//             "(([0-9]{4,})-([0-9]{2})-([0-9]{2})( +[^]+0-9>\r\n -]+)?( +([0-9]{1,2}):([0-9]{2}))?)");
// 
//     /*
//      * Time of day with optional end-time.
//      * From org-get-compact-tod.
//      */
//     public static final Pattern TIME_OF_DAY_P = Pattern.compile(
//             "(([012]?[0-9]):([0-5][0-9]))(-(([012]?[0-9]):([0-5][0-9])))?");
// 
//     public static final Pattern PLANNING_TIMES_P = Pattern.compile(
//             "(SCHEDULED:|CLOSED:|DEADLINE:) *" + DT_OR_RANGE);
// 
//     public static final Pattern HEAD_P = Pattern.compile("^([*]+)\\s+(.*)\\s*$");
//     public static final Pattern HEAD_PRIORITY_P = Pattern.compile("^\\s*\\[#([A-Z])](.*)");
//     public static final Pattern HEAD_TAGS_P = Pattern.compile("^(.*)\\s+:(\\S+):\\s*$");
// 
//     // org-property-re
//     public static final Pattern PROPERTY = Pattern.compile("^[ \\t]*:(\\S+):(|[ \\t]+.*?[ \\t]*)$");
// 
//     /*
//     https://orgmode.org/manual/In_002dbuffer-settings.html
// 
//     "In-buffer settings start with ‘#+’, followed by a keyword, a colon,
//     and then a word for each setting. Org accepts multiple settings on the same line.
//     Org also accepts multiple lines for a keyword."
// 
//     Here we don't allow multiple settings per line for now.
//      */
//     public static final Pattern KEYWORD_VALUE = Pattern.compile("^#\\+([A-Za-z0-9_]+):\\s*(.*?)\\s*$");
// }
// 
// Path: src/main/java/com/orgzly/org/OrgStringUtils.java
// public class OrgStringUtils {
//     public static String trimLines(String str) {
//         return str.replaceFirst("\n+[\\s]*$", "").replaceFirst("^[\\s]*\n", "");
//     }
// 
//     public static boolean isEmpty(String s) {
//         return s == null || s.length() == 0;
//     }
// 
//     public static String join(Collection set, String d) {
//         StringBuilder result = new StringBuilder();
// 
//         int i = 0;
//         for (Object str: set) {
//             result.append(str);
// 
//             if (i++ < set.size() - 1) { /* Not last. */
//                 result.append(d);
//             }
//         }
// 
//         return result.toString();
//     }
// 
// 
// 
//     public static int stringWidth(String str) {
//         int total = 0;
// 
//         for (int i = 0; i < str.length(); ) {
//             int cp = str.codePointAt(i);
// 
//             int width = codePointWidth(cp);
// 
//             // System.out.printf("Code point %c width: %d\n", cp, width);
// 
//             total += width;
// 
//             i += Character.charCount(cp);
//         }
// 
//         return total;
//     }
// 
//     private static int codePointWidth(int cp) {
//         return EastAsianWidth.CP.contains(cp) ? 2 : 1;
//     }
// }
// Path: src/main/java/com/orgzly/org/datetime/OrgRange.java
import com.orgzly.org.OrgPatterns;
import com.orgzly.org.OrgStringUtils;
import org.jetbrains.annotations.Nullable;
import java.util.Calendar;
import java.util.regex.Matcher;
package com.orgzly.org.datetime;
/**
 * Org mode range.
 *
 * For example {@literal <2004-08-23 Mon>} or {@literal <2004-08-23 Mon>--<2004-08-26 Thu>}.
 */
public class OrgRange {
    private OrgDateTime startTime;
    private OrgDateTime endTime;
    public static OrgRange parseOrNull(String str) { | 
	        if (OrgStringUtils.isEmpty(str)) { | 
| 
	orgzly/org-java | 
	src/main/java/com/orgzly/org/datetime/OrgRange.java | 
	// Path: src/main/java/com/orgzly/org/OrgPatterns.java
// public class OrgPatterns {
//     // org-ts-regexp-both
//     private static final String DT = "(([\\[<])[0-9]{4,}-[0-9]{2}-[0-9]{2} ?[^]\r\n>]*?[]>])";
// 
//     // org-tsr-regexp-both
//     private static final String DT_OR_RANGE = "(" + DT + "(--?-?" + DT + ")?)";
// 
//     public static final Pattern DT_OR_RANGE_P = Pattern.compile(OrgPatterns.DT_OR_RANGE);
// 
//     //  org-repeat-re
//     public static final Pattern REPEAT_P = Pattern.compile(
//             "[0-9]{4,}-[0-9][0-9]-[0-9][0-9] [^>\n]*?([.+]?\\+[0-9]+[hdwmy](/[0-9]+[hdwmy])?)");
// 
//     public static final Pattern TIME_DELAY_P = Pattern.compile("([-]{1,2}+)([0-9]+)([hdwmy])");
// 
//     public static final Pattern REPEATER = Pattern.compile(
//             "(([.+]?\\+)([0-9]+)([hdwmy]))(/([0-9]+)([hdwmy]))?");
// 
//     // org-ts-regexp0
//     public static final Pattern DT_MAYBE_WITH_TIME_P = Pattern.compile(
//             "(([0-9]{4,})-([0-9]{2})-([0-9]{2})( +[^]+0-9>\r\n -]+)?( +([0-9]{1,2}):([0-9]{2}))?)");
// 
//     /*
//      * Time of day with optional end-time.
//      * From org-get-compact-tod.
//      */
//     public static final Pattern TIME_OF_DAY_P = Pattern.compile(
//             "(([012]?[0-9]):([0-5][0-9]))(-(([012]?[0-9]):([0-5][0-9])))?");
// 
//     public static final Pattern PLANNING_TIMES_P = Pattern.compile(
//             "(SCHEDULED:|CLOSED:|DEADLINE:) *" + DT_OR_RANGE);
// 
//     public static final Pattern HEAD_P = Pattern.compile("^([*]+)\\s+(.*)\\s*$");
//     public static final Pattern HEAD_PRIORITY_P = Pattern.compile("^\\s*\\[#([A-Z])](.*)");
//     public static final Pattern HEAD_TAGS_P = Pattern.compile("^(.*)\\s+:(\\S+):\\s*$");
// 
//     // org-property-re
//     public static final Pattern PROPERTY = Pattern.compile("^[ \\t]*:(\\S+):(|[ \\t]+.*?[ \\t]*)$");
// 
//     /*
//     https://orgmode.org/manual/In_002dbuffer-settings.html
// 
//     "In-buffer settings start with ‘#+’, followed by a keyword, a colon,
//     and then a word for each setting. Org accepts multiple settings on the same line.
//     Org also accepts multiple lines for a keyword."
// 
//     Here we don't allow multiple settings per line for now.
//      */
//     public static final Pattern KEYWORD_VALUE = Pattern.compile("^#\\+([A-Za-z0-9_]+):\\s*(.*?)\\s*$");
// }
// 
// Path: src/main/java/com/orgzly/org/OrgStringUtils.java
// public class OrgStringUtils {
//     public static String trimLines(String str) {
//         return str.replaceFirst("\n+[\\s]*$", "").replaceFirst("^[\\s]*\n", "");
//     }
// 
//     public static boolean isEmpty(String s) {
//         return s == null || s.length() == 0;
//     }
// 
//     public static String join(Collection set, String d) {
//         StringBuilder result = new StringBuilder();
// 
//         int i = 0;
//         for (Object str: set) {
//             result.append(str);
// 
//             if (i++ < set.size() - 1) { /* Not last. */
//                 result.append(d);
//             }
//         }
// 
//         return result.toString();
//     }
// 
// 
// 
//     public static int stringWidth(String str) {
//         int total = 0;
// 
//         for (int i = 0; i < str.length(); ) {
//             int cp = str.codePointAt(i);
// 
//             int width = codePointWidth(cp);
// 
//             // System.out.printf("Code point %c width: %d\n", cp, width);
// 
//             total += width;
// 
//             i += Character.charCount(cp);
//         }
// 
//         return total;
//     }
// 
//     private static int codePointWidth(int cp) {
//         return EastAsianWidth.CP.contains(cp) ? 2 : 1;
//     }
// }
 | 
	import com.orgzly.org.OrgPatterns;
import com.orgzly.org.OrgStringUtils;
import org.jetbrains.annotations.Nullable;
import java.util.Calendar;
import java.util.regex.Matcher; | 
	package com.orgzly.org.datetime;
/**
 * Org mode range.
 *
 * For example {@literal <2004-08-23 Mon>} or {@literal <2004-08-23 Mon>--<2004-08-26 Thu>}.
 */
public class OrgRange {
    private OrgDateTime startTime;
    private OrgDateTime endTime;
    public static OrgRange parseOrNull(String str) {
        if (OrgStringUtils.isEmpty(str)) {
            return null;
        }
        return parse(str);
    }
    public static OrgRange parse(String str) {
        if (str == null) {
            throw new IllegalArgumentException("OrgRange cannot be created from null string");
        }
        if (str.length() == 0) {
            throw new IllegalArgumentException("OrgRange cannot be created from null string");
        }
        OrgRange t = new OrgRange();
 | 
	// Path: src/main/java/com/orgzly/org/OrgPatterns.java
// public class OrgPatterns {
//     // org-ts-regexp-both
//     private static final String DT = "(([\\[<])[0-9]{4,}-[0-9]{2}-[0-9]{2} ?[^]\r\n>]*?[]>])";
// 
//     // org-tsr-regexp-both
//     private static final String DT_OR_RANGE = "(" + DT + "(--?-?" + DT + ")?)";
// 
//     public static final Pattern DT_OR_RANGE_P = Pattern.compile(OrgPatterns.DT_OR_RANGE);
// 
//     //  org-repeat-re
//     public static final Pattern REPEAT_P = Pattern.compile(
//             "[0-9]{4,}-[0-9][0-9]-[0-9][0-9] [^>\n]*?([.+]?\\+[0-9]+[hdwmy](/[0-9]+[hdwmy])?)");
// 
//     public static final Pattern TIME_DELAY_P = Pattern.compile("([-]{1,2}+)([0-9]+)([hdwmy])");
// 
//     public static final Pattern REPEATER = Pattern.compile(
//             "(([.+]?\\+)([0-9]+)([hdwmy]))(/([0-9]+)([hdwmy]))?");
// 
//     // org-ts-regexp0
//     public static final Pattern DT_MAYBE_WITH_TIME_P = Pattern.compile(
//             "(([0-9]{4,})-([0-9]{2})-([0-9]{2})( +[^]+0-9>\r\n -]+)?( +([0-9]{1,2}):([0-9]{2}))?)");
// 
//     /*
//      * Time of day with optional end-time.
//      * From org-get-compact-tod.
//      */
//     public static final Pattern TIME_OF_DAY_P = Pattern.compile(
//             "(([012]?[0-9]):([0-5][0-9]))(-(([012]?[0-9]):([0-5][0-9])))?");
// 
//     public static final Pattern PLANNING_TIMES_P = Pattern.compile(
//             "(SCHEDULED:|CLOSED:|DEADLINE:) *" + DT_OR_RANGE);
// 
//     public static final Pattern HEAD_P = Pattern.compile("^([*]+)\\s+(.*)\\s*$");
//     public static final Pattern HEAD_PRIORITY_P = Pattern.compile("^\\s*\\[#([A-Z])](.*)");
//     public static final Pattern HEAD_TAGS_P = Pattern.compile("^(.*)\\s+:(\\S+):\\s*$");
// 
//     // org-property-re
//     public static final Pattern PROPERTY = Pattern.compile("^[ \\t]*:(\\S+):(|[ \\t]+.*?[ \\t]*)$");
// 
//     /*
//     https://orgmode.org/manual/In_002dbuffer-settings.html
// 
//     "In-buffer settings start with ‘#+’, followed by a keyword, a colon,
//     and then a word for each setting. Org accepts multiple settings on the same line.
//     Org also accepts multiple lines for a keyword."
// 
//     Here we don't allow multiple settings per line for now.
//      */
//     public static final Pattern KEYWORD_VALUE = Pattern.compile("^#\\+([A-Za-z0-9_]+):\\s*(.*?)\\s*$");
// }
// 
// Path: src/main/java/com/orgzly/org/OrgStringUtils.java
// public class OrgStringUtils {
//     public static String trimLines(String str) {
//         return str.replaceFirst("\n+[\\s]*$", "").replaceFirst("^[\\s]*\n", "");
//     }
// 
//     public static boolean isEmpty(String s) {
//         return s == null || s.length() == 0;
//     }
// 
//     public static String join(Collection set, String d) {
//         StringBuilder result = new StringBuilder();
// 
//         int i = 0;
//         for (Object str: set) {
//             result.append(str);
// 
//             if (i++ < set.size() - 1) { /* Not last. */
//                 result.append(d);
//             }
//         }
// 
//         return result.toString();
//     }
// 
// 
// 
//     public static int stringWidth(String str) {
//         int total = 0;
// 
//         for (int i = 0; i < str.length(); ) {
//             int cp = str.codePointAt(i);
// 
//             int width = codePointWidth(cp);
// 
//             // System.out.printf("Code point %c width: %d\n", cp, width);
// 
//             total += width;
// 
//             i += Character.charCount(cp);
//         }
// 
//         return total;
//     }
// 
//     private static int codePointWidth(int cp) {
//         return EastAsianWidth.CP.contains(cp) ? 2 : 1;
//     }
// }
// Path: src/main/java/com/orgzly/org/datetime/OrgRange.java
import com.orgzly.org.OrgPatterns;
import com.orgzly.org.OrgStringUtils;
import org.jetbrains.annotations.Nullable;
import java.util.Calendar;
import java.util.regex.Matcher;
package com.orgzly.org.datetime;
/**
 * Org mode range.
 *
 * For example {@literal <2004-08-23 Mon>} or {@literal <2004-08-23 Mon>--<2004-08-26 Thu>}.
 */
public class OrgRange {
    private OrgDateTime startTime;
    private OrgDateTime endTime;
    public static OrgRange parseOrNull(String str) {
        if (OrgStringUtils.isEmpty(str)) {
            return null;
        }
        return parse(str);
    }
    public static OrgRange parse(String str) {
        if (str == null) {
            throw new IllegalArgumentException("OrgRange cannot be created from null string");
        }
        if (str.length() == 0) {
            throw new IllegalArgumentException("OrgRange cannot be created from null string");
        }
        OrgRange t = new OrgRange();
 | 
	        Matcher m = OrgPatterns.DT_OR_RANGE_P.matcher(str); | 
| 
	orgzly/org-java | 
	src/main/java/com/orgzly/org/datetime/OrgRepeater.java | 
	// Path: src/main/java/com/orgzly/org/OrgPatterns.java
// public class OrgPatterns {
//     // org-ts-regexp-both
//     private static final String DT = "(([\\[<])[0-9]{4,}-[0-9]{2}-[0-9]{2} ?[^]\r\n>]*?[]>])";
// 
//     // org-tsr-regexp-both
//     private static final String DT_OR_RANGE = "(" + DT + "(--?-?" + DT + ")?)";
// 
//     public static final Pattern DT_OR_RANGE_P = Pattern.compile(OrgPatterns.DT_OR_RANGE);
// 
//     //  org-repeat-re
//     public static final Pattern REPEAT_P = Pattern.compile(
//             "[0-9]{4,}-[0-9][0-9]-[0-9][0-9] [^>\n]*?([.+]?\\+[0-9]+[hdwmy](/[0-9]+[hdwmy])?)");
// 
//     public static final Pattern TIME_DELAY_P = Pattern.compile("([-]{1,2}+)([0-9]+)([hdwmy])");
// 
//     public static final Pattern REPEATER = Pattern.compile(
//             "(([.+]?\\+)([0-9]+)([hdwmy]))(/([0-9]+)([hdwmy]))?");
// 
//     // org-ts-regexp0
//     public static final Pattern DT_MAYBE_WITH_TIME_P = Pattern.compile(
//             "(([0-9]{4,})-([0-9]{2})-([0-9]{2})( +[^]+0-9>\r\n -]+)?( +([0-9]{1,2}):([0-9]{2}))?)");
// 
//     /*
//      * Time of day with optional end-time.
//      * From org-get-compact-tod.
//      */
//     public static final Pattern TIME_OF_DAY_P = Pattern.compile(
//             "(([012]?[0-9]):([0-5][0-9]))(-(([012]?[0-9]):([0-5][0-9])))?");
// 
//     public static final Pattern PLANNING_TIMES_P = Pattern.compile(
//             "(SCHEDULED:|CLOSED:|DEADLINE:) *" + DT_OR_RANGE);
// 
//     public static final Pattern HEAD_P = Pattern.compile("^([*]+)\\s+(.*)\\s*$");
//     public static final Pattern HEAD_PRIORITY_P = Pattern.compile("^\\s*\\[#([A-Z])](.*)");
//     public static final Pattern HEAD_TAGS_P = Pattern.compile("^(.*)\\s+:(\\S+):\\s*$");
// 
//     // org-property-re
//     public static final Pattern PROPERTY = Pattern.compile("^[ \\t]*:(\\S+):(|[ \\t]+.*?[ \\t]*)$");
// 
//     /*
//     https://orgmode.org/manual/In_002dbuffer-settings.html
// 
//     "In-buffer settings start with ‘#+’, followed by a keyword, a colon,
//     and then a word for each setting. Org accepts multiple settings on the same line.
//     Org also accepts multiple lines for a keyword."
// 
//     Here we don't allow multiple settings per line for now.
//      */
//     public static final Pattern KEYWORD_VALUE = Pattern.compile("^#\\+([A-Za-z0-9_]+):\\s*(.*?)\\s*$");
// }
// 
// Path: src/main/java/com/orgzly/org/OrgStringUtils.java
// public class OrgStringUtils {
//     public static String trimLines(String str) {
//         return str.replaceFirst("\n+[\\s]*$", "").replaceFirst("^[\\s]*\n", "");
//     }
// 
//     public static boolean isEmpty(String s) {
//         return s == null || s.length() == 0;
//     }
// 
//     public static String join(Collection set, String d) {
//         StringBuilder result = new StringBuilder();
// 
//         int i = 0;
//         for (Object str: set) {
//             result.append(str);
// 
//             if (i++ < set.size() - 1) { /* Not last. */
//                 result.append(d);
//             }
//         }
// 
//         return result.toString();
//     }
// 
// 
// 
//     public static int stringWidth(String str) {
//         int total = 0;
// 
//         for (int i = 0; i < str.length(); ) {
//             int cp = str.codePointAt(i);
// 
//             int width = codePointWidth(cp);
// 
//             // System.out.printf("Code point %c width: %d\n", cp, width);
// 
//             total += width;
// 
//             i += Character.charCount(cp);
//         }
// 
//         return total;
//     }
// 
//     private static int codePointWidth(int cp) {
//         return EastAsianWidth.CP.contains(cp) ? 2 : 1;
//     }
// }
 | 
	import com.orgzly.org.OrgPatterns;
import com.orgzly.org.OrgStringUtils;
import java.util.Calendar;
import java.util.regex.Matcher; | 
	package com.orgzly.org.datetime;
/**
 * http://orgmode.org/manual/Repeated-tasks.html
 */
public class OrgRepeater extends OrgInterval {
    public enum Type {
        CUMULATE,  //  +
        CATCH_UP,  //  ++
        RESTART    //  .+
    }
    private Type type;
    /** 4d in .+2d/4d (http://orgmode.org/manual/Tracking-your-habits.html) */
    private OrgInterval habitDeadline;
    public static OrgRepeater parse(String str) {
        OrgRepeater repeater = new OrgRepeater();
 | 
	// Path: src/main/java/com/orgzly/org/OrgPatterns.java
// public class OrgPatterns {
//     // org-ts-regexp-both
//     private static final String DT = "(([\\[<])[0-9]{4,}-[0-9]{2}-[0-9]{2} ?[^]\r\n>]*?[]>])";
// 
//     // org-tsr-regexp-both
//     private static final String DT_OR_RANGE = "(" + DT + "(--?-?" + DT + ")?)";
// 
//     public static final Pattern DT_OR_RANGE_P = Pattern.compile(OrgPatterns.DT_OR_RANGE);
// 
//     //  org-repeat-re
//     public static final Pattern REPEAT_P = Pattern.compile(
//             "[0-9]{4,}-[0-9][0-9]-[0-9][0-9] [^>\n]*?([.+]?\\+[0-9]+[hdwmy](/[0-9]+[hdwmy])?)");
// 
//     public static final Pattern TIME_DELAY_P = Pattern.compile("([-]{1,2}+)([0-9]+)([hdwmy])");
// 
//     public static final Pattern REPEATER = Pattern.compile(
//             "(([.+]?\\+)([0-9]+)([hdwmy]))(/([0-9]+)([hdwmy]))?");
// 
//     // org-ts-regexp0
//     public static final Pattern DT_MAYBE_WITH_TIME_P = Pattern.compile(
//             "(([0-9]{4,})-([0-9]{2})-([0-9]{2})( +[^]+0-9>\r\n -]+)?( +([0-9]{1,2}):([0-9]{2}))?)");
// 
//     /*
//      * Time of day with optional end-time.
//      * From org-get-compact-tod.
//      */
//     public static final Pattern TIME_OF_DAY_P = Pattern.compile(
//             "(([012]?[0-9]):([0-5][0-9]))(-(([012]?[0-9]):([0-5][0-9])))?");
// 
//     public static final Pattern PLANNING_TIMES_P = Pattern.compile(
//             "(SCHEDULED:|CLOSED:|DEADLINE:) *" + DT_OR_RANGE);
// 
//     public static final Pattern HEAD_P = Pattern.compile("^([*]+)\\s+(.*)\\s*$");
//     public static final Pattern HEAD_PRIORITY_P = Pattern.compile("^\\s*\\[#([A-Z])](.*)");
//     public static final Pattern HEAD_TAGS_P = Pattern.compile("^(.*)\\s+:(\\S+):\\s*$");
// 
//     // org-property-re
//     public static final Pattern PROPERTY = Pattern.compile("^[ \\t]*:(\\S+):(|[ \\t]+.*?[ \\t]*)$");
// 
//     /*
//     https://orgmode.org/manual/In_002dbuffer-settings.html
// 
//     "In-buffer settings start with ‘#+’, followed by a keyword, a colon,
//     and then a word for each setting. Org accepts multiple settings on the same line.
//     Org also accepts multiple lines for a keyword."
// 
//     Here we don't allow multiple settings per line for now.
//      */
//     public static final Pattern KEYWORD_VALUE = Pattern.compile("^#\\+([A-Za-z0-9_]+):\\s*(.*?)\\s*$");
// }
// 
// Path: src/main/java/com/orgzly/org/OrgStringUtils.java
// public class OrgStringUtils {
//     public static String trimLines(String str) {
//         return str.replaceFirst("\n+[\\s]*$", "").replaceFirst("^[\\s]*\n", "");
//     }
// 
//     public static boolean isEmpty(String s) {
//         return s == null || s.length() == 0;
//     }
// 
//     public static String join(Collection set, String d) {
//         StringBuilder result = new StringBuilder();
// 
//         int i = 0;
//         for (Object str: set) {
//             result.append(str);
// 
//             if (i++ < set.size() - 1) { /* Not last. */
//                 result.append(d);
//             }
//         }
// 
//         return result.toString();
//     }
// 
// 
// 
//     public static int stringWidth(String str) {
//         int total = 0;
// 
//         for (int i = 0; i < str.length(); ) {
//             int cp = str.codePointAt(i);
// 
//             int width = codePointWidth(cp);
// 
//             // System.out.printf("Code point %c width: %d\n", cp, width);
// 
//             total += width;
// 
//             i += Character.charCount(cp);
//         }
// 
//         return total;
//     }
// 
//     private static int codePointWidth(int cp) {
//         return EastAsianWidth.CP.contains(cp) ? 2 : 1;
//     }
// }
// Path: src/main/java/com/orgzly/org/datetime/OrgRepeater.java
import com.orgzly.org.OrgPatterns;
import com.orgzly.org.OrgStringUtils;
import java.util.Calendar;
import java.util.regex.Matcher;
package com.orgzly.org.datetime;
/**
 * http://orgmode.org/manual/Repeated-tasks.html
 */
public class OrgRepeater extends OrgInterval {
    public enum Type {
        CUMULATE,  //  +
        CATCH_UP,  //  ++
        RESTART    //  .+
    }
    private Type type;
    /** 4d in .+2d/4d (http://orgmode.org/manual/Tracking-your-habits.html) */
    private OrgInterval habitDeadline;
    public static OrgRepeater parse(String str) {
        OrgRepeater repeater = new OrgRepeater();
 | 
	        Matcher m = OrgPatterns.REPEATER.matcher(str); | 
| 
	orgzly/org-java | 
	src/main/java/com/orgzly/org/datetime/OrgRepeater.java | 
	// Path: src/main/java/com/orgzly/org/OrgPatterns.java
// public class OrgPatterns {
//     // org-ts-regexp-both
//     private static final String DT = "(([\\[<])[0-9]{4,}-[0-9]{2}-[0-9]{2} ?[^]\r\n>]*?[]>])";
// 
//     // org-tsr-regexp-both
//     private static final String DT_OR_RANGE = "(" + DT + "(--?-?" + DT + ")?)";
// 
//     public static final Pattern DT_OR_RANGE_P = Pattern.compile(OrgPatterns.DT_OR_RANGE);
// 
//     //  org-repeat-re
//     public static final Pattern REPEAT_P = Pattern.compile(
//             "[0-9]{4,}-[0-9][0-9]-[0-9][0-9] [^>\n]*?([.+]?\\+[0-9]+[hdwmy](/[0-9]+[hdwmy])?)");
// 
//     public static final Pattern TIME_DELAY_P = Pattern.compile("([-]{1,2}+)([0-9]+)([hdwmy])");
// 
//     public static final Pattern REPEATER = Pattern.compile(
//             "(([.+]?\\+)([0-9]+)([hdwmy]))(/([0-9]+)([hdwmy]))?");
// 
//     // org-ts-regexp0
//     public static final Pattern DT_MAYBE_WITH_TIME_P = Pattern.compile(
//             "(([0-9]{4,})-([0-9]{2})-([0-9]{2})( +[^]+0-9>\r\n -]+)?( +([0-9]{1,2}):([0-9]{2}))?)");
// 
//     /*
//      * Time of day with optional end-time.
//      * From org-get-compact-tod.
//      */
//     public static final Pattern TIME_OF_DAY_P = Pattern.compile(
//             "(([012]?[0-9]):([0-5][0-9]))(-(([012]?[0-9]):([0-5][0-9])))?");
// 
//     public static final Pattern PLANNING_TIMES_P = Pattern.compile(
//             "(SCHEDULED:|CLOSED:|DEADLINE:) *" + DT_OR_RANGE);
// 
//     public static final Pattern HEAD_P = Pattern.compile("^([*]+)\\s+(.*)\\s*$");
//     public static final Pattern HEAD_PRIORITY_P = Pattern.compile("^\\s*\\[#([A-Z])](.*)");
//     public static final Pattern HEAD_TAGS_P = Pattern.compile("^(.*)\\s+:(\\S+):\\s*$");
// 
//     // org-property-re
//     public static final Pattern PROPERTY = Pattern.compile("^[ \\t]*:(\\S+):(|[ \\t]+.*?[ \\t]*)$");
// 
//     /*
//     https://orgmode.org/manual/In_002dbuffer-settings.html
// 
//     "In-buffer settings start with ‘#+’, followed by a keyword, a colon,
//     and then a word for each setting. Org accepts multiple settings on the same line.
//     Org also accepts multiple lines for a keyword."
// 
//     Here we don't allow multiple settings per line for now.
//      */
//     public static final Pattern KEYWORD_VALUE = Pattern.compile("^#\\+([A-Za-z0-9_]+):\\s*(.*?)\\s*$");
// }
// 
// Path: src/main/java/com/orgzly/org/OrgStringUtils.java
// public class OrgStringUtils {
//     public static String trimLines(String str) {
//         return str.replaceFirst("\n+[\\s]*$", "").replaceFirst("^[\\s]*\n", "");
//     }
// 
//     public static boolean isEmpty(String s) {
//         return s == null || s.length() == 0;
//     }
// 
//     public static String join(Collection set, String d) {
//         StringBuilder result = new StringBuilder();
// 
//         int i = 0;
//         for (Object str: set) {
//             result.append(str);
// 
//             if (i++ < set.size() - 1) { /* Not last. */
//                 result.append(d);
//             }
//         }
// 
//         return result.toString();
//     }
// 
// 
// 
//     public static int stringWidth(String str) {
//         int total = 0;
// 
//         for (int i = 0; i < str.length(); ) {
//             int cp = str.codePointAt(i);
// 
//             int width = codePointWidth(cp);
// 
//             // System.out.printf("Code point %c width: %d\n", cp, width);
// 
//             total += width;
// 
//             i += Character.charCount(cp);
//         }
// 
//         return total;
//     }
// 
//     private static int codePointWidth(int cp) {
//         return EastAsianWidth.CP.contains(cp) ? 2 : 1;
//     }
// }
 | 
	import com.orgzly.org.OrgPatterns;
import com.orgzly.org.OrgStringUtils;
import java.util.Calendar;
import java.util.regex.Matcher; | 
	package com.orgzly.org.datetime;
/**
 * http://orgmode.org/manual/Repeated-tasks.html
 */
public class OrgRepeater extends OrgInterval {
    public enum Type {
        CUMULATE,  //  +
        CATCH_UP,  //  ++
        RESTART    //  .+
    }
    private Type type;
    /** 4d in .+2d/4d (http://orgmode.org/manual/Tracking-your-habits.html) */
    private OrgInterval habitDeadline;
    public static OrgRepeater parse(String str) {
        OrgRepeater repeater = new OrgRepeater();
        Matcher m = OrgPatterns.REPEATER.matcher(str);
        if (m.find()) {
            if (m.groupCount() == 7) {
                repeater.setTypeFromString(m.group(2));
                repeater.setValue(m.group(3));
                repeater.setUnit(m.group(4));
 | 
	// Path: src/main/java/com/orgzly/org/OrgPatterns.java
// public class OrgPatterns {
//     // org-ts-regexp-both
//     private static final String DT = "(([\\[<])[0-9]{4,}-[0-9]{2}-[0-9]{2} ?[^]\r\n>]*?[]>])";
// 
//     // org-tsr-regexp-both
//     private static final String DT_OR_RANGE = "(" + DT + "(--?-?" + DT + ")?)";
// 
//     public static final Pattern DT_OR_RANGE_P = Pattern.compile(OrgPatterns.DT_OR_RANGE);
// 
//     //  org-repeat-re
//     public static final Pattern REPEAT_P = Pattern.compile(
//             "[0-9]{4,}-[0-9][0-9]-[0-9][0-9] [^>\n]*?([.+]?\\+[0-9]+[hdwmy](/[0-9]+[hdwmy])?)");
// 
//     public static final Pattern TIME_DELAY_P = Pattern.compile("([-]{1,2}+)([0-9]+)([hdwmy])");
// 
//     public static final Pattern REPEATER = Pattern.compile(
//             "(([.+]?\\+)([0-9]+)([hdwmy]))(/([0-9]+)([hdwmy]))?");
// 
//     // org-ts-regexp0
//     public static final Pattern DT_MAYBE_WITH_TIME_P = Pattern.compile(
//             "(([0-9]{4,})-([0-9]{2})-([0-9]{2})( +[^]+0-9>\r\n -]+)?( +([0-9]{1,2}):([0-9]{2}))?)");
// 
//     /*
//      * Time of day with optional end-time.
//      * From org-get-compact-tod.
//      */
//     public static final Pattern TIME_OF_DAY_P = Pattern.compile(
//             "(([012]?[0-9]):([0-5][0-9]))(-(([012]?[0-9]):([0-5][0-9])))?");
// 
//     public static final Pattern PLANNING_TIMES_P = Pattern.compile(
//             "(SCHEDULED:|CLOSED:|DEADLINE:) *" + DT_OR_RANGE);
// 
//     public static final Pattern HEAD_P = Pattern.compile("^([*]+)\\s+(.*)\\s*$");
//     public static final Pattern HEAD_PRIORITY_P = Pattern.compile("^\\s*\\[#([A-Z])](.*)");
//     public static final Pattern HEAD_TAGS_P = Pattern.compile("^(.*)\\s+:(\\S+):\\s*$");
// 
//     // org-property-re
//     public static final Pattern PROPERTY = Pattern.compile("^[ \\t]*:(\\S+):(|[ \\t]+.*?[ \\t]*)$");
// 
//     /*
//     https://orgmode.org/manual/In_002dbuffer-settings.html
// 
//     "In-buffer settings start with ‘#+’, followed by a keyword, a colon,
//     and then a word for each setting. Org accepts multiple settings on the same line.
//     Org also accepts multiple lines for a keyword."
// 
//     Here we don't allow multiple settings per line for now.
//      */
//     public static final Pattern KEYWORD_VALUE = Pattern.compile("^#\\+([A-Za-z0-9_]+):\\s*(.*?)\\s*$");
// }
// 
// Path: src/main/java/com/orgzly/org/OrgStringUtils.java
// public class OrgStringUtils {
//     public static String trimLines(String str) {
//         return str.replaceFirst("\n+[\\s]*$", "").replaceFirst("^[\\s]*\n", "");
//     }
// 
//     public static boolean isEmpty(String s) {
//         return s == null || s.length() == 0;
//     }
// 
//     public static String join(Collection set, String d) {
//         StringBuilder result = new StringBuilder();
// 
//         int i = 0;
//         for (Object str: set) {
//             result.append(str);
// 
//             if (i++ < set.size() - 1) { /* Not last. */
//                 result.append(d);
//             }
//         }
// 
//         return result.toString();
//     }
// 
// 
// 
//     public static int stringWidth(String str) {
//         int total = 0;
// 
//         for (int i = 0; i < str.length(); ) {
//             int cp = str.codePointAt(i);
// 
//             int width = codePointWidth(cp);
// 
//             // System.out.printf("Code point %c width: %d\n", cp, width);
// 
//             total += width;
// 
//             i += Character.charCount(cp);
//         }
// 
//         return total;
//     }
// 
//     private static int codePointWidth(int cp) {
//         return EastAsianWidth.CP.contains(cp) ? 2 : 1;
//     }
// }
// Path: src/main/java/com/orgzly/org/datetime/OrgRepeater.java
import com.orgzly.org.OrgPatterns;
import com.orgzly.org.OrgStringUtils;
import java.util.Calendar;
import java.util.regex.Matcher;
package com.orgzly.org.datetime;
/**
 * http://orgmode.org/manual/Repeated-tasks.html
 */
public class OrgRepeater extends OrgInterval {
    public enum Type {
        CUMULATE,  //  +
        CATCH_UP,  //  ++
        RESTART    //  .+
    }
    private Type type;
    /** 4d in .+2d/4d (http://orgmode.org/manual/Tracking-your-habits.html) */
    private OrgInterval habitDeadline;
    public static OrgRepeater parse(String str) {
        OrgRepeater repeater = new OrgRepeater();
        Matcher m = OrgPatterns.REPEATER.matcher(str);
        if (m.find()) {
            if (m.groupCount() == 7) {
                repeater.setTypeFromString(m.group(2));
                repeater.setValue(m.group(3));
                repeater.setUnit(m.group(4));
 | 
	                if (! OrgStringUtils.isEmpty(m.group(6))) { | 
| 
	orgzly/org-java | 
	src/main/java/com/orgzly/org/datetime/OrgDateTime.java | 
	// Path: src/main/java/com/orgzly/org/OrgPatterns.java
// public class OrgPatterns {
//     // org-ts-regexp-both
//     private static final String DT = "(([\\[<])[0-9]{4,}-[0-9]{2}-[0-9]{2} ?[^]\r\n>]*?[]>])";
// 
//     // org-tsr-regexp-both
//     private static final String DT_OR_RANGE = "(" + DT + "(--?-?" + DT + ")?)";
// 
//     public static final Pattern DT_OR_RANGE_P = Pattern.compile(OrgPatterns.DT_OR_RANGE);
// 
//     //  org-repeat-re
//     public static final Pattern REPEAT_P = Pattern.compile(
//             "[0-9]{4,}-[0-9][0-9]-[0-9][0-9] [^>\n]*?([.+]?\\+[0-9]+[hdwmy](/[0-9]+[hdwmy])?)");
// 
//     public static final Pattern TIME_DELAY_P = Pattern.compile("([-]{1,2}+)([0-9]+)([hdwmy])");
// 
//     public static final Pattern REPEATER = Pattern.compile(
//             "(([.+]?\\+)([0-9]+)([hdwmy]))(/([0-9]+)([hdwmy]))?");
// 
//     // org-ts-regexp0
//     public static final Pattern DT_MAYBE_WITH_TIME_P = Pattern.compile(
//             "(([0-9]{4,})-([0-9]{2})-([0-9]{2})( +[^]+0-9>\r\n -]+)?( +([0-9]{1,2}):([0-9]{2}))?)");
// 
//     /*
//      * Time of day with optional end-time.
//      * From org-get-compact-tod.
//      */
//     public static final Pattern TIME_OF_DAY_P = Pattern.compile(
//             "(([012]?[0-9]):([0-5][0-9]))(-(([012]?[0-9]):([0-5][0-9])))?");
// 
//     public static final Pattern PLANNING_TIMES_P = Pattern.compile(
//             "(SCHEDULED:|CLOSED:|DEADLINE:) *" + DT_OR_RANGE);
// 
//     public static final Pattern HEAD_P = Pattern.compile("^([*]+)\\s+(.*)\\s*$");
//     public static final Pattern HEAD_PRIORITY_P = Pattern.compile("^\\s*\\[#([A-Z])](.*)");
//     public static final Pattern HEAD_TAGS_P = Pattern.compile("^(.*)\\s+:(\\S+):\\s*$");
// 
//     // org-property-re
//     public static final Pattern PROPERTY = Pattern.compile("^[ \\t]*:(\\S+):(|[ \\t]+.*?[ \\t]*)$");
// 
//     /*
//     https://orgmode.org/manual/In_002dbuffer-settings.html
// 
//     "In-buffer settings start with ‘#+’, followed by a keyword, a colon,
//     and then a word for each setting. Org accepts multiple settings on the same line.
//     Org also accepts multiple lines for a keyword."
// 
//     Here we don't allow multiple settings per line for now.
//      */
//     public static final Pattern KEYWORD_VALUE = Pattern.compile("^#\\+([A-Za-z0-9_]+):\\s*(.*?)\\s*$");
// }
// 
// Path: src/main/java/com/orgzly/org/OrgStringUtils.java
// public class OrgStringUtils {
//     public static String trimLines(String str) {
//         return str.replaceFirst("\n+[\\s]*$", "").replaceFirst("^[\\s]*\n", "");
//     }
// 
//     public static boolean isEmpty(String s) {
//         return s == null || s.length() == 0;
//     }
// 
//     public static String join(Collection set, String d) {
//         StringBuilder result = new StringBuilder();
// 
//         int i = 0;
//         for (Object str: set) {
//             result.append(str);
// 
//             if (i++ < set.size() - 1) { /* Not last. */
//                 result.append(d);
//             }
//         }
// 
//         return result.toString();
//     }
// 
// 
// 
//     public static int stringWidth(String str) {
//         int total = 0;
// 
//         for (int i = 0; i < str.length(); ) {
//             int cp = str.codePointAt(i);
// 
//             int width = codePointWidth(cp);
// 
//             // System.out.printf("Code point %c width: %d\n", cp, width);
// 
//             total += width;
// 
//             i += Character.charCount(cp);
//         }
// 
//         return total;
//     }
// 
//     private static int codePointWidth(int cp) {
//         return EastAsianWidth.CP.contains(cp) ? 2 : 1;
//     }
// }
 | 
	import com.orgzly.org.OrgPatterns;
import com.orgzly.org.OrgStringUtils;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | 
	        this.cal.setTimeInMillis(millis);
        this.cal.set(Calendar.SECOND, 0);
        this.cal.set(Calendar.MILLISECOND, 0);
        this.hasTime = true;
    }
    /**
     * Creates instance from the given string
     *
     * @param str Org timestamp such as {@code <2014-05-26> or [2014-05-26 Mon 09:15]}
     *
     * @return instance if the provided string is not empty
     */
    public static OrgDateTime parse(String str) {
        if (str == null) {
            throw new IllegalArgumentException("OrgDateTime cannot be created from null string");
        }
        if (str.length() == 0) {
            throw new IllegalArgumentException("OrgDateTime cannot be created from null string");
        }
        OrgDateTime time = new OrgDateTime();
        time.string = str;
        return time;
    }
    public static OrgDateTime parseOrNull(String str) { | 
	// Path: src/main/java/com/orgzly/org/OrgPatterns.java
// public class OrgPatterns {
//     // org-ts-regexp-both
//     private static final String DT = "(([\\[<])[0-9]{4,}-[0-9]{2}-[0-9]{2} ?[^]\r\n>]*?[]>])";
// 
//     // org-tsr-regexp-both
//     private static final String DT_OR_RANGE = "(" + DT + "(--?-?" + DT + ")?)";
// 
//     public static final Pattern DT_OR_RANGE_P = Pattern.compile(OrgPatterns.DT_OR_RANGE);
// 
//     //  org-repeat-re
//     public static final Pattern REPEAT_P = Pattern.compile(
//             "[0-9]{4,}-[0-9][0-9]-[0-9][0-9] [^>\n]*?([.+]?\\+[0-9]+[hdwmy](/[0-9]+[hdwmy])?)");
// 
//     public static final Pattern TIME_DELAY_P = Pattern.compile("([-]{1,2}+)([0-9]+)([hdwmy])");
// 
//     public static final Pattern REPEATER = Pattern.compile(
//             "(([.+]?\\+)([0-9]+)([hdwmy]))(/([0-9]+)([hdwmy]))?");
// 
//     // org-ts-regexp0
//     public static final Pattern DT_MAYBE_WITH_TIME_P = Pattern.compile(
//             "(([0-9]{4,})-([0-9]{2})-([0-9]{2})( +[^]+0-9>\r\n -]+)?( +([0-9]{1,2}):([0-9]{2}))?)");
// 
//     /*
//      * Time of day with optional end-time.
//      * From org-get-compact-tod.
//      */
//     public static final Pattern TIME_OF_DAY_P = Pattern.compile(
//             "(([012]?[0-9]):([0-5][0-9]))(-(([012]?[0-9]):([0-5][0-9])))?");
// 
//     public static final Pattern PLANNING_TIMES_P = Pattern.compile(
//             "(SCHEDULED:|CLOSED:|DEADLINE:) *" + DT_OR_RANGE);
// 
//     public static final Pattern HEAD_P = Pattern.compile("^([*]+)\\s+(.*)\\s*$");
//     public static final Pattern HEAD_PRIORITY_P = Pattern.compile("^\\s*\\[#([A-Z])](.*)");
//     public static final Pattern HEAD_TAGS_P = Pattern.compile("^(.*)\\s+:(\\S+):\\s*$");
// 
//     // org-property-re
//     public static final Pattern PROPERTY = Pattern.compile("^[ \\t]*:(\\S+):(|[ \\t]+.*?[ \\t]*)$");
// 
//     /*
//     https://orgmode.org/manual/In_002dbuffer-settings.html
// 
//     "In-buffer settings start with ‘#+’, followed by a keyword, a colon,
//     and then a word for each setting. Org accepts multiple settings on the same line.
//     Org also accepts multiple lines for a keyword."
// 
//     Here we don't allow multiple settings per line for now.
//      */
//     public static final Pattern KEYWORD_VALUE = Pattern.compile("^#\\+([A-Za-z0-9_]+):\\s*(.*?)\\s*$");
// }
// 
// Path: src/main/java/com/orgzly/org/OrgStringUtils.java
// public class OrgStringUtils {
//     public static String trimLines(String str) {
//         return str.replaceFirst("\n+[\\s]*$", "").replaceFirst("^[\\s]*\n", "");
//     }
// 
//     public static boolean isEmpty(String s) {
//         return s == null || s.length() == 0;
//     }
// 
//     public static String join(Collection set, String d) {
//         StringBuilder result = new StringBuilder();
// 
//         int i = 0;
//         for (Object str: set) {
//             result.append(str);
// 
//             if (i++ < set.size() - 1) { /* Not last. */
//                 result.append(d);
//             }
//         }
// 
//         return result.toString();
//     }
// 
// 
// 
//     public static int stringWidth(String str) {
//         int total = 0;
// 
//         for (int i = 0; i < str.length(); ) {
//             int cp = str.codePointAt(i);
// 
//             int width = codePointWidth(cp);
// 
//             // System.out.printf("Code point %c width: %d\n", cp, width);
// 
//             total += width;
// 
//             i += Character.charCount(cp);
//         }
// 
//         return total;
//     }
// 
//     private static int codePointWidth(int cp) {
//         return EastAsianWidth.CP.contains(cp) ? 2 : 1;
//     }
// }
// Path: src/main/java/com/orgzly/org/datetime/OrgDateTime.java
import com.orgzly.org.OrgPatterns;
import com.orgzly.org.OrgStringUtils;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
        this.cal.setTimeInMillis(millis);
        this.cal.set(Calendar.SECOND, 0);
        this.cal.set(Calendar.MILLISECOND, 0);
        this.hasTime = true;
    }
    /**
     * Creates instance from the given string
     *
     * @param str Org timestamp such as {@code <2014-05-26> or [2014-05-26 Mon 09:15]}
     *
     * @return instance if the provided string is not empty
     */
    public static OrgDateTime parse(String str) {
        if (str == null) {
            throw new IllegalArgumentException("OrgDateTime cannot be created from null string");
        }
        if (str.length() == 0) {
            throw new IllegalArgumentException("OrgDateTime cannot be created from null string");
        }
        OrgDateTime time = new OrgDateTime();
        time.string = str;
        return time;
    }
    public static OrgDateTime parseOrNull(String str) { | 
	        if (OrgStringUtils.isEmpty(str)) { | 
| 
	orgzly/org-java | 
	src/main/java/com/orgzly/org/datetime/OrgDateTime.java | 
	// Path: src/main/java/com/orgzly/org/OrgPatterns.java
// public class OrgPatterns {
//     // org-ts-regexp-both
//     private static final String DT = "(([\\[<])[0-9]{4,}-[0-9]{2}-[0-9]{2} ?[^]\r\n>]*?[]>])";
// 
//     // org-tsr-regexp-both
//     private static final String DT_OR_RANGE = "(" + DT + "(--?-?" + DT + ")?)";
// 
//     public static final Pattern DT_OR_RANGE_P = Pattern.compile(OrgPatterns.DT_OR_RANGE);
// 
//     //  org-repeat-re
//     public static final Pattern REPEAT_P = Pattern.compile(
//             "[0-9]{4,}-[0-9][0-9]-[0-9][0-9] [^>\n]*?([.+]?\\+[0-9]+[hdwmy](/[0-9]+[hdwmy])?)");
// 
//     public static final Pattern TIME_DELAY_P = Pattern.compile("([-]{1,2}+)([0-9]+)([hdwmy])");
// 
//     public static final Pattern REPEATER = Pattern.compile(
//             "(([.+]?\\+)([0-9]+)([hdwmy]))(/([0-9]+)([hdwmy]))?");
// 
//     // org-ts-regexp0
//     public static final Pattern DT_MAYBE_WITH_TIME_P = Pattern.compile(
//             "(([0-9]{4,})-([0-9]{2})-([0-9]{2})( +[^]+0-9>\r\n -]+)?( +([0-9]{1,2}):([0-9]{2}))?)");
// 
//     /*
//      * Time of day with optional end-time.
//      * From org-get-compact-tod.
//      */
//     public static final Pattern TIME_OF_DAY_P = Pattern.compile(
//             "(([012]?[0-9]):([0-5][0-9]))(-(([012]?[0-9]):([0-5][0-9])))?");
// 
//     public static final Pattern PLANNING_TIMES_P = Pattern.compile(
//             "(SCHEDULED:|CLOSED:|DEADLINE:) *" + DT_OR_RANGE);
// 
//     public static final Pattern HEAD_P = Pattern.compile("^([*]+)\\s+(.*)\\s*$");
//     public static final Pattern HEAD_PRIORITY_P = Pattern.compile("^\\s*\\[#([A-Z])](.*)");
//     public static final Pattern HEAD_TAGS_P = Pattern.compile("^(.*)\\s+:(\\S+):\\s*$");
// 
//     // org-property-re
//     public static final Pattern PROPERTY = Pattern.compile("^[ \\t]*:(\\S+):(|[ \\t]+.*?[ \\t]*)$");
// 
//     /*
//     https://orgmode.org/manual/In_002dbuffer-settings.html
// 
//     "In-buffer settings start with ‘#+’, followed by a keyword, a colon,
//     and then a word for each setting. Org accepts multiple settings on the same line.
//     Org also accepts multiple lines for a keyword."
// 
//     Here we don't allow multiple settings per line for now.
//      */
//     public static final Pattern KEYWORD_VALUE = Pattern.compile("^#\\+([A-Za-z0-9_]+):\\s*(.*?)\\s*$");
// }
// 
// Path: src/main/java/com/orgzly/org/OrgStringUtils.java
// public class OrgStringUtils {
//     public static String trimLines(String str) {
//         return str.replaceFirst("\n+[\\s]*$", "").replaceFirst("^[\\s]*\n", "");
//     }
// 
//     public static boolean isEmpty(String s) {
//         return s == null || s.length() == 0;
//     }
// 
//     public static String join(Collection set, String d) {
//         StringBuilder result = new StringBuilder();
// 
//         int i = 0;
//         for (Object str: set) {
//             result.append(str);
// 
//             if (i++ < set.size() - 1) { /* Not last. */
//                 result.append(d);
//             }
//         }
// 
//         return result.toString();
//     }
// 
// 
// 
//     public static int stringWidth(String str) {
//         int total = 0;
// 
//         for (int i = 0; i < str.length(); ) {
//             int cp = str.codePointAt(i);
// 
//             int width = codePointWidth(cp);
// 
//             // System.out.printf("Code point %c width: %d\n", cp, width);
// 
//             total += width;
// 
//             i += Character.charCount(cp);
//         }
// 
//         return total;
//     }
// 
//     private static int codePointWidth(int cp) {
//         return EastAsianWidth.CP.contains(cp) ? 2 : 1;
//     }
// }
 | 
	import com.orgzly.org.OrgPatterns;
import com.orgzly.org.OrgStringUtils;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | 
	            if (string == null) {
                throw new IllegalStateException("Missing string");
            }
            parseString();
        }
    }
    /**
     * Parse {@link OrgDateTime#string} and populate other fields.
     */
    private void parseString() {
        Matcher m;
        cal = Calendar.getInstance();
        endCal = null;
        switch (string.charAt(0)) {
            case '<':
                isActive = true;
                break;
            case '[':
                isActive = false;
                break;
            default:
                throw new IllegalArgumentException("Timestamp \"" + string + "\" must start with < or [");
        }
 | 
	// Path: src/main/java/com/orgzly/org/OrgPatterns.java
// public class OrgPatterns {
//     // org-ts-regexp-both
//     private static final String DT = "(([\\[<])[0-9]{4,}-[0-9]{2}-[0-9]{2} ?[^]\r\n>]*?[]>])";
// 
//     // org-tsr-regexp-both
//     private static final String DT_OR_RANGE = "(" + DT + "(--?-?" + DT + ")?)";
// 
//     public static final Pattern DT_OR_RANGE_P = Pattern.compile(OrgPatterns.DT_OR_RANGE);
// 
//     //  org-repeat-re
//     public static final Pattern REPEAT_P = Pattern.compile(
//             "[0-9]{4,}-[0-9][0-9]-[0-9][0-9] [^>\n]*?([.+]?\\+[0-9]+[hdwmy](/[0-9]+[hdwmy])?)");
// 
//     public static final Pattern TIME_DELAY_P = Pattern.compile("([-]{1,2}+)([0-9]+)([hdwmy])");
// 
//     public static final Pattern REPEATER = Pattern.compile(
//             "(([.+]?\\+)([0-9]+)([hdwmy]))(/([0-9]+)([hdwmy]))?");
// 
//     // org-ts-regexp0
//     public static final Pattern DT_MAYBE_WITH_TIME_P = Pattern.compile(
//             "(([0-9]{4,})-([0-9]{2})-([0-9]{2})( +[^]+0-9>\r\n -]+)?( +([0-9]{1,2}):([0-9]{2}))?)");
// 
//     /*
//      * Time of day with optional end-time.
//      * From org-get-compact-tod.
//      */
//     public static final Pattern TIME_OF_DAY_P = Pattern.compile(
//             "(([012]?[0-9]):([0-5][0-9]))(-(([012]?[0-9]):([0-5][0-9])))?");
// 
//     public static final Pattern PLANNING_TIMES_P = Pattern.compile(
//             "(SCHEDULED:|CLOSED:|DEADLINE:) *" + DT_OR_RANGE);
// 
//     public static final Pattern HEAD_P = Pattern.compile("^([*]+)\\s+(.*)\\s*$");
//     public static final Pattern HEAD_PRIORITY_P = Pattern.compile("^\\s*\\[#([A-Z])](.*)");
//     public static final Pattern HEAD_TAGS_P = Pattern.compile("^(.*)\\s+:(\\S+):\\s*$");
// 
//     // org-property-re
//     public static final Pattern PROPERTY = Pattern.compile("^[ \\t]*:(\\S+):(|[ \\t]+.*?[ \\t]*)$");
// 
//     /*
//     https://orgmode.org/manual/In_002dbuffer-settings.html
// 
//     "In-buffer settings start with ‘#+’, followed by a keyword, a colon,
//     and then a word for each setting. Org accepts multiple settings on the same line.
//     Org also accepts multiple lines for a keyword."
// 
//     Here we don't allow multiple settings per line for now.
//      */
//     public static final Pattern KEYWORD_VALUE = Pattern.compile("^#\\+([A-Za-z0-9_]+):\\s*(.*?)\\s*$");
// }
// 
// Path: src/main/java/com/orgzly/org/OrgStringUtils.java
// public class OrgStringUtils {
//     public static String trimLines(String str) {
//         return str.replaceFirst("\n+[\\s]*$", "").replaceFirst("^[\\s]*\n", "");
//     }
// 
//     public static boolean isEmpty(String s) {
//         return s == null || s.length() == 0;
//     }
// 
//     public static String join(Collection set, String d) {
//         StringBuilder result = new StringBuilder();
// 
//         int i = 0;
//         for (Object str: set) {
//             result.append(str);
// 
//             if (i++ < set.size() - 1) { /* Not last. */
//                 result.append(d);
//             }
//         }
// 
//         return result.toString();
//     }
// 
// 
// 
//     public static int stringWidth(String str) {
//         int total = 0;
// 
//         for (int i = 0; i < str.length(); ) {
//             int cp = str.codePointAt(i);
// 
//             int width = codePointWidth(cp);
// 
//             // System.out.printf("Code point %c width: %d\n", cp, width);
// 
//             total += width;
// 
//             i += Character.charCount(cp);
//         }
// 
//         return total;
//     }
// 
//     private static int codePointWidth(int cp) {
//         return EastAsianWidth.CP.contains(cp) ? 2 : 1;
//     }
// }
// Path: src/main/java/com/orgzly/org/datetime/OrgDateTime.java
import com.orgzly.org.OrgPatterns;
import com.orgzly.org.OrgStringUtils;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
            if (string == null) {
                throw new IllegalStateException("Missing string");
            }
            parseString();
        }
    }
    /**
     * Parse {@link OrgDateTime#string} and populate other fields.
     */
    private void parseString() {
        Matcher m;
        cal = Calendar.getInstance();
        endCal = null;
        switch (string.charAt(0)) {
            case '<':
                isActive = true;
                break;
            case '[':
                isActive = false;
                break;
            default:
                throw new IllegalArgumentException("Timestamp \"" + string + "\" must start with < or [");
        }
 | 
	        m = OrgPatterns.DT_MAYBE_WITH_TIME_P.matcher(string); | 
| 
	orgzly/org-java | 
	src/test/java/com/orgzly/org/OrgActiveTimestampsTest.java | 
	// Path: src/main/java/com/orgzly/org/datetime/OrgRange.java
// public class OrgRange {
//     private OrgDateTime startTime;
//     private OrgDateTime endTime;
// 
//     public static OrgRange parseOrNull(String str) {
//         if (OrgStringUtils.isEmpty(str)) {
//             return null;
//         }
// 
//         return parse(str);
//     }
// 
//     public static OrgRange parse(String str) {
//         if (str == null) {
//             throw new IllegalArgumentException("OrgRange cannot be created from null string");
//         }
// 
//         if (str.length() == 0) {
//             throw new IllegalArgumentException("OrgRange cannot be created from null string");
//         }
// 
//         OrgRange t = new OrgRange();
// 
//         Matcher m = OrgPatterns.DT_OR_RANGE_P.matcher(str);
// 
//         if (m.find()) {
// //            for (int i = 0; i < m.groupCount() + 1; i++) {
// //                System.out.println("group(" + i + ") " + m.group(i));
// //            }
// 
//             if (m.groupCount() == 6 && m.group(6) != null) { // Range - two timestamps
//                 t.startTime = OrgDateTime.parse(m.group(2));
//                 t.endTime = OrgDateTime.parse(m.group(5));
// 
//             } else { // Single timestamp
//                 t.startTime = OrgDateTime.parse(m.group(2));
//                 t.endTime = null;
//             }
// 
//             return t;
// 
//         } else {
//             throw new IllegalArgumentException(
//                     "String " + str +
//                     " cannot be parsed as OrgRange using pattern " + OrgPatterns.DT_OR_RANGE_P);
//         }
//     }
// 
//     // TODO: Rename to parse, rename other methods to getInstance, add *orThrow methods if needed
//     public static OrgRange doParse(String str) {
//         try {
//             // Make sure both OrgDateTime are actually parsed.
//             // This is pretty bad, clean these classes.
//             OrgRange range = OrgRange.parse(str);
//             range.startTime.getCalendar();
//             if (range.endTime != null) {
//                 range.endTime.getCalendar();
//             }
//             return range;
//         } catch (Exception e) {
//             return null;
//         }
//     }
// 
//     private OrgRange() {
//     }
// 
//     public OrgRange(OrgRange orgRange) {
//         this.startTime = new OrgDateTime(orgRange.getStartTime());
// 
//         if (orgRange.getEndTime() != null) {
//             this.endTime = new OrgDateTime(orgRange.getEndTime());
//         }
//     }
// 
//     public OrgRange(OrgDateTime fromTime) {
//         this(fromTime, null);
//     }
// 
//     public OrgRange(OrgDateTime fromTime, OrgDateTime endTime) {
//         if (fromTime == null) {
//             throw new IllegalArgumentException("OrgRange cannot be created from null OrgDateTime");
//         }
// 
//         this.startTime = fromTime;
//         this.endTime = endTime;
//     }
// 
//     public OrgDateTime getStartTime() {
//         return startTime;
//     }
// 
//     /**
//      * @return last time of the range, can be {@code null}
//      */
//     @Nullable
//     public OrgDateTime getEndTime() {
//         return endTime;
//     }
// 
//     public boolean isSet() {
//         return startTime != null;
//     }
// 
//     public String toString() {
//         StringBuilder s = new StringBuilder();
// 
//         s.append(startTime);
// 
//         if (endTime != null) {
//             s.append("--");
//             s.append(endTime);
//         }
// 
//         return s.toString();
//     }
// 
//     public String toStringWithoutBrackets() {
//         StringBuilder s = new StringBuilder();
// 
//         s.append(startTime.toStringWithoutBrackets());
// 
//         if (endTime != null) {
//             s.append("--");
//             s.append(endTime.toStringWithoutBrackets());
//         }
// 
//         return s.toString();
//     }
// 
//     public boolean shift() {
//         return shift(Calendar.getInstance());
//     }
// 
//     /**
//      * Shifts both timestamps by their repeater intervals.
//      *
//      * @param now current time
//      * @return {@code true} if shift was performed
//      */
//     public boolean shift(Calendar now) {
//         boolean shifted = false;
// 
//         if (startTime != null) {
//             if (startTime.shift(now)) {
//                 shifted = true;
//             }
//         }
// 
//         if (endTime != null) {
//             if (endTime.shift(now)) {
//                 shifted = true;
//             }
//         }
// 
//         return shifted;
//     }
// }
 | 
	import com.orgzly.org.datetime.OrgRange;
import org.junit.Assert;
import org.junit.Test;
import java.util.List; | 
	package com.orgzly.org;
public class OrgActiveTimestampsTest extends OrgTestParser {
    @Test
    public void testPlainTimestamp() {
        String str = "<2018-01-15 Mon>\n";
 | 
	// Path: src/main/java/com/orgzly/org/datetime/OrgRange.java
// public class OrgRange {
//     private OrgDateTime startTime;
//     private OrgDateTime endTime;
// 
//     public static OrgRange parseOrNull(String str) {
//         if (OrgStringUtils.isEmpty(str)) {
//             return null;
//         }
// 
//         return parse(str);
//     }
// 
//     public static OrgRange parse(String str) {
//         if (str == null) {
//             throw new IllegalArgumentException("OrgRange cannot be created from null string");
//         }
// 
//         if (str.length() == 0) {
//             throw new IllegalArgumentException("OrgRange cannot be created from null string");
//         }
// 
//         OrgRange t = new OrgRange();
// 
//         Matcher m = OrgPatterns.DT_OR_RANGE_P.matcher(str);
// 
//         if (m.find()) {
// //            for (int i = 0; i < m.groupCount() + 1; i++) {
// //                System.out.println("group(" + i + ") " + m.group(i));
// //            }
// 
//             if (m.groupCount() == 6 && m.group(6) != null) { // Range - two timestamps
//                 t.startTime = OrgDateTime.parse(m.group(2));
//                 t.endTime = OrgDateTime.parse(m.group(5));
// 
//             } else { // Single timestamp
//                 t.startTime = OrgDateTime.parse(m.group(2));
//                 t.endTime = null;
//             }
// 
//             return t;
// 
//         } else {
//             throw new IllegalArgumentException(
//                     "String " + str +
//                     " cannot be parsed as OrgRange using pattern " + OrgPatterns.DT_OR_RANGE_P);
//         }
//     }
// 
//     // TODO: Rename to parse, rename other methods to getInstance, add *orThrow methods if needed
//     public static OrgRange doParse(String str) {
//         try {
//             // Make sure both OrgDateTime are actually parsed.
//             // This is pretty bad, clean these classes.
//             OrgRange range = OrgRange.parse(str);
//             range.startTime.getCalendar();
//             if (range.endTime != null) {
//                 range.endTime.getCalendar();
//             }
//             return range;
//         } catch (Exception e) {
//             return null;
//         }
//     }
// 
//     private OrgRange() {
//     }
// 
//     public OrgRange(OrgRange orgRange) {
//         this.startTime = new OrgDateTime(orgRange.getStartTime());
// 
//         if (orgRange.getEndTime() != null) {
//             this.endTime = new OrgDateTime(orgRange.getEndTime());
//         }
//     }
// 
//     public OrgRange(OrgDateTime fromTime) {
//         this(fromTime, null);
//     }
// 
//     public OrgRange(OrgDateTime fromTime, OrgDateTime endTime) {
//         if (fromTime == null) {
//             throw new IllegalArgumentException("OrgRange cannot be created from null OrgDateTime");
//         }
// 
//         this.startTime = fromTime;
//         this.endTime = endTime;
//     }
// 
//     public OrgDateTime getStartTime() {
//         return startTime;
//     }
// 
//     /**
//      * @return last time of the range, can be {@code null}
//      */
//     @Nullable
//     public OrgDateTime getEndTime() {
//         return endTime;
//     }
// 
//     public boolean isSet() {
//         return startTime != null;
//     }
// 
//     public String toString() {
//         StringBuilder s = new StringBuilder();
// 
//         s.append(startTime);
// 
//         if (endTime != null) {
//             s.append("--");
//             s.append(endTime);
//         }
// 
//         return s.toString();
//     }
// 
//     public String toStringWithoutBrackets() {
//         StringBuilder s = new StringBuilder();
// 
//         s.append(startTime.toStringWithoutBrackets());
// 
//         if (endTime != null) {
//             s.append("--");
//             s.append(endTime.toStringWithoutBrackets());
//         }
// 
//         return s.toString();
//     }
// 
//     public boolean shift() {
//         return shift(Calendar.getInstance());
//     }
// 
//     /**
//      * Shifts both timestamps by their repeater intervals.
//      *
//      * @param now current time
//      * @return {@code true} if shift was performed
//      */
//     public boolean shift(Calendar now) {
//         boolean shifted = false;
// 
//         if (startTime != null) {
//             if (startTime.shift(now)) {
//                 shifted = true;
//             }
//         }
// 
//         if (endTime != null) {
//             if (endTime.shift(now)) {
//                 shifted = true;
//             }
//         }
// 
//         return shifted;
//     }
// }
// Path: src/test/java/com/orgzly/org/OrgActiveTimestampsTest.java
import com.orgzly.org.datetime.OrgRange;
import org.junit.Assert;
import org.junit.Test;
import java.util.List;
package com.orgzly.org;
public class OrgActiveTimestampsTest extends OrgTestParser {
    @Test
    public void testPlainTimestamp() {
        String str = "<2018-01-15 Mon>\n";
 | 
	        List<OrgRange> timestamps = OrgActiveTimestamps.parse(str); | 
| 
	orgzly/org-java | 
	src/test/java/com/orgzly/org/utils/StateChangeLogicTest.java | 
	// Path: src/main/java/com/orgzly/org/datetime/OrgRange.java
// public class OrgRange {
//     private OrgDateTime startTime;
//     private OrgDateTime endTime;
// 
//     public static OrgRange parseOrNull(String str) {
//         if (OrgStringUtils.isEmpty(str)) {
//             return null;
//         }
// 
//         return parse(str);
//     }
// 
//     public static OrgRange parse(String str) {
//         if (str == null) {
//             throw new IllegalArgumentException("OrgRange cannot be created from null string");
//         }
// 
//         if (str.length() == 0) {
//             throw new IllegalArgumentException("OrgRange cannot be created from null string");
//         }
// 
//         OrgRange t = new OrgRange();
// 
//         Matcher m = OrgPatterns.DT_OR_RANGE_P.matcher(str);
// 
//         if (m.find()) {
// //            for (int i = 0; i < m.groupCount() + 1; i++) {
// //                System.out.println("group(" + i + ") " + m.group(i));
// //            }
// 
//             if (m.groupCount() == 6 && m.group(6) != null) { // Range - two timestamps
//                 t.startTime = OrgDateTime.parse(m.group(2));
//                 t.endTime = OrgDateTime.parse(m.group(5));
// 
//             } else { // Single timestamp
//                 t.startTime = OrgDateTime.parse(m.group(2));
//                 t.endTime = null;
//             }
// 
//             return t;
// 
//         } else {
//             throw new IllegalArgumentException(
//                     "String " + str +
//                     " cannot be parsed as OrgRange using pattern " + OrgPatterns.DT_OR_RANGE_P);
//         }
//     }
// 
//     // TODO: Rename to parse, rename other methods to getInstance, add *orThrow methods if needed
//     public static OrgRange doParse(String str) {
//         try {
//             // Make sure both OrgDateTime are actually parsed.
//             // This is pretty bad, clean these classes.
//             OrgRange range = OrgRange.parse(str);
//             range.startTime.getCalendar();
//             if (range.endTime != null) {
//                 range.endTime.getCalendar();
//             }
//             return range;
//         } catch (Exception e) {
//             return null;
//         }
//     }
// 
//     private OrgRange() {
//     }
// 
//     public OrgRange(OrgRange orgRange) {
//         this.startTime = new OrgDateTime(orgRange.getStartTime());
// 
//         if (orgRange.getEndTime() != null) {
//             this.endTime = new OrgDateTime(orgRange.getEndTime());
//         }
//     }
// 
//     public OrgRange(OrgDateTime fromTime) {
//         this(fromTime, null);
//     }
// 
//     public OrgRange(OrgDateTime fromTime, OrgDateTime endTime) {
//         if (fromTime == null) {
//             throw new IllegalArgumentException("OrgRange cannot be created from null OrgDateTime");
//         }
// 
//         this.startTime = fromTime;
//         this.endTime = endTime;
//     }
// 
//     public OrgDateTime getStartTime() {
//         return startTime;
//     }
// 
//     /**
//      * @return last time of the range, can be {@code null}
//      */
//     @Nullable
//     public OrgDateTime getEndTime() {
//         return endTime;
//     }
// 
//     public boolean isSet() {
//         return startTime != null;
//     }
// 
//     public String toString() {
//         StringBuilder s = new StringBuilder();
// 
//         s.append(startTime);
// 
//         if (endTime != null) {
//             s.append("--");
//             s.append(endTime);
//         }
// 
//         return s.toString();
//     }
// 
//     public String toStringWithoutBrackets() {
//         StringBuilder s = new StringBuilder();
// 
//         s.append(startTime.toStringWithoutBrackets());
// 
//         if (endTime != null) {
//             s.append("--");
//             s.append(endTime.toStringWithoutBrackets());
//         }
// 
//         return s.toString();
//     }
// 
//     public boolean shift() {
//         return shift(Calendar.getInstance());
//     }
// 
//     /**
//      * Shifts both timestamps by their repeater intervals.
//      *
//      * @param now current time
//      * @return {@code true} if shift was performed
//      */
//     public boolean shift(Calendar now) {
//         boolean shifted = false;
// 
//         if (startTime != null) {
//             if (startTime.shift(now)) {
//                 shifted = true;
//             }
//         }
// 
//         if (endTime != null) {
//             if (endTime.shift(now)) {
//                 shifted = true;
//             }
//         }
// 
//         return shifted;
//     }
// }
 | 
	import com.orgzly.org.datetime.OrgRange;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collections;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull; | 
	package com.orgzly.org.utils;
public class StateChangeLogicTest {
    @Test
    public void testFromTodoToNext() {
        StateChangeLogic scl  = new StateChangeLogic(Collections.singleton("DONE"));
        scl.setState("NEXT", "TODO", null, null);
        assertEquals("NEXT", scl.getState());
        assertNull(scl.getClosed());
    }
    @Test
    public void testFromTodoToDone() {
        StateChangeLogic scl  = new StateChangeLogic(Collections.singleton("DONE"));
        scl.setState("DONE", "TODO", null, null);
        assertEquals("DONE", scl.getState());
        assertNotNull(scl.getClosed());
    }
    @Test
    public void testFromDoneToCncl() {
        StateChangeLogic scl  = new StateChangeLogic(Arrays.asList("DONE", "CNCL"));
        scl.setState("CNCL", "DONE", null, null);
        assertEquals("CNCL", scl.getState());
        assertNotNull(scl.getClosed());
    }
    @Test
    public void testFromNoteToDoneWithRepeater() {
        StateChangeLogic scl  = new StateChangeLogic(Collections.singleton("DONE")); | 
	// Path: src/main/java/com/orgzly/org/datetime/OrgRange.java
// public class OrgRange {
//     private OrgDateTime startTime;
//     private OrgDateTime endTime;
// 
//     public static OrgRange parseOrNull(String str) {
//         if (OrgStringUtils.isEmpty(str)) {
//             return null;
//         }
// 
//         return parse(str);
//     }
// 
//     public static OrgRange parse(String str) {
//         if (str == null) {
//             throw new IllegalArgumentException("OrgRange cannot be created from null string");
//         }
// 
//         if (str.length() == 0) {
//             throw new IllegalArgumentException("OrgRange cannot be created from null string");
//         }
// 
//         OrgRange t = new OrgRange();
// 
//         Matcher m = OrgPatterns.DT_OR_RANGE_P.matcher(str);
// 
//         if (m.find()) {
// //            for (int i = 0; i < m.groupCount() + 1; i++) {
// //                System.out.println("group(" + i + ") " + m.group(i));
// //            }
// 
//             if (m.groupCount() == 6 && m.group(6) != null) { // Range - two timestamps
//                 t.startTime = OrgDateTime.parse(m.group(2));
//                 t.endTime = OrgDateTime.parse(m.group(5));
// 
//             } else { // Single timestamp
//                 t.startTime = OrgDateTime.parse(m.group(2));
//                 t.endTime = null;
//             }
// 
//             return t;
// 
//         } else {
//             throw new IllegalArgumentException(
//                     "String " + str +
//                     " cannot be parsed as OrgRange using pattern " + OrgPatterns.DT_OR_RANGE_P);
//         }
//     }
// 
//     // TODO: Rename to parse, rename other methods to getInstance, add *orThrow methods if needed
//     public static OrgRange doParse(String str) {
//         try {
//             // Make sure both OrgDateTime are actually parsed.
//             // This is pretty bad, clean these classes.
//             OrgRange range = OrgRange.parse(str);
//             range.startTime.getCalendar();
//             if (range.endTime != null) {
//                 range.endTime.getCalendar();
//             }
//             return range;
//         } catch (Exception e) {
//             return null;
//         }
//     }
// 
//     private OrgRange() {
//     }
// 
//     public OrgRange(OrgRange orgRange) {
//         this.startTime = new OrgDateTime(orgRange.getStartTime());
// 
//         if (orgRange.getEndTime() != null) {
//             this.endTime = new OrgDateTime(orgRange.getEndTime());
//         }
//     }
// 
//     public OrgRange(OrgDateTime fromTime) {
//         this(fromTime, null);
//     }
// 
//     public OrgRange(OrgDateTime fromTime, OrgDateTime endTime) {
//         if (fromTime == null) {
//             throw new IllegalArgumentException("OrgRange cannot be created from null OrgDateTime");
//         }
// 
//         this.startTime = fromTime;
//         this.endTime = endTime;
//     }
// 
//     public OrgDateTime getStartTime() {
//         return startTime;
//     }
// 
//     /**
//      * @return last time of the range, can be {@code null}
//      */
//     @Nullable
//     public OrgDateTime getEndTime() {
//         return endTime;
//     }
// 
//     public boolean isSet() {
//         return startTime != null;
//     }
// 
//     public String toString() {
//         StringBuilder s = new StringBuilder();
// 
//         s.append(startTime);
// 
//         if (endTime != null) {
//             s.append("--");
//             s.append(endTime);
//         }
// 
//         return s.toString();
//     }
// 
//     public String toStringWithoutBrackets() {
//         StringBuilder s = new StringBuilder();
// 
//         s.append(startTime.toStringWithoutBrackets());
// 
//         if (endTime != null) {
//             s.append("--");
//             s.append(endTime.toStringWithoutBrackets());
//         }
// 
//         return s.toString();
//     }
// 
//     public boolean shift() {
//         return shift(Calendar.getInstance());
//     }
// 
//     /**
//      * Shifts both timestamps by their repeater intervals.
//      *
//      * @param now current time
//      * @return {@code true} if shift was performed
//      */
//     public boolean shift(Calendar now) {
//         boolean shifted = false;
// 
//         if (startTime != null) {
//             if (startTime.shift(now)) {
//                 shifted = true;
//             }
//         }
// 
//         if (endTime != null) {
//             if (endTime.shift(now)) {
//                 shifted = true;
//             }
//         }
// 
//         return shifted;
//     }
// }
// Path: src/test/java/com/orgzly/org/utils/StateChangeLogicTest.java
import com.orgzly.org.datetime.OrgRange;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collections;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
package com.orgzly.org.utils;
public class StateChangeLogicTest {
    @Test
    public void testFromTodoToNext() {
        StateChangeLogic scl  = new StateChangeLogic(Collections.singleton("DONE"));
        scl.setState("NEXT", "TODO", null, null);
        assertEquals("NEXT", scl.getState());
        assertNull(scl.getClosed());
    }
    @Test
    public void testFromTodoToDone() {
        StateChangeLogic scl  = new StateChangeLogic(Collections.singleton("DONE"));
        scl.setState("DONE", "TODO", null, null);
        assertEquals("DONE", scl.getState());
        assertNotNull(scl.getClosed());
    }
    @Test
    public void testFromDoneToCncl() {
        StateChangeLogic scl  = new StateChangeLogic(Arrays.asList("DONE", "CNCL"));
        scl.setState("CNCL", "DONE", null, null);
        assertEquals("CNCL", scl.getState());
        assertNotNull(scl.getClosed());
    }
    @Test
    public void testFromNoteToDoneWithRepeater() {
        StateChangeLogic scl  = new StateChangeLogic(Collections.singleton("DONE")); | 
	        scl.setState("DONE", "NOTE", OrgRange.parse("<2018-02-06 Tue +7d>"), null); | 
| 
	orgzly/org-java | 
	src/test/java/com/orgzly/org/parser/OrgNestedSetParserTest.java | 
	// Path: src/main/java/com/orgzly/org/OrgFile.java
// public class OrgFile {
// 
//     /** In-buffer settings. */
//     private OrgFileSettings settings;
// 
//     /** Text before the first heading. */
//     private String preface;
// 
//     public OrgFile() {
// 	}
// 
//     public OrgFileSettings getSettings() {
//         if (settings == null) {
//             settings = new OrgFileSettings();
//         }
//         return settings;
//     }
// 
//     /**
//      * @return Text before first {@link OrgHead} in the file.
//      */
//     public String getPreface() {
//         return preface != null ? preface : "";
//     }
// 
//     public void setPreface(String str) {
//         preface = str;
//     }
// 
//     public String toString() {
// 		return OrgFile.class.getSimpleName() + "[" + preface.length() + "]";
// 	}
// }
 | 
	import com.orgzly.org.OrgFile;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.io.IOException;
import java.util.Arrays;
import java.util.TreeMap;
import static org.junit.Assert.assertEquals; | 
	                        "" +
                                " 1  2 \n"
                },
                {
                        "" +
                                "* A\n" +
                                "* B\n",
                        "" +
                                " 1  6 \n" +
                                " 2  3 * A\n" +
                                " 4  5 * B\n"
                }
        });
    }
    @Test
    public void testNestedSetModelParser() throws IOException {
        final TreeMap<Long, OrgNodeInSet> map = new TreeMap<>();
        OrgParser.Builder parserBuilder = new OrgParser.Builder()
                .setTodoKeywords(new String[]{"TODO"})
                .setDoneKeywords(new String[]{"DONE"})
                .setInput(data)
                .setListener(new OrgNestedSetParserListener() {
                    @Override
                    public void onNode(OrgNodeInSet node) {
                        map.put(node.getLft(), node);
                    }
                    @Override | 
	// Path: src/main/java/com/orgzly/org/OrgFile.java
// public class OrgFile {
// 
//     /** In-buffer settings. */
//     private OrgFileSettings settings;
// 
//     /** Text before the first heading. */
//     private String preface;
// 
//     public OrgFile() {
// 	}
// 
//     public OrgFileSettings getSettings() {
//         if (settings == null) {
//             settings = new OrgFileSettings();
//         }
//         return settings;
//     }
// 
//     /**
//      * @return Text before first {@link OrgHead} in the file.
//      */
//     public String getPreface() {
//         return preface != null ? preface : "";
//     }
// 
//     public void setPreface(String str) {
//         preface = str;
//     }
// 
//     public String toString() {
// 		return OrgFile.class.getSimpleName() + "[" + preface.length() + "]";
// 	}
// }
// Path: src/test/java/com/orgzly/org/parser/OrgNestedSetParserTest.java
import com.orgzly.org.OrgFile;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.io.IOException;
import java.util.Arrays;
import java.util.TreeMap;
import static org.junit.Assert.assertEquals;
                        "" +
                                " 1  2 \n"
                },
                {
                        "" +
                                "* A\n" +
                                "* B\n",
                        "" +
                                " 1  6 \n" +
                                " 2  3 * A\n" +
                                " 4  5 * B\n"
                }
        });
    }
    @Test
    public void testNestedSetModelParser() throws IOException {
        final TreeMap<Long, OrgNodeInSet> map = new TreeMap<>();
        OrgParser.Builder parserBuilder = new OrgParser.Builder()
                .setTodoKeywords(new String[]{"TODO"})
                .setDoneKeywords(new String[]{"DONE"})
                .setInput(data)
                .setListener(new OrgNestedSetParserListener() {
                    @Override
                    public void onNode(OrgNodeInSet node) {
                        map.put(node.getLft(), node);
                    }
                    @Override | 
	                    public void onFile(OrgFile file) { | 
| 
	orgzly/org-java | 
	src/main/java/com/orgzly/org/parser/OrgSaxyParserListener.java | 
	// Path: src/main/java/com/orgzly/org/OrgFile.java
// public class OrgFile {
// 
//     /** In-buffer settings. */
//     private OrgFileSettings settings;
// 
//     /** Text before the first heading. */
//     private String preface;
// 
//     public OrgFile() {
// 	}
// 
//     public OrgFileSettings getSettings() {
//         if (settings == null) {
//             settings = new OrgFileSettings();
//         }
//         return settings;
//     }
// 
//     /**
//      * @return Text before first {@link OrgHead} in the file.
//      */
//     public String getPreface() {
//         return preface != null ? preface : "";
//     }
// 
//     public void setPreface(String str) {
//         preface = str;
//     }
// 
//     public String toString() {
// 		return OrgFile.class.getSimpleName() + "[" + preface.length() + "]";
// 	}
// }
 | 
	import com.orgzly.org.OrgFile;
import java.io.IOException; | 
	package com.orgzly.org.parser;
public interface OrgSaxyParserListener {
    /**
     * Called for each new heading found.
     *
     * @param node Node in list.
     * @throws IOException Exception throws on error
     */
    void onHead(OrgNodeInList node) throws IOException;
    /**
     * Called last, after everything has been parsed.
     *
     * @param file File
     * @throws IOException Exception throws on error
     */ | 
	// Path: src/main/java/com/orgzly/org/OrgFile.java
// public class OrgFile {
// 
//     /** In-buffer settings. */
//     private OrgFileSettings settings;
// 
//     /** Text before the first heading. */
//     private String preface;
// 
//     public OrgFile() {
// 	}
// 
//     public OrgFileSettings getSettings() {
//         if (settings == null) {
//             settings = new OrgFileSettings();
//         }
//         return settings;
//     }
// 
//     /**
//      * @return Text before first {@link OrgHead} in the file.
//      */
//     public String getPreface() {
//         return preface != null ? preface : "";
//     }
// 
//     public void setPreface(String str) {
//         preface = str;
//     }
// 
//     public String toString() {
// 		return OrgFile.class.getSimpleName() + "[" + preface.length() + "]";
// 	}
// }
// Path: src/main/java/com/orgzly/org/parser/OrgSaxyParserListener.java
import com.orgzly.org.OrgFile;
import java.io.IOException;
package com.orgzly.org.parser;
public interface OrgSaxyParserListener {
    /**
     * Called for each new heading found.
     *
     * @param node Node in list.
     * @throws IOException Exception throws on error
     */
    void onHead(OrgNodeInList node) throws IOException;
    /**
     * Called last, after everything has been parsed.
     *
     * @param file File
     * @throws IOException Exception throws on error
     */ | 
	    void onFile(OrgFile file) throws IOException; | 
| 
	orgzly/org-java | 
	src/main/java/com/orgzly/org/parser/OrgNestedSetParserListener.java | 
	// Path: src/main/java/com/orgzly/org/OrgFile.java
// public class OrgFile {
// 
//     /** In-buffer settings. */
//     private OrgFileSettings settings;
// 
//     /** Text before the first heading. */
//     private String preface;
// 
//     public OrgFile() {
// 	}
// 
//     public OrgFileSettings getSettings() {
//         if (settings == null) {
//             settings = new OrgFileSettings();
//         }
//         return settings;
//     }
// 
//     /**
//      * @return Text before first {@link OrgHead} in the file.
//      */
//     public String getPreface() {
//         return preface != null ? preface : "";
//     }
// 
//     public void setPreface(String str) {
//         preface = str;
//     }
// 
//     public String toString() {
// 		return OrgFile.class.getSimpleName() + "[" + preface.length() + "]";
// 	}
// }
 | 
	import com.orgzly.org.OrgFile;
import java.io.IOException; | 
	package com.orgzly.org.parser;
public interface OrgNestedSetParserListener {
    void onNode(OrgNodeInSet node) throws IOException;
 | 
	// Path: src/main/java/com/orgzly/org/OrgFile.java
// public class OrgFile {
// 
//     /** In-buffer settings. */
//     private OrgFileSettings settings;
// 
//     /** Text before the first heading. */
//     private String preface;
// 
//     public OrgFile() {
// 	}
// 
//     public OrgFileSettings getSettings() {
//         if (settings == null) {
//             settings = new OrgFileSettings();
//         }
//         return settings;
//     }
// 
//     /**
//      * @return Text before first {@link OrgHead} in the file.
//      */
//     public String getPreface() {
//         return preface != null ? preface : "";
//     }
// 
//     public void setPreface(String str) {
//         preface = str;
//     }
// 
//     public String toString() {
// 		return OrgFile.class.getSimpleName() + "[" + preface.length() + "]";
// 	}
// }
// Path: src/main/java/com/orgzly/org/parser/OrgNestedSetParserListener.java
import com.orgzly.org.OrgFile;
import java.io.IOException;
package com.orgzly.org.parser;
public interface OrgNestedSetParserListener {
    void onNode(OrgNodeInSet node) throws IOException;
 | 
	    void onFile(OrgFile file) throws IOException; | 
| 
	oldterns/VileBot | 
	vilebot/src/main/java/com/oldterns/vilebot/handlers/user/KarmaRoll.java | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/util/BaseNick.java
// public class BaseNick
// {
//     // This would grab the leading x out of a nick that actually contains it
//     private static Pattern nickPattern = Pattern.compile( "(?:x|)([a-zA-Z0-9]+)(?:\\p{Punct}+[a-zA-Z0-9]*|)" );
// 
//     private static String primaryBotNick;
// 
//     private static Set<String> allBotNicks = new HashSet<>();
// 
//     public static String toBaseNick( String nick )
//     {
//         if ( allBotNicks.contains( nick ) )
//         {
//             nick = primaryBotNick;
//         }
//         else
//         {
//             Matcher nickMatcher = nickPattern.matcher( nick );
// 
//             if ( nickMatcher.find() )
//             {
//                 return nickMatcher.group( 1 );
//             }
//         }
//         return nick;
//     }
// 
//     public static String getPrimaryBotNick()
//     {
//         return primaryBotNick;
//     }
// 
//     public static void setPrimaryBotNick( String primaryNick )
//     {
//         primaryBotNick = primaryNick;
//     }
// 
//     public static Set<String> getBotNicks()
//     {
//         return allBotNicks;
//     }
// 
//     public static void addBotNick( String nick )
//     {
//         allBotNicks.add( nick );
//     }
// }
 | 
	import java.security.SecureRandom;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.oldterns.vilebot.Vilebot;
import com.oldterns.vilebot.db.KarmaDB;
import com.oldterns.vilebot.util.BaseNick;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.events.MessageEvent;
import org.pircbotx.hooks.types.GenericMessageEvent; | 
	package com.oldterns.vilebot.handlers.user;
public class KarmaRoll
    extends ListenerAdapter
{
    private static final Pattern rollPattern = Pattern.compile( "!roll(?: for|)(?: +([0-9]+)|)" );
    private static final Pattern cancelPattern = Pattern.compile( "!roll ?cancel" );
    private static final int UPPER_WAGER = 10;
    private RollGame currentGame;
    private final Object currentGameMutex = new Object();
    @Override
    public void onGenericMessage( final GenericMessageEvent event )
    {
        String text = event.getMessage();
        Matcher rollMatcher = rollPattern.matcher( text );
        Matcher cancelMatcher = cancelPattern.matcher( text );
        if ( rollMatcher.matches() )
            userHelp( event, rollMatcher );
        if ( cancelMatcher.matches() )
            manualCancel( event );
    }
    // @Handler
    private void userHelp( GenericMessageEvent event, Matcher rollMatcher )
    { | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/util/BaseNick.java
// public class BaseNick
// {
//     // This would grab the leading x out of a nick that actually contains it
//     private static Pattern nickPattern = Pattern.compile( "(?:x|)([a-zA-Z0-9]+)(?:\\p{Punct}+[a-zA-Z0-9]*|)" );
// 
//     private static String primaryBotNick;
// 
//     private static Set<String> allBotNicks = new HashSet<>();
// 
//     public static String toBaseNick( String nick )
//     {
//         if ( allBotNicks.contains( nick ) )
//         {
//             nick = primaryBotNick;
//         }
//         else
//         {
//             Matcher nickMatcher = nickPattern.matcher( nick );
// 
//             if ( nickMatcher.find() )
//             {
//                 return nickMatcher.group( 1 );
//             }
//         }
//         return nick;
//     }
// 
//     public static String getPrimaryBotNick()
//     {
//         return primaryBotNick;
//     }
// 
//     public static void setPrimaryBotNick( String primaryNick )
//     {
//         primaryBotNick = primaryNick;
//     }
// 
//     public static Set<String> getBotNicks()
//     {
//         return allBotNicks;
//     }
// 
//     public static void addBotNick( String nick )
//     {
//         allBotNicks.add( nick );
//     }
// }
// Path: vilebot/src/main/java/com/oldterns/vilebot/handlers/user/KarmaRoll.java
import java.security.SecureRandom;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.oldterns.vilebot.Vilebot;
import com.oldterns.vilebot.db.KarmaDB;
import com.oldterns.vilebot.util.BaseNick;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.events.MessageEvent;
import org.pircbotx.hooks.types.GenericMessageEvent;
package com.oldterns.vilebot.handlers.user;
public class KarmaRoll
    extends ListenerAdapter
{
    private static final Pattern rollPattern = Pattern.compile( "!roll(?: for|)(?: +([0-9]+)|)" );
    private static final Pattern cancelPattern = Pattern.compile( "!roll ?cancel" );
    private static final int UPPER_WAGER = 10;
    private RollGame currentGame;
    private final Object currentGameMutex = new Object();
    @Override
    public void onGenericMessage( final GenericMessageEvent event )
    {
        String text = event.getMessage();
        Matcher rollMatcher = rollPattern.matcher( text );
        Matcher cancelMatcher = cancelPattern.matcher( text );
        if ( rollMatcher.matches() )
            userHelp( event, rollMatcher );
        if ( cancelMatcher.matches() )
            manualCancel( event );
    }
    // @Handler
    private void userHelp( GenericMessageEvent event, Matcher rollMatcher )
    { | 
	        String sender = BaseNick.toBaseNick( event.getUser().getNick() ); | 
| 
	oldterns/VileBot | 
	vilebot/src/main/java/com/oldterns/vilebot/CharactersThatBreakEclipse.java | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/util/Colors.java
// public class Colors
// {
//     public static final String BLACK = "\u000301";
// 
//     public static final String BLUE = "\u000312";
// 
//     public static final String BOLD = "\u0002";
// 
//     public static final String BROWN = "\u000305";
// 
//     public static final String CYAN = "\u000311";
// 
//     public static final String DARK_BLUE = "\u000302";
// 
//     public static final String DARK_GRAY = "\u000314";
// 
//     public static final String DARK_GREEN = "\u000303";
// 
//     public static final String GREEN = "\u000309";
// 
//     public static final String LIGHT_GRAY = "\u000315";
// 
//     public static final String MAGENTA = "\u000313";
// 
//     public static final String NORMAL = "\u000f";
// 
//     public static final String OLIVE = "\u000307";
// 
//     public static final String PURPLE = "\u000306";
// 
//     public static final String RED = "\u000304";
// 
//     public static final String REVERSE = "\u0016";
// 
//     public static final String TEAL = "\u000310";
// 
//     public static final String UNDERLINE = "\u001f";
// 
//     public static final String WHITE = "\u000300";
// 
//     public static final String YELLOW = "\u000308";
// 
//     /**
//      * Return a copy of the input String with IRC bold characters inserted.
//      *
//      * @return The modified copy of the input String
//      */
//     public static String bold( String input )
//     {
//         return BOLD + input + BOLD;
//     }
// }
 | 
	import com.oldterns.vilebot.util.Colors; | 
	/**
 * Copyright (C) 2013 Oldterns
 *
 * This file may be modified and distributed under the terms
 * of the MIT license. See the LICENSE file for details.
 */
package com.oldterns.vilebot;
/**
 * Class to contain characters and strings that cause the Eclipse line spacing to break if viewed directly.
 */
public class CharactersThatBreakEclipse
{ | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/util/Colors.java
// public class Colors
// {
//     public static final String BLACK = "\u000301";
// 
//     public static final String BLUE = "\u000312";
// 
//     public static final String BOLD = "\u0002";
// 
//     public static final String BROWN = "\u000305";
// 
//     public static final String CYAN = "\u000311";
// 
//     public static final String DARK_BLUE = "\u000302";
// 
//     public static final String DARK_GRAY = "\u000314";
// 
//     public static final String DARK_GREEN = "\u000303";
// 
//     public static final String GREEN = "\u000309";
// 
//     public static final String LIGHT_GRAY = "\u000315";
// 
//     public static final String MAGENTA = "\u000313";
// 
//     public static final String NORMAL = "\u000f";
// 
//     public static final String OLIVE = "\u000307";
// 
//     public static final String PURPLE = "\u000306";
// 
//     public static final String RED = "\u000304";
// 
//     public static final String REVERSE = "\u0016";
// 
//     public static final String TEAL = "\u000310";
// 
//     public static final String UNDERLINE = "\u001f";
// 
//     public static final String WHITE = "\u000300";
// 
//     public static final String YELLOW = "\u000308";
// 
//     /**
//      * Return a copy of the input String with IRC bold characters inserted.
//      *
//      * @return The modified copy of the input String
//      */
//     public static String bold( String input )
//     {
//         return BOLD + input + BOLD;
//     }
// }
// Path: vilebot/src/main/java/com/oldterns/vilebot/CharactersThatBreakEclipse.java
import com.oldterns.vilebot.util.Colors;
/**
 * Copyright (C) 2013 Oldterns
 *
 * This file may be modified and distributed under the terms
 * of the MIT license. See the LICENSE file for details.
 */
package com.oldterns.vilebot;
/**
 * Class to contain characters and strings that cause the Eclipse line spacing to break if viewed directly.
 */
public class CharactersThatBreakEclipse
{ | 
	    public static final String LODEMOT = Colors.BOLD + "ಠ" + Colors.BOLD + "_" + Colors.BOLD + "ಠ" + Colors.BOLD; | 
| 
	oldterns/VileBot | 
	vilebot/src/main/java/com/oldterns/vilebot/handlers/user/Weather.java | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/util/Ignore.java
// public class Ignore
// {
//     private static Set<String> onJoin = new ConcurrentSkipListSet<String>();
// 
//     private static Set<String> autoOp = new ConcurrentSkipListSet<String>();
// 
//     public static Set<String> getOnJoin()
//     {
//         return onJoin;
//     }
// 
//     public static Set<String> getAutoOp()
//     {
//         return autoOp;
//     }
// 
//     public static void addOnJoin( String nick )
//     {
//         onJoin.add( nick );
//     }
// 
//     public static void addAutoOp( String channel )
//     {
//         autoOp.add( channel );
//     }
// }
 | 
	import com.oldterns.vilebot.util.Ignore;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.types.GenericMessageEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | 
	package com.oldterns.vilebot.handlers.user;
public class Weather
    extends ListenerAdapter
{
    private static final Logger logger = LoggerFactory.getLogger( Weather.class );
    private static final String LESS_NICK = "owilliams";
    static
    { | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/util/Ignore.java
// public class Ignore
// {
//     private static Set<String> onJoin = new ConcurrentSkipListSet<String>();
// 
//     private static Set<String> autoOp = new ConcurrentSkipListSet<String>();
// 
//     public static Set<String> getOnJoin()
//     {
//         return onJoin;
//     }
// 
//     public static Set<String> getAutoOp()
//     {
//         return autoOp;
//     }
// 
//     public static void addOnJoin( String nick )
//     {
//         onJoin.add( nick );
//     }
// 
//     public static void addAutoOp( String channel )
//     {
//         autoOp.add( channel );
//     }
// }
// Path: vilebot/src/main/java/com/oldterns/vilebot/handlers/user/Weather.java
import com.oldterns.vilebot.util.Ignore;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.types.GenericMessageEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
package com.oldterns.vilebot.handlers.user;
public class Weather
    extends ListenerAdapter
{
    private static final Logger logger = LoggerFactory.getLogger( Weather.class );
    private static final String LESS_NICK = "owilliams";
    static
    { | 
	        Ignore.addOnJoin( LESS_NICK ); | 
| 
	oldterns/VileBot | 
	vilebot/src/main/java/com/oldterns/vilebot/handlers/user/RockPaperScissors.java | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/util/BaseNick.java
// public class BaseNick
// {
//     // This would grab the leading x out of a nick that actually contains it
//     private static Pattern nickPattern = Pattern.compile( "(?:x|)([a-zA-Z0-9]+)(?:\\p{Punct}+[a-zA-Z0-9]*|)" );
// 
//     private static String primaryBotNick;
// 
//     private static Set<String> allBotNicks = new HashSet<>();
// 
//     public static String toBaseNick( String nick )
//     {
//         if ( allBotNicks.contains( nick ) )
//         {
//             nick = primaryBotNick;
//         }
//         else
//         {
//             Matcher nickMatcher = nickPattern.matcher( nick );
// 
//             if ( nickMatcher.find() )
//             {
//                 return nickMatcher.group( 1 );
//             }
//         }
//         return nick;
//     }
// 
//     public static String getPrimaryBotNick()
//     {
//         return primaryBotNick;
//     }
// 
//     public static void setPrimaryBotNick( String primaryNick )
//     {
//         primaryBotNick = primaryNick;
//     }
// 
//     public static Set<String> getBotNicks()
//     {
//         return allBotNicks;
//     }
// 
//     public static void addBotNick( String nick )
//     {
//         allBotNicks.add( nick );
//     }
// }
 | 
	import com.oldterns.vilebot.Vilebot;
import com.oldterns.vilebot.util.BaseNick;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.events.MessageEvent;
import org.pircbotx.hooks.events.PrivateMessageEvent;
import org.pircbotx.hooks.types.GenericMessageEvent;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | 
	        return event instanceof PrivateMessageEvent;
    }
    private boolean inGameChannel( GenericMessageEvent event )
    {
        return event instanceof MessageEvent && ( (MessageEvent) event ).getChannel().getName().equals( RPS_CHANNEL );
    }
    private boolean correctSolutionChannel( GenericMessageEvent event )
    {
        if ( ( isPrivate( event ) && inGameChannel( event ) ) )
        {
            return true;
        }
        else if ( ( (MessageEvent) event ).getChannel().getName().equals( RPS_CHANNEL ) )
        {
            event.respondWith( getSubmissionRuleString( event ) );
            return false;
        }
        else
        {
            event.respondWith( "To play Rock Paper Scissors join : " + RPS_CHANNEL );
            return false;
        }
    }
    private synchronized void cancelGame( GenericMessageEvent event )
    {
        if ( null != currGame )
        { | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/util/BaseNick.java
// public class BaseNick
// {
//     // This would grab the leading x out of a nick that actually contains it
//     private static Pattern nickPattern = Pattern.compile( "(?:x|)([a-zA-Z0-9]+)(?:\\p{Punct}+[a-zA-Z0-9]*|)" );
// 
//     private static String primaryBotNick;
// 
//     private static Set<String> allBotNicks = new HashSet<>();
// 
//     public static String toBaseNick( String nick )
//     {
//         if ( allBotNicks.contains( nick ) )
//         {
//             nick = primaryBotNick;
//         }
//         else
//         {
//             Matcher nickMatcher = nickPattern.matcher( nick );
// 
//             if ( nickMatcher.find() )
//             {
//                 return nickMatcher.group( 1 );
//             }
//         }
//         return nick;
//     }
// 
//     public static String getPrimaryBotNick()
//     {
//         return primaryBotNick;
//     }
// 
//     public static void setPrimaryBotNick( String primaryNick )
//     {
//         primaryBotNick = primaryNick;
//     }
// 
//     public static Set<String> getBotNicks()
//     {
//         return allBotNicks;
//     }
// 
//     public static void addBotNick( String nick )
//     {
//         allBotNicks.add( nick );
//     }
// }
// Path: vilebot/src/main/java/com/oldterns/vilebot/handlers/user/RockPaperScissors.java
import com.oldterns.vilebot.Vilebot;
import com.oldterns.vilebot.util.BaseNick;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.events.MessageEvent;
import org.pircbotx.hooks.events.PrivateMessageEvent;
import org.pircbotx.hooks.types.GenericMessageEvent;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
        return event instanceof PrivateMessageEvent;
    }
    private boolean inGameChannel( GenericMessageEvent event )
    {
        return event instanceof MessageEvent && ( (MessageEvent) event ).getChannel().getName().equals( RPS_CHANNEL );
    }
    private boolean correctSolutionChannel( GenericMessageEvent event )
    {
        if ( ( isPrivate( event ) && inGameChannel( event ) ) )
        {
            return true;
        }
        else if ( ( (MessageEvent) event ).getChannel().getName().equals( RPS_CHANNEL ) )
        {
            event.respondWith( getSubmissionRuleString( event ) );
            return false;
        }
        else
        {
            event.respondWith( "To play Rock Paper Scissors join : " + RPS_CHANNEL );
            return false;
        }
    }
    private synchronized void cancelGame( GenericMessageEvent event )
    {
        if ( null != currGame )
        { | 
	            String caller = BaseNick.toBaseNick( event.getUser().getNick() ); | 
| 
	oldterns/VileBot | 
	vilebot/src/main/java/com/oldterns/vilebot/handlers/user/RemindMe.java | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/util/BaseNick.java
// public class BaseNick
// {
//     // This would grab the leading x out of a nick that actually contains it
//     private static Pattern nickPattern = Pattern.compile( "(?:x|)([a-zA-Z0-9]+)(?:\\p{Punct}+[a-zA-Z0-9]*|)" );
// 
//     private static String primaryBotNick;
// 
//     private static Set<String> allBotNicks = new HashSet<>();
// 
//     public static String toBaseNick( String nick )
//     {
//         if ( allBotNicks.contains( nick ) )
//         {
//             nick = primaryBotNick;
//         }
//         else
//         {
//             Matcher nickMatcher = nickPattern.matcher( nick );
// 
//             if ( nickMatcher.find() )
//             {
//                 return nickMatcher.group( 1 );
//             }
//         }
//         return nick;
//     }
// 
//     public static String getPrimaryBotNick()
//     {
//         return primaryBotNick;
//     }
// 
//     public static void setPrimaryBotNick( String primaryNick )
//     {
//         primaryBotNick = primaryNick;
//     }
// 
//     public static Set<String> getBotNicks()
//     {
//         return allBotNicks;
//     }
// 
//     public static void addBotNick( String nick )
//     {
//         allBotNicks.add( nick );
//     }
// }
 | 
	import com.oldterns.vilebot.util.BaseNick;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.types.GenericMessageEvent;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | 
	package com.oldterns.vilebot.handlers.user;
//@HandlerContainer
public class RemindMe
    extends ListenerAdapter
{
    private static final String timeFormat = "(\\d+\\w*)";
    private static final Pattern remindMePattern = Pattern.compile( "^!remindme (.+) " + timeFormat );
    private final String INVALID_TYPE_ERROR =
        "The time type given is not valid (use d for day, m for month, s for second)";
    private final String NO_TYPE_ERROR = "There was no type given for the time (use d/m/s)";
    private final String TIME_TOO_LARGE_ERROR = "The value of time given is greater than the maximum Integer value";
    private final String TOO_MANY_REMINDERS_ERROR =
        "There is a limit of 10 reminders, please wait until one reminder ends to set a new one.";
    private final String TIME_IS_OKAY = "Given time input is okay";
    private String timeError = TIME_IS_OKAY;
    private static Map<String, Integer> userReminders = new HashMap<>();
    private final int MAX_REMINDERS = 10;
    // @Handler
    @Override
    public void onGenericMessage( GenericMessageEvent event )
    {
        String text = event.getMessage();
        Matcher matcher = remindMePattern.matcher( text );
        if ( matcher.matches() )
        {
            String message = matcher.group( 1 );
            String time = matcher.group( 2 ); | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/util/BaseNick.java
// public class BaseNick
// {
//     // This would grab the leading x out of a nick that actually contains it
//     private static Pattern nickPattern = Pattern.compile( "(?:x|)([a-zA-Z0-9]+)(?:\\p{Punct}+[a-zA-Z0-9]*|)" );
// 
//     private static String primaryBotNick;
// 
//     private static Set<String> allBotNicks = new HashSet<>();
// 
//     public static String toBaseNick( String nick )
//     {
//         if ( allBotNicks.contains( nick ) )
//         {
//             nick = primaryBotNick;
//         }
//         else
//         {
//             Matcher nickMatcher = nickPattern.matcher( nick );
// 
//             if ( nickMatcher.find() )
//             {
//                 return nickMatcher.group( 1 );
//             }
//         }
//         return nick;
//     }
// 
//     public static String getPrimaryBotNick()
//     {
//         return primaryBotNick;
//     }
// 
//     public static void setPrimaryBotNick( String primaryNick )
//     {
//         primaryBotNick = primaryNick;
//     }
// 
//     public static Set<String> getBotNicks()
//     {
//         return allBotNicks;
//     }
// 
//     public static void addBotNick( String nick )
//     {
//         allBotNicks.add( nick );
//     }
// }
// Path: vilebot/src/main/java/com/oldterns/vilebot/handlers/user/RemindMe.java
import com.oldterns.vilebot.util.BaseNick;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.types.GenericMessageEvent;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
package com.oldterns.vilebot.handlers.user;
//@HandlerContainer
public class RemindMe
    extends ListenerAdapter
{
    private static final String timeFormat = "(\\d+\\w*)";
    private static final Pattern remindMePattern = Pattern.compile( "^!remindme (.+) " + timeFormat );
    private final String INVALID_TYPE_ERROR =
        "The time type given is not valid (use d for day, m for month, s for second)";
    private final String NO_TYPE_ERROR = "There was no type given for the time (use d/m/s)";
    private final String TIME_TOO_LARGE_ERROR = "The value of time given is greater than the maximum Integer value";
    private final String TOO_MANY_REMINDERS_ERROR =
        "There is a limit of 10 reminders, please wait until one reminder ends to set a new one.";
    private final String TIME_IS_OKAY = "Given time input is okay";
    private String timeError = TIME_IS_OKAY;
    private static Map<String, Integer> userReminders = new HashMap<>();
    private final int MAX_REMINDERS = 10;
    // @Handler
    @Override
    public void onGenericMessage( GenericMessageEvent event )
    {
        String text = event.getMessage();
        Matcher matcher = remindMePattern.matcher( text );
        if ( matcher.matches() )
        {
            String message = matcher.group( 1 );
            String time = matcher.group( 2 ); | 
	            String creator = BaseNick.toBaseNick( event.getUser().getNick() ); | 
| 
	oldterns/VileBot | 
	vilebot/src/main/java/com/oldterns/vilebot/handlers/user/Omgword.java | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/util/BaseNick.java
// public class BaseNick
// {
//     // This would grab the leading x out of a nick that actually contains it
//     private static Pattern nickPattern = Pattern.compile( "(?:x|)([a-zA-Z0-9]+)(?:\\p{Punct}+[a-zA-Z0-9]*|)" );
// 
//     private static String primaryBotNick;
// 
//     private static Set<String> allBotNicks = new HashSet<>();
// 
//     public static String toBaseNick( String nick )
//     {
//         if ( allBotNicks.contains( nick ) )
//         {
//             nick = primaryBotNick;
//         }
//         else
//         {
//             Matcher nickMatcher = nickPattern.matcher( nick );
// 
//             if ( nickMatcher.find() )
//             {
//                 return nickMatcher.group( 1 );
//             }
//         }
//         return nick;
//     }
// 
//     public static String getPrimaryBotNick()
//     {
//         return primaryBotNick;
//     }
// 
//     public static void setPrimaryBotNick( String primaryNick )
//     {
//         primaryBotNick = primaryNick;
//     }
// 
//     public static Set<String> getBotNicks()
//     {
//         return allBotNicks;
//     }
// 
//     public static void addBotNick( String nick )
//     {
//         allBotNicks.add( nick );
//     }
// }
 | 
	import com.oldterns.vilebot.Vilebot;
import com.oldterns.vilebot.db.KarmaDB;
import com.oldterns.vilebot.util.BaseNick;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.events.MessageEvent;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | 
	    private void startTimer( final MessageEvent event )
    {
        timer.submit( () -> {
            try
            {
                Thread.sleep( TIMEOUT );
                timeoutTimer( event );
            }
            catch ( InterruptedException e )
            {
                e.printStackTrace();
            }
        } );
    }
    private void timeoutTimer( MessageEvent event )
    {
        String message = currentGame.getTimeoutString();
        event.respondWith( message );
        currentGame = null;
    }
    private void stopTimer()
    {
        timer.shutdownNow();
        timer = Executors.newFixedThreadPool( 1 );
    }
    private synchronized void finishGame( MessageEvent event, String answer )
    { | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/util/BaseNick.java
// public class BaseNick
// {
//     // This would grab the leading x out of a nick that actually contains it
//     private static Pattern nickPattern = Pattern.compile( "(?:x|)([a-zA-Z0-9]+)(?:\\p{Punct}+[a-zA-Z0-9]*|)" );
// 
//     private static String primaryBotNick;
// 
//     private static Set<String> allBotNicks = new HashSet<>();
// 
//     public static String toBaseNick( String nick )
//     {
//         if ( allBotNicks.contains( nick ) )
//         {
//             nick = primaryBotNick;
//         }
//         else
//         {
//             Matcher nickMatcher = nickPattern.matcher( nick );
// 
//             if ( nickMatcher.find() )
//             {
//                 return nickMatcher.group( 1 );
//             }
//         }
//         return nick;
//     }
// 
//     public static String getPrimaryBotNick()
//     {
//         return primaryBotNick;
//     }
// 
//     public static void setPrimaryBotNick( String primaryNick )
//     {
//         primaryBotNick = primaryNick;
//     }
// 
//     public static Set<String> getBotNicks()
//     {
//         return allBotNicks;
//     }
// 
//     public static void addBotNick( String nick )
//     {
//         allBotNicks.add( nick );
//     }
// }
// Path: vilebot/src/main/java/com/oldterns/vilebot/handlers/user/Omgword.java
import com.oldterns.vilebot.Vilebot;
import com.oldterns.vilebot.db.KarmaDB;
import com.oldterns.vilebot.util.BaseNick;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.events.MessageEvent;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
    private void startTimer( final MessageEvent event )
    {
        timer.submit( () -> {
            try
            {
                Thread.sleep( TIMEOUT );
                timeoutTimer( event );
            }
            catch ( InterruptedException e )
            {
                e.printStackTrace();
            }
        } );
    }
    private void timeoutTimer( MessageEvent event )
    {
        String message = currentGame.getTimeoutString();
        event.respondWith( message );
        currentGame = null;
    }
    private void stopTimer()
    {
        timer.shutdownNow();
        timer = Executors.newFixedThreadPool( 1 );
    }
    private synchronized void finishGame( MessageEvent event, String answer )
    { | 
	        String answerer = BaseNick.toBaseNick( Objects.requireNonNull( event.getUser() ).getNick() ); | 
| 
	oldterns/VileBot | 
	vilebot/src/main/java/com/oldterns/vilebot/handlers/user/KarmaTransfer.java | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/util/BaseNick.java
// public class BaseNick
// {
//     // This would grab the leading x out of a nick that actually contains it
//     private static Pattern nickPattern = Pattern.compile( "(?:x|)([a-zA-Z0-9]+)(?:\\p{Punct}+[a-zA-Z0-9]*|)" );
// 
//     private static String primaryBotNick;
// 
//     private static Set<String> allBotNicks = new HashSet<>();
// 
//     public static String toBaseNick( String nick )
//     {
//         if ( allBotNicks.contains( nick ) )
//         {
//             nick = primaryBotNick;
//         }
//         else
//         {
//             Matcher nickMatcher = nickPattern.matcher( nick );
// 
//             if ( nickMatcher.find() )
//             {
//                 return nickMatcher.group( 1 );
//             }
//         }
//         return nick;
//     }
// 
//     public static String getPrimaryBotNick()
//     {
//         return primaryBotNick;
//     }
// 
//     public static void setPrimaryBotNick( String primaryNick )
//     {
//         primaryBotNick = primaryNick;
//     }
// 
//     public static Set<String> getBotNicks()
//     {
//         return allBotNicks;
//     }
// 
//     public static void addBotNick( String nick )
//     {
//         allBotNicks.add( nick );
//     }
// }
 | 
	import com.oldterns.vilebot.Vilebot;
import com.oldterns.vilebot.db.KarmaDB;
import com.oldterns.vilebot.util.BaseNick;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.events.MessageEvent;
import org.pircbotx.hooks.types.GenericMessageEvent;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | 
	        Matcher cancelTransferMatcher = cancelTransferPattern.matcher( text );
        Matcher acceptTransferMatcher = acceptTransferPattern.matcher( text );
        Matcher rejectTransferMatcher = rejectTransferPattern.matcher( text );
        if ( transferMatcher.matches() )
            transferKarma( event, transferMatcher );
        if ( cancelTransferMatcher.matches() )
            cancelTransfer( event );
        if ( acceptTransferMatcher.matches() )
            acceptTransfer( event );
        if ( rejectTransferMatcher.matches() )
            rejectTransfer( event );
    }
    private void transferKarma( GenericMessageEvent event, Matcher transferMatcher )
    {
        // Prevent users from transferring karma outside of #thefoobar
        if ( !( event instanceof MessageEvent )
            || !( (MessageEvent) event ).getChannel().getName().equals( Vilebot.getConfig().get( "ircChannel1" ) ) )
        {
            event.respondWith( "You must be in " + Vilebot.getConfig().get( "ircChannel1" ) + " to transfer karma." );
            return;
        }
        synchronized ( currentTransferMutex )
        {
            // No existing transfer
            if ( currentTransaction == null )
            {
                // Check if sender is the same as the receiver | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/util/BaseNick.java
// public class BaseNick
// {
//     // This would grab the leading x out of a nick that actually contains it
//     private static Pattern nickPattern = Pattern.compile( "(?:x|)([a-zA-Z0-9]+)(?:\\p{Punct}+[a-zA-Z0-9]*|)" );
// 
//     private static String primaryBotNick;
// 
//     private static Set<String> allBotNicks = new HashSet<>();
// 
//     public static String toBaseNick( String nick )
//     {
//         if ( allBotNicks.contains( nick ) )
//         {
//             nick = primaryBotNick;
//         }
//         else
//         {
//             Matcher nickMatcher = nickPattern.matcher( nick );
// 
//             if ( nickMatcher.find() )
//             {
//                 return nickMatcher.group( 1 );
//             }
//         }
//         return nick;
//     }
// 
//     public static String getPrimaryBotNick()
//     {
//         return primaryBotNick;
//     }
// 
//     public static void setPrimaryBotNick( String primaryNick )
//     {
//         primaryBotNick = primaryNick;
//     }
// 
//     public static Set<String> getBotNicks()
//     {
//         return allBotNicks;
//     }
// 
//     public static void addBotNick( String nick )
//     {
//         allBotNicks.add( nick );
//     }
// }
// Path: vilebot/src/main/java/com/oldterns/vilebot/handlers/user/KarmaTransfer.java
import com.oldterns.vilebot.Vilebot;
import com.oldterns.vilebot.db.KarmaDB;
import com.oldterns.vilebot.util.BaseNick;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.events.MessageEvent;
import org.pircbotx.hooks.types.GenericMessageEvent;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
        Matcher cancelTransferMatcher = cancelTransferPattern.matcher( text );
        Matcher acceptTransferMatcher = acceptTransferPattern.matcher( text );
        Matcher rejectTransferMatcher = rejectTransferPattern.matcher( text );
        if ( transferMatcher.matches() )
            transferKarma( event, transferMatcher );
        if ( cancelTransferMatcher.matches() )
            cancelTransfer( event );
        if ( acceptTransferMatcher.matches() )
            acceptTransfer( event );
        if ( rejectTransferMatcher.matches() )
            rejectTransfer( event );
    }
    private void transferKarma( GenericMessageEvent event, Matcher transferMatcher )
    {
        // Prevent users from transferring karma outside of #thefoobar
        if ( !( event instanceof MessageEvent )
            || !( (MessageEvent) event ).getChannel().getName().equals( Vilebot.getConfig().get( "ircChannel1" ) ) )
        {
            event.respondWith( "You must be in " + Vilebot.getConfig().get( "ircChannel1" ) + " to transfer karma." );
            return;
        }
        synchronized ( currentTransferMutex )
        {
            // No existing transfer
            if ( currentTransaction == null )
            {
                // Check if sender is the same as the receiver | 
	                String sender = BaseNick.toBaseNick( event.getUser().getNick() ); | 
| 
	oldterns/VileBot | 
	vilebot/src/main/java/com/oldterns/vilebot/handlers/user/Jokes.java | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/CharactersThatBreakEclipse.java
// public class CharactersThatBreakEclipse
// {
//     public static final String LODEMOT = Colors.BOLD + "ಠ" + Colors.BOLD + "_" + Colors.BOLD + "ಠ" + Colors.BOLD;
// 
//     public static final String KIRBYFLIP = "(╯°□°)╯︵<(x˙x)>";
// }
 | 
	import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.oldterns.vilebot.CharactersThatBreakEclipse;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.types.GenericMessageEvent; | 
	    private static final List<String> chucks = generateChucks();
    private static final List<String> jokes = generateJokes();
    @Override
    public void onGenericMessage( final GenericMessageEvent event )
    {
        String text = event.getMessage();
        Matcher containersIsLinuxMatcher = containerPattern.matcher( text );
        Matcher redditLODMatcher = redditPattern.matcher( text );
        Matcher listBasedJokesMatcher = listJokePattern.matcher( text );
        if ( containersIsLinuxMatcher.find() )
            containersIsLinux( event );
        if ( redditLODMatcher.matches() )
            redditLOD( event );
        if ( listBasedJokesMatcher.matches() )
            listBasedJokes( event, listBasedJokesMatcher );
    }
    private void containersIsLinux( GenericMessageEvent event )
    {
        event.respondWith( jokes.get( random.nextInt( jokes.size() ) ) );
    }
    private void redditLOD( GenericMessageEvent event )
    {
        if ( random.nextInt( 10 ) > 6 )
        { | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/CharactersThatBreakEclipse.java
// public class CharactersThatBreakEclipse
// {
//     public static final String LODEMOT = Colors.BOLD + "ಠ" + Colors.BOLD + "_" + Colors.BOLD + "ಠ" + Colors.BOLD;
// 
//     public static final String KIRBYFLIP = "(╯°□°)╯︵<(x˙x)>";
// }
// Path: vilebot/src/main/java/com/oldterns/vilebot/handlers/user/Jokes.java
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.oldterns.vilebot.CharactersThatBreakEclipse;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.types.GenericMessageEvent;
    private static final List<String> chucks = generateChucks();
    private static final List<String> jokes = generateJokes();
    @Override
    public void onGenericMessage( final GenericMessageEvent event )
    {
        String text = event.getMessage();
        Matcher containersIsLinuxMatcher = containerPattern.matcher( text );
        Matcher redditLODMatcher = redditPattern.matcher( text );
        Matcher listBasedJokesMatcher = listJokePattern.matcher( text );
        if ( containersIsLinuxMatcher.find() )
            containersIsLinux( event );
        if ( redditLODMatcher.matches() )
            redditLOD( event );
        if ( listBasedJokesMatcher.matches() )
            listBasedJokes( event, listBasedJokesMatcher );
    }
    private void containersIsLinux( GenericMessageEvent event )
    {
        event.respondWith( jokes.get( random.nextInt( jokes.size() ) ) );
    }
    private void redditLOD( GenericMessageEvent event )
    {
        if ( random.nextInt( 10 ) > 6 )
        { | 
	            event.respondWith( CharactersThatBreakEclipse.LODEMOT ); | 
| 
	oldterns/VileBot | 
	vilebot/src/main/java/com/oldterns/vilebot/db/PasswordDB.java | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/util/HMAC.java
// public class HMAC
// {
// 
//     private static Logger logger = LoggerFactory.getLogger( HMAC.class );
// 
//     /**
//      * Generate an HMAC signature from message and key, using the SHA2 512 bit hash algo.
//      * 
//      * @param message The message to be signed
//      * @param key The key
//      * @return HMAC signature of message using key if no error, else null
//      */
//     public static String generateHMAC( String message, String key )
//     {
//         try
//         {
//             return generateHMAC( "HmacSHA512", message, key );
//         }
//         catch ( NoSuchAlgorithmException e )
//         {
//             logger.error( e.getMessage() );
//             logger.error( "Hash algorithim unsupported" );
//         }
//         return null;
//     }
// 
//     /**
//      * Generate an HMAC signature from message and key, using the given hash algo.
//      * 
//      * @param algo An Hmac Algorithm to use, see {@link Mac#getInstance(String)}
//      * @param message The message to be signed
//      * @param key The key
//      * @return HMAC signature of message using key if no error, else null
//      */
//     public static String generateHMAC( String algo, String message, String key )
//         throws NoSuchAlgorithmException
//     {
//         Mac mac = Mac.getInstance( algo );
//         SecretKeySpec secret = new SecretKeySpec( key.getBytes(), algo );
//         try
//         {
//             mac.init( secret );
// 
//             byte[] digest = mac.doFinal( message.getBytes() );
//             return bytesToHex( digest );
//         }
//         catch ( InvalidKeyException e )
//         {
//             logger.error( e.getMessage() );
//             logger.error( "Can't init Mac instance with key" );
//         }
//         return null;
//     }
// 
//     /**
//      * http://stackoverflow.com/questions/9655181/convert-from-byte-array-to-hex-string-in-java
//      * 
//      * @param bytes byte array
//      * @return String of byte array converted to hex characters. Lower case alphabet.
//      */
//     private static String bytesToHex( byte[] bytes )
//     {
//         final char[] hexArray = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
//         char[] hexChars = new char[bytes.length * 2];
//         int v;
//         for ( int j = 0; j < bytes.length; j++ )
//         {
//             v = bytes[j] & 0xFF;
//             hexChars[j * 2] = hexArray[v >>> 4];
//             hexChars[j * 2 + 1] = hexArray[v & 0x0F];
//         }
//         return new String( hexChars );
//     }
// }
 | 
	import java.util.UUID;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;
import com.oldterns.vilebot.util.HMAC; | 
	/**
 * Copyright (C) 2013 Oldterns
 *
 * This file may be modified and distributed under the terms
 * of the MIT license. See the LICENSE file for details.
 */
package com.oldterns.vilebot.db;
public class PasswordDB
    extends RedisDB
{
    private static final String keyOfPassHash = "password";
    private static final String keyOfPassSaltsHash = "password-salts";
    // Note, there is some overlap in terms between the crypto term "Secure Hash" and the Redis structure "Hash". Redis
    // hashes are maps, though called hashes because of a common method of implementing them via a hash function. Except
    // for keyOfPassHash and keyOfPassSaltsHash, every use of "hash" in this file refers to the cryptography term.
    /**
     * @return A long random string
     */
    private static String generateSalt()
    {
        return UUID.randomUUID().toString();
    }
    private static String getSalt( String username )
    {
        Jedis jedis = pool.getResource();
        try
        {
            return jedis.hget( keyOfPassSaltsHash, username );
        }
        finally
        {
            pool.returnResource( jedis );
        }
    }
    private static String hash( String salt, String input )
    { | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/util/HMAC.java
// public class HMAC
// {
// 
//     private static Logger logger = LoggerFactory.getLogger( HMAC.class );
// 
//     /**
//      * Generate an HMAC signature from message and key, using the SHA2 512 bit hash algo.
//      * 
//      * @param message The message to be signed
//      * @param key The key
//      * @return HMAC signature of message using key if no error, else null
//      */
//     public static String generateHMAC( String message, String key )
//     {
//         try
//         {
//             return generateHMAC( "HmacSHA512", message, key );
//         }
//         catch ( NoSuchAlgorithmException e )
//         {
//             logger.error( e.getMessage() );
//             logger.error( "Hash algorithim unsupported" );
//         }
//         return null;
//     }
// 
//     /**
//      * Generate an HMAC signature from message and key, using the given hash algo.
//      * 
//      * @param algo An Hmac Algorithm to use, see {@link Mac#getInstance(String)}
//      * @param message The message to be signed
//      * @param key The key
//      * @return HMAC signature of message using key if no error, else null
//      */
//     public static String generateHMAC( String algo, String message, String key )
//         throws NoSuchAlgorithmException
//     {
//         Mac mac = Mac.getInstance( algo );
//         SecretKeySpec secret = new SecretKeySpec( key.getBytes(), algo );
//         try
//         {
//             mac.init( secret );
// 
//             byte[] digest = mac.doFinal( message.getBytes() );
//             return bytesToHex( digest );
//         }
//         catch ( InvalidKeyException e )
//         {
//             logger.error( e.getMessage() );
//             logger.error( "Can't init Mac instance with key" );
//         }
//         return null;
//     }
// 
//     /**
//      * http://stackoverflow.com/questions/9655181/convert-from-byte-array-to-hex-string-in-java
//      * 
//      * @param bytes byte array
//      * @return String of byte array converted to hex characters. Lower case alphabet.
//      */
//     private static String bytesToHex( byte[] bytes )
//     {
//         final char[] hexArray = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
//         char[] hexChars = new char[bytes.length * 2];
//         int v;
//         for ( int j = 0; j < bytes.length; j++ )
//         {
//             v = bytes[j] & 0xFF;
//             hexChars[j * 2] = hexArray[v >>> 4];
//             hexChars[j * 2 + 1] = hexArray[v & 0x0F];
//         }
//         return new String( hexChars );
//     }
// }
// Path: vilebot/src/main/java/com/oldterns/vilebot/db/PasswordDB.java
import java.util.UUID;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;
import com.oldterns.vilebot.util.HMAC;
/**
 * Copyright (C) 2013 Oldterns
 *
 * This file may be modified and distributed under the terms
 * of the MIT license. See the LICENSE file for details.
 */
package com.oldterns.vilebot.db;
public class PasswordDB
    extends RedisDB
{
    private static final String keyOfPassHash = "password";
    private static final String keyOfPassSaltsHash = "password-salts";
    // Note, there is some overlap in terms between the crypto term "Secure Hash" and the Redis structure "Hash". Redis
    // hashes are maps, though called hashes because of a common method of implementing them via a hash function. Except
    // for keyOfPassHash and keyOfPassSaltsHash, every use of "hash" in this file refers to the cryptography term.
    /**
     * @return A long random string
     */
    private static String generateSalt()
    {
        return UUID.randomUUID().toString();
    }
    private static String getSalt( String username )
    {
        Jedis jedis = pool.getResource();
        try
        {
            return jedis.hget( keyOfPassSaltsHash, username );
        }
        finally
        {
            pool.returnResource( jedis );
        }
    }
    private static String hash( String salt, String input )
    { | 
	        return HMAC.generateHMAC( input, salt ); | 
| 
	oldterns/VileBot | 
	vilebot/src/test/java/vilebot/util/BaseNickTest.java | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/util/BaseNick.java
// public class BaseNick
// {
//     // This would grab the leading x out of a nick that actually contains it
//     private static Pattern nickPattern = Pattern.compile( "(?:x|)([a-zA-Z0-9]+)(?:\\p{Punct}+[a-zA-Z0-9]*|)" );
// 
//     private static String primaryBotNick;
// 
//     private static Set<String> allBotNicks = new HashSet<>();
// 
//     public static String toBaseNick( String nick )
//     {
//         if ( allBotNicks.contains( nick ) )
//         {
//             nick = primaryBotNick;
//         }
//         else
//         {
//             Matcher nickMatcher = nickPattern.matcher( nick );
// 
//             if ( nickMatcher.find() )
//             {
//                 return nickMatcher.group( 1 );
//             }
//         }
//         return nick;
//     }
// 
//     public static String getPrimaryBotNick()
//     {
//         return primaryBotNick;
//     }
// 
//     public static void setPrimaryBotNick( String primaryNick )
//     {
//         primaryBotNick = primaryNick;
//     }
// 
//     public static Set<String> getBotNicks()
//     {
//         return allBotNicks;
//     }
// 
//     public static void addBotNick( String nick )
//     {
//         allBotNicks.add( nick );
//     }
// }
 | 
	import com.oldterns.vilebot.util.BaseNick;
import org.junit.Test;
import java.util.HashSet;
import java.util.Set;
import static org.junit.Assert.assertEquals; | 
	package vilebot.util;
public class BaseNickTest
{
    @Test
    public void baseNickTest()
    {
        String baseNick = "salman";
        Set<String> nicks = new HashSet<>();
        nicks.add( "salman" );
        nicks.add( "salman|wfh" );
        nicks.add( "salman_afk" );
        nicks.add( "xsalman" );
        nicks.add( "salman_server_room" );
        nicks.add( "salman|server_room" );
        for ( String nick : nicks )
        { | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/util/BaseNick.java
// public class BaseNick
// {
//     // This would grab the leading x out of a nick that actually contains it
//     private static Pattern nickPattern = Pattern.compile( "(?:x|)([a-zA-Z0-9]+)(?:\\p{Punct}+[a-zA-Z0-9]*|)" );
// 
//     private static String primaryBotNick;
// 
//     private static Set<String> allBotNicks = new HashSet<>();
// 
//     public static String toBaseNick( String nick )
//     {
//         if ( allBotNicks.contains( nick ) )
//         {
//             nick = primaryBotNick;
//         }
//         else
//         {
//             Matcher nickMatcher = nickPattern.matcher( nick );
// 
//             if ( nickMatcher.find() )
//             {
//                 return nickMatcher.group( 1 );
//             }
//         }
//         return nick;
//     }
// 
//     public static String getPrimaryBotNick()
//     {
//         return primaryBotNick;
//     }
// 
//     public static void setPrimaryBotNick( String primaryNick )
//     {
//         primaryBotNick = primaryNick;
//     }
// 
//     public static Set<String> getBotNicks()
//     {
//         return allBotNicks;
//     }
// 
//     public static void addBotNick( String nick )
//     {
//         allBotNicks.add( nick );
//     }
// }
// Path: vilebot/src/test/java/vilebot/util/BaseNickTest.java
import com.oldterns.vilebot.util.BaseNick;
import org.junit.Test;
import java.util.HashSet;
import java.util.Set;
import static org.junit.Assert.assertEquals;
package vilebot.util;
public class BaseNickTest
{
    @Test
    public void baseNickTest()
    {
        String baseNick = "salman";
        Set<String> nicks = new HashSet<>();
        nicks.add( "salman" );
        nicks.add( "salman|wfh" );
        nicks.add( "salman_afk" );
        nicks.add( "xsalman" );
        nicks.add( "salman_server_room" );
        nicks.add( "salman|server_room" );
        for ( String nick : nicks )
        { | 
	            assertEquals( baseNick, BaseNick.toBaseNick( nick ) ); | 
| 
	oldterns/VileBot | 
	vilebot/src/main/java/com/oldterns/vilebot/handlers/user/ImageToAscii.java | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/util/ASCII.java
// public final class ASCII
// {
//     private boolean negative;
// 
//     public ASCII()
//     {
//         this( false );
//     }
// 
//     public ASCII( final boolean negative )
//     {
//         this.negative = negative;
//     }
// 
//     public String convert( final BufferedImage image )
//     {
//         StringBuilder sb = new StringBuilder( ( image.getWidth() + 1 ) * image.getHeight() );
//         for ( int y = 0; y < image.getHeight(); y++ )
//         {
//             if ( sb.length() != 0 )
//                 sb.append( "\n" );
//             for ( int x = 0; x < image.getWidth(); x++ )
//             {
//                 Color pixelColor = new Color( image.getRGB( x, y ) );
//                 double gValue = (double) pixelColor.getRed() * 0.2989 + (double) pixelColor.getBlue() * 0.5870
//                     + (double) pixelColor.getGreen() * 0.1140;
//                 final char s = negative ? returnStrNeg( gValue ) : returnStrPos( gValue );
//                 sb.append( s );
//             }
//         }
//         return sb.toString();
//     }
// 
//     /**
//      * Create a new string and assign to it a string based on the grayscale value. If the grayscale value is very high,
//      * the pixel is very bright and assign characters such as . and , that do not appear very dark. If the grayscale
//      * value is very lowm the pixel is very dark, assign characters such as # and @ which appear very dark.
//      *
//      * @param g grayscale
//      * @return char
//      */
//     private char returnStrPos( double g )// takes the grayscale value as parameter
//     {
//         final char str;
// 
//         if ( g >= 230.0 )
//         {
//             str = ' ';
//         }
//         else if ( g >= 200.0 )
//         {
//             str = '.';
//         }
//         else if ( g >= 180.0 )
//         {
//             str = '*';
//         }
//         else if ( g >= 160.0 )
//         {
//             str = ':';
//         }
//         else if ( g >= 130.0 )
//         {
//             str = 'o';
//         }
//         else if ( g >= 100.0 )
//         {
//             str = '&';
//         }
//         else if ( g >= 70.0 )
//         {
//             str = '8';
//         }
//         else if ( g >= 50.0 )
//         {
//             str = '#';
//         }
//         else
//         {
//             str = '@';
//         }
//         return str; // return the character
//     }
// 
//     /**
//      * Same method as above, except it reverses the darkness of the pixel. A dark pixel is given a light character and
//      * vice versa.
//      *
//      * @param g grayscale
//      * @return char
//      */
//     private char returnStrNeg( double g )
//     {
//         final char str;
// 
//         if ( g >= 230.0 )
//         {
//             str = '@';
//         }
//         else if ( g >= 200.0 )
//         {
//             str = '#';
//         }
//         else if ( g >= 180.0 )
//         {
//             str = '8';
//         }
//         else if ( g >= 160.0 )
//         {
//             str = '&';
//         }
//         else if ( g >= 130.0 )
//         {
//             str = 'o';
//         }
//         else if ( g >= 100.0 )
//         {
//             str = ':';
//         }
//         else if ( g >= 70.0 )
//         {
//             str = '*';
//         }
//         else if ( g >= 50.0 )
//         {
//             str = '.';
//         }
//         else
//         {
//             str = ' ';
//         }
//         return str;
//     }
// }
 | 
	import com.oldterns.vilebot.util.ASCII;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.types.GenericMessageEvent;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | 
	package com.oldterns.vilebot.handlers.user;
/**
 * Created by eunderhi on 17/08/15.
 */
public class ImageToAscii
    extends ListenerAdapter
{
    private static final Pattern questionPattern = Pattern.compile( "^!(convert)\\s(.+)$" );
    @Override
    public void onGenericMessage( final GenericMessageEvent event )
    {
        String text = event.getMessage();
        Matcher matcher = questionPattern.matcher( text );
        if ( matcher.matches() )
        {
            String URL = matcher.group( 2 );
            try
            {
                String image = convertImage( URL );
                event.respondWith( image );
            }
            catch ( Exception e )
            {
                event.respondWith( "Could not convert image." );
            }
        }
    }
    private String convertImage( String strURL )
        throws Exception
    {
        URL url = new URL( strURL );
        BufferedImage image = ImageIO.read( url );
        image = shrink( image ); | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/util/ASCII.java
// public final class ASCII
// {
//     private boolean negative;
// 
//     public ASCII()
//     {
//         this( false );
//     }
// 
//     public ASCII( final boolean negative )
//     {
//         this.negative = negative;
//     }
// 
//     public String convert( final BufferedImage image )
//     {
//         StringBuilder sb = new StringBuilder( ( image.getWidth() + 1 ) * image.getHeight() );
//         for ( int y = 0; y < image.getHeight(); y++ )
//         {
//             if ( sb.length() != 0 )
//                 sb.append( "\n" );
//             for ( int x = 0; x < image.getWidth(); x++ )
//             {
//                 Color pixelColor = new Color( image.getRGB( x, y ) );
//                 double gValue = (double) pixelColor.getRed() * 0.2989 + (double) pixelColor.getBlue() * 0.5870
//                     + (double) pixelColor.getGreen() * 0.1140;
//                 final char s = negative ? returnStrNeg( gValue ) : returnStrPos( gValue );
//                 sb.append( s );
//             }
//         }
//         return sb.toString();
//     }
// 
//     /**
//      * Create a new string and assign to it a string based on the grayscale value. If the grayscale value is very high,
//      * the pixel is very bright and assign characters such as . and , that do not appear very dark. If the grayscale
//      * value is very lowm the pixel is very dark, assign characters such as # and @ which appear very dark.
//      *
//      * @param g grayscale
//      * @return char
//      */
//     private char returnStrPos( double g )// takes the grayscale value as parameter
//     {
//         final char str;
// 
//         if ( g >= 230.0 )
//         {
//             str = ' ';
//         }
//         else if ( g >= 200.0 )
//         {
//             str = '.';
//         }
//         else if ( g >= 180.0 )
//         {
//             str = '*';
//         }
//         else if ( g >= 160.0 )
//         {
//             str = ':';
//         }
//         else if ( g >= 130.0 )
//         {
//             str = 'o';
//         }
//         else if ( g >= 100.0 )
//         {
//             str = '&';
//         }
//         else if ( g >= 70.0 )
//         {
//             str = '8';
//         }
//         else if ( g >= 50.0 )
//         {
//             str = '#';
//         }
//         else
//         {
//             str = '@';
//         }
//         return str; // return the character
//     }
// 
//     /**
//      * Same method as above, except it reverses the darkness of the pixel. A dark pixel is given a light character and
//      * vice versa.
//      *
//      * @param g grayscale
//      * @return char
//      */
//     private char returnStrNeg( double g )
//     {
//         final char str;
// 
//         if ( g >= 230.0 )
//         {
//             str = '@';
//         }
//         else if ( g >= 200.0 )
//         {
//             str = '#';
//         }
//         else if ( g >= 180.0 )
//         {
//             str = '8';
//         }
//         else if ( g >= 160.0 )
//         {
//             str = '&';
//         }
//         else if ( g >= 130.0 )
//         {
//             str = 'o';
//         }
//         else if ( g >= 100.0 )
//         {
//             str = ':';
//         }
//         else if ( g >= 70.0 )
//         {
//             str = '*';
//         }
//         else if ( g >= 50.0 )
//         {
//             str = '.';
//         }
//         else
//         {
//             str = ' ';
//         }
//         return str;
//     }
// }
// Path: vilebot/src/main/java/com/oldterns/vilebot/handlers/user/ImageToAscii.java
import com.oldterns.vilebot.util.ASCII;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.types.GenericMessageEvent;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
package com.oldterns.vilebot.handlers.user;
/**
 * Created by eunderhi on 17/08/15.
 */
public class ImageToAscii
    extends ListenerAdapter
{
    private static final Pattern questionPattern = Pattern.compile( "^!(convert)\\s(.+)$" );
    @Override
    public void onGenericMessage( final GenericMessageEvent event )
    {
        String text = event.getMessage();
        Matcher matcher = questionPattern.matcher( text );
        if ( matcher.matches() )
        {
            String URL = matcher.group( 2 );
            try
            {
                String image = convertImage( URL );
                event.respondWith( image );
            }
            catch ( Exception e )
            {
                event.respondWith( "Could not convert image." );
            }
        }
    }
    private String convertImage( String strURL )
        throws Exception
    {
        URL url = new URL( strURL );
        BufferedImage image = ImageIO.read( url );
        image = shrink( image ); | 
	        return new ASCII().convert( image ); | 
| 
	oldterns/VileBot | 
	vilebot/src/test/java/vilebot/handlers/user/DownOrJustMeTest.java | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/handlers/user/DownOrJustMe.java
// public class DownOrJustMe
//     extends ListenerAdapter
// {
//     private static final Pattern DOWN_OR_JUST_ME_PATTERN = Pattern.compile( "^!(downorjustme)\\s(.+)$" );
// 
//     private static final int PING_TIMEOUT = 3000;
// 
//     private static final int HTTP_TIMEOUT = 5000;
// 
//     private static final String[] DISALLOWED_SUBNETS = new String[] { "10.0.0.0/8" };
// 
//     // Some sites check for this and returns non-2xx status. Ridiculous!
//     private static final String HTTP_UA =
//         "Mozilla/5.0 (X11; Fedora; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36";
// 
//     @Override
//     public void onGenericMessage( final GenericMessageEvent event )
//     {
//         String text = event.getMessage();
//         Matcher matcher = DOWN_OR_JUST_ME_PATTERN.matcher( text );
// 
//         if ( matcher.matches() )
//         {
//             check( event, matcher );
//         }
//     }
// 
//     protected static void check( GenericMessageEvent event, Matcher matcher )
//     {
//         String hostnameOrUrl = matcher.group( 2 );
//         InetAddress destination;
//         try
//         {
//             destination = getHostNetAddress( hostnameOrUrl );
//         }
//         catch ( UnknownHostException e )
//         {
//             event.respondWith( "Nope, it's not just you. The hostname is not resolvable from here, too!" );
//             return;
//         }
// 
//         try
//         {
//             validateDestination( destination );
//         }
//         catch ( IllegalArgumentException e )
//         {
//             event.respondWith( e.getMessage() );
//             return;
//         }
// 
//         URL url;
//         try
//         {
//             url = new URL( hostnameOrUrl );
//         }
//         catch ( MalformedURLException e )
//         {
//             try
//             {
//                 url = new URL( "http", hostnameOrUrl, 80, "/" );
//             }
//             catch ( MalformedURLException ex )
//             {
//                 throw new RuntimeException( ex ); // This should not happen
//             }
//         }
// 
//         int status = httpGet( url );
//         if ( status >= 400 )
//         {
//             event.respondWith( "It responded with a non-2xx status code (" + status + "), but the host is up." );
//             return;
//         }
//         else if ( status != -1 )
//         {
//             event.respondWith( "LGTM! It's just you." );
//             return;
//         }
// 
//         if ( icmpPing( destination ) )
//         {
//             event.respondWith( "Not sure about web services, but the host is definitely up." );
//         }
//         else
//         {
//             event.respondWith( "Nope, it's not just you. The host looks down from here, too!" );
//         }
//     }
// 
//     private static InetAddress getHostNetAddress( String hostnameOrUrl )
//         throws UnknownHostException
//     {
//         try
//         {
//             return InetAddress.getByName( new URL( hostnameOrUrl ).getHost() );
//         }
//         catch ( MalformedURLException e )
//         {
//             // noop
//         }
// 
//         return InetAddress.getByName( hostnameOrUrl );
//     }
// 
//     private static void validateDestination( InetAddress destination )
//     {
//         if ( destination.isMulticastAddress() )
//         {
//             throw new IllegalArgumentException( "A multicast address? Seriously? Stop flooding the network already." );
//         }
// 
//         if ( destination.isLoopbackAddress() )
//         {
//             throw new IllegalArgumentException( "You wouldn't think I was that vulnerable, right?" );
//         }
// 
//         for ( String subnet : DISALLOWED_SUBNETS )
//         {
//             InetAddress id;
//             try
//             {
//                 id = InetAddress.getByName( subnet.split( "/" )[0] );
//             }
//             catch ( UnknownHostException e )
//             {
//                 throw new RuntimeException( "Check DISALLOWED_SUBNETS constant validity!" );
//             }
//             int maskLength = Integer.parseInt( subnet.split( "/" )[1] );
// 
//             byte[] idBytes = id.getAddress();
//             byte[] destinationBytes = destination.getAddress();
//             if ( idBytes.length != destinationBytes.length )
//             {
//                 continue; // Don't match between IPv4 and IPv6
//             }
// 
//             if ( new BigInteger( idBytes ).shiftRight( idBytes.length
//                 * 8 - maskLength ).equals(
//                                            new BigInteger( destinationBytes ).shiftRight( destinationBytes.length * 8
//                                                - maskLength ) ) )
//             {
//                 throw new IllegalArgumentException( "Ah-ha! Destinations in subnet " + subnet + " are not allowed." );
//             }
//         }
//     }
// 
//     private static boolean icmpPing( InetAddress destination )
//     {
//         try
//         {
//             return destination.isReachable( PING_TIMEOUT );
//         }
//         catch ( IOException e )
//         {
//             return false;
//         }
//     }
// 
//     private static int httpGet( URL url )
//     {
//         try
//         {
//             HttpURLConnection httpClient = (HttpURLConnection) url.openConnection();
//             httpClient.setConnectTimeout( HTTP_TIMEOUT );
//             httpClient.setReadTimeout( HTTP_TIMEOUT );
//             httpClient.setRequestMethod( "GET" );
//             httpClient.setRequestProperty( "User-Agent", HTTP_UA );
//             return httpClient.getResponseCode();
//         }
//         catch ( IOException e )
//         {
//             return -1;
//         }
//     }
// }
 | 
	import com.oldterns.vilebot.handlers.user.DownOrJustMe;
import org.junit.Before;
import org.junit.Test;
import org.pircbotx.hooks.events.MessageEvent;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when; | 
	package vilebot.handlers.user;
public class DownOrJustMeTest
{ | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/handlers/user/DownOrJustMe.java
// public class DownOrJustMe
//     extends ListenerAdapter
// {
//     private static final Pattern DOWN_OR_JUST_ME_PATTERN = Pattern.compile( "^!(downorjustme)\\s(.+)$" );
// 
//     private static final int PING_TIMEOUT = 3000;
// 
//     private static final int HTTP_TIMEOUT = 5000;
// 
//     private static final String[] DISALLOWED_SUBNETS = new String[] { "10.0.0.0/8" };
// 
//     // Some sites check for this and returns non-2xx status. Ridiculous!
//     private static final String HTTP_UA =
//         "Mozilla/5.0 (X11; Fedora; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36";
// 
//     @Override
//     public void onGenericMessage( final GenericMessageEvent event )
//     {
//         String text = event.getMessage();
//         Matcher matcher = DOWN_OR_JUST_ME_PATTERN.matcher( text );
// 
//         if ( matcher.matches() )
//         {
//             check( event, matcher );
//         }
//     }
// 
//     protected static void check( GenericMessageEvent event, Matcher matcher )
//     {
//         String hostnameOrUrl = matcher.group( 2 );
//         InetAddress destination;
//         try
//         {
//             destination = getHostNetAddress( hostnameOrUrl );
//         }
//         catch ( UnknownHostException e )
//         {
//             event.respondWith( "Nope, it's not just you. The hostname is not resolvable from here, too!" );
//             return;
//         }
// 
//         try
//         {
//             validateDestination( destination );
//         }
//         catch ( IllegalArgumentException e )
//         {
//             event.respondWith( e.getMessage() );
//             return;
//         }
// 
//         URL url;
//         try
//         {
//             url = new URL( hostnameOrUrl );
//         }
//         catch ( MalformedURLException e )
//         {
//             try
//             {
//                 url = new URL( "http", hostnameOrUrl, 80, "/" );
//             }
//             catch ( MalformedURLException ex )
//             {
//                 throw new RuntimeException( ex ); // This should not happen
//             }
//         }
// 
//         int status = httpGet( url );
//         if ( status >= 400 )
//         {
//             event.respondWith( "It responded with a non-2xx status code (" + status + "), but the host is up." );
//             return;
//         }
//         else if ( status != -1 )
//         {
//             event.respondWith( "LGTM! It's just you." );
//             return;
//         }
// 
//         if ( icmpPing( destination ) )
//         {
//             event.respondWith( "Not sure about web services, but the host is definitely up." );
//         }
//         else
//         {
//             event.respondWith( "Nope, it's not just you. The host looks down from here, too!" );
//         }
//     }
// 
//     private static InetAddress getHostNetAddress( String hostnameOrUrl )
//         throws UnknownHostException
//     {
//         try
//         {
//             return InetAddress.getByName( new URL( hostnameOrUrl ).getHost() );
//         }
//         catch ( MalformedURLException e )
//         {
//             // noop
//         }
// 
//         return InetAddress.getByName( hostnameOrUrl );
//     }
// 
//     private static void validateDestination( InetAddress destination )
//     {
//         if ( destination.isMulticastAddress() )
//         {
//             throw new IllegalArgumentException( "A multicast address? Seriously? Stop flooding the network already." );
//         }
// 
//         if ( destination.isLoopbackAddress() )
//         {
//             throw new IllegalArgumentException( "You wouldn't think I was that vulnerable, right?" );
//         }
// 
//         for ( String subnet : DISALLOWED_SUBNETS )
//         {
//             InetAddress id;
//             try
//             {
//                 id = InetAddress.getByName( subnet.split( "/" )[0] );
//             }
//             catch ( UnknownHostException e )
//             {
//                 throw new RuntimeException( "Check DISALLOWED_SUBNETS constant validity!" );
//             }
//             int maskLength = Integer.parseInt( subnet.split( "/" )[1] );
// 
//             byte[] idBytes = id.getAddress();
//             byte[] destinationBytes = destination.getAddress();
//             if ( idBytes.length != destinationBytes.length )
//             {
//                 continue; // Don't match between IPv4 and IPv6
//             }
// 
//             if ( new BigInteger( idBytes ).shiftRight( idBytes.length
//                 * 8 - maskLength ).equals(
//                                            new BigInteger( destinationBytes ).shiftRight( destinationBytes.length * 8
//                                                - maskLength ) ) )
//             {
//                 throw new IllegalArgumentException( "Ah-ha! Destinations in subnet " + subnet + " are not allowed." );
//             }
//         }
//     }
// 
//     private static boolean icmpPing( InetAddress destination )
//     {
//         try
//         {
//             return destination.isReachable( PING_TIMEOUT );
//         }
//         catch ( IOException e )
//         {
//             return false;
//         }
//     }
// 
//     private static int httpGet( URL url )
//     {
//         try
//         {
//             HttpURLConnection httpClient = (HttpURLConnection) url.openConnection();
//             httpClient.setConnectTimeout( HTTP_TIMEOUT );
//             httpClient.setReadTimeout( HTTP_TIMEOUT );
//             httpClient.setRequestMethod( "GET" );
//             httpClient.setRequestProperty( "User-Agent", HTTP_UA );
//             return httpClient.getResponseCode();
//         }
//         catch ( IOException e )
//         {
//             return -1;
//         }
//     }
// }
// Path: vilebot/src/test/java/vilebot/handlers/user/DownOrJustMeTest.java
import com.oldterns.vilebot.handlers.user.DownOrJustMe;
import org.junit.Before;
import org.junit.Test;
import org.pircbotx.hooks.events.MessageEvent;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
package vilebot.handlers.user;
public class DownOrJustMeTest
{ | 
	    private DownOrJustMe instance; | 
| 
	oldterns/VileBot | 
	vilebot/src/main/java/com/oldterns/vilebot/handlers/user/LastSeen.java | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/util/BaseNick.java
// public class BaseNick
// {
//     // This would grab the leading x out of a nick that actually contains it
//     private static Pattern nickPattern = Pattern.compile( "(?:x|)([a-zA-Z0-9]+)(?:\\p{Punct}+[a-zA-Z0-9]*|)" );
// 
//     private static String primaryBotNick;
// 
//     private static Set<String> allBotNicks = new HashSet<>();
// 
//     public static String toBaseNick( String nick )
//     {
//         if ( allBotNicks.contains( nick ) )
//         {
//             nick = primaryBotNick;
//         }
//         else
//         {
//             Matcher nickMatcher = nickPattern.matcher( nick );
// 
//             if ( nickMatcher.find() )
//             {
//                 return nickMatcher.group( 1 );
//             }
//         }
//         return nick;
//     }
// 
//     public static String getPrimaryBotNick()
//     {
//         return primaryBotNick;
//     }
// 
//     public static void setPrimaryBotNick( String primaryNick )
//     {
//         primaryBotNick = primaryNick;
//     }
// 
//     public static Set<String> getBotNicks()
//     {
//         return allBotNicks;
//     }
// 
//     public static void addBotNick( String nick )
//     {
//         allBotNicks.add( nick );
//     }
// }
// 
// Path: vilebot/src/main/java/com/oldterns/vilebot/util/Ignore.java
// public class Ignore
// {
//     private static Set<String> onJoin = new ConcurrentSkipListSet<String>();
// 
//     private static Set<String> autoOp = new ConcurrentSkipListSet<String>();
// 
//     public static Set<String> getOnJoin()
//     {
//         return onJoin;
//     }
// 
//     public static Set<String> getAutoOp()
//     {
//         return autoOp;
//     }
// 
//     public static void addOnJoin( String nick )
//     {
//         onJoin.add( nick );
//     }
// 
//     public static void addAutoOp( String channel )
//     {
//         autoOp.add( channel );
//     }
// }
 | 
	import com.oldterns.vilebot.db.LastSeenDB;
import com.oldterns.vilebot.util.BaseNick;
import com.oldterns.vilebot.util.Ignore;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.events.JoinEvent;
import org.pircbotx.hooks.types.GenericMessageEvent;
import org.pircbotx.output.OutputIRC;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit; | 
	package com.oldterns.vilebot.handlers.user;
public class LastSeen
    extends ListenerAdapter
{
    private static TimeZone timeZone = TimeZone.getTimeZone( "America/Toronto" );
    private static DateFormat dateFormat = makeDateFormat();
    @Override
    public void onGenericMessage( final GenericMessageEvent event )
    { | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/util/BaseNick.java
// public class BaseNick
// {
//     // This would grab the leading x out of a nick that actually contains it
//     private static Pattern nickPattern = Pattern.compile( "(?:x|)([a-zA-Z0-9]+)(?:\\p{Punct}+[a-zA-Z0-9]*|)" );
// 
//     private static String primaryBotNick;
// 
//     private static Set<String> allBotNicks = new HashSet<>();
// 
//     public static String toBaseNick( String nick )
//     {
//         if ( allBotNicks.contains( nick ) )
//         {
//             nick = primaryBotNick;
//         }
//         else
//         {
//             Matcher nickMatcher = nickPattern.matcher( nick );
// 
//             if ( nickMatcher.find() )
//             {
//                 return nickMatcher.group( 1 );
//             }
//         }
//         return nick;
//     }
// 
//     public static String getPrimaryBotNick()
//     {
//         return primaryBotNick;
//     }
// 
//     public static void setPrimaryBotNick( String primaryNick )
//     {
//         primaryBotNick = primaryNick;
//     }
// 
//     public static Set<String> getBotNicks()
//     {
//         return allBotNicks;
//     }
// 
//     public static void addBotNick( String nick )
//     {
//         allBotNicks.add( nick );
//     }
// }
// 
// Path: vilebot/src/main/java/com/oldterns/vilebot/util/Ignore.java
// public class Ignore
// {
//     private static Set<String> onJoin = new ConcurrentSkipListSet<String>();
// 
//     private static Set<String> autoOp = new ConcurrentSkipListSet<String>();
// 
//     public static Set<String> getOnJoin()
//     {
//         return onJoin;
//     }
// 
//     public static Set<String> getAutoOp()
//     {
//         return autoOp;
//     }
// 
//     public static void addOnJoin( String nick )
//     {
//         onJoin.add( nick );
//     }
// 
//     public static void addAutoOp( String channel )
//     {
//         autoOp.add( channel );
//     }
// }
// Path: vilebot/src/main/java/com/oldterns/vilebot/handlers/user/LastSeen.java
import com.oldterns.vilebot.db.LastSeenDB;
import com.oldterns.vilebot.util.BaseNick;
import com.oldterns.vilebot.util.Ignore;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.events.JoinEvent;
import org.pircbotx.hooks.types.GenericMessageEvent;
import org.pircbotx.output.OutputIRC;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
package com.oldterns.vilebot.handlers.user;
public class LastSeen
    extends ListenerAdapter
{
    private static TimeZone timeZone = TimeZone.getTimeZone( "America/Toronto" );
    private static DateFormat dateFormat = makeDateFormat();
    @Override
    public void onGenericMessage( final GenericMessageEvent event )
    { | 
	        String userNick = BaseNick.toBaseNick( event.getUser().getNick() ); | 
| 
	oldterns/VileBot | 
	vilebot/src/main/java/com/oldterns/vilebot/handlers/user/LastSeen.java | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/util/BaseNick.java
// public class BaseNick
// {
//     // This would grab the leading x out of a nick that actually contains it
//     private static Pattern nickPattern = Pattern.compile( "(?:x|)([a-zA-Z0-9]+)(?:\\p{Punct}+[a-zA-Z0-9]*|)" );
// 
//     private static String primaryBotNick;
// 
//     private static Set<String> allBotNicks = new HashSet<>();
// 
//     public static String toBaseNick( String nick )
//     {
//         if ( allBotNicks.contains( nick ) )
//         {
//             nick = primaryBotNick;
//         }
//         else
//         {
//             Matcher nickMatcher = nickPattern.matcher( nick );
// 
//             if ( nickMatcher.find() )
//             {
//                 return nickMatcher.group( 1 );
//             }
//         }
//         return nick;
//     }
// 
//     public static String getPrimaryBotNick()
//     {
//         return primaryBotNick;
//     }
// 
//     public static void setPrimaryBotNick( String primaryNick )
//     {
//         primaryBotNick = primaryNick;
//     }
// 
//     public static Set<String> getBotNicks()
//     {
//         return allBotNicks;
//     }
// 
//     public static void addBotNick( String nick )
//     {
//         allBotNicks.add( nick );
//     }
// }
// 
// Path: vilebot/src/main/java/com/oldterns/vilebot/util/Ignore.java
// public class Ignore
// {
//     private static Set<String> onJoin = new ConcurrentSkipListSet<String>();
// 
//     private static Set<String> autoOp = new ConcurrentSkipListSet<String>();
// 
//     public static Set<String> getOnJoin()
//     {
//         return onJoin;
//     }
// 
//     public static Set<String> getAutoOp()
//     {
//         return autoOp;
//     }
// 
//     public static void addOnJoin( String nick )
//     {
//         onJoin.add( nick );
//     }
// 
//     public static void addAutoOp( String channel )
//     {
//         autoOp.add( channel );
//     }
// }
 | 
	import com.oldterns.vilebot.db.LastSeenDB;
import com.oldterns.vilebot.util.BaseNick;
import com.oldterns.vilebot.util.Ignore;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.events.JoinEvent;
import org.pircbotx.hooks.types.GenericMessageEvent;
import org.pircbotx.output.OutputIRC;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit; | 
	package com.oldterns.vilebot.handlers.user;
public class LastSeen
    extends ListenerAdapter
{
    private static TimeZone timeZone = TimeZone.getTimeZone( "America/Toronto" );
    private static DateFormat dateFormat = makeDateFormat();
    @Override
    public void onGenericMessage( final GenericMessageEvent event )
    {
        String userNick = BaseNick.toBaseNick( event.getUser().getNick() );
        String botNick = event.getBot().getNick();
        if ( !botNick.equals( userNick ) )
        {
            LastSeenDB.updateLastSeenTime( userNick );
        }
 | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/util/BaseNick.java
// public class BaseNick
// {
//     // This would grab the leading x out of a nick that actually contains it
//     private static Pattern nickPattern = Pattern.compile( "(?:x|)([a-zA-Z0-9]+)(?:\\p{Punct}+[a-zA-Z0-9]*|)" );
// 
//     private static String primaryBotNick;
// 
//     private static Set<String> allBotNicks = new HashSet<>();
// 
//     public static String toBaseNick( String nick )
//     {
//         if ( allBotNicks.contains( nick ) )
//         {
//             nick = primaryBotNick;
//         }
//         else
//         {
//             Matcher nickMatcher = nickPattern.matcher( nick );
// 
//             if ( nickMatcher.find() )
//             {
//                 return nickMatcher.group( 1 );
//             }
//         }
//         return nick;
//     }
// 
//     public static String getPrimaryBotNick()
//     {
//         return primaryBotNick;
//     }
// 
//     public static void setPrimaryBotNick( String primaryNick )
//     {
//         primaryBotNick = primaryNick;
//     }
// 
//     public static Set<String> getBotNicks()
//     {
//         return allBotNicks;
//     }
// 
//     public static void addBotNick( String nick )
//     {
//         allBotNicks.add( nick );
//     }
// }
// 
// Path: vilebot/src/main/java/com/oldterns/vilebot/util/Ignore.java
// public class Ignore
// {
//     private static Set<String> onJoin = new ConcurrentSkipListSet<String>();
// 
//     private static Set<String> autoOp = new ConcurrentSkipListSet<String>();
// 
//     public static Set<String> getOnJoin()
//     {
//         return onJoin;
//     }
// 
//     public static Set<String> getAutoOp()
//     {
//         return autoOp;
//     }
// 
//     public static void addOnJoin( String nick )
//     {
//         onJoin.add( nick );
//     }
// 
//     public static void addAutoOp( String channel )
//     {
//         autoOp.add( channel );
//     }
// }
// Path: vilebot/src/main/java/com/oldterns/vilebot/handlers/user/LastSeen.java
import com.oldterns.vilebot.db.LastSeenDB;
import com.oldterns.vilebot.util.BaseNick;
import com.oldterns.vilebot.util.Ignore;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.events.JoinEvent;
import org.pircbotx.hooks.types.GenericMessageEvent;
import org.pircbotx.output.OutputIRC;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
package com.oldterns.vilebot.handlers.user;
public class LastSeen
    extends ListenerAdapter
{
    private static TimeZone timeZone = TimeZone.getTimeZone( "America/Toronto" );
    private static DateFormat dateFormat = makeDateFormat();
    @Override
    public void onGenericMessage( final GenericMessageEvent event )
    {
        String userNick = BaseNick.toBaseNick( event.getUser().getNick() );
        String botNick = event.getBot().getNick();
        if ( !botNick.equals( userNick ) )
        {
            LastSeenDB.updateLastSeenTime( userNick );
        }
 | 
	        if ( event instanceof JoinEvent && !botNick.equals( userNick ) && !Ignore.getOnJoin().contains( userNick ) ) | 
| 
	oldterns/VileBot | 
	vilebot/src/test/java/vilebot/handlers/user/RemindMeTest.java | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/handlers/user/RemindMe.java
// public class RemindMe
//     extends ListenerAdapter
// {
// 
//     private static final String timeFormat = "(\\d+\\w*)";
// 
//     private static final Pattern remindMePattern = Pattern.compile( "^!remindme (.+) " + timeFormat );
// 
//     private final String INVALID_TYPE_ERROR =
//         "The time type given is not valid (use d for day, m for month, s for second)";
// 
//     private final String NO_TYPE_ERROR = "There was no type given for the time (use d/m/s)";
// 
//     private final String TIME_TOO_LARGE_ERROR = "The value of time given is greater than the maximum Integer value";
// 
//     private final String TOO_MANY_REMINDERS_ERROR =
//         "There is a limit of 10 reminders, please wait until one reminder ends to set a new one.";
// 
//     private final String TIME_IS_OKAY = "Given time input is okay";
// 
//     private String timeError = TIME_IS_OKAY;
// 
//     private static Map<String, Integer> userReminders = new HashMap<>();
// 
//     private final int MAX_REMINDERS = 10;
// 
//     // @Handler
//     @Override
//     public void onGenericMessage( GenericMessageEvent event )
//     {
//         String text = event.getMessage();
//         Matcher matcher = remindMePattern.matcher( text );
// 
//         if ( matcher.matches() )
//         {
//             String message = matcher.group( 1 );
//             String time = matcher.group( 2 );
//             String creator = BaseNick.toBaseNick( event.getUser().getNick() );
//             if ( !userReminders.containsKey( creator ) )
//             {
//                 userReminders.put( creator, 0 );
//             }
//             Calendar timerTime = getTimerTime( time, creator );
//             if ( timerTime == null )
//             {
//                 event.respondPrivateMessage( String.format( "The given time of %s is invalid. The cause is %s.", time,
//                                                             timeError ) );
//             }
//             else
//             {
//                 Timer timer = new Timer();
//                 timer.schedule( createTimerTask( event, message, creator ), timerTime.getTime() );
//                 event.respondPrivateMessage( "Created reminder for " + timerTime.getTime() );
//                 int amountOfReminders = userReminders.get( creator );
//                 amountOfReminders++;
//                 userReminders.put( creator, amountOfReminders );
//             }
//         }
//     }
// 
//     private TimerTask createTimerTask( final GenericMessageEvent event, final String message, final String creator )
//     {
//         return new TimerTask()
//         {
//             @Override
//             public void run()
//             {
//                 event.respondPrivateMessage( "This is your reminder that you should: " + message );
//                 int amountOfReminders = userReminders.get( creator );
//                 amountOfReminders--;
//                 userReminders.put( creator, amountOfReminders );
//             }
//         };
//     }
// 
//     private Calendar getTimerTime( final String time, final String creator )
//     {
//         Calendar calendar = Calendar.getInstance();
//         verifyTime( time, creator );
//         if ( !timeError.equals( TIME_IS_OKAY ) )
//         {
//             return null;
//         }
//         int timeValue = Integer.parseInt( time.substring( 0, time.length() - 1 ) );
//         switch ( time.substring( time.length() - 1 ) )
//         {
//             case "d":
//                 calendar.add( Calendar.DAY_OF_MONTH, timeValue );
//             case "m":
//                 calendar.add( Calendar.MINUTE, timeValue );
//             case "s":
//                 calendar.add( Calendar.SECOND, timeValue );
//         }
//         return calendar;
//     }
// 
//     private void verifyTime( final String time, final String creator )
//     {
//         String type = time.substring( time.length() - 1 );
//         if ( !type.equals( "d" ) && !type.equals( "m" ) && !type.equals( "s" ) )
//         {
//             if ( isNumeric( time ) )
//             {
//                 timeError = NO_TYPE_ERROR;
//             }
//             else
//             {
//                 timeError = INVALID_TYPE_ERROR;
//             }
//             return;
//         }
//         try
//         {
//             String givenTime = time.substring( 0, time.length() - 1 );
//             Integer.valueOf( givenTime );
//         }
//         catch ( Exception e )
//         {
//             timeError = TIME_TOO_LARGE_ERROR;
//             return;
//         }
//         if ( userReminders.get( creator ) == MAX_REMINDERS )
//         {
//             timeError = TOO_MANY_REMINDERS_ERROR;
//             return;
//         }
//         timeError = TIME_IS_OKAY;
//     }
// 
//     private boolean isNumeric( final String time )
//     {
//         try
//         {
//             Integer.valueOf( time );
//         }
//         catch ( Exception e )
//         {
//             return false;
//         }
//         return true;
//     }
// }
 | 
	import com.oldterns.vilebot.handlers.user.RemindMe;
import org.junit.Before;
import org.junit.Test;
import org.pircbotx.User;
import org.pircbotx.hooks.events.MessageEvent;
import java.util.Calendar;
import java.util.concurrent.TimeUnit;
import static org.mockito.Mockito.*; | 
	    @Test
    public void reminderTimeTooLargeMultipleWords()
    {
        final String time = "1000000000000s";
        final String createMessage = "!remindme test test " + time;
        final String failMessage =
            String.format( "The given time of %s is invalid. The cause is %s.", time, TIME_TOO_LARGE_ERROR );
        createRemindMeWithTime( createMessage, 1, failMessage );
    }
    @Test
    public void tooManyReminders()
        throws Exception
    {
        final String time = "1s";
        final String createMessage = "!remindme test test " + time;
        final String failMessage =
            String.format( "The given time of %s is invalid. The cause is %s.", time, TOO_MANY_REMINDERS_ERROR );
        createRemindMeWithTime( createMessage, 10, getTimerTime( time ) );
        createRemindMeWithTime( createMessage, 1, failMessage );
        TimeUnit.SECONDS.sleep( 10 );
    }
    private void createRemindMeWithTime( final String createMessage, final Integer invocations, final Calendar time )
    {
        for ( int i = 0; i < invocations; i++ )
        {
            when( event.getMessage() ).thenReturn( createMessage );
 | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/handlers/user/RemindMe.java
// public class RemindMe
//     extends ListenerAdapter
// {
// 
//     private static final String timeFormat = "(\\d+\\w*)";
// 
//     private static final Pattern remindMePattern = Pattern.compile( "^!remindme (.+) " + timeFormat );
// 
//     private final String INVALID_TYPE_ERROR =
//         "The time type given is not valid (use d for day, m for month, s for second)";
// 
//     private final String NO_TYPE_ERROR = "There was no type given for the time (use d/m/s)";
// 
//     private final String TIME_TOO_LARGE_ERROR = "The value of time given is greater than the maximum Integer value";
// 
//     private final String TOO_MANY_REMINDERS_ERROR =
//         "There is a limit of 10 reminders, please wait until one reminder ends to set a new one.";
// 
//     private final String TIME_IS_OKAY = "Given time input is okay";
// 
//     private String timeError = TIME_IS_OKAY;
// 
//     private static Map<String, Integer> userReminders = new HashMap<>();
// 
//     private final int MAX_REMINDERS = 10;
// 
//     // @Handler
//     @Override
//     public void onGenericMessage( GenericMessageEvent event )
//     {
//         String text = event.getMessage();
//         Matcher matcher = remindMePattern.matcher( text );
// 
//         if ( matcher.matches() )
//         {
//             String message = matcher.group( 1 );
//             String time = matcher.group( 2 );
//             String creator = BaseNick.toBaseNick( event.getUser().getNick() );
//             if ( !userReminders.containsKey( creator ) )
//             {
//                 userReminders.put( creator, 0 );
//             }
//             Calendar timerTime = getTimerTime( time, creator );
//             if ( timerTime == null )
//             {
//                 event.respondPrivateMessage( String.format( "The given time of %s is invalid. The cause is %s.", time,
//                                                             timeError ) );
//             }
//             else
//             {
//                 Timer timer = new Timer();
//                 timer.schedule( createTimerTask( event, message, creator ), timerTime.getTime() );
//                 event.respondPrivateMessage( "Created reminder for " + timerTime.getTime() );
//                 int amountOfReminders = userReminders.get( creator );
//                 amountOfReminders++;
//                 userReminders.put( creator, amountOfReminders );
//             }
//         }
//     }
// 
//     private TimerTask createTimerTask( final GenericMessageEvent event, final String message, final String creator )
//     {
//         return new TimerTask()
//         {
//             @Override
//             public void run()
//             {
//                 event.respondPrivateMessage( "This is your reminder that you should: " + message );
//                 int amountOfReminders = userReminders.get( creator );
//                 amountOfReminders--;
//                 userReminders.put( creator, amountOfReminders );
//             }
//         };
//     }
// 
//     private Calendar getTimerTime( final String time, final String creator )
//     {
//         Calendar calendar = Calendar.getInstance();
//         verifyTime( time, creator );
//         if ( !timeError.equals( TIME_IS_OKAY ) )
//         {
//             return null;
//         }
//         int timeValue = Integer.parseInt( time.substring( 0, time.length() - 1 ) );
//         switch ( time.substring( time.length() - 1 ) )
//         {
//             case "d":
//                 calendar.add( Calendar.DAY_OF_MONTH, timeValue );
//             case "m":
//                 calendar.add( Calendar.MINUTE, timeValue );
//             case "s":
//                 calendar.add( Calendar.SECOND, timeValue );
//         }
//         return calendar;
//     }
// 
//     private void verifyTime( final String time, final String creator )
//     {
//         String type = time.substring( time.length() - 1 );
//         if ( !type.equals( "d" ) && !type.equals( "m" ) && !type.equals( "s" ) )
//         {
//             if ( isNumeric( time ) )
//             {
//                 timeError = NO_TYPE_ERROR;
//             }
//             else
//             {
//                 timeError = INVALID_TYPE_ERROR;
//             }
//             return;
//         }
//         try
//         {
//             String givenTime = time.substring( 0, time.length() - 1 );
//             Integer.valueOf( givenTime );
//         }
//         catch ( Exception e )
//         {
//             timeError = TIME_TOO_LARGE_ERROR;
//             return;
//         }
//         if ( userReminders.get( creator ) == MAX_REMINDERS )
//         {
//             timeError = TOO_MANY_REMINDERS_ERROR;
//             return;
//         }
//         timeError = TIME_IS_OKAY;
//     }
// 
//     private boolean isNumeric( final String time )
//     {
//         try
//         {
//             Integer.valueOf( time );
//         }
//         catch ( Exception e )
//         {
//             return false;
//         }
//         return true;
//     }
// }
// Path: vilebot/src/test/java/vilebot/handlers/user/RemindMeTest.java
import com.oldterns.vilebot.handlers.user.RemindMe;
import org.junit.Before;
import org.junit.Test;
import org.pircbotx.User;
import org.pircbotx.hooks.events.MessageEvent;
import java.util.Calendar;
import java.util.concurrent.TimeUnit;
import static org.mockito.Mockito.*;
    @Test
    public void reminderTimeTooLargeMultipleWords()
    {
        final String time = "1000000000000s";
        final String createMessage = "!remindme test test " + time;
        final String failMessage =
            String.format( "The given time of %s is invalid. The cause is %s.", time, TIME_TOO_LARGE_ERROR );
        createRemindMeWithTime( createMessage, 1, failMessage );
    }
    @Test
    public void tooManyReminders()
        throws Exception
    {
        final String time = "1s";
        final String createMessage = "!remindme test test " + time;
        final String failMessage =
            String.format( "The given time of %s is invalid. The cause is %s.", time, TOO_MANY_REMINDERS_ERROR );
        createRemindMeWithTime( createMessage, 10, getTimerTime( time ) );
        createRemindMeWithTime( createMessage, 1, failMessage );
        TimeUnit.SECONDS.sleep( 10 );
    }
    private void createRemindMeWithTime( final String createMessage, final Integer invocations, final Calendar time )
    {
        for ( int i = 0; i < invocations; i++ )
        {
            when( event.getMessage() ).thenReturn( createMessage );
 | 
	            RemindMe remindMe = new RemindMe(); | 
| 
	oldterns/VileBot | 
	vilebot/src/main/java/com/oldterns/vilebot/handlers/user/ChatLogger.java | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/db/LogDB.java
// public class LogDB
//     extends RedisDB
// {
// 
//     public static String logKey = "chat-log";
// 
//     private static final int MAX_LOG_SIZE = 100000;
// 
//     public static void addItem( String chatMessage )
//     {
//         Jedis jedis = pool.getResource();
//         try
//         {
//             if ( jedis.strlen( logKey ) > MAX_LOG_SIZE )
//             {
//                 jedis.set( logKey, StringUtils.right( jedis.get( logKey ), MAX_LOG_SIZE - chatMessage.length() ) );
//             }
//             jedis.append( logKey, chatMessage );
//         }
//         finally
//         {
//             pool.returnResource( jedis );
//         }
//     }
// 
//     public static String getLog()
//     {
//         Jedis jedis = pool.getResource();
//         try
//         {
//             return jedis.get( logKey );
//         }
//         finally
//         {
//             pool.returnResource( jedis );
//         }
//     }
// 
//     public static void deleteLog()
//     {
//         Jedis jedis = pool.getResource();
//         try
//         {
//             jedis.del( logKey );
//         }
//         finally
//         {
//             pool.returnResource( jedis );
//         }
//     }
// }
 | 
	import com.oldterns.vilebot.Vilebot;
import com.oldterns.vilebot.db.LogDB;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.events.MessageEvent; | 
	package com.oldterns.vilebot.handlers.user;
/**
 * Created by eunderhi on 18/08/15.
 */
public class ChatLogger
    extends ListenerAdapter
{
    @Override
    public void onMessage( final MessageEvent event )
    {
        String logChannel = Vilebot.getConfig().get( "markovChannel" );
        String channel = event.getChannel().getName();
        String text = event.getMessage();
        boolean shouldLog = channel.equals( logChannel ) && !text.startsWith( "!" );
        if ( shouldLog )
        { | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/db/LogDB.java
// public class LogDB
//     extends RedisDB
// {
// 
//     public static String logKey = "chat-log";
// 
//     private static final int MAX_LOG_SIZE = 100000;
// 
//     public static void addItem( String chatMessage )
//     {
//         Jedis jedis = pool.getResource();
//         try
//         {
//             if ( jedis.strlen( logKey ) > MAX_LOG_SIZE )
//             {
//                 jedis.set( logKey, StringUtils.right( jedis.get( logKey ), MAX_LOG_SIZE - chatMessage.length() ) );
//             }
//             jedis.append( logKey, chatMessage );
//         }
//         finally
//         {
//             pool.returnResource( jedis );
//         }
//     }
// 
//     public static String getLog()
//     {
//         Jedis jedis = pool.getResource();
//         try
//         {
//             return jedis.get( logKey );
//         }
//         finally
//         {
//             pool.returnResource( jedis );
//         }
//     }
// 
//     public static void deleteLog()
//     {
//         Jedis jedis = pool.getResource();
//         try
//         {
//             jedis.del( logKey );
//         }
//         finally
//         {
//             pool.returnResource( jedis );
//         }
//     }
// }
// Path: vilebot/src/main/java/com/oldterns/vilebot/handlers/user/ChatLogger.java
import com.oldterns.vilebot.Vilebot;
import com.oldterns.vilebot.db.LogDB;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.events.MessageEvent;
package com.oldterns.vilebot.handlers.user;
/**
 * Created by eunderhi on 18/08/15.
 */
public class ChatLogger
    extends ListenerAdapter
{
    @Override
    public void onMessage( final MessageEvent event )
    {
        String logChannel = Vilebot.getConfig().get( "markovChannel" );
        String channel = event.getChannel().getName();
        String text = event.getMessage();
        boolean shouldLog = channel.equals( logChannel ) && !text.startsWith( "!" );
        if ( shouldLog )
        { | 
	            LogDB.addItem( text + "\n" ); | 
| 
	oldterns/VileBot | 
	vilebot/src/main/java/com/oldterns/vilebot/handlers/user/Excuses.java | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/db/ExcuseDB.java
// public class ExcuseDB
//     extends RedisDB
// {
//     private static final String keyOfExcuseSet = "excuses";
// 
//     public static void addExcuse( String excuse )
//     {
//         Jedis jedis = pool.getResource();
//         try
//         {
//             jedis.sadd( keyOfExcuseSet, excuse );
//         }
//         finally
//         {
//             pool.returnResource( jedis );
//         }
//     }
// 
//     public static String getRandExcuse()
//     {
//         Jedis jedis = pool.getResource();
//         try
//         {
//             return jedis.srandmember( keyOfExcuseSet );
//         }
//         finally
//         {
//             pool.returnResource( jedis );
//         }
//     }
// }
 | 
	import com.oldterns.vilebot.db.ExcuseDB;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.types.GenericMessageEvent;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | 
	package com.oldterns.vilebot.handlers.user;
public class Excuses
    extends ListenerAdapter
{
    private static final Pattern excusePattern = Pattern.compile( "!excuse" );
    @Override
    public void onGenericMessage( GenericMessageEvent event )
    {
        String text = event.getMessage();
        Matcher matcher = excusePattern.matcher( text );
        if ( matcher.matches() )
        { | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/db/ExcuseDB.java
// public class ExcuseDB
//     extends RedisDB
// {
//     private static final String keyOfExcuseSet = "excuses";
// 
//     public static void addExcuse( String excuse )
//     {
//         Jedis jedis = pool.getResource();
//         try
//         {
//             jedis.sadd( keyOfExcuseSet, excuse );
//         }
//         finally
//         {
//             pool.returnResource( jedis );
//         }
//     }
// 
//     public static String getRandExcuse()
//     {
//         Jedis jedis = pool.getResource();
//         try
//         {
//             return jedis.srandmember( keyOfExcuseSet );
//         }
//         finally
//         {
//             pool.returnResource( jedis );
//         }
//     }
// }
// Path: vilebot/src/main/java/com/oldterns/vilebot/handlers/user/Excuses.java
import com.oldterns.vilebot.db.ExcuseDB;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.types.GenericMessageEvent;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
package com.oldterns.vilebot.handlers.user;
public class Excuses
    extends ListenerAdapter
{
    private static final Pattern excusePattern = Pattern.compile( "!excuse" );
    @Override
    public void onGenericMessage( GenericMessageEvent event )
    {
        String text = event.getMessage();
        Matcher matcher = excusePattern.matcher( text );
        if ( matcher.matches() )
        { | 
	            String excuse = ExcuseDB.getRandExcuse(); | 
| 
	oldterns/VileBot | 
	vilebot/src/test/java/vilebot/util/StringUtilTest.java | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/util/StringUtil.java
// public class StringUtil
// {
// 
//     private StringUtil()
//     {
//     }
// 
//     /**
//      * Capitalizes the first letter of the message and returns the result. If the argument is null, then null is
//      * returned. If the first letter is capitalized this will return an identical string. If the string is empty then it
//      * will return the same empty string back.
//      * 
//      * @param message The message to convert.
//      * @return The converted message, or null if the argument is null.
//      */
//     public static final String capitalizeFirstLetter( String message )
//     {
//         if ( message == null || message.length() == 0 )
//         {
//             return message;
//         }
// 
//         char firstUpperCaseLetter = Character.toUpperCase( message.charAt( 0 ) );
//         String remainderOfMessage = message.substring( 1 );
//         return firstUpperCaseLetter + remainderOfMessage;
//     }
// }
 | 
	import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.oldterns.vilebot.util.StringUtil; | 
	package vilebot.util;
public class StringUtilTest
{
    @Test
    public void nullArgReturnsNull()
    { | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/util/StringUtil.java
// public class StringUtil
// {
// 
//     private StringUtil()
//     {
//     }
// 
//     /**
//      * Capitalizes the first letter of the message and returns the result. If the argument is null, then null is
//      * returned. If the first letter is capitalized this will return an identical string. If the string is empty then it
//      * will return the same empty string back.
//      * 
//      * @param message The message to convert.
//      * @return The converted message, or null if the argument is null.
//      */
//     public static final String capitalizeFirstLetter( String message )
//     {
//         if ( message == null || message.length() == 0 )
//         {
//             return message;
//         }
// 
//         char firstUpperCaseLetter = Character.toUpperCase( message.charAt( 0 ) );
//         String remainderOfMessage = message.substring( 1 );
//         return firstUpperCaseLetter + remainderOfMessage;
//     }
// }
// Path: vilebot/src/test/java/vilebot/util/StringUtilTest.java
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.oldterns.vilebot.util.StringUtil;
package vilebot.util;
public class StringUtilTest
{
    @Test
    public void nullArgReturnsNull()
    { | 
	        assertEquals( null, StringUtil.capitalizeFirstLetter( null ) ); | 
| 
	oldterns/VileBot | 
	vilebot/src/test/java/vilebot/handlers/user/TwitterCorrectionTest.java | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/handlers/user/TwitterCorrection.java
// public class TwitterCorrection
//     extends ListenerAdapter
// {
//     private static final Pattern twitterSyntaxUsePattern = Pattern.compile( "(?:^|\\s+)[@](\\S+)(?:\\s|:|)" );
// 
//     @Override
//     public void onGenericMessage( final GenericMessageEvent event )
//     {
//         String text = event.getMessage();
//         Matcher matcher = twitterSyntaxUsePattern.matcher( text );
// 
//         if ( matcher.find() )
//         {
//             String word = matcher.group( 1 );
// 
//             String sb = "You seem to be using twitter addressing syntax. On IRC you would say this instead: "
//                 + word.replaceAll( "[^A-Za-z0-9]$", "" ) + ": message";
//             event.respond( sb );
//         }
//     }
// }
 | 
	import com.oldterns.vilebot.handlers.user.TwitterCorrection;
import org.junit.Before;
import org.junit.Test;
import org.pircbotx.hooks.events.MessageEvent;
import static org.mockito.Mockito.*; | 
	package vilebot.handlers.user;
public class TwitterCorrectionTest
{
    private String correctResponse =
        "You seem to be using twitter addressing syntax. On IRC you would say this instead: ipun: message";
 | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/handlers/user/TwitterCorrection.java
// public class TwitterCorrection
//     extends ListenerAdapter
// {
//     private static final Pattern twitterSyntaxUsePattern = Pattern.compile( "(?:^|\\s+)[@](\\S+)(?:\\s|:|)" );
// 
//     @Override
//     public void onGenericMessage( final GenericMessageEvent event )
//     {
//         String text = event.getMessage();
//         Matcher matcher = twitterSyntaxUsePattern.matcher( text );
// 
//         if ( matcher.find() )
//         {
//             String word = matcher.group( 1 );
// 
//             String sb = "You seem to be using twitter addressing syntax. On IRC you would say this instead: "
//                 + word.replaceAll( "[^A-Za-z0-9]$", "" ) + ": message";
//             event.respond( sb );
//         }
//     }
// }
// Path: vilebot/src/test/java/vilebot/handlers/user/TwitterCorrectionTest.java
import com.oldterns.vilebot.handlers.user.TwitterCorrection;
import org.junit.Before;
import org.junit.Test;
import org.pircbotx.hooks.events.MessageEvent;
import static org.mockito.Mockito.*;
package vilebot.handlers.user;
public class TwitterCorrectionTest
{
    private String correctResponse =
        "You seem to be using twitter addressing syntax. On IRC you would say this instead: ipun: message";
 | 
	    private TwitterCorrection tester = new TwitterCorrection(); | 
| 
	oldterns/VileBot | 
	vilebot/src/main/java/com/oldterns/vilebot/handlers/user/Summon.java | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/util/BaseNick.java
// public class BaseNick
// {
//     // This would grab the leading x out of a nick that actually contains it
//     private static Pattern nickPattern = Pattern.compile( "(?:x|)([a-zA-Z0-9]+)(?:\\p{Punct}+[a-zA-Z0-9]*|)" );
// 
//     private static String primaryBotNick;
// 
//     private static Set<String> allBotNicks = new HashSet<>();
// 
//     public static String toBaseNick( String nick )
//     {
//         if ( allBotNicks.contains( nick ) )
//         {
//             nick = primaryBotNick;
//         }
//         else
//         {
//             Matcher nickMatcher = nickPattern.matcher( nick );
// 
//             if ( nickMatcher.find() )
//             {
//                 return nickMatcher.group( 1 );
//             }
//         }
//         return nick;
//     }
// 
//     public static String getPrimaryBotNick()
//     {
//         return primaryBotNick;
//     }
// 
//     public static void setPrimaryBotNick( String primaryNick )
//     {
//         primaryBotNick = primaryNick;
//     }
// 
//     public static Set<String> getBotNicks()
//     {
//         return allBotNicks;
//     }
// 
//     public static void addBotNick( String nick )
//     {
//         allBotNicks.add( nick );
//     }
// }
// 
// Path: vilebot/src/main/java/com/oldterns/vilebot/util/LimitCommand.java
// public class LimitCommand
// {
//     private Map<String, Integer> usesUserMap = new HashMap<>();
// 
//     private int maxUsesPerPeriod = 2;
// 
//     private int timePeriodSeconds = 300;
// 
//     private static final String OKAY_STRING = " has less than the maximum uses";
// 
//     private static final String NOT_OKAY_STRING = " has the maximum uses";
// 
//     public LimitCommand()
//     {
//     }
// 
//     public LimitCommand( int maxUsesPerPeriod, int timePeriodSeconds )
//     {
//         this.maxUsesPerPeriod = maxUsesPerPeriod;
//         this.timePeriodSeconds = timePeriodSeconds;
//     }
// 
//     public int getMaxUses()
//     {
//         return maxUsesPerPeriod;
//     }
// 
//     public int getPeriodSeconds()
//     {
//         return timePeriodSeconds;
//     }
// 
//     public String addUse( String user )
//     {
//         Timer timer = new Timer();
//         if ( !usesUserMap.containsKey( user ) )
//         {
//             usesUserMap.put( user, 0 );
//         }
//         int uses = getUses( user );
//         if ( uses < maxUsesPerPeriod )
//         {
//             timer.schedule( createTimerTask( user ), timePeriodSeconds * 1000 );
//             uses++;
//             usesUserMap.put( user, uses );
//             return "";
//         }
//         else
//         {
//             return user + NOT_OKAY_STRING;
//         }
//     }
// 
//     public int getUses( String user )
//     {
//         return usesUserMap.get( user );
//     }
// 
//     public String checkUses( String user )
//     {
//         int uses = getUses( user );
//         if ( uses < maxUsesPerPeriod )
//         {
//             return user + OKAY_STRING;
//         }
//         else
//         {
//             return user + NOT_OKAY_STRING;
//         }
//     }
// 
//     private TimerTask createTimerTask( final String user )
//     {
//         return new TimerTask()
//         {
//             @Override
//             public void run()
//             {
//                 int amountOfUses = usesUserMap.get( user );
//                 amountOfUses--;
//                 usesUserMap.put( user, amountOfUses );
//             }
//         };
//     }
// }
 | 
	import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.oldterns.vilebot.Vilebot;
import com.oldterns.vilebot.util.BaseNick;
import com.oldterns.vilebot.util.LimitCommand;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.events.MessageEvent;
import org.pircbotx.hooks.types.GenericMessageEvent; | 
	package com.oldterns.vilebot.handlers.user;
public class Summon
    extends ListenerAdapter
{
    private static final Pattern nounPattern = Pattern.compile( "\\S+" );
    private static final Pattern summonPattern = Pattern.compile( "^!summon (" + nounPattern + ")\\s*$" );
 | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/util/BaseNick.java
// public class BaseNick
// {
//     // This would grab the leading x out of a nick that actually contains it
//     private static Pattern nickPattern = Pattern.compile( "(?:x|)([a-zA-Z0-9]+)(?:\\p{Punct}+[a-zA-Z0-9]*|)" );
// 
//     private static String primaryBotNick;
// 
//     private static Set<String> allBotNicks = new HashSet<>();
// 
//     public static String toBaseNick( String nick )
//     {
//         if ( allBotNicks.contains( nick ) )
//         {
//             nick = primaryBotNick;
//         }
//         else
//         {
//             Matcher nickMatcher = nickPattern.matcher( nick );
// 
//             if ( nickMatcher.find() )
//             {
//                 return nickMatcher.group( 1 );
//             }
//         }
//         return nick;
//     }
// 
//     public static String getPrimaryBotNick()
//     {
//         return primaryBotNick;
//     }
// 
//     public static void setPrimaryBotNick( String primaryNick )
//     {
//         primaryBotNick = primaryNick;
//     }
// 
//     public static Set<String> getBotNicks()
//     {
//         return allBotNicks;
//     }
// 
//     public static void addBotNick( String nick )
//     {
//         allBotNicks.add( nick );
//     }
// }
// 
// Path: vilebot/src/main/java/com/oldterns/vilebot/util/LimitCommand.java
// public class LimitCommand
// {
//     private Map<String, Integer> usesUserMap = new HashMap<>();
// 
//     private int maxUsesPerPeriod = 2;
// 
//     private int timePeriodSeconds = 300;
// 
//     private static final String OKAY_STRING = " has less than the maximum uses";
// 
//     private static final String NOT_OKAY_STRING = " has the maximum uses";
// 
//     public LimitCommand()
//     {
//     }
// 
//     public LimitCommand( int maxUsesPerPeriod, int timePeriodSeconds )
//     {
//         this.maxUsesPerPeriod = maxUsesPerPeriod;
//         this.timePeriodSeconds = timePeriodSeconds;
//     }
// 
//     public int getMaxUses()
//     {
//         return maxUsesPerPeriod;
//     }
// 
//     public int getPeriodSeconds()
//     {
//         return timePeriodSeconds;
//     }
// 
//     public String addUse( String user )
//     {
//         Timer timer = new Timer();
//         if ( !usesUserMap.containsKey( user ) )
//         {
//             usesUserMap.put( user, 0 );
//         }
//         int uses = getUses( user );
//         if ( uses < maxUsesPerPeriod )
//         {
//             timer.schedule( createTimerTask( user ), timePeriodSeconds * 1000 );
//             uses++;
//             usesUserMap.put( user, uses );
//             return "";
//         }
//         else
//         {
//             return user + NOT_OKAY_STRING;
//         }
//     }
// 
//     public int getUses( String user )
//     {
//         return usesUserMap.get( user );
//     }
// 
//     public String checkUses( String user )
//     {
//         int uses = getUses( user );
//         if ( uses < maxUsesPerPeriod )
//         {
//             return user + OKAY_STRING;
//         }
//         else
//         {
//             return user + NOT_OKAY_STRING;
//         }
//     }
// 
//     private TimerTask createTimerTask( final String user )
//     {
//         return new TimerTask()
//         {
//             @Override
//             public void run()
//             {
//                 int amountOfUses = usesUserMap.get( user );
//                 amountOfUses--;
//                 usesUserMap.put( user, amountOfUses );
//             }
//         };
//     }
// }
// Path: vilebot/src/main/java/com/oldterns/vilebot/handlers/user/Summon.java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.oldterns.vilebot.Vilebot;
import com.oldterns.vilebot.util.BaseNick;
import com.oldterns.vilebot.util.LimitCommand;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.events.MessageEvent;
import org.pircbotx.hooks.types.GenericMessageEvent;
package com.oldterns.vilebot.handlers.user;
public class Summon
    extends ListenerAdapter
{
    private static final Pattern nounPattern = Pattern.compile( "\\S+" );
    private static final Pattern summonPattern = Pattern.compile( "^!summon (" + nounPattern + ")\\s*$" );
 | 
	    public static LimitCommand limitCommand = new LimitCommand(); | 
| 
	oldterns/VileBot | 
	vilebot/src/main/java/com/oldterns/vilebot/handlers/user/Summon.java | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/util/BaseNick.java
// public class BaseNick
// {
//     // This would grab the leading x out of a nick that actually contains it
//     private static Pattern nickPattern = Pattern.compile( "(?:x|)([a-zA-Z0-9]+)(?:\\p{Punct}+[a-zA-Z0-9]*|)" );
// 
//     private static String primaryBotNick;
// 
//     private static Set<String> allBotNicks = new HashSet<>();
// 
//     public static String toBaseNick( String nick )
//     {
//         if ( allBotNicks.contains( nick ) )
//         {
//             nick = primaryBotNick;
//         }
//         else
//         {
//             Matcher nickMatcher = nickPattern.matcher( nick );
// 
//             if ( nickMatcher.find() )
//             {
//                 return nickMatcher.group( 1 );
//             }
//         }
//         return nick;
//     }
// 
//     public static String getPrimaryBotNick()
//     {
//         return primaryBotNick;
//     }
// 
//     public static void setPrimaryBotNick( String primaryNick )
//     {
//         primaryBotNick = primaryNick;
//     }
// 
//     public static Set<String> getBotNicks()
//     {
//         return allBotNicks;
//     }
// 
//     public static void addBotNick( String nick )
//     {
//         allBotNicks.add( nick );
//     }
// }
// 
// Path: vilebot/src/main/java/com/oldterns/vilebot/util/LimitCommand.java
// public class LimitCommand
// {
//     private Map<String, Integer> usesUserMap = new HashMap<>();
// 
//     private int maxUsesPerPeriod = 2;
// 
//     private int timePeriodSeconds = 300;
// 
//     private static final String OKAY_STRING = " has less than the maximum uses";
// 
//     private static final String NOT_OKAY_STRING = " has the maximum uses";
// 
//     public LimitCommand()
//     {
//     }
// 
//     public LimitCommand( int maxUsesPerPeriod, int timePeriodSeconds )
//     {
//         this.maxUsesPerPeriod = maxUsesPerPeriod;
//         this.timePeriodSeconds = timePeriodSeconds;
//     }
// 
//     public int getMaxUses()
//     {
//         return maxUsesPerPeriod;
//     }
// 
//     public int getPeriodSeconds()
//     {
//         return timePeriodSeconds;
//     }
// 
//     public String addUse( String user )
//     {
//         Timer timer = new Timer();
//         if ( !usesUserMap.containsKey( user ) )
//         {
//             usesUserMap.put( user, 0 );
//         }
//         int uses = getUses( user );
//         if ( uses < maxUsesPerPeriod )
//         {
//             timer.schedule( createTimerTask( user ), timePeriodSeconds * 1000 );
//             uses++;
//             usesUserMap.put( user, uses );
//             return "";
//         }
//         else
//         {
//             return user + NOT_OKAY_STRING;
//         }
//     }
// 
//     public int getUses( String user )
//     {
//         return usesUserMap.get( user );
//     }
// 
//     public String checkUses( String user )
//     {
//         int uses = getUses( user );
//         if ( uses < maxUsesPerPeriod )
//         {
//             return user + OKAY_STRING;
//         }
//         else
//         {
//             return user + NOT_OKAY_STRING;
//         }
//     }
// 
//     private TimerTask createTimerTask( final String user )
//     {
//         return new TimerTask()
//         {
//             @Override
//             public void run()
//             {
//                 int amountOfUses = usesUserMap.get( user );
//                 amountOfUses--;
//                 usesUserMap.put( user, amountOfUses );
//             }
//         };
//     }
// }
 | 
	import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.oldterns.vilebot.Vilebot;
import com.oldterns.vilebot.util.BaseNick;
import com.oldterns.vilebot.util.LimitCommand;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.events.MessageEvent;
import org.pircbotx.hooks.types.GenericMessageEvent; | 
	        if ( event instanceof MessageEvent
            && ( (MessageEvent) event ).getChannel().getName().equals( RESTRICTED_CHANNEL ) )
        {
            String text = event.getMessage();
            Matcher summonMatcher = summonPattern.matcher( text );
            if ( summonMatcher.matches() )
            {
                String toSummon = summonMatcher.group( 1 ).trim();
                if ( ( (MessageEvent) event ).getChannel().getUsers().stream().filter( u -> u.getNick().equals( toSummon ) ).findAny().isPresent() )
                {
                    event.respondWith( toSummon + " is already in the channel." );
                }
                else
                {
                    String isLimit = limitCommand.addUse( event.getUser().getNick() );
                    if ( isLimit.isEmpty() )
                        summonNick( event, toSummon );
                    else
                        event.respondWith( isLimit );
                }
            }
        }
    }
    private void summonNick( GenericMessageEvent event, String nick )
    {
        event.getBot().sendIRC().invite( nick, RESTRICTED_CHANNEL );
        event.getBot().sendIRC().message( nick, "You are summoned by " | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/util/BaseNick.java
// public class BaseNick
// {
//     // This would grab the leading x out of a nick that actually contains it
//     private static Pattern nickPattern = Pattern.compile( "(?:x|)([a-zA-Z0-9]+)(?:\\p{Punct}+[a-zA-Z0-9]*|)" );
// 
//     private static String primaryBotNick;
// 
//     private static Set<String> allBotNicks = new HashSet<>();
// 
//     public static String toBaseNick( String nick )
//     {
//         if ( allBotNicks.contains( nick ) )
//         {
//             nick = primaryBotNick;
//         }
//         else
//         {
//             Matcher nickMatcher = nickPattern.matcher( nick );
// 
//             if ( nickMatcher.find() )
//             {
//                 return nickMatcher.group( 1 );
//             }
//         }
//         return nick;
//     }
// 
//     public static String getPrimaryBotNick()
//     {
//         return primaryBotNick;
//     }
// 
//     public static void setPrimaryBotNick( String primaryNick )
//     {
//         primaryBotNick = primaryNick;
//     }
// 
//     public static Set<String> getBotNicks()
//     {
//         return allBotNicks;
//     }
// 
//     public static void addBotNick( String nick )
//     {
//         allBotNicks.add( nick );
//     }
// }
// 
// Path: vilebot/src/main/java/com/oldterns/vilebot/util/LimitCommand.java
// public class LimitCommand
// {
//     private Map<String, Integer> usesUserMap = new HashMap<>();
// 
//     private int maxUsesPerPeriod = 2;
// 
//     private int timePeriodSeconds = 300;
// 
//     private static final String OKAY_STRING = " has less than the maximum uses";
// 
//     private static final String NOT_OKAY_STRING = " has the maximum uses";
// 
//     public LimitCommand()
//     {
//     }
// 
//     public LimitCommand( int maxUsesPerPeriod, int timePeriodSeconds )
//     {
//         this.maxUsesPerPeriod = maxUsesPerPeriod;
//         this.timePeriodSeconds = timePeriodSeconds;
//     }
// 
//     public int getMaxUses()
//     {
//         return maxUsesPerPeriod;
//     }
// 
//     public int getPeriodSeconds()
//     {
//         return timePeriodSeconds;
//     }
// 
//     public String addUse( String user )
//     {
//         Timer timer = new Timer();
//         if ( !usesUserMap.containsKey( user ) )
//         {
//             usesUserMap.put( user, 0 );
//         }
//         int uses = getUses( user );
//         if ( uses < maxUsesPerPeriod )
//         {
//             timer.schedule( createTimerTask( user ), timePeriodSeconds * 1000 );
//             uses++;
//             usesUserMap.put( user, uses );
//             return "";
//         }
//         else
//         {
//             return user + NOT_OKAY_STRING;
//         }
//     }
// 
//     public int getUses( String user )
//     {
//         return usesUserMap.get( user );
//     }
// 
//     public String checkUses( String user )
//     {
//         int uses = getUses( user );
//         if ( uses < maxUsesPerPeriod )
//         {
//             return user + OKAY_STRING;
//         }
//         else
//         {
//             return user + NOT_OKAY_STRING;
//         }
//     }
// 
//     private TimerTask createTimerTask( final String user )
//     {
//         return new TimerTask()
//         {
//             @Override
//             public void run()
//             {
//                 int amountOfUses = usesUserMap.get( user );
//                 amountOfUses--;
//                 usesUserMap.put( user, amountOfUses );
//             }
//         };
//     }
// }
// Path: vilebot/src/main/java/com/oldterns/vilebot/handlers/user/Summon.java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.oldterns.vilebot.Vilebot;
import com.oldterns.vilebot.util.BaseNick;
import com.oldterns.vilebot.util.LimitCommand;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.events.MessageEvent;
import org.pircbotx.hooks.types.GenericMessageEvent;
        if ( event instanceof MessageEvent
            && ( (MessageEvent) event ).getChannel().getName().equals( RESTRICTED_CHANNEL ) )
        {
            String text = event.getMessage();
            Matcher summonMatcher = summonPattern.matcher( text );
            if ( summonMatcher.matches() )
            {
                String toSummon = summonMatcher.group( 1 ).trim();
                if ( ( (MessageEvent) event ).getChannel().getUsers().stream().filter( u -> u.getNick().equals( toSummon ) ).findAny().isPresent() )
                {
                    event.respondWith( toSummon + " is already in the channel." );
                }
                else
                {
                    String isLimit = limitCommand.addUse( event.getUser().getNick() );
                    if ( isLimit.isEmpty() )
                        summonNick( event, toSummon );
                    else
                        event.respondWith( isLimit );
                }
            }
        }
    }
    private void summonNick( GenericMessageEvent event, String nick )
    {
        event.getBot().sendIRC().invite( nick, RESTRICTED_CHANNEL );
        event.getBot().sendIRC().message( nick, "You are summoned by " | 
	            + BaseNick.toBaseNick( event.getUser().getNick() ) + " to join " + RESTRICTED_CHANNEL ); | 
| 
	oldterns/VileBot | 
	vilebot/src/main/java/com/oldterns/vilebot/handlers/user/Trivia.java | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/util/BaseNick.java
// public class BaseNick
// {
//     // This would grab the leading x out of a nick that actually contains it
//     private static Pattern nickPattern = Pattern.compile( "(?:x|)([a-zA-Z0-9]+)(?:\\p{Punct}+[a-zA-Z0-9]*|)" );
// 
//     private static String primaryBotNick;
// 
//     private static Set<String> allBotNicks = new HashSet<>();
// 
//     public static String toBaseNick( String nick )
//     {
//         if ( allBotNicks.contains( nick ) )
//         {
//             nick = primaryBotNick;
//         }
//         else
//         {
//             Matcher nickMatcher = nickPattern.matcher( nick );
// 
//             if ( nickMatcher.find() )
//             {
//                 return nickMatcher.group( 1 );
//             }
//         }
//         return nick;
//     }
// 
//     public static String getPrimaryBotNick()
//     {
//         return primaryBotNick;
//     }
// 
//     public static void setPrimaryBotNick( String primaryNick )
//     {
//         primaryBotNick = primaryNick;
//     }
// 
//     public static Set<String> getBotNicks()
//     {
//         return allBotNicks;
//     }
// 
//     public static void addBotNick( String nick )
//     {
//         allBotNicks.add( nick );
//     }
// }
 | 
	import com.oldterns.vilebot.Vilebot;
import com.oldterns.vilebot.db.KarmaDB;
import com.oldterns.vilebot.util.BaseNick;
import info.debatty.java.stringsimilarity.NormalizedLevenshtein;
import org.jsoup.Jsoup;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.events.MessageEvent;
import org.pircbotx.hooks.types.GenericMessageEvent;
import twitter4j.JSONArray;
import twitter4j.JSONObject;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | 
	        timer.submit( () -> {
            try
            {
                Thread.sleep( TIMEOUT );
                timeoutTimer( event );
            }
            catch ( InterruptedException e )
            {
                e.printStackTrace();
            }
        } );
    }
    private void timeoutTimer( GenericMessageEvent event )
    {
        for ( String msg : currentGame.getTimeoutString() )
        {
            event.respondWith( msg );
        }
        currentGame = null;
    }
    private void stopTimer()
    {
        timer.shutdownNow();
        timer = Executors.newFixedThreadPool( 1 );
    }
    private synchronized void finishGame( GenericMessageEvent event, String answer )
    { | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/util/BaseNick.java
// public class BaseNick
// {
//     // This would grab the leading x out of a nick that actually contains it
//     private static Pattern nickPattern = Pattern.compile( "(?:x|)([a-zA-Z0-9]+)(?:\\p{Punct}+[a-zA-Z0-9]*|)" );
// 
//     private static String primaryBotNick;
// 
//     private static Set<String> allBotNicks = new HashSet<>();
// 
//     public static String toBaseNick( String nick )
//     {
//         if ( allBotNicks.contains( nick ) )
//         {
//             nick = primaryBotNick;
//         }
//         else
//         {
//             Matcher nickMatcher = nickPattern.matcher( nick );
// 
//             if ( nickMatcher.find() )
//             {
//                 return nickMatcher.group( 1 );
//             }
//         }
//         return nick;
//     }
// 
//     public static String getPrimaryBotNick()
//     {
//         return primaryBotNick;
//     }
// 
//     public static void setPrimaryBotNick( String primaryNick )
//     {
//         primaryBotNick = primaryNick;
//     }
// 
//     public static Set<String> getBotNicks()
//     {
//         return allBotNicks;
//     }
// 
//     public static void addBotNick( String nick )
//     {
//         allBotNicks.add( nick );
//     }
// }
// Path: vilebot/src/main/java/com/oldterns/vilebot/handlers/user/Trivia.java
import com.oldterns.vilebot.Vilebot;
import com.oldterns.vilebot.db.KarmaDB;
import com.oldterns.vilebot.util.BaseNick;
import info.debatty.java.stringsimilarity.NormalizedLevenshtein;
import org.jsoup.Jsoup;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.events.MessageEvent;
import org.pircbotx.hooks.types.GenericMessageEvent;
import twitter4j.JSONArray;
import twitter4j.JSONObject;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
        timer.submit( () -> {
            try
            {
                Thread.sleep( TIMEOUT );
                timeoutTimer( event );
            }
            catch ( InterruptedException e )
            {
                e.printStackTrace();
            }
        } );
    }
    private void timeoutTimer( GenericMessageEvent event )
    {
        for ( String msg : currentGame.getTimeoutString() )
        {
            event.respondWith( msg );
        }
        currentGame = null;
    }
    private void stopTimer()
    {
        timer.shutdownNow();
        timer = Executors.newFixedThreadPool( 1 );
    }
    private synchronized void finishGame( GenericMessageEvent event, String answer )
    { | 
	        String answerer = BaseNick.toBaseNick( event.getUser().getNick() ); | 
| 
	oldterns/VileBot | 
	vilebot/src/test/java/vilebot/util/MangleNicksTest.java | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/util/MangleNicks.java
// public class MangleNicks
// {
// 
//     public static String mangleNicks( MessageEvent event, String message )
//     {
//         return mangleNicks( event.getChannel().getUsersNicks(), message );
//     }
// 
//     public static String mangleNicks( JoinEvent event, String message )
//     {
//         return mangleNicks( event.getChannel().getUsersNicks(), message );
//     }
// 
//     public static String mangleNicks( PrivateMessageEvent event, String message )
//     {
//         return mangleNicks( ImmutableSortedSet.of( Objects.requireNonNull( event.getUser() ).getNick() ), message );
//     }
// 
//     public static String mangleNicks( GenericMessageEvent event, String message )
//     {
//         if ( event instanceof MessageEvent )
//         {
//             return mangleNicks( (MessageEvent) event, message );
//         }
//         else if ( event instanceof JoinEvent )
//         {
//             return mangleNicks( (JoinEvent) event, message );
//         }
//         else if ( event instanceof PrivateMessageEvent )
//         {
//             return mangleNicks( (PrivateMessageEvent) event, message );
//         }
//         else
//         {
//             return mangleNicks( ImmutableSortedSet.of(), message );
//         }
//     }
// 
//     private static String mangleNicks( ImmutableSortedSet<String> nicks, String message )
//     {
// 
//         if ( nicks.isEmpty() )
//         {
//             return message;
//         }
// 
//         StringBuilder reply = new StringBuilder();
//         for ( String word : message.split( " " ) )
//         {
//             reply.append( " " );
//             reply.append( inside( nicks, word ) ? mangled( word ) : word );
//         }
//         return reply.toString().trim();
//     }
// 
//     private static String mangled( String word )
//     {
//         return new StringBuilder( word ).reverse().toString();
//     }
// 
//     private static boolean inside( ImmutableSortedSet<String> nicks, String word )
//     {
//         for ( String nick : nicks )
//         {
//             if ( word.contains( nick ) )
//             {
//                 return true;
//             }
//         }
//         return false;
//     }
// }
 | 
	import com.google.common.collect.ImmutableSortedSet;
import com.oldterns.vilebot.util.MangleNicks;
import org.junit.Before;
import org.junit.Test;
import org.pircbotx.Channel;
import org.pircbotx.PircBotX;
import org.pircbotx.hooks.events.JoinEvent;
import org.pircbotx.hooks.events.MessageEvent;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; | 
	package vilebot.util;
public class MangleNicksTest
{
    private MessageEvent rcvPrivMsg;
    private JoinEvent rcvJoin;
    private ImmutableSortedSet<String> nickList = ImmutableSortedSet.of( "salman", "sasiddiq" );
    @Before
    public void setup()
    {
        Channel chan = mock( Channel.class );
        rcvPrivMsg = mock( MessageEvent.class );
        rcvJoin = mock( JoinEvent.class );
        when( rcvPrivMsg.getChannel() ).thenReturn( chan );
        when( rcvJoin.getChannel() ).thenReturn( chan );
        when( chan.getUsersNicks() ).thenReturn( nickList );
    }
    @Test
    public void noNicks()
    {
        String messageText = "i am the karma police"; | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/util/MangleNicks.java
// public class MangleNicks
// {
// 
//     public static String mangleNicks( MessageEvent event, String message )
//     {
//         return mangleNicks( event.getChannel().getUsersNicks(), message );
//     }
// 
//     public static String mangleNicks( JoinEvent event, String message )
//     {
//         return mangleNicks( event.getChannel().getUsersNicks(), message );
//     }
// 
//     public static String mangleNicks( PrivateMessageEvent event, String message )
//     {
//         return mangleNicks( ImmutableSortedSet.of( Objects.requireNonNull( event.getUser() ).getNick() ), message );
//     }
// 
//     public static String mangleNicks( GenericMessageEvent event, String message )
//     {
//         if ( event instanceof MessageEvent )
//         {
//             return mangleNicks( (MessageEvent) event, message );
//         }
//         else if ( event instanceof JoinEvent )
//         {
//             return mangleNicks( (JoinEvent) event, message );
//         }
//         else if ( event instanceof PrivateMessageEvent )
//         {
//             return mangleNicks( (PrivateMessageEvent) event, message );
//         }
//         else
//         {
//             return mangleNicks( ImmutableSortedSet.of(), message );
//         }
//     }
// 
//     private static String mangleNicks( ImmutableSortedSet<String> nicks, String message )
//     {
// 
//         if ( nicks.isEmpty() )
//         {
//             return message;
//         }
// 
//         StringBuilder reply = new StringBuilder();
//         for ( String word : message.split( " " ) )
//         {
//             reply.append( " " );
//             reply.append( inside( nicks, word ) ? mangled( word ) : word );
//         }
//         return reply.toString().trim();
//     }
// 
//     private static String mangled( String word )
//     {
//         return new StringBuilder( word ).reverse().toString();
//     }
// 
//     private static boolean inside( ImmutableSortedSet<String> nicks, String word )
//     {
//         for ( String nick : nicks )
//         {
//             if ( word.contains( nick ) )
//             {
//                 return true;
//             }
//         }
//         return false;
//     }
// }
// Path: vilebot/src/test/java/vilebot/util/MangleNicksTest.java
import com.google.common.collect.ImmutableSortedSet;
import com.oldterns.vilebot.util.MangleNicks;
import org.junit.Before;
import org.junit.Test;
import org.pircbotx.Channel;
import org.pircbotx.PircBotX;
import org.pircbotx.hooks.events.JoinEvent;
import org.pircbotx.hooks.events.MessageEvent;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
package vilebot.util;
public class MangleNicksTest
{
    private MessageEvent rcvPrivMsg;
    private JoinEvent rcvJoin;
    private ImmutableSortedSet<String> nickList = ImmutableSortedSet.of( "salman", "sasiddiq" );
    @Before
    public void setup()
    {
        Channel chan = mock( Channel.class );
        rcvPrivMsg = mock( MessageEvent.class );
        rcvJoin = mock( JoinEvent.class );
        when( rcvPrivMsg.getChannel() ).thenReturn( chan );
        when( rcvJoin.getChannel() ).thenReturn( chan );
        when( chan.getUsersNicks() ).thenReturn( nickList );
    }
    @Test
    public void noNicks()
    {
        String messageText = "i am the karma police"; | 
	        String returnText1 = MangleNicks.mangleNicks( rcvPrivMsg, messageText ); | 
| 
	oldterns/VileBot | 
	vilebot/src/main/java/com/oldterns/vilebot/handlers/user/Countdown.java | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/util/BaseNick.java
// public class BaseNick
// {
//     // This would grab the leading x out of a nick that actually contains it
//     private static Pattern nickPattern = Pattern.compile( "(?:x|)([a-zA-Z0-9]+)(?:\\p{Punct}+[a-zA-Z0-9]*|)" );
// 
//     private static String primaryBotNick;
// 
//     private static Set<String> allBotNicks = new HashSet<>();
// 
//     public static String toBaseNick( String nick )
//     {
//         if ( allBotNicks.contains( nick ) )
//         {
//             nick = primaryBotNick;
//         }
//         else
//         {
//             Matcher nickMatcher = nickPattern.matcher( nick );
// 
//             if ( nickMatcher.find() )
//             {
//                 return nickMatcher.group( 1 );
//             }
//         }
//         return nick;
//     }
// 
//     public static String getPrimaryBotNick()
//     {
//         return primaryBotNick;
//     }
// 
//     public static void setPrimaryBotNick( String primaryNick )
//     {
//         primaryBotNick = primaryNick;
//     }
// 
//     public static Set<String> getBotNicks()
//     {
//         return allBotNicks;
//     }
// 
//     public static void addBotNick( String nick )
//     {
//         allBotNicks.add( nick );
//     }
// }
 | 
	import bsh.EvalError;
import bsh.Interpreter;
import com.oldterns.vilebot.Vilebot;
import com.oldterns.vilebot.db.KarmaDB;
import com.oldterns.vilebot.util.BaseNick;
import org.apache.commons.lang3.ArrayUtils;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.events.MessageEvent;
import org.pircbotx.hooks.events.PrivateMessageEvent;
import org.pircbotx.hooks.types.GenericMessageEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Hashtable;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | 
	        else
        {
            event.respondWith( "To play Countdown join : " + COUNTDOWN_CHANNEL );
        }
        return false;
    }
    private synchronized void startCountdownGame( GenericMessageEvent event )
    {
        if ( currGame == null )
        {
            currGame = new CountdownGame();
            for ( String line : currGame.getCountdownIntro() )
            {
                event.respondWith( line );
            }
            event.respondWith( getSubmissionRuleString( event ) );
            startTimer( event );
        }
        else
        {
            for ( String line : currGame.alreadyPlaying() )
            {
                event.respondWith( line );
            }
        }
    }
    private synchronized void checkAnswer( GenericMessageEvent event, String submission )
    { | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/util/BaseNick.java
// public class BaseNick
// {
//     // This would grab the leading x out of a nick that actually contains it
//     private static Pattern nickPattern = Pattern.compile( "(?:x|)([a-zA-Z0-9]+)(?:\\p{Punct}+[a-zA-Z0-9]*|)" );
// 
//     private static String primaryBotNick;
// 
//     private static Set<String> allBotNicks = new HashSet<>();
// 
//     public static String toBaseNick( String nick )
//     {
//         if ( allBotNicks.contains( nick ) )
//         {
//             nick = primaryBotNick;
//         }
//         else
//         {
//             Matcher nickMatcher = nickPattern.matcher( nick );
// 
//             if ( nickMatcher.find() )
//             {
//                 return nickMatcher.group( 1 );
//             }
//         }
//         return nick;
//     }
// 
//     public static String getPrimaryBotNick()
//     {
//         return primaryBotNick;
//     }
// 
//     public static void setPrimaryBotNick( String primaryNick )
//     {
//         primaryBotNick = primaryNick;
//     }
// 
//     public static Set<String> getBotNicks()
//     {
//         return allBotNicks;
//     }
// 
//     public static void addBotNick( String nick )
//     {
//         allBotNicks.add( nick );
//     }
// }
// Path: vilebot/src/main/java/com/oldterns/vilebot/handlers/user/Countdown.java
import bsh.EvalError;
import bsh.Interpreter;
import com.oldterns.vilebot.Vilebot;
import com.oldterns.vilebot.db.KarmaDB;
import com.oldterns.vilebot.util.BaseNick;
import org.apache.commons.lang3.ArrayUtils;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.events.MessageEvent;
import org.pircbotx.hooks.events.PrivateMessageEvent;
import org.pircbotx.hooks.types.GenericMessageEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Hashtable;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
        else
        {
            event.respondWith( "To play Countdown join : " + COUNTDOWN_CHANNEL );
        }
        return false;
    }
    private synchronized void startCountdownGame( GenericMessageEvent event )
    {
        if ( currGame == null )
        {
            currGame = new CountdownGame();
            for ( String line : currGame.getCountdownIntro() )
            {
                event.respondWith( line );
            }
            event.respondWith( getSubmissionRuleString( event ) );
            startTimer( event );
        }
        else
        {
            for ( String line : currGame.alreadyPlaying() )
            {
                event.respondWith( line );
            }
        }
    }
    private synchronized void checkAnswer( GenericMessageEvent event, String submission )
    { | 
	        String contestant = BaseNick.toBaseNick( event.getUser().getNick() ); | 
| 
	oldterns/VileBot | 
	vilebot/src/main/java/com/oldterns/vilebot/handlers/user/Ascii.java | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/util/LimitCommand.java
// public class LimitCommand
// {
//     private Map<String, Integer> usesUserMap = new HashMap<>();
// 
//     private int maxUsesPerPeriod = 2;
// 
//     private int timePeriodSeconds = 300;
// 
//     private static final String OKAY_STRING = " has less than the maximum uses";
// 
//     private static final String NOT_OKAY_STRING = " has the maximum uses";
// 
//     public LimitCommand()
//     {
//     }
// 
//     public LimitCommand( int maxUsesPerPeriod, int timePeriodSeconds )
//     {
//         this.maxUsesPerPeriod = maxUsesPerPeriod;
//         this.timePeriodSeconds = timePeriodSeconds;
//     }
// 
//     public int getMaxUses()
//     {
//         return maxUsesPerPeriod;
//     }
// 
//     public int getPeriodSeconds()
//     {
//         return timePeriodSeconds;
//     }
// 
//     public String addUse( String user )
//     {
//         Timer timer = new Timer();
//         if ( !usesUserMap.containsKey( user ) )
//         {
//             usesUserMap.put( user, 0 );
//         }
//         int uses = getUses( user );
//         if ( uses < maxUsesPerPeriod )
//         {
//             timer.schedule( createTimerTask( user ), timePeriodSeconds * 1000 );
//             uses++;
//             usesUserMap.put( user, uses );
//             return "";
//         }
//         else
//         {
//             return user + NOT_OKAY_STRING;
//         }
//     }
// 
//     public int getUses( String user )
//     {
//         return usesUserMap.get( user );
//     }
// 
//     public String checkUses( String user )
//     {
//         int uses = getUses( user );
//         if ( uses < maxUsesPerPeriod )
//         {
//             return user + OKAY_STRING;
//         }
//         else
//         {
//             return user + NOT_OKAY_STRING;
//         }
//     }
// 
//     private TimerTask createTimerTask( final String user )
//     {
//         return new TimerTask()
//         {
//             @Override
//             public void run()
//             {
//                 int amountOfUses = usesUserMap.get( user );
//                 amountOfUses--;
//                 usesUserMap.put( user, amountOfUses );
//             }
//         };
//     }
// }
 | 
	import com.github.lalyos.jfiglet.FigletFont;
import com.oldterns.vilebot.Vilebot;
import com.oldterns.vilebot.util.LimitCommand;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.events.MessageEvent;
import org.pircbotx.hooks.types.GenericMessageEvent;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | 
	package com.oldterns.vilebot.handlers.user;
public class Ascii
    extends ListenerAdapter
{
    private static final Pattern asciiPattern = Pattern.compile( "^!(ascii)\\s(.+)$" );
    private static final Pattern asciiFontsPattern = Pattern.compile( "!asciifonts" );
    private static final int MAX_CHARS_PER_LINE = 20;
    private static final int MAX_CHARS = MAX_CHARS_PER_LINE * 3; // max 3 lines
    private static final String fontFile = "./files/fonts/%s.flf";
    private static final String fontFileDir = "./files/fonts/";
    private static final List<String> availableFonts = getAvailableFonts();
 | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/util/LimitCommand.java
// public class LimitCommand
// {
//     private Map<String, Integer> usesUserMap = new HashMap<>();
// 
//     private int maxUsesPerPeriod = 2;
// 
//     private int timePeriodSeconds = 300;
// 
//     private static final String OKAY_STRING = " has less than the maximum uses";
// 
//     private static final String NOT_OKAY_STRING = " has the maximum uses";
// 
//     public LimitCommand()
//     {
//     }
// 
//     public LimitCommand( int maxUsesPerPeriod, int timePeriodSeconds )
//     {
//         this.maxUsesPerPeriod = maxUsesPerPeriod;
//         this.timePeriodSeconds = timePeriodSeconds;
//     }
// 
//     public int getMaxUses()
//     {
//         return maxUsesPerPeriod;
//     }
// 
//     public int getPeriodSeconds()
//     {
//         return timePeriodSeconds;
//     }
// 
//     public String addUse( String user )
//     {
//         Timer timer = new Timer();
//         if ( !usesUserMap.containsKey( user ) )
//         {
//             usesUserMap.put( user, 0 );
//         }
//         int uses = getUses( user );
//         if ( uses < maxUsesPerPeriod )
//         {
//             timer.schedule( createTimerTask( user ), timePeriodSeconds * 1000 );
//             uses++;
//             usesUserMap.put( user, uses );
//             return "";
//         }
//         else
//         {
//             return user + NOT_OKAY_STRING;
//         }
//     }
// 
//     public int getUses( String user )
//     {
//         return usesUserMap.get( user );
//     }
// 
//     public String checkUses( String user )
//     {
//         int uses = getUses( user );
//         if ( uses < maxUsesPerPeriod )
//         {
//             return user + OKAY_STRING;
//         }
//         else
//         {
//             return user + NOT_OKAY_STRING;
//         }
//     }
// 
//     private TimerTask createTimerTask( final String user )
//     {
//         return new TimerTask()
//         {
//             @Override
//             public void run()
//             {
//                 int amountOfUses = usesUserMap.get( user );
//                 amountOfUses--;
//                 usesUserMap.put( user, amountOfUses );
//             }
//         };
//     }
// }
// Path: vilebot/src/main/java/com/oldterns/vilebot/handlers/user/Ascii.java
import com.github.lalyos.jfiglet.FigletFont;
import com.oldterns.vilebot.Vilebot;
import com.oldterns.vilebot.util.LimitCommand;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.events.MessageEvent;
import org.pircbotx.hooks.types.GenericMessageEvent;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
package com.oldterns.vilebot.handlers.user;
public class Ascii
    extends ListenerAdapter
{
    private static final Pattern asciiPattern = Pattern.compile( "^!(ascii)\\s(.+)$" );
    private static final Pattern asciiFontsPattern = Pattern.compile( "!asciifonts" );
    private static final int MAX_CHARS_PER_LINE = 20;
    private static final int MAX_CHARS = MAX_CHARS_PER_LINE * 3; // max 3 lines
    private static final String fontFile = "./files/fonts/%s.flf";
    private static final String fontFileDir = "./files/fonts/";
    private static final List<String> availableFonts = getAvailableFonts();
 | 
	    public LimitCommand limitCommand = new LimitCommand(); | 
| 
	oldterns/VileBot | 
	vilebot/src/main/java/com/oldterns/vilebot/handlers/user/LastMessageSed.java | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/util/Colors.java
// public class Colors
// {
//     public static final String BLACK = "\u000301";
// 
//     public static final String BLUE = "\u000312";
// 
//     public static final String BOLD = "\u0002";
// 
//     public static final String BROWN = "\u000305";
// 
//     public static final String CYAN = "\u000311";
// 
//     public static final String DARK_BLUE = "\u000302";
// 
//     public static final String DARK_GRAY = "\u000314";
// 
//     public static final String DARK_GREEN = "\u000303";
// 
//     public static final String GREEN = "\u000309";
// 
//     public static final String LIGHT_GRAY = "\u000315";
// 
//     public static final String MAGENTA = "\u000313";
// 
//     public static final String NORMAL = "\u000f";
// 
//     public static final String OLIVE = "\u000307";
// 
//     public static final String PURPLE = "\u000306";
// 
//     public static final String RED = "\u000304";
// 
//     public static final String REVERSE = "\u0016";
// 
//     public static final String TEAL = "\u000310";
// 
//     public static final String UNDERLINE = "\u001f";
// 
//     public static final String WHITE = "\u000300";
// 
//     public static final String YELLOW = "\u000308";
// 
//     /**
//      * Return a copy of the input String with IRC bold characters inserted.
//      *
//      * @return The modified copy of the input String
//      */
//     public static String bold( String input )
//     {
//         return BOLD + input + BOLD;
//     }
// }
 | 
	import com.oldterns.vilebot.util.Colors;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.types.GenericMessageEvent;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | 
	        if ( sedMatcher.matches() )
        {
            String correction = "Correction: ";
            // If the last group of the regex captures a non-null string, the user is fixing another user's message.
            if ( sedMatcher.group( 5 ) != null )
            {
                nick = sedMatcher.group( 5 );
                correction = nick + ", ftfy: ";
            }
            if ( lastMessageMapByNick.containsKey( nick ) )
            {
                String regexp = sedMatcher.group( 2 );
                String replacement = sedMatcher.group( 3 );
                String endFlag = sedMatcher.group( 4 );
                synchronized ( lastMessageMapByNickMutex )
                {
                    String lastMessage = lastMessageMapByNick.get( nick );
                    if ( !lastMessage.contains( regexp ) )
                    {
                        event.respondWith( "Wow. Seriously? Try subbing out a string that actually occurred. Do you even sed, bro?" );
                    }
                    else
                    {
                        String replacedMsg;
                        String replacedMsgWHL;
 | 
	// Path: vilebot/src/main/java/com/oldterns/vilebot/util/Colors.java
// public class Colors
// {
//     public static final String BLACK = "\u000301";
// 
//     public static final String BLUE = "\u000312";
// 
//     public static final String BOLD = "\u0002";
// 
//     public static final String BROWN = "\u000305";
// 
//     public static final String CYAN = "\u000311";
// 
//     public static final String DARK_BLUE = "\u000302";
// 
//     public static final String DARK_GRAY = "\u000314";
// 
//     public static final String DARK_GREEN = "\u000303";
// 
//     public static final String GREEN = "\u000309";
// 
//     public static final String LIGHT_GRAY = "\u000315";
// 
//     public static final String MAGENTA = "\u000313";
// 
//     public static final String NORMAL = "\u000f";
// 
//     public static final String OLIVE = "\u000307";
// 
//     public static final String PURPLE = "\u000306";
// 
//     public static final String RED = "\u000304";
// 
//     public static final String REVERSE = "\u0016";
// 
//     public static final String TEAL = "\u000310";
// 
//     public static final String UNDERLINE = "\u001f";
// 
//     public static final String WHITE = "\u000300";
// 
//     public static final String YELLOW = "\u000308";
// 
//     /**
//      * Return a copy of the input String with IRC bold characters inserted.
//      *
//      * @return The modified copy of the input String
//      */
//     public static String bold( String input )
//     {
//         return BOLD + input + BOLD;
//     }
// }
// Path: vilebot/src/main/java/com/oldterns/vilebot/handlers/user/LastMessageSed.java
import com.oldterns.vilebot.util.Colors;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.types.GenericMessageEvent;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
        if ( sedMatcher.matches() )
        {
            String correction = "Correction: ";
            // If the last group of the regex captures a non-null string, the user is fixing another user's message.
            if ( sedMatcher.group( 5 ) != null )
            {
                nick = sedMatcher.group( 5 );
                correction = nick + ", ftfy: ";
            }
            if ( lastMessageMapByNick.containsKey( nick ) )
            {
                String regexp = sedMatcher.group( 2 );
                String replacement = sedMatcher.group( 3 );
                String endFlag = sedMatcher.group( 4 );
                synchronized ( lastMessageMapByNickMutex )
                {
                    String lastMessage = lastMessageMapByNick.get( nick );
                    if ( !lastMessage.contains( regexp ) )
                    {
                        event.respondWith( "Wow. Seriously? Try subbing out a string that actually occurred. Do you even sed, bro?" );
                    }
                    else
                    {
                        String replacedMsg;
                        String replacedMsgWHL;
 | 
	                        String replacementWHL = Colors.bold( replacement ); | 
| 
	massivedisaster/ADAL | 
	adal-location/src/main/java/com/massivedisaster/location/AbstractLocationManager.java | 
	// Path: adal-location/src/main/java/com/massivedisaster/location/broadcast/LocationStatusBroadcastReceiver.java
// public class LocationStatusBroadcastReceiver extends BroadcastReceiver {
// 
//     private static final int PROVIDER_ENABLED = 1;
//     private static final int PROVIDER_DISABLED = 0;
//     private static final int PROVIDER_NONE = -1;
// 
//     protected int mStatus = PROVIDER_NONE;
//     protected OnLocationStatusProviderListener mOnLocationStatusProviderListener;
// 
//     @Override
//     public void onReceive(Context context, Intent intent) {
//         if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
//             checkGPSStatus(context);
//         }
//     }
// 
//     /**
//      * Listener to check provider status
//      *
//      * @param onLocationStatusProviderListener the listener
//      */
//     public void setOnLocationStatusProviderListener(OnLocationStatusProviderListener onLocationStatusProviderListener) {
//         this.mOnLocationStatusProviderListener = onLocationStatusProviderListener;
//     }
// 
//     /**
//      * Check the GPS status
//      *
//      * @param context the context from BroadcasteReceiver
//      */
//     private void checkGPSStatus(Context context) {
//         android.location.LocationManager locationManager =
//                 (android.location.LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
//         if (locationManager != null) {
//             boolean isLocationEnabled = LocationUtils.isLocationEnabled(locationManager);
//             if (isLocationEnabled && mStatus != PROVIDER_ENABLED) {
//                 mStatus = PROVIDER_ENABLED;
//                 Log.w(LocationStatusBroadcastReceiver.class.getSimpleName(), "PROVIDER PROVIDER_ENABLED");
//                 if (mOnLocationStatusProviderListener != null) {
//                     mOnLocationStatusProviderListener.onProviderEnabled();
//                 }
//             } else if (!isLocationEnabled && mStatus != PROVIDER_DISABLED) {
//                 mStatus = PROVIDER_DISABLED;
//                 Log.w(LocationStatusBroadcastReceiver.class.getSimpleName(), "PROVIDER PROVIDER_DISABLED");
//                 if (mOnLocationStatusProviderListener != null) {
//                     mOnLocationStatusProviderListener.onProviderDisabled();
//                 }
//             }
//         } else {
//             Log.w(LocationManager.class.getSimpleName(), "PROVIDER ERROR");
//         }
//     }
// }
// 
// Path: adal-location/src/main/java/com/massivedisaster/location/listener/OnLocationStatusProviderListener.java
// public interface OnLocationStatusProviderListener {
// 
//     /**
//      * Called if provider is enabled
//      */
//     void onProviderEnabled();
// 
//     /**
//      * Called if provider is disabled
//      */
//     void onProviderDisabled();
// }
// 
// Path: adal-location/src/main/java/com/massivedisaster/location/utils/LocationError.java
// public enum LocationError {
//     TIMEOUT,
//     DISABLED,
//     REQUEST_NEEDED,
//     REQUEST_UPDATES_ENABLED
// }
 | 
	import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.util.Log;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationAvailability;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.SettingsClient;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.massivedisaster.location.broadcast.LocationStatusBroadcastReceiver;
import com.massivedisaster.location.listener.OnLocationStatusProviderListener;
import com.massivedisaster.location.utils.LocationError; | 
	/*
 * ADAL - A set of Android libraries to help speed up Android development.
 * Copyright (C) 2017 ADAL.
 *
 * ADAL is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 3 of the License, or any later version.
 *
 * ADAL is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Lesser General Public License along
 * with ADAL. If not, see <http://www.gnu.org/licenses/>.
 */
package com.massivedisaster.location;
/**
 * AbstractLocationManager contains the base methods to request device location
 * <p>
 * PermissionsManager implemented in all requests.
 */
abstract class AbstractLocationManager extends AbstractPermissionsLocationManager {
    protected static final int REQUEST_CHECK_SETTINGS = 909;
    protected FusedLocationProviderClient mFusedLocationClient;
    protected SettingsClient mSettingsClient;
    protected LocationSettingsRequest mLocationSettingsRequest;
    protected LocationCallback mLocationCallback;
    protected boolean mLastKnowLocation;
    protected Handler mHandler;
    private long mTimeout;
 | 
	// Path: adal-location/src/main/java/com/massivedisaster/location/broadcast/LocationStatusBroadcastReceiver.java
// public class LocationStatusBroadcastReceiver extends BroadcastReceiver {
// 
//     private static final int PROVIDER_ENABLED = 1;
//     private static final int PROVIDER_DISABLED = 0;
//     private static final int PROVIDER_NONE = -1;
// 
//     protected int mStatus = PROVIDER_NONE;
//     protected OnLocationStatusProviderListener mOnLocationStatusProviderListener;
// 
//     @Override
//     public void onReceive(Context context, Intent intent) {
//         if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
//             checkGPSStatus(context);
//         }
//     }
// 
//     /**
//      * Listener to check provider status
//      *
//      * @param onLocationStatusProviderListener the listener
//      */
//     public void setOnLocationStatusProviderListener(OnLocationStatusProviderListener onLocationStatusProviderListener) {
//         this.mOnLocationStatusProviderListener = onLocationStatusProviderListener;
//     }
// 
//     /**
//      * Check the GPS status
//      *
//      * @param context the context from BroadcasteReceiver
//      */
//     private void checkGPSStatus(Context context) {
//         android.location.LocationManager locationManager =
//                 (android.location.LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
//         if (locationManager != null) {
//             boolean isLocationEnabled = LocationUtils.isLocationEnabled(locationManager);
//             if (isLocationEnabled && mStatus != PROVIDER_ENABLED) {
//                 mStatus = PROVIDER_ENABLED;
//                 Log.w(LocationStatusBroadcastReceiver.class.getSimpleName(), "PROVIDER PROVIDER_ENABLED");
//                 if (mOnLocationStatusProviderListener != null) {
//                     mOnLocationStatusProviderListener.onProviderEnabled();
//                 }
//             } else if (!isLocationEnabled && mStatus != PROVIDER_DISABLED) {
//                 mStatus = PROVIDER_DISABLED;
//                 Log.w(LocationStatusBroadcastReceiver.class.getSimpleName(), "PROVIDER PROVIDER_DISABLED");
//                 if (mOnLocationStatusProviderListener != null) {
//                     mOnLocationStatusProviderListener.onProviderDisabled();
//                 }
//             }
//         } else {
//             Log.w(LocationManager.class.getSimpleName(), "PROVIDER ERROR");
//         }
//     }
// }
// 
// Path: adal-location/src/main/java/com/massivedisaster/location/listener/OnLocationStatusProviderListener.java
// public interface OnLocationStatusProviderListener {
// 
//     /**
//      * Called if provider is enabled
//      */
//     void onProviderEnabled();
// 
//     /**
//      * Called if provider is disabled
//      */
//     void onProviderDisabled();
// }
// 
// Path: adal-location/src/main/java/com/massivedisaster/location/utils/LocationError.java
// public enum LocationError {
//     TIMEOUT,
//     DISABLED,
//     REQUEST_NEEDED,
//     REQUEST_UPDATES_ENABLED
// }
// Path: adal-location/src/main/java/com/massivedisaster/location/AbstractLocationManager.java
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.util.Log;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationAvailability;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.SettingsClient;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.massivedisaster.location.broadcast.LocationStatusBroadcastReceiver;
import com.massivedisaster.location.listener.OnLocationStatusProviderListener;
import com.massivedisaster.location.utils.LocationError;
/*
 * ADAL - A set of Android libraries to help speed up Android development.
 * Copyright (C) 2017 ADAL.
 *
 * ADAL is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 3 of the License, or any later version.
 *
 * ADAL is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Lesser General Public License along
 * with ADAL. If not, see <http://www.gnu.org/licenses/>.
 */
package com.massivedisaster.location;
/**
 * AbstractLocationManager contains the base methods to request device location
 * <p>
 * PermissionsManager implemented in all requests.
 */
abstract class AbstractLocationManager extends AbstractPermissionsLocationManager {
    protected static final int REQUEST_CHECK_SETTINGS = 909;
    protected FusedLocationProviderClient mFusedLocationClient;
    protected SettingsClient mSettingsClient;
    protected LocationSettingsRequest mLocationSettingsRequest;
    protected LocationCallback mLocationCallback;
    protected boolean mLastKnowLocation;
    protected Handler mHandler;
    private long mTimeout;
 | 
	    private final LocationStatusBroadcastReceiver mLocationStatusBroadcastReceiver = new LocationStatusBroadcastReceiver(); | 
| 
	massivedisaster/ADAL | 
	adal-location/src/main/java/com/massivedisaster/location/AbstractLocationManager.java | 
	// Path: adal-location/src/main/java/com/massivedisaster/location/broadcast/LocationStatusBroadcastReceiver.java
// public class LocationStatusBroadcastReceiver extends BroadcastReceiver {
// 
//     private static final int PROVIDER_ENABLED = 1;
//     private static final int PROVIDER_DISABLED = 0;
//     private static final int PROVIDER_NONE = -1;
// 
//     protected int mStatus = PROVIDER_NONE;
//     protected OnLocationStatusProviderListener mOnLocationStatusProviderListener;
// 
//     @Override
//     public void onReceive(Context context, Intent intent) {
//         if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
//             checkGPSStatus(context);
//         }
//     }
// 
//     /**
//      * Listener to check provider status
//      *
//      * @param onLocationStatusProviderListener the listener
//      */
//     public void setOnLocationStatusProviderListener(OnLocationStatusProviderListener onLocationStatusProviderListener) {
//         this.mOnLocationStatusProviderListener = onLocationStatusProviderListener;
//     }
// 
//     /**
//      * Check the GPS status
//      *
//      * @param context the context from BroadcasteReceiver
//      */
//     private void checkGPSStatus(Context context) {
//         android.location.LocationManager locationManager =
//                 (android.location.LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
//         if (locationManager != null) {
//             boolean isLocationEnabled = LocationUtils.isLocationEnabled(locationManager);
//             if (isLocationEnabled && mStatus != PROVIDER_ENABLED) {
//                 mStatus = PROVIDER_ENABLED;
//                 Log.w(LocationStatusBroadcastReceiver.class.getSimpleName(), "PROVIDER PROVIDER_ENABLED");
//                 if (mOnLocationStatusProviderListener != null) {
//                     mOnLocationStatusProviderListener.onProviderEnabled();
//                 }
//             } else if (!isLocationEnabled && mStatus != PROVIDER_DISABLED) {
//                 mStatus = PROVIDER_DISABLED;
//                 Log.w(LocationStatusBroadcastReceiver.class.getSimpleName(), "PROVIDER PROVIDER_DISABLED");
//                 if (mOnLocationStatusProviderListener != null) {
//                     mOnLocationStatusProviderListener.onProviderDisabled();
//                 }
//             }
//         } else {
//             Log.w(LocationManager.class.getSimpleName(), "PROVIDER ERROR");
//         }
//     }
// }
// 
// Path: adal-location/src/main/java/com/massivedisaster/location/listener/OnLocationStatusProviderListener.java
// public interface OnLocationStatusProviderListener {
// 
//     /**
//      * Called if provider is enabled
//      */
//     void onProviderEnabled();
// 
//     /**
//      * Called if provider is disabled
//      */
//     void onProviderDisabled();
// }
// 
// Path: adal-location/src/main/java/com/massivedisaster/location/utils/LocationError.java
// public enum LocationError {
//     TIMEOUT,
//     DISABLED,
//     REQUEST_NEEDED,
//     REQUEST_UPDATES_ENABLED
// }
 | 
	import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.util.Log;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationAvailability;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.SettingsClient;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.massivedisaster.location.broadcast.LocationStatusBroadcastReceiver;
import com.massivedisaster.location.listener.OnLocationStatusProviderListener;
import com.massivedisaster.location.utils.LocationError; | 
	     */
    public void onCreate(Context context) {
        mContext = context;
        initialize();
    }
    /**
     * Stop and destroy location requests
     */
    public void onDestroy() {
        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            stopRequestLocation();
        }
        mHandler.removeCallbacksAndMessages(null);
        if (mActivity != null) {
            mActivity.unregisterReceiver(mLocationStatusBroadcastReceiver);
        }
    }
    /**
     * Initialize location manager.
     */
    private void initialize() {
        mHandler = new Handler();
        if (mActivity != null) { | 
	// Path: adal-location/src/main/java/com/massivedisaster/location/broadcast/LocationStatusBroadcastReceiver.java
// public class LocationStatusBroadcastReceiver extends BroadcastReceiver {
// 
//     private static final int PROVIDER_ENABLED = 1;
//     private static final int PROVIDER_DISABLED = 0;
//     private static final int PROVIDER_NONE = -1;
// 
//     protected int mStatus = PROVIDER_NONE;
//     protected OnLocationStatusProviderListener mOnLocationStatusProviderListener;
// 
//     @Override
//     public void onReceive(Context context, Intent intent) {
//         if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
//             checkGPSStatus(context);
//         }
//     }
// 
//     /**
//      * Listener to check provider status
//      *
//      * @param onLocationStatusProviderListener the listener
//      */
//     public void setOnLocationStatusProviderListener(OnLocationStatusProviderListener onLocationStatusProviderListener) {
//         this.mOnLocationStatusProviderListener = onLocationStatusProviderListener;
//     }
// 
//     /**
//      * Check the GPS status
//      *
//      * @param context the context from BroadcasteReceiver
//      */
//     private void checkGPSStatus(Context context) {
//         android.location.LocationManager locationManager =
//                 (android.location.LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
//         if (locationManager != null) {
//             boolean isLocationEnabled = LocationUtils.isLocationEnabled(locationManager);
//             if (isLocationEnabled && mStatus != PROVIDER_ENABLED) {
//                 mStatus = PROVIDER_ENABLED;
//                 Log.w(LocationStatusBroadcastReceiver.class.getSimpleName(), "PROVIDER PROVIDER_ENABLED");
//                 if (mOnLocationStatusProviderListener != null) {
//                     mOnLocationStatusProviderListener.onProviderEnabled();
//                 }
//             } else if (!isLocationEnabled && mStatus != PROVIDER_DISABLED) {
//                 mStatus = PROVIDER_DISABLED;
//                 Log.w(LocationStatusBroadcastReceiver.class.getSimpleName(), "PROVIDER PROVIDER_DISABLED");
//                 if (mOnLocationStatusProviderListener != null) {
//                     mOnLocationStatusProviderListener.onProviderDisabled();
//                 }
//             }
//         } else {
//             Log.w(LocationManager.class.getSimpleName(), "PROVIDER ERROR");
//         }
//     }
// }
// 
// Path: adal-location/src/main/java/com/massivedisaster/location/listener/OnLocationStatusProviderListener.java
// public interface OnLocationStatusProviderListener {
// 
//     /**
//      * Called if provider is enabled
//      */
//     void onProviderEnabled();
// 
//     /**
//      * Called if provider is disabled
//      */
//     void onProviderDisabled();
// }
// 
// Path: adal-location/src/main/java/com/massivedisaster/location/utils/LocationError.java
// public enum LocationError {
//     TIMEOUT,
//     DISABLED,
//     REQUEST_NEEDED,
//     REQUEST_UPDATES_ENABLED
// }
// Path: adal-location/src/main/java/com/massivedisaster/location/AbstractLocationManager.java
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.util.Log;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationAvailability;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.SettingsClient;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.massivedisaster.location.broadcast.LocationStatusBroadcastReceiver;
import com.massivedisaster.location.listener.OnLocationStatusProviderListener;
import com.massivedisaster.location.utils.LocationError;
     */
    public void onCreate(Context context) {
        mContext = context;
        initialize();
    }
    /**
     * Stop and destroy location requests
     */
    public void onDestroy() {
        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            stopRequestLocation();
        }
        mHandler.removeCallbacksAndMessages(null);
        if (mActivity != null) {
            mActivity.unregisterReceiver(mLocationStatusBroadcastReceiver);
        }
    }
    /**
     * Initialize location manager.
     */
    private void initialize() {
        mHandler = new Handler();
        if (mActivity != null) { | 
	            mLocationStatusBroadcastReceiver.setOnLocationStatusProviderListener(new OnLocationStatusProviderListener() { | 
| 
	massivedisaster/ADAL | 
	adal-location/src/main/java/com/massivedisaster/location/AbstractLocationManager.java | 
	// Path: adal-location/src/main/java/com/massivedisaster/location/broadcast/LocationStatusBroadcastReceiver.java
// public class LocationStatusBroadcastReceiver extends BroadcastReceiver {
// 
//     private static final int PROVIDER_ENABLED = 1;
//     private static final int PROVIDER_DISABLED = 0;
//     private static final int PROVIDER_NONE = -1;
// 
//     protected int mStatus = PROVIDER_NONE;
//     protected OnLocationStatusProviderListener mOnLocationStatusProviderListener;
// 
//     @Override
//     public void onReceive(Context context, Intent intent) {
//         if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
//             checkGPSStatus(context);
//         }
//     }
// 
//     /**
//      * Listener to check provider status
//      *
//      * @param onLocationStatusProviderListener the listener
//      */
//     public void setOnLocationStatusProviderListener(OnLocationStatusProviderListener onLocationStatusProviderListener) {
//         this.mOnLocationStatusProviderListener = onLocationStatusProviderListener;
//     }
// 
//     /**
//      * Check the GPS status
//      *
//      * @param context the context from BroadcasteReceiver
//      */
//     private void checkGPSStatus(Context context) {
//         android.location.LocationManager locationManager =
//                 (android.location.LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
//         if (locationManager != null) {
//             boolean isLocationEnabled = LocationUtils.isLocationEnabled(locationManager);
//             if (isLocationEnabled && mStatus != PROVIDER_ENABLED) {
//                 mStatus = PROVIDER_ENABLED;
//                 Log.w(LocationStatusBroadcastReceiver.class.getSimpleName(), "PROVIDER PROVIDER_ENABLED");
//                 if (mOnLocationStatusProviderListener != null) {
//                     mOnLocationStatusProviderListener.onProviderEnabled();
//                 }
//             } else if (!isLocationEnabled && mStatus != PROVIDER_DISABLED) {
//                 mStatus = PROVIDER_DISABLED;
//                 Log.w(LocationStatusBroadcastReceiver.class.getSimpleName(), "PROVIDER PROVIDER_DISABLED");
//                 if (mOnLocationStatusProviderListener != null) {
//                     mOnLocationStatusProviderListener.onProviderDisabled();
//                 }
//             }
//         } else {
//             Log.w(LocationManager.class.getSimpleName(), "PROVIDER ERROR");
//         }
//     }
// }
// 
// Path: adal-location/src/main/java/com/massivedisaster/location/listener/OnLocationStatusProviderListener.java
// public interface OnLocationStatusProviderListener {
// 
//     /**
//      * Called if provider is enabled
//      */
//     void onProviderEnabled();
// 
//     /**
//      * Called if provider is disabled
//      */
//     void onProviderDisabled();
// }
// 
// Path: adal-location/src/main/java/com/massivedisaster/location/utils/LocationError.java
// public enum LocationError {
//     TIMEOUT,
//     DISABLED,
//     REQUEST_NEEDED,
//     REQUEST_UPDATES_ENABLED
// }
 | 
	import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.util.Log;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationAvailability;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.SettingsClient;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.massivedisaster.location.broadcast.LocationStatusBroadcastReceiver;
import com.massivedisaster.location.listener.OnLocationStatusProviderListener;
import com.massivedisaster.location.utils.LocationError; | 
	            mFusedLocationClient = LocationServices.getFusedLocationProviderClient(mActivity);
            mSettingsClient = LocationServices.getSettingsClient(mActivity);
        } else {
            mFusedLocationClient = LocationServices.getFusedLocationProviderClient(mContext);
            mSettingsClient = LocationServices.getSettingsClient(mContext);
        }
        initLocationCallback();
        initPermissionsManager();
    }
    /**
     * Initialize Location Callback
     */
    protected void initLocationCallback() {
        mLocationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {
                mHandler.removeCallbacksAndMessages(null);
                if (mOnLocationManager != null) {
                    mOnLocationManager.onLocationFound(locationResult.getLastLocation(), false);
                }
            }
            @Override
            public void onLocationAvailability(LocationAvailability locationAvailability) {
                if (!locationAvailability.isLocationAvailable() && mOnLocationManager != null) { | 
	// Path: adal-location/src/main/java/com/massivedisaster/location/broadcast/LocationStatusBroadcastReceiver.java
// public class LocationStatusBroadcastReceiver extends BroadcastReceiver {
// 
//     private static final int PROVIDER_ENABLED = 1;
//     private static final int PROVIDER_DISABLED = 0;
//     private static final int PROVIDER_NONE = -1;
// 
//     protected int mStatus = PROVIDER_NONE;
//     protected OnLocationStatusProviderListener mOnLocationStatusProviderListener;
// 
//     @Override
//     public void onReceive(Context context, Intent intent) {
//         if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
//             checkGPSStatus(context);
//         }
//     }
// 
//     /**
//      * Listener to check provider status
//      *
//      * @param onLocationStatusProviderListener the listener
//      */
//     public void setOnLocationStatusProviderListener(OnLocationStatusProviderListener onLocationStatusProviderListener) {
//         this.mOnLocationStatusProviderListener = onLocationStatusProviderListener;
//     }
// 
//     /**
//      * Check the GPS status
//      *
//      * @param context the context from BroadcasteReceiver
//      */
//     private void checkGPSStatus(Context context) {
//         android.location.LocationManager locationManager =
//                 (android.location.LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
//         if (locationManager != null) {
//             boolean isLocationEnabled = LocationUtils.isLocationEnabled(locationManager);
//             if (isLocationEnabled && mStatus != PROVIDER_ENABLED) {
//                 mStatus = PROVIDER_ENABLED;
//                 Log.w(LocationStatusBroadcastReceiver.class.getSimpleName(), "PROVIDER PROVIDER_ENABLED");
//                 if (mOnLocationStatusProviderListener != null) {
//                     mOnLocationStatusProviderListener.onProviderEnabled();
//                 }
//             } else if (!isLocationEnabled && mStatus != PROVIDER_DISABLED) {
//                 mStatus = PROVIDER_DISABLED;
//                 Log.w(LocationStatusBroadcastReceiver.class.getSimpleName(), "PROVIDER PROVIDER_DISABLED");
//                 if (mOnLocationStatusProviderListener != null) {
//                     mOnLocationStatusProviderListener.onProviderDisabled();
//                 }
//             }
//         } else {
//             Log.w(LocationManager.class.getSimpleName(), "PROVIDER ERROR");
//         }
//     }
// }
// 
// Path: adal-location/src/main/java/com/massivedisaster/location/listener/OnLocationStatusProviderListener.java
// public interface OnLocationStatusProviderListener {
// 
//     /**
//      * Called if provider is enabled
//      */
//     void onProviderEnabled();
// 
//     /**
//      * Called if provider is disabled
//      */
//     void onProviderDisabled();
// }
// 
// Path: adal-location/src/main/java/com/massivedisaster/location/utils/LocationError.java
// public enum LocationError {
//     TIMEOUT,
//     DISABLED,
//     REQUEST_NEEDED,
//     REQUEST_UPDATES_ENABLED
// }
// Path: adal-location/src/main/java/com/massivedisaster/location/AbstractLocationManager.java
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.util.Log;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationAvailability;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.SettingsClient;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.massivedisaster.location.broadcast.LocationStatusBroadcastReceiver;
import com.massivedisaster.location.listener.OnLocationStatusProviderListener;
import com.massivedisaster.location.utils.LocationError;
            mFusedLocationClient = LocationServices.getFusedLocationProviderClient(mActivity);
            mSettingsClient = LocationServices.getSettingsClient(mActivity);
        } else {
            mFusedLocationClient = LocationServices.getFusedLocationProviderClient(mContext);
            mSettingsClient = LocationServices.getSettingsClient(mContext);
        }
        initLocationCallback();
        initPermissionsManager();
    }
    /**
     * Initialize Location Callback
     */
    protected void initLocationCallback() {
        mLocationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {
                mHandler.removeCallbacksAndMessages(null);
                if (mOnLocationManager != null) {
                    mOnLocationManager.onLocationFound(locationResult.getLastLocation(), false);
                }
            }
            @Override
            public void onLocationAvailability(LocationAvailability locationAvailability) {
                if (!locationAvailability.isLocationAvailable() && mOnLocationManager != null) { | 
	                    mOnLocationManager.onLocationError(LocationError.DISABLED); | 
| 
	massivedisaster/ADAL | 
	adal-adapters/src/main/java/com/massivedisaster/adal/adapter/FragmentPagerAdapter.java | 
	// Path: adal-utils/src/main/java/com/massivedisaster/adal/utils/LogUtils.java
// public final class LogUtils {
// 
//     /**
//      * Private constructor to avoid user implement as a single instance instead of a Singleton
//      */
//     private LogUtils() {
// 
//     }
// 
//     /**
//      * Logs a error exception
//      *
//      * @param enclosingClass the caller class
//      * @param exception      the exception
//      */
//     public static void logErrorException(@NonNull Class<?> enclosingClass, @NonNull Throwable exception) {
//         String message = exception.getMessage() == null ? "Exception error." : exception.getMessage();
//         Log.e(enclosingClass.getName(), message, exception);
//     }
// 
// }
 | 
	import com.massivedisaster.adal.utils.LogUtils;
import java.util.List;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.util.SparseArray; | 
	/*
 * ADAL - A set of Android libraries to help speed up Android development.
 *
 * Copyright (c) 2017 ADAL
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package com.massivedisaster.adal.adapter;
/**
 * The adapter of fragments.
 */
public class FragmentPagerAdapter extends FragmentStatePagerAdapter {
    private final List<Class<? extends Fragment>> mLstFragments;
    private final SparseArray<Fragment> mFragmentSparseArray;
    /**
     * Constructor of the adapter.
     *
     * @param fm          The fragment manager.
     * @param lstFragment The list of fragments to be add to the adapter.
     */
    public FragmentPagerAdapter(FragmentManager fm, List<Class<? extends Fragment>> lstFragment) {
        super(fm);
        mLstFragments = lstFragment;
        mFragmentSparseArray = new SparseArray<>(lstFragment.size());
    }
    @Override
    public Fragment getItem(int position) {
        try {
            Fragment fragment = mFragmentSparseArray.get(position);
            if (fragment == null) {
                fragment = mLstFragments.get(position).newInstance();
                mFragmentSparseArray.put(position, fragment);
                fragment.setRetainInstance(true);
            }
            return fragment;
        } catch (InstantiationException e) { | 
	// Path: adal-utils/src/main/java/com/massivedisaster/adal/utils/LogUtils.java
// public final class LogUtils {
// 
//     /**
//      * Private constructor to avoid user implement as a single instance instead of a Singleton
//      */
//     private LogUtils() {
// 
//     }
// 
//     /**
//      * Logs a error exception
//      *
//      * @param enclosingClass the caller class
//      * @param exception      the exception
//      */
//     public static void logErrorException(@NonNull Class<?> enclosingClass, @NonNull Throwable exception) {
//         String message = exception.getMessage() == null ? "Exception error." : exception.getMessage();
//         Log.e(enclosingClass.getName(), message, exception);
//     }
// 
// }
// Path: adal-adapters/src/main/java/com/massivedisaster/adal/adapter/FragmentPagerAdapter.java
import com.massivedisaster.adal.utils.LogUtils;
import java.util.List;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.util.SparseArray;
/*
 * ADAL - A set of Android libraries to help speed up Android development.
 *
 * Copyright (c) 2017 ADAL
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package com.massivedisaster.adal.adapter;
/**
 * The adapter of fragments.
 */
public class FragmentPagerAdapter extends FragmentStatePagerAdapter {
    private final List<Class<? extends Fragment>> mLstFragments;
    private final SparseArray<Fragment> mFragmentSparseArray;
    /**
     * Constructor of the adapter.
     *
     * @param fm          The fragment manager.
     * @param lstFragment The list of fragments to be add to the adapter.
     */
    public FragmentPagerAdapter(FragmentManager fm, List<Class<? extends Fragment>> lstFragment) {
        super(fm);
        mLstFragments = lstFragment;
        mFragmentSparseArray = new SparseArray<>(lstFragment.size());
    }
    @Override
    public Fragment getItem(int position) {
        try {
            Fragment fragment = mFragmentSparseArray.get(position);
            if (fragment == null) {
                fragment = mLstFragments.get(position).newInstance();
                mFragmentSparseArray.put(position, fragment);
                fragment.setRetainInstance(true);
            }
            return fragment;
        } catch (InstantiationException e) { | 
	            LogUtils.logErrorException(FragmentPagerAdapter.class, e); | 
| 
	massivedisaster/ADAL | 
	adal-location/src/main/java/com/massivedisaster/location/LocationManager.java | 
	// Path: adal-location/src/main/java/com/massivedisaster/location/listener/OnLocationManager.java
// public interface OnLocationManager {
// 
//     /**
//      * Called if location manager retrieve the user position
//      *
//      * @param location           The user location
//      * @param isLastKnowLocation True if a location its given from the last know position
//      */
//     void onLocationFound(Location location, boolean isLastKnowLocation);
// 
//     /**
//      * Called if the request gives an error
//      *
//      * @param locationError The location error
//      */
//     void onLocationError(LocationError locationError);
// 
//     /**
//      * Called if user don't permissions to get location
//      */
//     void onPermissionsDenied();
// 
//     /**
//      * Called if provider is enabled
//      */
//     void onProviderEnabled();
// 
//     /**
//      * Called if provider is disabled
//      */
//     void onProviderDisabled();
// 
//     /**
//      * Called if location manager stop request update
//      */
//     void onStopRequestUpdate();
// }
// 
// Path: adal-location/src/main/java/com/massivedisaster/location/utils/LocationError.java
// public enum LocationError {
//     TIMEOUT,
//     DISABLED,
//     REQUEST_NEEDED,
//     REQUEST_UPDATES_ENABLED
// }
 | 
	import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.ResolvableApiException;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationSettingsResponse;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.massivedisaster.location.listener.OnLocationManager;
import com.massivedisaster.location.utils.LocationError;
import android.content.IntentSender;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.util.Log; | 
	/*
 * ADAL - A set of Android libraries to help speed up Android development.
 *
 * Copyright (c) 2017 ADAL
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package com.massivedisaster.location;
/**
 * LocationManager requests single or multiple device locations.
 */
public class LocationManager extends AbstractLocationManager {
    private static final long DEFAULT_TIMEOUT_LOCATION = 20000;
    private static final long REQUEST_LOCATION_INTERVAL = 1000;
    protected LocationRequest mLocationRequest;
    protected boolean mRequestingLocationUpdates;
    /**
     * Request a single user location
     *
     * @param lastKnowLocation  if you want to get last know location in case of timeout
     * @param onLocationManager callback
     */ | 
	// Path: adal-location/src/main/java/com/massivedisaster/location/listener/OnLocationManager.java
// public interface OnLocationManager {
// 
//     /**
//      * Called if location manager retrieve the user position
//      *
//      * @param location           The user location
//      * @param isLastKnowLocation True if a location its given from the last know position
//      */
//     void onLocationFound(Location location, boolean isLastKnowLocation);
// 
//     /**
//      * Called if the request gives an error
//      *
//      * @param locationError The location error
//      */
//     void onLocationError(LocationError locationError);
// 
//     /**
//      * Called if user don't permissions to get location
//      */
//     void onPermissionsDenied();
// 
//     /**
//      * Called if provider is enabled
//      */
//     void onProviderEnabled();
// 
//     /**
//      * Called if provider is disabled
//      */
//     void onProviderDisabled();
// 
//     /**
//      * Called if location manager stop request update
//      */
//     void onStopRequestUpdate();
// }
// 
// Path: adal-location/src/main/java/com/massivedisaster/location/utils/LocationError.java
// public enum LocationError {
//     TIMEOUT,
//     DISABLED,
//     REQUEST_NEEDED,
//     REQUEST_UPDATES_ENABLED
// }
// Path: adal-location/src/main/java/com/massivedisaster/location/LocationManager.java
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.ResolvableApiException;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationSettingsResponse;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.massivedisaster.location.listener.OnLocationManager;
import com.massivedisaster.location.utils.LocationError;
import android.content.IntentSender;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.util.Log;
/*
 * ADAL - A set of Android libraries to help speed up Android development.
 *
 * Copyright (c) 2017 ADAL
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package com.massivedisaster.location;
/**
 * LocationManager requests single or multiple device locations.
 */
public class LocationManager extends AbstractLocationManager {
    private static final long DEFAULT_TIMEOUT_LOCATION = 20000;
    private static final long REQUEST_LOCATION_INTERVAL = 1000;
    protected LocationRequest mLocationRequest;
    protected boolean mRequestingLocationUpdates;
    /**
     * Request a single user location
     *
     * @param lastKnowLocation  if you want to get last know location in case of timeout
     * @param onLocationManager callback
     */ | 
	    public void requestSingleLocation(boolean lastKnowLocation, OnLocationManager onLocationManager) { | 
| 
	massivedisaster/ADAL | 
	adal-location/src/main/java/com/massivedisaster/location/LocationManager.java | 
	// Path: adal-location/src/main/java/com/massivedisaster/location/listener/OnLocationManager.java
// public interface OnLocationManager {
// 
//     /**
//      * Called if location manager retrieve the user position
//      *
//      * @param location           The user location
//      * @param isLastKnowLocation True if a location its given from the last know position
//      */
//     void onLocationFound(Location location, boolean isLastKnowLocation);
// 
//     /**
//      * Called if the request gives an error
//      *
//      * @param locationError The location error
//      */
//     void onLocationError(LocationError locationError);
// 
//     /**
//      * Called if user don't permissions to get location
//      */
//     void onPermissionsDenied();
// 
//     /**
//      * Called if provider is enabled
//      */
//     void onProviderEnabled();
// 
//     /**
//      * Called if provider is disabled
//      */
//     void onProviderDisabled();
// 
//     /**
//      * Called if location manager stop request update
//      */
//     void onStopRequestUpdate();
// }
// 
// Path: adal-location/src/main/java/com/massivedisaster/location/utils/LocationError.java
// public enum LocationError {
//     TIMEOUT,
//     DISABLED,
//     REQUEST_NEEDED,
//     REQUEST_UPDATES_ENABLED
// }
 | 
	import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.ResolvableApiException;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationSettingsResponse;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.massivedisaster.location.listener.OnLocationManager;
import com.massivedisaster.location.utils.LocationError;
import android.content.IntentSender;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.util.Log; | 
	/*
 * ADAL - A set of Android libraries to help speed up Android development.
 *
 * Copyright (c) 2017 ADAL
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package com.massivedisaster.location;
/**
 * LocationManager requests single or multiple device locations.
 */
public class LocationManager extends AbstractLocationManager {
    private static final long DEFAULT_TIMEOUT_LOCATION = 20000;
    private static final long REQUEST_LOCATION_INTERVAL = 1000;
    protected LocationRequest mLocationRequest;
    protected boolean mRequestingLocationUpdates;
    /**
     * Request a single user location
     *
     * @param lastKnowLocation  if you want to get last know location in case of timeout
     * @param onLocationManager callback
     */
    public void requestSingleLocation(boolean lastKnowLocation, OnLocationManager onLocationManager) {
        requestSingleLocation(lastKnowLocation, DEFAULT_TIMEOUT_LOCATION, onLocationManager);
    }
    /**
     * Request a single user location with a custom timeout
     *
     * @param lastKnowLocation  if you want to get last know location in case of timeout
     * @param timeOut           to get the user location
     * @param onLocationManager callback
     */
    public void requestSingleLocation(boolean lastKnowLocation, long timeOut, OnLocationManager onLocationManager) {
        if (mRequestingLocationUpdates && onLocationManager != null) { | 
	// Path: adal-location/src/main/java/com/massivedisaster/location/listener/OnLocationManager.java
// public interface OnLocationManager {
// 
//     /**
//      * Called if location manager retrieve the user position
//      *
//      * @param location           The user location
//      * @param isLastKnowLocation True if a location its given from the last know position
//      */
//     void onLocationFound(Location location, boolean isLastKnowLocation);
// 
//     /**
//      * Called if the request gives an error
//      *
//      * @param locationError The location error
//      */
//     void onLocationError(LocationError locationError);
// 
//     /**
//      * Called if user don't permissions to get location
//      */
//     void onPermissionsDenied();
// 
//     /**
//      * Called if provider is enabled
//      */
//     void onProviderEnabled();
// 
//     /**
//      * Called if provider is disabled
//      */
//     void onProviderDisabled();
// 
//     /**
//      * Called if location manager stop request update
//      */
//     void onStopRequestUpdate();
// }
// 
// Path: adal-location/src/main/java/com/massivedisaster/location/utils/LocationError.java
// public enum LocationError {
//     TIMEOUT,
//     DISABLED,
//     REQUEST_NEEDED,
//     REQUEST_UPDATES_ENABLED
// }
// Path: adal-location/src/main/java/com/massivedisaster/location/LocationManager.java
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.ResolvableApiException;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationSettingsResponse;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.massivedisaster.location.listener.OnLocationManager;
import com.massivedisaster.location.utils.LocationError;
import android.content.IntentSender;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.util.Log;
/*
 * ADAL - A set of Android libraries to help speed up Android development.
 *
 * Copyright (c) 2017 ADAL
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package com.massivedisaster.location;
/**
 * LocationManager requests single or multiple device locations.
 */
public class LocationManager extends AbstractLocationManager {
    private static final long DEFAULT_TIMEOUT_LOCATION = 20000;
    private static final long REQUEST_LOCATION_INTERVAL = 1000;
    protected LocationRequest mLocationRequest;
    protected boolean mRequestingLocationUpdates;
    /**
     * Request a single user location
     *
     * @param lastKnowLocation  if you want to get last know location in case of timeout
     * @param onLocationManager callback
     */
    public void requestSingleLocation(boolean lastKnowLocation, OnLocationManager onLocationManager) {
        requestSingleLocation(lastKnowLocation, DEFAULT_TIMEOUT_LOCATION, onLocationManager);
    }
    /**
     * Request a single user location with a custom timeout
     *
     * @param lastKnowLocation  if you want to get last know location in case of timeout
     * @param timeOut           to get the user location
     * @param onLocationManager callback
     */
    public void requestSingleLocation(boolean lastKnowLocation, long timeOut, OnLocationManager onLocationManager) {
        if (mRequestingLocationUpdates && onLocationManager != null) { | 
	            onLocationManager.onLocationError(LocationError.REQUEST_UPDATES_ENABLED); | 
| 
	massivedisaster/ADAL | 
	adal-permissions/src/main/java/com/massivedisaster/adal/permissions/PermissionUtils.java | 
	// Path: adal-utils/src/main/java/com/massivedisaster/adal/utils/LogUtils.java
// public final class LogUtils {
// 
//     /**
//      * Private constructor to avoid user implement as a single instance instead of a Singleton
//      */
//     private LogUtils() {
// 
//     }
// 
//     /**
//      * Logs a error exception
//      *
//      * @param enclosingClass the caller class
//      * @param exception      the exception
//      */
//     public static void logErrorException(@NonNull Class<?> enclosingClass, @NonNull Throwable exception) {
//         String message = exception.getMessage() == null ? "Exception error." : exception.getMessage();
//         Log.e(enclosingClass.getName(), message, exception);
//     }
// 
// }
 | 
	import com.massivedisaster.adal.utils.LogUtils;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat; | 
	/*
 * ADAL - A set of Android libraries to help speed up Android development.
 *
 * Copyright (c) 2017 ADAL
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package com.massivedisaster.adal.permissions;
/**
 * Permissions utilities.
 */
public final class PermissionUtils {
    /**
     * Private constructor to avoid user implement as a single instance instead of a Singleton.
     */
    private PermissionUtils() {
    }
    /**
     * Verify if all permissions given are granted
     *
     * @param context     the application context
     * @param permissions one or more permission to check
     * @return true if all permissions are granted
     */
    public static boolean hasPermissions(Context context, String... permissions) {
        if (permissions == null || permissions.length == 0) {
            return false;
        }
        for (String permission : permissions) {
            if ((ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED)) {
                return false;
            }
        }
        return true;
    }
    /**
     * Verify if the permission given are added on manifest
     *
     * @param context    the application context
     * @param permission the permission to check
     * @return true if permission are added on manifest
     */
    public static boolean hasPermissionInManifest(Context context, String permission) {
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_PERMISSIONS);
            if (info.requestedPermissions != null) {
                for (String p : info.requestedPermissions) {
                    if (p.equals(permission)) {
                        return true;
                    }
                }
            }
        } catch (PackageManager.NameNotFoundException e) { | 
	// Path: adal-utils/src/main/java/com/massivedisaster/adal/utils/LogUtils.java
// public final class LogUtils {
// 
//     /**
//      * Private constructor to avoid user implement as a single instance instead of a Singleton
//      */
//     private LogUtils() {
// 
//     }
// 
//     /**
//      * Logs a error exception
//      *
//      * @param enclosingClass the caller class
//      * @param exception      the exception
//      */
//     public static void logErrorException(@NonNull Class<?> enclosingClass, @NonNull Throwable exception) {
//         String message = exception.getMessage() == null ? "Exception error." : exception.getMessage();
//         Log.e(enclosingClass.getName(), message, exception);
//     }
// 
// }
// Path: adal-permissions/src/main/java/com/massivedisaster/adal/permissions/PermissionUtils.java
import com.massivedisaster.adal.utils.LogUtils;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
/*
 * ADAL - A set of Android libraries to help speed up Android development.
 *
 * Copyright (c) 2017 ADAL
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package com.massivedisaster.adal.permissions;
/**
 * Permissions utilities.
 */
public final class PermissionUtils {
    /**
     * Private constructor to avoid user implement as a single instance instead of a Singleton.
     */
    private PermissionUtils() {
    }
    /**
     * Verify if all permissions given are granted
     *
     * @param context     the application context
     * @param permissions one or more permission to check
     * @return true if all permissions are granted
     */
    public static boolean hasPermissions(Context context, String... permissions) {
        if (permissions == null || permissions.length == 0) {
            return false;
        }
        for (String permission : permissions) {
            if ((ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED)) {
                return false;
            }
        }
        return true;
    }
    /**
     * Verify if the permission given are added on manifest
     *
     * @param context    the application context
     * @param permission the permission to check
     * @return true if permission are added on manifest
     */
    public static boolean hasPermissionInManifest(Context context, String permission) {
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_PERMISSIONS);
            if (info.requestedPermissions != null) {
                for (String p : info.requestedPermissions) {
                    if (p.equals(permission)) {
                        return true;
                    }
                }
            }
        } catch (PackageManager.NameNotFoundException e) { | 
	            LogUtils.logErrorException(PermissionUtils.class, e); | 
| 
	massivedisaster/ADAL | 
	adal-dialogs/src/main/java/com/massivedisaster/adal/dialogs/BaseDialogFragment.java | 
	// Path: adal-utils/src/main/java/com/massivedisaster/adal/utils/KeyboardUtils.java
// public final class KeyboardUtils {
// 
//     private static final int HIDE_SOFT_INPUT_FLAGS_NONE = 0;
// 
//     /**
//      * Private constructor to avoid user implement as a single instance instead of a Singleton
//      */
//     private KeyboardUtils() {
// 
//     }
// 
//     /**
//      * Show the keyboard
//      *
//      * @param context  the context
//      */
//     private static void show(Context context) {
//         InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
//         imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, HIDE_SOFT_INPUT_FLAGS_NONE);
//     }
// 
//     /**
//      * Hide keyboard
//      *
//      * @param activity the visible activity
//      */
//     public static void hide(Activity activity) {
//         internalHide(activity, activity.getCurrentFocus());
//     }
// 
//     /**
//      * Hide keyboard
//      *
//      * @param activity the visible activity
//      * @param view     view to get getWindowToken
//      */
//     public static void hide(Activity activity, View view) {
//         internalHide(activity, view);
//     }
// 
//     /**
//      *
//      *
//      * @param activity  context to retrieve system services
//      * @param view      view to get getWindowToken
//      */
//     private static void internalHide(Activity activity, View view) {
//         if (view != null) {
//             InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
//             imm.hideSoftInputFromWindow(view.getWindowToken(), HIDE_SOFT_INPUT_FLAGS_NONE);
//         }
//     }
// }
 | 
	import android.support.v7.app.AppCompatDialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import com.massivedisaster.adal.utils.KeyboardUtils;
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable; | 
	    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Dialog dialog = super.onCreateDialog(savedInstanceState);
        dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        return dialog;
    }
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = null;
        if (layoutToInflate() != INVALID_RESOURCE_ID) {
            view = inflater.inflate(layoutToInflate(), container, false);
            mView = view;
        }
        restoreInstanceState(savedInstanceState);
        if (getArguments() != null) {
            getFromBundle(getArguments());
        }
        doOnCreated();
        return view;
    }
    @Override
    public void onPause() { | 
	// Path: adal-utils/src/main/java/com/massivedisaster/adal/utils/KeyboardUtils.java
// public final class KeyboardUtils {
// 
//     private static final int HIDE_SOFT_INPUT_FLAGS_NONE = 0;
// 
//     /**
//      * Private constructor to avoid user implement as a single instance instead of a Singleton
//      */
//     private KeyboardUtils() {
// 
//     }
// 
//     /**
//      * Show the keyboard
//      *
//      * @param context  the context
//      */
//     private static void show(Context context) {
//         InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
//         imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, HIDE_SOFT_INPUT_FLAGS_NONE);
//     }
// 
//     /**
//      * Hide keyboard
//      *
//      * @param activity the visible activity
//      */
//     public static void hide(Activity activity) {
//         internalHide(activity, activity.getCurrentFocus());
//     }
// 
//     /**
//      * Hide keyboard
//      *
//      * @param activity the visible activity
//      * @param view     view to get getWindowToken
//      */
//     public static void hide(Activity activity, View view) {
//         internalHide(activity, view);
//     }
// 
//     /**
//      *
//      *
//      * @param activity  context to retrieve system services
//      * @param view      view to get getWindowToken
//      */
//     private static void internalHide(Activity activity, View view) {
//         if (view != null) {
//             InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
//             imm.hideSoftInputFromWindow(view.getWindowToken(), HIDE_SOFT_INPUT_FLAGS_NONE);
//         }
//     }
// }
// Path: adal-dialogs/src/main/java/com/massivedisaster/adal/dialogs/BaseDialogFragment.java
import android.support.v7.app.AppCompatDialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import com.massivedisaster.adal.utils.KeyboardUtils;
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Dialog dialog = super.onCreateDialog(savedInstanceState);
        dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        return dialog;
    }
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = null;
        if (layoutToInflate() != INVALID_RESOURCE_ID) {
            view = inflater.inflate(layoutToInflate(), container, false);
            mView = view;
        }
        restoreInstanceState(savedInstanceState);
        if (getArguments() != null) {
            getFromBundle(getArguments());
        }
        doOnCreated();
        return view;
    }
    @Override
    public void onPause() { | 
	        KeyboardUtils.hide(getActivity(), getView()); | 
| 
	massivedisaster/ADAL | 
	adal-alarm/src/main/java/com/massivedisaster/adal/alarm/AlarmManager.java | 
	// Path: adal-utils/src/main/java/com/massivedisaster/adal/utils/LogUtils.java
// public final class LogUtils {
// 
//     /**
//      * Private constructor to avoid user implement as a single instance instead of a Singleton
//      */
//     private LogUtils() {
// 
//     }
// 
//     /**
//      * Logs a error exception
//      *
//      * @param enclosingClass the caller class
//      * @param exception      the exception
//      */
//     public static void logErrorException(@NonNull Class<?> enclosingClass, @NonNull Throwable exception) {
//         String message = exception.getMessage() == null ? "Exception error." : exception.getMessage();
//         Log.e(enclosingClass.getName(), message, exception);
//     }
// 
// }
 | 
	import android.preference.PreferenceManager;
import com.massivedisaster.adal.utils.LogUtils;
import org.json.JSONArray;
import org.json.JSONException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build; | 
	     */
    private static void removeAlarmId(Context context, int id) {
        List<Integer> idsAlarms = getAlarmIds(context);
        for (int i = 0; i < idsAlarms.size(); i++) {
            if (idsAlarms.get(i) == id) {
                idsAlarms.remove(i);
            }
        }
        saveIdsInPreferences(context, idsAlarms);
    }
    /**
     * Get all alarms identifiers.
     *
     * @param context the context.
     * @return list of alarm identifiers.
     */
    private static List<Integer> getAlarmIds(Context context) {
        List<Integer> ids = new ArrayList<>();
        try {
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
            JSONArray jsonArray2 = new JSONArray(prefs.getString(context.getPackageName() + TAG_ALARMS, "[]"));
            for (int i = 0; i < jsonArray2.length(); i++) {
                ids.add(jsonArray2.getInt(i));
            }
        } catch (JSONException e) { | 
	// Path: adal-utils/src/main/java/com/massivedisaster/adal/utils/LogUtils.java
// public final class LogUtils {
// 
//     /**
//      * Private constructor to avoid user implement as a single instance instead of a Singleton
//      */
//     private LogUtils() {
// 
//     }
// 
//     /**
//      * Logs a error exception
//      *
//      * @param enclosingClass the caller class
//      * @param exception      the exception
//      */
//     public static void logErrorException(@NonNull Class<?> enclosingClass, @NonNull Throwable exception) {
//         String message = exception.getMessage() == null ? "Exception error." : exception.getMessage();
//         Log.e(enclosingClass.getName(), message, exception);
//     }
// 
// }
// Path: adal-alarm/src/main/java/com/massivedisaster/adal/alarm/AlarmManager.java
import android.preference.PreferenceManager;
import com.massivedisaster.adal.utils.LogUtils;
import org.json.JSONArray;
import org.json.JSONException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
     */
    private static void removeAlarmId(Context context, int id) {
        List<Integer> idsAlarms = getAlarmIds(context);
        for (int i = 0; i < idsAlarms.size(); i++) {
            if (idsAlarms.get(i) == id) {
                idsAlarms.remove(i);
            }
        }
        saveIdsInPreferences(context, idsAlarms);
    }
    /**
     * Get all alarms identifiers.
     *
     * @param context the context.
     * @return list of alarm identifiers.
     */
    private static List<Integer> getAlarmIds(Context context) {
        List<Integer> ids = new ArrayList<>();
        try {
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
            JSONArray jsonArray2 = new JSONArray(prefs.getString(context.getPackageName() + TAG_ALARMS, "[]"));
            for (int i = 0; i < jsonArray2.length(); i++) {
                ids.add(jsonArray2.getInt(i));
            }
        } catch (JSONException e) { | 
	            LogUtils.logErrorException(AlarmManager.class, e); | 
| 
	massivedisaster/ADAL | 
	sample/src/main/java/com/massivedisaster/adal/sample/feature/alarm/AlarmReceiver.java | 
	// Path: sample/src/main/java/com/massivedisaster/adal/sample/base/activity/ActivityFullScreen.java
// public class ActivityFullScreen extends AbstractFragmentActivity {
//     @Override
//     public int getLayoutResId() {
//         return R.layout.activity_fullscreen;
//     }
// 
//     @Override
//     public int getContainerViewId() {
//         return R.id.frmContainer;
//     }
// }
 | 
	import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import com.massivedisaster.adal.sample.R;
import com.massivedisaster.adal.sample.base.activity.ActivityFullScreen;
import static android.R.attr.id;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent; | 
	/*
 * ADAL - A set of Android libraries to help speed up Android development.
 *
 * Copyright (c) 2017 ADAL
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package com.massivedisaster.adal.sample.feature.alarm;
public class AlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) { | 
	// Path: sample/src/main/java/com/massivedisaster/adal/sample/base/activity/ActivityFullScreen.java
// public class ActivityFullScreen extends AbstractFragmentActivity {
//     @Override
//     public int getLayoutResId() {
//         return R.layout.activity_fullscreen;
//     }
// 
//     @Override
//     public int getContainerViewId() {
//         return R.id.frmContainer;
//     }
// }
// Path: sample/src/main/java/com/massivedisaster/adal/sample/feature/alarm/AlarmReceiver.java
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import com.massivedisaster.adal.sample.R;
import com.massivedisaster.adal.sample.base.activity.ActivityFullScreen;
import static android.R.attr.id;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
/*
 * ADAL - A set of Android libraries to help speed up Android development.
 *
 * Copyright (c) 2017 ADAL
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package com.massivedisaster.adal.sample.feature.alarm;
public class AlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) { | 
	        Intent i = new Intent(context, ActivityFullScreen.class); | 
| 
	massivedisaster/ADAL | 
	adal-bus/src/main/java/com/massivedisaster/adal/bus/BangBus.java | 
	// Path: adal-utils/src/main/java/com/massivedisaster/adal/utils/LogUtils.java
// public final class LogUtils {
// 
//     /**
//      * Private constructor to avoid user implement as a single instance instead of a Singleton
//      */
//     private LogUtils() {
// 
//     }
// 
//     /**
//      * Logs a error exception
//      *
//      * @param enclosingClass the caller class
//      * @param exception      the exception
//      */
//     public static void logErrorException(@NonNull Class<?> enclosingClass, @NonNull Throwable exception) {
//         String message = exception.getMessage() == null ? "Exception error." : exception.getMessage();
//         Log.e(enclosingClass.getName(), message, exception);
//     }
// 
// }
 | 
	import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.annotation.NonNull;
import android.support.v4.content.LocalBroadcastManager;
import com.massivedisaster.adal.utils.LogUtils;
import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set; | 
	                        .registerReceiver(mBroadcastReceiver, new IntentFilter(filter));
            }
        }
        return this;
    }
    /**
     * Get a broadcast receiver for the <var>method</var>
     *
     * @param method the method to be analized.
     * @return s
     */
    @NonNull
    private BroadcastReceiver getBroadcastReceiver(final Method method) {
        return new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                try {
                    if (intent.hasExtra(ARGUMENT_DATA)) {
                        Object object = intent.getSerializableExtra(ARGUMENT_DATA);
                        method.setAccessible(true);
                        method.invoke(mObject, object);
                        method.setAccessible(false);
                    } else {
                        method.setAccessible(true);
                        method.invoke(mObject);
                        method.setAccessible(false);
                    }
                } catch (IllegalAccessException e) { | 
	// Path: adal-utils/src/main/java/com/massivedisaster/adal/utils/LogUtils.java
// public final class LogUtils {
// 
//     /**
//      * Private constructor to avoid user implement as a single instance instead of a Singleton
//      */
//     private LogUtils() {
// 
//     }
// 
//     /**
//      * Logs a error exception
//      *
//      * @param enclosingClass the caller class
//      * @param exception      the exception
//      */
//     public static void logErrorException(@NonNull Class<?> enclosingClass, @NonNull Throwable exception) {
//         String message = exception.getMessage() == null ? "Exception error." : exception.getMessage();
//         Log.e(enclosingClass.getName(), message, exception);
//     }
// 
// }
// Path: adal-bus/src/main/java/com/massivedisaster/adal/bus/BangBus.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.annotation.NonNull;
import android.support.v4.content.LocalBroadcastManager;
import com.massivedisaster.adal.utils.LogUtils;
import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
                        .registerReceiver(mBroadcastReceiver, new IntentFilter(filter));
            }
        }
        return this;
    }
    /**
     * Get a broadcast receiver for the <var>method</var>
     *
     * @param method the method to be analized.
     * @return s
     */
    @NonNull
    private BroadcastReceiver getBroadcastReceiver(final Method method) {
        return new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                try {
                    if (intent.hasExtra(ARGUMENT_DATA)) {
                        Object object = intent.getSerializableExtra(ARGUMENT_DATA);
                        method.setAccessible(true);
                        method.invoke(mObject, object);
                        method.setAccessible(false);
                    } else {
                        method.setAccessible(true);
                        method.invoke(mObject);
                        method.setAccessible(false);
                    }
                } catch (IllegalAccessException e) { | 
	                    LogUtils.logErrorException(BangBus.class, e); | 
| 
	massivedisaster/ADAL | 
	adal-network/src/main/java/com/massivedisaster/adal/network/APIRequestCallback.java | 
	// Path: adal-utils/src/main/java/com/massivedisaster/adal/utils/LogUtils.java
// public final class LogUtils {
// 
//     /**
//      * Private constructor to avoid user implement as a single instance instead of a Singleton
//      */
//     private LogUtils() {
// 
//     }
// 
//     /**
//      * Logs a error exception
//      *
//      * @param enclosingClass the caller class
//      * @param exception      the exception
//      */
//     public static void logErrorException(@NonNull Class<?> enclosingClass, @NonNull Throwable exception) {
//         String message = exception.getMessage() == null ? "Exception error." : exception.getMessage();
//         Log.e(enclosingClass.getName(), message, exception);
//     }
// 
// }
 | 
	import com.massivedisaster.adal.utils.LogUtils;
import java.io.IOException;
import java.lang.reflect.Field;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Converter;
import retrofit2.Response;
import android.annotation.SuppressLint;
import android.content.Context;
import android.net.ConnectivityManager;
import android.util.Log; | 
	/*
 * ADAL - A set of Android libraries to help speed up Android development.
 *
 * Copyright (c) 2017 ADAL
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package com.massivedisaster.adal.network;
/**
 * Base request API callbacks.
 *
 * @param <T> the type of the data in the requests.
 */
public abstract class APIRequestCallback<T extends APIErrorListener> implements Callback<T> {
    private final Context mContext;
    /**
     * Constructcs {@link APIRequestCallback}
     *
     * @param context the context.
     */
    public APIRequestCallback(Context context) {
        mContext = context;
    }
    /**
     * @param t response
     */
    public abstract void onSuccess(T t);
    /**
     * @param error         the error.
     * @param isServerError is a server error.
     */
    public abstract void onError(APIError error, boolean isServerError);
    /**
     * Called when response ends.
     *
     * @param call     the call.
     * @param response the response.
     */
    @Override
    public void onResponse(Call<T> call, Response<T> response) {
        if (call.isCanceled()) {
            return;
        }
        if (response == null) {
            processError(new APIError(mContext.getString(R.string.error_network_general)), true);
            return;
        }
        if (response.errorBody() != null) {
            try {
                Converter<ResponseBody, T> errorConverter = getRetrofitConverter(call);
                T error = errorConverter.convert(response.errorBody());
                if (error != null) {
                    processError(new APIError(error.getErrorCode(), error.getError()), true);
                    return;
                }
            } catch (IllegalAccessException e) { | 
	// Path: adal-utils/src/main/java/com/massivedisaster/adal/utils/LogUtils.java
// public final class LogUtils {
// 
//     /**
//      * Private constructor to avoid user implement as a single instance instead of a Singleton
//      */
//     private LogUtils() {
// 
//     }
// 
//     /**
//      * Logs a error exception
//      *
//      * @param enclosingClass the caller class
//      * @param exception      the exception
//      */
//     public static void logErrorException(@NonNull Class<?> enclosingClass, @NonNull Throwable exception) {
//         String message = exception.getMessage() == null ? "Exception error." : exception.getMessage();
//         Log.e(enclosingClass.getName(), message, exception);
//     }
// 
// }
// Path: adal-network/src/main/java/com/massivedisaster/adal/network/APIRequestCallback.java
import com.massivedisaster.adal.utils.LogUtils;
import java.io.IOException;
import java.lang.reflect.Field;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Converter;
import retrofit2.Response;
import android.annotation.SuppressLint;
import android.content.Context;
import android.net.ConnectivityManager;
import android.util.Log;
/*
 * ADAL - A set of Android libraries to help speed up Android development.
 *
 * Copyright (c) 2017 ADAL
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package com.massivedisaster.adal.network;
/**
 * Base request API callbacks.
 *
 * @param <T> the type of the data in the requests.
 */
public abstract class APIRequestCallback<T extends APIErrorListener> implements Callback<T> {
    private final Context mContext;
    /**
     * Constructcs {@link APIRequestCallback}
     *
     * @param context the context.
     */
    public APIRequestCallback(Context context) {
        mContext = context;
    }
    /**
     * @param t response
     */
    public abstract void onSuccess(T t);
    /**
     * @param error         the error.
     * @param isServerError is a server error.
     */
    public abstract void onError(APIError error, boolean isServerError);
    /**
     * Called when response ends.
     *
     * @param call     the call.
     * @param response the response.
     */
    @Override
    public void onResponse(Call<T> call, Response<T> response) {
        if (call.isCanceled()) {
            return;
        }
        if (response == null) {
            processError(new APIError(mContext.getString(R.string.error_network_general)), true);
            return;
        }
        if (response.errorBody() != null) {
            try {
                Converter<ResponseBody, T> errorConverter = getRetrofitConverter(call);
                T error = errorConverter.convert(response.errorBody());
                if (error != null) {
                    processError(new APIError(error.getErrorCode(), error.getError()), true);
                    return;
                }
            } catch (IllegalAccessException e) { | 
	                LogUtils.logErrorException(APIRequestCallback.class, e); | 
| 
	massivedisaster/ADAL | 
	adal-fragments/src/main/java/com/massivedisaster/adal/fragment/BaseFragment.java | 
	// Path: adal-utils/src/main/java/com/massivedisaster/adal/utils/KeyboardUtils.java
// public final class KeyboardUtils {
// 
//     private static final int HIDE_SOFT_INPUT_FLAGS_NONE = 0;
// 
//     /**
//      * Private constructor to avoid user implement as a single instance instead of a Singleton
//      */
//     private KeyboardUtils() {
// 
//     }
// 
//     /**
//      * Show the keyboard
//      *
//      * @param context  the context
//      */
//     private static void show(Context context) {
//         InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
//         imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, HIDE_SOFT_INPUT_FLAGS_NONE);
//     }
// 
//     /**
//      * Hide keyboard
//      *
//      * @param activity the visible activity
//      */
//     public static void hide(Activity activity) {
//         internalHide(activity, activity.getCurrentFocus());
//     }
// 
//     /**
//      * Hide keyboard
//      *
//      * @param activity the visible activity
//      * @param view     view to get getWindowToken
//      */
//     public static void hide(Activity activity, View view) {
//         internalHide(activity, view);
//     }
// 
//     /**
//      *
//      *
//      * @param activity  context to retrieve system services
//      * @param view      view to get getWindowToken
//      */
//     private static void internalHide(Activity activity, View view) {
//         if (view != null) {
//             InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
//             imm.hideSoftInputFromWindow(view.getWindowToken(), HIDE_SOFT_INPUT_FLAGS_NONE);
//         }
//     }
// }
 | 
	import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import com.massivedisaster.adal.utils.KeyboardUtils;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable; | 
	    protected <T extends View> T findViewByIdOnActivity(@IdRes int viewId) {
        Activity activity = getActivity();
        if (activity == null) {
            return null;
        }
        return (T) activity.findViewById(viewId);
    }
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = null;
        if (layoutToInflate() != INVALID_RESOURCE_ID) {
            view = inflater.inflate(layoutToInflate(), container, false);
            mView = view;
        }
        restoreInstanceState(savedInstanceState);
        if (getArguments() != null) {
            getFromBundle(getArguments());
        }
        doOnCreated();
        return view;
    }
    @Override
    public void onPause() { | 
	// Path: adal-utils/src/main/java/com/massivedisaster/adal/utils/KeyboardUtils.java
// public final class KeyboardUtils {
// 
//     private static final int HIDE_SOFT_INPUT_FLAGS_NONE = 0;
// 
//     /**
//      * Private constructor to avoid user implement as a single instance instead of a Singleton
//      */
//     private KeyboardUtils() {
// 
//     }
// 
//     /**
//      * Show the keyboard
//      *
//      * @param context  the context
//      */
//     private static void show(Context context) {
//         InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
//         imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, HIDE_SOFT_INPUT_FLAGS_NONE);
//     }
// 
//     /**
//      * Hide keyboard
//      *
//      * @param activity the visible activity
//      */
//     public static void hide(Activity activity) {
//         internalHide(activity, activity.getCurrentFocus());
//     }
// 
//     /**
//      * Hide keyboard
//      *
//      * @param activity the visible activity
//      * @param view     view to get getWindowToken
//      */
//     public static void hide(Activity activity, View view) {
//         internalHide(activity, view);
//     }
// 
//     /**
//      *
//      *
//      * @param activity  context to retrieve system services
//      * @param view      view to get getWindowToken
//      */
//     private static void internalHide(Activity activity, View view) {
//         if (view != null) {
//             InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
//             imm.hideSoftInputFromWindow(view.getWindowToken(), HIDE_SOFT_INPUT_FLAGS_NONE);
//         }
//     }
// }
// Path: adal-fragments/src/main/java/com/massivedisaster/adal/fragment/BaseFragment.java
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import com.massivedisaster.adal.utils.KeyboardUtils;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
    protected <T extends View> T findViewByIdOnActivity(@IdRes int viewId) {
        Activity activity = getActivity();
        if (activity == null) {
            return null;
        }
        return (T) activity.findViewById(viewId);
    }
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = null;
        if (layoutToInflate() != INVALID_RESOURCE_ID) {
            view = inflater.inflate(layoutToInflate(), container, false);
            mView = view;
        }
        restoreInstanceState(savedInstanceState);
        if (getArguments() != null) {
            getFromBundle(getArguments());
        }
        doOnCreated();
        return view;
    }
    @Override
    public void onPause() { | 
	        KeyboardUtils.hide(getActivity(), getView()); | 
| 
	massivedisaster/ADAL | 
	adal-location/src/main/java/com/massivedisaster/location/listener/OnLocationManager.java | 
	// Path: adal-location/src/main/java/com/massivedisaster/location/utils/LocationError.java
// public enum LocationError {
//     TIMEOUT,
//     DISABLED,
//     REQUEST_NEEDED,
//     REQUEST_UPDATES_ENABLED
// }
 | 
	import android.location.Location;
import com.massivedisaster.location.utils.LocationError; | 
	/*
 * ADAL - A set of Android libraries to help speed up Android development.
 * Copyright (C) 2017 ADAL.
 *
 * ADAL is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 3 of the License, or any later version.
 *
 * ADAL is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Lesser General Public License along
 * with ADAL. If not, see <http://www.gnu.org/licenses/>.
 */
package com.massivedisaster.location.listener;
/**
 * Manages location.
 */
public interface OnLocationManager {
    /**
     * Called if location manager retrieve the user position
     *
     * @param location           The user location
     * @param isLastKnowLocation True if a location its given from the last know position
     */
    void onLocationFound(Location location, boolean isLastKnowLocation);
    /**
     * Called if the request gives an error
     *
     * @param locationError The location error
     */ | 
	// Path: adal-location/src/main/java/com/massivedisaster/location/utils/LocationError.java
// public enum LocationError {
//     TIMEOUT,
//     DISABLED,
//     REQUEST_NEEDED,
//     REQUEST_UPDATES_ENABLED
// }
// Path: adal-location/src/main/java/com/massivedisaster/location/listener/OnLocationManager.java
import android.location.Location;
import com.massivedisaster.location.utils.LocationError;
/*
 * ADAL - A set of Android libraries to help speed up Android development.
 * Copyright (C) 2017 ADAL.
 *
 * ADAL is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 3 of the License, or any later version.
 *
 * ADAL is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Lesser General Public License along
 * with ADAL. If not, see <http://www.gnu.org/licenses/>.
 */
package com.massivedisaster.location.listener;
/**
 * Manages location.
 */
public interface OnLocationManager {
    /**
     * Called if location manager retrieve the user position
     *
     * @param location           The user location
     * @param isLastKnowLocation True if a location its given from the last know position
     */
    void onLocationFound(Location location, boolean isLastKnowLocation);
    /**
     * Called if the request gives an error
     *
     * @param locationError The location error
     */ | 
	    void onLocationError(LocationError locationError); | 
| 
	massivedisaster/ADAL | 
	sample/src/main/java/com/massivedisaster/adal/sample/network/IRequests.java | 
	// Path: sample/src/main/java/com/massivedisaster/adal/sample/model/Photo.java
// public class Photo {
// 
//     @SerializedName("albumId")
//     private int mUserId;
//     @SerializedName("id")
//     private int mId;
//     @SerializedName("title")
//     private String mTitle;
//     @SerializedName("url")
//     private String mUrl;
//     @SerializedName("thumbnailUrl")
//     private String mThumbnailUrl;
// 
//     public int getUserId() {
//         return mUserId;
//     }
// 
//     public void setUserId(int userId) {
//         this.mUserId = userId;
//     }
// 
//     public int getId() {
//         return mId;
//     }
// 
//     public void setId(int id) {
//         this.mId = id;
//     }
// 
//     public String getTitle() {
//         return mTitle;
//     }
// 
//     public void setTitle(String title) {
//         this.mTitle = title;
//     }
// 
//     public String getUrl() {
//         return mUrl;
//     }
// 
//     public void setUrl(String url) {
//         this.mUrl = url;
//     }
// 
//     public String getThumbnailUrl() {
//         return mThumbnailUrl;
//     }
// 
//     public void setThumbnailUrl(String thumbnailUrl) {
//         this.mThumbnailUrl = thumbnailUrl;
//     }
// }
// 
// Path: sample/src/main/java/com/massivedisaster/adal/sample/model/Post.java
// public class Post {
// 
//     @SerializedName("userId")
//     private int mUserId;
//     @SerializedName("id")
//     private int mId;
//     @SerializedName("title")
//     private String mTitle;
//     @SerializedName("body")
//     private String mBody;
// 
//     public int getUserId() {
//         return mUserId;
//     }
// 
//     public void setUserId(int userId) {
//         this.mUserId = userId;
//     }
// 
//     public int getId() {
//         return mId;
//     }
// 
//     public void setId(int id) {
//         this.mId = id;
//     }
// 
//     public String getTitle() {
//         return mTitle;
//     }
// 
//     public void setTitle(String title) {
//         this.mTitle = title;
//     }
// 
//     public String getBody() {
//         return mBody;
//     }
// 
//     public void setBody(String body) {
//         this.mBody = body;
//     }
// }
 | 
	import com.massivedisaster.adal.sample.model.Photo;
import com.massivedisaster.adal.sample.model.Post;
import retrofit2.Call;
import retrofit2.http.GET; | 
	/*
 * ADAL - A set of Android libraries to help speed up Android development.
 *
 * Copyright (c) 2017 ADAL
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package com.massivedisaster.adal.sample.network;
public interface IRequests {
    @GET("posts") | 
	// Path: sample/src/main/java/com/massivedisaster/adal/sample/model/Photo.java
// public class Photo {
// 
//     @SerializedName("albumId")
//     private int mUserId;
//     @SerializedName("id")
//     private int mId;
//     @SerializedName("title")
//     private String mTitle;
//     @SerializedName("url")
//     private String mUrl;
//     @SerializedName("thumbnailUrl")
//     private String mThumbnailUrl;
// 
//     public int getUserId() {
//         return mUserId;
//     }
// 
//     public void setUserId(int userId) {
//         this.mUserId = userId;
//     }
// 
//     public int getId() {
//         return mId;
//     }
// 
//     public void setId(int id) {
//         this.mId = id;
//     }
// 
//     public String getTitle() {
//         return mTitle;
//     }
// 
//     public void setTitle(String title) {
//         this.mTitle = title;
//     }
// 
//     public String getUrl() {
//         return mUrl;
//     }
// 
//     public void setUrl(String url) {
//         this.mUrl = url;
//     }
// 
//     public String getThumbnailUrl() {
//         return mThumbnailUrl;
//     }
// 
//     public void setThumbnailUrl(String thumbnailUrl) {
//         this.mThumbnailUrl = thumbnailUrl;
//     }
// }
// 
// Path: sample/src/main/java/com/massivedisaster/adal/sample/model/Post.java
// public class Post {
// 
//     @SerializedName("userId")
//     private int mUserId;
//     @SerializedName("id")
//     private int mId;
//     @SerializedName("title")
//     private String mTitle;
//     @SerializedName("body")
//     private String mBody;
// 
//     public int getUserId() {
//         return mUserId;
//     }
// 
//     public void setUserId(int userId) {
//         this.mUserId = userId;
//     }
// 
//     public int getId() {
//         return mId;
//     }
// 
//     public void setId(int id) {
//         this.mId = id;
//     }
// 
//     public String getTitle() {
//         return mTitle;
//     }
// 
//     public void setTitle(String title) {
//         this.mTitle = title;
//     }
// 
//     public String getBody() {
//         return mBody;
//     }
// 
//     public void setBody(String body) {
//         this.mBody = body;
//     }
// }
// Path: sample/src/main/java/com/massivedisaster/adal/sample/network/IRequests.java
import com.massivedisaster.adal.sample.model.Photo;
import com.massivedisaster.adal.sample.model.Post;
import retrofit2.Call;
import retrofit2.http.GET;
/*
 * ADAL - A set of Android libraries to help speed up Android development.
 *
 * Copyright (c) 2017 ADAL
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package com.massivedisaster.adal.sample.network;
public interface IRequests {
    @GET("posts") | 
	    Call<ResponseList<Post>> getPosts(); | 
| 
	massivedisaster/ADAL | 
	sample/src/main/java/com/massivedisaster/adal/sample/network/IRequests.java | 
	// Path: sample/src/main/java/com/massivedisaster/adal/sample/model/Photo.java
// public class Photo {
// 
//     @SerializedName("albumId")
//     private int mUserId;
//     @SerializedName("id")
//     private int mId;
//     @SerializedName("title")
//     private String mTitle;
//     @SerializedName("url")
//     private String mUrl;
//     @SerializedName("thumbnailUrl")
//     private String mThumbnailUrl;
// 
//     public int getUserId() {
//         return mUserId;
//     }
// 
//     public void setUserId(int userId) {
//         this.mUserId = userId;
//     }
// 
//     public int getId() {
//         return mId;
//     }
// 
//     public void setId(int id) {
//         this.mId = id;
//     }
// 
//     public String getTitle() {
//         return mTitle;
//     }
// 
//     public void setTitle(String title) {
//         this.mTitle = title;
//     }
// 
//     public String getUrl() {
//         return mUrl;
//     }
// 
//     public void setUrl(String url) {
//         this.mUrl = url;
//     }
// 
//     public String getThumbnailUrl() {
//         return mThumbnailUrl;
//     }
// 
//     public void setThumbnailUrl(String thumbnailUrl) {
//         this.mThumbnailUrl = thumbnailUrl;
//     }
// }
// 
// Path: sample/src/main/java/com/massivedisaster/adal/sample/model/Post.java
// public class Post {
// 
//     @SerializedName("userId")
//     private int mUserId;
//     @SerializedName("id")
//     private int mId;
//     @SerializedName("title")
//     private String mTitle;
//     @SerializedName("body")
//     private String mBody;
// 
//     public int getUserId() {
//         return mUserId;
//     }
// 
//     public void setUserId(int userId) {
//         this.mUserId = userId;
//     }
// 
//     public int getId() {
//         return mId;
//     }
// 
//     public void setId(int id) {
//         this.mId = id;
//     }
// 
//     public String getTitle() {
//         return mTitle;
//     }
// 
//     public void setTitle(String title) {
//         this.mTitle = title;
//     }
// 
//     public String getBody() {
//         return mBody;
//     }
// 
//     public void setBody(String body) {
//         this.mBody = body;
//     }
// }
 | 
	import com.massivedisaster.adal.sample.model.Photo;
import com.massivedisaster.adal.sample.model.Post;
import retrofit2.Call;
import retrofit2.http.GET; | 
	/*
 * ADAL - A set of Android libraries to help speed up Android development.
 *
 * Copyright (c) 2017 ADAL
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package com.massivedisaster.adal.sample.network;
public interface IRequests {
    @GET("posts")
    Call<ResponseList<Post>> getPosts();
    @GET("albums/1/photos") | 
	// Path: sample/src/main/java/com/massivedisaster/adal/sample/model/Photo.java
// public class Photo {
// 
//     @SerializedName("albumId")
//     private int mUserId;
//     @SerializedName("id")
//     private int mId;
//     @SerializedName("title")
//     private String mTitle;
//     @SerializedName("url")
//     private String mUrl;
//     @SerializedName("thumbnailUrl")
//     private String mThumbnailUrl;
// 
//     public int getUserId() {
//         return mUserId;
//     }
// 
//     public void setUserId(int userId) {
//         this.mUserId = userId;
//     }
// 
//     public int getId() {
//         return mId;
//     }
// 
//     public void setId(int id) {
//         this.mId = id;
//     }
// 
//     public String getTitle() {
//         return mTitle;
//     }
// 
//     public void setTitle(String title) {
//         this.mTitle = title;
//     }
// 
//     public String getUrl() {
//         return mUrl;
//     }
// 
//     public void setUrl(String url) {
//         this.mUrl = url;
//     }
// 
//     public String getThumbnailUrl() {
//         return mThumbnailUrl;
//     }
// 
//     public void setThumbnailUrl(String thumbnailUrl) {
//         this.mThumbnailUrl = thumbnailUrl;
//     }
// }
// 
// Path: sample/src/main/java/com/massivedisaster/adal/sample/model/Post.java
// public class Post {
// 
//     @SerializedName("userId")
//     private int mUserId;
//     @SerializedName("id")
//     private int mId;
//     @SerializedName("title")
//     private String mTitle;
//     @SerializedName("body")
//     private String mBody;
// 
//     public int getUserId() {
//         return mUserId;
//     }
// 
//     public void setUserId(int userId) {
//         this.mUserId = userId;
//     }
// 
//     public int getId() {
//         return mId;
//     }
// 
//     public void setId(int id) {
//         this.mId = id;
//     }
// 
//     public String getTitle() {
//         return mTitle;
//     }
// 
//     public void setTitle(String title) {
//         this.mTitle = title;
//     }
// 
//     public String getBody() {
//         return mBody;
//     }
// 
//     public void setBody(String body) {
//         this.mBody = body;
//     }
// }
// Path: sample/src/main/java/com/massivedisaster/adal/sample/network/IRequests.java
import com.massivedisaster.adal.sample.model.Photo;
import com.massivedisaster.adal.sample.model.Post;
import retrofit2.Call;
import retrofit2.http.GET;
/*
 * ADAL - A set of Android libraries to help speed up Android development.
 *
 * Copyright (c) 2017 ADAL
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package com.massivedisaster.adal.sample.network;
public interface IRequests {
    @GET("posts")
    Call<ResponseList<Post>> getPosts();
    @GET("albums/1/photos") | 
	    Call<ResponseList<Photo>> getPhotos(); | 
| 
	tudarmstadt-lt/GermaNER | 
	germaner/src/main/java/de/tu/darmstadt/lt/ner/feature/extractor/FreeBaseFeatureExtractor.java | 
	// Path: germaner/src/main/java/de/tu/darmstadt/lt/ner/feature/variables/FreeBaseFeature.java
// public class FreeBaseFeature {
// 
// 	public static LinkedList<String> freebaseFeature=new LinkedList<String>();
// 
// }
 | 
	import java.util.Collections;
import java.util.List;
import org.cleartk.ml.Feature;
import org.cleartk.ml.feature.function.FeatureFunction;
import de.tu.darmstadt.lt.ner.feature.variables.FreeBaseFeature; | 
	/*******************************************************************************
 * Copyright 2014
 * FG Language Technology
 * Technische Universität Darmstadt
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
package de.tu.darmstadt.lt.ner.feature.extractor;
public class FreeBaseFeatureExtractor
    implements FeatureFunction
{
    public FreeBaseFeatureExtractor()
    {
    }
    public static final String DEFAULT_NAME = "FreebaseFeature";
    @Override
    public List<Feature> apply(Feature feature)
    {
        try {
            Object featureValue = feature.getValue();
            if (featureValue == null) {
                return Collections.singletonList(new Feature("FreeBase", "FreeBase_null"));
            }
 | 
	// Path: germaner/src/main/java/de/tu/darmstadt/lt/ner/feature/variables/FreeBaseFeature.java
// public class FreeBaseFeature {
// 
// 	public static LinkedList<String> freebaseFeature=new LinkedList<String>();
// 
// }
// Path: germaner/src/main/java/de/tu/darmstadt/lt/ner/feature/extractor/FreeBaseFeatureExtractor.java
import java.util.Collections;
import java.util.List;
import org.cleartk.ml.Feature;
import org.cleartk.ml.feature.function.FeatureFunction;
import de.tu.darmstadt.lt.ner.feature.variables.FreeBaseFeature;
/*******************************************************************************
 * Copyright 2014
 * FG Language Technology
 * Technische Universität Darmstadt
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
package de.tu.darmstadt.lt.ner.feature.extractor;
public class FreeBaseFeatureExtractor
    implements FeatureFunction
{
    public FreeBaseFeatureExtractor()
    {
    }
    public static final String DEFAULT_NAME = "FreebaseFeature";
    @Override
    public List<Feature> apply(Feature feature)
    {
        try {
            Object featureValue = feature.getValue();
            if (featureValue == null) {
                return Collections.singletonList(new Feature("FreeBase", "FreeBase_null"));
            }
 | 
	            String k = FreeBaseFeature.freebaseFeature.remove(); | 
| 
	tudarmstadt-lt/GermaNER | 
	germaner/src/main/java/de/tu/darmstadt/lt/ner/feature/extractor/PositionFeatureExtractor.java | 
	// Path: germaner/src/main/java/de/tu/darmstadt/lt/ner/feature/variables/PositionFeature.java
// public class PositionFeature {
// 	
// 	public static LinkedList<Integer> posistion=new LinkedList<Integer>();
// 
// }
 | 
	import java.util.Collections;
import java.util.List;
import org.cleartk.ml.Feature;
import org.cleartk.ml.feature.function.FeatureFunction;
import de.tu.darmstadt.lt.ner.feature.variables.PositionFeature; | 
	/*******************************************************************************
 * Copyright 2014
 * FG Language Technology
 * Technische Universität Darmstadt
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
package de.tu.darmstadt.lt.ner.feature.extractor;
public class PositionFeatureExtractor
    implements FeatureFunction
{
    public PositionFeatureExtractor()
    {
    }
 | 
	// Path: germaner/src/main/java/de/tu/darmstadt/lt/ner/feature/variables/PositionFeature.java
// public class PositionFeature {
// 	
// 	public static LinkedList<Integer> posistion=new LinkedList<Integer>();
// 
// }
// Path: germaner/src/main/java/de/tu/darmstadt/lt/ner/feature/extractor/PositionFeatureExtractor.java
import java.util.Collections;
import java.util.List;
import org.cleartk.ml.Feature;
import org.cleartk.ml.feature.function.FeatureFunction;
import de.tu.darmstadt.lt.ner.feature.variables.PositionFeature;
/*******************************************************************************
 * Copyright 2014
 * FG Language Technology
 * Technische Universität Darmstadt
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
package de.tu.darmstadt.lt.ner.feature.extractor;
public class PositionFeatureExtractor
    implements FeatureFunction
{
    public PositionFeatureExtractor()
    {
    }
 | 
	    public static final String DEFAULT_NAME = "PositionFeature"; | 
| 
	tudarmstadt-lt/GermaNER | 
	germaner/src/main/java/de/tu/darmstadt/lt/ner/writer/EvaluatedNERWriter.java | 
	// Path: germaner/src/main/java/de/tu/darmstadt/lt/ner/types/GoldNamedEntity.java
// public class GoldNamedEntity extends Annotation {
//   /** @generated
//    * @ordered 
//    */
//   @SuppressWarnings ("hiding")
//   public final static int typeIndexID = JCasRegistry.register(GoldNamedEntity.class);
//   /** @generated
//    * @ordered 
//    */
//   @SuppressWarnings ("hiding")
//   public final static int type = typeIndexID;
//   /** @generated
//    * @return index of the type  
//    */
//   @Override
//   public              int getTypeIndexID() {return typeIndexID;}
//  
//   /** Never called.  Disable default constructor
//    * @generated */
//   protected GoldNamedEntity() {/* intentionally empty block */}
//     
//   /** Internal - constructor used by generator 
//    * @generated
//    * @param addr low level Feature Structure reference
//    * @param type the type of this Feature Structure 
//    */
//   public GoldNamedEntity(int addr, TOP_Type type) {
//     super(addr, type);
//     readObject();
//   }
//   
//   /** @generated
//    * @param jcas JCas to which this Feature Structure belongs 
//    */
//   public GoldNamedEntity(JCas jcas) {
//     super(jcas);
//     readObject();   
//   } 
// 
//   /** @generated
//    * @param jcas JCas to which this Feature Structure belongs
//    * @param begin offset to the begin spot in the SofA
//    * @param end offset to the end spot in the SofA 
//   */  
//   public GoldNamedEntity(JCas jcas, int begin, int end) {
//     super(jcas);
//     setBegin(begin);
//     setEnd(end);
//     readObject();
//   }   
// 
//   /** 
//    * <!-- begin-user-doc -->
//    * Write your own initialization here
//    * <!-- end-user-doc -->
//    *
//    * @generated modifiable 
//    */
//   private void readObject() {/*default - does nothing empty block */}
//      
//  
//     
//   //*--------------*
//   //* Feature: NamedEntityType
// 
//   /** getter for NamedEntityType - gets 
//    * @generated
//    * @return value of the feature 
//    */
//   public String getNamedEntityType() {
//     if (GoldNamedEntity_Type.featOkTst && ((GoldNamedEntity_Type)jcasType).casFeat_NamedEntityType == null)
//       jcasType.jcas.throwFeatMissing("NamedEntityType", "de.tu.darmstadt.lt.ner.types.GoldNamedEntity");
//     return jcasType.ll_cas.ll_getStringValue(addr, ((GoldNamedEntity_Type)jcasType).casFeatCode_NamedEntityType);}
//     
//   /** setter for NamedEntityType - sets  
//    * @generated
//    * @param v value to set into the feature 
//    */
//   public void setNamedEntityType(String v) {
//     if (GoldNamedEntity_Type.featOkTst && ((GoldNamedEntity_Type)jcasType).casFeat_NamedEntityType == null)
//       jcasType.jcas.throwFeatMissing("NamedEntityType", "de.tu.darmstadt.lt.ner.types.GoldNamedEntity");
//     jcasType.ll_cas.ll_setStringValue(addr, ((GoldNamedEntity_Type)jcasType).casFeatCode_NamedEntityType, v);}    
//   }
 | 
	import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
import org.apache.uima.fit.component.JCasConsumer_ImplBase;
import org.apache.uima.fit.descriptor.ConfigurationParameter;
import org.apache.uima.fit.util.JCasUtil;
import org.apache.uima.jcas.JCas;
import org.apache.uima.util.Level;
import de.tu.darmstadt.lt.ner.types.GoldNamedEntity;
import de.tudarmstadt.ukp.dkpro.core.api.ner.type.NamedEntity;
import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Sentence;
 | 
	                nodOutputWriter = new FileWriter(nodOutputFile);
            }
            int sentenceIndex = 0;
            List<Sentence> sentences = new ArrayList<Sentence>(sentencesNER.keySet());
            // sort sentences by sentence
            Collections.sort(sentences, new Comparator<Sentence>()
            {
                @Override
                public int compare(Sentence arg0, Sentence arg1)
                {
                    return arg0.getBegin() - arg1.getBegin();
                }
            });
            for (Sentence sentence : sentences) {
                List<String> personSb = new ArrayList<String>();
                List<String> orgSb = new ArrayList<String>();
                String prevNeType = "O";
                String namedEntity = "";
                for (NamedEntity neAnnotation : sentencesNER.get(sentence)) {
                    String text = neAnnotation.getCoveredText().replace(" ", "");
                    String neType = neAnnotation.getValue();
                    StringBuilder sb = new StringBuilder();
                    sb.append(text);
                    sb.append(" ");
                    if (isGold) {
 | 
	// Path: germaner/src/main/java/de/tu/darmstadt/lt/ner/types/GoldNamedEntity.java
// public class GoldNamedEntity extends Annotation {
//   /** @generated
//    * @ordered 
//    */
//   @SuppressWarnings ("hiding")
//   public final static int typeIndexID = JCasRegistry.register(GoldNamedEntity.class);
//   /** @generated
//    * @ordered 
//    */
//   @SuppressWarnings ("hiding")
//   public final static int type = typeIndexID;
//   /** @generated
//    * @return index of the type  
//    */
//   @Override
//   public              int getTypeIndexID() {return typeIndexID;}
//  
//   /** Never called.  Disable default constructor
//    * @generated */
//   protected GoldNamedEntity() {/* intentionally empty block */}
//     
//   /** Internal - constructor used by generator 
//    * @generated
//    * @param addr low level Feature Structure reference
//    * @param type the type of this Feature Structure 
//    */
//   public GoldNamedEntity(int addr, TOP_Type type) {
//     super(addr, type);
//     readObject();
//   }
//   
//   /** @generated
//    * @param jcas JCas to which this Feature Structure belongs 
//    */
//   public GoldNamedEntity(JCas jcas) {
//     super(jcas);
//     readObject();   
//   } 
// 
//   /** @generated
//    * @param jcas JCas to which this Feature Structure belongs
//    * @param begin offset to the begin spot in the SofA
//    * @param end offset to the end spot in the SofA 
//   */  
//   public GoldNamedEntity(JCas jcas, int begin, int end) {
//     super(jcas);
//     setBegin(begin);
//     setEnd(end);
//     readObject();
//   }   
// 
//   /** 
//    * <!-- begin-user-doc -->
//    * Write your own initialization here
//    * <!-- end-user-doc -->
//    *
//    * @generated modifiable 
//    */
//   private void readObject() {/*default - does nothing empty block */}
//      
//  
//     
//   //*--------------*
//   //* Feature: NamedEntityType
// 
//   /** getter for NamedEntityType - gets 
//    * @generated
//    * @return value of the feature 
//    */
//   public String getNamedEntityType() {
//     if (GoldNamedEntity_Type.featOkTst && ((GoldNamedEntity_Type)jcasType).casFeat_NamedEntityType == null)
//       jcasType.jcas.throwFeatMissing("NamedEntityType", "de.tu.darmstadt.lt.ner.types.GoldNamedEntity");
//     return jcasType.ll_cas.ll_getStringValue(addr, ((GoldNamedEntity_Type)jcasType).casFeatCode_NamedEntityType);}
//     
//   /** setter for NamedEntityType - sets  
//    * @generated
//    * @param v value to set into the feature 
//    */
//   public void setNamedEntityType(String v) {
//     if (GoldNamedEntity_Type.featOkTst && ((GoldNamedEntity_Type)jcasType).casFeat_NamedEntityType == null)
//       jcasType.jcas.throwFeatMissing("NamedEntityType", "de.tu.darmstadt.lt.ner.types.GoldNamedEntity");
//     jcasType.ll_cas.ll_setStringValue(addr, ((GoldNamedEntity_Type)jcasType).casFeatCode_NamedEntityType, v);}    
//   }
// Path: germaner/src/main/java/de/tu/darmstadt/lt/ner/writer/EvaluatedNERWriter.java
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
import org.apache.uima.fit.component.JCasConsumer_ImplBase;
import org.apache.uima.fit.descriptor.ConfigurationParameter;
import org.apache.uima.fit.util.JCasUtil;
import org.apache.uima.jcas.JCas;
import org.apache.uima.util.Level;
import de.tu.darmstadt.lt.ner.types.GoldNamedEntity;
import de.tudarmstadt.ukp.dkpro.core.api.ner.type.NamedEntity;
import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Sentence;
                nodOutputWriter = new FileWriter(nodOutputFile);
            }
            int sentenceIndex = 0;
            List<Sentence> sentences = new ArrayList<Sentence>(sentencesNER.keySet());
            // sort sentences by sentence
            Collections.sort(sentences, new Comparator<Sentence>()
            {
                @Override
                public int compare(Sentence arg0, Sentence arg1)
                {
                    return arg0.getBegin() - arg1.getBegin();
                }
            });
            for (Sentence sentence : sentences) {
                List<String> personSb = new ArrayList<String>();
                List<String> orgSb = new ArrayList<String>();
                String prevNeType = "O";
                String namedEntity = "";
                for (NamedEntity neAnnotation : sentencesNER.get(sentence)) {
                    String text = neAnnotation.getCoveredText().replace(" ", "");
                    String neType = neAnnotation.getValue();
                    StringBuilder sb = new StringBuilder();
                    sb.append(text);
                    sb.append(" ");
                    if (isGold) {
 | 
	                        sb.append(JCasUtil.selectCovered(jCas, GoldNamedEntity.class, neAnnotation)
 | 
| 
	tudarmstadt-lt/GermaNER | 
	germaner/src/main/java/de/tu/darmstadt/lt/ner/feature/extractor/ClarkPosInductionFeatureExtractor.java | 
	// Path: germaner/src/main/java/de/tu/darmstadt/lt/ner/feature/variables/ClarkPosInduction.java
// public class ClarkPosInduction
// {
//     public static Map<String,String> posInduction = new HashMap();
// 
// }
 | 
	import java.util.Collections;
import java.util.List;
import org.cleartk.ml.Feature;
import org.cleartk.ml.feature.function.FeatureFunction;
import de.tu.darmstadt.lt.ner.feature.variables.ClarkPosInduction; | 
	/*******************************************************************************
 * Copyright 2014
 * FG Language Technology
 * Technische Universität Darmstadt
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
package de.tu.darmstadt.lt.ner.feature.extractor;
public class ClarkPosInductionFeatureExtractor
    implements FeatureFunction
{
    public ClarkPosInductionFeatureExtractor()
    {
    }
 | 
	// Path: germaner/src/main/java/de/tu/darmstadt/lt/ner/feature/variables/ClarkPosInduction.java
// public class ClarkPosInduction
// {
//     public static Map<String,String> posInduction = new HashMap();
// 
// }
// Path: germaner/src/main/java/de/tu/darmstadt/lt/ner/feature/extractor/ClarkPosInductionFeatureExtractor.java
import java.util.Collections;
import java.util.List;
import org.cleartk.ml.Feature;
import org.cleartk.ml.feature.function.FeatureFunction;
import de.tu.darmstadt.lt.ner.feature.variables.ClarkPosInduction;
/*******************************************************************************
 * Copyright 2014
 * FG Language Technology
 * Technische Universität Darmstadt
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
package de.tu.darmstadt.lt.ner.feature.extractor;
public class ClarkPosInductionFeatureExtractor
    implements FeatureFunction
{
    public ClarkPosInductionFeatureExtractor()
    {
    }
 | 
	    public static final String DEFAULT_NAME = "ClarkPosInduction"; | 
| 
	dextorer/BuildingForAndroidTV | 
	episode_4/TVDemoApp/app/src/main/java/com/sgottard/tvdemoapp/presenter/CardPresenter.java | 
	// Path: episode_4/TVDemoApp/app/src/main/java/com/sgottard/tvdemoapp/model/Movie.java
// public class Movie implements Parcelable {
//     private static final String TAG = "Movie";
//     static final long serialVersionUID = 727566175075960653L;
//     private static int sCount = 0;
//     private String mId;
//     private String mTitle;
//     private String mDescription;
//     private String mBgImageUrl;
//     private String mCardImageUrl;
//     private String mVideoUrl;
//     private String mStudio;
//     private String mCategory;
// 
//     public Movie() {
// 
//     }
// 
//     public Movie(Parcel in){
//         String[] data = new String[8];
// 
//         in.readStringArray(data);
//         mId = data[0];
//         mTitle = data[1];
//         mDescription = data[2];
//         mBgImageUrl = data[3];
//         mCardImageUrl = data[4];
//         mVideoUrl = data[5];
//         mStudio = data[6];
//         mCategory = data[7];
//     }
// 
//     public static String getCount() {
//         return Integer.toString(sCount);
//     }
// 
//     public static void incrementCount() {
//         sCount++;
//     }
// 
//     public String getId() {
//         return mId;
//     }
// 
//     public void setId(String id) {
//         mId = id;
//     }
// 
//     public String getTitle() {
//         return mTitle;
//     }
// 
//     public void setTitle(String title) {
//         mTitle = title;
//     }
// 
//     public String getDescription() {
//         return mDescription;
//     }
// 
//     public void setDescription(String description) {
//         mDescription = description;
//     }
// 
//     public String getStudio() {
//         return mStudio;
//     }
// 
//     public void setStudio(String studio) {
//         mStudio = studio;
//     }
// 
//     public String getVideoUrl() {
//         return mVideoUrl;
//     }
// 
//     public void setVideoUrl(String videoUrl) {
//         mVideoUrl = videoUrl;
//     }
// 
//     public String getBackgroundImageUrl() {
//         return mBgImageUrl;
//     }
// 
//     public void setBackgroundImageUrl(String bgImageUrl) {
//         mBgImageUrl = bgImageUrl;
//     }
// 
//     public String getCardImageUrl() {
//         return mCardImageUrl;
//     }
// 
//     public void setCardImageUrl(String cardImageUrl) {
//         mCardImageUrl = cardImageUrl;
//     }
// 
//     public String getCategory() {
//         return mCategory;
//     }
// 
//     public void setCategory(String category) {
//         mCategory = category;
//     }
// 
//     public URI getBackgroundImageURI() {
//         try {
//             return new URI(getBackgroundImageUrl());
//         } catch (URISyntaxException e) {
//             return null;
//         }
//     }
// 
//     public int describeContents() {
//         return 0;
//     }
// 
//     @Override
//     public void writeToParcel(Parcel dest, int flags) {
//         dest.writeStringArray(new String[] {mId,
//                 mTitle,
//                 mDescription,
//                 mBgImageUrl,
//                 mCardImageUrl,
//                 mVideoUrl,
//                 mStudio,
//                 mCategory});
//     }
// 
//     @Override
//     public String toString() {
//         StringBuilder sb = new StringBuilder(200);
//         sb.append("Movie{");
//         sb.append("mId=" + mId);
//         sb.append(", mTitle='" + mTitle + '\'');
//         sb.append(", mVideoUrl='" + mVideoUrl + '\'');
//         sb.append(", backgroundImageUrl='" + mBgImageUrl + '\'');
//         sb.append(", backgroundImageURI='" + getBackgroundImageURI().toString() + '\'');
//         sb.append(", mCardImageUrl='" + mCardImageUrl + '\'');
//         sb.append('}');
//         return sb.toString();
//     }
// 
//     public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
//         public Movie createFromParcel(Parcel in) {
//             return new Movie(in);
//         }
// 
//         public Movie[] newArray(int size) {
//             return new Movie[size];
//         }
//     };
// }
 | 
	import android.graphics.drawable.Drawable;
import android.support.v17.leanback.widget.ImageCardView;
import android.support.v17.leanback.widget.Presenter;
import android.util.Log;
import android.view.ViewGroup;
import com.bumptech.glide.Glide;
import com.sgottard.tvdemoapp.model.Movie;
import com.sgottard.tvdemoapp.tvleanback.R; | 
	        Log.d(TAG, "onCreateViewHolder");
        sDefaultBackgroundColor = parent.getResources().getColor(R.color.default_background);
        sSelectedBackgroundColor = parent.getResources().getColor(R.color.selected_background);
        mDefaultCardImage = parent.getResources().getDrawable(R.drawable.movie);
        ImageCardView cardView = new ImageCardView(parent.getContext()) {
            @Override
            public void setSelected(boolean selected) {
                updateCardBackgroundColor(this, selected);
                super.setSelected(selected);
            }
        };
        cardView.setFocusable(true);
        cardView.setFocusableInTouchMode(true);
        updateCardBackgroundColor(cardView, false);
        return new ViewHolder(cardView);
    }
    private static void updateCardBackgroundColor(ImageCardView view, boolean selected) {
        int color = selected ? sSelectedBackgroundColor : sDefaultBackgroundColor;
        // Both background colors should be set because the view's background is temporarily visible
        // during animations.
        view.setBackgroundColor(color);
        view.findViewById(R.id.info_field).setBackgroundColor(color);
    }
    @Override
    public void onBindViewHolder(Presenter.ViewHolder viewHolder, Object item) { | 
	// Path: episode_4/TVDemoApp/app/src/main/java/com/sgottard/tvdemoapp/model/Movie.java
// public class Movie implements Parcelable {
//     private static final String TAG = "Movie";
//     static final long serialVersionUID = 727566175075960653L;
//     private static int sCount = 0;
//     private String mId;
//     private String mTitle;
//     private String mDescription;
//     private String mBgImageUrl;
//     private String mCardImageUrl;
//     private String mVideoUrl;
//     private String mStudio;
//     private String mCategory;
// 
//     public Movie() {
// 
//     }
// 
//     public Movie(Parcel in){
//         String[] data = new String[8];
// 
//         in.readStringArray(data);
//         mId = data[0];
//         mTitle = data[1];
//         mDescription = data[2];
//         mBgImageUrl = data[3];
//         mCardImageUrl = data[4];
//         mVideoUrl = data[5];
//         mStudio = data[6];
//         mCategory = data[7];
//     }
// 
//     public static String getCount() {
//         return Integer.toString(sCount);
//     }
// 
//     public static void incrementCount() {
//         sCount++;
//     }
// 
//     public String getId() {
//         return mId;
//     }
// 
//     public void setId(String id) {
//         mId = id;
//     }
// 
//     public String getTitle() {
//         return mTitle;
//     }
// 
//     public void setTitle(String title) {
//         mTitle = title;
//     }
// 
//     public String getDescription() {
//         return mDescription;
//     }
// 
//     public void setDescription(String description) {
//         mDescription = description;
//     }
// 
//     public String getStudio() {
//         return mStudio;
//     }
// 
//     public void setStudio(String studio) {
//         mStudio = studio;
//     }
// 
//     public String getVideoUrl() {
//         return mVideoUrl;
//     }
// 
//     public void setVideoUrl(String videoUrl) {
//         mVideoUrl = videoUrl;
//     }
// 
//     public String getBackgroundImageUrl() {
//         return mBgImageUrl;
//     }
// 
//     public void setBackgroundImageUrl(String bgImageUrl) {
//         mBgImageUrl = bgImageUrl;
//     }
// 
//     public String getCardImageUrl() {
//         return mCardImageUrl;
//     }
// 
//     public void setCardImageUrl(String cardImageUrl) {
//         mCardImageUrl = cardImageUrl;
//     }
// 
//     public String getCategory() {
//         return mCategory;
//     }
// 
//     public void setCategory(String category) {
//         mCategory = category;
//     }
// 
//     public URI getBackgroundImageURI() {
//         try {
//             return new URI(getBackgroundImageUrl());
//         } catch (URISyntaxException e) {
//             return null;
//         }
//     }
// 
//     public int describeContents() {
//         return 0;
//     }
// 
//     @Override
//     public void writeToParcel(Parcel dest, int flags) {
//         dest.writeStringArray(new String[] {mId,
//                 mTitle,
//                 mDescription,
//                 mBgImageUrl,
//                 mCardImageUrl,
//                 mVideoUrl,
//                 mStudio,
//                 mCategory});
//     }
// 
//     @Override
//     public String toString() {
//         StringBuilder sb = new StringBuilder(200);
//         sb.append("Movie{");
//         sb.append("mId=" + mId);
//         sb.append(", mTitle='" + mTitle + '\'');
//         sb.append(", mVideoUrl='" + mVideoUrl + '\'');
//         sb.append(", backgroundImageUrl='" + mBgImageUrl + '\'');
//         sb.append(", backgroundImageURI='" + getBackgroundImageURI().toString() + '\'');
//         sb.append(", mCardImageUrl='" + mCardImageUrl + '\'');
//         sb.append('}');
//         return sb.toString();
//     }
// 
//     public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
//         public Movie createFromParcel(Parcel in) {
//             return new Movie(in);
//         }
// 
//         public Movie[] newArray(int size) {
//             return new Movie[size];
//         }
//     };
// }
// Path: episode_4/TVDemoApp/app/src/main/java/com/sgottard/tvdemoapp/presenter/CardPresenter.java
import android.graphics.drawable.Drawable;
import android.support.v17.leanback.widget.ImageCardView;
import android.support.v17.leanback.widget.Presenter;
import android.util.Log;
import android.view.ViewGroup;
import com.bumptech.glide.Glide;
import com.sgottard.tvdemoapp.model.Movie;
import com.sgottard.tvdemoapp.tvleanback.R;
        Log.d(TAG, "onCreateViewHolder");
        sDefaultBackgroundColor = parent.getResources().getColor(R.color.default_background);
        sSelectedBackgroundColor = parent.getResources().getColor(R.color.selected_background);
        mDefaultCardImage = parent.getResources().getDrawable(R.drawable.movie);
        ImageCardView cardView = new ImageCardView(parent.getContext()) {
            @Override
            public void setSelected(boolean selected) {
                updateCardBackgroundColor(this, selected);
                super.setSelected(selected);
            }
        };
        cardView.setFocusable(true);
        cardView.setFocusableInTouchMode(true);
        updateCardBackgroundColor(cardView, false);
        return new ViewHolder(cardView);
    }
    private static void updateCardBackgroundColor(ImageCardView view, boolean selected) {
        int color = selected ? sSelectedBackgroundColor : sDefaultBackgroundColor;
        // Both background colors should be set because the view's background is temporarily visible
        // during animations.
        view.setBackgroundColor(color);
        view.findViewById(R.id.info_field).setBackgroundColor(color);
    }
    @Override
    public void onBindViewHolder(Presenter.ViewHolder viewHolder, Object item) { | 
	        Movie movie = (Movie) item; | 
| 
	dextorer/BuildingForAndroidTV | 
	episode_4/TVDemoApp/app/src/main/java/com/sgottard/tvdemoapp/data/VideoProvider.java | 
	// Path: episode_4/TVDemoApp/app/src/main/java/com/sgottard/tvdemoapp/model/Movie.java
// public class Movie implements Parcelable {
//     private static final String TAG = "Movie";
//     static final long serialVersionUID = 727566175075960653L;
//     private static int sCount = 0;
//     private String mId;
//     private String mTitle;
//     private String mDescription;
//     private String mBgImageUrl;
//     private String mCardImageUrl;
//     private String mVideoUrl;
//     private String mStudio;
//     private String mCategory;
// 
//     public Movie() {
// 
//     }
// 
//     public Movie(Parcel in){
//         String[] data = new String[8];
// 
//         in.readStringArray(data);
//         mId = data[0];
//         mTitle = data[1];
//         mDescription = data[2];
//         mBgImageUrl = data[3];
//         mCardImageUrl = data[4];
//         mVideoUrl = data[5];
//         mStudio = data[6];
//         mCategory = data[7];
//     }
// 
//     public static String getCount() {
//         return Integer.toString(sCount);
//     }
// 
//     public static void incrementCount() {
//         sCount++;
//     }
// 
//     public String getId() {
//         return mId;
//     }
// 
//     public void setId(String id) {
//         mId = id;
//     }
// 
//     public String getTitle() {
//         return mTitle;
//     }
// 
//     public void setTitle(String title) {
//         mTitle = title;
//     }
// 
//     public String getDescription() {
//         return mDescription;
//     }
// 
//     public void setDescription(String description) {
//         mDescription = description;
//     }
// 
//     public String getStudio() {
//         return mStudio;
//     }
// 
//     public void setStudio(String studio) {
//         mStudio = studio;
//     }
// 
//     public String getVideoUrl() {
//         return mVideoUrl;
//     }
// 
//     public void setVideoUrl(String videoUrl) {
//         mVideoUrl = videoUrl;
//     }
// 
//     public String getBackgroundImageUrl() {
//         return mBgImageUrl;
//     }
// 
//     public void setBackgroundImageUrl(String bgImageUrl) {
//         mBgImageUrl = bgImageUrl;
//     }
// 
//     public String getCardImageUrl() {
//         return mCardImageUrl;
//     }
// 
//     public void setCardImageUrl(String cardImageUrl) {
//         mCardImageUrl = cardImageUrl;
//     }
// 
//     public String getCategory() {
//         return mCategory;
//     }
// 
//     public void setCategory(String category) {
//         mCategory = category;
//     }
// 
//     public URI getBackgroundImageURI() {
//         try {
//             return new URI(getBackgroundImageUrl());
//         } catch (URISyntaxException e) {
//             return null;
//         }
//     }
// 
//     public int describeContents() {
//         return 0;
//     }
// 
//     @Override
//     public void writeToParcel(Parcel dest, int flags) {
//         dest.writeStringArray(new String[] {mId,
//                 mTitle,
//                 mDescription,
//                 mBgImageUrl,
//                 mCardImageUrl,
//                 mVideoUrl,
//                 mStudio,
//                 mCategory});
//     }
// 
//     @Override
//     public String toString() {
//         StringBuilder sb = new StringBuilder(200);
//         sb.append("Movie{");
//         sb.append("mId=" + mId);
//         sb.append(", mTitle='" + mTitle + '\'');
//         sb.append(", mVideoUrl='" + mVideoUrl + '\'');
//         sb.append(", backgroundImageUrl='" + mBgImageUrl + '\'');
//         sb.append(", backgroundImageURI='" + getBackgroundImageURI().toString() + '\'');
//         sb.append(", mCardImageUrl='" + mCardImageUrl + '\'');
//         sb.append('}');
//         return sb.toString();
//     }
// 
//     public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
//         public Movie createFromParcel(Parcel in) {
//             return new Movie(in);
//         }
// 
//         public Movie[] newArray(int size) {
//             return new Movie[size];
//         }
//     };
// }
 | 
	import java.io.InputStreamReader;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.content.Context;
import android.util.Log;
import com.sgottard.tvdemoapp.model.Movie;
import com.sgottard.tvdemoapp.tvleanback.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream; | 
	/*
 * Copyright (C) 2015 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.sgottard.tvdemoapp.data;
/*
 * This class loads videos from a backend and saves them into a HashMap
 */
public class VideoProvider {
    private static final String TAG = "VideoProvider";
    private static String TAG_MEDIA = "videos";
    private static String TAG_GOOGLE_VIDEOS = "googlevideos";
    private static String TAG_CATEGORY = "category";
    private static String TAG_STUDIO = "studio";
    private static String TAG_SOURCES = "sources";
    private static String TAG_DESCRIPTION = "description";
    private static String TAG_CARD_THUMB = "card";
    private static String TAG_BACKGROUND = "background";
    private static String TAG_TITLE = "title";
 | 
	// Path: episode_4/TVDemoApp/app/src/main/java/com/sgottard/tvdemoapp/model/Movie.java
// public class Movie implements Parcelable {
//     private static final String TAG = "Movie";
//     static final long serialVersionUID = 727566175075960653L;
//     private static int sCount = 0;
//     private String mId;
//     private String mTitle;
//     private String mDescription;
//     private String mBgImageUrl;
//     private String mCardImageUrl;
//     private String mVideoUrl;
//     private String mStudio;
//     private String mCategory;
// 
//     public Movie() {
// 
//     }
// 
//     public Movie(Parcel in){
//         String[] data = new String[8];
// 
//         in.readStringArray(data);
//         mId = data[0];
//         mTitle = data[1];
//         mDescription = data[2];
//         mBgImageUrl = data[3];
//         mCardImageUrl = data[4];
//         mVideoUrl = data[5];
//         mStudio = data[6];
//         mCategory = data[7];
//     }
// 
//     public static String getCount() {
//         return Integer.toString(sCount);
//     }
// 
//     public static void incrementCount() {
//         sCount++;
//     }
// 
//     public String getId() {
//         return mId;
//     }
// 
//     public void setId(String id) {
//         mId = id;
//     }
// 
//     public String getTitle() {
//         return mTitle;
//     }
// 
//     public void setTitle(String title) {
//         mTitle = title;
//     }
// 
//     public String getDescription() {
//         return mDescription;
//     }
// 
//     public void setDescription(String description) {
//         mDescription = description;
//     }
// 
//     public String getStudio() {
//         return mStudio;
//     }
// 
//     public void setStudio(String studio) {
//         mStudio = studio;
//     }
// 
//     public String getVideoUrl() {
//         return mVideoUrl;
//     }
// 
//     public void setVideoUrl(String videoUrl) {
//         mVideoUrl = videoUrl;
//     }
// 
//     public String getBackgroundImageUrl() {
//         return mBgImageUrl;
//     }
// 
//     public void setBackgroundImageUrl(String bgImageUrl) {
//         mBgImageUrl = bgImageUrl;
//     }
// 
//     public String getCardImageUrl() {
//         return mCardImageUrl;
//     }
// 
//     public void setCardImageUrl(String cardImageUrl) {
//         mCardImageUrl = cardImageUrl;
//     }
// 
//     public String getCategory() {
//         return mCategory;
//     }
// 
//     public void setCategory(String category) {
//         mCategory = category;
//     }
// 
//     public URI getBackgroundImageURI() {
//         try {
//             return new URI(getBackgroundImageUrl());
//         } catch (URISyntaxException e) {
//             return null;
//         }
//     }
// 
//     public int describeContents() {
//         return 0;
//     }
// 
//     @Override
//     public void writeToParcel(Parcel dest, int flags) {
//         dest.writeStringArray(new String[] {mId,
//                 mTitle,
//                 mDescription,
//                 mBgImageUrl,
//                 mCardImageUrl,
//                 mVideoUrl,
//                 mStudio,
//                 mCategory});
//     }
// 
//     @Override
//     public String toString() {
//         StringBuilder sb = new StringBuilder(200);
//         sb.append("Movie{");
//         sb.append("mId=" + mId);
//         sb.append(", mTitle='" + mTitle + '\'');
//         sb.append(", mVideoUrl='" + mVideoUrl + '\'');
//         sb.append(", backgroundImageUrl='" + mBgImageUrl + '\'');
//         sb.append(", backgroundImageURI='" + getBackgroundImageURI().toString() + '\'');
//         sb.append(", mCardImageUrl='" + mCardImageUrl + '\'');
//         sb.append('}');
//         return sb.toString();
//     }
// 
//     public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
//         public Movie createFromParcel(Parcel in) {
//             return new Movie(in);
//         }
// 
//         public Movie[] newArray(int size) {
//             return new Movie[size];
//         }
//     };
// }
// Path: episode_4/TVDemoApp/app/src/main/java/com/sgottard/tvdemoapp/data/VideoProvider.java
import java.io.InputStreamReader;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.content.Context;
import android.util.Log;
import com.sgottard.tvdemoapp.model.Movie;
import com.sgottard.tvdemoapp.tvleanback.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
/*
 * Copyright (C) 2015 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.sgottard.tvdemoapp.data;
/*
 * This class loads videos from a backend and saves them into a HashMap
 */
public class VideoProvider {
    private static final String TAG = "VideoProvider";
    private static String TAG_MEDIA = "videos";
    private static String TAG_GOOGLE_VIDEOS = "googlevideos";
    private static String TAG_CATEGORY = "category";
    private static String TAG_STUDIO = "studio";
    private static String TAG_SOURCES = "sources";
    private static String TAG_DESCRIPTION = "description";
    private static String TAG_CARD_THUMB = "card";
    private static String TAG_BACKGROUND = "background";
    private static String TAG_TITLE = "title";
 | 
	    private static HashMap<String, List<Movie>> sMovieList; | 
| 
	dextorer/BuildingForAndroidTV | 
	episode_4/TVDemoApp/app/src/main/java/com/sgottard/tvdemoapp/ui/CustomHeadersFragment.java | 
	// Path: episode_4/TVDemoApp/app/src/main/java/com/sgottard/tvdemoapp/Utils.java
// public class Utils {
// 
//     /*
//      * Making sure public utility methods remain static
//      */
//     private Utils() {
//     }
// 
//     /**
//      * Returns the screen/display size
//      */
//     public static Point getDisplaySize(Context context) {
//         WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
//         Display display = wm.getDefaultDisplay();
//         Point size = new Point();
//         display.getSize(size);
//         int width = size.x;
//         int height = size.y;
//         return size;
//     }
// 
//     /**
//      * Shows a (long) toast
//      */
//     public static void showToast(Context context, String msg) {
//         Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
//     }
// 
//     /**
//      * Shows a (long) toast.
//      */
//     public static void showToast(Context context, int resourceId) {
//         Toast.makeText(context, context.getString(resourceId), Toast.LENGTH_LONG).show();
//     }
// 
//     public static int convertDpToPixel(Context ctx, int dp) {
//         float density = ctx.getResources().getDisplayMetrics().density;
//         return Math.round((float) dp * density);
//     }
// 
// 
//     public static long getDuration(String videoUrl) {
//         MediaMetadataRetriever mmr = new MediaMetadataRetriever();
//         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
//             mmr.setDataSource(videoUrl, new HashMap<String, String>());
//         } else {
//             mmr.setDataSource(videoUrl);
//         }
//         return Long.parseLong(mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
//     }
// }
 | 
	import android.app.Fragment;
import android.os.Bundle;
import android.support.v17.leanback.app.HeadersFragment;
import android.support.v17.leanback.widget.ArrayObjectAdapter;
import android.support.v17.leanback.widget.HeaderItem;
import android.support.v17.leanback.widget.ListRow;
import android.support.v17.leanback.widget.OnChildSelectedListener;
import android.support.v17.leanback.widget.VerticalGridView;
import android.view.View;
import android.view.ViewGroup;
import com.sgottard.tvdemoapp.Utils;
import com.sgottard.tvdemoapp.tvleanback.R;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.LinkedHashMap; | 
			VerticalGridView gridView = ((MainActivity) getActivity()).getVerticalGridView(this);
		gridView.setOnChildSelectedListener(new OnChildSelectedListener() {
			@Override
			public void onChildSelected(ViewGroup viewGroup, View view, int i, long l) {
				Object obj = ((ListRow) getAdapter().get(i)).getAdapter().get(0);
				getFragmentManager().beginTransaction().replace(R.id.rows_container, (Fragment) obj).commit();
				((MainActivity) getActivity()).updateCurrentFragment((Fragment) obj);
			}
		});
	}
	private void setHeaderAdapter() {
		adapter = new ArrayObjectAdapter();
		LinkedHashMap<Integer, Fragment> fragments = ((MainActivity) getActivity()).getFragments();
		int id = 0;
		for (int i = 0; i < fragments.size(); i++) {
			HeaderItem header = new HeaderItem(id, "Category " + i);
			ArrayObjectAdapter innerAdapter = new ArrayObjectAdapter();
			innerAdapter.add(fragments.get(i));
			adapter.add(id, new ListRow(header, innerAdapter));
			id++;
		}
		setAdapter(adapter);
	}
	private void setCustomPadding() { | 
	// Path: episode_4/TVDemoApp/app/src/main/java/com/sgottard/tvdemoapp/Utils.java
// public class Utils {
// 
//     /*
//      * Making sure public utility methods remain static
//      */
//     private Utils() {
//     }
// 
//     /**
//      * Returns the screen/display size
//      */
//     public static Point getDisplaySize(Context context) {
//         WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
//         Display display = wm.getDefaultDisplay();
//         Point size = new Point();
//         display.getSize(size);
//         int width = size.x;
//         int height = size.y;
//         return size;
//     }
// 
//     /**
//      * Shows a (long) toast
//      */
//     public static void showToast(Context context, String msg) {
//         Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
//     }
// 
//     /**
//      * Shows a (long) toast.
//      */
//     public static void showToast(Context context, int resourceId) {
//         Toast.makeText(context, context.getString(resourceId), Toast.LENGTH_LONG).show();
//     }
// 
//     public static int convertDpToPixel(Context ctx, int dp) {
//         float density = ctx.getResources().getDisplayMetrics().density;
//         return Math.round((float) dp * density);
//     }
// 
// 
//     public static long getDuration(String videoUrl) {
//         MediaMetadataRetriever mmr = new MediaMetadataRetriever();
//         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
//             mmr.setDataSource(videoUrl, new HashMap<String, String>());
//         } else {
//             mmr.setDataSource(videoUrl);
//         }
//         return Long.parseLong(mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
//     }
// }
// Path: episode_4/TVDemoApp/app/src/main/java/com/sgottard/tvdemoapp/ui/CustomHeadersFragment.java
import android.app.Fragment;
import android.os.Bundle;
import android.support.v17.leanback.app.HeadersFragment;
import android.support.v17.leanback.widget.ArrayObjectAdapter;
import android.support.v17.leanback.widget.HeaderItem;
import android.support.v17.leanback.widget.ListRow;
import android.support.v17.leanback.widget.OnChildSelectedListener;
import android.support.v17.leanback.widget.VerticalGridView;
import android.view.View;
import android.view.ViewGroup;
import com.sgottard.tvdemoapp.Utils;
import com.sgottard.tvdemoapp.tvleanback.R;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.LinkedHashMap;
		VerticalGridView gridView = ((MainActivity) getActivity()).getVerticalGridView(this);
		gridView.setOnChildSelectedListener(new OnChildSelectedListener() {
			@Override
			public void onChildSelected(ViewGroup viewGroup, View view, int i, long l) {
				Object obj = ((ListRow) getAdapter().get(i)).getAdapter().get(0);
				getFragmentManager().beginTransaction().replace(R.id.rows_container, (Fragment) obj).commit();
				((MainActivity) getActivity()).updateCurrentFragment((Fragment) obj);
			}
		});
	}
	private void setHeaderAdapter() {
		adapter = new ArrayObjectAdapter();
		LinkedHashMap<Integer, Fragment> fragments = ((MainActivity) getActivity()).getFragments();
		int id = 0;
		for (int i = 0; i < fragments.size(); i++) {
			HeaderItem header = new HeaderItem(id, "Category " + i);
			ArrayObjectAdapter innerAdapter = new ArrayObjectAdapter();
			innerAdapter.add(fragments.get(i));
			adapter.add(id, new ListRow(header, innerAdapter));
			id++;
		}
		setAdapter(adapter);
	}
	private void setCustomPadding() { | 
			getView().setPadding(0, Utils.convertDpToPixel(getActivity(), 128), Utils.convertDpToPixel(getActivity(), 48), 0); | 
| 
	dextorer/BuildingForAndroidTV | 
	episode_4/TVDemoApp/app/src/main/java/com/sgottard/tvdemoapp/data/VideoDatabase.java | 
	// Path: episode_4/TVDemoApp/app/src/main/java/com/sgottard/tvdemoapp/model/Movie.java
// public class Movie implements Parcelable {
//     private static final String TAG = "Movie";
//     static final long serialVersionUID = 727566175075960653L;
//     private static int sCount = 0;
//     private String mId;
//     private String mTitle;
//     private String mDescription;
//     private String mBgImageUrl;
//     private String mCardImageUrl;
//     private String mVideoUrl;
//     private String mStudio;
//     private String mCategory;
// 
//     public Movie() {
// 
//     }
// 
//     public Movie(Parcel in){
//         String[] data = new String[8];
// 
//         in.readStringArray(data);
//         mId = data[0];
//         mTitle = data[1];
//         mDescription = data[2];
//         mBgImageUrl = data[3];
//         mCardImageUrl = data[4];
//         mVideoUrl = data[5];
//         mStudio = data[6];
//         mCategory = data[7];
//     }
// 
//     public static String getCount() {
//         return Integer.toString(sCount);
//     }
// 
//     public static void incrementCount() {
//         sCount++;
//     }
// 
//     public String getId() {
//         return mId;
//     }
// 
//     public void setId(String id) {
//         mId = id;
//     }
// 
//     public String getTitle() {
//         return mTitle;
//     }
// 
//     public void setTitle(String title) {
//         mTitle = title;
//     }
// 
//     public String getDescription() {
//         return mDescription;
//     }
// 
//     public void setDescription(String description) {
//         mDescription = description;
//     }
// 
//     public String getStudio() {
//         return mStudio;
//     }
// 
//     public void setStudio(String studio) {
//         mStudio = studio;
//     }
// 
//     public String getVideoUrl() {
//         return mVideoUrl;
//     }
// 
//     public void setVideoUrl(String videoUrl) {
//         mVideoUrl = videoUrl;
//     }
// 
//     public String getBackgroundImageUrl() {
//         return mBgImageUrl;
//     }
// 
//     public void setBackgroundImageUrl(String bgImageUrl) {
//         mBgImageUrl = bgImageUrl;
//     }
// 
//     public String getCardImageUrl() {
//         return mCardImageUrl;
//     }
// 
//     public void setCardImageUrl(String cardImageUrl) {
//         mCardImageUrl = cardImageUrl;
//     }
// 
//     public String getCategory() {
//         return mCategory;
//     }
// 
//     public void setCategory(String category) {
//         mCategory = category;
//     }
// 
//     public URI getBackgroundImageURI() {
//         try {
//             return new URI(getBackgroundImageUrl());
//         } catch (URISyntaxException e) {
//             return null;
//         }
//     }
// 
//     public int describeContents() {
//         return 0;
//     }
// 
//     @Override
//     public void writeToParcel(Parcel dest, int flags) {
//         dest.writeStringArray(new String[] {mId,
//                 mTitle,
//                 mDescription,
//                 mBgImageUrl,
//                 mCardImageUrl,
//                 mVideoUrl,
//                 mStudio,
//                 mCategory});
//     }
// 
//     @Override
//     public String toString() {
//         StringBuilder sb = new StringBuilder(200);
//         sb.append("Movie{");
//         sb.append("mId=" + mId);
//         sb.append(", mTitle='" + mTitle + '\'');
//         sb.append(", mVideoUrl='" + mVideoUrl + '\'');
//         sb.append(", backgroundImageUrl='" + mBgImageUrl + '\'');
//         sb.append(", backgroundImageURI='" + getBackgroundImageURI().toString() + '\'');
//         sb.append(", mCardImageUrl='" + mCardImageUrl + '\'');
//         sb.append('}');
//         return sb.toString();
//     }
// 
//     public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
//         public Movie createFromParcel(Parcel in) {
//             return new Movie(in);
//         }
// 
//         public Movie[] newArray(int size) {
//             return new Movie[size];
//         }
//     };
// }
 | 
	import org.json.JSONException;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.SearchManager;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.media.Rating;
import android.provider.BaseColumns;
import android.util.Log;
import com.sgottard.tvdemoapp.model.Movie;
import com.sgottard.tvdemoapp.tvleanback.R; | 
	                        KEY_RATING_SCORE + "," +
                        KEY_PRODUCTION_YEAR + "," +
                        KEY_COLUMN_DURATION + "," +
                        KEY_ACTION + ");";
        @Override
        public void onCreate(SQLiteDatabase db) {
            mDatabase = db;
            mDatabase.execSQL(FTS_TABLE_CREATE);
            loadDatabase();
        }
        /**
         * Starts a thread to load the database table with words
         */
        private void loadDatabase() {
            new Thread(new Runnable() {
                public void run() {
                    try {
                        loadMovies();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            }).start();
        }
        private void loadMovies() throws IOException {
            Log.d(TAG, "Loading movies...");
 | 
	// Path: episode_4/TVDemoApp/app/src/main/java/com/sgottard/tvdemoapp/model/Movie.java
// public class Movie implements Parcelable {
//     private static final String TAG = "Movie";
//     static final long serialVersionUID = 727566175075960653L;
//     private static int sCount = 0;
//     private String mId;
//     private String mTitle;
//     private String mDescription;
//     private String mBgImageUrl;
//     private String mCardImageUrl;
//     private String mVideoUrl;
//     private String mStudio;
//     private String mCategory;
// 
//     public Movie() {
// 
//     }
// 
//     public Movie(Parcel in){
//         String[] data = new String[8];
// 
//         in.readStringArray(data);
//         mId = data[0];
//         mTitle = data[1];
//         mDescription = data[2];
//         mBgImageUrl = data[3];
//         mCardImageUrl = data[4];
//         mVideoUrl = data[5];
//         mStudio = data[6];
//         mCategory = data[7];
//     }
// 
//     public static String getCount() {
//         return Integer.toString(sCount);
//     }
// 
//     public static void incrementCount() {
//         sCount++;
//     }
// 
//     public String getId() {
//         return mId;
//     }
// 
//     public void setId(String id) {
//         mId = id;
//     }
// 
//     public String getTitle() {
//         return mTitle;
//     }
// 
//     public void setTitle(String title) {
//         mTitle = title;
//     }
// 
//     public String getDescription() {
//         return mDescription;
//     }
// 
//     public void setDescription(String description) {
//         mDescription = description;
//     }
// 
//     public String getStudio() {
//         return mStudio;
//     }
// 
//     public void setStudio(String studio) {
//         mStudio = studio;
//     }
// 
//     public String getVideoUrl() {
//         return mVideoUrl;
//     }
// 
//     public void setVideoUrl(String videoUrl) {
//         mVideoUrl = videoUrl;
//     }
// 
//     public String getBackgroundImageUrl() {
//         return mBgImageUrl;
//     }
// 
//     public void setBackgroundImageUrl(String bgImageUrl) {
//         mBgImageUrl = bgImageUrl;
//     }
// 
//     public String getCardImageUrl() {
//         return mCardImageUrl;
//     }
// 
//     public void setCardImageUrl(String cardImageUrl) {
//         mCardImageUrl = cardImageUrl;
//     }
// 
//     public String getCategory() {
//         return mCategory;
//     }
// 
//     public void setCategory(String category) {
//         mCategory = category;
//     }
// 
//     public URI getBackgroundImageURI() {
//         try {
//             return new URI(getBackgroundImageUrl());
//         } catch (URISyntaxException e) {
//             return null;
//         }
//     }
// 
//     public int describeContents() {
//         return 0;
//     }
// 
//     @Override
//     public void writeToParcel(Parcel dest, int flags) {
//         dest.writeStringArray(new String[] {mId,
//                 mTitle,
//                 mDescription,
//                 mBgImageUrl,
//                 mCardImageUrl,
//                 mVideoUrl,
//                 mStudio,
//                 mCategory});
//     }
// 
//     @Override
//     public String toString() {
//         StringBuilder sb = new StringBuilder(200);
//         sb.append("Movie{");
//         sb.append("mId=" + mId);
//         sb.append(", mTitle='" + mTitle + '\'');
//         sb.append(", mVideoUrl='" + mVideoUrl + '\'');
//         sb.append(", backgroundImageUrl='" + mBgImageUrl + '\'');
//         sb.append(", backgroundImageURI='" + getBackgroundImageURI().toString() + '\'');
//         sb.append(", mCardImageUrl='" + mCardImageUrl + '\'');
//         sb.append('}');
//         return sb.toString();
//     }
// 
//     public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
//         public Movie createFromParcel(Parcel in) {
//             return new Movie(in);
//         }
// 
//         public Movie[] newArray(int size) {
//             return new Movie[size];
//         }
//     };
// }
// Path: episode_4/TVDemoApp/app/src/main/java/com/sgottard/tvdemoapp/data/VideoDatabase.java
import org.json.JSONException;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.SearchManager;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.media.Rating;
import android.provider.BaseColumns;
import android.util.Log;
import com.sgottard.tvdemoapp.model.Movie;
import com.sgottard.tvdemoapp.tvleanback.R;
                        KEY_RATING_SCORE + "," +
                        KEY_PRODUCTION_YEAR + "," +
                        KEY_COLUMN_DURATION + "," +
                        KEY_ACTION + ");";
        @Override
        public void onCreate(SQLiteDatabase db) {
            mDatabase = db;
            mDatabase.execSQL(FTS_TABLE_CREATE);
            loadDatabase();
        }
        /**
         * Starts a thread to load the database table with words
         */
        private void loadDatabase() {
            new Thread(new Runnable() {
                public void run() {
                    try {
                        loadMovies();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            }).start();
        }
        private void loadMovies() throws IOException {
            Log.d(TAG, "Loading movies...");
 | 
	            HashMap<String, List<Movie>> movies = null; | 
| 
	dextorer/BuildingForAndroidTV | 
	episode_4/TVDemoApp/app/src/main/java/com/sgottard/tvdemoapp/ui/MoreSamplesFragment.java | 
	// Path: episode_4/TVDemoApp/app/src/main/java/com/sgottard/tvdemoapp/Utils.java
// public class Utils {
// 
//     /*
//      * Making sure public utility methods remain static
//      */
//     private Utils() {
//     }
// 
//     /**
//      * Returns the screen/display size
//      */
//     public static Point getDisplaySize(Context context) {
//         WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
//         Display display = wm.getDefaultDisplay();
//         Point size = new Point();
//         display.getSize(size);
//         int width = size.x;
//         int height = size.y;
//         return size;
//     }
// 
//     /**
//      * Shows a (long) toast
//      */
//     public static void showToast(Context context, String msg) {
//         Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
//     }
// 
//     /**
//      * Shows a (long) toast.
//      */
//     public static void showToast(Context context, int resourceId) {
//         Toast.makeText(context, context.getString(resourceId), Toast.LENGTH_LONG).show();
//     }
// 
//     public static int convertDpToPixel(Context ctx, int dp) {
//         float density = ctx.getResources().getDisplayMetrics().density;
//         return Math.round((float) dp * density);
//     }
// 
// 
//     public static long getDuration(String videoUrl) {
//         MediaMetadataRetriever mmr = new MediaMetadataRetriever();
//         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
//             mmr.setDataSource(videoUrl, new HashMap<String, String>());
//         } else {
//             mmr.setDataSource(videoUrl);
//         }
//         return Long.parseLong(mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
//     }
// }
// 
// Path: episode_4/TVDemoApp/app/src/main/java/com/sgottard/tvdemoapp/presenter/GridItemPresenter.java
// public class GridItemPresenter extends Presenter {
//     private static int GRID_ITEM_WIDTH = 200;
//     private static int GRID_ITEM_HEIGHT = 200;
// 
//     private Fragment mainFragment;
// 
//     public GridItemPresenter(Fragment fragment) {
//         this.mainFragment = fragment;
//     }
// 
//     @Override
//     public ViewHolder onCreateViewHolder(ViewGroup parent) {
//         TextView view = new TextView(parent.getContext());
//         view.setLayoutParams(new ViewGroup.LayoutParams(GRID_ITEM_WIDTH, GRID_ITEM_HEIGHT));
//         view.setFocusable(true);
//         view.setFocusableInTouchMode(true);
//         view.setBackgroundColor(mainFragment.getResources().getColor(R.color.default_background));
//         view.setTextColor(Color.WHITE);
//         view.setGravity(Gravity.CENTER);
//         return new ViewHolder(view);
//     }
// 
//     @Override
//     public void onBindViewHolder(ViewHolder viewHolder, Object item) {
//         ((TextView) viewHolder.view).setText((String) item);
//     }
// 
//     @Override
//     public void onUnbindViewHolder(ViewHolder viewHolder) {
//     }
// }
 | 
	import android.content.Intent;
import android.os.Bundle;
import android.support.v17.leanback.app.RowsFragment;
import android.support.v17.leanback.widget.ArrayObjectAdapter;
import android.support.v17.leanback.widget.HeaderItem;
import android.support.v17.leanback.widget.ListRow;
import android.support.v17.leanback.widget.ListRowPresenter;
import android.support.v17.leanback.widget.OnItemViewClickedListener;
import android.support.v17.leanback.widget.Presenter;
import android.support.v17.leanback.widget.Row;
import android.support.v17.leanback.widget.RowPresenter;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.sgottard.tvdemoapp.Utils;
import com.sgottard.tvdemoapp.presenter.GridItemPresenter;
import com.sgottard.tvdemoapp.tvleanback.R; | 
	    }
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        loadRows();
        setCustomPadding();
        setOnItemViewClickedListener(new OnItemViewClickedListener() {
            @Override
            public void onItemClicked(Presenter.ViewHolder itemViewHolder, Object item, RowPresenter.ViewHolder rowViewHolder, Row row) {
                if (((String) item).indexOf(getString(R.string.grid_view)) >= 0) {
                    Intent intent = new Intent(getActivity(), VerticalGridActivity.class);
                    getActivity().startActivity(intent);
                } else if (((String) item).indexOf(getString(R.string.error_fragment)) >= 0) {
                    Intent intent = new Intent(getActivity(), BrowseErrorActivity.class);
                    getActivity().startActivity(intent);
                } else if (((String) item)
                        .indexOf(getString(R.string.guidedstep_first_title)) >= 0) {
                    Intent intent = new Intent(getActivity(), GuidedStepActivity.class);
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(getActivity(), SettingsActivity.class);
                    getActivity().startActivity(intent);
                }
            }
        });
    }
    private void setCustomPadding() { | 
	// Path: episode_4/TVDemoApp/app/src/main/java/com/sgottard/tvdemoapp/Utils.java
// public class Utils {
// 
//     /*
//      * Making sure public utility methods remain static
//      */
//     private Utils() {
//     }
// 
//     /**
//      * Returns the screen/display size
//      */
//     public static Point getDisplaySize(Context context) {
//         WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
//         Display display = wm.getDefaultDisplay();
//         Point size = new Point();
//         display.getSize(size);
//         int width = size.x;
//         int height = size.y;
//         return size;
//     }
// 
//     /**
//      * Shows a (long) toast
//      */
//     public static void showToast(Context context, String msg) {
//         Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
//     }
// 
//     /**
//      * Shows a (long) toast.
//      */
//     public static void showToast(Context context, int resourceId) {
//         Toast.makeText(context, context.getString(resourceId), Toast.LENGTH_LONG).show();
//     }
// 
//     public static int convertDpToPixel(Context ctx, int dp) {
//         float density = ctx.getResources().getDisplayMetrics().density;
//         return Math.round((float) dp * density);
//     }
// 
// 
//     public static long getDuration(String videoUrl) {
//         MediaMetadataRetriever mmr = new MediaMetadataRetriever();
//         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
//             mmr.setDataSource(videoUrl, new HashMap<String, String>());
//         } else {
//             mmr.setDataSource(videoUrl);
//         }
//         return Long.parseLong(mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
//     }
// }
// 
// Path: episode_4/TVDemoApp/app/src/main/java/com/sgottard/tvdemoapp/presenter/GridItemPresenter.java
// public class GridItemPresenter extends Presenter {
//     private static int GRID_ITEM_WIDTH = 200;
//     private static int GRID_ITEM_HEIGHT = 200;
// 
//     private Fragment mainFragment;
// 
//     public GridItemPresenter(Fragment fragment) {
//         this.mainFragment = fragment;
//     }
// 
//     @Override
//     public ViewHolder onCreateViewHolder(ViewGroup parent) {
//         TextView view = new TextView(parent.getContext());
//         view.setLayoutParams(new ViewGroup.LayoutParams(GRID_ITEM_WIDTH, GRID_ITEM_HEIGHT));
//         view.setFocusable(true);
//         view.setFocusableInTouchMode(true);
//         view.setBackgroundColor(mainFragment.getResources().getColor(R.color.default_background));
//         view.setTextColor(Color.WHITE);
//         view.setGravity(Gravity.CENTER);
//         return new ViewHolder(view);
//     }
// 
//     @Override
//     public void onBindViewHolder(ViewHolder viewHolder, Object item) {
//         ((TextView) viewHolder.view).setText((String) item);
//     }
// 
//     @Override
//     public void onUnbindViewHolder(ViewHolder viewHolder) {
//     }
// }
// Path: episode_4/TVDemoApp/app/src/main/java/com/sgottard/tvdemoapp/ui/MoreSamplesFragment.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v17.leanback.app.RowsFragment;
import android.support.v17.leanback.widget.ArrayObjectAdapter;
import android.support.v17.leanback.widget.HeaderItem;
import android.support.v17.leanback.widget.ListRow;
import android.support.v17.leanback.widget.ListRowPresenter;
import android.support.v17.leanback.widget.OnItemViewClickedListener;
import android.support.v17.leanback.widget.Presenter;
import android.support.v17.leanback.widget.Row;
import android.support.v17.leanback.widget.RowPresenter;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.sgottard.tvdemoapp.Utils;
import com.sgottard.tvdemoapp.presenter.GridItemPresenter;
import com.sgottard.tvdemoapp.tvleanback.R;
    }
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        loadRows();
        setCustomPadding();
        setOnItemViewClickedListener(new OnItemViewClickedListener() {
            @Override
            public void onItemClicked(Presenter.ViewHolder itemViewHolder, Object item, RowPresenter.ViewHolder rowViewHolder, Row row) {
                if (((String) item).indexOf(getString(R.string.grid_view)) >= 0) {
                    Intent intent = new Intent(getActivity(), VerticalGridActivity.class);
                    getActivity().startActivity(intent);
                } else if (((String) item).indexOf(getString(R.string.error_fragment)) >= 0) {
                    Intent intent = new Intent(getActivity(), BrowseErrorActivity.class);
                    getActivity().startActivity(intent);
                } else if (((String) item)
                        .indexOf(getString(R.string.guidedstep_first_title)) >= 0) {
                    Intent intent = new Intent(getActivity(), GuidedStepActivity.class);
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(getActivity(), SettingsActivity.class);
                    getActivity().startActivity(intent);
                }
            }
        });
    }
    private void setCustomPadding() { | 
	        getView().setPadding(Utils.convertDpToPixel(getActivity(), -24), Utils.convertDpToPixel(getActivity(), 128), Utils.convertDpToPixel(getActivity(), 48), 0); | 
| 
	dextorer/BuildingForAndroidTV | 
	episode_4/TVDemoApp/app/src/main/java/com/sgottard/tvdemoapp/ui/MoreSamplesFragment.java | 
	// Path: episode_4/TVDemoApp/app/src/main/java/com/sgottard/tvdemoapp/Utils.java
// public class Utils {
// 
//     /*
//      * Making sure public utility methods remain static
//      */
//     private Utils() {
//     }
// 
//     /**
//      * Returns the screen/display size
//      */
//     public static Point getDisplaySize(Context context) {
//         WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
//         Display display = wm.getDefaultDisplay();
//         Point size = new Point();
//         display.getSize(size);
//         int width = size.x;
//         int height = size.y;
//         return size;
//     }
// 
//     /**
//      * Shows a (long) toast
//      */
//     public static void showToast(Context context, String msg) {
//         Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
//     }
// 
//     /**
//      * Shows a (long) toast.
//      */
//     public static void showToast(Context context, int resourceId) {
//         Toast.makeText(context, context.getString(resourceId), Toast.LENGTH_LONG).show();
//     }
// 
//     public static int convertDpToPixel(Context ctx, int dp) {
//         float density = ctx.getResources().getDisplayMetrics().density;
//         return Math.round((float) dp * density);
//     }
// 
// 
//     public static long getDuration(String videoUrl) {
//         MediaMetadataRetriever mmr = new MediaMetadataRetriever();
//         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
//             mmr.setDataSource(videoUrl, new HashMap<String, String>());
//         } else {
//             mmr.setDataSource(videoUrl);
//         }
//         return Long.parseLong(mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
//     }
// }
// 
// Path: episode_4/TVDemoApp/app/src/main/java/com/sgottard/tvdemoapp/presenter/GridItemPresenter.java
// public class GridItemPresenter extends Presenter {
//     private static int GRID_ITEM_WIDTH = 200;
//     private static int GRID_ITEM_HEIGHT = 200;
// 
//     private Fragment mainFragment;
// 
//     public GridItemPresenter(Fragment fragment) {
//         this.mainFragment = fragment;
//     }
// 
//     @Override
//     public ViewHolder onCreateViewHolder(ViewGroup parent) {
//         TextView view = new TextView(parent.getContext());
//         view.setLayoutParams(new ViewGroup.LayoutParams(GRID_ITEM_WIDTH, GRID_ITEM_HEIGHT));
//         view.setFocusable(true);
//         view.setFocusableInTouchMode(true);
//         view.setBackgroundColor(mainFragment.getResources().getColor(R.color.default_background));
//         view.setTextColor(Color.WHITE);
//         view.setGravity(Gravity.CENTER);
//         return new ViewHolder(view);
//     }
// 
//     @Override
//     public void onBindViewHolder(ViewHolder viewHolder, Object item) {
//         ((TextView) viewHolder.view).setText((String) item);
//     }
// 
//     @Override
//     public void onUnbindViewHolder(ViewHolder viewHolder) {
//     }
// }
 | 
	import android.content.Intent;
import android.os.Bundle;
import android.support.v17.leanback.app.RowsFragment;
import android.support.v17.leanback.widget.ArrayObjectAdapter;
import android.support.v17.leanback.widget.HeaderItem;
import android.support.v17.leanback.widget.ListRow;
import android.support.v17.leanback.widget.ListRowPresenter;
import android.support.v17.leanback.widget.OnItemViewClickedListener;
import android.support.v17.leanback.widget.Presenter;
import android.support.v17.leanback.widget.Row;
import android.support.v17.leanback.widget.RowPresenter;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.sgottard.tvdemoapp.Utils;
import com.sgottard.tvdemoapp.presenter.GridItemPresenter;
import com.sgottard.tvdemoapp.tvleanback.R; | 
	        setCustomPadding();
        setOnItemViewClickedListener(new OnItemViewClickedListener() {
            @Override
            public void onItemClicked(Presenter.ViewHolder itemViewHolder, Object item, RowPresenter.ViewHolder rowViewHolder, Row row) {
                if (((String) item).indexOf(getString(R.string.grid_view)) >= 0) {
                    Intent intent = new Intent(getActivity(), VerticalGridActivity.class);
                    getActivity().startActivity(intent);
                } else if (((String) item).indexOf(getString(R.string.error_fragment)) >= 0) {
                    Intent intent = new Intent(getActivity(), BrowseErrorActivity.class);
                    getActivity().startActivity(intent);
                } else if (((String) item)
                        .indexOf(getString(R.string.guidedstep_first_title)) >= 0) {
                    Intent intent = new Intent(getActivity(), GuidedStepActivity.class);
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(getActivity(), SettingsActivity.class);
                    getActivity().startActivity(intent);
                }
            }
        });
    }
    private void setCustomPadding() {
        getView().setPadding(Utils.convertDpToPixel(getActivity(), -24), Utils.convertDpToPixel(getActivity(), 128), Utils.convertDpToPixel(getActivity(), 48), 0);
    }
    private void loadRows() {
        rowsAdapter = new ArrayObjectAdapter(new ListRowPresenter());
        HeaderItem gridHeader = new HeaderItem(1, getString(R.string.more_samples)); | 
	// Path: episode_4/TVDemoApp/app/src/main/java/com/sgottard/tvdemoapp/Utils.java
// public class Utils {
// 
//     /*
//      * Making sure public utility methods remain static
//      */
//     private Utils() {
//     }
// 
//     /**
//      * Returns the screen/display size
//      */
//     public static Point getDisplaySize(Context context) {
//         WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
//         Display display = wm.getDefaultDisplay();
//         Point size = new Point();
//         display.getSize(size);
//         int width = size.x;
//         int height = size.y;
//         return size;
//     }
// 
//     /**
//      * Shows a (long) toast
//      */
//     public static void showToast(Context context, String msg) {
//         Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
//     }
// 
//     /**
//      * Shows a (long) toast.
//      */
//     public static void showToast(Context context, int resourceId) {
//         Toast.makeText(context, context.getString(resourceId), Toast.LENGTH_LONG).show();
//     }
// 
//     public static int convertDpToPixel(Context ctx, int dp) {
//         float density = ctx.getResources().getDisplayMetrics().density;
//         return Math.round((float) dp * density);
//     }
// 
// 
//     public static long getDuration(String videoUrl) {
//         MediaMetadataRetriever mmr = new MediaMetadataRetriever();
//         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
//             mmr.setDataSource(videoUrl, new HashMap<String, String>());
//         } else {
//             mmr.setDataSource(videoUrl);
//         }
//         return Long.parseLong(mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
//     }
// }
// 
// Path: episode_4/TVDemoApp/app/src/main/java/com/sgottard/tvdemoapp/presenter/GridItemPresenter.java
// public class GridItemPresenter extends Presenter {
//     private static int GRID_ITEM_WIDTH = 200;
//     private static int GRID_ITEM_HEIGHT = 200;
// 
//     private Fragment mainFragment;
// 
//     public GridItemPresenter(Fragment fragment) {
//         this.mainFragment = fragment;
//     }
// 
//     @Override
//     public ViewHolder onCreateViewHolder(ViewGroup parent) {
//         TextView view = new TextView(parent.getContext());
//         view.setLayoutParams(new ViewGroup.LayoutParams(GRID_ITEM_WIDTH, GRID_ITEM_HEIGHT));
//         view.setFocusable(true);
//         view.setFocusableInTouchMode(true);
//         view.setBackgroundColor(mainFragment.getResources().getColor(R.color.default_background));
//         view.setTextColor(Color.WHITE);
//         view.setGravity(Gravity.CENTER);
//         return new ViewHolder(view);
//     }
// 
//     @Override
//     public void onBindViewHolder(ViewHolder viewHolder, Object item) {
//         ((TextView) viewHolder.view).setText((String) item);
//     }
// 
//     @Override
//     public void onUnbindViewHolder(ViewHolder viewHolder) {
//     }
// }
// Path: episode_4/TVDemoApp/app/src/main/java/com/sgottard/tvdemoapp/ui/MoreSamplesFragment.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v17.leanback.app.RowsFragment;
import android.support.v17.leanback.widget.ArrayObjectAdapter;
import android.support.v17.leanback.widget.HeaderItem;
import android.support.v17.leanback.widget.ListRow;
import android.support.v17.leanback.widget.ListRowPresenter;
import android.support.v17.leanback.widget.OnItemViewClickedListener;
import android.support.v17.leanback.widget.Presenter;
import android.support.v17.leanback.widget.Row;
import android.support.v17.leanback.widget.RowPresenter;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.sgottard.tvdemoapp.Utils;
import com.sgottard.tvdemoapp.presenter.GridItemPresenter;
import com.sgottard.tvdemoapp.tvleanback.R;
        setCustomPadding();
        setOnItemViewClickedListener(new OnItemViewClickedListener() {
            @Override
            public void onItemClicked(Presenter.ViewHolder itemViewHolder, Object item, RowPresenter.ViewHolder rowViewHolder, Row row) {
                if (((String) item).indexOf(getString(R.string.grid_view)) >= 0) {
                    Intent intent = new Intent(getActivity(), VerticalGridActivity.class);
                    getActivity().startActivity(intent);
                } else if (((String) item).indexOf(getString(R.string.error_fragment)) >= 0) {
                    Intent intent = new Intent(getActivity(), BrowseErrorActivity.class);
                    getActivity().startActivity(intent);
                } else if (((String) item)
                        .indexOf(getString(R.string.guidedstep_first_title)) >= 0) {
                    Intent intent = new Intent(getActivity(), GuidedStepActivity.class);
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(getActivity(), SettingsActivity.class);
                    getActivity().startActivity(intent);
                }
            }
        });
    }
    private void setCustomPadding() {
        getView().setPadding(Utils.convertDpToPixel(getActivity(), -24), Utils.convertDpToPixel(getActivity(), 128), Utils.convertDpToPixel(getActivity(), 48), 0);
    }
    private void loadRows() {
        rowsAdapter = new ArrayObjectAdapter(new ListRowPresenter());
        HeaderItem gridHeader = new HeaderItem(1, getString(R.string.more_samples)); | 
	        GridItemPresenter gridPresenter = new GridItemPresenter(this); | 
| 
	jfinkels/analyticalengine | 
	src/test/java/analyticalengine/attendant/DefaultAttendantTest.java | 
	// Path: src/test/java/analyticalengine/TestUtils.java
// public final class TestUtils {
// 
//     /**
//      * The message produced when {@link #shouldHaveThrownException()} is
//      * called.
//      */
//     private static final String EXCEPTION_MSG = "Exception should have been"
//             + " thrown on previous line.";
// 
//     /**
//      * Prints the stack trace of the specified Exception to stderr and calls
//      * {@link org.junit.Assert#fail(String)} in order to fail the test in which
//      * this method is called.
//      * 
//      * @param exception
//      *            The Exception which caused the test failure.
//      */
//     public static synchronized void fail(final Throwable exception) {
//         exception.printStackTrace(System.err);
//         org.junit.Assert.fail(exception.getMessage());
//     }
// 
//     /**
//      * Fails the test in which this method is called with the message that an
//      * Exception should have been thrown on the previous line.
//      */
//     public static void shouldHaveThrownException() {
//         org.junit.Assert.fail(EXCEPTION_MSG);
//     }
// 
//     /** Instantiation disallowed. */
//     private TestUtils() {
//         // intentionally unimplemented
//     }
// }
// 
// Path: src/main/java/analyticalengine/cards/BadCard.java
// public class BadCard extends CardException {
// 
//     /**
//      * A default generated serial version UID.
//      */
//     private static final long serialVersionUID = -3311831632309378417L;
// 
//     /**
//      * Instantiates this exception with the specified error message and the
//      * specified card that caused the exception.
//      * 
//      * @param message
//      *            The error message.
//      * @param cause
//      *            The card that caused this exception.
//      */
//     public BadCard(final String message, final Card cause) {
//         super(message, cause);
//     }
// 
//     /**
//      * Instantiates this exception with the specified error message, card that
//      * caused the exception, and exception that caused the exception.
//      * 
//      * @param message
//      *            The error message.
//      * @param cardCause
//      *            The card that caused the exception.
//      * @param throwableCause
//      *            The throwable that caused this exception.
//      */
//     public BadCard(final String message, final Card cardCause,
//             final Throwable throwableCause) {
//         super(message, cardCause, throwableCause);
//     }
// 
// }
// 
// Path: src/main/java/analyticalengine/cards/UnknownCard.java
// public class UnknownCard extends Exception {
// 
//     /**
//      * A default generated serial version UID.
//      */
//     private static final long serialVersionUID = -5748344376227284027L;
// 
//     /**
//      * Creates a new exception with the specified error message.
//      * 
//      * @param string
//      *            The error message.
//      */
//     public UnknownCard(final String string) {
//         super(string);
//     }
// 
// }
 | 
	import analyticalengine.cards.UnknownCard;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.Test;
import analyticalengine.TestUtils;
import analyticalengine.cards.BadCard; | 
	/**
 * DefaultAttendantTest.java -
 * 
 * Copyright 2014-2016 Jeffrey Finkelstein.
 * 
 * This file is part of analyticalengine.
 * 
 * analyticalengine is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option)
 * any later version.
 * 
 * analyticalengine is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * analyticalengine. If not, see <http://www.gnu.org/licenses/>.
 */
package analyticalengine.attendant;
/**
 * Unit tets for the default attendant implementation.
 * 
 * @author Jeffrey Finkelstein <[email protected]>
 * @since 0.0.1
 */
public class DefaultAttendantTest extends AttendantTestBase {
    /**
     * Tests for attempting to load an unknown library file.
     * 
     * @throws IOException
     * @throws UnknownCard
     * @throws BadCard
     */
    @Test
    public void testUnknownLibraryFile() | 
	// Path: src/test/java/analyticalengine/TestUtils.java
// public final class TestUtils {
// 
//     /**
//      * The message produced when {@link #shouldHaveThrownException()} is
//      * called.
//      */
//     private static final String EXCEPTION_MSG = "Exception should have been"
//             + " thrown on previous line.";
// 
//     /**
//      * Prints the stack trace of the specified Exception to stderr and calls
//      * {@link org.junit.Assert#fail(String)} in order to fail the test in which
//      * this method is called.
//      * 
//      * @param exception
//      *            The Exception which caused the test failure.
//      */
//     public static synchronized void fail(final Throwable exception) {
//         exception.printStackTrace(System.err);
//         org.junit.Assert.fail(exception.getMessage());
//     }
// 
//     /**
//      * Fails the test in which this method is called with the message that an
//      * Exception should have been thrown on the previous line.
//      */
//     public static void shouldHaveThrownException() {
//         org.junit.Assert.fail(EXCEPTION_MSG);
//     }
// 
//     /** Instantiation disallowed. */
//     private TestUtils() {
//         // intentionally unimplemented
//     }
// }
// 
// Path: src/main/java/analyticalengine/cards/BadCard.java
// public class BadCard extends CardException {
// 
//     /**
//      * A default generated serial version UID.
//      */
//     private static final long serialVersionUID = -3311831632309378417L;
// 
//     /**
//      * Instantiates this exception with the specified error message and the
//      * specified card that caused the exception.
//      * 
//      * @param message
//      *            The error message.
//      * @param cause
//      *            The card that caused this exception.
//      */
//     public BadCard(final String message, final Card cause) {
//         super(message, cause);
//     }
// 
//     /**
//      * Instantiates this exception with the specified error message, card that
//      * caused the exception, and exception that caused the exception.
//      * 
//      * @param message
//      *            The error message.
//      * @param cardCause
//      *            The card that caused the exception.
//      * @param throwableCause
//      *            The throwable that caused this exception.
//      */
//     public BadCard(final String message, final Card cardCause,
//             final Throwable throwableCause) {
//         super(message, cardCause, throwableCause);
//     }
// 
// }
// 
// Path: src/main/java/analyticalengine/cards/UnknownCard.java
// public class UnknownCard extends Exception {
// 
//     /**
//      * A default generated serial version UID.
//      */
//     private static final long serialVersionUID = -5748344376227284027L;
// 
//     /**
//      * Creates a new exception with the specified error message.
//      * 
//      * @param string
//      *            The error message.
//      */
//     public UnknownCard(final String string) {
//         super(string);
//     }
// 
// }
// Path: src/test/java/analyticalengine/attendant/DefaultAttendantTest.java
import analyticalengine.cards.UnknownCard;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.Test;
import analyticalengine.TestUtils;
import analyticalengine.cards.BadCard;
/**
 * DefaultAttendantTest.java -
 * 
 * Copyright 2014-2016 Jeffrey Finkelstein.
 * 
 * This file is part of analyticalengine.
 * 
 * analyticalengine is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option)
 * any later version.
 * 
 * analyticalengine is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * analyticalengine. If not, see <http://www.gnu.org/licenses/>.
 */
package analyticalengine.attendant;
/**
 * Unit tets for the default attendant implementation.
 * 
 * @author Jeffrey Finkelstein <[email protected]>
 * @since 0.0.1
 */
public class DefaultAttendantTest extends AttendantTestBase {
    /**
     * Tests for attempting to load an unknown library file.
     * 
     * @throws IOException
     * @throws UnknownCard
     * @throws BadCard
     */
    @Test
    public void testUnknownLibraryFile() | 
	            throws BadCard, UnknownCard, IOException { | 
| 
	jfinkels/analyticalengine | 
	src/test/java/analyticalengine/attendant/DefaultAttendantTest.java | 
	// Path: src/test/java/analyticalengine/TestUtils.java
// public final class TestUtils {
// 
//     /**
//      * The message produced when {@link #shouldHaveThrownException()} is
//      * called.
//      */
//     private static final String EXCEPTION_MSG = "Exception should have been"
//             + " thrown on previous line.";
// 
//     /**
//      * Prints the stack trace of the specified Exception to stderr and calls
//      * {@link org.junit.Assert#fail(String)} in order to fail the test in which
//      * this method is called.
//      * 
//      * @param exception
//      *            The Exception which caused the test failure.
//      */
//     public static synchronized void fail(final Throwable exception) {
//         exception.printStackTrace(System.err);
//         org.junit.Assert.fail(exception.getMessage());
//     }
// 
//     /**
//      * Fails the test in which this method is called with the message that an
//      * Exception should have been thrown on the previous line.
//      */
//     public static void shouldHaveThrownException() {
//         org.junit.Assert.fail(EXCEPTION_MSG);
//     }
// 
//     /** Instantiation disallowed. */
//     private TestUtils() {
//         // intentionally unimplemented
//     }
// }
// 
// Path: src/main/java/analyticalengine/cards/BadCard.java
// public class BadCard extends CardException {
// 
//     /**
//      * A default generated serial version UID.
//      */
//     private static final long serialVersionUID = -3311831632309378417L;
// 
//     /**
//      * Instantiates this exception with the specified error message and the
//      * specified card that caused the exception.
//      * 
//      * @param message
//      *            The error message.
//      * @param cause
//      *            The card that caused this exception.
//      */
//     public BadCard(final String message, final Card cause) {
//         super(message, cause);
//     }
// 
//     /**
//      * Instantiates this exception with the specified error message, card that
//      * caused the exception, and exception that caused the exception.
//      * 
//      * @param message
//      *            The error message.
//      * @param cardCause
//      *            The card that caused the exception.
//      * @param throwableCause
//      *            The throwable that caused this exception.
//      */
//     public BadCard(final String message, final Card cardCause,
//             final Throwable throwableCause) {
//         super(message, cardCause, throwableCause);
//     }
// 
// }
// 
// Path: src/main/java/analyticalengine/cards/UnknownCard.java
// public class UnknownCard extends Exception {
// 
//     /**
//      * A default generated serial version UID.
//      */
//     private static final long serialVersionUID = -5748344376227284027L;
// 
//     /**
//      * Creates a new exception with the specified error message.
//      * 
//      * @param string
//      *            The error message.
//      */
//     public UnknownCard(final String string) {
//         super(string);
//     }
// 
// }
 | 
	import analyticalengine.cards.UnknownCard;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.Test;
import analyticalengine.TestUtils;
import analyticalengine.cards.BadCard; | 
	/**
 * DefaultAttendantTest.java -
 * 
 * Copyright 2014-2016 Jeffrey Finkelstein.
 * 
 * This file is part of analyticalengine.
 * 
 * analyticalengine is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option)
 * any later version.
 * 
 * analyticalengine is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * analyticalengine. If not, see <http://www.gnu.org/licenses/>.
 */
package analyticalengine.attendant;
/**
 * Unit tets for the default attendant implementation.
 * 
 * @author Jeffrey Finkelstein <[email protected]>
 * @since 0.0.1
 */
public class DefaultAttendantTest extends AttendantTestBase {
    /**
     * Tests for attempting to load an unknown library file.
     * 
     * @throws IOException
     * @throws UnknownCard
     * @throws BadCard
     */
    @Test
    public void testUnknownLibraryFile() | 
	// Path: src/test/java/analyticalengine/TestUtils.java
// public final class TestUtils {
// 
//     /**
//      * The message produced when {@link #shouldHaveThrownException()} is
//      * called.
//      */
//     private static final String EXCEPTION_MSG = "Exception should have been"
//             + " thrown on previous line.";
// 
//     /**
//      * Prints the stack trace of the specified Exception to stderr and calls
//      * {@link org.junit.Assert#fail(String)} in order to fail the test in which
//      * this method is called.
//      * 
//      * @param exception
//      *            The Exception which caused the test failure.
//      */
//     public static synchronized void fail(final Throwable exception) {
//         exception.printStackTrace(System.err);
//         org.junit.Assert.fail(exception.getMessage());
//     }
// 
//     /**
//      * Fails the test in which this method is called with the message that an
//      * Exception should have been thrown on the previous line.
//      */
//     public static void shouldHaveThrownException() {
//         org.junit.Assert.fail(EXCEPTION_MSG);
//     }
// 
//     /** Instantiation disallowed. */
//     private TestUtils() {
//         // intentionally unimplemented
//     }
// }
// 
// Path: src/main/java/analyticalengine/cards/BadCard.java
// public class BadCard extends CardException {
// 
//     /**
//      * A default generated serial version UID.
//      */
//     private static final long serialVersionUID = -3311831632309378417L;
// 
//     /**
//      * Instantiates this exception with the specified error message and the
//      * specified card that caused the exception.
//      * 
//      * @param message
//      *            The error message.
//      * @param cause
//      *            The card that caused this exception.
//      */
//     public BadCard(final String message, final Card cause) {
//         super(message, cause);
//     }
// 
//     /**
//      * Instantiates this exception with the specified error message, card that
//      * caused the exception, and exception that caused the exception.
//      * 
//      * @param message
//      *            The error message.
//      * @param cardCause
//      *            The card that caused the exception.
//      * @param throwableCause
//      *            The throwable that caused this exception.
//      */
//     public BadCard(final String message, final Card cardCause,
//             final Throwable throwableCause) {
//         super(message, cardCause, throwableCause);
//     }
// 
// }
// 
// Path: src/main/java/analyticalengine/cards/UnknownCard.java
// public class UnknownCard extends Exception {
// 
//     /**
//      * A default generated serial version UID.
//      */
//     private static final long serialVersionUID = -5748344376227284027L;
// 
//     /**
//      * Creates a new exception with the specified error message.
//      * 
//      * @param string
//      *            The error message.
//      */
//     public UnknownCard(final String string) {
//         super(string);
//     }
// 
// }
// Path: src/test/java/analyticalengine/attendant/DefaultAttendantTest.java
import analyticalengine.cards.UnknownCard;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.Test;
import analyticalengine.TestUtils;
import analyticalengine.cards.BadCard;
/**
 * DefaultAttendantTest.java -
 * 
 * Copyright 2014-2016 Jeffrey Finkelstein.
 * 
 * This file is part of analyticalengine.
 * 
 * analyticalengine is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option)
 * any later version.
 * 
 * analyticalengine is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * analyticalengine. If not, see <http://www.gnu.org/licenses/>.
 */
package analyticalengine.attendant;
/**
 * Unit tets for the default attendant implementation.
 * 
 * @author Jeffrey Finkelstein <[email protected]>
 * @since 0.0.1
 */
public class DefaultAttendantTest extends AttendantTestBase {
    /**
     * Tests for attempting to load an unknown library file.
     * 
     * @throws IOException
     * @throws UnknownCard
     * @throws BadCard
     */
    @Test
    public void testUnknownLibraryFile() | 
	            throws BadCard, UnknownCard, IOException { | 
| 
	jfinkels/analyticalengine | 
	src/test/java/analyticalengine/attendant/DefaultAttendantTest.java | 
	// Path: src/test/java/analyticalengine/TestUtils.java
// public final class TestUtils {
// 
//     /**
//      * The message produced when {@link #shouldHaveThrownException()} is
//      * called.
//      */
//     private static final String EXCEPTION_MSG = "Exception should have been"
//             + " thrown on previous line.";
// 
//     /**
//      * Prints the stack trace of the specified Exception to stderr and calls
//      * {@link org.junit.Assert#fail(String)} in order to fail the test in which
//      * this method is called.
//      * 
//      * @param exception
//      *            The Exception which caused the test failure.
//      */
//     public static synchronized void fail(final Throwable exception) {
//         exception.printStackTrace(System.err);
//         org.junit.Assert.fail(exception.getMessage());
//     }
// 
//     /**
//      * Fails the test in which this method is called with the message that an
//      * Exception should have been thrown on the previous line.
//      */
//     public static void shouldHaveThrownException() {
//         org.junit.Assert.fail(EXCEPTION_MSG);
//     }
// 
//     /** Instantiation disallowed. */
//     private TestUtils() {
//         // intentionally unimplemented
//     }
// }
// 
// Path: src/main/java/analyticalengine/cards/BadCard.java
// public class BadCard extends CardException {
// 
//     /**
//      * A default generated serial version UID.
//      */
//     private static final long serialVersionUID = -3311831632309378417L;
// 
//     /**
//      * Instantiates this exception with the specified error message and the
//      * specified card that caused the exception.
//      * 
//      * @param message
//      *            The error message.
//      * @param cause
//      *            The card that caused this exception.
//      */
//     public BadCard(final String message, final Card cause) {
//         super(message, cause);
//     }
// 
//     /**
//      * Instantiates this exception with the specified error message, card that
//      * caused the exception, and exception that caused the exception.
//      * 
//      * @param message
//      *            The error message.
//      * @param cardCause
//      *            The card that caused the exception.
//      * @param throwableCause
//      *            The throwable that caused this exception.
//      */
//     public BadCard(final String message, final Card cardCause,
//             final Throwable throwableCause) {
//         super(message, cardCause, throwableCause);
//     }
// 
// }
// 
// Path: src/main/java/analyticalengine/cards/UnknownCard.java
// public class UnknownCard extends Exception {
// 
//     /**
//      * A default generated serial version UID.
//      */
//     private static final long serialVersionUID = -5748344376227284027L;
// 
//     /**
//      * Creates a new exception with the specified error message.
//      * 
//      * @param string
//      *            The error message.
//      */
//     public UnknownCard(final String string) {
//         super(string);
//     }
// 
// }
 | 
	import analyticalengine.cards.UnknownCard;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.Test;
import analyticalengine.TestUtils;
import analyticalengine.cards.BadCard; | 
	/**
 * DefaultAttendantTest.java -
 * 
 * Copyright 2014-2016 Jeffrey Finkelstein.
 * 
 * This file is part of analyticalengine.
 * 
 * analyticalengine is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option)
 * any later version.
 * 
 * analyticalengine is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * analyticalengine. If not, see <http://www.gnu.org/licenses/>.
 */
package analyticalengine.attendant;
/**
 * Unit tets for the default attendant implementation.
 * 
 * @author Jeffrey Finkelstein <[email protected]>
 * @since 0.0.1
 */
public class DefaultAttendantTest extends AttendantTestBase {
    /**
     * Tests for attempting to load an unknown library file.
     * 
     * @throws IOException
     * @throws UnknownCard
     * @throws BadCard
     */
    @Test
    public void testUnknownLibraryFile()
            throws BadCard, UnknownCard, IOException {
        try {
            this.loadProgramString("A include from library cards for bogus"); | 
	// Path: src/test/java/analyticalengine/TestUtils.java
// public final class TestUtils {
// 
//     /**
//      * The message produced when {@link #shouldHaveThrownException()} is
//      * called.
//      */
//     private static final String EXCEPTION_MSG = "Exception should have been"
//             + " thrown on previous line.";
// 
//     /**
//      * Prints the stack trace of the specified Exception to stderr and calls
//      * {@link org.junit.Assert#fail(String)} in order to fail the test in which
//      * this method is called.
//      * 
//      * @param exception
//      *            The Exception which caused the test failure.
//      */
//     public static synchronized void fail(final Throwable exception) {
//         exception.printStackTrace(System.err);
//         org.junit.Assert.fail(exception.getMessage());
//     }
// 
//     /**
//      * Fails the test in which this method is called with the message that an
//      * Exception should have been thrown on the previous line.
//      */
//     public static void shouldHaveThrownException() {
//         org.junit.Assert.fail(EXCEPTION_MSG);
//     }
// 
//     /** Instantiation disallowed. */
//     private TestUtils() {
//         // intentionally unimplemented
//     }
// }
// 
// Path: src/main/java/analyticalengine/cards/BadCard.java
// public class BadCard extends CardException {
// 
//     /**
//      * A default generated serial version UID.
//      */
//     private static final long serialVersionUID = -3311831632309378417L;
// 
//     /**
//      * Instantiates this exception with the specified error message and the
//      * specified card that caused the exception.
//      * 
//      * @param message
//      *            The error message.
//      * @param cause
//      *            The card that caused this exception.
//      */
//     public BadCard(final String message, final Card cause) {
//         super(message, cause);
//     }
// 
//     /**
//      * Instantiates this exception with the specified error message, card that
//      * caused the exception, and exception that caused the exception.
//      * 
//      * @param message
//      *            The error message.
//      * @param cardCause
//      *            The card that caused the exception.
//      * @param throwableCause
//      *            The throwable that caused this exception.
//      */
//     public BadCard(final String message, final Card cardCause,
//             final Throwable throwableCause) {
//         super(message, cardCause, throwableCause);
//     }
// 
// }
// 
// Path: src/main/java/analyticalengine/cards/UnknownCard.java
// public class UnknownCard extends Exception {
// 
//     /**
//      * A default generated serial version UID.
//      */
//     private static final long serialVersionUID = -5748344376227284027L;
// 
//     /**
//      * Creates a new exception with the specified error message.
//      * 
//      * @param string
//      *            The error message.
//      */
//     public UnknownCard(final String string) {
//         super(string);
//     }
// 
// }
// Path: src/test/java/analyticalengine/attendant/DefaultAttendantTest.java
import analyticalengine.cards.UnknownCard;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.Test;
import analyticalengine.TestUtils;
import analyticalengine.cards.BadCard;
/**
 * DefaultAttendantTest.java -
 * 
 * Copyright 2014-2016 Jeffrey Finkelstein.
 * 
 * This file is part of analyticalengine.
 * 
 * analyticalengine is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option)
 * any later version.
 * 
 * analyticalengine is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * analyticalengine. If not, see <http://www.gnu.org/licenses/>.
 */
package analyticalengine.attendant;
/**
 * Unit tets for the default attendant implementation.
 * 
 * @author Jeffrey Finkelstein <[email protected]>
 * @since 0.0.1
 */
public class DefaultAttendantTest extends AttendantTestBase {
    /**
     * Tests for attempting to load an unknown library file.
     * 
     * @throws IOException
     * @throws UnknownCard
     * @throws BadCard
     */
    @Test
    public void testUnknownLibraryFile()
            throws BadCard, UnknownCard, IOException {
        try {
            this.loadProgramString("A include from library cards for bogus"); | 
	            TestUtils.shouldHaveThrownException(); | 
| 
	jfinkels/analyticalengine | 
	src/test/java/analyticalengine/main/MainTest.java | 
	// Path: src/test/java/analyticalengine/TestUtils.java
// public final class TestUtils {
// 
//     /**
//      * The message produced when {@link #shouldHaveThrownException()} is
//      * called.
//      */
//     private static final String EXCEPTION_MSG = "Exception should have been"
//             + " thrown on previous line.";
// 
//     /**
//      * Prints the stack trace of the specified Exception to stderr and calls
//      * {@link org.junit.Assert#fail(String)} in order to fail the test in which
//      * this method is called.
//      * 
//      * @param exception
//      *            The Exception which caused the test failure.
//      */
//     public static synchronized void fail(final Throwable exception) {
//         exception.printStackTrace(System.err);
//         org.junit.Assert.fail(exception.getMessage());
//     }
// 
//     /**
//      * Fails the test in which this method is called with the message that an
//      * Exception should have been thrown on the previous line.
//      */
//     public static void shouldHaveThrownException() {
//         org.junit.Assert.fail(EXCEPTION_MSG);
//     }
// 
//     /** Instantiation disallowed. */
//     private TestUtils() {
//         // intentionally unimplemented
//     }
// }
 | 
	import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import analyticalengine.TestUtils; | 
	        // write a program that includes the file with baseName
        String withoutExtension = baseName.toString().replace(".ae", "");
        try (BufferedWriter writer = Files.newBufferedWriter(tempProgram,
                Charset.defaultCharset())) {
            writer.write("A include from library cards for "
                    + withoutExtension + "\n");
        }
        // list tempDir2 first, so we expect 28 as output
        String[] argv = new String[] { "-X", "-s", tempDir2 + ":" + tempDir1,
                tempProgram.toString() };
        Main.main(argv);
        String output = this.stdout.toString().toLowerCase();
        assertTrue(output.contains("28"));
        assertFalse(output.contains("6"));
    }
    /**
     * Test for listing the cards only.
     * 
     * @throws IOException
     *             If there is a problem reading from the test file.
     */
    @Test
    public void testList() throws IOException {
        Path testfile;
        try {
            testfile = Paths.get(this.getClass().getResource("/test_basic.ae")
                    .toURI());
        } catch (URISyntaxException e) { | 
	// Path: src/test/java/analyticalengine/TestUtils.java
// public final class TestUtils {
// 
//     /**
//      * The message produced when {@link #shouldHaveThrownException()} is
//      * called.
//      */
//     private static final String EXCEPTION_MSG = "Exception should have been"
//             + " thrown on previous line.";
// 
//     /**
//      * Prints the stack trace of the specified Exception to stderr and calls
//      * {@link org.junit.Assert#fail(String)} in order to fail the test in which
//      * this method is called.
//      * 
//      * @param exception
//      *            The Exception which caused the test failure.
//      */
//     public static synchronized void fail(final Throwable exception) {
//         exception.printStackTrace(System.err);
//         org.junit.Assert.fail(exception.getMessage());
//     }
// 
//     /**
//      * Fails the test in which this method is called with the message that an
//      * Exception should have been thrown on the previous line.
//      */
//     public static void shouldHaveThrownException() {
//         org.junit.Assert.fail(EXCEPTION_MSG);
//     }
// 
//     /** Instantiation disallowed. */
//     private TestUtils() {
//         // intentionally unimplemented
//     }
// }
// Path: src/test/java/analyticalengine/main/MainTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import analyticalengine.TestUtils;
        // write a program that includes the file with baseName
        String withoutExtension = baseName.toString().replace(".ae", "");
        try (BufferedWriter writer = Files.newBufferedWriter(tempProgram,
                Charset.defaultCharset())) {
            writer.write("A include from library cards for "
                    + withoutExtension + "\n");
        }
        // list tempDir2 first, so we expect 28 as output
        String[] argv = new String[] { "-X", "-s", tempDir2 + ":" + tempDir1,
                tempProgram.toString() };
        Main.main(argv);
        String output = this.stdout.toString().toLowerCase();
        assertTrue(output.contains("28"));
        assertFalse(output.contains("6"));
    }
    /**
     * Test for listing the cards only.
     * 
     * @throws IOException
     *             If there is a problem reading from the test file.
     */
    @Test
    public void testList() throws IOException {
        Path testfile;
        try {
            testfile = Paths.get(this.getClass().getResource("/test_basic.ae")
                    .toURI());
        } catch (URISyntaxException e) { | 
	            TestUtils.fail(e); | 
| 
	jeremiehuchet/nominatim-java-api | 
	src/main/java/fr/dudie/nominatim/client/request/OsmTypeAndIdReverseQuery.java | 
	// Path: src/main/java/fr/dudie/nominatim/client/request/paramhelper/OsmType.java
// public enum OsmType {
// 
//     /** A node. */
//     NODE("N"),
// 
//     /** A way. */
//     WAY("W"),
// 
//     /** A relation. */
//     RELATION("R");
// 
//     private static final Logger LOGGER = LoggerFactory.getLogger(OsmType.class);
// 
//     /** The parameter value. */
//     private final String value;
// 
//     private OsmType(final String param) {
//         this.value = param;
//     }
// 
//     @Override
//     public String toString() {
//         return value;
//     }
// 
//     public static OsmType from(final String type) {
//         OsmType result = null;
//         final OsmType[] v = values();
//         for (int i = 0; null == result && i < v.length; i++) {
//             if (v[i].value.equalsIgnoreCase(type)) {
//                 result = v[i];
//             }
//         }
//         if (null == result) {
//             LOGGER.warn("Unexpected OsmType value: {}. {}", type, Arrays.toString(v));
//         }
//         return result;
//     }
// }
 | 
	import fr.dudie.nominatim.client.request.paramhelper.OsmType;
import fr.dudie.nominatim.client.request.paramhelper.QueryParameter; | 
	package fr.dudie.nominatim.client.request;
/*
 * [license]
 * Nominatim Java API client
 * ~~~~
 * Copyright (C) 2010 - 2014 Dudie
 * ~~~~
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Lesser Public License for more details.
 * 
 * You should have received a copy of the GNU General Lesser Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/lgpl-3.0.html>.
 * [/license]
 */
/**
 * Holds OSM TYPE and ID of the reverse geocoding request.
 * <p>
 * Attributes documentation was extracted from <a href="https://wiki.openstreetmap.org/wiki/Nominatim">Nominatim Wiki</a>
 * page on October 26th, 2013.
 * 
 * @author Jeremie Huchet
 */
public class OsmTypeAndIdReverseQuery extends ReverseQuery {
    /**
     * The type of the searched element.
     */
    @QueryParameter("osm_type=%s") | 
	// Path: src/main/java/fr/dudie/nominatim/client/request/paramhelper/OsmType.java
// public enum OsmType {
// 
//     /** A node. */
//     NODE("N"),
// 
//     /** A way. */
//     WAY("W"),
// 
//     /** A relation. */
//     RELATION("R");
// 
//     private static final Logger LOGGER = LoggerFactory.getLogger(OsmType.class);
// 
//     /** The parameter value. */
//     private final String value;
// 
//     private OsmType(final String param) {
//         this.value = param;
//     }
// 
//     @Override
//     public String toString() {
//         return value;
//     }
// 
//     public static OsmType from(final String type) {
//         OsmType result = null;
//         final OsmType[] v = values();
//         for (int i = 0; null == result && i < v.length; i++) {
//             if (v[i].value.equalsIgnoreCase(type)) {
//                 result = v[i];
//             }
//         }
//         if (null == result) {
//             LOGGER.warn("Unexpected OsmType value: {}. {}", type, Arrays.toString(v));
//         }
//         return result;
//     }
// }
// Path: src/main/java/fr/dudie/nominatim/client/request/OsmTypeAndIdReverseQuery.java
import fr.dudie.nominatim.client.request.paramhelper.OsmType;
import fr.dudie.nominatim.client.request.paramhelper.QueryParameter;
package fr.dudie.nominatim.client.request;
/*
 * [license]
 * Nominatim Java API client
 * ~~~~
 * Copyright (C) 2010 - 2014 Dudie
 * ~~~~
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Lesser Public License for more details.
 * 
 * You should have received a copy of the GNU General Lesser Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/lgpl-3.0.html>.
 * [/license]
 */
/**
 * Holds OSM TYPE and ID of the reverse geocoding request.
 * <p>
 * Attributes documentation was extracted from <a href="https://wiki.openstreetmap.org/wiki/Nominatim">Nominatim Wiki</a>
 * page on October 26th, 2013.
 * 
 * @author Jeremie Huchet
 */
public class OsmTypeAndIdReverseQuery extends ReverseQuery {
    /**
     * The type of the searched element.
     */
    @QueryParameter("osm_type=%s") | 
	    private OsmType type; | 
| 
	jeremiehuchet/nominatim-java-api | 
	src/test/java/fr/dudie/nominatim/client/request/NominatimReverseRequestTest.java | 
	// Path: src/main/java/fr/dudie/nominatim/client/request/paramhelper/OsmType.java
// public enum OsmType {
// 
//     /** A node. */
//     NODE("N"),
// 
//     /** A way. */
//     WAY("W"),
// 
//     /** A relation. */
//     RELATION("R");
// 
//     private static final Logger LOGGER = LoggerFactory.getLogger(OsmType.class);
// 
//     /** The parameter value. */
//     private final String value;
// 
//     private OsmType(final String param) {
//         this.value = param;
//     }
// 
//     @Override
//     public String toString() {
//         return value;
//     }
// 
//     public static OsmType from(final String type) {
//         OsmType result = null;
//         final OsmType[] v = values();
//         for (int i = 0; null == result && i < v.length; i++) {
//             if (v[i].value.equalsIgnoreCase(type)) {
//                 result = v[i];
//             }
//         }
//         if (null == result) {
//             LOGGER.warn("Unexpected OsmType value: {}. {}", type, Arrays.toString(v));
//         }
//         return result;
//     }
// }
 | 
	import static org.junit.Assert.*;
import java.io.UnsupportedEncodingException;
import org.junit.Before;
import org.junit.Test;
import fr.dudie.nominatim.client.request.paramhelper.OsmType; | 
	package fr.dudie.nominatim.client.request;
/*
 * [license]
 * Nominatim Java API client
 * ~~~~
 * Copyright (C) 2010 - 2014 Dudie
 * ~~~~
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Lesser Public License for more details.
 * 
 * You should have received a copy of the GNU General Lesser Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/lgpl-3.0.html>.
 * [/license]
 */
public class NominatimReverseRequestTest {
    private NominatimReverseRequest req;
    @Before
    public void reset() {
        req = new NominatimReverseRequest();
    }
    @Test
    public void simpleCoordQuery() throws UnsupportedEncodingException {
        req.setQuery(-1.14465546607971, 48.1462173461914);
        assertEquals("lat=48.14621734619140&lon=-1.14465546607971", req.getQueryString());
    }
    @Test
    public void simpleOsmTypeAndIdQuery() throws UnsupportedEncodingException { | 
	// Path: src/main/java/fr/dudie/nominatim/client/request/paramhelper/OsmType.java
// public enum OsmType {
// 
//     /** A node. */
//     NODE("N"),
// 
//     /** A way. */
//     WAY("W"),
// 
//     /** A relation. */
//     RELATION("R");
// 
//     private static final Logger LOGGER = LoggerFactory.getLogger(OsmType.class);
// 
//     /** The parameter value. */
//     private final String value;
// 
//     private OsmType(final String param) {
//         this.value = param;
//     }
// 
//     @Override
//     public String toString() {
//         return value;
//     }
// 
//     public static OsmType from(final String type) {
//         OsmType result = null;
//         final OsmType[] v = values();
//         for (int i = 0; null == result && i < v.length; i++) {
//             if (v[i].value.equalsIgnoreCase(type)) {
//                 result = v[i];
//             }
//         }
//         if (null == result) {
//             LOGGER.warn("Unexpected OsmType value: {}. {}", type, Arrays.toString(v));
//         }
//         return result;
//     }
// }
// Path: src/test/java/fr/dudie/nominatim/client/request/NominatimReverseRequestTest.java
import static org.junit.Assert.*;
import java.io.UnsupportedEncodingException;
import org.junit.Before;
import org.junit.Test;
import fr.dudie.nominatim.client.request.paramhelper.OsmType;
package fr.dudie.nominatim.client.request;
/*
 * [license]
 * Nominatim Java API client
 * ~~~~
 * Copyright (C) 2010 - 2014 Dudie
 * ~~~~
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Lesser Public License for more details.
 * 
 * You should have received a copy of the GNU General Lesser Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/lgpl-3.0.html>.
 * [/license]
 */
public class NominatimReverseRequestTest {
    private NominatimReverseRequest req;
    @Before
    public void reset() {
        req = new NominatimReverseRequest();
    }
    @Test
    public void simpleCoordQuery() throws UnsupportedEncodingException {
        req.setQuery(-1.14465546607971, 48.1462173461914);
        assertEquals("lat=48.14621734619140&lon=-1.14465546607971", req.getQueryString());
    }
    @Test
    public void simpleOsmTypeAndIdQuery() throws UnsupportedEncodingException { | 
	        req.setQuery(OsmType.NODE, 12345); | 
| 
	jeremiehuchet/nominatim-java-api | 
	src/main/java/fr/dudie/nominatim/client/request/NominatimReverseRequest.java | 
	// Path: src/main/java/fr/dudie/nominatim/client/request/paramhelper/BooleanSerializer.java
// public class BooleanSerializer implements QueryParameterSerializer {
// 
//     /**
//      * Converts the input value into a nominatim boolean parameter.
//      * 
//      * @return either <code>1</code> or <code>0</code>
//      * @see fr.dudie.nominatim.client.request.paramhelper.QueryParameterSerializer#handle(java.lang.Object)
//      */
//     @Override
//     public String handle(final Object value) {
//         if (Boolean.parseBoolean(value.toString())) {
//             return "1";
//         } else {
//             return "0";
//         }
//     }
// 
// }
// 
// Path: src/main/java/fr/dudie/nominatim/client/request/paramhelper/OsmType.java
// public enum OsmType {
// 
//     /** A node. */
//     NODE("N"),
// 
//     /** A way. */
//     WAY("W"),
// 
//     /** A relation. */
//     RELATION("R");
// 
//     private static final Logger LOGGER = LoggerFactory.getLogger(OsmType.class);
// 
//     /** The parameter value. */
//     private final String value;
// 
//     private OsmType(final String param) {
//         this.value = param;
//     }
// 
//     @Override
//     public String toString() {
//         return value;
//     }
// 
//     public static OsmType from(final String type) {
//         OsmType result = null;
//         final OsmType[] v = values();
//         for (int i = 0; null == result && i < v.length; i++) {
//             if (v[i].value.equalsIgnoreCase(type)) {
//                 result = v[i];
//             }
//         }
//         if (null == result) {
//             LOGGER.warn("Unexpected OsmType value: {}. {}", type, Arrays.toString(v));
//         }
//         return result;
//     }
// }
 | 
	import fr.dudie.nominatim.client.request.paramhelper.BooleanSerializer;
import fr.dudie.nominatim.client.request.paramhelper.OsmType;
import fr.dudie.nominatim.client.request.paramhelper.QueryParameter; | 
	package fr.dudie.nominatim.client.request;
/*
 * [license]
 * Nominatim Java API client
 * ~~~~
 * Copyright (C) 2010 - 2014 Dudie
 * ~~~~
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Lesser Public License for more details.
 * 
 * You should have received a copy of the GNU General Lesser Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/lgpl-3.0.html>.
 * [/license]
 */
/**
 * Holds request parameters for a reverse geocoding request.
 * <p>
 * Attributes documentation was extracted from <a href="https://wiki.openstreetmap.org/wiki/Nominatim">Nominatim Wiki</a>
 * page on October 26th, 2013.
 * 
 * @author Jeremie Huchet
 */
public class NominatimReverseRequest extends NominatimRequest {
    /**
     * Preferred language order for showing search results, overrides the browser value. Either uses standard rfc2616
     * accept-language string or a simple comma separated list of language codes.
     */
    @QueryParameter("accept-language=%s")
    private String acceptLanguage;
    /** Holds the OSM reverse geocoding request. */
    @QueryParameter
    private ReverseQuery query;
    /** Level of detail required where 0 is country and 18 is house/building. */
    @QueryParameter("zoom=%s")
    private Integer zoom;
    /** Include a breakdown of the address into elements. */ | 
	// Path: src/main/java/fr/dudie/nominatim/client/request/paramhelper/BooleanSerializer.java
// public class BooleanSerializer implements QueryParameterSerializer {
// 
//     /**
//      * Converts the input value into a nominatim boolean parameter.
//      * 
//      * @return either <code>1</code> or <code>0</code>
//      * @see fr.dudie.nominatim.client.request.paramhelper.QueryParameterSerializer#handle(java.lang.Object)
//      */
//     @Override
//     public String handle(final Object value) {
//         if (Boolean.parseBoolean(value.toString())) {
//             return "1";
//         } else {
//             return "0";
//         }
//     }
// 
// }
// 
// Path: src/main/java/fr/dudie/nominatim/client/request/paramhelper/OsmType.java
// public enum OsmType {
// 
//     /** A node. */
//     NODE("N"),
// 
//     /** A way. */
//     WAY("W"),
// 
//     /** A relation. */
//     RELATION("R");
// 
//     private static final Logger LOGGER = LoggerFactory.getLogger(OsmType.class);
// 
//     /** The parameter value. */
//     private final String value;
// 
//     private OsmType(final String param) {
//         this.value = param;
//     }
// 
//     @Override
//     public String toString() {
//         return value;
//     }
// 
//     public static OsmType from(final String type) {
//         OsmType result = null;
//         final OsmType[] v = values();
//         for (int i = 0; null == result && i < v.length; i++) {
//             if (v[i].value.equalsIgnoreCase(type)) {
//                 result = v[i];
//             }
//         }
//         if (null == result) {
//             LOGGER.warn("Unexpected OsmType value: {}. {}", type, Arrays.toString(v));
//         }
//         return result;
//     }
// }
// Path: src/main/java/fr/dudie/nominatim/client/request/NominatimReverseRequest.java
import fr.dudie.nominatim.client.request.paramhelper.BooleanSerializer;
import fr.dudie.nominatim.client.request.paramhelper.OsmType;
import fr.dudie.nominatim.client.request.paramhelper.QueryParameter;
package fr.dudie.nominatim.client.request;
/*
 * [license]
 * Nominatim Java API client
 * ~~~~
 * Copyright (C) 2010 - 2014 Dudie
 * ~~~~
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Lesser Public License for more details.
 * 
 * You should have received a copy of the GNU General Lesser Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/lgpl-3.0.html>.
 * [/license]
 */
/**
 * Holds request parameters for a reverse geocoding request.
 * <p>
 * Attributes documentation was extracted from <a href="https://wiki.openstreetmap.org/wiki/Nominatim">Nominatim Wiki</a>
 * page on October 26th, 2013.
 * 
 * @author Jeremie Huchet
 */
public class NominatimReverseRequest extends NominatimRequest {
    /**
     * Preferred language order for showing search results, overrides the browser value. Either uses standard rfc2616
     * accept-language string or a simple comma separated list of language codes.
     */
    @QueryParameter("accept-language=%s")
    private String acceptLanguage;
    /** Holds the OSM reverse geocoding request. */
    @QueryParameter
    private ReverseQuery query;
    /** Level of detail required where 0 is country and 18 is house/building. */
    @QueryParameter("zoom=%s")
    private Integer zoom;
    /** Include a breakdown of the address into elements. */ | 
	    @QueryParameter(value = "addressdetails=%s", serializer = BooleanSerializer.class) | 
| 
	jeremiehuchet/nominatim-java-api | 
	src/main/java/fr/dudie/nominatim/client/request/NominatimReverseRequest.java | 
	// Path: src/main/java/fr/dudie/nominatim/client/request/paramhelper/BooleanSerializer.java
// public class BooleanSerializer implements QueryParameterSerializer {
// 
//     /**
//      * Converts the input value into a nominatim boolean parameter.
//      * 
//      * @return either <code>1</code> or <code>0</code>
//      * @see fr.dudie.nominatim.client.request.paramhelper.QueryParameterSerializer#handle(java.lang.Object)
//      */
//     @Override
//     public String handle(final Object value) {
//         if (Boolean.parseBoolean(value.toString())) {
//             return "1";
//         } else {
//             return "0";
//         }
//     }
// 
// }
// 
// Path: src/main/java/fr/dudie/nominatim/client/request/paramhelper/OsmType.java
// public enum OsmType {
// 
//     /** A node. */
//     NODE("N"),
// 
//     /** A way. */
//     WAY("W"),
// 
//     /** A relation. */
//     RELATION("R");
// 
//     private static final Logger LOGGER = LoggerFactory.getLogger(OsmType.class);
// 
//     /** The parameter value. */
//     private final String value;
// 
//     private OsmType(final String param) {
//         this.value = param;
//     }
// 
//     @Override
//     public String toString() {
//         return value;
//     }
// 
//     public static OsmType from(final String type) {
//         OsmType result = null;
//         final OsmType[] v = values();
//         for (int i = 0; null == result && i < v.length; i++) {
//             if (v[i].value.equalsIgnoreCase(type)) {
//                 result = v[i];
//             }
//         }
//         if (null == result) {
//             LOGGER.warn("Unexpected OsmType value: {}. {}", type, Arrays.toString(v));
//         }
//         return result;
//     }
// }
 | 
	import fr.dudie.nominatim.client.request.paramhelper.BooleanSerializer;
import fr.dudie.nominatim.client.request.paramhelper.OsmType;
import fr.dudie.nominatim.client.request.paramhelper.QueryParameter; | 
	package fr.dudie.nominatim.client.request;
/*
 * [license]
 * Nominatim Java API client
 * ~~~~
 * Copyright (C) 2010 - 2014 Dudie
 * ~~~~
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Lesser Public License for more details.
 * 
 * You should have received a copy of the GNU General Lesser Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/lgpl-3.0.html>.
 * [/license]
 */
/**
 * Holds request parameters for a reverse geocoding request.
 * <p>
 * Attributes documentation was extracted from <a href="https://wiki.openstreetmap.org/wiki/Nominatim">Nominatim Wiki</a>
 * page on October 26th, 2013.
 * 
 * @author Jeremie Huchet
 */
public class NominatimReverseRequest extends NominatimRequest {
    /**
     * Preferred language order for showing search results, overrides the browser value. Either uses standard rfc2616
     * accept-language string or a simple comma separated list of language codes.
     */
    @QueryParameter("accept-language=%s")
    private String acceptLanguage;
    /** Holds the OSM reverse geocoding request. */
    @QueryParameter
    private ReverseQuery query;
    /** Level of detail required where 0 is country and 18 is house/building. */
    @QueryParameter("zoom=%s")
    private Integer zoom;
    /** Include a breakdown of the address into elements. */
    @QueryParameter(value = "addressdetails=%s", serializer = BooleanSerializer.class)
    private Boolean addressDetails;
    /**
     * Gets the preferred language order for showing search results which overrides the browser value.
     * 
     * @return the accept-language value
     */
    public String getAcceptLanguage() {
        return acceptLanguage;
    }
    /**
     * Sets the preferred language order for showing search results, overrides the browser value.
     * 
     * @param acceptLanguage
     *            a standard rfc2616 accept-language string or a simple comma separated list of language codes
     */
    public void setAcceptLanguage(final String acceptLanguage) {
        this.acceptLanguage = acceptLanguage;
    }
    /**
     * @return the reverse geocoding query parameters
     */
    public ReverseQuery getQuery() {
        return query;
    }
    /**
     * @param query
     *            the reverse geocoding query parameters to set
     */
    public void setQuery(final ReverseQuery query) {
        this.query = query;
    }
 | 
	// Path: src/main/java/fr/dudie/nominatim/client/request/paramhelper/BooleanSerializer.java
// public class BooleanSerializer implements QueryParameterSerializer {
// 
//     /**
//      * Converts the input value into a nominatim boolean parameter.
//      * 
//      * @return either <code>1</code> or <code>0</code>
//      * @see fr.dudie.nominatim.client.request.paramhelper.QueryParameterSerializer#handle(java.lang.Object)
//      */
//     @Override
//     public String handle(final Object value) {
//         if (Boolean.parseBoolean(value.toString())) {
//             return "1";
//         } else {
//             return "0";
//         }
//     }
// 
// }
// 
// Path: src/main/java/fr/dudie/nominatim/client/request/paramhelper/OsmType.java
// public enum OsmType {
// 
//     /** A node. */
//     NODE("N"),
// 
//     /** A way. */
//     WAY("W"),
// 
//     /** A relation. */
//     RELATION("R");
// 
//     private static final Logger LOGGER = LoggerFactory.getLogger(OsmType.class);
// 
//     /** The parameter value. */
//     private final String value;
// 
//     private OsmType(final String param) {
//         this.value = param;
//     }
// 
//     @Override
//     public String toString() {
//         return value;
//     }
// 
//     public static OsmType from(final String type) {
//         OsmType result = null;
//         final OsmType[] v = values();
//         for (int i = 0; null == result && i < v.length; i++) {
//             if (v[i].value.equalsIgnoreCase(type)) {
//                 result = v[i];
//             }
//         }
//         if (null == result) {
//             LOGGER.warn("Unexpected OsmType value: {}. {}", type, Arrays.toString(v));
//         }
//         return result;
//     }
// }
// Path: src/main/java/fr/dudie/nominatim/client/request/NominatimReverseRequest.java
import fr.dudie.nominatim.client.request.paramhelper.BooleanSerializer;
import fr.dudie.nominatim.client.request.paramhelper.OsmType;
import fr.dudie.nominatim.client.request.paramhelper.QueryParameter;
package fr.dudie.nominatim.client.request;
/*
 * [license]
 * Nominatim Java API client
 * ~~~~
 * Copyright (C) 2010 - 2014 Dudie
 * ~~~~
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Lesser Public License for more details.
 * 
 * You should have received a copy of the GNU General Lesser Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/lgpl-3.0.html>.
 * [/license]
 */
/**
 * Holds request parameters for a reverse geocoding request.
 * <p>
 * Attributes documentation was extracted from <a href="https://wiki.openstreetmap.org/wiki/Nominatim">Nominatim Wiki</a>
 * page on October 26th, 2013.
 * 
 * @author Jeremie Huchet
 */
public class NominatimReverseRequest extends NominatimRequest {
    /**
     * Preferred language order for showing search results, overrides the browser value. Either uses standard rfc2616
     * accept-language string or a simple comma separated list of language codes.
     */
    @QueryParameter("accept-language=%s")
    private String acceptLanguage;
    /** Holds the OSM reverse geocoding request. */
    @QueryParameter
    private ReverseQuery query;
    /** Level of detail required where 0 is country and 18 is house/building. */
    @QueryParameter("zoom=%s")
    private Integer zoom;
    /** Include a breakdown of the address into elements. */
    @QueryParameter(value = "addressdetails=%s", serializer = BooleanSerializer.class)
    private Boolean addressDetails;
    /**
     * Gets the preferred language order for showing search results which overrides the browser value.
     * 
     * @return the accept-language value
     */
    public String getAcceptLanguage() {
        return acceptLanguage;
    }
    /**
     * Sets the preferred language order for showing search results, overrides the browser value.
     * 
     * @param acceptLanguage
     *            a standard rfc2616 accept-language string or a simple comma separated list of language codes
     */
    public void setAcceptLanguage(final String acceptLanguage) {
        this.acceptLanguage = acceptLanguage;
    }
    /**
     * @return the reverse geocoding query parameters
     */
    public ReverseQuery getQuery() {
        return query;
    }
    /**
     * @param query
     *            the reverse geocoding query parameters to set
     */
    public void setQuery(final ReverseQuery query) {
        this.query = query;
    }
 | 
	    public void setQuery(final OsmType type, final long id) { | 
| 
	jeremiehuchet/nominatim-java-api | 
	src/main/java/fr/dudie/nominatim/client/request/NominatimLookupRequest.java | 
	// Path: src/main/java/fr/dudie/nominatim/client/request/paramhelper/BooleanSerializer.java
// public class BooleanSerializer implements QueryParameterSerializer {
// 
//     /**
//      * Converts the input value into a nominatim boolean parameter.
//      * 
//      * @return either <code>1</code> or <code>0</code>
//      * @see fr.dudie.nominatim.client.request.paramhelper.QueryParameterSerializer#handle(java.lang.Object)
//      */
//     @Override
//     public String handle(final Object value) {
//         if (Boolean.parseBoolean(value.toString())) {
//             return "1";
//         } else {
//             return "0";
//         }
//     }
// 
// }
 | 
	import java.util.List;
import fr.dudie.nominatim.client.request.paramhelper.BooleanSerializer;
import fr.dudie.nominatim.client.request.paramhelper.QueryParameter; | 
	package fr.dudie.nominatim.client.request;
/*
 * [license]
 * Nominatim Java API client
 * ~~~~
 * Copyright (C) 2010 - 2014 Dudie
 * ~~~~
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Lesser Public License for more details.
 * 
 * You should have received a copy of the GNU General Lesser Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/lgpl-3.0.html>.
 * [/license]
 */
/**
 * Holds request parameters for a lookup request.
 * <p>
 * Attributes documentation was extracted from <a href="https://wiki.openstreetmap.org/wiki/Nominatim">Nominatim Wiki</a>
 * page on September 1st, 2015.
 * 
 * @author Sunil D S
 */
public class NominatimLookupRequest extends NominatimRequest {
    /**
     * Preferred language order for showing search results, overrides the browser value. Either uses standard rfc2616
     * accept-language string or a simple comma separated list of language codes.
     */
    @QueryParameter("accept-language=%s")
    private String acceptLanguage;
    /** Holds the OSM lookup request. */
    @QueryParameter
    private LookupQuery query;
    /** Include a breakdown of the address into elements. */ | 
	// Path: src/main/java/fr/dudie/nominatim/client/request/paramhelper/BooleanSerializer.java
// public class BooleanSerializer implements QueryParameterSerializer {
// 
//     /**
//      * Converts the input value into a nominatim boolean parameter.
//      * 
//      * @return either <code>1</code> or <code>0</code>
//      * @see fr.dudie.nominatim.client.request.paramhelper.QueryParameterSerializer#handle(java.lang.Object)
//      */
//     @Override
//     public String handle(final Object value) {
//         if (Boolean.parseBoolean(value.toString())) {
//             return "1";
//         } else {
//             return "0";
//         }
//     }
// 
// }
// Path: src/main/java/fr/dudie/nominatim/client/request/NominatimLookupRequest.java
import java.util.List;
import fr.dudie.nominatim.client.request.paramhelper.BooleanSerializer;
import fr.dudie.nominatim.client.request.paramhelper.QueryParameter;
package fr.dudie.nominatim.client.request;
/*
 * [license]
 * Nominatim Java API client
 * ~~~~
 * Copyright (C) 2010 - 2014 Dudie
 * ~~~~
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Lesser Public License for more details.
 * 
 * You should have received a copy of the GNU General Lesser Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/lgpl-3.0.html>.
 * [/license]
 */
/**
 * Holds request parameters for a lookup request.
 * <p>
 * Attributes documentation was extracted from <a href="https://wiki.openstreetmap.org/wiki/Nominatim">Nominatim Wiki</a>
 * page on September 1st, 2015.
 * 
 * @author Sunil D S
 */
public class NominatimLookupRequest extends NominatimRequest {
    /**
     * Preferred language order for showing search results, overrides the browser value. Either uses standard rfc2616
     * accept-language string or a simple comma separated list of language codes.
     */
    @QueryParameter("accept-language=%s")
    private String acceptLanguage;
    /** Holds the OSM lookup request. */
    @QueryParameter
    private LookupQuery query;
    /** Include a breakdown of the address into elements. */ | 
	    @QueryParameter(value = "addressdetails=%s", serializer = BooleanSerializer.class) | 
| 
	jeremiehuchet/nominatim-java-api | 
	src/main/java/fr/dudie/nominatim/client/request/QueryParameterAnnotationHandler.java | 
	// Path: src/main/java/fr/dudie/nominatim/client/request/paramhelper/ToStringSerializer.java
// public class ToStringSerializer implements QueryParameterSerializer {
// 
//     /**
//      * {@inheritDoc}
//      * 
//      * @see fr.dudie.nominatim.client.request.paramhelper.QueryParameterSerializer#handle(java.lang.Object)
//      */
//     @Override
//     public String handle(final Object value) {
//         if (value instanceof NominatimRequest) {
//             return ((NominatimRequest) value).getQueryString();
//         } else {
//             return value.toString();
//         }
//     }
// }
 | 
	import fr.dudie.nominatim.client.request.paramhelper.QueryParameter;
import fr.dudie.nominatim.client.request.paramhelper.ToStringSerializer;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | 
	    }
    private static String uriEncode(String paramValue) {
        try {
            return new URI(null, null, null, paramValue, null).getRawQuery();
        } catch (final URISyntaxException e) {
            LOGGER.error("Failure encoding query parameter value {}", new Object[] { paramValue, e });
            return paramValue;
        }
    }
    /**
     * Serializes the field value regardless of reflection errors. Fallback to the {@link ToStringSerializer}.
     * 
     * @param paramMetadata
     *            the query parameter annotation
     * @param fieldValue
     *            the field value
     * @param fieldName
     *            the field name (for logging purposes only)
     * @return the serialized value
     * @throws UnsupportedEncodingException
     *             UTF-8 encoding issue
     */
    private static String serialize(final QueryParameter paramMetadata, final Object fieldValue, final String fieldName) {
        String paramValue;
        try {
            paramValue = paramMetadata.serializer().newInstance().handle(fieldValue);
        } catch (final InstantiationException e) {
            LOGGER.error("Failure while serializing field {}", new Object[] { fieldName, e }); | 
	// Path: src/main/java/fr/dudie/nominatim/client/request/paramhelper/ToStringSerializer.java
// public class ToStringSerializer implements QueryParameterSerializer {
// 
//     /**
//      * {@inheritDoc}
//      * 
//      * @see fr.dudie.nominatim.client.request.paramhelper.QueryParameterSerializer#handle(java.lang.Object)
//      */
//     @Override
//     public String handle(final Object value) {
//         if (value instanceof NominatimRequest) {
//             return ((NominatimRequest) value).getQueryString();
//         } else {
//             return value.toString();
//         }
//     }
// }
// Path: src/main/java/fr/dudie/nominatim/client/request/QueryParameterAnnotationHandler.java
import fr.dudie.nominatim.client.request.paramhelper.QueryParameter;
import fr.dudie.nominatim.client.request.paramhelper.ToStringSerializer;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
    }
    private static String uriEncode(String paramValue) {
        try {
            return new URI(null, null, null, paramValue, null).getRawQuery();
        } catch (final URISyntaxException e) {
            LOGGER.error("Failure encoding query parameter value {}", new Object[] { paramValue, e });
            return paramValue;
        }
    }
    /**
     * Serializes the field value regardless of reflection errors. Fallback to the {@link ToStringSerializer}.
     * 
     * @param paramMetadata
     *            the query parameter annotation
     * @param fieldValue
     *            the field value
     * @param fieldName
     *            the field name (for logging purposes only)
     * @return the serialized value
     * @throws UnsupportedEncodingException
     *             UTF-8 encoding issue
     */
    private static String serialize(final QueryParameter paramMetadata, final Object fieldValue, final String fieldName) {
        String paramValue;
        try {
            paramValue = paramMetadata.serializer().newInstance().handle(fieldValue);
        } catch (final InstantiationException e) {
            LOGGER.error("Failure while serializing field {}", new Object[] { fieldName, e }); | 
	            paramValue = new ToStringSerializer().handle(fieldValue); | 
| 
	jeremiehuchet/nominatim-java-api | 
	src/test/java/fr/dudie/nominatim/client/request/NominatimSearchRequestTest.java | 
	// Path: src/main/java/fr/dudie/nominatim/model/BoundingBox.java
// public class BoundingBox implements Serializable {
// 
//     /** The north bound of the boundingbox. */
//     private double north;
// 
//     /** The west bound of the boundingbox. */
//     private double west;
// 
//     /** The east bound of the boundingbox. */
//     private double east;
// 
//     /** The south bound of the boundingbox. */
//     private double south;
// 
//     /**
//      * Gets the north.
//      * 
//      * @return the north
//      */
//     public final double getNorth() {
// 
//         return north;
//     }
// 
//     /**
//      * Gets the north.
//      * 
//      * @return the north
//      */
//     public final int getNorthE6() {
// 
//         return (int) (north * 1E6);
//     }
// 
//     /**
//      * Sets the north.
//      * 
//      * @param north
//      *            the north to set
//      */
//     public final void setNorth(final double north) {
// 
//         this.north = north;
//     }
// 
//     /**
//      * Sets the north.
//      * 
//      * @param north
//      *            the north to set
//      */
//     public final void setNorthE6(final int north) {
// 
//         this.north = north / 1E6;
//     }
// 
//     /**
//      * Gets the west.
//      * 
//      * @return the west
//      */
//     public final double getWest() {
// 
//         return west;
//     }
// 
//     /**
//      * Gets the west.
//      * 
//      * @return the west
//      */
//     public final int getWestE6() {
// 
//         return (int) (west * 1E6);
//     }
// 
//     /**
//      * Sets the west.
//      * 
//      * @param west
//      *            the west to set
//      */
//     public final void setWest(final double west) {
// 
//         this.west = west;
//     }
// 
//     /**
//      * Sets the west.
//      * 
//      * @param west
//      *            the west to set
//      */
//     public final void setWestE6(final int west) {
// 
//         this.west = west / 1E6;
//     }
// 
//     /**
//      * Gets the east.
//      * 
//      * @return the east
//      */
//     public final double getEast() {
// 
//         return east;
//     }
// 
//     /**
//      * Gets the east.
//      * 
//      * @return the east
//      */
//     public final int getEastE6() {
// 
//         return (int) (east * 1E6);
//     }
// 
//     /**
//      * Sets the east.
//      * 
//      * @param east
//      *            the east to set
//      */
//     public final void setEast(final double east) {
// 
//         this.east = east;
//     }
// 
//     /**
//      * Sets the east.
//      * 
//      * @param east
//      *            the east to set
//      */
//     public final void setEastE6(final int east) {
// 
//         this.east = east / 1E6;
//     }
// 
//     /**
//      * Gets the south.
//      * 
//      * @return the south
//      */
//     public final double getSouth() {
// 
//         return south;
//     }
// 
//     /**
//      * Gets the south.
//      * 
//      * @return the south
//      */
//     public final int getSouthE6() {
// 
//         return (int) (south * 1E6);
//     }
// 
//     /**
//      * Sets the south.
//      * 
//      * @param south
//      *            the south to set
//      */
//     public final void setSouth(final double south) {
// 
//         this.south = south;
//     }
// 
//     /**
//      * Sets the south.
//      * 
//      * @param south
//      *            the south to set
//      */
//     public final void setSouthE6(final int south) {
// 
//         this.south = south / 1E6;
//     }
// 
// }
 | 
	import fr.dudie.nominatim.model.BoundingBox;
import org.junit.Before;
import org.junit.Test;
import java.io.UnsupportedEncodingException;
import static org.junit.Assert.assertEquals; | 
	    }
    @Test
    public void simpleQueryWithoutAddress() throws UnsupportedEncodingException {
        req.setQuery("france");
        req.setAddress(false);
        assertEquals("q=france&addressdetails=0", req.getQueryString());
    }
    @Test
    public void simpleQueryWithCountryCodes() throws UnsupportedEncodingException {
        req.setQuery("france");
        req.addCountryCode("FR");
        assertEquals("q=france&countrycodes=FR", req.getQueryString());
        req.addCountryCode("BE");
        assertEquals("q=france&countrycodes=FR,BE", req.getQueryString());
    }
    @Test
    public void simpleQueryWithViewBox() throws UnsupportedEncodingException {
        final double w = -1.14465546607971;
        final double n = 48.1462173461914;
        final double e = -1.24950230121613;
        final double s = 48.0747871398926;
        final String expectedQueryString = "q=france&viewbox=-1.14465546607971,48.14621734619140,-1.24950230121613,48.07478713989260";
        final String expectedQueryStringE6 = "q=france&viewbox=-1.14465500000000,48.14621700000000,-1.24950200000000,48.07478700000000";
        req.setQuery("france"); | 
	// Path: src/main/java/fr/dudie/nominatim/model/BoundingBox.java
// public class BoundingBox implements Serializable {
// 
//     /** The north bound of the boundingbox. */
//     private double north;
// 
//     /** The west bound of the boundingbox. */
//     private double west;
// 
//     /** The east bound of the boundingbox. */
//     private double east;
// 
//     /** The south bound of the boundingbox. */
//     private double south;
// 
//     /**
//      * Gets the north.
//      * 
//      * @return the north
//      */
//     public final double getNorth() {
// 
//         return north;
//     }
// 
//     /**
//      * Gets the north.
//      * 
//      * @return the north
//      */
//     public final int getNorthE6() {
// 
//         return (int) (north * 1E6);
//     }
// 
//     /**
//      * Sets the north.
//      * 
//      * @param north
//      *            the north to set
//      */
//     public final void setNorth(final double north) {
// 
//         this.north = north;
//     }
// 
//     /**
//      * Sets the north.
//      * 
//      * @param north
//      *            the north to set
//      */
//     public final void setNorthE6(final int north) {
// 
//         this.north = north / 1E6;
//     }
// 
//     /**
//      * Gets the west.
//      * 
//      * @return the west
//      */
//     public final double getWest() {
// 
//         return west;
//     }
// 
//     /**
//      * Gets the west.
//      * 
//      * @return the west
//      */
//     public final int getWestE6() {
// 
//         return (int) (west * 1E6);
//     }
// 
//     /**
//      * Sets the west.
//      * 
//      * @param west
//      *            the west to set
//      */
//     public final void setWest(final double west) {
// 
//         this.west = west;
//     }
// 
//     /**
//      * Sets the west.
//      * 
//      * @param west
//      *            the west to set
//      */
//     public final void setWestE6(final int west) {
// 
//         this.west = west / 1E6;
//     }
// 
//     /**
//      * Gets the east.
//      * 
//      * @return the east
//      */
//     public final double getEast() {
// 
//         return east;
//     }
// 
//     /**
//      * Gets the east.
//      * 
//      * @return the east
//      */
//     public final int getEastE6() {
// 
//         return (int) (east * 1E6);
//     }
// 
//     /**
//      * Sets the east.
//      * 
//      * @param east
//      *            the east to set
//      */
//     public final void setEast(final double east) {
// 
//         this.east = east;
//     }
// 
//     /**
//      * Sets the east.
//      * 
//      * @param east
//      *            the east to set
//      */
//     public final void setEastE6(final int east) {
// 
//         this.east = east / 1E6;
//     }
// 
//     /**
//      * Gets the south.
//      * 
//      * @return the south
//      */
//     public final double getSouth() {
// 
//         return south;
//     }
// 
//     /**
//      * Gets the south.
//      * 
//      * @return the south
//      */
//     public final int getSouthE6() {
// 
//         return (int) (south * 1E6);
//     }
// 
//     /**
//      * Sets the south.
//      * 
//      * @param south
//      *            the south to set
//      */
//     public final void setSouth(final double south) {
// 
//         this.south = south;
//     }
// 
//     /**
//      * Sets the south.
//      * 
//      * @param south
//      *            the south to set
//      */
//     public final void setSouthE6(final int south) {
// 
//         this.south = south / 1E6;
//     }
// 
// }
// Path: src/test/java/fr/dudie/nominatim/client/request/NominatimSearchRequestTest.java
import fr.dudie.nominatim.model.BoundingBox;
import org.junit.Before;
import org.junit.Test;
import java.io.UnsupportedEncodingException;
import static org.junit.Assert.assertEquals;
    }
    @Test
    public void simpleQueryWithoutAddress() throws UnsupportedEncodingException {
        req.setQuery("france");
        req.setAddress(false);
        assertEquals("q=france&addressdetails=0", req.getQueryString());
    }
    @Test
    public void simpleQueryWithCountryCodes() throws UnsupportedEncodingException {
        req.setQuery("france");
        req.addCountryCode("FR");
        assertEquals("q=france&countrycodes=FR", req.getQueryString());
        req.addCountryCode("BE");
        assertEquals("q=france&countrycodes=FR,BE", req.getQueryString());
    }
    @Test
    public void simpleQueryWithViewBox() throws UnsupportedEncodingException {
        final double w = -1.14465546607971;
        final double n = 48.1462173461914;
        final double e = -1.24950230121613;
        final double s = 48.0747871398926;
        final String expectedQueryString = "q=france&viewbox=-1.14465546607971,48.14621734619140,-1.24950230121613,48.07478713989260";
        final String expectedQueryStringE6 = "q=france&viewbox=-1.14465500000000,48.14621700000000,-1.24950200000000,48.07478700000000";
        req.setQuery("france"); | 
	        final BoundingBox bbox = new BoundingBox(); | 
| 
	dangdangdotcom/config-toolkit | 
	config-toolkit-demo/src/main/java/com/dangdang/config/service/easyzk/demo/spring/SpelSupportTest.java | 
	// Path: config-toolkit/src/main/java/com/dangdang/config/service/GeneralConfigGroup.java
// public abstract class GeneralConfigGroup extends ConcurrentHashMap<String, String> implements ConfigGroup {
// 
//     private static final long serialVersionUID = 1L;
// 
//     private ConfigGroup internalConfigGroup;
// 
//     /**
//      * 兼容spring,是否通过EnumerablePropertySource加载配置组
//      */
//     protected boolean enumerable = false;
// 
//     protected GeneralConfigGroup(ConfigGroup internalConfigGroup) {
//         this.internalConfigGroup = internalConfigGroup;
//     }
// 
//     private static final Logger LOGGER = LoggerFactory.getLogger(GeneralConfigGroup.class);
// 
//     /**
//      * 配置组的最后加载时间
//      */
//     private long lastLoadTime;
// 
//     public long getLastLoadTime() {
//         return lastLoadTime;
//     }
// 
//     @Override
//     public final String get(String key) {
//         String val = super.get(key);
//         if (val == null && internalConfigGroup != null) {
//             val = internalConfigGroup.get(key);
//         }
//         return val;
//     }
// 
//     @Override
//     public final String get(Object key) {
//         return get(key.toString());
//     }
// 
//     protected final void cleanAndPutAll(Map<? extends String, ? extends String> configs) {
//         lastLoadTime = System.currentTimeMillis();
//         if (configs != null && configs.size() > 0) {
//             // clear
//             if (this.size() > 0) {
//                 for (String key : new HashSet<>(this.keySet())) {
//                     if (!configs.containsKey(key)) {
//                         super.remove(key);
//                     }
//                 }
//             }
// 
//             // update
//             for (Map.Entry<? extends String, ? extends String> entry : configs.entrySet()) {
//                 this.put(entry.getKey(), entry.getValue());
//             }
// 
//         } else {
//             LOGGER.debug("Config group has none keys, clear.");
//             super.clear();
//         }
//     }
// 
//     @Override
//     public final String put(String key, String value) {
//         if (value != null) {
//             value = value.trim();
//         }
//         String preValue = super.get(key);
//         if (value != null && !value.equals(preValue)) {
//             LOGGER.debug("Key " + key + " change from {} to {}", preValue, value);
//             super.put(key, value);
// 
//             // If value change, notify
//             if (preValue != null) {
//                 notify(key, value);
//             }
//         }
//         return preValue;
//     }
// 
//     /**
//      * 观察者列表
//      */
//     private final List<IObserver> watchers = new ArrayList<>();
// 
//     @Override
//     public void register(final IObserver watcher) {
//         if(watcher == null) {
//             throw new IllegalArgumentException("watcher cannot be null");
//         }
//         watchers.add(watcher);
//     }
// 
//     @Override
//     public void notify(final String key, final String value) {
//         for (final IObserver watcher : watchers) {
//             new Thread(new Runnable() {
// 
//                 @Override
//                 public void run() {
//                     watcher.notified(key, value);
//                 }
//             }).start();
//         }
//     }
// 
//     @Override
//     public String remove(Object key) {
//         throw new UnsupportedOperationException();
//     }
// 
//     @Override
//     public void clear() {
//         throw new UnsupportedOperationException();
//     }
// 
//     @Override
//     public boolean isEnumerable() {
//         return this.enumerable;
//     }
// }
// 
// Path: config-toolkit-demo/src/main/java/com/dangdang/config/service/easyzk/demo/simple/ExampleBeanWithSpel.java
// @Component
// @RefreshScope
// @EnableAutoConfiguration // somewhere
// public class ExampleBeanWithSpel {
// 
// 	@Value("#{propertyGroup1['string_property_key']}")
// 	private String stringProperty;
// 
// 	@Value("#{propertyGroup1['int_property_key']}")
// 	private int intProperty;
// 
// 	private String computedValue;
// 
// 	@PostConstruct
// 	private void init() {
// 		computedValue = stringProperty + intProperty;
// 	}
// 
// 	public void someMethod() {
// 		System.out.println(String.format("My properties: [%s] - [%s] - [%s]", stringProperty, intProperty, computedValue));
// 	}
// 
// }
// 
// Path: config-toolkit/src/main/java/com/dangdang/config/service/observer/IObserver.java
// public interface IObserver {
// 
// 	/**
// 	 * 通知
// 	 * 
// 	 * @param data
// 	 */
// 	void notified(String data, String value);
// 
// }
 | 
	import org.springframework.cloud.context.scope.refresh.RefreshScope;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.dangdang.config.service.GeneralConfigGroup;
import com.dangdang.config.service.easyzk.demo.simple.ExampleBeanWithSpel;
import com.dangdang.config.service.observer.IObserver; | 
	package com.dangdang.config.service.easyzk.demo.spring;
/**
 * @author <a href="mailto:[email protected]">Yuxuan Wang</a>
 *
 */
public class SpelSupportTest {
	public static void main(String[] args) {
		try (final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:config-toolkit-simple.xml")) {
			context.registerShutdownHook();
			context.start();
 | 
	// Path: config-toolkit/src/main/java/com/dangdang/config/service/GeneralConfigGroup.java
// public abstract class GeneralConfigGroup extends ConcurrentHashMap<String, String> implements ConfigGroup {
// 
//     private static final long serialVersionUID = 1L;
// 
//     private ConfigGroup internalConfigGroup;
// 
//     /**
//      * 兼容spring,是否通过EnumerablePropertySource加载配置组
//      */
//     protected boolean enumerable = false;
// 
//     protected GeneralConfigGroup(ConfigGroup internalConfigGroup) {
//         this.internalConfigGroup = internalConfigGroup;
//     }
// 
//     private static final Logger LOGGER = LoggerFactory.getLogger(GeneralConfigGroup.class);
// 
//     /**
//      * 配置组的最后加载时间
//      */
//     private long lastLoadTime;
// 
//     public long getLastLoadTime() {
//         return lastLoadTime;
//     }
// 
//     @Override
//     public final String get(String key) {
//         String val = super.get(key);
//         if (val == null && internalConfigGroup != null) {
//             val = internalConfigGroup.get(key);
//         }
//         return val;
//     }
// 
//     @Override
//     public final String get(Object key) {
//         return get(key.toString());
//     }
// 
//     protected final void cleanAndPutAll(Map<? extends String, ? extends String> configs) {
//         lastLoadTime = System.currentTimeMillis();
//         if (configs != null && configs.size() > 0) {
//             // clear
//             if (this.size() > 0) {
//                 for (String key : new HashSet<>(this.keySet())) {
//                     if (!configs.containsKey(key)) {
//                         super.remove(key);
//                     }
//                 }
//             }
// 
//             // update
//             for (Map.Entry<? extends String, ? extends String> entry : configs.entrySet()) {
//                 this.put(entry.getKey(), entry.getValue());
//             }
// 
//         } else {
//             LOGGER.debug("Config group has none keys, clear.");
//             super.clear();
//         }
//     }
// 
//     @Override
//     public final String put(String key, String value) {
//         if (value != null) {
//             value = value.trim();
//         }
//         String preValue = super.get(key);
//         if (value != null && !value.equals(preValue)) {
//             LOGGER.debug("Key " + key + " change from {} to {}", preValue, value);
//             super.put(key, value);
// 
//             // If value change, notify
//             if (preValue != null) {
//                 notify(key, value);
//             }
//         }
//         return preValue;
//     }
// 
//     /**
//      * 观察者列表
//      */
//     private final List<IObserver> watchers = new ArrayList<>();
// 
//     @Override
//     public void register(final IObserver watcher) {
//         if(watcher == null) {
//             throw new IllegalArgumentException("watcher cannot be null");
//         }
//         watchers.add(watcher);
//     }
// 
//     @Override
//     public void notify(final String key, final String value) {
//         for (final IObserver watcher : watchers) {
//             new Thread(new Runnable() {
// 
//                 @Override
//                 public void run() {
//                     watcher.notified(key, value);
//                 }
//             }).start();
//         }
//     }
// 
//     @Override
//     public String remove(Object key) {
//         throw new UnsupportedOperationException();
//     }
// 
//     @Override
//     public void clear() {
//         throw new UnsupportedOperationException();
//     }
// 
//     @Override
//     public boolean isEnumerable() {
//         return this.enumerable;
//     }
// }
// 
// Path: config-toolkit-demo/src/main/java/com/dangdang/config/service/easyzk/demo/simple/ExampleBeanWithSpel.java
// @Component
// @RefreshScope
// @EnableAutoConfiguration // somewhere
// public class ExampleBeanWithSpel {
// 
// 	@Value("#{propertyGroup1['string_property_key']}")
// 	private String stringProperty;
// 
// 	@Value("#{propertyGroup1['int_property_key']}")
// 	private int intProperty;
// 
// 	private String computedValue;
// 
// 	@PostConstruct
// 	private void init() {
// 		computedValue = stringProperty + intProperty;
// 	}
// 
// 	public void someMethod() {
// 		System.out.println(String.format("My properties: [%s] - [%s] - [%s]", stringProperty, intProperty, computedValue));
// 	}
// 
// }
// 
// Path: config-toolkit/src/main/java/com/dangdang/config/service/observer/IObserver.java
// public interface IObserver {
// 
// 	/**
// 	 * 通知
// 	 * 
// 	 * @param data
// 	 */
// 	void notified(String data, String value);
// 
// }
// Path: config-toolkit-demo/src/main/java/com/dangdang/config/service/easyzk/demo/spring/SpelSupportTest.java
import org.springframework.cloud.context.scope.refresh.RefreshScope;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.dangdang.config.service.GeneralConfigGroup;
import com.dangdang.config.service.easyzk.demo.simple.ExampleBeanWithSpel;
import com.dangdang.config.service.observer.IObserver;
package com.dangdang.config.service.easyzk.demo.spring;
/**
 * @author <a href="mailto:[email protected]">Yuxuan Wang</a>
 *
 */
public class SpelSupportTest {
	public static void main(String[] args) {
		try (final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:config-toolkit-simple.xml")) {
			context.registerShutdownHook();
			context.start();
 | 
				ExampleBeanWithSpel bean = context.getBean(ExampleBeanWithSpel.class); | 
| 
	dangdangdotcom/config-toolkit | 
	config-toolkit-demo/src/main/java/com/dangdang/config/service/easyzk/demo/spring/SpelSupportTest.java | 
	// Path: config-toolkit/src/main/java/com/dangdang/config/service/GeneralConfigGroup.java
// public abstract class GeneralConfigGroup extends ConcurrentHashMap<String, String> implements ConfigGroup {
// 
//     private static final long serialVersionUID = 1L;
// 
//     private ConfigGroup internalConfigGroup;
// 
//     /**
//      * 兼容spring,是否通过EnumerablePropertySource加载配置组
//      */
//     protected boolean enumerable = false;
// 
//     protected GeneralConfigGroup(ConfigGroup internalConfigGroup) {
//         this.internalConfigGroup = internalConfigGroup;
//     }
// 
//     private static final Logger LOGGER = LoggerFactory.getLogger(GeneralConfigGroup.class);
// 
//     /**
//      * 配置组的最后加载时间
//      */
//     private long lastLoadTime;
// 
//     public long getLastLoadTime() {
//         return lastLoadTime;
//     }
// 
//     @Override
//     public final String get(String key) {
//         String val = super.get(key);
//         if (val == null && internalConfigGroup != null) {
//             val = internalConfigGroup.get(key);
//         }
//         return val;
//     }
// 
//     @Override
//     public final String get(Object key) {
//         return get(key.toString());
//     }
// 
//     protected final void cleanAndPutAll(Map<? extends String, ? extends String> configs) {
//         lastLoadTime = System.currentTimeMillis();
//         if (configs != null && configs.size() > 0) {
//             // clear
//             if (this.size() > 0) {
//                 for (String key : new HashSet<>(this.keySet())) {
//                     if (!configs.containsKey(key)) {
//                         super.remove(key);
//                     }
//                 }
//             }
// 
//             // update
//             for (Map.Entry<? extends String, ? extends String> entry : configs.entrySet()) {
//                 this.put(entry.getKey(), entry.getValue());
//             }
// 
//         } else {
//             LOGGER.debug("Config group has none keys, clear.");
//             super.clear();
//         }
//     }
// 
//     @Override
//     public final String put(String key, String value) {
//         if (value != null) {
//             value = value.trim();
//         }
//         String preValue = super.get(key);
//         if (value != null && !value.equals(preValue)) {
//             LOGGER.debug("Key " + key + " change from {} to {}", preValue, value);
//             super.put(key, value);
// 
//             // If value change, notify
//             if (preValue != null) {
//                 notify(key, value);
//             }
//         }
//         return preValue;
//     }
// 
//     /**
//      * 观察者列表
//      */
//     private final List<IObserver> watchers = new ArrayList<>();
// 
//     @Override
//     public void register(final IObserver watcher) {
//         if(watcher == null) {
//             throw new IllegalArgumentException("watcher cannot be null");
//         }
//         watchers.add(watcher);
//     }
// 
//     @Override
//     public void notify(final String key, final String value) {
//         for (final IObserver watcher : watchers) {
//             new Thread(new Runnable() {
// 
//                 @Override
//                 public void run() {
//                     watcher.notified(key, value);
//                 }
//             }).start();
//         }
//     }
// 
//     @Override
//     public String remove(Object key) {
//         throw new UnsupportedOperationException();
//     }
// 
//     @Override
//     public void clear() {
//         throw new UnsupportedOperationException();
//     }
// 
//     @Override
//     public boolean isEnumerable() {
//         return this.enumerable;
//     }
// }
// 
// Path: config-toolkit-demo/src/main/java/com/dangdang/config/service/easyzk/demo/simple/ExampleBeanWithSpel.java
// @Component
// @RefreshScope
// @EnableAutoConfiguration // somewhere
// public class ExampleBeanWithSpel {
// 
// 	@Value("#{propertyGroup1['string_property_key']}")
// 	private String stringProperty;
// 
// 	@Value("#{propertyGroup1['int_property_key']}")
// 	private int intProperty;
// 
// 	private String computedValue;
// 
// 	@PostConstruct
// 	private void init() {
// 		computedValue = stringProperty + intProperty;
// 	}
// 
// 	public void someMethod() {
// 		System.out.println(String.format("My properties: [%s] - [%s] - [%s]", stringProperty, intProperty, computedValue));
// 	}
// 
// }
// 
// Path: config-toolkit/src/main/java/com/dangdang/config/service/observer/IObserver.java
// public interface IObserver {
// 
// 	/**
// 	 * 通知
// 	 * 
// 	 * @param data
// 	 */
// 	void notified(String data, String value);
// 
// }
 | 
	import org.springframework.cloud.context.scope.refresh.RefreshScope;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.dangdang.config.service.GeneralConfigGroup;
import com.dangdang.config.service.easyzk.demo.simple.ExampleBeanWithSpel;
import com.dangdang.config.service.observer.IObserver; | 
	package com.dangdang.config.service.easyzk.demo.spring;
/**
 * @author <a href="mailto:[email protected]">Yuxuan Wang</a>
 *
 */
public class SpelSupportTest {
	public static void main(String[] args) {
		try (final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:config-toolkit-simple.xml")) {
			context.registerShutdownHook();
			context.start();
			ExampleBeanWithSpel bean = context.getBean(ExampleBeanWithSpel.class); | 
	// Path: config-toolkit/src/main/java/com/dangdang/config/service/GeneralConfigGroup.java
// public abstract class GeneralConfigGroup extends ConcurrentHashMap<String, String> implements ConfigGroup {
// 
//     private static final long serialVersionUID = 1L;
// 
//     private ConfigGroup internalConfigGroup;
// 
//     /**
//      * 兼容spring,是否通过EnumerablePropertySource加载配置组
//      */
//     protected boolean enumerable = false;
// 
//     protected GeneralConfigGroup(ConfigGroup internalConfigGroup) {
//         this.internalConfigGroup = internalConfigGroup;
//     }
// 
//     private static final Logger LOGGER = LoggerFactory.getLogger(GeneralConfigGroup.class);
// 
//     /**
//      * 配置组的最后加载时间
//      */
//     private long lastLoadTime;
// 
//     public long getLastLoadTime() {
//         return lastLoadTime;
//     }
// 
//     @Override
//     public final String get(String key) {
//         String val = super.get(key);
//         if (val == null && internalConfigGroup != null) {
//             val = internalConfigGroup.get(key);
//         }
//         return val;
//     }
// 
//     @Override
//     public final String get(Object key) {
//         return get(key.toString());
//     }
// 
//     protected final void cleanAndPutAll(Map<? extends String, ? extends String> configs) {
//         lastLoadTime = System.currentTimeMillis();
//         if (configs != null && configs.size() > 0) {
//             // clear
//             if (this.size() > 0) {
//                 for (String key : new HashSet<>(this.keySet())) {
//                     if (!configs.containsKey(key)) {
//                         super.remove(key);
//                     }
//                 }
//             }
// 
//             // update
//             for (Map.Entry<? extends String, ? extends String> entry : configs.entrySet()) {
//                 this.put(entry.getKey(), entry.getValue());
//             }
// 
//         } else {
//             LOGGER.debug("Config group has none keys, clear.");
//             super.clear();
//         }
//     }
// 
//     @Override
//     public final String put(String key, String value) {
//         if (value != null) {
//             value = value.trim();
//         }
//         String preValue = super.get(key);
//         if (value != null && !value.equals(preValue)) {
//             LOGGER.debug("Key " + key + " change from {} to {}", preValue, value);
//             super.put(key, value);
// 
//             // If value change, notify
//             if (preValue != null) {
//                 notify(key, value);
//             }
//         }
//         return preValue;
//     }
// 
//     /**
//      * 观察者列表
//      */
//     private final List<IObserver> watchers = new ArrayList<>();
// 
//     @Override
//     public void register(final IObserver watcher) {
//         if(watcher == null) {
//             throw new IllegalArgumentException("watcher cannot be null");
//         }
//         watchers.add(watcher);
//     }
// 
//     @Override
//     public void notify(final String key, final String value) {
//         for (final IObserver watcher : watchers) {
//             new Thread(new Runnable() {
// 
//                 @Override
//                 public void run() {
//                     watcher.notified(key, value);
//                 }
//             }).start();
//         }
//     }
// 
//     @Override
//     public String remove(Object key) {
//         throw new UnsupportedOperationException();
//     }
// 
//     @Override
//     public void clear() {
//         throw new UnsupportedOperationException();
//     }
// 
//     @Override
//     public boolean isEnumerable() {
//         return this.enumerable;
//     }
// }
// 
// Path: config-toolkit-demo/src/main/java/com/dangdang/config/service/easyzk/demo/simple/ExampleBeanWithSpel.java
// @Component
// @RefreshScope
// @EnableAutoConfiguration // somewhere
// public class ExampleBeanWithSpel {
// 
// 	@Value("#{propertyGroup1['string_property_key']}")
// 	private String stringProperty;
// 
// 	@Value("#{propertyGroup1['int_property_key']}")
// 	private int intProperty;
// 
// 	private String computedValue;
// 
// 	@PostConstruct
// 	private void init() {
// 		computedValue = stringProperty + intProperty;
// 	}
// 
// 	public void someMethod() {
// 		System.out.println(String.format("My properties: [%s] - [%s] - [%s]", stringProperty, intProperty, computedValue));
// 	}
// 
// }
// 
// Path: config-toolkit/src/main/java/com/dangdang/config/service/observer/IObserver.java
// public interface IObserver {
// 
// 	/**
// 	 * 通知
// 	 * 
// 	 * @param data
// 	 */
// 	void notified(String data, String value);
// 
// }
// Path: config-toolkit-demo/src/main/java/com/dangdang/config/service/easyzk/demo/spring/SpelSupportTest.java
import org.springframework.cloud.context.scope.refresh.RefreshScope;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.dangdang.config.service.GeneralConfigGroup;
import com.dangdang.config.service.easyzk.demo.simple.ExampleBeanWithSpel;
import com.dangdang.config.service.observer.IObserver;
package com.dangdang.config.service.easyzk.demo.spring;
/**
 * @author <a href="mailto:[email protected]">Yuxuan Wang</a>
 *
 */
public class SpelSupportTest {
	public static void main(String[] args) {
		try (final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:config-toolkit-simple.xml")) {
			context.registerShutdownHook();
			context.start();
			ExampleBeanWithSpel bean = context.getBean(ExampleBeanWithSpel.class); | 
				GeneralConfigGroup cg1 = (GeneralConfigGroup) context.getBean("propertyGroup1"); | 
| 
	dangdangdotcom/config-toolkit | 
	config-toolkit-demo/src/main/java/com/dangdang/config/service/easyzk/demo/spring/SpelSupportTest.java | 
	// Path: config-toolkit/src/main/java/com/dangdang/config/service/GeneralConfigGroup.java
// public abstract class GeneralConfigGroup extends ConcurrentHashMap<String, String> implements ConfigGroup {
// 
//     private static final long serialVersionUID = 1L;
// 
//     private ConfigGroup internalConfigGroup;
// 
//     /**
//      * 兼容spring,是否通过EnumerablePropertySource加载配置组
//      */
//     protected boolean enumerable = false;
// 
//     protected GeneralConfigGroup(ConfigGroup internalConfigGroup) {
//         this.internalConfigGroup = internalConfigGroup;
//     }
// 
//     private static final Logger LOGGER = LoggerFactory.getLogger(GeneralConfigGroup.class);
// 
//     /**
//      * 配置组的最后加载时间
//      */
//     private long lastLoadTime;
// 
//     public long getLastLoadTime() {
//         return lastLoadTime;
//     }
// 
//     @Override
//     public final String get(String key) {
//         String val = super.get(key);
//         if (val == null && internalConfigGroup != null) {
//             val = internalConfigGroup.get(key);
//         }
//         return val;
//     }
// 
//     @Override
//     public final String get(Object key) {
//         return get(key.toString());
//     }
// 
//     protected final void cleanAndPutAll(Map<? extends String, ? extends String> configs) {
//         lastLoadTime = System.currentTimeMillis();
//         if (configs != null && configs.size() > 0) {
//             // clear
//             if (this.size() > 0) {
//                 for (String key : new HashSet<>(this.keySet())) {
//                     if (!configs.containsKey(key)) {
//                         super.remove(key);
//                     }
//                 }
//             }
// 
//             // update
//             for (Map.Entry<? extends String, ? extends String> entry : configs.entrySet()) {
//                 this.put(entry.getKey(), entry.getValue());
//             }
// 
//         } else {
//             LOGGER.debug("Config group has none keys, clear.");
//             super.clear();
//         }
//     }
// 
//     @Override
//     public final String put(String key, String value) {
//         if (value != null) {
//             value = value.trim();
//         }
//         String preValue = super.get(key);
//         if (value != null && !value.equals(preValue)) {
//             LOGGER.debug("Key " + key + " change from {} to {}", preValue, value);
//             super.put(key, value);
// 
//             // If value change, notify
//             if (preValue != null) {
//                 notify(key, value);
//             }
//         }
//         return preValue;
//     }
// 
//     /**
//      * 观察者列表
//      */
//     private final List<IObserver> watchers = new ArrayList<>();
// 
//     @Override
//     public void register(final IObserver watcher) {
//         if(watcher == null) {
//             throw new IllegalArgumentException("watcher cannot be null");
//         }
//         watchers.add(watcher);
//     }
// 
//     @Override
//     public void notify(final String key, final String value) {
//         for (final IObserver watcher : watchers) {
//             new Thread(new Runnable() {
// 
//                 @Override
//                 public void run() {
//                     watcher.notified(key, value);
//                 }
//             }).start();
//         }
//     }
// 
//     @Override
//     public String remove(Object key) {
//         throw new UnsupportedOperationException();
//     }
// 
//     @Override
//     public void clear() {
//         throw new UnsupportedOperationException();
//     }
// 
//     @Override
//     public boolean isEnumerable() {
//         return this.enumerable;
//     }
// }
// 
// Path: config-toolkit-demo/src/main/java/com/dangdang/config/service/easyzk/demo/simple/ExampleBeanWithSpel.java
// @Component
// @RefreshScope
// @EnableAutoConfiguration // somewhere
// public class ExampleBeanWithSpel {
// 
// 	@Value("#{propertyGroup1['string_property_key']}")
// 	private String stringProperty;
// 
// 	@Value("#{propertyGroup1['int_property_key']}")
// 	private int intProperty;
// 
// 	private String computedValue;
// 
// 	@PostConstruct
// 	private void init() {
// 		computedValue = stringProperty + intProperty;
// 	}
// 
// 	public void someMethod() {
// 		System.out.println(String.format("My properties: [%s] - [%s] - [%s]", stringProperty, intProperty, computedValue));
// 	}
// 
// }
// 
// Path: config-toolkit/src/main/java/com/dangdang/config/service/observer/IObserver.java
// public interface IObserver {
// 
// 	/**
// 	 * 通知
// 	 * 
// 	 * @param data
// 	 */
// 	void notified(String data, String value);
// 
// }
 | 
	import org.springframework.cloud.context.scope.refresh.RefreshScope;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.dangdang.config.service.GeneralConfigGroup;
import com.dangdang.config.service.easyzk.demo.simple.ExampleBeanWithSpel;
import com.dangdang.config.service.observer.IObserver; | 
	package com.dangdang.config.service.easyzk.demo.spring;
/**
 * @author <a href="mailto:[email protected]">Yuxuan Wang</a>
 *
 */
public class SpelSupportTest {
	public static void main(String[] args) {
		try (final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:config-toolkit-simple.xml")) {
			context.registerShutdownHook();
			context.start();
			ExampleBeanWithSpel bean = context.getBean(ExampleBeanWithSpel.class);
			GeneralConfigGroup cg1 = (GeneralConfigGroup) context.getBean("propertyGroup1");
			 | 
	// Path: config-toolkit/src/main/java/com/dangdang/config/service/GeneralConfigGroup.java
// public abstract class GeneralConfigGroup extends ConcurrentHashMap<String, String> implements ConfigGroup {
// 
//     private static final long serialVersionUID = 1L;
// 
//     private ConfigGroup internalConfigGroup;
// 
//     /**
//      * 兼容spring,是否通过EnumerablePropertySource加载配置组
//      */
//     protected boolean enumerable = false;
// 
//     protected GeneralConfigGroup(ConfigGroup internalConfigGroup) {
//         this.internalConfigGroup = internalConfigGroup;
//     }
// 
//     private static final Logger LOGGER = LoggerFactory.getLogger(GeneralConfigGroup.class);
// 
//     /**
//      * 配置组的最后加载时间
//      */
//     private long lastLoadTime;
// 
//     public long getLastLoadTime() {
//         return lastLoadTime;
//     }
// 
//     @Override
//     public final String get(String key) {
//         String val = super.get(key);
//         if (val == null && internalConfigGroup != null) {
//             val = internalConfigGroup.get(key);
//         }
//         return val;
//     }
// 
//     @Override
//     public final String get(Object key) {
//         return get(key.toString());
//     }
// 
//     protected final void cleanAndPutAll(Map<? extends String, ? extends String> configs) {
//         lastLoadTime = System.currentTimeMillis();
//         if (configs != null && configs.size() > 0) {
//             // clear
//             if (this.size() > 0) {
//                 for (String key : new HashSet<>(this.keySet())) {
//                     if (!configs.containsKey(key)) {
//                         super.remove(key);
//                     }
//                 }
//             }
// 
//             // update
//             for (Map.Entry<? extends String, ? extends String> entry : configs.entrySet()) {
//                 this.put(entry.getKey(), entry.getValue());
//             }
// 
//         } else {
//             LOGGER.debug("Config group has none keys, clear.");
//             super.clear();
//         }
//     }
// 
//     @Override
//     public final String put(String key, String value) {
//         if (value != null) {
//             value = value.trim();
//         }
//         String preValue = super.get(key);
//         if (value != null && !value.equals(preValue)) {
//             LOGGER.debug("Key " + key + " change from {} to {}", preValue, value);
//             super.put(key, value);
// 
//             // If value change, notify
//             if (preValue != null) {
//                 notify(key, value);
//             }
//         }
//         return preValue;
//     }
// 
//     /**
//      * 观察者列表
//      */
//     private final List<IObserver> watchers = new ArrayList<>();
// 
//     @Override
//     public void register(final IObserver watcher) {
//         if(watcher == null) {
//             throw new IllegalArgumentException("watcher cannot be null");
//         }
//         watchers.add(watcher);
//     }
// 
//     @Override
//     public void notify(final String key, final String value) {
//         for (final IObserver watcher : watchers) {
//             new Thread(new Runnable() {
// 
//                 @Override
//                 public void run() {
//                     watcher.notified(key, value);
//                 }
//             }).start();
//         }
//     }
// 
//     @Override
//     public String remove(Object key) {
//         throw new UnsupportedOperationException();
//     }
// 
//     @Override
//     public void clear() {
//         throw new UnsupportedOperationException();
//     }
// 
//     @Override
//     public boolean isEnumerable() {
//         return this.enumerable;
//     }
// }
// 
// Path: config-toolkit-demo/src/main/java/com/dangdang/config/service/easyzk/demo/simple/ExampleBeanWithSpel.java
// @Component
// @RefreshScope
// @EnableAutoConfiguration // somewhere
// public class ExampleBeanWithSpel {
// 
// 	@Value("#{propertyGroup1['string_property_key']}")
// 	private String stringProperty;
// 
// 	@Value("#{propertyGroup1['int_property_key']}")
// 	private int intProperty;
// 
// 	private String computedValue;
// 
// 	@PostConstruct
// 	private void init() {
// 		computedValue = stringProperty + intProperty;
// 	}
// 
// 	public void someMethod() {
// 		System.out.println(String.format("My properties: [%s] - [%s] - [%s]", stringProperty, intProperty, computedValue));
// 	}
// 
// }
// 
// Path: config-toolkit/src/main/java/com/dangdang/config/service/observer/IObserver.java
// public interface IObserver {
// 
// 	/**
// 	 * 通知
// 	 * 
// 	 * @param data
// 	 */
// 	void notified(String data, String value);
// 
// }
// Path: config-toolkit-demo/src/main/java/com/dangdang/config/service/easyzk/demo/spring/SpelSupportTest.java
import org.springframework.cloud.context.scope.refresh.RefreshScope;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.dangdang.config.service.GeneralConfigGroup;
import com.dangdang.config.service.easyzk.demo.simple.ExampleBeanWithSpel;
import com.dangdang.config.service.observer.IObserver;
package com.dangdang.config.service.easyzk.demo.spring;
/**
 * @author <a href="mailto:[email protected]">Yuxuan Wang</a>
 *
 */
public class SpelSupportTest {
	public static void main(String[] args) {
		try (final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:config-toolkit-simple.xml")) {
			context.registerShutdownHook();
			context.start();
			ExampleBeanWithSpel bean = context.getBean(ExampleBeanWithSpel.class);
			GeneralConfigGroup cg1 = (GeneralConfigGroup) context.getBean("propertyGroup1");
			 | 
				cg1.register(new IObserver() { | 
| 
	dangdangdotcom/config-toolkit | 
	config-toolkit/src/main/java/com/dangdang/config/service/sugar/RefreshableBox.java | 
	// Path: config-toolkit/src/main/java/com/dangdang/config/service/GeneralConfigGroup.java
// public abstract class GeneralConfigGroup extends ConcurrentHashMap<String, String> implements ConfigGroup {
// 
//     private static final long serialVersionUID = 1L;
// 
//     private ConfigGroup internalConfigGroup;
// 
//     /**
//      * 兼容spring,是否通过EnumerablePropertySource加载配置组
//      */
//     protected boolean enumerable = false;
// 
//     protected GeneralConfigGroup(ConfigGroup internalConfigGroup) {
//         this.internalConfigGroup = internalConfigGroup;
//     }
// 
//     private static final Logger LOGGER = LoggerFactory.getLogger(GeneralConfigGroup.class);
// 
//     /**
//      * 配置组的最后加载时间
//      */
//     private long lastLoadTime;
// 
//     public long getLastLoadTime() {
//         return lastLoadTime;
//     }
// 
//     @Override
//     public final String get(String key) {
//         String val = super.get(key);
//         if (val == null && internalConfigGroup != null) {
//             val = internalConfigGroup.get(key);
//         }
//         return val;
//     }
// 
//     @Override
//     public final String get(Object key) {
//         return get(key.toString());
//     }
// 
//     protected final void cleanAndPutAll(Map<? extends String, ? extends String> configs) {
//         lastLoadTime = System.currentTimeMillis();
//         if (configs != null && configs.size() > 0) {
//             // clear
//             if (this.size() > 0) {
//                 for (String key : new HashSet<>(this.keySet())) {
//                     if (!configs.containsKey(key)) {
//                         super.remove(key);
//                     }
//                 }
//             }
// 
//             // update
//             for (Map.Entry<? extends String, ? extends String> entry : configs.entrySet()) {
//                 this.put(entry.getKey(), entry.getValue());
//             }
// 
//         } else {
//             LOGGER.debug("Config group has none keys, clear.");
//             super.clear();
//         }
//     }
// 
//     @Override
//     public final String put(String key, String value) {
//         if (value != null) {
//             value = value.trim();
//         }
//         String preValue = super.get(key);
//         if (value != null && !value.equals(preValue)) {
//             LOGGER.debug("Key " + key + " change from {} to {}", preValue, value);
//             super.put(key, value);
// 
//             // If value change, notify
//             if (preValue != null) {
//                 notify(key, value);
//             }
//         }
//         return preValue;
//     }
// 
//     /**
//      * 观察者列表
//      */
//     private final List<IObserver> watchers = new ArrayList<>();
// 
//     @Override
//     public void register(final IObserver watcher) {
//         if(watcher == null) {
//             throw new IllegalArgumentException("watcher cannot be null");
//         }
//         watchers.add(watcher);
//     }
// 
//     @Override
//     public void notify(final String key, final String value) {
//         for (final IObserver watcher : watchers) {
//             new Thread(new Runnable() {
// 
//                 @Override
//                 public void run() {
//                     watcher.notified(key, value);
//                 }
//             }).start();
//         }
//     }
// 
//     @Override
//     public String remove(Object key) {
//         throw new UnsupportedOperationException();
//     }
// 
//     @Override
//     public void clear() {
//         throw new UnsupportedOperationException();
//     }
// 
//     @Override
//     public boolean isEnumerable() {
//         return this.enumerable;
//     }
// }
// 
// Path: config-toolkit/src/main/java/com/dangdang/config/service/observer/IObserver.java
// public interface IObserver {
// 
// 	/**
// 	 * 通知
// 	 * 
// 	 * @param data
// 	 */
// 	void notified(String data, String value);
// 
// }
 | 
	import com.dangdang.config.service.GeneralConfigGroup;
import com.dangdang.config.service.observer.IObserver;
import java.util.List;
import java.util.concurrent.locks.ReentrantReadWriteLock; | 
	/**
 * Copyright 1999-2014 dangdang.com.
 *  
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.dangdang.config.service.sugar;
/**
 * 根据属性变化自刷新的容器
 * 
 * @author <a href="mailto:[email protected]">Yuxuan Wang</a>
 *
 */
public abstract class RefreshableBox<T> implements IObserver {
	/**
	 * 真实对象
	 */
	private T obj;
	/**
	 * 会影响真实对象的属性值,为空时代表任意属性变化都会刷新对象
	 */
	private List<String> propertyKeysCare;
 | 
	// Path: config-toolkit/src/main/java/com/dangdang/config/service/GeneralConfigGroup.java
// public abstract class GeneralConfigGroup extends ConcurrentHashMap<String, String> implements ConfigGroup {
// 
//     private static final long serialVersionUID = 1L;
// 
//     private ConfigGroup internalConfigGroup;
// 
//     /**
//      * 兼容spring,是否通过EnumerablePropertySource加载配置组
//      */
//     protected boolean enumerable = false;
// 
//     protected GeneralConfigGroup(ConfigGroup internalConfigGroup) {
//         this.internalConfigGroup = internalConfigGroup;
//     }
// 
//     private static final Logger LOGGER = LoggerFactory.getLogger(GeneralConfigGroup.class);
// 
//     /**
//      * 配置组的最后加载时间
//      */
//     private long lastLoadTime;
// 
//     public long getLastLoadTime() {
//         return lastLoadTime;
//     }
// 
//     @Override
//     public final String get(String key) {
//         String val = super.get(key);
//         if (val == null && internalConfigGroup != null) {
//             val = internalConfigGroup.get(key);
//         }
//         return val;
//     }
// 
//     @Override
//     public final String get(Object key) {
//         return get(key.toString());
//     }
// 
//     protected final void cleanAndPutAll(Map<? extends String, ? extends String> configs) {
//         lastLoadTime = System.currentTimeMillis();
//         if (configs != null && configs.size() > 0) {
//             // clear
//             if (this.size() > 0) {
//                 for (String key : new HashSet<>(this.keySet())) {
//                     if (!configs.containsKey(key)) {
//                         super.remove(key);
//                     }
//                 }
//             }
// 
//             // update
//             for (Map.Entry<? extends String, ? extends String> entry : configs.entrySet()) {
//                 this.put(entry.getKey(), entry.getValue());
//             }
// 
//         } else {
//             LOGGER.debug("Config group has none keys, clear.");
//             super.clear();
//         }
//     }
// 
//     @Override
//     public final String put(String key, String value) {
//         if (value != null) {
//             value = value.trim();
//         }
//         String preValue = super.get(key);
//         if (value != null && !value.equals(preValue)) {
//             LOGGER.debug("Key " + key + " change from {} to {}", preValue, value);
//             super.put(key, value);
// 
//             // If value change, notify
//             if (preValue != null) {
//                 notify(key, value);
//             }
//         }
//         return preValue;
//     }
// 
//     /**
//      * 观察者列表
//      */
//     private final List<IObserver> watchers = new ArrayList<>();
// 
//     @Override
//     public void register(final IObserver watcher) {
//         if(watcher == null) {
//             throw new IllegalArgumentException("watcher cannot be null");
//         }
//         watchers.add(watcher);
//     }
// 
//     @Override
//     public void notify(final String key, final String value) {
//         for (final IObserver watcher : watchers) {
//             new Thread(new Runnable() {
// 
//                 @Override
//                 public void run() {
//                     watcher.notified(key, value);
//                 }
//             }).start();
//         }
//     }
// 
//     @Override
//     public String remove(Object key) {
//         throw new UnsupportedOperationException();
//     }
// 
//     @Override
//     public void clear() {
//         throw new UnsupportedOperationException();
//     }
// 
//     @Override
//     public boolean isEnumerable() {
//         return this.enumerable;
//     }
// }
// 
// Path: config-toolkit/src/main/java/com/dangdang/config/service/observer/IObserver.java
// public interface IObserver {
// 
// 	/**
// 	 * 通知
// 	 * 
// 	 * @param data
// 	 */
// 	void notified(String data, String value);
// 
// }
// Path: config-toolkit/src/main/java/com/dangdang/config/service/sugar/RefreshableBox.java
import com.dangdang.config.service.GeneralConfigGroup;
import com.dangdang.config.service.observer.IObserver;
import java.util.List;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
 * Copyright 1999-2014 dangdang.com.
 *  
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.dangdang.config.service.sugar;
/**
 * 根据属性变化自刷新的容器
 * 
 * @author <a href="mailto:[email protected]">Yuxuan Wang</a>
 *
 */
public abstract class RefreshableBox<T> implements IObserver {
	/**
	 * 真实对象
	 */
	private T obj;
	/**
	 * 会影响真实对象的属性值,为空时代表任意属性变化都会刷新对象
	 */
	private List<String> propertyKeysCare;
 | 
		private GeneralConfigGroup node; | 
| 
	dangdangdotcom/config-toolkit | 
	config-toolkit/src/main/java/com/dangdang/config/service/file/contenttype/XmlContentType.java | 
	// Path: config-toolkit/src/main/java/com/dangdang/config/service/exception/InvalidPathException.java
// public class InvalidPathException extends ConfigToolkitException {
// 
// 	private static final long serialVersionUID = 1L;
// 
// 	public InvalidPathException() {
// 		super();
// 	}
// 
// 	public InvalidPathException(String message, Throwable cause) {
// 		super(message, cause);
// 	}
// 
// 	public InvalidPathException(String message) {
// 		super(message);
// 	}
// 
// 	public InvalidPathException(Throwable cause) {
// 		super(cause);
// 	}
// 
// }
 | 
	import com.dangdang.config.service.exception.InvalidPathException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties; | 
	package com.dangdang.config.service.file.contenttype;
/**
 * <p>
 * The XML document must have the following DOCTYPE declaration:
 * 
 * <pre>
 * <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
 * </pre>
 * 
 * Furthermore, the document must satisfy the properties DTD described above.
 * 
 * @author <a href="mailto:[email protected]">Yuxuan Wang</a>
 *
 */
public class XmlContentType implements ContentType {
	@Override | 
	// Path: config-toolkit/src/main/java/com/dangdang/config/service/exception/InvalidPathException.java
// public class InvalidPathException extends ConfigToolkitException {
// 
// 	private static final long serialVersionUID = 1L;
// 
// 	public InvalidPathException() {
// 		super();
// 	}
// 
// 	public InvalidPathException(String message, Throwable cause) {
// 		super(message, cause);
// 	}
// 
// 	public InvalidPathException(String message) {
// 		super(message);
// 	}
// 
// 	public InvalidPathException(Throwable cause) {
// 		super(cause);
// 	}
// 
// }
// Path: config-toolkit/src/main/java/com/dangdang/config/service/file/contenttype/XmlContentType.java
import com.dangdang.config.service.exception.InvalidPathException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
package com.dangdang.config.service.file.contenttype;
/**
 * <p>
 * The XML document must have the following DOCTYPE declaration:
 * 
 * <pre>
 * <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
 * </pre>
 * 
 * Furthermore, the document must satisfy the properties DTD described above.
 * 
 * @author <a href="mailto:[email protected]">Yuxuan Wang</a>
 *
 */
public class XmlContentType implements ContentType {
	@Override | 
		public Map<String, String> resolve(byte[] data, String encoding) throws InvalidPathException { | 
| 
	dangdangdotcom/config-toolkit | 
	config-toolkit/src/main/java/com/dangdang/config/service/GeneralConfigGroup.java | 
	// Path: config-toolkit/src/main/java/com/dangdang/config/service/observer/IObserver.java
// public interface IObserver {
// 
// 	/**
// 	 * 通知
// 	 * 
// 	 * @param data
// 	 */
// 	void notified(String data, String value);
// 
// }
 | 
	import com.dangdang.config.service.observer.IObserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; | 
	                this.put(entry.getKey(), entry.getValue());
            }
        } else {
            LOGGER.debug("Config group has none keys, clear.");
            super.clear();
        }
    }
    @Override
    public final String put(String key, String value) {
        if (value != null) {
            value = value.trim();
        }
        String preValue = super.get(key);
        if (value != null && !value.equals(preValue)) {
            LOGGER.debug("Key " + key + " change from {} to {}", preValue, value);
            super.put(key, value);
            // If value change, notify
            if (preValue != null) {
                notify(key, value);
            }
        }
        return preValue;
    }
    /**
     * 观察者列表
     */ | 
	// Path: config-toolkit/src/main/java/com/dangdang/config/service/observer/IObserver.java
// public interface IObserver {
// 
// 	/**
// 	 * 通知
// 	 * 
// 	 * @param data
// 	 */
// 	void notified(String data, String value);
// 
// }
// Path: config-toolkit/src/main/java/com/dangdang/config/service/GeneralConfigGroup.java
import com.dangdang.config.service.observer.IObserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
                this.put(entry.getKey(), entry.getValue());
            }
        } else {
            LOGGER.debug("Config group has none keys, clear.");
            super.clear();
        }
    }
    @Override
    public final String put(String key, String value) {
        if (value != null) {
            value = value.trim();
        }
        String preValue = super.get(key);
        if (value != null && !value.equals(preValue)) {
            LOGGER.debug("Key " + key + " change from {} to {}", preValue, value);
            super.put(key, value);
            // If value change, notify
            if (preValue != null) {
                notify(key, value);
            }
        }
        return preValue;
    }
    /**
     * 观察者列表
     */ | 
	    private final List<IObserver> watchers = new ArrayList<>(); | 
| 
	dangdangdotcom/config-toolkit | 
	config-toolkit-demo/src/main/java/com/dangdang/config/service/easyzk/demo/spring/PlaceHodlerSupport.java | 
	// Path: config-toolkit-demo/src/main/java/com/dangdang/config/service/easyzk/demo/simple/ExampleBean.java
// public class ExampleBean {
// 	
// 	private String stringProperty;
// 	
// 	private int intProperty;
// 	
// 	private boolean cool;
// 
// 	public ExampleBean(String stringProperty, int intProperty) {
// 		super();
// 		this.stringProperty = stringProperty;
// 		this.intProperty = intProperty;
// 	}
// 
// 	public String getStringProperty() {
// 		return stringProperty;
// 	}
// 
// 	public int getIntProperty() {
// 		return intProperty;
// 	}
// 
// 	public boolean isCool() {
// 		return cool;
// 	}
// 
// 	public void setCool(boolean cool) {
// 		this.cool = cool;
// 	}
// 
// 	@Override
// 	public String toString() {
// 		return "ExampleBean [stringProperty=" + stringProperty + ", intProperty=" + intProperty + ", cool=" + cool + "]";
// 	}
// 
// }
 | 
	import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.dangdang.config.service.easyzk.demo.simple.ExampleBean; | 
	package com.dangdang.config.service.easyzk.demo.spring;
/**
 * @author <a href="mailto:[email protected]">Yuxuan Wang</a>
 *
 */
public class PlaceHodlerSupport {
	
	public static void main(String[] args) {
		ClassPathXmlApplicationContext context = null;
		try {
			context = new ClassPathXmlApplicationContext("classpath:config-toolkit-placeholder-support.xml");
			context.registerShutdownHook();
			context.start();
 | 
	// Path: config-toolkit-demo/src/main/java/com/dangdang/config/service/easyzk/demo/simple/ExampleBean.java
// public class ExampleBean {
// 	
// 	private String stringProperty;
// 	
// 	private int intProperty;
// 	
// 	private boolean cool;
// 
// 	public ExampleBean(String stringProperty, int intProperty) {
// 		super();
// 		this.stringProperty = stringProperty;
// 		this.intProperty = intProperty;
// 	}
// 
// 	public String getStringProperty() {
// 		return stringProperty;
// 	}
// 
// 	public int getIntProperty() {
// 		return intProperty;
// 	}
// 
// 	public boolean isCool() {
// 		return cool;
// 	}
// 
// 	public void setCool(boolean cool) {
// 		this.cool = cool;
// 	}
// 
// 	@Override
// 	public String toString() {
// 		return "ExampleBean [stringProperty=" + stringProperty + ", intProperty=" + intProperty + ", cool=" + cool + "]";
// 	}
// 
// }
// Path: config-toolkit-demo/src/main/java/com/dangdang/config/service/easyzk/demo/spring/PlaceHodlerSupport.java
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.dangdang.config.service.easyzk.demo.simple.ExampleBean;
package com.dangdang.config.service.easyzk.demo.spring;
/**
 * @author <a href="mailto:[email protected]">Yuxuan Wang</a>
 *
 */
public class PlaceHodlerSupport {
	
	public static void main(String[] args) {
		ClassPathXmlApplicationContext context = null;
		try {
			context = new ClassPathXmlApplicationContext("classpath:config-toolkit-placeholder-support.xml");
			context.registerShutdownHook();
			context.start();
 | 
				ExampleBean bean = context.getBean(ExampleBean.class); | 
			Subsets and Splits
				
	
				
			
				
No community queries yet
The top public SQL queries from the community will appear here once available.
