text:
#include <linux/config.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/security.h>
#include <linux/netlink.h>
#include <linux/fs.h>
#include <linux/namei.h>
#include <linux/mount.h>
#include <linux/capability.h>
#include <linux/time.h>
#include <linux/proc_fs.h>
#include <linux/kobject.h>
#include <linux/crypto.h>
#include <asm/scatterlist.h>
#include <linux/gfp.h>
#include <linux/sysfs.h>

#define SHA1_DIGEST_SIZE 20

/**
 * Module parameter that defines the initial secure level.
 *
 * When built as a module, it defaults to seclvl 1, which is the
 * behavior of BSD secure levels.  Note that this default behavior
 * wrecks havoc on a machine when the seclvl module is compiled into
 * the kernel.	In that case, we default to seclvl 0.
 */
#ifdef CONFIG_SECURITY_SECLVL_MODULE
static int initlvl = 1;
#else
static int initlvl;
#endif
module_param(initlvl, int, 0);
MODULE_PARM_DESC(initlvl, "Initial secure level (defaults to 1)");

/* Module parameter that defines the verbosity level */
static int verbosity;
module_param(verbosity, int, 0);
MODULE_PARM_DESC(verbosity, "Initial verbosity level (0 or 1; defaults to "
		 "0, which is Quiet)");

/**
 * Optional password which can be passed in to bring seclvl to 0
 * (i.e., for halt/reboot).  Defaults to NULL (the passwd attribute
 * file will not be registered in sysfs).
 *
 * This gets converted to its SHA1 hash when stored.  It's probably
 * not a good idea to use this parameter when loading seclvl from a
 * script; use sha1_passwd instead.
 */

#define MAX_PASSWD_SIZE	32
static char passwd[MAX_PASSWD_SIZE];
module_param_string(passwd, passwd, sizeof(passwd), 0);
MODULE_PARM_DESC(passwd,
		 "Plaintext of password that sets seclvl=0 when written to "
		 "(sysfs mount point)/seclvl/passwd\n");

/**
 * SHA1 hashed version of the optional password which can be passed in
 * to bring seclvl to 0 (i.e., for halt/reboot).  Must be in
 * hexadecimal format (40 characters).	Defaults to NULL (the passwd
 * attribute file will not be registered in sysfs).
 *
 * Use the sha1sum utility to generate the SHA1 hash of a password:
 *
 * echo -n "secret" | sha1sum
 */
#define MAX_SHA1_PASSWD	41
static char sha1_passwd[MAX_SHA1_PASSWD];
module_param_string(sha1_passwd, sha1_passwd, sizeof(sha1_passwd), 0);
MODULE_PARM_DESC(sha1_passwd,
		 "SHA1 hash (40 hexadecimal characters) of password that "
		 "sets seclvl=0 when plaintext password is written to "
		 "(sysfs mount point)/seclvl/passwd\n");

static int hideHash = 1;
module_param(hideHash, int, 0);
MODULE_PARM_DESC(hideHash, "When set to 0, reading seclvl/passwd from sysfs "
		 "will return the SHA1-hashed value of the password that "
		 "lowers the secure level to 0.\n");

#define MY_NAME "seclvl"

/**
 * This time-limits log writes to one per second.
 */
#define seclvl_printk(verb, type, fmt, arg...)			\
	do {							\
		if (verbosity >= verb) {			\
			static unsigned long _prior;		\
			unsigned long _now = jiffies;		\
			if ((_now - _prior) > HZ) {		\
				printk(type "%s: %s: " fmt,	\
					MY_NAME, __FUNCTION__ ,	\
					## arg);		\
				_prior = _now;			\
			}					\
		}						\
	} while (0)

/**
 * The actual security level.  Ranges between -1 and 2 inclusive.
 */
static int seclvl;

/**
 * flag to keep track of how we were registered
 */
static int secondary;

/**
 * Verifies that the requested secure level is valid, given the current
 * secure level.
 */
static int seclvl_sanity(int reqlvl)
{
	if ((reqlvl < -1) || (reqlvl > 2)) {
		seclvl_printk(1, KERN_WARNING, "Attempt to set seclvl out of "
			      "range: [%d]\n", reqlvl);
		return -EINVAL;
	}
	if ((seclvl == 0) && (reqlvl == -1))
		return 0;
	if (reqlvl < seclvl) {
		seclvl_printk(1, KERN_WARNING, "Attempt to lower seclvl to "
			      "[%d]\n", reqlvl);
		return -EPERM;
	}
	return 0;
}

/**
 * security level advancement rules:
 *   Valid levels are -1 through 2, inclusive.
 *   From -1, stuck.  [ in case compiled into kernel ]
 *   From 0 or above, can only increment.
 */
static void do_seclvl_advance(void *data, u64 val)
{
	int ret;
	int newlvl = (int)val;

	ret = seclvl_sanity(newlvl);
	if (ret)
		return;

	if (newlvl > 2) {
		seclvl_printk(1, KERN_WARNING, "Cannot advance to seclvl "
			      "[%d]\n", newlvl);
		return;
	}
	if (seclvl == -1) {
		seclvl_printk(1, KERN_WARNING, "Not allowed to advance to "
			      "seclvl [%d]\n", seclvl);
		return;
	}
	seclvl = newlvl;  /* would it be more "correct" to set *data? */
	return;
}

static u64 seclvl_int_get(void *data)
{
	return *(int *)data;
}

DEFINE_SIMPLE_ATTRIBUTE(seclvl_file_ops, seclvl_int_get, do_seclvl_advance, "%lld\n");

static unsigned char hashedPassword[SHA1_DIGEST_SIZE];

/**
 * Converts a block of plaintext of into its SHA1 hashed value.
 *
 * It would be nice if crypto had a wrapper to do this for us linear
 * people...
 */
static int
plaintext_to_sha1(unsigned char *hash, const char *plaintext, int len)
{
	char *pgVirtAddr;
	struct crypto_tfm *tfm;
	struct scatterlist sg[1];
	if (len > PAGE_SIZE) {
		seclvl_printk(0, KERN_ERR, "Plaintext password too large (%d "
			      "characters).  Largest possible is %lu "
			      "bytes.\n", len, PAGE_SIZE);
		return -ENOMEM;
	}
	tfm = crypto_alloc_tfm("sha1", CRYPTO_TFM_REQ_MAY_SLEEP);
	if (tfm == NULL) {
		seclvl_printk(0, KERN_ERR,
			      "Failed to load transform for SHA1\n");
		return -ENOSYS;
	}
	// Just get a new page; don't play around with page boundaries
	// and scatterlists.
	pgVirtAddr = (char *)__get_free_page(GFP_KERNEL);
	sg[0].page = virt_to_page(pgVirtAddr);
	sg[0].offset = 0;
	sg[0].length = len;
	strncpy(pgVirtAddr, plaintext, len);
	crypto_digest_init(tfm);
	crypto_digest_update(tfm, sg, 1);
	crypto_digest_final(tfm, hash);
	crypto_free_tfm(tfm);
	free_page((unsigned long)pgVirtAddr);
	return 0;
}

/**
 * Called whenever the user writes to the sysfs passwd handle to this kernel
 * object.  It hashes the password and compares the hashed results.
 */
static ssize_t
passwd_write_file(struct file * file, const char __user * buf,
				size_t count, loff_t *ppos)
{
	int i;
	unsigned char tmp[SHA1_DIGEST_SIZE];
	char *page;
	int rc;
	int len;

	if (!*passwd && !*sha1_passwd) {
		seclvl_printk(0, KERN_ERR, "Attempt to password-unlock the "
			      "seclvl module, but neither a plain text "
			      "password nor a SHA1 hashed password was "
			      "passed in as a module parameter!  This is a "
			      "bug, since it should not be possible to be in "
			      "this part of the module; please tell a "
			      "maintainer about this event.\n");
		return -EINVAL;
	}

	if (count < 0 || count >= PAGE_SIZE)
		return -EINVAL;
	if (*ppos != 0)
		return -EINVAL;
	page = (char *)get_zeroed_page(GFP_KERNEL);
	if (!page)
		return -ENOMEM;
	len = -EFAULT;
	if (copy_from_user(page, buf, count))
		goto out;

	len = strlen(page);
	/* ``echo "secret" > seclvl/passwd'' includes a newline */
	if (page[len - 1] == '\n')
		len--;
	/* Hash the password, then compare the hashed values */
	if ((rc = plaintext_to_sha1(tmp, page, len))) {
		seclvl_printk(0, KERN_ERR, "Error hashing password: rc = "
			      "[%d]\n", rc);
		return rc;
	}
	for (i = 0; i < SHA1_DIGEST_SIZE; i++) {
		if (hashedPassword[i] != tmp[i])
			return -EPERM;
	}
	seclvl_printk(0, KERN_INFO,
		      "Password accepted; seclvl reduced to 0.\n");
	seclvl = 0;
	len = count;

out:
	free_page((unsigned long)page);
	return len;
}

static struct file_operations passwd_file_ops = {
	.write = passwd_write_file,
};

/**
 * Explicitely disallow ptrace'ing the init process.
 */
static int seclvl_ptrace(struct task_struct *parent, struct task_struct *child)
{
	if (seclvl >= 0) {
		if (child->pid == 1) {
			seclvl_printk(1, KERN_WARNING, "Attempt to ptrace "
				      "the init process dissallowed in "
				      "secure level %d\n", seclvl);
			return -EPERM;
		}
	}
	return 0;
}

/**
 * Capability checks for seclvl.  The majority of the policy
 * enforcement for seclvl takes place here.
 */
static int seclvl_capable(struct task_struct *tsk, int cap)
{
	/* init can do anything it wants */
	if (tsk->pid == 1)
		return 0;

	switch (seclvl) {
	case 2:
		/* fall through */
	case 1:
		if (cap == CAP_LINUX_IMMUTABLE) {
			seclvl_printk(1, KERN_WARNING, "Attempt to modify "
				      "the IMMUTABLE and/or APPEND extended "
				      "attribute on a file with the IMMUTABLE "
				      "and/or APPEND extended attribute set "
				      "denied in seclvl [%d]\n", seclvl);
			return -EPERM;
		} else if (cap == CAP_SYS_RAWIO) {	// Somewhat broad...
			seclvl_printk(1, KERN_WARNING, "Attempt to perform "
				      "raw I/O while in secure level [%d] "
				      "denied\n", seclvl);
			return -EPERM;
		} else if (cap == CAP_NET_ADMIN) {
			seclvl_printk(1, KERN_WARNING, "Attempt to perform "
				      "network administrative task while "
				      "in secure level [%d] denied\n", seclvl);
			return -EPERM;
		} else if (cap == CAP_SETUID) {
			seclvl_printk(1, KERN_WARNING, "Attempt to setuid "
				      "while in secure level [%d] denied\n",
				      seclvl);
			return -EPERM;
		} else if (cap == CAP_SETGID) {
			seclvl_printk(1, KERN_WARNING, "Attempt to setgid "
				      "while in secure level [%d] denied\n",
				      seclvl);
		} else if (cap == CAP_SYS_MODULE) {
			seclvl_printk(1, KERN_WARNING, "Attempt to perform "
				      "a module operation while in secure "
				      "level [%d] denied\n", seclvl);
			return -EPERM;
		}
		break;
	default:
		break;
	}
	/* from dummy.c */
	if (cap_is_fs_cap(cap) ? tsk->fsuid == 0 : tsk->euid == 0)
		return 0;	/* capability granted */
	seclvl_printk(1, KERN_WARNING, "Capability denied\n");
	return -EPERM;		/* capability denied */
}

/**
 * Disallow reversing the clock in seclvl > 1
 */
static int seclvl_settime(struct timespec *tv, struct timezone *tz)
{
	if (tv && seclvl > 1) {
		struct timespec now;
		now = current_kernel_time();
		if (tv->tv_sec < now.tv_sec ||
		    (tv->tv_sec == now.tv_sec && tv->tv_nsec < now.tv_nsec)) {
			seclvl_printk(1, KERN_WARNING, "Attempt to decrement "
				      "time in secure level %d denied: "
				      "current->pid = [%d], "
				      "current->group_leader->pid = [%d]\n",
				      seclvl, current->pid,
				      current->group_leader->pid);
			return -EPERM;
		}		/* if attempt to decrement time */
	}			/* if seclvl > 1 */
	return 0;
}

/* claim the blockdev to exclude mounters, release on file close */
static int seclvl_bd_claim(struct inode *inode)
{
	int holder;
	struct block_device *bdev = NULL;
	dev_t dev = inode->i_rdev;
	bdev = open_by_devnum(dev, FMODE_WRITE);
	if (bdev) {
		if (bd_claim(bdev, &holder)) {
			blkdev_put(bdev);
			return -EPERM;
		}
		/* claimed, mark it to release on close */
		inode->i_security = current;
	}
	return 0;
}

/* release the blockdev if you claimed it */
static void seclvl_bd_release(struct inode *inode)
{
	if (inode && S_ISBLK(inode->i_mode) && inode->i_security == current) {
		struct block_device *bdev = inode->i_bdev;
		if (bdev) {
			bd_release(bdev);
			blkdev_put(bdev);
			inode->i_security = NULL;
		}
	}
}

/**
 * Security for writes to block devices is regulated by this seclvl
 * function.  Deny all writes to block devices in seclvl 2.  In
 * seclvl 1, we only deny writes to *mounted* block devices.
 */
static int
seclvl_inode_permission(struct inode *inode, int mask, struct nameidata *nd)
{
	if (current->pid != 1 && S_ISBLK(inode->i_mode) && (mask & MAY_WRITE)) {
		switch (seclvl) {
		case 2:
			seclvl_printk(1, KERN_WARNING, "Write to block device "
				      "denied in secure level [%d]\n", seclvl);
			return -EPERM;
		case 1:
			if (seclvl_bd_claim(inode)) {
				seclvl_printk(1, KERN_WARNING,
					      "Write to mounted block device "
					      "denied in secure level [%d]\n",
					      seclvl);
				return -EPERM;
			}
		}
	}
	return 0;
}

/**
 * The SUID and SGID bits cannot be set in seclvl >= 1
 */
static int seclvl_inode_setattr(struct dentry *dentry, struct iattr *iattr)
{
	if (seclvl > 0) {
		if (iattr->ia_valid & ATTR_MODE)
			if (iattr->ia_mode & S_ISUID ||
			    iattr->ia_mode & S_ISGID) {
				seclvl_printk(1, KERN_WARNING, "Attempt to "
					      "modify SUID or SGID bit "
					      "denied in seclvl [%d]\n",
					      seclvl);
				return -EPERM;
			}
	}
	return 0;
}

/* release busied block devices */
static void seclvl_file_free_security(struct file *filp)
{
	struct dentry *dentry = filp->f_dentry;
	struct inode *inode = NULL;

	if (dentry) {
		inode = dentry->d_inode;
		seclvl_bd_release(inode);
	}
}

/**
 * Cannot unmount in secure level 2
 */
static int seclvl_umount(struct vfsmount *mnt, int flags)
{
	if (current->pid == 1)
		return 0;
	if (seclvl == 2) {
		seclvl_printk(1, KERN_WARNING, "Attempt to unmount in secure "
			      "level %d\n", seclvl);
		return -EPERM;
	}
	return 0;
}

static struct security_operations seclvl_ops = {
	.ptrace = seclvl_ptrace,
	.capable = seclvl_capable,
	.inode_permission = seclvl_inode_permission,
	.inode_setattr = seclvl_inode_setattr,
	.file_free_security = seclvl_file_free_security,
	.settime = seclvl_settime,
	.sb_umount = seclvl_umount,
};

/**
 * Process the password-related module parameters
 */
static int processPassword(void)
{
	int rc = 0;
	hashedPassword[0] = '\0';
	if (*passwd) {
		if (*sha1_passwd) {
			seclvl_printk(0, KERN_ERR, "Error: Both "
				      "passwd and sha1_passwd "
				      "were set, but they are mutually "
				      "exclusive.\n");
			return -EINVAL;
		}
		if ((rc = plaintext_to_sha1(hashedPassword, passwd,
					    strlen(passwd)))) {
			seclvl_printk(0, KERN_ERR, "Error: SHA1 support not "
				      "in kernel\n");
			return rc;
		}
		/* All static data goes to the BSS, which zero's the
		 * plaintext password out for us. */
	} else if (*sha1_passwd) {	// Base 16
		int i;
		i = strlen(sha1_passwd);
		if (i != (SHA1_DIGEST_SIZE * 2)) {
			seclvl_printk(0, KERN_ERR, "Received [%d] bytes; "
				      "expected [%d] for the hexadecimal "
				      "representation of the SHA1 hash of "
				      "the password.\n",
				      i, (SHA1_DIGEST_SIZE * 2));
			return -EINVAL;
		}
		while ((i -= 2) + 2) {
			unsigned char tmp;
			tmp = sha1_passwd[i + 2];
			sha1_passwd[i + 2] = '\0';
			hashedPassword[i / 2] = (unsigned char)
			    simple_strtol(&sha1_passwd[i], NULL, 16);
			sha1_passwd[i + 2] = tmp;
		}
	}
	return 0;
}

/**
 * securityfs registrations
 */
struct dentry *dir_ino, *seclvl_ino, *passwd_ino;

static int seclvlfs_register(void)
{
	dir_ino = securityfs_create_dir("seclvl", NULL);
	if (!dir_ino)
		return -EFAULT;

	seclvl_ino = securityfs_create_file("seclvl", S_IRUGO | S_IWUSR,
				dir_ino, &seclvl, &seclvl_file_ops);
	if (!seclvl_ino)
		goto out_deldir;
	if (*passwd || *sha1_passwd) {
		passwd_ino = securityfs_create_file("passwd", S_IRUGO | S_IWUSR,
				dir_ino, NULL, &passwd_file_ops);
		if (!passwd_ino)
			goto out_delf;
	}
	return 0;

out_deldir:
	securityfs_remove(dir_ino);
out_delf:
	securityfs_remove(seclvl_ino);

	return -EFAULT;
}

/**
 * Initialize the seclvl module.
 */
static int __init seclvl_init(void)
{
	int rc = 0;
	if (verbosity < 0 || verbosity > 1) {
		printk(KERN_ERR "Error: bad verbosity [%d]; only 0 or 1 "
		       "are valid values\n", verbosity);
		rc = -EINVAL;
		goto exit;
	}
	if (initlvl < -1 || initlvl > 2) {
		seclvl_printk(0, KERN_ERR, "Error: bad initial securelevel "
			      "[%d].\n", initlvl);
		rc = -EINVAL;
		goto exit;
	}
	seclvl = initlvl;
	if ((rc = processPassword())) {
		seclvl_printk(0, KERN_ERR, "Error processing the password "
			      "module parameter(s): rc = [%d]\n", rc);
		goto exit;
	}
	/* register ourselves with the security framework */
	if (register_security(&seclvl_ops)) {
		seclvl_printk(0, KERN_ERR,
			      "seclvl: Failure registering with the "
			      "kernel.\n");
		/* try registering with primary module */
		rc = mod_reg_security(MY_NAME, &seclvl_ops);
		if (rc) {
			seclvl_printk(0, KERN_ERR, "seclvl: Failure "
				      "registering with primary security "
				      "module.\n");
			goto exit;
		}		/* if primary module registered */
		secondary = 1;
	}			/* if we registered ourselves with the security framework */
	if ((rc = seclvlfs_register())) {
		seclvl_printk(0, KERN_ERR, "Error registering with sysfs\n");
		goto exit;
	}
	seclvl_printk(0, KERN_INFO, "seclvl: Successfully initialized.\n");
 exit:
	if (rc) {
		printk(KERN_ERR "seclvl: Error during initialization: rc = "
		       "[%d]\n", rc);
	}
	return rc;
}

/**
 * Remove the seclvl module.
 */
static void __exit seclvl_exit(void)
{
	securityfs_remove(seclvl_ino);
	if (*passwd || *sha1_passwd)
		securityfs_remove(passwd_ino);
	securityfs_remove(dir_ino);
	if (secondary == 1) {
		mod_unreg_security(MY_NAME, &seclvl_ops);
	} else if (unregister_security(&seclvl_ops)) {
		seclvl_printk(0, KERN_INFO,
			      "seclvl: Failure unregistering with the "
			      "kernel\n");
	}
}

module_init(seclvl_init);
module_exit(seclvl_exit);

MODULE_AUTHOR("Michael A. Halcrow <mike@halcrow.us>");
MODULE_DESCRIPTION("LSM implementation of the BSD Secure Levels");
MODULE_LICENSE("GPL");


text:
<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
    <dimen name="three_dp">3dp</dimen>
    <dimen name="six_dp">6dp</dimen>
    <dimen name="card_elevation">2dp</dimen>
    <dimen name="card_corner_radius">6dp</dimen>
    <dimen name="details_toolbar_container_height">156dp</dimen>
    <dimen name="sixteen_dp">16dp</dimen>
    <dimen name="twenty_four_dp">24dp</dimen>
    <dimen name="eight_dp">8dp</dimen>

    <dimen name="font_title">26sp</dimen>
    <dimen name="font_large">22sp</dimen>
    <dimen name="font_medium">18sp</dimen>
    <dimen name="font_normal">16sp</dimen>
    <dimen name="fourty_eight_dp">48dp</dimen>
    <dimen name="fab_translateY">100dp</dimen>
    <dimen name="four_dp">4dp</dimen>
    <dimen name="fifty_six_dp">56dp</dimen>
    <dimen name="eight_sp">8sp</dimen>
    <dimen name="ten_sp">10sp</dimen>
    <dimen name="twelve_sp">12sp</dimen>
    <dimen name="spacing">6dp</dimen>
</resources>

redpajama_set_name: RedPajamaGithub


text:
import time

def listCFDistributions():
    return cf_client.list_distributions()

def checkCloudFrontExists(CFId):
    try:
        return cf_client.get_distribution_config(Id=CFId)
    except Exception:
        return False

def getCloudFrontStatus(CFId):
    try:
        return cf_client.get_distribution(Id=CFId)
    except Exception:
        return False

def deleteCloudFront(CFId, eTAG):
    print("\tcalling delete of CloudFront Dist ( " + CFId + " )")
    try:
        cf_client.delete_distribution(Id=CFId, IfMatch=eTAG)
        print("\t\tSuccessfully deleted CloudFront Distribution ( " + CFId +
              " )")
    except Exception:
        print("\t\tError deleting CloudFront Distribution ( " + CFId + " )")

def disableCloudFront(CFId, eTAG, dconfig):
    try:
        return cf_client.update_distribution(Id=CFId, DistributionConfig=dconfig, IfMatch=eTAG)
    except Exception:
        return False

def delete_cf_dists(stackname, client, deletedists=False):
    global cf_client
    cf_client = client

    print("Fetching Cloud Front Distributions")

    jsonCFDists = listCFDistributions()

    print("Done Fetching Cloud Front Distributions.")

    # First disable all the active Cloud Fronts             #
    print("Starting disable of CF Distributions for stack: {0}".format(
        stackname))

    for cfDistItem in jsonCFDists['DistributionList']['Items']:
        if (cfDistItem['Origins']['Items'][0]['Id'].startswith(stackname)):

            cfGetConfigResp = checkCloudFrontExists(cfDistItem['Id'])
            cfReadyToDelete = False

            if (cfGetConfigResp is not False):
                jsonCFGetConfig = cfGetConfigResp

                if (jsonCFGetConfig['DistributionConfig']['Enabled'] is True):
                    jsonCFGetConfig['DistributionConfig']['Enabled'] = False
                    print("Found Stack CF Distribution  ( " +
                          cfDistItem['Id'] + " ) that needs to be disabled")
                    retval = disableCloudFront(cfDistItem['Id'],
                                               jsonCFGetConfig['ETag'],
                                               jsonCFGetConfig['DistributionConfig'])
                    if (retval is not False):
                        print("Dist ( " + cfDistItem['Id'] +
                              " ) Disable has been called successfully..... ")
                    else:
                        print("ERROR Dist ( " + cfDistItem['Id'] +
                              " ) Disable call was NOT successful ERROR.")

            else:
                print("Error Fetching Dist ( " + cfDistItem['Id'] +
                      " ) details.....continuing")

    print("Finished disabling of CF Distributions for stack: {0}".format(
        stackname))

    if not deletedists:
        return

    # Keep going, we're disabling + deleting
    # Then continue deleting the CloudFront Distributions

    print("Starting deletion of CF Distributions for stack: {0}".format(
        stackname))

    for cfDistItem in jsonCFDists['DistributionList']['Items']:
        if (cfDistItem['Origins']['Items'][0]['Id'].startswith(stackname)):
            cfGetConfigResp = checkCloudFrontExists(cfDistItem['Id'])
            cfReadyToDelete = False

            if (cfGetConfigResp is not False):
                jsonCFGetConfig = cfGetConfigResp
                print("\tStarted on CloudFront Distribution ( " +
                      cfDistItem['Id'] + " ) which is enabled==" +
                      str(jsonCFGetConfig['DistributionConfig']['Enabled']))
                if (jsonCFGetConfig['DistributionConfig']['Enabled'] is True):
                    jsonCFGetConfig['DistributionConfig']['Enabled'] = False
                    print(
                        "\t\tFirst Disabling the Cloud Front Distribution ( " +
                        cfDistItem['Id'] + " ) set enabled==" + str(
                            jsonCFGetConfig['DistributionConfig']['Enabled']))
                    disableCloudFront(cfDistItem['Id'],
                                      jsonCFGetConfig['ETag'], jsonCFGetConfig['DistributionConfig'])

                    while (cfReadyToDelete is False):
                        valuesStatus = getCloudFrontStatus(cfDistItem['Id'])
                        if (valuesStatus['Distribution']['Status'] ==
                                "InProgress"):
                            cfReadyToDelete = False
                            print(
                                "\t\t\tsleeping for 30 secs (POST Disabling) on ::"
                                + cfDistItem['Id'])
                            time.sleep(30)
                            print("\t\t\tAwake and checking on::" +
                                  cfDistItem['Id'])
                        else:
                            cfReadyToDelete = True

                    deleteCloudFront(cfDistItem['Id'], jsonCFGetConfig['ETag'])

                else:
                    while (cfReadyToDelete is False):
                        valuesStatus = getCloudFrontStatus(cfDistItem['Id'])
                        if (valuesStatus['Distribution']['Status'] ==
                                "InProgress"):
                            cfReadyToDelete = False
                            print(
                                "\t\tsleeping for 30 secs (WAITING To DELETE)::"
                                + cfDistItem['Id'])
                            time.sleep(30)
                            print("\t\tAwake and checking on::" +
                                  cfDistItem['Id'])
                        else:
                            cfReadyToDelete = True

                    deleteCloudFront(cfDistItem['Id'], jsonCFGetConfig['ETag'])

    print("Completed deleting of CF Distributions for stack {0}".format(
        stackname))


text:
<!DOCTYPE html>

  <meta charset="utf-8" />
  <title>zero.md - Grip</title>
  <link rel="icon" href="/__/grip/static/favicon.ico" />


text:
var React = require('react');
var ReactPropTypes = React.PropTypes;

var ENTER_KEY_CODE = 13;

var SearchField = React.createClass({

	propTypes: {
	    className: ReactPropTypes.string,
	    id: ReactPropTypes.string,
	    size: ReactPropTypes.number,
	    onSave: ReactPropTypes.func.isRequired,
  	},

	getInitialState: function() {
	    return {
	      	value: ''
	    };
	},

	render: function() {
		return (
			<input
				className={this.props.className}
		        id={this.props.id}
		        name={this.props.id}
		        type="search"
		        size={this.props.size}
		        onChange={this._onChange}
		        onKeyDown={this._onKeyDown}
		        value={this.state.value}
		        autoFocus={true}
		    />
		);
	},

  /**
   * Invokes the callback passed in as onSave, allowing this component to be
   * used in different ways.
   */
  _save: function() {
    this.props.onSave(this.state.value);
  },

  /**
   * @param {object} event
   */
  _onChange: function(/*object*/ event) {
    this.setState({
      value: event.target.value
    });
  },

  /**
   * @param  {object} event
   */
  _onKeyDown: function(event) {
    if (event.keyCode === ENTER_KEY_CODE) {
      this._save();
    }
  }

});

module.exports = SearchField;


text:
package com.my.oracle;
public class OracleService {}
//package com.my.oracle;
//
//import java.text.ParseException;
//import java.text.SimpleDateFormat;
//import java.util.ArrayList;
//import java.util.HashMap;
//import java.util.LinkedHashMap;
//import java.util.List;
//import java.util.Map;
//import java.util.AbstractMap.SimpleEntry;
//import java.util.TreeMap;
//
//import javax.annotation.Resource;
//
//import oracle.jdbc.OracleTypes;
//import oracle.sql.DATE;
//
//import org.springframework.jdbc.core.JdbcTemplate;
//import org.springframework.jdbc.core.SqlParameter;
//import org.springframework.jdbc.core.simple.SimpleJdbcCall;
//import org.springframework.stereotype.Service;
//
//@Service
//public class OracleService {
//	private @Resource(name = "jdbcDev") JdbcTemplate template;
//	private Map<String, Object> paramsEntity = new HashMap<String, Object>();
//	private static final LinkedHashMap<String, SimpleEntry<String, Integer>> namesAndTypeEntity = new LinkedHashMap<String, SimpleEntry<String, Integer>>() {
//		{
//			put("p_domain_name", new SimpleEntry<String, Integer>("p_domain_name", OracleTypes.VARCHAR));
//			put("conceptId_qcode", new SimpleEntry<String, Integer>("p_code", OracleTypes.VARCHAR));
//			put("type_qcode", new SimpleEntry<String, Integer>("p_entity_type", OracleTypes.VARCHAR));
//			put("p_english_name", new SimpleEntry<String, Integer>("p_english_name", OracleTypes.VARCHAR));
//			put("p_english_definition", new SimpleEntry<String, Integer>("p_english_definition", OracleTypes.VARCHAR));
//			put("stage_current", new SimpleEntry<String, Integer>("p_stage", OracleTypes.VARCHAR));
//			put("stage_date", new SimpleEntry<String, Integer>("p_stage_date", OracleTypes.DATE));
//			put("appliesTo_profile", new SimpleEntry<String, Integer>("p_applies_to", OracleTypes.VARCHAR));
//			put("created", new SimpleEntry<String, Integer>("p_created", OracleTypes.DATE));
//			put("isContentGrouping", new SimpleEntry<String, Integer>("p_is_content_grouping", OracleTypes.VARCHAR));
//			put("isIsoHistorical", new SimpleEntry<String, Integer>("p_is_iso_historical", OracleTypes.VARCHAR));
//			put("isNotForThirdPartyUse", new SimpleEntry<String, Integer>("p_is_not_for_third_party_use", OracleTypes.VARCHAR));
//			put("isForThirdPartyUseOnly", new SimpleEntry<String, Integer>("p_is_for_third_party_use_only", OracleTypes.VARCHAR));
//			put("additionalCodes", new SimpleEntry<String, Integer>("p_additional_codes", OracleTypes.VARCHAR));
//			put("isNotForDisplay", new SimpleEntry<String, Integer>("p_is_not_for_display", OracleTypes.VARCHAR));
//		}
//	};
//
//	private static List<SqlParameter> list = new ArrayList<SqlParameter>();
//	//private static SqlParameter[] pList = new SqlParameter[namesAndTypeEntity.size()];
//	static {
////		list.add(new SqlParameter(namesAndTypeEntity.get("p_domain_name").getKey(), namesAndTypeEntity.get("p_domain_name").getValue()));
////		list.add(new SqlParameter(namesAndTypeEntity.get("p_code").getKey(), namesAndTypeEntity.get("p_code").getValue()));
////		list.add(new SqlParameter(namesAndTypeEntity.get("p_entity_type").getKey(), namesAndTypeEntity.get("p_entity_type").getValue()));
////		list.add(new SqlParameter(namesAndTypeEntity.get("p_english_name").getKey(), namesAndTypeEntity.get("p_english_name").getValue()));
////		list.add(new SqlParameter(namesAndTypeEntity.get("p_english_definition").getKey(), namesAndTypeEntity.get("p_english_definition").getValue()));
////		list.add(new SqlParameter(namesAndTypeEntity.get("p_stage").getKey(), namesAndTypeEntity.get("p_stage").getValue()));
////		list.add(new SqlParameter(namesAndTypeEntity.get("p_stage_date").getKey(), namesAndTypeEntity.get("p_stage_date").getValue()));
////		list.add(new SqlParameter(namesAndTypeEntity.get("p_applies_to").getKey(), namesAndTypeEntity.get("p_applies_to").getValue()));
////		list.add(new SqlParameter(namesAndTypeEntity.get("p_created").getKey(), namesAndTypeEntity.get("p_created").getValue()));
////		list.add(new SqlParameter(namesAndTypeEntity.get("p_is_content_grouping").getKey(), namesAndTypeEntity.get("p_is_content_grouping").getValue()));
////		list.add(new SqlParameter(namesAndTypeEntity.get("p_is_iso_historical").getKey(), namesAndTypeEntity.get("p_is_iso_historical").getValue()));
////		list.add(new SqlParameter(namesAndTypeEntity.get("p_is_not_for_third_party_use").getKey(), namesAndTypeEntity.get("p_is_not_for_third_party_use").getValue()));
////		list.add(new SqlParameter(namesAndTypeEntity.get("p_is_for_third_party_use_only").getKey(), namesAndTypeEntity.get("p_is_for_third_party_use_only").getValue()));
////		list.add(new SqlParameter(namesAndTypeEntity.get("p_additional_codes").getKey(), namesAndTypeEntity.get("p_additional_codes").getValue()));
////		list.add(new SqlParameter(namesAndTypeEntity.get("p_is_not_for_display").getKey(), namesAndTypeEntity.get("p_is_not_for_display").getValue()));
//
//				int i =0;
//		for (String key : namesAndTypeEntity.keySet()) {
//			list.add(new SqlParameter(namesAndTypeEntity.get(key).getKey(), namesAndTypeEntity.get(key).getValue()));
//			//pList[i] = new SqlParameter(namesAndTypeEntity.get(key).getKey(), namesAndTypeEntity.get(key).getValue());
//			i++;
//		}
//	}
//
//	private SqlParameter[] pSqlParameters = new SqlParameter[] {
//			new SqlParameter("p_domain_name", OracleTypes.VARCHAR),
//			new SqlParameter("p_code", OracleTypes.VARCHAR),
//			new SqlParameter("p_entity_type", OracleTypes.VARCHAR),
//			new SqlParameter("p_english_name", OracleTypes.VARCHAR),
//			new SqlParameter("p_english_definition", OracleTypes.VARCHAR),
//			new SqlParameter("p_stage", OracleTypes.VARCHAR),
//			new SqlParameter("p_stage_date", OracleTypes.DATE),
//			new SqlParameter("p_applies_to", OracleTypes.VARCHAR),
//			new SqlParameter("p_created", OracleTypes.DATE),
//			new SqlParameter("p_is_content_grouping", OracleTypes.VARCHAR),
//			new SqlParameter("p_is_iso_historical", OracleTypes.VARCHAR),
//			new SqlParameter("p_is_not_for_third_party_use", OracleTypes.VARCHAR),
//			new SqlParameter("p_is_for_third_party_use_only", OracleTypes.VARCHAR),
//			new SqlParameter("p_additional_codes", OracleTypes.VARCHAR),
//			new SqlParameter("p_is_not_for_display", OracleTypes.VARCHAR) };
//
//	private void getArgs(SqlParameter ...parameters) {
//		System.out.println("---->>>>");
//		for (SqlParameter p : parameters) {
//			System.out.println(p.getName() + ":" + p.getSqlType());
//		}
//	}
//
//	public void test2() {
//		getArgs(list.toArray(new SqlParameter[0]));
//	}
//
//	public void test3() {
//		getArgs(
//				new SqlParameter("p_domain_name",OracleTypes.VARCHAR),
//				new SqlParameter("p_code",OracleTypes.VARCHAR),
//				new SqlParameter("p_entity_type",OracleTypes.VARCHAR),
//				new SqlParameter("p_english_name",OracleTypes.VARCHAR),
//				new SqlParameter("p_english_definition",OracleTypes.VARCHAR),
//				new SqlParameter("p_stage",OracleTypes.VARCHAR),
//				new SqlParameter("p_stage_date",OracleTypes.DATE),
//				new SqlParameter("p_applies_to",OracleTypes.VARCHAR),
//				new SqlParameter("p_created",OracleTypes.DATE),
//				new SqlParameter("p_is_content_grouping",OracleTypes.VARCHAR),
//				new SqlParameter("p_is_iso_historical",OracleTypes.VARCHAR),
//				new SqlParameter("p_is_not_for_third_party_use",OracleTypes.VARCHAR),
//				new SqlParameter("p_is_for_third_party_use_only",OracleTypes.VARCHAR),
//				new SqlParameter("p_additional_codes",OracleTypes.VARCHAR),
//				new SqlParameter("p_is_not_for_display",OracleTypes.VARCHAR));
//	}
//
//	public void test() {
//
////		list.add(new SqlParameter(namesAndTypeEntity.get("p_domain_name").getKey(), namesAndTypeEntity.get("p_domain_name").getValue()));
////		list.add(new SqlParameter(namesAndTypeEntity.get("conceptId_qcode").getKey(), namesAndTypeEntity.get("conceptId_qcode").getValue()));
////		list.add(new SqlParameter(namesAndTypeEntity.get("type_qcode").getKey(), namesAndTypeEntity.get("type_qcode").getValue()));
////		list.add(new SqlParameter(namesAndTypeEntity.get("p_english_name").getKey(), namesAndTypeEntity.get("p_english_name").getValue()));
////		list.add(new SqlParameter(namesAndTypeEntity.get("p_english_definition").getKey(), namesAndTypeEntity.get("p_english_definition").getValue()));
////		list.add(new SqlParameter(namesAndTypeEntity.get("stage_current").getKey(), namesAndTypeEntity.get("stage_current").getValue()));
////		list.add(new SqlParameter(namesAndTypeEntity.get("stage_date").getKey(), namesAndTypeEntity.get("stage_date").getValue()));
////		list.add(new SqlParameter(namesAndTypeEntity.get("appliesTo_profile").getKey(), namesAndTypeEntity.get("appliesTo_profile").getValue()));
////		list.add(new SqlParameter(namesAndTypeEntity.get("created").getKey(), namesAndTypeEntity.get("created").getValue()));
////		list.add(new SqlParameter(namesAndTypeEntity.get("isContentGrouping").getKey(), namesAndTypeEntity.get("isContentGrouping").getValue()));
////		list.add(new SqlParameter(namesAndTypeEntity.get("isIsoHistorical").getKey(), namesAndTypeEntity.get("isIsoHistorical").getValue()));
////		list.add(new SqlParameter(namesAndTypeEntity.get("isNotForThirdPartyUse").getKey(), namesAndTypeEntity.get("isNotForThirdPartyUse").getValue()));
////		list.add(new SqlParameter(namesAndTypeEntity.get("isForThirdPartyUseOnly").getKey(), namesAndTypeEntity.get("isForThirdPartyUseOnly").getValue()));
////		list.add(new SqlParameter(namesAndTypeEntity.get("additionalCodes").getKey(), namesAndTypeEntity.get("additionalCodes").getValue()));
////		list.add(new SqlParameter(namesAndTypeEntity.get("isNotForDisplay").getKey(), namesAndTypeEntity.get("isNotForDisplay").getValue()));
//
//
//
//		//Arrays.eq
//		SimpleJdbcCall simpleJdbcCall = new SimpleJdbcCall(template);
//		simpleJdbcCall.withoutProcedureColumnMetaDataAccess()
//		.withCatalogName("pkg_load_rcs")
//		.withProcedureName("insert_entity")
//		//.declareParameters(pList);
//		//.declareParameters(Arrays.asList(pSqlParameters).toArray(new SqlParameter[0]));
//		.declareParameters(list.toArray(new SqlParameter[0]));
//
//		java.util.Date date = null;
//		try {
//			date = new SimpleDateFormat("yyyy-MM-dd").parse("1900-01-01");
//		} catch (ParseException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		java.sql.Date date2 = new java.sql.Date(date.getTime());
//		DATE sqlDate = new DATE(date2);
//		paramsEntity.put("p_domain_name", "agriculture");
//		paramsEntity.put("p_code", "M:1");
//		paramsEntity.put("p_entity_type", "cptType:49");
//		paramsEntity.put("p_english_name", null);
//		paramsEntity.put("p_english_definition", null);
//		paramsEntity.put("p_stage", "stg:live");
//		paramsEntity.put("p_stage_date", null);
//		paramsEntity.put("p_applies_to", null);
//		paramsEntity.put("p_created", sqlDate);
//		paramsEntity.put("p_is_content_grouping", "isContentGrouping");
//		paramsEntity.put("p_is_iso_historical", null);
//		paramsEntity.put("p_is_not_for_third_party_use", null);
//		paramsEntity.put("p_is_for_third_party_use_only", null);
//		paramsEntity.put("p_additional_codes", null);
//		paramsEntity.put("p_is_not_for_display", null);
//
//		simpleJdbcCall.execute(paramsEntity);
//	}
//}


text:
"use strict";
var __module_chai = require("chai");
var PeerMock = require("../lib/PeerMock");
var DataConnectionMock = require("../lib/DataConnectionMock");
var expect = __module_chai.expect;

describe('DataConnectionMock', function() {
    var remote = null;
    var local = null;

    beforeEach(function() {
        var localPeer = new PeerMock('local');
        var remotePeer = new PeerMock('remote');
        local = new DataConnectionMock('remote', localPeer);
        remote = new DataConnectionMock('local', remotePeer);
        local._connection = remote;
        remote._connection = local;
    });

    it('should emit close on close', function(done) {
        local.open = true;
        local.on('close', function() {
            return done();
        });
        local.close();
    });

    it('should receive what is sent', function(done) {
        remote.on('data', function(message) {
            expect(message).to.equal('hi there!');
            done();
        });
        local.send('hi there!');
    });
});

module.exports = {
    'PeerMock': PeerMock,
    'DataConnectionMock': DataConnectionMock,
    'expect': expect
};


text:
package geekheads.tuples;

import java.util.Optional;

public class Monople<T> implements Tuple<Monople<T>> {
  public final T first;

  public static <V> Monople<V> of(V v) {
    return new Monople<>(v);
  }

  private Monople(T t) {
    this.first = t;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }

    Monople<?> tuple1 = (Monople<?>) o;

    return !(first != null ? !first.equals(tuple1.first) : tuple1.first != null);
  }

  @Override
  public int hashCode() {
    return first != null ? first.hashCode() : 0;
  }

  @Override
  public Optional<Object> apply(int value) {
    switch (value) {
      case 0:
        return Optional.of(this.first);
      default:
        return Optional.empty();
    }
  }

  @Override
  public String toString() {
    return "(" + first + ')';
  }

  @Override
  public int size() {
    return 1;
  }
}


text:
using System;
using System.Collections.Generic;
using System.Html;

namespace wwtlib
{

    public class SimpleLineShader
    {
        public SimpleLineShader()
        {

        }

        internal static WebGLShader frag;
        internal static WebGLShader vert;

        public static int vertLoc;
        public static WebGLUniformLocation lineColorLoc;
        public static WebGLUniformLocation projMatLoc;
        public static WebGLUniformLocation mvMatLoc;

        public static bool initialized = false;
        public static void Init(RenderContext renderContext)
        {
            GL gl = renderContext.gl;

            String fragShaderText =
                      " precision highp float;                                                              \n" +
                      " uniform vec4 lineColor;                                                               \n" +
                      "                                                                                \n" +
                      "   void main(void) {                                                                   \n" +
                      "   gl_FragColor = lineColor;         \n" +
                      "   }                                                                                \n";

            String vertexShaderText =
                    "     attribute vec3 aVertexPosition;                                              \n" +
                    "                                                                                \n" +
                    "     uniform mat4 uMVMatrix;                                                      \n" +
                    "     uniform mat4 uPMatrix;                                                       \n" +
                    "                                                                                \n" +
                    "                                                                                \n" +
                    "                                                                                \n" +
                    "     void main(void) {                                                            \n" +
                    "         gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);         \n" +
                    "     }                                                                            \n" +
                    "                                                                                \n";
            frag = gl.createShader(GL.FRAGMENT_SHADER);
            gl.shaderSource(frag, fragShaderText);
            gl.compileShader(frag);

            object stat = gl.getShaderParameter(frag, GL.COMPILE_STATUS);

            vert = gl.createShader(GL.VERTEX_SHADER);
            gl.shaderSource(vert, vertexShaderText);
            gl.compileShader(vert);
            object stat1 = gl.getShaderParameter(vert, GL.COMPILE_STATUS);

            prog = gl.createProgram();

            gl.attachShader(prog, vert);
            gl.attachShader(prog, frag);
            gl.linkProgram(prog);
            object errcode = gl.getProgramParameter(prog, GL.LINK_STATUS);

            gl.useProgram(prog);

            vertLoc = gl.getAttribLocation(prog, "aVertexPosition");
            lineColorLoc = gl.getUniformLocation(prog, "lineColor");
            projMatLoc = gl.getUniformLocation(prog, "uPMatrix");
            mvMatLoc = gl.getUniformLocation(prog, "uMVMatrix");

            gl.enable(GL.BLEND);
            gl.blendFunc(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA);
            initialized = true;
        }

        private static WebGLProgram prog = null;

        public static void Use(RenderContext renderContext, WebGLBuffer vertex, Color lineColor)
        {
            GL gl = renderContext.gl;
            if (gl != null)
            {
                if (!initialized)
                {
                    Init(renderContext);
                }

                gl.useProgram(prog);

                Matrix3d mvMat = Matrix3d.MultiplyMatrix(renderContext.World, renderContext.View);

                gl.uniformMatrix4fv(mvMatLoc, false, mvMat.FloatArray());
                gl.uniformMatrix4fv(projMatLoc, false, renderContext.Projection.FloatArray());
                gl.uniform4f(lineColorLoc, lineColor.R/255, lineColor.G/255, lineColor.B/255, 1);
                if (renderContext.Space)
                {
                    gl.disable(GL.DEPTH_TEST);
                }
                else
                {
                    gl.enable(GL.DEPTH_TEST);
                }
                gl.disableVertexAttribArray(0);
                gl.disableVertexAttribArray(1);
                gl.disableVertexAttribArray(2);
                gl.disableVertexAttribArray(3);

                gl.enableVertexAttribArray(vertLoc);

                gl.bindBuffer(GL.ARRAY_BUFFER, vertex);
                gl.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, null);
                gl.vertexAttribPointer(vertLoc, 3, GL.FLOAT, false, 0, 0);
                gl.lineWidth(1.0f);
                gl.blendFunc(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA);
            }
        }
    }

    public class LineShaderNormalDates
    {
        public LineShaderNormalDates()
        {

        }

        internal static WebGLShader frag;
        internal static WebGLShader vert;

        public static int vertLoc;
        public static int colorLoc;
        public static int timeLoc;
        public static WebGLUniformLocation lineColorLoc;
        public static WebGLUniformLocation projMatLoc;
        public static WebGLUniformLocation mvMatLoc;
        public static WebGLUniformLocation jNowLoc;
        public static WebGLUniformLocation decayLoc;

        public static bool initialized = false;
        public static void Init(RenderContext renderContext)
        {
            GL gl = renderContext.gl;

            String fragShaderText =
                    "    precision highp float;                                                              \n" +
                    "    uniform vec4 lineColor;                                                             \n" +
                    "    varying lowp vec4 vColor;                                                           \n" +
                    "    void main(void)                                                                     \n" +
                    "    {                                                                                \n" +
                    "        gl_FragColor = lineColor * vColor;                                              \n" +
                    "    }                                                                                \n";

            String vertexShaderText =
                    "    attribute vec3 aVertexPosition;                                                     \n" +
                    "    attribute vec4 aVertexColor;                                                        \n" +
                    "    attribute vec2 aTime;                                                               \n" +
                    "    uniform mat4 uMVMatrix;                                                             \n" +
                    "    uniform mat4 uPMatrix;                                                              \n" +
                    "    uniform float jNow;                                                                 \n" +
                    "    uniform float decay;                                                                \n" +
                    "                                                                                \n" +
                    "    varying lowp vec4 vColor;                                                           \n" +
                    "                                                                                \n" +
                    "    void main(void)                                                                     \n" +
                    "    {                                                                                \n" +
                    "        gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);                \n" +
                    "        float dAlpha = 1.0;                                                             \n" +
                    "        if ( decay > 0.0)                                                               \n" +
                    "        {                                                                               \n" +
                    "             dAlpha = 1.0 - ((jNow - aTime.y) / decay);                                 \n " +
                    "             if (dAlpha > 1.0 )                                                         \n" +
                    "             {                                                                          \n" +
                    "                  dAlpha = 1.0;                                                         \n" +
                    "             }                                                                          \n" +
                    "        }                                                                               \n" +
                    "     if (jNow < aTime.x && decay > 0.0)                                                 \n" +
                    "     {                                                                                \n" +
                    "         vColor = vec4(0.0, 0.0, 0.0, 0.0);                                             \n" +
                    "     }                                                                                \n" +
                    "     else                                                                               \n" +
                    "     {                                                                                \n" +
                    "        vColor = vec4(aVertexColor.r, aVertexColor.g, aVertexColor.b, dAlpha);          \n" +
                    "     }                                                                                \n" +
                    "    }                                                                                \n" +
                    "                                                                                \n";

            frag = gl.createShader(GL.FRAGMENT_SHADER);
            gl.shaderSource(frag, fragShaderText);
            gl.compileShader(frag);

            object stat = gl.getShaderParameter(frag, GL.COMPILE_STATUS);

            vert = gl.createShader(GL.VERTEX_SHADER);
            gl.shaderSource(vert, vertexShaderText);
            gl.compileShader(vert);
            object stat1 = gl.getShaderParameter(vert, GL.COMPILE_STATUS);

            prog = gl.createProgram();

            gl.attachShader(prog, vert);
            gl.attachShader(prog, frag);
            gl.linkProgram(prog);
            object errcode = gl.getProgramParameter(prog, GL.LINK_STATUS);

            gl.useProgram(prog);

            vertLoc = gl.getAttribLocation(prog, "aVertexPosition");
            colorLoc = gl.getAttribLocation(prog, "aVertexColor");
            timeLoc = gl.getAttribLocation(prog, "aVertexColor");
            lineColorLoc = gl.getUniformLocation(prog, "lineColor");
            projMatLoc = gl.getUniformLocation(prog, "uPMatrix");
            mvMatLoc = gl.getUniformLocation(prog, "uMVMatrix");
            jNowLoc = gl.getUniformLocation(prog, "jNow");
            decayLoc = gl.getUniformLocation(prog, "decay");

            gl.enable(GL.BLEND);
            gl.blendFunc(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA);
            initialized = true;
        }

        private static WebGLProgram prog = null;

        public static void Use(RenderContext renderContext, WebGLBuffer vertex, Color lineColor, bool zBuffer, float jNow, float decay)
        {
            GL gl = renderContext.gl;
            if (gl != null)
            {
                if (!initialized)
                {
                    Init(renderContext);
                }

                gl.useProgram(prog);

                Matrix3d mvMat = Matrix3d.MultiplyMatrix(renderContext.World, renderContext.View);

                gl.uniformMatrix4fv(mvMatLoc, false, mvMat.FloatArray());
                gl.uniformMatrix4fv(projMatLoc, false, renderContext.Projection.FloatArray());
                gl.uniform4f(lineColorLoc, lineColor.R / 255, lineColor.G / 255, lineColor.B / 255, 1);
                gl.uniform1f(jNowLoc, jNow);
                gl.uniform1f(decayLoc, decay);

                if (zBuffer)
                {
                    gl.enable(GL.DEPTH_TEST);
                }
                else
                {
                    gl.disable(GL.DEPTH_TEST);
                }
                gl.disableVertexAttribArray(0);
                gl.disableVertexAttribArray(1);
                gl.disableVertexAttribArray(2);
                gl.disableVertexAttribArray(3);

                gl.enableVertexAttribArray(vertLoc);
                gl.enableVertexAttribArray(colorLoc);

                gl.bindBuffer(GL.ARRAY_BUFFER, vertex);
                gl.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, null);
                gl.vertexAttribPointer(vertLoc, 3, GL.FLOAT, false, 36, 0);
                gl.vertexAttribPointer(colorLoc, 4, GL.FLOAT, false, 36, 12);
                gl.vertexAttribPointer(colorLoc, 2, GL.FLOAT, false, 36, 28);
                gl.lineWidth(1.0f);
                gl.blendFunc(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA);
            }
        }
    }

    public class TimeSeriesPointSpriteShader
    {
        public TimeSeriesPointSpriteShader()
        {

        }

        internal static WebGLShader frag;
        internal static WebGLShader vert;

        public static int vertLoc;
        public static int colorLoc;
        public static int pointSizeLoc;
        public static int timeLoc;
        public static WebGLUniformLocation projMatLoc;
        public static WebGLUniformLocation mvMatLoc;
        public static WebGLUniformLocation sampLoc;
        public static WebGLUniformLocation jNowLoc;
        public static WebGLUniformLocation decayLoc;
        public static WebGLUniformLocation lineColorLoc;

        public static bool initialized = false;
        public static void Init(RenderContext renderContext)
        {
            GL gl = renderContext.gl;

            String fragShaderText =
                    "    precision mediump float;                                                            \n" +
                    "    uniform vec4 lineColor;                                                             \n" +
                    "    varying lowp vec4 vColor;                                                           \n" +
                    "    uniform sampler2D uSampler;                                                         \n" +
                    "    void main(void)                                                                     \n" +
                    "    {                                                                                \n" +
                    "        vec4 texColor;                                                                  \n" +
                    "        texColor = texture2D(uSampler, gl_PointCoord);                                  \n" +
                    "                                                                                \n" +
                    "                                                                                \n" +
                    "        gl_FragColor = lineColor * vColor * texColor;                                   \n" +
                    "    }                                                                                \n";

            String vertexShaderText =
                    "    attribute vec3 aVertexPosition;                                                     \n" +
                    "    attribute vec4 aVertexColor;                                                        \n" +
                    "    attribute vec2 aTime;                                                               \n" +
                    "    attribute float aPointSize;                                                         \n" +
                    "    uniform mat4 uMVMatrix;                                                             \n" +
                    "    uniform mat4 uPMatrix;                                                              \n" +
                    "    uniform float jNow;                                                                 \n" +
                    "    uniform float decay;                                                                \n" +
                    "                                                                                \n" +
                    "    varying lowp vec4 vColor;                                                           \n" +
                    "                                                                                \n" +
                    "    void main(void)                                                                     \n" +
                    "    {                                                                                \n" +
                    "        gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);                \n" +
                    "        float dAlpha = 1.0;                                                             \n" +
                    "        if ( decay > 0.0)                                                               \n" +
                    "        {                                                                               \n" +
                    "             dAlpha = 1.0 - ((jNow - aTime.y) / decay);                                 \n " +
                    "             if (dAlpha > 1.0 )                                                         \n" +
                    "             {                                                                          \n" +
                    "                  dAlpha = 1.0;                                                         \n" +
                    "             }                                                                          \n" +
                    "        }                                                                               \n" +
                    "     if (jNow < aTime.x && decay > 0.0)                                                 \n" +
                    "     {                                                                                \n" +
                    "         vColor = vec4(0.0, 0.0, 0.0, 0.0);                                             \n" +
                    "     }                                                                                \n" +
                    "     else                                                                               \n" +
                    "     {                                                                                \n" +
                    "        vColor = vec4(aVertexColor.r, aVertexColor.g, aVertexColor.b, dAlpha);          \n" +
                    "     }                                                                                \n" +
                    "        gl_PointSize = aPointSize/0.1;                                                  \n" +
                    "    }                                                                                \n" +
                    "                                                                                \n";

            frag = gl.createShader(GL.FRAGMENT_SHADER);
            gl.shaderSource(frag, fragShaderText);
            gl.compileShader(frag);

            object stat = gl.getShaderParameter(frag, GL.COMPILE_STATUS);

            vert = gl.createShader(GL.VERTEX_SHADER);
            gl.shaderSource(vert, vertexShaderText);
            gl.compileShader(vert);
            object stat1 = gl.getShaderParameter(vert, GL.COMPILE_STATUS);
            object compilationLog = gl.getShaderInfoLog(vert);
            prog = gl.createProgram();

            gl.attachShader(prog, vert);
            gl.attachShader(prog, frag);
            gl.linkProgram(prog);
            object errcode = gl.getProgramParameter(prog, GL.LINK_STATUS);

            gl.useProgram(prog);

            vertLoc = gl.getAttribLocation(prog, "aVertexPosition");
            colorLoc = gl.getAttribLocation(prog, "aVertexColor");
            pointSizeLoc = gl.getAttribLocation(prog, "aPointSize");
            timeLoc = gl.getAttribLocation(prog, "aTime");
            projMatLoc = gl.getUniformLocation(prog, "uPMatrix");
            mvMatLoc = gl.getUniformLocation(prog, "uMVMatrix");
            sampLoc = gl.getUniformLocation(prog, "uSampler");
            jNowLoc = gl.getUniformLocation(prog, "jNow");
            decayLoc = gl.getUniformLocation(prog, "decay");
            lineColorLoc = gl.getUniformLocation(prog, "lineColor");

            gl.enable(GL.BLEND);

            initialized = true;
        }

        private static WebGLProgram prog = null;

        public static void Use(RenderContext renderContext, WebGLBuffer vertex, WebGLTexture texture, Color lineColor, bool zBuffer, float jNow, float decay)
        {
            GL gl = renderContext.gl;
            if (gl != null)
            {
                if (!initialized)
                {
                    Init(renderContext);
                }

                gl.useProgram(prog);

                Matrix3d mvMat = Matrix3d.MultiplyMatrix(renderContext.World, renderContext.View);

                gl.uniformMatrix4fv(mvMatLoc, false, mvMat.FloatArray());
                gl.uniformMatrix4fv(projMatLoc, false, renderContext.Projection.FloatArray());
                gl.uniform1i(sampLoc, 0);
                gl.uniform1f(jNowLoc, jNow);
                gl.uniform1f(decayLoc, decay);
                gl.uniform4f(lineColorLoc, lineColor.R / 255f, lineColor.G / 255f, lineColor.B / 255f, 1f);

                if (zBuffer)
                {
                    gl.enable(GL.DEPTH_TEST);
                }
                else
                {
                    gl.disable(GL.DEPTH_TEST);
                }
                //gl.enable(0x8642);
                gl.disableVertexAttribArray(0);
                gl.disableVertexAttribArray(1);
                gl.disableVertexAttribArray(2);
                gl.disableVertexAttribArray(3);

                gl.enableVertexAttribArray(vertLoc);
                gl.enableVertexAttribArray(colorLoc);
                gl.enableVertexAttribArray(pointSizeLoc);
                gl.enableVertexAttribArray(timeLoc);

                gl.bindBuffer(GL.ARRAY_BUFFER, vertex);
                gl.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, null);
                gl.vertexAttribPointer(vertLoc, 3, GL.FLOAT, false, 40, 0);
                gl.vertexAttribPointer(colorLoc, 4, GL.FLOAT, false, 40, 12);
                gl.vertexAttribPointer(pointSizeLoc, 1, GL.FLOAT, false, 40, 36);
                gl.vertexAttribPointer(timeLoc, 2, GL.FLOAT, false, 40, 28);
                gl.activeTexture(GL.TEXTURE0);
                gl.bindTexture(GL.TEXTURE_2D, texture);
                gl.lineWidth(1.0f);
                gl.blendFunc(GL.SRC_ALPHA, GL.ONE);
            }
        }
    }

    public class TileShader
    {
        public TileShader()
        {

        }

        internal static WebGLShader frag;
        internal static WebGLShader vert;

        public static int vertLoc;
        public static int textureLoc;
        public static WebGLUniformLocation projMatLoc;
        public static WebGLUniformLocation mvMatLoc;
        public static WebGLUniformLocation sampLoc;

        public static bool initialized = false;
        public static void Init(RenderContext renderContext)
        {
            GL gl = renderContext.gl;

            String fragShaderText =
                      " precision mediump float;                                                              \n" +
                      "                                                                                \n" +
                      "   varying vec2 vTextureCoord;                                                         \n" +
                      "                                                                                \n" +
                      "   uniform sampler2D uSampler;                                                         \n" +
                      "                                                                                \n" +
                      "   void main(void) {                                                                   \n" +
                      "   gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t));         \n" +
                      "   }                                                                                \n";

            String vertexShaderText =
                    "     attribute vec3 aVertexPosition;                                              \n" +
                    "     attribute vec2 aTextureCoord;                                                \n" +
                    "                                                                                \n" +
                    "     uniform mat4 uMVMatrix;                                                      \n" +
                    "     uniform mat4 uPMatrix;                                                       \n" +
                    "                                                                                \n" +
                    "     varying vec2 vTextureCoord;                                                  \n" +
                    "                                                                                \n" +
                    "                                                                                \n" +
                    "     void main(void) {                                                            \n" +
                    "         gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);         \n" +
                    "         vTextureCoord = aTextureCoord;                                           \n" +
                    "     }                                                                            \n" +
                    "                                                                                \n";
            frag = gl.createShader(GL.FRAGMENT_SHADER);
            gl.shaderSource(frag, fragShaderText);
            gl.compileShader(frag);

            object stat = gl.getShaderParameter(frag, GL.COMPILE_STATUS);

            vert = gl.createShader(GL.VERTEX_SHADER);
            gl.shaderSource(vert, vertexShaderText);
            gl.compileShader(vert);
            object stat1 = gl.getShaderParameter(vert, GL.COMPILE_STATUS);

            prog = gl.createProgram();

            gl.attachShader(prog, vert);
            gl.attachShader(prog, frag);
            gl.linkProgram(prog);
            object errcode = gl.getProgramParameter(prog, GL.LINK_STATUS);

            gl.useProgram(prog);

            vertLoc = gl.getAttribLocation(prog, "aVertexPosition");
            textureLoc = gl.getAttribLocation(prog, "aTextureCoord");
            projMatLoc = gl.getUniformLocation(prog, "uPMatrix");
            mvMatLoc = gl.getUniformLocation(prog, "uMVMatrix");
            sampLoc = gl.getUniformLocation(prog, "uSampler");

            Tile.uvMultiple = 1;
            Tile.DemEnabled = true;

            gl.enable(GL.BLEND);
            gl.blendFunc(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA);
            initialized = true;
        }

        private static WebGLProgram prog = null;

        public static void Use(RenderContext renderContext, WebGLBuffer vertex, WebGLBuffer index, WebGLTexture texture)
        {
            GL gl = renderContext.gl;
            if (gl != null)
            {
                if (!initialized)
                {
                    Init(renderContext);
                }

                gl.useProgram(prog);

                Matrix3d mvMat = Matrix3d.MultiplyMatrix(renderContext.World, renderContext.View);

                gl.uniformMatrix4fv(mvMatLoc, false, mvMat.FloatArray());
                gl.uniformMatrix4fv(projMatLoc, false, renderContext.Projection.FloatArray());
                gl.uniform1i(sampLoc, 0);
                if (renderContext.Space)
                {
                    gl.disable(GL.DEPTH_TEST);
                }
                else
                {
                    gl.enable(GL.DEPTH_TEST);
                }

                gl.enableVertexAttribArray(vertLoc);
                gl.enableVertexAttribArray(textureLoc);
                gl.bindBuffer(GL.ARRAY_BUFFER, vertex);
                gl.vertexAttribPointer(vertLoc, 3, GL.FLOAT, false, 20, 0);
                gl.vertexAttribPointer(textureLoc, 2, GL.FLOAT, false, 20, 12);
                gl.activeTexture(GL.TEXTURE0);
                gl.bindTexture(GL.TEXTURE_2D, texture);
                gl.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, index);
                gl.blendFunc(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA);
            }
        }
    }

    public class TextShader
    {
        public TextShader()
        {

        }

        internal static WebGLShader frag;
        internal static WebGLShader vert;

        public static int vertLoc;
        public static int textureLoc;
        public static WebGLUniformLocation projMatLoc;
        public static WebGLUniformLocation mvMatLoc;
        public static WebGLUniformLocation sampLoc;

        public static bool initialized = false;
        public static void Init(RenderContext renderContext)
        {
            GL gl = renderContext.gl;

            String fragShaderText =
                      " precision mediump float;                                                              \n" +
                      "                                                                                \n" +
                      "   varying vec2 vTextureCoord;                                                         \n" +
                      "                                                                                \n" +
                      "   uniform sampler2D uSampler;                                                         \n" +
                      "                                                                                \n" +
                      "   void main(void) {                                                                   \n" +
                      "   gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t));         \n" +
                      "   }                                                                                \n";

            String vertexShaderText =
                    "     attribute vec3 aVertexPosition;                                              \n" +
                    "     attribute vec2 aTextureCoord;                                                \n" +
                    "                                                                                \n" +
                    "     uniform mat4 uMVMatrix;                                                      \n" +
                    "     uniform mat4 uPMatrix;                                                       \n" +
                    "                                                                                \n" +
                    "     varying vec2 vTextureCoord;                                                  \n" +
                    "                                                                                \n" +
                    "                                                                                \n" +
                    "     void main(void) {                                                            \n" +
                    "         gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);         \n" +
                    "         vTextureCoord = aTextureCoord;                                           \n" +
                    "     }                                                                            \n" +
                    "                                                                                \n";
            frag = gl.createShader(GL.FRAGMENT_SHADER);
            gl.shaderSource(frag, fragShaderText);
            gl.compileShader(frag);

            object stat = gl.getShaderParameter(frag, GL.COMPILE_STATUS);

            vert = gl.createShader(GL.VERTEX_SHADER);
            gl.shaderSource(vert, vertexShaderText);
            gl.compileShader(vert);
            object stat1 = gl.getShaderParameter(vert, GL.COMPILE_STATUS);

            prog = gl.createProgram();

            gl.attachShader(prog, vert);
            gl.attachShader(prog, frag);
            gl.linkProgram(prog);
            object errcode = gl.getProgramParameter(prog, GL.LINK_STATUS);

            gl.useProgram(prog);

            vertLoc = gl.getAttribLocation(prog, "aVertexPosition");
            textureLoc = gl.getAttribLocation(prog, "aTextureCoord");
            projMatLoc = gl.getUniformLocation(prog, "uPMatrix");
            mvMatLoc = gl.getUniformLocation(prog, "uMVMatrix");
            sampLoc = gl.getUniformLocation(prog, "uSampler");

            Tile.uvMultiple = 1;
            Tile.DemEnabled = true;

            gl.enable(GL.BLEND);
            gl.blendFunc(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA);
            initialized = true;
        }

        private static WebGLProgram prog = null;

        public static void Use(RenderContext renderContext, WebGLBuffer vertex, WebGLTexture texture)
        {
            GL gl = renderContext.gl;
            if (gl != null)
            {
                if (!initialized)
                {
                    Init(renderContext);
                }

                gl.useProgram(prog);

                Matrix3d mvMat = Matrix3d.MultiplyMatrix(renderContext.World, renderContext.View);

                gl.uniformMatrix4fv(mvMatLoc, false, mvMat.FloatArray());
                gl.uniformMatrix4fv(projMatLoc, false, renderContext.Projection.FloatArray());
                gl.uniform1i(sampLoc, 0);
                if (renderContext.Space)
                {
                    gl.disable(GL.DEPTH_TEST);
                }
                else
                {
                    gl.enable(GL.DEPTH_TEST);
                }
                //gl.disableVertexAttribArray(0);
                //gl.disableVertexAttribArray(1);
                //gl.disableVertexAttribArray(2);
                //gl.disableVertexAttribArray(3);

                gl.enableVertexAttribArray(vertLoc);
                gl.enableVertexAttribArray(textureLoc);
                gl.bindBuffer(GL.ARRAY_BUFFER, vertex);
                gl.vertexAttribPointer(vertLoc, 3, GL.FLOAT, false, 20, 0);
                gl.vertexAttribPointer(textureLoc, 2, GL.FLOAT, false, 20, 12);
                gl.activeTexture(GL.TEXTURE0);
                gl.bindTexture(GL.TEXTURE_2D, texture);
                //gl.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, null);
                gl.blendFunc(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA);
            }
        }
    }

}


text:
---
uid: SolidEdgeFrameworkSupport.Boundary2d.Layer
summary:
remarks:
example: [*content]
---
[!code-vb[Main](..\snippets\SolidEdgeFrameworkSupport.Boundary2d.Layer.vb]
[!code-csharp[Main](..\snippets\SolidEdgeFrameworkSupport.Boundary2d.Layer.cs]


text:
package com.github.jjYBdx4IL.utils.gfx;

import static org.junit.Assert.*;

import com.github.jjYBdx4IL.test.GraphicsResource;
import com.github.jjYBdx4IL.utils.env.Maven;
import com.github.jjYBdx4IL.utils.junit4.ImageTesterTest;
import com.github.jjYBdx4IL.utils.junit4.InteractiveTestBase;
import com.github.jjYBdx4IL.utils.klass.ClassReloader;

import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;

import javax.imageio.ImageIO;

// CHECKSTYLE:OFF
/**
 *
 * @author jjYBdx4IL
 */

public class ImageUtilsTest extends InteractiveTestBase implements Runnable {

    private static final Logger LOG = LoggerFactory.getLogger(ImageUtilsTest.class);
    private static final File TEMP_DIR = Maven.getTempTestDir(ImageUtilsTest.class);

    private static BufferedImage createImg1() {
        BufferedImage img = new BufferedImage(3, 3, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = (Graphics2D) img.getGraphics();
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, 3, 3);
        g.setColor(Color.RED);
        g.fillRect(1, 1, 1, 1);
        assertEquals(Color.WHITE, new Color(img.getRGB(0, 0)));
        assertEquals(Color.RED, new Color(img.getRGB(1, 1)));
        assertEquals(Color.WHITE, new Color(img.getRGB(2, 2)));
        return img;
    }

    private static BufferedImage createImg2() {
        BufferedImage img = new BufferedImage(150, 150, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = (Graphics2D) img.getGraphics();
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, 150, 150);
        g.setColor(Color.RED);
        g.fillRect(50, 50, 50, 50);
        return img;
    }

    private static BufferedImage createImg3() {
        BufferedImage img = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = (Graphics2D) img.getGraphics();
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, 100, 100);
        g.setColor(Color.RED);
        g.fillRect(20, 20, 1, 1);
        g.fillRect(30, 40, 1, 1);
        return img;
    }

    @Test
    public void testAutoCrop() throws IOException, InterruptedException, InvocationTargetException {
        openWindow();

        BufferedImage img = ImageIO.read(ImageTesterTest.class.getResourceAsStream("greenish.png"));
        appendImage(img);
        assertEquals(800, img.getWidth());
        assertEquals(20, img.getHeight());
        BufferedImage img2 = new BufferedImage(img.getWidth(), img.getHeight(), img.getType());
        img = ImageUtils.autoCrop(img);
        Graphics2D g = (Graphics2D) img2.getGraphics();
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, img2.getWidth(), img2.getHeight());
        g.drawImage(img, (img2.getWidth() - img.getWidth()) / 2, (img2.getHeight() - img.getHeight()) / 2, null);
        appendImage(img2);
        assertEquals(424, img.getWidth());
        assertEquals(11, img.getHeight());

        saveWindowAsImage("testAutoCrop");
        waitForWindowClosing();
    }

    @Test
    public void testAutoCrop2() {
        BufferedImage img = ImageUtils.autoCrop(createImg1());
        assertEquals(1, img.getWidth());
        assertEquals(1, img.getHeight());
        assertEquals(Color.RED, new Color(img.getRGB(0, 0)));
    }

    @Test
    public void testAutoCrop2Border() throws InterruptedException, InvocationTargetException {
        BufferedImage img;

        img = ImageUtils.autoCrop(createImg1(), 1, 0, 0, 0);
        assertEquals(2, img.getWidth());
        assertEquals(1, img.getHeight());
        assertEquals(Color.WHITE, new Color(img.getRGB(0, 0)));
        assertEquals(Color.RED, new Color(img.getRGB(1, 0)));

        img = ImageUtils.autoCrop(createImg1(), 0, 1, 0, 0);
        assertEquals(2, img.getWidth());
        assertEquals(1, img.getHeight());
        assertEquals(Color.RED, new Color(img.getRGB(0, 0)));
        assertEquals(Color.WHITE, new Color(img.getRGB(1, 0)));

        img = ImageUtils.autoCrop(createImg1(), 0, 0, 1, 0);
        assertEquals(1, img.getWidth());
        assertEquals(2, img.getHeight());
        assertEquals(Color.WHITE, new Color(img.getRGB(0, 0)));
        assertEquals(Color.RED, new Color(img.getRGB(0, 1)));

        img = ImageUtils.autoCrop(createImg1(), 0, 0, 0, 1);
        assertEquals(1, img.getWidth());
        assertEquals(2, img.getHeight());
        assertEquals(Color.RED, new Color(img.getRGB(0, 0)));
        assertEquals(Color.WHITE, new Color(img.getRGB(0, 1)));

        img = ImageUtils.autoCrop(createImg2(), 50, 150, 100, 200);

        openWindow();
        appendImage(img);
        saveWindowAsImage("testAutoCrop2Border");
        waitForWindowClosing();
    }

    @Test
    public void testAutoCrop3() {
        BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = (Graphics2D) img.getGraphics();
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, 1, 1);

        try {
            img = ImageUtils.autoCrop(img);
            fail();
        } catch (IllegalArgumentException ex) {
        }
    }

    @Test
    public void testAutoCrop4() {
        BufferedImage img = new BufferedImage(3, 3, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = (Graphics2D) img.getGraphics();
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, 3, 3);

        try {
            img = ImageUtils.autoCrop(img);
            fail();
        } catch (IllegalArgumentException ex) {
        }
    }

    @Test
    public void testDeepCopy() throws IOException {
        BufferedImage img = new BufferedImage(10, 10, BufferedImage.TYPE_BYTE_GRAY);
        BufferedImage img2 = ImageUtils.deepCopy(img);

        assertTrue(img.getColorModel().equals(img2.getColorModel()));
        assertEquals(img.isAlphaPremultiplied(), img2.isAlphaPremultiplied());
        assertEquals(img.getWidth(), img2.getWidth());
        assertEquals(img.getHeight(), img2.getHeight());
        for (int y = 0; y < img.getHeight(); y++) {
            for (int x = 0; x < img.getWidth(); x++) {
                assertEquals(img.getRGB(x, y), img2.getRGB(x, y));
            }
        }
        img.getRaster().setPixel(1, 1, new int[]{120});
        assertNotEquals(img.getRGB(1, 1), img2.getRGB(1, 1));

        // ImageIO.write sometimes fails silenty and creates no file if something is not right,
        // so we use that as an additional validation
        File jpg = new File(TEMP_DIR, "testDeepCopy.jpg");
        ImageIO.write(img2, "jpg", jpg);
        assertTrue(jpg.exists());
        assertTrue(jpg.length() > 0);
    }

    @SuppressWarnings("unused")
	@Test
    public void testDeepCopySubImage() {
        BufferedImage img = new BufferedImage(10, 10, BufferedImage.TYPE_BYTE_GRAY);
        BufferedImage img2 = ImageUtils.deepCopy(img.getSubimage(2, 2, 5, 6));
    }

    @Test
    public void testDeducePaletteSimple() {
        BufferedImage img = new BufferedImage(3, 1, BufferedImage.TYPE_INT_ARGB);
        img.setRGB(0, 0, Color.BLUE.getRGB());
        img.setRGB(1, 0, Color.CYAN.getRGB());
        img.setRGB(2, 0, Color.CYAN.getRGB());
        int[] pal = ImageUtils.deducePalette(img, 2);
        assertEquals(2, pal.length);
        Arrays.sort(pal);
        assertEquals(Color.BLUE.getRGB(), pal[0]);
        assertEquals(Color.CYAN.getRGB(), pal[1]);
    }

    @Ignore // out of memery problems
    @SuppressWarnings("unused")
	@Test
    public void testDeducePalettePerformance() {
        BufferedImage img = GraphicsResource.OPENIMAJ_TESTRES_AESTHETICODE.loadImage().getSubimage(0, 0, 200, 200);
        long start = System.currentTimeMillis();
        int[] pal = ImageUtils.deducePalette(img, 32);
        long duration = System.currentTimeMillis() - start;
        LOG.info(String.format("deducePalette performance: %dkpix/sec", img.getWidth() * img.getHeight() / duration));
    }

    @Test
    public void testFindClosest() {
        int[] pal = new int[]{0, 1, 10};
        assertEquals(0, ImageUtils.findClosest(pal, 0));
        assertEquals(1, ImageUtils.findClosest(pal, 1));
        assertEquals(1, ImageUtils.findClosest(pal, 5));
        assertEquals(10, ImageUtils.findClosest(pal, 6));
        assertEquals(10, ImageUtils.findClosest(pal, 255));

        assertEquals(0, ImageUtils.findClosest(pal, 0 + 0xFFFF00));
        assertEquals(1, ImageUtils.findClosest(pal, 1 + 0xFFFF00));
        assertEquals(1, ImageUtils.findClosest(pal, 5 + 0xFF0000));
        assertEquals(10, ImageUtils.findClosest(pal, 6 + 0xFFFF00));
        assertEquals(10, ImageUtils.findClosest(pal, 255 + 0x00FF00));
    }

    @Test
    public void testFindClosestBinary() {
        int[] pal = new int[]{0, 1, 10};
        assertEquals(0, ImageUtils.findClosestBinary(pal, 0));
        assertEquals(1, ImageUtils.findClosestBinary(pal, 1));
        assertEquals(1, ImageUtils.findClosestBinary(pal, 5));
        assertEquals(10, ImageUtils.findClosestBinary(pal, 6));
        assertEquals(10, ImageUtils.findClosestBinary(pal, 255));

        assertEquals(0, ImageUtils.findClosestBinary(pal, 0 + 0xFFFF00));
        assertEquals(1, ImageUtils.findClosestBinary(pal, 1 + 0xFFFF00));
        assertEquals(1, ImageUtils.findClosestBinary(pal, 5 + 0xFF0000));
        assertEquals(10, ImageUtils.findClosestBinary(pal, 6 + 0xFFFF00));
        assertEquals(10, ImageUtils.findClosestBinary(pal, 255 + 0x00FF00));
    }

    public static void main(String[] args) throws InterruptedException, IOException {
        LOG.info("started");
        Thread t = ClassReloader.watchLoadAndRun("target/test-classes", ImageUtilsTest.class.getName());
        t.join();
    }

    @Override
    public void run() {
        LOG.info("running");
        try {
            testFindClosest();
        } catch (Throwable ex) {
            LOG.error("", ex);
        }
    }

    @Test
    public void testScale() {
        BufferedImage image = new BufferedImage(20, 20, BufferedImage.TYPE_3BYTE_BGR);
        Graphics2D g = image.createGraphics();
        g.setColor(Color.red);
        g.fillRect(0, 0, image.getWidth(), image.getHeight());

        BufferedImage result = ImageUtils.scale(image, 2, 5);

        assertEquals(2, result.getWidth());
        assertEquals(5, result.getHeight());
        assertEquals(BufferedImage.TYPE_3BYTE_BGR, result.getType());

        for (int x = 0; x < result.getWidth(); x++) {
            for (int y = 0; y < result.getHeight(); y++) {
                assertEquals(Color.red, new Color(result.getRGB(x, y)));
            }
        }
    }

    @Test
    public void testScale3() throws IOException {
        BufferedImage img = createImg3();
        File f = new File(TEMP_DIR, "testScale3_1.png");
        assertTrue(ImageIO.write(img, "png", f));

        File f2 = new File(TEMP_DIR, "testScale3_2.png");
        ImageUtils.scale(f.toPath(), f2.toPath(), 30, 30);
    }

    @Test
    public void testGetBoundingBox() throws Exception {
        BufferedImage img = createImg3();
        Rectangle r = ImageUtils.getBoundingBox(img);
        assertEquals(new Rectangle(20, 20, 11, 21), r);
    }
}


text:
package com.intuit.wasabi.assignment.impl;

import com.intuit.wasabi.assignmentobjects.AssignmentEnvelopePayload;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class NoopDatabaseAssignmentEnvelopeTest {

    private NoopDatabaseAssignmentEnvelope envelope;

    @Before
    public void setUp() throws Exception {
        envelope = new NoopDatabaseAssignmentEnvelope();
    }

    @Test
    public void test() {
        assertEquals(envelope, envelope.withPayload(new AssignmentEnvelopePayload()));
        envelope.run();
    }

}


text:
using System.Collections.Generic;
using Org.Apache.REEF.Tang.Interface;

namespace Org.Apache.REEF.IMRU.API
{
    /// <summary>
    /// Describes an IMRU Job.
    /// </summary>
    /// <seealso cref="IMRUJobDefinitionBuilder" />
    public sealed class IMRUJobDefinition
    {
        private readonly string _jobName;
        private readonly IConfiguration _mapFunctionConfiguration;
        private readonly IConfiguration _mapInputCodecConfiguration;
        private readonly IConfiguration _updateFunctionCodecsConfiguration;
        private readonly IConfiguration _reduceFunctionConfiguration;
        private readonly IConfiguration _updateFunctionConfiguration;
        private readonly IConfiguration _mapOutputPipelineDataConverterConfiguration;
        private readonly IConfiguration _mapInputPipelineDataConverterConfiguration;
        private readonly IConfiguration _partitionedDatasetConfiguration;
        private readonly int _numberOfMappers;
        private readonly int _memoryPerMapper;
        private readonly int _updateTaskMemory;
        private readonly int _mapTaskCores;
        private readonly int _updateTaskCores;
        private readonly ISet<IConfiguration> _perMapConfigGeneratorConfig;
        private readonly bool _invokeGC;

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="mapFunctionConfiguration">Map function configuration</param>
        /// <param name="mapInputCodecConfiguration">Map input codec configuration</param>
        /// <param name="updateFunctionCodecsConfiguration">codec configuration for update
        /// function. It is union of TMapInput, TMapOutput and TResult configuration</param>
        /// <param name="reduceFunctionConfiguration">Reduce function configuration</param>
        /// <param name="updateFunctionConfiguration">Update function configuration</param>
        /// <param name="mapOutputPipelineDataConverterConfiguration">Configuration of
        /// PipelineDataConverter for TMapOutput</param>
        /// <param name="mapInputPipelineDataConverterConfiguration">Configuration of
        /// PipelineDataConverter for TMapInput</param>
        /// <param name="partitionedDatasetConfiguration">Configuration of partitioned
        /// dataset</param>
        /// <param name="perMapConfigGeneratorConfig">Per mapper configuration</param>
        /// <param name="numberOfMappers">Number of mappers</param>
        /// <param name="memoryPerMapper">Per Mapper memory.</param>
        /// <param name="updateTaskMemory">Update task memory</param>
        /// <param name="mapTaskCores">Number of map task cores</param>
        /// <param name="updateTaskCores">Number of update task cores</param>
        /// <param name="jobName">Job name</param>
        /// <param name="invokeGC">Whether to call garbage collector after each iteration</param>
        internal IMRUJobDefinition(
            IConfiguration mapFunctionConfiguration,
            IConfiguration mapInputCodecConfiguration,
            IConfiguration updateFunctionCodecsConfiguration,
            IConfiguration reduceFunctionConfiguration,
            IConfiguration updateFunctionConfiguration,
            IConfiguration mapOutputPipelineDataConverterConfiguration,
            IConfiguration mapInputPipelineDataConverterConfiguration,
            IConfiguration partitionedDatasetConfiguration,
            ISet<IConfiguration> perMapConfigGeneratorConfig,
            int numberOfMappers,
            int memoryPerMapper,
            int updateTaskMemory,
            int mapTaskCores,
            int updateTaskCores,
            string jobName,
            bool invokeGC)
        {
            _mapFunctionConfiguration = mapFunctionConfiguration;
            _mapInputCodecConfiguration = mapInputCodecConfiguration;
            _updateFunctionCodecsConfiguration = updateFunctionCodecsConfiguration;
            _reduceFunctionConfiguration = reduceFunctionConfiguration;
            _updateFunctionConfiguration = updateFunctionConfiguration;
            _mapOutputPipelineDataConverterConfiguration = mapOutputPipelineDataConverterConfiguration;
            _mapInputPipelineDataConverterConfiguration = mapInputPipelineDataConverterConfiguration;
            _partitionedDatasetConfiguration = partitionedDatasetConfiguration;
            _numberOfMappers = numberOfMappers;
            _jobName = jobName;
            _memoryPerMapper = memoryPerMapper;
            _updateTaskMemory = updateTaskMemory;
            _mapTaskCores = mapTaskCores;
            _updateTaskCores = updateTaskCores;
            _perMapConfigGeneratorConfig = perMapConfigGeneratorConfig;
            _invokeGC = invokeGC;
        }

        /// <summary>
        /// Name of the job
        /// </summary>
        internal string JobName
        {
            get { return _jobName; }
        }

        /// <summary>
        /// Configuration of map function
        /// </summary>
        internal IConfiguration MapFunctionConfiguration
        {
            get { return _mapFunctionConfiguration; }
        }

        /// <summary>
        /// Configuration of codec for TMapInput
        /// </summary>
        internal IConfiguration MapInputCodecConfiguration
        {
            get { return _mapInputCodecConfiguration; }
        }

        /// <summary>
        /// Configuration of codecs needed by Update function
        /// </summary>
        internal IConfiguration UpdateFunctionCodecsConfiguration
        {
            get { return _updateFunctionCodecsConfiguration; }
        }

        /// <summary>
        /// Configuration of reduce function
        /// </summary>
        internal IConfiguration ReduceFunctionConfiguration
        {
            get { return _reduceFunctionConfiguration; }
        }

        /// <summary>
        /// Configuration of update function
        /// </summary>
        internal IConfiguration UpdateFunctionConfiguration
        {
            get { return _updateFunctionConfiguration; }
        }

        /// <summary>
        /// Configuration of PipelineDataConverter for Map outout
        /// </summary>
        internal IConfiguration MapOutputPipelineDataConverterConfiguration
        {
            get { return _mapOutputPipelineDataConverterConfiguration; }
        }

        /// <summary>
        /// Configuration of PipelineDataConverter for Map Input
        /// </summary>
        internal IConfiguration MapInputPipelineDataConverterConfiguration
        {
            get { return _mapInputPipelineDataConverterConfiguration; }
        }

        /// <summary>
        /// Configuration of partitioned dataset
        /// </summary>
        internal IConfiguration PartitionedDatasetConfiguration
        {
            get { return _partitionedDatasetConfiguration; }
        }

        /// <summary>
        /// Number of mappers
        /// </summary>
        /// TODO: This is duplicate in a sense that it can be determined
        /// TODO: automatically from IPartitionedDataset. However, right now
        /// TODO: GroupComm. instantiated in IMRUDriver needs this parameter
        /// TODO: in constructor. This will be removed once we remove it from GroupComm.
        internal int NumberOfMappers {
            get { return _numberOfMappers; }
        }

        /// <summary>
        /// Memory for each mapper in MB
        /// </summary>
        internal int MapperMemory
        {
            get { return _memoryPerMapper; }
        }

        /// <summary>
        /// Memory for update task in MB
        /// </summary>
        internal int UpdateTaskMemory
        {
            get { return _updateTaskMemory; }
        }

        /// <summary>
        /// Cores for each mapper
        /// </summary>
        internal int MapTaskCores
        {
            get { return _mapTaskCores; }
        }

        /// <summary>
        /// Cores for update task
        /// </summary>
        internal int UpdateTaskCores
        {
            get { return _updateTaskCores; }
        }

        /// <summary>
        /// Per mapper configuration
        /// </summary>
        internal ISet<IConfiguration> PerMapConfigGeneratorConfig
        {
            get { return _perMapConfigGeneratorConfig; }
        }

        /// <summary>
        /// Whether to call Garbage Collector after each iteration
        /// </summary>
        internal bool InvokeGarbageCollectorAfterIteration
        {
            get { return _invokeGC; }
        }
    }
}