text:
(function() {
  "use strict";
  module.exports = function() {

    var banner =
      "\n";

    var sources = {
      scripts: ['Gruntfile.js', 'the-*/*.js', 'the-*/*.html', 'index.js'],
      // elements: ['the-*/*.html'],
      stylus: ['themes/*/*.styl'],
      css: ['themes/*.css'],
      tests: ['spec/*.coffee', 'spec/runner.html']
    };

    var glob = require('glob');
    var stylExpand = glob.sync('./themes/*.styl').join(' ');

    this.initConfig({
      pkg: this.file.readJSON('package.json'),
      'bower-install-simple': {
        deps: {
          options: {
            interactive: false,
            forceLatest: false,
            directory: 'bower_components'
          }
        }
      },
      exec: {
        build_stylus: {
          command: 'node ./node_modules/stylus/bin/stylus ' + stylExpand
        },
        build_fa: {
          command: 'node ./scripts/build-font-awesome-javascript.js'
        }
      },
      coffee: {
        specs: {
          options: {
            bare: true
          },
          expand: true,
          cwd: 'spec',
          src: ['**.coffee'],
          dest: 'spec',
          ext: '.js'
        }
      },
      browserify: {
        libs: {
          files: {
            'dist/the-graph.js': ['index.js'],
          },
          options: {
            transform: ['coffeeify'],
            browserifyOptions: {
              standalone: 'TheGraph'
            }
          }
        }
      },
      jshint: {
        options: {
          extract: 'auto',
          strict: false,
          newcap: false,
          "globals": { "Polymer": true }
        },
        all: {
          src: sources.scripts
        },
        force: {
          src: sources.scripts,
          options: { force: true }
        }
      },
      connect: {
        server: {
          options: {
            port: 3000,
            hostname: '*', // Allow connection from mobile
            livereload: true
          }
        }
      },
      watch: {
        scripts: {
          files: sources.scripts,
          tasks: ['jshint:force', 'browserify:libs'],
          options: {
            livereload: true
          }
        },
        stylus: {
          files: sources.stylus,
          tasks: ['exec:build_stylus'],
          options: {
            livereload: false
          }
        },
        css: {
          files: sources.css,
          options: {
            livereload: true
          }
        },
        tests: {
          files: sources.tests,
          tasks: ['coffee'],
          options: {
            livereload: false
          }
        },
      },
      'saucelabs-mocha': {
        all: {
          options: {
            urls: ['http://127.0.0.1:3000/spec/runner.html'],
            browsers: [
              {
                browserName: 'googlechrome',
                version: '39'
              }
            ],
            build: process.env.TRAVIS_JOB_ID,
            testname: 'the-graph browser tests',
            tunnelTimeout: 5,
            concurrency: 1,
            detailedError: true
          }
        }
      }
    });

    this.loadNpmTasks('grunt-bower-install-simple');
    this.loadNpmTasks('grunt-exec');
    this.loadNpmTasks('grunt-contrib-watch');
    this.loadNpmTasks('grunt-contrib-jshint');
    this.loadNpmTasks('grunt-contrib-connect');
    this.loadNpmTasks('grunt-contrib-coffee');
    this.loadNpmTasks('grunt-browserify');
    this.loadNpmTasks('grunt-saucelabs');

    this.registerTask('dev', ['test', 'watch']);
    this.registerTask('build', ['bower-install-simple', 'exec:build_stylus', 'exec:build_fa', 'browserify:libs']);
    this.registerTask('test', ['jshint:all', 'build', 'coffee', 'connect:server']);
    this.registerTask('crossbrowser', ['test', 'saucelabs-mocha']);
    this.registerTask('default', ['test']);
  };

}).call(this);


text:
/*
 * Linux device driver for CONNECTAL portals on FPGAs connected via PCIe.
 */

#include <linux/module.h>
#include <linux/version.h>      /* LINUX_VERSION_CODE, KERNEL_VERSION */
#include <linux/pci.h>          /* pci device types, fns, etc. */
#include <linux/errno.h>        /* error codes */
#include <linux/io.h>           /* I/O mapping, reading, writing */
#include <linux/cdev.h>         /* struct cdev */
#include <linux/fs.h>           /* struct file_operations */
#include <linux/init.h>         /* __init, __exit, etc. */
#include <linux/ioctl.h>        /* ioctl macros */
#include <linux/interrupt.h>    /* request_irq, free_irq, etc. */
#include <linux/mm.h>           /* kmalloc, kfree, struct page, etc. */
#include <linux/sched.h>        /* task_struct */
#include <linux/scatterlist.h>  /* sg_* operations */
#include <linux/mutex.h>        /* mutex_lock, mutex_unlock, etc. */
#include <linux/poll.h>         /* poll_table, etc. */
#include <asm/uaccess.h>        /* copy_to_user, copy_from_user */
#include <linux/dma-buf.h>

#include "pcieportal.h"
#define CONNECTAL_DRIVER_CODE
#include "portal.h" // PORTAL_BASE_OFFSET
#include "dmaSendFd.h"
#include "portalKernel.h"

/* stem used for module and device names */
#define DEV_NAME "portal"

/* Bluespec's standard vendor ID */
#define BLUESPEC_VENDOR_ID 0x1be7

/* CONNECTAL device ID */
#define CONNECTAL_DEVICE_ID 0xc100

/* CSR address space offsets */
#define CSR_ID                        (   0 << 2) /* 64-bit */
#define CSR_TLPDATAFIFO_DEQ           ( 768 << 2)
#define CSR_TLPTRACELENGTHREG         ( 774 << 2)
#define CSR_TLPTRACINGREG             ( 775 << 2)
#define CSR_TLPDATABRAMRESPONSESLICE0 ( 776 << 2)
#define CSR_TLPDATABRAMRESPONSESLICE1 ( 777 << 2)
#define CSR_TLPDATABRAMRESPONSESLICE2 ( 778 << 2)
#define CSR_TLPDATABRAMRESPONSESLICE3 ( 779 << 2)
#define CSR_TLPDATABRAMRESPONSESLICE4 ( 780 << 2)
#define CSR_TLPDATABRAMRESPONSESLICE5 ( 781 << 2)
#define CSR_TLPPCIEWRADDRREG          ( 792 << 2)
/* MSIX must be in separate 4kb page */
#define CSR_MSIX_ADDR_LO              (1024 << 2)
#define CSR_MSIX_ADDR_HI              (1025 << 2)
#define CSR_MSIX_MSG_DATA             (1026 << 2)
#define CSR_MSIX_MASKED               (1027 << 2)

#define PCR_IID_OFFSET 0x010
#define PCR_NUM_TILES_OFFSET 0x008
#define PCR_NUM_PORTALS_OFFSET 0x014
#define MAX_MSIX_ENTRIES 16
#define MAX_MINOR_COUNT (NUM_BOARDS * MAX_NUM_PORTALS)

/* static device data */
static dev_t device_number;
static char portalp[MAX_MINOR_COUNT]; // free map of minor numbers
static struct class *pcieportal_class = NULL;
typedef struct extra_info { /* these datatypes are not available to userspace */
        struct cdev       cdev; /* per-portal cdev structure */
        wait_queue_head_t wait_queue; /* used for interrupt notifications */
        dma_addr_t        dma_handle;
        tPortal          *portal;
} extra_info;
static extra_info extra_portal_info[MAX_MINOR_COUNT];
static extra_info extra_board_info[NUM_BOARDS];
static tBoard board_map[NUM_BOARDS + 1];
static unsigned long long expected_magic = 'B' | ((unsigned long long) 'l' << 8)
    | ((unsigned long long) 'u' << 16) | ((unsigned long long) 'e' << 24)
    | ((unsigned long long) 's' << 32) | ((unsigned long long) 'p' << 40)
    | ((unsigned long long) 'e' << 48) | ((unsigned long long) 'c' << 56);
static tTraceInfo traceInfo;

/*
 * interrupt handler
 */
static irqreturn_t intr_handler(int irq, void *p)
{
        tPortal *this_portal = p;
        //printk(KERN_INFO "%s_%d: interrupt! (num:%d name:%d)\n", DEV_NAME, this_portal->portal_number, this_portal->portal_number, this_portal->device_name);
        wake_up_interruptible(&(this_portal->extra->wait_queue));
        return IRQ_HANDLED;
}

/*
 * driver file operations
 */

/* open the device file */
static int pcieportal_open(struct inode *inode, struct file *filp)
{
        int err = 0;
        tPortal *this_portal = ((extra_info *)inode->i_cdev)->portal;

        if (!this_portal) {
        printk("pcieportal_open: device_number=%x /dev/connectal\n", device_number);
        }
        else {
        printk("pcieportal_open: device_number=%x device_name=%d device_tile=%d\n",
	       device_number, this_portal->device_name, this_portal->device_tile);
//printk("[%s:%d] inode %p filp %p portal %p priv %p privp %p extra %p\n", __FUNCTION__, __LINE__, inode, filp, this_portal, filp->private_data, privp, this_portal->extra);
        init_waitqueue_head(&(this_portal->extra->wait_queue));
        /* increment the open file count */
        this_portal->board->open_count += 1;
        // FIXME: why does the kernel think this device is RDONLY?
        }
        filp->private_data = (void *) this_portal;
        filp->f_mode |= FMODE_WRITE;

        return err;
}

/* close the device file */
static int pcieportal_release(struct inode *inode, struct file *filp)
{
        tPortal *this_portal = (tPortal *) filp->private_data;
        if (this_portal) {
	tBoard  *this_board  = this_portal->board;
	struct list_head *pmlist;
	PortalInternal devptr = {.map_base = (volatile int *)(this_board->bar2io + PORTAL_BASE_OFFSET * this_portal->portal_number),
				 .item = &kernelfunc};

        /* decrement the open file count */
        init_waitqueue_head(&(this_portal->extra->wait_queue));
        this_portal->board->open_count -= 1;
	printk("%s_%d_%d: Closed device file\n", DEV_NAME, this_portal->device_tile, this_portal->device_name);
	list_for_each(pmlist, &this_portal->pmlist) {
		struct pmentry *pmentry = list_entry(pmlist, struct pmentry, pmlist);
		printk("    returning id=%d fmem=%p\n", pmentry->id, pmentry->fmem);
		MMURequest_idReturn(&devptr, pmentry->id);
		kfree(pmentry);
	}
	INIT_LIST_HEAD(&this_portal->pmlist);
        }
        return 0;                /* success */
}

/* poll operation to predict blocking of reads & writes */
static unsigned int pcieportal_poll(struct file *filp, poll_table *poll_table)
{
        unsigned int mask = 0;
        uint32_t intr_status = 0;
        tPortal *this_portal = (tPortal *) filp->private_data;
        //tBoard *this_board = this_portal->board;

        //printk(KERN_INFO "%s_%d_%d: poll function called\n", DEV_NAME, this_portal->device_tile, this_portal->device_name);
        poll_wait(filp, &this_portal->extra->wait_queue, poll_table);
	if (this_portal->regs) {
            intr_status = *this_portal->regs;
        }
        if (intr_status)
            mask |= POLLIN  | POLLRDNORM; /* readable */
        //mask |= POLLOUT | POLLWRNORM; /* writable */
        //printk(KERN_INFO "%s_%d_%d: poll return status is %x\n", DEV_NAME, this_portal->device_tile, this_portal->device_name, mask);
        return mask;
}

/*
 * driver IOCTL operations
 */

static long pcieportal_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
        int err = 0;
        tPortal *this_portal = (tPortal *) filp->private_data;
        tBoard *this_board = NULL;
        //tBoardInfo info;
        static int trace_index;

        if (this_portal)
            this_board = this_portal->board;
        /* basic sanity checks */
        if (_IOC_DIR(cmd) & _IOC_READ)
                err = !access_ok(VERIFY_WRITE, (void __user *) arg, _IOC_SIZE(cmd));
        else if (_IOC_DIR(cmd) & _IOC_WRITE)
                err = !access_ok(VERIFY_READ, (void __user *) arg, _IOC_SIZE(cmd));
        if (!err)
        switch (cmd) {
        case BNOC_GET_TLP:
                {
                /* copy board identification info to a user-space struct */
                unsigned int tlp[6];
                memset((char *) tlp, 0xbf, sizeof(tlp));
                tlp[5] = ioread32(this_board->bar0io + CSR_TLPDATABRAMRESPONSESLICE5);
                mb();
                tlp[0] = ioread32(this_board->bar0io + CSR_TLPDATABRAMRESPONSESLICE0);
                mb();
                tlp[4] = ioread32(this_board->bar0io + CSR_TLPDATABRAMRESPONSESLICE4);
                mb();
                tlp[1] = ioread32(this_board->bar0io + CSR_TLPDATABRAMRESPONSESLICE1);
                mb();
                tlp[3] = ioread32(this_board->bar0io + CSR_TLPDATABRAMRESPONSESLICE3);
                mb();
                tlp[2] = ioread32(this_board->bar0io + CSR_TLPDATABRAMRESPONSESLICE2);
                iowrite32(trace_index++, this_board->bar0io + CSR_TLPDATAFIFO_DEQ);
                // now deq the tlpDataFifo
                err = copy_to_user((void __user *) arg, tlp, sizeof(tTlpData));
                break;
                }
        case BNOC_TRACE:
                {
                trace_index = 0;
                iowrite32(0, this_board->bar0io + CSR_TLPPCIEWRADDRREG);
                traceInfo.trace = ioread32(this_board->bar0io + CSR_TLPTRACINGREG);
                traceInfo.traceLength = ioread32(this_board->bar0io + CSR_TLPTRACELENGTHREG);
		if (traceInfo.traceLength == 0xbad0add0) // unimplemented
			 traceInfo.traceLength = 2048; // default value
                iowrite32(0, this_board->bar0io + CSR_TLPTRACINGREG);  // disable tracing
                printk("disable tracing old trace=%d\n", traceInfo.trace);
                err = copy_to_user((void __user *) arg, &traceInfo, sizeof(tTraceInfo));
                iowrite32(trace_index++, this_board->bar0io + CSR_TLPDATAFIFO_DEQ);
                }
                break;
        case BNOC_ENABLE_TRACE:
                traceInfo.trace = ioread32(this_board->bar0io + CSR_TLPTRACINGREG);
                iowrite32(1, this_board->bar0io + CSR_TLPTRACINGREG);  // disable tracing
                break;
        case PCIE_SEND_FD:
                {
                /* pushd down allocated fd */
		tSendFd sendFd;
		struct pmentry *pmentry;
                PortalInternal devptr = {.map_base = (volatile int *)(this_board->bar2io + PORTAL_BASE_OFFSET * this_portal->portal_number),
                    .item = &kernelfunc};

                err = copy_from_user(&sendFd, (void __user *) arg, sizeof(sendFd));
                if (err)
                    break;
		pmentry = (struct pmentry *)kzalloc(sizeof(struct pmentry), GFP_KERNEL);
		INIT_LIST_HEAD(&pmentry->pmlist);
		pmentry->fmem = fget(sendFd.fd);
		pmentry->id   = sendFd.id;
                printk("[%s:%d] PCIE_SEND_FD fd=%x id=%x fmem=%p  **\n", __FUNCTION__, __LINE__, sendFd.fd, sendFd.id, pmentry->fmem);
		list_add(&pmentry->pmlist, &this_portal->pmlist);
                err = send_fd_to_portal(&devptr, sendFd.fd, sendFd.id, 0);
                if (err < 0)
                    break;
                err = 0;
                }
                break;
        case PCIE_DEREFERENCE: {
		int id = arg;
		struct list_head *pmlist, *n;
		PortalInternal devptr = {.map_base = (volatile int *)(this_board->bar2io + PORTAL_BASE_OFFSET * this_portal->portal_number),
					 .item = &kernelfunc};
		err = -ENOENT;
		MMURequest_idReturn(&devptr, id);
		list_for_each_safe(pmlist, n, &this_portal->pmlist) {
			struct pmentry *pmentry = list_entry(pmlist, struct pmentry, pmlist);
			if (pmentry->id == id) {
				printk("%s:%d releasing portalmem id=%d fmem=%p count=%zd\n", __FUNCTION__, __LINE__, id, pmentry->fmem, pmentry->fmem->f_count.counter);
				fput(pmentry->fmem);
				list_del(&pmentry->pmlist);
				kfree(pmentry);
				err = 0;
				break;
			}
		}
	} break;
        case PCIE_SIGNATURE: {
                PortalSignaturePcie signature;
                static struct {
                    const char md5[33];
                    const char filename[33];
                } filesignatures[] = {
#include "pcieportal_signature_file.h"
                    };
                int err = copy_from_user(&signature, (void __user *) arg, sizeof(signature));
                if (err)
                        return -EFAULT;
                signature.md5[0] = 0;
                signature.filename[0] = 0;
//printk("%s: index %d/%ld\n", __FUNCTION__, signature.index, (long)sizeof(filesignatures)/sizeof(filesignatures[0]));
                if (signature.index < sizeof(filesignatures)/sizeof(filesignatures[0])) {
                    memcpy(signature.md5, filesignatures[signature.index].md5, sizeof(signature.md5));
                    memcpy(signature.filename, filesignatures[signature.index].filename, sizeof(signature.filename));
                }
                if (copy_to_user((void __user *)arg, &signature, sizeof(signature)))
                        return -EFAULT;
                return 0;
                }
        default:
                return -ENOTTY;
        }
        if (err)
                return -EFAULT;
        return 0;
}

static int portal_mmap(struct file *filp, struct vm_area_struct *vma)
{
        tPortal *this_portal = (tPortal *) filp->private_data;
        struct pci_dev *pci_dev = this_portal->board->pci_dev;
        off_t off;

        if (vma->vm_pgoff > (~0UL >> PAGE_SHIFT))
                return -EINVAL;
        if (vma->vm_pgoff < 16) {
                off = pci_dev->resource[2].start + PORTAL_BASE_OFFSET * this_portal->portal_number;
                printk("portal_mmap portal_number=%d board_start=%012lx portal_start=%012lx\n",
                     this_portal->portal_number, (long) pci_dev->resource[2].start, off);
                vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
                vma->vm_pgoff = off >> PAGE_SHIFT;
                //vma->vm_flags |= VM_IO | VM_RESERVED;
        } else {
                if (!this_portal->virt) {
                        this_portal->virt = dma_alloc_coherent(&pci_dev->dev,
                             vma->vm_end - vma->vm_start, &this_portal->extra->dma_handle, GFP_ATOMIC);
                        //this_portal->virt =pci_alloc_consistent(pci_dev, PORTAL_BASE_OFFSET, &this_portal->extra->dma_handle);
                        printk("dma_alloc_coherent virt=%p dma_handle=%p\n",
                             this_portal->virt, (void *) this_portal->extra->dma_handle);
                }
                //vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
                off = this_portal->extra->dma_handle;
        }
        vma->vm_flags |= VM_IO;
        if (io_remap_pfn_range(vma, vma->vm_start, off >> PAGE_SHIFT,
             vma->vm_end - vma->vm_start, vma->vm_page_prot))
                return -EAGAIN;

        return 0;
}

static ssize_t pcieportal_read(struct file *filp,
      char *buffer, size_t length, loff_t *offset)
{
        return 0;
}

/* file operations pointers */
static const struct file_operations pcieportal_fops = {
        .owner = THIS_MODULE,
        .open = pcieportal_open,
	.read   = pcieportal_read,
        .release = pcieportal_release,
        .poll = pcieportal_poll,
        .unlocked_ioctl = pcieportal_ioctl,
        .compat_ioctl = pcieportal_ioctl,
        .mmap = portal_mmap
};

static int board_activate(int activate, tBoard *this_board, struct pci_dev *dev)
{
	int i;
        int rc, err = 0;
        unsigned long long magic_num;
	int num_entries = MAX_MSIX_ENTRIES;
	struct msix_entry msix_entries[MAX_MSIX_ENTRIES];
	int fpn = 0;
	int num_tiles, tile_index;
	void __iomem *ptile;

printk("[%s:%d]\n", __FUNCTION__, __LINE__);
        for (i = 0; i < MAX_NUM_PORTALS; i++)
        	if (!this_board->portal[i].extra) {
                        printk(KERN_ERR "%s: extra not initialized!!! %s\n", DEV_NAME, pci_name(dev));
                        err = -EFAULT;
                        goto err_exit;
                }
        if (activate) {
		dev_t this_device_number;
   	        for (i = 0; i < MAX_NUM_PORTALS; i++)
		  this_board->portal[i].device_name = -1;
   	        for (i = 0; i < MAX_NUM_PORTALS; i++)
		  init_waitqueue_head(&(this_board->portal[i].extra->wait_queue));
                this_board->pci_dev = dev;
                /* enable the PCI device */
                if (pci_enable_device(dev)) {
                        printk(KERN_ERR "%s: failed to enable %s\n", DEV_NAME, pci_name(dev));
                        err = -EFAULT;
                        goto err_exit;
                }
                /* reserve PCI memory regions */
                for (i = 0; i < 5; i++)
                        printk("pci bar %d start=%08lx end=%08lx flags=%lx\n", i,
                             (unsigned long) dev->resource[i].start,
                             (unsigned long) dev->resource[i].end,
                             dev->resource[i].flags);
                traceInfo.base = dev->resource[2].start; /* remember physical address of bar2 */
                if ((rc = pci_request_region(dev, 0, "bar0"))) {
                        printk("failed to request region bar0 rc=%d\n", rc);
                        err = -EBUSY;
                        goto PCI_DEV_ENABLED_label;
                }
                rc = pci_request_region(dev, 1, "bar1");
                printk("reserving region bar1 rc=%d\n", rc);
                rc = pci_request_region(dev, 2, "bar2");
                printk("reserving region bar2 rc=%d\n", rc);
                /* map BARs */
                this_board->bar0io = pci_iomap(dev, 0, 0);
                printk("bar0io=%p\n", this_board->bar0io);
                this_board->bar1io = pci_iomap(dev, 1, 0);
                printk("bar1io=%p\n", this_board->bar1io);
                this_board->bar2io = pci_iomap(dev, 2, 0);
                printk("bar2io=%p\n", this_board->bar2io);
                if (!this_board->bar1io) {
                        this_board->bar1io = pci_iomap(dev, 1, 8192);
                        printk("bar1io=%p\n", this_board->bar1io);
                }
                if (!this_board->bar0io) {
                        printk("failed to map bar0\n");
                        err = -EFAULT;
                        goto BARS_ALLOCATED_label;
                }
                if (!this_board->bar2io) {
                        printk("failed to map bar2\n");
                        err = -EFAULT;
                        goto BARS_ALLOCATED_label;
                }
        	// this replaces 'connectal/pcie/connectalutil/connectalutil trace /dev/fpga0'
        	// but why is it needed?...
        	iowrite32(0, this_board->bar0io + CSR_TLPPCIEWRADDRREG);
        	// enable tracing
                iowrite32(1, this_board->bar0io + CSR_TLPTRACINGREG);
                /* check the magic number in BAR 0 */
                magic_num = ((long long)ioread32(this_board->bar0io + CSR_ID +  4)) << 32;
                magic_num |= ioread32(this_board->bar0io + CSR_ID);
                if (magic_num != expected_magic) {
                        printk(KERN_ERR "%s: magic number %llx does not match expected %llx\n",
                               DEV_NAME, magic_num, expected_magic);
                        err = -EINVAL;
                        goto BARS_MAPPED_label;
                }
                /* set DMA mask */
                if (pci_set_dma_mask(dev, DMA_BIT_MASK(48))) {
                        printk(KERN_ERR "%s: pci_set_dma_mask failed for 48-bit DMA\n", DEV_NAME);
                        err = -EIO;
                        goto BARS_MAPPED_label;
                }
                /* enable MSIX */
		for (i = 0; i < num_entries; i++)
			msix_entries[i].entry = i;
		if (pci_enable_msix(dev, msix_entries, num_entries)) {
			printk(KERN_ERR "%s: Failed to setup MSIX interrupts\n", DEV_NAME);
			err = -EFAULT;
                        goto BARS_MAPPED_label;
		}
		this_board->irq_num = msix_entries[0].vector;
		printk(KERN_INFO "%s: Using MSIX interrupts num_entries=%d check_device\n", DEV_NAME, num_entries);
		for (i = 0; i < num_entries; i++)
			printk(KERN_INFO "%s: msix_entries[%d] vector=%d entry=%08x\n", DEV_NAME, i, msix_entries[i].vector, msix_entries[i].entry);
		/* install the IRQ handler */
		for (i = 0; i < num_entries; i++) {
			if (request_irq(this_board->irq_num + i, intr_handler, 0, DEV_NAME, (void *) &this_board->portal[i])) {
				printk(KERN_ERR "%s: Failed to get requested IRQ %d\n", DEV_NAME, this_board->irq_num);
				err = -EBUSY;
				goto MSI_ENABLED_label;
			}
		}
		/* set MSIX Entry 0 Vector Control value to 0 (unmasked) */
		printk(KERN_INFO "%s: MSIX interrupts enabled with %d IRQs starting at %d\n",
		       DEV_NAME, num_entries, this_board->irq_num);
		iowrite32(0, this_board->bar0io + CSR_MSIX_MASKED);
                pci_set_master(dev); /* enable PCI bus master */

		ptile = this_board->bar2io;
		num_tiles = *(volatile uint32_t *)(ptile + PCR_NUM_TILES_OFFSET);
		tile_index = 0;
		do {  // loop over all tiles
		  void __iomem *pportal = ptile;
		  int num_portals = *(volatile uint32_t *)(pportal + PCR_NUM_PORTALS_OFFSET);
		  int portal_index = 0;
		  do {  // loop over all portals in a tile
		    int freep;
		    uint32_t iid = *(volatile uint32_t *)(pportal + PCR_IID_OFFSET);
		    tPortal *this_portal = &this_board->portal[portal_index];
		    printk("%s:%d num_tiles %x/%x num_portals %x/%x fpn %x iid=%d\n", __FUNCTION__, __LINE__, tile_index, num_tiles, portal_index, num_portals, fpn, iid);
		    traceInfo.intval[fpn] = ioread32(this_board->bar0io + CSR_MSIX_MSG_DATA  + 16*fpn);
		    traceInfo.name[fpn] = iid;
		    for (freep = 0; freep < sizeof(portalp)/sizeof(portalp[0]); freep++)
		        if (!portalp[freep])
		             break;
		    if (freep == sizeof(portalp)/sizeof(portalp[0])) {
		        printk(KERN_ERR "%s: too many portals\n", KERN_ERR);
		        err = -EFAULT;
		    }
		    else
		        portalp[freep] = 1;
		    this_board->portal[fpn].device_number = freep;
		    this_board->portal[fpn].device_tile = tile_index;
		    this_board->portal[fpn].portal_number = fpn;
		    this_board->portal[fpn].device_name = iid;
		    this_board->portal[fpn].board = this_board;
		    this_board->portal[fpn].regs = (volatile uint32_t *)pportal;
		    /* add the device operations */
		    cdev_init(&this_board->portal[fpn].extra->cdev, &pcieportal_fops);
		    this_device_number = MKDEV(MAJOR(device_number), MINOR(device_number) + this_portal->device_number);
		    if (cdev_add(&this_board->portal[fpn].extra->cdev, this_device_number, 1)) {
		      printk(KERN_ERR "%s: cdev_add %x failed\n",
			     DEV_NAME, this_device_number);
		      err = -EFAULT;
		    } else {
		      /* create a device node via udev */
		      device_create(pcieportal_class, NULL,
				    this_device_number, this_portal, "%s_%d_%d", DEV_NAME, this_portal->device_tile, this_portal->device_name);
		      printk(KERN_INFO "%s: /dev/%s_%d_%d = %x created\n",
			     DEV_NAME, DEV_NAME, this_portal->device_tile, this_portal->device_name, this_device_number);
		    }
		    if (++fpn >= MAX_NUM_PORTALS){
		      printk(KERN_INFO "%s: MAX_NUM_PORTALS exceeded", __func__);
		      err = -EFAULT;
		      break;
		    }
		    pportal += PORTAL_BASE_OFFSET;
		  } while (++portal_index < num_portals);
		  ptile += TILE_BASE_OFFSET;
		} while (++tile_index < num_tiles);
		this_board->info.num_portals = fpn;
                pci_set_drvdata(dev, this_board);
		this_device_number = MKDEV(MAJOR(device_number), MINOR(device_number) + MAX_MINOR_COUNT);
		cdev_init(&this_board->extra->cdev, &pcieportal_fops);
		if (cdev_add(&this_board->extra->cdev, this_device_number, 1)) {
		    printk(KERN_ERR "%s: cdev_add board failed\n", DEV_NAME);
                }
		device_create(pcieportal_class, NULL, this_device_number, NULL, "connectal");
                if (err == 0)
                    return err; /* if board activated correctly, return */
        } /* end of if(activate) */

        /******** deactivate board *******/
	device_destroy(pcieportal_class, MKDEV(MAJOR(device_number), MINOR(device_number) + MAX_MINOR_COUNT));
        cdev_del(&this_board->extra->cdev);
	fpn = 0;
	while(fpn < this_board->info.num_portals) {
                tPortal *this_portal = &this_board->portal[fpn];
		  /* remove device node in udev */
		dev_t this_device_number = MKDEV(MAJOR(device_number), MINOR(device_number) + this_portal->device_number);
		portalp[this_portal->device_name] = 0;
                device_destroy(pcieportal_class, this_device_number);
                printk(KERN_INFO "%s: /dev/%s_%d_%d = %x removed\n",
		       DEV_NAME, DEV_NAME, this_portal->device_tile, this_portal->device_name, this_device_number);
                /* remove device */
                cdev_del(&this_board->portal[fpn].extra->cdev);
		fpn++;
        }
        pci_clear_master(dev); /* disable PCI bus master */
        /* set MSIX Entry 0 Vector Control value to 1 (masked) */
        iowrite32(1, this_board->bar0io + CSR_MSIX_MASKED);
        disable_irq(this_board->irq_num);
	for (i = 0; i < num_entries; i++)
		free_irq(this_board->irq_num + i, (void *) &this_board->portal[i]);
MSI_ENABLED_label:
        /* disable MSI/MSIX */
        pci_disable_msix(dev);
BARS_MAPPED_label:
        /* unmap PCI BARs */
        if (this_board->bar0io)
                pci_iounmap(dev, this_board->bar0io);
        if (this_board->bar1io)
                pci_iounmap(dev, this_board->bar1io);
        if (this_board->bar2io)
                pci_iounmap(dev, this_board->bar2io);
BARS_ALLOCATED_label:
        pci_release_regions(dev); /* release PCI memory regions */
PCI_DEV_ENABLED_label:
        pci_disable_device(dev); /* disable pci device */
err_exit:
        this_board->pci_dev = NULL;
        pci_set_drvdata(dev, NULL);
        return err;
}

/* driver PCI operations */

static int pcieportal_probe(struct pci_dev *dev, const struct pci_device_id *id)
{
        tBoard *this_board = NULL;
        int i, board_number = 0;

printk("******[%s:%d] probe %p dev %p id %p getdrv %p\n", __FUNCTION__, __LINE__, &pcieportal_probe, dev, id, pci_get_drvdata(dev));
        printk(KERN_INFO "%s: PCI probe for 0x%04x 0x%04x\n", DEV_NAME, dev->vendor, dev->device);
        /* double-check vendor and device */
        if (dev->vendor != BLUESPEC_VENDOR_ID || dev->device != CONNECTAL_DEVICE_ID) {
                printk(KERN_ERR "%s: probe with invalid vendor or device ID\n", DEV_NAME);
                return -EINVAL;
        }
        /* assign a board number */
        while (board_map[board_number].pci_dev && board_number < NUM_BOARDS)
                board_number++;
        if (board_number >= NUM_BOARDS) {
                printk(KERN_ERR "%s: %d boards are already in use!\n", DEV_NAME, NUM_BOARDS);
                return -EBUSY;
        }
        this_board = &board_map[board_number];
        printk(KERN_INFO "%s: board_number = %d\n", DEV_NAME, board_number);
        memset(this_board, 0, sizeof(tBoard));
        for (i = 0; i < MAX_NUM_PORTALS; i++) {
                this_board->portal[i].extra = &extra_portal_info[board_number * MAX_NUM_PORTALS + i];
                extra_portal_info[board_number * MAX_NUM_PORTALS + i].portal = &this_board->portal[i];
		INIT_LIST_HEAD(&this_board->portal[i].pmlist);
	}
        this_board->extra = &extra_board_info[board_number];
        this_board->info.board_number = board_number;
        return board_activate(1, this_board, dev);
}

static void pcieportal_remove(struct pci_dev *dev)
{
        tBoard *this_board = pci_get_drvdata(dev);
printk("*****[%s:%d] getdrv %p\n", __FUNCTION__, __LINE__, this_board);
        if (!this_board) {
                printk(KERN_ERR "%s: Unable to locate board when removing PCI device %p\n", DEV_NAME, dev);
                return;
        }
        board_activate(0, this_board, dev);
}

/* PCI ID pattern table */
static DEFINE_PCI_DEVICE_TABLE(pcieportal_id_table) = {{
        PCI_DEVICE(BLUESPEC_VENDOR_ID, CONNECTAL_DEVICE_ID)}, { /* end: all zeros */ } };

MODULE_DEVICE_TABLE(pci, pcieportal_id_table);

/* PCI driver operations pointers */
static struct pci_driver pcieportal_ops = {
        .name = DEV_NAME,
        .id_table = pcieportal_id_table,
        .probe = pcieportal_probe,
        .remove = pcieportal_remove
};

/*
 *
 * get the tBoard struct
 *
 */

tBoard* get_pcie_portal_descriptor(void)
{
  return &board_map[0];
}

/*
 * driver initialization and exit
 *
 * these routines are responsible for allocating and
 * freeing kernel resources, creating device nodes,
 * registering the driver, obtaining a major and minor
 * numbers, etc.
 */

/* first routine called on module load */
static int pcieportal_init(void)
{
        int status;

printk("[%s:%d]\n", __FUNCTION__, __LINE__);
        pcieportal_class = class_create(THIS_MODULE, "Connectal");
        if (IS_ERR(pcieportal_class)) {
                printk(KERN_ERR "%s: failed to create class Connectal\n", DEV_NAME);
                return PTR_ERR(pcieportal_class);
        }
        /* dynamically allocate a device number */
        if (alloc_chrdev_region(&device_number, 1, MAX_MINOR_COUNT + 1, DEV_NAME) < 0) {
                printk(KERN_ERR "%s: failed to allocate character device region\n", DEV_NAME);
                class_destroy(pcieportal_class);
                return -1;
        }
        /* initialize driver data */
        memset(board_map, 0, sizeof(board_map));
        /* log the fact that we loaded the driver module */
        printk(KERN_INFO "%s: Registered Connectal Pcieportal driver %s\n", DEV_NAME, DRIVER_VERSION);
        printk(KERN_INFO "%s: Major = %d  Minors = %d to %d\n", DEV_NAME,
               MAJOR(device_number), MINOR(device_number),
               MINOR(device_number) + MAX_MINOR_COUNT - 1);
        /* register the driver with the PCI subsystem */
        status = pci_register_driver(&pcieportal_ops);
        if (status < 0) {
                printk(KERN_ERR "%s: failed to register PCI driver\n", DEV_NAME);
                class_destroy(pcieportal_class);
                return status;
        }
printk("[%s:%d]\n", __FUNCTION__, __LINE__);
        return 0;                /* success */
}

/* routine called on module unload */
static void pcieportal_exit(void)
{
        /* unregister the driver with the PCI subsystem */
        pci_unregister_driver(&pcieportal_ops);
        /* release reserved device numbers */
        unregister_chrdev_region(device_number, MAX_MINOR_COUNT + 1);
        class_destroy(pcieportal_class);
        /* log that the driver module has been unloaded */
        printk(KERN_INFO "%s: Unregistered Connectal Pcieportal driver %s\n", DEV_NAME, DRIVER_VERSION);
}

/*
 * driver module data for the kernel
 */

module_init(pcieportal_init);
module_exit(pcieportal_exit);

EXPORT_SYMBOL(get_pcie_portal_descriptor);

MODULE_AUTHOR("Bluespec, Inc., Cambridge hackers");
MODULE_DESCRIPTION("PCIe device driver for PCIe FPGA portals");
MODULE_LICENSE("Dual BSD/GPL");
MODULE_VERSION(DRIVER_VERSION);

redpajama_set_name: RedPajamaGithub


text:
    do { int errcount = 0;\
         GLenum err;\
         while((err = glGetError()) != GL_NO_ERROR) {errcount++; printf("GLERROR @%d: %x\n", __LINE__, err); }\
         if (errcount)  assert(!"GL Errors. Aborting");\
    } while (0);

struct global {
    struct { int width, height; } framebuffer;
    struct { int width, height; } window;
    glm::mat4 projection;
};

static void
window_size(GLFWwindow *window, int width, int height)
{
    auto *globals = (struct global*)glfwGetWindowUserPointer(window);
    assert(globals != NULL);

    globals->window.width = width;
    globals->window.height = height;
    float aspect = (float)width / (float)height;
    globals->projection = glm::perspective(45.0f, aspect, 0.1f, 100.0f);
    printf("Win size : %dx%d\n", globals->window.width, globals->window.height);
}

static void
framebuffer_size(GLFWwindow *window, int width, int height)
{
    auto *globals = (struct global*)glfwGetWindowUserPointer(window);
    assert(globals != NULL);

    globals->framebuffer.width = width;
    globals->framebuffer.height = height;
    printf("FB size  : %dx%d\n", globals->framebuffer.width, globals->framebuffer.height);
}

void
key_action(GLFWwindow *window, int,int,int,int)
{
    printf("Key action\n");
    glfwSetWindowShouldClose(window, 1);
}

int
main(int argc, char *argv[])
{
    struct global globals;
    if (!glfwInit()) {
        return -1;
    }

    GLFWwindow *window;
    {
        glfwWindowHint(GLFW_DEPTH_BITS, 16);
        glfwWindowHint(GLFW_SAMPLES, 1);
        glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
        glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
        glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
        glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

        window = glfwCreateWindow(800, 480, argv[0], NULL, NULL);
        glfwSetWindowUserPointer(window, &globals);
        assert(window != NULL);

        glfwSetFramebufferSizeCallback(window, framebuffer_size);
        glfwSetWindowSizeCallback(window, window_size);
        glfwSetKeyCallback(window, key_action);
        glfwMakeContextCurrent(window);

        const GLubyte* renderer = glGetString (GL_RENDERER); // get renderer string
        const GLubyte* version = glGetString (GL_VERSION); // version as a string
        printf("Renderer : %s\n", renderer);
        printf("OpenGL   : %s\n", version);
        printf("Shader   : %s\n", glGetString(GL_SHADING_LANGUAGE_VERSION));
        printf("GLFW     : %s\n", glfwGetVersionString());

        glfwSwapInterval(1);
    }

    {
        int width, height;

        glfwGetWindowSize(window, &width, &height);
        window_size(window, width, height);

        glfwGetFramebufferSize(window, &width, &height);
        framebuffer_size(window, width, height);
    }

    GLuint shader;
    int position_index, colour_index;
    int projection_index, modelview_index;
    {
        #include "shader.h"
        GLuint vsh;
        {
            vsh = glCreateShader(GL_VERTEX_SHADER);
            glShaderSource(vsh, 1, &vertex_shader, NULL);
            glCompileShader(vsh);

            int is_ok;
            glGetShaderiv(vsh, GL_COMPILE_STATUS, &is_ok);
            assert(is_ok == GL_TRUE && "Failed to compile vertex shader");
        }
        GLuint fsh;
        {
            fsh = glCreateShader(GL_FRAGMENT_SHADER);
            glShaderSource(fsh, 1, &fragment_shader, NULL);
            glCompileShader(fsh);

            int is_ok;
            glGetShaderiv(fsh, GL_COMPILE_STATUS, &is_ok);
            assert(is_ok == GL_TRUE && "Failed to compile fragment shader");
        }

        shader = glCreateProgram ();
        glAttachShader(shader, vsh);
        glAttachShader(shader, fsh);
        glLinkProgram(shader);

        int is_ok = 42;
        glGetProgramiv(shader, GL_LINK_STATUS, &is_ok);
        assert(is_ok == GL_TRUE && "Failed to link shader");

        position_index = glGetAttribLocation(shader, "position");
        assert(position_index != -1);

        colour_index = glGetAttribLocation(shader, "colour");
        assert(colour_index != -1);

        projection_index = glGetUniformLocation(shader, "projection");
        assert(projection_index != -1);

        modelview_index = glGetUniformLocation(shader, "modelview");
        assert(modelview_index != -1);
    }
    catchGlError();

    GLuint vao;
    int num_triangles;
    {
        GLuint vbo;
        #include "tri_geometry.h"
        glGenBuffers(1, &vbo);
        glBindBuffer (GL_ARRAY_BUFFER, vbo);
        glBufferData (GL_ARRAY_BUFFER, triangle_geometry.data_size, triangle_geometry.data, GL_STATIC_DRAW);
        num_triangles = triangle_geometry.num_triangles;

        glGenVertexArrays(1, &vao);

        glBindVertexArray(vao);
        glBindBuffer (GL_ARRAY_BUFFER, vbo);

        glEnableVertexAttribArray(position_index);
        glVertexAttribPointer(position_index, 4, GL_FLOAT, 0, 0, (void*)0);

        uintptr_t offset_to_colours = sizeof(float)*num_triangles*4*3;
        glEnableVertexAttribArray(colour_index);
        glVertexAttribPointer(colour_index  , 4, GL_FLOAT, 0, 0, (void*)offset_to_colours );
    }
    catchGlError();

    glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
    catchGlError();
    while (!glfwWindowShouldClose(window)) {
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        auto translate_vec = glm::vec3(0,0, -2);
        auto rotate_vec = glm::vec3(0,1,0);
        static float rot = 0;

        auto modelview = glm::mat4(1);
        modelview = glm::translate(modelview, translate_vec);
        modelview = glm::rotate   (modelview, rot+=0.05f, rotate_vec);

        glUseProgram(shader);
        glBindVertexArray(vao);

        glUniformMatrix4fv(projection_index,
                1, GL_FALSE, glm::value_ptr(globals.projection));
        glUniformMatrix4fv(modelview_index,
                1, GL_FALSE, glm::value_ptr(modelview));

        glDrawArrays(GL_TRIANGLES, 0, 3);

        glfwSwapBuffers(window);
        glfwPollEvents();
        catchGlError();
    }

    glfwDestroyWindow(window);
    glfwTerminate();
    printf("Goodbye\n");

    return 0;
}


text:
package com.dedudevgmail.activityanalyzer.model.database;

import java.util.List;

import io.reactivex.Completable;
import io.reactivex.Maybe;

/**
 * com.dedudevgmail.activityanalyzer.model.database
 * Created by Llullas on 07.04.2017.
 */
public interface DatabaseSource {

	Completable createItem(Item item);

	Completable deleteItem(Item item);

	Maybe<List<Item>> getItemList(String uid);

	//For testing
	void setReturnFail(boolean bool);

	void setReturnEmpty(boolean bool);
}


text:
@interface SystranCrossDomainApi ()
    @property (readwrite, nonatomic, strong) NSMutableDictionary *defaultHeaders;
@end

@implementation SystranCrossDomainApi

static SystranCrossDomainApi* singletonAPI = nil;

#pragma mark - Initialize methods

- (id) init {
    self = [super init];
    if (self) {
        SystranConfiguration *config = [SystranConfiguration sharedConfig];
        if (config.apiClient == nil) {
            config.apiClient = [[SystranApiClient alloc] init];
        }
        self.apiClient = config.apiClient;
        self.defaultHeaders = [NSMutableDictionary dictionary];
    }
    return self;
}

- (id) initWithApiClient:(SystranApiClient *)apiClient {
    self = [super init];
    if (self) {
        self.apiClient = apiClient;
        self.defaultHeaders = [NSMutableDictionary dictionary];
    }
    return self;
}

#pragma mark -

+(SystranCrossDomainApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key {

    if (singletonAPI == nil) {
        singletonAPI = [[SystranCrossDomainApi alloc] init];
        [singletonAPI addHeader:headerValue forKey:key];
    }
    return singletonAPI;
}

+(SystranCrossDomainApi*) sharedAPI {

    if (singletonAPI == nil) {
        singletonAPI = [[SystranCrossDomainApi alloc] init];
    }
    return singletonAPI;
}

-(void) addHeader:(NSString*)value forKey:(NSString*)key {
    [self.defaultHeaders setValue:value forKey:key];
}

-(void) setHeaderValue:(NSString*) value
           forKey:(NSString*)key {
    [self.defaultHeaders setValue:value forKey:key];
}

-(unsigned long) requestQueueSize {
    return [SystranApiClient requestQueueSize];
}

#pragma mark - Api Methods

///
/// Silverlight client access policy file
/// Silverlight client access policy file (clientaccesspolicy.xml) to handle cross-domain requests.
///  @returns NSURL*
///
-(NSNumber*) clientaccesspolicyXmlGetWithCompletionBlock:
        (void (^)(NSURL* output, NSError* error))completionBlock {

    NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/clientaccesspolicy.xml"];

    // remove format in URL if needed
    if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) {
        [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"];
    }

    NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init];

    NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init];

    NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders];

    // HTTP header `Accept`
    headerParams[@"Accept"] = [SystranApiClient selectHeaderAccept:@[@"application/xml"]];
    if ([headerParams[@"Accept"] length] == 0) {
        [headerParams removeObjectForKey:@"Accept"];
    }

    // response content type
    NSString *responseContentType;
    if ([headerParams objectForKey:@"Accept"]) {
        responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0];
    }
    else {
        responseContentType = @"";
    }

    // request content type
    NSString *requestContentType = [SystranApiClient selectHeaderContentType:@[]];

    // Authentication setting
    NSArray *authSettings = @[];

    id bodyParam = nil;
    NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init];
    NSMutableDictionary *files = [[NSMutableDictionary alloc] init];

    return [self.apiClient requestWithCompletionBlock: resourcePath
                                               method: @"GET"
                                           pathParams: pathParams
                                          queryParams: queryParams
                                           formParams: formParams
                                                files: files
                                                 body: bodyParam
                                         headerParams: headerParams
                                         authSettings: authSettings
                                   requestContentType: requestContentType
                                  responseContentType: responseContentType
                                         responseType: @"NSURL*"
                                      completionBlock: ^(id data, NSError *error) {

                  completionBlock((NSURL*)data, error);
              }
          ];
}

///
/// Adobe Flash cross-domain policy file
/// Adobe Flash cross-domain policy file (crossdomain.xml) to handle cross-domain requests.
///  @returns NSURL*
///
-(NSNumber*) crossdomainXmlGetWithCompletionBlock:
        (void (^)(NSURL* output, NSError* error))completionBlock {

    NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/crossdomain.xml"];

    // remove format in URL if needed
    if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) {
        [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"];
    }

    NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init];

    NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init];

    NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders];

    // HTTP header `Accept`
    headerParams[@"Accept"] = [SystranApiClient selectHeaderAccept:@[@"application/xml"]];
    if ([headerParams[@"Accept"] length] == 0) {
        [headerParams removeObjectForKey:@"Accept"];
    }

    // response content type
    NSString *responseContentType;
    if ([headerParams objectForKey:@"Accept"]) {
        responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0];
    }
    else {
        responseContentType = @"";
    }

    // request content type
    NSString *requestContentType = [SystranApiClient selectHeaderContentType:@[]];

    // Authentication setting
    NSArray *authSettings = @[];

    id bodyParam = nil;
    NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init];
    NSMutableDictionary *files = [[NSMutableDictionary alloc] init];

    return [self.apiClient requestWithCompletionBlock: resourcePath
                                               method: @"GET"
                                           pathParams: pathParams
                                          queryParams: queryParams
                                           formParams: formParams
                                                files: files
                                                 body: bodyParam
                                         headerParams: headerParams
                                         authSettings: authSettings
                                   requestContentType: requestContentType
                                  responseContentType: responseContentType
                                         responseType: @"NSURL*"
                                      completionBlock: ^(id data, NSError *error) {

                  completionBlock((NSURL*)data, error);
              }
          ];
}

@end


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:orientation="vertical">

    <View
        android:id="@+id/view"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="@color/cool_green_normal" />

    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <com.google.android.material.appbar.AppBarLayout
            android:id="@+id/appbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <!--标题栏-->
            <include layout="@layout/cool_title" />

            <!--选项卡-->
            <com.google.android.material.tabs.TabLayout
                android:id="@+id/tabLayout"
                android:layout_width="match_parent"
                android:layout_height="42dp"
                android:background="@color/cool_green_normal"
                app:tabIndicatorColor="@android:color/white"
                app:tabMode="fixed"
                app:tabSelectedTextColor="@android:color/white"
                app:tabTextColor="@color/colorBarText" />
        </com.google.android.material.appbar.AppBarLayout>

        <!--包含可滑动的布局内容(RecyclerView,NestedScrollView,不支持ListView,ScrollView)
        必须要设置app:layout_behavior="@string/appbar_scrolling_view_behavior"
        属性来告知CoordinatorLayout该组件是带有滑动行为的组件,
        然后CoordinatorLayout在接受到滑动时会通知AppBarLayout中可滑动的Toolbar可以滑出屏幕-->
        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recyclerView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
            app:layout_behavior="@string/appbar_scrolling_view_behavior" />
    </androidx.coordinatorlayout.widget.CoordinatorLayout>
</LinearLayout>


text:
Task Tree is a CLI tool that helps you keep track of your tasks in a tree structure

## Disclaimer
This project is still in early development, any suggestions, pull requests are more than welcome!
Don't be too surprised if things go wrong!

## Dependencies
- Figlet
- Figlet fonts, there are many fonts readily available for figlet the best place is probably [figlet.org](http://www.figlet.org/fontdb.cgi)
- The default is larry3d.

## Installation

Add this line to your application's Gemfile:

    $ gem install task-tree

## Usage

task-tree

## Development

After checking out the repo, run `bin/setup` to install dependencies. You can also run `bin/console` for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).

## Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/hellola/task-tree.

## License

The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).


text:
<?php

namespace GoogleApi\Contrib\Prediction;

use GoogleApi\Service\Model;

class Image extends Model
{
    public $kind;
    public $description;
    protected $__rawDiskType = '\GoogleApi\Contrib\Prediction\Image\RawDisk';
    protected $__rawDiskDataType = '';
    public $rawDisk;
    public $preferredKernel;
    protected $__diskSnapshotType = '\GoogleApi\Contrib\Prediction\Image\DiskSnapshot';
    protected $__diskSnapshotDataType = '';
    public $diskSnapshot;
    public $sourceType;
    public $creationTimestamp;
    public $id;
    public $selfLink;
    public $name;

    public function setKind($kind)
    {
        $this->kind = $kind;
    }

    public function getKind()
    {
        return $this->kind;
    }

    public function setDescription($description)
    {
        $this->description = $description;
    }

    public function getDescription()
    {
        return $this->description;
    }

    public function setRawDisk(\GoogleApi\Contrib\Prediction\Image\RawDisk $rawDisk)
    {
        $this->rawDisk = $rawDisk;
    }

    public function getRawDisk()
    {
        return $this->rawDisk;
    }

    public function setPreferredKernel($preferredKernel)
    {
        $this->preferredKernel = $preferredKernel;
    }

    public function getPreferredKernel()
    {
        return $this->preferredKernel;
    }

    public function setDiskSnapshot(\GoogleApi\Contrib\Prediction\Image\DiskSnapshot $diskSnapshot)
    {
        $this->diskSnapshot = $diskSnapshot;
    }

    public function getDiskSnapshot()
    {
        return $this->diskSnapshot;
    }

    public function setSourceType($sourceType)
    {
        $this->sourceType = $sourceType;
    }

    public function getSourceType()
    {
        return $this->sourceType;
    }

    public function setCreationTimestamp($creationTimestamp)
    {
        $this->creationTimestamp = $creationTimestamp;
    }

    public function getCreationTimestamp()
    {
        return $this->creationTimestamp;
    }

    public function setId($id)
    {
        $this->id = $id;
    }

    public function getId()
    {
        return $this->id;
    }

    public function setSelfLink($selfLink)
    {
        $this->selfLink = $selfLink;
    }

    public function getSelfLink()
    {
        return $this->selfLink;
    }

    public function setName($name)
    {
        $this->name = $name;
    }

    public function getName()
    {
        return $this->name;
    }
}


text:
import * as React from 'react';
import { makeStyles, Theme, createStyles } from '@material-ui/core/styles';
import Popper from '@material-ui/core/Popper';
// web.cjs is required for IE11 support
import { useSpring, animated } from 'react-spring/web.cjs';

const useStyles = makeStyles((theme: Theme) =>
  createStyles({
    paper: {
      border: '1px solid',
      padding: theme.spacing(1),
      backgroundColor: theme.palette.background.paper,
    },
  }),
);

interface FadeProps {
  children?: React.ReactElement;
  in?: boolean;
  onEnter?: () => {};
  onExited?: () => {};
}

const Fade = React.forwardRef<HTMLDivElement, FadeProps>(function Fade(props, ref) {
  const { in: open, children, onEnter, onExited, ...other } = props;
  const style = useSpring({
    from: { opacity: 0 },
    to: { opacity: open ? 1 : 0 },
    onStart: () => {
      if (open && onEnter) {
        onEnter();
      }
    },
    onRest: () => {
      if (!open && onExited) {
        onExited();
      }
    },
  });

  return (
    <animated.div ref={ref} style={style} {...other}>
      {children}
    </animated.div>
  );
});

export default function SpringPopper() {
  const classes = useStyles();
  const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);

  const handleClick = (event: React.MouseEvent<HTMLElement>) => {
    setAnchorEl(anchorEl ? null : event.currentTarget);
  };

  const open = Boolean(anchorEl);
  const id = open ? 'spring-popper' : undefined;

  return (

      <button aria-describedby={id} type="button" onClick={handleClick}>
        Toggle Popper
      </button>
      <Popper id={id} open={open} anchorEl={anchorEl} transition>
        {({ TransitionProps }) => (
          <Fade {...TransitionProps}>

The content of the Popper.

          </Fade>
        )}
      </Popper>

  );
}


text:
package com.google.gerrit.server.group;

import com.google.gerrit.common.data.GroupDescription;
import com.google.gerrit.extensions.restapi.RestView;
import com.google.gerrit.reviewdb.client.AccountGroup;
import com.google.inject.TypeLiteral;

public class SubgroupResource extends GroupResource {
  public static final TypeLiteral<RestView<SubgroupResource>> SUBGROUP_KIND =
      new TypeLiteral<RestView<SubgroupResource>>() {};

  private final GroupDescription.Basic member;

  public SubgroupResource(GroupResource group, GroupDescription.Basic member) {
    super(group);
    this.member = member;
  }

  public AccountGroup.UUID getMember() {
    return getMemberDescription().getGroupUUID();
  }

  public GroupDescription.Basic getMemberDescription() {
    return member;
  }
}


text:
package views;

import play.templates.JavaExtensions;

/**
 * @author Manuel Bernhardt <bernhardt.manuel@gmail.com>
 */
public class ViewExtensions extends JavaExtensions {

    public static String pluralize(String singular) {
        return !singular.endsWith("y") ? singular + "s" : singular.substring(0, singular.length() - 1) + "ies";
    }

}


text:
#ifndef _CRIS_PAGE_H
#define _CRIS_PAGE_H

#include <arch/page.h>
#include <linux/const.h>

/* PAGE_SHIFT determines the page size */
#define PAGE_SHIFT	13
#define PAGE_SIZE	(_AC(1, UL) << PAGE_SHIFT)
#define PAGE_MASK	(~(PAGE_SIZE-1))

#define clear_page(page)        memset((void *)(page), 0, PAGE_SIZE)
#define copy_page(to,from)      memcpy((void *)(to), (void *)(from), PAGE_SIZE)

#define clear_user_page(page, vaddr, pg)    clear_page(page)
#define copy_user_page(to, from, vaddr, pg) copy_page(to, from)

#define __alloc_zeroed_user_highpage(movableflags, vma, vaddr) \
	alloc_page_vma(GFP_HIGHUSER | __GFP_ZERO | movableflags, vma, vaddr)
#define __HAVE_ARCH_ALLOC_ZEROED_USER_HIGHPAGE

/*
 * These are used to make use of C type-checking..
 */
#ifndef __ASSEMBLY__
typedef struct { unsigned long pte; } pte_t;
typedef struct { unsigned long pgd; } pgd_t;
typedef struct { unsigned long pgprot; } pgprot_t;
typedef struct page *pgtable_t;
#endif

#define pte_val(x)	((x).pte)
#define pgd_val(x)	((x).pgd)
#define pgprot_val(x)	((x).pgprot)

#define __pte(x)	((pte_t) { (x) } )
#define __pgd(x)	((pgd_t) { (x) } )
#define __pgprot(x)	((pgprot_t) { (x) } )

/* On CRIS the PFN numbers doesn't start at 0 so we have to compensate */
/* for that before indexing into the page table starting at mem_map    */
#define ARCH_PFN_OFFSET		(PAGE_OFFSET >> PAGE_SHIFT)
#define pfn_valid(pfn)		(((pfn) - (PAGE_OFFSET >> PAGE_SHIFT)) < max_mapnr)

/* to index into the page map. our pages all start at physical addr PAGE_OFFSET so
 * we can let the map start there. notice that we subtract PAGE_OFFSET because
 * we start our mem_map there - in other ports they map mem_map physically and
 * use __pa instead. in our system both the physical and virtual address of DRAM
 * is too high to let mem_map start at 0, so we do it this way instead (similar
 * to arm and m68k I think)
 */

#define virt_to_page(kaddr)    (mem_map + (((unsigned long)(kaddr) - PAGE_OFFSET) >> PAGE_SHIFT))
#define VALID_PAGE(page)       (((page) - mem_map) < max_mapnr)
#define virt_addr_valid(kaddr)	pfn_valid((unsigned)(kaddr) >> PAGE_SHIFT)

/* convert a page (based on mem_map and forward) to a physical address
 * do this by figuring out the virtual address and then use __pa
 */

#define page_to_phys(page)     __pa((((page) - mem_map) << PAGE_SHIFT) + PAGE_OFFSET)

#ifndef __ASSEMBLY__

#endif /* __ASSEMBLY__ */

#define VM_DATA_DEFAULT_FLAGS	(VM_READ | VM_WRITE | VM_EXEC | \
				 VM_MAYREAD | VM_MAYWRITE | VM_MAYEXEC)

#include <asm-generic/memory_model.h>
#include <asm-generic/getorder.h>

#endif /* _CRIS_PAGE_H */


text:
title: Kristan McGachey
gender: female
graduated: 2011
submitted: false
---


text:
describe('query string', function(){
	var module = window.__module, http;

	beforeAll(function(){
		http = window.__getHttp();
	});

	it('matches by query string', function(done){
		http.get('github.com/user/search?id=1&city=ny%26ny').then(function(response){
			expect(response.data.name).toBe('Carlos QS');
			done();
		});
	});

	it('query string is optional in the mock config', function(done){
		http.get('github.com/user/search?id=2&city=another').then(function(response){
			expect(response.data.name).toBe('Whatever you search');
			done();
		});
	});
});


text:
package com.taobao.api;

import com.taobao.api.domain.AddressResult;
import com.taobao.api.domain.LogisticsCompany;
import com.taobao.api.domain.LogisticsPartner;
import com.taobao.api.request.*;
import com.taobao.api.response.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class LogisticsApi {
    private static final Logger log = LoggerFactory.getLogger(LogisticsApi.class);

    private static final String LOGISTICS_COMPANY_FIELDS = "id,code,name,reg_mail_no";

    private ImprovedTaobaoClient taobaoClient;

    public LogisticsApi(ImprovedTaobaoClient taobaoClient) {
        this.taobaoClient = taobaoClient;
    }

    /**
     * 查询淘宝网合作的物流公司信息
     *
     * @return
     */
    public List<LogisticsCompany> getLogisticsCompanies() {
        LogisticsCompaniesGetRequest request = new LogisticsCompaniesGetRequest();
        request.setFields(LOGISTICS_COMPANY_FIELDS);
        LogisticsCompaniesGetResponse response = taobaoClient.execute(request);
        return response.getLogisticsCompanies();
    }

    public List<LogisticsPartner> getLogisticsPartners(String serviceType) {
        LogisticsPartnersGetRequest req = new LogisticsPartnersGetRequest();
        req.setServiceType(serviceType);
        req.setIsNeedCarriage(false);
        LogisticsPartnersGetResponse response = taobaoClient.execute(req);
        return response.getLogisticsPartners();
    }

    public List<AddressResult> searchAddresses(String session) {
        LogisticsAddressSearchRequest request = new LogisticsAddressSearchRequest();
        LogisticsAddressSearchResponse response = taobaoClient.execute(request, session);
        return response.getAddresses();
    }

    /**
     * 自己联系物流(线下物流)发货
     *
     * @param tid                  订单id
     * @param waybillNo            快递单号
     * @param logisticsCompanyCode 物流公司代码
     */
    public void offlineSend(Long tid, String waybillNo, String logisticsCompanyCode, String session) {
        if(log.isDebugEnabled()) {
            log.debug("offline send tid: " + tid + ", waybill no: " + waybillNo + ", logistics company code: " + logisticsCompanyCode);
        }

        LogisticsOfflineSendRequest request = new LogisticsOfflineSendRequest();
        request.setTid(tid);
        request.setOutSid(waybillNo);
        request.setCompanyCode(logisticsCompanyCode);

        LogisticsOfflineSendResponse response = taobaoClient.execute(request, session);
        if(!response.isSuccess()) {
            throw new TaobaoApiException("", "fail to ship order by offline send api : " + tid);
        }
    }

    /**
     * 在线订单发货处理(支持货到付款)
     *
     * @param tid                  订单id
     * @param waybillNo            快递单号
     * @param logisticsCompanyCode 物流公司代码
     */
    public void onlineSend(Long tid, String waybillNo, String logisticsCompanyCode, String session) {
        if(log.isDebugEnabled()) {
            log.debug("online send tid: " + tid + ", waybill no: " + waybillNo + ", logistics company code: " + logisticsCompanyCode);
        }
        LogisticsOnlineSendRequest request = new LogisticsOnlineSendRequest();
        request.setTid(tid);
        request.setOutSid(waybillNo);
        request.setCompanyCode(logisticsCompanyCode);

        LogisticsOnlineSendResponse response = taobaoClient.execute(request, session);
        if(!response.isSuccess()) {
            throw new TaobaoApiException("", "fail to ship order by online send api : " + tid);
        }
    }

    /**
     * 无需物流(虚拟)发货处理
     *
     * @param tid 订单id
     */
    public void dummySend(Long tid, String session) {
        log.debug("dummy send tid: {}", tid);
        LogisticsDummySendRequest request = new LogisticsDummySendRequest();
        request.setTid(tid);
        LogisticsDummySendResponse response = taobaoClient.execute(request, session);
        if(!response.isSuccess()) {
            throw new TaobaoApiException("", "fail to ship order by dummy send api : " + tid);
        }
    }
}


text:
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using FluentAssertions;
using Moq;
using WireMock.Handlers;
using WireMock.Models;
using WireMock.ResponseBuilders;
using WireMock.Settings;
using WireMock.Types;
using WireMock.Util;
using Xunit;

namespace WireMock.Net.Tests.ResponseBuilders
{
    public class ResponseWithCallbackTests
    {
        private const string ClientIp = "::1";

        private readonly Mock<IFileSystemHandler> _filesystemHandlerMock;
        private readonly WireMockServerSettings _settings = new WireMockServerSettings();

        public ResponseWithCallbackTests()
        {
            _filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
            _filesystemHandlerMock.Setup(fs => fs.ReadResponseBodyAsString(It.IsAny<string>())).Returns("abc");

            _settings.FileSystemHandler = _filesystemHandlerMock.Object;
        }

        [Fact]
        public async Task Response_WithCallbackAsync()
        {
            // Assign
            var requestMessage = new RequestMessage(new UrlDetails("http://localhost/foo"), "GET", "::1");
            var responseBuilder = Response.Create()
                .WithCallback(async request =>
                {
                    await Task.Delay(1);

                    return new ResponseMessage
                    {
                        BodyData = new BodyData
                        {
                            DetectedBodyType = BodyType.String,
                            BodyAsString = request.Path + "Bar"
                        },
                        StatusCode = 302
                    };
                });

            // Act
            var response = await responseBuilder.ProvideResponseAsync(requestMessage, _settings).ConfigureAwait(false);

            // Assert
            response.Message.BodyData.BodyAsString.Should().Be("/fooBar");
            response.Message.StatusCode.Should().Be(302);
        }

        [Fact]
        public async Task Response_WithCallback()
        {
            // Assign
            var requestMessage = new RequestMessage(new UrlDetails("http://localhost/foo"), "GET", "::1");
            var responseBuilder = Response.Create()
                .WithCallback(request => new ResponseMessage
                {
                    BodyData = new BodyData
                    {
                        DetectedBodyType = BodyType.String,
                        BodyAsString = request.Path + "Bar"
                    },
                    StatusCode = 302
                });

            // Act
            var response = await responseBuilder.ProvideResponseAsync(requestMessage, _settings).ConfigureAwait(false);

            // Assert
            response.Message.BodyData.BodyAsString.Should().Be("/fooBar");
            response.Message.StatusCode.Should().Be(302);
        }

        [Fact]
        public async Task Response_WithCallback_ShouldUseStatusCodeAndHeaderInTheCallback()
        {
            // Assign
            var header = "X-UserId";
            var requestMessage = new RequestMessage(new UrlDetails("http://localhost/foo"), "GET", "::1");
            var responseBuilder = Response.Create()
                .WithCallback(request => new ResponseMessage
                {
                    BodyData = new BodyData
                    {
                        DetectedBodyType = BodyType.String,
                        BodyAsString = request.Path + "Bar"
                    },
                    StatusCode = HttpStatusCode.Accepted,
                    Headers = new Dictionary<string, WireMockList<string>>
                    {
                        { header, new WireMockList<string>("Stef") }
                    }
                });

            // Act
            var response = await responseBuilder.ProvideResponseAsync(requestMessage, _settings).ConfigureAwait(false);

            // Assert
            response.Message.BodyData.BodyAsString.Should().Be("/fooBar");
            response.Message.StatusCode.Should().Be(HttpStatusCode.Accepted);
            response.Message.Headers[header].Should().ContainSingle("Stef");
        }

        [Fact]
        public async Task Response_WithCallback_And_Additional_WithStatusCode_And_WithHeader_ShouldUseAdditional()
        {
            // Assign
            var header = "X-UserId";
            var requestMessage = new RequestMessage(new UrlDetails("http://localhost/foo"), "GET", "::1");
            var responseBuilder = Response.Create()
                .WithCallback(request => new ResponseMessage
                {
                    BodyData = new BodyData
                    {
                        DetectedBodyType = BodyType.String,
                        BodyAsString = request.Path + "Bar"
                    },
                    StatusCode = HttpStatusCode.NotFound,
                    Headers = new Dictionary<string, WireMockList<string>>
                    {
                        { header, new WireMockList<string>("NA") }
                    }
                })
                .WithStatusCode(HttpStatusCode.Accepted)
                .WithHeader(header, "Stef");

            // Act
            var response = await responseBuilder.ProvideResponseAsync(requestMessage, _settings).ConfigureAwait(false);

            // Assert
            response.Message.BodyData.BodyAsString.Should().Be("/fooBar");
            response.Message.StatusCode.Should().Be((int) HttpStatusCode.Accepted);
            response.Message.Headers[header].Should().ContainSingle("Stef");
        }

        [Fact]
        public async Task Response_WithCallback_And_UseTransformer_Is_True()
        {
            // Assign
            var requestMessage = new RequestMessage(new UrlDetails("http://localhost/foo"), "GET", "::1");
            var responseBuilder = Response.Create()
                .WithCallback(request => new ResponseMessage
                {
                    BodyData = new BodyData
                    {
                        DetectedBodyType = BodyType.String,
                        BodyAsString = "{{request.Path}}Bar"
                    },
                    StatusCode = 302
                })
                .WithTransformer();

            // Act
            var response = await responseBuilder.ProvideResponseAsync(requestMessage, _settings).ConfigureAwait(false);

            // Assert
            response.Message.BodyData.BodyAsString.Should().Be("/fooBar");
            response.Message.StatusCode.Should().Be(302);
        }
    }
}


text:
package com.intellij.ui;

import com.intellij.openapi.ui.FixedSizeButton;
import com.intellij.openapi.wm.IdeFocusManager;

import javax.swing.*;
import javax.swing.table.TableCellEditor;
import java.awt.*;
import java.awt.event.*;
import java.io.Serializable;
import java.util.EventObject;

public class TableCellEditorWithButton extends AbstractCellEditor implements TableCellEditor {

  protected final MyComponent myComponent;
  protected final EditorDelegate delegate;
  protected final int myClickCountToStart = 1;

  public TableCellEditorWithButton() {
    myComponent = new MyComponent();
    delegate = new EditorDelegate() {
      public void setValue(Object value) {
        myComponent.getTextField().setText((value != null) ? value.toString() : "");
      }

      public Object getCellEditorValue() {
        return myComponent.getTextField().getText();
      }
    };
    myComponent.getTextField().addActionListener(delegate);
  }

  public JButton getButton() {
    return myComponent.getButton();
  }

  public JTextField getTextField() {
    return myComponent.getTextField();
  }

  public Object getCellEditorValue() {
    return delegate.getCellEditorValue();
  }

  public boolean isCellEditable(EventObject anEvent) {
    return delegate.isCellEditable(anEvent);
  }

  public boolean shouldSelectCell(EventObject anEvent) {
    return delegate.shouldSelectCell(anEvent);
  }

  public boolean stopCellEditing() {
    return delegate.stopCellEditing();
  }

  public void cancelCellEditing() {
    delegate.cancelCellEditing();
  }

  public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
    delegate.setValue(value);
    return myComponent;
  }

  protected class EditorDelegate implements ActionListener, ItemListener, Serializable {

    protected Object value;

    public Object getCellEditorValue() {
      return value;
    }

    public void setValue(Object value) {
      this.value = value;
    }

    public boolean isCellEditable(EventObject anEvent) {
      if (anEvent instanceof MouseEvent) {
        return ((MouseEvent)anEvent).getClickCount() >= myClickCountToStart;
      }
      return true;
    }

    public boolean shouldSelectCell(EventObject anEvent) {
      return true;
    }

    public boolean stopCellEditing() {
      fireEditingStopped();
      return true;
    }

    public void cancelCellEditing() {
      fireEditingCanceled();
    }

    public void actionPerformed(ActionEvent e) {
      TableCellEditorWithButton.this.stopCellEditing();
    }

    public void itemStateChanged(ItemEvent e) {
      TableCellEditorWithButton.this.stopCellEditing();
    }
  }

  private class MyComponent extends JPanel {
    private final JTextField myTextField;
    private final FixedSizeButton myButton;

    public MyComponent() {
      super(new GridBagLayout());

      myTextField = new JTextField();
      myButton = new FixedSizeButton(myTextField);

      add(myTextField, new GridBagConstraints(0, 0, 1, 1, 1, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
      add(myButton, new GridBagConstraints(1, 0, 1, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
    }

    public FixedSizeButton getButton() {
      return myButton;
    }

    public JTextField getTextField() {
      return myTextField;
    }

    public boolean requestDefaultFocus() {
      IdeFocusManager.getGlobalInstance().doForceFocusWhenFocusSettlesDown(myTextField);
      return true;
    }
  }
}


text:
ACCEPTED

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

#### Published in
null

#### Original name
Sphaeria caprifoliorum Desm., 1840

### Remarks
null


text:
package org.mapdb;

import org.junit.Test;

import java.io.Serializable;
import java.util.HashSet;

import static org.junit.Assert.assertTrue;

public class Issue164Test {

    public static class Scenario implements Serializable {
        private static final long serialVersionUID = 1L;
        protected String id = null;
        protected String brief = null;
        protected String headNodeId = null;
        protected HashSet nodeIdSet = null;
        public Scenario() {
            id = Long.toHexString(System.nanoTime());
            brief = null;
            headNodeId = null;
            nodeIdSet = null;
        }
        public void setId(String arg_id) {
            synchronized(this) {
                id = arg_id;
            }
        }
        public String getId() {
            synchronized(this) {
                return id;
            }
        }
        public void setBrief(String arg_brief) {
            synchronized(this) {
                brief = arg_brief;
            }
        }
        public String getBrief() {
            synchronized(this) {
                return brief;
            }
        }
        public String getHeadNodeId() {
            synchronized(this) {
                return headNodeId;
            }
        }
        public void setHeadNodeId(String arg_header_node_id) {
            synchronized(this) {
                headNodeId = arg_header_node_id;
                if (!nodeIdSet.contains(arg_header_node_id))
                    nodeIdSet.add(arg_header_node_id);
            }
        }
        public void addConversationNodeId(String arg_conversation_node_id) throws Exception {
            synchronized(this) {
                if (headNodeId == null) {
                    headNodeId = arg_conversation_node_id;
                    nodeIdSet.add(arg_conversation_node_id);
                }
                else
                    throw new Exception();
            } // of synchronized(this)
        }
        public void removeConversationNodeId(String arg_conversation_node_id) {
            synchronized(this) {
                if (headNodeId != null) {
                    nodeIdSet.remove(arg_conversation_node_id);
                    if (arg_conversation_node_id.equals(headNodeId))
                        headNodeId = null; // the set is empty now
                }
            } // of synchronized(this)
        }
    }

    @Test
    public void main() {
        int rc = 0;
        BTreeMap map=null;
        try {
            DB db = DBMaker.memoryDB()
                    .closeOnJvmShutdown()
                    .make();
// the following test shows that the db is opened if it always exists
            map = db.treeMap("test");
            if (!map.containsKey("t1")) {
                map.put("t1", new Scenario());
                db.commit();
            }
            rc = 1;
        } catch(Exception ex) {
            rc = -1;
        }
        assertTrue(map.get("t1")!=null);
        assertTrue(rc > 0);

    }
}


text:
from .service import ServiceStubber

class KeyPairStubber(ServiceStubber):

    client_service = "ec2"

    def add_describe_keypairs_empty_response_by_name(self):
        return self.add_response(
            "describe_key_pairs",
            service_response={"KeyPairs": []},
            expected_params={"KeyNames": [self.resource.name]},
        )

    def add_describe_keypairs_one_response_by_name(self):
        return self.add_response(
            "describe_key_pairs",
            service_response={"KeyPairs": [{"KeyName": self.resource.name}]},
            expected_params={"KeyNames": [self.resource.name]},
        )

    def add_import_key_pair(self, public_key):
        return self.add_response(
            "import_key_pair",
            service_response={"KeyName": self.resource.name},
            expected_params={
                "KeyName": self.resource.name,
                "PublicKeyMaterial": public_key,
            },
        )

    def add_delete_key_pair(self):
        return self.add_response(
            "delete_key_pair",
            service_response={},
            expected_params={"KeyName": self.resource.name},
        )


text:
require 'spec_helper'

describe Locomotive::Steam::AuthService do

  let(:site)            { instance_double('CurrentSite') }
  let(:entries)         { instance_double('ContentService', locale: 'en') }
  let(:emails)          { instance_double('EmailService') }
  let(:service)         { described_class.new(site, entries, emails) }
  let(:liquid_context)  { {} }

  let(:default_auth_options) { {
    type:               'accounts',
    id_field:           'email',
    id:                 'john@doe.net',
    password_field:     'password',
    password:           'easyone',
    reset_password_url: '/reset-password',
    reset_token:        '42',
    from:               'contact@acme.org',
    subject:            'Instructions for changing your password',
    email_handle:       'reset-password-email',
    smtp:               {}
  } }

  let(:auth_options) { instance_double('AuthOptions', default_auth_options) }

  describe '#sign_up' do

    let(:errors)                { [] }
    let(:entry_attributes)      { { fullname: 'Chris Cornell', band: 'Soundgarden', email: 'chris@soundgarden.band', password: 'easyone', password_confirmation:  'easyone' } }
    let(:entry)                 { instance_double('Account', errors: errors) }
    let(:email_disabled)        { false }
    let(:default_auth_options)  { {
      type:                   'accounts',
      id_field:               'email',
      id:                     'chris@soundgarden.band',
      password_field:         'password',
      from:                   'no-reply@acme.org',
      subject:                'Your account has been created',
      email_handle:           'account-created',
      smtp:                   {},
      disable_email:          email_disabled,
      entry:                  entry_attributes
    } }

    subject { service.sign_up(auth_options, liquid_context) }

    context 'the entry has errors' do

      let(:errors) { [:invalid_password] }

      it 'returns invalid_entry and the entry' do
        expect(entries).to receive(:create).with('accounts', {
          fullname:               'Chris Cornell',
          band:                   'Soundgarden',
          email:                  'chris@soundgarden.band',
          password:               'easyone',
          password_confirmation:  'easyone'
        }).and_return(entry)
        is_expected.to eq [:invalid_entry, entry]
      end

    end

    it "returns both :created and the entry if it was able to create it (+ send email)" do
      expect(entries).to receive(:create).with('accounts', {
        fullname:               'Chris Cornell',
        band:                   'Soundgarden',
        email:                  'chris@soundgarden.band',
        password:               'easyone',
        password_confirmation:  'easyone'
      }).and_return(entry)
      expect(emails).to receive(:send_email).with({
        from:         'no-reply@acme.org',
        to:           'chris@soundgarden.band',
        subject:      'Your account has been created',
        page_handle:  'account-created',
        smtp:         {} }, liquid_context)
      is_expected.to eq [:entry_created, entry]
    end

    context 'email is disabled' do

      let(:email_disabled) { true }

      it "doesn't send a notification email" do
        allow(entries).to receive(:create).and_return(entry)
        expect(emails).to_not receive(:send_email)
        is_expected.to eq [:entry_created, entry]
      end

    end

    describe Locomotive::Steam::AuthService::ContentEntryAuth do

      let(:repository)  { instance_double('FieldRepository', all: nil, required: []) }
      let(:type)        { instance_double('ContentType', slug: 'accounts', label_field_name: :title, fields: repository, fields_by_name: {}) }
      let(:attributes)  { { password: 'easyone', password_confirmation: 'easyone' } }
      let(:content_entry) { Locomotive::Steam::ContentEntry.new(attributes).tap { |e| e.content_type = type } }

      before { content_entry.extend(described_class) }

      describe '#valid?' do

        before { content_entry[:_password_field] = 'password' }

        subject { content_entry.valid? }

        it { is_expected.to eq true }

        it 'encrypts the password since there is no error' do
          expect(BCrypt::Password).to receive(:create).with('easyone').and_return('42a')
          subject
          expect(content_entry[:password_hash]).to eq '42a'
          expect(content_entry.attributes[:password]).to eq nil
          expect(content_entry.attributes[:password_confirmation]).to eq nil
        end

        context 'the password is less than 6 characters' do

          let(:attributes) { { password: 'easy', password_confirmation: 'easy' } }

          it 'returns false' do
            is_expected.to eq false
            expect(content_entry.errors[:password]).to eq(['is too short (minimum is 6 characters)'])
          end

        end

        context "the password doesn't match the confirmation" do

          let(:type)        { instance_double('ContentType', slug: 'accounts', label_field_name: :title, fields: repository, fields_by_name: {}, field_label_of: 'password') }
          let(:attributes)  { { password: 'easyone', password_confirmation: 'oneeasy' } }

          it 'returns false' do
            is_expected.to eq false
            expect(content_entry.errors[:password_confirmation]).to eq(["doesn't match password"])
          end

        end

      end

    end

  end

  describe '#sign_in' do

    subject { service.sign_in(auth_options, nil) }

    it 'returns :wrong_credentials if no entry matches the email' do
      expect(entries).to receive(:all).with('accounts', { 'email' => 'john@doe.net' }).and_return([])
      is_expected.to eq :wrong_credentials
    end

    it "returns :wrong_credentials if the password doesn't the entry's password" do
      entry = build_account('fakeone')
      expect(entries).to receive(:all).with('accounts', { 'email' => 'john@doe.net' }).and_return([entry])
      is_expected.to eq :wrong_credentials
    end

    it "returns :wrong_credentials if the password is nil" do
      entry = instance_double('Account', password: nil)
      expect(entries).to receive(:all).with('accounts', { 'email' => 'john@doe.net' }).and_return([entry])
      is_expected.to eq :wrong_credentials
    end

    it "returns :wrong_credentials if the password is blank" do
      entry = instance_double('Account', password: '')
      expect(entries).to receive(:all).with('accounts', { 'email' => 'john@doe.net' }).and_return([entry])
      is_expected.to eq :wrong_credentials
    end

    it "returns both :signed_in and the entry if the password matches the entry's password" do
      entry = build_account('easyone')
      expect(entries).to receive(:all).with('accounts', { 'email' => 'john@doe.net' }).and_return([entry])
      is_expected.to eq [:signed_in, entry]
    end

  end

  describe '#forgot_password' do

    subject { service.forgot_password(auth_options, liquid_context) }

    it 'returns :wrong_email if no entry matches the email' do
      expect(entries).to receive(:all).with('accounts', { 'email' => 'john@doe.net' }).and_return([])
      is_expected.to eq :wrong_email
    end

    it 'sends the instructions by email if an entry matches the email' do
      entry = build_account('easyone', '42a')
      expect(entries).to receive(:all).with('accounts', { 'email' => 'john@doe.net' }).and_return([entry])
      expect(entries).to receive(:update_decorated_entry)
      expect(emails).to receive(:send_email).with({
        from:         'contact@acme.org',
        to:           'john@doe.net',
        subject:      'Instructions for changing your password',
        page_handle:  'reset-password-email',
        smtp:         {} }, liquid_context)
      is_expected.to eq :reset_password_instructions_sent
      expect(liquid_context['reset_password_url']).to eq '/reset-password?auth_reset_token=42a'
    end

    context 'no email template' do

      let(:_auth_options) { default_auth_options.merge(email_handle: nil) }
      let(:auth_options)  { instance_double('AuthOptions', _auth_options) }

      it 'also sends the instructions by email with a default email template' do
        entry = build_account('easyone', '42a')
        expect(entries).to receive(:all).with('accounts', { 'email' => 'john@doe.net' }).and_return([entry])
        expect(entries).to receive(:update_decorated_entry)
        expect(emails).to receive(:send_email).with({
          from:         'contact@acme.org',
          to:           'john@doe.net',
          subject:      'Instructions for changing your password',
          body:         (<<-EMAIL
Hi,
To reset your password please follow the link below: /reset-password?auth_reset_token=42a.
Thanks!
EMAIL
          ),
          smtp:         {} }, liquid_context)
        is_expected.to eq :reset_password_instructions_sent
        expect(liquid_context['reset_password_url']).to eq '/reset-password?auth_reset_token=42a'
      end

    end

  end

  describe '#reset_password' do

    let(:request) { instance_double('Request') }
    let(:_auth_options) { default_auth_options }
    let(:auth_options) { instance_double('AuthOptions', _auth_options) }

    subject { service.reset_password(auth_options, request) }

    context 'no auth token' do

      let(:_auth_options) { default_auth_options.merge({ reset_token: '' }) }
      it { is_expected.to eq :invalid_token }

    end

    context 'password too short' do

      let(:_auth_options) { default_auth_options.merge({ password: '' }) }
      it { is_expected.to eq :password_too_short }

    end

    context 'expired auth token' do

      it 'returns :invalid_token' do
        entry = instance_double('Account', :[] => (Time.zone.now - 3.hours).iso8601)
        expect(entries).to receive(:all).with('accounts', { '_auth_reset_token' => '42' }).and_return([entry])
        is_expected.to eq :invalid_token
      end

    end

    context 'valid auth token and password' do

      it 'returns :password_reset and entry' do
        entry = instance_double('Account', :[] => (Time.zone.now - 1.hours).iso8601)
        expect(entries).to receive(:all).with('accounts', { '_auth_reset_token' => '42' }).and_return([entry])
        expect(BCrypt::Password).to receive(:create).with('easyone').and_return('hashedeasyone')
        expect(entries).to receive(:update_decorated_entry).with(entry, { 'password_hash' => 'hashedeasyone', '_auth_reset_token' => nil, '_auth_reset_sent_at' => nil })
        is_expected.to eq [:password_reset, entry]
      end

    end

  end

  def build_account(password = 'easyone', reset_token = nil)
    encrypted_password = BCrypt::Password.create(password)
    entry = instance_double('Account', password: BCrypt::Password.new(encrypted_password))
    allow(entry).to receive(:[]).with(:password_hash).and_return(encrypted_password)
    allow(entry).to receive(:[]).with('_auth_reset_token').and_return(reset_token)
    entry
  end

end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
 ~  Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 ~
 ~  WSO2 Inc. licenses this file to you 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.
-->
<template name="deleteMessages" xmlns="http://ws.apache.org/ns/synapse">
    <parameter name="id" description="The ID of the message to delete"/>
    <sequence>
        <property name="uri.var.id" expression="$func:id"/>
        <call>
            <endpoint>
                <http method="delete"
                      uri-template="{+uri.var.gmail.apiUrl}/{+uri.var.gmail.apiVersion}/users/{+uri.var.gmail.userId}/messages/{+uri.var.id}"/>
            </endpoint>
        </call>
        <!-- Remove response custom header information -->
        <header name="x-li-format" scope="transport" action="remove"/>
        <header name="X-LI-UUID" scope="transport" action="remove"/>
        <header name="X-Li-Pop" scope="transport" action="remove"/>
        <header name="X-Li-Fabric" scope="transport" action="remove"/>
        <header name="x-li-request-id" scope="transport" action="remove"/>
    </sequence>
</template>