text:
/**********************************************************************
* $Id$		master.c  				2010-05-21
*//**
* @file		master.c
* @brief	This example describes how to configure I2C as master device
* @version	2.0
* @date		21. May. 2010
* @author	NXP MCU SW Application Team
*
* Copyright(C) 2010, NXP Semiconductor
* All rights reserved.
*
***********************************************************************
* Software that is described herein is for illustrative purposes only
* which provides customers with programming information regarding the
* products. This software is supplied "AS IS" without any warranties.
* NXP Semiconductors assumes no responsibility or liability for the
* use of the software, conveys no license or title under any patent,
* copyright, or mask work right to the product. NXP Semiconductors
* reserves the right to make changes in the software without
* notification. NXP Semiconductors also make no representation or
* warranty that such application will be suitable for the specified
* use without further testing or modification.
* Permission to use, copy, modify, and distribute this software and its
* documentation is hereby granted, under NXP Semiconductors'
* relevant copyright in the software, without fee, provided that it
* is used in conjunction with NXP Semiconductors microcontrollers.  This
* copyright, permission, and disclaimer notice must appear in all copies of
* this code.
**********************************************************************/
#include "lpc17xx_i2c.h"
#include "lpc17xx_libcfg.h"
#include "lpc17xx_pinsel.h"
#include "debug_frmwrk.h"

/* Example group ----------------------------------------------------------- */
/** @defgroup I2C_master	master
 * @ingroup I2C_Examples
 * @{
 */

/************************** PRIVATE DEFINITIONS *************************/
/** Used I2C device as slave definition */
#define USEDI2CDEV_M		0
/** Own Slave address in Slave I2C device */
#define I2CDEV_S_ADDR	(0xA0>>1)

/** Max buffer length */
#define BUFFER_SIZE			0x10

#if (USEDI2CDEV_M == 0)
#define I2CDEV_M LPC_I2C0
#elif (USEDI2CDEV_M == 2)
#define I2CDEV_M LPC_I2C2
#else
#error "Master I2C device not defined!"
#endif

/************************** PRIVATE VARIABLES *************************/
uint8_t menu1[] =
"********************************************************************************\n\r"
"Hello NXP Semiconductors \n\r"
"I2C demo \n\r"
"\t - MCU: LPC17xx \n\r"
"\t - Core: ARM Cortex-M3 \n\r"
"\t - This example uses two I2C peripheral, one set as master and \n\r"
"\t the other set as slave \n\r"
"\t Test Master mode as alone device \n\r"
"********************************************************************************\n\r";

/** These global variables below used in interrupt mode - Slave device ----------------*/
uint8_t Master_Buf[BUFFER_SIZE];
uint8_t master_test[2];

/************************** PRIVATE FUNCTIONS *************************/
void print_menu(void);
void Buffer_Init(uint8_t type);

/*-------------------------PRIVATE FUNCTIONS-----------------------------*/
/*********************************************************************//**
 * @brief		Print Welcome menu
 * @param[in]	none
 * @return 		None
 **********************************************************************/
void print_menu(void)
{
	_DBG_(menu1);
}

/*********************************************************************//**
 * @brief		Initialize buffer
 * @param[in]	type:
 * 				- 0: Initialize Master_Buf with increment value from 0
 * 					Fill all member in Slave_Buf with 0
 * 				- 1: Initialize Slave_Buf with increment value from 0
 * 					Fill all member in Master_Buf with 0
 * @return 		None
 **********************************************************************/
void Buffer_Init(uint8_t type)
{
	uint8_t i;

	Master_Buf[0] = 0x00;
	Master_Buf[1] = 0x01;
	if (type)
	{
		for (i = 2; i < BUFFER_SIZE; i++) {
			Master_Buf[i] = i;
		}
	}
	else
	{
		for (i = 0; i < BUFFER_SIZE; i++) {
			Master_Buf[i] = 0;
		}
	}
}

/*-------------------------MAIN FUNCTION------------------------------*/
/*********************************************************************//**
 * @brief		c_entry: Main program body
 * @param[in]	None
 * @return 		int
 **********************************************************************/
int c_entry(void)
{
	PINSEL_CFG_Type PinCfg;
	I2C_M_SETUP_Type transferMCfg;
	uint32_t tempp;
	uint8_t *pdat;
	uint8_t word_addr[2];

	/* Initialize debug via UART0
	 * � 115200bps
	 * � 8 data bit
	 * � No parity
	 * � 1 stop bit
	 * � No flow control
	 */
	debug_frmwrk_init();

	print_menu();

	/* I2C block ------------------------------------------------------------------- */

	/*
	 * Init I2C pin connect
	 */
	PinCfg.OpenDrain = PINSEL_PINMODE_OPENDRAIN;
	PinCfg.Pinmode = PINSEL_PINMODE_TRISTATE;
#if ((USEDI2CDEV_M == 0))
	PinCfg.Funcnum = 1;
	PinCfg.Pinnum = 27;
	PinCfg.Portnum = 0;
	PINSEL_ConfigPin(&PinCfg);
	PinCfg.Pinnum = 28;
	PINSEL_ConfigPin(&PinCfg);
#endif
#if ((USEDI2CDEV_M == 2))
	PinCfg.Funcnum = 2;
	PinCfg.Pinnum = 10;
	PinCfg.Portnum = 0;
	PINSEL_ConfigPin(&PinCfg);
	PinCfg.Pinnum = 11;
	PINSEL_ConfigPin(&PinCfg);
#endif

	// Initialize Slave I2C peripheral
	I2C_Init(I2CDEV_M, 100000);

	/* Enable Slave I2C operation */
	I2C_Cmd(I2CDEV_M, I2C_MASTER_MODE, ENABLE);

	/* Transmit -------------------------------------------------------- */

	/* Initialize buffer */
	Buffer_Init(1);
	word_addr[1] = 0x01;
	word_addr[0] = 0x00;
	/* Start I2C slave device first */
	transferMCfg.sl_addr7bit = I2CDEV_S_ADDR;
	transferMCfg.tx_data = Master_Buf;
	transferMCfg.tx_length = sizeof(Master_Buf);
	transferMCfg.rx_data = NULL;
	transferMCfg.rx_length = 0;
	transferMCfg.retransmissions_max = 1;
	I2C_MasterTransferData(I2CDEV_M, &transferMCfg, I2C_TRANSFER_POLLING);

	/* Receive -------------------------------------------------------- */

	/* Initialize buffer */
	Buffer_Init(0);

	/* Start I2C slave device first */
	transferMCfg.sl_addr7bit = I2CDEV_S_ADDR;
	transferMCfg.tx_data = word_addr ;
	transferMCfg.tx_length = 2;
	transferMCfg.rx_data = NULL;
	transferMCfg.rx_length = 0;
	transferMCfg.retransmissions_max = 3;
	I2C_MasterTransferData(I2CDEV_M, &transferMCfg, I2C_TRANSFER_POLLING);

  transferMCfg.sl_addr7bit = I2CDEV_S_ADDR;
	transferMCfg.tx_data = NULL ;
	transferMCfg.tx_length = 0;
	transferMCfg.rx_data = Master_Buf;
	transferMCfg.rx_length = sizeof(Master_Buf);
	transferMCfg.retransmissions_max = 3;
	I2C_MasterTransferData(I2CDEV_M, &transferMCfg, I2C_TRANSFER_POLLING);
	pdat = Master_Buf;
	// Verify
	for (tempp = 0; tempp < sizeof(Master_Buf); tempp++){
		if (*pdat++ != tempp){
			_DBG_("Verify error");
			break;
		}
	}
	if (tempp == sizeof(Master_Buf)){
		_DBG_("Verify successfully");
	}

#if 1
	/* Transmit and receive -------------------------------------------------------- */

	/* Initialize buffer */
	Buffer_Init(0);
	master_test[0] = 0xAA;
	master_test[1] = 0x55;

	/* Start I2C slave device first */
	transferMCfg.sl_addr7bit = I2CDEV_S_ADDR;
	transferMCfg.tx_data = master_test ;
	transferMCfg.tx_length = sizeof(master_test);
	transferMCfg.rx_data = Master_Buf;
	transferMCfg.rx_length = sizeof(Master_Buf);
	transferMCfg.retransmissions_max = 3;
	I2C_MasterTransferData(I2CDEV_M, &transferMCfg, I2C_TRANSFER_POLLING);
#endif

	pdat = Master_Buf;
	// Verify
	for (tempp = 0; tempp < sizeof(Master_Buf); tempp++){
		if (*pdat++ != tempp){
			_DBG_("Verify error");
			break;
		}
	}
	if (tempp == sizeof(Master_Buf)){
		_DBG_("Verify successfully");
	}
	I2C_DeInit(I2CDEV_M);
    /* Loop forever */
    while(1);
    return 1;
}

/* With ARM and GHS toolsets, the entry point is main() - this will
   allow the linker to generate wrapper code to setup stacks, allocate
   heap area, and initialize and copy code and data segments. For GNU
   toolsets, the entry point is through __start() in the crt0_gnu.asm
   file, and that startup code will setup stacks and data */
int main(void)
{
    return c_entry();
}

#ifdef  DEBUG
/*******************************************************************************
* @brief		Reports the name of the source file and the source line number
* 				where the CHECK_PARAM error has occurred.
* @param[in]	file Pointer to the source file name
* @param[in]    line assert_param error line source number
* @return		None
*******************************************************************************/
void check_failed(uint8_t *file, uint32_t line)
{
	/* User can add his own implementation to report the file name and line number,
	 ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */

	/* Infinite loop */
	while(1);
}
#endif

/*
 * @}
 */


text:
package gouda

import (
	"reflect"
	//	"fmt"
	"strings"
)
/** Types **/
type ModelInterface interface {
	TableName() string
	Identifier() string
}

type AssociationKind int

const (
	BELONGS_TO AssociationKind = iota
	HAS_MANY
	HAS_ONE
	HAS_AND_BELONGS_TO_MANY
)

type Association struct {
	model     *Model
	kind      AssociationKind
	fieldname string
}

type Model struct {
	tablename    string
	identifier   string
	attributes   map[string]reflect.Type
	object_cache map[int]map[string]Value
	runtype      reflect.Type
	connection   *Connection
	associations map[string]Association
}

type ModelRelation struct {
	model    *Model
	relation *Relation
}

type ModelStore map[string]*Model

var _ModelStore = make(ModelStore)

/** NullModel **/

type NullModel struct{}

func (n NullModel) TableName() string { return "" }

func (n NullModel) Identifier() string { return "Id" }

/** utils **/

func attributes(m interface{}) (map[string]reflect.Type, reflect.Type) {
	var st *reflect.StructType
	var typ reflect.Type
	if _, ok := reflect.Typeof(m).(*reflect.PtrType); ok {
		typ = reflect.Typeof(m).(*reflect.PtrType).Elem()
	} else {
		typ = reflect.Typeof(m)
	}
	st = typ.(*reflect.StructType)

	//fmt.Println(st.NumField())

	ret := make(map[string]reflect.Type)

	for i := 0; i < st.NumField(); i++ {
		p := st.Field(i)
		//fmt.Println(p.Name)
		if !p.Anonymous {
			ret[p.Name] = p.Type
		}
	}

	return ret, typ
}

/** Model **/
func (m *Model) TableName() string { return m.tablename }

func (m *Model) Attributes() map[string]reflect.Type {
	return m.attributes
}

func (m *Model) AttributesNames() (ret []string) {
	ret = make([]string, len(m.attributes))
	i := 0
	for k, _ := range m.attributes {
		ret[i] = k
		i++
	}
	return ret
}

func (m *Model) addAssociation(am *Model, name string, kind AssociationKind, fieldname string) {
	var a = Association{kind: kind, model: am, fieldname: fieldname}
	m.associations[name] = a
}

func (m *Model) BelongsToKey(am *Model, name, key string) {
	m.addAssociation(am, name, BELONGS_TO, key)
}

func (m *Model) HasManyKey(am *Model, name, key string) {
	m.addAssociation(am, name, HAS_MANY, key)
}

func (m *Model) HasONEKey(am *Model, name, key string) {
	m.addAssociation(am, name, HAS_ONE, key)
}

func (m *Model) GetAssociated(name string, in interface{}) interface{} {
	st := reflect.NewValue(in)
	if p, ok := st.(*reflect.PtrValue); ok {
		st = p.Elem()
	}
	ama, ok := m.associations[name]
	if !ok {
		panic("No Such Association : " + name)
	}
	fieldname := ""
	if ama.kind == HAS_MANY || ama.kind == HAS_ONE {
		fieldname = ama.fieldname
	} else {
		fieldname = m.identifier
	}
	id := st.(*reflect.StructValue).FieldByName(ama.model.identifier).(*reflect.IntValue).Get()
	req := ama.model.Where(F(fieldname).Eq(id))
	if ama.kind == BELONGS_TO || ama.kind == HAS_ONE {
		return req.First()
	}
	return req.All()

}

func (m *Model) Last() interface{} {
	q := NewRelation(m.tablename).Order(strings.ToLower(m.identifier), "desc").First()
	ret := m.connection.Query(q)
	if ret.Len() < 1 {
		return nil
	}
	v := ret.At(0).(map[string]Value)
	return m.translateObject(v)
}

func (m *Model) First() interface{} {
	q := NewRelation(m.tablename).First()
	ret := m.connection.Query(q)
	if ret.Len() < 1 {
		return nil
	}
	v := ret.At(0).(map[string]Value)
	return m.translateObject(v)
}

func (m *Model) All() []interface{} {
	q := NewRelation(m.tablename)
	ret := m.connection.Query(q)
	v := make([]interface{}, ret.Len())
	for i := 0; i < ret.Len(); i++ {
		v[i] = m.translateObject(ret.At(i).(map[string]Value))
	}
	return v
}

func (m *Model) Refresh(a interface{}) interface{} {
	st := reflect.NewValue(a)
	if p, ok := st.(*reflect.PtrValue); ok {
		st = p.Elem()
	}

	id := m.getId(st.(*reflect.StructValue))
	q := NewRelation(m.tablename).Where(F(m.identifier).Eq(id)).First()
	ret := m.connection.Query(q)
	if ret.Len() < 1 {
		return nil
	}
	v := ret.At(0).(map[string]Value)
	return m.translateObject(v)
}

func (m *Model) getId(st *reflect.StructValue) int {
	return st.FieldByName(m.identifier).(*reflect.IntValue).Get()
}

func (m *Model) Delete(a interface{}) interface{} {
	st := reflect.NewValue(a)
	if p, ok := st.(*reflect.PtrValue); ok {
		st = p.Elem()
	}
	id := m.getId(st.(*reflect.StructValue))
	q := NewRelation(m.tablename).Where(F(m.identifier).Eq(id)).Delete()
	m.connection.Query(q)
	return a
}
func (m *Model) Save(a interface{}) interface{} {
	stv := reflect.NewValue(a)
	if p, ok := stv.(*reflect.PtrValue); ok {
		stv = p.Elem()
	}
	st := stv.(*reflect.StructValue)
	id := m.getId(st)
	if v, present := m.object_cache[id]; present {
		if up := m.buildUpdateMap(st, v); len(up) > 0 {
			r := new(Relation)
			r.Table(m.tablename)
			r.Update(up, m.identifier, id)
			m.connection.Query(r)
		}
		return a
	}

	r := new(Relation)
	r.Table(m.tablename)
	r.Insert(m.translateMap(st))
	m.connection.Query(r)

	//Ugly Hack to get Last Inserted Id
	q := NewRelation(m.tablename).Order(strings.ToLower(m.identifier), "desc").First()
	ret := m.connection.Query(q)
	if ret.Len() < 1 {
		return nil
	}
	v := ret.At(0).(map[string]Value)
	m.translateObjectValue(v, st)
	return a
}

func (m *Model) buildUpdateMap(st *reflect.StructValue, old map[string]Value) map[string]Value {
	ret := make(map[string]Value)
	for attr, typ := range m.attributes {
		switch typ.(type) {
		case *reflect.IntType:
			if tmp := st.FieldByName(attr).(*reflect.IntValue).Get(); int(old[strings.ToLower(attr)].Int()) != tmp {
				ret[attr] = SysInt(tmp).Value()
			}
		case *reflect.StringType:
			if tmp := st.FieldByName(attr).(*reflect.StringValue).Get(); string(old[strings.ToLower(attr)].String()) != tmp {
				ret[attr] = SysString(tmp).Value()
			}
		}
	}
	return ret
}

func (m *Model) translateMap(obj *reflect.StructValue) map[string]Value {
	ret := make(map[string]Value)
	for attr, typ := range m.attributes {
		switch typ.(type) {
		case *reflect.IntType:
			ret[attr] = SysInt(obj.FieldByName(attr).(*reflect.IntValue).Get()).Value()
		case *reflect.StringType:
			ret[attr] = SysString(obj.FieldByName(attr).(*reflect.StringValue).Get()).Value()
		case nil:
			ret[attr] = new(_Null)
		}
	}
	return ret
}

func (m *Model) translateObject(v map[string]Value) interface{} {
	p := reflect.MakeZero(m.runtype).(*reflect.StructValue)
	return m.translateObjectValue(v, p)
}

func (m *Model) translateObjectValue(v map[string]Value, p *reflect.StructValue) interface{} {
	for lbl, _ := range m.Attributes() {
		vl := v[strings.ToLower(lbl)]
		switch vl.Kind() {
		//TODO MakeZero ??
		case IntKind:
			tmp := reflect.NewValue(1).(*reflect.IntValue)
			tmp.Set(int(vl.Int()))
			p.FieldByName(lbl).SetValue(tmp)
		case StringKind:
			tmp := reflect.NewValue("").(*reflect.StringValue)
			tmp.Set(string(vl.String()))
			p.FieldByName(lbl).SetValue(tmp)
		}
	}
	m.object_cache[int(v[strings.ToLower(m.identifier)].Int())] = v
	return p.Interface()

}

func Refresh(a interface{}) interface{} { return M(a.(ModelInterface)).Refresh(a) }
func Save(a interface{}) interface{}    { return M(a.(ModelInterface)).Save(a) }
func Delete(a interface{}) interface{}  { return M(a.(ModelInterface)).Delete(a) }

/** ModelInterface **/

func ModelName(m ModelInterface) (ret string) {
	t := reflect.Typeof(m).String()
	tab := strings.Split(t, ".", 0)
	return tab[len(tab)-1] + "-" + GetTableName(m)
}

func M(m ModelInterface) *Model {
	modelname := ModelName(m)
	if model, present := _ModelStore[modelname]; present {
		return model
	}
	return GetModelStore().RegisterModel(m)

}

func GetTableName(m ModelInterface) string {
	s := m.TableName()
	if s == "" {
		t := reflect.Typeof(m).String()
		tab := strings.Split(t, ".", 0)
		return strings.ToLower(tab[len(tab)-1]) + "s"
	}
	return s
}

/** ModelStore **/

func GetModelStore() *ModelStore { return &_ModelStore }

func (st *ModelStore) RegisterModel(m ModelInterface) *Model {
	return st.RegisterModelWithConnection(m, GetConnectionStore().Last())
}

func (st *ModelStore) RegisterModelWithConnection(m ModelInterface, conn *Connection) *Model {
	modelname := ModelName(m)
	mod := new(Model)
	mod.tablename = GetTableName(m)
	mod.identifier = m.Identifier()
	attr, run := attributes(m)
	mod.attributes = attr
	mod.runtype = run
	mod.connection = conn
	mod.object_cache = make(map[int]map[string]Value)
	mod.associations = make(map[string]Association)
	(*st)[modelname] = mod
	return mod
}

/** Model RelationLike methods**/

func (m *Model) newRelation() *ModelRelation {
	mr := new(ModelRelation)
	mr.model = m
	mr.relation = new(Relation)
	mr.relation.Table(m.tablename)
	return mr
}

func (m *Model) Where(x *Condition) *ModelRelation {
	return m.newRelation().Where(x)
}

func (m *Model) Order(x, y string) *ModelRelation {
	return m.newRelation().Order(x, y)
}

func (m *Model) Count(fields ...[]string) int { return m.newRelation().Count(fields) }

/** ModelRelation **/

func (r *ModelRelation) Where(x *Condition) *ModelRelation {
	r.relation.Where(x)
	return r
}

func (r *ModelRelation) Order(x, y string) *ModelRelation {
	r.relation.Order(x, y)
	return r
}

func (r *ModelRelation) First() interface{} {
	q := r.relation.First()
	ret := r.model.connection.Query(q)
	if ret.Len() < 1 {
		return nil
	}
	v := ret.At(0).(map[string]Value)
	return r.model.translateObject(v)
}

func (r *ModelRelation) Last() interface{} {
	q := r.relation.Order(r.model.identifier, "DESC").First()
	ret := r.model.connection.Query(q)
	if ret.Len() < 1 {
		return nil
	}
	v := ret.At(0).(map[string]Value)
	return r.model.translateObject(v)
}

func (r *ModelRelation) All() []interface{} {
	ret := r.model.connection.Query(r.relation)
	v := make([]interface{}, ret.Len())
	for i := 0; i < ret.Len(); i++ {
		v[i] = r.model.translateObject(ret.At(i).(map[string]Value))
	}
	return v
}

func (r *ModelRelation) Count(fields ...[]string) int {
	q := r.relation
	if len(fields) == 0 {
		field := make([]string, 1)
		field[0] = r.model.identifier
		q = r.relation.Count(field)
	} else {
		q = r.relation.Count(fields[0])
	}

	ret := r.model.connection.Query(q)
	if ret.Len() < 1 {
		return -1
	}
	v := ret.At(0).(map[string]Value)
	return int(v["_count"].Int())
}

redpajama_set_name: RedPajamaGithub


text:
package org.tinymediamanager.core.tvshow.tasks;

import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import java.util.ResourceBundle;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tinymediamanager.Globals;
import org.tinymediamanager.core.Message;
import org.tinymediamanager.core.Message.MessageLevel;
import org.tinymediamanager.core.MessageManager;
import org.tinymediamanager.core.threading.TmmTask;
import org.tinymediamanager.core.threading.TmmTaskManager;
import org.tinymediamanager.core.threading.TmmThreadPool;
import org.tinymediamanager.core.tvshow.TvShowList;
import org.tinymediamanager.core.tvshow.TvShowScraperMetadataConfig;
import org.tinymediamanager.core.tvshow.TvShowSearchAndScrapeOptions;
import org.tinymediamanager.core.tvshow.entities.TvShow;
import org.tinymediamanager.scraper.IMediaArtworkProvider;
import org.tinymediamanager.scraper.ITvShowMetadataProvider;
import org.tinymediamanager.scraper.MediaArtwork;
import org.tinymediamanager.scraper.MediaArtwork.MediaArtworkType;
import org.tinymediamanager.scraper.MediaMetadata;
import org.tinymediamanager.scraper.MediaScrapeOptions;
import org.tinymediamanager.scraper.MediaSearchResult;
import org.tinymediamanager.scraper.MediaType;
import org.tinymediamanager.scraper.trakttv.SyncTraktTvTask;
import org.tinymediamanager.ui.UTF8Control;

/**
 * The class TvShowScrapeTask. This starts scraping of TV shows
 *
 * @author Manuel Laggner
 */
public class TvShowScrapeTask extends TmmThreadPool {
  private final static Logger          LOGGER = LoggerFactory.getLogger(TvShowScrapeTask.class);
  private static final ResourceBundle  BUNDLE = ResourceBundle.getBundle("messages", new UTF8Control()); //$NON-NLS-1$

  private List<TvShow>                 tvShowsToScrape;
  private boolean                      doSearch;
  private TvShowSearchAndScrapeOptions options;

  /**
   * Instantiates a new tv show scrape task.
   *
   * @param tvShowsToScrape
   *          the tv shows to scrape
   * @param doSearch
   *          the do search
   * @param options
   *          the options
   */
  public TvShowScrapeTask(List<TvShow> tvShowsToScrape, boolean doSearch, TvShowSearchAndScrapeOptions options) {
    super(BUNDLE.getString("tvshow.scraping"));
    this.tvShowsToScrape = tvShowsToScrape;
    this.doSearch = doSearch;
    this.options = options;
  }

  @Override
  protected void doInBackground() {
    LOGGER.debug("start scraping tv shows...");
    start();

    initThreadPool(3, "scrape");
    for (TvShow tvShow : tvShowsToScrape) {
      submitTask(new Worker(tvShow));
    }

    waitForCompletionOrCancel();

    if (Globals.settings.getTvShowSettings().getSyncTrakt()) {
      TmmTask task = new SyncTraktTvTask(null, tvShowsToScrape);
      TmmTaskManager.getInstance().addUnnamedTask(task);
    }

    LOGGER.debug("done scraping tv shows...");
  }

  private class Worker implements Runnable {
    private TvShowList tvShowList = TvShowList.getInstance();
    private TvShow     tvShow;

    public Worker(TvShow tvShow) {
      this.tvShow = tvShow;
    }

    @Override
    public void run() {
      try {
        // set up scrapers
        TvShowScraperMetadataConfig scraperMetadataConfig = options.getScraperMetadataConfig();
        ITvShowMetadataProvider mediaMetadataProvider = tvShowList.getMetadataProvider(options.getMetadataScraper());
        List<IMediaArtworkProvider> artworkProviders = tvShowList.getArtworkProviders(options.getArtworkScrapers());
        // List<IMediaTrailerProvider> trailerProviders = tvShowList.getTrailerProviders(options.getTrailerScrapers());

        // scrape tv show

        // search for tv show
        MediaSearchResult result1 = null;
        if (doSearch) {
          List<MediaSearchResult> results = tvShowList.searchTvShow(tvShow.getTitle(), mediaMetadataProvider);
          if (results != null && !results.isEmpty()) {
            result1 = results.get(0);
            // check if there is an other result with 100% score
            if (results.size() > 1) {
              MediaSearchResult result2 = results.get(1);
              // if both results have 100% score - do not take any result
              if (result1.getScore() == 1 && result2.getScore() == 1) {
                LOGGER.info("two 100% results, can't decide whitch to take - ignore result");
                MessageManager.instance.pushMessage(new Message(MessageLevel.ERROR, tvShow, "tvshow.scrape.nomatchfound"));
                return;
              }
              // create a treshold of 0.75 - to minimize false positives
              if (result1.getScore() < 0.75) {
                LOGGER.info("score is lower than 0.75 (" + result1.getScore() + ") - ignore result");
                MessageManager.instance.pushMessage(new Message(MessageLevel.ERROR, tvShow, "tvshow.scrape.nomatchfound"));
                return;
              }
            }
          }
          else {
            LOGGER.info("no result found for " + tvShow.getTitle());
            MessageManager.instance.pushMessage(new Message(MessageLevel.ERROR, tvShow, "tvshow.scrape.nomatchfound"));
          }
        }

        // get metadata and artwork
        if ((doSearch && result1 != null) || !doSearch) {
          try {
            MediaScrapeOptions options = new MediaScrapeOptions();
            options.setType(MediaType.TV_SHOW);
            options.setResult(result1);
            options.setLanguage(Globals.settings.getTvShowSettings().getScraperLanguage());
            options.setCountry(Globals.settings.getTvShowSettings().getCertificationCountry());

            // we didn't do a search - pass imdbid and tmdbid from movie
            // object
            if (!doSearch) {
              for (Entry<String, Object> entry : tvShow.getIds().entrySet()) {
                options.setId(entry.getKey(), entry.getValue().toString());
              }
            }

            // override scraper with one from search result
            mediaMetadataProvider = tvShowList.getMetadataProvider(result1.getProviderId());
            // scrape metadata if wanted
            MediaMetadata md = null;

            if (scraperMetadataConfig.isCast() || scraperMetadataConfig.isCertification() || scraperMetadataConfig.isGenres()
                || scraperMetadataConfig.isAired() || scraperMetadataConfig.isPlot() || scraperMetadataConfig.isRating()
                || scraperMetadataConfig.isRuntime() || scraperMetadataConfig.isStatus() || scraperMetadataConfig.isTitle()
                || scraperMetadataConfig.isYear()) {
              md = mediaMetadataProvider.getTvShowMetadata(options);
              tvShow.setMetadata(md, scraperMetadataConfig);
            }

            // scrape episodes
            if (scraperMetadataConfig.isEpisodes()) {
              tvShow.scrapeAllEpisodes();
            }

            // scrape artwork if wanted
            if (scraperMetadataConfig.isArtwork()) {
              tvShow.setArtwork(getArtwork(tvShow, md, artworkProviders), scraperMetadataConfig);
            }

          }
          catch (Exception e) {
            LOGGER.error("tvShow.setMetadata", e);
            MessageManager.instance.pushMessage(new Message(MessageLevel.ERROR, tvShow, "message.scrape.metadatatvshowfailed"));
          }
        }
      }

      catch (Exception e) {
        LOGGER.error("Thread crashed", e);
        MessageManager.instance.pushMessage(new Message(MessageLevel.ERROR, "TvShowScraper", "message.scrape.threadcrashed", new String[] { ":",
            e.getLocalizedMessage() }));
      }
    }

    /**
     * Gets the artwork.
     *
     * @param metadata
     *          the metadata
     * @return the artwork
     */
    public List<MediaArtwork> getArtwork(TvShow tvShow, MediaMetadata metadata, List<IMediaArtworkProvider> artworkProviders) {
      List<MediaArtwork> artwork = new ArrayList<MediaArtwork>();

      MediaScrapeOptions options = new MediaScrapeOptions();
      options.setType(MediaType.TV_SHOW);
      options.setArtworkType(MediaArtworkType.ALL);
      options.setMetadata(metadata);
      options.setLanguage(Globals.settings.getTvShowSettings().getScraperLanguage());
      options.setCountry(Globals.settings.getTvShowSettings().getCertificationCountry());
      for (Entry<String, Object> entry : tvShow.getIds().entrySet()) {
        options.setId(entry.getKey(), entry.getValue().toString());
      }

      // scrape providers till one artwork has been found
      for (IMediaArtworkProvider artworkProvider : artworkProviders) {
        try {
          artwork.addAll(artworkProvider.getArtwork(options));
        }
        catch (Exception e) {
          LOGGER.error("getArtwork", e);
          MessageManager.instance.pushMessage(new Message(MessageLevel.ERROR, tvShow, "message.scrape.tvshowartworkfailed"));
        }
      }
      return artwork;
    }
  }

  @Override
  public void callback(Object obj) {
    // do not publish task description here, because with different workers the text is never right
    publishState(progressDone);
  }
}


text:
(function() {
  var HollaBack;
  var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __slice = Array.prototype.slice;
  HollaBack = (function() {
    function HollaBack() {
      this.events = {};
    }
    HollaBack.prototype.bind = function(events, func) {
      var addEvent, eventName, functionNameSpaceSet, i, identifiers, _event, _i, _len, _ref, _ref2;
      if (!func) {
        throw "BindMissingEventHandler";
      }
      addEvent = __bind(function(label, functionNameSpaceSet) {
        if (this.events[label] == null) {
          this.events[label] = [];
        }
        this.events[label].push(functionNameSpaceSet);
        return null;
      }, this);
      _ref = events.split(' ');
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        _event = _ref[_i];
        identifiers = _event.split('.');
        eventName = '';
        functionNameSpaceSet = [func];
        for (i = 0, _ref2 = identifiers.length - 1; (0 <= _ref2 ? i <= _ref2 : i >= _ref2); (0 <= _ref2 ? i += 1 : i -= 1)) {
          if (identifiers[i].match(/^\.|^[0-9]|^$/)) {
            throw "EventNameUnacceptable";
          }
          if (i === 0) {
            eventName = identifiers[i];
          } else {
            functionNameSpaceSet.push(identifiers[i]);
          }
        }
        addEvent(eventName, functionNameSpaceSet);
      }
      return null;
    };
    HollaBack.prototype.unbind = function(events, func) {
      var eventList, eventName, eventNames, i, identifiers, matchFunction, matchNamespace, name, namespacedFunc, namespaces, _event, _i, _j, _len, _len2, _ref, _ref2;
      eventList = __bind(function() {

      var eventnames = []
      for(eventname in this.events) {
        eventnames.push(eventname);
      }
      ;        return eventnames;
      }, this);
      _ref = events.split(' ');
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        _event = _ref[_i];
        if (_event[0] === '.') {
          namespaces = _event.split('.');
          namespaces.shift();
          eventName = '';
        } else {
          identifiers = _event.split('.');
          eventName = identifiers.shift();
          namespaces = identifiers;
        }
        if (eventName !== '' && !(func != null) && namespaces.length === 0) {
          delete this.events[eventName];
        } else {
          eventNames = eventName === '' ? eventList() : [eventName];
          for (_j = 0, _len2 = eventNames.length; _j < _len2; _j++) {
            name = eventNames[_j];
            for (i = 0, _ref2 = this.events[name].length - 1; (0 <= _ref2 ? i <= _ref2 : i >= _ref2); (0 <= _ref2 ? i += 1 : i -= 1)) {
              namespacedFunc = this.events[name].shift();
              matchNamespace = this.functionInNamepspace(namespacedFunc, namespaces);
              if (func != null) {
                matchFunction = namespacedFunc[0] === func;
              } else {
                matchFunction = true;
              }
              if (!(matchNamespace && matchFunction)) {
                this.events[name].push(namespacedFunc);
              }
            }
            if (this.events[name].length === 0) {
              delete this.events[name];
            }
          }
        }
      }
      return null;
    };
    HollaBack.prototype.trigger = function() {
      var args, eventName, funcNamespace, identifiers, namespaces, _event, _i, _len, _ref;
      _event = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
      if (_event != null) {
        if (_event[0] === '.' || _event.indexOf(' ') > -1) {
          throw 'IllegalTrigger';
        }
        identifiers = _event.split('.');
        eventName = identifiers[0];
        namespaces = identifiers.slice(1, (identifiers.length - 1 + 1) || 9e9);
        if (this.events[eventName] != null) {
          _ref = this.events[eventName];
          for (_i = 0, _len = _ref.length; _i < _len; _i++) {
            funcNamespace = _ref[_i];
            if (this.functionInNamepspace(funcNamespace, namespaces, true)) {
              funcNamespace[0].apply(this, args);
            }
          }
        }
      }
      return null;
    };
    HollaBack.prototype.functionInNamepspace = function(listenerFunction, namespaces, strict) {
      var i, isInNameSpace;
      if (namespaces.length === 0 || listenerFunction.length === 1) {
        return true;
      }
      if (strict) {
        i = 1;
        isInNameSpace = true;
        while (i < listenerFunction.length) {
          isInNameSpace = namespaces.indexOf(listenerFunction[i]) > -1;
          if (isInNameSpace) {
            i++;
          } else {
            i = listenerFunction.length;
          }
        }
      } else {
        i = 0;
        isInNameSpace = false;
        while (i < namespaces.length && !isInNameSpace) {
          isInNameSpace = listenerFunction.indexOf(namespaces[i]) > -1;
          i++;
        }
      }
      return isInNameSpace;
    };
    return HollaBack;
  })();
  if (typeof window != "undefined" && window !== null) {
    window.HollaBack = HollaBack;
  } else {
    module.exports = HollaBack;
  }
}).call(this);


text:
package io.realm;

import androidx.test.annotation.UiThreadTest;
import androidx.test.rule.UiThreadTestRule;

import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.util.Arrays;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.util.concurrent.CountDownLatch;

import io.realm.entities.AllJavaTypes;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

@RunWith(Parameterized.class)
public class OrderedRealmCollectionIteratorTests extends CollectionTests {

    private static final int TEST_SIZE = 10;

    @Rule
    public final UiThreadTestRule uiThreadTestRule = new UiThreadTestRule();
    @Rule
    public final TestRealmConfigurationFactory configFactory = new TestRealmConfigurationFactory();
    @Rule
    public final ExpectedException thrown = ExpectedException.none();

    private final CollectionClass collectionClass;
    private Realm realm;
    private OrderedRealmCollection<AllJavaTypes> collection;

    @Parameterized.Parameters(name = "{0}")
    public static List<CollectionClass> data() {
        return Arrays.asList(CollectionClass.values());
    }

    public OrderedRealmCollectionIteratorTests(CollectionClass collectionType) {
        this.collectionClass = collectionType;
    }

    @Before
    public void setup() {
        realm = Realm.getInstance(configFactory.createConfiguration());
        collection = createCollection(realm, collectionClass, TEST_SIZE);
    }

    @After
    public void tearDown() {
        realm.close();
    }

    private OrderedRealmCollection<AllJavaTypes> createCollection(Realm realm, CollectionClass collectionClass, int sampleSize) {
        OrderedRealmCollection<AllJavaTypes> orderedCollection;

        switch (collectionClass) {
            case REALMRESULTS_SNAPSHOT_LIST_BASE:
            case MANAGED_REALMLIST:
                boolean isEmpty = (sampleSize == 0);
                int newSampleSize = (isEmpty) ? 2 : sampleSize;
                populateRealm(realm, newSampleSize);
                orderedCollection = realm.where(AllJavaTypes.class)
                        .equalTo(AllJavaTypes.FIELD_LONG, isEmpty ? 1 : 0)
                        .findFirst()
                        .getFieldList();
                break;

            case UNMANAGED_REALMLIST:
                populateRealm(realm, sampleSize);
                RealmResults<AllJavaTypes> objects = realm.where(AllJavaTypes.class)
                        .sort(AllJavaTypes.FIELD_LONG, Sort.ASCENDING)
                        .findAll();
                RealmList<AllJavaTypes> inMemoryList = new RealmList<AllJavaTypes>();
                inMemoryList.addAll(objects);
                return inMemoryList;

            case REALMRESULTS_SNAPSHOT_RESULTS_BASE:
            case REALMRESULTS:
                populateRealm(realm, sampleSize);
                orderedCollection = realm.where(AllJavaTypes.class)
                        .sort(AllJavaTypes.FIELD_LONG, Sort.ASCENDING)
                        .findAll();
                break;

            default:
                throw new AssertionError("Unsupported class: " + collectionClass);
        }
        if (isSnapshot(collectionClass)) {
            orderedCollection = orderedCollection.createSnapshot();
        }
        return orderedCollection;
    }

    private void createNewObject() {
        Number currentMax = realm.where(AllJavaTypes.class).max(AllJavaTypes.FIELD_ID);
        long nextId = 0;
        if (currentMax != null) {
            nextId = currentMax.longValue() + 1;
        }

        realm.beginTransaction();
        realm.createObject(AllJavaTypes.class, nextId);
        realm.commitTransaction();
    }

    /**
     * Helper method for checking if the unit test isn't supported for the current collectionClass.
     *
     * @param unsupportedTypes list of unsupported test types
     * @return {@code true} if the unit test should be aborted, {@code false} if it should continue.
     */
    private boolean skipTest(CollectionClass... unsupportedTypes) {
        //noinspection ForLoopReplaceableByForEach
        for (int i = 0; i < unsupportedTypes.length; i++) {
            if (unsupportedTypes[i].equals(collectionClass)) {
                return true;
            }
        }
        return false;
    }

    private void assertResultsOrSnapshot() {
        if (collectionClass != CollectionClass.REALMRESULTS && !isSnapshot(collectionClass))  {
            fail("Collection class " + collectionClass + "is not results or snapshot.");
        }
    }

    private void assertRealmList() {
        if (collectionClass != CollectionClass.UNMANAGED_REALMLIST &&
                collectionClass != CollectionClass.MANAGED_REALMLIST)  {
            fail("Collection class " + collectionClass + "is not RealmList.");
        }
    }

    @Test
    public void iterator() {
        Iterator<AllJavaTypes> it = collection.iterator();
        int i = 0;
        while (it.hasNext()) {
            AllJavaTypes item = it.next();
            assertEquals("Failed at index: " + i, i, item.getFieldLong());
            i++;
        }
        assertEquals(TEST_SIZE, collection.size());
        assertEquals(TEST_SIZE, i);
    }

    @Test
    public void iterator_empty() {
        collection = createCollection(realm, collectionClass, 0);
        Iterator<AllJavaTypes> it = collection.iterator();
        assertFalse(it.hasNext());
        assertEquals(0, collection.size());
    }

    @Test
    public void iterator_oneElement() {
        collection = createCollection(realm, collectionClass, 1);
        Iterator<AllJavaTypes> it = collection.iterator();
        //noinspection WhileLoopReplaceableByForEach
        int i = 0;
        while (it.hasNext()) {
            AllJavaTypes item = it.next();
            assertEquals(0, item.getFieldLong());
            i++;
        }
        assertEquals(1, collection.size());
        assertEquals(1, i);
    }

    @Test
    public void iterator_unrelatedTransactionBeforeNextItem() {
        Iterator<AllJavaTypes> it = collection.iterator();
        int i = 0;
        while (it.hasNext()) {
            AllJavaTypes item = it.next();
            assertEquals("Failed at index: " + i, i, item.getFieldLong());
            i++;

            // Committing unrelated transactions while iterating should not effect the current iterator.
            createNewObject();
        }
    }

    @Test
    public void iterator_closedRealm_methodsThrows() {
        if (skipTest(CollectionClass.UNMANAGED_REALMLIST)) {
            return;
        }

        Iterator<AllJavaTypes> it = collection.iterator();
        realm.close();
        try {
            it.hasNext();
            fail();
        } catch (IllegalStateException ignored) {
        }

        try {
            it.next();
            fail();
        } catch (IllegalStateException ignored) {
        }

        try {
            it.remove();
            fail();
        } catch (IllegalStateException e) {
            assertEquals(CollectionClass.MANAGED_REALMLIST, collectionClass);
        } catch (UnsupportedOperationException e) {
            assertResultsOrSnapshot();
        }
    }

    @Test
    public void iterator_remove_beforeNext() {
        Iterator<AllJavaTypes> it = collection.iterator();
        realm.beginTransaction();

        try {
            it.remove();
            fail();
        } catch (UnsupportedOperationException e) {
            assertResultsOrSnapshot();
        } catch (IllegalStateException ignored) {
            assertRealmList();
        }
    }

    @Test
    public void iterator_remove() {
        Iterator<AllJavaTypes> it = collection.iterator();
        AllJavaTypes obj = it.next();
        assertEquals("test data 0", obj.getFieldString());
        realm.beginTransaction();

        try {
            it.remove();
        } catch (UnsupportedOperationException e) {
            // RealmResults doesn't support remove.
            assertResultsOrSnapshot();
            return;
        }

        // Unmanaged objects are always invalid, but cannot be GC'ed while we have a reference.
        // managed objects should not be deleted (= invalid).
        assertNotEquals(CollectionClass.REALMRESULTS, collectionClass);
        assertTrue(obj.isValid());
        assertEquals("test data 1", collection.iterator().next().getFieldString());
        assertEquals(TEST_SIZE - 1, collection.size());
    }

    @Test
    public void iterator_deleteManagedObjectIndirectly() {
        realm.beginTransaction();
        Iterator<AllJavaTypes> it = collection.iterator();
        it.next(); // First item is a cyclic reference to the entire graph, avoid deleting that.
        it.next().deleteFromRealm();
        realm.commitTransaction();

        switch (collectionClass) {
            // Snapshot
            case REALMRESULTS_SNAPSHOT_RESULTS_BASE:
            case REALMRESULTS_SNAPSHOT_LIST_BASE:
                assertFalse(collection.get(1).isValid());
                break;
            // Managed RealmLists are directly associated with their table. Thus any indirect deletion will
            // also remove it from the LinkView.
            case MANAGED_REALMLIST:
            case REALMRESULTS:
                assertEquals(TEST_SIZE - 1, collection.size());
                break;

            // Unmanaged collections are not affected by changes to Realm.
            case UNMANAGED_REALMLIST:
                assertEquals(TEST_SIZE, collection.size());
                break;

            default:
                fail();
        }
    }

    @Test
    public void iterator_removeCalledTwice() {
        if (skipTest(CollectionClass.REALMRESULTS, CollectionClass.REALMRESULTS_SNAPSHOT_LIST_BASE,
                CollectionClass.REALMRESULTS_SNAPSHOT_RESULTS_BASE)) {
            return; // remove() not supported by RealmResults.
        }

        Iterator<AllJavaTypes> it = collection.iterator();
        it.next();
        realm.beginTransaction();
        it.remove();

        thrown.expect(IllegalStateException.class);
        it.remove();
    }

    @Test
    public void listIterator_empty() {
        collection = createCollection(realm, collectionClass, 0);
        ListIterator<AllJavaTypes> it = collection.listIterator();

        assertFalse(it.hasPrevious());
        assertFalse(it.hasNext());
        assertEquals(0, it.nextIndex());
        assertEquals(-1, it.previousIndex());

        try {
            it.next();
            fail();
        } catch (NoSuchElementException ignored) {
        }

        try {
            it.previous();
            fail();
        } catch (NoSuchElementException ignored) {
        }
    }

    @Test
    public void listIterator_oneElement() {
        collection = createCollection(realm, collectionClass, 1);
        ListIterator<AllJavaTypes> it = collection.listIterator();

        // Tests beginning of the list.
        assertFalse(it.hasPrevious());
        assertTrue(it.hasNext());
        assertEquals(-1, it.previousIndex());
        assertEquals(0, it.nextIndex());

        // Tests end of the list.
        AllJavaTypes firstObject = it.next();
        assertEquals(0, firstObject.getFieldLong());
        assertTrue(it.hasPrevious());
        assertFalse(it.hasNext());
        assertEquals(0, it.previousIndex());
        assertEquals(1, it.nextIndex());
    }

    @Test
    public void listIterator_manyElements() {
        ListIterator<AllJavaTypes> it = collection.listIterator();

        // Tests beginning of the list.
        assertFalse(it.hasPrevious());
        assertTrue(it.hasNext());
        assertEquals(-1, it.previousIndex());
        assertEquals(0, it.nextIndex());

        // Tests 1st element in the list.
        AllJavaTypes firstObject = it.next();
        assertEquals(0, firstObject.getFieldLong());
        assertTrue(it.hasPrevious());
        assertEquals(0, it.previousIndex());

        // Moves to second last element.
        for (int i = 1; i < TEST_SIZE - 1; i++) {
            it.next();
        }
        assertTrue(it.hasPrevious());
        assertTrue(it.hasNext());
        assertEquals(TEST_SIZE - 1, it.nextIndex());

        // Tests end of the list.
        AllJavaTypes lastObject = it.next();
        assertEquals(TEST_SIZE - 1, lastObject.getFieldLong());
        assertTrue(it.hasPrevious());
        assertFalse(it.hasNext());
        assertEquals(TEST_SIZE, it.nextIndex());
    }

    @Test
    public void listIterator_defaultStartIndex() {
        ListIterator<AllJavaTypes> it1 = collection.listIterator(0);
        ListIterator<AllJavaTypes> it2 = collection.listIterator();

        assertEquals(it1.previousIndex(), it2.previousIndex());
        assertEquals(it1.nextIndex(), it2.nextIndex());
    }

    @Test
    public void listIterator_startIndex() {
        int i = TEST_SIZE / 2;
        ListIterator<AllJavaTypes> it = collection.listIterator(i);

        assertTrue(it.hasPrevious());
        assertTrue(it.hasNext());
        assertEquals(i - 1, it.previousIndex());
        assertEquals(i, it.nextIndex());
        AllJavaTypes nextObject = it.next();
        assertEquals(i, nextObject.getFieldLong());
    }

    @Test
    public void listIterator_remove_beforeNext() {
        Iterator<AllJavaTypes> it = collection.listIterator();
        realm.beginTransaction();

        try {
            it.remove();
            fail();
        } catch (IllegalStateException e) {
            assertRealmList();
        } catch (UnsupportedOperationException e) {
            assertResultsOrSnapshot();
        }
    }

    @Test
    public void listIterator_remove_calledTwice() {
        Iterator<AllJavaTypes> it = collection.listIterator();
        it.next();
        realm.beginTransaction();

        switch (collectionClass) {
            case MANAGED_REALMLIST:
            case UNMANAGED_REALMLIST:
                it.remove();
                thrown.expect(IllegalStateException.class);
                it.remove();
                break;
            case REALMRESULTS_SNAPSHOT_LIST_BASE:
            case REALMRESULTS_SNAPSHOT_RESULTS_BASE:
            case REALMRESULTS:
                try {
                    it.remove(); // Method not supported.
                    fail();
                } catch (UnsupportedOperationException ignored) {
                }
                break;
            default:
                fail("Unknown collection class: " + collectionClass);
        }
    }

    @Test
    public void listIterator_transactionBeforeNextItem() {
        Iterator<AllJavaTypes> it = collection.listIterator();
        int i = 0;
        while (it.hasNext()) {
            AllJavaTypes item = it.next();
            assertEquals("Failed at index: " + i, i, item.getFieldLong());
            i++;

            // Committing transactions while iterating should not effect the current iterator if on a looper thread.
            createNewObject();
        }
    }

    @Test
    public void listIterator_closedRealm_methods() {
        if (skipTest(CollectionClass.UNMANAGED_REALMLIST)) {
            return;
        }

        int location = TEST_SIZE / 2;
        ListIterator<AllJavaTypes> it = collection.listIterator(location);
        realm.close();

        try {
            assertEquals(location - 1, it.previousIndex());
        } catch (IllegalStateException e) {
            fail();
        }

        try {
            assertEquals(location, it.nextIndex());
        } catch (IllegalStateException e) {
            fail();
        }

        try {
            assertTrue(it.hasNext());
        } catch (IllegalStateException ignored) {
        }

        try {
            it.next();
            fail();
        } catch (IllegalStateException ignored) {
        }

        try {
            it.previous();
            fail();
        } catch (IllegalStateException ignored) {
        }

        try {
            it.remove();
            fail();
        } catch (IllegalStateException e) {
            assertRealmList();
        } catch (UnsupportedOperationException ignored) {
            assertResultsOrSnapshot();
        }
    }

    @Test
    public void listIterator_deleteManagedObjectIndirectly() {
        if (skipTest(CollectionClass.REALMRESULTS_SNAPSHOT_LIST_BASE,
                CollectionClass.REALMRESULTS_SNAPSHOT_RESULTS_BASE)) {
            return;
        }

        realm.beginTransaction();
        ListIterator<AllJavaTypes> it = collection.listIterator();
        it.next();
        it.next().deleteFromRealm();
        realm.commitTransaction();

        switch (collectionClass) {
            case MANAGED_REALMLIST:
            case REALMRESULTS:
                assertEquals(TEST_SIZE - 1, collection.size());
                break;
            case UNMANAGED_REALMLIST:
                assertEquals(TEST_SIZE, collection.size());
                break;
            default:
                fail();
                return;
        }
        it.previous();
        AllJavaTypes types = it.next(); // Iterator can still access the deleted object

        //noinspection SimplifiableConditionalExpression
        assertTrue(collectionClass == CollectionClass.MANAGED_REALMLIST ? types.isValid() : !types.isValid());
    }

    @Test
    public void listIterator_remove_realmList_doesNotDeleteObject() {
        if (skipTest(CollectionClass.REALMRESULTS, CollectionClass.REALMRESULTS_SNAPSHOT_LIST_BASE,
                CollectionClass.REALMRESULTS_SNAPSHOT_RESULTS_BASE)) {
            return;
        }
        ListIterator<AllJavaTypes> it = collection.listIterator();
        AllJavaTypes obj = it.next();
        assertEquals("test data 0", obj.getFieldString());
        realm.beginTransaction();
        it.remove();
        assertTrue(obj.isValid());
    }

    @Test
    public void listIterator_remove_nonRealmList_throwUnsupported() {
        if (skipTest(CollectionClass.MANAGED_REALMLIST, CollectionClass.UNMANAGED_REALMLIST)) {
           return;
        }
        ListIterator<AllJavaTypes> it = collection.listIterator();
        AllJavaTypes obj = it.next();
        assertEquals("test data 0", obj.getFieldString());
        realm.beginTransaction();
        thrown.expect(UnsupportedOperationException.class);
        it.remove();
    }

    @Test
    public void listIterator_set() {
        if (skipTest(CollectionClass.REALMRESULTS, CollectionClass.REALMRESULTS_SNAPSHOT_RESULTS_BASE,
                CollectionClass.REALMRESULTS_SNAPSHOT_LIST_BASE)) {
            return;
        }

        realm.beginTransaction();
        ListIterator<AllJavaTypes> it = collection.listIterator();

        // Calling set() before next() should throw.
        try {
            it.set(new AllJavaTypes());
            fail();
        } catch (IllegalStateException ignored) {
        }

        AllJavaTypes obj = it.next();
        assertEquals(0, obj.getFieldLong());
        it.set(new AllJavaTypes(42));

        it.next();
        it.previous(); // A big ListIterator WTF!, but it is by design.
        obj = it.previous();
        assertEquals(42, obj.getFieldLong());
    }

    @Test
    public void listIterator_add() {
        if (skipTest(CollectionClass.REALMRESULTS, CollectionClass.REALMRESULTS_SNAPSHOT_RESULTS_BASE,
                CollectionClass.REALMRESULTS_SNAPSHOT_LIST_BASE)) {
            return;
        }

        realm.beginTransaction();
        ListIterator<AllJavaTypes> it = collection.listIterator();

        // The element is inserted immediately before the element that would be returned by next(), if any, and after
        // the element that would be returned by previous(), if any. (If the list contains no elements, the new element
        // becomes the sole element on the list.)
        it.add(new AllJavaTypes(4242));
        AllJavaTypes obj = collection.first();
        assertNotNull(obj);
        assertEquals(4242, obj.getFieldLong());

        obj = it.next();
        assertEquals(0, obj.getFieldLong());
        it.add(new AllJavaTypes(42));
        obj = it.previous();
        assertEquals(42, obj.getFieldLong());
    }

    @Test
    public void listIterator_unsupportedMethods() {
        ListIterator<AllJavaTypes> it = collection.listIterator();
        try {
            it.remove();
            fail();
        } catch (UnsupportedOperationException e) {
            assertResultsOrSnapshot();
        } catch (IllegalStateException e) { // since next() was never called.
            assertRealmList();
        }

        try {
            it.add(null);
            if (collectionClass != CollectionClass.UNMANAGED_REALMLIST) {
                fail();
            }
        } catch (UnsupportedOperationException e) {
            assertResultsOrSnapshot();
        } catch (IllegalArgumentException e) {
            if (collectionClass == CollectionClass.UNMANAGED_REALMLIST) {
                fail();
            }
            assertRealmList();
        }

        try {
            it.set(new AllJavaTypes());
            fail();
        } catch (UnsupportedOperationException e) {
            assertResultsOrSnapshot();
        } catch (IllegalStateException e) { // since the collection is empty
            assertRealmList();
        }
    }

    @Test
    public void iterator_outsideChangeToSizeThrowsConcurrentModification() {
        if (skipTest(CollectionClass.REALMRESULTS, CollectionClass.REALMRESULTS_SNAPSHOT_RESULTS_BASE,
                CollectionClass.REALMRESULTS_SNAPSHOT_LIST_BASE)) {
            return;
        }

        // Tests all standard collection methods.
        for (CollectionMethod method : CollectionMethod.values()) {
            collection = createCollection(realm, collectionClass, TEST_SIZE);
            realm.beginTransaction();
            Iterator<AllJavaTypes> it = collection.iterator();
            switch (method) {
                case ADD_OBJECT: collection.add(new AllJavaTypes(TEST_SIZE)); break;
                case ADD_ALL_OBJECTS: collection.addAll(Collections.singletonList(new AllJavaTypes(TEST_SIZE))); break;
                case CLEAR: collection.clear(); break;
                case REMOVE_OBJECT: collection.remove(collection.get(0)); break;
                case REMOVE_ALL: collection.removeAll(Collections.singletonList(collection.get(0))); break;
                case RETAIN_ALL: collection.retainAll(Collections.singletonList(collection.get(0))); break;

                // Does not impact size, so does not trigger ConcurrentModificationException.
                case CONTAINS:
                case CONTAINS_ALL:
                case EQUALS:
                case HASHCODE:
                case IS_EMPTY:
                case ITERATOR:
                case SIZE:
                case TO_ARRAY:
                case TO_ARRAY_INPUT:
                    realm.cancelTransaction();
                    continue;
                default:
                    fail("Unknown method: " + method);
            }
            checkIteratorThrowsConcurrentModification(realm, method.toString(), it);
        }

        for (ListMethod method : ListMethod.values()) {
            collection = createCollection(realm, collectionClass, TEST_SIZE);
            realm.beginTransaction();
            Iterator<AllJavaTypes> it = collection.iterator();
            switch (method) {
                case ADD_INDEX: collection.add(0, new AllJavaTypes(TEST_SIZE)); break;
                case ADD_ALL_INDEX: collection.addAll(0, Collections.singleton(new AllJavaTypes(TEST_SIZE))); break;
                case REMOVE_INDEX: collection.remove(0); break;

                // Does not impact size, so does not trigger ConcurrentModificationException.
                case FIRST:
                case LAST:
                case GET_INDEX:
                case INDEX_OF:
                case LAST_INDEX_OF:
                case LIST_ITERATOR:
                case LIST_ITERATOR_INDEX:
                case SET:
                case SUBLIST:
                    realm.cancelTransaction();
                    continue;

                default:
                    fail("Unknown method: " + method);
            }
            checkIteratorThrowsConcurrentModification(realm, method.toString(), it);
        }
    }

    @Test
    public void iterator_outsideChangeToSizeThrowsConcurrentModification_managedCollection() {
        if (skipTest(CollectionClass.REALMRESULTS, CollectionClass.UNMANAGED_REALMLIST,
                CollectionClass.REALMRESULTS_SNAPSHOT_LIST_BASE, CollectionClass.REALMRESULTS_SNAPSHOT_RESULTS_BASE)) {
            return;
        }

        // Tests all RealmCollection methods.
        for (RealmCollectionMethod method : RealmCollectionMethod.values()) {
            collection = createCollection(realm, collectionClass, TEST_SIZE);
            realm.beginTransaction();
            collection.remove(0); // Removes object creating circular dependency which will crash deleteAll.
            Iterator<AllJavaTypes> it = collection.iterator();
            switch (method) {
                case DELETE_ALL_FROM_REALM:
                    collection.deleteAllFromRealm(); break;

                // Does not impact size, so does not trigger ConcurrentModificationException.
                case WHERE:
                case MIN:
                case MAX:
                case SUM:
                case AVERAGE:
                case MIN_DATE:
                case MAX_DATE:
                case IS_VALID:
                case IS_MANAGED:
                case IS_FROZEN:
                case FREEZE:
                    realm.cancelTransaction();
                    continue;

                default:
                    fail("Unknown method: " + method);
            }
            checkIteratorThrowsConcurrentModification(realm, method.toString(), it);
        }

        // Tests all OrderedRealmCollection methods.
        for (OrderedRealmCollectionMethod method : OrderedRealmCollectionMethod.values()) {
            collection = createCollection(realm, collectionClass, TEST_SIZE);
            realm.beginTransaction();
            Iterator<AllJavaTypes> it = collection.iterator();
            switch (method) {
                case DELETE_INDEX: collection.deleteFromRealm(0); break;
                case DELETE_FIRST: collection.deleteFirstFromRealm(); break;
                case DELETE_LAST: collection.deleteLastFromRealm(); break;

                // Does not impact size, so does not trigger ConcurrentModificationException.
                case SORT:
                case SORT_FIELD:
                case SORT_2FIELDS:
                case SORT_MULTI:
                case CREATE_SNAPSHOT:
                    realm.cancelTransaction();
                    continue;
                default:
                    fail("Unknown method: " + method);

            }
            checkIteratorThrowsConcurrentModification(realm, method.toString(), it);
        }
    }

    private void checkIteratorThrowsConcurrentModification(Realm realm, String method, Iterator<AllJavaTypes> it) {
        try {
            it.next();
            fail("Method should have thrown: " + method);
        } catch (ConcurrentModificationException ignored) {
        } catch (Exception e) {
            throw new RuntimeException("Method failed: " + method, e);
        } finally {
            realm.cancelTransaction();
        }
    }

    // Accessing RealmResults iterator after receving remote change notification will throw.
    // But it is valid operation for snapshot.
    @Test
    public void iterator_realmResultsThrowConcurrentModification_snapshotJustWorks() {
        if (skipTest(CollectionClass.MANAGED_REALMLIST, CollectionClass.UNMANAGED_REALMLIST)) {
            return;
        }

        // Verifies that ConcurrentModification is correctly detected on non-looper threads.
        Iterator<AllJavaTypes> it = collection.iterator();
        final CountDownLatch bgDone = new CountDownLatch(1);
        new Thread(new Runnable() {
            @Override
            public void run() {
                Realm bgRealm = Realm.getInstance(realm.getConfiguration());
                bgRealm.beginTransaction();
                bgRealm.createObject(AllJavaTypes.class, TEST_SIZE);
                bgRealm.commitTransaction();
                bgRealm.close();
                bgDone.countDown();
            }
        }).start();
        TestHelper.awaitOrFail(bgDone);
        realm.refresh();
        try {
            it.next();
            assertEquals(TEST_SIZE, collection.size());
        } catch (ConcurrentModificationException ignored) {
            assertEquals(collectionClass, CollectionClass.REALMRESULTS);
        }
    }

    @Test
    public void useCase_simpleIterator_modifyQueryResult_innerTransaction() {
        if (skipTest(CollectionClass.MANAGED_REALMLIST, CollectionClass.UNMANAGED_REALMLIST,
                CollectionClass.REALMRESULTS)) {
            return;
        }

        assertEquals(TEST_SIZE, collection.size());
        for (int i = 0; i < collection.size(); i++) {
            realm.beginTransaction();
            AllJavaTypes obj = collection.get(i);
            obj.setFieldLong(obj.getFieldLong() + TEST_SIZE);
            realm.commitTransaction();
        }

        // Verifies that all elements were modified.
        assertEquals(0, realm.where(AllJavaTypes.class).lessThan(AllJavaTypes.FIELD_LONG, TEST_SIZE).count());
    }

    @Test
    public void useCase_simpleIterator_modifyQueryResult_outerTransaction() {
        if (skipTest(CollectionClass.MANAGED_REALMLIST, CollectionClass.UNMANAGED_REALMLIST,
                CollectionClass.REALMRESULTS)) {
            return;
        }

        assertEquals(TEST_SIZE, collection.size());
        realm.beginTransaction();
        for (int i = 0; i < collection.size(); i++) {
            AllJavaTypes obj = collection.get(i);
            obj.setFieldLong(obj.getFieldLong() + TEST_SIZE);
        }
        realm.commitTransaction();

        // Verifies that all elements were modified.
        assertEquals(0, realm.where(AllJavaTypes.class).lessThan(AllJavaTypes.FIELD_LONG, TEST_SIZE).count());
    }

    @Test
    public void useCase_forEachIterator_modifyQueryResult_innerTransaction() {
        if (skipTest(CollectionClass.MANAGED_REALMLIST, CollectionClass.UNMANAGED_REALMLIST)) {
            return;
        }

        assertEquals(TEST_SIZE, collection.size());
        for (AllJavaTypes obj : collection) {
            realm.beginTransaction();
            obj.setFieldLong(obj.getFieldLong() + TEST_SIZE);
            realm.commitTransaction();
        }

        // Verifies that all elements were modified.
        assertEquals(0, realm.where(AllJavaTypes.class).lessThan(AllJavaTypes.FIELD_LONG, TEST_SIZE).count());
    }

    @Test
    public void useCase_forEachIterator_modifyQueryResult_outerTransaction() {
        if (skipTest(CollectionClass.MANAGED_REALMLIST, CollectionClass.UNMANAGED_REALMLIST)) {
            return;
        }

        assertEquals(TEST_SIZE, collection.size());
        realm.beginTransaction();
        for (AllJavaTypes obj : collection) {
            obj.setFieldLong(obj.getFieldLong() + TEST_SIZE);
        }
        realm.commitTransaction();

        // Verifies that all elements were modified.
        assertEquals(0, realm.where(AllJavaTypes.class).lessThan(AllJavaTypes.FIELD_LONG, TEST_SIZE).count());
    }

    @Test
    @UiThreadTest
    public void useCase_simpleIterator_modifyQueryResult_innerTransaction_looperThread() {
        if (skipTest(CollectionClass.MANAGED_REALMLIST, CollectionClass.UNMANAGED_REALMLIST,
                CollectionClass.REALMRESULTS)) {
            return;
        }

        assertEquals(TEST_SIZE, collection.size());
        for (int i = 0; i < collection.size(); i++) {
            realm.beginTransaction();
            AllJavaTypes obj = collection.get(i);
            obj.setFieldLong(obj.getFieldLong() + TEST_SIZE);
            realm.commitTransaction();
        }

        // Verifies that all elements were modified.
        assertEquals(0, realm.where(AllJavaTypes.class).lessThan(AllJavaTypes.FIELD_LONG, TEST_SIZE).count());
    }

    @Test
    @UiThreadTest
    public void useCase_simpleIterator_modifyQueryResult_outerTransaction_looperThread() {
        if (skipTest(CollectionClass.MANAGED_REALMLIST, CollectionClass.UNMANAGED_REALMLIST,
                CollectionClass.REALMRESULTS)) {
            return;
        }

        assertEquals(TEST_SIZE, collection.size());
        realm.beginTransaction();
        for (int i = 0; i < collection.size(); i++) {
            AllJavaTypes obj = collection.get(i);
            obj.setFieldLong(obj.getFieldLong() + TEST_SIZE);
        }
        realm.commitTransaction();

        // Verifies that all elements were modified.
        assertEquals(0, realm.where(AllJavaTypes.class).lessThan(AllJavaTypes.FIELD_LONG, TEST_SIZE).count());
    }

    @Test
    @UiThreadTest
    public void useCase_forEachIterator_modifyQueryResult_innerTransaction_looperThread() {
        if (skipTest(CollectionClass.MANAGED_REALMLIST, CollectionClass.UNMANAGED_REALMLIST)) {
            return;
        }

        assertEquals(TEST_SIZE, collection.size());
        for (AllJavaTypes obj : collection) {
            realm.beginTransaction();
            obj.setFieldLong(obj.getFieldLong() + TEST_SIZE);
            realm.commitTransaction();
        }

        // Verifies that all elements were modified.
        assertEquals(0, realm.where(AllJavaTypes.class).lessThan(AllJavaTypes.FIELD_LONG, TEST_SIZE).count());
    }

    @Test
    @UiThreadTest
    public void useCase_forEachIterator_modifyQueryResult_outerTransaction_looperThread() {
        if (skipTest(CollectionClass.MANAGED_REALMLIST, CollectionClass.UNMANAGED_REALMLIST)) {
            return;
        }

        assertEquals(TEST_SIZE, collection.size());
        realm.beginTransaction();
        for (AllJavaTypes obj : collection) {
            obj.setFieldLong(obj.getFieldLong() + TEST_SIZE);
        }
        realm.commitTransaction();

        // Verifies that all elements were modified.
        assertEquals(0, realm.where(AllJavaTypes.class).lessThan(AllJavaTypes.FIELD_LONG, TEST_SIZE).count());
    }
}


text:
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.diagnostic;

import com.intellij.openapi.diagnostic.IdeaLogRecordFormatter;
import com.intellij.openapi.diagnostic.Attachment;
import com.intellij.openapi.diagnostic.IdeaLoggingEvent;
import com.intellij.openapi.util.objectTree.ThrowableInterner;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class LogMessage extends AbstractMessage {
  private final Throwable myThrowable;
  private final String myMessage;
  private final List<Attachment> myAttachments;

  LogMessage(Throwable throwable, String message, List<Attachment> attachments) {
    myThrowable = ThrowableInterner.intern(throwable);

    String str = message;
    if (str != null && throwable.getMessage() != null) {
      str = StringUtil.trimStart(str, throwable.getMessage());
      if (str != message) {
        str = StringUtil.trimStart(str, ": ");
      }
    }
    if ("null".equals(str)) {
      str = null;
    }
    myMessage = StringUtil.nullize(str, true);

    myAttachments = new ArrayList<>(ContainerUtil.filter(attachments, attachment -> attachment != null));
  }

  @Override
  public @NotNull Throwable getThrowable() {
    return myThrowable;
  }

  @Override
  public @NotNull String getThrowableText() {
    return IdeaLogRecordFormatter.formatThrowable(myThrowable);
  }

  @Override
  public @NotNull String getMessage() {
    return myMessage != null ? myMessage : "";
  }

  @Override
  public @NotNull List<Attachment> getAllAttachments() {
    return Collections.unmodifiableList(myAttachments);
  }

  /** @deprecated pass all attachments to {@link #createEvent(Throwable, String, Attachment...)} */
  @Deprecated(forRemoval = true)
  public synchronized void addAttachment(@NotNull Attachment attachment) {
    myAttachments.add(attachment);
  }

  // factory methods

  /**
   * @param userMessage      user-friendly message description (short, single line if possible)
   * @param attachments      attachments that will be suggested to include to the report
   */
  public static IdeaLoggingEvent createEvent(@NotNull Throwable throwable, @Nullable String userMessage, Attachment @NotNull ... attachments) {
    AbstractMessage message = new LogMessage(throwable, userMessage, Arrays.asList(attachments));
    return new IdeaLoggingEvent(userMessage, throwable, message);
  }
}


text:
package edu.ur.ir.item;

import edu.ur.dao.CountableDAO;
import edu.ur.dao.CrudDAO;
import edu.ur.dao.NameListDAO;
import edu.ur.ir.item.ItemLink;

/**
 * Interface for saving an item link.
 *
 * @author Nathan Sarr
 *
 */
public interface ItemLinkDAO extends CountableDAO,
CrudDAO<ItemLink>, NameListDAO{}


text:
package iso20022

type ReferToFundOrderDesk1Code string


text:
from django.conf.urls import patterns, url
from django.views.generic import RedirectView

from mturk.views import external_incompatible, external_compatible, \
    external_task, admin_experiments, admin_preview_task, \
    admin_stats, admin_stats_table, admin_feedback, admin_pending_content, \
    admin_example, admin_example_ajax, admin_submission
from common.utils import todo_view

urlpatterns = patterns(
    '',

    ### PUBLIC

    url(r'^contribute/$', todo_view, name='mturk-contribute'),

    ### MTURK MARKETPLACE ("EXTERNAL")

    url(r'^external/incompatible/(?P<id>[-\w]+)/$',
        external_incompatible, name='mturk-external-incompatible'),

    url(r'^external/compatible/(?P<id>[-\w]+)/$',
        external_compatible, name='mturk-external-compatible'),

    url(r'^external/task/(?P<experiment_id>\d+)/$',
        external_task, name='mturk-external-task'),

    ### ADMIN

    url(r'^admin/$', RedirectView.as_view(url='/admin/experiments/', permanent=False)),

    url(r'^admin/experiments/$', admin_experiments, name='mturk-admin-experiments'),

    url(r'^admin/preview-task/(?P<experiment_id>\d+)/(?P<override>\w+)/$',
        admin_preview_task, name='mturk-admin-preview-task'),

    url(
        r'^admin/preview-task/(?P<experiment_id>\d+)/(?P<override>\w+)/(?P<hit_id>\w+)/$',
        admin_preview_task, name='mturk-admin-preview-task'),

    url(r'^admin/stats/$', admin_stats, name='mturk-admin-stats'),

    url(r'^admin/stats/(?P<experiment_slug>\w+)/table/$', admin_stats_table,
        name='mturk-admin-stats-table'),

    url(r'^admin/stats/(?P<experiment_slug>\w+)/$', admin_stats,
        name='mturk-admin-stats'),

    url(r'^admin/pending-content/$', admin_pending_content,
        name='mturk-admin-pending-content'),

    url(r'^admin/pending-content/(?P<experiment_slug>\w+)/(?P<filter_key>\w+)/$',
        admin_pending_content, name='mturk-admin-pending-content'),

    url(r'^admin/example/$', admin_example, name='mturk-admin-example'),

    url(r'^admin/example/ajax/$', admin_example_ajax,
        name='mturk-admin-example-ajax'),

    url(r'^admin/example/(?P<experiment_slug>\w+)/$',
        admin_example, name='mturk-admin-example'),

    url(r'^admin/feedback/$', admin_feedback,
        name='mturk-admin-feedback'),

    url(r'^admin/feedback/(?P<experiment_slug>\w+)/$', admin_feedback,
        name='mturk-admin-feedback'),

    url(r'^admin/submission/$', admin_submission,
        name='mturk-admin-submission'),

    url(r'^admin/submission/(?P<experiment_slug>\w+)/(?P<filter_key>\w+)/$',
        admin_submission, name='mturk-admin-submission'),
)


text:
package greycatTest.internal.task;

import greycat.ActionFunction;
import greycat.TaskContext;
import org.junit.Assert;
import org.junit.Test;

import static greycat.internal.task.CoreActions.*;
import static greycat.Tasks.*;

public class ActionReadVarTest extends AbstractActionTest {

    @Test
    public void test() {
        initGraph();
        newTask()
                .then(readIndex("nodes"))
                .then(defineAsGlobalVar("x"))
                .then(inject("uselessPayload"))
                .then(readVar("x"))
                .thenDo(new ActionFunction() {
                    @Override
                    public void eval(TaskContext ctx) {
                        Assert.assertEquals(ctx.resultAsNodes().get(0).get("name"), "n0");
                        Assert.assertEquals(ctx.resultAsNodes().get(1).get("name"), "n1");
                        Assert.assertEquals(ctx.resultAsNodes().get(2).get("name"), "root");
                    }
                })
                .execute(graph, null);
        removeGraph();
    }

    @Test
    public void testIndex() {
        initGraph();
        newTask()
                .then(readIndex("nodes"))
                .then(defineAsGlobalVar("x"))
                .then(inject("uselessPayload"))
                .then(readVar("x[0]"))
                .thenDo(new ActionFunction() {
                    @Override
                    public void eval(TaskContext ctx) {
                        Assert.assertEquals(ctx.resultAsNodes().get(0).get("name"), "n0");
                        Assert.assertEquals(1, ctx.resultAsNodes().size());
                    }
                })
                .execute(graph, null);
        removeGraph();
    }

}


text:
#ifndef TENSORFLOW_PLATFORM_STREAM_EXECUTOR_H_
#define TENSORFLOW_PLATFORM_STREAM_EXECUTOR_H_

#include "tensorflow/core/platform/platform.h"

#if defined(PLATFORM_GOOGLE)
#include "tensorflow/core/platform/google/stream_executor.h"
#else
#include "tensorflow/core/platform/default/stream_executor.h"
#endif

#endif  // TENSORFLOW_PLATFORM_STREAM_EXECUTOR_H_


text:
When(/^I open automationpractice website$/) do
  visit AutomationHomePage
end

And(/^I login using data from yml$/) do
  on(AutomationHomePage).sign_in.when_present(10).click
  on(LoginPage).login_yml
end

And(/^I login with username "([^"]*)" and password "([^"]*)"$/) do |username, password|
  on(AutomationHomePage).sign_in.when_present(10).click
  on(LoginPage).login(username,password)
end

Then(/^I verify that I successfully logged in by logging out$/) do
  on(AutomationHomePage).sign_out.when_present(10).click
end

Then(/^I hover on women menu item and click summer dresses$/) do
  expect(on(AutomationHomePage).sign_out.present?).to be_truthy
  on(AutomationHomePage::HeaderPage).menu_women.when_present(10).hover
  on(AutomationHomePage::HeaderPage::DressesPage).summer_dresses.when_present(10).click
  expect(on(SummerDressesCatalogPage).category_name.text.strip).to eql("SUMMER DRESSES")
end

Then(/^I add a summer dress to cart$/) do
  on(SummerDressesCatalogPage::PrintedSummerDress1).img_dress1.when_present(10).hover
  @unit_price = on(SummerDressesCatalogPage::PrintedSummerDress1).product_price.text
  on(SummerDressesCatalogPage::PrintedSummerDress1).add_cart_dress1.when_present(10).click
  on(SummerDressesCatalogPage::CartPopup).proceed_to_checkout.when_present(10).click

end

Then(/^verify the item and price$/) do
  expect(@unit_price).to eql(on(ShoppingCartSummaryPage).unit_price.text)
  on(ShoppingCartSummaryPage).proceed_to_checkout.click
end

Then(/^I verify the address and proceed$/) do
  expect(on(AddressPage).page_heading.when_present(10).text).to eql("ADDRESSES")
  on(AddressPage).message.set "Test message"
  on(AddressPage).proceed_to_checkout.click
end

Then(/^I verify shipping address and proceed$/) do
  expect(on(ShippingAddressPage).page_heading.when_present(10).text).to eql("SHIPPING")
  on(ShippingAddressPage).terms.set
  on(ShippingAddressPage).proceed_to_checkout.click
end

Then(/^I select payment method$/) do
  expect(on(PaymentMethodPage).page_heading.when_present(10).text).to eql("PLEASE CHOOSE YOUR PAYMENT METHOD")
  on(PaymentMethodPage).check.click
end

Then(/^I confirm the order$/) do
  expect(on(OrderSummaryPage).page_heading.when_present(10).text).to eql("ORDER SUMMARY")
  on(OrderSummaryPage).confirm_order.click
end

Then(/^I verify successful purchase$/) do
  expect(on(OrderConfirmationPage).page_heading.when_present(30).text).to eql("ORDER CONFIRMATION")
end


text:
import sys
from django.test import TestCase
from django.core.management import call_command
from django.utils.six import StringIO
from admintools.models import IssueResolverPatch, DataQualityIssue
from opencivicdata.core.models import (Person, Jurisdiction, Division,
                                       Organization, Membership,
                                       PersonContactDetail)
from admintools.resolvers.person import setup_person_resolver

class CommandsTestCase(TestCase):
    "Test `resolve issues` command"

    def test_resolve_issues_command(self):
        out = StringIO()
        sys.stout = out
        args = ['issues']
        call_command('resolve', *args, stdout=out)
        self.assertIn('Successfully Imported People Issue Resolver Patches'
                      ' into DB',
                      out.getvalue())

class PeoplePatchesTest(TestCase):

    def setUp(self):
        division = Division.objects.create(
            id='ocd-division/country:us', name='USA')
        jur = Jurisdiction.objects.create(
                id="ocd-division/country:us/state:mo",
                name="Missouri State Senate",
                url="http://www.senate.mo.gov",
                division=division,
            )
        Organization.objects.create(name="Democratic", jurisdiction=jur)

    def test_name_patches(self):
        jur = Jurisdiction.objects.get(id='ocd-division/country:us/state:mo')
        org = Organization.objects.get(name="Democratic")
        person = Person.objects.create(name="Wrong Name")
        Membership.objects.create(person=person, organization=org)
        IssueResolverPatch.objects.create(content_object=person,
                                          jurisdiction=jur,
                                          status='deprecated',
                                          old_value='Wrong Name',
                                          new_value='Garg',
                                          category='name',
                                          alert='error',
                                          applied_by='admin')
        IssueResolverPatch.objects.create(content_object=person,
                                          jurisdiction=jur,
                                          status='rejected',
                                          old_value='Wrong Name',
                                          new_value='Hitesh',
                                          category='name',
                                          alert='error',
                                          applied_by='admin')
        IssueResolverPatch.objects.create(content_object=person,
                                          jurisdiction=jur,
                                          status='approved',
                                          old_value='Wrong Name',
                                          new_value='Hitesh Garg',
                                          category='name',
                                          alert='error',
                                          applied_by='admin')
        setup_person_resolver()
        # getting updated object
        p = Person.objects.get(id=person.id)
        self.assertEqual(p.name, "Hitesh Garg")

    def test_image_patches(self):
        jur = Jurisdiction.objects.get(id='ocd-division/country:us/state:mo')
        org = Organization.objects.get(name="Democratic")
        person = Person.objects.create(name="Wrong Image",
                                       image="http://www.image.png")
        Membership.objects.create(person=person, organization=org)
        IssueResolverPatch.objects.create(content_object=person,
                                          jurisdiction=jur,
                                          status='rejected',
                                          old_value='http://www.image.png',
                                          new_value='http://www.ht.png',
                                          category='image',
                                          alert='error',
                                          applied_by='admin')
        IssueResolverPatch.objects.create(content_object=person,
                                          jurisdiction=jur,
                                          status='deprecated',
                                          old_value='http://www.image.png',
                                          new_value='http://www.rt.png',
                                          category='image',
                                          alert='error',
                                          applied_by='admin')
        IssueResolverPatch.objects.create(content_object=person,
                                          jurisdiction=jur,
                                          status='approved',
                                          old_value='http://www.image.png',
                                          new_value='http://www.right.png',
                                          category='image',
                                          alert='error',
                                          applied_by='admin')
        setup_person_resolver()
        # getting updated object
        p = Person.objects.get(id=person.id)
        self.assertEqual(p.image, "http://www.right.png")

    def test_address_patches(self):
        jur = Jurisdiction.objects.get(id='ocd-division/country:us/state:mo')
        org = Organization.objects.get(name="Democratic")
        person = Person.objects.create(name="Wrong Address")
        PersonContactDetail.objects.create(person=person, type='address',
                                           value="New York")
        PersonContactDetail.objects.create(person=person, type='address',
                                           value="Wyoming")
        Membership.objects.create(person=person, organization=org)
        IssueResolverPatch.objects.create(content_object=person,
                                          jurisdiction=jur,
                                          status='deprecated',
                                          old_value='New York',
                                          new_value='Ma',
                                          category='address',
                                          alert='error',
                                          applied_by='admin')
        IssueResolverPatch.objects.create(content_object=person,
                                          jurisdiction=jur,
                                          status='approved',
                                          old_value='New York',
                                          new_value='Maine',
                                          category='address',
                                          alert='error',
                                          applied_by='admin')
        IssueResolverPatch.objects.create(content_object=person,
                                          jurisdiction=jur,
                                          status='rejected',
                                          old_value='Wyoming',
                                          new_value='W',
                                          category='address',
                                          alert='error',
                                          applied_by='admin')
        IssueResolverPatch.objects.create(content_object=person,
                                          jurisdiction=jur,
                                          status='approved',
                                          old_value='Wyoming',
                                          new_value='WY',
                                          category='address',
                                          alert='error',
                                          applied_by='admin')
        setup_person_resolver()
        # getting updated object
        pc = PersonContactDetail.objects.filter(person=person)
        self.assertEqual(pc.filter(value="WY").count(), 1)
        self.assertEqual(pc.filter(value="Maine").count(), 1)

    def test_missing_voice_patches(self):
        jur = Jurisdiction.objects.get(id='ocd-division/country:us/state:mo')
        org = Organization.objects.get(name="Democratic")
        person = Person.objects.create(name="Missing Phone Number")
        Membership.objects.create(person=person, organization=org)
        IssueResolverPatch.objects.create(content_object=person,
                                          jurisdiction=jur,
                                          status='deprecated',
                                          new_value='321',
                                          category='voice',
                                          alert='warning',
                                          applied_by='admin')
        IssueResolverPatch.objects.create(content_object=person,
                                          jurisdiction=jur,
                                          status='approved',
                                          new_value='456',
                                          category='voice',
                                          alert='warning',
                                          applied_by='user')
        IssueResolverPatch.objects.create(content_object=person,
                                          jurisdiction=jur,
                                          status='rejected',
                                          new_value='753',
                                          category='voice',
                                          alert='warning',
                                          applied_by='admin')
        IssueResolverPatch.objects.create(content_object=person,
                                          jurisdiction=jur,
                                          status='approved',
                                          new_value='852',
                                          category='voice',
                                          alert='warning',
                                          applied_by='user')
        DataQualityIssue.objects.create(content_object=person,
                                        jurisdiction=jur,
                                        alert='warning',
                                        issue='person-missing-phone')
        setup_person_resolver()
        # getting updated object
        pc = PersonContactDetail.objects.filter(person=person)
        self.assertEqual(pc.filter(value='456').count(), 1)
        self.assertEqual(pc.filter(value='852').count(), 1)
        # make sure that DataQualityIssue has been deleted
        dqi = DataQualityIssue.objects.filter(object_id=person.id)
        self.assertQuerysetEqual(dqi, [])

    def test_email_patches(self):
        jur = Jurisdiction.objects.get(id='ocd-division/country:us/state:mo')
        org = Organization.objects.get(name="Democratic")
        person1 = Person.objects.create(name="Missing Email")
        person2 = Person.objects.create(name="Wrong Email")
        Membership.objects.create(person=person1, organization=org)
        Membership.objects.create(person=person2, organization=org)
        PersonContactDetail.objects.create(person=person2, type='email',
                                           value="wrong@gmail.com")
        IssueResolverPatch.objects.create(content_object=person1,
                                          jurisdiction=jur,
                                          status='deprecated',
                                          new_value='correct@gmail.com',
                                          category='email',
                                          alert='warning',
                                          applied_by='admin')
        IssueResolverPatch.objects.create(content_object=person1,
                                          jurisdiction=jur,
                                          status='approved',
                                          new_value='right@gmail.com',
                                          category='email',
                                          alert='warning',
                                          applied_by='user')
        IssueResolverPatch.objects.create(content_object=person2,
                                          jurisdiction=jur,
                                          status='rejected',
                                          old_value='wrong@gmail.com',
                                          new_value='xyz@gmail.com',
                                          category='email',
                                          alert='error',
                                          applied_by='user')
        IssueResolverPatch.objects.create(content_object=person2,
                                          jurisdiction=jur,
                                          status='approved',
                                          old_value='wrong@gmail.com',
                                          new_value='right@gmail.com',
                                          category='email',
                                          alert='error',
                                          applied_by='admin')
        DataQualityIssue.objects.create(content_object=person1,
                                        jurisdiction=jur,
                                        alert='warning',
                                        issue='person-missing-email')
        setup_person_resolver()
        # getting updated object
        pc1 = PersonContactDetail.objects.filter(person=person1)
        pc2 = PersonContactDetail.objects.filter(person=person2)
        self.assertEqual(pc1.filter(value='right@gmail.com').count(), 1)
        self.assertEqual(pc2.filter(value='right@gmail.com').count(), 1)
        # make sure that DataQualityIssue has been deleted
        dqi = DataQualityIssue.objects.filter(object_id=person1.id)
        self.assertQuerysetEqual(dqi, [])


text:
#define TC_M32R

#define LISTING_HEADER \
  (target_big_endian ? "M32R GAS" : "M32R GAS Little Endian")

/* The target BFD architecture.  */
#define TARGET_ARCH bfd_arch_m32r

/* The endianness of the target format may change based on command
   line arguments.  */
#define TARGET_FORMAT m32r_target_format()
extern const char *m32r_target_format (void);

/* Default to big endian.  */
#ifndef TARGET_BYTES_BIG_ENDIAN
#define TARGET_BYTES_BIG_ENDIAN 1
#endif

/* Call md_pcrel_from_section, not md_pcrel_from.  */
long md_pcrel_from_section (struct fix *, segT);
#define MD_PCREL_FROM_SECTION(FIX, SEC) md_pcrel_from_section(FIX, SEC)

/* Permit temporary numeric labels.  */
#define LOCAL_LABELS_FB 1

#define DIFF_EXPR_OK		/* .-foo gets turned into PC relative relocs.  */

/* We don't need to handle .word strangely.  */
#define WORKING_DOT_WORD

/* For 8 vs 16 vs 32 bit branch selection.  */
extern const struct relax_type md_relax_table[];
#define TC_GENERIC_RELAX_TABLE md_relax_table

extern long m32r_relax_frag (segT, fragS *, long);
#define md_relax_frag(segment, fragP, stretch) \
  m32r_relax_frag (segment, fragP, stretch)

/* Account for nop if 32 bit insn falls on odd halfword boundary.  */
#define TC_CGEN_MAX_RELAX(insn, len)	6

/* Fill in rs_align_code fragments.  */
extern void m32r_handle_align (fragS *);
#define HANDLE_ALIGN(f)  m32r_handle_align (f)

#define MAX_MEM_FOR_RS_ALIGN_CODE  (1 + 2 + 4)

/* Values passed to md_apply_fix don't include the symbol value.  */
#define MD_APPLY_SYM_VALUE(FIX) 0

#define md_apply_fix gas_cgen_md_apply_fix

#define tc_fix_adjustable(FIX) m32r_fix_adjustable (FIX)
bfd_boolean m32r_fix_adjustable (struct fix *);

/* After creating a fixup for an instruction operand, we need to check for
   HI16 relocs and queue them up for later sorting.  */
#define md_cgen_record_fixup_exp m32r_cgen_record_fixup_exp

#define TC_HANDLES_FX_DONE

extern int pic_code;

extern bfd_boolean m32r_fix_adjustable (struct fix *);

/* This arranges for gas/write.c to not apply a relocation if
   obj_fix_adjustable() says it is not adjustable.  */
#define TC_FIX_ADJUSTABLE(fixP) obj_fix_adjustable (fixP)

#define tc_frob_file_before_fix() m32r_frob_file ()
extern void m32r_frob_file (void);

/* No shared lib support, so we don't need to ensure externally
   visible symbols can be overridden.
#define EXTERN_FORCE_RELOC 0 */

/* When relaxing, we need to emit various relocs we otherwise wouldn't.  */
#define TC_FORCE_RELOCATION(fix) m32r_force_relocation (fix)
extern int m32r_force_relocation (struct fix *);

/* Ensure insns at labels are aligned to 32 bit boundaries.  */
int m32r_fill_insn (int);
#define TC_START_LABEL(ch, s, ptr)	(ch == ':' && m32r_fill_insn (0))

#define md_cleanup()               m32r_fill_insn (1)
#define md_elf_section_change_hook m32r_elf_section_change_hook
extern void m32r_elf_section_change_hook (void);

#define md_flush_pending_output()       m32r_flush_pending_output ()
extern void m32r_flush_pending_output (void);

#define elf_tc_final_processing 	m32r_elf_final_processing
extern void m32r_elf_final_processing (void);

#define md_parse_name(name, exprP, mode, nextcharP) \
  m32r_parse_name ((name), (exprP), (mode), (nextcharP))
extern int m32r_parse_name (char const *, expressionS *, enum expr_mode, char *);

/* This is used to construct expressions out of @GOTOFF, @PLT and @GOT
   symbols.  The relocation type is stored in X_md.  */
#define O_PIC_reloc O_md1

#define TC_CGEN_PARSE_FIX_EXP(opinfo, exp) \
  m32r_cgen_parse_fix_exp(opinfo, exp)
extern int m32r_cgen_parse_fix_exp (int, expressionS *);


text:
package net.glowstone.generator.populators.overworld;

import net.glowstone.generator.decorators.EntityDecorator;
import net.glowstone.generator.decorators.overworld.MushroomDecorator;
import net.glowstone.generator.decorators.overworld.TreeDecorator.TreeDecoration;
import net.glowstone.generator.objects.trees.BrownMushroomTree;
import net.glowstone.generator.objects.trees.RedMushroomTree;
import org.bukkit.Chunk;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Biome;
import org.bukkit.entity.EntityType;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Random;

public class MushroomFieldsPopulator extends BiomePopulator {

    private static final Biome[] BIOMES = {Biome.MUSHROOM_FIELDS, Biome.MUSHROOM_FIELD_SHORE};
    private static final TreeDecoration[] TREES = {new TreeDecoration(RedMushroomTree::new, 1),
        new TreeDecoration(BrownMushroomTree::new, 1)};

    protected final MushroomDecorator islandBrownMushroomDecorator = new MushroomDecorator(
        Material.BROWN_MUSHROOM);
    protected final MushroomDecorator islandRedMushroomDecorator = new MushroomDecorator(
        Material.RED_MUSHROOM);

    /**
     * Creates a populator for the mushroom fields biome.
     */
    public MushroomFieldsPopulator() {
        treeDecorator.setAmount(1);
        treeDecorator.setTrees(TREES);
        flowerDecorator.setAmount(0);
        tallGrassDecorator.setAmount(0);
        islandBrownMushroomDecorator.setAmount(1);
        islandBrownMushroomDecorator.setUseFixedHeightRange();
        islandBrownMushroomDecorator.setDensity(0.25D);
        islandRedMushroomDecorator.setAmount(1);
        islandRedMushroomDecorator.setDensity(0.125D);
        entityDecorators.clear();
        EntityDecorator mushroomDecorator = new EntityDecorator(EntityType.MUSHROOM_COW);
        mushroomDecorator.setGroupSize(4, 8);
        entityDecorators.add(mushroomDecorator);
    }

    @Override
    public Collection<Biome> getBiomes() {
        return Collections.unmodifiableList(Arrays.asList(BIOMES));
    }

    @Override
    public void populateOnGround(World world, Random random, Chunk chunk) {
        super.populateOnGround(world, random, chunk);
        islandBrownMushroomDecorator.populate(world, random, chunk);
        islandRedMushroomDecorator.populate(world, random, chunk);
    }
}