text:
/**************************************************************************
 * FILE NAME
 *
 *       platform.c
 *
 * DESCRIPTION
 *
 *       This file is the Implementation of IPC hardware layer interface
 *       for Xilinx Zynq ZC702EVK platform.
 *
 **************************************************************************/

#include <string.h>
#include <errno.h>
#include <openamp/hil.h>
#include <metal/alloc.h>
#include <metal/irq.h>
#include <metal/atomic.h>

/* ------------------------- Macros --------------------------*/
#define SCUGIC_PERIPH_BASE      	   0xF8F00000
#define SCUGIC_DIST_BASE        	   (SCUGIC_PERIPH_BASE + 0x00001000)
#define ESAL_DP_SLCR_BASE                  0xF8000000
#define GIC_DIST_SOFTINT                   0xF00
#define GIC_SFI_TRIG_CPU_MASK              0x00FF0000
#define GIC_SFI_TRIG_SATT_MASK             0x00008000
#define GIC_SFI_TRIG_INTID_MASK            0x0000000F
#define GIC_CPU_ID_BASE                    (1 << 4)
#define A9_CPU_SLCR_RESET_CTRL             0x244
#define A9_CPU_SLCR_CLK_STOP               (1 << 4)
#define A9_CPU_SLCR_RST                    (1 << 0)

#define unlock_slcr()                       HIL_MEM_WRITE32(ESAL_DP_SLCR_BASE + 0x08, 0xDF0DDF0D)
#define lock_slcr()                         HIL_MEM_WRITE32(ESAL_DP_SLCR_BASE + 0x04, 0x767B767B)

/* L2Cpl310 L2 cache controller base address. */
#define         HIL_PL130_BASE              0xF8F02000

/********************/
/* Register offsets */
/********************/

#define         HIL_PL130_INVALLINE         0x770
#define         HIL_PL130_CLEANINVLINE      0x7F0

#define         HIL_PA_SBZ_MASK             ~(HIL_CACHE_LINE_SIZE - 1UL)
#define         HIL_CACHE_LINE_SIZE         32
#define         HIL_CACHE_INV_ALL_WAYS      0xFF
#define         HIL_CACHE_UNLOCK_ALL_WAYS   0xFFFF0000
#define         HIL_CACHE_CLEAR_INT         0x1FF

/* Memory attributes */
#define NORM_NONCACHE 0x11DE2 	/* Normal Non-cacheable */
#define STRONG_ORDERED 0xC02	/* Strongly ordered */
#define DEVICE_MEMORY 0xC06	/* Device memory */
#define RESERVED 0x0		/* reserved memory */

#define HIL_DEV_NAME_PREFIX "hil-dev."

#define _rproc_wait() asm volatile("wfi")

/*--------------------------- Declare Functions ------------------------ */
static int _enable_interrupt(struct proc_intr *intr);
static void _notify(struct hil_proc *proc, struct proc_intr *intr_info);
static int _boot_cpu(struct hil_proc *proc, unsigned int load_addr);
static void _shutdown_cpu(struct hil_proc *proc);
static int _poll(struct hil_proc *proc, int nonblock);
static int _initialize(struct hil_proc *proc);
static void _release(struct hil_proc *proc);
static int _ipi_handler(int vect_id, void *data);
static struct metal_io_region* _alloc_shm(struct hil_proc *proc,
			metal_phys_addr_t pa,
			size_t size,
			struct metal_device **dev);
static void _release_shm(struct hil_proc *proc,
			struct metal_device *dev,
			struct metal_io_region *io);

/*--------------------------- Globals ---------------------------------- */
struct hil_platform_ops zynq_a9_proc_ops = {
	.enable_interrupt = _enable_interrupt,
	.notify           = _notify,
	.boot_cpu         = _boot_cpu,
	.shutdown_cpu     = _shutdown_cpu,
	.poll             = _poll,
	.alloc_shm = _alloc_shm,
	.release_shm = _release_shm,
	.initialize = _initialize,
	.release = _release,
};

struct hil_mem_device {
	struct metal_device device;
	char name[64];
	metal_phys_addr_t pa;
};

static metal_phys_addr_t git_dist_base_addr = SCUGIC_DIST_BASE;
static struct metal_io_region gic_dist_io = {
	(void *)SCUGIC_DIST_BASE,
	&git_dist_base_addr,
	0x1000,
	(sizeof(metal_phys_addr_t) << 3),
	(metal_phys_addr_t)(-1),
	0,
	{NULL},
};

//volatile unsigned int ipi_counter = 0;
//volatile unsigned int enableirq_counter = 0;

int _ipi_handler(int vect_id, void *data)
{
	struct proc_intr *intr_info = data;

	(void) vect_id;

	atomic_flag_clear((atomic_uint *)&(intr_info->data));

	//ipi_counter++;
	return 0;
}

static int _enable_interrupt(struct proc_intr *intr)
{
	//enableirq_counter++;
	/* Register ISR */
	metal_irq_register(intr->vect_id, _ipi_handler,
			intr->dev, intr);

	/* Enable the interrupts */
	metal_irq_enable(intr->vect_id);

	/* FIXME: This is a workaround for Zynq. As Linux is possible
	 * to have already generate the soft IRQ
	 */
	atomic_flag_clear((atomic_uint *)&(intr->data));
	return 0;
}

static void _notify(struct hil_proc *proc, struct proc_intr *intr_info)
{
	unsigned long mask = 0;

	mask = ((1 << (GIC_CPU_ID_BASE + proc->cpu_id)) | (intr_info->vect_id))
	    & (GIC_SFI_TRIG_CPU_MASK | GIC_SFI_TRIG_INTID_MASK);

	/* Trigger IPI */
	metal_io_write32(&gic_dist_io, GIC_DIST_SOFTINT, mask);
}

static int _poll(struct hil_proc *proc, int nonblock)
{
	struct proc_vring *vring;
	unsigned int flags;
	struct proc_intr *intr_info;
	int i = 0;
	int kicked = 0;

	while(1) {
		vring = &proc->vdev.vring_info[i];
		intr_info = &(vring->intr_info);
		flags = metal_irq_save_disable();
		if (!(atomic_flag_test_and_set(
			(atomic_uint *)&(intr_info->data)))) {
			metal_irq_restore_enable(flags);
			virtqueue_notification(vring->vq);
			kicked = 1;
			if (i)
				return 0;
			i++;
		} else if (!i) {
			metal_irq_restore_enable(flags);
			i++;
		} else {
			if (kicked) {
				metal_irq_restore_enable(flags);
				return 0;
			} else if (nonblock) {
				metal_irq_restore_enable(flags);
				return -EAGAIN;
			} else {
				_rproc_wait();
				metal_irq_restore_enable(flags);
				i--;
				continue;
			}
		}
	}
}

extern char zynq_trampoline;
extern char zynq_trampoline_jump;
extern char zynq_trampoline_end;

static int _boot_cpu(struct hil_proc *proc, unsigned int load_addr)
{
	/* FIXME: Will need to add the boot_cpu implementation back */
#if 0
	unsigned int reg;
	unsigned int tramp_size;
	unsigned int tramp_addr = 0;

	if (load_addr) {
		tramp_size = zynq_trampoline_end - zynq_trampoline;
		if ((load_addr < tramp_size) || (load_addr & 0x3)) {
			return -1;
		}

		tramp_size = &zynq_trampoline_jump - &zynq_trampoline;

		/*
		 * Trampoline code is copied to address 0 from where remote core is expected to
		 * fetch first instruction after reset.If master is using the address 0 then
		 * this mem copy will screwed the system. It is user responsibility to not
		 * copy trampoline code in such cases.
		 *
		 */
		memcpy((char *)tramp_addr, &zynq_trampoline, tramp_size);
		/* Write image address at the word reserved at the trampoline end */
		HIL_MEM_WRITE32((char *)(tramp_addr + tramp_size), load_addr);
	}

	unlock_slcr();

	reg = HIL_MEM_READ32(ESAL_DP_SLCR_BASE + A9_CPU_SLCR_RESET_CTRL);
	reg &= ~(A9_CPU_SLCR_CLK_STOP << cpu_id);
	HIL_MEM_WRITE32(ESAL_DP_SLCR_BASE + A9_CPU_SLCR_RESET_CTRL, reg);
	/* De-assert reset signal and start clock to start the core */
	reg &= ~(A9_CPU_SLCR_RST << cpu_id);
	HIL_MEM_WRITE32(ESAL_DP_SLCR_BASE + A9_CPU_SLCR_RESET_CTRL, reg);

	lock_slcr();

#else
	(void)proc;
	(void)load_addr;
#endif
	return 0;
}

static void _shutdown_cpu(struct hil_proc *proc)
{
	/* FIXME: Will need to add the shutdown CPU implementation back */
#if 0
	unsigned int reg;

	unlock_slcr();

	reg = HIL_MEM_READ32(ESAL_DP_SLCR_BASE + A9_CPU_SLCR_RESET_CTRL);
	/* Assert reset signal and stop clock to halt the core */
	reg |= (A9_CPU_SLCR_CLK_STOP | A9_CPU_SLCR_RST) << cpu_id;
	HIL_MEM_WRITE32(ESAL_DP_SLCR_BASE + A9_CPU_SLCR_RESET_CTRL, reg);

	lock_slcr();
#else
	(void)proc;
#endif
}

static struct metal_io_region* _alloc_shm(struct hil_proc *proc,
			metal_phys_addr_t pa,
			size_t size,
			struct metal_device **dev)
{
	(void)proc;

	*dev = hil_create_generic_mem_dev(pa, size,
				NORM_NONCACHE | STRONG_ORDERED);
	if ((*dev))
		return &((*dev)->regions[0]);

	return NULL;

}

static void _release_shm(struct hil_proc *proc,
			struct metal_device *dev,
			struct metal_io_region *io)
{
	(void)proc;
	(void)io;
	hil_close_generic_mem_dev(dev);
}

static int _initialize(struct hil_proc *proc)
{
	int i;
	struct proc_intr *intr_info;

	for (i = 0; i < 2; i++) {
		intr_info = &(proc->vdev.vring_info[i].intr_info);
		atomic_store((atomic_uint *)&(intr_info->data), 1);
	}

	return 0;
}

static void _release(struct hil_proc *proc)
{
	(void)proc;
	return;
}


text:
package com.gregorbyte.xsp.library;

import com.ibm.xsp.library.AbstractXspLibrary;

public class BundleInspectorXspLibrary extends AbstractXspLibrary {

	public static final String PLUGIN_ID = "com.gregorbyte.xsp.bundleinspector";
	public static final String LIBRARY_ID = "com.gregorbyte.xsp.bundleinspector.library";

	public BundleInspectorXspLibrary() {

	}

	@Override
	public String getLibraryId() {
		return LIBRARY_ID;
	}

	@Override
	public String[] getFacesConfigFiles() {

		return new String[] { "com/gregorbyte/xsp/config/gregorbyte-bundles-faces-config.xml" };

	}

	@Override
	public String getPluginId() {
		return PLUGIN_ID;
	}

}

redpajama_set_name: RedPajamaGithub


text:
The name pretty much gives it away, doesn't it...

-------------------------------------------------

## About

This tool can be used to activate one of a list
of pre-configured WiFi networks, something
you'd usually do using wpa_cli.

It's thought for users who manage their wifi
connections with wpa_supplicant and netctl,
and like the sparsity of dmenu.
Probably also using some minimalist window
manager like i3, monad or awesome.

It's still pre-alpha, but since it is unable
to change anything in your system besides
the connection state of your wifi, it
should be harmless enough.

Just put it somewhere you'll find it again
and make it executable (+x). Maybe ~/bin.
Usually you'd bind it to some hotkey, which
makes using it much more convenient.

## Troubleshooting

I can, unfortunately, only describe
the process for Arch Linux using systemd.

__dmenu_wpa_cli__, as the name says,
utilizes __dmenu__ as well as __wpa_cli__,
so both of these should be installed in your
system. Furthermore, in order for this to
work, wpa_cli must have write access to
the socket used by wpa_supplicant.

To make this work, make sure you enable
`wpa_supplicant@.service` instead of
`wpa_supplicant.service` for your adapter.
So if its udev name is `wlan0` for instance,
you'd use

`systemctl enable wpa_supplicant@wlan0.service`

Aditionally the path to your wpa_supplicant
config file should be

`/etc/wpa_supplicant/wpa_supplicant-wlan0.config`

again named after your adapter.

At last you need to pass the group which
has write access to the socket in your
config file. The first line should be
something in the way of

`ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=wifi`

If your user is member of the `wifi` group,
everything should work just fine.

Furthermore you should have FontAwesome installed
in your system for various icons used in the menu.
Otherwise you'll have to replace the symbols in
the script by hand, I'm afraid. At least at the
moment. Maybe I'll add a command line switch
to disable them.

## TODO

- [ ] pass (debug) messages to wpa_supplicant's log
- [ ] menu item to rescan available networks
- [ ] command line arguments switches to configure:
	- [ ] output (menu wise)
	- [ ] scan timeout
	- [ ] message log
	- [ ] FontAwesome symbols
- [ ] script for notification daemon
- [ ] waiting 'til network scan is finished


text:
package hudson.plugins.report.jck.parsers;

import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.plugins.report.jck.model.ReportFull;
import hudson.plugins.report.jck.model.Suite;
import hudson.plugins.report.jck.model.Test;
import hudson.plugins.report.jck.model.TestOutput;
import hudson.plugins.report.jck.model.TestStatus;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.ArchiveInputStream;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
import org.apache.commons.compress.compressors.xz.XZCompressorInputStream;
import org.apache.commons.io.input.CloseShieldInputStream;

import static javax.xml.stream.XMLStreamConstants.CDATA;
import static javax.xml.stream.XMLStreamConstants.CHARACTERS;
import static javax.xml.stream.XMLStreamConstants.END_ELEMENT;
import static javax.xml.stream.XMLStreamConstants.START_ELEMENT;
import javax.xml.stream.XMLStreamException;

public class JtregReportParser implements ReportParser {

    private static final Map<String, ArchiveFactory> SUPPORTED_ARCHIVE_TYPES_MAP = createSupportedArchiveTypesMap();

    @Override
    @SuppressFBWarnings(value = {"REC_CATCH_EXCEPTION", "NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE", "RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE"}, justification = " npe of spotbugs sucks")
    public Suite parsePath(Path path) {
        List<Test> testsList = new ArrayList<>();
        try (ArchiveInputStream in = streamPath(path)) {
            XMLInputFactory inputFactory = XMLInputFactory.newInstance();
            ArchiveEntry entry;
            while ((entry = in.getNextEntry()) != null) {
                String entryName = entry.getName();
                if (entryName == null || !entryName.endsWith(".jtr.xml")) {
                    continue;
                }
                try {
                    XMLStreamReader reader = inputFactory.createXMLStreamReader(new CloseShieldInputStream(in), "UTF-8");
                    testsList.addAll(parseTestsuites(reader));
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        if (testsList.isEmpty()) {
            return null;
        }
        List<String> testNames = testsList.stream()
                .sequential()
                .map(t -> t.getName())
                .sorted()
                .collect(Collectors.toList());
        List<Test> testProblems = testsList.stream()
                .sequential()
                .filter(t -> t.getStatus() == TestStatus.ERROR || t.getStatus() == TestStatus.FAILED)
                .sorted()
                .collect(Collectors.toList());
        ReportFull fullReport = new ReportFull(
                (int) testsList.stream().sequential().filter(t -> t.getStatus() == TestStatus.PASSED).count(),
                (int) testsList.stream().sequential().filter(t -> t.getStatus() == TestStatus.NOT_RUN).count(),
                (int) testsList.stream().sequential().filter(t -> t.getStatus() == TestStatus.FAILED).count(),
                (int) testsList.stream().sequential().filter(t -> t.getStatus() == TestStatus.ERROR).count(),
                testsList.size(), testProblems, testNames);
        return new Suite(suiteName(path), fullReport);
    }

    @SuppressFBWarnings(value = "NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE", justification = "We desrve to die")
    private String suiteName(Path path) {
        for (Entry<String, ArchiveFactory> factory : SUPPORTED_ARCHIVE_TYPES_MAP.entrySet()) {
            String pathName = path.getFileName().toString();
            if (pathName.toLowerCase().endsWith(factory.getKey())) {
                return pathName.substring(0, pathName.length() - factory.getKey().length());
            }
        }
        return path.getFileName().toString();
    }

    private List<Test> parseTestsuites(XMLStreamReader in) throws Exception {
        List<Test> r = new ArrayList<>();
        String ignored = "com.google.security.wycheproof.OpenJDKAllTests";
        while (in.hasNext()) {
            int event = in.next();
            if (event == START_ELEMENT && TESTSUITE.equals(in.getLocalName())) {
                JtregBackwardCompatibileSuite suite = parseTestSuite(in);
                if (ignored.equals(suite.name)) {
                    System.out.println("Skipping ignored suite : " + ignored);
                } else {
                    r.addAll(suite.getTests());
                }
            }
        }
        return r;
    }
    private static final String SYSTEMOUT = "system-out";
    private static final String SYSTEMERR = "system-err";
    private static final String TESTSUITE = "testsuite";
    private static final String TESTCASE = "testcase";
    private static final String PROPERTIES = "properties";
    private static final String FAILURE = "failure";
    private static final String SKIPPED = "skipped";
    private static final String ERROR = "error";

    private String findAttributeValue(XMLStreamReader in, String name) {
        int count = in.getAttributeCount();
        for (int i = 0; i < count; i++) {
            if (name.equals(in.getAttributeLocalName(i))) {
                return in.getAttributeValue(i);
            }
        }
        return null;
    }

    private int tryParseString(String value) {
        if (value == null || value.trim().isEmpty()) {
            return 0;
        }
        try {
            return Integer.parseInt(value);
        } catch (Exception e) {
        }
        return 1;
    }

    private String findStatusLine(XMLStreamReader in) throws Exception {
        while (in.hasNext()) {
            int event = in.next();
            if (event == END_ELEMENT && PROPERTIES.equals(in.getLocalName())) {
                break;
            }
            if (event == START_ELEMENT && "property".equals(in.getLocalName())) {
                if ("execStatus".equals(findAttributeValue(in, "name"))) {
                    return findAttributeValue(in, "value");
                }
            }
        }
        return "";
    }

    private String captureCharacters(XMLStreamReader in, String element) throws Exception {
        while (in.hasNext()) {
            int event = in.next();
            if (event == END_ELEMENT && element.equals(in.getLocalName())) {
                break;
            }
            if (event == CDATA || event == CHARACTERS) {
                StringBuilder outputString = new StringBuilder();
                do {
                    outputString.append(in.getText());
                    event = in.next();
                } while (event == CDATA || event == CHARACTERS);
                return outputString.toString().trim();
            }
        }
        return "";
    }

    @SuppressFBWarnings(value = "NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE", justification = "We desrve to die")
    private ArchiveInputStream streamPath(Path path) throws IOException {
        for (Entry<String, ArchiveFactory> factory : SUPPORTED_ARCHIVE_TYPES_MAP.entrySet()) {
            String pathName = path.getFileName().toString().toLowerCase();
            if (pathName.endsWith(factory.getKey())) {
                InputStream stream = new BufferedInputStream(Files.newInputStream(path));
                return factory.getValue().create(stream);
            }
        }
        throw new IOException("Unsupported archive format: " + path.getFileName());
    }

    private static Map<String, ArchiveFactory> createSupportedArchiveTypesMap() {
        Map<String, ArchiveFactory> map = new HashMap<>();

        map.put(".zip", in -> new ZipArchiveInputStream(in));
        map.put(".tar", in -> new TarArchiveInputStream(in));
        map.put(".tar.gz", in -> new TarArchiveInputStream(new GzipCompressorInputStream(in)));
        map.put(".tar.bz2", in -> new TarArchiveInputStream(new BZip2CompressorInputStream(in)));
        map.put(".tar.xz", in -> new TarArchiveInputStream(new XZCompressorInputStream(in)));

        return Collections.unmodifiableMap(map);
    }

    private JtregBackwardCompatibileSuite parseTestSuite(XMLStreamReader in) throws XMLStreamException, Exception {

        final String name = findAttributeValue(in, "name");
        final String failuresStr = findAttributeValue(in, "failures");
        final String errorsStr = findAttributeValue(in, "errors");
        final String totalStr = findAttributeValue(in, "tests");
        final String totalSkip = findAttributeValue(in, "skipped");

        final int failures = tryParseString(failuresStr);
        final int errors = tryParseString(errorsStr);
        final int total = tryParseString(totalStr);
        final int skipped = tryParseString(totalSkip);

        JtregBackwardCompatibileSuite suite = new JtregBackwardCompatibileSuite(name, failures, errors, total, skipped);

        String statusLine = "";
        String stdOutput = "";
        String errOutput = "";

        while (in.hasNext()) {
            int event = in.next();
            if (event == START_ELEMENT && TESTCASE.equals(in.getLocalName())) {
                JtregBackwardCompatibileTest test = parseTestcase(in);
                suite.add(test);
                continue;
            }

            if (event == START_ELEMENT && PROPERTIES.equals(in.getLocalName())) {
                statusLine = findStatusLine(in);
                continue;
            }
            if (event == START_ELEMENT && SYSTEMOUT.equals(in.getLocalName())) {
                stdOutput = captureCharacters(in, SYSTEMOUT);
                continue;
            }
            if (event == START_ELEMENT && SYSTEMERR.equals(in.getLocalName())) {
                errOutput = captureCharacters(in, SYSTEMERR);
                continue;
            }

            if (event == END_ELEMENT && TESTSUITE.equals(in.getLocalName())) {
                break;
            }
        }

        //order imortant! see revalidateTests
        List<TestOutput> outputs = Arrays.asList(
                new TestOutput(SYSTEMOUT, stdOutput),
                new TestOutput(SYSTEMERR, errOutput)
        );

        suite.setStatusLine(statusLine);
        suite.setOutputs(outputs);
        return suite;

    }

    /**
     * Test status of testcase is determined from its child tags( <skipped>, <failure>, <error> ).
     * If it doesn't contain any of these tags, test is considered passed. If it contains both failure and error tags,
     * test status is set to error.
     */

    private JtregBackwardCompatibileTest parseTestcase(XMLStreamReader in) throws Exception {

        final String testName = findAttributeValue(in, "name");
        final String className = findAttributeValue(in, "classname");

        TestStatus status = TestStatus.PASSED;

        String failureOutput = "";
        String stdOutput = "";
        String sysErrOutput = "";
        String message = "";
        StringBuilder errOutput = new StringBuilder();

        while (in.hasNext()) {
            int event = in.next();
            if (event == START_ELEMENT && FAILURE.equals(in.getLocalName())) {
                final String lEmessage = findAttributeValue(in, "message");
                if (lEmessage != null) {
                    message = lEmessage;
                }
                failureOutput = captureCharacters(in, FAILURE);
                if (status != TestStatus.ERROR) {
                    status = TestStatus.FAILED;
                }
                continue;
            }
            if (event == START_ELEMENT && SYSTEMOUT.equals(in.getLocalName())) {
                stdOutput = captureCharacters(in, SYSTEMOUT);
                continue;
            }
            if (event == START_ELEMENT && SYSTEMERR.equals(in.getLocalName())) {
                sysErrOutput = captureCharacters(in, SYSTEMERR);
                continue;
            }
            if (event == START_ELEMENT && SKIPPED.equals(in.getLocalName())) {
                status = TestStatus.NOT_RUN;
                continue;
            }
            if (event == START_ELEMENT && ERROR.equals(in.getLocalName())) {
                status = TestStatus.ERROR;
                errOutput.append(captureCharacters(in, ERROR)).append('\n');
                continue;
            }
            if (event == END_ELEMENT && TESTCASE.equals(in.getLocalName())) {
                break;
            }
        }

        //order imortant! see revalidateTests
        List<TestOutput> outputs = Arrays.asList(
                new TestOutput(SYSTEMOUT, stdOutput),
                new TestOutput(SYSTEMERR, sysErrOutput)
        );

        return new JtregBackwardCompatibileTest(className, status, message, outputs, testName, failureOutput, errOutput.toString());
    }

    @FunctionalInterface
    private static interface ArchiveFactory {

        ArchiveInputStream create(InputStream in) throws IOException;
    }

    @SuppressFBWarnings(value = "EQ_DOESNT_OVERRIDE_EQUALS", justification = "The Test ishandlig classes properly,but yes, this may get broken any time")
    private static class JtregBackwardCompatibileTest extends Test {

        private final String testName;
        private final String failureOutput;
        private final String errorOutput;

        public JtregBackwardCompatibileTest(String className, TestStatus status, String statusLine, List<TestOutput> outputs, String testName, String failureOutput, String errorOutput) {
            super(className, status, statusLine, outputs);
            this.testName = testName;
            this.failureOutput = failureOutput;
            this.errorOutput = errorOutput;
        }

    }

    private static class JtregBackwardCompatibileSuite {

        private final String name;
        private final int failures;
        private final int errors;
        private final int total;
        private final int skipped;
        private List<TestOutput> outputs;
        private final List<JtregBackwardCompatibileTest> settedTests = new ArrayList<>();
        private List<Test> revalidatedCopyOfTests;
        private String statusLine;
        private boolean validated = false;

        /**
         * This method is handling backward compatibility by converting JtregBackwardCompatibleTest to Test
         */
        private void revalidateTests() {
            revalidatedCopyOfTests = new ArrayList<>(settedTests.size());
            //control summs
            int cPass = 0;
            int cFail = 0;
            int cErr = 0;
            int cSkipp = 0;
            int cTotoal = 0;
            for (JtregBackwardCompatibileTest testcase : settedTests) {
                final Test t = mergeOutputs(name + '#' + testcase.testName, testcase, testcase.getStatus());

                switch (t.getStatus()) {
                    case ERROR:
                        cErr++;
                        break;
                    case FAILED:
                        cFail++;
                        break;
                    case NOT_RUN:
                        cSkipp++;
                        break;
                    case PASSED:
                        cPass++;
                        break;
                }
                cTotoal++;
                revalidatedCopyOfTests.add(t);
            }
            //check control summs ony for more then one
            int i = 0;
            System.out.println("Control summs '" + name + "'(skipped " + cSkipp + "):");
            if (cTotoal != total) {
                System.out.println("Total tests expected " + total + " got " + cTotoal);
                i++;
            }
            if (cFail != failures) {
                System.out.println("Failed tests expected " + failures + " got " + cFail);
                i++;
            }
            if (cErr != errors) {
                System.out.println("Error tests expected " + errors + " got " + cErr);
                i++;
            }
            if (cSkipp != skipped) {
                System.out.println("Skipped tests expected " + skipped + " got " + cSkipp);
                i++;
            }
            if (cErr + cFail + cPass + cSkipp != cTotoal) {
                System.out.println("Total(2) tests expected " + cTotoal + " got " + (cErr + cFail + cPass + cSkipp));
                i++;
            }
            if (i == 0) {
                System.out.println("Pass");
            }
            validated = true;
        }

        private JtregBackwardCompatibileSuite(String name, int failures, int errors, int totals, int skipped) {
            this.name = name;
            this.failures = failures;
            this.errors = errors;
            this.total = totals;
            this.skipped = skipped;
        }

        private Collection<? extends Test> getTests() {
            if (!validated) {
                revalidateTests();
            }
            return revalidatedCopyOfTests;
        }

        private void setStatusLine(String statusLine) {
            this.statusLine = statusLine;
        }

        private void setOutputs(List<TestOutput> outputs) {
            this.outputs = outputs;
        }

        private void add(JtregBackwardCompatibileTest test) {
            validated = false;
            settedTests.add(test);
        }

        private Test mergeOutputs(String nwName, JtregBackwardCompatibileTest testcase, TestStatus st) {
            List<TestOutput> newOutputs = Arrays.asList(
                    new TestOutput(SYSTEMOUT, "---- suite ----\n" + outputs.get(0).getValue() + "\n---- test ----\n" + testcase.getOutputs().get(0).getValue()),
                    new TestOutput(SYSTEMERR, "---- suite ----\n" + outputs.get(1).getValue() + "\n---- test ----\n" + testcase.getOutputs().get(1).getValue() + "\n---- fail ----\n" + testcase.failureOutput + "\n---- error ----\n" + testcase.errorOutput)
            );
            //merge status line of suite, and testcase (failure is already in stderr)
            String nwStatus;
            if (statusLine.equals(testcase.getStatusLine())) {
                nwStatus = statusLine;
            } else {
                String del = "";
                if (statusLine.trim().length() > 0 && testcase.getStatusLine().trim().length() > 0) {
                    del = " ; ";
                }
                nwStatus = statusLine + del + testcase.getStatusLine();
            }
            return new Test(nwName, st, nwStatus, newOutputs);

        }

    }

}


text:
package aecor.runtime

import cats.Applicative
import cats.implicits._

final class NoopKeyValueStore[F[_]: Applicative, K, V] extends KeyValueStore[F, K, V] {
  override def setValue(key: K, value: V): F[Unit] = ().pure[F]
  override def getValue(key: K): F[Option[V]] = none[V].pure[F]
  override def deleteValue(key: K): F[Unit] = ().pure[F]
}

object NoopKeyValueStore {
  def apply[F[_]: Applicative, K, V]: NoopKeyValueStore[F, K, V] = new NoopKeyValueStore[F, K, V]
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<title>R: impute: Imputation for microarray data</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="R.css" />

 impute: Imputation for microarray data

Documentation for package ‘impute’ version 1.52.0

DESCRIPTION file.

Help Pages

impute.knn
A function to impute missing expression data

khanmiss
Khan microarray data with random missing values


text:
title: Radio buttons
---

* use these to let users choose a single option from a list
* for more than two options, radio buttons should be stacked
* radio buttons with large hit areas are easier to select with a mouse or touch devices

```
[TODO: Add example from here](http://govuk-elements.herokuapp.com/form-elements/example-radios-checkboxes/)
```


text:
using System;

class Qualifiers
{
    public short S => Static<short>(null);

    public int I => Instance<int>();

    public bool B => this.Instance<bool>();

    static T Static<T>(object o) => default(T);

    T Instance<T>() => default(T);
}


text:
# Test Examples Using `PhpUnitTestCase`

The method being tested:

    public function storeEvent(array $event)
    {
        $mutators['outflows.do'] =
        $mutators['inflows.do'] =
        $mutators['actions.do'] =
        $mutators['outflows.undo'] =
        $mutators['inflows.undo'] =
        $mutators['actions.undo'] = [
            'value' => null,
        ];

        if (isset($mutators[$event['event']])) {
            $event = $this->mutateData($event, $mutators[$event['event']]);
        }

        $this->db->insert('events', $event);
        $this->storeLastEvent($event);

        return $event;
    }

And the tests to test it showing mocking:

    public function testStoreEventInsertsMutatedEventInTableEvents()
    {
        $called = [];
        $this->objArgs[1] = $this->getMockable('insert', function ($table, $event) use (&$called) {
            $called = func_get_args();
        });
        $this->createObj();
        $obj = $this->getMockedObj('storeLastEvent', null);

        $obj->storeEvent(['value' => 'alpha', 'event' => 'outflows.do']);

        list($table, $record) = $called;
        $this->assertSame('events', $table);
        $this->assertArrayHasKey('value', $record);
        $this->assertNull($record['value']);
    }

    /**
     * Provides data for testStoreEventSetsValueToNullForAllEvents.
     */
    public function DataForTestStoreEventSetsValueToNullForAllEventsProvider()
    {
        $tests = array();
        $tests[] = array(
            ['value' => 'alpha', 'event' => 'outflows.do'],
        );

        return $tests;
    }

    /**
     * @dataProvider DataForTestStoreEventSetsValueToNullForAllEventsProvider
     */
    public function testStoreEventSetsValueToNullForAllDoAndUndoEvents($event)
    {
        $db = $this->getMockable('insert', true);
        $this->objArgs[1] = $db;
        $this->createObj();

        $obj = $this->getMockedObj('storeLastEvent', true);
        $event = $obj->storeEvent($event);
        $this->assertNull($event['value']);
    }


text:
<?php

namespace App\Services;

use App\Repositories\Criteria\GroupBy;
use App\Repositories\Criteria\OrderBy;
use App\Repositories\Criteria\RawSelect;
use App\Repositories\Criteria\Where;
use App\Repositories\SolutionRepository;
use Carbon\Carbon;

class SolutionService
{
    /** @var SolutionRepository */
    private $repository;

    /**
     * SolutionService constructor.
     */
    public function __construct()
    {
        $this->repository = app(SolutionRepository::class);
    }

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

    /**
     * @param Carbon $from
     *
     * @return mixed
     */
    public function getSubmissionStats($from)
    {
        $this->repository->clearCriteria();
        $rawSql = 'DATE_FORMAT(created_at,\'%Y-%m-%d\') as date, count(*) as number';
        $this->repository->pushCriteria(new RawSelect($rawSql));
        $this->repository->pushCriteria(new Where('created_at', $from->format('Y-m-d h:i:s'), '>'));
        $this->repository->pushCriteria(new GroupBy('date'));
        $this->repository->pushCriteria(new OrderBy('created_at', 'desc'));

        return $this->repository->all();
    }
}


text:
package controller;

import Modelos.Cliente;
import Modelos.Provincia;
import Modelos.ClienteValidate;
import Modelos.Comuna;
import Modelos.Conexion;
import Modelos.JSONValid;
import com.google.gson.Gson;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.dao.DataAccessException;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;

import org.springframework.stereotype.Controller;

import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class AdministracionController {

    private final ClienteValidate clienteValidate;

    private final JdbcTemplate jdbcTemplate;

    public AdministracionController() {
        this.clienteValidate = new ClienteValidate(); //Implementar Validator
        Conexion con = new Conexion();
        this.jdbcTemplate = new JdbcTemplate(con.conectar());
    }

    @RequestMapping(value = "Administracion/cliente.htm", method = RequestMethod.GET)
    public ModelAndView cliente() {
        ModelAndView mav = new ModelAndView();
        String sql = "SELECT COMUNA_NOMBRE,REGION_NOMBRE,PROVINCIA_NOMBRE,RUT_EMPRESA,NOMBRE_EMPRESA,RAZON_SOCIAL,TELEFONO_EMPRESA,CORREO_EMPRESA,DIRECCION_EMPRESA FROM region inner join  provincia on REGION_ID = PROVINCIA_REGION_ID inner join comuna on PROVINCIA_ID = COMUNA_PROVINCIA_ID inner join EMPRESA on COMUNA_EMPRESA = COMUNA_ID order by NOMBRE_EMPRESA";
        List datos = this.jdbcTemplate.queryForList(sql);
        mav.addObject("datos", datos);
        mav.addObject("cliente", new Cliente());
        mav.setViewName("Administracion/cliente");
        return mav;
    }

    @RequestMapping(value = "Administracion/cliente.htm", method = RequestMethod.POST)
    public ModelAndView formBuscarAdm( @ModelAttribute("cliente") Cliente cli, BindingResult result, SessionStatus status) {

        ModelAndView mav = new ModelAndView();
        mav.setViewName("Administracion/cliente");
        String sql = "SELECT COMUNA_NOMBRE,REGION_NOMBRE,RUT_EMPRESA,NOMBRE_EMPRESA,TELEFONO_EMPRESA,CORREO_EMPRESA,DIRECCION_EMPRESA FROM region inner join  provincia on REGION_ID = PROVINCIA_REGION_ID inner join comuna on PROVINCIA_ID = COMUNA_PROVINCIA_ID inner join EMPRESA on COMUNA_EMPRESA = COMUNA_ID where NOMBRE_EMPRESA regexp '" + cli.getNombre() + "'";
        List cliente = this.jdbcTemplate.queryForList(sql);
        mav.addObject("datos", cliente);
        String Nombre = cli.getNombre();
        mav.addObject("NomEmp", Nombre);
        mav.addObject("cliente", new Cliente());
        return mav;

    }

     @RequestMapping(value = "Administracion/infoCliente.htm")
    public ModelAndView infoCliente(HttpServletRequest request)
    {
        ModelAndView mav=new ModelAndView();
        String rut=request.getParameter("rut");
        Cliente datos=this.selectCliente(rut);
        mav.setViewName("Administracion/infoCliente");
        mav.addObject("cliente",new Cliente(rut,datos.getNombre(),datos.getNombreLargo(),datos.getEmail(),datos.getTelefono(),datos.getComuna(),datos.getRegion(),datos.getProvincia(),datos.getDireccion()));
        return mav;
    }

    @RequestMapping(value = "receta.htm")
    public ModelAndView receta() {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("Administracion/receta");
        return mav;
    }

    @RequestMapping(value = "ingrediente.htm")
    public ModelAndView ingrediente() {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("Administracion/ingrediente");
        return mav;
    }

    @RequestMapping(value = "Administracion/AñadirCliente.htm", method = RequestMethod.GET)
    public ModelAndView añadirCliente() {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("Administracion/AñadirCliente");
        List regiones = this.jdbcTemplate.queryForList("select REGION_ID, REGION_NOMBRE from region");
        List comunas = this.jdbcTemplate.queryForList("select COMUNA_ID, COMUNA_NOMBRE from comuna");
        mav.addObject("regiones", regiones);
        mav.addObject("comunas", comunas);
        mav.addObject("cliente", new Cliente());
        return mav;
    }

    @RequestMapping(value = "Administracion/buscarProvincia.do", method = RequestMethod.GET)
    @ResponseBody
    public void buscarProvincia(@RequestParam(value = "regionID") String region, HttpServletRequest request,
            HttpServletResponse response) {
        String sql = "SELECT PROVINCIA_ID,PROVINCIA_NOMBRE FROM provincia where PROVINCIA_REGION_ID=" + region + " ";
        List<Provincia> provincias = jdbcTemplate.query(
                sql, new RowMapper<Provincia>() {
            @Override
            public Provincia mapRow(ResultSet rs, int rowNum) throws SQLException {
                Provincia c = new Provincia();
                c.setProvinciaId(Integer.parseInt(rs.getString("PROVINCIA_ID")));
                c.setProvinciaName(rs.getString("PROVINCIA_NOMBRE"));
                return c;
            }
        });

        //List<Provincia> provincia= this.jdbcTemplate.queryForObject("SELECT PROVINCIA_ID,PROVINCIA_NOMBRE FROM provincia where PROVINCIA_REGION_ID="+region+" ",Provincia);
        String json = null;
        json = new Gson().toJson(provincias);
        response.setContentType("Administracion/AñadirCliente");
        try {
            response.getWriter().write(json);
        } catch (IOException ex) {
            Logger.getLogger(AdministracionController.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    @RequestMapping(value = "Administracion/buscarComuna.do", method = RequestMethod.GET)
    public void buscarComuna(@RequestParam(value = "provinciaID") String provincia, HttpServletRequest request,
            HttpServletResponse response) {

        String sql = "select COMUNA_ID, COMUNA_NOMBRE from comuna where COMUNA_PROVINCIA_ID=" + provincia + " ";
        List<Comuna> comunas = jdbcTemplate.query(
                sql, new RowMapper<Comuna>() {
            @Override
            public Comuna mapRow(ResultSet rs, int rowNum) throws SQLException {
                Comuna c = new Comuna();
                c.setComunaId(Integer.parseInt(rs.getString("COMUNA_ID")));
                c.setComunaName(rs.getString("COMUNA_NOMBRE"));
                return c;
            }
        });

        String json = null;
        json = new Gson().toJson(comunas);
        response.setContentType("Administracion/AñadirCliente");
        try {
            response.getWriter().write(json);
        } catch (IOException ex) {
            Logger.getLogger(AdministracionController.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    @RequestMapping(value = "Administracion/AñadirCliente.htm", method = RequestMethod.POST)
    public ModelAndView form(@ModelAttribute("cliente") Cliente cli, BindingResult result, SessionStatus status) {

            this.jdbcTemplate.update("insert into EMPRESA (RUT_EMPRESA,NOMBRE_EMPRESA,RAZON_SOCIAL,TELEFONO_EMPRESA,CORREO_EMPRESA,Region_Empresa,ProvinciaEmpresa,Comuna_Empresa,Direccion_Empresa) values (?,?,?,?,?,?,?,?,?)",
                     cli.getRut(), cli.getNombre(), cli.getNombreLargo(), cli.getTelefono(), cli.getEmail(), cli.getRegion(), cli.getProvincia(), cli.getComuna(), cli.getDireccion());

            return new ModelAndView("redirect:cliente.htm");

    }

    @RequestMapping(value = "Administracion/ValidarCliente.do", method = RequestMethod.GET)
    @ResponseBody
    public void ValidarClienteRut(@RequestParam(value = "rut") String Ingrediente, HttpServletRequest request,
            HttpServletResponse response) {
        String Nombre= request.getParameter("rut");
        JSONValid valida= new JSONValid();
        int ingrediente = this.jdbcTemplate.queryForObject("SELECT COUNT(*) from EMPRESA where RUT_EMPRESA='"+Nombre+"'", Integer.class);
        Boolean valid = true;
        if (ingrediente != 0) {
            valid=false;
        }
        valida.setValid(valid);
        String json = null;
        json = new Gson().toJson(valida);
        response.setContentType("Administracion/AñadirCliente");
        try {
            response.getWriter().write(json);
        } catch (IOException ex) {
            Logger.getLogger(AdministracionController.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

     public Cliente selectCliente(String rut)
    {
        final Cliente cliente = new Cliente();
       // String quer = "SELECT * FROM EMPRESA WHERE RUT_EMPRESA='" + rut+"'";
        String quer="SELECT\n" +
"    COMUNA_NOMBRE,\n" +
"    REGION_NOMBRE,PROVINCIA_NOMBRE,\n" +
"    RUT_EMPRESA,\n" +
"    NOMBRE_EMPRESA,\n" +
"    TELEFONO_EMPRESA,\n" +
"    CORREO_EMPRESA,\n" +
"    DIRECCION_EMPRESA,RAZON_SOCIAL\n" +
"FROM\n" +
"    region  inner join\n" +
"    provincia on REGION_ID = PROVINCIA_REGION_ID inner join\n" +
"    comuna on PROVINCIA_ID = COMUNA_PROVINCIA_ID inner join\n" +
"    EMPRESA on COMUNA_EMPRESA = COMUNA_ID"
                + " WHERE RUT_EMPRESA='" + rut+"'";
        return (Cliente) jdbcTemplate.query
        (
                quer, new ResultSetExtractor<Cliente>()
            {
                public Cliente extractData(ResultSet rs) throws SQLException, DataAccessException
                {
                    if (rs.next())
                    {
                        cliente.setNombre(rs.getString("Nombre_EMPRESA"));
                        cliente.setEmail(rs.getString("CORREO_EMPRESA"));
                        cliente.setTelefono(rs.getString("TELEFONO_EMPRESA"));
                        cliente.setComuna(rs.getString("COMUNA_NOMBRE"));
                        cliente.setDireccion(rs.getString("DIRECCION_EMPRESA"));
                        cliente.setRegion(rs.getString("REGION_NOMBRE"));
                        cliente.setProvincia(rs.getString("PROVINCIA_NOMBRE"));
                        cliente.setNombreLargo(rs.getString("RAZON_SOCIAL"));

                    }
                    return cliente;
                }

            }
        );
    }

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Archetype-CSS/ u-text Visual Unit Tests</title>
    <link rel="stylesheet" href="css/u-layout.css">
    <link rel="stylesheet" href="css/test.css">

Archetype-CSS/u-layout: Visual Unit Tests

.u-cf

contain floats using micro-clearfix

        This div is floated left

        This div is floated left

.u-nbfc

force a new block formating context

The div is floated left

        This text should not wrap under the float....Morbi leo risusporta ac consectetur acvestibulum at eros. Nullam id dolor id nibh ultricies vehicula ut id elit. Etiam porta sem malesuada magna mollis euismod. Maecenas faucibus mollis interdum. Sed posuere consectetur est at lobortis. Lorem ipsum dolor sit ametconsectetur adipiscing elit. Nullam quis risus eget urna mollis ornare vel eu leo. Donec id elit non mi porta gravida at eget metus. Morbi leo risusporta ac consectetur acvestibulum at eros.

.nbfcAlt

alternate method for forcing a new block formating context

The div is floated left

        This text should not wrap under the float....Morbi leo risusporta ac consectetur acvestibulum at eros. Nullam id dolor id nibh ultricies vehicula ut id elit. Etiam porta sem malesuada magna mollis euismod. Maecenas faucibus mollis interdum. Sed posuere consectetur est at lobortis. Lorem ipsum dolor sit ametconsectetur adipiscing elit. Nullam quis risus eget urna mollis ornare vel eu leo. Donec id elit non mi porta gravida at eget metus. Morbi leo risusporta ac consectetur acvestibulum at eros.

.u-pullLeft

float left

The div is floated left

.u-pullRight

float right

The div is floated left


text:
use { serde_json };
use error::*;
use libflo_action_std::Action;
use libflo_std::LIBFLO;
use serde::Serialize;

pub unsafe fn send_to_guifast<T>(action: &T) -> Result<()>
    where T: Action + Serialize {
    let message = serde_json::to_string(&action)?;
    let libflo = LIBFLO.read()?;
    libflo.sendln(&message)?;
    Ok(())
}


text:
package jef.ui.model;

import jef.common.RGB;

public class MColor extends AbstractInputModel implements InputModel<RGB>{
	private RGB color;
	private int width;

	public MColor(String label) {
		super(label);
	}

	public RGB get() {
		return color;
	}

	public void set(RGB data) {
		this.color=data;
	}

	public int getWidth() {
		return width;
	}

	public void setWidth(int width) {
		this.width = width;
	}

}


text:
import socket

import pytest
from eventlet import wsgi
from mock import patch
from werkzeug.contrib.fixers import ProxyFix

from nameko.exceptions import ConfigurationError
from nameko.web.handlers import HttpRequestHandler, http
from nameko.web.server import (
    BaseHTTPServer, HttpOnlyProtocol, WebServer, parse_address)

class ExampleService(object):
    name = "exampleservice"

    @http('GET', '/')
    def do_index(self, request):
        return ''

    @http('GET', '/large')
    def do_large(self, request):
        # more than a buffer's worth
        return 'x' * (10**6)

def test_broken_pipe(
    container_factory, web_config, web_config_port, web_session
):
    container = container_factory(ExampleService, web_config)
    container.start()

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(('127.0.0.1', web_config_port))
    s.sendall(b'GET /large \r\n\r\n')
    s.recv(10)
    s.close()  # break connection while there is still more data coming

    # server should still work
    assert web_session.get('/').text == ''

def test_other_socket_error(
    container_factory, web_config, web_config_port, web_session
):
    container = container_factory(ExampleService, web_config)
    container.start()

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(('127.0.0.1', web_config_port))

    with patch.object(BaseHTTPServer.BaseHTTPRequestHandler, 'finish') as fin:
        fin.side_effect = socket.error('boom')
        s.sendall(b'GET / \r\n\r\n')
        s.recv(10)
        s.close()

    # takes down container
    with pytest.raises(socket.error) as exc:
        container.wait()
    assert 'boom' in str(exc)

def test_client_disconnect_os_error(
    container_factory, web_config, web_config_port, web_session
):
    """ Regression for https://github.com/nameko/nameko/issues/368
    """
    container = container_factory(ExampleService, web_config)
    container.start()

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(('127.0.0.1', web_config_port))

    with patch.object(HttpOnlyProtocol, 'handle_one_request') as handle:
        handle.side_effect = OSError('raw readinto() returned invalid length')
        s.sendall(b'GET / \r\n\r\n')
        s.recv(10)
        s.close()

    # server should still work
    assert web_session.get('/').text == ''

def test_other_os_error(
    container_factory, web_config, web_config_port, web_session
):
    """ Regression for https://github.com/nameko/nameko/issues/368
    """
    container = container_factory(ExampleService, web_config)
    container.start()

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(('127.0.0.1', web_config_port))

    with patch.object(BaseHTTPServer.BaseHTTPRequestHandler, 'finish') as fin:
        fin.side_effect = OSError('boom')
        s.sendall(b'GET / \r\n\r\n')
        s.recv(10)
        s.close()

    # takes down container
    with pytest.raises(OSError) as exc:
        container.wait()
    assert 'boom' in str(exc)

@pytest.mark.parametrize(['source', 'result'], [
    ('8000', ('', 8000)),
    ('foo:8000', ('foo', 8000)),
    ('foo', None),
])
def test_parse_address(source, result):
    if result is None:
        with pytest.raises(ConfigurationError) as exc:
            parse_address(source)
        assert 'Misconfigured bind address' in str(exc)
        assert '`foo`' in str(exc)

    else:
        assert parse_address(source) == result

def test_adding_middleware_with_get_wsgi_app(container_factory, web_config):

    class CustomWebServer(WebServer):
        def get_wsgi_app(self):
            # get the original WSGI app that processes http requests
            app = super(CustomWebServer, self).get_wsgi_app()
            # apply the ProxyFix middleware as an example
            return ProxyFix(app, num_proxies=1)

    class CustomHttpRequestHandler(HttpRequestHandler):
        server = CustomWebServer()

    http = CustomHttpRequestHandler.decorator

    class CustomServerExampleService(object):
        name = 'customserverservice'

        @http('GET', '/')
        def do_index(self, request):
            return ''  # pragma: no cover

    container = container_factory(CustomServerExampleService, web_config)
    with patch.object(CustomWebServer, 'get_wsgi_server') as get_wsgi_server:
        container.start()

    wsgi_app = get_wsgi_server.call_args[0][1]
    assert isinstance(wsgi_app, ProxyFix)

def test_custom_wsgi_server_is_used(
    container_factory, web_config, web_config_port, web_session
):
    def custom_wsgi_app(environ, start_response):
        start_response('200 OK', [])
        return 'Override'

    class CustomWebServer(WebServer):
        def get_wsgi_server(
            self, sock, wsgi_app, protocol=HttpOnlyProtocol, debug=False
        ):
            return wsgi.Server(
                sock,
                sock.getsockname(),
                custom_wsgi_app,
                protocol=protocol,
                debug=debug
            )

    class CustomHttpRequestHandler(HttpRequestHandler):
        server = CustomWebServer()

    http = CustomHttpRequestHandler.decorator

    class CustomServerExampleService(object):
        name = 'customserverservice'

        @http('GET', '/')
        def do_index(self, request):
            return ''  # pragma: no cover

    container = container_factory(CustomServerExampleService, web_config)
    container.start()

    assert web_session.get('/').text == 'Override'


text:
<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.ovirt.engine.ui</groupId>
    <artifactId>webadmin-modules</artifactId>
    <version>3.1.0</version>
  </parent>
  <artifactId>gwt-extension</artifactId>
  <packaging>jar</packaging>
  <name>Extensions for GWT</name>
  <properties>
    <sourceDir>${project.basedir}/src/main/java</sourceDir>
    <gwt-plugin.extraJvmArgs>-Xms1024M -Xmx1024M -XX:PermSize=256M -XX:MaxPermSize=256M</gwt-plugin.extraJvmArgs>
    <!-- Versions need to be inherited -->
    <gwt.version>2.3.0</gwt.version>
  </properties>
  <dependencies>
    <dependency>
      <groupId>com.google.gwt</groupId>
      <artifactId>gwt-user</artifactId>
      <version>${gwt.version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>com.google.gwt</groupId>
      <artifactId>gwt-dev</artifactId>
      <version>${gwt.version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>${engine.groupId}</groupId>
      <artifactId>genericapi</artifactId>
      <version>${engine.version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjrt</artifactId>
      <version>${aspectj.version}</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <excludes>
            <exclude>**/uioverrides/**/*</exclude>
          </excludes>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-source-plugin</artifactId>
        <executions>
          <execution>
            <id>attach-sources</id>
            <phase>verify</phase>
            <goals>
              <goal>jar-no-fork</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>aspectj-maven-plugin</artifactId>
        <version>${aspectj-maven-plugin.version}</version>
        <executions>
          <execution>
            <goals>
              <goal>compile</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>


text:
/**
 *
 */
package org.necros.auth;

/**
 * @author weiht
 *
 */
public interface PasswordEncoder {
	public abstract String encode(String passwd, String login, Object salt);
}


text:
namespace policy {

// This class implements a RemoteCommandJob that clears the cellular EUICC
// (Embedded Universal Integrated Circuit Card) on the device, that stores all
// installed eSIM profiles. This effectively removes all eSIM profiles installed
// on the device.
class DeviceCommandResetEuiccJob : public RemoteCommandJob {
 public:
  DeviceCommandResetEuiccJob();
  DeviceCommandResetEuiccJob(const DeviceCommandResetEuiccJob&) = delete;
  DeviceCommandResetEuiccJob& operator=(const DeviceCommandResetEuiccJob&) =
      delete;
  ~DeviceCommandResetEuiccJob() override;

  static const char kResetEuiccNotificationId[];

  // RemoteCommandJob:
  enterprise_management::RemoteCommand_Type GetType() const override;

 private:
  friend class DeviceCommandResetEuiccJobTest;
  FRIEND_TEST_ALL_PREFIXES(DeviceCommandResetEuiccJobTest, ResetEuicc);
  FRIEND_TEST_ALL_PREFIXES(DeviceCommandResetEuiccJobTest, ResetEuiccFailure);

  // These values are persisted to logs. Entries should not be renumbered and
  // numeric values should never be reused.
  enum class ResetEuiccResult {
    kSuccess = 0,
    kInhibitFailed = 1,
    kHermesResetFailed = 2,
    kMaxValue = kHermesResetFailed
  };
  static void RecordResetEuiccResult(ResetEuiccResult result);

  // RemoteCommandJob:
  void RunImpl(CallbackWithResult succeeded_callback,
               CallbackWithResult failed_callback) override;

  CallbackWithResult CreateTimedResetMemorySuccessCallback(
      CallbackWithResult success_callback);

  void OnResetMemoryResponse(CallbackWithResult succeeded_callback,
                             CallbackWithResult failed_callback,
                             bool status);
  void RunResultCallback(CallbackWithResult callback);
  void ShowResetEuiccNotification();

  base::WeakPtrFactory<DeviceCommandResetEuiccJob> weak_ptr_factory_{this};
};

}  // namespace policy

#endif  // CHROME_BROWSER_ASH_POLICY_REMOTE_COMMANDS_DEVICE_COMMAND_RESET_EUICC_JOB_H_


text:
/******************************************************************

 iLBC Speech Coder ANSI-C Source Code

 WebRtcIlbcfix_IndexConvDec.h

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

#ifndef WEBRTC_MODULES_AUDIO_CODING_CODECS_ILBC_MAIN_SOURCE_INDEX_CONV_DEC_H_
#define WEBRTC_MODULES_AUDIO_CODING_CODECS_ILBC_MAIN_SOURCE_INDEX_CONV_DEC_H_

#include "defines.h"

void WebRtcIlbcfix_IndexConvDec(
    WebRtc_Word16 *index   /* (i/o) Codebook indexes */
                                );

#endif


text:
@interface PodsDummy_PushClientSDK : NSObject
@end
@implementation PodsDummy_PushClientSDK
@end


text:
package com.codeyn.jfinal.handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.jfinal.core.JFinal;
import com.jfinal.handler.Handler;
import com.jfinal.render.TextRender;

public class HeartBeatHandler extends Handler {

    private static final Log logger = LogFactory.getLog(HeartBeatHandler.class);

    private static final String DEFAULT_URI = "/heartbeat";

    private String uri;

    public HeartBeatHandler(){
        this.uri = DEFAULT_URI;
    }

    public HeartBeatHandler(String uri){
        this.uri = StringUtils.isBlank(uri) ? DEFAULT_URI : uri;
    }

    @Override
    public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled){
        if(JFinal.me().getConstants().getDevMode()){
            logger.debug("Heart beat try uri: " + target);
        }

        if(uri.equals(target)){
            new TextRender("Success").setContext(request, response).render();
            isHandled[0] = true;
            return;
        }
        nextHandler.handle(target, request, response, isHandled);
    }

}


text:
//
//  LTLsongSheet.m
//  音乐播放器
//
//  Created by LiTaiLiang on 16/11/18.
//  Copyright © 2016年 LiTaiLiang. All rights reserved.
//

#import "LTLsongSheet.h"
#import "LTLsongSheetCell.h"
#import "LTLGroupHeader.h"
#import "LTLsongSheetLayout.h"

@interface LTLsongSheet ()<UICollectionViewDelegate,UICollectionViewDataSource,UINavigationControllerDelegate>
/**
 *  歌单数组
 */
@property(nonatomic,strong)NSMutableArray *songSheetArray;

//约束
@property (strong, nonatomic)  UICollectionViewFlowLayout *flowtLayout;

@end
//重用标识符
static NSString *HeaderID = @"HeaderView";
//cell重用标识符
static NSString *cellID = @"colleCell";

static NSString *FooterID = @"FooterView";

@implementation LTLsongSheet

#pragma mark - 懒加载
//懒加载
-(NSMutableArray *)songSheetArray
{
    if (_songSheetArray == nil) {
        _songSheetArray = [NSMutableArray array];
    }
    return _songSheetArray;
}

+(LTLsongSheet *)initSongSheet
{
    LTLsongSheetLayout *layout = [[LTLsongSheetLayout alloc]init];
    //尾视图
    //头视图高度
    layout.headerReferenceSize = CGSizeMake(25, 25);

    LTLsongSheet *songSheet = [[LTLsongSheet alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
    songSheet.flowtLayout = layout;
    songSheet.backgroundColor = [UIColor whiteColor];
    return songSheet;
}

#pragma mark - 初始化
-(instancetype)initWithFrame:(CGRect)frame collectionViewLayout:(UICollectionViewLayout *)layout
{
    if (self = [super initWithFrame:frame collectionViewLayout:layout]) {

        self.bounces = NO;

        self.delegate = self;
        self.dataSource = self;
        ///注册 cell
        [self registerNib:[UINib nibWithNibName:@"LTLsongSheetCell" bundle:nil] forCellWithReuseIdentifier:cellID];
        [self registerNib:[UINib nibWithNibName:@"LTLGroupHeader" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:HeaderID];

        [self registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:FooterID];

        //获取数据
        [self DataAcquisition];

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(DataAcquisition) name:LTLRefreshKey object:nil];
    }
    return self;
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

//Items数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    LTLRecommendAlbums *model =self.songSheetArray[section];

    return model.albums.count;
    //    return 100;
}
//组
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return self.songSheetArray.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    //    //重用标识符
    //    static NSString *ID = @"colleCell";
    ///从循环池从取出 cell
    LTLsongSheetCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
    //取出模型数据
    LTLRecommendAlbums *Recommend = self.songSheetArray[indexPath.section];
    XMAlbum *model = Recommend.albums[indexPath.row];
    //赋值模型数据
    cell.model = model;

    return cell;
}
//设置头视图
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (kind == UICollectionElementKindSectionHeader) {

        ///从循环池从取出 cellheadView
        LTLGroupHeader *headView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:HeaderID forIndexPath:indexPath];
        headView.tag = indexPath.section;

        LTLRecommendAlbums *model = self.songSheetArray[indexPath.section];

        headView.model = model;

//        headView.backgroundColor = [UIColor blueColor];
        return headView;

    } else {

        UICollectionReusableView *FooterView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:FooterID forIndexPath:indexPath];
        FooterView.backgroundColor = [UIColor yellowColor];
        FooterView.highly = 0;
        if (indexPath.section == self.songSheetArray.count-1) {
             FooterView.highly = 36;
        }
        return FooterView;
    }

}

#pragma mark - 点击歌单
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    //    NSLog(@"%ld",indexPath.row);
    LTLSongViewController *song = [[LTLSongViewController alloc]init];

    LTLRecommendAlbums *model = self.songSheetArray[indexPath.section];

    song.XMAlbumModel = model.albums[indexPath.row];

//    if ([self.LTLDelegate respondsToSelector:@selector(LTLsongSheet:VC:)]) {
//        [self.LTLDelegate LTLsongSheet:self VC:song];
//    }
    /// 当前信息
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"pushView"] = song;
    dic[@"toView"] = self;
    dic[@"isAnimate"] = @(YES);
    ///发送通知
    [[NSNotificationCenter defaultCenter] postNotificationName:LTLPushViewKey object:nil userInfo:[dic copy]];
}
#pragma mark - 数据
///数据
-(void)DataAcquisition
{

   [LTLNetworkRequest RecommendAlbums:^(NSArray<LTLRecommendAlbums *> * _Nullable modelArray) {
       [self.songSheetArray addObjectsFromArray:modelArray];
       [self reloadData];
   }];

}

@end


text:
public class Subset {
    public static void main(String[] args) {
        RandomizedQueue<String> q = new RandomizedQueue<String>();
        int number = Integer.parseInt(args[0]);
        while (!StdIn.isEmpty()) {
            q.enqueue(StdIn.readString());
        }
       // String [] store = new String[number];
        for (int i = 0; i < number; i++) {
            //String s = q.dequeue();
            StdOut.println(q.dequeue());
        }

    }
}


text:
package auth;

import java.io.Serializable;
import java.util.List;
import java.util.Map;
/**
 * a request for a user's entire login history.
 * effectively GETINFO requests for the users entire history.
 * @author kAG0
 *
 */
public class HISTORY extends Request implements Serializable {
	public List<Map<String, Object>> reply;
	//also needs userPW or (adminName and adminPW) to be set
	public HISTORY(String userName) {
		super(Operation.HISTORY);
		username = userName;
	}
	@Override
	public void setReply(Object reply) {
		this.reply = (List<Map<String, Object>>) reply;
	}
	public String getOpUserName(){
		return username;
	}
	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return super.toString() + "\nHISTORY [reply=" + reply + "]";
	}

}


text:
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
using EOLib.Net;
using EOLib.Net.Communication;
using Moq;

namespace EOLib.Test.TestHelpers
{
    [ExcludeFromCodeCoverage]
    internal static class PacketSendServiceHelpers
    {
        /// <summary>
        /// Setup the PacketSendService mock to return a packet with the specified family/action/data from SendEncodedPacketAndWaitAsync
        /// </summary>
        /// <param name="packetSendServiceMock">The mocked packet send service</param>
        /// <param name="family">Packet family for the "received" packet</param>
        /// <param name="action">Packet action for the "received" packet</param>
        /// <param name="data">Packet data payload (any additional data that should be in the packet)</param>
        internal static void SetupReceivedPacketHasHeader(this Mock<IPacketSendService> packetSendServiceMock,
                                                          PacketFamily family,
                                                          PacketAction action,
                                                          params byte[] data)
        {
            var receivedPacket = new PacketBuilder(family, action)
                .AddBytes(data)
                .Build();

            packetSendServiceMock.Setup(x => x.SendEncodedPacketAndWaitAsync(It.IsAny<IPacket>()))
                                 .Returns(Task.FromResult(receivedPacket));
        }
    }
}


text:
package com.skysport.core.constant;

/**
 * 类说明:
 * Created by zhangjh on 2015/8/21.
 */
public class Authentication {

}


text:
<?php

/**
 * Used for building query string
 */
Define("PARAMS_DELIMITER", "pz_");
/**
 * Used for building query string
 */
Define("STRING_DELIMITER", "sz_");
/**
 * Used for building query string
 */
Define("EQ_DELIMITER", "qz_");

/**
 * Module class
 * @category Modules
 * @package Framework
 * @author Serge Dzheigalo <jey@activeunit.com>
 * @copyright 2002 ActiveUnit
 * @license http://opensource.org/licenses/mit-license.php MIT License
 * @link https://github.com/sergejey/majordomo/blob/master/lib/modules.class.php
 */
class module
{
    /**
     * @var string module name
     */
    var $name;
    /**
     * @var array module output data
     */
    var $data;
    /**
     * @var string module instance name (optional)
     */
    var $instance;
    /**
     * @var string module teplate file (optional)
     */
    var $template;
    /**
     * @var string module execution result
     */
    var $result;
    /**
     * @var object module owner (parent module)
     */
    var $owner;
    /**
     * @var array module configuration
     */
    var $config;

    /**
     * Module constructor
     * this method should me used in context of each module
     * @access public
     */
    public function __construct()
    {
    }

    /**
     * Module execution
     * this method should me used in context of each module
     * @access public
     * @return void
     */
    public function run()
    {
    }

    /**
     * Getting module params from query string
     *
     * Used for getting module execution params
     * this method should me used in context of each module
     *
     * @access public
     * @return void
     */
    public function getParams()
    {
    }

    /**
     * Saving module params for correct query strings building
     * Used to prevent loosing current module state while interraction with child modules
     * @param array $data params to save
     * @access public
     * @return string|void
     */
    public function saveParams($data = 1)
    {
        if (is_array($data)) {
            if (isset($this->instance)) {
                $data["instance"] = $this->instance;
            }

            // echo $this->name." ".$this->instance."
";
            $res = $this->createParamsString($data, $this->name) . PARAMS_DELIMITER . $this->saveParentParams();

            return $res;
        }
    }

    /**
     * Generating query string for saved params
     *
     * @param array $data Params to save
     * @param string $name Name
     * @access private
     * @return string current module params query string
     */
    public function createParamsString($data, $name)
    {
        $params = "";
        $params1 = array();

        foreach ($data as $k => $v) {
            if ($v == "") {
                unset($data[$k]);
            } else {
                $params .= "m" . STRING_DELIMITER . $name . STRING_DELIMITER . $k . EQ_DELIMITER . $v . PARAMS_DELIMITER;
                $params1[] = "$k=$v";
            }
        }

        //echo $params."
";
        //$params=toXML($data);
        //$params=serialize($data);
        if (count($params1)) {
            $params = "$name:{" . implode(",", $params1) . "}";
            //echo $params."
";
            $params = urlencode(base64_encode($params));
        } else {
            $params = "";
            //echo "-
";
        }

        /*
        if (count($data)>0) {
        $temp[$this->name]=$data;
        $xml=new xml_data($temp);
        $res=$xml->string;
        }
         */
        $res = $params;

        return $res;
    }
    // --------------------------------------------------------------------
    /**
     * Restoring module data from query string
     *
     */
    public function restoreParams()
    {
        $pd = gr('pd');
        if (strpos($pd, 'm' . STRING_DELIMITER)) {
            $this->restoreParamsOld();
            return;
        }
        // getting params of all modules
        $modules = explode(PARAMS_DELIMITER, $pd);
        $modulesCnt = count($modules);

        for ($i = 0; $i < $modulesCnt; $i++) {
            $data = base64_decode(urldecode($modules[$i]));

            if (preg_match_all('/(.+?):{(.+?)}/', $data, $matches2, PREG_PATTERN_ORDER)) {
                $matches2Cnt = count($matches2[1]);

                for ($k = 0; $k < $matches2Cnt; $k++) {
                    $cr = array();  // creating params array for current module
                    $module_name = $matches2[1][$k];
                    $module_params = explode(",", $matches2[2][$k]);

                    $moduleParamsCnt = count($module_params);

                    for ($m = 0; $m < $moduleParamsCnt; $m++) {
                        $ar = explode("=", trim($module_params[$m]));

                        $param_name = trim($ar[0]);
                        $param_value = trim($ar[1]);

                        $cr[$param_name] = $param_value;
                    }

                    // setting params for current module
                    // module has instance in params
                    if (isset($cr['instance']) && $cr['instance'] != '') {
                        $instance_params[$module_name][$cr['instance']] = $cr;
                    } else {
                        // module has no instance
                        $global_params[$module_name] = $cr;
                    }
                }
            }
        }

        // restoring params for non-active module
        if (isset($this->instance) && isset($instance_params[$this->name][$this->instance])) {
            // setting params for current instance
            $module_data = $instance_params[$this->name][$this->instance];

            foreach ($module_data as $k => $v) {
                $this->{$k} = $v;
            }
        } elseif (!isset($this->instance)) {
            // module has no instances at all
            $module_data = $global_params[$this->name];
        }

        // setting module data
        if (isset($module_data)) {
            foreach ($module_data as $k => $v) {
                $this->{$k} = $v;
            }
        }
    }

    /**
     * Restoring module data from query string (old version)
     * @deprecated
     * @return void
     */
    public function restoreParamsOld()
    {
        $md=gr('md');             // query param - current module
        $pd=gr('pd');             // query param - all params

        $global_params = array();

        // getting params of all modules
        $pd = str_replace(EQ_DELIMITER, "=", $pd);
        $matchPattern = '/m' . STRING_DELIMITER . '(\w+?)' . STRING_DELIMITER . '(\w+?)=(.*?)' . PARAMS_DELIMITER . '/';

        if (preg_match_all($matchPattern, $pd, $matches, PREG_PATTERN_ORDER)) {
            $matchesCnt = count($matches[1]);
            for ($i = 0; $i < $matchesCnt; $i++) {
                $global_params[$matches[1][$i]][$matches[2][$i]] = $matches[3][$i];
            }
        }

        $xml = new xml_data($global_params);

        if ($md != $this->name) {
            // restoring params for non-active module
            if (isset($xml->hash[$this->name])) {
                $module_data = $xml->hash[$this->name];

                if ((isset($this->instance) && ($module_data["instance"] == $this->instance)) || (!isset($this->instance))) {
                    foreach ($module_data as $k => $v) {
                        $this->{$k} = $v;
                    }
                }
            }
        }

        if ($md == $this->name) {
            // if current module then we should take params directly from query string
            $params = (is_array($_POST) && (count($_POST) > 0)) ? $_POST : $_GET;

            foreach ($params as $k => $v) {
                if (($k == "md") || ($k == "pd") || ($k == "inst") || ($k == "name"))
                    continue;

                // setting params as module properties
                $this->{$k} = $v;
            }
        }
    }

    /**
     * Saving parent module params for correct query strings building
     *
     * @access private
     * @return string parent module params query string
     */
    public function saveParentParams()
    {
        if (isset($this->owner->name))
            return $this->owner->saveParams();

        return "";
    }

    /**
     * Checking module installation status and process with installation if neccessary
     * @return void
     * @access public
     */
    public function checkInstalled()
    {

        $flag_filename = ROOT.'cms/modules_installed/'.$this->name . '.installed';
        if (!file_exists($flag_filename)) {
            $this->install();
        } else {
            /*
            $sqlQuery = "SELECT ID FROM project_modules WHERE NAME = '" . $this->name . "'";
            $rec = SQLSelectOne($sqlQuery);
            if (!isset($rec["ID"])) {
                $this->install();
            }
            */
        }
    }

    /**
     * Getting module configuration
     * Used for loading module config data in $this->config variable
     * @access public
     * @return array
     */
    public function getConfig()
    {
        $sqlQuery = "SELECT *
                     FROM project_modules
                    WHERE NAME = '" . $this->name . "'";

        $rec = SQLSelectOne($sqlQuery);
        $data = $rec["DATA"];

        $this->config = unserialize($data);

        return $this->config;
    }

    /**
     * Saving module configuration
     *
     * Used for saving $this->config variable in project module repository database for future
     * @access public
     * @return void
     */
    public function saveConfig()
    {
        $sqlQuery = "SELECT *
                     FROM project_modules
                    WHERE NAME = '" . $this->name . "'";

        $rec = SQLSelectOne($sqlQuery);

        $rec["DATA"] = serialize($this->config);

        SQLUpdate("project_modules", $rec);
    }

    /**
     * Installing current module
     *
     * Adding information about module in project registry and
     * processing to database installation routine if file "installed" does not
     * exists in module directory.
     *
     * @param string $parent_name Optional parent module for installing packages (reserved for future development)
     * @access private
     * @return void
     */
    public function install($parent_name = "")
    {
        $this->dbInstall("");

        $sqlQuery = "SELECT *
                     FROM project_modules
                    WHERE NAME = '" . $this->name . "'";

        $rec = SQLSelectOne($sqlQuery);
        $rec["NAME"] = $this->name;

        if (!isset($this->title))
            $this->title = $this->name;

        $rec["TITLE"] = $this->title;

        if (isset($this->module_category))
            $rec["CATEGORY"] = $this->module_category;

        if (!isset($rec["ID"])) {
            $rec["ID"] = SQLInsert("project_modules", $rec);
        } else {
            SQLUpdate("project_modules", $rec);
        }
        SQLExec("DELETE FROM project_modules WHERE NAME = '".$this->name."' AND ID!=".$rec["ID"]);

        if (!is_dir(ROOT.'cms/modules_installed')) {
            umask(0);
            mkdir(ROOT.'cms/modules_installed',0777);
        }
        $flag_filename = ROOT.'cms/modules_installed/'.$this->name . '.installed';
        if (!file_exists($flag_filename)) SaveFile($flag_filename, date("H:m d.M.Y"));
    }

    /**
     * UnInstalling current module
     *
     * Removing information about module in project registry and
     *
     * @access private
     * @return void
     */
    public function uninstall()
    {
        $sqlQuery = "SELECT *
                     FROM project_modules
                    WHERE NAME = '" . $this->name . "'";

        $rec = SQLSelectOne($sqlQuery);

        if (isset($rec["ID"])) {
            $sqlQuery = "DELETE
                        FROM project_modules
                       WHERE ID = '" . $rec["ID"] . "'";
            SQLExec($sqlQuery);
        }

        $flag_filename = ROOT.'cms/modules_installed/'.$this->name . '.installed';
        if (file_exists($flag_filename)) unlink($flag_filename);
    }

    // --------------------------------------------------------------------
    /**
     * Module data installation
     *
     * Installing required module data structure into project.
     * (Notes: file "initial.sql" will be executed if found in project directory)
     *
     * @access private
     * @param string $data Required database tables and fields
     * @return void
     */
    public function dbInstall($data)
    {
        $need_optimzation = array();
        $table_defined = array();

        $sql = "";

        $strings = explode("\n", $data);
        $stringsCnt = count($strings);

        for ($i = 0; $i < $stringsCnt; $i++) {
            $strings[$i] = preg_replace('/\/\/.+$/is', '', $strings[$i]);

            $fields = explode(":", $strings[$i]);
            $table = trim(array_shift($fields));

            $definition = trim(implode(':', $fields));
            $definition = str_replace("\r", "", trim($definition));

            if ($definition == "") continue;

            $tmp = explode(" ", $definition);
            $field = $tmp[0];

            if (!in_array(strtolower($field), array('key', 'index', 'fulltext'))) {
                $definition = str_replace($field . ' ', '`' . $field . '` ', $definition);
            }

            if (!isset($table_defined[$table])) {
                // new table
                if (strpos($definition, "auto_increment")) {
                    $definition .= ", PRIMARY KEY(" . $field . ")";
                    //$definition.=", KEY(".$field.")";
                }

                $sql = "CREATE TABLE IF NOT EXISTS $table ($definition) CHARACTER SET utf8 COLLATE utf8_general_ci;";

                $table_defined[$table] = 1;

                SQLExec($sql);

                $result = SQLGetFields($table);
                if (is_array($result)) {
                    foreach ($result as $row) {
                        $tbl_fields[$table][$row['Field']] = 1;
                    }
                }

            } elseif ((strtolower($field) == 'key') || (strtolower($field) == 'index') || (strtolower($field) == 'fulltext')) {
                if (!$indexes_retrieved[$table]) {
                    $result = SQLGetIndexes($table);
                    foreach ($result as $row) {
                        $tbl_indexes[$table][$row['Key_name']] = 1;
                    }

                    $indexes_retrieved[$table] = 1;
                }

                preg_match('/\((.+?)\)/', $definition, $matches);

                $key_name = trim($matches[1], " `");

                if (!isset($tbl_indexes[$table][$key_name])) {
                    $definition = str_replace('`', '', $definition);
                    $sql = "ALTER TABLE $table ADD $definition;";
                    SQLExec($sql);
                    SQLExec("FLUSH TABLES ".$table.";");
                    $to_optimize[] = $table;
                }
            } elseif (!isset($tbl_fields[$table][$field])) {
                // new field
                $sql = "ALTER TABLE $table ADD $definition;";
                SQLExec($sql);
                SQLExec("FLUSH TABLES ".$table.";");
            }
        }

        if (isset($to_optimize[0])) {
            foreach ($to_optimize as $table) {
                SQLExec("OPTIMIZE TABLE " . $table . ";");
            }
        }

        // executing initial query and comments each line to prevent execution next time
        $initialFile = DIR_MODULES . $this->name . "/initial.sql";
        if (file_exists($initialFile)) {
            $data = LoadFile($initialFile);
            $data .= "\n";
            $data = str_replace("\r", "", $data);

            $query = explode("\n", $data);
            $queryCnt = count($query) - 1;

            for ($i = 0; $i < $queryCnt; $i++) {
                if ($query[$i][0] != "#") {
                    SQLExec($query[$i]);
                    $mdf[] = "#" . $query[$i];
                } else {
                    $mdf[] = $query[$i];
                }
            }

            SaveFile($initialFile, join("\n", $mdf));
        }
    }

    /**
     * Getting list of sub-modules
     *
     * Reserved for future development
     *
     * @access private
     * @return array
     */
    public function getSubModules()
    {
        $sqlQuery = "SELECT *
                     FROM project_modules
                    WHERE PARENT_NAME = '" . $this->name . "'";

        return SQLSelect($sqlQuery);
    }

    /**
     * Redirect to another URL whithin project
     *
     * Used for redirection from one URL to another within current module or project
     *
     * @param string $url Special formatted url (ex: "?mode=new", "?(application:{action=test})&md=test&var=value1", etc)
     * @return void
     * @access private
     */
    public function redirect($url)
    {
        global $session;
        global $db;

        $url = $this->makeRealURL($url);

        $session->save();

        if ($_GET['part_load']) {
            $res = array();
            $res['CONTENT'] = '';
            $res['NEED_RELOAD'] = 1;
            $res['REDIRECT'] = $url;
            echo json_encode($res);
            exit;
        }

        if (!headers_sent()) {
            header("Location: $url\n\n");
        } else {
            print "Headers already sent in $filename on line $linenum
\n" . "Cannot redirect instead\n";
        }

        exit;
    }

    /**
     * Create "real" URL for current module
     * @access public
     * @param mixed $url Url
     * @return mixed
     */
    public function makeRealURL($url)
    {
        $param_str = $this->parseLinks("");
        preg_match("", $param_str, $matches);

        $url = $matches[1];
        $url = str_replace("?", "?" . session_name() . "=" . session_id() . "&", $url);

        return $url;
    }

    /**
     * Summary of cached
     * @access public
     * @param mixed $content Content
     * @return string
     */
    public function cached($content)
    {
        $h = md5($content);

        $filename = ROOT . 'cms/cached/' . $this->name . '_' . $h . '.txt';
        $cache_expire = 15 * 60; // 15 minutes cache expiration time

        if (file_exists($filename)) {
            if ((time() - filemtime($filename)) <= $cache_expire) {
                $cached_result = LoadFile($filename);
            } else {
                unlink($filename);
            }
        }

        if (isset($cached_result) && $cached_result == '') {
            $p = new jTemplate(DIR_TEMPLATES . 'null.html', $this->data, $this);

            $cached_result = $p->parse($content, $this->data, DIR_TEMPLATES);

            SaveFile($filename, $cached_result);
        }

        return $cached_result;
    }

    /**
     * Summary of dynamic
     * @access public
     *
     * @param mixed $content Content
     * @return string
     */
    public function dynamic($content)
    {
        $h = md5($content);

        $content = "" . $content . "";
        $filename = ROOT . 'templates_ajax/' . $this->name . '_' . $h . '.html';

        if (!file_exists($filename))
            SaveFile($filename, $content);

        $url = $this->makeRealURL("?");

        if (preg_match('/\?/is', $url)) {
            $url .= "&ajt=" . $h;
        } else {
            $url .= "?ajt=" . $h;
        }

        $res .= "
Loading...
";
        $res .= "";

        return $res;
    }

    /**
     * Parsing links to maintain modules structure and data
     *
     * Used to maintain framework structure by saving modules data
     * in query strings and hidden fields
     * Usage:
     * following will be changed
     * [#link param1=value1#]
     *
     *
     * (note: to prevent link modification use )
     * </form> (note: to prevent "</form>" changing use "</form>" construction)
     *
     * @access private
     *
     * @param mixed $result Result
     * @return mixed
     */
    public function parseLinks($result)
    {
        $md=gr('md');
        if (!isset($_SERVER['PHP_SELF'])) {
            global $PHP_SELF;
            $_SERVER['PHP_SELF'] = $PHP_SELF;
        }

        $param_str = '';

        if ($md != $this->name) {
            $param_str = $this->saveParams();
        } elseif (isset($this->owner)) {
            $param_str = $this->owner->saveParams();
        }

        // a href links like
        if ((preg_match_all('/="\?(.*?)"/is', $result, $matches, PREG_PATTERN_ORDER))) {
            $matchesCnt = count($matches[1]);
            for ($i = 0; $i < $matchesCnt; $i++) {
                $link = $matches[1][$i];

                if (!is_integer(strpos($link, '')))   // skip custom links
                {
                    if (preg_match('/^\((.+?)\)(.*)$/', $link, $matches1)) {
                        $other = $matches1[2];
                        $res_str = $this->codeParams($matches1[1]);
                        $result = str_replace($matches[0][$i], '="' . $_SERVER['PHP_SELF'] . '?pd=' . $res_str . $other . '"', $result);
                    } elseif (strpos($link, "md=") !== 0) {
                        $replaceString = '="' . $_SERVER['PHP_SELF'] . '?pd=' . $param_str;
                        $replaceString .= '&md=' . $this->name . '&inst=' . $this->instance . '&' . $link . '"';

                        $result = str_replace($matches[0][$i], $replaceString, $result); // links
                    } else {
                        $result = str_replace('action="?', 'action="' . $_SERVER['PHP_SELF'] . '"', $result); // forms
                    }
                } else {
                    // remove modified param
                    $link = str_replace('', '', $link);
                    $result = str_replace($matches[0][$i], '="' . $link . '"', $result);
                }
            }
        }

        // form hidden params
        if (preg_match_all('/\<input([^\<\>]+?)(value="\((.*?)\)")([^\<\>]*?)\>/is', $result, $matches, PREG_PATTERN_ORDER)) {
            $matches3Cnt = count($matches[3]);

            for ($i = 0; $i < $matches3Cnt; $i++) {
                if (strpos($matches[1][$i], 'type="hidden"') !== false || strpos($matches[4][$i], 'type="hidden"') !== false) {
                    $res_str = 'value="' . $this->codeParams($matches[3][$i]) . '"';
                    $result = str_replace($matches[2][$i], $res_str, $result);
                }
            }
        }

        // [#link ...#]
        if (preg_match_all('/\[#link (.*?)#\]/is', $result, $matches, PREG_PATTERN_ORDER)) {
            $matches1Cnt = count($matches[1]);
            for ($i = 0; $i < $matches1Cnt; $i++) {
                $link = $matches[1][$i];

                if (preg_match('/^\((.+?)\)(.*)$/', $link, $matches1)) {
                    $other = $matches1[2];
                    $res_str = $this->codeParams($matches1[1]);
                    $result = str_replace($matches[0][$i], $_SERVER['PHP_SELF'] . '?pd=' . $res_str . $other, $result);
                } elseif (strpos($link, "md=") !== 0) {
                    $replaceString = $_SERVER['PHP_SELF'] . '?pd=' . $param_str . '&md=' . $this->name . '&inst=' . $this->instance . '&' . $link;

                    $result = str_replace($matches[0][$i], $replaceString, $result); // links
                }
            }
        }

        // form hidden variables (exclude </form>)
        $replaceString = "<input type=\"hidden\" name=\"pd\" value=\"$param_str\">\n";
        $replaceString .= "<input type=\"hidden\" name=\"md\" value=\"" . $this->name . "\">\n";
        $replaceString .= "<input type=\"hidden\" name=\"inst\" value=\"" . $this->instance . "\">\n";
        $replaceString .= "</FORM>";

        // forms
        $result = preg_replace("/<\/form>(?!)/is", $replaceString, $result);

        return $result;
    }

    /**
     * Parsing params in coded string
     *
     * Used to maintain framework structure by saving modules data
     * in query strings and hidden fields
     *
     * @access private
     *
     * @param mixed $in In
     * @return string
     */
    public function codeParams($in)
    {
        $res_str = '';

        if (preg_match_all('/(.+?):{(.+?)}/', $in, $matches2, PREG_PATTERN_ORDER)) {
            $total = count($matches2[1]);

            for ($k = 0; $k < $total; $k++) {
                $data = array();

                $module_name = $matches2[1][$k];
                $module_params = explode(',', $matches2[2][$k]);

                $totalp = count($module_params);
                for ($m = 0; $m < $totalp; $m++) {
                    $ar = explode("=", trim($module_params[$m]));

                    $data[trim($ar[0])] = trim($ar[1]);
                }

                $res_str .= $this->createParamsString($data, $module_name) . PARAMS_DELIMITER;
            }
        }

        return $res_str;
    }

	public function sendNotification($str, $type = 'default')
    {

        if (!SQLTableExists('module_notifications')) {
            return json_encode(array('status'=>false));
        }

		if($type != 'info' && $type != 'danger' && $type != 'warning' && $type != 'success' && $type != 'default') {
			$type = 'default';
		}

		$rec["ADDED"] = date('Y-m-d H:i:s');
		$rec["TYPE"] = $type;
		$rec["MODULE_NAME"] = $this->name;
		$rec["MESSAGE"] = htmlspecialchars(strip_tags($str));

		if(SQLSelectOne("SELECT COUNT(*) AS TOTAL_UNREAD FROM `module_notifications` WHERE `MODULE_NAME` = '".$rec["MODULE_NAME"]."' AND `IS_READ` = '0'")['TOTAL_UNREAD'] > 10) {
			return json_encode(array('status' => false, 'error' => 'More than 10 notifications in the unread status.'));
		}

		$ifExist = SQLSelectOne("SELECT ID FROM `module_notifications` WHERE `MESSAGE` = '".DBSafe($rec['MESSAGE'])."' AND TYPE='".DBSafe($rec['TYPE'])."' AND `IS_READ` = '0'");
		if(!empty($ifExist) && is_array($ifExist)) {
			return json_encode(array('status' => false, 'error' => 'Notification already exists. ID: '.$ifExist['ID'], 'id' => $ifExist['ID']));
		}

		$rec["ID"] = SQLInsert("module_notifications", $rec);

		return json_encode(array('status' => true, 'id' => $rec["ID"]));

    }

	public function readNotification($notification_id)
    {

        if (!SQLTableExists('module_notifications')) {
            return json_encode(array('status'=>false));
        }

		$rec["ID"] = $notification_id;
		$rec["IS_READ"] = 1;

		if(empty(SQLSelectOne("SELECT ID FROM `module_notifications` WHERE `ID` = '".$rec["ID"]."' AND `IS_READ` = '0'")['ID'])) {
			return json_encode(array('status' => false, 'error' => 'No such noty found'));
		}

		SQLUpdate("module_notifications", $rec);

		return json_encode(array('status' => true));

    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">

<link rel="stylesheet" href="../skin/tigris.css" type="text/css">
<link rel="stylesheet" href="../skin/mysite.css" type="text/css">
<link rel="stylesheet" href="../skin/site.css" type="text/css">
<link media="print" rel="stylesheet" href="../skin/print.css" type="text/css">
<title>Apache POI - POIFS - Java implementation of the OLE 2 Compound Document format</title>

Apache | POI

Home |  | PDF

Apache POI

Top

POIFS

Overview

How To

Embeded Documents

File System Documentation

Use Cases

<form target="_blank" action="http://www.google.com/search" method="get">

	<input value="poi.apache.org" name="sitesearch" type="hidden"><input size="10" name="q" id="query" type="text"><input name="Search" value="GO" type="submit">

                          Search poi

</form>

Apache POI - POIFS - Java implementation of the OLE 2 Compound Document format

Overview

POIFS is a pure Java implementation of the OLE 2 Compound
         Document format.

By definition, all APIs developed by the POI project are
         based somehow on the POIFS API.

A common confusion is on just what POIFS buys you or what OLE
         2 Compound Document format is exactly. POIFS does not buy you
         DOC, or XLS, but is necessary to generate or read DOC or XLS
         files. You see, all file formats based on the OLE 2 Compound
         Document Format have a common structure. The OLE 2 Compound
         Document Format is essentially a convoluted archive
         format. Think of POIFS as a "zip" library. Once you can get
         the data in a zip file you still need to interpret the
         data. As a general rule, while all of our formats use
         POIFS, most of them attempt to abstract you from it. There
         are some circumstances where this is not possible, but as a
         general rule this is true.

If you're an end user type just looking to generate XLS
         files, then you'd be looking for HSSF not POIFS; however, if
         you have legacy code that uses MFC property sets, POIFS is
         for you!  Regardless, you may or may not need to know how to
         use POIFS but ultimately if you use technologies that come
         from the POI project, you're using POIFS underneith.  Perhaps
         we should have a branding campaign "POIFS Inside!".  ;-)

by Andrew C. Oliver, Nicola Ken Barozzi

              Copyright © 2002-2007 The Apache Software Foundation. All rights reserved.


text:
export { User } from './user'
export { Task } from './task'


text:
package ces;

import java.util.Random;
import java.util.Scanner;

public class JogoAdvinha {

	public static void main(String[] args) {
		// Instancia um objeto do tipo Scanner que serve
		// para ler dados a partir do teclado.
		Scanner keyboard = new Scanner(System.in);
		// Instancia vari�veis
		Random gerador = new Random();
		int valor = gerador.nextInt(10) + 1;
		int numero;
		int tentativas = 0;
		// System.out.println(valor);

		do {
			System.out.println("Digite o n�mero: ");

			numero = keyboard.nextInt();

			// Valida n�mero digitado com sorteado
			if (valor < numero) {
				System.out.println("Tente um numero Menor!\n");
				// Soma as tentativas
				tentativas++;

			} else {
				System.out.println("Tente um numero Maior");
				tentativas++;
			}

			// Enquanto n�o acertar o n�mero repete o la�o
		} while (numero != valor);

		// Imprime resultado
		System.out.println("\n\nParab�ns - voc� acertou o n�mero "+ valor +" em " + tentativas
				+ " tentativas");

		keyboard.close();
	}

}