text:
#ifndef __KERNEL__
#include "jfs_user.h"
#else
#include <linux/time.h>
#include <linux/fs.h>
#include <linux/jbd.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/list.h>
#include <linux/smp_lock.h>
#include <linux/init.h>
#endif

static kmem_cache_t *revoke_record_cache;
static kmem_cache_t *revoke_table_cache;

/* Each revoke record represents one single revoked block.  During
   journal replay, this involves recording the transaction ID of the
   last transaction to revoke this block. */

struct jbd_revoke_record_s
{
	struct list_head  hash;
	tid_t		  sequence;	/* Used for recovery only */
	unsigned long	  blocknr;
};

/* The revoke table is just a simple hash table of revoke records. */
struct jbd_revoke_table_s
{
	/* It is conceivable that we might want a larger hash table
	 * for recovery.  Must be a power of two. */
	int		  hash_size;
	int		  hash_shift;
	struct list_head *hash_table;
};

#ifdef __KERNEL__
static void write_one_revoke_record(journal_t *, transaction_t *,
				    struct journal_head **, int *,
				    struct jbd_revoke_record_s *);
static void flush_descriptor(journal_t *, struct journal_head *, int);
#endif

/* Utility functions to maintain the revoke table */

/* Borrowed from buffer.c: this is a tried and tested block hash function */
static inline int hash(journal_t *journal, unsigned long block)
{
	struct jbd_revoke_table_s *table = journal->j_revoke;
	int hash_shift = table->hash_shift;

	return ((block << (hash_shift - 6)) ^
		(block >> 13) ^
		(block << (hash_shift - 12))) & (table->hash_size - 1);
}

static int insert_revoke_hash(journal_t *journal, unsigned long blocknr,
			      tid_t seq)
{
	struct list_head *hash_list;
	struct jbd_revoke_record_s *record;

repeat:
	record = kmem_cache_alloc(revoke_record_cache, GFP_NOFS);
	if (!record)
		goto oom;

	record->sequence = seq;
	record->blocknr = blocknr;
	hash_list = &journal->j_revoke->hash_table[hash(journal, blocknr)];
	spin_lock(&journal->j_revoke_lock);
	list_add(&record->hash, hash_list);
	spin_unlock(&journal->j_revoke_lock);
	return 0;

oom:
	if (!journal_oom_retry)
		return -ENOMEM;
	jbd_debug(1, "ENOMEM in %s, retrying\n", __FUNCTION__);
	yield();
	goto repeat;
}

/* Find a revoke record in the journal's hash table. */

static struct jbd_revoke_record_s *find_revoke_record(journal_t *journal,
						      unsigned long blocknr)
{
	struct list_head *hash_list;
	struct jbd_revoke_record_s *record;

	hash_list = &journal->j_revoke->hash_table[hash(journal, blocknr)];

	spin_lock(&journal->j_revoke_lock);
	record = (struct jbd_revoke_record_s *) hash_list->next;
	while (&(record->hash) != hash_list) {
		if (record->blocknr == blocknr) {
			spin_unlock(&journal->j_revoke_lock);
			return record;
		}
		record = (struct jbd_revoke_record_s *) record->hash.next;
	}
	spin_unlock(&journal->j_revoke_lock);
	return NULL;
}

int __init journal_init_revoke_caches(void)
{
	revoke_record_cache = kmem_cache_create("revoke_record",
					   sizeof(struct jbd_revoke_record_s),
					   0, SLAB_HWCACHE_ALIGN, NULL, NULL);
	if (revoke_record_cache == 0)
		return -ENOMEM;

	revoke_table_cache = kmem_cache_create("revoke_table",
					   sizeof(struct jbd_revoke_table_s),
					   0, 0, NULL, NULL);
	if (revoke_table_cache == 0) {
		kmem_cache_destroy(revoke_record_cache);
		revoke_record_cache = NULL;
		return -ENOMEM;
	}
	return 0;
}

void journal_destroy_revoke_caches(void)
{
	kmem_cache_destroy(revoke_record_cache);
	revoke_record_cache = NULL;
	kmem_cache_destroy(revoke_table_cache);
	revoke_table_cache = NULL;
}

/* Initialise the revoke table for a given journal to a given size. */

int journal_init_revoke(journal_t *journal, int hash_size)
{
	int shift, tmp;

	J_ASSERT (journal->j_revoke_table[0] == NULL);

	shift = 0;
	tmp = hash_size;
	while((tmp >>= 1UL) != 0UL)
		shift++;

	journal->j_revoke_table[0] = kmem_cache_alloc(revoke_table_cache, GFP_KERNEL);
	if (!journal->j_revoke_table[0])
		return -ENOMEM;
	journal->j_revoke = journal->j_revoke_table[0];

	/* Check that the hash_size is a power of two */
	J_ASSERT ((hash_size & (hash_size-1)) == 0);

	journal->j_revoke->hash_size = hash_size;

	journal->j_revoke->hash_shift = shift;

	journal->j_revoke->hash_table =
		kmalloc(hash_size * sizeof(struct list_head), GFP_KERNEL);
	if (!journal->j_revoke->hash_table) {
		kmem_cache_free(revoke_table_cache, journal->j_revoke_table[0]);
		journal->j_revoke = NULL;
		return -ENOMEM;
	}

	for (tmp = 0; tmp < hash_size; tmp++)
		INIT_LIST_HEAD(&journal->j_revoke->hash_table[tmp]);

	journal->j_revoke_table[1] = kmem_cache_alloc(revoke_table_cache, GFP_KERNEL);
	if (!journal->j_revoke_table[1]) {
		kfree(journal->j_revoke_table[0]->hash_table);
		kmem_cache_free(revoke_table_cache, journal->j_revoke_table[0]);
		return -ENOMEM;
	}

	journal->j_revoke = journal->j_revoke_table[1];

	/* Check that the hash_size is a power of two */
	J_ASSERT ((hash_size & (hash_size-1)) == 0);

	journal->j_revoke->hash_size = hash_size;

	journal->j_revoke->hash_shift = shift;

	journal->j_revoke->hash_table =
		kmalloc(hash_size * sizeof(struct list_head), GFP_KERNEL);
	if (!journal->j_revoke->hash_table) {
		kfree(journal->j_revoke_table[0]->hash_table);
		kmem_cache_free(revoke_table_cache, journal->j_revoke_table[0]);
		kmem_cache_free(revoke_table_cache, journal->j_revoke_table[1]);
		journal->j_revoke = NULL;
		return -ENOMEM;
	}

	for (tmp = 0; tmp < hash_size; tmp++)
		INIT_LIST_HEAD(&journal->j_revoke->hash_table[tmp]);

	spin_lock_init(&journal->j_revoke_lock);

	return 0;
}

/* Destoy a journal's revoke table.  The table must already be empty! */

void journal_destroy_revoke(journal_t *journal)
{
	struct jbd_revoke_table_s *table;
	struct list_head *hash_list;
	int i;

	table = journal->j_revoke_table[0];
	if (!table)
		return;

	for (i=0; i<table->hash_size; i++) {
		hash_list = &table->hash_table[i];
		J_ASSERT (list_empty(hash_list));
	}

	kfree(table->hash_table);
	kmem_cache_free(revoke_table_cache, table);
	journal->j_revoke = NULL;

	table = journal->j_revoke_table[1];
	if (!table)
		return;

	for (i=0; i<table->hash_size; i++) {
		hash_list = &table->hash_table[i];
		J_ASSERT (list_empty(hash_list));
	}

	kfree(table->hash_table);
	kmem_cache_free(revoke_table_cache, table);
	journal->j_revoke = NULL;
}

#ifdef __KERNEL__

/*
 * journal_revoke: revoke a given buffer_head from the journal.  This
 * prevents the block from being replayed during recovery if we take a
 * crash after this current transaction commits.  Any subsequent
 * metadata writes of the buffer in this transaction cancel the
 * revoke.
 *
 * Note that this call may block --- it is up to the caller to make
 * sure that there are no further calls to journal_write_metadata
 * before the revoke is complete.  In ext3, this implies calling the
 * revoke before clearing the block bitmap when we are deleting
 * metadata.
 *
 * Revoke performs a journal_forget on any buffer_head passed in as a
 * parameter, but does _not_ forget the buffer_head if the bh was only
 * found implicitly.
 *
 * bh_in may not be a journalled buffer - it may have come off
 * the hash tables without an attached journal_head.
 *
 * If bh_in is non-zero, journal_revoke() will decrement its b_count
 * by one.
 */

int journal_revoke(handle_t *handle, unsigned long blocknr,
		   struct buffer_head *bh_in)
{
	struct buffer_head *bh = NULL;
	journal_t *journal;
	struct block_device *bdev;
	int err;

	might_sleep();
	if (bh_in)
		BUFFER_TRACE(bh_in, "enter");

	journal = handle->h_transaction->t_journal;
	if (!journal_set_features(journal, 0, 0, JFS_FEATURE_INCOMPAT_REVOKE)){
		J_ASSERT (!"Cannot set revoke feature!");
		return -EINVAL;
	}

	bdev = journal->j_fs_dev;
	bh = bh_in;

	if (!bh) {
		bh = __find_get_block(bdev, blocknr, journal->j_blocksize);
		if (bh)
			BUFFER_TRACE(bh, "found on hash");
	}
#ifdef JBD_EXPENSIVE_CHECKING
	else {
		struct buffer_head *bh2;

		/* If there is a different buffer_head lying around in
		 * memory anywhere... */
		bh2 = __find_get_block(bdev, blocknr, journal->j_blocksize);
		if (bh2) {
			/* ... and it has RevokeValid status... */
			if (bh2 != bh && buffer_revokevalid(bh2))
				/* ...then it better be revoked too,
				 * since it's illegal to create a revoke
				 * record against a buffer_head which is
				 * not marked revoked --- that would
				 * risk missing a subsequent revoke
				 * cancel. */
				J_ASSERT_BH(bh2, buffer_revoked(bh2));
			put_bh(bh2);
		}
	}
#endif

	/* We really ought not ever to revoke twice in a row without
           first having the revoke cancelled: it's illegal to free a
           block twice without allocating it in between! */
	if (bh) {
		if (!J_EXPECT_BH(bh, !buffer_revoked(bh),
				 "inconsistent data on disk")) {
			if (!bh_in)
				brelse(bh);
			return -EIO;
		}
		set_buffer_revoked(bh);
		set_buffer_revokevalid(bh);
		if (bh_in) {
			BUFFER_TRACE(bh_in, "call journal_forget");
			journal_forget(handle, bh_in);
		} else {
			BUFFER_TRACE(bh, "call brelse");
			__brelse(bh);
		}
	}

	jbd_debug(2, "insert revoke for block %lu, bh_in=%p\n", blocknr, bh_in);
	err = insert_revoke_hash(journal, blocknr,
				handle->h_transaction->t_tid);
	BUFFER_TRACE(bh_in, "exit");
	return err;
}

/*
 * Cancel an outstanding revoke.  For use only internally by the
 * journaling code (called from journal_get_write_access).
 *
 * We trust buffer_revoked() on the buffer if the buffer is already
 * being journaled: if there is no revoke pending on the buffer, then we
 * don't do anything here.
 *
 * This would break if it were possible for a buffer to be revoked and
 * discarded, and then reallocated within the same transaction.  In such
 * a case we would have lost the revoked bit, but when we arrived here
 * the second time we would still have a pending revoke to cancel.  So,
 * do not trust the Revoked bit on buffers unless RevokeValid is also
 * set.
 *
 * The caller must have the journal locked.
 */
int journal_cancel_revoke(handle_t *handle, struct journal_head *jh)
{
	struct jbd_revoke_record_s *record;
	journal_t *journal = handle->h_transaction->t_journal;
	int need_cancel;
	int did_revoke = 0;	/* akpm: debug */
	struct buffer_head *bh = jh2bh(jh);

	jbd_debug(4, "journal_head %p, cancelling revoke\n", jh);

	/* Is the existing Revoke bit valid?  If so, we trust it, and
	 * only perform the full cancel if the revoke bit is set.  If
	 * not, we can't trust the revoke bit, and we need to do the
	 * full search for a revoke record. */
	if (test_set_buffer_revokevalid(bh)) {
		need_cancel = test_clear_buffer_revoked(bh);
	} else {
		need_cancel = 1;
		clear_buffer_revoked(bh);
	}

	if (need_cancel) {
		record = find_revoke_record(journal, bh->b_blocknr);
		if (record) {
			jbd_debug(4, "cancelled existing revoke on "
				  "blocknr %llu\n", (unsigned long long)bh->b_blocknr);
			spin_lock(&journal->j_revoke_lock);
			list_del(&record->hash);
			spin_unlock(&journal->j_revoke_lock);
			kmem_cache_free(revoke_record_cache, record);
			did_revoke = 1;
		}
	}

#ifdef JBD_EXPENSIVE_CHECKING
	/* There better not be one left behind by now! */
	record = find_revoke_record(journal, bh->b_blocknr);
	J_ASSERT_JH(jh, record == NULL);
#endif

	/* Finally, have we just cleared revoke on an unhashed
	 * buffer_head?  If so, we'd better make sure we clear the
	 * revoked status on any hashed alias too, otherwise the revoke
	 * state machine will get very upset later on. */
	if (need_cancel) {
		struct buffer_head *bh2;
		bh2 = __find_get_block(bh->b_bdev, bh->b_blocknr, bh->b_size);
		if (bh2) {
			if (bh2 != bh)
				clear_buffer_revoked(bh2);
			__brelse(bh2);
		}
	}
	return did_revoke;
}

/* journal_switch_revoke table select j_revoke for next transaction
 * we do not want to suspend any processing until all revokes are
 * written -bzzz
 */
void journal_switch_revoke_table(journal_t *journal)
{
	int i;

	if (journal->j_revoke == journal->j_revoke_table[0])
		journal->j_revoke = journal->j_revoke_table[1];
	else
		journal->j_revoke = journal->j_revoke_table[0];

	for (i = 0; i < journal->j_revoke->hash_size; i++)
		INIT_LIST_HEAD(&journal->j_revoke->hash_table[i]);
}

/*
 * Write revoke records to the journal for all entries in the current
 * revoke hash, deleting the entries as we go.
 *
 * Called with the journal lock held.
 */

void journal_write_revoke_records(journal_t *journal,
				  transaction_t *transaction)
{
	struct journal_head *descriptor;
	struct jbd_revoke_record_s *record;
	struct jbd_revoke_table_s *revoke;
	struct list_head *hash_list;
	int i, offset, count;

	descriptor = NULL;
	offset = 0;
	count = 0;

	/* select revoke table for committing transaction */
	revoke = journal->j_revoke == journal->j_revoke_table[0] ?
		journal->j_revoke_table[1] : journal->j_revoke_table[0];

	for (i = 0; i < revoke->hash_size; i++) {
		hash_list = &revoke->hash_table[i];

		while (!list_empty(hash_list)) {
			record = (struct jbd_revoke_record_s *)
				hash_list->next;
			write_one_revoke_record(journal, transaction,
						&descriptor, &offset,
						record);
			count++;
			list_del(&record->hash);
			kmem_cache_free(revoke_record_cache, record);
		}
	}
	if (descriptor)
		flush_descriptor(journal, descriptor, offset);
	jbd_debug(1, "Wrote %d revoke records\n", count);
}

/*
 * Write out one revoke record.  We need to create a new descriptor
 * block if the old one is full or if we have not already created one.
 */

static void write_one_revoke_record(journal_t *journal,
				    transaction_t *transaction,
				    struct journal_head **descriptorp,
				    int *offsetp,
				    struct jbd_revoke_record_s *record)
{
	struct journal_head *descriptor;
	int offset;
	journal_header_t *header;

	/* If we are already aborting, this all becomes a noop.  We
           still need to go round the loop in
           journal_write_revoke_records in order to free all of the
           revoke records: only the IO to the journal is omitted. */
	if (is_journal_aborted(journal))
		return;

	descriptor = *descriptorp;
	offset = *offsetp;

	/* Make sure we have a descriptor with space left for the record */
	if (descriptor) {
		if (offset == journal->j_blocksize) {
			flush_descriptor(journal, descriptor, offset);
			descriptor = NULL;
		}
	}

	if (!descriptor) {
		descriptor = journal_get_descriptor_buffer(journal);
		if (!descriptor)
			return;
		header = (journal_header_t *) &jh2bh(descriptor)->b_data[0];
		header->h_magic     = cpu_to_be32(JFS_MAGIC_NUMBER);
		header->h_blocktype = cpu_to_be32(JFS_REVOKE_BLOCK);
		header->h_sequence  = cpu_to_be32(transaction->t_tid);

		/* Record it so that we can wait for IO completion later */
		JBUFFER_TRACE(descriptor, "file as BJ_LogCtl");
		journal_file_buffer(descriptor, transaction, BJ_LogCtl);

		offset = sizeof(journal_revoke_header_t);
		*descriptorp = descriptor;
	}

	* ((__be32 *)(&jh2bh(descriptor)->b_data[offset])) =
		cpu_to_be32(record->blocknr);
	offset += 4;
	*offsetp = offset;
}

/*
 * Flush a revoke descriptor out to the journal.  If we are aborting,
 * this is a noop; otherwise we are generating a buffer which needs to
 * be waited for during commit, so it has to go onto the appropriate
 * journal buffer list.
 */

static void flush_descriptor(journal_t *journal,
			     struct journal_head *descriptor,
			     int offset)
{
	journal_revoke_header_t *header;
	struct buffer_head *bh = jh2bh(descriptor);

	if (is_journal_aborted(journal)) {
		put_bh(bh);
		return;
	}

	header = (journal_revoke_header_t *) jh2bh(descriptor)->b_data;
	header->r_count = cpu_to_be32(offset);
	set_buffer_jwrite(bh);
	BUFFER_TRACE(bh, "write");
	set_buffer_dirty(bh);
	ll_rw_block(SWRITE, 1, &bh);
}
#endif

/*
 * Revoke support for recovery.
 *
 * Recovery needs to be able to:
 *
 *  record all revoke records, including the tid of the latest instance
 *  of each revoke in the journal
 *
 *  check whether a given block in a given transaction should be replayed
 *  (ie. has not been revoked by a revoke record in that or a subsequent
 *  transaction)
 *
 *  empty the revoke table after recovery.
 */

/*
 * First, setting revoke records.  We create a new revoke record for
 * every block ever revoked in the log as we scan it for recovery, and
 * we update the existing records if we find multiple revokes for a
 * single block.
 */

int journal_set_revoke(journal_t *journal,
		       unsigned long blocknr,
		       tid_t sequence)
{
	struct jbd_revoke_record_s *record;

	record = find_revoke_record(journal, blocknr);
	if (record) {
		/* If we have multiple occurrences, only record the
		 * latest sequence number in the hashed record */
		if (tid_gt(sequence, record->sequence))
			record->sequence = sequence;
		return 0;
	}
	return insert_revoke_hash(journal, blocknr, sequence);
}

/*
 * Test revoke records.  For a given block referenced in the log, has
 * that block been revoked?  A revoke record with a given transaction
 * sequence number revokes all blocks in that transaction and earlier
 * ones, but later transactions still need replayed.
 */

int journal_test_revoke(journal_t *journal,
			unsigned long blocknr,
			tid_t sequence)
{
	struct jbd_revoke_record_s *record;

	record = find_revoke_record(journal, blocknr);
	if (!record)
		return 0;
	if (tid_gt(sequence, record->sequence))
		return 0;
	return 1;
}

/*
 * Finally, once recovery is over, we need to clear the revoke table so
 * that it can be reused by the running filesystem.
 */

void journal_clear_revoke(journal_t *journal)
{
	int i;
	struct list_head *hash_list;
	struct jbd_revoke_record_s *record;
	struct jbd_revoke_table_s *revoke;

	revoke = journal->j_revoke;

	for (i = 0; i < revoke->hash_size; i++) {
		hash_list = &revoke->hash_table[i];
		while (!list_empty(hash_list)) {
			record = (struct jbd_revoke_record_s*) hash_list->next;
			list_del(&record->hash);
			kmem_cache_free(revoke_record_cache, record);
		}
	}
}


text:
package com.glooory.flatreader.entity.ithome;

import org.simpleframework.xml.Element;
import org.simpleframework.xml.Path;
import org.simpleframework.xml.Root;

/**
 * Created by Glooory on 2016/10/13 0013 10:11.
 */

@Root(name = "rss", strict = false)
public class ITHomeContentBean {

    @Path("channel/item")
    @Element(name = "newssource")
    private String newssource;
    @Path("channel/item")
    @Element(name = "newsauthor")
    private String newsauthor;
    @Path("channel/item")
    @Element(name = "detail")
    private String detail;

    public String getNewssource() {
        return newssource;
    }

    public void setNewssource(String newssource) {
        this.newssource = newssource;
    }

    public String getAuthor() {
        return newsauthor;
    }

    public void setAuthor(String author) {
        this.newsauthor = author;
    }

    public String getDetail() {
        return detail;
    }

    public void setDetail(String detail) {
        this.detail = detail;
    }

}

redpajama_set_name: RedPajamaGithub


text:
#include <cetty/gearman/GearmanWorker.h>

#include <cetty/bootstrap/ClientBootstrap.h>

namespace cetty {
namespace gearman {

using namespace cetty::bootstrap;
using namespace cetty::channel;
using namespace cetty::service;
using namespace cetty::service::pool;

GearmanWorker::GearmanWorker(const EventLoopPtr& eventLoop,
                             const PipelineInitializer& initializer,
                             const Connections& connections)
    : connectionPool_(connections,
                      eventLoop,
                     static_cast<int>(connections.size()),
                     static_cast<int>(connections.size())) {
    connectionPool_.setInitializer(initializer);
    connectionPool_.start();
}

GearmanWorker::~GearmanWorker() {
}

void GearmanWorker::setCando(const std::string& cando) {

}

void GearmanWorker::setCando(const std::string& cando, int64_t timeout) {

}

void GearmanWorker::setCantdo(const std::string& cantdo) {

}

void GearmanWorker::resetAbilities() {

}

void GearmanWorker::grabJob() {

}

void GearmanWorker::grabUniqueJob() {

}

}
}


text:
package com.googlecode.objectify.impl;

import com.googlecode.objectify.ObjectifyFactory;
import com.googlecode.objectify.TxnType;
import com.googlecode.objectify.Work;

/**
 * Implementation for when we start a transaction.  Maintains a separate session, but then copies all
 * data into the original session on successful commit.
 *
 * @author Jeff Schnitzer <jeff@infohazard.org>
 */
class TransactorYes extends Transactor
{
	/** Our transaction. */
	private final AsyncTransaction transaction;

	/** The non-transactional transactor that spawned us */
	private final TransactorNo parentTransactor;

	/**
	 */
	TransactorYes(final ObjectifyFactory factory, final boolean cache, final TransactorNo parentTransactor) {
		super(factory);

		this.transaction = factory.asyncDatastore(cache).newTransaction(this::committed);
		this.parentTransactor = parentTransactor;
	}

	/* (non-Javadoc)
	 * @see com.googlecode.objectify.impl.cmd.Transactor#getTransaction()
	 */
	@Override
	public AsyncTransaction getTransaction() {
		return this.transaction;
	}

	/**
	 * This version goes back to life without a transaction, but preserves current options.
	 * We use the session from the parent, ie life before transactions.
	 */
	@Override
	public ObjectifyImpl transactionless(final ObjectifyImpl parent) {
		return parent.transactor(new TransactorNo(parent.factory(), parentTransactor.getSession()));
	}

	/* (non-Javadoc)
	 * @see com.googlecode.objectify.impl.cmd.Transactor#execute(com.googlecode.objectify.TxnType, com.googlecode.objectify.Work)
	 */
	@Override
	public <R> R execute(final ObjectifyImpl parent, final TxnType txnType, final Work<R> work) {
		switch (txnType) {
			case MANDATORY:
			case REQUIRED:
			case SUPPORTS:
				return work.run();

			case NOT_SUPPORTED:
				return transactionless(parent, work);

			case NEVER:
				throw new IllegalStateException("MANDATORY transaction but no transaction present");

			case REQUIRES_NEW:
				return transactNew(parent, Transactor.DEFAULT_TRY_LIMIT, work);

			default:
				throw new IllegalStateException("Impossible, some unknown txn type");
		}
	}

	@Override
	public <R> R transactionless(final ObjectifyImpl parent, final Work<R> work) {
		final ObjectifyImpl ofy = parent.factory().open(parent.getOptions(), new TransactorNo(parent.factory(), parentTransactor.getSession()));
		try {
			return work.run();
		} finally {
			ofy.close();
		}
	}

	/* (non-Javadoc)
	 * @see com.googlecode.objectify.impl.Transactor#transact(com.googlecode.objectify.impl.ObjectifyImpl, com.googlecode.objectify.Work)
	 */
	@Override
	public <R> R transact(final ObjectifyImpl parent, final Work<R> work) {
		return work.run();
	}

	/**
	 * We need to make sure the parentSession is the transactionless session, not the session
	 * for our transaction.  This gives proper transaction isolation.
	 */
	@Override
	public <R> R transactNew(final ObjectifyImpl parent, final int limitTries, final Work<R> work) {
		return transactionless(parent).transactNew(limitTries, work);
	}

	/**
	 * Called when the associated transaction is committed. Dumps the contents of the transactional session into the parent's
	 * session.
	 */
	public void committed() {
		parentTransactor.getSession().addAll(getSession());
	}

	@Override
	public AsyncDatastoreReaderWriter asyncDatastore(final ObjectifyImpl ofy) {
		return this.transaction;
	}
}


text:
Motivation: I needed J's speed and expressiveness in C# for a webapp
Credits: JSoftware, Inc. for releasing the source code and for making excellent documentation available. Heavily influenced by [An Implementation of J](http://www.jsoftware.com/books/pdf/aioj.pdf)

Original version can be found in my [lang-lab](https://github.com/joebo/lang-lab/blob/master/csharp/jsharp/jsharp.cs). The initial version did not use generics and then was rewritten to its current form. Generics were chosen when I found I was adding type specific code to every verb.

## Status: Proof of concept

### Repl - Building / Running (tested on windows/linux)
1. run build.bat (windows) or mcs microj.cs primitives.cs repl.cs (mono)
2. run bin\microj.exe or microj.exe to get a repl, hit ctrl+c to exit or type exit

### Shared Library - Building (tested on windows)
1. c:\windows\Microsoft.NET\Framework\v4.0.30319\MSBuild microj.msbuild /p:Configuration=Library
2. new Parser().exec("1+1") //tested in linqpad

### Command Line Options
- filename
- i to run the repl (with other arguments specified)
- -tp to run parser tests (see tests at bottom of file)
- -t to run the supplied file in test mode
- -q to suppress output on file run
- -js "1+1" to run a string
- -n 10 -js "+/ i. 5" to run an operations N times

### Primitive status

Starting with list from
[http://www.jsoftware.com/jwiki/DevonMcCormick/MinimalBeginningJ](http://www.jsoftware.com/jwiki/DevonMcCormick/MinimalBeginningJ)

| Primitive | Status                                          | Monad  | Dyad            |
|-----------|-------------------------------------------------|--------|-----------------|
| =.        | Not Implemented (HOLD) / waiting on local scope |        |                 |
| =:        | Implemented                                     |        |                 |
| _         | Implemented                                     |        |                 |
| NB.       | Implemented                                     |        |                 |
| $         | Implemented                                     | shape  | reshape         |
| #         | Implemented                                     | tally  | copy            |
| ,         | Partially Implemented (missing non-equal shapes)| ravel  | append          |
| ;         | Not Implemented                                 |        |                 |
| {.        | Partially Implemented                           | head   | take            |
| }.        | Partially Implemented                           | behead | drop            |
| /         | Implemented                                     | insert | table           |
| i.        | Partially Implemented                           | iota   | indexof         |
| +         | Partially Implemented                           |        | plus (math)     |
| *         | Partially Implemented                           |        | times (math)    |
| -         | Partially Implemented                           |        | subtract (math) |
| %         | Partially Implemented                           |        | divide (math)   |
| ^         | Not Implemented                                 |        |                 |
| ^.        | Not Implemented                                 |        |                 |
| <.        | Implemented                                     | floor  | min             |
| >.        | Implemented                                     | ceiling| max             |

Data Types:
- integer (long) -- (consider int32 support)
- float (double)
- string
- bool (partial)
- boxed

## Todo:
1. More J primitives

## Vision:
Not intended to be a replacement for J. It may be useful to hack on to learn J better or embed in C#


text:
function f_approx = solve_pde(Xcenter, model, kernel, assemble_method)
% Solve pde, assemble_method for A,b assemble,
% construct approximant,
%
% Xcenter: kernel center, one node per row
% model: poisson or generel
% assemble_method: RBF or other methods

% $Author: yihu $	$Date: 2016/01/21 21:56:44 $	$Revision: 0.1 $

%     kernel = @(X1,X2) k_gauss(X1,X2,gamma);
%     kernel_grad = k_gauss_grad(dim,gamma);
%     [A,b] = assemble_method(model,kernel,kernel_grad,Xcenter,Xcenter);
[A,b] = assemble_method(model,kernel,Xcenter,Xcenter);
alpha = A\b;
f_approx = @(Xtest) kernel(Xtest, Xcenter)*alpha;

end


text:
@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    UIWindow *window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window = window;

    // 沙盒版本
    NSString *version =[NSKeyedUnarchiver unarchiveObjectWithFile:[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"version.data"]];
    // app当前版本
    NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];
    NSString *currentVersion = [infoDict objectForKey:@"CFBundleShortVersionString"];

    if ([currentVersion isEqualToString:version]) {

        self.window.rootViewController = [[ViewController alloc] init];
    }else{

//        XQNewFeatureVC *newVc = [[XQNewFeatureVC alloc] initWithFeatureImagesNameArray:@[@"1",@"2",@"3",@"4"]];
        ViewController1 *vc1 = [ViewController1 new];
        ViewController2 *vc2 = [ViewController2 new];
        ViewController3 *vc3 = [ViewController3 new];
        XQNewFeatureVC *newVc = [[XQNewFeatureVC alloc] initWithFeatureControllerArray:@[vc1,vc2,vc3]];
        newVc.pageIndicatorTintColor = [UIColor randomColor];
        self.window.rootViewController = newVc;
        newVc.completeBlock = ^{
            self.window.rootViewController = [[ViewController alloc] init];
        };

        [self.window makeKeyAndVisible];
        // 保存当前版本
//        [NSKeyedArchiver archiveRootObject:currentVersion toFile:[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"version.data"]];
    }

    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end


text:
Delete Item?

Are you sure you want to delete this item?

Deleting this item will also delete any associated notes users have created on their devices.

    Cancel

    Delete


text:
package com.gmail.thelimeglass.Effects;

import org.bukkit.Chunk;
import org.bukkit.event.Event;
import org.eclipse.jdt.annotation.Nullable;

import com.gmail.thelimeglass.Utils.Annotations.Config;
import com.gmail.thelimeglass.Utils.Annotations.Syntax;

import ch.njol.skript.lang.Effect;
import ch.njol.skript.lang.Expression;
import ch.njol.skript.lang.SkriptParser.ParseResult;
import ch.njol.util.Kleenean;

@Syntax("[skellett] load chunk %chunk% [[with] generat(e|ing) %-boolean%]")
@Config("Chunks")
public class EffChunkLoad extends Effect {

	private Expression<Chunk> chunk;
	private Expression<Boolean> generate;

	@SuppressWarnings("unchecked")
	@Override
	public boolean init(Expression<?>[] e, int matchedPattern, Kleenean isDelayed, ParseResult parser) {
		chunk = (Expression<Chunk>) e[0];
		generate = (Expression<Boolean>) e[1];
		return true;
	}

	@Override
	public String toString(@Nullable Event paramEvent, boolean paramBoolean) {
		return "[skellett] load chunk %chunk% [[with] generat(e|ing) %-boolean%]";
	}

	@Override
	protected void execute(Event event) {
		boolean generating = generate == null ? true : generate.getSingle(event);
		chunk.getSingle(event).load(generating);
	}

}


text:
/* --------------------------------------------------------------------------------------------- */
/* --- SURFACE WIDGET -------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------------------------- */

/*
    Assigned to every node managed by an instance of the Toolkit. They are required to be positioned absolute, to
    enable dragging to work properly.
*/
.jtk-node {
    position: absolute;
}

/*
    This style was created in response to this Chrome bug:
    http://stackoverflow.com/questions/13758215/artifacts-when-css-scaled-in-chrome

    Basically it's about how sometimes there can be artefacts left on screen when the user drags an element. It seems
    the issue has been fixed in more recent versions of Chrome, but the style is left here in case you come across
    the problem.
*/
.jtk-node.jsplumb-drag {
    /*-webkit-backface-visibility: hidden;*/
}

/*
    Assigned to an element that is the `Container` in a `render` call.
    Elements that are acting as Surface widgets should have overflow:hidden set to prevent libs from
    scrolling them during drag (we don't want scrollbars; we have an infinite canvas). Position is set to
    `relative` as this is the parent for nodes, which are positioned absolute (and for absolute positioning
    to work, you need to ensure the parent node has `position:relative`). This style also sets some default
    values for the cursor - using a `grab` cursor where supported.
*/
.jtk-surface {
    overflow: hidden !important;
    position: relative;
    cursor: move;
    cursor: -moz-grab;
    cursor: -webkit-grab;

    /*
        For IE10+. As discussed on this page:

        https://msdn.microsoft.com/en-us/library/ie/jj583807(v=vs.85).aspx

        Microsoft have very helpfully implemented default behaviours for a bunch of touch events and
        then consumed the events so you don't have to be bothered by them. They've "done a lot of research"
        about this stuff and put together a really great default experience for everyone in the entire world.
    */
    touch-action:none;

    /*
        Another Chrome issue that appears to have been fixed in later versions
        http://stackoverflow.com/questions/15464055/css-transition-effect-makes-image-blurry-moves-image-1px-in-chrome
    */
    /*
    -webkit-backface-visibility: hidden;
    -webkit-transform: translateZ(0) scale(1.0, 1.0);
    */
}

/*
    Assigned to the surface when it is being panned. The default is to change the cursor (in browsers that support
    a `grabbing` cursor), and to disable tex selection.
*/
.jtk-surface-panning {
    cursor: -moz-grabbing;
    cursor: -webkit-grabbing;
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

/*
    The work area in a surface renderer.
*/
.jtk-surface-canvas {
    overflow: visible !important;
}

/*
    For IE10+. Discussed above in the .jtk-surface styles. This one is specific to elements that are configured
    to be droppable on a Surface via its `registerDroppableNodes` method.
*/
.jtk-surface-droppable-node {
    touch-action:none;
}

/*
    Assigned to a Surface widget when panning is disabled (and therefore the app is relying on scrollbars when the content overflows).
*/
.jtk-surface-nopan {
    overflow: scroll !important;
    cursor:default;
}

/*
Assigned to tile images in a tiled background
*/
.jtk-surface-tile {
    border:none;
    outline:none;
    margin:0;
    -webkit-transition: opacity .3s ease .15s;
    -moz-transition: opacity .3s ease .15s;
    -o-transition: opacity .3s ease .15s;
    -ms-transition: opacity .3s ease .15s;
    transition: opacity .3s ease .15s;
}

/*
    Assigned to the element used for node select with the mouse ("lasso").
*/
.jtk-lasso {
    border: 2px solid rgb(49, 119, 184);
    background-color: WhiteSmoke;
    opacity: 0.5;
    display: none;
    z-index: 20000;
    position: absolute;
}

/*
    This class is added to the document body on lasso drag start and removed at the end of lasso dragging. Its purpose
    is to switch off text selection on all elements while the user is dragging the lasso.
*/
.jtk-lasso-select-defeat * {
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

/**
    Added to the lasso mask when it is operating in 'inverted' mode, ie. the excluded parts of the UI are covered, rather
    than the normal mode in which the selected parts of the UI are covered.
*/
.jtk-lasso-mask {
    position:fixed;
    z-index:20000;
    display:none;
    opacity:0.5;
    background-color: #07234E;
    top:0;
    bottom:0;
    left:0;
    right:0;
}

/*
    Assigned to some element that has been selected (either via lasso or programmatically).
*/
.jtk-surface-selected-element {
    border: 2px dashed #f76258 !important;
}

/*
    Assigned to all pan buttons in a surface widget.
*/
.jtk-surface-pan {
    background-color: Azure;
    opacity: 0.4;
    text-align: center;
    cursor: pointer;
    z-index: 2;
    -webkit-transition: background-color 0.15s ease-in;
    -moz-transition: background-color 0.15s ease-in;
    -o-transition: background-color 0.15s ease-in;
    transition: background-color 0.15s ease-in;
}

/*
    Specific styles for the top and bottom pan buttons.
    Top/bottom are 100% width and 20px high by default
*/
.jtk-surface-pan-top, .jtk-surface-pan-bottom {
    width: 100%;
    height: 20px;
}

/*
    Hover styles for all pan buttons.
    On hover, change color, background color, font weight and opacity.
*/
.jtk-surface-pan-top:hover, .jtk-surface-pan-bottom:hover, .jtk-surface-pan-left:hover, .jtk-surface-pan-right:hover {
    opacity: 0.6;
    background-color: rgb(49, 119, 184);
    color: white;
    font-weight: bold;
}

/*
    Specific styles for the left and right pan buttons.
    Left/right pan buttons are 100% height and 20px wide
*/
.jtk-surface-pan-left, .jtk-surface-pan-right {
    width: 20px;
    height: 100%;
    line-height: 40;
}

/* ---------------------------------------------------------------------------------------------------- */
/* --- page structure --------------------------------------------------------------------------------- */
/* ---------------------------------------------------------------------------------------------------- */

.jtk-demo-main {
    background-color: transparent;
    margin-left: auto;
    margin-right: auto;
    max-width:1500px;
    position: relative;
}

.jtk-demo-canvas {
    margin-left: 160px;
    height:550px;
    max-height:700px;
    border:1px solid #CCC;
    background-color:white;
}

.canvas-wide {
    margin-left:0;
}

/* ---------------------------------------------------------------------------------------------------- */
/* --- jsPlumb setup ---------------------------------------------------------------------------------- */
/* ---------------------------------------------------------------------------------------------------- */

.jsplumb-connector {
    z-index:9;
}

.jsplumb-endpoint {
    z-index:12;
    opacity:0.8;
    cursor:pointer;
}

.jsplumb-overlay {
    background-color: white;
    color: #434343;
    font-weight: 400;
    padding: 4px;
    z-index:10;

}

.jsplumb-overlay.jsplumb-hover {
    color: #434343;
}

path {
    cursor:pointer;
}

.w {
    padding: 16px;
    position: absolute;
    z-index: 4;
    border: solid 1px #ababab;
    border-radius: 8px;
    opacity: 0.8;
    cursor: move;
    background-color: white;
    font-size: 11px;
    -webkit-transition: background-color 0.1s ease-in;
    -moz-transition: background-color 0.1s ease-in;
    transition: background-color 0.1s ease-in;
    width: 200px;
}

.w:hover {
    background-color: #e8e6e3;
}

.ep {
    top: 37%;
    border-radius: 50%;
    behavior: url(PIE.htc); /* remove if you don't care about IE8 */
    position: absolute;
    right: -0.5em;
    width: 1em;
    height: 1em;
    background-color: #26a69a;
    cursor: pointer;
    -webkit-transition: -webkit-box-shadow 0.25s ease-in;
    -moz-transition: -moz-box-shadow 0.25s ease-in;
    transition: box-shadow 0.25s ease-in;
}

.w .collapsible {
    border: none;
    margin: 0px;
    box-shadow: none;
}

.w .collapsible div {
    margin: 0px;
    padding: 0px;
    background-color: transparent;
    border: none;
}

path, .jsplumb-endpoint { cursor:pointer; }

.btnClose {
    top: -5px;
    right: -5px;
    border-radius: 50%;
    position: absolute;
    width: 14px;
    height: 14px;
    color: white;
    background-color: #f44346;
    cursor: pointer;
    transition: visibility 0s, opacity 0.25s linear;
    visibility: hidden;
    opacity:0;
    z-index: 100;
}

.w:hover .btnClose{
    visibility: visible;
    opacity:1;
}

.settings {
    margin-top: 20px;
}

.settings input,
.settings select {
    height: 1rem;
    font-size: 0.8rem;
}

.settings .input-field{
    margin-top: 0px;
    margin-bottom: 1rem;
}


text:
#pragma once
#include <aws/guardduty/GuardDuty_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/DateTime.h>
#include <aws/guardduty/model/Owner.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/guardduty/model/DefaultServerSideEncryption.h>
#include <aws/guardduty/model/PublicAccess.h>
#include <aws/guardduty/model/Tag.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace GuardDuty
{
namespace Model
{

  /**
   *
Contains information on the S3 bucket.

See Also:
   AWS
   * API Reference

   */
  class AWS_GUARDDUTY_API S3BucketDetail
  {
  public:
    S3BucketDetail();
    S3BucketDetail(Aws::Utils::Json::JsonView jsonValue);
    S3BucketDetail& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The Amazon Resource Name (ARN) of the S3 bucket.

     */
    inline const Aws::String& GetArn() const{ return m_arn; }

    /**
     *
The Amazon Resource Name (ARN) of the S3 bucket.

     */
    inline bool ArnHasBeenSet() const { return m_arnHasBeenSet; }

    /**
     *
The Amazon Resource Name (ARN) of the S3 bucket.

     */
    inline void SetArn(const Aws::String& value) { m_arnHasBeenSet = true; m_arn = value; }

    /**
     *
The Amazon Resource Name (ARN) of the S3 bucket.

     */
    inline void SetArn(Aws::String&& value) { m_arnHasBeenSet = true; m_arn = std::move(value); }

    /**
     *
The Amazon Resource Name (ARN) of the S3 bucket.

     */
    inline void SetArn(const char* value) { m_arnHasBeenSet = true; m_arn.assign(value); }

    /**
     *
The Amazon Resource Name (ARN) of the S3 bucket.

     */
    inline S3BucketDetail& WithArn(const Aws::String& value) { SetArn(value); return *this;}

    /**
     *
The Amazon Resource Name (ARN) of the S3 bucket.

     */
    inline S3BucketDetail& WithArn(Aws::String&& value) { SetArn(std::move(value)); return *this;}

    /**
     *
The Amazon Resource Name (ARN) of the S3 bucket.

     */
    inline S3BucketDetail& WithArn(const char* value) { SetArn(value); return *this;}

    /**
     *
The name of the S3 bucket.

     */
    inline const Aws::String& GetName() const{ return m_name; }

    /**
     *
The name of the S3 bucket.

     */
    inline bool NameHasBeenSet() const { return m_nameHasBeenSet; }

    /**
     *
The name of the S3 bucket.

     */
    inline void SetName(const Aws::String& value) { m_nameHasBeenSet = true; m_name = value; }

    /**
     *
The name of the S3 bucket.

     */
    inline void SetName(Aws::String&& value) { m_nameHasBeenSet = true; m_name = std::move(value); }

    /**
     *
The name of the S3 bucket.

     */
    inline void SetName(const char* value) { m_nameHasBeenSet = true; m_name.assign(value); }

    /**
     *
The name of the S3 bucket.

     */
    inline S3BucketDetail& WithName(const Aws::String& value) { SetName(value); return *this;}

    /**
     *
The name of the S3 bucket.

     */
    inline S3BucketDetail& WithName(Aws::String&& value) { SetName(std::move(value)); return *this;}

    /**
     *
The name of the S3 bucket.

     */
    inline S3BucketDetail& WithName(const char* value) { SetName(value); return *this;}

    /**
     *
Describes whether the bucket is a source or destination bucket.

     */
    inline const Aws::String& GetType() const{ return m_type; }

    /**
     *
Describes whether the bucket is a source or destination bucket.

     */
    inline bool TypeHasBeenSet() const { return m_typeHasBeenSet; }

    /**
     *
Describes whether the bucket is a source or destination bucket.

     */
    inline void SetType(const Aws::String& value) { m_typeHasBeenSet = true; m_type = value; }

    /**
     *
Describes whether the bucket is a source or destination bucket.

     */
    inline void SetType(Aws::String&& value) { m_typeHasBeenSet = true; m_type = std::move(value); }

    /**
     *
Describes whether the bucket is a source or destination bucket.

     */
    inline void SetType(const char* value) { m_typeHasBeenSet = true; m_type.assign(value); }

    /**
     *
Describes whether the bucket is a source or destination bucket.

     */
    inline S3BucketDetail& WithType(const Aws::String& value) { SetType(value); return *this;}

    /**
     *
Describes whether the bucket is a source or destination bucket.

     */
    inline S3BucketDetail& WithType(Aws::String&& value) { SetType(std::move(value)); return *this;}

    /**
     *
Describes whether the bucket is a source or destination bucket.

     */
    inline S3BucketDetail& WithType(const char* value) { SetType(value); return *this;}

    /**
     *
The date and time the bucket was created at.

     */
    inline const Aws::Utils::DateTime& GetCreatedAt() const{ return m_createdAt; }

    /**
     *
The date and time the bucket was created at.

     */
    inline bool CreatedAtHasBeenSet() const { return m_createdAtHasBeenSet; }

    /**
     *
The date and time the bucket was created at.

     */
    inline void SetCreatedAt(const Aws::Utils::DateTime& value) { m_createdAtHasBeenSet = true; m_createdAt = value; }

    /**
     *
The date and time the bucket was created at.

     */
    inline void SetCreatedAt(Aws::Utils::DateTime&& value) { m_createdAtHasBeenSet = true; m_createdAt = std::move(value); }

    /**
     *
The date and time the bucket was created at.

     */
    inline S3BucketDetail& WithCreatedAt(const Aws::Utils::DateTime& value) { SetCreatedAt(value); return *this;}

    /**
     *
The date and time the bucket was created at.

     */
    inline S3BucketDetail& WithCreatedAt(Aws::Utils::DateTime&& value) { SetCreatedAt(std::move(value)); return *this;}

    /**
     *
The owner of the S3 bucket.

     */
    inline const Owner& GetOwner() const{ return m_owner; }

    /**
     *
The owner of the S3 bucket.

     */
    inline bool OwnerHasBeenSet() const { return m_ownerHasBeenSet; }

    /**
     *
The owner of the S3 bucket.

     */
    inline void SetOwner(const Owner& value) { m_ownerHasBeenSet = true; m_owner = value; }

    /**
     *
The owner of the S3 bucket.

     */
    inline void SetOwner(Owner&& value) { m_ownerHasBeenSet = true; m_owner = std::move(value); }

    /**
     *
The owner of the S3 bucket.

     */
    inline S3BucketDetail& WithOwner(const Owner& value) { SetOwner(value); return *this;}

    /**
     *
The owner of the S3 bucket.

     */
    inline S3BucketDetail& WithOwner(Owner&& value) { SetOwner(std::move(value)); return *this;}

    /**
     *
All tags attached to the S3 bucket

     */
    inline const Aws::Vector<Tag>& GetTags() const{ return m_tags; }

    /**
     *
All tags attached to the S3 bucket

     */
    inline bool TagsHasBeenSet() const { return m_tagsHasBeenSet; }

    /**
     *
All tags attached to the S3 bucket

     */
    inline void SetTags(const Aws::Vector<Tag>& value) { m_tagsHasBeenSet = true; m_tags = value; }

    /**
     *
All tags attached to the S3 bucket

     */
    inline void SetTags(Aws::Vector<Tag>&& value) { m_tagsHasBeenSet = true; m_tags = std::move(value); }

    /**
     *
All tags attached to the S3 bucket

     */
    inline S3BucketDetail& WithTags(const Aws::Vector<Tag>& value) { SetTags(value); return *this;}

    /**
     *
All tags attached to the S3 bucket

     */
    inline S3BucketDetail& WithTags(Aws::Vector<Tag>&& value) { SetTags(std::move(value)); return *this;}

    /**
     *
All tags attached to the S3 bucket

     */
    inline S3BucketDetail& AddTags(const Tag& value) { m_tagsHasBeenSet = true; m_tags.push_back(value); return *this; }

    /**
     *
All tags attached to the S3 bucket

     */
    inline S3BucketDetail& AddTags(Tag&& value) { m_tagsHasBeenSet = true; m_tags.push_back(std::move(value)); return *this; }

    /**
     *
Describes the server side encryption method used in the S3 bucket.

     */
    inline const DefaultServerSideEncryption& GetDefaultServerSideEncryption() const{ return m_defaultServerSideEncryption; }

    /**
     *
Describes the server side encryption method used in the S3 bucket.

     */
    inline bool DefaultServerSideEncryptionHasBeenSet() const { return m_defaultServerSideEncryptionHasBeenSet; }

    /**
     *
Describes the server side encryption method used in the S3 bucket.

     */
    inline void SetDefaultServerSideEncryption(const DefaultServerSideEncryption& value) { m_defaultServerSideEncryptionHasBeenSet = true; m_defaultServerSideEncryption = value; }

    /**
     *
Describes the server side encryption method used in the S3 bucket.

     */
    inline void SetDefaultServerSideEncryption(DefaultServerSideEncryption&& value) { m_defaultServerSideEncryptionHasBeenSet = true; m_defaultServerSideEncryption = std::move(value); }

    /**
     *
Describes the server side encryption method used in the S3 bucket.

     */
    inline S3BucketDetail& WithDefaultServerSideEncryption(const DefaultServerSideEncryption& value) { SetDefaultServerSideEncryption(value); return *this;}

    /**
     *
Describes the server side encryption method used in the S3 bucket.

     */
    inline S3BucketDetail& WithDefaultServerSideEncryption(DefaultServerSideEncryption&& value) { SetDefaultServerSideEncryption(std::move(value)); return *this;}

    /**
     *
Describes the public access policies that apply to the S3 bucket.

     */
    inline const PublicAccess& GetPublicAccess() const{ return m_publicAccess; }

    /**
     *
Describes the public access policies that apply to the S3 bucket.

     */
    inline bool PublicAccessHasBeenSet() const { return m_publicAccessHasBeenSet; }

    /**
     *
Describes the public access policies that apply to the S3 bucket.

     */
    inline void SetPublicAccess(const PublicAccess& value) { m_publicAccessHasBeenSet = true; m_publicAccess = value; }

    /**
     *
Describes the public access policies that apply to the S3 bucket.

     */
    inline void SetPublicAccess(PublicAccess&& value) { m_publicAccessHasBeenSet = true; m_publicAccess = std::move(value); }

    /**
     *
Describes the public access policies that apply to the S3 bucket.

     */
    inline S3BucketDetail& WithPublicAccess(const PublicAccess& value) { SetPublicAccess(value); return *this;}

    /**
     *
Describes the public access policies that apply to the S3 bucket.

     */
    inline S3BucketDetail& WithPublicAccess(PublicAccess&& value) { SetPublicAccess(std::move(value)); return *this;}

  private:

    Aws::String m_arn;
    bool m_arnHasBeenSet;

    Aws::String m_name;
    bool m_nameHasBeenSet;

    Aws::String m_type;
    bool m_typeHasBeenSet;

    Aws::Utils::DateTime m_createdAt;
    bool m_createdAtHasBeenSet;

    Owner m_owner;
    bool m_ownerHasBeenSet;

    Aws::Vector<Tag> m_tags;
    bool m_tagsHasBeenSet;

    DefaultServerSideEncryption m_defaultServerSideEncryption;
    bool m_defaultServerSideEncryptionHasBeenSet;

    PublicAccess m_publicAccess;
    bool m_publicAccessHasBeenSet;
  };

} // namespace Model
} // namespace GuardDuty
} // namespace Aws


text:
package mdb;
import Jakarta.util.*;
import java.io.*;
import java.util.*;

abstract public class Field_name extends Field_spec {

    public void execute () {

        super.execute();
    }

}


text:
// Generated from /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/rt.jar

#pragma once

#include <fwd-POI.hpp>
#include <java/lang/fwd-POI.hpp>
#include <java/nio/fwd-POI.hpp>
#include <java/lang/Object.hpp>

struct default_init_tag;

class java::nio::Buffer
    : public virtual ::java::lang::Object
{

public:
    typedef ::java::lang::Object super;

public: /* package */
    static constexpr int32_t SPLITERATOR_CHARACTERISTICS { int32_t(16464) };
    int64_t address {  };

private:
    int32_t capacity_ {  };
    int32_t limit_ {  };
    int32_t mark_ {  };
    int32_t position_ {  };

protected:
    void ctor(int32_t mark, int32_t pos, int32_t lim, int32_t cap);

public:
    virtual ::java::lang::Object* array() = 0;
    virtual int32_t arrayOffset() = 0;
    int32_t capacity();

public: /* package */
    static void checkBounds(int32_t off, int32_t len, int32_t size);
    int32_t checkIndex(int32_t i);
    int32_t checkIndex(int32_t i, int32_t nb);

public:
    Buffer* clear();

public: /* package */
    void discardMark();

public:
    Buffer* flip();
    virtual bool hasArray_() = 0;
    bool hasRemaining();
    virtual bool isDirect() = 0;
    virtual bool isReadOnly() = 0;
    int32_t limit();
    Buffer* limit(int32_t newLimit);
    Buffer* mark();

public: /* package */
    int32_t markValue();
    int32_t nextGetIndex();
    int32_t nextGetIndex(int32_t nb);
    int32_t nextPutIndex();
    int32_t nextPutIndex(int32_t nb);

public:
    int32_t position();
    Buffer* position(int32_t newPosition);
    int32_t remaining();
    Buffer* reset();
    Buffer* rewind();

public: /* package */
    void truncate();

    // Generated
    Buffer(int32_t mark, int32_t pos, int32_t lim, int32_t cap);
protected:
    Buffer(const ::default_init_tag&);

public:
    static ::java::lang::Class *class_();

private:
    virtual ::java::lang::Class* getClass0();
};


text:
import getParents from '../get/parents';

function getIntersectingRect(one, two) {
  // identify the rectangle that _element and _container overlap in
  const top = Math.max(one.top, two.top);
  const left = Math.max(one.left, two.left);
  // make sure bottom can't be above top, right can't be before left
  const right = Math.max(Math.min(one.right, two.right), left);
  const bottom = Math.max(Math.min(one.bottom, two.bottom), top);
  // return something resembling ClientRect
  return {
    top: top,
    right: right,
    bottom: bottom,
    left: left,
    width: right - left,
    height: bottom - top,
  };
}

function getViewportRect() {
  const width = window.innerWidth || document.documentElement.clientWidth;
  const height = window.innerHeight || document.documentElement.clientHeight;
  // return something resembling ClientRect
  return {
    top: 0,
    right: width,
    bottom: height,
    left: 0,
    width: width,
    height: height,
  };
}

function getInnerBoundingClientRect(element) {
  // convenience for the .reduce() in getScrollableParentRect()
  const rect = element.getBoundingClientRect();

  // remove the width of the scrollbar because that
  // area is not really considered visible
  // NOTE: assuming scrollbar is always to the right and bottom
  const scrollbarWidth = element.offsetWidth - element.clientWidth;
  const scrollbarHeight = element.offsetHeight - element.clientHeight;
  // cannot mutate rect because it has readonly properties
  const _rect = {
    top: rect.top,
    left: rect.left,
    right: rect.right - scrollbarWidth,
    bottom: rect.bottom - scrollbarHeight,
    width: rect.width - scrollbarWidth,
    height: rect.height - scrollbarHeight,
    area: 0,
  };

  _rect.area = _rect.width * _rect.height;
  return _rect;
}

function isOverflowingElement(element) {
  const style = window.getComputedStyle(element, null);
  const value = 'visible';
  return style.getPropertyValue('overflow-x') !== value
    && style.getPropertyValue('overflow-y') !== value;
}

function isScrollableElement(element) {
  // an element not scrollable if it doesn't crop its content
  if (!isOverflowingElement(element)) {
    return false;
  }

  // an element is scrollable when it is smaller than its content
  return element.offsetHeight < element.scrollHeight
    || element.offsetWidth < element.scrollWidth;
}

function getScrollableParentRect(element) {
  // get largest possible space constrained by scrolling containers

  // find scrollable parents
  const scrollingContainers = getParents({context: element}).slice(1).filter(isScrollableElement);

  if (!scrollingContainers.length) {
    // no containers, no joy
    return null;
  }

  // identify the currently visible intersection of all scrolling container parents
  return scrollingContainers.reduce(function(previous, current) {
    const rect = getInnerBoundingClientRect(current);
    const intersection = getIntersectingRect(rect, previous);
    // identify the smallest scrolling container so we know how much space
    // our element can fill at the most - note that this is NOT the area
    // of the intersection, intersection is just abused as a vehicle
    intersection.area = Math.min(rect.area, previous.area);
    return intersection;
  }, getInnerBoundingClientRect(scrollingContainers[0]));
}

export default function(element) {
  // dimensions of the element itself
  const _element = element.getBoundingClientRect();
  // dimensions of the viewport
  const _viewport = getViewportRect();
  // we need the area to know how much of the element can be displayed at the most
  _viewport.area = _viewport.width * _viewport.height;

  let _area = _viewport;
  // dimensions of the intersection of all scrollable parents
  const _container = getScrollableParentRect(element);
  if (_container) {
    if (!_container.width || !_container.height) {
      // scrollable containers without dimensions are invisible,
      // meaning that the element is not visible at all
      return 0;
    }

    // dimension the element can currently be rendered in
    _area = getIntersectingRect(_container, _viewport);
    _area.area = _container.area;
  }

  // dimension of the element currently rendered in identified space
  const _visible = getIntersectingRect(_element, _area);
  if (!_visible.width || !_visible.height) {
    // element is not shown within the identified area
    return 0;
  }

  // compare the element's currently visible size to the size it
  // could take up at the most, being either the element's actual
  // size, or the space theroetically made available if all
  // scrollable parents are aligned properly
  const area = _element.width * _element.height;
  const maxArea = Math.min(area, _area.area);
  // Firefox may return sub-pixel bounding client rect
  return Math.round(_visible.width) * Math.round(_visible.height) / maxArea;
}


text:
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

using System;
using System.Diagnostics;
using System.Collections.Generic;
using ICSharpCode.WpfDesign.Interfaces;
using ICSharpCode.WpfDesign.XamlDom;
using ICSharpCode.WpfDesign.Designer.Services;
using System.Collections.Specialized;

namespace ICSharpCode.WpfDesign.Designer.Xaml
{
	sealed class XamlModelCollectionElementsCollection : IObservableList<DesignItem>, INotifyCollectionChanged
	{
		readonly XamlModelProperty modelProperty;
		readonly XamlProperty property;
		readonly XamlDesignContext context;

		public event NotifyCollectionChangedEventHandler CollectionChanged;

		public XamlModelCollectionElementsCollection(XamlModelProperty modelProperty, XamlProperty property)
		{
			this.modelProperty = modelProperty;
			this.property = property;
			this.context = (XamlDesignContext)modelProperty.DesignItem.Context;
		}

		public int Count {
			get {
				return property.CollectionElements.Count;
			}
		}

		public bool IsReadOnly {
			get {
				return false;
			}
		}

		public void Add(DesignItem item)
		{
			Insert(this.Count, item);
		}

		public void Clear()
		{
			while (this.Count > 0) {
				RemoveAt(this.Count - 1);
			}

			if (CollectionChanged != null)
				CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
		}

		public bool Contains(DesignItem item)
		{
			XamlDesignItem xitem = CheckItemNoException(item);
			if (xitem != null)
				return property.CollectionElements.Contains(xitem.XamlObject);
			else
				return false;
		}

		public int IndexOf(DesignItem item)
		{
			XamlDesignItem xitem = CheckItemNoException(item);
			if (xitem != null)
				return property.CollectionElements.IndexOf(xitem.XamlObject);
			else
				return -1;
		}

		public void CopyTo(DesignItem[] array, int arrayIndex)
		{
			for (int i = 0; i < this.Count; i++) {
				array[arrayIndex + i] = this[i];
			}
		}

		public bool Remove(DesignItem item)
		{
			int index = IndexOf(item);
			if (index < 0)
				return false;

			RemoveAt(index);

			return true;
		}

		public IEnumerator<DesignItem> GetEnumerator()
		{
			foreach (XamlPropertyValue val in property.CollectionElements) {
				var item = GetItem(val);
				if (item != null)
					yield return item;
			}
		}

		System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
		{
			return this.GetEnumerator();
		}

		DesignItem GetItem(XamlPropertyValue val)
		{
			if (val is XamlObject) {
				return context._componentService.GetDesignItem( ((XamlObject)val).Instance );
			} else {
				return null; //	throw new NotImplementedException();
			}
		}

		XamlDesignItem CheckItem(DesignItem item)
		{
			if (item == null)
				throw new ArgumentNullException("item");
			if (item.Context != modelProperty.DesignItem.Context)
				throw new ArgumentException("The item must belong to the same context as this collection", "item");
			XamlDesignItem xitem = item as XamlDesignItem;
			Debug.Assert(xitem != null);
			return xitem;
		}

		XamlDesignItem CheckItemNoException(DesignItem item)
		{
			return item as XamlDesignItem;
		}

		public DesignItem this[int index] {
			get {
				return GetItem(property.CollectionElements[index]);
			}
			set {
				RemoveAt(index);
				Insert(index, value);
			}
		}

		public void Insert(int index, DesignItem item)
		{
			Execute(new InsertAction(this, index, CheckItem(item)));
		}

		public void RemoveAt(int index)
		{
			Execute(new RemoveAtAction(this, index, (XamlDesignItem)this[index]));
		}

		internal ITransactionItem CreateResetTransaction()
		{
			return new ResetAction(this);
		}

		void Execute(ITransactionItem item)
		{
			UndoService undoService = context.Services.GetService<UndoService>();
			if (undoService != null)
				undoService.Execute(item);
			else
				item.Do();
		}

		void RemoveInternal(int index, XamlDesignItem item)
		{
			RemoveFromNamescopeRecursive(item);

			Debug.Assert(property.CollectionElements[index] == item.XamlObject);
			property.CollectionElements.RemoveAt(index);

			if (CollectionChanged != null)
				CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, item, index));
		}

		void InsertInternal(int index, XamlDesignItem item)
		{
			property.CollectionElements.Insert(index, item.XamlObject);

			if (CollectionChanged != null)
				CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item, index));

			AddToNamescopeRecursive(item);
		}

		private static void RemoveFromNamescopeRecursive(XamlDesignItem designItem)
		{
			NameScopeHelper.NameChanged(designItem.XamlObject, designItem.Name, null);

			foreach (var p in designItem.Properties)
			{
				if (p.Value != null) {
					RemoveFromNamescopeRecursive((XamlDesignItem)p.Value);
				}
				else if (p.IsCollection && p.CollectionElements != null) {
					foreach (var c in p.CollectionElements) {
						RemoveFromNamescopeRecursive((XamlDesignItem)c);
					}
				}
			}
		}

		private static void AddToNamescopeRecursive(XamlDesignItem designItem)
		{
			NameScopeHelper.NameChanged(designItem.XamlObject, null, designItem.Name);

			foreach (var p in designItem.Properties)
			{
				if (p.Value != null) {
					AddToNamescopeRecursive((XamlDesignItem)p.Value);
				}
				else if (p.IsCollection && p.CollectionElements != null) {
					foreach (var c in p.CollectionElements) {
						AddToNamescopeRecursive((XamlDesignItem)c);
					}
				}
			}
		}

		sealed class InsertAction : ITransactionItem
		{
			readonly XamlModelCollectionElementsCollection collection;
			readonly int index;
			readonly XamlDesignItem item;

			public InsertAction(XamlModelCollectionElementsCollection collection, int index, XamlDesignItem item)
			{
				this.collection = collection;
				this.index = index;
				this.item = item;
			}

			public ICollection<DesignItem> AffectedElements {
				get {
					return new DesignItem[] { item };
				}
			}

			public string Title {
				get {
					return "Insert into collection";
				}
			}

			public void Do()
			{
				collection.InsertInternal(index, item);
				collection.modelProperty.XamlDesignItem.NotifyPropertyChanged(collection.modelProperty);
			}

			public void Undo()
			{
				collection.RemoveInternal(index, item);
				collection.modelProperty.XamlDesignItem.NotifyPropertyChanged(collection.modelProperty);
			}

			public bool MergeWith(ITransactionItem other)
			{
				return false;
			}
		}

		sealed class RemoveAtAction : ITransactionItem
		{
			readonly XamlModelCollectionElementsCollection collection;
			readonly int index;
			readonly XamlDesignItem item;

			public RemoveAtAction(XamlModelCollectionElementsCollection collection, int index, XamlDesignItem item)
			{
				this.collection = collection;
				this.index = index;
				this.item = item;
			}

			public ICollection<DesignItem> AffectedElements {
				get {
					return new DesignItem[] { collection.modelProperty.DesignItem };
				}
			}

			public string Title {
				get {
					return "Remove from collection";
				}
			}

			public void Do()
			{
				collection.RemoveInternal(index, item);
				collection.modelProperty.XamlDesignItem.NotifyPropertyChanged(collection.modelProperty);
			}

			public void Undo()
			{
				collection.InsertInternal(index, item);
				collection.modelProperty.XamlDesignItem.NotifyPropertyChanged(collection.modelProperty);
			}

			public bool MergeWith(ITransactionItem other)
			{
				return false;
			}
		}

		sealed class ResetAction : ITransactionItem
		{
			readonly XamlModelCollectionElementsCollection collection;
			readonly XamlDesignItem[] items;

			public ResetAction(XamlModelCollectionElementsCollection collection)
			{
				this.collection = collection;

				items = new XamlDesignItem[collection.Count];
				for (int i = 0; i < collection.Count; i++) {
					items[i] = (XamlDesignItem)collection[i];
				}
			}

			#region ITransactionItem implementation

			public void Do()
			{
				for (int i = items.Length - 1; i >= 0; i--) {
					collection.RemoveInternal(i, items[i]);
				}
				collection.modelProperty.XamlDesignItem.NotifyPropertyChanged(collection.modelProperty);
			}
			public void Undo()
			{
				for (int i = 0; i < items.Length; i++) {
					collection.InsertInternal(i, items[i]);
				}
				collection.modelProperty.XamlDesignItem.NotifyPropertyChanged(collection.modelProperty);
			}
			public bool MergeWith(ITransactionItem other)
			{
				return false;
			}

			#endregion

			#region IUndoAction implementation

			public ICollection<DesignItem> AffectedElements {
				get {
					return new DesignItem[] { collection.modelProperty.DesignItem };
				}
			}

			public string Title {
				get {
					return "Reset collection";
				}
			}

			#endregion
		}
	}
}


text:
import {Component, Input, NO_ERRORS_SCHEMA, ViewChild} from '@angular/core';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {CardFobComponent} from './card_fob_component';
import {AxisDirection} from './card_fob_types';

@Component({
  selector: 'testable-fob-comp',
  template: `
    <card-fob
      #Fob
      [axisDirection]="axisDirection"
      [step]="step"
      [allowRemoval]="allowRemoval"
      (stepChanged)="stepChanged($event)"
    ></card-fob>
  `,
})
class TestableFobComponent {
  @ViewChild('Fob')
  fob!: CardFobComponent;

  @Input() step!: number;
  @Input() axisDirection!: AxisDirection;
  @Input() allowRemoval: boolean = true;

  @Input() stepChanged!: (newStep: number) => void;
}

describe('card fob', () => {
  let stepChangedSpy: jasmine.Spy;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [TestableFobComponent, CardFobComponent],
      schemas: [NO_ERRORS_SCHEMA],
    }).compileComponents();
  });

  function createFobComponent(input: {
    step?: number;
    allowRemoval?: boolean;
    axisDirection?: AxisDirection;
  }): ComponentFixture<TestableFobComponent> {
    const fixture = TestBed.createComponent(TestableFobComponent);
    fixture.componentInstance.step = input.step ? input.step : 1;
    fixture.componentInstance.axisDirection = input.axisDirection
      ? input.axisDirection
      : AxisDirection.HORIZONTAL;
    if (input.allowRemoval !== undefined) {
      fixture.componentInstance.allowRemoval = input.allowRemoval;
    }

    stepChangedSpy = jasmine.createSpy();
    fixture.componentInstance.stepChanged = stepChangedSpy;

    return fixture;
  }

  it('renders step span in fob', () => {
    const fixture = createFobComponent({step: 3});
    fixture.detectChanges();

    const stepSpan = fixture.debugElement.query(By.css('span'));
    expect(stepSpan.nativeElement.innerText).toBe('3');
  });

  it('does not render deselect button when allowRemoval is false', () => {
    const fixture = createFobComponent({
      allowRemoval: false,
    });
    fixture.detectChanges();
    expect(fixture.debugElement.query(By.css('button'))).toBeNull();
  });

  it('emits stepChange when pressing enter key', () => {
    const fixture = createFobComponent({});
    fixture.detectChanges();

    const stepSpan = fixture.debugElement.query(By.css('span'));
    stepSpan.nativeElement.innerText = '3';
    stepSpan.triggerEventHandler('keydown.enter', {
      target: stepSpan.nativeElement,
      preventDefault: () => {},
    });

    expect(stepChangedSpy).toHaveBeenCalledWith(3);
  });

  it('emits stepChange on blur', () => {
    const fixture = createFobComponent({});
    fixture.detectChanges();

    const stepSpan = fixture.debugElement.query(By.css('span'));
    stepSpan.nativeElement.innerText = '3';
    stepSpan.triggerEventHandler('blur', {
      target: stepSpan.nativeElement,
      preventDefault: () => {},
    });

    expect(stepChangedSpy).toHaveBeenCalledWith(3);
  });

  it('emits stepChange with null when entering empty string', () => {
    const fixture = createFobComponent({});
    fixture.detectChanges();

    const stepSpan = fixture.debugElement.query(By.css('span'));
    stepSpan.nativeElement.innerText = '';
    stepSpan.triggerEventHandler('keydown.enter', {
      target: stepSpan.nativeElement,
      preventDefault: () => {},
    });

    expect(stepChangedSpy).toHaveBeenCalledWith(null);
  });

  it('does not emit preventDefault when pressing number', () => {
    const fixture = createFobComponent({});
    fixture.detectChanges();

    const stepSpan = fixture.debugElement.query(By.css('span'));
    const keyboardEvent = new KeyboardEvent('keypress', {
      key: '2',
      keyCode: 50,
    });
    const preventDefaultSpy = jasmine.createSpy();
    keyboardEvent.preventDefault = preventDefaultSpy;

    stepSpan.triggerEventHandler('keypress', keyboardEvent);

    expect(preventDefaultSpy).not.toHaveBeenCalled();
  });

  it('emits preventDefault when pressing space key', () => {
    const fixture = createFobComponent({});
    fixture.detectChanges();

    const stepSpan = fixture.debugElement.query(By.css('span'));
    const keyboardEvent = new KeyboardEvent('keypress', {
      key: ' ',
      keyCode: 32,
    });
    const preventDefaultSpy = jasmine.createSpy();
    keyboardEvent.preventDefault = preventDefaultSpy;

    stepSpan.triggerEventHandler('keypress', keyboardEvent);

    expect(preventDefaultSpy).toHaveBeenCalled();
  });

  it('emits preventDefault when pressing character key', () => {
    const fixture = createFobComponent({});
    fixture.detectChanges();

    const stepSpan = fixture.debugElement.query(By.css('span'));
    const keyboardEvent = new KeyboardEvent('keypress', {
      key: 'd',
      keyCode: 100,
    });
    const preventDefaultSpy = jasmine.createSpy();
    keyboardEvent.preventDefault = preventDefaultSpy;

    stepSpan.triggerEventHandler('keypress', keyboardEvent);

    expect(preventDefaultSpy).toHaveBeenCalled();
  });

  it('emits preventDefault when pressing shift enter key', () => {
    const fixture = createFobComponent({});
    fixture.detectChanges();

    const stepSpan = fixture.debugElement.query(By.css('span'));
    const preventDefaultSpy = jasmine.createSpy();

    stepSpan.triggerEventHandler('keydown.shift.enter', {
      preventDefault: preventDefaultSpy,
    });

    expect(preventDefaultSpy).toHaveBeenCalled();
  });
});


text:
import os.path

def ole2rtf(oleFilename):
    if not oleFilename.endswith("ole"):
        return []
    targetFile = os.path.splitext(oleFilename)[0] + ".rtf"
    fileContent = open(oleFilename, "rb").read()
    outFile = open(targetFile, "wb")
    outFile.write("{\\rtf1\\ansi\\deff3\\adeflang1025\n")
    outFile.write(fileContent)
    outFile.write("\n}")
    outFile.close()
    return [targetFile]
#    outFile = open()


text:
package com.YC2010.MyClass.callbacks;

import android.support.design.widget.Snackbar;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.View;

import com.YC2010.MyClass.ui.adapters.ItemTouchHelperAdapter;

public class SimpleItemTouchHelperCallback extends ItemTouchHelper.Callback {

    private final ItemTouchHelperAdapter mAdapter;
    private final View mView;

    public SimpleItemTouchHelperCallback(ItemTouchHelperAdapter adapter, View view) {
        mAdapter = adapter;
        mView = view;
    }

    @Override
    public boolean isLongPressDragEnabled() {
        return true;
    }

    @Override
    public boolean isItemViewSwipeEnabled() {
        return true;
    }

    @Override
    public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
        int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
        int swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END;
        return makeMovementFlags(dragFlags, swipeFlags);
    }

    @Override
    public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder,
                          RecyclerView.ViewHolder target) {
        return true;
    }

    @Override
    public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
        mAdapter.onItemDismiss(viewHolder.getAdapterPosition());

        // show snackBar Event updated
        Snackbar.make(mView, "Event Removed", Snackbar.LENGTH_SHORT)
                .show();
    }

}


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using GitReleaseNotes.Git;
using LibGit2Sharp;
using NSubstitute;
using Shouldly;
using Xunit;

namespace GitReleaseNotes.Tests
{
    public class CommitGrouperTests
    {
        private readonly Dictionary<Commit, string> tags;
        private readonly IRepository repository;
        private readonly Random random;
        private DateTimeOffset nextCommitDate;

        public CommitGrouperTests()
        {
            nextCommitDate = DateTimeOffset.Now;
            repository = Substitute.For<IRepository>();
            tags = new Dictionary<Commit, string>();
            var tagCollection = Substitute.For<TagCollection>();
            tagCollection.GetEnumerator().Returns(c => tags.Select(p =>
            {
                var tag = Substitute.For<Tag>();
                tag.Target.Returns(p.Key);
                tag.Name.Returns(p.Value);
                return tag;
            }).GetEnumerator());
            repository.Tags.Returns(tagCollection);
            random = new Random();
        }

        [Fact]
        public void DoesNotIncludeCommitsOlderThanTag()
        {
            var commit1 = CreateCommit();
            var startTagCommit = CreateCommit();
            var commit3 = CreateCommit();
            SubstituteCommitLog(commit1, startTagCommit, commit3);
            var startTag = new TaggedCommit(startTagCommit, "1.0.0");

            var results = ReleaseFinder.FindReleases(repository, startTag, new ReleaseInfo
            {
                PreviousReleaseDate = startTagCommit.Author.When
            });

            var firstRelease = results.First();
            firstRelease.PreviousReleaseDate.ShouldBe(startTagCommit.Author.When);
        }

        [Fact]
        public void GroupsTagsByReleases()
        {
            var commit1 = CreateCommit();
            var commit2 = CreateCommit();
            var commit3 = CreateCommit();
            var startTagCommit = CreateCommit();
            SubstituteCommitLog(commit1, commit2, commit3, startTagCommit);
            tags.Add(commit2, "1.1.0");
            var startTag = new TaggedCommit(startTagCommit, "1.0.0");

            var results = ReleaseFinder.FindReleases(repository, startTag, new ReleaseInfo());

            results.Count.ShouldBe(2);
            results.ElementAt(0).Name.ShouldBe(null);
            results.ElementAt(0).PreviousReleaseDate.ShouldBe(commit2.Author.When);
            results.ElementAt(1).Name.ShouldBe("1.1.0");
            results.ElementAt(1).PreviousReleaseDate.ShouldBe(null);
        }

        [Fact]
        public void GroupsTagsByReleasesIncludesEndDateOfRelease()
        {
            var commit1 = CreateCommit();
            var commit2 = CreateCommit();
            var commit3 = CreateCommit();
            var startTagCommit = CreateCommit();
            var firstCommit = CreateCommit();
            SubstituteCommitLog(commit1, commit2, commit3, startTagCommit, firstCommit);
            tags.Add(commit2, "1.1.0");
            tags.Add(startTagCommit, "1.0.0");

            var results = ReleaseFinder.FindReleases(repository, null, new ReleaseInfo());

            results.Count.ShouldBe(3);
            results.ElementAt(0).Name.ShouldBe(null);
            results.ElementAt(0).When.ShouldBe(null);
            results.ElementAt(0).PreviousReleaseDate.ShouldBe(commit2.Author.When);
            results.ElementAt(1).When.ShouldBe(commit2.Author.When);
            results.ElementAt(1).PreviousReleaseDate.ShouldBe(startTagCommit.Author.When);
            results.ElementAt(2).Name.ShouldBe("1.0.0");
            results.ElementAt(2).When.ShouldBe(startTagCommit.Author.When);
            results.ElementAt(2).PreviousReleaseDate.ShouldBe(null);
        }

        private Commit CreateCommit()
        {
            var commit = Substitute.For<Commit>();
            commit.Author.Returns(new Signature("Some Dude", "some@dude.com", nextCommitDate));
            nextCommitDate = nextCommitDate.AddHours(-1);
            var randomString = this.random.Next().ToString(CultureInfo.InvariantCulture);
            var randomSha1 = SHA1.Create().ComputeHash(Encoding.ASCII.GetBytes(randomString));
            commit.Id.Returns(new ObjectId(randomSha1));
            commit.Sha.Returns(BitConverter.ToString(randomSha1).Replace("-", string.Empty));
            return commit;
        }

        private void SubstituteCommitLog(params Commit[] commits)
        {
            var commitLog = Substitute.For<IQueryableCommitLog>();
            var returnThis = commits.AsEnumerable().GetEnumerator();
            commitLog.GetEnumerator().Returns(returnThis);
            repository.Commits.Returns(commitLog);
        }

    }
}


text:
require 'spec_helper'

feature 'Rebinding Markdown' do

  scenario 'should only bind new markdown elements when nested add is clicked', js: true do
    release = FactoryGirl.create(:release, name: 'Ima Release', vintage: '2012', price: 13, varietal_id: 2, show: Date.today)
    admin_login
    visit edit_admin_release_path(release)
    click_link 'Add Aroma'
    click_link 'Add Aroma'

    expect(page).to have_selector('.CodeMirror', count: 2)
  end

end


text:
<?php
/**
 * Created by PhpStorm.
 * User: yerganat
 * Date: 4/23/15
 * Time: 11:08 PM
 */

namespace Pidzhak\Sms;

class SmsUtil {

    public static function sendSmsWithDbWrite($sms, $tableGateWay){
        $tableGateWay->saveSms($sms);
        $lastInsertedSms = $tableGateWay->insertedSms();

        $saved_sms = $tableGateWay->getSms($lastInsertedSms);

        if($saved_sms==null)
            return;

        $numbers_array = SmsXmlParser::add_numbers_to_send_sms($sms->number, $lastInsertedSms);

        $send_xml = SmsXmlParser::buildSendSms($saved_sms->text, $numbers_array);
        $saved_sms->send_sms_xml = $send_xml;

        $response_xml = SmsXmlParser::sendSmsToUrl($send_xml);

        $RESPONSE = SmsXmlParser::parseResponseXml($response_xml);

        if($RESPONSE==null)
            return;

        $saved_sms->first_status = $RESPONSE->status;
        $saved_sms->credits = $RESPONSE->credits;

        $tableGateWay->saveSms($saved_sms);

    }

}


text:
FROM ruby:2.2.2

RUN apt-get update -qq && apt-get install -y build-essential

# for postgres
RUN apt-get install -y libpq-dev

# for nokogiri
RUN apt-get install -y libxml2-dev libxslt1-dev

# for capybara-webkit
RUN apt-get install -y libqt4-webkit libqt4-dev xvfb

# for a JS runtime
RUN apt-get install -y nodejs

ENV APP_HOME /app
RUN mkdir $APP_HOME
WORKDIR $APP_HOME

ADD Gemfile* $APP_HOME/
RUN bundle install

ADD . $APP_HOME


text:
package org.olat.presentation.framework.core.control;

import org.olat.presentation.framework.core.GlobalSettings;
import org.olat.presentation.framework.core.UserRequest;
import org.olat.presentation.framework.core.WindowManager;
import org.olat.presentation.framework.core.components.Component;
import org.olat.presentation.framework.core.components.Window;
import org.olat.presentation.framework.core.control.guistack.GuiStack;
import org.olat.presentation.framework.core.control.info.WindowControlInfo;
import org.olat.presentation.framework.core.control.winmgr.BackHandler;
import org.olat.presentation.framework.core.control.winmgr.Command;
import org.olat.system.event.Event;
import org.olat.system.event.GenericEventListener;

/**
 * Description:

 * TODO: Felix Jost Class Description for Trans
 *

 * Initial Date: 10.02.2007

 *
 * @author Felix Jost, http://www.goodsolutions.ch
 */
public interface WindowBackOffice extends Disposable {

    Event IGNORE_BOOKMARK_ONE_TIME = new Event("ibot");

    WindowManager getWindowManager();

    /**
     * @return the window associated
     */
    Window getWindow();

    /**
     * @param ureq
     * @param windowControl
     * @return
     */
    Controller createDevelopmentController(UserRequest ureq, WindowControl windowControl);

    /**
     * @return
     */
    GlobalSettings getGlobalSettings();

    /**
     * @param ureq
     * @param windowControl
     * @return
     */
    Controller createDebugDispatcherController(UserRequest ureq, WindowControl windowControl);

    /**
     * Factory method to create the inline translation tool dispatcher controller. This implicitly sets the translation controller on the window back office
     *
     * @param ureq
     * @param windowControl
     * @return
     */
    Controller createInlineTranslationDispatcherController(UserRequest ureq, WindowControl windowControl);

    /**
     * @param ureq
     * @return
     */
    Controller createAJAXController(UserRequest ureq);

    /**
     * @return
     */
    boolean isDebuging();

    void informControllerDispatched(WindowControl wControl, Controller controller, Component source, Event event);

    /**
     * @param controller
     */
    void informControllerCreated(WindowControl wControl, Controller controller);

    public String getBusinessControlPath();

    /**
     * @param initialComponent
     * @return
     */
    public GuiStack createGuiStack(Component initialComponent);

    /**
     * Use this method for asynchronous updates to the gui.

     * invokes the runnable at a time when it is safe, that is the dispatching and rendering of the window is not disturbed.
     *
     * @param runnable
     *            the runnable
     */
    public void invokeLater(Runnable runnable);

    /**
     * @param wco
     *            the Command to be sent to the client (all requests are queued and sent in a batch at the end of the request)
     */
    public void sendCommandTo(Command wco);

    /**
     * together with getData and registerForCycleEvents, this serves to exchange request-transient render-related data amongst parties, e.g. layoutcontrollers telling the
     * implementor of the windowcontrol/guimessage receiver where to visually put the guimessage.

     * all the data is clear before the inline-rendering-about-to-start event, since after that point no state change must occur.
     *
     * @param key
     *            the key (to be agreed upon by the inter-communicating parties)
     * @param value
     *            any object
     */
    public void putData(String key, Object value);

    /**
     * gets the data
     *
     * @param key
     *            the key
     * @return
     */
    public Object getData(String key);

    /**
     * not used normally! normally you do not have to care about when happens what - you should only need to know what to do in your event-methods of your controllers.
     * when listeners want to be informed about cycles in the dispatching/validating/rendering
     *
     * @param gel
     *            the listener
     */
    public void addCycleListener(GenericEventListener gel);

    public void removeCycleListener(GenericEventListener gel);

    public void adjustGuiPathCenter(WindowControlInfo wci);

    /**
     * when set, all browser-back and forward moves are sent to the backHandler instead of the ordinary handling (which reverts to the latest gui path in case of back).
     * use when "critical" use cases/controllers are in progress, such as a qti-test where a (unintended) back-button-click should not leave the current workflow.

     * this method should be called from the constructor of the controller that wishes to control the back-handling.

     * an existing backhandler will be overridden, that is, only the latest set has any effect TODO: check if boolean (done/skip) instead of void makes sense here to
     * backevent-bubble. or if the back-handlers should be stacked (what would be real use cases for such a thing?)
     *
     * @param backHandler
     */
    public void acquireBackHandling(BackHandler backHandler);

    /**
     * releases any back handler. must be called by a controller in its dispose method when it acquired a backhandling in its contructor.
     *
     * @param backHandler
     *            the backhandler to release
     */
    public void releaseBackHandling(BackHandler backHandler);

}


text:
<?php
namespace Api\Admin\User\Signin;

use Slim\Http\Response;
use Slim\Http\Request;
use Captcha\Image;
use Api\Admin;

class Captcha extends Admin
{

    function get(Request $request, Response $response)
    {
        $captcha = Image::getInstance();
        $captcha->getSession()->setExpirationHops(1);
        $res = array();
        $res['id'] = $captcha->generate();
        $res['url'] = $captcha->getImgUrl() . $res['id'] . $captcha->getSuffix();
        return $response->withStatus(200)->withJson($res);
    }
}


text:
index: 80
tag: trail

# Filmy Fern House

![Ferns in the filmy Fern house](image:filmy-fern-house.jpg)

The fern house dates back over 100 years to late
Victorian times and can be seen on the OS map of
1895. Glasgow is considered to have one of the best
filmy fern houses in the country, which is due to the
purity of Glasgow's water.
A tour of the above facilities is available on request Ask
at the Gardens office.


text:
<?php
namespace Composer\Installers;

class MediaWikiInstaller extends BaseInstaller
{
    protected $locations = array(
        'extension' => 'extensions/{$name}/',
    );

    /**
     * Format package name to CamelCase keeping existing uppercase chars.
     */
    public function inflectPackageVars($vars)
    {
        $vars['name'] = str_replace('-', ' ', $vars['name']);
        $vars['name'] = str_replace(' ', '', ucwords($vars['name']));

        return $vars;
    }

}


text:
/*
 * Based on JUEL 2.2.1 code, 2006-2009 Odysseus Software GmbH
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.activiti.engine.impl.juel;

import java.lang.reflect.Method;
import java.util.Collection;

import org.activiti.engine.impl.javax.el.ELException;
import org.activiti.engine.impl.javax.el.FunctionMapper;
import org.activiti.engine.impl.javax.el.ValueExpression;
import org.activiti.engine.impl.javax.el.VariableMapper;

/**
 * Parsed expression, usually created by a {@link org.activiti.engine.impl.juel.TreeBuilder}.
 * The {@link #bind(FunctionMapper, VariableMapper)} method is used to create
 * {@link org.activiti.engine.impl.juel.Bindings}, which are needed at evaluation time to
 * lookup functions and variables. The tree itself does not contain such information,
 * because it would make the tree depend on the function/variable mapper supplied at
 * parse time.
 *
 * @author Christoph Beck
 */
public class Tree {
	private final ExpressionNode root;
	private final Collection<FunctionNode> functions;
	private final Collection<IdentifierNode> identifiers;
	private final boolean deferred;

	/**
	 *
	 * Constructor.
	 * @param root root node
	 * @param functions collection of function nodes
	 * @param identifiers collection of identifier nodes
	 */
	public Tree(ExpressionNode root, Collection<FunctionNode> functions, Collection<IdentifierNode> identifiers, boolean deferred) {
		super();
		this.root = root;
		this.functions = functions;
		this.identifiers = identifiers;
		this.deferred = deferred;
	}

	/**
	 * Get function nodes (in no particular order)
	 */
	public Iterable<FunctionNode> getFunctionNodes() {
		return functions;
	}

	/**
	 * Get identifier nodes (in no particular order)
	 */
	public Iterable<IdentifierNode> getIdentifierNodes() {
		return identifiers;
	}

	/**
	 * @return root node
	 */
	public ExpressionNode getRoot() {
		return root;
	}

	public boolean isDeferred() {
		return deferred;
	}

	@Override
	public String toString() {
		return getRoot().getStructuralId(null);
	}

	/**
	 * Create a bindings.
	 * @param fnMapper the function mapper to use
	 * @param varMapper the variable mapper to use
	 * @return tree bindings
	 */
	public Bindings bind(FunctionMapper fnMapper, VariableMapper varMapper) {
		return bind(fnMapper, varMapper, null);
	}

	/**
	 * Create a bindings.
	 * @param fnMapper the function mapper to use
	 * @param varMapper the variable mapper to use
	 * @param converter custom type converter
	 * @return tree bindings
	 */
	public Bindings bind(FunctionMapper fnMapper, VariableMapper varMapper, TypeConverter converter) {
		Method[] methods = null;
		if (!functions.isEmpty()) {
			if (fnMapper == null) {
				throw new ELException(LocalMessages.get("error.function.nomapper"));
			}
			methods = new Method[functions.size()];
			for (FunctionNode node: functions) {
				String image = node.getName();
				Method method = null;
				int colon = image.indexOf(':');
				if (colon < 0) {
					method = fnMapper.resolveFunction("", image);
				} else {
					method = fnMapper.resolveFunction(image.substring(0, colon), image.substring(colon + 1));
				}
				if (method == null) {
					throw new ELException(LocalMessages.get("error.function.notfound", image));
				}
				if (node.isVarArgs() && method.isVarArgs()) {
					if (method.getParameterTypes().length > node.getParamCount() + 1) {
						throw new ELException(LocalMessages.get("error.function.params", image));
					}
				} else {
					if (method.getParameterTypes().length != node.getParamCount()) {
						throw new ELException(LocalMessages.get("error.function.params", image));
					}
				}
				methods[node.getIndex()] = method;
			}
		}
		ValueExpression[] expressions = null;
		if (identifiers.size() > 0) {
			expressions = new ValueExpression[identifiers.size()];
			for (IdentifierNode node: identifiers) {
				ValueExpression expression = null;
				if (varMapper != null) {
					expression = varMapper.resolveVariable(node.getName());
				}
				expressions[node.getIndex()] = expression;
			}
		}
		return new Bindings(methods, expressions, converter);
	}
}


text:
/**
 * @jest-environment jsdom
 */

/* global expect jest */

import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import {
  userLoginRequest,
  saveUser
} from '../../actions/loginActions';
import {
  SAVE_USER
} from '../../constants/user';
import {
  successClient
} from '../__mocks__/helpers/mockClients';
import {
  user
} from '../__mocks__/helpers/fixtures';

let store;

const setUpStore = (client) => {
  const middlewares = [thunk.withExtraArgument({
    client
  })];
  const mockStore = configureMockStore(middlewares);
  store = mockStore({
    user: {}
  });
};

describe('actions', () => {
  it('should create an action for a successful login', () => {
    const expectedAction = {
      type: SAVE_USER,
      user,
      category: 'currentUser'
    };
    expect(saveUser(user, 'currentUser')).toEqual(expectedAction);
  });
});

describe('login actions', () => {
  it('dispatch SAVE_USER when login is successful', () => {
    const expectedActions = [{
      type: SAVE_USER,
      user,
      category: 'currentUser'
    }];
    setUpStore(successClient);
    return store.dispatch(userLoginRequest()).then(() => {
      expect(store.getActions()).toEqual(expectedActions);
    });
  });
});


text:
package intro.proj.p1.v3;

/* Contains the report for gathering
 *
 */
public class GatherReport
{
    public static void run(CurrentUser theUser)
    {
        if (theUser.defGatRec[2].getValue() == 0)
        {
            System.out.println("You can't " + theUser.defGatRec[1].getVerb() + " any " + theUser.gold.getName() + " without assigning some " + theUser.defGatRec[1].getName() + "!");
        }
        else
        {
            int p = produced(theUser);

            if (p > 0)
            {
                System.out.println("Your " + theUser.defGatRec[1].getName() + " " + theUser.defGatRec[1].getPast() + " " + p + " " + theUser.gold.getName() + " today!");
                theUser.gold.addValue(p);
                System.out.println("Your " + theUser.getLocation() + " now has " + theUser.gold.getValue() + " " + theUser.gold.getName() + "!");
            }
            else
            {
                System.out.println("Your " + theUser.defGatRec[1].getName() + " weren't able to " + theUser.defGatRec[1].getVerb() + " any " + theUser.gold.getName() + " today, sorry!");
            }
        }
    }
    private static int produced(CurrentUser theUser)
    {
        return (int)(0.5 + (theUser.buildings[1].getBonus() / 3) + ((theUser.defGatRec[1].getValue() * (Math.random() * 4)) / (theUser.getDifficulty() + 1)));
    }
}