text:
#include <debug.h>
#include <dev/fbcon.h>
#include <target.h>
#include <mmc.h>
#include <partition_parser.h>
#include <platform.h>
#include <crypto_hash.h>
#include <malloc.h>
#include <sha.h>
#include <string.h>
#include <rand.h>
#include <stdlib.h>
#include <boot_verifier.h>
#include <image_verify.h>
#include "scm.h"
#include "mdtp.h"

#define DIP_ENCRYPT              (0)
#define DIP_DECRYPT              (1)
#define MAX_CIPHER_DIP_SCM_CALLS (3)

#define MDTP_MAJOR_VERSION (0)
#define MDTP_MINOR_VERSION (2)

/** Extract major version number from complete version. */
#define MDTP_GET_MAJOR_VERSION(version) ((version) >> 16)

static int mdtp_tzbsp_dec_verify_DIP(DIP_t *enc_dip, DIP_t *dec_dip, uint32_t *verified);
static int mdtp_tzbsp_enc_hash_DIP(DIP_t *dec_dip, DIP_t *enc_dip);
static void mdtp_tzbsp_disallow_cipher_DIP(void);

uint32_t g_mdtp_version = (((MDTP_MAJOR_VERSION << 16) & 0xFFFF0000) | (MDTP_MINOR_VERSION & 0x0000FFFF));
static int is_mdtp_activated = -1;

int check_aboot_addr_range_overlap(uint32_t start, uint32_t size);
int scm_random(uint32_t * rbuf, uint32_t  r_len);
void free_mdtp_image(void);

/********************************************************************************/

/* Read the DIP from EMMC */
static int read_DIP(DIP_t *dip)
{
	unsigned long long ptn = 0;
	uint32_t actual_partition_size;
	uint32_t block_size = mmc_get_device_blocksize();

	int index = INVALID_PTN;

	ASSERT(dip != NULL);

	index = partition_get_index("dip");
	ptn = partition_get_offset(index);

	if(ptn == 0)
	{
		return -1;
	}

	actual_partition_size = ROUNDUP(sizeof(DIP_t), block_size);

	if(mmc_read(ptn, (void *)dip, actual_partition_size))
	{
		dprintf(CRITICAL, "mdtp: read_DIP: ERROR, cannot read DIP info\n");
		return -1;
	}

	dprintf(SPEW, "mdtp: read_DIP: SUCCESS, read %d bytes\n", actual_partition_size);

	return 0;
}

/* Store the DIP into the EMMC */
static int write_DIP(DIP_t *dip)
{
	unsigned long long ptn = 0;
	uint32_t block_size = mmc_get_device_blocksize();

	int index = INVALID_PTN;

	ASSERT(dip != NULL);

	index = partition_get_index("dip");
	ptn = partition_get_offset(index);

	if(ptn == 0)
	{
		return -1;
	}

	if(mmc_write(ptn, ROUNDUP(sizeof(DIP_t), block_size), (void *)dip))
	{
		dprintf(CRITICAL, "mdtp: write_DIP: ERROR, cannot write DIP info\n");
		return -1;
	}

	dprintf(SPEW, "mdtp: write_DIP: SUCCESS, write %d bytes\n", ROUNDUP(sizeof(DIP_t), block_size));

	return 0;
}

/* Deactivate MDTP by storing the default DIP into the EMMC */
static void write_deactivated_DIP()
{
	DIP_t *enc_dip;
	DIP_t *dec_dip;
	int ret;

	enc_dip = malloc(sizeof(DIP_t));
	if (enc_dip == NULL)
	{
		dprintf(CRITICAL, "mdtp: write_deactivated_DIP: ERROR, cannot allocate DIP\n");
		return;
	}

	dec_dip = malloc(sizeof(DIP_t));
	if (dec_dip == NULL)
	{
		dprintf(CRITICAL, "mdtp: write_deactivated_DIP: ERROR, cannot allocate DIP\n");
		free(enc_dip);
		return;
	}

	memset(dec_dip, 0, sizeof(DIP_t));

	dec_dip->status = DIP_STATUS_DEACTIVATED;
	dec_dip->version = g_mdtp_version;

	ret = mdtp_tzbsp_enc_hash_DIP(dec_dip, enc_dip);
	if(ret < 0)
	{
		dprintf(CRITICAL, "mdtp: write_deactivated_DIP: ERROR, cannot cipher DIP\n");
		goto out;
	}

	ret = write_DIP(enc_dip);
	if(ret < 0)
	{
		dprintf(CRITICAL, "mdtp: write_deactivated_DIP: ERROR, cannot write DIP\n");
		goto out;
	}

out:
	free(enc_dip);
	free(dec_dip);
}

/* Validate a hash calculated on entire given partition */
static int verify_partition_single_hash(char *name, uint64_t size, DIP_hash_table_entry_t *hash_table)
{
	unsigned char digest[HASH_LEN]={0};
	unsigned long long ptn = 0;
	int index = INVALID_PTN;
	unsigned char *buf = (unsigned char *)target_get_scratch_address() + MDTP_SCRATCH_OFFSET;
	uint32_t block_size = mmc_get_device_blocksize();
	uint64_t actual_partition_size = ROUNDUP(size, block_size);

	dprintf(SPEW, "mdtp: verify_partition_single_hash: %s, %llu\n", name, size);

	ASSERT(name != NULL);
	ASSERT(hash_table != NULL);
	ASSERT(size > 0);

	index = partition_get_index(name);
	ptn = partition_get_offset(index);

	if(ptn == 0) {
		dprintf(CRITICAL, "mdtp: verify_partition_single_hash: %s: partition was not found\n", name);
		return -1;
	}

	if (mmc_read(ptn, (void *)buf, actual_partition_size))
	{
		dprintf(CRITICAL, "mdtp: verify_partition_single_hash: %s: mmc_read() fail.\n", name);
		return -1;
	}

	/* calculating the hash value using HW crypto */
	target_crypto_init_params();
	hash_find(buf, size, digest, CRYPTO_AUTH_ALG_SHA256);

	if (memcmp(digest, hash_table->hash, HASH_LEN))
	{
		dprintf(CRITICAL, "mdtp: verify_partition_single_hash: %s: Failed partition hash verification\n", name);

		return -1;
	}

	dprintf(SPEW, "verify_partition_single_hash: %s: VERIFIED!\n", name);

	return 0;
}

/* Validate a hash table calculated per block of a given partition */
static int verify_partition_block_hash(char *name,
								uint64_t size,
								uint32_t verify_num_blocks,
								DIP_hash_table_entry_t *hash_table,
								uint8_t *force_verify_block)
{
	unsigned char digest[HASH_LEN]={0};
	unsigned long long ptn = 0;
	int index = INVALID_PTN;
	unsigned char *buf = (unsigned char *)target_get_scratch_address() + MDTP_SCRATCH_OFFSET;
	uint32_t bytes_to_read;
	uint32_t block_num = 0;
	uint32_t total_num_blocks = ((size - 1) / MDTP_FWLOCK_BLOCK_SIZE) + 1;
	uint32_t rand_int;
	uint32_t block_size = mmc_get_device_blocksize();

	dprintf(SPEW, "mdtp: verify_partition_block_hash: %s, %llu\n", name, size);

	ASSERT(name != NULL);
	ASSERT(hash_table != NULL);
	ASSERT(size > 0);
	ASSERT(force_verify_block != NULL);

	index = partition_get_index(name);
	ptn = partition_get_offset(index);

	if(ptn == 0) {
		dprintf(CRITICAL, "mdtp: verify_partition_block_hash: %s: partition was not found\n", name);
		return -1;
	}

	/* initiating parameters for hash calculation using HW crypto */
	target_crypto_init_params();
	if (check_aboot_addr_range_overlap((uint32_t)buf, ROUNDUP(MDTP_FWLOCK_BLOCK_SIZE, block_size)))
	{
		dprintf(CRITICAL, "mdtp: verify_partition_block_hash: %s: image buffer address overlaps with aboot addresses.\n", name);
		return -1;
	}

	while (MDTP_FWLOCK_BLOCK_SIZE * block_num < size)
	{
		if (*force_verify_block == 0)
		{
			if(scm_random((uint32_t *)&rand_int, sizeof(rand_int)))
			{
				dprintf(CRITICAL,"mdtp: scm_call for random failed\n");
				return -1;
			}

			/* Skip validation of this block with probability of verify_num_blocks / total_num_blocks */
			if ((rand_int % total_num_blocks) >= verify_num_blocks)
			{
				block_num++;
				hash_table += 1;
				force_verify_block += 1;
				dprintf(CRITICAL, "mdtp: verify_partition_block_hash: %s: skipped verification of block %d\n", name, block_num);
				continue;
			}
		}

		if ((size - (MDTP_FWLOCK_BLOCK_SIZE * block_num) <  MDTP_FWLOCK_BLOCK_SIZE))
		{
			bytes_to_read = size - (MDTP_FWLOCK_BLOCK_SIZE * block_num);
		} else
		{
			bytes_to_read = MDTP_FWLOCK_BLOCK_SIZE;
		}

		if (mmc_read(ptn + (MDTP_FWLOCK_BLOCK_SIZE * block_num), (void *)buf, ROUNDUP(bytes_to_read, block_size)))
		{
			dprintf(CRITICAL, "mdtp: verify_partition_block_hash: %s: mmc_read() fail.\n", name);
			return -1;
		}

		/* calculating the hash value using HW */
		hash_find(buf, bytes_to_read, digest, CRYPTO_AUTH_ALG_SHA256);

		if (memcmp(digest, hash_table->hash, HASH_LEN))
		{
			dprintf(CRITICAL, "mdtp: verify_partition_block_hash: %s: Failed partition hash[%d] verification\n", name, block_num);
			return -1;
		}

		block_num++;
		hash_table += 1;
		force_verify_block += 1;
	}

	dprintf(SPEW, "verify_partition_block_hash: %s: VERIFIED!\n", name);

	return 0;
}

/* Validate the partition parameters read from DIP */
static int validate_partition_params(uint64_t size,
						mdtp_fwlock_mode_t hash_mode,
						uint32_t verify_ratio)
{
	if (size == 0 || size > (uint64_t)MDTP_FWLOCK_BLOCK_SIZE * (uint64_t)MAX_BLOCKS ||
		hash_mode >= MDTP_FWLOCK_MODE_SIZE || verify_ratio > 100)
	{
		dprintf(CRITICAL, "mdtp: validate_partition_params: error, size=%llu, hash_mode=%d, verify_ratio=%d\n",
			size, hash_mode, verify_ratio);
		return -1;
	}

	return 0;
}

/* Verify a given partitinon */
static int verify_partition(char *name,
						uint64_t size,
						mdtp_fwlock_mode_t hash_mode,
						uint32_t verify_num_blocks,
						DIP_hash_table_entry_t *hash_table,
						uint8_t *force_verify_block)
{
	if (hash_mode == MDTP_FWLOCK_MODE_SINGLE)
	{
		return verify_partition_single_hash(name, size, hash_table);
	} else if (hash_mode == MDTP_FWLOCK_MODE_BLOCK || hash_mode == MDTP_FWLOCK_MODE_FILES)
	{
		return verify_partition_block_hash(name, size, verify_num_blocks, hash_table, force_verify_block);
	}

	/* Illegal value of hash_mode */
	return -1;
}

static int validate_dip(DIP_t *dip)
{
	uint8_t *dip_p;

	ASSERT(dip != NULL);

	/* Make sure DIP version is supported by current SW */
	if (MDTP_GET_MAJOR_VERSION(dip->version) != MDTP_MAJOR_VERSION)
	{
		dprintf(CRITICAL, "mdtp: validate_dip: Wrong DIP version 0x%x\n", dip->version);
		return -1;
	}

	/* Make sure that deactivated DIP content is as expected */
	if (dip->status == DIP_STATUS_DEACTIVATED)
	{
		dip_p = (uint8_t*)&dip->mdtp_cfg;
		while (dip_p < dip->hash)
		{
			if (*dip_p != 0)
			{
				dprintf(CRITICAL, "mdtp: validate_dip: error in deactivated DIP\n");
				return -1;
			}
			dip_p++;
		}
	}

	return 0;
}

/* Display the recovery UI to allow the user to enter the PIN and continue boot */
static void display_recovery_ui(mdtp_cfg_t *mdtp_cfg)
{
	uint32_t pin_length = 0;
	char entered_pin[MDTP_MAX_PIN_LEN+1] = {0};
	uint32_t i;
	char pin_mismatch = 0;

	if (mdtp_cfg->enable_local_pin_authentication)
	{
		dprintf(SPEW, "mdtp: display_recovery_ui: Local deactivation enabled\n");

		pin_length = strlen(mdtp_cfg->mdtp_pin.mdtp_pin);

		if (pin_length > MDTP_MAX_PIN_LEN || pin_length < MDTP_MIN_PIN_LEN)
		{
			dprintf(CRITICAL, "mdtp: display_recovery_ui: Error, invalid PIN length\n");
			display_error_msg(); /* This will never return */
		}

		// Set entered_pin to initial '0' string + null terminator
		for (i=0; i<pin_length; i++)
		{
			entered_pin[i] = '0';
		}

		// Allow the user to enter the PIN as many times as he wishes
		// (with INVALID_PIN_DELAY_MSECONDS after each failed attempt)
		while (1)
		{
			get_pin_from_user(entered_pin, pin_length);

			// Go over the entire PIN in any case, to prevent side-channel attacks
			for (i=0; i<pin_length; i++)
			{
				pin_mismatch |= mdtp_cfg->mdtp_pin.mdtp_pin[i] ^ entered_pin[i];
			}

			if (0 == pin_mismatch)
			{
				// Valid PIN - deactivate and continue boot
				dprintf(SPEW, "mdtp: display_recovery_ui: valid PIN, continue boot\n");
				write_deactivated_DIP();
				goto out;
			}
			else
			{
				// Invalid PIN - display an appropriate message (which also includes a wait
				// for INVALID_PIN_DELAY_MSECONDS), and allow the user to try again
				dprintf(CRITICAL, "mdtp: display_recovery_ui: ERROR, invalid PIN\n");
				display_invalid_pin_msg();

				pin_mismatch = 0;
			}
		}
	}
	else
	{
		dprintf(CRITICAL, "mdtp: display_recovery_ui: Local deactivation disabled, unable to display recovery UI\n");
		display_error_msg(); /* This will never return */
	}

	out:
	free_mdtp_image();
}

/* Verify the boot or recovery partitions using boot_verifier. */
static int verify_ext_partition(mdtp_ext_partition_verification_t *ext_partition)
{
	int ret = 0;
	bool restore_to_orange = false;
	unsigned long long ptn = 0;
	int index = INVALID_PTN;

	/* If image was already verified in aboot, return its status */
	if (ext_partition->integrity_state == MDTP_PARTITION_STATE_INVALID)
	{
		dprintf(CRITICAL, "mdtp: verify_ext_partition: image %s verified externally and failed.\n",
				ext_partition->partition == MDTP_PARTITION_BOOT ? "boot" : "recovery");
		return -1;
	}
	else if (ext_partition->integrity_state == MDTP_PARTITION_STATE_VALID)
	{
		dprintf(CRITICAL, "mdtp: verify_ext_partition: image %s verified externally succesfully.\n",
				ext_partition->partition == MDTP_PARTITION_BOOT ? "boot" : "recovery");
		return 0;
	}

	/* If image was not verified in aboot, verify it ourselves using boot_verifier. */

	/* 1) Initialize keystore. We don't care about return value which is Verified Boot's state machine state. */
	boot_verify_keystore_init();

	/* 2) If boot_verifier is ORANGE, it will prevent verifying an image. So
	 *    temporarly change boot_verifier state to BOOT_INIT.
	 */
	if (boot_verify_get_state() == ORANGE)
		restore_to_orange = true;
	boot_verify_send_event(BOOT_INIT);

	switch (ext_partition->partition)
	{
	case MDTP_PARTITION_BOOT:
	case MDTP_PARTITION_RECOVERY:

		/* 3) Signature may or may not be at the end of the image. Read the signature if needed. */
		if (!ext_partition->sig_avail)
		{
			if (check_aboot_addr_range_overlap((uint32_t)(ext_partition->image_addr + ext_partition->image_size), ext_partition->page_size))
			{
				dprintf(CRITICAL, "ERROR: Signature read buffer address overlaps with aboot addresses.\n");
				return -1;
			}

			index = partition_get_index(ext_partition->partition == MDTP_PARTITION_BOOT ? "boot" : "recovery");
			ptn = partition_get_offset(index);
			if(ptn == 0) {
				dprintf(CRITICAL, "ERROR: partition %s not found\n",
					ext_partition->partition == MDTP_PARTITION_BOOT ? "boot" : "recovery");
				return -1;
			}

			if(mmc_read(ptn + ext_partition->image_size, (void *)(ext_partition->image_addr + ext_partition->image_size), ext_partition->page_size))
			{
				dprintf(CRITICAL, "ERROR: Cannot read %s image signature\n",
					ext_partition->partition == MDTP_PARTITION_BOOT ? "boot" : "recovery");
				return -1;
			}
		}

		/* 4) Verify the image using its signature. */
		ret = boot_verify_image((unsigned char *)ext_partition->image_addr,
								ext_partition->image_size,
								ext_partition->partition == MDTP_PARTITION_BOOT ? "/boot" : "/recovery");
		break;

	default:
		/* Only boot and recovery are legal here */
		dprintf(CRITICAL, "ERROR: wrong partition %d\n", ext_partition->partition);
		return -1;
	}

	if (ret)
	{
		dprintf(INFO, "mdtp: verify_ext_partition: image %s verified succesfully in MDTP.\n",
				ext_partition->partition == MDTP_PARTITION_BOOT ? "boot" : "recovery");
	}
	else
	{
		dprintf(CRITICAL, "mdtp: verify_ext_partition: image %s verification failed in MDTP.\n",
				ext_partition->partition == MDTP_PARTITION_BOOT ? "boot" : "recovery");
	}

	/* 5) Restore the right boot_verifier state upon exit. */
	if (restore_to_orange)
	{
		boot_verify_send_event(DEV_UNLOCK);
	}

	return ret ? 0 : -1;
}

/* Verify all protected partitinons according to the DIP */
static void verify_all_partitions(DIP_t *dip,
								 mdtp_ext_partition_verification_t *ext_partition,
								 verify_result_t *verify_result)
{
	int i;
	int verify_failure = 0;
	int ext_partition_verify_failure = 0;
	uint32_t total_num_blocks;

	ASSERT(dip != NULL);
	ASSERT(verify_result != NULL);

	*verify_result = VERIFY_FAILED;

	if (validate_dip(dip))
	{
		dprintf(CRITICAL, "mdtp: verify_all_partitions: failed DIP validation\n");
		return;
	}

	if (dip->status == DIP_STATUS_DEACTIVATED)
	{
		*verify_result = VERIFY_SKIPPED;
		return;
	}
	else
	{
		for(i=0; i<MAX_PARTITIONS; i++)
		{
			if(dip->partition_cfg[i].lock_enabled && dip->partition_cfg[i].size)
			{
				total_num_blocks = ((dip->partition_cfg[i].size - 1) / MDTP_FWLOCK_BLOCK_SIZE);
				if (validate_partition_params(dip->partition_cfg[i].size,
					dip->partition_cfg[i].hash_mode,
					dip->partition_cfg[i].verify_ratio))
				{
					dprintf(CRITICAL, "mdtp: verify_all_partitions: Wrong partition parameters\n");
					verify_failure = TRUE;
					break;
				}

				verify_failure |= (verify_partition(dip->partition_cfg[i].name,
							 dip->partition_cfg[i].size,
							 dip->partition_cfg[i].hash_mode,
							 (dip->partition_cfg[i].verify_ratio * total_num_blocks) / 100,
							 dip->partition_cfg[i].hash_table,
							 dip->partition_cfg[i].force_verify_block) != 0);
			}
		}

		ext_partition_verify_failure = verify_ext_partition(ext_partition);

		if (verify_failure || ext_partition_verify_failure)
		{
			dprintf(CRITICAL, "mdtp: verify_all_partitions: Failed partition verification\n");
			return;
		}
		is_mdtp_activated = 1;

	}

	*verify_result = VERIFY_OK;
	return;
}

/* Verify the DIP and all protected partitions */
static void validate_DIP_and_firmware(mdtp_ext_partition_verification_t *ext_partition)
{
	int ret;
	DIP_t *enc_dip;
	DIP_t *dec_dip;
	uint32_t verified = 0;
	verify_result_t verify_result;
	uint32_t block_size = mmc_get_device_blocksize();
	mdtp_cfg_t mdtp_cfg;

	enc_dip = malloc(ROUNDUP(sizeof(DIP_t), block_size));
	if (enc_dip == NULL)
	{
		dprintf(CRITICAL, "mdtp: validate_DIP_and_firmware: ERROR, cannot allocate DIP\n");
		display_error_msg(); /* This will never return */
	}

	dec_dip = malloc(ROUNDUP(sizeof(DIP_t), block_size));
	if (dec_dip == NULL)
	{
		dprintf(CRITICAL, "mdtp: validate_DIP_and_firmware: ERROR, cannot allocate DIP\n");
		free(enc_dip);
		display_error_msg(); /* This will never return */
	}

	/* Read the DIP holding the MDTP Firmware Lock state from the DIP partition */
	ret = read_DIP(enc_dip);
	if(ret < 0)
	{
		dprintf(CRITICAL, "mdtp: validate_DIP_and_firmware: ERROR, cannot read DIP\n");
		display_error_msg(); /* This will never return */
	}

	/* Decrypt and verify the integrity of the DIP */
	ret = mdtp_tzbsp_dec_verify_DIP(enc_dip, dec_dip, &verified);
	if(ret < 0)
	{
		dprintf(CRITICAL, "mdtp: validate_DIP_and_firmware: ERROR, cannot verify DIP\n");
		display_error_msg(); /* This will never return */
	}

	/* In case DIP integrity verification fails, notify the user and halt */
	if(!verified)
	{
		dprintf(CRITICAL, "mdtp: validate_DIP_and_firmware: ERROR, corrupted DIP\n");
		display_error_msg(); /* This will never return */
	}

	/* Verify the integrity of the partitions which are protected, according to the content of the DIP */
	verify_all_partitions(dec_dip, ext_partition, &verify_result);

	mdtp_cfg = dec_dip->mdtp_cfg;

	/* Clear decrypted DIP since we don't need it anymore */
	memset(dec_dip, 0, sizeof(DIP_t));

	if (verify_result == VERIFY_OK)
	{
		dprintf(SPEW, "mdtp: validate_DIP_and_firmware: Verify OK\n");
	}
	else if (verify_result  == VERIFY_SKIPPED)
	{
		dprintf(SPEW, "mdtp: validate_DIP_and_firmware: Verify skipped\n");
	} else /* VERIFY_FAILED */
	{
		dprintf(CRITICAL, "mdtp: validate_DIP_and_firmware: ERROR, corrupted firmware\n");
		display_recovery_ui(&mdtp_cfg);
	}

	memset(&mdtp_cfg, 0, sizeof(mdtp_cfg));

	free(enc_dip);
	free(dec_dip);

	return;
}

/********************************************************************************/

/** Entry point of the MDTP Firmware Lock.
 *  If needed, verify the DIP and all protected partitions.
 *  Allow passing information about partition verified using an external method
 *  (either boot or recovery). For boot and recovery, either use aboot's
 *  verification result, or use boot_verifier APIs to verify internally.
 **/
void mdtp_fwlock_verify_lock(mdtp_ext_partition_verification_t *ext_partition)
{
	int ret;
	bool enabled;

	/* sets the default value of this global to be MDTP not activated */
	is_mdtp_activated = 0;

	do {
		if (ext_partition == NULL)
		{
			dprintf(CRITICAL, "mdtp: mdtp_fwlock_verify_lock: ERROR, external partition is NULL\n");
			display_error_msg(); /* This will never return */
			break;
		}

		ret = mdtp_fuse_get_enabled(&enabled);
		if(ret)
		{
			dprintf(CRITICAL, "mdtp: mdtp_fwlock_verify_lock: ERROR, cannot get enabled fuse\n");
			display_error_msg(); /* This will never return */
		}

		/* Continue with Firmware Lock verification only if enabled by eFuse */
		if (enabled)
		{
			/* This function will handle firmware verification failure via UI */
			validate_DIP_and_firmware(ext_partition);
		}
	} while (0);

	/* Disallow CIPHER_DIP SCM call from this point, unless we are in recovery */
	/* The recovery image will disallow CIPHER_DIP SCM call by itself. */
	if (ext_partition->partition != MDTP_PARTITION_RECOVERY)
	{
		mdtp_tzbsp_disallow_cipher_DIP();
	}
}
/********************************************************************************/

/** Indicates whether the MDTP is currently in ACTIVATED state **/
int mdtp_activated(bool * activated){
	if(is_mdtp_activated < 0){
		/* mdtp_fwlock_verify_lock was not called before, the value is not valid */
		return is_mdtp_activated;
	}

	*activated = is_mdtp_activated;
	return 0;
}

/********************************************************************************/

/* Decrypt a given DIP and verify its integrity */
static int mdtp_tzbsp_dec_verify_DIP(DIP_t *enc_dip, DIP_t *dec_dip, uint32_t *verified)
{
	unsigned char hash[HASH_LEN];
	SHA256_CTX sha256_ctx;
	int ret;

	ASSERT(enc_dip != NULL);
	ASSERT(dec_dip != NULL);
	ASSERT(verified != NULL);

	arch_clean_invalidate_cache_range((addr_t)enc_dip, sizeof(DIP_t));
	arch_invalidate_cache_range((addr_t)dec_dip, sizeof(DIP_t));

	ret = mdtp_cipher_dip_cmd((uint8_t*)enc_dip, sizeof(DIP_t),
								(uint8_t*)dec_dip, sizeof(DIP_t),
								DIP_DECRYPT);
	if (ret)
	{
		dprintf(CRITICAL, "mdtp: mdtp_tzbsp_dec_verify_DIP: ERROR, cannot cipher DIP\n");
		*verified = 0;
		memset(dec_dip, 0, sizeof(DIP_t));
		return -1;
	}

	arch_invalidate_cache_range((addr_t)dec_dip, sizeof(DIP_t));

	SHA256_Init(&sha256_ctx);
	SHA256_Update(&sha256_ctx, dec_dip, sizeof(DIP_t) - HASH_LEN);
	SHA256_Final(hash, &sha256_ctx);

	if (memcmp(hash, dec_dip->hash, HASH_LEN))
	{
		*verified = 0;
		memset(dec_dip, 0, sizeof(DIP_t));
	}
	else
	{
		*verified = 1;
	}

	return 0;
}

/* Encrypt a given DIP and calculate its integrity information */
static int mdtp_tzbsp_enc_hash_DIP(DIP_t *dec_dip, DIP_t *enc_dip)
{
	SHA256_CTX sha256_ctx;
	int ret;

	ASSERT(dec_dip != NULL);
	ASSERT(enc_dip != NULL);

	SHA256_Init(&sha256_ctx);
	SHA256_Update(&sha256_ctx, dec_dip, sizeof(DIP_t) - HASH_LEN);
	SHA256_Final(dec_dip->hash, &sha256_ctx);

	arch_clean_invalidate_cache_range((addr_t)dec_dip, sizeof(DIP_t));
	arch_invalidate_cache_range((addr_t)enc_dip, sizeof(DIP_t));

	ret = mdtp_cipher_dip_cmd((uint8_t*)dec_dip, sizeof(DIP_t),
								(uint8_t*)enc_dip, sizeof(DIP_t),
								DIP_ENCRYPT);
	if (ret)
	{
		dprintf(CRITICAL, "mdtp: mdtp_tzbsp_enc_hash_DIP: ERROR, cannot cipher DIP\n");
		return -1;
	}

	arch_invalidate_cache_range((addr_t)enc_dip, sizeof(DIP_t));

	return 0;
}

/* Disallow the CIPHER_DIP SCM call */
static void mdtp_tzbsp_disallow_cipher_DIP(void)
{
	DIP_t *dip;
	int i;

	dip = malloc(sizeof(DIP_t));
	if (dip == NULL)
	{
		dprintf(CRITICAL, "mdtp: mdtp_tzbsp_disallow_cipher_DIP: ERROR, cannot allocate DIP\n");
		return;
	}

	/* Disallow the CIPHER_DIP SCM by calling it MAX_CIPHER_DIP_SCM_CALLS times */
	for (i=0; i<MAX_CIPHER_DIP_SCM_CALLS; i++)
	{
		mdtp_tzbsp_enc_hash_DIP(dip, dip);
	}

	free(dip);
}


text:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Description;
using GeekQuiz.Models;

namespace QuizeApplication.Controllers
{
    [Authorize]
    public class TriviaController : ApiController
    {
        private TriviaContext db = new TriviaContext();

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                this.db.Dispose();
            }

            base.Dispose(disposing);
        }
        private async Task<TriviaQuestion> NextQuestionAsync(string userId)
        {
            var lastQuestionId = await this.db.TriviaAnswers
                .Where(a => a.UserId == userId)
                .GroupBy(a => a.QuestionId)
                .Select(g => new { QuestionId = g.Key, Count = g.Count() })
                .OrderByDescending(q => new { q.Count, QuestionId = q.QuestionId })
                .Select(q => q.QuestionId)
                .FirstOrDefaultAsync();

            var questionsCount = await this.db.TriviaQuestions.CountAsync();

            var nextQuestionId = (lastQuestionId % questionsCount) + 1;
            return await this.db.TriviaQuestions.FindAsync(CancellationToken.None, nextQuestionId);
        }
        [ResponseType(typeof(TriviaQuestion))]
        public async Task<IHttpActionResult> Get()
        {
            var userId = User.Identity.Name;

            TriviaQuestion nextQuestion = await this.NextQuestionAsync(userId);

            if (nextQuestion == null)
            {
                return this.NotFound();
            }

            return this.Ok(nextQuestion);
        }
        private async Task<bool> StoreAsync(TriviaAnswer answer)
        {
            this.db.TriviaAnswers.Add(answer);

            await this.db.SaveChangesAsync();
            var selectedOption = await this.db.TriviaOptions.FirstOrDefaultAsync(o => o.Id == answer.OptionId
                && o.QuestionId == answer.QuestionId);

            return selectedOption.IsCorrect;
        }
        [ResponseType(typeof(TriviaAnswer))]
        public async Task<IHttpActionResult> Post(TriviaAnswer answer)
        {
            if (!ModelState.IsValid)
            {
                return this.BadRequest(this.ModelState);
            }

            answer.UserId = User.Identity.Name;

            var isCorrect = await this.StoreAsync(answer);
            return this.Ok<bool>(isCorrect);
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
<?php

final class PhabricatorPolicyException extends Exception {

}


text:
class Python
  def initialize(classname, methodnames)
    @classname = classname.chomp
    @methodnames = methodnames
  end

  def generate
    puts
    puts 'import *.*'
    puts
    puts "class #{@classname}(object):"
    puts "  def __init__(self, args):"
    puts "    # Do something"
    @methodnames.each do |methodname|
      puts
      puts "  def #{methodname}(self, args):"
      puts '    # Do something'
    end
    puts
    puts 'if __name__ == "__main__"'
    puts '    # Do something'
    puts
  end
end


text:
set -e

# If we are running inside of Travis then do not run the rest of this
# script unless we want to TEST_ASSETS
if [[ "${TRAVIS}" == "true" && "${TEST_ASSETS}" == "false" ]]; then
  exit
fi

pushd assets > /dev/null
  grunt test
popd > /dev/null


text:
package org.scalameta.paradise

import scala.tools.nsc.{Global, Phase, SubComponent}
import scala.tools.nsc.plugins.{Plugin => NscPlugin, PluginComponent => NscPluginComponent}
import scala.collection.{mutable, immutable}
import org.scalameta.paradise.reflect.ReflectToolkit
import org.scalameta.paradise.converters.Converter
import org.scalameta.paradise.parser.HijackSyntaxAnalyzer
import org.scalameta.paradise.typechecker.HijackAnalyzer
import org.scalameta.paradise.typechecker.AnalyzerPlugins

class Plugin(val global: Global)
    extends NscPlugin
    with HijackSyntaxAnalyzer
    with HijackAnalyzer
    with AnalyzerPlugins {
  val name        = "macroparadise"
  val description = "Empowers production Scala compiler with latest macro developments"
  val components  = Nil

  hijackSyntaxAnalyzer()
  val newAnalyzer = hijackAnalyzer()
  newAnalyzer.addAnalyzerPlugin(AnalyzerPlugin)
  newAnalyzer.addMacroPlugin(MacroPlugin)
}


text:
using System;
using System.Linq;
using System.ComponentModel.DataAnnotations;
using Csla;
using System.ComponentModel;
using System.Threading.Tasks;

namespace ProjectTracker.Library
{
  [Serializable()]
  public class ResourceEdit : CslaBaseTypes.BusinessBase<ResourceEdit>
  {
    public static readonly PropertyInfo<byte[]> TimeStampProperty = RegisterProperty<byte[]>(c => c.TimeStamp);
    [Browsable(false)]
    [EditorBrowsable(EditorBrowsableState.Never)]
    public byte[] TimeStamp
    {
      get { return GetProperty(TimeStampProperty); }
      set { SetProperty(TimeStampProperty, value); }
    }

    public static readonly PropertyInfo<int> IdProperty = RegisterProperty<int>(c => c.Id);
    [Display(Name = "Resource id")]
    public int Id
    {
      get { return GetProperty(IdProperty); }
      set { SetProperty(IdProperty, value); }
    }

    public static readonly PropertyInfo<string> LastNameProperty =
      RegisterProperty<string>(c => c.LastName);
    [Display(Name = "Last name")]
    [Required]
    [StringLength(50)]
    public string LastName
    {
      get { return GetProperty(LastNameProperty); }
      set { SetProperty(LastNameProperty, value); }
    }

    public static readonly PropertyInfo<string> FirstNameProperty =
      RegisterProperty<string>(c => c.FirstName);
    [Display(Name = "First name")]
    [Required]
    [StringLength(50)]
    public string FirstName
    {
      get { return GetProperty(FirstNameProperty); }
      set { SetProperty(FirstNameProperty, value); }
    }

    [Display(Name = "Full name")]
    public string FullName
    {
      get { return LastName + ", " + FirstName; }
    }

    public static readonly PropertyInfo<ResourceAssignments> AssignmentsProperty =
      RegisterProperty<ResourceAssignments>(c => c.Assignments, RelationshipTypes.Child);
    public ResourceAssignments Assignments
    {
      get { return GetProperty(AssignmentsProperty); }
      private set { LoadProperty(AssignmentsProperty, value); }
    }

    public override string ToString()
    {
      return Id.ToString();
    }

    protected override void AddBusinessRules()
    {
      base.AddBusinessRules();
      BusinessRules.AddRule(new Csla.Rules.CommonRules.IsInRole(Csla.Rules.AuthorizationActions.WriteProperty, LastNameProperty, "ProjectManager"));
      BusinessRules.AddRule(new Csla.Rules.CommonRules.IsInRole(Csla.Rules.AuthorizationActions.WriteProperty, FirstNameProperty, "ProjectManager"));
      BusinessRules.AddRule(new NoDuplicateProject { PrimaryProperty = AssignmentsProperty });
    }

    [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
    public static void AddObjectAuthorizationRules()
    {
      Csla.Rules.BusinessRules.AddRule(typeof(ResourceEdit), new Csla.Rules.CommonRules.IsInRole(Csla.Rules.AuthorizationActions.CreateObject, "ProjectManager"));
      Csla.Rules.BusinessRules.AddRule(typeof(ResourceEdit), new Csla.Rules.CommonRules.IsInRole(Csla.Rules.AuthorizationActions.EditObject, "ProjectManager"));
      Csla.Rules.BusinessRules.AddRule(typeof(ResourceEdit), new Csla.Rules.CommonRules.IsInRole(Csla.Rules.AuthorizationActions.DeleteObject, "ProjectManager", "Administrator"));
    }

    protected override void OnChildChanged(Csla.Core.ChildChangedEventArgs e)
    {
      if (e.ChildObject is ResourceAssignments)
      {
        BusinessRules.CheckRules(AssignmentsProperty);
        OnPropertyChanged(AssignmentsProperty);
      }
      base.OnChildChanged(e);
    }

    private class NoDuplicateProject : Csla.Rules.BusinessRule
    {
      protected override void Execute(Csla.Rules.IRuleContext context)
      {
        var target = (ResourceEdit)context.Target;
        foreach (var item in target.Assignments)
        {
          var count = target.Assignments.Count(r => r.ProjectId == item.ProjectId);
          if (count > 1)
          {
            context.AddErrorResult("Duplicate projects not allowed");
            return;
          }
        }
      }
    }

    public static async Task<ResourceEdit> NewResourceEditAsync()
    {
      return await DataPortal.CreateAsync<ResourceEdit>();
    }

    public static async Task<ResourceEdit> GetResourceEditAsync(int id)
    {
      return await DataPortal.FetchAsync<ResourceEdit>(id);
    }

    public static async Task<bool> ExistsAsync(int id)
    {
      var cmd = new ResourceExistsCommand(id);
      cmd = await DataPortal.ExecuteAsync(cmd);
      return cmd.ResourceExists;
    }

    public static void NewResourceEdit(EventHandler<DataPortalResult<ResourceEdit>> callback)
    {
      DataPortal.BeginCreate<ResourceEdit>(callback);
    }

    public static void GetResourceEdit(int id, EventHandler<DataPortalResult<ResourceEdit>> callback)
    {
      DataPortal.BeginFetch<ResourceEdit>(id, callback);
    }

    public static ResourceEdit NewResourceEdit()
    {
      return DataPortal.Create<ResourceEdit>();
    }

    public static ResourceEdit GetResourceEdit(int id)
    {
      return DataPortal.Fetch<ResourceEdit>(id);
    }

    public static void DeleteResourceEdit(int id)
    {
      DataPortal.Delete<ResourceEdit>(id);
    }

    public static bool Exists(int id)
    {
      var cmd = new ResourceExistsCommand(id);
      cmd = DataPortal.Execute(cmd);
      return cmd.ResourceExists;
    }

    [RunLocal]
    protected override void DataPortal_Create()
    {
      LoadProperty(AssignmentsProperty, DataPortal.CreateChild<ResourceAssignments>());
      base.DataPortal_Create();
    }

    private void DataPortal_Fetch(int id)
    {
      using (var ctx = ProjectTracker.Dal.DalFactory.GetManager())
      {
        var dal = ctx.GetProvider<ProjectTracker.Dal.IResourceDal>();
        var data = dal.Fetch(id);
        using (BypassPropertyChecks)
        {
          Id = data.Id;
          FirstName = data.FirstName;
          LastName = data.LastName;
          TimeStamp = data.LastChanged;
          Assignments = DataPortal.FetchChild<ResourceAssignments>(id);
        }
      }
    }

    protected override void DataPortal_Insert()
    {
      using (var ctx = ProjectTracker.Dal.DalFactory.GetManager())
      {
        var dal = ctx.GetProvider<ProjectTracker.Dal.IResourceDal>();
        using (BypassPropertyChecks)
        {
          var item = new ProjectTracker.Dal.ResourceDto
          {
            FirstName = this.FirstName,
            LastName = this.LastName
          };
          dal.Insert(item);
          Id = item.Id;
          TimeStamp = item.LastChanged;
        }
        FieldManager.UpdateChildren(this);
      }
    }

    protected override void DataPortal_Update()
    {
      using (var ctx = ProjectTracker.Dal.DalFactory.GetManager())
      {
        var dal = ctx.GetProvider<ProjectTracker.Dal.IResourceDal>();
        using (BypassPropertyChecks)
        {
          var item = new ProjectTracker.Dal.ResourceDto
          {
            Id = this.Id,
            FirstName = this.FirstName,
            LastName = this.LastName,
            LastChanged = this.TimeStamp
          };
          dal.Update(item);
          TimeStamp = item.LastChanged;
        }
        FieldManager.UpdateChildren(this);
      }
    }

    protected override void DataPortal_DeleteSelf()
    {
      using (BypassPropertyChecks)
        DataPortal_Delete(this.Id);
    }

    private void DataPortal_Delete(int id)
    {
      using (var ctx = ProjectTracker.Dal.DalFactory.GetManager())
      {
        Assignments.Clear();
        FieldManager.UpdateChildren(this);
        var dal = ctx.GetProvider<ProjectTracker.Dal.IResourceDal>();
        dal.Delete(id);
      }
    }
  }
}


text:
<?php

$installer = $this;
/* @var $installer Mage_Catalog_Model_Resource_Eav_Mysql4_Setup */

$installer->startSetup();
$installer->getConnection()->addColumn($installer->getTable('catalog/product'), 'required_options', 'tinyint(1) unsigned NOT NULL default 0');

$entityTypeId   = 'catalog_product';
$attributeId    = $installer->getAttributeId($entityTypeId, 'required_options');
$attributeTable = $installer->getAttributeTable($entityTypeId, $attributeId);

if ($attributeTable != $installer->getTable('catalog/product')) {
    $installer->run("
    UPDATE `{$installer->getTable('catalog/product')}` AS `p`
    INNER JOIN `{$attributeTable}` AS `a` ON `p`.`entity_id`=`a`.`entity_id`
        AND `a`.`attribute_id`={$attributeId} AND `a`.`store_id`=0
    SET `p`.`required_options` = `a`.`value`;
    ");

    $installer->updateAttribute($entityTypeId, $attributeId, 'backend_type', 'static');

    $installer->run("
    DELETE FROM `{$attributeTable}` WHERE `attribute_id`={$attributeId};
    ");
}

$installer->endSetup();


text:
fn main() {
    println!("cargo:rustc-flags=-l photoacquireuid");
}


text:
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/watch_time"
        android:textSize="30sp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:textColor="#FF0000"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/watch_battery"
        android:textSize="13sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#FF0000"
        android:layout_alignRight="@id/watch_time"
        android:layout_below="@+id/watch_time"
        />
</RelativeLayout>


text:
Roger plugin to transpile ES6 code with BabelJS

```ruby
 gem "roger_babeljs"
```

## Use it in the server

```ruby
  mockup.serve do |server|
    server.use RogerBabeljs::Middleware, {
      match: [%r{/url/you/want/to/match/*\.js}],
      babel_options: {
        # ... Options to pass to Babel
      }
    }
  end
```

## Changes and versions

Have a look at the [CHANGELOG](CHANGELOG.md) to see what's new.

## Contributors

[View contributors](https://github.com/digitpaint/roger_babeljs/graphs/contributors)

## License

MIT License, see [LICENSE](LICENSE) for more info.


text:
#import <Foundation/NSCoder.h>

@interface NSKeyedUnarchiver : NSCoder
{
    id _delegate;
    unsigned int _flags;
    id _objRefMap;
    id _replacementMap;
    id _nameClassMap;
    id _tmpRefObjMap;
    id _refObjMap;
    int _genericKey;
    id _data;
    void *_offsetData;
    id _containers;
    id _objects;
    const char *_bytes;
    unsigned long long _len;
    id _helper;
    void *_reserved0;
}

+ (Class)classForClassName:(id)arg1;
+ (void)setClass:(Class)arg1 forClassName:(id)arg2;
+ (id)unarchiveObjectWithData:(id)arg1;
+ (id)unarchiveObjectWithFile:(id)arg1;
+ (void)initialize;
- (unsigned int)systemVersion;
- (long long)versionForClassName:(id)arg1;
- (void)decodeArrayOfObjCType:(const char *)arg1 count:(unsigned long long)arg2 at:(void *)arg3;
- (void)decodeValueOfObjCType:(const char *)arg1 at:(void *)arg2;
- (void)decodeValuesOfObjCTypes:(const char *)arg1;
- (void *)decodeBytesWithReturnedLength:(unsigned long long *)arg1;
- (id)decodeDataObject;
- (id)decodeObject;
- (unsigned int)_currentUniqueIdentifier;
- (id)_decodePropertyListForKey:(id)arg1;
- (const char *)decodeBytesForKey:(id)arg1 returnedLength:(unsigned long long *)arg2;
- (double)decodeDoubleForKey:(id)arg1;
- (float)decodeFloatForKey:(id)arg1;
- (long long)decodeInt64ForKey:(id)arg1;
- (int)decodeInt32ForKey:(id)arg1;
- (int)decodeIntForKey:(id)arg1;
- (_Bool)decodeBoolForKey:(id)arg1;
- (id)_decodeArrayOfObjectsForKey:(id)arg1;
- (void)setRequiresSecureCoding:(_Bool)arg1;
- (_Bool)requiresSecureCoding;
- (id)allowedClasses;
- (id)decodeObjectOfClasses:(id)arg1 forKey:(id)arg2;
- (id)decodeObjectOfClass:(Class)arg1 forKey:(id)arg2;
- (id)decodeObjectForKey:(id)arg1;
- (_Bool)containsValueForKey:(id)arg1;
- (void)_replaceObject:(id)arg1 withObject:(id)arg2;
- (void)replaceObject:(id)arg1 withObject:(id)arg2;
- (void)_temporaryMapReplaceObject:(id)arg1 withObject:(id)arg2;
- (void)finishDecoding;
- (void)setAllowedClasses:(id)arg1;
- (void)_setAllowedClassNames:(id)arg1;
- (id)_allowedClassNames;
- (Class)classForClassName:(id)arg1;
- (void)setClass:(Class)arg1 forClassName:(id)arg2;
- (id)delegate;
- (void)setDelegate:(id)arg1;
- (_Bool)allowsKeyedCoding;
- (id)description;
- (void)finalize;
- (void)dealloc;
- (id)initWithStream:(id)arg1;
- (id)initForReadingWithData:(id)arg1;
- (id)_initWithStream:(struct __CFReadStream *)arg1 data:(id)arg2 topDict:(struct __CFDictionary *)arg3;
- (id)init;
- (id)_blobForCurrentObject;

@end


text:
package com.example.adapterview;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

import com.example.hoperun.myapplication.R;

public class AdapterViewDemo extends Activity implements View.OnClickListener {

    private Button btn1;
    private Button btn2;
    private Button btn3;
    private Button btn4;
    private Button btn5;
    private Button btn6;
    private Button btn7;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_adapter_view_demo);

        btn1 = (Button) findViewById(R.id.btn1);
        btn2 = (Button) findViewById(R.id.btn2);
        btn3 = (Button) findViewById(R.id.btn3);
        btn4 = (Button) findViewById(R.id.btn4);
        btn5 = (Button) findViewById(R.id.btn5);
        btn6 = (Button) findViewById(R.id.btn6);
        btn7 = (Button) findViewById(R.id.btn7);

        btn1.setOnClickListener(this);
        btn2.setOnClickListener(this);
        btn3.setOnClickListener(this);
        btn4.setOnClickListener(this);
        btn5.setOnClickListener(this);
        btn6.setOnClickListener(this);
        btn7.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn1:
                ;
                startActivity(new Intent(this, ArrayAdapterDemo.class));
                break;
            case R.id.btn2:
                ;
                startActivity(new Intent(this, SimpleAdapterDemo.class));
                break;
            case R.id.btn3:
                ;
                startActivity(new Intent(this, BaseAdapterDemo.class));
                break;
            case R.id.btn4:
                ;
                startActivity(new Intent(this, AutoCompleteTextDemo.class));
                break;
            case R.id.btn5:
                ;
                startActivity(new Intent(this, GidViewDemo.class));
                break;
            case R.id.btn6:
                ;
                startActivity(new Intent(this, AdapterViewFlipperDemo.class));
                break;

            case R.id.btn7:
                ;
                startActivity(new Intent(this, StackView.class));
                break;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_adapter_view_demo, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

}


text:
class ControllerHelperTestController < ApplicationController
  def index
    @instance_variable = "Helper Test"
    local_variable = 42
    console
  end
end


text:
    <?php foreach ($special_offers as $so) {
        $offer = $so->product_offers;
        ?>

                    <a class="img-wrap" href="/product/view?id=<?= $offer->productID ?>"><img class="img-responsive" src="/products_pictures/<?= $offer->picture ?>" alt="">

                    <a href="/product/view?id=<?= $offer->productID ?>" title="<?=$offer->name?>"><?php $_trim($offer->name, 50) ?>

<?php $_trim($offer->description, 80) ?>$<?= $offer->Price ?>

    <?php } ?>


text:
<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
  <title>login</title>
  <script type="text/javascript" src="script/login.js"></script>
</head>
<body></body>
</html>


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
in Sheard, Bryologist 95(1): 84 (1992)

#### Original name
Lecidea callispora C. Knight

### Remarks
null


text:
#ifndef __ASM_EXCEPTION_H
#define __ASM_EXCEPTION_H

#define __exception	__attribute__((section(".exception.text")))
#define __exception_irq_entry	__exception

#endif	/* __ASM_EXCEPTION_H */


text:
<!doctype html>

	<title>Dialog Visual Tests Page</title>
	<link rel="stylesheet" href="../all.css" type="text/css">
	<link rel="stylesheet" href="../../../themes/base/ui.all.css" type="text/css">

	Dialog

		<button>Open</button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

	Dialog with buttons

		<button>Open</button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.


text:
var constants = {
  TRUE: true,
  FALSE: false,
  HAS_A18_ATTRS: 'button, input',
  DISABLED: 'disabled',
  eventPrefix: 'lu:',
  events: {
    SELECTED: 'selected',
    SELECT: 'select',
    STATED: 'stated',
    STATE: 'state',
    UPDATED: 'updated',
    UPDATE: 'update',
    LOAD: 'load',
    OUT_OF_BOUNDS: 'out_of_bounds',
    NEXT: 'next',
    PREVIOUS: 'previous',
    FIRST: 'first',
    LAST: 'last',
    PLAY: 'play',
    PAUSE: 'pause',
    HIDE: 'hide',
    SHOW: 'show'
  },
  statePrefix: 'lu-state-',
  states: {
    STATE: 'state',
    STATED: 'stated',
    SELECTED: 'selected',
    DISABLED: 'disabled',
    LOADING: 'loading',
    LOADED: 'loaded',
    MAXED: 'maxed',
    FLOORED: 'floored',
    TRANSITIONING: 'transitioning',
    TRANSITIONED: 'transitioned',
    PLAYING: 'playing',
    PAUSED: 'paused',
    ACTIVE: 'active',
    INACTIVE: 'inactive',
    ERRED: 'erred',
    REVERSE: 'reverse',
    FORWARD: 'forward',
    PLACEHOLDER: 'placeholder'
  }
};

//Export to Common JS Loader
if( typeof module !== 'undefined' ){
  if( typeof module.setExports === 'function' ){
    module.setExports( constants );
  } else if( module.exports ){
    module.exports = constants;
  }
}


text:
package com.evolveum.midpoint.web.component.sample;

import java.util.ArrayList;
import java.util.List;

import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;

import com.evolveum.midpoint.gui.api.model.LoadableModel;
import com.evolveum.midpoint.gui.api.page.PageBase;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.util.exception.CommunicationException;
import com.evolveum.midpoint.util.exception.ConfigurationException;
import com.evolveum.midpoint.util.exception.ObjectNotFoundException;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.exception.SecurityViolationException;
import com.evolveum.midpoint.util.logging.LoggingUtils;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.web.component.assignment.AssignmentEditorDto;
import com.evolveum.midpoint.web.component.assignment.SimpleRoleSelector;
import com.evolveum.midpoint.web.component.form.Form;
import com.evolveum.midpoint.web.component.objectdetails.AbstractFocusTabPanel;
import com.evolveum.midpoint.web.component.prism.ObjectWrapper;
import com.evolveum.midpoint.web.page.admin.users.dto.FocusSubwrapperDto;
import com.evolveum.midpoint.xml.ns._public.common.common_3.FocusType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.RoleType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType;

/**
 * Sample showing a custom focus form that displays semi-static form.
 *
 * @author Radovan Semancik
 *
 */
public class SampleFormFocusTabPanel<F extends FocusType> extends AbstractFocusTabPanel<F> {

    private static final String DOT_CLASS = SampleFormFocusTabPanel.class.getName() + ".";
    private static final String OPERATION_SEARCH_ROLES = DOT_CLASS + "searchRoles";

    private static final String ID_HEADER = "header";

    private static final String ID_PROP_NAME = "propName";
    private static final String ID_PROP_FULL_NAME = "propFullName";

    private static final String ID_ROLES = "roles";

    private static final Trace LOGGER = TraceManager.getTrace(SampleFormFocusTabPanel.class);

    public SampleFormFocusTabPanel(String id, Form mainForm,
                                   LoadableModel<ObjectWrapper<F>> focusWrapperModel,
                                   LoadableModel<List<AssignmentEditorDto>> assignmentsModel,
                                   LoadableModel<List<FocusSubwrapperDto<ShadowType>>> projectionModel,
                                   PageBase pageBase) {
        super(id, mainForm, focusWrapperModel, assignmentsModel, projectionModel, pageBase);
        initLayout(focusWrapperModel, assignmentsModel, pageBase);
    }

    private void initLayout(final LoadableModel<ObjectWrapper<F>> focusModel, LoadableModel<List<AssignmentEditorDto>> assignmentsModel, PageBase pageBase) {
        add(new Label(ID_HEADER, "Object details"));
        WebMarkupContainer body = new WebMarkupContainer("body");
        add(body);

        addPrismPropertyPanel(body, ID_PROP_NAME, FocusType.F_NAME);
        addPrismPropertyPanel(body, ID_PROP_FULL_NAME, UserType.F_FULL_NAME);

        // TODO: create proxy for these operations
        Task task = pageBase.createSimpleTask(OPERATION_SEARCH_ROLES);
        List<PrismObject<RoleType>> availableRoles;
        try {
            availableRoles = pageBase.getModelService().searchObjects(RoleType.class, null, null, task, task.getResult());
        } catch (SchemaException | ObjectNotFoundException | SecurityViolationException | CommunicationException | ConfigurationException e) {
            task.getResult().recordFatalError(e);
            LoggingUtils.logUnexpectedException(LOGGER, "Couldn't load roles", e);
            availableRoles = new ArrayList<>();
            // TODO: better errror reporting
        }

        add(new SimpleRoleSelector<F,RoleType>(ID_ROLES, assignmentsModel, availableRoles));
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Copyright 2016-2018 Seznam.cz, a.s.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <parent>
    <artifactId>euphoria-parent</artifactId>
    <groupId>cz.seznam.euphoria</groupId>
    <version>0.8-SNAPSHOT</version>
  </parent>
  <modelVersion>4.0.0</modelVersion>

  <artifactId>euphoria-flink</artifactId>
  <packaging>jar</packaging>

  <name>${project.groupId}:${project.artifactId}</name>
  <description>
    An euphoria executor based on Apache Flink.
  </description>

  <dependencies>

    <dependency>
      <groupId>${project.groupId}</groupId>
      <artifactId>euphoria-core</artifactId>
    </dependency>

    <dependency>
      <groupId>${project.groupId}</groupId>
      <artifactId>euphoria-testing</artifactId>
    </dependency>

    <dependency>
      <groupId>com.google.code.findbugs</groupId>
      <artifactId>jsr305</artifactId>
      <version>1.3.9</version>
    </dependency>

    <!-- Flink dependencies -->
    <dependency>
      <groupId>org.apache.flink</groupId>
      <artifactId>flink-streaming-java_${scala.version}</artifactId>
      <version>${flink.version}</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>org.apache.flink</groupId>
      <artifactId>flink-java</artifactId>
      <version>${flink.version}</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>org.apache.flink</groupId>
      <artifactId>flink-clients_${scala.version}</artifactId>
      <version>${flink.version}</version>
      <scope>provided</scope>
    </dependency>

    <!-- test -->
    <dependency>
      <groupId>cz.seznam.euphoria</groupId>
      <artifactId>euphoria-operator-testkit</artifactId>
      <version>${project.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.flink</groupId>
      <artifactId>flink-statebackend-rocksdb_${scala.version}</artifactId>
      <version>${flink.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>

</project>


text:
Overview
========

The MPInterfaces package contains python modules that enable the creation of
FireWorks workflows for ligand-slab interface and slab-slab interface
calculations with VASP.

The package is structured as python modules (listed in modules section
of docs and contained in mpinterfaces folder), examples notebooks
(ipython notebooks) and workflows scripts to be
used with a locally set up FireWorks database.

The examples folder contains scripts for interface creation and utility post processing and
ipython notebook examples and workflow submission scripts.

Apart from these, there are utility scripts for the plotting of band structures,
density of states and equations of state.

The example folder "notebooks" also provides example calculations of Pourbaix diagrams,
and Phase diagrams based on the method implemented in pymatgen/examples

Capabilities
============

MPInterfaces extends object oriented definitions of materialsproject pymatgen to
interfaces and features:

Interface Creation
------------------
extended object oriented definitions to
the pymatgen Slab called "Interface" and an
adsorbate extension of pymatgen Molecule
called "Ligand" and scripts to create Interfaces.

Example scripts:
    - create_interface.py : creates an example ligand + slab interface illustrating
    - ligand_interface.py : creates a list of ligand + slab interfaces with pre-configuration
    - hetero_interface.py : creates a slab – slab heterostructure interface
    - nanoparticle.py     : creates a nanoparticle based on Wulff Construction

Offline vasp project management
--------------------------------

The script, **mpint**, in the scripts folder serves as a management
tool for vasp projects, starting from encut, kpoint or other parameter
optimization till the solvation calculations. Just define all types of
calculations with their corresponding specifications needed for the
project in a yaml file and run or rerun calculaitons as required.

it takes 3 arguments: input yaml file, type of calculation and the
run mode

example:

   ```
   mpint -i naf.yaml -t bulk_calibrate run
   ```

   this will read in the specifications for 'bulk_calibrate' job
   from the input yaml file, naf.yaml(in examples folder), and
   runs the job i.e submits to the PBS que.

**Job Monitoring**:

Everytime jobs are submitted or its status queried, information
such as job ids, job folders etc are written to the calibrate.json(the default name)
checkpoint file. This makes it easier to identify job ids and their
corresponding job folders. Also provides all job info including
converged final energies in one place, in the checkpoint file.

update the calibrate.json(default name) checkpoint file with the final
energies(if converged):

   ```
   mpint update
   ```

update custom name(example:- step1.json) checkpoint file with the
final energies(if converged):

   ```
   mpint update step1.json
   ```

update checkpoint files from calibrate runs:

   ```
   mpint update step1.json step2.json
   ```

update calibrate.json and rerun jobs(will reset the poscar from the contcar
file if one exists) with the given ids:

   ```
   mpint update 14692739.moab.ufhpc 14692740.moab.ufhpc
   ```

update calibrate.json and rerun jobs in the given job directory paths:

   ```
   mpint update all_poscars/POS/CBr2_294_C1Br2 all_poscars/POS/CoBr2_294_Co1Br2
   ```

update calibrate.json and rerun jobs in the given folders(job ids are also accepted)
with incar or kpoints or que parameters overridden by the parmaters in
the override_input.yaml file:

   ```
   mpint -i override_input.yaml update all_poscars/POS/CBr2_294_C1Br2 all_poscars/POS/CoBr2_294_Co1Br2
   ```

High throughput VASP workflows with FireWorks
---------------------------------------------

High throughput VASP workflows can be handled by creating your own FireWorks database server.
The FireWorks package from the materialsproject is installed at the time of installation.
We have defined FireTasks customized to Interface studies as follows:

Calibrate, Measurement and DatabaseSubmit.
    -  Calibrate Task:
       Defines all tasks that involve the calibration of
       VASP input parameters. For example, energy cutoff convergence,
       kpoints convergence,vacuum convergence, thickness convergence in case of slabs
       Calibrate module defined in calibrate.py provides customized
       Bulk, Molecule, Slab and Interface objects for the Calibrate Task

    -  Measurement Task:
       Tasks for VASP jobs dependent on a previous calculation. Currently implemented
       tasks include Static calculation following a Calibrate Task and Solvation calculation following a Calibrate Task
       Measurement tasks are linked to calibrate tasks and are capable of copying
       the necessary files from the previous calculation to restart the calculation.
       for example, CONTCAR from a Relaxation for a Static calculation, CONTCAR and WAVECAR for a Solvation calculation

    -  Database Task:
       Submits data to a MongoDB database similar to VasptoDBtaskDrone
       of pymatgen extended to use Interface specific keys of miller index of slab
       and ligand chemical formula in .json format

Refer examples/Workflows for example workflow submission scripts.

Example of FireWorks Database Queries
=====================================

After installation and setup of your database according to
FireWorks documentation, create your own my_launchpad.yaml using

lpad init

Set the path to this file to LAUNCHPAD_LOC in
the fw_config.py found in your installation directory.

TIP: create the my_launchpad.yaml in the directory
     ~/.fireworks

Make sure to configure your my_launchpad.yaml file to your local
database settings (host name, database name, etc.)

Workflow submission and launching
---------------------------------

Refer examples folder for simple workflow scripts

      -> general submission of workflow to the database:

      python workflow_script.py

      Fireworks package has some nice utility scripts for launching
      fireworks and checking job status. If the fireworks package is
      installed then those scripts are already in your PATH. Some
      examples are given below:

      -> reset database to erase all workflows

	 CAUTION: Be careful when using the following command as it will
	 erase all workflows from the database:

         lpad reset

      -> launch a single firework:

         rlaunch singleshot -f [fw_id]

      -> get all fireworks info:

         lpad get_fws

      -> get all workflows info:

         lpad get_wflows

      -> reset database to erase all workflows

         CAUTION: Be careful when using the following command as it will
         erase all workflows from the database:

         lpad reset

Workflow query examples
------------------------

      -> query by name:

           example:
	   lpad get_wflows -n "Ag_100"

      -> query by state

           lpad get_wflows -s STATE

           or

           lpad get_wflows -q '{"state":STATE}' --sort created_on

           where STATE = "READY", "WAITING", "RUNNING", "FIZZLED" or "DEFUSED"

      -> delete workflows:

           example:
           lpad delete_wflows -n Ag_100

Query for individual Fireworks
------------------------------

      -> query by state
           lpad get_fws -s STATE

      or

           lpad get_fws -q '{"state":STATE}' --sort created_on

           where STATE = "READY", "WAITING", "RUNNING", "FIZZLED", "DEFUSED"

      -> query fireworks by name or id:

           example:
           lpad get_fws -n "solvation"

	   lpad get_fws -i 102 -d all

      -> re-run firework with id, fw_id. Same as marking the firework as ready
           lpad rerun_fws -i fw_id

      -> re-run a finished or fizzled firework with updated specs:
           example: update the sol_params of the first task of the firework with id 102
	   lpad rerun_fws -i 102

           lpad update_fws -i 102 -u '{"_tasks.0.other_params.sol_params.NELECT":[-1,-0.5,0,0.5,1]}'

Connecting to our local Database
--------------------------------

The mongo database for job submission('fireworks') is set up on the
machine 'hydrogen'.
Please use your own account to connect to the database
Contact me (km468@cornell.edu) to create a database account


text:
"use strict";
var inherits = require('util').inherits;
var AuthProvider = require('authen/lib/auth_provider');

var ServiceAuthProvider = function (opt_options) {
	AuthProvider.call(this, opt_options);
};
inherits(ServiceAuthProvider, AuthProvider);

ServiceAuthProvider.prototype.prepareAuthResult = function (ctx, options, authResult, cb) {
	var result = {
		type: this.type,
		identity: this.getIdentity(authResult),
		authResult: result
	};
	if (options.allowOnBehalf && this.options.allowOnBehalf) {
		var onBehalf = this.createOnBehalfResult(ctx);
		if (onBehalf != null) {
			var via = result;
			result = onBehalf;
			result.via = via;
		}
	}
	cb(null, result);
};

ServiceAuthProvider.prototype.unpackOnBehalfIdentity = function (identityStr) {
	return identityStr;
};

ServiceAuthProvider.prototype.createOnBehalfResult = function (ctx) {
	var result = null;
	var onBehalfData = this.adapter.extractOnBehalfData(ctx);
	if (onBehalfData != null) {
		result = {
			type: onBehalfData.type || this.options.defaultOnBehalfAuthType,
			identity: this.unpackOnBehalfIdentity(onBehalfData.identityStr),
			onBehalfData: onBehalfData
		};
	}
	return result;
};

module.exports = ServiceAuthProvider;


text:
<?php
/**
 * Created by PhpStorm.
 * User: visa
 * Date: 17/05/16
 * Time: 11.20
 */

namespace ImgManTest\Apigility\Asset;

use ImgMan\Apigility\Entity\ImageEntity;
use ImgMan\Image\ImageTrait;

class TestImage extends ImageEntity
{
}


text:
package freestyle

import scala.annotation.tailrec
import scala.reflect.macros.whitebox.Context
import scala.util.Try

import cats.data.NonEmptyList
import cats.data.{ Validated, ValidatedNel }
import cats.syntax.either._
import cats.syntax.flatMap._
import cats.syntax.traverse._
import cats.syntax.validated._
import cats.instances.all._

trait FreeModuleLike

// $COVERAGE-OFF$ ScalaJS + coverage = fails with NoClassDef exceptions

final class moduleImpl(val c: Context) {
  import c.universe.{ Try => _, _ }
  import c.universe.internal.reificationSupport.{ ConstantType => _, _ }
  import compat._

  private[this] lazy val FF       = freshTypeName("FF")
  private[this] lazy val LL       = freshTypeName("LL")
  private[this] lazy val AA       = freshTypeName("AA")

  private[this] lazy val tpnme_EMPTY_PACKAGE_NAME = termNames.EMPTY_PACKAGE_NAME.toTypeName

  private[this] lazy val FreeModuleLike = typeOf[freestyle.FreeModuleLike].typeSymbol
  private[this] lazy val Coproduct      = typeOf[cats.data.Coproduct[Nothing, Nothing, _]].typeSymbol
  private[this] lazy val CopK           = typeOf[iota.CopK[_, _]].typeSymbol
  private[this] lazy val KNil           = typeOf[iota.KNil].typeSymbol
  private[this] lazy val KCons          = typeOf[iota.KCons[Nothing, _]].typeSymbol

  private[this] lazy val wildcard =
    TypeDef(Modifiers(Flag.PARAM), typeNames.WILDCARD, List(),
      TypeBoundsTree(EmptyTree, EmptyTree))

  private[this] lazy val FFtypeConstructor =
    TypeDef(Modifiers(Flag.PARAM), FF, List(wildcard),
      TypeBoundsTree(EmptyTree, EmptyTree))

  private[this] implicit final class ValidateFlatmap[E, A](v: Validated[E, A]) {
    def flatMap[EE >: E, B](f: A => Validated[EE, B]): Validated[EE, B] =
      v.andThen(f)
  }

  def impl(annottees: c.Expr[Any]*): Tree =
    foldAbort(for {
      cls             <- decodeAnnotationTarget(annottees.toList)
      effectTuples     = gatherEffects(cls)
      classTree       <- makeClassTree(cls)
      coproductTree   <- makeCoproductTree(effectTuples)
      objectTree      <- makeModuleTree(cls, coproductTree, effectTuples)
    } yield q"$classTree; $objectTree")

  private[this] def decodeAnnotationTarget(annottees: List[c.Expr[Any]]) =
    annottees.map(_.tree) match {
      case (cls: ClassDef) :: Nil =>
        if (cls.mods.hasFlag(Flag.TRAIT | Flag.ABSTRACT)) cls.validNel
        else
          "The `@module` annotation can only be applied to a trait or an abstract class.".invalidNel

      case (cls: ClassDef) :: more =>
        "The trait or class annotated with `@module` must have no companion object.".invalidNel
      case trees =>
        "Unexpected trees $trees encountered for `@module` annotation".invalidNel
  }

  private[this] def gatherEffects(cls: ClassDef): List[(Name, Tree)] =
    cls.impl.body.collect {
      case valDef: ValDef if valDef.rhs.isEmpty => (valDef.name, valDef.tpt) }

  private[this] def makeClassTree(cls: ClassDef): ValidatedNel[String, ClassDef] = {
    val ClassDef(mods, name, tparams, Template(parents, self, body)) = cls
    val body0 = body.map {
      case q"$mods val $name: $tpt[..$args]" => q"$mods val $name: $tpt[$FF, ..$args]"
      case x => x
    }
    val parentTrees = parents ++ List(tq"_root_.freestyle.FreeModuleLike", tq"_root_.freestyle.EffectLike[$FF]")
    ClassDef(mods, name, FFtypeConstructor :: tparams,
      Template(parentTrees, self, body0)).validNel
  }

  private[this] def makeCoproductTree(effectTuples: List[(Name, Tree)]): ValidatedNel[String, Tree] = {

    val Ltpes = effectTuples.map(_._2).traverse { t =>
      val treeCode = s"type Z = $t.OpTypes"
      // (‡▼益▼)<!! would love to find a better solution (instead of c.parse)
      try {
        val q"type Z = $select" = c.parse(treeCode)
        select.validNel
      } catch {
        case t: Throwable => s"Error ${t.getMessage} when parsing $treeCode".invalidNel
      }
    }

    Ltpes
      .map {
        case Nil         => tq"_root_.iota.KNil"
        case tree :: Nil => tree
        case trees       => trees.reduce((l, r) => tq"_root_.iota.KList.Op.Concat[$l, $r]")
      }
      .map(L =>
        q"""
          type OpTypes = $L
          type Op[A]  = _root_.iota.CopK[OpTypes, A]""")
  }

  private[this] def makeModuleTree(
    cls: ClassDef,
    coproductTree: Tree,
    effects: List[(Name, Tree)]
  ): ValidatedNel[String, ModuleDef] = {

    import cls.{ tparams, name }

    val builtArgs = effects.traverse {
      case (n, tq"$tpt[..$args]") => q"""${n.toTermName}: $tpt[$LL, ..$args]""".validNel
      case (n, t) => s"unexpected type $n: $t when building args".invalidNel
    }

    builtArgs.map(args => q"""
      object ${name.toTermName} {
        ..$coproductTree
        def apply[$LL[_], ..$tparams](implicit ev: $name[$LL, ..$tparams]): $name[$LL, ..$tparams] = ev
        implicit def to[$LL[_], ..$tparams](implicit ..$args): To[$LL, ..$tparams] =
          new To[$LL, ..$tparams]()
        class To[$LL[_], ..$tparams](implicit ..$args) extends $name[$LL, ..$tparams]
      }""")
  }

  private[this] def foldAbort[A](v: ValidatedNel[String, A]): A =
    v fold (
      errors => c.abort(c.enclosingPosition, errors.toList.mkString(", and\n")),
      a      => a)
}


text:
package org.ovirt.engine.core.common.action;

import org.ovirt.engine.core.common.businessentities.*;

public class SetAdGroupRoleParameters extends AdGroupElementParametersBase {
    private static final long serialVersionUID = 3039952946152646137L;
    private boolean _isRestored;

    public SetAdGroupRoleParameters(ad_groups adGroup, boolean isRestored) {
        super(adGroup);
        _isRestored = isRestored;
    }

    public boolean getIsRestored() {
        return _isRestored;
    }

    public SetAdGroupRoleParameters() {
    }
}


text:
using System.Collections.Generic;
using Content.Server.GameObjects.Components.Power.ApcNetComponents;
using Content.Server.GameObjects.EntitySystems;
using Content.Shared.Research;
using Robust.Shared.GameObjects;
using Robust.Shared.GameObjects.Systems;
using Robust.Shared.Serialization;
using Robust.Shared.ViewVariables;

namespace Content.Server.GameObjects.Components.Research
{
    [RegisterComponent]
    public class ResearchServerComponent : Component
    {
        public static int ServerCount = 0;

        public override string Name => "ResearchServer";

        [ViewVariables(VVAccess.ReadWrite)] public string ServerName => _serverName;

        private string _serverName = "RDSERVER";
        private float _timer = 0f;
        public TechnologyDatabaseComponent Database { get; private set; }

        [ViewVariables(VVAccess.ReadWrite)] private int _points = 0;

        [ViewVariables(VVAccess.ReadOnly)] public int Id { get; private set; }

        // You could optimize research by keeping a list of unlocked recipes too.
        [ViewVariables(VVAccess.ReadOnly)]
        public IReadOnlyList<TechnologyPrototype> UnlockedTechnologies => Database.Technologies;

        [ViewVariables(VVAccess.ReadOnly)]
        public List<ResearchPointSourceComponent> PointSources { get; } = new List<ResearchPointSourceComponent>();

        [ViewVariables(VVAccess.ReadOnly)]
        public List<ResearchClientComponent> Clients { get; } = new List<ResearchClientComponent>();

        public int Point => _points;

        /// <summary>
        ///     How many points per second this R&D server gets.
        ///     The value is calculated from all point sources connected to it.
        /// </summary>
        [ViewVariables(VVAccess.ReadOnly)]
        public int PointsPerSecond
        {
            // This could be changed to PointsPerMinute quite easily for optimization.
            get
            {
                var points = 0;

                if (CanRun)
                {
                    foreach (var source in PointSources)
                    {
                        if (source.CanProduce) points += source.PointsPerSecond;
                    }
                }

                return points;
            }
        }

        /// <remarks>If no <see cref="PowerReceiverComponent"/> is found, it's assumed power is not required.</remarks>
        [ViewVariables]
        public bool CanRun => _powerReceiver is null || _powerReceiver.Powered;

        private PowerReceiverComponent _powerReceiver;

        public override void Initialize()
        {
            base.Initialize();
            Id = ServerCount++;
            EntitySystem.Get<ResearchSystem>()?.RegisterServer(this);
            Database = Owner.EnsureComponent<TechnologyDatabaseComponent>();
            Owner.TryGetComponent(out _powerReceiver);
        }

        /// <inheritdoc />
        protected override void Shutdown()
        {
            base.Shutdown();
            EntitySystem.Get<ResearchSystem>()?.UnregisterServer(this);
        }

        public override void ExposeData(ObjectSerializer serializer)
        {
            base.ExposeData(serializer);
            serializer.DataField(ref _serverName, "servername", "RDSERVER");
            serializer.DataField(ref _points, "points", 0);
        }

        public bool CanUnlockTechnology(TechnologyPrototype technology)
        {
            if (!Database.CanUnlockTechnology(technology) || _points < technology.RequiredPoints ||
                Database.IsTechnologyUnlocked(technology)) return false;
            return true;
        }

        /// <summary>
        ///     Unlocks a technology, but only if there are enough research points for it.
        ///     If there are, it subtracts the amount of points from the total.
        /// </summary>
        /// <param name="technology"></param>
        /// <returns></returns>
        public bool UnlockTechnology(TechnologyPrototype technology)
        {
            if (!CanUnlockTechnology(technology)) return false;
            var result = Database.UnlockTechnology(technology);
            if (result)
                _points -= technology.RequiredPoints;
            return result;
        }

        /// <summary>
        ///     Check whether a technology is unlocked or not.
        /// </summary>
        /// <param name="technology"></param>
        /// <returns></returns>
        public bool IsTechnologyUnlocked(TechnologyPrototype technology)
        {
            return Database.IsTechnologyUnlocked(technology);
        }

        /// <summary>
        ///     Registers a remote client on this research server.
        /// </summary>
        /// <param name="client"></param>
        /// <returns></returns>
        public bool RegisterClient(ResearchClientComponent client)
        {
            if (client is ResearchPointSourceComponent source)
            {
                if (PointSources.Contains(source)) return false;
                PointSources.Add(source);
                source.Server = this;
                return true;
            }

            if (Clients.Contains(client)) return false;
            Clients.Add(client);
            client.Server = this;
            return true;
        }

        /// <summary>
        ///     Unregisters a remote client from this server.
        /// </summary>
        /// <param name="client"></param>
        public void UnregisterClient(ResearchClientComponent client)
        {
            if (client is ResearchPointSourceComponent source)
            {
                PointSources.Remove(source);
                return;
            }

            Clients.Remove(client);
        }

        public void Update(float frameTime)
        {
            if (!CanRun) return;
            _timer += frameTime;
            if (_timer < 1f) return;
            _timer = 0f;
            _points += PointsPerSecond;
        }
    }
}


text:
  Aubréville est
       un village
       localisé dans le département de Meuse en Lorraine. Elle totalisait 395 habitants en 2008.

La commune compte quelques  équipements sportifs, elle propose entre autres un terrain de sport.

Le nombre de logements, à Aubréville, était réparti en 2011 en cinq appartements et 208 maisons soit
 un marché relativement équilibré.

Si vous pensez venir habiter à Aubréville, vous pourrez facilement trouver une maison à vendre.

À proximité de Aubréville sont localisées les villes de
Vauquois située à 6 km, 20 habitants,
Les Islettes localisée à 6 km, 825 habitants,
Neuvilly-en-Argonne localisée à 2 km, 204 habitants,
Clermont-en-Argonne située à 4 km, 1 636 habitants,
Brocourt-en-Argonne à 6 km, 51 habitants,
Boureuilles localisée à 6 km, 124 habitants,
 entre autres. De plus, Aubréville est située à seulement 21 km de Verdun.


text: <link rel="stylesheet" type="text/css" media="all" href="/css/styles.css">


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = _default;

var _lodash = _interopRequireDefault(require("lodash"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _default() {
  return function ({
    addUtilities,
    e,
    theme,
    variants
  }) {
    const utilities = _lodash.default.fromPairs(_lodash.default.map(theme('order'), (value, modifier) => {
      return [`.${e(`order-${modifier}`)}`, {
        order: value
      }];
    }));

    addUtilities(utilities, variants('order'));
  };
}