text:
package org.kie.workbench.common.services.datamodel.backend.server;

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

import org.drools.workbench.models.datamodel.oracle.Annotation;
import org.drools.workbench.models.datamodel.oracle.DataType;
import org.drools.workbench.models.datamodel.oracle.MethodInfo;
import org.drools.workbench.models.datamodel.oracle.ModelField;
import org.drools.workbench.models.datamodel.oracle.PackageDataModelOracle;
import org.drools.workbench.models.datamodel.oracle.ProjectDataModelOracle;
import org.drools.workbench.models.datamodel.oracle.TypeSource;
import org.kie.workbench.common.services.datamodel.model.LazyModelField;
import org.kie.workbench.common.services.datamodel.model.PackageDataModelOracleBaselinePayload;
import org.kie.workbench.common.services.datamodel.model.PackageDataModelOracleIncrementalPayload;

/**
 * Utilities to query ProjectDMO content
 */
public class DataModelOracleUtilities {

    /**
     * Convenience method to get an array of all fully qualified class names available in a project
     * @param oracle The DMO representing a project
     * @return
     */
    public static String[] getFactTypes( final ProjectDataModelOracle oracle ) {

        List<String> packageNames = oracle.getProjectPackageNames();

        final Map<String, ModelField[]> modelFields = oracle.getProjectModelFields();
        final List<String> types = new ArrayList<String>();
        for ( String type : modelFields.keySet() ) {
            int beginIndex = type.lastIndexOf( '.' );

            if ( beginIndex < 0 ) {
                types.add( type );
            } else {
                String substring = type.substring( 0, beginIndex );
                if ( packageNames.contains( substring ) ) {
                    types.add( type );
                }
            }
        }
        Collections.sort( types );

        return types.toArray( new String[ types.size() ] );
    }

    /**
     * Convenience method to get an array of field names for a type in a project
     * @param oracle The DMO representing a project
     * @param fullyQualifiedClassName The FQCN of the type
     * @return
     */
    public static String[] getFieldNames( final ProjectDataModelOracle oracle,
                                          final String fullyQualifiedClassName ) {
        final ModelField[] modelFields = oracle.getProjectModelFields().get( fullyQualifiedClassName );
        if ( modelFields == null ) {
            return new String[ 0 ];
        }

        final String[] fieldNames = new String[ modelFields.length ];
        for ( int i = 0; i < modelFields.length; i++ ) {
            fieldNames[ i ] = modelFields[ i ].getName();
        }
        return fieldNames;
    }

    /**
     * Convenience method to get the fully qualified class name of the super type of another type in a project
     * @param oracle The DMO representing a project
     * @param fullyQualifiedClassName The FQCN of the type
     * @return
     */
    public static String getSuperType( final ProjectDataModelOracle oracle,
                                       final String fullyQualifiedClassName ) {
        List<String> superTypes = oracle.getProjectSuperTypes().get( fullyQualifiedClassName );
        if ( superTypes != null && superTypes.size() > 0 ) {
            return superTypes.get( 0 );
        } else {
            return null;
        }
    }

    /**
     * Convenience method to get a set of annotations on a type in a project
     * @param oracle The DMO representing a project
     * @param fullyQualifiedClassName The FQCN of the type
     * @return
     */
    public static Set<Annotation> getTypeAnnotations( final ProjectDataModelOracle oracle,
                                                      final String fullyQualifiedClassName ) {
        final Map<String, Set<Annotation>> typeAnnotations = oracle.getProjectTypeAnnotations();
        if ( !typeAnnotations.containsKey( fullyQualifiedClassName ) ) {
            return Collections.EMPTY_SET;
        }
        return typeAnnotations.get( fullyQualifiedClassName );
    }

    /**
     * Convenience method to get all field annotations on a type in a project
     * @param oracle The DMO representing a project
     * @param fullyQualifiedClassName The FQCN of the type
     * @return
     */
    public static Map<String, Set<Annotation>> getTypeFieldsAnnotations( final ProjectDataModelOracle oracle,
                                                                         final String fullyQualifiedClassName ) {
        final Map<String, Map<String, Set<Annotation>>> typeFieldsAnnotations = oracle.getProjectTypeFieldsAnnotations();
        if ( !typeFieldsAnnotations.containsKey( fullyQualifiedClassName ) ) {
            return Collections.EMPTY_MAP;
        }
        return typeFieldsAnnotations.get( fullyQualifiedClassName );
    }

    /**
     * Convenience method to get the fully qualified class name of a field on a type in a project
     * @param oracle The DMO representing a project
     * @param fullyQualifiedClassName The FQCN of the type
     * @param fieldName The field Name
     * @return
     */
    public static String getFieldClassName( final ProjectDataModelOracle oracle,
                                            final String fullyQualifiedClassName,
                                            final String fieldName ) {
        final ModelField field = getField( oracle,
                                           fullyQualifiedClassName,
                                           fieldName );
        return field == null ? null : field.getClassName();
    }

    private static ModelField getField( final ProjectDataModelOracle oracle,
                                        final String fullyQualifiedClassName,
                                        final String fieldName ) {
        final String shortName = getFactNameFromType( oracle,
                                                      fullyQualifiedClassName );
        final ModelField[] fields = oracle.getProjectModelFields().get( shortName );
        if ( fields == null ) {
            return null;
        }
        for ( ModelField modelField : fields ) {
            if ( modelField.getName().equals( fieldName ) ) {
                return modelField;
            }
        }
        return null;
    }

    private static String getFactNameFromType( final ProjectDataModelOracle oracle,
                                               final String fullyQualifiedClassName ) {
        if ( fullyQualifiedClassName == null ) {
            return null;
        }
        if ( oracle.getProjectModelFields().containsKey( fullyQualifiedClassName ) ) {
            return fullyQualifiedClassName;
        }
        for ( Map.Entry<String, ModelField[]> entry : oracle.getProjectModelFields().entrySet() ) {
            for ( ModelField mf : entry.getValue() ) {
                if ( DataType.TYPE_THIS.equals( mf.getName() ) && fullyQualifiedClassName.equals( mf.getClassName() ) ) {
                    return entry.getKey();
                }
            }
        }
        return null;
    }

    /**
     * Convenience method to get the generic type of a field on a type in a project
     * @param oracle The DMO representing a project
     * @param fullyQualifiedClassName The FQCN of the type
     * @param fieldName The field Name
     * @return
     */
    public static String getParametricFieldType( final ProjectDataModelOracle oracle,
                                                 final String fullyQualifiedClassName,
                                                 final String fieldName ) {
        final String qualifiedFactFieldName = fullyQualifiedClassName + "#" + fieldName;
        return oracle.getProjectFieldParametersType().get( qualifiedFactFieldName );
    }

    /**
     * Convenience method to get the source of a type in a project
     * @param oracle The DMO representing a project
     * @param fullyQualifiedClassName The FQCN of the type
     * @return
     */
    public static TypeSource getTypeSource( final ProjectDataModelOracle oracle,
                                            final String fullyQualifiedClassName ) {
        return oracle.getProjectTypeSources().get( fullyQualifiedClassName );
    }

    public static void populateDataModel( final PackageDataModelOracle oracle,
                                          final PackageDataModelOracleBaselinePayload dataModel,
                                          final Set<String> usedFullyQualifiedClassNames ) {
        dataModel.setProjectName( oracle.getProjectName() );
        dataModel.setPackageName( oracle.getPackageName() );
        dataModel.setModelFields( setupModelFields( usedFullyQualifiedClassNames,
                                                    oracle.getProjectModelFields(),
                                                    oracle.getPackageGlobals() ) );
        dataModel.setFieldParametersType( filterFieldParametersTypes( usedFullyQualifiedClassNames,
                                                                      oracle.getProjectFieldParametersType() ) );
        dataModel.setEventTypes( filterEventTypes( usedFullyQualifiedClassNames,
                                                   oracle.getProjectEventTypes() ) );
        dataModel.setTypeSources( filterTypeSources( usedFullyQualifiedClassNames,
                                                     oracle.getProjectTypeSources() ) );
        dataModel.setSuperTypes( filterSuperTypes( usedFullyQualifiedClassNames,
                                                   oracle.getProjectSuperTypes() ) );
        dataModel.setTypeAnnotations( filterTypeAnnotations( usedFullyQualifiedClassNames,
                                                             oracle.getProjectTypeAnnotations() ) );
        dataModel.setTypeFieldsAnnotations( filterTypeFieldsAnnotations( usedFullyQualifiedClassNames,
                                                                         oracle.getProjectTypeFieldsAnnotations() ) );
        dataModel.setJavaEnumDefinitions( oracle.getProjectJavaEnumDefinitions() );
        dataModel.setWorkbenchEnumDefinitions( oracle.getPackageWorkbenchDefinitions() );
        dataModel.setMethodInformation( filterMethodInformation( usedFullyQualifiedClassNames,
                                                                 oracle.getProjectMethodInformation() ) );
        dataModel.setCollectionTypes( filterCollectionTypes( usedFullyQualifiedClassNames,
                                                             oracle.getProjectCollectionTypes() ) );
        dataModel.setDslConditionSentences( oracle.getPackageDslConditionSentences() );
        dataModel.setDslActionSentences( oracle.getPackageDslActionSentences() );
        dataModel.setGlobalTypes( oracle.getPackageGlobals() );
        dataModel.setPackageNames( oracle.getProjectPackageNames() );
    }

    public static void populateDataModel( final PackageDataModelOracle oracle,
                                          final PackageDataModelOracleIncrementalPayload dataModel,
                                          final String usedFullyQualifiedClassName ) {
        final Set<String> usedFullyQualifiedClassNames = new HashSet<String>();
        usedFullyQualifiedClassNames.add( usedFullyQualifiedClassName );
        dataModel.setModelFields( filterModelFields( usedFullyQualifiedClassNames,
                                                     oracle.getProjectModelFields() ) );
        dataModel.setFieldParametersType( filterFieldParametersTypes( usedFullyQualifiedClassNames,
                                                                      oracle.getProjectFieldParametersType() ) );
        dataModel.setEventTypes( filterEventTypes( usedFullyQualifiedClassNames,
                                                   oracle.getProjectEventTypes() ) );
        dataModel.setTypeSources( filterTypeSources( usedFullyQualifiedClassNames,
                                                     oracle.getProjectTypeSources() ) );
        dataModel.setSuperTypes( filterSuperTypes( usedFullyQualifiedClassNames,
                                                   oracle.getProjectSuperTypes() ) );
        dataModel.setTypeAnnotations( filterTypeAnnotations( usedFullyQualifiedClassNames,
                                                             oracle.getProjectTypeAnnotations() ) );
        dataModel.setTypeFieldsAnnotations( filterTypeFieldsAnnotations( usedFullyQualifiedClassNames,
                                                                         oracle.getProjectTypeFieldsAnnotations() ) );
        dataModel.setMethodInformation( filterMethodInformation( usedFullyQualifiedClassNames,
                                                                 oracle.getProjectMethodInformation() ) );
        dataModel.setCollectionTypes( filterCollectionTypes( usedFullyQualifiedClassNames,
                                                             oracle.getProjectCollectionTypes() ) );
    }

    //Setup Model Fields for lazy loading client-side
    private static Map<String, ModelField[]> setupModelFields( final Set<String> usedFullyQualifiedClassNames,
                                                               final Map<String, ModelField[]> projectModelFields,
                                                               final Map<String, String> packageGlobals ) {
        final Map<String, ModelField[]> scopedModelFields = new HashMap<String, ModelField[]>();
        for ( Map.Entry<String, ModelField[]> e : projectModelFields.entrySet() ) {
            final String mfQualifiedType = e.getKey();
            if ( usedFullyQualifiedClassNames.contains( mfQualifiedType ) ) {
                scopedModelFields.put( mfQualifiedType,
                                       e.getValue() );
            } else if ( packageGlobals.containsValue( mfQualifiedType ) ) {
                scopedModelFields.put( mfQualifiedType,
                                       e.getValue() );
            } else {
                scopedModelFields.put( mfQualifiedType,
                                       makeLazyProxyModelField( e.getValue() ) );
            }
        }
        return scopedModelFields;
    }

    //AsyncPackageDataModelOracle.getFactNameFromType() uses THIS to determine the simple Type from a FQCN.
    //Therefore ensure we provide this minimal information for every Type in the DMO to prevent getFactNameFromType()
    //needing a callback to the server which makes things more complicated than really needed.
    private static ModelField[] makeLazyProxyModelField( final ModelField[] modelFields ) {
        for ( ModelField modelField : modelFields ) {
            if ( DataType.TYPE_THIS.equals( modelField.getName() ) ) {
                final ModelField[] result = new ModelField[ 1 ];
                //LazyModelField is a place-holder to tell AsyncPackageDataModelOracle that it needs to load more information
                result[ 0 ] = new LazyModelField( modelField.getName(),
                                                  modelField.getClassName(),
                                                  modelField.getClassType(),
                                                  modelField.getOrigin(),
                                                  modelField.getAccessorsAndMutators(),
                                                  modelField.getType() );
                return result;
            }
        }
        return null;
    }

    //Filter Model Fields by the types used
    private static Map<String, ModelField[]> filterModelFields( final Set<String> usedFullyQualifiedClassNames,
                                                                final Map<String, ModelField[]> projectModelFields ) {
        final Map<String, ModelField[]> scopedModelFields = new HashMap<String, ModelField[]>();
        for ( Map.Entry<String, ModelField[]> e : projectModelFields.entrySet() ) {
            final String mfQualifiedType = e.getKey();
            final ModelField[] mfModelFields = e.getValue();
            if ( isTypeUsed( mfQualifiedType,
                             usedFullyQualifiedClassNames ) ) {
                scopedModelFields.put( mfQualifiedType,
                                       mfModelFields );
            }
        }
        return scopedModelFields;
    }

    //Filter Collection Types by the types used
    private static Map<String, Boolean> filterCollectionTypes( final Set<String> usedFullyQualifiedClassNames,
                                                               final Map<String, Boolean> projectCollectionTypes ) {
        final Map<String, Boolean> scopedCollectionTypes = new HashMap<String, Boolean>();
        for ( Map.Entry<String, Boolean> e : projectCollectionTypes.entrySet() ) {
            final String collectionQualifiedType = e.getKey();
            if ( isTypeUsed( collectionQualifiedType,
                             usedFullyQualifiedClassNames ) ) {
                scopedCollectionTypes.put( collectionQualifiedType,
                                           e.getValue() );

            }
        }
        return scopedCollectionTypes;
    }

    //Filter Event Types by the types used
    private static Map<String, Boolean> filterEventTypes( final Set<String> usedFullyQualifiedClassNames,
                                                          final Map<String, Boolean> projectEventTypes ) {
        final Map<String, Boolean> scopedEventTypes = new HashMap<String, Boolean>();
        for ( Map.Entry<String, Boolean> e : projectEventTypes.entrySet() ) {
            final String eventQualifiedType = e.getKey();
            if ( isTypeUsed( eventQualifiedType,
                             usedFullyQualifiedClassNames ) ) {
                scopedEventTypes.put( eventQualifiedType,
                                      e.getValue() );
            }
        }
        return scopedEventTypes;
    }

    //Filter TypeSource by the types used
    private static Map<String, TypeSource> filterTypeSources( final Set<String> usedFullyQualifiedClassNames,
                                                              final Map<String, TypeSource> projectTypeSources ) {
        final Map<String, TypeSource> scopedTypeSources = new HashMap<String, TypeSource>();
        for ( Map.Entry<String, TypeSource> e : projectTypeSources.entrySet() ) {
            final String typeQualifiedType = e.getKey();
            if ( isTypeUsed( typeQualifiedType,
                             usedFullyQualifiedClassNames ) ) {
                scopedTypeSources.put( typeQualifiedType,
                                       e.getValue() );
            }
        }
        return scopedTypeSources;
    }

    //Filter Super Types by the types used
    private static Map<String, List<String>> filterSuperTypes( final Set<String> usedFullyQualifiedClassNames,
                                                               final Map<String, List<String>> projectSuperTypes ) {
        final Map<String, List<String>> scopedSuperTypes = new HashMap<String, List<String>>();
        for ( Map.Entry<String, List<String>> e : projectSuperTypes.entrySet() ) {
            final String typeQualifiedType = e.getKey();
            final List<String> superTypeQualifiedTypes = e.getValue();
            if ( isTypeUsed( typeQualifiedType,
                             usedFullyQualifiedClassNames ) ) {
                scopedSuperTypes.put( typeQualifiedType,
                                      superTypeQualifiedTypes );
            }
        }
        return scopedSuperTypes;
    }

    //Filter Type Annotations by the types used
    private static Map<String, Set<Annotation>> filterTypeAnnotations( final Set<String> usedFullyQualifiedClassNames,
                                                                       final Map<String, Set<Annotation>> projectTypeAnnotations ) {
        final Map<String, Set<Annotation>> scopedTypeAnnotations = new HashMap<String, Set<Annotation>>();
        for ( Map.Entry<String, Set<Annotation>> e : projectTypeAnnotations.entrySet() ) {
            final String typeAnnotationQualifiedType = e.getKey();
            if ( isTypeUsed( typeAnnotationQualifiedType,
                             usedFullyQualifiedClassNames ) ) {
                scopedTypeAnnotations.put( typeAnnotationQualifiedType,
                                           e.getValue() );
            }
        }
        return scopedTypeAnnotations;
    }

    //Filter Type Fields Annotations by the types used
    private static Map<String, Map<String, Set<Annotation>>> filterTypeFieldsAnnotations( final Set<String> usedFullyQualifiedClassNames,
                                                                                final Map<String, Map<String, Set<Annotation>>> projectTypeFieldsAnnotations ) {
        final Map<String, Map<String, Set<Annotation>>> scopedTypeFieldsAnnotations = new HashMap<String, Map<String, Set<Annotation>>>();
        for ( Map.Entry<String, Map<String, Set<Annotation>>> e : projectTypeFieldsAnnotations.entrySet() ) {
            final String typeAnnotationQualifiedType = e.getKey();
            if ( isTypeUsed( typeAnnotationQualifiedType,
                             usedFullyQualifiedClassNames ) ) {
                scopedTypeFieldsAnnotations.put( typeAnnotationQualifiedType,
                                                 e.getValue() );
            }
        }
        return scopedTypeFieldsAnnotations;
    }

    //Filter Method Information (used by ActionCallXXX and ExpressionBuilder) by the types used
    private static Map<String, List<MethodInfo>> filterMethodInformation( final Set<String> usedFullyQualifiedClassNames,
                                                                          final Map<String, List<MethodInfo>> projectMethodInformation ) {
        final Map<String, List<MethodInfo>> scopedMethodInformation = new HashMap<String, List<MethodInfo>>();
        for ( Map.Entry<String, List<MethodInfo>> e : projectMethodInformation.entrySet() ) {
            final String miQualifiedType = e.getKey();
            if ( isTypeUsed( miQualifiedType,
                             usedFullyQualifiedClassNames ) ) {
                scopedMethodInformation.put( miQualifiedType,
                                             e.getValue() );
            }
        }
        return scopedMethodInformation;
    }

    //Filter Field Parameter Types by the types used
    private static Map<String, String> filterFieldParametersTypes( final Set<String> usedFullyQualifiedClassNames,
                                                                   final Map<String, String> projectFieldParametersTypes ) {
        final Map<String, String> scopedFieldParametersType = new HashMap<String, String>();
        for ( Map.Entry<String, String> e : projectFieldParametersTypes.entrySet() ) {
            final String fieldName = e.getKey();
            final String fieldType = e.getValue();
            final String fFieldName_QualifiedType = getQualifiedTypeFromEncodedFieldName( fieldName );
            if ( isTypeUsed( fFieldName_QualifiedType,
                             usedFullyQualifiedClassNames ) ) {
                scopedFieldParametersType.put( fieldName,
                                               fieldType );
            }
        }
        return scopedFieldParametersType;
    }

    private static String getQualifiedTypeFromEncodedFieldName( final String encodedFieldName ) {
        String typeName = encodedFieldName;
        int hashIndex = typeName.lastIndexOf( "#" );
        if ( hashIndex != -1 ) {
            typeName = typeName.substring( 0,
                                           hashIndex );
        }
        return typeName;
    }

    private static boolean isTypeUsed( final String fullyQualifiedClassName,
                                       final Set<String> usedFullyQualifiedClassNames ) {
        return usedFullyQualifiedClassNames.contains( fullyQualifiedClassName );
    }

}


text:
package painter1024.emptyptoject.lib_android.util.storage.file;

import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;

import java.io.File;

/**
 * 文件信息工具
 */

public class FileInfoUtil {
    public static final String TAG = "FileInfoUtil";

    /***
     * 文件是否存在
     */
    public static boolean exists(File file){
        return file.exists();
    }

    /***
     * 判断文件大小是否为0
     */
    public static boolean isEmpty(File file) {
        return file.length() == 0;
    }

    /***
     * 获取文件大小
     * */
    public static long getSize(File file) {
        if (file == null || !file.exists()) return 0;
        long fileLength = file.length();
        return fileLength;
    }

    /**
     * 获取指定文件夹内所有文件大小的和
     */
    public static long getFolderSize(File file) {
        if(!file.isDirectory()) return file.length();

        long size = 0;
        File[] fileList = file.listFiles();
        for (File aFileList : fileList) {
            if (aFileList.isDirectory()) {
                size = size + getFolderSize(aFileList);
            } else {
                size = size + aFileList.length();
            }
        }
        return size;
    }

    /**
     * 获取路径
     */
    public static String getPath(final Context context, final Uri uri) {

        Log.d(TAG + " File -",
                "Authority: " + uri.getAuthority() +
                        ", Fragment: " + uri.getFragment() +
                        ", Port: " + uri.getPort() +
                        ", Query: " + uri.getQuery() +
                        ", Scheme: " + uri.getScheme() +
                        ", Host: " + uri.getHost() +
                        ", Segments: " + uri.getPathSegments().toString());

        // DocumentProvider
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT &&
                DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }

            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{
                        split[1]
                };

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // Return the remote address
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();

            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
        return null;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context The context.
     * @param uri The Uri to query.
     * @param selection (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

// Exit if accessed directly
if( !defined( 'ABSPATH' ) ) {
	exit;
}

?>
<?php get_header(); ?>

	<?php responsive_entry_before(); ?>

		<?php responsive_entry_top(); ?>

			<?php get_template_part( 'loop-no-posts' ); ?>

		<?php responsive_entry_bottom(); ?>

	<?php responsive_entry_after(); ?>

<?php get_footer(); ?>


text:
// ==UserScript==
// @name           Stack Overflow: switch language of syntax highlighting
// @description    Enable switching the language of syntax highlighting on Stack Overflow
// @namespace      {{{ pkg.author.url }}}
// @author         {{{ pkg.author.name }}} ({{{ pkg.author.email }}})
// @homepage       {{{ pkg.homepage }}}
// @license        {{{ pkg.license }}}
// @version        2.0
// @icon           http://cdn.sstatic.net/Sites/stackoverflow/img/favicon.ico
// @include        http://stackoverflow.com/questions/*
// @run-at         document-end
// @grant          none
// ==/UserScript==

(function () {
    // helper functions to inject


text:
<?php
namespace App\Providers;

use Silex\Application;
use Silex\ServiceProviderInterface;

use App\DataAccesses;

class DataAccessServiceProvider implements ServiceProviderInterface {
    public function register(Application $app)
    {
        $app['dataaccess.wpdb'] = $app->share(function() use($app) {
            return new DataAccesses\WpdbHandler(
                $app['dbs']['mysql_read'],
                $app['dbs']['mysql_write']
            );
        });
    }

    public function boot(Application $app)
    {
    }
}


text:
> Automatically change screen layout.

- Save the current screen layout:

`autorandr -s {{profile_name}}`

- Show the saved profiles:

`autorandr`

- Change the profile:

`autorandr -l {{profile_name}}`

- Set the default profile:

`autorandr -d {{profile_name}}`


text:
/**
 * @fileoverview Tests for config object.
 * @author Seth McLaughlin
 */

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

var assert = require("chai").assert,
    path = require("path"),
    Config = require("../../lib/config"),
    sinon = require("sinon");

//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------

describe("config", function() {
    describe("findLocalConfigFile", function() {
        var code = path.resolve(__dirname, "..", "fixtures", "configurations", "single-quotes");

        it("should find local config file", function() {
            var configHelper = new Config(),
                expected = path.resolve(code, ".eslintrc"),
                actual = configHelper.findLocalConfigFile(code);

            assert.equal(expected, actual);
        });
    });

    describe("mergeConfigs", function() {
        var code = { person: { name: "Seth", car: "prius" }, town: "MV" };

        it("should merge configs", function() {
            var configHelper = new Config(),
                expected = { person: { name: "Bob", car: "prius" }, town: "PA" },
                actual = configHelper.mergeConfigs(code, { person: { name: "Bob" }, town: "PA" });

            assert.deepEqual(expected, actual);
        });
    });

    describe("getConfig with env rules", function() {
        var code = path.resolve(__dirname, "..", "fixtures", "configurations",
                "env-node.json");

        it("should be no-global-strict off for node env", function() {

            var configHelper = new Config({config: code}),
                config = configHelper.getConfig(),
                expected = 0,
                actual = config.rules["no-global-strict"];

            assert.equal(expected, actual);
        });
    });

    describe("getConfig with env and user rules", function() {
        var code = path.resolve(__dirname, "..", "fixtures", "configurations",
                "env-node-override.json");

        it("should be no-global-strict a warning", function() {
            var configHelper = new Config({config: code}),
                config = configHelper.getConfig(),
                expected = 1,
                actual = config.rules["no-global-strict"];

            assert.equal(expected, actual);
        });
    });

    describe("getLocalConfig with directory", function() {
        var code = path.resolve(__dirname, "..", "fixtures", "configurations", "single-quotes", ".eslintrc");

        it("should be single quotes config", function() {
            var configHelper = new Config(),
                config = configHelper.getConfig(code),
                expected = [1, "single"],
                actual = config.rules.quotes;

            assert.deepEqual(expected, actual);
        });
    });

    describe("getConfig with exclude", function() {
        var code = path.resolve(__dirname, "..", "fixtures", ".eslintrc");

        it("should exclude passing.js", function() {
            var configHelper = new Config();
            configHelper.getConfig(code);

            configHelper.cacheExclusions(path.resolve(__dirname, "..", "fixtures"), true);

            assert.isTrue(configHelper.checkForExclusion(path.resolve(__dirname, "..", "fixtures", "passing.js")));
        });
    });

    describe("getLocalConfig with invalid directory", function() {
        var code = path.resolve(__dirname, "..", "fixtures", "configurations", "single-quotes");

        it("should be default config", function() {
            var configHelper = new Config();
            sinon.stub(configHelper, "findLocalConfigFile", function(directory) { return path.resolve(directory, ".eslintrc"); });
            sinon.stub(console, "error").returns({});

            configHelper.getConfig(code);

            assert.isTrue(console.error.calledTwice);
            configHelper.findLocalConfigFile.restore();
            console.error.restore();
        });
    });

    describe("should cache config", function() {
        var code = path.resolve(__dirname, "..", "fixtures", "configurations", "single-quotes", ".eslintrc");

        it("should resolve config only once", function() {
            var configHelper = new Config();

            sinon.spy(configHelper, "findLocalConfigFile");
            configHelper.getConfig(code);
            configHelper.getConfig(code);

            assert.isTrue(configHelper.findLocalConfigFile.calledOnce);
            configHelper.findLocalConfigFile.restore();
        });
    });

    describe("when searching for exclusions in directory without .eslintignore and empty parent .eslintignore", function() {
        it("should not have any exclusions", function() {
            var configHelper = new Config();

            configHelper.cacheExclusions(path.resolve(__dirname, "..", "fixtures", "rules", "test"));

            assert.isUndefined(configHelper.exclusionsCache[path.resolve(__dirname, "..", "fixtures", "rules", "test")]);
        });
    });

    describe("when searching for exclusions in directory with .eslintignore", function() {
        it("should have correct exclusions", function() {
            var configHelper = new Config();
            configHelper.cacheExclusions(path.resolve(__dirname, "..", "fixtures"));

            assert.isTrue(configHelper.checkForExclusion(path.resolve(__dirname, "..", "fixtures", "rules", "eslint.json")));
            assert.isTrue(configHelper.checkForExclusion(path.resolve(__dirname, "..", "fixtures", "passing.js")));
        });
    });

    describe("when searching for exclusions in directory with .eslintignore in parents", function() {
        it("should have correct exclusions", function() {
            var configHelper = new Config();
            configHelper.cacheExclusions(path.resolve(__dirname, "..", "fixtures", "formatters"));

            assert.isTrue(configHelper.checkForExclusion(path.resolve(__dirname, "..", "fixtures", "formatters", "simple.js")));
            assert.isFalse(configHelper.checkForExclusion(path.resolve(__dirname, "..", "fixtures", "passing.js")));
        });
    });

    describe("when searching for exclusions in directory with plain text .eslintignore", function() {
        it("should have correct exclusions", function() {
            var configHelper = new Config();
            configHelper.cacheExclusions(path.resolve(__dirname, "..", "fixtures", "eslintrc"));

            assert.isFalse(configHelper.checkForExclusion(path.resolve(__dirname, "..", "fixtures", "eslintrc", "quotes.js")));
            assert.isTrue(configHelper.checkForExclusion(path.resolve(__dirname, "..", "fixtures", "eslintrc", "ignored.json")));
        });
    });

    describe("getLocalConfig with current directory", function() {
        it("should return false", function() {
            var configHelper = new Config();

            var output = configHelper.findLocalConfigFile("/");
            assert.isFalse(output);
        });
    });

    describe("getLocalConfig with no directory", function() {
        it("should return global config", function() {
            var configHelper = new Config();

            var output = configHelper.findLocalConfigFile();
            assert.include(output, ".eslintrc");
        });
    });

    describe("getConfig with no directory", function() {
        it("should return cwd config", function() {
            var cwd = process.cwd();
            process.chdir(path.resolve(__dirname, "..", "fixtures", "configurations", "cwd"));

            try {
                var configHelper = new Config(),
                    code = path.resolve(__dirname, "..", "fixtures", "configurations", "single-quotes", ".eslintrc"),
                    expected = configHelper.getConfig(code),
                    expectedQuotes = expected.rules.quotes[0],
                    actual = configHelper.getConfig(),
                    actualQuotes = actual.rules.quotes[0];

                assert.notEqual(expectedQuotes, actualQuotes);
            }
            finally {
                process.chdir(cwd);
            }
        });
    });

    describe("Config with abitrarily named config file", function() {
        it("should load the config file", function() {
            var configPath = path.resolve(__dirname, "..", "fixtures", "configurations", "my-awesome-config"),
                configHelper = new Config({config: configPath}),
                quotes = configHelper.useSpecificConfig.rules.quotes[0];

            assert.equal(quotes, 3);
        });
    });

    describe("Config with comments", function() {
        it("should load the config file", function() {
            var configPath = path.resolve(__dirname, "..", "fixtures", "configurations", "comments.json"),
                configHelper = new Config({config: configPath}),
                semi = configHelper.useSpecificConfig.rules.semi,
                strict = configHelper.useSpecificConfig.rules.strict;

            assert.equal(semi, 1);
            assert.equal(strict, 0);
        });
    });

    describe("YAML config", function() {
        it("should load the config file", function() {
            var configPath = path.resolve(__dirname, "..", "fixtures", "configurations", "env-browser.yaml"),
                configHelper = new Config({config: configPath}),
                noAlert = configHelper.useSpecificConfig.rules["no-alert"],
                noUndef = configHelper.useSpecificConfig.rules["no-undef"];

            assert.equal(noAlert, 0);
            assert.equal(noUndef, 2);
        });
    });

});


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace m.Indexer
{
    public class NodeHierarchy
    {
        public NodeEnvelope Envelope { get; set; }
        public virtual String Name { get { return Envelope.Header.FileName; } }
        public List<NodeHierarchy> Children { get; set; }
        public Dictionary<string, int> ClassCounts { get; set; }
        public NodeHierarchy Parent { get; set; }

        public String GetFullPath()
        {
            var names = new List<String>() { Name };
            var currentNode = this;
            while (currentNode.Parent != null)
            {
                currentNode = currentNode.Parent;
                names.Insert(0, currentNode.Name);
            }
            return Path.Combine(names.ToArray());
        }

        public NodeHierarchy FindSubNode(NodeEnvelope node)
        {
            if(GetFullPath().Length > node.Header.FullDirectoryPath.Length)
            {
                return this;
            }
            string subPath = node.Header.FullDirectoryPath.Substring(GetFullPath().Length + 1);
            var nodeParts = subPath.Split('\\');
            var searchNode = this;
            for (int i = 0; i < nodeParts.Length; i++)
            {
                var child = searchNode.Children.FirstOrDefault(a => a.Name == nodeParts[i]);
                if (child != null)
                {
                    searchNode = child;
                }
                else
                {
                    throw new ApplicationException($"Could not find subpath: {subPath}");
                }
            }
            return searchNode;
        }

        public override string ToString()
        {
            return $"{this.GetFullPath()}";
        }

        protected static void RecurseUpTreeCalculatingStats(NodeHierarchy node, int depth)
        {
            if (node.Children.Any())
            {
                node.ClassCounts = new Dictionary<string, int>() { { node.Envelope.GetClass(), 1 } };
                foreach (var child in node.Children)
                {
                    RecurseUpTreeCalculatingStats(child, depth + 1);
                    foreach (var classCount in child.ClassCounts)
                    {
                        if (node.ClassCounts.ContainsKey(classCount.Key))
                        {
                            node.ClassCounts[classCount.Key] += classCount.Value;
                        }
                        else
                        {
                            node.ClassCounts[classCount.Key] = classCount.Value;
                        }
                    }
                }
            }
            else
            {
                node.ClassCounts = new Dictionary<string, int>() { { node.Envelope.GetClass(), 1 } };
            }
        }

    }
}


text:
<?php

namespace App\Listeners\FileWasUploaded;

use Log;
use Storage;

class PrepareToProcessFile
{
    /**
     * Handle the event.
     *
     * @param  FileWasUploaded  $event
     * @return void
     */
    public function handle($event)
    {
        // prepend a timestamp for (close to) uniqueness
        $uniqueName = date('Y-m-d_H-i-s_').$event->file;

        // let's move the file to the processing area
        // in a larger system we might namespace this for different clients, but that might be overkill
        Storage::move("uploads/$event->file", "processing/$uniqueName");

        // and apply the new name so that subsequent steps know where to find it
        $event->file = $uniqueName;

        // nothing hapopening here yet, so we'll pass on through, noting that we've been here along the way
        Log::info('prepare to process data (not yet active)');
    }
}


text:
'use strict';

/**
 * Module dependencies
 */
var classroomsPolicy = require('../policies/classrooms.server.policy'),
  classrooms = require('../controllers/classrooms.server.controller');

module.exports = function (app) {
  // Classrooms Routes
  app.route('/api/classrooms').all(classroomsPolicy.isAllowed)
    .get(classrooms.list)
    .post(classrooms.create);

  app.route('/api/classrooms/:classroomId').all(classroomsPolicy.isAllowed)
    .get(classrooms.read)
    .put(classrooms.update)
    .delete(classrooms.delete);

  // Finish by binding the Classroom middleware
  app.param('classroomId', classrooms.classroomByID);
};


text:
<?php

namespace Accessible;

use \Accessible\MethodManager\MethodCallManager;
use \Accessible\MethodManager\ListManager;
use \Accessible\MethodManager\MapManager;
use \Accessible\MethodManager\SetManager;

trait AutoMethodsTrait
{
    /**
     * This function will be called each time a getter or a setter that is not
     * already defined in the class is called.
     *
     * @param  string $name The name of the called function.
     *                      It must be a getter or a setter.
     * @param  array  $args The array of arguments for the called function.
     *                      It should be empty for a getter call,
     *                      and should have one item for a setter call.
     *
     * @return mixed    The value that should be returned by the function called if it is a getter,
     *                  the object itself if the function called is a setter.
     *
     * @throws \BadMethodCallException      When the method called is neither a getter nor a setter,
     *         						   		or if the access right has not be given for this method,
     *         						     	or if the method is a setter called without argument.
     * @throws \InvalidArgumentException    When the argument given to the method called (as a setter)
     *         								does not satisfy the constraints attached to the property
     *         								to modify.
     */
    public function __call($name, array $args)
    {
        $this->getPropertiesInfo();

        $methodCallInfo = $this->getMethodCallInfo($name);
        $method = $methodCallInfo['method'];
        $property = $methodCallInfo['property'];
        $collectionProperties = $methodCallInfo['collectionProperties'];

        $valuesToUpdate = array();

        switch ($method) {
            case 'get':
            case 'is':
            case 'call':
                MethodCallManager::assertArgsNumber(0, $args);
                return $this->$property;

            case 'set':
                MethodCallManager::assertArgsNumber(1, $args);
                // we set a collection here if there is an association with it
                if (
                    !empty($this->_collectionsItemNames['byProperty'][$property])
                    && !(empty($this->_associationsList[$property]))
                ) {
                    $itemName = $this->_collectionsItemNames['byProperty'][$property]['itemName'];
                    $propertyAddMethod = 'add' . ucfirst($itemName);
                    $propertyRemoveMethod = 'remove' . ucfirst($itemName);

                    foreach ($this->$property as $item) {
                        $this->$propertyRemoveMethod($item);
                    }
                    foreach ($args[0] as $item) {
                        $this->$propertyAddMethod($item);
                    }
                }
                // we set a regular property here
                else {
                    $oldValue = $this->$property;
                    $newValue = $args[0];
                    $valuesToUpdate = array(
                        'oldValue' => $oldValue,
                        'newValue' => $newValue
                    );
                    // check that the setter argument respects the property constraints
                    $this->assertPropertyValue($property, $newValue);
                    $this->$property = $newValue;
                }
                break;

            case 'add':
            case 'remove':
                $valueToUpdate = ($method === 'add') ? 'newValue' : 'oldValue';
                switch ($collectionProperties['behavior']) {
                    case 'list':
                        ListManager::$method($this->$property, $args);
                        $valuesToUpdate[$valueToUpdate] = $args[0];
                        break;
                    case 'map':
                        MapManager::$method($this->$property, $args);
                        break;
                    case 'set':
                        SetManager::$method($this->$property, $args);
                        $valuesToUpdate[$valueToUpdate] = $args[0];
                        break;
                }
                $this->assertPropertyValue($property, $this->$property);
                break;
        }

        // manage associations
        if (in_array($method, array('set', 'add', 'remove'))) {
            $this->updatePropertyAssociation($property, $valuesToUpdate);
        }

        return $this;
    }

    /**
     * Extract the info about the method called.
     *
     * @param string $name
     *
     * @return array
     */
    private function getMethodCallInfo($name)
    {
        $extractedMethod = preg_match("/^(set|get|is|add|remove)([A-Z].*)/", $name, $pregMatches);
        if ($extractedMethod) {
            $method = $pregMatches[1];
            $property = lcfirst($pregMatches[2]);
        } else {
            $method = 'call';
            $property = $name;
        }

        $collectionProperties = null;
        if (in_array($method, array('add', 'remove'))) {
            $collectionProperties = $this->_collectionsItemNames['byItemName'][$property];
            $property = $collectionProperties['property'];
        }

        // check that the method is accepted by the targeted property
        if (
            empty($this->_accessProperties[$property])
            || !in_array($method, $this->_accessProperties[$property])
        ) {
            throw new \BadMethodCallException("Method $name does not exist.");
        }

        return array(
            'method' => $method,
            'property' => $property,
            'collectionProperties' => $collectionProperties
        );
    }
}


text:
#include "QmitkUSNavigationZoneDistancesWidget.h"
#include "QmitkZoneProgressBar.h"

#include "mitkDataNode.h"
#include "mitkNavigationData.h"

#include <QVBoxLayout>

QmitkUSNavigationZoneDistancesWidget::QmitkUSNavigationZoneDistancesWidget(QWidget *parent) :
  m_SizePropertyKey("zone.size"),
  QWidget(parent)
{
  this->setLayout(new QVBoxLayout(this));
}

QmitkUSNavigationZoneDistancesWidget::~QmitkUSNavigationZoneDistancesWidget()
{
}

void QmitkUSNavigationZoneDistancesWidget::SetSizePropertyKey(const std::string& sizePropertyKey)
{
  m_SizePropertyKey = sizePropertyKey;
}

const std::string& QmitkUSNavigationZoneDistancesWidget::GetSizePropertyKey() const
{
  return m_SizePropertyKey;
}

void QmitkUSNavigationZoneDistancesWidget::AddZone(itk::SmartPointer<mitk::DataNode> zoneNode)
{
  m_ZoneNodes.append(zoneNode);
  QmitkZoneProgressBar* progressBar =
    new QmitkZoneProgressBar(QString::fromStdString(zoneNode->GetName())+QString(": %1 mm"), 60, 25, this);

  float color[3] = {1, 0, 0};
  progressBar->SetWarnColor(color);

  zoneNode->GetColor(color);
  progressBar->SetColor(color);

  m_ZoneProgressBars.append(progressBar);
  this->layout()->addWidget(progressBar);
}

void QmitkUSNavigationZoneDistancesWidget::ClearZones()
{
  // clear risk zones
  for (QVector<QmitkZoneProgressBar*>::Iterator it = m_ZoneProgressBars.begin();
       it != m_ZoneProgressBars.end(); ++it)
  {
    this->layout()->removeWidget(*it);
    delete *it;
  }

  m_ZoneProgressBars.clear();
  m_ZoneNodes.clear();
}

void QmitkUSNavigationZoneDistancesWidget::UpdateDistancesToNeedlePosition(mitk::NavigationData::Pointer needle)
{
  if ( needle.IsNull() )
  {
    MITK_ERROR("QmitkUSAbstractNavigationStep")("QmitkUSNavigationStepMarkerIntervention")
      << "Current Navigation Data for needle must not be null.";
    mitkThrow() << "Current Navigation Data for needle must not be null.";
  }

  // get needle position
  if (needle->IsDataValid())
  {
    mitk::Point3D needlePosition = needle->GetPosition();

    for (int n = 0; n < m_ZoneNodes.size(); ++n)
    {
      mitk::Point3D zoneOrigin = m_ZoneNodes.at(n)->GetData()->GetGeometry()->GetOrigin();

      // calculate absolute distance
      mitk::ScalarType distance = sqrt( pow(zoneOrigin[0] - needlePosition[0], 2) + pow(zoneOrigin[1] - needlePosition[1], 2) + pow(zoneOrigin[2] - needlePosition[2], 2) );

      // subtract zone size
      float zoneSize;
      m_ZoneNodes.at(n)->GetFloatProperty(m_SizePropertyKey.c_str(), zoneSize);
      distance = distance - zoneSize;

      m_ZoneProgressBars.at(n)->setValue(distance);

      if ( distance < 0 ) { SignalZoneViolated(m_ZoneNodes.at(n), needlePosition); }
    }
  }
}


text:
{% extends "base.html" %}

{% load url from future %}
{% load i18n %}
{% load static %}

{% block head_title %}{% trans "Delete Exam?" %}{% endblock %}

{% block extra_headers %}

<link href="{% static 'css/form-page.css' %}" rel="stylesheet">

{% endblock %}

{% block content %}

Delete Exam?

  <form action="" method="post">{% csrf_token %}

Are you sure you want to delete "{{ object }}"? You cannot undo this action

      This will also delete its version history, so you will not be
      able to recover it.

        <button class="btn btn-danger" type="submit">Confirm Delete</button>
         Cancel

  </form>

{% endblock %}


text:
package com.rtg.sam;

import java.io.File;
import java.io.IOException;

import com.rtg.launcher.globals.GlobalFlags;
import com.rtg.launcher.globals.ToolsGlobalFlags;
import com.rtg.util.integrity.Exam;
import com.rtg.util.integrity.Integrity;

import htsjdk.samtools.SAMFileHeader;
import htsjdk.samtools.SAMRecord;

/**
 * Adds some support to SkipInvalidRecordsIterator to allow externally coordinated reading of multiple SAM files.
 */

public final class SamFileAndRecord extends SkipInvalidRecordsIterator implements Comparable<SamFileAndRecord>, Integrity {

  private final int mId;
  private final String mPath;

  // work around to allow user to force file loading when sam header is malformed
  private static final boolean IGNORE_HEADER_SORTORDER = GlobalFlags.isSet(ToolsGlobalFlags.SAM_IGNORE_SORT_ORDER_FLAG);

  protected SamFileAndRecord(String path, int id, RecordIterator<SAMRecord> adaptor) throws IOException {
    super(path, adaptor, false);
    mId = id;
    mPath = path;
    validateParams(path);
  }

  /**
   * @param samFile file to be read.
   * @param id unique identifier within one instance of a SAMMultifileIterator.
   * @throws IOException if an IO Error occurs
   */
  public SamFileAndRecord(final File samFile, final int id) throws IOException {
    super(samFile);
    mPath = samFile.getPath();
    mId = id;
    validateParams(samFile.getPath());
  }

  private void validateParams(String path) throws IOException {
    if (mId < 0) {
      close();
      throw new IllegalArgumentException("id less than zero supplied: " + mId);
    }
    if (header().getSortOrder() != SAMFileHeader.SortOrder.coordinate) {
      if (!IGNORE_HEADER_SORTORDER) {
        throw new IOException("\"" + path + "\" is not sorted in coordinate order.");
      }
    }
  }

  /**
   * Get the name of the underlying file.
   * @return the name of the underlying file.
   */
  public String name() {
    return mPath;
  }

  @Override
  public boolean equals(Object obj) {
    // to keep findbugs quiet
    return super.equals(obj);
  }

  @Override
  public int hashCode() {
    // to keep findbugs quiet
    return super.hashCode();
  }

  @Override
  public int compareTo(final SamFileAndRecord that) {
    final int samCompare = SamCompareUtils.compareSamRecords(this.mRecord, that.mRecord);
    if (samCompare != 0) {
      return samCompare;
    }
    final int thisId = this.mId;
    final int thatId = that.mId;
    //System.err.println("id  this=" + thisId + " that=" + thatId);
    if (thisId < thatId) {
      return -1;
    }
    if (thisId > thatId) {
      return +1;
    }
    assert this == that;
    return 0;
  }

  @Override
  public String toString() {
    return "SamFileAndRecord:" + mId + " line=" + mRecordCount + " file=" + mPath + " record=" + mRecord.getSAMString().trim();
  }

  @Override
  public boolean integrity() {
    Exam.assertTrue(mId >= 0);

    return true;
  }

  @Override
  public boolean globalIntegrity() {
    return integrity();
  }

}


text:
<?php

abstract class P2P_Factory {

	protected $key;

	protected $queue = array();

	function __construct() {
		add_action( 'p2p_registered_connection_type', array( $this, 'check_ctype' ), 10, 2 );
	}

	// Check if a newly registered connection type needs an item to be produced.
	function check_ctype( $ctype, $args ) {
		$sub_args = $this->expand_arg( $args );

		if ( !$sub_args['show'] )
			return false;

		$this->queue[ $ctype->name ] = (object) $sub_args;
	}

	// Collect sub-args from main connection type args and set defaults
	protected function expand_arg( $args ) {
		if ( isset( $args[ $this->key ] ) ) {
			$sub_args = $args[ $this->key ];

			if ( !is_array( $sub_args ) ) {
				$sub_args = array( 'show' => $sub_args );
			}
		} else {
			$sub_args = array( 'show' => false );
		}

		$sub_args = wp_parse_args( $sub_args, array(
			'show' => 'any',
		) );

		return $sub_args;
	}

	// Begin processing item queue for a particular screen.
	function add_items() {
		$screen = get_current_screen();

		$screen_map = array(
			'edit' => 'post',
			'users' => 'user'
		);

		if ( !isset( $screen_map[ $screen->base ] ) )
			return;

		$object_type = $screen_map[ $screen->base ];

		$this->filter( $object_type, $screen->post_type );
	}

	// Filter item queue based on object type.
	function filter( $object_type, $post_type ) {
		foreach ( $this->queue as $p2p_type => $args ) {
			$ctype = p2p_type( $p2p_type );

			$directions = self::determine_directions( $ctype, $object_type, $post_type, $args->show );

			$title = self::get_title( $directions, $ctype );

			foreach ( $directions as $direction ) {
				$key = ( 'to' == $direction ) ? 'to' : 'from';

				$directed = $ctype->set_direction( $direction );

				$this->add_item( $directed, $object_type, $post_type, $title[$key] );
			}
		}
	}

	// Produce an item and add it to the screen.
	abstract function add_item( $directed, $object_type, $post_type, $title );

	protected static function get_title( $directions, $ctype ) {
		$title = array(
			'from' => $ctype->get_field( 'title', 'from' ),
			'to' => $ctype->get_field( 'title', 'to' )
		);

		if ( count( $directions ) > 1 && $title['from'] == $title['to'] ) {
			$title['from'] .= __( ' (from)', P2P_TEXTDOMAIN );
			$title['to']   .= __( ' (to)', P2P_TEXTDOMAIN );
		}

		return $title;
	}

	protected static function determine_directions( $ctype, $object_type, $post_type, $show_ui ) {
		$direction = $ctype->direction_from_types( $object_type, $post_type );
		if ( !$direction )
			return array();

		return $ctype->strategy->directions_for_admin( $direction, $show_ui );
	}
}


text:
package meTube.domain.models.view;

public class ProfileTubeViewModel {

    private String id;
    private String title;
    private String author;

    public ProfileTubeViewModel() {
    }

    public String getId() {
        return this.id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getTitle() {
        return this.title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getAuthor() {
        return this.author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 1.0 Transitional//EN">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="../includes/main.css" type="text/css">
<link rel="shortcut icon" href="../favicon.ico" type="image/x-icon">
<title>Apache CloudStack | The Power Behind Your Cloud</title>

									Apache CloudStack v4.9.0 Root Admin API Reference

listDomains

Lists domains and provides detailed information for listed domains

Request parameters

Parameter Name	Description	Required

id	List domain by domain ID.	false

keyword	List by keyword	false

level	List domains by domain level.	false

listall	If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false	false

name	List domain by domain name.	false

page		false

pagesize		false

Response Tags

Response Name	Description

id	the ID of the domain

cpuavailable	the total number of cpu cores available to be created for this domain

cpulimit	the total number of cpu cores the domain can own

cputotal	the total number of cpu cores owned by domain

haschild	whether the domain has one or more sub-domains

ipavailable	the total number of public ip addresses available for this domain to acquire

iplimit	the total number of public ip addresses this domain can acquire

iptotal	the total number of public ip addresses allocated for this domain

level	the level of the domain

memoryavailable	the total memory (in MB) available to be created for this domain

memorylimit	the total memory (in MB) the domain can own

memorytotal	the total memory (in MB) owned by domain

name	the name of the domain

networkavailable	the total number of networks available to be created for this domain

networkdomain	the network domain

networklimit	the total number of networks the domain can own

networktotal	the total number of networks owned by domain

parentdomainid	the domain ID of the parent domain

parentdomainname	the domain name of the parent domain

path	the path of the domain

primarystorageavailable	the total primary storage space (in GiB) available to be used for this domain

primarystoragelimit	the total primary storage space (in GiB) the domain can own

primarystoragetotal	the total primary storage space (in GiB) owned by domain

projectavailable	the total number of projects available for administration by this domain

projectlimit	the total number of projects the domain can own

projecttotal	the total number of projects being administrated by this domain

secondarystorageavailable	the total secondary storage space (in GiB) available to be used for this domain

secondarystoragelimit	the total secondary storage space (in GiB) the domain can own

secondarystoragetotal	the total secondary storage space (in GiB) owned by domain

snapshotavailable	the total number of snapshots available for this domain

snapshotlimit	the total number of snapshots which can be stored by this domain

snapshottotal	the total number of snapshots stored by this domain

state	the state of the domain

templateavailable	the total number of templates available to be created by this domain

templatelimit	the total number of templates which can be created by this domain

templatetotal	the total number of templates which have been created by this domain

vmavailable	the total number of virtual machines available for this domain to acquire

vmlimit	the total number of virtual machines that can be deployed by this domain

vmtotal	the total number of virtual machines deployed by this domain

volumeavailable	the total volume available for this domain

volumelimit	the total volume which can be used by this domain

volumetotal	the total volume being used by this domain

vpcavailable	the total number of vpcs available to be created for this domain

vpclimit	the total number of vpcs the domain can own

vpctotal	the total number of vpcs owned by domain

Copyright © 2015 The Apache Software Foundation, Licensed under the
                   Apache License, Version 2.0.

                Apache, CloudStack, Apache CloudStack, the Apache CloudStack logo, the CloudMonkey logo  and the Apache feather logo are trademarks of The Apache Software Foundation.


text:
import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Subscription } from 'rxjs/Rx';
import { JhiEventManager, JhiParseLinks, JhiPaginationUtil, JhiLanguageService, JhiAlertService } from 'ng-jhipster';

import { Invoice } from './invoice.model';
import { InvoiceService } from './invoice.service';
import { ITEMS_PER_PAGE, Principal, ResponseWrapper } from '../../shared';
import { PaginationConfig } from '../../blocks/config/uib-pagination.config';

@Component({
    selector: 'jhi-invoice',
    templateUrl: './invoice.component.html'
})
export class InvoiceComponent implements OnInit, OnDestroy {

currentAccount: any;
    invoices: Invoice[];
    error: any;
    success: any;
    eventSubscriber: Subscription;
    routeData: any;
    links: any;
    totalItems: any;
    queryCount: any;
    itemsPerPage: any;
    page: any;
    predicate: any;
    previousPage: any;
    reverse: any;

    constructor(
        private invoiceService: InvoiceService,
        private parseLinks: JhiParseLinks,
        private alertService: JhiAlertService,
        private principal: Principal,
        private activatedRoute: ActivatedRoute,
        private router: Router,
        private eventManager: JhiEventManager,
        private paginationUtil: JhiPaginationUtil,
        private paginationConfig: PaginationConfig
    ) {
        this.itemsPerPage = ITEMS_PER_PAGE;
        this.routeData = this.activatedRoute.data.subscribe((data) => {
            this.page = data['pagingParams'].page;
            this.previousPage = data['pagingParams'].page;
            this.reverse = data['pagingParams'].ascending;
            this.predicate = data['pagingParams'].predicate;
        });
    }

    loadAll() {
        this.invoiceService.query({
            page: this.page - 1,
            size: this.itemsPerPage,
            sort: this.sort()}).subscribe(
            (res: ResponseWrapper) => this.onSuccess(res.json, res.headers),
            (res: ResponseWrapper) => this.onError(res.json)
        );
    }
    loadPage(page: number) {
        if (page !== this.previousPage) {
            this.previousPage = page;
            this.transition();
        }
    }
    transition() {
        this.router.navigate(['/invoice'], {queryParams:
            {
                page: this.page,
                size: this.itemsPerPage,
                sort: this.predicate + ',' + (this.reverse ? 'asc' : 'desc')
            }
        });
        this.loadAll();
    }

    clear() {
        this.page = 0;
        this.router.navigate(['/invoice', {
            page: this.page,
            sort: this.predicate + ',' + (this.reverse ? 'asc' : 'desc')
        }]);
        this.loadAll();
    }
    ngOnInit() {
        this.loadAll();
        this.principal.identity().then((account) => {
            this.currentAccount = account;
        });
        this.registerChangeInInvoices();
    }

    ngOnDestroy() {
        this.eventManager.destroy(this.eventSubscriber);
    }

    trackId(index: number, item: Invoice) {
        return item.id;
    }
    registerChangeInInvoices() {
        this.eventSubscriber = this.eventManager.subscribe('invoiceListModification', (response) => this.loadAll());
    }

    sort() {
        const result = [this.predicate + ',' + (this.reverse ? 'asc' : 'desc')];
        if (this.predicate !== 'id') {
            result.push('id');
        }
        return result;
    }

    private onSuccess(data, headers) {
        this.links = this.parseLinks.parse(headers.get('link'));
        this.totalItems = headers.get('X-Total-Count');
        this.queryCount = this.totalItems;
        // this.page = pagingParams.page;
        this.invoices = data;
    }
    private onError(error) {
        this.alertService.error(error.message, null, null);
    }
}


text:
"""Meteo-France component constants."""
from __future__ import annotations

from dataclasses import dataclass

from homeassistant.components.sensor import (
    STATE_CLASS_MEASUREMENT,
    SensorEntityDescription,
)
from homeassistant.components.weather import (
    ATTR_CONDITION_CLEAR_NIGHT,
    ATTR_CONDITION_CLOUDY,
    ATTR_CONDITION_EXCEPTIONAL,
    ATTR_CONDITION_FOG,
    ATTR_CONDITION_HAIL,
    ATTR_CONDITION_LIGHTNING,
    ATTR_CONDITION_LIGHTNING_RAINY,
    ATTR_CONDITION_PARTLYCLOUDY,
    ATTR_CONDITION_POURING,
    ATTR_CONDITION_RAINY,
    ATTR_CONDITION_SNOWY,
    ATTR_CONDITION_SNOWY_RAINY,
    ATTR_CONDITION_SUNNY,
    ATTR_CONDITION_WINDY,
    ATTR_CONDITION_WINDY_VARIANT,
)
from homeassistant.const import (
    DEVICE_CLASS_PRESSURE,
    DEVICE_CLASS_TEMPERATURE,
    DEVICE_CLASS_TIMESTAMP,
    LENGTH_MILLIMETERS,
    PERCENTAGE,
    PRESSURE_HPA,
    SPEED_KILOMETERS_PER_HOUR,
    TEMP_CELSIUS,
    UV_INDEX,
)

DOMAIN = "meteo_france"
PLATFORMS = ["sensor", "weather"]
COORDINATOR_FORECAST = "coordinator_forecast"
COORDINATOR_RAIN = "coordinator_rain"
COORDINATOR_ALERT = "coordinator_alert"
UNDO_UPDATE_LISTENER = "undo_update_listener"
ATTRIBUTION = "Data provided by Météo-France"
MODEL = "Météo-France mobile API"
MANUFACTURER = "Météo-France"

CONF_CITY = "city"
FORECAST_MODE_HOURLY = "hourly"
FORECAST_MODE_DAILY = "daily"
FORECAST_MODE = [FORECAST_MODE_HOURLY, FORECAST_MODE_DAILY]

ATTR_NEXT_RAIN_1_HOUR_FORECAST = "1_hour_forecast"
ATTR_NEXT_RAIN_DT_REF = "forecast_time_ref"

@dataclass
class MeteoFranceRequiredKeysMixin:
    """Mixin for required keys."""

    data_path: str

@dataclass
class MeteoFranceSensorEntityDescription(
    SensorEntityDescription, MeteoFranceRequiredKeysMixin
):
    """Describes Meteo-France sensor entity."""

SENSOR_TYPES: tuple[MeteoFranceSensorEntityDescription, ...] = (
    MeteoFranceSensorEntityDescription(
        key="pressure",
        name="Pressure",
        native_unit_of_measurement=PRESSURE_HPA,
        device_class=DEVICE_CLASS_PRESSURE,
        state_class=STATE_CLASS_MEASUREMENT,
        entity_registry_enabled_default=False,
        data_path="current_forecast:sea_level",
    ),
    MeteoFranceSensorEntityDescription(
        key="wind_gust",
        name="Wind gust",
        native_unit_of_measurement=SPEED_KILOMETERS_PER_HOUR,
        state_class=STATE_CLASS_MEASUREMENT,
        icon="mdi:weather-windy-variant",
        entity_registry_enabled_default=False,
        data_path="current_forecast:wind:gust",
    ),
    MeteoFranceSensorEntityDescription(
        key="wind_speed",
        name="Wind speed",
        native_unit_of_measurement=SPEED_KILOMETERS_PER_HOUR,
        state_class=STATE_CLASS_MEASUREMENT,
        icon="mdi:weather-windy",
        entity_registry_enabled_default=False,
        data_path="current_forecast:wind:speed",
    ),
    MeteoFranceSensorEntityDescription(
        key="temperature",
        name="Temperature",
        native_unit_of_measurement=TEMP_CELSIUS,
        device_class=DEVICE_CLASS_TEMPERATURE,
        state_class=STATE_CLASS_MEASUREMENT,
        entity_registry_enabled_default=False,
        data_path="current_forecast:T:value",
    ),
    MeteoFranceSensorEntityDescription(
        key="uv",
        name="UV",
        native_unit_of_measurement=UV_INDEX,
        icon="mdi:sunglasses",
        data_path="today_forecast:uv",
    ),
    MeteoFranceSensorEntityDescription(
        key="precipitation",
        name="Daily precipitation",
        native_unit_of_measurement=LENGTH_MILLIMETERS,
        icon="mdi:cup-water",
        data_path="today_forecast:precipitation:24h",
    ),
    MeteoFranceSensorEntityDescription(
        key="cloud",
        name="Cloud cover",
        native_unit_of_measurement=PERCENTAGE,
        icon="mdi:weather-partly-cloudy",
        data_path="current_forecast:clouds",
    ),
    MeteoFranceSensorEntityDescription(
        key="original_condition",
        name="Original condition",
        entity_registry_enabled_default=False,
        data_path="current_forecast:weather:desc",
    ),
    MeteoFranceSensorEntityDescription(
        key="daily_original_condition",
        name="Daily original condition",
        entity_registry_enabled_default=False,
        data_path="today_forecast:weather12H:desc",
    ),
)

SENSOR_TYPES_RAIN: tuple[MeteoFranceSensorEntityDescription, ...] = (
    MeteoFranceSensorEntityDescription(
        key="next_rain",
        name="Next rain",
        device_class=DEVICE_CLASS_TIMESTAMP,
        data_path="",
    ),
)

SENSOR_TYPES_ALERT: tuple[MeteoFranceSensorEntityDescription, ...] = (
    MeteoFranceSensorEntityDescription(
        key="weather_alert",
        name="Weather alert",
        icon="mdi:weather-cloudy-alert",
        data_path="",
    ),
)

SENSOR_TYPES_PROBABILITY: tuple[MeteoFranceSensorEntityDescription, ...] = (
    MeteoFranceSensorEntityDescription(
        key="rain_chance",
        name="Rain chance",
        native_unit_of_measurement=PERCENTAGE,
        icon="mdi:weather-rainy",
        data_path="probability_forecast:rain:3h",
    ),
    MeteoFranceSensorEntityDescription(
        key="snow_chance",
        name="Snow chance",
        native_unit_of_measurement=PERCENTAGE,
        icon="mdi:weather-snowy",
        data_path="probability_forecast:snow:3h",
    ),
    MeteoFranceSensorEntityDescription(
        key="freeze_chance",
        name="Freeze chance",
        native_unit_of_measurement=PERCENTAGE,
        icon="mdi:snowflake",
        data_path="probability_forecast:freezing",
    ),
)

CONDITION_CLASSES = {
    ATTR_CONDITION_CLEAR_NIGHT: ["Nuit Claire", "Nuit claire"],
    ATTR_CONDITION_CLOUDY: ["Très nuageux", "Couvert"],
    ATTR_CONDITION_FOG: [
        "Brume ou bancs de brouillard",
        "Brume",
        "Brouillard",
        "Brouillard givrant",
        "Bancs de Brouillard",
    ],
    ATTR_CONDITION_HAIL: ["Risque de grêle", "Risque de grèle"],
    ATTR_CONDITION_LIGHTNING: ["Risque d'orages", "Orages"],
    ATTR_CONDITION_LIGHTNING_RAINY: [
        "Pluie orageuses",
        "Pluies orageuses",
        "Averses orageuses",
    ],
    ATTR_CONDITION_PARTLYCLOUDY: [
        "Ciel voilé",
        "Ciel voilé nuit",
        "Éclaircies",
        "Eclaircies",
        "Peu nuageux",
    ],
    ATTR_CONDITION_POURING: ["Pluie forte"],
    ATTR_CONDITION_RAINY: [
        "Bruine / Pluie faible",
        "Bruine",
        "Pluie faible",
        "Pluies éparses / Rares averses",
        "Pluies éparses",
        "Rares averses",
        "Pluie modérée",
        "Pluie / Averses",
        "Averses",
        "Pluie",
    ],
    ATTR_CONDITION_SNOWY: [
        "Neige / Averses de neige",
        "Neige",
        "Averses de neige",
        "Neige forte",
        "Quelques flocons",
    ],
    ATTR_CONDITION_SNOWY_RAINY: ["Pluie et neige", "Pluie verglaçante"],
    ATTR_CONDITION_SUNNY: ["Ensoleillé"],
    ATTR_CONDITION_WINDY: [],
    ATTR_CONDITION_WINDY_VARIANT: [],
    ATTR_CONDITION_EXCEPTIONAL: [],
}


text:
<?php
namespace Accounting\Entity;

use Zend\Permissions\Acl\Resource\ResourceInterface;
use Doctrine\ORM\Mapping AS ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Application\Entity\EditableEntity;
use Application\Entity\User;
use People\Entity\Organization;
/**
 * @ORM\Entity
 * @ORM\Table(name="accounts")
 * @ORM\InheritanceType("SINGLE_TABLE")
 * @ORM\DiscriminatorColumn(name="type", type="string")
 */
abstract class Account extends EditableEntity implements ResourceInterface {

	/**
	 * @ORM\Embedded(class="Accounting\Entity\Balance")
	 * @var Balance
	 */
	protected $balance;
	/**
	 * @ORM\ManyToMany(targetEntity="Application\Entity\User", cascade={"PERSIST", "REMOVE"}, indexBy="id")
	 * @ORM\JoinTable(name="account_holders", joinColumns={@ORM\JoinColumn(name="account_id", referencedColumnName="id", onDelete="CASCADE")},
	 * 		inverseJoinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id", onDelete="CASCADE")}
	 * )
	 * @var User[]
	 */
	protected $holders;
	/**
	 * @ORM\OneToOne(targetEntity="People\Entity\Organization")
	 * @ORM\JoinColumn(name="organization_id", referencedColumnName="id", onDelete="CASCADE")
	 * @var Organization
	 */
	protected $organization;

	/**
	 * @param $id
	 * @param Organization $organization
	 */
	public function __construct($id, Organization $organization) {
		parent::__construct($id);
		$this->organization = $organization;
		$this->holders = new ArrayCollection();
	}

	/**
	 * @param Balance $balance
	 * @return $this
	 */
	public function setBalance(Balance $balance) {
		$this->balance = $balance;
		return $this;
	}

	/**
	 * @return Balance
	 */
	public function getBalance() {
		if(is_null($this->balance)) {
			$this->balance = new Balance(0, $this->getCreatedAt());
		}
		return $this->balance;
	}

	/**
	 * @return \Application\Entity\User[]
	 */
	public function getHolders() {
		return $this->holders->toArray();
	}

	/**
	 * @param User $holder
	 * @return $this
	 */
	public function addHolder(User $holder) {
		$this->holders->set($holder->getId(), $holder);
		return $this;
	}

	/**
	 * @param User $user
	 * @return bool
	 */
	public function isHeldBy(User $user) {
		return $this->holders->containsKey($user->getId());
	}

	/**
	 * @return Organization
	 */
	public function getOrganization() {
		return $this->organization;
	}

	/**
	 * @return string
	 */
	public function getOrganizationId() {
		return $this->getOrganization()->getId();
	}

	/**
	 * @return string
	 */
	public function getName() {
		if($this->holders->count() > 0) {
			$holder = $this->holders->first();
			return $holder->getFirstname() . ' ' . $holder->getLastname();
		}
		return null;
	}
}


text:
package com.core.jpa.entity.movie;

import com.common.dto.movie.type.CountryType;

import javax.annotation.Generated;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
import java.util.Date;

/**
 * Representation of the movie's metamodel release date.
 */
@Generated(value = "org.eclipse.persistence.internal.jpa.modelgen.CanonicalModelProcessor")
@StaticMetamodel(MovieReleaseDateEntity.class)
public abstract class MovieReleaseDateEntity_ extends MovieInfoEntity_ {
    public static volatile SingularAttribute<MovieReleaseDateEntity, Date> date;
    public static volatile SingularAttribute<MovieReleaseDateEntity, CountryType> country;
}


text:
import json
import logging
import requests
import time
from itertools import izip

import defaults
from utils import iter_lines

LOG = logging.getLogger(__name__)

def iter_request_events(fd):
    '''Iterate over the events from a Kubernetes event stream.'''

    lines = iter_lines(fd)
    for expected_len, data, marker in izip(lines, lines, lines):
        expected_len = int(expected_len, base=16)
        actual_len = len(data)
        if expected_len != actual_len + 1:
            raise ValueError('data length mismatch (expected %d, have %d)',
                             expected_len,
                             actual_len)

        yield json.loads(data)

def iter_events(url, interval=1):
    '''Generates an infinite string of Kubernetes events'''

    while True:
        try:
            r = requests.get(url, stream=True)
            r.raise_for_status()
            for event in iter_request_events(r.raw):
                yield event
        except Exception as exc:
            LOG.error('connection failed: %s' % exc)
            time.sleep(interval)

class ServiceWatcher (object):
    '''A ServiceWatcher is an iterator that watches the Kubernetes API for
    changes to services, and yields these events as Python dictionaries.'''

    def __init__(self,
                 reconnect_interval=defaults.reconnect_interval,
                 kube_endpoint=defaults.kube_endpoint):
        super(ServiceWatcher, self).__init__()

        self.kube_api = '%s/api/v1' % kube_endpoint
        self.reconnect_interval = reconnect_interval

    def __iter__(self):
        url = '%s/watch/services' % self.kube_api

        for event in iter_events(url, interval=self.reconnect_interval):
            service = event['object']
            LOG.debug('received %s for %s',
                      event['type'],
                      service['metadata']['name'])

            handler = getattr(self,
                              'handle_%s' % event['type'].lower())

            # we log missing handlers at debug level because we probably
            # intentionally have not written a handler for the event.
            if not handler:
                LOG.debug('unknown event: %(type)s' % event)
                continue

            yield(handler(service))

    def handle_added(self, service):
        return({'message': 'add-service',
                'target': service['metadata']['name'],
                'service': service})

    def handle_deleted(self, service):
        return({'message': 'delete-service',
                'target': service['metadata']['name'],
                'service': service})

    def handle_modified(self, service):
        return({'message': 'update-service',
                'target': service['metadata']['name'],
                'service': service})

if __name__ == '__main__':
    import pprint

    logging.basicConfig(level=logging.DEBUG)
    s = ServiceWatcher()

    for msg in s:
        pprint.pprint(msg)


text:
package util;

import java.util.AbstractSet;
import java.util.HashSet;
import java.util.Iterator;

//public class PairSet<T1, T2> extends AbstractSet<Pair<T1,T2>>{
public class PairSet<T1> extends HashSet<Pair<T1>>{
	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	public PairSet(){

	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//PairSet<Integer, Integer> set = new PairSet<Integer, Integer>();
		//HashSet<Integer> set2 = new HashSet<Integer>();
	}

}


text:
/**
*============================================================================
*  The Ohio State University Research Foundation, The University of Chicago -
*  Argonne National Laboratory, Emory University, SemanticBits LLC,
*  and Ekagra Software Technologies Ltd.
*
*  Distributed under the OSI-approved BSD 3-Clause License.
*  See http://ncip.github.com/cagrid-portal/LICENSE.txt for details.
*============================================================================
**/
/**
 *
 */
package gov.nih.nci.cagrid.portal.portlet.util;

import gov.nih.nci.cagrid.portal.domain.catalog.Temporal;

import java.util.Comparator;

/**
 * @author Joshua Phillips
 *
 */
public class TemporalComparator implements Comparator<Temporal> {

	/* (non-Javadoc)
	 * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
	 */
	public int compare(Temporal t1, Temporal t2) {
		return t1.getCreatedAt().compareTo(t2.getCreatedAt());
	}

}