text:
#include "mali_pp_job.h"
#include "mali_pp.h"
#include "mali_hw_core.h"
#include "mali_group.h"
#include "regs/mali_200_regs.h"
#include "mali_kernel_common.h"
#include "mali_kernel_core.h"
#if defined(CONFIG_MALI400_PROFILING)
#include "mali_osk_profiling.h"
#endif

/* Number of frame registers on Mali-200 */
#define MALI_PP_MALI200_NUM_FRAME_REGISTERS ((0x04C/4)+1)
/* Number of frame registers on Mali-300 and later */
#define MALI_PP_MALI400_NUM_FRAME_REGISTERS ((0x058/4)+1)

static struct mali_pp_core* mali_global_pp_cores[MALI_MAX_NUMBER_OF_PP_CORES];
static u32 mali_global_num_pp_cores = 0;

/* Interrupt handlers */
static void mali_pp_irq_probe_trigger(void *data);
static _mali_osk_errcode_t mali_pp_irq_probe_ack(void *data);

struct mali_pp_core *mali_pp_create(const _mali_osk_resource_t *resource, struct mali_group *group, mali_bool is_virtual)
{
	struct mali_pp_core* core = NULL;

	MALI_DEBUG_PRINT(2, ("Mali PP: Creating Mali PP core: %s\n", resource->description));
	MALI_DEBUG_PRINT(2, ("Mali PP: Base address of PP core: 0x%x\n", resource->base));

	if (mali_global_num_pp_cores >= MALI_MAX_NUMBER_OF_PP_CORES)
	{
		MALI_PRINT_ERROR(("Mali PP: Too many PP core objects created\n"));
		return NULL;
	}

	core = _mali_osk_malloc(sizeof(struct mali_pp_core));
	if (NULL != core)
	{
		core->core_id = mali_global_num_pp_cores;
		core->counter_src0_used = MALI_HW_CORE_NO_COUNTER;
		core->counter_src1_used = MALI_HW_CORE_NO_COUNTER;

		if (_MALI_OSK_ERR_OK == mali_hw_core_create(&core->hw_core, resource, MALI200_REG_SIZEOF_REGISTER_BANK))
		{
			_mali_osk_errcode_t ret;

			if (!is_virtual)
			{
				ret = mali_pp_reset(core);
			}
			else
			{
				ret = _MALI_OSK_ERR_OK;
			}

			if (_MALI_OSK_ERR_OK == ret)
			{
				ret = mali_group_add_pp_core(group, core);
				if (_MALI_OSK_ERR_OK == ret)
				{
					/* Setup IRQ handlers (which will do IRQ probing if needed) */
					MALI_DEBUG_ASSERT(!is_virtual || -1 != resource->irq);

					core->irq = _mali_osk_irq_init(resource->irq,
					                               mali_group_upper_half_pp,
					                               group,
					                               mali_pp_irq_probe_trigger,
					                               mali_pp_irq_probe_ack,
					                               core,
					                               "mali_pp_irq_handlers");
					if (NULL != core->irq)
					{
						mali_global_pp_cores[mali_global_num_pp_cores] = core;
						mali_global_num_pp_cores++;

						return core;
					}
					else
					{
						MALI_PRINT_ERROR(("Mali PP: Failed to setup interrupt handlers for PP core %s\n", core->hw_core.description));
					}
					mali_group_remove_pp_core(group);
				}
				else
				{
					MALI_PRINT_ERROR(("Mali PP: Failed to add core %s to group\n", core->hw_core.description));
				}
			}
			mali_hw_core_delete(&core->hw_core);
		}

		_mali_osk_free(core);
	}
	else
	{
		MALI_PRINT_ERROR(("Mali PP: Failed to allocate memory for PP core\n"));
	}

	return NULL;
}

void mali_pp_delete(struct mali_pp_core *core)
{
	u32 i;

	MALI_DEBUG_ASSERT_POINTER(core);

	_mali_osk_irq_term(core->irq);
	mali_hw_core_delete(&core->hw_core);

	/* Remove core from global list */
	for (i = 0; i < MALI_MAX_NUMBER_OF_PP_CORES; i++)
	{
		if (mali_global_pp_cores[i] == core)
		{
			mali_global_pp_cores[i] = NULL;
			mali_global_num_pp_cores--;
			break;
		}
	}

	_mali_osk_free(core);
}

void mali_pp_stop_bus(struct mali_pp_core *core)
{
	MALI_DEBUG_ASSERT_POINTER(core);
	/* Will only send the stop bus command, and not wait for it to complete */
	mali_hw_core_register_write(&core->hw_core, MALI200_REG_ADDR_MGMT_CTRL_MGMT, MALI200_REG_VAL_CTRL_MGMT_STOP_BUS);
}

_mali_osk_errcode_t mali_pp_stop_bus_wait(struct mali_pp_core *core)
{
	int i;

	MALI_DEBUG_ASSERT_POINTER(core);

	/* Send the stop bus command. */
	mali_pp_stop_bus(core);

	/* Wait for bus to be stopped */
	for (i = 0; i < MALI_REG_POLL_COUNT_FAST; i++)
	{
		if (mali_hw_core_register_read(&core->hw_core, MALI200_REG_ADDR_MGMT_STATUS) & MALI200_REG_VAL_STATUS_BUS_STOPPED)
			break;
	}

	if (MALI_REG_POLL_COUNT_FAST == i)
	{
		MALI_PRINT_ERROR(("Mali PP: Failed to stop bus on %s. Status: 0x%08x\n", core->hw_core.description, mali_hw_core_register_read(&core->hw_core, MALI200_REG_ADDR_MGMT_STATUS)));
		return _MALI_OSK_ERR_FAULT;
	}
	return _MALI_OSK_ERR_OK;
}

/* Frame register reset values.
 * Taken from the Mali400 TRM, 3.6. Pixel processor control register summary */
static const u32 mali_frame_registers_reset_values[_MALI_PP_MAX_FRAME_REGISTERS] =
{
	0x0, /* Renderer List Address Register */
	0x0, /* Renderer State Word Base Address Register */
	0x0, /* Renderer Vertex Base Register */
	0x2, /* Feature Enable Register */
	0x0, /* Z Clear Value Register */
	0x0, /* Stencil Clear Value Register */
	0x0, /* ABGR Clear Value 0 Register */
	0x0, /* ABGR Clear Value 1 Register */
	0x0, /* ABGR Clear Value 2 Register */
	0x0, /* ABGR Clear Value 3 Register */
	0x0, /* Bounding Box Left Right Register */
	0x0, /* Bounding Box Bottom Register */
	0x0, /* FS Stack Address Register */
	0x0, /* FS Stack Size and Initial Value Register */
	0x0, /* Reserved */
	0x0, /* Reserved */
	0x0, /* Origin Offset X Register */
	0x0, /* Origin Offset Y Register */
	0x75, /* Subpixel Specifier Register */
	0x0, /* Tiebreak mode Register */
	0x0, /* Polygon List Format Register */
	0x0, /* Scaling Register */
	0x0 /* Tilebuffer configuration Register */
};

/* WBx register reset values */
static const u32 mali_wb_registers_reset_values[_MALI_PP_MAX_WB_REGISTERS] =
{
	0x0, /* WBx Source Select Register */
	0x0, /* WBx Target Address Register */
	0x0, /* WBx Target Pixel Format Register */
	0x0, /* WBx Target AA Format Register */
	0x0, /* WBx Target Layout */
	0x0, /* WBx Target Scanline Length */
	0x0, /* WBx Target Flags Register */
	0x0, /* WBx MRT Enable Register */
	0x0, /* WBx MRT Offset Register */
	0x0, /* WBx Global Test Enable Register */
	0x0, /* WBx Global Test Reference Value Register */
	0x0  /* WBx Global Test Compare Function Register */
};

/* Performance Counter 0 Enable Register reset value */
static const u32 mali_perf_cnt_enable_reset_value = 0;

_mali_osk_errcode_t mali_pp_hard_reset(struct mali_pp_core *core)
{
	/* Bus must be stopped before calling this function */
	const u32 reset_invalid_value = 0xC0FFE000;
	const u32 reset_check_value = 0xC01A0000;
	int i;

	MALI_DEBUG_ASSERT_POINTER(core);
	MALI_DEBUG_PRINT(2, ("Mali PP: Hard reset of core %s\n", core->hw_core.description));

	/* Set register to a bogus value. The register will be used to detect when reset is complete */
	mali_hw_core_register_write_relaxed(&core->hw_core, MALI200_REG_ADDR_MGMT_WRITE_BOUNDARY_LOW, reset_invalid_value);
	mali_hw_core_register_write_relaxed(&core->hw_core, MALI200_REG_ADDR_MGMT_INT_MASK, MALI200_REG_VAL_IRQ_MASK_NONE);

	/* Force core to reset */
	mali_hw_core_register_write(&core->hw_core, MALI200_REG_ADDR_MGMT_CTRL_MGMT, MALI200_REG_VAL_CTRL_MGMT_FORCE_RESET);

	/* Wait for reset to be complete */
	for (i = 0; i < MALI_REG_POLL_COUNT_FAST; i++)
	{
		mali_hw_core_register_write(&core->hw_core, MALI200_REG_ADDR_MGMT_WRITE_BOUNDARY_LOW, reset_check_value);
		if (reset_check_value == mali_hw_core_register_read(&core->hw_core, MALI200_REG_ADDR_MGMT_WRITE_BOUNDARY_LOW))
		{
			break;
		}
	}

	if (MALI_REG_POLL_COUNT_FAST == i)
	{
		MALI_PRINT_ERROR(("Mali PP: The hard reset loop didn't work, unable to recover\n"));
	}

	mali_hw_core_register_write(&core->hw_core, MALI200_REG_ADDR_MGMT_WRITE_BOUNDARY_LOW, 0x00000000); /* set it back to the default */
	/* Re-enable interrupts */
	mali_hw_core_register_write(&core->hw_core, MALI200_REG_ADDR_MGMT_INT_CLEAR, MALI200_REG_VAL_IRQ_MASK_ALL);
	mali_hw_core_register_write(&core->hw_core, MALI200_REG_ADDR_MGMT_INT_MASK, MALI200_REG_VAL_IRQ_MASK_USED);

	return _MALI_OSK_ERR_OK;
}

void mali_pp_reset_async(struct mali_pp_core *core)
{
	MALI_DEBUG_ASSERT_POINTER(core);

	MALI_DEBUG_PRINT(4, ("Mali PP: Reset of core %s\n", core->hw_core.description));

	mali_hw_core_register_write(&core->hw_core, MALI200_REG_ADDR_MGMT_INT_MASK, 0); /* disable the IRQs */
	mali_hw_core_register_write(&core->hw_core, MALI200_REG_ADDR_MGMT_INT_RAWSTAT, MALI200_REG_VAL_IRQ_MASK_ALL);
	mali_hw_core_register_write(&core->hw_core, MALI200_REG_ADDR_MGMT_CTRL_MGMT, MALI400PP_REG_VAL_CTRL_MGMT_SOFT_RESET);
}

_mali_osk_errcode_t mali_pp_reset_wait(struct mali_pp_core *core)
{
	int i;
	u32 rawstat = 0;

	/* TODO: For virtual Mali-450 core, check that PP active in STATUS is 0 (this must be initiated from group) */

	for (i = 0; i < MALI_REG_POLL_COUNT_FAST; i++)
	{
		rawstat = mali_hw_core_register_read(&core->hw_core, MALI200_REG_ADDR_MGMT_INT_RAWSTAT);
		if (rawstat & MALI400PP_REG_VAL_IRQ_RESET_COMPLETED)
		{
			break;
		}
	}

	if (i == MALI_REG_POLL_COUNT_FAST)
	{
		MALI_PRINT_ERROR(("Mali PP: Failed to reset core %s, rawstat: 0x%08x\n",
		                 core->hw_core.description, rawstat));
		return _MALI_OSK_ERR_FAULT;
	}

	/* Re-enable interrupts */
	mali_hw_core_register_write(&core->hw_core, MALI200_REG_ADDR_MGMT_INT_CLEAR, MALI200_REG_VAL_IRQ_MASK_ALL);
	mali_hw_core_register_write(&core->hw_core, MALI200_REG_ADDR_MGMT_INT_MASK, MALI200_REG_VAL_IRQ_MASK_USED);

	return _MALI_OSK_ERR_OK;
}

_mali_osk_errcode_t mali_pp_reset(struct mali_pp_core *core)
{
	mali_pp_reset_async(core);
	return mali_pp_reset_wait(core);
}

void mali_pp_job_start(struct mali_pp_core *core, struct mali_pp_job *job, u32 sub_job, mali_bool restart_virtual)
{
	u32 num_frame_registers;
	u32 relative_address;
	u32 start_index;
	u32 nr_of_regs;
	u32 *frame_registers = mali_pp_job_get_frame_registers(job);
	u32 *wb0_registers = mali_pp_job_get_wb0_registers(job);
	u32 *wb1_registers = mali_pp_job_get_wb1_registers(job);
	u32 *wb2_registers = mali_pp_job_get_wb2_registers(job);
	core->counter_src0_used = mali_pp_job_get_perf_counter_src0(job);
	core->counter_src1_used = mali_pp_job_get_perf_counter_src1(job);

	MALI_DEBUG_ASSERT_POINTER(core);

	/* Write frame registers */
	num_frame_registers = (_MALI_PRODUCT_ID_MALI200 == mali_kernel_core_get_product_id()) ? MALI_PP_MALI200_NUM_FRAME_REGISTERS : MALI_PP_MALI400_NUM_FRAME_REGISTERS;

	/*
	 * There are two frame registers which are different for each sub job:
	 * 1. The Renderer List Address Register (MALI200_REG_ADDR_FRAME)
	 * 2. The FS Stack Address Register (MALI200_REG_ADDR_STACK)
	 */
	mali_hw_core_register_write_relaxed_conditional(&core->hw_core, MALI200_REG_ADDR_FRAME, mali_pp_job_get_addr_frame(job, sub_job), mali_frame_registers_reset_values[MALI200_REG_ADDR_FRAME / sizeof(u32)]);

	/* For virtual jobs, the stack address shouldn't be broadcast but written individually */
	if (!mali_pp_job_is_virtual(job) || restart_virtual)
	{
		mali_hw_core_register_write_relaxed_conditional(&core->hw_core, MALI200_REG_ADDR_STACK, mali_pp_job_get_addr_stack(job, sub_job), mali_frame_registers_reset_values[MALI200_REG_ADDR_STACK / sizeof(u32)]);
	}

	/* Write registers between MALI200_REG_ADDR_FRAME and MALI200_REG_ADDR_STACK */
	relative_address = MALI200_REG_ADDR_RSW;
	start_index = MALI200_REG_ADDR_RSW / sizeof(u32);
	nr_of_regs = (MALI200_REG_ADDR_STACK - MALI200_REG_ADDR_RSW) / sizeof(u32);

	mali_hw_core_register_write_array_relaxed_conditional(&core->hw_core,
	        relative_address, &frame_registers[start_index],
	        nr_of_regs, &mali_frame_registers_reset_values[start_index]);

	/* MALI200_REG_ADDR_STACK_SIZE */
	relative_address = MALI200_REG_ADDR_STACK_SIZE;
	start_index = MALI200_REG_ADDR_STACK_SIZE / sizeof(u32);

	mali_hw_core_register_write_relaxed_conditional(&core->hw_core,
	        relative_address, frame_registers[start_index],
	        mali_frame_registers_reset_values[start_index]);

	/* Skip 2 reserved registers */

	/* Write remaining registers */
	relative_address = MALI200_REG_ADDR_ORIGIN_OFFSET_X;
	start_index = MALI200_REG_ADDR_ORIGIN_OFFSET_X / sizeof(u32);
	nr_of_regs = num_frame_registers - MALI200_REG_ADDR_ORIGIN_OFFSET_X / sizeof(u32);

	mali_hw_core_register_write_array_relaxed_conditional(&core->hw_core,
	        relative_address, &frame_registers[start_index],
	        nr_of_regs, &mali_frame_registers_reset_values[start_index]);

	/* Write WBx registers */
	if (wb0_registers[0]) /* M200_WB0_REG_SOURCE_SELECT register */
	{
		mali_hw_core_register_write_array_relaxed_conditional(&core->hw_core, MALI200_REG_ADDR_WB0, wb0_registers, _MALI_PP_MAX_WB_REGISTERS, mali_wb_registers_reset_values);
	}

	if (wb1_registers[0]) /* M200_WB1_REG_SOURCE_SELECT register */
	{
		mali_hw_core_register_write_array_relaxed_conditional(&core->hw_core, MALI200_REG_ADDR_WB1, wb1_registers, _MALI_PP_MAX_WB_REGISTERS, mali_wb_registers_reset_values);
	}

	if (wb2_registers[0]) /* M200_WB2_REG_SOURCE_SELECT register */
	{
		mali_hw_core_register_write_array_relaxed_conditional(&core->hw_core, MALI200_REG_ADDR_WB2, wb2_registers, _MALI_PP_MAX_WB_REGISTERS, mali_wb_registers_reset_values);
	}

	if (MALI_HW_CORE_NO_COUNTER != core->counter_src0_used)
	{
		mali_hw_core_register_write_relaxed(&core->hw_core, MALI200_REG_ADDR_MGMT_PERF_CNT_0_SRC, core->counter_src0_used);
		mali_hw_core_register_write_relaxed_conditional(&core->hw_core, MALI200_REG_ADDR_MGMT_PERF_CNT_0_ENABLE, MALI200_REG_VAL_PERF_CNT_ENABLE, mali_perf_cnt_enable_reset_value);
	}
	if (MALI_HW_CORE_NO_COUNTER != core->counter_src1_used)
	{
		mali_hw_core_register_write_relaxed(&core->hw_core, MALI200_REG_ADDR_MGMT_PERF_CNT_1_SRC, core->counter_src1_used);
		mali_hw_core_register_write_relaxed_conditional(&core->hw_core, MALI200_REG_ADDR_MGMT_PERF_CNT_1_ENABLE, MALI200_REG_VAL_PERF_CNT_ENABLE, mali_perf_cnt_enable_reset_value);
	}

	MALI_DEBUG_PRINT(3, ("Mali PP: Starting job 0x%08X part %u/%u on PP core %s\n", job, sub_job + 1, mali_pp_job_get_sub_job_count(job), core->hw_core.description));

	/* Adding barrier to make sure all rester writes are finished */
	_mali_osk_write_mem_barrier();

	/* This is the command that starts the core. */
	mali_hw_core_register_write_relaxed(&core->hw_core, MALI200_REG_ADDR_MGMT_CTRL_MGMT, MALI200_REG_VAL_CTRL_MGMT_START_RENDERING);

	/* Adding barrier to make sure previous rester writes is finished */
	_mali_osk_write_mem_barrier();
}

u32 mali_pp_core_get_version(struct mali_pp_core *core)
{
	MALI_DEBUG_ASSERT_POINTER(core);
	return mali_hw_core_register_read(&core->hw_core, MALI200_REG_ADDR_MGMT_VERSION);
}

struct mali_pp_core* mali_pp_get_global_pp_core(u32 index)
{
	if (MALI_MAX_NUMBER_OF_PP_CORES > index)
	{
		return mali_global_pp_cores[index];
	}

	return NULL;
}

u32 mali_pp_get_glob_num_pp_cores(void)
{
	return mali_global_num_pp_cores;
}

/* ------------- interrupt handling below ------------------ */
static void mali_pp_irq_probe_trigger(void *data)
{
	struct mali_pp_core *core = (struct mali_pp_core *)data;
	mali_hw_core_register_write(&core->hw_core, MALI200_REG_ADDR_MGMT_INT_MASK, MALI200_REG_VAL_IRQ_MASK_USED);
	mali_hw_core_register_write(&core->hw_core, MALI200_REG_ADDR_MGMT_INT_RAWSTAT, MALI200_REG_VAL_IRQ_FORCE_HANG);
	_mali_osk_mem_barrier();
}

static _mali_osk_errcode_t mali_pp_irq_probe_ack(void *data)
{
	struct mali_pp_core *core = (struct mali_pp_core *)data;
	u32 irq_readout;

	irq_readout = mali_hw_core_register_read(&core->hw_core, MALI200_REG_ADDR_MGMT_INT_STATUS);
	if (MALI200_REG_VAL_IRQ_FORCE_HANG & irq_readout)
	{
		mali_hw_core_register_write(&core->hw_core, MALI200_REG_ADDR_MGMT_INT_CLEAR, MALI200_REG_VAL_IRQ_FORCE_HANG);
		_mali_osk_mem_barrier();
		return _MALI_OSK_ERR_OK;
	}

	return _MALI_OSK_ERR_FAULT;
}

#if 0
static void mali_pp_print_registers(struct mali_pp_core *core)
{
	MALI_DEBUG_PRINT(2, ("Mali PP: Register MALI200_REG_ADDR_MGMT_VERSION = 0x%08X\n", mali_hw_core_register_read(&core->hw_core, MALI200_REG_ADDR_MGMT_VERSION)));
	MALI_DEBUG_PRINT(2, ("Mali PP: Register MALI200_REG_ADDR_MGMT_CURRENT_REND_LIST_ADDR = 0x%08X\n", mali_hw_core_register_read(&core->hw_core, MALI200_REG_ADDR_MGMT_CURRENT_REND_LIST_ADDR)));
	MALI_DEBUG_PRINT(2, ("Mali PP: Register MALI200_REG_ADDR_MGMT_STATUS = 0x%08X\n", mali_hw_core_register_read(&core->hw_core, MALI200_REG_ADDR_MGMT_STATUS)));
	MALI_DEBUG_PRINT(2, ("Mali PP: Register MALI200_REG_ADDR_MGMT_INT_RAWSTAT = 0x%08X\n", mali_hw_core_register_read(&core->hw_core, MALI200_REG_ADDR_MGMT_INT_RAWSTAT)));
	MALI_DEBUG_PRINT(2, ("Mali PP: Register MALI200_REG_ADDR_MGMT_INT_MASK = 0x%08X\n", mali_hw_core_register_read(&core->hw_core, MALI200_REG_ADDR_MGMT_INT_MASK)));
	MALI_DEBUG_PRINT(2, ("Mali PP: Register MALI200_REG_ADDR_MGMT_INT_STATUS = 0x%08X\n", mali_hw_core_register_read(&core->hw_core, MALI200_REG_ADDR_MGMT_INT_STATUS)));
	MALI_DEBUG_PRINT(2, ("Mali PP: Register MALI200_REG_ADDR_MGMT_BUS_ERROR_STATUS = 0x%08X\n", mali_hw_core_register_read(&core->hw_core, MALI200_REG_ADDR_MGMT_BUS_ERROR_STATUS)));
	MALI_DEBUG_PRINT(2, ("Mali PP: Register MALI200_REG_ADDR_MGMT_PERF_CNT_0_ENABLE = 0x%08X\n", mali_hw_core_register_read(&core->hw_core, MALI200_REG_ADDR_MGMT_PERF_CNT_0_ENABLE)));
	MALI_DEBUG_PRINT(2, ("Mali PP: Register MALI200_REG_ADDR_MGMT_PERF_CNT_0_SRC = 0x%08X\n", mali_hw_core_register_read(&core->hw_core, MALI200_REG_ADDR_MGMT_PERF_CNT_0_SRC)));
	MALI_DEBUG_PRINT(2, ("Mali PP: Register MALI200_REG_ADDR_MGMT_PERF_CNT_0_VALUE = 0x%08X\n", mali_hw_core_register_read(&core->hw_core, MALI200_REG_ADDR_MGMT_PERF_CNT_0_VALUE)));
	MALI_DEBUG_PRINT(2, ("Mali PP: Register MALI200_REG_ADDR_MGMT_PERF_CNT_1_ENABLE = 0x%08X\n", mali_hw_core_register_read(&core->hw_core, MALI200_REG_ADDR_MGMT_PERF_CNT_1_ENABLE)));
	MALI_DEBUG_PRINT(2, ("Mali PP: Register MALI200_REG_ADDR_MGMT_PERF_CNT_1_SRC = 0x%08X\n", mali_hw_core_register_read(&core->hw_core, MALI200_REG_ADDR_MGMT_PERF_CNT_1_SRC)));
	MALI_DEBUG_PRINT(2, ("Mali PP: Register MALI200_REG_ADDR_MGMT_PERF_CNT_1_VALUE = 0x%08X\n", mali_hw_core_register_read(&core->hw_core, MALI200_REG_ADDR_MGMT_PERF_CNT_1_VALUE)));
}
#endif

#if 0
void mali_pp_print_state(struct mali_pp_core *core)
{
	MALI_DEBUG_PRINT(2, ("Mali PP: State: 0x%08x\n", mali_hw_core_register_read(&core->hw_core, MALI200_REG_ADDR_MGMT_STATUS) ));
}
#endif

void mali_pp_update_performance_counters(struct mali_pp_core *core, struct mali_pp_job *job, u32 subjob)
{
	u32 val0 = 0;
	u32 val1 = 0;
#if defined(CONFIG_MALI400_PROFILING)
	int counter_index = COUNTER_FP0_C0 + (2 * core->core_id);
#endif

	if (MALI_HW_CORE_NO_COUNTER != core->counter_src0_used)
	{
		val0 = mali_hw_core_register_read(&core->hw_core, MALI200_REG_ADDR_MGMT_PERF_CNT_0_VALUE);

		mali_pp_job_set_perf_counter_value0(job, subjob, val0);

#if defined(CONFIG_MALI400_PROFILING)
		/*todo: check if the group is virtual - in such case, does it make sense to send a HW counter ?*/
		_mali_osk_profiling_report_hw_counter(counter_index, val0);
#endif
	}

	if (MALI_HW_CORE_NO_COUNTER != core->counter_src1_used)
	{
		val1 = mali_hw_core_register_read(&core->hw_core, MALI200_REG_ADDR_MGMT_PERF_CNT_1_VALUE);
		mali_pp_job_set_perf_counter_value1(job, subjob, val1);

#if defined(CONFIG_MALI400_PROFILING)
		/*todo: check if the group is virtual - in such case, does it make sense to send a HW counter ?*/
		_mali_osk_profiling_report_hw_counter(counter_index + 1, val1);
#endif
	}
}

#if MALI_STATE_TRACKING
u32 mali_pp_dump_state(struct mali_pp_core *core, char *buf, u32 size)
{
	int n = 0;

	n += _mali_osk_snprintf(buf + n, size - n, "\tPP #%d: %s\n", core->core_id, core->hw_core.description);

	return n;
}
#endif


text:
ROM::SQL.migration do
  up do
    sql = <<-SQL
      CREATE OR REPLACE FUNCTION set_updated_at_column() RETURNS TRIGGER AS $$
      BEGIN
        NEW.updated_at = (now() at time zone 'utc');
        RETURN NEW;
      END;
      $$ language 'plpgsql';
    SQL
    run sql
  end

  down do
    sql = <<-SQL
      CREATE OR REPLACE FUNCTION set_updated_at_column() RETURNS TRIGGER AS $$
      BEGIN
        NEW.updated_at = CURRENT_TIMESTAMP;
        RETURN NEW;
      END;
      $$ language 'plpgsql';
    SQL
    run sql
  end
end

redpajama_set_name: RedPajamaGithub


text:
import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    TouchableOpacity,
    InteractionManager
} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';

// import NavBar from 'react-native-navbar';
// import ScrollableTabView, {DefaultTabBar, ScrollableTabBar} from 'react-native-scrollable-tab-view';
// import HomeList from './homeList';

export default class mainContainer extends Component {
  static navigationOptions = {
    title:'我的',
    tabBarLabel: '我的',
    tabBarIcon: ({ focused, tintColor }) => {
      return (<Icon name="md-contact" size={30} color={focused?'#d81e06':'#333'} style={{marginTop:10}}/>)
    },
  };
  render(){
    return(<Text>mainContainer</Text>);
  }
}

// /**
//  * Sample React Native App
//  * https://github.com/facebook/react-native
//  * @flow
//  */

// import React, { Component } from 'react';
// import {
//     AppRegistry,
//     StyleSheet,
//     Text,
//     View
// } from 'react-native';

// import NavBar from 'react-native-navbar';

// export default class mainContainer extends Component {
// <<<<<<< HEAD
//     constructor(props) {
//         super(props);
//         let nowTime = (new Date()).valueOf();
//         this.state = {
//             text:React.PropTypes.string,
//         };
//     }

//     componentDidMount(){
//         console.log('componentDidMount');
//         this.loadData();
//     }

//     loadData(){
//         let config = {
//             authDomain: wilddogID + '.wilddog.com',
//             syncURL : wilddogUrl,
//         };
//         wilddog.initializeApp(config);
//         let ref = wilddog.sync().ref('/home');
//         ref.on("value", (a)=>{
//             console.log(a.val().news.text);
//             let text = a.val().news.text;

//             let realm = new Realm({schema:[DetailInfo]});

//             realm.write(()=>{
//                 let Detail = realm.create('Detail',{text: text,img:'111'});
//                 // let Sams = realm.objects('Dog');
//                 // realm.delete(Sams);
//             });

//             // console.log(realm.objects('Detail'));

//             this.setState({
//                 text: text
//             });
//         });

//         //

//         // let dogArr = realm.objects('Dog');
//         // for (let i = 0; i< dogArr.length;i ++){
//         //     let dogName = dogArr[i];
//         //     console.log(dogName.name);
//         // }

//     }

// =======
// >>>>>>> origin/master
//     render() {
//         let titleConfig = {
//             title: '我的',
//             style: {color:'black',fontSize:20,fontWeight:'600'}
//         };
//         return (
//             <View style={styles.container}>
//                 <NavBar
//                     title={titleConfig}
//                     style={{height:44,borderBottomWidth:1,borderBottomColor:'#dddddd'}}
//                 />
//                 <Text style={styles.welcome}>
//                     Welcome to React Native!
//                 </Text>

//             </View>
//         );
//     }
// }

// const styles = StyleSheet.create({
//     container: {
//         flex: 1,
//         backgroundColor: '#F5FCFF',
//     },
//     welcome: {
//         fontSize: 20,
//         textAlign: 'center',
//         margin: 10,
//     },
//     instructions: {
//         textAlign: 'center',
//         color: '#333333',
//         marginBottom: 5,
//     },
// });

// AppRegistry.registerComponent('BaiSi', () => BaiSi);


text:
package org.jboss.elasticsearch.river.remote;

import org.elasticsearch.common.settings.SettingsException;
import org.junit.Assert;
import org.junit.Test;

/**
 * Unit test for {@link CommentIndexingMode}.
 *
 * @author Vlastimil Elias (velias at redhat dot com)
 */
public class CommentIndexingModeTest {

	@Test
	public void parseConfiguration() {
		Assert.assertEquals(CommentIndexingMode.NONE, CommentIndexingMode.parseConfiguration("none"));
		Assert.assertEquals(CommentIndexingMode.NONE, CommentIndexingMode.parseConfiguration("None"));
		Assert.assertEquals(CommentIndexingMode.CHILD, CommentIndexingMode.parseConfiguration("child"));
		Assert.assertEquals(CommentIndexingMode.CHILD, CommentIndexingMode.parseConfiguration("Child"));
		Assert.assertEquals(CommentIndexingMode.STANDALONE, CommentIndexingMode.parseConfiguration("standalone"));
		Assert.assertEquals(CommentIndexingMode.STANDALONE, CommentIndexingMode.parseConfiguration("Standalone"));
		Assert.assertEquals(CommentIndexingMode.EMBEDDED, CommentIndexingMode.parseConfiguration("embedded"));
		Assert.assertEquals(CommentIndexingMode.EMBEDDED, CommentIndexingMode.parseConfiguration("Embedded"));
		Assert.assertEquals(CommentIndexingMode.NONE, CommentIndexingMode.parseConfiguration(null));
		Assert.assertEquals(CommentIndexingMode.NONE, CommentIndexingMode.parseConfiguration("  "));

		try {
			CommentIndexingMode.parseConfiguration("nonsense");
			Assert.fail("SettingsException must be thrown");
		} catch (SettingsException e) {
			// OK
		}
	}

	@Test
	public void isExtraDocumentIndexed() {
		Assert.assertFalse(CommentIndexingMode.NONE.isExtraDocumentIndexed());
		Assert.assertFalse(CommentIndexingMode.EMBEDDED.isExtraDocumentIndexed());
		Assert.assertTrue(CommentIndexingMode.STANDALONE.isExtraDocumentIndexed());
		Assert.assertTrue(CommentIndexingMode.CHILD.isExtraDocumentIndexed());
	}

}


text:
#ifndef TGBOT_PASSPORTELEMENTERRORTRANSLATIONFILE_H
#define TGBOT_PASSPORTELEMENTERRORTRANSLATIONFILE_H

#include "tgbot/types/PassportElementError.h"

#include <string>
#include <memory>

namespace TgBot {

/**
 * @brief Represents an issue with one of the files that constitute the translation of a document.
 * The error is considered resolved when the file changes.
 *
 * @ingroup types
 */
class PassportElementErrorTranslationFile : public PassportElementError {
public:
    static const std::string SOURCE;

    typedef std::shared_ptr<PassportElementErrorTranslationFile> Ptr;

    PassportElementErrorTranslationFile() {
        this->source = SOURCE;
    }

    /**
     * @brief Base64-encoded file hash
     */
    std::string fileHash;
};
}

#endif //TGBOT_PASSPORTELEMENTERRORTRANSLATIONFILE_H


text:
@interface ABI43_0_0AIRGoogleMapManager : ABI43_0_0RCTViewManager
@property (nonatomic) BOOL isGesture;

@end

#endif


text:
require_relative '../spec_helper'

module Selenium
  module WebDriver
    module Chrome
      describe Service, exclusive: {browser: :chrome} do
        let(:service) { Service.new }
        let(:service_manager) { service.launch }

        after { service_manager.stop }

        it 'auto uses chromedriver' do
          allow(Platform).to receive(:find_binary)
          expect(service_manager.uri).to be_a(URI)
        end
      end
    end # Chrome
  end # WebDriver
end # Selenium


text:
package settings

import (
	"fmt"
	"regexp"
	"strconv"
	"strings"
	"time"

	"poule/gh"
	"poule/operations"

	"github.com/Sirupsen/logrus"
	"github.com/google/go-github/github"
	"github.com/pkg/errors"
	"github.com/urfave/cli"
)

const filterFlagName = "filter"

// FilteringFlag is the command-line flag that gets automatically added to
// every available operation.
var FilteringFlag = cli.StringSliceFlag{
	Name:  filterFlagName,
	Usage: "filter based on item attributes",
}

// ParseCliFilters reads filter definitions from the command line.
func ParseCliFilters(c *cli.Context) ([]*Filter, error) {
	value, err := NewMultiValuedKeysFromSlice(c.StringSlice(filterFlagName))
	if err != nil {
		return nil, err
	}
	return ParseConfigurationFilters(value.ToSerializedFormat())
}

// ParseConfigurationFilters reads filter definitions from the serialized
// configuration format.
func ParseConfigurationFilters(values map[string]interface{}) (Filters, error) {
	filters := Filters{}
	for filterType, rawValue := range values {
		value, err := filterValue(rawValue)
		if err != nil {
			return []*Filter{}, err
		}
		filter, err := MakeFilter(filterType, value)
		if err != nil {
			return []*Filter{}, err
		}
		filters = append(filters, filter)
	}
	return filters, nil
}

// Filters is a collection of Filter instances.
type Filters []*Filter

// Apply returns true only if all filters accept the item.
func (f Filters) Apply(context operations.Context, item gh.Item) bool {
	for _, filter := range f {
		if !filter.Apply(context, item) {
			return false
		}
	}
	return true
}

// Filter accepts or rejects a GitHub item based on a strategy.
type Filter struct {
	Strategy fmt.Stringer
}

// Apply returns whether the internal strategy is accepting or rejecting the
// specified GitHub item.
func (f *Filter) Apply(context operations.Context, item gh.Item) bool {
	switch {
	case item.IsIssue():
		if f, ok := f.Strategy.(issueFilter); ok {
			return f.ApplyIssue(context, item.Issue)
		}
	case item.IsPullRequest():
		if f, ok := f.Strategy.(pullRequestFilter); ok {
			return f.ApplyPullRequest(context, item.PullRequest)
		}
	default:
		panic("unreachable")
	}
	return true
}

// issueFilter is a filtering strategy that applies to GitHub issues.
type issueFilter interface {
	ApplyIssue(operations.Context, *github.Issue) bool
	String() string
}

// pullRequestFilter is a filtering strategy that applies to GitHub pull
// requests.
type pullRequestFilter interface {
	ApplyPullRequest(operations.Context, *github.PullRequest) bool
	String() string
}

// MakeFilter creates a filter from a type identifier and a string value.
func MakeFilter(filterType, value string) (*Filter, error) {
	typeMapping := map[string]func(string) (*Filter, error){
		"age":      makeAgeFilter,
		"assigned": makeAssignedFilter,
		"comments": makeCommentsFilter,
		"is":       makeIsFilter,
		"labels":   makeWithLabelsFilter,
		"~labels":  makeWithoutLabelsFilter,
		"contains": makeContainsFilter,
	}
	if constructor, ok := typeMapping[filterType]; ok {
		return constructor(value)
	}
	return nil, errors.Errorf("unknown filter type %q", filterType)
}

// ContainsFilter implements a filter for regexps that checks comments.
type ContainsFilter struct {
	regexp *regexp.Regexp
}

func makeContainsFilter(value string) (*Filter, error) {
	regex, err := regexp.Compile(value)
	if err != nil {
		return nil, err
	}

	return asFilter(ContainsFilter{regexp: regex}), nil
}

func (f ContainsFilter) filter(context operations.Context, issueNum int) bool {
	comments, _, err := context.Client.Issues().ListComments(context.Username, context.Repository, issueNum, nil)
	if err != nil {
		logrus.Error(err)
		return false
	}

	for _, comment := range comments {
		// Remove CRs from the CRLF line endings. \r should never be deliberately
		// in a github comment, I hope at least.
		body := strings.Replace(*comment.Body, "\r", "", -1)
		if f.regexp.MatchString(body) {
			return true
		}
	}

	return false
}

// ApplyIssue applies the filter to the specified issue.
func (f ContainsFilter) ApplyIssue(context operations.Context, issue *github.Issue) bool {
	return f.filter(context, *(issue.Number))
}

// ApplyPullRequest applies the filter to the specified pull request.
func (f ContainsFilter) ApplyPullRequest(context operations.Context, pullRequest *github.PullRequest) bool {
	return f.filter(context, *(pullRequest.Number))
}

// String returns a string representation of the filter
func (f ContainsFilter) String() string {
	return fmt.Sprintf("ContainsFilter(%s)", f.regexp)
}

// AgeFilter filters items based on their age.
type AgeFilter struct {
	age ExtDuration
}

func makeAgeFilter(value string) (*Filter, error) {
	d, err := ParseExtDuration(value)
	if err != nil {
		return nil, errors.Errorf("invalid value %q for \"age\" filter", value)
	}
	return asFilter(AgeFilter{d}), nil
}

// ApplyIssue applies the filter to the specified issue.
func (f AgeFilter) ApplyIssue(context operations.Context, issue *github.Issue) bool {
	return time.Since(*issue.CreatedAt) > f.age.Duration()
}

// ApplyPullRequest applies the filter to the specified pull request.
func (f AgeFilter) ApplyPullRequest(context operations.Context, pullRequest *github.PullRequest) bool {
	return time.Since(*pullRequest.CreatedAt) > f.age.Duration()
}

// String returns a string representation of the filter
func (f AgeFilter) String() string {
	return fmt.Sprintf("AgeFilter(%s)", f.age)
}

// AssignedFilter filters issues based on whether they are assigned or not.
type AssignedFilter struct {
	isAssigned bool
}

func makeAssignedFilter(value string) (*Filter, error) {
	b, err := strconv.ParseBool(value)
	if err != nil {
		return nil, errors.Errorf("invalid value %q for \"assigned\" filter", value)
	}
	return asFilter(AssignedFilter{b}), nil
}

// ApplyIssue applies the filter to the specified issue.
func (f AssignedFilter) ApplyIssue(context operations.Context, issue *github.Issue) bool {
	return f.isAssigned == (issue.Assignee != nil)
}

// String returns a string representation of the filter
func (f AssignedFilter) String() string {
	return fmt.Sprintf("AssignedFilter(%t)", f.isAssigned)
}

// CommentsFilter filters issues based on the number of comments.
type CommentsFilter struct {
	filtValue string
	predicate func(int) bool
}

func makeCommentsFilter(value string) (*Filter, error) {
	var count int
	var operation rune
	if n, err := fmt.Sscanf(value, "%c%d", &operation, &count); n != 2 || err != nil {
		return nil, errors.Errorf("invalid value %q for \"comments\" filter", value)
	}

	var predicate func(int) bool
	switch operation {
	case '<':
		predicate = func(n int) bool { return n < count }
		break
	case '=':
		predicate = func(n int) bool { return n == count }
		break
	case '>':
		predicate = func(n int) bool { return n > count }
		break
	default:
		return nil, errors.Errorf("invalid operator %c for \"comments\" filter", operation)
	}
	return asFilter(CommentsFilter{
		filtValue: value,
		predicate: predicate,
	}), nil
}

// ApplyIssue applies the filter to the specified issue.
func (f CommentsFilter) ApplyIssue(context operations.Context, issue *github.Issue) bool {
	return f.predicate(*issue.Comments)
}

// String returns a string representation of the filter
func (f CommentsFilter) String() string {
	return fmt.Sprintf("CommentsFilter(%s)", f.filtValue)
}

// ApplyPullRequest applies the filter to the specified pull request.
func (f CommentsFilter) ApplyPullRequest(context operations.Context, pullRequest *github.PullRequest) bool {
	return f.predicate(*pullRequest.Comments)
}

// IsFilter filters issues and pull requests based on their type.
type IsFilter struct {
	PullRequestOnly bool
}

func makeIsFilter(value string) (*Filter, error) {
	switch value {
	case "pr":
		return asFilter(IsFilter{PullRequestOnly: true}), nil
	case "issue":
		return asFilter(IsFilter{PullRequestOnly: false}), nil
	default:
		return nil, errors.Errorf("invalid value %q for \"is\" filter", value)
	}
}

// ApplyIssue applies the filter to the specified issue.
func (f IsFilter) ApplyIssue(context operations.Context, issue *github.Issue) bool {
	// We're called on an issue: filter passes unless configured to accept pull
	// requests, and if the issue isn't really a pull request.
	return !f.PullRequestOnly && (issue.PullRequestLinks == nil)
}

// ApplyPullRequest applies the filter to the specified pull request.
func (f IsFilter) ApplyPullRequest(context operations.Context, pullRequest *github.PullRequest) bool {
	// We're called on a pull request: filter passes if configured to accept
	// pull requests.
	return f.PullRequestOnly
}

// String returns a string representation of the filter
func (f IsFilter) String() string {
	return fmt.Sprintf("IsFilter(PullRequestOnly=%t)", f.PullRequestOnly)
}

// WithLabelsFilter filters issues based on whether they bear all of the
// specified labels.
type WithLabelsFilter struct {
	labels []string
}

func makeWithLabelsFilter(value string) (*Filter, error) {
	labels := strings.Split(value, ",")
	return asFilter(WithLabelsFilter{labels}), nil
}

// ApplyIssue applies the filter to the specified issue.
func (f WithLabelsFilter) ApplyIssue(context operations.Context, issue *github.Issue) bool {
	return gh.HasAllLabels(f.labels, issue.Labels)
}

// String returns a string representation of the filter
func (f WithLabelsFilter) String() string {
	return fmt.Sprintf("WithLabelsFilter(%s)", strings.Join(f.labels, ","))
}

// WithoutLabelsFilter filters issues based on whether they bear none of the
// specified labels.
type WithoutLabelsFilter struct {
	labels []string
}

func makeWithoutLabelsFilter(value string) (*Filter, error) {
	labels := strings.Split(value, ",")
	return asFilter(WithoutLabelsFilter{labels}), nil
}

// ApplyIssue applies the filter to the specified issue.
func (f WithoutLabelsFilter) ApplyIssue(context operations.Context, issue *github.Issue) bool {
	return !gh.HasAnyLabels(f.labels, issue.Labels)
}

// String returns a string representation of the filter
func (f WithoutLabelsFilter) String() string {
	return fmt.Sprintf("WithoutLabelsFilter(%s)", strings.Join(f.labels, ","))
}

// Type conversion utilities.

func asFilter(impl fmt.Stringer) *Filter {
	return &Filter{
		Strategy: impl,
	}
}

func filterValue(value interface{}) (string, error) {
	// When value is a string, return it directly.
	if s, ok := value.(string); ok {
		return s, nil
	}
	// When value is a []interface{}, convert it into a []string.
	if s, ok := value.([]interface{}); ok {
		strslice := []string{}
		for _, v := range s {
			if str, ok := v.(string); ok {
				strslice = append(strslice, str)
			} else {
				return "", errors.Errorf("non-string \"%v\" in filter value", v)
			}
		}
		value = strslice
	}
	// When value is a []string, return the result of a strings.Join.
	if s, ok := value.([]string); ok {
		return strings.Join(s, ","), nil
	}
	// Anything else is an error.
	return "", errors.Errorf("invalid data type \"%#v\" for filter value", value)
}

// Mass filtering utilities.

// FilterIncludesIssues is a predicate to determine whether or not a set of
// filters should include issues.
func FilterIncludesIssues(filters []*Filter) bool {
	for _, filter := range filters {
		if f, ok := filter.Strategy.(IsFilter); ok && f.PullRequestOnly {
			return false
		}
	}
	return true
}

// FilterIncludesPullRequests is similar to FilterIncludesIssues only with
// respect to pull requests.
func FilterIncludesPullRequests(filters []*Filter) bool {
	for _, filter := range filters {
		if f, ok := filter.Strategy.(IsFilter); ok && !f.PullRequestOnly {
			return false
		}
	}
	return true
}


text:
layout: post
title: Entity Framework 6 vs EF Core 6 Query Performance
---

Should you upgrade your project from a Net Framework application using Entity Framework 6 to a Net 6 application using EF Core 6? One of the biggest decisions as to whether you would go down this route which may require a serious investment of time is; will there be a performance benefit?

## Why Performance Matters

There are two main reasons:

- If an application is slow then the users of that application may get frustrated and seek an alternative provider
- A more performant application will use less CPU and Memory and so infrastructure or hosting costs can be reduced

## Creating the Benchmarking Tests

Off the back of a project by Chad Golden, using his DB schema and seed script, I have created a solution that compares the query performance of Entity Framework 6, EF Core 3 and EF Core 6. There is a project in the solution for each version of Entity Framework using BenchmarkDotNet which runs the following queries:

- Retrieve all books
- Retrieve all books, using "No Tracking"
- Retrieve all books, including the author info, using an Include
- Retrieve all books, including the author info, projected to a DTO
- Retrieve all books, including the author info, projected to a DTO, using "No Tracking"
- Retrieve all books, including the author info, using an Include, Ordered By Author
- Retrieve all books, including the author info, projected to a DTO, Ordered By Author
- Retrieve all books, including the author info, projected to a DTO, using "No Tracking", Ordered By Author

## Running the tests

To run the tests you will need to :

- Open the repo in Visual Studio
- Publish the database project (right click it and select "Publish"), to "(localdb)\MSSQLLocalDB" with the name "EFPerformanceDB"
- Run Each Of the projects in "Implementations" in turn in "Release" mode

## Test Results

### Entity Framework 6.4 on Net Framework 4.8

| Method                                         |      Mean |     Error |    StdDev |    Median |
|----------------------------------------------- |----------:|----------:|----------:|----------:|
| LoadAllBookBooks                               | 204.06 ms |  7.952 ms |  5.260 ms | 203.19 ms |
| LoadAllBooksUntracked                          |  32.07 ms |  1.575 ms |  1.042 ms |  32.20 ms |
| LoadAllBookBooksIncludingAuthor                | 302.80 ms | 15.428 ms | 10.204 ms | 302.20 ms |
| LoadAllBooksWithAuthorProjection               |  40.94 ms |  4.892 ms |  3.236 ms |  39.57 ms |
| LoadAllBooksWithAuthorProjectionUntracked      |  40.35 ms |  2.641 ms |  1.747 ms |  40.23 ms |
| LoadAllBooksWithAuthorOrderedByAuthor          | 353.90 ms | 10.720 ms |  7.091 ms | 353.45 ms |
| LoadAllBooksOrderedByAuthorProjection          |  72.25 ms |  1.625 ms |  0.967 ms |  72.33 ms |
| LoadAllBooksOrderedByAuthorProjectionUntracked |  72.90 ms |  2.428 ms |  1.445 ms |  73.40 ms |

### EF Core 3 on Net Core 3.1

|                                         Method |      Mean |     Error |   StdDev |    Median |
|----------------------------------------------- |----------:|----------:|---------:|----------:|
| LoadAllBookBooks                               |  64.89 ms |  3.923 ms | 2.334 ms |  64.68 ms |
| LoadAllBooksUntracked                          |  17.23 ms |  0.977 ms | 0.511 ms |  17.10 ms |
| LoadAllBookBooksIncludingAuthor                | 104.91 ms |  4.156 ms | 2.174 ms | 104.25 ms |
| LoadAllBooksWithAuthorProjection               |  38.71 ms |  3.687 ms | 2.438 ms |  37.74 ms |
| LoadAllBooksWithAuthorProjectionUntracked      |  39.07 ms |  4.986 ms | 2.608 ms |  37.82 ms |
| LoadAllBooksWithAuthorOrderedByAuthor          | 148.25 ms | 14.324 ms | 9.475 ms | 145.93 ms |
| LoadAllBooksOrderedByAuthorProjection          |  71.79 ms |  5.547 ms | 3.669 ms |  70.61 ms |
| LoadAllBooksOrderedByAuthorProjectionUntracked |  71.35 ms |  4.723 ms | 3.124 ms |  69.41 ms |

### EF Core 6 on Net 6

| Method                                         |      Mean |     Error |    StdDev |    Median |
|----------------------------------------------- |----------:|----------:|----------:|----------:|
| LoadAllBookBooks                               |  48.36 ms |  1.434 ms |  0.750 ms |  48.32 ms |
| LoadAllBooksUntracked                          |  18.89 ms |  2.209 ms |  1.461 ms |  18.84 ms |
| LoadAllBookBooksIncludingAuthor                |  92.66 ms |  5.287 ms |  3.146 ms |  91.37 ms |
| LoadAllBooksWithAuthorProjection               |  38.83 ms |  6.200 ms |  3.690 ms |  37.25 ms |
| LoadAllBooksWithAuthorProjectionUntracked      |  38.42 ms |  2.534 ms |  1.676 ms |  37.76 ms |
| LoadAllBooksWithAuthorOrderedByAuthor          | 134.84 ms | 21.555 ms | 14.258 ms | 127.06 ms |
| LoadAllBooksOrderedByAuthorProjection          |  71.02 ms |  5.152 ms |  3.066 ms |  70.51 ms |
| LoadAllBooksOrderedByAuthorProjectionUntracked |  70.88 ms |  4.888 ms |  3.233 ms |  70.79 ms |

## Analysing the results

### Retrieve all books

- EF Core 3 was 68% faster then Entity Framework 6
- EF Core 6 was 76% faster then Entity Framework 6

### Retrieve all books, using "No Tracking"

- EF Core 3 was 46% faster then Entity Framework 6
- EF Core 6 was 41% faster then Entity Framework 6

### Retrieve all books, including the author info, using an Include

- EF Core 3 was 65% faster then Entity Framework 6
- EF Core 6 was 69% faster then Entity Framework 6

### Retrieve all books, including the author info, projected to a DTO

- EF Core 3 was 5% faster then Entity Framework 6
- EF Core 6 was 5% faster then Entity Framework 6

### Retrieve all books, including the author info, projected to a DTO, using "No Tracking"

- EF Core 3 was 3% faster then Entity Framework 6
- EF Core 6 was 5% faster then Entity Framework 6

### Retrieve all books, including the author info, using an Include, Ordered By Author

- EF Core 3 was 58% faster then Entity Framework 6
- EF Core 6 was 61% faster then Entity Framework 6

### Retrieve all books, including the author info, projected to a DTO, Ordered By Author

- EF Core 3 was 0.5% faster then Entity Framework 6
- EF Core 6 was 1.7% faster then Entity Framework 6

### Retrieve all books, including the author info, projected to a DTO, using "No Tracking", Ordered By Author

- EF Core 3 was 0.5% faster then Entity Framework 6
- EF Core 6 was 2.7 faster then Entity Framework 6

## Conclusions

### Entity Framework 6 vs EF Core 3

EF Core 3 was faster in every test. Projected queries however were practically identical.

### EF Core 6 vs EF Core 3

EF Core 6 was marginally faster in every test bar one outlier.

### Projections

The results across all three versions show that projections are by far the best thing you can do to improve performance. However, I was surprised at how little difference there was in the performance of these tests across the three versions, and what little impact "No Tracking" has on projections. So if you have already optimized your Entity Framework 6 queries by selecting to DTOs or using something like AutoMapper projections, then there may not be as much of a saving for you by upgrading as you may imagine.


text:
class Customer
  attr_reader :name

  def initialize(name)
    @name = name
    @rentals = []
  end

  def add_rental(arg)
    @rentals << arg
  end

  def statement
    result = "Rental Record for #{@name}\n"
    @rentals.each do |element|
      # show figures for this rental
      result += "\t" + element.movie.title + "\t" + element.charge.to_s + "\n"
    end

    # add footer lines
    result += "Amount owed is #{total_charge}\n"
    result += "You earned #{total_frequent_renter_points} frequent renter points"
    result
  end

  def html_statement
    result = "
Rentals for #{@name}

\n"
    @rentals.each do |element|
      # show figures for this rental
      result += "\t" + each.movie.title + ': ' + element.charge.to_s + "
\n"
    end
    # add footer lines
    result += "
You owe #{total_charge}
\n"
    result += 'On this rental you earned ' +
              "#{total_frequent_renter_points} " +
              'frequent renter points
'
    result
  end

  private

  def total_charge
    @rentals.inject(0) { |sum, rental| sum + rental.charge }
  end

  def total_frequent_renter_points
    @rentals.inject(0) { |sum, rental| sum + rental.frequent_renter_points }
  end
end


text:
c
c $Id: comcon.h,v 1.1.1.1 2004/02/27 05:44:07 rca Exp $
c $Author: rca $
c
C
C Physical constants. This is the master set. All parameterizations set
C their local values from these values.
C
      common/comcon/cappa   ,cpvir   ,cpwv    ,cpair   ,epsilo  ,
     $              ez      ,gravit  ,latvap  ,latice  ,omega   ,
     $              rair    ,rearth  ,rh2o    ,rhoh2o  ,ra      ,
     $              rga     ,stebol  ,tmelt   ,zvir    ,t0(plev)
C
      real cappa       ! R/Cp
      real cpvir       ! cpwv/cpair - 1
      real cpwv        ! Specific heat of water vapor
      real cpair       ! Specific heat of dry air
      real epsilo      ! Ratio of h2o to dry air molecular weights
      real ez          ! Coriolis expansion coeff -> omega/sqrt(0.375)
      real gravit      ! Gravitational acceleration
      real latvap      ! Latent heat of vaporization
      real latice      ! Latent heat of fusion
      real omega       ! Angular velocity of Earth's rotation
      real rair        ! Gas constant for dry air
      real rearth      ! Radius of the earth
      real rh2o        ! Gas constant for water vapor
      real rhoh2o      ! Density of liquid water (STP)
      real ra          ! Reciprocal of earth radius
      real rga         ! Reciprocal of gravitational acceleration
      real stebol      ! Stefan-Boltzmann's constant
      real tmelt       ! Freezing point of water
      real zvir        ! rh2o/rair - 1
      real t0          ! Reference temperature for t-prime computations
C


text:
/* glibconfig.h
 *
 * This is a generated file.  Please modify 'configure.ac'
 */

#ifndef __G_LIBCONFIG_H__
#define __G_LIBCONFIG_H__

#include <glib/gmacros.h>

#include <limits.h>
#include <float.h>

G_BEGIN_DECLS

#define G_MINFLOAT	FLT_MIN
#define G_MAXFLOAT	FLT_MAX
#define G_MINDOUBLE	DBL_MIN
#define G_MAXDOUBLE	DBL_MAX
#define G_MINSHORT	SHRT_MIN
#define G_MAXSHORT	SHRT_MAX
#define G_MAXUSHORT	USHRT_MAX
#define G_MININT	INT_MIN
#define G_MAXINT	INT_MAX
#define G_MAXUINT	UINT_MAX
#define G_MINLONG	LONG_MIN
#define G_MAXLONG	LONG_MAX
#define G_MAXULONG	ULONG_MAX

typedef signed char gint8;
typedef unsigned char guint8;
typedef signed short gint16;
typedef unsigned short guint16;
#define G_GINT16_MODIFIER "h"
#define G_GINT16_FORMAT "hi"
#define G_GUINT16_FORMAT "hu"
typedef signed int gint32;
typedef unsigned int guint32;
#define G_GINT32_MODIFIER ""
#define G_GINT32_FORMAT "i"
#define G_GUINT32_FORMAT "u"
#define G_HAVE_GINT64 1          /* deprecated, always true */

#ifndef _MSC_VER
G_GNUC_EXTENSION typedef signed long long gint64;
G_GNUC_EXTENSION typedef unsigned long long guint64;
#else /* _MSC_VER */
typedef signed __int64 gint64;
typedef unsigned __int64 guint64;
#endif /* _MSC_VER */

#ifndef _MSC_VER
#define G_GINT64_CONSTANT(val)	(G_GNUC_EXTENSION (val##LL))
#else /* _MSC_VER */
#define G_GINT64_CONSTANT(val)	(val##i64)
#endif /* _MSC_VER */
#ifndef _MSC_VER
#define G_GUINT64_CONSTANT(val)	(G_GNUC_EXTENSION (val##ULL))
#else /* _MSC_VER */
#define G_GUINT64_CONSTANT(val)	(val##Ui64)
#endif /* _MSC_VER */
#define G_GINT64_MODIFIER "I64"
#define G_GINT64_FORMAT "I64i"
#define G_GUINT64_FORMAT "I64u"

#if defined(_WIN64) || defined(_M_X64) || defined(_M_AMD64)

#define GLIB_SIZEOF_VOID_P 8
#define GLIB_SIZEOF_LONG   4
#define GLIB_SIZEOF_SIZE_T 8

typedef signed long long gssize;
typedef unsigned long long gsize;
#define G_GSIZE_MODIFIER "I64"
#define G_GSSIZE_FORMAT "I64d"
#define G_GSIZE_FORMAT "I64u"

#define G_MAXSIZE	G_MAXUINT64
#define G_MINSSIZE	G_MININT64
#define G_MAXSSIZE	G_MAXINT64

#else

#define GLIB_SIZEOF_VOID_P 4
#define GLIB_SIZEOF_LONG   4
#define GLIB_SIZEOF_SIZE_T 4

typedef signed int gssize;
typedef unsigned int gsize;
#define G_GSIZE_MODIFIER ""
#define G_GSSIZE_FORMAT "i"
#define G_GSIZE_FORMAT "u"

#define G_MAXSIZE	G_MAXUINT
#define G_MINSSIZE	G_MININT
#define G_MAXSSIZE	G_MAXINT

#endif

typedef gint64 goffset;
#define G_MINOFFSET	G_MININT64
#define G_MAXOFFSET	G_MAXINT64

#define G_GOFFSET_MODIFIER      G_GINT64_MODIFIER
#define G_GOFFSET_FORMAT        G_GINT64_FORMAT
#define G_GOFFSET_CONSTANT(val) G_GINT64_CONSTANT(val)

#ifndef _WIN64

#define GPOINTER_TO_INT(p)	((gint)   (p))
#define GPOINTER_TO_UINT(p)	((guint)  (p))

#define GINT_TO_POINTER(i)	((gpointer)  (i))
#define GUINT_TO_POINTER(u)	((gpointer)  (u))

typedef signed int gintptr;
typedef unsigned int guintptr;

#define G_GINTPTR_MODIFIER      ""
#define G_GINTPTR_FORMAT        "i"
#define G_GUINTPTR_FORMAT       "u"

#else

#define GPOINTER_TO_INT(p)	((gint)  (gint64) (p))
#define GPOINTER_TO_UINT(p)	((guint) (guint64) (p))

#define GINT_TO_POINTER(i)	((gpointer) (gint64) (i))
#define GUINT_TO_POINTER(u)	((gpointer) (guint64) (u))

#ifndef _MSC_VER
typedef signed long long gintptr;
typedef unsigned long long guintptr;
#else
typedef signed __int64 gintptr;
typedef unsigned __int64 guintptr;
#endif

#define G_GINTPTR_MODIFIER      "I64"
#define G_GINTPTR_FORMAT        "I64i"
#define G_GUINTPTR_FORMAT       "I64u"

#endif

#ifdef NeXT /* @#%@! NeXTStep */
# define g_ATEXIT(proc)	(!atexit (proc))
#else
# define g_ATEXIT(proc)	(atexit (proc))
#endif

#define g_memmove(dest,src,len) G_STMT_START { memmove ((dest), (src), (len)); } G_STMT_END

#define GLIB_MAJOR_VERSION 2
#define GLIB_MINOR_VERSION 26
#define GLIB_MICRO_VERSION 1

#define G_OS_WIN32
#define G_PLATFORM_WIN32

#ifndef _MSC_VER
#define G_VA_COPY	va_copy
#endif /* not _MSC_VER */

#ifdef	__cplusplus
#define	G_HAVE_INLINE	1
#else	/* !__cplusplus */
#ifndef _MSC_VER
#define G_HAVE_INLINE 1
#endif /* _MSC_VER */
#define G_HAVE___INLINE 1
#if !defined(_MSC_VER) && !defined(__DMC__)
#define G_HAVE___INLINE__ 1
#endif /* !_MSC_VER and !__DMC__ */
#endif	/* !__cplusplus */

#ifdef	__cplusplus
#define G_CAN_INLINE	1
#else	/* !__cplusplus */
#define G_CAN_INLINE	1
#endif

#ifndef _MSC_VER
#define G_HAVE_ISO_VARARGS 1

/* gcc-2.95.x supports both gnu style and ISO varargs, but if -ansi
 * is passed ISO vararg support is turned off, and there is no work
 * around to turn it on, so we unconditionally turn it off.
 */
#if __GNUC__ == 2 && __GNUC_MINOR__ == 95
#  undef G_HAVE_ISO_VARARGS
#endif

#define G_HAVE_GNUC_VARARGS 1
#else /* _MSC_VER */
/* varargs macros available since msvc8 (vs2005) */
#  if _MSC_VER >= 1400
#    define G_HAVE_ISO_VARARGS 1
#   endif
#endif /* not _MSC_VER */
#define G_HAVE_GROWING_STACK 0

#if defined(__SUNPRO_C) && (__SUNPRO_C >= 0x590)
#define G_GNUC_INTERNAL __attribute__((visibility("hidden")))
#elif defined(__SUNPRO_C) && (__SUNPRO_C >= 0x550)
#define G_GNUC_INTERNAL __hidden
#elif defined (__GNUC__) && defined (G_HAVE_GNUC_VISIBILITY)
#define G_GNUC_INTERNAL __attribute__((visibility("hidden")))
#else
#define G_GNUC_INTERNAL
#endif

#define G_THREADS_ENABLED
#define G_THREADS_IMPL_WIN32
typedef struct _GMutex* GStaticMutex;
#define G_STATIC_MUTEX_INIT NULL
#define g_static_mutex_get_mutex(mutex) \
  (g_static_mutex_get_mutex_impl_shortcut (mutex))
/* This represents a system thread as used by the implementation. An
 * alien implementaion, as loaded by g_thread_init can only count on
 * "sizeof (gpointer)" bytes to store their info. We however need more
 * for some of our native implementations. */
typedef union _GSystemThread GSystemThread;
union _GSystemThread
{
#ifndef _WIN64
  char   data[4];
#else
  char   data[8];
#endif
  double dummy_double;
  void  *dummy_pointer;
  long   dummy_long;
};

#define G_ATOMIC_OP_MEMORY_BARRIER_NEEDED 1

#define GINT16_TO_LE(val)	((gint16) (val))
#define GUINT16_TO_LE(val)	((guint16) (val))
#define GINT16_TO_BE(val)	((gint16) GUINT16_SWAP_LE_BE (val))
#define GUINT16_TO_BE(val)	(GUINT16_SWAP_LE_BE (val))
#define GINT32_TO_LE(val)	((gint32) (val))
#define GUINT32_TO_LE(val)	((guint32) (val))
#define GINT32_TO_BE(val)	((gint32) GUINT32_SWAP_LE_BE (val))
#define GUINT32_TO_BE(val)	(GUINT32_SWAP_LE_BE (val))
#define GINT64_TO_LE(val)	((gint64) (val))
#define GUINT64_TO_LE(val)	((guint64) (val))
#define GINT64_TO_BE(val)	((gint64) GUINT64_SWAP_LE_BE (val))
#define GUINT64_TO_BE(val)	(GUINT64_SWAP_LE_BE (val))
#define GLONG_TO_LE(val)	((glong) GINT32_TO_LE (val))
#define GULONG_TO_LE(val)	((gulong) GUINT32_TO_LE (val))
#define GLONG_TO_BE(val)	((glong) GINT32_TO_BE (val))
#define GULONG_TO_BE(val)	((gulong) GUINT32_TO_BE (val))
#define GINT_TO_LE(val)		((gint) GINT32_TO_LE (val))
#define GUINT_TO_LE(val)	((guint) GUINT32_TO_LE (val))
#define GINT_TO_BE(val)		((gint) GINT32_TO_BE (val))
#define GUINT_TO_BE(val)	((guint) GUINT32_TO_BE (val))
#define GSIZE_TO_LE(val)	((gsize) GUINT32_TO_LE (val))
#define GSSIZE_TO_LE(val)	((gssize) GINT32_TO_LE (val))
#define GSIZE_TO_BE(val)	((gsize) GUINT32_TO_BE (val))
#define GSSIZE_TO_BE(val)	((gssize) GINT32_TO_BE (val))
#define G_BYTE_ORDER G_LITTLE_ENDIAN

#define GLIB_SYSDEF_POLLIN =1
#define GLIB_SYSDEF_POLLOUT =4
#define GLIB_SYSDEF_POLLPRI =2
#define GLIB_SYSDEF_POLLHUP =16
#define GLIB_SYSDEF_POLLERR =8
#define GLIB_SYSDEF_POLLNVAL =32

#define G_MODULE_SUFFIX "dll"

/* A GPid is an abstraction for a process "handle". It is *not* an
 * abstraction for a process identifier in general. GPid is used in
 * GLib only for descendant processes spawned with the g_spawn*
 * functions. On POSIX there is no "process handle" concept as such,
 * but on Windows a GPid is a handle to a process, a kind of pointer,
 * not a process identifier.
 */
typedef void * GPid;

#define GLIB_SYSDEF_AF_UNIX 1
#define GLIB_SYSDEF_AF_INET 2
#define GLIB_SYSDEF_AF_INET6 23

#define GLIB_SYSDEF_MSG_OOB 1
#define GLIB_SYSDEF_MSG_PEEK 2
#define GLIB_SYSDEF_MSG_DONTROUTE 4

G_END_DECLS

#endif /* GLIBCONFIG_H */


text:
require 'open3'
require 'thread'

module NixonPi
  class DirectIO
    def initialize
      @stdin, @stdout, @stderr, @wait_thr = Open3.popen3("sudo #{Dir.pwd}/c-driver/abiocard/abiocardserver -stdio")
      # pid = @wait_thr[:pid]
      @mutex = Mutex.new
    end

    ##
    # Write to direct stdin and get values from stdout
    # @param [String] value
    # Pass a block if you like to handle the return value
    def cmd(value)
      @mutex.synchronize do
        @stdin.puts(value)
        yield @stdout.gets if block_given?
      end
    end

    # Close io connections
    def close
      @mutex.synchronize do
        @stdin.puts('QU')
        @stdin.close
        @stdout.close
        @stderr.close
      end
      exit_status = @wait_thr.value # Process::Status object returned.
    end
  end
end


text:
var ChildObject = Parse.Object.extend({className: "ChildObject"});
var ParentObject = Parse.Object.extend({className: "ParentObject"});

describe('Parse.Relation testing', () => {
  it("simple add and remove relation", (done) => {
    var child = new ChildObject();
    child.set("x", 2);
    var parent = new ParentObject();
    parent.set("x", 4);
    var relation = parent.relation("child");

    child.save().then(() => {
      relation.add(child);
      return parent.save();
    }, (e) => {
      fail(e);
    }).then(() => {
      return relation.query().find();
    }).then((list) => {
      equal(list.length, 1,
            "Should have gotten one element back");
      equal(list[0].id, child.id,
            "Should have gotten the right value");
      ok(!parent.dirty("child"),
         "The relation should not be dirty");

      relation.remove(child);
      return parent.save();
    }).then(() => {
      return relation.query().find();
    }).then((list) => {
      equal(list.length, 0,
            "Delete should have worked");
      ok(!parent.dirty("child"),
         "The relation should not be dirty");
      done();
    });
  });

  it("query relation without schema", (done) => {
    var ChildObject = Parse.Object.extend("ChildObject");
    var childObjects = [];
    for (var i = 0; i < 10; i++) {
      childObjects.push(new ChildObject({x:i}));
    };

    Parse.Object.saveAll(childObjects, expectSuccess({
      success: function(list) {
        var ParentObject = Parse.Object.extend("ParentObject");
        var parent = new ParentObject();
        parent.set("x", 4);
        var relation = parent.relation("child");
        relation.add(childObjects[0]);
        parent.save(null, expectSuccess({
          success: function() {
            var parentAgain = new ParentObject();
            parentAgain.id = parent.id;
            var relation = parentAgain.relation("child");
            relation.query().find(expectSuccess({
              success: function(list) {
                equal(list.length, 1,
                      "Should have gotten one element back");
                equal(list[0].id, childObjects[0].id,
                      "Should have gotten the right value");
                done();
              }
            }));
          }
        }));
      }
    }));
  });

  it("relations are constructed right from query", (done) => {

    var ChildObject = Parse.Object.extend("ChildObject");
    var childObjects = [];
    for (var i = 0; i < 10; i++) {
      childObjects.push(new ChildObject({x: i}));
    }

    Parse.Object.saveAll(childObjects, {
      success: function(list) {
        var ParentObject = Parse.Object.extend("ParentObject");
        var parent = new ParentObject();
        parent.set("x", 4);
        var relation = parent.relation("child");
        relation.add(childObjects[0]);
        parent.save(null, {
          success: function() {
            var query = new Parse.Query(ParentObject);
            query.get(parent.id, {
              success: function(object) {
                var relationAgain = object.relation("child");
                relationAgain.query().find({
                  success: function(list) {
                    equal(list.length, 1,
                          "Should have gotten one element back");
                    equal(list[0].id, childObjects[0].id,
                          "Should have gotten the right value");
                    ok(!parent.dirty("child"),
                       "The relation should not be dirty");
                    done();
                  },
                  error: function(list) {
                    ok(false, "This shouldn't have failed");
                    done();
                  }
                });

              }
            });
          }
        });
      }
    });

  });

  it("compound add and remove relation", (done) => {
    var ChildObject = Parse.Object.extend("ChildObject");
    var childObjects = [];
    for (var i = 0; i < 10; i++) {
      childObjects.push(new ChildObject({x: i}));
    }

    var parent;
    var relation;

    Parse.Object.saveAll(childObjects).then(function(list) {
      var ParentObject = Parse.Object.extend('ParentObject');
      parent = new ParentObject();
      parent.set('x', 4);
      relation = parent.relation('child');
      relation.add(childObjects[0]);
      relation.add(childObjects[1]);
      relation.remove(childObjects[0]);
      relation.add(childObjects[2]);
      return parent.save();
    }).then(function() {
      return relation.query().find();
    }).then(function(list) {
      equal(list.length, 2, 'Should have gotten two elements back');
      ok(!parent.dirty('child'), 'The relation should not be dirty');
      relation.remove(childObjects[1]);
      relation.remove(childObjects[2]);
      relation.add(childObjects[1]);
      relation.add(childObjects[0]);
      return parent.save();
    }).then(function() {
      return relation.query().find();
    }).then(function(list) {
      equal(list.length, 2, 'Deletes and then adds should have worked');
      ok(!parent.dirty('child'), 'The relation should not be dirty');
      done();
    }, function(err) {
      ok(false, err.message);
      done();
    });
  });

  it("queries with relations", (done) => {

    var ChildObject = Parse.Object.extend("ChildObject");
    var childObjects = [];
    for (var i = 0; i < 10; i++) {
      childObjects.push(new ChildObject({x: i}));
    }

    Parse.Object.saveAll(childObjects, {
      success: function() {
        var ParentObject = Parse.Object.extend("ParentObject");
        var parent = new ParentObject();
        parent.set("x", 4);
        var relation = parent.relation("child");
        relation.add(childObjects[0]);
        relation.add(childObjects[1]);
        relation.add(childObjects[2]);
        parent.save(null, {
          success: function() {
            var query = relation.query();
            query.equalTo("x", 2);
            query.find({
              success: function(list) {
                equal(list.length, 1,
                      "There should only be one element");
                ok(list[0] instanceof ChildObject,
                   "Should be of type ChildObject");
                equal(list[0].id, childObjects[2].id,
                      "We should have gotten back the right result");
                done();
              }
            });
          }
        });
      }
    });
  });

  it("queries on relation fields", (done) => {
    var ChildObject = Parse.Object.extend("ChildObject");
    var childObjects = [];
    for (var i = 0; i < 10; i++) {
      childObjects.push(new ChildObject({x: i}));
    }

    Parse.Object.saveAll(childObjects, {
      success: function() {
        var ParentObject = Parse.Object.extend("ParentObject");
        var parent = new ParentObject();
        parent.set("x", 4);
        var relation = parent.relation("child");
        relation.add(childObjects[0]);
        relation.add(childObjects[1]);
        relation.add(childObjects[2]);
        var parent2 = new ParentObject();
        parent2.set("x", 3);
        var relation2 = parent2.relation("child");
        relation2.add(childObjects[4]);
        relation2.add(childObjects[5]);
        relation2.add(childObjects[6]);
        var parents = [];
        parents.push(parent);
        parents.push(parent2);
        Parse.Object.saveAll(parents, {
          success: function() {
            var query = new Parse.Query(ParentObject);
            var objects = [];
            objects.push(childObjects[4]);
            objects.push(childObjects[9]);
            query.containedIn("child", objects);
            query.find({
              success: function(list) {
                equal(list.length, 1, "There should be only one result");
                equal(list[0].id, parent2.id,
                      "Should have gotten back the right result");
                done();
              }
            });
          }
        });
      }
    });
  });

  it("queries on relation fields with multiple ins", (done) => {
    var ChildObject = Parse.Object.extend("ChildObject");
    var childObjects = [];
    for (var i = 0; i < 10; i++) {
      childObjects.push(new ChildObject({x: i}));
    }

    Parse.Object.saveAll(childObjects).then(() => {
      var ParentObject = Parse.Object.extend("ParentObject");
      var parent = new ParentObject();
      parent.set("x", 4);
      var relation = parent.relation("child");
      relation.add(childObjects[0]);
      relation.add(childObjects[1]);
      relation.add(childObjects[2]);
      var parent2 = new ParentObject();
      parent2.set("x", 3);
      var relation2 = parent2.relation("child");
      relation2.add(childObjects[4]);
      relation2.add(childObjects[5]);
      relation2.add(childObjects[6]);

      var otherChild2 = parent2.relation("otherChild");
      otherChild2.add(childObjects[0]);
      otherChild2.add(childObjects[1]);
      otherChild2.add(childObjects[2]);

      var parents = [];
      parents.push(parent);
      parents.push(parent2);
      return Parse.Object.saveAll(parents);
    }).then(() => {
      var query = new Parse.Query(ParentObject);
      var objects = [];
      objects.push(childObjects[0]);
      query.containedIn("child", objects);
      query.containedIn("otherChild", [childObjects[0]]);
      return query.find();
    }).then((list) => {
      equal(list.length, 2, "There should be 2 results");
      done();
    });
  });

  it("query on pointer and relation fields with equal", (done) => {
    var ChildObject = Parse.Object.extend("ChildObject");
    var childObjects = [];
    for (var i = 0; i < 10; i++) {
      childObjects.push(new ChildObject({x: i}));
    }

    Parse.Object.saveAll(childObjects).then(() => {
        var ParentObject = Parse.Object.extend("ParentObject");
        var parent = new ParentObject();
        parent.set("x", 4);
        var relation = parent.relation("toChilds");
        relation.add(childObjects[0]);
        relation.add(childObjects[1]);
        relation.add(childObjects[2]);

        var parent2 = new ParentObject();
        parent2.set("x", 3);
        parent2.set("toChild", childObjects[2]);

        var parents = [];
        parents.push(parent);
        parents.push(parent2);
        parents.push(new ParentObject());

       return Parse.Object.saveAll(parents).then(() => {
          var query = new Parse.Query(ParentObject);
          query.equalTo("objectId", parent.id);
          query.equalTo("toChilds", childObjects[2]);

          return query.find().then((list) => {
            equal(list.length, 1, "There should be 1 result");
            done();
          });
        });
    });
  });

  it("query on pointer and relation fields with equal bis", (done) => {
    var ChildObject = Parse.Object.extend("ChildObject");
    var childObjects = [];
    for (var i = 0; i < 10; i++) {
      childObjects.push(new ChildObject({x: i}));
    }

    Parse.Object.saveAll(childObjects).then(() => {
        var ParentObject = Parse.Object.extend("ParentObject");
        var parent = new ParentObject();
        parent.set("x", 4);
        var relation = parent.relation("toChilds");
        relation.add(childObjects[0]);
        relation.add(childObjects[1]);
        relation.add(childObjects[2]);

        var parent2 = new ParentObject();
        parent2.set("x", 3);
        parent2.relation("toChilds").add(childObjects[2]);

        var parents = [];
        parents.push(parent);
        parents.push(parent2);
        parents.push(new ParentObject());

       return Parse.Object.saveAll(parents).then(() => {
          var query = new Parse.Query(ParentObject);
          query.equalTo("objectId", parent2.id);
          // childObjects[2] is in 2 relations
          // before the fix, that woul yield 2 results
          query.equalTo("toChilds", childObjects[2]);

          return query.find().then((list) => {
            equal(list.length, 1, "There should be 1 result");
            done();
          });
        });
    });
  });

  it("or queries on pointer and relation fields", (done) => {
    var ChildObject = Parse.Object.extend("ChildObject");
    var childObjects = [];
    for (var i = 0; i < 10; i++) {
      childObjects.push(new ChildObject({x: i}));
    }

    Parse.Object.saveAll(childObjects).then(() => {
        var ParentObject = Parse.Object.extend("ParentObject");
        var parent = new ParentObject();
        parent.set("x", 4);
        var relation = parent.relation("toChilds");
        relation.add(childObjects[0]);
        relation.add(childObjects[1]);
        relation.add(childObjects[2]);

        var parent2 = new ParentObject();
        parent2.set("x", 3);
        parent2.set("toChild", childObjects[2]);

        var parents = [];
        parents.push(parent);
        parents.push(parent2);
        parents.push(new ParentObject());

       return Parse.Object.saveAll(parents).then(() => {
          var query1 = new Parse.Query(ParentObject);
          query1.containedIn("toChilds", [childObjects[2]]);
          var query2 = new Parse.Query(ParentObject);
          query2.equalTo("toChild", childObjects[2]);
          var query = Parse.Query.or(query1, query2);
          return query.find().then((list) => {
            var objectIds = list.map(function(item){
              return item.id;
            });
            expect(objectIds.indexOf(parent.id)).not.toBe(-1);
            expect(objectIds.indexOf(parent2.id)).not.toBe(-1);
            equal(list.length, 2, "There should be 2 results");
            done();
          });
        });
    });
  });

  it("Get query on relation using un-fetched parent object", (done) => {
    // Setup data model
    var Wheel = Parse.Object.extend('Wheel');
    var Car = Parse.Object.extend('Car');
    var origWheel = new Wheel();
    origWheel.save().then(function() {
      var car = new Car();
      var relation = car.relation('wheels');
      relation.add(origWheel);
      return car.save();
    }).then(function(car) {
      // Test starts here.
      // Create an un-fetched shell car object
      var unfetchedCar = new Car();
      unfetchedCar.id = car.id;
      var relation = unfetchedCar.relation('wheels');
      var query = relation.query();

      // Parent object is un-fetched, so this will call /1/classes/Car instead
      // of /1/classes/Wheel and pass { "redirectClassNameForKey":"wheels" }.
      return query.get(origWheel.id);
    }).then(function(wheel) {
      // Make sure this is Wheel and not Car.
      strictEqual(wheel.className, 'Wheel');
      strictEqual(wheel.id, origWheel.id);
    }).then(function() {
      done();
    },function(err) {
      ok(false, 'unexpected error: ' + JSON.stringify(err));
      done();
    });
  });

  it("Find query on relation using un-fetched parent object", (done) => {
    // Setup data model
    var Wheel = Parse.Object.extend('Wheel');
    var Car = Parse.Object.extend('Car');
    var origWheel = new Wheel();
    origWheel.save().then(function() {
      var car = new Car();
      var relation = car.relation('wheels');
      relation.add(origWheel);
      return car.save();
    }).then(function(car) {
      // Test starts here.
      // Create an un-fetched shell car object
      var unfetchedCar = new Car();
      unfetchedCar.id = car.id;
      var relation = unfetchedCar.relation('wheels');
      var query = relation.query();

      // Parent object is un-fetched, so this will call /1/classes/Car instead
      // of /1/classes/Wheel and pass { "redirectClassNameForKey":"wheels" }.
      return query.find(origWheel.id);
    }).then(function(results) {
      // Make sure this is Wheel and not Car.
      var wheel = results[0];
      strictEqual(wheel.className, 'Wheel');
      strictEqual(wheel.id, origWheel.id);
    }).then(function() {
      done();
    },function(err) {
      ok(false, 'unexpected error: ' + JSON.stringify(err));
      done();
    });
  });

  it('Find objects with a related object using equalTo', (done) => {
    // Setup the objects
    var Card = Parse.Object.extend('Card');
    var House = Parse.Object.extend('House');
    var card = new Card();
    card.save().then(() => {
      var house = new House();
      var relation = house.relation('cards');
      relation.add(card);
      return house.save();
    }).then(() => {
      var query = new Parse.Query('House');
      query.equalTo('cards', card);
      return query.find();
    }).then((results) => {
      expect(results.length).toEqual(1);
      done();
    });
  });

});


text:
var ArgumentInvalidException = require(
	'../../exception/argument-invalid-exception');
var isString = require('lodash/lang/isString');

/**
 * Assert an object is an objet.
 * @param  {string} name - The property name
 * @param  {string} data - The data to validate.
 * @return {undefined} - Return nothing, throw an Exception if this is not valid.
 */
module.exports = function(name, data) {
	if (!isString(data)) {
		throw new ArgumentInvalidException(`${name} should be a string`, data);
	}
};


text:
var __hasProp = {}.hasOwnProperty,
  __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

define(function(require) {
  var Navbar, templ, _ref;

  templ = require('templates/navbar');
  Navbar = (function(_super) {
    __extends(Navbar, _super);

    function Navbar() {
      _ref = Navbar.__super__.constructor.apply(this, arguments);
      return _ref;
    }

    Navbar.prototype.className = "navbar-view";

    Navbar.prototype.content = templ;

    return Navbar;

  })(dermis.View);
  return Navbar;
});


text:
package com.qaprosoft.carina.demo.mobile.gui.pages.common;

import org.openqa.selenium.WebDriver;

import com.qaprosoft.carina.core.gui.AbstractPage;

public abstract class LoginPageBase extends AbstractPage {

	public LoginPageBase(WebDriver driver) {
		super(driver);
	}

	public abstract void typeName(String name);

	public abstract void typePassword(String password);

	public abstract void selectMaleSex();

	public abstract void checkPrivacyPolicyCheckbox();

	public abstract CarinaDescriptionPageBase clickLoginBtn();

	public abstract boolean isLoginBtnActive();

	public abstract CarinaDescriptionPageBase login();

}


text:
using System;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.TextFormatting;

using SharpLib.Texter.Utils;

namespace SharpLib.Texter.Rendering
{
    public class FormattedTextElement : VisualLineElement
    {
        #region Поля

        internal readonly FormattedText formattedText;

        internal string text;

        internal TextLine textLine;

        #endregion

        #region Свойства

        public LineBreakCondition BreakBefore { get; set; }

        public LineBreakCondition BreakAfter { get; set; }

        #endregion

        #region Конструктор

        public FormattedTextElement(string text, int documentLength)
            : base(1, documentLength)
        {
            if (text == null)
            {
                throw new ArgumentNullException("text");
            }
            this.text = text;
            BreakBefore = LineBreakCondition.BreakPossible;
            BreakAfter = LineBreakCondition.BreakPossible;
        }

        public FormattedTextElement(TextLine text, int documentLength)
            : base(1, documentLength)
        {
            if (text == null)
            {
                throw new ArgumentNullException("text");
            }
            textLine = text;
            BreakBefore = LineBreakCondition.BreakPossible;
            BreakAfter = LineBreakCondition.BreakPossible;
        }

        public FormattedTextElement(FormattedText text, int documentLength)
            : base(1, documentLength)
        {
            if (text == null)
            {
                throw new ArgumentNullException("text");
            }
            formattedText = text;
            BreakBefore = LineBreakCondition.BreakPossible;
            BreakAfter = LineBreakCondition.BreakPossible;
        }

        #endregion

        #region Методы

        public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context)
        {
            if (textLine == null)
            {
                var formatter = TextFormatterFactory.Create(context.TextView);
                textLine = PrepareText(formatter, text, TextRunProperties);
                text = null;
            }
            return new FormattedTextRun(this, TextRunProperties);
        }

        public static TextLine PrepareText(TextFormatter formatter, string text, TextRunProperties properties)
        {
            if (formatter == null)
            {
                throw new ArgumentNullException("formatter");
            }
            if (text == null)
            {
                throw new ArgumentNullException("text");
            }
            if (properties == null)
            {
                throw new ArgumentNullException("properties");
            }
            return formatter.FormatLine(
                new SimpleTextSource(text, properties),
                0,
                32000,
                new VisualLineTextParagraphProperties
                {
                    defaultTextRunProperties = properties,
                    textWrapping = TextWrapping.NoWrap,
                    tabSize = 40
                },
                null);
        }

        #endregion
    }
}