text:
package org.flywaydb.core.api.callback;

import lombok.RequiredArgsConstructor;
import lombok.Getter;

/**
 * The Flyway lifecycle events that can be handled in callbacks.
 */
@RequiredArgsConstructor
public enum Event {
    /**
     * Fired before clean is executed. This event will be fired in a separate transaction from the actual clean operation.
     */
    BEFORE_CLEAN("beforeClean"),
    /**
     * Fired after clean has succeeded. This event will be fired in a separate transaction from the actual clean operation.
     */
    AFTER_CLEAN("afterClean"),
    /**
     * Fired after clean has failed. This event will be fired in a separate transaction from the actual clean operation.
     */
    AFTER_CLEAN_ERROR("afterCleanError"),

    /**
     * Fired before migrate is executed. This event will be fired in a separate transaction from the actual migrate operation.
     */
    BEFORE_MIGRATE("beforeMigrate"),
    /**
     * Fired before each individual migration is executed. This event will be fired within the same transaction (if any)
     * as the migration and can be used for things like setting up connection parameters that are required by migrations.
     */
    BEFORE_EACH_MIGRATE("beforeEachMigrate"),
    /**
     * Fired before each individual statement in a migration is executed. This event will be fired within the same transaction (if any)
     * as the migration and can be used for things like asserting a statement complies with policy (for example: no grant statements allowed).
     *
Flyway Teams Edition only

     */
    BEFORE_EACH_MIGRATE_STATEMENT("beforeEachMigrateStatement"),
    /**
     * Fired after each individual statement in a migration that succeeded. This event will be fired within the same transaction (if any)
     * as the migration.
     *
Flyway Teams Edition only

     */
    AFTER_EACH_MIGRATE_STATEMENT("afterEachMigrateStatement"),
    /**
     * Fired after each individual statement in a migration that failed. This event will be fired within the same transaction (if any)
     * as the migration.
     *
Flyway Teams Edition only

     */
    AFTER_EACH_MIGRATE_STATEMENT_ERROR("afterEachMigrateStatementError"),
    /**
     * Fired after each individual migration that succeeded. This event will be fired within the same transaction (if any)
     * as the migration.
     */
    AFTER_EACH_MIGRATE("afterEachMigrate"),
    /**
     * Fired after each individual migration that failed. This event will be fired within the same transaction (if any)
     * as the migration.
     */
    AFTER_EACH_MIGRATE_ERROR("afterEachMigrateError"),
    /**
     * Fired before any repeatable migrations are applied. This event will be fired in a separate transaction from the actual migrate operation.
     */
    BEFORE_REPEATABLES("beforeRepeatables"),
    /**
     * Fired after all versioned migrations are applied. This event will be fired in a separate transaction from the actual migrate operation.
     */
    AFTER_VERSIONED("afterVersioned"),
    /**
     * Fired after migrate has succeeded, and at least one migration has been applied. This event will be fired in a separate transaction from the actual migrate operation.
     */
    AFTER_MIGRATE_APPLIED("afterMigrateApplied"),
    /**
     * Fired after migrate has succeeded. This event will be fired in a separate transaction from the actual migrate operation.
     */
    AFTER_MIGRATE("afterMigrate"),
    /**
     * Fired after migrate has failed. This event will be fired in a separate transaction from the actual migrate operation.
     */
    AFTER_MIGRATE_ERROR("afterMigrateError"),

    /**
     * Fired before undo is executed. This event will be fired in a separate transaction from the actual undo operation.
     *
Flyway Teams Edition only

     */
    BEFORE_UNDO("beforeUndo"),
    /**
     * Fired before each individual undo is executed. This event will be fired within the same transaction (if any)
     * as the undo and can be used for things like setting up connection parameters that are required by undo.
     *
Flyway Teams Edition only

     */
    BEFORE_EACH_UNDO("beforeEachUndo"),
    /**
     * Fired before each individual statement in an undo migration is executed. This event will be fired within the same transaction (if any)
     * as the migration and can be used for things like asserting a statement complies with policy (for example: no grant statements allowed).
     *
Flyway Teams Edition only

     */
    BEFORE_EACH_UNDO_STATEMENT("beforeEachUndoStatement"),
    /**
     * Fired after each individual statement in an undo migration that succeeded. This event will be fired within the same transaction (if any)
     * as the migration.
     *
Flyway Teams Edition only

     */
    AFTER_EACH_UNDO_STATEMENT("afterEachUndoStatement"),
    /**
     * Fired after each individual statement in an undo migration that failed. This event will be fired within the same transaction (if any)
     * as the migration.
     *
Flyway Teams Edition only

     */
    AFTER_EACH_UNDO_STATEMENT_ERROR("afterEachUndoStatementError"),
    /**
     * Fired after each individual undo that succeeded. This event will be fired within the same transaction (if any)
     * as the undo.
     *
Flyway Teams Edition only

     */
    AFTER_EACH_UNDO("afterEachUndo"),
    /**
     * Fired after each individual undo that failed. This event will be fired within the same transaction (if any)
     * as the undo.
     *
Flyway Teams Edition only

     */
    AFTER_EACH_UNDO_ERROR("afterEachUndoError"),
    /**
     * Fired after undo has succeeded. This event will be fired in a separate transaction from the actual undo operation.
     *
Flyway Teams Edition only

     */
    AFTER_UNDO("afterUndo"),
    /**
     * Fired after undo has failed. This event will be fired in a separate transaction from the actual undo operation.
     *
Flyway Teams Edition only

     */
    AFTER_UNDO_ERROR("afterUndoError"),

    /**
     * Fired before validate is executed. This event will be fired in a separate transaction from the actual validate operation.
     */
    BEFORE_VALIDATE("beforeValidate"),
    /**
     * Fired after validate has succeeded. This event will be fired in a separate transaction from the actual validate operation.
     */
    AFTER_VALIDATE("afterValidate"),
    /**
     * Fired after validate has failed. This event will be fired in a separate transaction from the actual validate operation.
     */
    AFTER_VALIDATE_ERROR("afterValidateError"),

    /**
     * Fired before baseline is executed. This event will be fired in a separate transaction from the actual baseline operation.
     */
    BEFORE_BASELINE("beforeBaseline"),
    /**
     * Fired after baseline has succeeded. This event will be fired in a separate transaction from the actual baseline operation.
     */
    AFTER_BASELINE("afterBaseline"),
    /**
     * Fired after baseline has failed. This event will be fired in a separate transaction from the actual baseline operation.
     */
    AFTER_BASELINE_ERROR("afterBaselineError"),

    /**
     * Fired before repair is executed. This event will be fired in a separate transaction from the actual repair operation.
     */
    BEFORE_REPAIR("beforeRepair"),
    /**
     * Fired after repair has succeeded. This event will be fired in a separate transaction from the actual repair operation.
     */
    AFTER_REPAIR("afterRepair"),
    /**
     * Fired after repair has failed. This event will be fired in a separate transaction from the actual repair operation.
     */
    AFTER_REPAIR_ERROR("afterRepairError"),

    /**
     * Fired before info is executed. This event will be fired in a separate transaction from the actual info operation.
     */
    BEFORE_INFO("beforeInfo"),
    /**
     * Fired after info has succeeded. This event will be fired in a separate transaction from the actual info operation.
     */
    AFTER_INFO("afterInfo"),
    /**
     * Fired after info has failed. This event will be fired in a separate transaction from the actual info operation.
     */
    AFTER_INFO_ERROR("afterInfoError"),
    /**
     * Fired after a migrate operation has finished.
     */
    AFTER_MIGRATE_OPERATION_FINISH("afterMigrateOperationFinish"),
    /**
     * Fired after an info operation has finished.
     */
    AFTER_INFO_OPERATION_FINISH("afterInfoOperationFinish"),
    /**
     * Fired after a clean operation has finished.
     */
    AFTER_CLEAN_OPERATION_FINISH("afterInfoOperationFinish"),
    /**
     * Fired after a validate operation has finished.
     */
    AFTER_VALIDATE_OPERATION_FINISH("afterInfoOperationFinish"),
    /**
     * Fired after a validate operation has finished.
     */
    AFTER_UNDO_OPERATION_FINISH("afterInfoOperationFinish"),
    /**
     * Fired after a validate operation has finished.
     */
    AFTER_REPAIR_OPERATION_FINISH("afterInfoOperationFinish"),
    /**
     * Fired after a validate operation has finished.
     */
    AFTER_BASELINE_OPERATION_FINISH("afterInfoOperationFinish"),
    /**
     * Fired before any non-existent schemas are created.
     */
    CREATE_SCHEMA("createSchema"),
    /**
     * Fired before a connection is created. These must be arbitrary scripts only (e.g. ps1, cmd, sh etc.)
     *
Flyway Teams Edition only

     */
    BEFORE_CONNECT("beforeConnect");

    /**
     * @return The id of an event. Examples: {@code beforeClean}, {@code afterEachMigrate}, ...
     */
    @Getter
    private final String id;

    /**
     * Retrieves the event with this id.
     *
     * @param id The id.
     * @return The event. {@code null} if not found.
     */
    public static Event fromId(String id) {
        for (Event event : values()) {
            if (event.id.equals(id)) {
                return event;
            }
        }
        return null;
    }

    @Override
    public String toString() {
        return id;
    }
}


text:
package com.jhouseke.onemessageaway.app.ui.dialogs;

import android.animation.Animator;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jhouseke.onemessageaway.app.R;
import com.jhouseke.onemessageaway.app.dataprovider.LocalBackupManager;
import com.jhouseke.onemessageaway.app.util.LogUtil;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

/**
 * Created by timothymiko on 12/12/14.
 */
public class BackupRestoreDialog extends MaterialDialogFragment {

    private LinearLayout mList;
    private Adapter mAdapter;
    private Handler mHandler;

    public BackupRestoreDialog() {
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        if ( getActivity() != null ) {

            setTitle(R.string.tap_to_restore);
            setContentView(R.layout.backup_restore_dialog);

            final Dialog dialog = super.onCreateDialog(savedInstanceState);
            dialog.findViewById(R.id.dialog_buttons_layout).setVisibility(View.GONE);

            final View loader = dialog.findViewById(R.id.loading_indicator);
            mList = (LinearLayout) dialog.findViewById(R.id.list);
            final TextView noBackupsTextView = (TextView) dialog.findViewById(R.id.no_backups_found);
            mHandler = new Handler(Looper.getMainLooper());

            new Thread() {
                @Override
                public void run() {
                    super.run();
                    // get the data
                    final File[] backups = LocalBackupManager.getBackups();

                    if ( backups == null || backups.length == 0 ) {
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                noBackupsTextView.setVisibility(View.VISIBLE);
                                loader.animate().alpha(0f).start();
                                noBackupsTextView.animate().alpha(1f).start();
                            }
                        });
                        return;
                    }

                    final List<File> backupList = new ArrayList<File>();
                    for (int i = 0; i < backups.length; i++)
                        backupList.add(backups[i]);

                    Collections.sort(backupList, new Comparator<File>() {
                        @Override
                        public int compare(File lhs, File rhs) {
                            return lhs.getName().compareTo(rhs.getName());
                        }
                    });

                    final String[] titles = new String[backupList.size()];

                    for ( int i = 0; i < backupList.size(); i++ ) {
                        Date date = null;
                        for ( int j = 0; j < backupList.get(i).getName().length(); j++ ) {
                            if ( backupList.get(i).getName().charAt(j) == '-' ) {
                                try {
                                    date = LocalBackupManager.DATE_FORMAT.parse(backupList.get(i).getName().substring(j+1));
                                } catch (ParseException e) {
                                    e.printStackTrace();
                                    LogUtil.e("Narrate", "Failed to parse Narrate backup file.");
                                    date = null;
                                }
                                break;
                            }
                        }

                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                        if ( date != null ) {
                            titles[i] = df.format(date);
                        }
                    }

                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            mAdapter = new Adapter(getActivity(), R.layout.simple_list_item_1, titles);
                            mAdapter.setItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                                    setCancelable(false);
                                    textViewTitle.setText(R.string.local_backup_restoring);
                                    loader.animate().alpha(1f).start();
                                    mList.animate().alpha(0f).setListener(new Animator.AnimatorListener() {
                                        @Override
                                        public void onAnimationStart(Animator animation) {

                                        }

                                        @Override
                                        public void onAnimationEnd(Animator animation) {
                                            mList.setVisibility(View.INVISIBLE);
                                        }

                                        @Override
                                        public void onAnimationCancel(Animator animation) {

                                        }

                                        @Override
                                        public void onAnimationRepeat(Animator animation) {

                                        }
                                    }).start();
                                    new Thread() {
                                        @Override
                                        public void run() {
                                            super.run();
                                            LocalBackupManager.restore(backupList.get(position));
                                            dismiss();
                                        }
                                    }.start();
                                }
                            });
                            loader.animate().alpha(0f).start();
                            updateListViews();
                        }
                    });
                }
            }.start();

            return dialog;

        } else
             return null;
    }

    private void updateListViews() {
        mList.removeAllViews();

        for ( int i = 0; i < mAdapter.getCount(); i++ ) {
            View v = mAdapter.getView(i, null, null);

            if ( v != null )
                mList.addView(v);
        }
    }

    private class Adapter extends ArrayAdapter<String> {

        private AdapterView.OnItemClickListener itemClickListener;

        public Adapter(Context context, int resource, String[] objects) {
            super(context, resource, objects);
        }

        public void setItemClickListener(AdapterView.OnItemClickListener itemClickListener) {
            this.itemClickListener = itemClickListener;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            if ( getItem(position) != null ) {
                View v = super.getView(position, convertView, parent);

                v.setClickable(true);
                v.setBackgroundResource(R.drawable.default_selector);
                v.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (itemClickListener != null)
                            itemClickListener.onItemClick(null, v, position, 0);
                    }
                });

                return v;
            } else
                return null;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.teavm.classlib.java.nio.charset.impl;

import org.teavm.classlib.java.nio.charset.TCharset;
import org.teavm.classlib.java.nio.charset.TCharsetDecoder;
import org.teavm.classlib.java.nio.charset.TCharsetEncoder;

/**
 *
 * @author Alexey Andreev
 */
public class TLatin1Charset extends TCharset {
    public TLatin1Charset() {
        super("ISO-8859-1", new String[0]);
    }

    @Override
    public boolean contains(TCharset cs) {
        return cs == this;
    }

    @Override
    public TCharsetDecoder newDecoder() {
        return new TLatin1Decoder(this);
    }

    @Override
    public TCharsetEncoder newEncoder() {
        return new TLatin1Encoder(this);
    }
}


text:
This tool can be used to generate the Security Advisories for WSO2 products.

Note: This repository is under active development.

## Support
### Product Families
* WSO2 Carbon 4 Based Products

## Build
```
mvn clean install
```

## Usage

Extract the advisorytool-1.0-SNAPSHOT.zip

1. To generate the customer security advisory HTML
```
java -jar advisorytool-1.0-SNAPSHOT.jar -type customer -out html
```

2. To generate the customer security advisory XML
```
java -jar advisorytool-1.0-SNAPSHOT.jar -type customer -out xml
```

3. To generate the customer security advisory PDF
```
java -jar advisorytool-1.0-SNAPSHOT.jar -type customer -out pdf
```

4. To generate the customer security advisory PDF from HTML
```
java -jar advisorytool-1.0-SNAPSHOT.jar -type customer -out html2pdf
```

5. To generate the security advisory PDF from XML
```
java -jar advisorytool-1.0-SNAPSHOT.jar -type customer -out xml2pdf
```

6. To generate the security advisory HTML from XML
```
java -jar advisorytool-1.0-SNAPSHOT.jar -type customer -out html2xml
```


text:
<?php

	Class extension_noediting extends Extension{

		public function about(){
			return array('name' => ' Filter: No Editing of Entries',
						 'version' => '1.0',
						 'release-date' => '2009-06-12',
						 'author' => array('name' => 'Nils Werner',
										   'website' => 'http://www.phoque.de/projekte/symphony',
										   'email' => 'nils.werner@gmail.com'),
						 'description' => 'Allows you to prevent users from editing entries from front end forms.'
				 		);
		}

		public function getSubscribedDelegates(){
			return array(
						array(
							'page' => '/blueprints/events/new/',
							'delegate' => 'AppendEventFilter',
							'callback' => 'addFilterToEventEditor'
						),

						array(
							'page' => '/blueprints/events/edit/',
							'delegate' => 'AppendEventFilter',
							'callback' => 'addFilterToEventEditor'
						),

						array(
							'page' => '/blueprints/events/new/',
							'delegate' => 'AppendEventFilterDocumentation',
							'callback' => 'addFilterDocumentationToEvent'
						),

						array(
							'page' => '/blueprints/events/edit/',
							'delegate' => 'AppendEventFilterDocumentation',
							'callback' => 'addFilterDocumentationToEvent'
						),

						array(
							'page' => '/frontend/',
							'delegate' => 'EventPreSaveFilter',
							'callback' => 'processEventData'
						),
			);
		}

		public function addFilterToEventEditor($context){
			$context['options'][] = array('no-editing', @in_array('no-editing', $context['selected']) ,'No Editing of Entries');
		}

		public function addFilterDocumentationToEvent($context){
			if(!in_array('no-editing', $context['selected'])) return;

			$context['documentation'][] = new XMLElement('h3', 'Prevent Editing');

			$context['documentation'][] = new XMLElement('p', 'Prevents users from supplying an entry ID to edit entries like so:');
			$code = '<input name="id" type="hidden" value="23" />';

			$context['documentation'][] = contentBlueprintsEvents::processDocumentationCode($code);

			$context['documentation'][] = new XMLElement('p', 'The following is an example of the XML returned form this filter:');
			$code = '<filter name="no-editing" status="passed" />
					<filter name="no-editing" status="failed">You are not allowed to edit entries.</filter>';

			$context['documentation'][] = contentBlueprintsEvents::processDocumentationCode($code);

		}

		public function processEventData($context){

			if(!in_array('no-editing', $context['event']->eParamFILTERS)) return;

			if(isset($_POST['id'])) {
				$context['messages'][] = array('no-editing', false, 'You are not allowed to edit entries.');
			}

		}

		public function uninstall(){
			return true;
		}

	}


text:
<?xml version="1.0" encoding="UTF-8"?>
<localization xmlns="http://www.i18n.purelib.chav1961.ru/">
	<lang name="en">
<!-- Application window localization -->
		<key name="JScreen.caption">(c) 2017..2018, Alexander V.Chernomyrdin aka chav1961, Funny Prolog V.R=0.0.2</key>
		<key name="JScreen.status.initialHelp">To execute Funny Prolog sentence, highlight console sentence and press F5</key>
		<key name="JScreen.about.title">About...</key>
		<key name="JScreen.about.content">uri(aboutApplication.cre)</key>

<!-- Application menu localization -->
		<key name="menu.file">File</key>
		<key name="menu.file.tt">Manage files and exit from application</key>
		<key name="menu.file.new">New</key>
		<key name="menu.file.new.tt">Create new *.frp file</key>
		<key name="menu.file.open">Open</key>
		<key name="menu.file.open.tt">Open existent *.frp file</key>
		<key name="menu.file.preparefrb">Prepare FRB</key>
		<key name="menu.file.preparefrb.tt">Prepare new Funny Prolog fact/rule base. To use it, Funny Prolog VM must be stopped firstly</key>
		<key name="menu.file.consult">Consult...</key>
		<key name="menu.file.consult.tt">Consult a set of files into Funny Prolog fact/rule base</key>
		<key name="menu.file.exit">Exit</key>
		<key name="menu.file.exit.tt">Exit Funny Prolog</key>
		<key name="menu.actions">Actions</key>
		<key name="menu.actions.tt">Manage Funny Prolog virtual machine</key>
		<key name="menu.actions.startvm">Start VM</key>
		<key name="menu.actions.startvm.tt">Start Funny Prolog virtual machine</key>
		<key name="menu.actions.stopvm">Stop VM</key>
		<key name="menu.actions.stopvm.tt">Stop Funny Prolog virtual machine</key>
		<key name="menu.actions.parameters">VM parameters</key>
		<key name="menu.actions.parameters.tt">Funny Prolog virtual machine parameters</key>
		<key name="menu.tools">Tools</key>
		<key name="menu.tools.tt">Usual tools</key>
		<key name="menu.tools.laf">Change Look & Feel</key>
		<key name="menu.tools.laf.tt">Change Current Look & Feel</key>
		<key name="menu.tools.languages">Language</key>
		<key name="menu.tools.languages.tt">Change current language</key>
		<key name="menu.help">Help & Settings</key>
		<key name="menu.help.tt">Set of helps and settings</key>
		<key name="menu.help.settings">Settings</key>
		<key name="menu.help.settings.tt">Application settings</key>
		<key name="menu.help.about">About...</key>
		<key name="menu.help.about.tt">About Funny Prolog</key>
	</lang>
	<lang name="ru">
<!-- Локализация окна приложения -->
		<key name="JScreen.caption">(c) 2017..2018, А. Черномырдин aka chav1961, Funny Prolog V.R=0.0.2</key>
		<key name="JScreen.status.initialHelp">Для выполнения предложения Funny Prolog выделите в консоли предложение и нажмите F5... </key>
		<key name="JScreen.about.title">О программе</key>
		<key name="JScreen.about.content">uri(aboutApplication.cre)</key>

<!-- Локализация меню приложения -->
		<key name="menu.file">Файл</key>
		<key name="menu.file.tt">Манипуляции файлами и завершение работы программы</key>
		<key name="menu.file.new">Создать</key>
		<key name="menu.file.new.tt">Создать новый файл *.frp</key>
		<key name="menu.file.open">Открыть</key>
		<key name="menu.file.open.tt">Открыть существующий файл *.frp</key>
		<key name="menu.file.preparefrb">Подготовить FRB</key>
		<key name="menu.file.preparefrb.tt">Подготовить новую базу фактов/правил Funny Prolog. Для его работы нужно вначале остановить виртуальную машину Funny Prolog</key>
		<key name="menu.file.consult">Подгрузить...</key>
		<key name="menu.file.consult.tt">Подгрузить файлы в базу фактов/правил Funny Prolog</key>
		<key name="menu.file.exit">Выход</key>
		<key name="menu.file.exit.tt">Завершение работы Finny Prolog</key>
		<key name="menu.actions">Действия</key>
		<key name="menu.actions.tt">Управление виртуальной машиной Funny Prolog</key>
		<key name="menu.actions.startvm">Запуск VM</key>
		<key name="menu.actions.startvm.tt">Запустить виртуальную машину Funny Prolog</key>
		<key name="menu.actions.stopvm">Остановка VM</key>
		<key name="menu.actions.stopvm.tt">Остановить виртуальную машину Funny Prolog</key>
		<key name="menu.actions.parameters">Параметры VM</key>
		<key name="menu.actions.parameters.tt">Параметры виртуальной машины Funny Prolog</key>
		<key name="menu.tools">Инструменты</key>
		<key name="menu.tools.tt">Различные инструменты</key>
		<key name="menu.tools.laf">Изменить внешний вид (Look & Feel)</key>
		<key name="menu.tools.laf.tt">Настройка внешнего виде приложения</key>
		<key name="menu.tools.languages">Язык</key>
		<key name="menu.tools.languages.tt">Изменить язык приложения</key>
		<key name="menu.help">Помощь и настройки</key>
		<key name="menu.help.tt">Различные настройки и помощь</key>
		<key name="menu.help.settings">Настройки</key>
		<key name="menu.help.settings.tt">Настройки приложения</key>
		<key name="menu.help.about">О программе...</key>
		<key name="menu.help.about.tt">Информация о Funny Prolog</key>
	</lang>
</localization>


text:
This project aims to provide a simple and customizable pull to refresh implementation. Made in [Yalantis] (http://yalantis.com/)

Check this [project on Dribbble] (https://dribbble.com/shots/1650317-Pull-to-Refresh-Rentals)
Check this [project on Behance] (https://www.behance.net/gallery/20411445/Mobile-Animations-Interactions)

<img src="https://d13yacurqjgara.cloudfront.net/users/125056/screenshots/1650317/realestate-pull_1-2-3.gif" alt="alt text" style="width:200;height:200">

#Usage

*For a working implementation, Have a look at the Sample Project - sample*

1. Add folder YALSunnyRefreshControll to your project.
2. Implement header and setup YALSunnyRefreshControl as a property.
3. Init and associate YALSunnyRefreshControl with your UITableView or UICollectionView.
4. Add images from Images.xcassets folder in Sample Project.

```objective-c
#import "YALSunnyRefreshControl.h"

@property (nonatomic,strong) YALSunnyRefreshControl *sunnyRefreshControl;

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupRefreshControl];
}

-(void)setupRefreshControl{

    self.sunnyRefreshControl = [YALSunnyRefreshControl attachToScrollView:self.tableView
                                                                  target:self
                                                           refreshAction:@selector(sunnyControlDidStartAnimation)];

}

-(void)sunnyControlDidStartAnimation{

    // start loading something
}

-(IBAction)endAnimationHandle{

    [self.sunnyRefreshControl endRefreshing];
}

```

#Customization

To customize drawables you can change:
   * sun.png - Sun image
   * sky.png - background image
   * buildings.png - foreground image

#Compatibility

  * IOS 7,8

# Changelog

### Version: 1.0

  * Initial Build

## License

    Copyright 2015, Yalantis

    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.


text:
package com.faforever.client.main.event;

public class OpenTeamMatchmakingEvent extends NavigateEvent {
  public OpenTeamMatchmakingEvent() {
    super(NavigationItem.PLAY);
  }
}


text:
module Dhl
  module Intraship
    class PersonAddress < Address
      attr_accessor :salutation, :firstname, :lastname

      protected

      def company_xml(xml)
        xml.cis(:Person) do |xml|
          xml.cis(:salutation, salutation)
          xml.cis(:firstname, firstname)
          xml.cis(:lastname, lastname)
        end
      end
    end
  end
end


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TypeMock.ArrangeActAssert;

using Nucleo.Configuration;
using Nucleo.Logs.Configuration;
using Nucleo.TestingTools;

namespace Nucleo.Logs
{
	[TestClass]
	public class LoggerTest
	{
		#region " Tests "

		[TestMethod]
		public void AttachingLoggersToComponentAddsLoggersToCollection()
		{
			var logCollectionFake = Isolate.Fake.Instance<LogManagerCollection>();
			Isolate.Swap.NextInstance<LogManagerCollection>().With(logCollectionFake);
			Isolate.WhenCalled(() => logCollectionFake.Add(null)).IgnoreCall();

			var loggerFake = Isolate.Fake.Instance<Logger>();
			Isolate.NonPublic.Property.WhenGetCalled(loggerFake, "Logs").CallOriginal();
			Isolate.WhenCalled(() => loggerFake.RegisterLogManager(null)).CallOriginal();

			var fakeManager = Isolate.Fake.Instance<FakeLogManager>();

			loggerFake.RegisterLogManager(fakeManager);

			Isolate.Verify.WasCalledWithAnyArguments(() => logCollectionFake.Add(fakeManager));

			Isolate.CleanUp();
		}

		[TestMethod]
		public void CreatingLoggerWithNoConfigThrowsException()
		{
			//Arrange
			Isolate.Fake.StaticMethods(typeof(LoggerSettingsSection));
			Isolate.WhenCalled(() => LoggerSettingsSection.Instance).WillReturn(null);

			//Act

			//Assert
			ExceptionTester.CheckException(true, (s) => { Logger.Create(); });

			Isolate.CleanUp();
		}

		[TestMethod]
		public void CreatingLoggerWithCurrentVerbosityInConfigButWithMismatchedNameThrowsException()
		{
			var verbosityTypeElements = new LogVerbosityTypeElementCollection();
			verbosityTypeElements.Add(new LogVerbosityTypeElement { Name = "Third", Level = 3 });
			verbosityTypeElements.Add(new LogVerbosityTypeElement { Name = "Fourth", Level = 4 });

			LoggerSettingsSection sectionFake = Isolate.Fake.Instance<LoggerSettingsSection>();
			Isolate.WhenCalled(() => sectionFake.VerbosityTypes).WillReturn(verbosityTypeElements);
			Isolate.WhenCalled(() => sectionFake.CurrentVerbosityName).WillReturn("Fifth");

			Isolate.Fake.StaticMethods(typeof(LoggerSettingsSection));
			Isolate.WhenCalled(() => LoggerSettingsSection.Instance).WillReturn(sectionFake);

			//Assert
			try
			{
				Logger.Create();
				Assert.Fail("Creating logger with invalid params didn't throw exception");
			}
			catch (ArgumentException ex)
			{
				StringAssert.Contains(ex.Message, "The current verbosity setting does not match an item in the list.");
				Assert.AreEqual("CurrentVerbosityName", ex.ParamName, "Param name doesn't match");
			}

			Isolate.CleanUp();
		}

		[TestMethod]
		public void CreatingLoggerWithCurrentVerbosityInConfigEstablishesSetting()
		{
			var verbosityTypeElements = new LogVerbosityTypeElementCollection();
			verbosityTypeElements.Add(new LogVerbosityTypeElement { Name = "Third", Level = 3 });
			verbosityTypeElements.Add(new LogVerbosityTypeElement { Name = "Fourth", Level = 4 });

			LoggerSettingsSection sectionFake = Isolate.Fake.Instance<LoggerSettingsSection>();
			Isolate.WhenCalled(() => sectionFake.VerbosityTypes).WillReturn(verbosityTypeElements);
			Isolate.WhenCalled(() => sectionFake.CurrentVerbosityName).WillReturn("Fourth");

			Isolate.Fake.StaticMethods(typeof(LoggerSettingsSection));
			Isolate.WhenCalled(() => LoggerSettingsSection.Instance).WillReturn(sectionFake);

			//Act
			Logger logger = Logger.Create();

			//Assert
			Assert.AreEqual("Fourth", logger.CurrentVerbosity.Name);
			Assert.AreEqual(4, logger.CurrentVerbosity.Level);

			Isolate.CleanUp();
		}

		[TestMethod]
		public void CreatingLoggerWithLogManagersInstantiatesCorrectNumberOfLogs()
		{
			var logManagerElements = new NameTypeElementCollection();
			logManagerElements.Add(new NameTypeElement { Name = "First", Type = "FirstType" });
			logManagerElements.Add(new NameTypeElement { Name = "Second", Type = "SecondType" });
			logManagerElements.Add(new NameTypeElement { Name = "Third", Type = "ThirdType" });

			LoggerSettingsSection sectionFake = Isolate.Fake.Instance<LoggerSettingsSection>();
			Isolate.WhenCalled(() => sectionFake.LogManagers).WillReturn(logManagerElements);

			Isolate.Fake.StaticMethods(typeof(LoggerSettingsSection));
			Isolate.WhenCalled(() => LoggerSettingsSection.Instance).WillReturn(sectionFake);

			//Act
			Isolate.NonPublic.WhenCalled(typeof(Logger), "CreateLogManagerInstance").WillReturn(new FakeLogManager());
			Logger logger = Logger.Create();

			var logManagers = logger.GetLogManagers();

			//Assert
			Assert.AreEqual(3, logManagers.Count);

			Isolate.CleanUp();
		}

		[TestMethod]
		public void CreatingLoggerWithMessageTypesReturnsLoggerWithMessageTypes()
		{
			var messageTypeElements = new LogMessageTypeElementCollection();
			messageTypeElements.Add(new LogMessageTypeElement { Name = "First", Value = 1 });
			messageTypeElements.Add(new LogMessageTypeElement { Name = "Second", Value = 2 });

			Isolate.Fake.StaticMethods(typeof(LoggerSettingsSection));
			LoggerSettingsSection sectionFake = Isolate.Fake.Instance<LoggerSettingsSection>();
			Isolate.WhenCalled(() => sectionFake.MessageTypes).WillReturn(messageTypeElements);
			Isolate.WhenCalled(() => LoggerSettingsSection.Instance).WillReturn(sectionFake);

			Logger logger = Logger.Create();

			var messageTypes = logger.GetMessageTypes();
			Assert.AreEqual(5, messageTypes.Count);
			Assert.AreEqual("First", messageTypes[3].Name);
			Assert.AreEqual("Second", messageTypes[4].Name);

			Isolate.CleanUp();
		}

		[TestMethod]
		public void CreatingLoggerReturnsDefaultMessageTypes()
		{
			Isolate.Fake.StaticMethods(typeof(LoggerSettingsSection));
			Isolate.WhenCalled(() => LoggerSettingsSection.Instance).WillReturn(null);

			Logger logger = Logger.Create(new LoggerOptions());

			var messageTypes = logger.GetMessageTypes();
			Assert.AreEqual(3, messageTypes.Count);

			Assert.AreEqual("Information", messageTypes[0].Name);
			Assert.AreEqual(0, messageTypes[0].Value);

			Assert.AreEqual("Warning", messageTypes[1].Name);
			Assert.AreEqual(127, messageTypes[1].Value);

			Assert.AreEqual("Error", messageTypes[2].Name);
			Assert.AreEqual(255, messageTypes[2].Value);

			Isolate.CleanUp();
		}

		[TestMethod]
		public void CreatingLoggerReturnsDefaultVerbosity()
		{
			Isolate.Fake.StaticMethods(typeof(LoggerSettingsSection));
			Isolate.WhenCalled(() => LoggerSettingsSection.Instance).WillReturn(null);

			Logger logger = Logger.Create(new LoggerOptions());

			var verbosityTypes = logger.GetVerbosityTypes();
			Assert.AreEqual(3, verbosityTypes.Count);

			Assert.AreEqual("Minimal", verbosityTypes[0].Name);
			Assert.AreEqual(0, verbosityTypes[0].Level);

			Assert.AreEqual("Normal", verbosityTypes[1].Name);
			Assert.AreEqual(127, verbosityTypes[1].Level);

			Assert.AreEqual("Verbose", verbosityTypes[2].Name);
			Assert.AreEqual(255, verbosityTypes[2].Level);

			Isolate.CleanUp();
		}

		[TestMethod]
		public void CreatingLoggerWithVerbosityTypesReturnsLoggerWithVerbosityTypes()
		{
			var verbosityTypeElements = new LogVerbosityTypeElementCollection();
			verbosityTypeElements.Add(new LogVerbosityTypeElement { Name = "Third", Level = 3 });
			verbosityTypeElements.Add(new LogVerbosityTypeElement { Name = "Fourth", Level = 4 });

			Isolate.Fake.StaticMethods(typeof(LoggerSettingsSection));
			LoggerSettingsSection sectionFake = Isolate.Fake.Instance<LoggerSettingsSection>();
			Isolate.WhenCalled(() => sectionFake.VerbosityTypes).WillReturn(verbosityTypeElements);
			Isolate.WhenCalled(() => LoggerSettingsSection.Instance).WillReturn(sectionFake);

			Logger logger = Logger.Create();

			var verbosityTypes = logger.GetVerbosityTypes();
			Assert.AreEqual(5, verbosityTypes.Count);
			Assert.AreEqual("Third", verbosityTypes[3].Name);
			Assert.AreEqual("Fourth", verbosityTypes[4].Name);

			Isolate.CleanUp();
		}

		[TestMethod]
		public void LoggingDetailsOfObjectLogsCorrectInformation()
		{
			//Arrange
			var fakeManager = new FakeLogManager();
			var objectToLog = new LogVerbosityType("Test", 100);

			var loggerFake = Isolate.Fake.Instance<Logger>(Members.CallOriginal);
			Isolate.NonPublic.Property.WhenGetCalled(loggerFake, "Logs").WillReturn(
				new LogManagerCollection { fakeManager });

			var messageTypeFake = Isolate.Fake.Instance<LogMessageType>();
			var verbosityFake = Isolate.Fake.Instance<LogVerbosityType>();

			//Act
			loggerFake.LogObjectDetails(objectToLog, "Test", messageTypeFake, verbosityFake);
			var objectDetails = string.Format("{0}: {1}={2}, {3}={4}", objectToLog.GetType().FullName,
				"Level", objectToLog.Level, "Name", objectToLog.Name);

			//Assert
			var entries = fakeManager.GetEntries();
			Assert.AreEqual(1, entries.Count);
			Assert.AreEqual(objectDetails, entries[0].Message);

			Isolate.CleanUp();
		}

		[TestMethod]
		public void LoggingExceptionsToLoggerCallsLogMethodsInAllLogs()
		{
			//Arrange
			var fakeManager = new FakeLogManager();

			var loggerFake = Isolate.Fake.Instance<Logger>(Members.CallOriginal);
			Isolate.NonPublic.Property.WhenGetCalled(loggerFake, "Logs").WillReturn(
				new LogManagerCollection { fakeManager });
			Isolate.WhenCalled(() => loggerFake.LogError(null, null, null, null)).CallOriginal();

			var messageTypeFake = Isolate.Fake.Instance<LogMessageType>();
			var verbosityFake = Isolate.Fake.Instance<LogVerbosityType>();

			//Act
			loggerFake.LogError(new Exception("Test"), "App", messageTypeFake, verbosityFake);

			//Assert
			var entries = fakeManager.GetEntries();
			Assert.AreEqual(1, entries.Count);

			Isolate.CleanUp();
		}

		[TestMethod]
		public void LoggingMessageToLoggerCallsLogMethodsInAllLogs()
		{
			//Arrange
			var fakeManager = new FakeLogManager();

			var loggerFake = Isolate.Fake.Instance<Logger>(Members.CallOriginal);
			Isolate.NonPublic.Property.WhenGetCalled(loggerFake, "Logs").WillReturn(
				new LogManagerCollection { fakeManager });
			Isolate.WhenCalled(() => loggerFake.LogMessage(null, null, null, null)).CallOriginal();

			var messageTypeFake = Isolate.Fake.Instance<LogMessageType>();
			var verbosityFake = Isolate.Fake.Instance<LogVerbosityType>();

			//Act
			loggerFake.LogMessage("Test", "App", messageTypeFake, verbosityFake);

			//Assert
			var entries = fakeManager.GetEntries();
			Assert.AreEqual(1, entries.Count);

			Isolate.CleanUp();
		}

		[TestMethod]
		public void LoggingMessageWithCurrentVerbosityEqualsMessageVerbosityAt0DoesLogMessage()
		{
			//Arrange
			var fakeManager = new FakeLogManager();

			var loggerFake = Isolate.Fake.Instance<Logger>(Members.CallOriginal);
			Isolate.NonPublic.Property.WhenGetCalled(loggerFake, "Logs").WillReturn(
				new LogManagerCollection { fakeManager });
			Isolate.WhenCalled(() => loggerFake.LogMessage(null, null, null, null)).CallOriginal();
			Isolate.WhenCalled(() => loggerFake.CurrentVerbosity).WillReturn(new LogVerbosityType("Verbose", 0));

			//Act
			var messageType = new LogMessageType("Information", 1);

			loggerFake.LogMessage("Test Message", "App", messageType,
				new LogVerbosityType("Verbose", 0));
			loggerFake.LogMessage("Test Message2", "App2", messageType,
				new LogVerbosityType("Verbose", 0));

			//Assert
			Assert.AreEqual(2, fakeManager.GetEntries().Count);

			Isolate.CleanUp();
		}

		[TestMethod]
		public void LoggingMessageWithCurrentVerbosityEqualsMessageVerbosityAt127DoesLogMessage()
		{
			//Arrange
			var fakeManager = new FakeLogManager();

			var loggerFake = Isolate.Fake.Instance<Logger>(Members.CallOriginal);
			Isolate.NonPublic.Property.WhenGetCalled(loggerFake, "Logs").WillReturn(
				new LogManagerCollection { fakeManager });
			Isolate.WhenCalled(() => loggerFake.LogMessage(null, null, null, null)).CallOriginal();
			Isolate.WhenCalled(() => loggerFake.CurrentVerbosity).WillReturn(new LogVerbosityType("Verbose", 127));

			//Act
			var messageType = new LogMessageType("Information", 1);

			loggerFake.LogMessage("Test Message", "App", messageType,
				new LogVerbosityType("Verbose", 127));
			loggerFake.LogMessage("Test Message2", "App2", messageType,
				new LogVerbosityType("Verbose", 127));

			//Assert
			Assert.AreEqual(2, fakeManager.GetEntries().Count);

			Isolate.CleanUp();
		}

		[TestMethod]
		public void LoggingMessageWithCurrentVerbosityEqualsMessageVerbosityAt255DoesLogMessage()
		{
			var fakeManager = new FakeLogManager();

			var loggerFake = Isolate.Fake.Instance<Logger>(Members.CallOriginal);
			Isolate.NonPublic.Property.WhenGetCalled(loggerFake, "Logs").WillReturn(
				new LogManagerCollection { fakeManager });
			Isolate.WhenCalled(() => loggerFake.LogMessage(null, null, null, null)).CallOriginal();
			Isolate.WhenCalled(() => loggerFake.CurrentVerbosity).WillReturn(new LogVerbosityType("Verbose", 255));

			var messageType = new LogMessageType("Information", 1);

			loggerFake.LogMessage("Test Message", "App", messageType,
				new LogVerbosityType("Verbose", 255));
			loggerFake.LogMessage("Test Message2", "App2", messageType,
				new LogVerbosityType("Verbose", 255));

			//Assert
			Assert.AreEqual(2, fakeManager.GetEntries().Count);

			Isolate.CleanUp();
		}

		[TestMethod]
		public void LoggingMessageWithCurrentVerbosityGreaterThanMessageVerbosityDoesLogMessage()
		{
			var fakeManager = new FakeLogManager();

			var loggerFake = Isolate.Fake.Instance<Logger>(Members.CallOriginal);
			Isolate.NonPublic.Property.WhenGetCalled(loggerFake, "Logs").WillReturn(
				new LogManagerCollection { fakeManager });
			Isolate.WhenCalled(() => loggerFake.LogMessage(null, null, null, null)).CallOriginal();
			Isolate.WhenCalled(() => loggerFake.CurrentVerbosity).WillReturn(new LogVerbosityType("Verbose", 255));

			var messageType = new LogMessageType("Information", 1);

			loggerFake.LogMessage("Test Message", "App", messageType,
				new LogVerbosityType("Normal", 127));

			loggerFake.LogMessage("Test Message", "App", messageType,
				new LogVerbosityType("Normal", 200));

			loggerFake.LogMessage("Test Message", "App", messageType,
				new LogVerbosityType("Normal", 254));

			Assert.AreEqual(3, fakeManager.GetEntries().Count);

			Isolate.CleanUp();
		}

		[TestMethod]
		public void LoggingMessageWithCurrentVerbosityLessThanMessageVerbosityDoesntLogMessage()
		{
			var fakeManager = new FakeLogManager();

			var loggerFake = Isolate.Fake.Instance<Logger>(Members.CallOriginal);
			Isolate.NonPublic.Property.WhenGetCalled(loggerFake, "Logs").WillReturn(
				new LogManagerCollection { fakeManager });
			Isolate.WhenCalled(() => loggerFake.LogMessage(null, null, null, null)).CallOriginal();
			Isolate.WhenCalled(() => loggerFake.CurrentVerbosity).WillReturn(new LogVerbosityType("Normal", 127));

			var messageType = new LogMessageType("Information", 1);

			loggerFake.LogMessage("Test Message", "App", messageType,
				new LogVerbosityType("Verbose", 255));

			loggerFake.LogMessage("Test Message", "App", messageType,
				new LogVerbosityType("Verbose", 175));

			loggerFake.LogMessage("Test Message", "App", messageType,
				new LogVerbosityType("Verbose", 128));

			Assert.AreEqual(0, fakeManager.GetEntries().Count);

			Isolate.CleanUp();
		}

		#endregion
	}
}


text:
<?php

namespace Rexmac\Zyndax\Form;

use Rexmac\Zyndax\Controller\Request\HttpRequest,
    Rexmac\Zyndax\Form\Decorator\FormErrors,
    \Zend_Controller_Front as FrontController,
    \Zend_Form_Element as FormElement;

/**
 * Custom Zend_Form class
 *
 * @category   Zyndax
 * @package    Rexmac_Zyndax
 * @subpackage Form
 * @copyright  Copyright (c) 2011-2012 Rex McConnell (http://rexmac.com/)
 * @license    http://rexmac.com/license/bsd2c.txt Modified BSD License
 * @author     Rex McConnell <rex@rexmac.com>
 */
abstract class Form extends \Zend_Form {

  /**
   * Constructor
   *
   * @return void
   */
  public function __construct() {
    $request = FrontController::getInstance()->getRequest();
    if($request instanceof HttpRequest && $request->isMobileRequest()) {
      $this->setDecorators(array(
        'FormElements',
        'Form',
        new FormErrors(array(
          'placement'           => 'prepend',
          'markupListEnd'       => '
',
          'markupListItemEnd'   => '',
          'markupListItemStart' => '',
          'markupListStart'     => '
',
        )),
      ));

      $this->setElementDecorators(array(
        'ViewHelper',
        'Label'
      ));
    } else {
      $this->setDecorators(array(
        'FormElements',
        array('HtmlTag', array('tag' => 'ol')),
        'Form',
        new FormErrors(array(
          'placement'           => 'prepend',
          'markupListEnd'       => '
',
          'markupListItemEnd'   => '',
          'markupListItemStart' => '',
          'markupListStart'     => '
',
        )),
      ));

      $this->setElementDecorators(array(
        'ViewHelper',
        #new \Rexmac\Zyndax\Form\Decorator\DescriptionTooltip(),
        array('Description', array('tag' => 'p', 'class' => 'description', 'escape' => false)),
        array('Label', array(
          'optionalSuffix' => '  ',
          'requiredSuffix' => ' *',
          'escape' => false
        )),
        array('HtmlTag', array('tag' => 'li'))
      ));
    }

    parent::__construct();
  }

  /**
   * Add a new element
   *
   * $element may be either a string element type, or an object of type
   * Zend_Form_Element. If a string element type is provided, $name must be
   * provided, and $options may be optionally provided for configuring the
   * element.
   *
   * If a Zend_Form_Element is provided, $name may be optionally provided,
   * and any provided $options will be ignored.
   *
   * @param  string|Zend_Form_Element $element
   * @param  string $name
   * @param  array|Zend_Config $options
   * @throws Zend_Form_Exception on invalid element
   * @return Zend_Form_Element
   */
  public function addElement($element, $name = null, $options = null) {
    parent::addElement($element, $name, $options);
    if($element instanceof FormElement) {
      return $element;
    }
    return $this->getElement($name);
  }
}


text:
namespace Simpl.Serialization
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using Simpl.Serialization.Attributes;

    /// <summary>
    /// Adds override to a given Type to get all requisite types for a serialization type scope.
    /// Adding an extension method to Type feels daring and dangerous, but it can improve the readability of some of our code.
    /// Will help replace some declarations that look like this:
    /// typeof(ClassA), typeof(ClassA_DependentType), typeof(ClassA_AnotherDependentType)
    /// with just
    /// typeof(ClassA)
    /// </summary>
    public static class TypeExtensions
    {
        /// <summary>
        /// Returns all types that this type "Depends" upon, filtered by a member info predicate (to filter for attributes, etc)
        /// </summary>
        public static IEnumerable<Type> GetAllDependentTypes(this Type currentType, Func<MemberInfo, bool> matchesPredicate)
        {
            return GetDependentTypesWithDuplicates(currentType, matchesPredicate).Distinct();
        }

        /// <summary>
        /// Determines if this currentType can be assigned to the TargetType
        /// </summary>
        /// <typeparam name="TargetType">Type to asign to</typeparam>
        /// <param name="currentType">Our current Type</param>
        /// <returns>True if so (If the targetType is assignable from the current type, the current type is assignable TO the target type)</returns>
        public static bool IsAssignableTo<TargetType>(this Type currentType)
        {
            return typeof(TargetType).GetTypeInfo().IsAssignableFrom(currentType.GetTypeInfo());
        }

        private static IEnumerable<Type> GetDependentTypesWithDuplicates(Type currentType, Func<MemberInfo, bool> matchesPredicate)
        {
            // Check over all Properties first.

            //BindingFlags bindingParameters = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.Instance;

            foreach (var propInfo in currentType.GetTypeInfo().DeclaredProperties)
            {
                if (matchesPredicate(propInfo))
                {
                    yield return propInfo.PropertyType;
                }
            }

            // check over all fields next

            foreach (var fieldInfo in currentType.GetTypeInfo().DeclaredFields)
            {
                if (matchesPredicate(fieldInfo))
                {
                    yield return fieldInfo.FieldType;
                }
            }

            yield return currentType;
        }

        /// <summary>
        /// Returns all types that this type "Depends" upon. These types are the types of fields and properties of the given type.
        /// </summary>
        /// <param name="currentType"></param>
        /// <returns></returns>
        public static IEnumerable<Type> GetAllDependentTypes(this Type currentType)
        {
            return currentType.GetAllDependentTypes(matchesPredicate: memberInfo => true); // Fetch all members with a predicate that always returns true
        }

        public static Type[] GetAllDependentSimplTypes(this Type currentType)
        {
            return currentType.GetAllDependentTypes(matchesPredicate: member => member.IsSimplMember()).ToArray();
        }

        private static Type[] simplAttributes = new[] { typeof(SimplScalar), typeof(SimplCollection), typeof(SimplComposite), typeof(SimplCompositeAsScalar) };

        private static bool MemberHasSimplAttributes<T>(T member) where T : MemberInfo
        {
            return member.GetCustomAttributes(true).Where(attrObj => simplAttributes.Contains(attrObj.GetType())).Any();
        }

        /// <summary>
        /// If a member is a Simpl type (scalar, collection, etc.)
        /// </summary>
        /// <param name="member"></param>
        /// <returns></returns>
        public static bool IsSimplMember(this MemberInfo member)
        {
            return MemberHasSimplAttributes(member);
        }
    }
}


text:
package org.keycloak.models.sessions.infinispan;

import org.infinispan.Cache;
import org.infinispan.distexec.mapreduce.MapReduceTask;
import org.jboss.logging.Logger;
import org.keycloak.models.*;
import org.keycloak.models.session.UserSessionPersisterProvider;
import org.keycloak.models.sessions.infinispan.entities.*;
import org.keycloak.models.sessions.infinispan.mapreduce.*;
import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.models.utils.RealmInfoUtil;
import org.keycloak.common.util.Time;

import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author Stian Thorgersen
 */
public class InfinispanUserSessionProvider implements UserSessionProvider {

    private static final Logger log = Logger.getLogger(InfinispanUserSessionProvider.class);

    private final KeycloakSession session;
    private final Cache<String, SessionEntity> sessionCache;
    private final Cache<String, SessionEntity> offlineSessionCache;
    private final Cache<LoginFailureKey, LoginFailureEntity> loginFailureCache;
    private final InfinispanKeycloakTransaction tx;

    public InfinispanUserSessionProvider(KeycloakSession session, Cache<String, SessionEntity> sessionCache, Cache<String, SessionEntity> offlineSessionCache,
                                         Cache<LoginFailureKey, LoginFailureEntity> loginFailureCache) {
        this.session = session;
        this.sessionCache = sessionCache;
        this.offlineSessionCache = offlineSessionCache;
        this.loginFailureCache = loginFailureCache;
        this.tx = new InfinispanKeycloakTransaction();

        session.getTransaction().enlistAfterCompletion(tx);
    }

    protected Cache<String, SessionEntity> getCache(boolean offline) {
        return offline ? offlineSessionCache : sessionCache;
    }

    @Override
    public ClientSessionModel createClientSession(RealmModel realm, ClientModel client) {
        String id = KeycloakModelUtils.generateId();

        ClientSessionEntity entity = new ClientSessionEntity();
        entity.setId(id);
        entity.setRealm(realm.getId());
        entity.setTimestamp(Time.currentTime());
        entity.setClient(client.getId());

        tx.put(sessionCache, id, entity);

        return wrap(realm, entity, false);
    }

    @Override
    public UserSessionModel createUserSession(RealmModel realm, UserModel user, String loginUsername, String ipAddress, String authMethod, boolean rememberMe, String brokerSessionId, String brokerUserId) {
        String id = KeycloakModelUtils.generateId();

        UserSessionEntity entity = new UserSessionEntity();
        entity.setId(id);
        entity.setRealm(realm.getId());
        entity.setUser(user.getId());
        entity.setLoginUsername(loginUsername);
        entity.setIpAddress(ipAddress);
        entity.setAuthMethod(authMethod);
        entity.setRememberMe(rememberMe);
        entity.setBrokerSessionId(brokerSessionId);
        entity.setBrokerUserId(brokerUserId);

        int currentTime = Time.currentTime();

        entity.setStarted(currentTime);
        entity.setLastSessionRefresh(currentTime);

        tx.put(sessionCache, id, entity);

        return wrap(realm, entity, false);
    }

    @Override
    public ClientSessionModel getClientSession(RealmModel realm, String id) {
        return getClientSession(realm, id, false);
    }

    protected ClientSessionModel getClientSession(RealmModel realm, String id, boolean offline) {
        Cache<String, SessionEntity> cache = getCache(offline);
        ClientSessionEntity entity = (ClientSessionEntity) cache.get(id);

        // Chance created in this transaction
        if (entity == null) {
            entity = (ClientSessionEntity) tx.get(cache, id);
        }

        return wrap(realm, entity, offline);
    }

    @Override
    public ClientSessionModel getClientSession(String id) {
        ClientSessionEntity entity = (ClientSessionEntity) sessionCache.get(id);

        // Chance created in this transaction
        if (entity == null) {
            entity = (ClientSessionEntity) tx.get(sessionCache, id);
        }

        if (entity != null) {
            RealmModel realm = session.realms().getRealm(entity.getRealm());
            return wrap(realm, entity, false);
        }
        return null;
    }

    @Override
    public UserSessionModel getUserSession(RealmModel realm, String id) {
        return getUserSession(realm, id, false);
    }

    protected UserSessionAdapter getUserSession(RealmModel realm, String id, boolean offline) {
        Cache<String, SessionEntity> cache = getCache(offline);
        UserSessionEntity entity = (UserSessionEntity) cache.get(id);

        // Chance created in this transaction
        if (entity == null) {
            entity = (UserSessionEntity) tx.get(cache, id);
        }

        return wrap(realm, entity, offline);
    }

    @Override
    public List<UserSessionModel> getUserSessions(RealmModel realm, UserModel user) {
        Map<String, UserSessionEntity> sessions = new MapReduceTask(sessionCache)
                .mappedWith(UserSessionMapper.create(realm.getId()).user(user.getId()))
                .reducedWith(new FirstResultReducer())
                .execute();

        return wrapUserSessions(realm, sessions.values(), false);
    }

    @Override
    public List<UserSessionModel> getUserSessionByBrokerUserId(RealmModel realm, String brokerUserId) {
        Map<String, UserSessionEntity> sessions = new MapReduceTask(sessionCache)
                .mappedWith(UserSessionMapper.create(realm.getId()).brokerUserId(brokerUserId))
                .reducedWith(new FirstResultReducer())
                .execute();

        return wrapUserSessions(realm, sessions.values(), false);
    }

    @Override
    public UserSessionModel getUserSessionByBrokerSessionId(RealmModel realm, String brokerSessionId) {
        Map<String, UserSessionEntity> sessions = new MapReduceTask(sessionCache)
                .mappedWith(UserSessionMapper.create(realm.getId()).brokerSessionId(brokerSessionId))
                .reducedWith(new FirstResultReducer())
                .execute();

        List<UserSessionModel> userSessionModels = wrapUserSessions(realm, sessions.values(), false);
        if (userSessionModels.isEmpty()) return null;
        return userSessionModels.get(0);
    }

    @Override
    public List<UserSessionModel> getUserSessions(RealmModel realm, ClientModel client) {
        return getUserSessions(realm, client, -1, -1);
    }

    @Override
    public List<UserSessionModel> getUserSessions(RealmModel realm, ClientModel client, int firstResult, int maxResults) {
        return getUserSessions(realm, client, firstResult, maxResults, false);
    }

    protected List<UserSessionModel> getUserSessions(RealmModel realm, ClientModel client, int firstResult, int maxResults, boolean offline) {
        Cache<String, SessionEntity> cache = getCache(offline);

        Map<String, Integer> map = new MapReduceTask(cache)
                .mappedWith(ClientSessionMapper.create(realm.getId()).client(client.getId()).emitUserSessionAndTimestamp())
                .reducedWith(new LargestResultReducer())
                .execute();

        List<Map.Entry<String, Integer>> sessionTimestamps = new LinkedList<Map.Entry<String, Integer>>(map.entrySet());

        Collections.sort(sessionTimestamps, new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> e1, Map.Entry<String, Integer> e2) {
                return e1.getValue().compareTo(e2.getValue());
            }
        });

        if (firstResult != -1 || maxResults == -1) {
            if (firstResult == -1) {
                firstResult = 0;
            }

            if (maxResults == -1) {
                maxResults = Integer.MAX_VALUE;
            }

            if (firstResult > sessionTimestamps.size()) {
                return Collections.emptyList();
            }

            int toIndex = (firstResult + maxResults) < sessionTimestamps.size() ? firstResult + maxResults : sessionTimestamps.size();
            sessionTimestamps = sessionTimestamps.subList(firstResult, toIndex);
        }

        List<UserSessionModel> userSessions = new LinkedList<UserSessionModel>();
        for (Map.Entry<String, Integer> e : sessionTimestamps) {
            UserSessionEntity userSessionEntity = (UserSessionEntity) cache.get(e.getKey());
            if (userSessionEntity != null) {
                userSessions.add(wrap(realm, userSessionEntity, offline));
            }
        }

        return userSessions;
    }

    @Override
    public List<UserSessionModel> getUserSessionsByNote(RealmModel realm, String noteName, String noteValue) {
        HashMap<String, String> notes = new HashMap<>();
        notes.put(noteName, noteValue);
        return getUserSessionsByNotes(realm, notes);
    }

    public List<UserSessionModel> getUserSessionsByNotes(RealmModel realm, Map<String, String> notes) {
        Map<String, UserSessionEntity> sessions = new MapReduceTask(sessionCache)
                .mappedWith(UserSessionNoteMapper.create(realm.getId()).notes(notes))
                .reducedWith(new FirstResultReducer())
                .execute();

        return wrapUserSessions(realm, sessions.values(), false);

    }

    @Override
    public int getActiveUserSessions(RealmModel realm, ClientModel client) {
        return getUserSessionsCount(realm, client, false);
    }

    protected int getUserSessionsCount(RealmModel realm, ClientModel client, boolean offline) {
        Cache<String, SessionEntity> cache = getCache(offline);

        Map map = new MapReduceTask(cache)
                .mappedWith(ClientSessionMapper.create(realm.getId()).client(client.getId()).emitUserSessionAndTimestamp())
                .reducedWith(new LargestResultReducer()).execute();

        return map.size();
    }

    @Override
    public void removeUserSession(RealmModel realm, UserSessionModel session) {
        removeUserSession(realm, session.getId());
    }

    @Override
    public void removeUserSessions(RealmModel realm, UserModel user) {
        removeUserSessions(realm, user, false);
    }

    protected void removeUserSessions(RealmModel realm, UserModel user, boolean offline) {
        Cache<String, SessionEntity> cache = getCache(offline);

        Map<String, String> sessions = new MapReduceTask(cache)
                .mappedWith(UserSessionMapper.create(realm.getId()).user(user.getId()).emitKey())
                .reducedWith(new FirstResultReducer())
                .execute();

        for (String id : sessions.keySet()) {
            removeUserSession(realm, id, offline);
        }
    }

    @Override
    public void removeExpiredUserSessions(RealmModel realm) {
        UserSessionPersisterProvider persister = session.getProvider(UserSessionPersisterProvider.class);

        int expired = Time.currentTime() - realm.getSsoSessionMaxLifespan();
        int expiredRefresh = Time.currentTime() - realm.getSsoSessionIdleTimeout();
        int expiredOffline = Time.currentTime() - realm.getOfflineSessionIdleTimeout();
        int expiredDettachedClientSession = Time.currentTime() - RealmInfoUtil.getDettachedClientSessionLifespan(realm);

        Map<String, String> map = new MapReduceTask(sessionCache)
                .mappedWith(UserSessionMapper.create(realm.getId()).expired(expired, expiredRefresh).emitKey())
                .reducedWith(new FirstResultReducer())
                .execute();

        for (String id : map.keySet()) {
            removeUserSession(realm, id);
        }

        map = new MapReduceTask(sessionCache)
                .mappedWith(ClientSessionMapper.create(realm.getId()).expiredRefresh(expiredDettachedClientSession).requireNullUserSession(true).emitKey())
                .reducedWith(new FirstResultReducer())
                .execute();

        for (String id : map.keySet()) {
            tx.remove(sessionCache, id);
        }

        // Remove expired offline user sessions
        Map<String, SessionEntity> map2 = new MapReduceTask(offlineSessionCache)
                .mappedWith(UserSessionMapper.create(realm.getId()).expired(null, expiredOffline))
                .reducedWith(new FirstResultReducer())
                .execute();

        for (Map.Entry<String, SessionEntity> entry : map2.entrySet()) {
            String userSessionId = entry.getKey();
            tx.remove(offlineSessionCache, userSessionId);
            // Propagate to persister
            persister.removeUserSession(userSessionId, true);

            UserSessionEntity entity = (UserSessionEntity) entry.getValue();
            for (String clientSessionId : entity.getClientSessions()) {
                tx.remove(offlineSessionCache, clientSessionId);
            }
        }

        // Remove expired offline client sessions
        map = new MapReduceTask(offlineSessionCache)
                .mappedWith(ClientSessionMapper.create(realm.getId()).expiredRefresh(expiredOffline).emitKey())
                .reducedWith(new FirstResultReducer())
                .execute();

        for (String clientSessionId : map.keySet()) {
            tx.remove(offlineSessionCache, clientSessionId);
            persister.removeClientSession(clientSessionId, true);
        }

        // Remove expired client initial access
        map = new MapReduceTask(sessionCache)
                .mappedWith(ClientInitialAccessMapper.create(realm.getId()).expired(Time.currentTime()).emitKey())
                .reducedWith(new FirstResultReducer())
                .execute();

        for (String id : map.keySet()) {
            tx.remove(sessionCache, id);
        }
    }

    @Override
    public void removeUserSessions(RealmModel realm) {
        removeUserSessions(realm, false);
    }

    protected void removeUserSessions(RealmModel realm, boolean offline) {
        Cache<String, SessionEntity> cache = getCache(offline);

        Map<String, String> ids = new MapReduceTask(cache)
                .mappedWith(SessionMapper.create(realm.getId()).emitKey())
                .reducedWith(new FirstResultReducer())
                .execute();

        for (String id : ids.keySet()) {
            cache.remove(id);
        }
    }

    @Override
    public UsernameLoginFailureModel getUserLoginFailure(RealmModel realm, String username) {
        LoginFailureKey key = new LoginFailureKey(realm.getId(), username);
        return wrap(key, loginFailureCache.get(key));
    }

    @Override
    public UsernameLoginFailureModel addUserLoginFailure(RealmModel realm, String username) {
        LoginFailureKey key = new LoginFailureKey(realm.getId(), username);
        LoginFailureEntity entity = new LoginFailureEntity();
        entity.setRealm(realm.getId());
        entity.setUsername(username);
        tx.put(loginFailureCache, key, entity);
        return wrap(key, entity);
    }

    @Override
    public void removeUserLoginFailure(RealmModel realm, String username) {
        LoginFailureKey key = new LoginFailureKey(realm.getId(), username);
        tx.remove(loginFailureCache, key);
    }

    @Override
    public void removeAllUserLoginFailures(RealmModel realm) {
        Map<LoginFailureKey, Object> sessions = new MapReduceTask(loginFailureCache)
                .mappedWith(UserLoginFailureMapper.create(realm.getId()).emitKey())
                .reducedWith(new FirstResultReducer())
                .execute();

        for (LoginFailureKey id : sessions.keySet()) {
            tx.remove(loginFailureCache, id);
        }
    }

    @Override
    public void onRealmRemoved(RealmModel realm) {
        removeUserSessions(realm, true);
        removeUserSessions(realm, false);
        removeAllUserLoginFailures(realm);
    }

    @Override
    public void onClientRemoved(RealmModel realm, ClientModel client) {
        onClientRemoved(realm, client, true);
        onClientRemoved(realm, client, false);
    }

    private void onClientRemoved(RealmModel realm, ClientModel client, boolean offline) {
        Cache<String, SessionEntity> cache = getCache(offline);

        Map<String, ClientSessionEntity> map = new MapReduceTask(cache)
                .mappedWith(ClientSessionMapper.create(realm.getId()).client(client.getId()))
                .reducedWith(new FirstResultReducer())
                .execute();

        for (Map.Entry<String, ClientSessionEntity> entry : map.entrySet()) {

            // detach from userSession
            ClientSessionAdapter adapter = wrap(realm, entry.getValue(), offline);
            adapter.setUserSession(null);

            tx.remove(cache, entry.getKey());
        }
    }

    @Override
    public void onUserRemoved(RealmModel realm, UserModel user) {
        removeUserSessions(realm, user, true);
        removeUserSessions(realm, user, false);

        loginFailureCache.remove(new LoginFailureKey(realm.getId(), user.getUsername()));
        loginFailureCache.remove(new LoginFailureKey(realm.getId(), user.getEmail()));
    }

    @Override
    public void close() {
    }

    void attachSession(UserSessionAdapter userSession, ClientSessionModel clientSession) {
        UserSessionEntity entity = userSession.getEntity();
        String clientSessionId = clientSession.getId();
        if (entity.getClientSessions() == null) {
            entity.setClientSessions(new HashSet<String>());
        }
        if (!entity.getClientSessions().contains(clientSessionId)) {
            entity.getClientSessions().add(clientSessionId);
            userSession.update();
        }
    }

    @Override
    public void removeClientSession(RealmModel realm, ClientSessionModel clientSession) {
        removeClientSession(realm, clientSession, false);
    }

    protected void removeClientSession(RealmModel realm, ClientSessionModel clientSession, boolean offline) {
        Cache<String, SessionEntity> cache = getCache(offline);

        UserSessionModel userSession = clientSession.getUserSession();
        if (userSession != null)  {
            UserSessionEntity entity = ((UserSessionAdapter) userSession).getEntity();
            if (entity.getClientSessions() != null) {
                entity.getClientSessions().remove(clientSession.getId());

            }
            tx.replace(cache, entity.getId(), entity);
        }
        tx.remove(cache, clientSession.getId());
    }

    void dettachSession(UserSessionAdapter userSession, ClientSessionModel clientSession) {
        UserSessionEntity entity = userSession.getEntity();
        String clientSessionId = clientSession.getId();
        if (entity.getClientSessions() != null && entity.getClientSessions().contains(clientSessionId)) {
            entity.getClientSessions().remove(clientSessionId);
            if (entity.getClientSessions().isEmpty()) {
                entity.setClientSessions(null);
            }
            userSession.update();
        }
    }

    protected void removeUserSession(RealmModel realm, String userSessionId) {
        removeUserSession(realm, userSessionId, false);
    }

    protected void removeUserSession(RealmModel realm, String userSessionId, boolean offline) {
        Cache<String, SessionEntity> cache = getCache(offline);

        tx.remove(cache, userSessionId);

        // TODO: Isn't more effective to retrieve from userSessionEntity directly?
        Map<String, String> map = new MapReduceTask(cache)
                .mappedWith(ClientSessionMapper.create(realm.getId()).userSession(userSessionId).emitKey())
                .reducedWith(new FirstResultReducer())
                .execute();

        for (String id : map.keySet()) {
            tx.remove(cache, id);
        }
    }

    InfinispanKeycloakTransaction getTx() {
        return tx;
    }

    UserSessionAdapter wrap(RealmModel realm, UserSessionEntity entity, boolean offline) {
        Cache<String, SessionEntity> cache = getCache(offline);
        return entity != null ? new UserSessionAdapter(session, this, cache, realm, entity, offline) : null;
    }

    List<UserSessionModel> wrapUserSessions(RealmModel realm, Collection<UserSessionEntity> entities, boolean offline) {
        List<UserSessionModel> models = new LinkedList<UserSessionModel>();
        for (UserSessionEntity e : entities) {
            models.add(wrap(realm, e, offline));
        }
        return models;
    }

    List<ClientInitialAccessModel> wrapClientInitialAccess(RealmModel realm, Collection<ClientInitialAccessEntity> entities) {
        List<ClientInitialAccessModel> models = new LinkedList<>();
        for (ClientInitialAccessEntity e : entities) {
            models.add(wrap(realm, e));
        }
        return models;
    }

    ClientSessionAdapter wrap(RealmModel realm, ClientSessionEntity entity, boolean offline) {
        Cache<String, SessionEntity> cache = getCache(offline);
        return entity != null ? new ClientSessionAdapter(session, this, cache, realm, entity, offline) : null;
    }

    ClientInitialAccessAdapter wrap(RealmModel realm, ClientInitialAccessEntity entity) {
        Cache<String, SessionEntity> cache = getCache(false);
        return entity != null ? new ClientInitialAccessAdapter(session, this, cache, realm, entity) : null;
    }

    UsernameLoginFailureModel wrap(LoginFailureKey key, LoginFailureEntity entity) {
        return entity != null ? new UsernameLoginFailureAdapter(this, loginFailureCache, key, entity) : null;
    }

    List<ClientSessionModel> wrapClientSessions(RealmModel realm, Collection<ClientSessionEntity> entities, boolean offline) {
        List<ClientSessionModel> models = new LinkedList<ClientSessionModel>();
        for (ClientSessionEntity e : entities) {
            models.add(wrap(realm, e, offline));
        }
        return models;
    }

    @Override
    public UserSessionModel createOfflineUserSession(UserSessionModel userSession) {
        UserSessionAdapter offlineUserSession = importUserSession(userSession, true);

        // started and lastSessionRefresh set to current time
        int currentTime = Time.currentTime();
        offlineUserSession.getEntity().setStarted(currentTime);
        offlineUserSession.setLastSessionRefresh(currentTime);

        return offlineUserSession;
    }

    @Override
    public UserSessionModel getOfflineUserSession(RealmModel realm, String userSessionId) {
        return getUserSession(realm, userSessionId, true);
    }

    @Override
    public void removeOfflineUserSession(RealmModel realm, String userSessionId) {
        removeUserSession(realm, userSessionId, true);
    }

    @Override
    public ClientSessionModel createOfflineClientSession(ClientSessionModel clientSession) {
        ClientSessionAdapter offlineClientSession = importClientSession(clientSession, true);

        // update timestamp to current time
        offlineClientSession.setTimestamp(Time.currentTime());

        return offlineClientSession;
    }

    @Override
    public ClientSessionModel getOfflineClientSession(RealmModel realm, String clientSessionId) {
        return getClientSession(realm, clientSessionId, true);
    }

    @Override
    public List<ClientSessionModel> getOfflineClientSessions(RealmModel realm, UserModel user) {
        Map<String, UserSessionEntity> sessions = new MapReduceTask(offlineSessionCache)
                .mappedWith(UserSessionMapper.create(realm.getId()).user(user.getId()))
                .reducedWith(new FirstResultReducer())
                .execute();

        List<ClientSessionEntity> clientSessions = new LinkedList<>();
        for (UserSessionEntity userSession : sessions.values()) {
            Set<String> currClientSessions = userSession.getClientSessions();
            for (String clientSessionId : currClientSessions) {
                ClientSessionEntity cls = (ClientSessionEntity) offlineSessionCache.get(clientSessionId);
                if (cls != null) {
                    clientSessions.add(cls);
                }
            }
        }

        return wrapClientSessions(realm, clientSessions, true);
    }

    @Override
    public void removeOfflineClientSession(RealmModel realm, String clientSessionId) {
        ClientSessionModel clientSession = getOfflineClientSession(realm, clientSessionId);
        removeClientSession(realm, clientSession, true);
    }

    @Override
    public int getOfflineSessionsCount(RealmModel realm, ClientModel client) {
        return getUserSessionsCount(realm, client, true);
    }

    @Override
    public List<UserSessionModel> getOfflineUserSessions(RealmModel realm, ClientModel client, int first, int max) {
        return getUserSessions(realm, client, first, max, true);
    }

    @Override
    public UserSessionAdapter importUserSession(UserSessionModel userSession, boolean offline) {
        UserSessionEntity entity = new UserSessionEntity();
        entity.setId(userSession.getId());
        entity.setRealm(userSession.getRealm().getId());

        entity.setAuthMethod(userSession.getAuthMethod());
        entity.setBrokerSessionId(userSession.getBrokerSessionId());
        entity.setBrokerUserId(userSession.getBrokerUserId());
        entity.setIpAddress(userSession.getIpAddress());
        entity.setLoginUsername(userSession.getLoginUsername());
        entity.setNotes(userSession.getNotes());
        entity.setRememberMe(userSession.isRememberMe());
        entity.setState(userSession.getState());
        entity.setUser(userSession.getUser().getId());

        entity.setStarted(userSession.getStarted());
        entity.setLastSessionRefresh(userSession.getLastSessionRefresh());

        Cache<String, SessionEntity> cache = getCache(offline);
        tx.put(cache, userSession.getId(), entity);
        return wrap(userSession.getRealm(), entity, offline);
    }

    @Override
    public ClientSessionAdapter importClientSession(ClientSessionModel clientSession, boolean offline) {
        ClientSessionEntity entity = new ClientSessionEntity();
        entity.setId(clientSession.getId());
        entity.setRealm(clientSession.getRealm().getId());

        entity.setAction(clientSession.getAction());
        entity.setAuthenticatorStatus(clientSession.getExecutionStatus());
        entity.setAuthMethod(clientSession.getAuthMethod());
        if (clientSession.getAuthenticatedUser() != null) {
            entity.setAuthUserId(clientSession.getAuthenticatedUser().getId());
        }
        entity.setClient(clientSession.getClient().getId());
        entity.setNotes(clientSession.getNotes());
        entity.setProtocolMappers(clientSession.getProtocolMappers());
        entity.setRedirectUri(clientSession.getRedirectUri());
        entity.setRoles(clientSession.getRoles());
        entity.setTimestamp(clientSession.getTimestamp());
        entity.setUserSessionNotes(clientSession.getUserSessionNotes());

        Cache<String, SessionEntity> cache = getCache(offline);
        tx.put(cache, clientSession.getId(), entity);
        return wrap(clientSession.getRealm(), entity, offline);
    }

    @Override
    public ClientInitialAccessModel createClientInitialAccessModel(RealmModel realm, int expiration, int count) {
        String id = KeycloakModelUtils.generateId();

        ClientInitialAccessEntity entity = new ClientInitialAccessEntity();
        entity.setId(id);
        entity.setRealm(realm.getId());
        entity.setTimestamp(Time.currentTime());
        entity.setExpiration(expiration);
        entity.setCount(count);
        entity.setRemainingCount(count);

        tx.put(sessionCache, id, entity);

        return wrap(realm, entity);
    }

    @Override
    public ClientInitialAccessModel getClientInitialAccessModel(RealmModel realm, String id) {
        Cache<String, SessionEntity> cache = getCache(false);
        ClientInitialAccessEntity entity = (ClientInitialAccessEntity) cache.get(id);

        // If created in this transaction
        if (entity == null) {
            entity = (ClientInitialAccessEntity) tx.get(cache, id);
        }

        return wrap(realm, entity);
    }

    @Override
    public void removeClientInitialAccessModel(RealmModel realm, String id) {
        tx.remove(getCache(false), id);
    }

    @Override
    public List<ClientInitialAccessModel> listClientInitialAccess(RealmModel realm) {
        Map<String, ClientInitialAccessEntity> entities = new MapReduceTask(sessionCache)
                .mappedWith(ClientInitialAccessMapper.create(realm.getId()))
                .reducedWith(new FirstResultReducer())
                .execute();
        return wrapClientInitialAccess(realm, entities.values());
    }

    class InfinispanKeycloakTransaction implements KeycloakTransaction {

        private boolean active;
        private boolean rollback;
        private Map<Object, CacheTask> tasks = new HashMap<Object, CacheTask>();

        @Override
        public void begin() {
            active = true;
        }

        @Override
        public void commit() {
            if (rollback) {
                throw new RuntimeException("Rollback only!");
            }

            for (CacheTask task : tasks.values()) {
                task.execute();
            }
        }

        @Override
        public void rollback() {
            tasks.clear();
        }

        @Override
        public void setRollbackOnly() {
            rollback = true;
        }

        @Override
        public boolean getRollbackOnly() {
            return rollback;
        }

        @Override
        public boolean isActive() {
            return active;
        }

        public void put(Cache cache, Object key, Object value) {
            log.tracev("Adding cache operation: {0} on {1}", CacheOperation.ADD, key);

            Object taskKey = getTaskKey(cache, key);
            if (tasks.containsKey(taskKey)) {
                throw new IllegalStateException("Can't add session: task in progress for session");
            } else {
                tasks.put(taskKey, new CacheTask(cache, CacheOperation.ADD, key, value));
            }
        }

        public void replace(Cache cache, Object key, Object value) {
            log.tracev("Adding cache operation: {0} on {1}", CacheOperation.REPLACE, key);

            Object taskKey = getTaskKey(cache, key);
            CacheTask current = tasks.get(taskKey);
            if (current != null) {
                switch (current.operation) {
                    case ADD:
                    case REPLACE:
                        current.value = value;
                        return;
                    case REMOVE:
                        return;
                }
            } else {
                tasks.put(taskKey, new CacheTask(cache, CacheOperation.REPLACE, key, value));
            }
        }

        public void remove(Cache cache, Object key) {
            log.tracev("Adding cache operation: {0} on {1}", CacheOperation.REMOVE, key);

            Object taskKey = getTaskKey(cache, key);
            tasks.put(taskKey, new CacheTask(cache, CacheOperation.REMOVE, key, null));
        }

        // This is for possibility to lookup for session by id, which was created in this transaction
        public Object get(Cache cache, Object key) {
            Object taskKey = getTaskKey(cache, key);
            CacheTask current = tasks.get(taskKey);
            if (current != null) {
                switch (current.operation) {
                    case ADD:
                    case REPLACE:
                        return current.value;                 }
            }

            return null;
        }

        private Object getTaskKey(Cache cache, Object key) {
            if (key instanceof String) {
                return new StringBuilder(cache.getName())
                        .append("::")
                        .append(key.toString()).toString();
            } else {
                // loginFailure cache
                return key;
            }
        }

        public class CacheTask {
            private Cache cache;
            private CacheOperation operation;
            private Object key;
            private Object value;

            public CacheTask(Cache cache, CacheOperation operation, Object key, Object value) {
                this.cache = cache;
                this.operation = operation;
                this.key = key;
                this.value = value;
            }

            public void execute() {
                log.tracev("Executing cache operation: {0} on {1}", operation, key);

                switch (operation) {
                    case ADD:
                        cache.put(key, value);
                        break;
                    case REMOVE:
                        cache.remove(key);
                        break;
                    case REPLACE:
                        cache.replace(key, value);
                        break;
                }
            }
        }

    }

    public enum CacheOperation {
        ADD, REMOVE, REPLACE
    }

}


text:
=begin
  list_openstack_tenant_network_ids.rb

  Author: Nate Stephany <nate@redhat.com, Kevin Morey <kmorey@redhat.com>

  Description: list OpenStack network ids based on

-------------------------------------------------------------------------------
   Copyright 2016 Kevin Morey <kmorey@redhat.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.
-------------------------------------------------------------------------------
=end
def log(level, msg, update_message = false)
  $evm.log(level, "#{msg}")
  @task.message = msg if @task && (update_message || level == 'error')
end

def get_provider(provider_id=nil)
  # if we get pass the provider_id when calling the method...
  if provider_id
    provider = $evm.vmdb(:ManageIQ_Providers_Openstack_CloudManager).find_by_id(provider_id)
  else
    # otherwise, pull the provider_id from the dialog options
    $evm.root.attributes.detect { |k,v| provider_id = v if k.end_with?('provider_id') } rescue nil
    provider = $evm.vmdb(:ManageIQ_Providers_Openstack_CloudManager).find_by_id(provider_id)
  end

  if provider
    log(:info, "Found provider: #{provider.name} via provider_id: #{provider.id}")
  else
    # if all else fails, grab the first provider of this type
    provider = $evm.vmdb(:ManageIQ_Providers_Openstack_CloudManager).first
    log(:info, "Found provider: #{provider.name} via default method")
  end
  provider ? (return provider) : (return nil)
end

def get_provider_from_template(template_guid=nil)
  $evm.root.attributes.detect { |k,v| template_guid = v if k.end_with?('_guid') } rescue nil
  template = $evm.vmdb(:ManageIQ_Providers_Openstack_CloudManager_Template).find_by_guid(template_guid)
  return nil unless template
  provider = $evm.vmdb(:ManageIQ_Providers_Openstack_CloudManager).find_by_id(template.ems_id)
  log(:info, "Found provider: #{provider.name} via template.ems_id: #{template.ems_id}") if provider
  provider ? (return provider) : (return nil)
end

def query_catalogitem(option_key, option_value=nil)
  # use this method to query a catalogitem
  # note that this only works for items not bundles since we do not know which item within a bundle(s) to query from
  service_template = $evm.root['service_template']
  unless service_template.nil?
    begin
      if service_template.service_type == 'atomic'
        log(:info, "Catalog item: #{service_template.name}")
        service_template.service_resources.each do |catalog_item|
          catalog_item_resource = catalog_item.resource
          if catalog_item_resource.respond_to?('get_option')
            option_value = catalog_item_resource.get_option(option_key)
          else
            option_value = catalog_item_resource[option_key] rescue nil
          end
          log(:info, "Found {#{option_key} => #{option_value}}") if option_value
        end
      else
        log(:info, "Catalog bundle: #{service_template.name} found, skipping query")
      end
    rescue
      return nil
    end
  end
  option_value ? (return option_value) : (return nil)
end

def get_user
  user_search = $evm.root.attributes.detect { |k,v| k.end_with?('user_id') } ||
    $evm.root.attributes.detect { |k,v| k.end_with?('_userid') }
  user = $evm.vmdb(:user).find_by_id(user_search) || $evm.vmdb(:user).find_by_userid(user_search) ||
    $evm.root['user']
  log(:info, "Found user: #{user.userid}")
  user
end

def get_current_group_rbac_array
  rbac_array = []
  unless @user.current_group.filters.blank?
    # this will come back as an array of arrays, so we need to flatten it
    # flatten will turn it into an array of hashes
    @user.current_group.filters['managed'].flatten.each do |filter|
      next unless /(?<category>\w*)\/(?<tag>\w*)$/i =~ filter
      rbac_array << {category=>tag}
    end
  end
  log(:info, "userid: #{@user.userid} rbac_array: #{rbac_array}")
  rbac_array
end

def object_eligible?(obj)
  # loops through each of the hashes in the rbac_array and compares to the object's tags
  @rbac_array.each do |rbac_hash|
    rbac_hash.each do |rbac_category, rbac_tags|
      Array.wrap(rbac_tags).each {|rbac_tag_entry| return false unless obj.tagged_with?(rbac_category, rbac_tag_entry) }
    end
    true
  end
end

def get_tenant(tenant_id=nil)
  # get the cloud_tenant id from $evm.root if already set
  $evm.root.attributes.detect { |k,v| tenant_id = v if k.end_with?('cloud_tenant') } rescue nil
  tenant = $evm.vmdb(:cloud_tenant).find_by_id(tenant_id)
  log(:info, "Found tenant: #{tenant.name} via tenant_id: #{tenant.id}") if tenant

  unless tenant
    # default to admin tenant if the user is admin
    if @user.userid == "admin"
      tenant = @provider.cloud_tenants.detect { |ct| ct.name == "admin" }
      log(:info, "Found tenant via default method: #{tenant.name}")
    else
      # otherwise, find the first tenant that is tagged with the filter of the user
      tenant = @provider.cloud_tenants.detect { |ct| object_eligible?(ct) && ct.enabled }
      log(:info, "Found tenant based on rbac_array: #{tenant.name}")
    end
  end
  tenant ? (return tenant) : (return nil)
end

$evm.root.attributes.sort.each { |k, v| log(:info, "\t Attribute: #{k} = #{v}")}

@user = get_user
@rbac_array = get_current_group_rbac_array
@provider = get_provider(query_catalogitem(:src_ems_id)) || get_provider_from_template()
@tenant = get_tenant

dialog_hash = {}

if @tenant
  @tenant.cloud_networks.each do |cloud_network|
    next unless cloud_network.enabled || cloud_network.status == 'active'
    dialog_hash[cloud_network.id] = "#{cloud_network.name} on #{cloud_network.ext_management_system.name}"
  end
end

if dialog_hash.blank?
  dialog_hash[''] = "< no cloud networks found >"
else
  $evm.object['default_value'] = dialog_hash.first[0]
end

$evm.object['values'] = dialog_hash
log(:info, "$evm.object['values']: #{$evm.object['values'].inspect}")


text:
<?xml version="1.0" encoding="utf-8" ?>
<!--Created:cb85b80c-f585-40ff-8bfc-12ff4d0e34a9-->
<App xmlns="http://schemas.microsoft.com/sharepoint/2012/app/manifest"
     Name="ChainStore"
     ProductID="{e1e20c69-6fb1-4457-a312-e011e77f53c1}"
     Version="1.0.0.0"
     SharePointMinVersion="16.0.0.0"
>
  <Properties>
    <Title>Chain Store</Title>
    <StartPage>~remoteAppUrl/Pages/CorporateDataViewer.aspx?{StandardTokens}&SPAddInVersion=1.0.0.0</StartPage>
    <InstalledEventEndpoint>~remoteAppUrl/Services/AppEventReceiver.svc</InstalledEventEndpoint>
    <UninstallingEventEndpoint>~remoteAppUrl/Services/AppEventReceiver.svc</UninstallingEventEndpoint>
  </Properties>

  <AppPrincipal>
    <RemoteWebApplication ClientId="*" />
  </AppPrincipal>
  <AppPermissionRequests AllowAppOnlyPolicy="false">
    <AppPermissionRequest Scope="http://sharepoint/content/sitecollection/web" Right="FullControl" />
  </AppPermissionRequests>
</App>


text:
//Given an array of N integers, can you find the sum of its elements?

//Input Format
//The first line contains an integer, N, denoting the size of the array.
//The second line contains N space-separated integers representing the array's elements.

//Output Format
//Print the sum of the array's elements as a single integer.

//Sample Input
//6
//1 2 3 4 10 11

//Sample Output
//31

//Explanation
//We print the sum of the array's elements, which is: 1+2+3+4+10+11=31.

using System;

class Solution
{
    static void Main()
    {
        int arraySize = int.Parse(Console.ReadLine());
        string[] stringNumbers = Console.ReadLine().Split(' ');
        int sum = 0;
        for (int i = 0; i < arraySize; i++)
        {
            sum += int.Parse(stringNumbers[i]);
        }
        Console.WriteLine(sum);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace SimpleAuth
{
	public abstract class Authenticator
	{

		public string AuthCode
		{
			get;
			private set;
		}

		public Authenticator()
		{
			AllowsCancel = true;
			Title = "Sign in";
		}

		public string Title
		{
			get;
			set;
		}

		protected TaskCompletionSource<string> TokenTask = new TaskCompletionSource<string> ();

		public Task PrepareAuthenticator ()
		{
			TokenTask?.TrySetCanceled ();
			HasCompleted = false;
			TokenTask = new TaskCompletionSource<string> ();
			return Task.FromResult (true);
		}

		public Task<string> GetAuthCode()
		{
			return TokenTask.Task;
		}

		public bool AllowsCancel
		{
			get;
			set;
		}

		public void OnCancelled()
		{
			HasCompleted = true;
			TokenTask?.TrySetCanceled();
		}

		protected void FoundAuthCode(string authCode)
		{
			HasCompleted = !string.IsNullOrWhiteSpace(authCode);
			AuthCode = authCode;
			TokenTask?.TrySetResult(authCode);
		}

		public void OnError(string error)
		{
			if(!HasCompleted)
				TokenTask?.TrySetException(new Exception(error));
		}

		public string ClientId
		{
			get;
			set;
		}

		public bool HasCompleted
		{
			get;
			private set;
		}

	}

}


text:
<?php

declare(strict_types=1);

namespace Eelly\SDK\Data\Api;

use Eelly\SDK\EellyClient;
use Eelly\SDK\Data\Service\SummaryInterface;
use Eelly\DTO\SummaryDTO;

/**
 *
 * @author shadonTools<localhost.shell@gmail.com>
 */
class Summary implements SummaryInterface
{
    /**
     * @author eellytools<localhost.shell@gmail.com>
     */
    public function getSummary(int $summaryId): SummaryDTO
    {
        return EellyClient::request('data/summary', 'getSummary', true, $summaryId);
    }

    /**
     * @author eellytools<localhost.shell@gmail.com>
     */
    public function getSummaryAsync(int $summaryId)
    {
        return EellyClient::request('data/summary', 'getSummary', false, $summaryId);
    }

    /**
     * @author eellytools<localhost.shell@gmail.com>
     */
    public function addSummary(array $data): bool
    {
        return EellyClient::request('data/summary', 'addSummary', true, $data);
    }

    /**
     * @author eellytools<localhost.shell@gmail.com>
     */
    public function addSummaryAsync(array $data)
    {
        return EellyClient::request('data/summary', 'addSummary', false, $data);
    }

    /**
     * @author eellytools<localhost.shell@gmail.com>
     */
    public function updateSummary(int $summaryId, array $data): bool
    {
        return EellyClient::request('data/summary', 'updateSummary', true, $summaryId, $data);
    }

    /**
     * @author eellytools<localhost.shell@gmail.com>
     */
    public function updateSummaryAsync(int $summaryId, array $data)
    {
        return EellyClient::request('data/summary', 'updateSummary', false, $summaryId, $data);
    }

    /**
     * @author eellytools<localhost.shell@gmail.com>
     */
    public function deleteSummary(int $summaryId): bool
    {
        return EellyClient::request('data/summary', 'deleteSummary', true, $summaryId);
    }

    /**
     * @author eellytools<localhost.shell@gmail.com>
     */
    public function deleteSummaryAsync(int $summaryId)
    {
        return EellyClient::request('data/summary', 'deleteSummary', false, $summaryId);
    }

    /**
     * @author eellytools<localhost.shell@gmail.com>
     */
    public function listSummaryPage(array $condition = [], int $currentPage = 1, int $limit = 10): array
    {
        return EellyClient::request('data/summary', 'listSummaryPage', true, $condition, $currentPage, $limit);
    }

    /**
     * @author eellytools<localhost.shell@gmail.com>
     */
    public function listSummaryPageAsync(array $condition = [], int $currentPage = 1, int $limit = 10)
    {
        return EellyClient::request('data/summary', 'listSummaryPage', false, $condition, $currentPage, $limit);
    }

    /**
     * @return self
     */
    public static function getInstance(): self
    {
        static $instance;
        if (null === $instance) {
            $instance = new self();
        }

        return $instance;
    }
}