text:
package com.hurence.logisland.engine.spark.remote;

import okhttp3.Credentials;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.junit.Assert;
import org.junit.Test;

import javax.ws.rs.core.HttpHeaders;
import java.time.Duration;
import java.util.concurrent.TimeUnit;

public class RemoteApiClientTest {

    private final String dataflowName = "dummy";

    private RemoteApiClient createInstance(MockWebServer server, String user, String password) {
        return new RemoteApiClient(new RemoteApiClient.ConnectionSettings( server.url("/").toString(),
                Duration.ofSeconds(2), Duration.ofSeconds(2), user, password));
    }

    @Test
    public void testAllUnsecured() throws Exception {

        try (MockWebServer mockWebServer = new MockWebServer()) {
            mockWebServer.enqueue(new MockResponse().setResponseCode(404));
            mockWebServer.enqueue(new MockResponse().setBodyDelay(3, TimeUnit.SECONDS));
            final String dummy = "\"name\":\"myName\", \"component\":\"myComponent\"";
            mockWebServer.enqueue(new MockResponse().setBody("{" + dummy + ",\"lastModified\":\"1983-06-04T10:01:02Z\"," +
                    "\"streams\":[{" + dummy + "}]}"));
            RemoteApiClient client = createInstance(mockWebServer, null, null);
            Assert.assertFalse(client.fetchDataflow(dataflowName, new RemoteApiClient.State()).isPresent());
            Assert.assertFalse(client.fetchDataflow(dataflowName, new RemoteApiClient.State()).isPresent());
            Assert.assertTrue(client.fetchDataflow(dataflowName, new RemoteApiClient.State()).isPresent());

        }

    }

    @Test
    public void testValidationFails() throws Exception {
        try (MockWebServer mockWebServer = new MockWebServer()) {
            mockWebServer.enqueue(new MockResponse().setBody("{\"name\":\"divPo\", \"lastModified\":\"1983-06-04T10:01:02Z\",\"services\":[{}],\"streams\":[{}]}"));
            RemoteApiClient client = createInstance(mockWebServer, null, null);
            Assert.assertFalse(client.fetchDataflow(dataflowName, new RemoteApiClient.State()).isPresent());
        }

    }

    @Test
    public void testAuthentication() throws Exception {
        try (MockWebServer mockWebServer = new MockWebServer()) {
            RemoteApiClient client = createInstance(mockWebServer, "test", "test");
            mockWebServer.enqueue(new MockResponse().setBody("{}"));
            client.fetchDataflow(dataflowName, new RemoteApiClient.State());
            RecordedRequest request = mockWebServer.takeRequest();
            String auth = request.getHeader(HttpHeaders.AUTHORIZATION);
            Assert.assertEquals(Credentials.basic("test", "test"), auth);
        }
    }

    @Test
    public void testUri() throws Exception {
        try (MockWebServer mockWebServer = new MockWebServer()) {
            RemoteApiClient client = createInstance(mockWebServer, null, null);
            mockWebServer.enqueue(new MockResponse().setBody("{}"));
            client.fetchDataflow(dataflowName, new RemoteApiClient.State());
            RecordedRequest request = mockWebServer.takeRequest();
            Assert.assertEquals("/dataflows/"+dataflowName, request.getPath());
        }
    }
}


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

    <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=9"/>
    <meta name="generator" content="Doxygen 1.8.6"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <title>Generic Image Library: packed_image_type< BitField, ChannelBitSizeVector, Layout, Alloc > Struct Template Reference</title>
    <link href="tabs.css" rel="stylesheet" type="text/css"/>

    <link href="doxygen.css" rel="stylesheet" type="text/css" />
    <link href="doxygen-boost.css" rel="stylesheet" type="text/css"/>

Main Page

Modules

Classes

Files

Class List

Class Index

Class Hierarchy

Class Members

boost

gil

packed_image_type

Public Types |
List of all members

packed_image_type< BitField, ChannelBitSizeVector, Layout, Alloc > Struct Template Reference
packed_image_type,bit_aligned_image_type

Returns the type of an interleaved packed image: an image whose channels may not be byte-aligned, but whose pixels are byte aligned.
 More...

#include <metafunctions.hpp>

Public Types

typedef image< typename

packed_pixel_type< BitField,

ChannelBitSizeVector, Layout >

::type, false, Alloc > 	type

Detailed Description

template<typename BitField, typename ChannelBitSizeVector, typename Layout, typename Alloc = std::allocator<unsigned char>>

struct boost::gil::packed_image_type< BitField, ChannelBitSizeVector, Layout, Alloc >

Returns the type of an interleaved packed image: an image whose channels may not be byte-aligned, but whose pixels are byte aligned.

The documentation for this struct was generated from the following file:

metafunctions.hpp

     <address class="footer">

        Generated on Wed Dec 5 2018 20:05:51 for Generic Image Library by  doxygen 1.8.6

    </address>

redpajama_set_name: RedPajamaGithub


text:
package com.sun.java.util.jar.pack;

import com.sun.java.util.jar.pack.ConstantPool.ClassEntry;
import com.sun.java.util.jar.pack.ConstantPool.DescriptorEntry;
import com.sun.java.util.jar.pack.ConstantPool.Entry;
import com.sun.java.util.jar.pack.ConstantPool.SignatureEntry;
import com.sun.java.util.jar.pack.ConstantPool.MemberEntry;
import com.sun.java.util.jar.pack.ConstantPool.MethodHandleEntry;
import com.sun.java.util.jar.pack.ConstantPool.BootstrapMethodEntry;
import com.sun.java.util.jar.pack.ConstantPool.Utf8Entry;
import com.sun.java.util.jar.pack.Package.Class;
import com.sun.java.util.jar.pack.Package.InnerClass;
import java.io.DataInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import static com.sun.java.util.jar.pack.Constants.*;

/**
 * Reader for a class file that is being incorporated into a package.
 * @author John Rose
 */
class ClassReader {
    int verbose;

    Package pkg;
    Class cls;
    long inPos;
    long constantPoolLimit = -1;
    DataInputStream in;
    Map<Attribute.Layout, Attribute> attrDefs;
    Map<Attribute.Layout, String> attrCommands;
    String unknownAttrCommand = "error";;

    ClassReader(Class cls, InputStream in) throws IOException {
        this.pkg = cls.getPackage();
        this.cls = cls;
        this.verbose = pkg.verbose;
        this.in = new DataInputStream(new FilterInputStream(in) {
            public int read(byte b[], int off, int len) throws IOException {
                int nr = super.read(b, off, len);
                if (nr >= 0)  inPos += nr;
                return nr;
            }
            public int read() throws IOException {
                int ch = super.read();
                if (ch >= 0)  inPos += 1;
                return ch;
            }
            public long skip(long n) throws IOException {
                long ns = super.skip(n);
                if (ns >= 0)  inPos += ns;
                return ns;
            }
        });
    }

    public void setAttrDefs(Map<Attribute.Layout, Attribute> attrDefs) {
        this.attrDefs = attrDefs;
    }

    public void setAttrCommands(Map<Attribute.Layout, String> attrCommands) {
        this.attrCommands = attrCommands;
    }

    private void skip(int n, String what) throws IOException {
        Utils.log.warning("skipping "+n+" bytes of "+what);
        long skipped = 0;
        while (skipped < n) {
            long j = in.skip(n - skipped);
            assert(j > 0);
            skipped += j;
        }
        assert(skipped == n);
    }

    private int readUnsignedShort() throws IOException {
        return in.readUnsignedShort();
    }

    private int readInt() throws IOException {
        return in.readInt();
    }

    /** Read a 2-byte int, and return the global CP entry for it. */
    private Entry readRef() throws IOException {
        int i = in.readUnsignedShort();
        return i == 0 ? null : cls.cpMap[i];
    }

    private Entry readRef(byte tag) throws IOException {
        Entry e = readRef();
        assert(!(e instanceof UnresolvedEntry));
        checkTag(e, tag);
        return e;
    }

    /** Throw a ClassFormatException if the entry does not match the expected tag type. */
    private Entry checkTag(Entry e, byte tag) throws ClassFormatException {
        if (e == null || !e.tagMatches(tag)) {
            String where = (inPos == constantPoolLimit
                                ? " in constant pool"
                                : " at pos: " + inPos);
            String got = (e == null
                            ? "null CP index"
                            : "type=" + ConstantPool.tagName(e.tag));
            throw new ClassFormatException("Bad constant, expected type=" +
                    ConstantPool.tagName(tag) +
                    " got "+ got + ", in File: " + cls.file.nameString + where);
        }
        return e;
    }
    private Entry checkTag(Entry e, byte tag, boolean nullOK) throws ClassFormatException {
        return nullOK && e == null ? null : checkTag(e, tag);
    }

    private Entry readRefOrNull(byte tag) throws IOException {
        Entry e = readRef();
        checkTag(e, tag, true);
        return e;
    }

    private Utf8Entry readUtf8Ref() throws IOException {
        return (Utf8Entry) readRef(CONSTANT_Utf8);
    }

    private ClassEntry readClassRef() throws IOException {
        return (ClassEntry) readRef(CONSTANT_Class);
    }

    private ClassEntry readClassRefOrNull() throws IOException {
        return (ClassEntry) readRefOrNull(CONSTANT_Class);
    }

    private SignatureEntry readSignatureRef() throws IOException {
        // The class file stores a Utf8, but we want a Signature.
        Entry e = readRef(CONSTANT_Signature);
        return (e != null && e.getTag() == CONSTANT_Utf8)
                ? ConstantPool.getSignatureEntry(e.stringValue())
                : (SignatureEntry) e;
    }

    void read() throws IOException {
        boolean ok = false;
        try {
            readMagicNumbers();
            readConstantPool();
            readHeader();
            readMembers(false);  // fields
            readMembers(true);   // methods
            readAttributes(ATTR_CONTEXT_CLASS, cls);
            fixUnresolvedEntries();
            cls.finishReading();
            assert(0 >= in.read(new byte[1]));
            ok = true;
        } finally {
            if (!ok) {
                if (verbose > 0) Utils.log.warning("Erroneous data at input offset "+inPos+" of "+cls.file);
            }
        }
    }

    void readMagicNumbers() throws IOException {
        cls.magic = in.readInt();
        if (cls.magic != JAVA_MAGIC)
            throw new Attribute.FormatException
                ("Bad magic number in class file "
                 +Integer.toHexString(cls.magic),
                 ATTR_CONTEXT_CLASS, "magic-number", "pass");
        int minver = (short) readUnsignedShort();
        int majver = (short) readUnsignedShort();
        cls.version = Package.Version.of(majver, minver);

        //System.out.println("ClassFile.version="+cls.majver+"."+cls.minver);
        String bad = checkVersion(cls.version);
        if (bad != null) {
            throw new Attribute.FormatException
                ("classfile version too "+bad+": "
                 +cls.version+" in "+cls.file,
                 ATTR_CONTEXT_CLASS, "version", "pass");
        }
    }

    private String checkVersion(Package.Version ver) {
        int majver = ver.major;
        int minver = ver.minor;
        if (majver < pkg.minClassVersion.major ||
            (majver == pkg.minClassVersion.major &&
             minver < pkg.minClassVersion.minor)) {
            return "small";
        }
        if (majver > pkg.maxClassVersion.major ||
            (majver == pkg.maxClassVersion.major &&
             minver > pkg.maxClassVersion.minor)) {
            return "large";
        }
        return null;  // OK
    }

    void readConstantPool() throws IOException {
        int length = in.readUnsignedShort();
        //System.err.println("reading CP, length="+length);

        int[] fixups = new int[length*4];
        int fptr = 0;

        Entry[] cpMap = new Entry[length];
        cpMap[0] = null;
        for (int i = 1; i < length; i++) {
            //System.err.println("reading CP elt, i="+i);
            int tag = in.readByte();
            switch (tag) {
                case CONSTANT_Utf8:
                    cpMap[i] = ConstantPool.getUtf8Entry(in.readUTF());
                    break;
                case CONSTANT_Integer:
                    {
                        cpMap[i] = ConstantPool.getLiteralEntry(in.readInt());
                    }
                    break;
                case CONSTANT_Float:
                    {
                        cpMap[i] = ConstantPool.getLiteralEntry(in.readFloat());
                    }
                    break;
                case CONSTANT_Long:
                    {
                        cpMap[i] = ConstantPool.getLiteralEntry(in.readLong());
                        cpMap[++i] = null;
                    }
                    break;
                case CONSTANT_Double:
                    {
                        cpMap[i] = ConstantPool.getLiteralEntry(in.readDouble());
                        cpMap[++i] = null;
                    }
                    break;

                // just read the refs; do not attempt to resolve while reading
                case CONSTANT_Class:
                case CONSTANT_String:
                case CONSTANT_MethodType:
                    fixups[fptr++] = i;
                    fixups[fptr++] = tag;
                    fixups[fptr++] = in.readUnsignedShort();
                    fixups[fptr++] = -1;  // empty ref2
                    break;
                case CONSTANT_Fieldref:
                case CONSTANT_Methodref:
                case CONSTANT_InterfaceMethodref:
                case CONSTANT_NameandType:
                    fixups[fptr++] = i;
                    fixups[fptr++] = tag;
                    fixups[fptr++] = in.readUnsignedShort();
                    fixups[fptr++] = in.readUnsignedShort();
                    break;
                case CONSTANT_InvokeDynamic:
                    fixups[fptr++] = i;
                    fixups[fptr++] = tag;
                    fixups[fptr++] = -1 ^ in.readUnsignedShort();  // not a ref
                    fixups[fptr++] = in.readUnsignedShort();
                    break;
                case CONSTANT_MethodHandle:
                    fixups[fptr++] = i;
                    fixups[fptr++] = tag;
                    fixups[fptr++] = -1 ^ in.readUnsignedByte();
                    fixups[fptr++] = in.readUnsignedShort();
                    break;
                default:
                    throw new ClassFormatException("Bad constant pool tag " +
                            tag + " in File: " + cls.file.nameString +
                            " at pos: " + inPos);
            }
        }
        constantPoolLimit = inPos;

        // Fix up refs, which might be out of order.
        while (fptr > 0) {
            if (verbose > 3)
                Utils.log.fine("CP fixups ["+fptr/4+"]");
            int flimit = fptr;
            fptr = 0;
            for (int fi = 0; fi < flimit; ) {
                int cpi = fixups[fi++];
                int tag = fixups[fi++];
                int ref = fixups[fi++];
                int ref2 = fixups[fi++];
                if (verbose > 3)
                    Utils.log.fine("  cp["+cpi+"] = "+ConstantPool.tagName(tag)+"{"+ref+","+ref2+"}");
                if (ref >= 0 && cpMap[ref] == null || ref2 >= 0 && cpMap[ref2] == null) {
                    // Defer.
                    fixups[fptr++] = cpi;
                    fixups[fptr++] = tag;
                    fixups[fptr++] = ref;
                    fixups[fptr++] = ref2;
                    continue;
                }
                switch (tag) {
                case CONSTANT_Class:
                    cpMap[cpi] = ConstantPool.getClassEntry(cpMap[ref].stringValue());
                    break;
                case CONSTANT_String:
                    cpMap[cpi] = ConstantPool.getStringEntry(cpMap[ref].stringValue());
                    break;
                case CONSTANT_Fieldref:
                case CONSTANT_Methodref:
                case CONSTANT_InterfaceMethodref:
                    ClassEntry      mclass = (ClassEntry)      checkTag(cpMap[ref],  CONSTANT_Class);
                    DescriptorEntry mdescr = (DescriptorEntry) checkTag(cpMap[ref2], CONSTANT_NameandType);
                    cpMap[cpi] = ConstantPool.getMemberEntry((byte)tag, mclass, mdescr);
                    break;
                case CONSTANT_NameandType:
                    Utf8Entry mname = (Utf8Entry) checkTag(cpMap[ref],  CONSTANT_Utf8);
                    Utf8Entry mtype = (Utf8Entry) checkTag(cpMap[ref2], CONSTANT_Signature);
                    cpMap[cpi] = ConstantPool.getDescriptorEntry(mname, mtype);
                    break;
                case CONSTANT_MethodType:
                    cpMap[cpi] = ConstantPool.getMethodTypeEntry((Utf8Entry) checkTag(cpMap[ref], CONSTANT_Signature));
                    break;
                case CONSTANT_MethodHandle:
                    byte refKind = (byte)(-1 ^ ref);
                    MemberEntry memRef = (MemberEntry) checkTag(cpMap[ref2], CONSTANT_AnyMember);
                    cpMap[cpi] = ConstantPool.getMethodHandleEntry(refKind, memRef);
                    break;
                case CONSTANT_InvokeDynamic:
                    DescriptorEntry idescr = (DescriptorEntry) checkTag(cpMap[ref2], CONSTANT_NameandType);
                    cpMap[cpi] = new UnresolvedEntry((byte)tag, (-1 ^ ref), idescr);
                    // Note that ref must be resolved later, using the BootstrapMethods attribute.
                    break;
                default:
                    assert(false);
                }
            }
            assert(fptr < flimit);  // Must make progress.
        }

        cls.cpMap = cpMap;
    }

    private /*non-static*/
    class UnresolvedEntry extends Entry {
        final Object[] refsOrIndexes;
        UnresolvedEntry(byte tag, Object... refsOrIndexes) {
            super(tag);
            this.refsOrIndexes = refsOrIndexes;
            ClassReader.this.haveUnresolvedEntry = true;
        }
        Entry resolve() {
            Class cls = ClassReader.this.cls;
            Entry res;
            switch (tag) {
            case CONSTANT_InvokeDynamic:
                BootstrapMethodEntry iboots = cls.bootstrapMethods.get((Integer) refsOrIndexes[0]);
                DescriptorEntry         idescr = (DescriptorEntry) refsOrIndexes[1];
                res = ConstantPool.getInvokeDynamicEntry(iboots, idescr);
                break;
            default:
                throw new AssertionError();
            }
            return res;
        }
        private void unresolved() { throw new RuntimeException("unresolved entry has no string"); }
        public int compareTo(Object x) { unresolved(); return 0; }
        public boolean equals(Object x) { unresolved(); return false; }
        protected int computeValueHash() { unresolved(); return 0; }
        public String stringValue() { unresolved(); return toString(); }
        public String toString() { return "(unresolved "+ConstantPool.tagName(tag)+")"; }
    }

    boolean haveUnresolvedEntry;
    private void fixUnresolvedEntries() {
        if (!haveUnresolvedEntry)  return;
        Entry[] cpMap = cls.getCPMap();
        for (int i = 0; i < cpMap.length; i++) {
            Entry e = cpMap[i];
            if (e instanceof UnresolvedEntry) {
                cpMap[i] = e = ((UnresolvedEntry)e).resolve();
                assert(!(e instanceof UnresolvedEntry));
            }
        }
        haveUnresolvedEntry = false;
    }

    void readHeader() throws IOException {
        cls.flags = readUnsignedShort();
        cls.thisClass = readClassRef();
        cls.superClass = readClassRefOrNull();
        int ni = readUnsignedShort();
        cls.interfaces = new ClassEntry[ni];
        for (int i = 0; i < ni; i++) {
            cls.interfaces[i] = readClassRef();
        }
    }

    void readMembers(boolean doMethods) throws IOException {
        int nm = readUnsignedShort();
        for (int i = 0; i < nm; i++) {
            readMember(doMethods);
        }
    }

    void readMember(boolean doMethod) throws IOException {
        int    mflags = readUnsignedShort();
        Utf8Entry       mname = readUtf8Ref();
        SignatureEntry  mtype = readSignatureRef();
        DescriptorEntry descr = ConstantPool.getDescriptorEntry(mname, mtype);
        Class.Member m;
        if (!doMethod)
            m = cls.new Field(mflags, descr);
        else
            m = cls.new Method(mflags, descr);
        readAttributes(!doMethod ? ATTR_CONTEXT_FIELD : ATTR_CONTEXT_METHOD,
                       m);
    }
    void readAttributes(int ctype, Attribute.Holder h) throws IOException {
        int na = readUnsignedShort();
        if (na == 0)  return;  // nothing to do here
        if (verbose > 3)
            Utils.log.fine("readAttributes "+h+" ["+na+"]");
        for (int i = 0; i < na; i++) {
            String name = readUtf8Ref().stringValue();
            int length = readInt();
            // See if there is a special command that applies.
            if (attrCommands != null) {
                Attribute.Layout lkey = Attribute.keyForLookup(ctype, name);
                String cmd = attrCommands.get(lkey);
                if (cmd != null) {
                    switch (cmd) {
                        case "pass":
                            String message1 = "passing attribute bitwise in " + h;
                            throw new Attribute.FormatException(message1, ctype, name, cmd);
                        case "error":
                            String message2 = "attribute not allowed in " + h;
                            throw new Attribute.FormatException(message2, ctype, name, cmd);
                        case "strip":
                            skip(length, name + " attribute in " + h);
                            continue;
                    }
                }
            }
            // Find canonical instance of the requested attribute.
            Attribute a = Attribute.lookup(Package.attrDefs, ctype, name);
            if (verbose > 4 && a != null)
                Utils.log.fine("pkg_attribute_lookup "+name+" = "+a);
            if (a == null) {
                a = Attribute.lookup(this.attrDefs, ctype, name);
                if (verbose > 4 && a != null)
                    Utils.log.fine("this "+name+" = "+a);
            }
            if (a == null) {
                a = Attribute.lookup(null, ctype, name);
                if (verbose > 4 && a != null)
                    Utils.log.fine("null_attribute_lookup "+name+" = "+a);
            }
            if (a == null && length == 0) {
                // Any zero-length attr is "known"...
                // We can assume an empty attr. has an empty layout.
                // Handles markers like Enum, Bridge, Synthetic, Deprecated.
                a = Attribute.find(ctype, name, "");
            }
            boolean isStackMap = (ctype == ATTR_CONTEXT_CODE
                                  && (name.equals("StackMap") ||
                                      name.equals("StackMapX")));
            if (isStackMap) {
                // Known attribute but with a corner case format, "pass" it.
                Code code = (Code) h;
                final int TOO_BIG = 0x10000;
                if (code.max_stack   >= TOO_BIG ||
                    code.max_locals  >= TOO_BIG ||
                    code.getLength() >= TOO_BIG ||
                    name.endsWith("X")) {
                    // No, we don't really know what to do this this one.
                    // Do not compress the rare and strange "u4" and "X" cases.
                    a = null;
                }
            }
            if (a == null) {
                if (isStackMap) {
                    // Known attribute but w/o a format; pass it.
                    String message = "unsupported StackMap variant in "+h;
                    throw new Attribute.FormatException(message, ctype, name,
                                                        "pass");
                } else if ("strip".equals(unknownAttrCommand)) {
                    // Skip the unknown attribute.
                    skip(length, "unknown "+name+" attribute in "+h);
                    continue;
                } else {
                    String message = " is unknown attribute in class " + h;
                    throw new Attribute.FormatException(message, ctype, name,
                                                        unknownAttrCommand);
                }
            }
            long pos0 = inPos;  // in case we want to check it
            if (a.layout() == Package.attrCodeEmpty) {
                // These are hardwired.
                Class.Method m = (Class.Method) h;
                m.code = new Code(m);
                try {
                    readCode(m.code);
                } catch (Instruction.FormatException iie) {
                    String message = iie.getMessage() + " in " + h;
                    throw new ClassReader.ClassFormatException(message, iie);
                }
                assert(length == inPos - pos0);
                // Keep empty attribute a...
            } else if (a.layout() == Package.attrBootstrapMethodsEmpty) {
                assert(h == cls);
                readBootstrapMethods(cls);
                assert(length == inPos - pos0);
                // Delete the attribute; it is logically part of the constant pool.
                continue;
            } else if (a.layout() == Package.attrInnerClassesEmpty) {
                // These are hardwired also.
                assert(h == cls);
                readInnerClasses(cls);
                assert(length == inPos - pos0);
                // Keep empty attribute a...
            } else if (length > 0) {
                byte[] bytes = new byte[length];
                in.readFully(bytes);
                a = a.addContent(bytes);
            }
            if (a.size() == 0 && !a.layout().isEmpty()) {
                throw new ClassFormatException(name +
                        ": attribute length cannot be zero, in " + h);
            }
            h.addAttribute(a);
            if (verbose > 2)
                Utils.log.fine("read "+a);
        }
    }

    void readCode(Code code) throws IOException {
        code.max_stack = readUnsignedShort();
        code.max_locals = readUnsignedShort();
        code.bytes = new byte[readInt()];
        in.readFully(code.bytes);
        Entry[] cpMap = cls.getCPMap();
        Instruction.opcodeChecker(code.bytes, cpMap, this.cls.version);
        int nh = readUnsignedShort();
        code.setHandlerCount(nh);
        for (int i = 0; i < nh; i++) {
            code.handler_start[i] = readUnsignedShort();
            code.handler_end[i]   = readUnsignedShort();
            code.handler_catch[i] = readUnsignedShort();
            code.handler_class[i] = readClassRefOrNull();
        }
        readAttributes(ATTR_CONTEXT_CODE, code);
    }

    void readBootstrapMethods(Class cls) throws IOException {
        BootstrapMethodEntry[] bsms = new BootstrapMethodEntry[readUnsignedShort()];
        for (int i = 0; i < bsms.length; i++) {
            MethodHandleEntry bsmRef = (MethodHandleEntry) readRef(CONSTANT_MethodHandle);
            Entry[] argRefs = new Entry[readUnsignedShort()];
            for (int j = 0; j < argRefs.length; j++) {
                argRefs[j] = readRef(CONSTANT_LoadableValue);
            }
            bsms[i] = ConstantPool.getBootstrapMethodEntry(bsmRef, argRefs);
        }
        cls.setBootstrapMethods(Arrays.asList(bsms));
    }

    void readInnerClasses(Class cls) throws IOException {
        int nc = readUnsignedShort();
        ArrayList<InnerClass> ics = new ArrayList<>(nc);
        for (int i = 0; i < nc; i++) {
            InnerClass ic =
                new InnerClass(readClassRef(),
                               readClassRefOrNull(),
                               (Utf8Entry)readRefOrNull(CONSTANT_Utf8),
                               readUnsignedShort());
            ics.add(ic);
        }
        cls.innerClasses = ics;  // set directly; do not use setInnerClasses.
        // (Later, ics may be transferred to the pkg.)
    }

    static class ClassFormatException extends IOException {
        private static final long serialVersionUID = -3564121733989501833L;

        public ClassFormatException(String message) {
            super(message);
        }

        public ClassFormatException(String message, Throwable cause) {
            super(message, cause);
        }
    }
}


text:
using System;

namespace WaterLogged.Serialization
{
    public class ConfigReadException : Exception
    {
        public ConfigReadException()
        {
        }

        public ConfigReadException(string message) : base(message)
        {
        }

        public ConfigReadException(string message, Exception inner) : base(message, inner)
        {
        }
    }
}


text:
- Slide pour se présenter
- Fixer les snippets trop grands
- Appli Mobiles


text:
![latest tag](https://img.shields.io/github/v/tag/STMicroelectronics/cmsis_device_u5.svg?color=brightgreen)

## Overview

**STM32Cube** is an STMicroelectronics original initiative to ease the developers life by reducing efforts, time and cost.

**STM32Cube** covers the overall STM32 products portfolio. It includes a comprehensive embedded software platform delivered for each STM32 series.
   * The CMSIS modules (core and device) corresponding to the ARM(tm) core implemented in this STM32 product.
   * The STM32 HAL-LL drivers, an abstraction layer offering a set of APIs ensuring maximized portability across the STM32 portfolio.
   * The BSP drivers of each evaluation, demonstration or nucleo board provided for this STM32 series.
   * A consistent set of middleware libraries such as RTOS, USB, FatFS, graphics, touch sensing library...
   * A full set of software projects (basic examples, applications, and demonstrations) for each board provided for this STM32 series.

Two models of publication are proposed for the STM32Cube embedded software:
   * The monolithic **MCU Package**: all STM32Cube software modules of one STM32 series are present (Drivers, Middleware, Projects, Utilities) in the repository (usual name **STM32Cubexx**, xx corresponding to the STM32 series).
   * The **MCU component**: each STM32Cube software module being part of the STM32Cube MCU Package, is delivered as an individual repository, allowing the user to select and get only the required software functions.

## Description

This **cmsis_device_u5** MCU component repo is one element of the STM32CubeU5 MCU embedded software package, providing the **cmsis device** part.

## Release note

Details about the content of this release are available in the release note [here](https://htmlpreview.github.io/?https://github.com/STMicroelectronics/cmsis_device_u5/blob/main/Release_Notes.html).

## Compatibility information

In this table, you can find the successive versions of this CMSIS Device component, in-line with the corresponding versions of the full MCU package:

CMSIS Device U5 | CMSIS Core      | Was delivered in the full MCU package
--------------- | --------------- | -------------------------------------
Tag v1.0.0      | Tag v5.6.0_cm33 | Tag v1.0.0 (and following, if any, till next CMSIS tag)
Tag v1.0.1      | Tag v5.6.0_cm33 | Tag v1.0.1 (and following, if any, till next CMSIS tag)

The full **STM32CubeU5** MCU package is available [here](https://github.com/STMicroelectronics/STM32CubeU5).

## Troubleshooting

Please refer to the [CONTRIBUTING.md](CONTRIBUTING.md) guide.


text:
{-# OPTIONS_GHC -Wall -fno-warn-hi-shadowing -fno-warn-unused-do-bind -fno-warn-name-shadowing #-}
module Env where

import Types

import Data.IORef (writeIORef, readIORef, newIORef)
import Control.Monad.IO.Class (liftIO)
import Control.Monad (liftM)
import Control.Monad.Error (throwError)

isBound :: Env -> String -> IO Bool
isBound envRef var = readIORef envRef >>= return . maybe False (const True) . lookup var

getVar :: Env -> String -> IOThrowsError TVal
getVar envRef var = do
    env <- liftIO $ readIORef envRef
    case lookup var env of
        Just v  -> liftIO $ readIORef v
        Nothing -> throwError $ UnboundVar "Getting an unbound variable" var

setVar :: Env -> String -> TVal -> IOThrowsError TVal
setVar envRef var val = do
    env <- liftIO $ readIORef envRef
    case lookup var env of
        Just v  -> liftIO $ writeIORef v val
        Nothing -> throwError $ UnboundVar "Setting an unbound variable." var
    return val

defineVar :: Env -> String -> TVal -> IOThrowsError TVal
defineVar envRef var val = do
    alreadyDefined <- liftIO $ isBound envRef var
    if alreadyDefined
        then setVar envRef var val >> return val
        else liftIO $ do
            valRef <- newIORef val
            env <- readIORef envRef
            writeIORef envRef ((var, valRef):env)
            return val

bindVars :: Env -> [(String, TVal)] -> IO Env
bindVars envRef bindings = do
    env <- readIORef envRef
    extEnv <- extendEnv bindings env
    newIORef extEnv
  where extendEnv bindings env = liftM (++ env) (mapM addBinding bindings)
        addBinding (var, val) = do
            ref <- newIORef val
            return (var, ref)


text:
(function(){

	function CalendarService($resource){
		var CalendarService = {};

		CalendarService.resource = $resource('/forum/calendar',{viewTypeId : '@viewTypeId'},
		{
			upcomingEvents : {
				url : '/forum/calendar/upcoming',
				method : 'GET',
				isArray: true
			},
			upcomingBirthdays : {
				url : '/forum/calendar/birthday',
				method : 'GET',
				isArray : true
			}
		});

		CalendarService.getToday = function(){
			var today = new Date();
			var mm = today.getMonth() + 1; // getMonth() is zero-based
			var dd = today.getDate();

			return [(mm>9 ? '' : '0') + mm,
					(dd>9 ? '' : '0') + dd,
					today.getFullYear()
		         ].join('/');
		};

		CalendarService.formatDate = function(day, month, year){
			return [(month>9 ? '' : '0') + month,
				(day>9 ? '' : '0') + day,
				year
	         ].join('/');
		};

		CalendarService.getMonth = function(month, year){
			var formattedDate = CalendarService.formatDate(1, month, year);

			return CalendarService.resource.get({viewTypeId: 0, startingDt: formattedDate});
		};

		CalendarService.changeDate = function(vm, date){
			if(date.date !== null){
				vm.calendar.selectedDate = date;

				//set the selected param
				vm.calendar.weeks.forEach(function(week){
					week.daysOfWeek.forEach(function(day){
						day.isSelected = false;
					});
				});

				date.isSelected = true;
			}
		};

		return CalendarService;
	}

	angular.module("zfgc.calendar")
		   .service('CalendarService', ['$resource', CalendarService]);

})();


text:
PhotonEndPoint makePhotonEndPoint(const Photon photon, const Intersection intersection) {

	return (PhotonEndPoint) {photon, intersection};
}


text:
namespace RAT {

  CfGen::CfGen() :
    stateStr(""),
    isotope(252),
    posGen(0)
  {
    // As in the combo generator, use a default time generator if the
    // user does not supply one.
    timeGen = new GLG4TimeGen_Poisson();

    // Initialize the decay particles.
    neutron = G4Neutron::Neutron();
    gamma   = G4Gamma::Gamma();
  }

  CfGen::~CfGen()
  {
    delete timeGen;
    delete posGen;
  }

  void CfGen::GenerateEvent(G4Event* event)
  {
    // Initialize a new Cf fission.
    CfSource cfSource(isotope);

    // Generate the position of the isotope.  Note that, for now, we
    // don't change the position of the isotope as it decays.
    G4ThreeVector position;
    posGen->GeneratePosition(position);

    // Number of neutrons and prompt photons produced in the fission.
    int numberNeutrons = cfSource.GetNumNeutron();
    int numberGammas   = cfSource.GetNumGamma();

#ifdef DEBUG
    G4cout << "RAT::CfGen::GenerateEvent: "
	   << numberNeutrons << " neutrons, "
	   << numberGammas << " photons" << G4endl;
#endif

    // For each neutron...
    for ( int i = 0; i < numberNeutrons; i++ )
      {
	// Get the particle's information (momentum and time)
	CLHEP::HepLorentzVector p = cfSource.GetCfNeutronMomentum(i);
	double t = cfSource.GetCfNeutronTime(i);

	// Adjust the time from the t0 of the event.
	G4double time = NextTime() + t;

	// generate a vertex with a primary particle
	G4PrimaryVertex* vertex = new G4PrimaryVertex(position, time);
	G4PrimaryParticle* particle =
	  new G4PrimaryParticle(neutron,
				p.px(),
				p.py(),
				p.pz());
	particle->SetMass(neutron->GetPDGMass()); // Apparently this is useful in IBD code.
	vertex->SetPrimary(particle);
	event->AddPrimaryVertex(vertex);

#ifdef DEBUG
	G4cout << "RAT::CfGen::GenerateEvent: "
	       << "Neutron " << i << " of " << numberNeutrons
	       << "    time=" << G4BestUnit(time,"Time")
	       << ", position=" << G4BestUnit(position,"Length")
	       << ", momentum=" << G4BestUnit(p,"Energy")
	       << G4endl;
#endif

      } // for each neutron

    // For each prompt photon...
    for ( int i = 0; i < numberGammas; i++ )
      {
	// Get the particle's information (momentum and time)
	CLHEP::HepLorentzVector p = cfSource.GetCfGammaMomentum(i);
	double t = cfSource.GetCfGammaTime(i);

	// Adjust the time from the t0 of the event.
	G4double time = NextTime() + t;

	// generate a vertex with a primary particle
	G4PrimaryVertex* vertex = new G4PrimaryVertex(position, time);
	G4PrimaryParticle* particle =
	  new G4PrimaryParticle(gamma,
				p.px(),
				p.py(),
				p.pz());
	particle->SetMass(gamma->GetPDGMass()); // Who knows?  Let's do this the same way as the others.
	vertex->SetPrimary(particle);
	event->AddPrimaryVertex(vertex);

#ifdef DEBUG
	G4cout << "RAT::CfGen::GenerateEvent: "
	       << "Gamma " << i << " of " << numberGammas
	       << "    time=" << G4BestUnit(time,"Time")
	       << ", position=" << G4BestUnit(position,"Length")
	       << ", momentum=" << G4BestUnit(p,"Energy")
	       << G4endl;
#endif

      } // for each prompt photon

  }

  void CfGen::ResetTime(double offset)
  {
    double eventTime = timeGen->GenerateEventTime();
    nextTime = eventTime + offset;
#ifdef DEBUG
    G4cout << "RAT::CfGen::ResetTime:"
	   << " eventTime=" << G4BestUnit(eventTime,"Time")
	   << ", offset=" << G4BestUnit(offset,"Time")
	   << ", nextTime=" << G4BestUnit(nextTime,"Time")
	   << G4endl;
#endif
  }

  void CfGen::SetState(G4String state)
  {
#ifdef DEBUG
    G4cout << "RAT::CfGen::SetState called with state='"
	   << state << "'" << G4endl;
#endif

    // Break the argument to the this generator into sub-strings
    // separated by ":".
    state = util_strip_default(state);
    std::vector<std::string> parts = util_split(state, ":");
    size_t nArgs = parts.size();

#ifdef DEBUG
    G4cout << "RAT::CfGen::SetState: nArgs="
	   << nArgs << G4endl;
#endif

    try {

      if ( nArgs >= 3 )
	{
	  // The last argument is an optional time generator
	  delete timeGen; timeGen = 0; // In case of exception in next line
	  timeGen = GlobalFactory<GLG4TimeGen>::New(parts[2]);
	}

      if ( nArgs >= 2 )
	{
	  // The first argument is the Californium isotope.  At
	  // present, only Cf252 is supported.
	  isotope = util_to_int( parts[0] );

	  if ( isotope != 252 )
	    {
	      G4cerr << "RAT::CfGen::SetState: Only cf 252 is supported"
		     << G4endl;
	    }

	  // The second argument is a position generator.
	  delete posGen; posGen = 0;
	  posGen = GlobalFactory<GLG4PosGen>::New(parts[1]);
	}
      else
	{
	  G4Exception(__FILE__, "Invalid Parameter", FatalException, ("CfGen syntax error: '" +
								      state +
								      "' does not have a position generator").c_str());
	}

      stateStr = state; // Save for later call to GetState()
    } catch (FactoryUnknownID &unknown) {
      G4cerr << "Unknown generator \"" << unknown.id << "\"" << G4endl;
    }
  }

  G4String CfGen::GetState() const
  {
    return stateStr;
  }

  void CfGen::SetTimeState(G4String state)
  {
    if (timeGen)
      timeGen->SetState(state);
    else
      G4cerr << "CfGen error: Cannot set time state, no time generator selected" << G4endl;
  }

  G4String CfGen::GetTimeState() const
  {
    if (timeGen)
      return timeGen->GetState();
    else
      return G4String("CfGen error: no time generator selected");
  }

  void CfGen::SetPosState(G4String state)
  {
    if (posGen)
      posGen->SetState(state);
    else
      G4cerr << "CfGen error: Cannot set position state, no position generator selected" << G4endl;
  }

  G4String CfGen::GetPosState() const
  {
    if (posGen)
      return posGen->GetState();
    else
      return G4String("CfGen error: no position generator selected");
  }

} // namespace RAT


text:
<?php

/**
 * Descuen form.
 *
 * @package    sf_sandbox
 * @subpackage form
 * @author     Your name here
 * @version    SVN: $Id: sfDoctrineFormTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class DescuenForm extends BaseDescuenForm
{
  public function configure()
  {
  }
}


text:
<!DOCTYPE html>

<title>Reference mismatch: ::first-line supports opacity.</title>
<link rel="author" title="Mats Palmgren" href="https://bugzilla.mozilla.org/show_bug.cgi?id=1639664">

First
Second


text:
Welcome to my Blog. This is a learning experience for me.
I forked two different themes together.
Main Theme:  Nice Blog  (https://github.com/itisbenjamin/Nice_Blog)

Authors:
Main Theme: [![Twitter Follow](https://img.shields.io/twitter/follow/itisbenjamin1.svg?style=social)](https://twitter.com/itisbenjamin1)

Most of my code changes came from my friend:[![Twitter Follow](https://img.shields.io/twitter/follow/samurailink3.svg?style=social)](https://twitter.com/samurailink3)

I'm completely learning, and have no idea what I'm doing.
License  [![License](https://img.shields.io/npm/l/express.svg)](https://github.com/itisbenjamin/Nice_Blog/blob/master/LICENSE)
Use MIT License.


text:
import sys
from lxml import etree
from datetime import datetime
# from pprint import pprint

import logging
import requests

from util import reg_person, reg_financial_data
from util import reg_representative, reg_organisation
from util import reg_action_field
from util import reg_interest, reg_country_of_member
from util import reg_financial_data_turnover
from util import reg_financial_data_custom_source
from util import dateconv, intconv

log = logging.getLogger('scraper_interests')
logging.basicConfig(level=logging.INFO)

URL = 'http://ec.europa.eu/transparencyregister/public/consultation/statistics.do?action=getLobbyistsXml&fileType=NEW'
NS2 = "{http://www.w3.org/1999/xlink}"
NS = "{http://intragate.ec.europa.eu/transparencyregister/intws/20141104}"
SI = "{http://www.w3.org/2001/XMLSchema-instance}"

def parse_rep(rep_el):
    rep = {}
    rep['identification_code'] = rep_el.findtext(NS + 'identificationCode')
    rep['status'] = rep_el.findtext(NS + 'status')
    rep['registration_date'] = dateconv(rep_el.findtext(NS + 'registrationDate'))
    rep['last_update_date'] = dateconv(rep_el.findtext(NS + 'lastUpdateDate'))
    rep['legal_status'] = rep_el.findtext(NS + 'legalStatus')
    rep['acronym'] = rep_el.findtext(NS + 'acronym')
    rep['original_name'] = rep_el.findtext('.//' + NS + 'originalName')
    el = rep_el.find(NS + 'webSiteURL')
    rep['web_site_url'] = el.get(NS2 + 'href') if el is not None else None
    rep['main_category'] = rep_el.findtext('.//' + NS + 'mainCategory')
    rep['sub_category'] = rep_el.findtext('.//' + NS + 'subCategory')

    legal = {}
    legal['title'] = rep_el.findtext(NS + 'legalResp/' + NS + 'title')
    legal['first_name'] = rep_el.findtext(NS + 'legalResp/' + NS + 'firstName')
    legal['last_name'] = rep_el.findtext(NS + 'legalResp/' + NS + 'lastName')
    legal['position'] = rep_el.findtext(NS + 'legalResp/' + NS + 'position')
    rep['legal_person'] = legal

    eu = {}
    eu['title'] = rep_el.findtext(NS + 'euRelationsResp/' + NS + 'title')
    eu['first_name'] = rep_el.findtext(NS + 'euRelationsResp/' + NS + 'firstName')
    eu['last_name'] = rep_el.findtext(NS + 'euRelationsResp/' + NS + 'lastName')
    eu['position'] = rep_el.findtext(NS + 'euRelationsResp/' + NS + 'position')
    rep['eu_person'] = eu

    rep['contact_street'] = rep_el.findtext(NS + 'contactDetails/' + NS + 'addressline1')
    rep['contact_number'] = rep_el.findtext(NS + 'contactDetails/' + NS + 'number')
    rep['contact_post_code'] = rep_el.findtext(NS + 'contactDetails/' + NS
            + 'postCode')
    rep['contact_town'] = rep_el.findtext(NS + 'contactDetails/' + NS
            + 'town')
    rep['contact_country'] = rep_el.findtext(NS + 'contactDetails/' + NS
            + 'country')
    rep['contact_indic_phone'] = rep_el.findtext(NS + 'contactDetails//' + NS
            + 'indicPhone')
    rep['contact_indic_fax'] = rep_el.findtext(NS + 'contactDetails//' + NS
            + 'indicFax')
    rep['contact_fax'] = rep_el.findtext(NS + 'contactDetails//' + NS
            + 'fax')
    rep['contact_phone'] = rep_el.findtext(NS + 'contactDetails//' + NS
            + 'phoneNumber')
    rep['contact_more'] = rep_el.findtext(NS + 'contactDetails/' + NS
            + 'moreContactDetails')

    rep['goals'] = rep_el.findtext(NS + 'goals')
    rep['networking'] = rep_el.findtext(NS + 'networking')

    # rep['activities'] = rep_el.findtext(NS + 'activities')
    act_el = rep_el.find(NS + 'activities')
    if act_el is not None:
        rep['activity_eu_legislative'] = act_el.findtext(NS + 'activityEuLegislative')
        rep['activity_communication'] = act_el.findtext(NS + 'activityRelevantComm')
        rep['activity_high_level_groups'] = act_el.findtext(NS + 'activityHighLevelGroups')
        rep['activity_consult_committee'] = act_el.findtext(NS + 'activityConsultCommittees')
        rep['activity_expert_groups'] = act_el.findtext(NS + 'activityExpertGroups')
        rep['activity_inter_groups'] = act_el.findtext(NS + 'activityInterGroups')
        rep['activity_industry_forums'] = act_el.findtext(NS + 'activityIndustryForums')
        rep['activity_other'] = act_el.findtext(NS + 'activityOther')

    rep['code_of_conduct'] = rep_el.findtext(NS + 'codeOfConduct')
    rep['action_fields'] = []
    for field in rep_el.findall('.//' + NS + 'actionField/' + NS + 'actionField'):
        rep['action_fields'].append(field.text)
    rep['interests'] = []
    for interest in rep_el.findall('.//' + NS + 'interest/' + NS + 'name'):
        rep['interests'].append(interest.text)

    rep['number_of_natural_persons'] = intconv(rep_el.findtext('.//' + NS + 'structure/' + NS
            + 'numberOfNaturalPersons'))
    rep['number_of_organisations'] = intconv(rep_el.findtext('.//' + NS + 'structure/' + NS
            + 'numberOfOrganisations'))

    mem_el = rep_el.find(NS + 'members')
    if mem_el is not None:
        rep['members_100_percent'] = mem_el.findtext(NS + 'members100Percent')
        rep['members_25_percent'] = mem_el.findtext(NS + 'members25Percent')
        rep['members_total'] = mem_el.findtext(NS + 'members')
        rep['members_fte'] = mem_el.findtext(NS + 'membersFTE')
        rep['members_info'] = mem_el.findtext(NS + 'infoMembers')

    #pprint((rep['numberOfNaturalPersons'], rep['numberOfOrganisations']))
    rep['country_of_members'] = []
    el = rep_el.find(NS + 'structure/' + NS + 'countries')
    if el is not None:
        for country in el.findall('.//' + NS + 'country'):
            rep['country_of_members'].append(country.text)

    rep['organisations'] = []
    el = rep_el.find(NS + 'structure/' + NS + 'organisations')
    if el is not None:
        for org_el in el.findall(NS + 'organisation'):
            org = {}
            org['name'] = org_el.findtext(NS + 'name')
            org['number_of_members'] = org_el.findtext(NS + 'numberOfMembers')
            rep['organisations'].append(org)

    fd = {}
    fd_el = rep_el.find(NS + 'financialData')
    if fd_el is not None:
        fd['start_date'] = dateconv(fd_el.findtext(NS + 'startDate'))
        fd['end_date'] = dateconv(fd_el.findtext(NS + 'endDate'))
        fd['eur_sources_procurement'] = intconv(fd_el.findtext(NS + 'eurSourcesProcurement'))
        fd['eur_sources_grants'] = intconv(fd_el.findtext(NS + 'eurSourcesGrants'))
        fi = fd_el.find(NS + 'financialInformation')
        fd['type'] = fi.get(SI + 'type')
        #import ipdb; ipdb.set_trace()
        fd['total_budget'] = intconv(fi.findtext('.//' + NS +
            'total_budget'))
        fd['public_financing_total'] = intconv(fi.findtext('.//' + NS +
            'totalPublicFinancing'))
        fd['public_financing_national'] = intconv(fi.findtext('.//' + NS +
            'nationalSources'))
        fd['public_financing_infranational'] = intconv(fi.findtext('.//' + NS +
            'infranationalSources'))
        cps = fi.find('.//' + NS + 'customisedPublicSources')
        fd['public_customized'] = []
        if cps is not None:
            for src_el in cps.findall(NS + 'customizedSource'):
                src = {}
                src['name'] = src_el.findtext(NS + 'name')
                src['amount'] = intconv(src_el.findtext(NS + 'amount'))
                fd['public_customized'].append(src)
        fd['other_sources_total'] = intconv(fi.findtext('.//' + NS +
            'totalOtherSources'))
        fd['other_sources_donation'] = intconv(fi.findtext('.//' + NS +
            'donation'))
        fd['other_sources_contributions'] = intconv(fi.findtext('.//' + NS +
            'contributions'))

        # TODO customisedOther
        cps = fi.find('.//' + NS + 'customisedOther')
        fd['other_customized'] = []
        if cps is not None:
            for src_el in cps.findall(NS + 'customizedSource'):
                src = {}
                src['name'] = src_el.findtext(NS + 'name')
                src['amount'] = intconv(src_el.findtext(NS + 'amount'))
                fd['other_customized'].append(src)

        fd['direct_rep_costs_min'] = intconv(fi.findtext('.//' + NS +
            'directRepresentationCosts//' + NS + 'min'))
        fd['direct_rep_costs_max'] = intconv(fi.findtext('.//' + NS +
            'directRepresentationCosts//' + NS + 'max'))
        fd['cost_min'] = intconv(fi.findtext('.//' + NS +
            'cost//' + NS + 'min'))
        fd['cost_max'] = intconv(fi.findtext('.//' + NS +
            'cost//' + NS + 'max'))
        fd['cost_absolute'] = intconv(fi.findtext('.//' + NS +
            'cost//' + NS + 'absoluteAmount'))
        fd['turnover_min'] = intconv(fi.findtext('.//' + NS +
            'turnover//' + NS + 'min'))
        fd['turnover_max'] = intconv(fi.findtext('.//' + NS +
            'turnover//' + NS + 'max'))
        fd['turnover_absolute'] = intconv(fi.findtext('.//' + NS +
            'turnover//' + NS + 'absoluteAmount'))
        tb = fi.find(NS + 'turnoverBreakdown')
        fd['turnover_breakdown'] = []
        if tb is not None:
            for range_ in tb.findall(NS + 'customersGroupsInAbsoluteRange'):
                max_ = range_.findtext('.//' + NS + 'max')
                min_ = range_.findtext('.//' + NS + 'min')
                for customer in range_.findall('.//' + NS + 'customer'):
                    fd['turnover_breakdown'].append({
                        'name': customer.findtext(NS + 'name'),
                        'min': intconv(min_),
                        'max': intconv(max_)
                        })
            for range_ in tb.findall(NS + 'customersGroupsInPercentageRange'):
                # FIXME: I hate political compromises going into DB design
                # so directly.
                max_ = range_.findtext('.//' + NS + 'max')
                if max_:
                    max_ = float(max_) / 100.0 * \
                            float(fd['turnover_absolute'] or
                                  fd['turnover_max'] or fd['turnover_min'])
                min_ = range_.findtext('.//' + NS + 'min')
                if min_:
                    min_ = float(min_) / 100.0 * \
                            float(fd['turnover_absolute'] or
                                  fd['turnover_min'] or fd['turnover_max'])
                for customer in range_.findall('.//' + NS + 'customer'):
                    fd['turnover_breakdown'].append({
                        'name': customer.findtext(NS + 'name'),
                        'min': intconv(min_),
                        'max': intconv(max_)
                        })
    # from pprint import pprint
    # pprint(rep)
    rep['fd'] = fd
    return rep

def load_person(person, role, childBase):
    person_ = childBase.copy()
    person_.update(person)
    person_['role'] = role
    person_['name'] = '%s %s %s' % (person['title'] or '',
                                    person['first_name'] or '',
                                    person['last_name'] or '')
    person_['name'] = person_['name'].strip()
    reg_person.upsert(person_, ['representative_etl_id', 'role', 'name'])

def load_finances(financialData, childBase):
    etlId = '%s//%s' % (financialData['start_date'], financialData['end_date'])

    financial_sources = \
        [(s, 'other') for s in financialData.pop("other_customized")] + \
        [(s, 'public') for s in financialData.pop("public_customized")]
    for financial_source, type_ in financial_sources:
        financial_source['type'] = type_
        financial_source['financial_data_etl_id'] = etlId
        financial_source.update(childBase)
        reg_financial_data_custom_source.upsert(financial_source, ['representative_etl_id', 'financial_data_etl_id', 'type', 'name'])

    for turnover in financialData.pop("turnover_breakdown"):
        turnover['financial_data_etl_id'] = etlId
        turnover['name'] = turnover['name'].strip()
        turnover.update(childBase)
        reg_financial_data_turnover.upsert(turnover, ['representative_etl_id', 'financial_data_etl_id', 'name'])

    financialData['etl_id'] = etlId
    financialData.update(childBase)
    reg_financial_data.upsert(financialData, ['representative_etl_id', 'etl_id'])
    #pprint(financialData)

def load_rep(rep):
    rep['first_seen'] = datetime.utcnow()
    rep['last_seen'] = rep['first_seen']
    existing = reg_representative.find_one(identification_code=rep['identification_code'])
    if existing is not None:
        rep['first_seen'] = existing.get('first_seen', rep['first_seen'])
    etlId = rep['etl_id'] = "%s//ALL" % rep['identification_code']
    childBase = {'representative_etl_id': etlId,
                 'representative_update_date': rep['last_update_date']}
    if not rep['original_name']:
        log.error("Unnamed representative: %r", rep)
        return
    load_person(rep.pop('legal_person'), 'legal', childBase)
    load_person(rep.pop('eu_person'), 'eu', childBase)
    for actionField in rep.pop('action_fields'):
        rec = childBase.copy()
        rec['action_field'] = actionField
        reg_action_field.upsert(rec, ['representative_etl_id', 'action_field'])

    for interest in rep.pop('interests'):
        rec = childBase.copy()
        rec['interest'] = interest
        reg_interest.upsert(rec, ['representative_etl_id', 'interest'])

    for countryOfMember in rep.pop('country_of_members'):
        rec = childBase.copy()
        rec['country'] = countryOfMember
        reg_country_of_member.upsert(rec, ['representative_etl_id', 'country'])

    for organisation in rep.pop('organisations'):
        rec = childBase.copy()
        rec.update(organisation)
        rec['name'] = organisation['name'].strip()
        reg_organisation.upsert(rec, ['representative_etl_id', 'name'])

    fd = rep.pop('fd')
    if len(fd.keys()):
        load_finances(fd, childBase)
    rep['name'] = rep['original_name'].strip()
    log.info("Representative: %s", rep['name'])
    reg_representative.upsert(rep, ['etl_id'])

def parse():
    # parser = etree.XMLParser(recover=True)
    res = requests.get(URL, stream=True)
    res.raw.decode_content = True
    for evt, el in etree.iterparse(res.raw, recover=True):
        if evt != 'end' or el.tag != NS + 'interestRepresentative':
            continue
        # print etree.tostring(el, pretty_print=True)
        yield parse_rep(el)
        el.clear()

def extract():
    log.info("Extracting registered interests data...")
    for i, rep in enumerate(parse()):
        load_rep(rep)
        # if i % 100 == 0:
        #     log.info("Extracted: %s...", i)

if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO)
    extract()


text:
package me.dags.daflight.utils;

import me.dags.daflight.DaFlight;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;

public class Tools
{

    private static DecimalFormat df1;
    private static DecimalFormat df2;

    static
    {
        DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale.ENGLISH);
        dfs.setDecimalSeparator(".".charAt(0));
        df1 = new DecimalFormat("0.0", dfs);
        df2 = new DecimalFormat("0.00", dfs);
    }

    public static float round(float f)
    {
        return Float.valueOf(df2.format(f));
    }

    public static String round1Dp(float f)
    {
        return df1.format(f);
    }

    public static String round2Dp(float f)
    {
        return df2.format(f);
    }

    public static File getOrCreateFile(File folder, String fileName)
    {
        folder.mkdirs();
        File file = new File(folder, fileName);
        if (!file.exists())
        {
            try
            {
                file.createNewFile();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        return file;
    }

    public static File getOrCreateFolder(File parent, String name)
    {
        File folder = new File(parent, name);
        folder.mkdirs();
        return folder;
    }

    public static String createGlobalConfig()
    {
        String fileName = "global.json";
        File configFile = new File(DaFlight.getConfigFolder(), fileName);
        if (!configFile.exists())
        {
            try
            {
                configFile.createNewFile();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        return "daflight/" + fileName;
    }
}


text:
var num1 = Number(window.prompt("Entre com primeiro numero"));
var num2 = Number(window.prompt("Entre com segundo numero"));
if (num1 >= 0 && num2 >= 0) {
    var i = Math.min(num1, num2);
    while (i <= Math.max(num1, num2)) console.log(i++);
}

var num1 = Number(window.prompt("Entre com primeiro numero"));
var num2 = Number(window.prompt("Entre com segundo numero"));
for (var i = Math.min(num1, num2); num1 >= 0 && num2 >= 0 && i <= Math.max(num1, num2); i++) console.log(i);

//https://pt.stackoverflow.com/q/154809/101


text:
package org.reactnative.camera.tasks;

import com.facebook.react.bridge.WritableMap;

public interface PictureSavedDelegate {
    void onPictureSaved(WritableMap response);
}


text:
package hu.akarnokd.reactive4javaflow.impl.util;

import hu.akarnokd.reactive4javaflow.impl.*;

import java.lang.invoke.*;
import java.util.Objects;

public final class MpscLinkedArrayQueue<T> implements PlainQueue<T> {

    final int capacity;

    static final VarHandle ARRAY = MethodHandles.arrayElementVarHandle(Object[].class);

    Island producerArray;
    static final VarHandle PRODUCER_ARRAY = VH.find(MethodHandles.lookup(), MpscLinkedArrayQueue.class, "producerArray", Island.class);
    static final VarHandle PRODUCER_INDEX = VH.find(MethodHandles.lookup(), Island.class, "producerIndex", Integer.TYPE);

    Island consumerArray;
    int consumerIndex;
    static final VarHandle CONSUMER_INDEX = VH.find(MethodHandles.lookup(), MpscLinkedArrayQueue.class, "consumerIndex", Integer.TYPE);

    static final VarHandle NEXT_ISLAND = VH.find(MethodHandles.lookup(), Island.class, "next", Island.class);

    static final Island EMPTY = new Island(0);

    public MpscLinkedArrayQueue(int capacity) {
        int c = QueueHelper.pow2(Math.max(4, capacity));
        producerArray = consumerArray = new Island(c);
        this.capacity = c;
    }

    @Override
    public boolean offer(T item) {
        Objects.requireNonNull(item, "item == null");
        int c = capacity;
        for (;;) {
            Island a = (Island)PRODUCER_ARRAY.getAcquire(this);
            int idx = (int)PRODUCER_INDEX.getAndAdd(a, 1);
            if (idx >= c) {
                Island b = (Island)NEXT_ISLAND.getAcquire(a);
                if (b != null) {
                    if (b != EMPTY) {
                        PRODUCER_ARRAY.compareAndSet(this, a, b);
                    }
                    continue;
                }
                b = new Island(c);
                b.array[0] = item;
                b.producerIndex = 1;
                if (NEXT_ISLAND.compareAndSet(a, null, b)) {
                    PRODUCER_ARRAY.compareAndSet(this, a, b);
                    return true;
                }
                continue;
            }
            ARRAY.setRelease(a.array, idx, item);
            return true;
        }
    }

    @Override
    public T poll() {
        Island a = consumerArray;
        int ci = consumerIndex;
        int c = capacity;

        if (ci < c) {
            @SuppressWarnings("unchecked")
            T v = (T)ARRAY.getAcquire(a.array, ci);
            if (v != null) {
                ARRAY.set(a.array, ci, null);
                consumerIndex = ci + 1;
            }
            return v;
        }

        Island b = (Island)NEXT_ISLAND.getAcquire(a);
        if (b == null) {
            return null;
        }
        @SuppressWarnings("unchecked")
        T v = (T)ARRAY.getAcquire(b.array, 0);
        ARRAY.set(b.array, 0, null);
        consumerIndex = 1;
        consumerArray = b;
        NEXT_ISLAND.setRelease(a, EMPTY);
        return v;

    }

    @Override
    public boolean isEmpty() {
        Island a = consumerArray;
        int ci = consumerIndex;

        if (ci >= capacity) {
            return NEXT_ISLAND.getAcquire(a) == null;
        }

        return ARRAY.getAcquire(a.array, ci) == null;
    }

    @Override
    public void clear() {
        QueueHelper.clear(this);
    }

    static final class Island {
        final Object[] array;

        Island next;

        int producerIndex;

        Island(int capacity) {
            array = new Object[capacity];
        }
    }

}


text:
package com.amazonaws.services.simpleworkflow.model;

import com.amazonaws.AmazonServiceException;

/**
 * <p>
 * Returned when the named resource cannot be found with in the scope of
 * this operation (region or domain). This could happen if the named
 * resource was never created or is no longer available for this
 * operation.
 * </p>
 */
public class UnknownResourceException extends AmazonServiceException {
    private static final long serialVersionUID = 1L;

    /**
     * Constructs a new UnknownResourceException with the specified error
     * message.
     *
     * @param message Describes the error encountered.
     */
    public UnknownResourceException(String message) {
        super(message);
    }

}


text:
/**
 * Created by kylemills on 9/18/17.
 */

var chai = require('chai');
var chaiAsPromised = require("chai-as-promised");
chai.use(chaiAsPromised);
var expect = chai.expect;

describe('Toggle Directive', function () {
    var $compile,
        $rootScope,
        $templateCache,
        element,
        scope;

    beforeEach(function () {
        angular.mock.module('vbr-style-guide');
    });

    /* Transform HTML into loadable module via ng-html2js*/
    beforeEach(function () {
        angular.mock.module('my.templates');
    });

    // Store references to $rootScope and $compile
    // so they are available to all tests in this describe block
    beforeEach(inject(function(_$compile_, _$rootScope_,_$templateCache_){
        // The injector unwraps the underscores (_) from around the parameter names when matching
        $compile = _$compile_;
        $rootScope = _$rootScope_;
        $templateCache = _$templateCache_;
        scope = $rootScope.$new();

    }));

    it('Should init without crashing',function () {
        element = $compile("<form name='someForm'><vbr-toggle id='test-toggle' form='someForm'></vbr-toggle></form>")(scope);
        scope.$digest();
        expect(true).to.equal(true);
    });

});


text:
using Foundation;
using System;
using System.CodeDom.Compiler;
using UIKit;

namespace TTGSnackbarSample
{
    [Register ("ViewController")]
    partial class ViewController
    {
        [Action ("buttonClicked:")]
        [GeneratedCode ("iOS Designer", "1.0")]
        partial void buttonClicked (UIKit.UIButton sender);

        void ReleaseDesignerOutlets ()
        {
        }
    }
}


text:
import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
} from 'react-native';

import Calendar from 'react-native-calendar';
import moment from 'moment';

const customDayHeadings = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
const customMonthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May',
  'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingTop: 20,
    backgroundColor: '#f7f7f7',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedDate: moment().format(),
    };
  }

  render() {
    return (
      <View style={styles.container}>
        <Calendar
          ref="calendar"
          eventDates={['2016-07-03', '2016-07-05', '2016-07-28', '2016-07-30']}
          scrollEnabled
          showControls
          dayHeadings={customDayHeadings}
          monthNames={customMonthNames}
          titleFormat={'MMMM YYYY'}
          prevButtonText={'Prev'}
          nextButtonText={'Next'}
          onDateSelect={(date) => this.setState({ selectedDate: date })}
          onTouchPrev={() => console.log('Back TOUCH')}     // eslint-disable-line no-console
          onTouchNext={() => console.log('Forward TOUCH')}  // eslint-disable-line no-console
          onSwipePrev={() => console.log('Back SWIPE')}     // eslint-disable-line no-console
          onSwipeNext={() => console.log('Forward SWIPE')}  // eslint-disable-line no-console
        />
        <Text>Selected Date: {moment(this.state.selectedDate).format('MMMM DD YYYY')}</Text>
      </View>

    );
  }
}

module.exports = App;


text:
package org.talend.components.google.drive.runtime;

import static org.talend.components.google.drive.GoogleDriveMimeTypes.MIME_TYPE_GOOGLE_DOCUMENT;
import static org.talend.components.google.drive.GoogleDriveMimeTypes.MIME_TYPE_GOOGLE_DRAWING;
import static org.talend.components.google.drive.GoogleDriveMimeTypes.MIME_TYPE_GOOGLE_PRESENTATION;
import static org.talend.components.google.drive.GoogleDriveMimeTypes.MIME_TYPE_GOOGLE_SPREADSHEET;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.talend.components.api.component.runtime.ComponentDriverInitialization;
import org.talend.components.api.container.RuntimeContainer;
import org.talend.components.api.exception.ComponentException;
import org.talend.components.api.properties.ComponentProperties;
import org.talend.components.google.drive.GoogleDriveComponentProperties.AccessMethod;
import org.talend.components.google.drive.GoogleDriveMimeTypes;
import org.talend.components.google.drive.GoogleDriveMimeTypes.MimeType;
import org.talend.components.google.drive.delete.GoogleDriveDeleteDefinition;
import org.talend.components.google.drive.get.GoogleDriveGetProperties;
import org.talend.components.google.drive.runtime.utils.GoogleDriveGetParameters;
import org.talend.components.google.drive.runtime.utils.GoogleDriveGetResult;
import org.talend.daikon.properties.ValidationResult;
import org.talend.daikon.properties.ValidationResult.Result;

public class GoogleDriveGetRuntime extends GoogleDriveRuntime implements ComponentDriverInitialization<ComponentProperties> {

    private GoogleDriveGetProperties properties;

    private String fileId;

    private transient static final Logger LOG = LoggerFactory.getLogger(GoogleDriveGetRuntime.class);

    @Override
    public ValidationResult initialize(RuntimeContainer container, ComponentProperties properties) {
        ValidationResult vr = super.initialize(container, properties);
        if (vr.getStatus().equals(Result.ERROR)) {
            return vr;
        }
        this.properties = (GoogleDriveGetProperties) properties;
        return validateProperties(this.properties);
    }

    @Override
    public void runAtDriver(RuntimeContainer container) {
        getFile(container);
        setReturnValues(container);
    }

    public void getFile(RuntimeContainer container) {
        try {
            GoogleDriveUtils utils = getDriveUtils();
            utils.setIncludeSharedDrives(properties.includeSharedDrives.getValue());
            if (properties.includeSharedDrives.getValue()) {
                utils.setCorpora(properties.corpora.getValue());
                utils.setDriveId(properties.driveId.getValue());
            }
            String resourceId = properties.fileAccessMethod.getValue().equals(AccessMethod.Id)
                    ? properties.file.getValue()
                    : utils.getFileId(properties.file.getValue(), properties.includeSharedItems.getValue());
            Map<String, MimeType> mimes = GoogleDriveMimeTypes.newDefaultMimeTypesSupported();
            mimes.put(MIME_TYPE_GOOGLE_DOCUMENT, properties.exportDocument.getValue());
            mimes.put(MIME_TYPE_GOOGLE_DRAWING, properties.exportDrawing.getValue());
            mimes.put(MIME_TYPE_GOOGLE_PRESENTATION, properties.exportPresentation.getValue());
            mimes.put(MIME_TYPE_GOOGLE_SPREADSHEET, properties.exportSpreadsheet.getValue());
            GoogleDriveGetParameters p = new GoogleDriveGetParameters(resourceId, mimes, properties.storeToLocal.getValue(),
                    properties.outputFileName.getValue(), properties.setOutputExt.getValue(), false);
            //
            GoogleDriveGetResult r = utils.getResource(p);
            fileId = r.getId();
        } catch (IOException | GeneralSecurityException e) {
            LOG.error(e.getMessage());
            throw new ComponentException(e);
        }
    }

    public void setReturnValues(RuntimeContainer container) {
        String componentId = container.getCurrentComponentId();
        container.setComponentData(componentId, getStudioName(GoogleDriveDeleteDefinition.RETURN_FILE_ID), fileId);
    }
}


text:
module Undress
  # Grammars give you a DSL to declare how to convert an HTML document into a
  # different markup language.
  class Grammar
    def self.inherited(base) # :nodoc:
      base.instance_variable_set(:@post_processing_rules, post_processing_rules)
      base.instance_variable_set(:@pre_processing_rules, pre_processing_rules)
    end

    # Add a parsing rule for a group of html tags.
    #
    #     rule_for :p do |element|
    #       "<this was a paragraph>#{content_of(element)}</this was a paragraph>"
    #     end
    #
    # will replace your <tt>
</tt> tags for <tt><this was a paragraph></tt>
    # tags, without altering the contents.
    #
    # The element yielded to the block is an Hpricot element for the given tag.
    def self.rule_for(*tags, &handler) # :yields: element
      tags.each do |tag|
        define_method tag.to_sym, &handler
      end
    end

    # Set a default rule for unrecognized tags.
    #
    # Unless you define a special case, it will ignore the tags and just output
    # the contents of unrecognized tags.
    def self.default(&handler) # :yields: element
      define_method :method_missing do |tag, node, *args|
        handler.call(node)
      end
    end

    # Add a post-processing rule to your parser.
    #
    # This takes a regular expression that will be applied to the output after
    # processing any nodes. It can take a string as a replacement, or a block
    # that will be passed to String#gsub.
    #
    #     post_processing(/\n\n+/, "\n\n") # compress more than two newlines
    #     post_processing(/whatever/) { ... }
    def self.post_processing(regexp, replacement = nil, &handler) #:yields: matched_string
      post_processing_rules[regexp] = replacement || handler
    end

    # Add a pre-processing rule to your parser.
    #
    # This lets you mutate the DOM before applying any rule defined with
    # +rule_for+. You need to pass a CSS/XPath selector, and a block that
    # takes an Hpricot element to parse it.
    #
    #     pre_processing "ul.toc" do |element|
    #       element.swap("
[[toc]]
")
    #     end
    #
    # Would replace any unordered lists with the class +toc+ for a
    # paragraph containing the code <tt>[[toc]]</tt>.
    def self.pre_processing(selector, &handler) # :yields: element
      pre_processing_rules[selector] = handler
    end

    # Set a list of attributes you wish to whitelist
    #
    # Any attribute not in this list at the moment of parsing will be ignored by the
    # parser. The method Grammar#attributes(node) will return a hash of the filtered
    # attributes. Read its documentation for more details.
    #
    #     whitelist_attributes :id, :class, :lang
    def self.whitelist_attributes(*attrs)
      @whitelisted_attributes = attrs
    end

    def self.whitelisted_attributes #:nodoc:
      @whitelisted_attributes || []
    end

    def self.post_processing_rules #:nodoc:
      @post_processing_rules ||= {}
    end

    def self.pre_processing_rules #:nodoc:
      @pre_processing_rules ||= {}
    end

    def self.process!(node) #:nodoc:
      new.process!(node)
    end

    attr_reader :pre_processing_rules #:nodoc:
    attr_reader :post_processing_rules #:nodoc:
    attr_reader :whitelisted_attributes #:nodoc:

    def initialize #:nodoc:
      @pre_processing_rules = self.class.pre_processing_rules.dup
      @post_processing_rules = self.class.post_processing_rules.dup
      @whitelisted_attributes = self.class.whitelisted_attributes.dup
    end

    # Process a DOM node, converting it to your markup language according to
    # your defined rules. If the node is a Text node, it will return it's
    # string representation. Otherwise it will call the rule defined for it.
    def process(nodes)
      Array(nodes).map do |node|
        if node.text?
          node.to_html
        elsif node.elem?
          send node.name.to_sym, node
        else
          ""
        end
      end.join("")
    end

    def process!(node) #:nodoc:
      pre_processing_rules.each do |selector, handler|
        node.search(selector).each(&handler)
      end

      process(node.children).tap do |text|
        post_processing_rules.each do |rule, handler|
          handler.is_a?(String) ?  text.gsub!(rule, handler) : text.gsub!(rule, &handler)
        end
      end
    end

    # Get the result of parsing the contents of a node.
    def content_of(node)
      process(node.respond_to?(:children) ? node.children : node)
    end

    # Helper method that tells you if the given DOM node is immediately
    # surrounded by whitespace.
    def surrounded_by_whitespace?(node)
      (node.previous.text? && node.previous.to_s =~ /\s+$/) ||
        (node.next.text? && node.next.to_s =~ /^\s+/)
    end

    # Hash of attributes, according to the white list. By default, no attributes
    # are whitelisted, so you must set which ones to whitelist on each grammar.
    #
    # Supposing you set <tt>:id</tt> and <tt>:class</tt> as your
    # <tt>whitelisted_attributes</tt>, and you have a node representing this
    # HTML:
    #
    #
Hello World

    #
    # Then the method would return:
    #
    #     { :class => "greeting" }
    #
    # You can override this method in each grammar and call +super+ if you
    # will represent your attributes consistently across all nodes (for
    # example, +Textile+ always shows class an id inside parenthesis.)
    def attributes(node)
      node.attributes.inject({}) do |attrs,(key,value)|
        attrs[key.to_sym] = value if whitelisted_attributes.include?(key.to_sym)
        attrs
      end
    end

    def method_missing(tag, node, *args) #:nodoc:
      process(node.children)
    end
  end
end


text:
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;

[assembly: AssemblyTitle("Math.NET Spatial Unit Tests")]
[assembly: AssemblyDescription("Math.NET Spatial")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Math.NET Project")]
[assembly: AssemblyProduct("Math.NET Spatial")]
[assembly: AssemblyCopyright("Copyright (c) Math.NET Project")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: CLSCompliant(false)]
[assembly: NeutralResourcesLanguage("en")]

[assembly: ComVisible(false)]
[assembly: Guid("4f5a2dca-ef86-4ef9-89d0-8da13c9e8825")]

[assembly: AssemblyVersion("0.2.0.0")]
[assembly: AssemblyFileVersion("0.2.0.0")]
[assembly: AssemblyInformationalVersion("0.2.0-alpha")]


text:
using Core.BaseTypes;
using Core.Cells;
using Core.Enums;
using NUnit.Framework;
using Tests.RulesForTesting;

namespace Tests.Cells.ShipTst {
    [TestFixture]
    public class WhenShipMoves {
        [SetUp]
        public void TestInit() {}

        [Test]
        public void OldCellShouldReleaseShip() {
            // arrange
            var originalCell = new WaterCell(1, 1);
            var team = new Team(TeamType.Black, new TestEmptyRules());
            var ship = new Ship(team, originalCell);
            ship.Pirates.Add(team.Pirates.Current);

            // Act
            var newCell = new WaterCell(1, 2);
            ship.MoveTo(newCell);

            // Assert
            ship.Cell
                .ShouldBeEqual(newCell);
        }

        [Test]
        public void AllPiratesShouldMoveWithShip() {
            // arrange
            var originalCell = new WaterCell(1, 1);
            var team = new Team(TeamType.Black, new TestEmptyRules());
            var ship = new Ship(team, originalCell);
            ship.Pirates.Add(team.Pirates.Current);
            ship.Pirates.Add(team.Pirates.GetNext());

            // Act
            var newCell = new WaterCell(1, 2);
            ship.MoveTo(newCell);

            // Assert
            foreach (var pirate in ship.Pirates) {
                pirate.Position
                    .ShouldBeEqual(newCell.Position);
            }
        }
    }
}


text:
package org.apache.wicket.examples.tree.content;

import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.examples.tree.Foo;
import org.apache.wicket.extensions.markup.html.repeater.tree.AbstractTree;
import org.apache.wicket.extensions.markup.html.repeater.tree.ITreeProvider;
import org.apache.wicket.extensions.markup.html.repeater.tree.content.Folder;
import org.apache.wicket.extensions.markup.html.repeater.util.ProviderSubset;
import org.apache.wicket.model.IModel;

/**
 * @author Sven Meier
 */
public class MultiSelectableFolderContent extends Content
{

	private static final long serialVersionUID = 1L;

	private ProviderSubset<Foo> selected;

	public MultiSelectableFolderContent(ITreeProvider<Foo> provider)
	{
		selected = new ProviderSubset<Foo>(provider, false);
	}

	@Override
	public void detach()
	{
		selected.detach();
	}

	protected boolean isSelected(Foo foo)
	{
		return selected.contains(foo);
	}

	protected void toggle(Foo foo, AbstractTree<Foo> tree, final AjaxRequestTarget target)
	{
		if (isSelected(foo))
		{
			selected.remove(foo);
		}
		else
		{
			selected.add(foo);
		}

		tree.updateNode(foo, target);
	}

	@Override
	public Component newContentComponent(String id, final AbstractTree<Foo> tree, IModel<Foo> model)
	{
		return new Folder<Foo>(id, tree, model)
		{
			private static final long serialVersionUID = 1L;

			/**
			 * Always clickable.
			 */
			@Override
			protected boolean isClickable()
			{
				return true;
			}

			@Override
			protected void onClick(AjaxRequestTarget target)
			{
				MultiSelectableFolderContent.this.toggle(getModelObject(), tree, target);
			}

			@Override
			protected boolean isSelected()
			{
				return MultiSelectableFolderContent.this.isSelected(getModelObject());
			}
		};
	}
}


text:
local fw = require "fw.init"

local Endscreen = fw.gamestate.newState()

function Endscreen.new(o)

   o = o or {}

   setmetatable(o,Endscreen)
   Endscreen.__index = Endscreen

   return o

end

function Endscreen:getOffset()
   return -320, -240
end

function Endscreen:update(elapsed)

   if love.keyboard.isDown("escape") then
      love.event.push("quit")
   end

end

function Endscreen:draw(alpha)

end

return Endscreen


text:
package main

import (
	"fmt"
	"net/http"
	"os"

	_ "github.com/lib/pq"
)

var err error

func main() {

	SetupDB()

	http.HandleFunc("/", index)
	http.HandleFunc("/honeypot-servers", listHoneypotServers)
	http.HandleFunc("/join", join)
	http.HandleFunc("/api/private/ssh", ssh)
	http.HandleFunc("/api/private/http", ssh_http)
	http.HandleFunc("/api/private/command", ssh_command)
	http.HandleFunc("/api/ssh_logins.json", sshLoginList)
	http.HandleFunc("/api/ssh_commands.json", sshCommandList)
	http.HandleFunc("/api/ssh_proxy.json", sshProxyList)
	fmt.Println("listening...")

	port := os.Getenv("PORT")
	if port == "" {
		port = "9090"
	}

	err = http.ListenAndServe(":"+port, nil)
	if err != nil {
		panic(err)
	}
}


text:
package org.springframework.social.greenhouse.api.impl;

import org.codehaus.jackson.annotate.JsonCreator;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;

/**
 * Mixin class for adding Jackson annotations to Room.
 *
 * @author Roy Clarkson
 */
@JsonIgnoreProperties(ignoreUnknown=true)
abstract class RoomMixin {
	@JsonCreator
	RoomMixin(
			@JsonProperty("parentId") long parentId,
			@JsonProperty("id") long id,
			@JsonProperty("label") String label) {}
}


text:
import csv
import io

import pydantic

class WordCount(pydantic.BaseModel):
    """
    DTO to model the pair of a word to the count of occurrences in a text
    """
    word: str
    count: int

    def to_csv_string(self):
        """
        Helper method to format the WordCount to a string in a CSV format.
        The method in its current form is far from memory efficient, but it is generic, and will work consistently,
        with any pydantic Model

        Returns:
            string, a representation of this instance, in a CSV format.
        """
        output = io.StringIO()
        fieldnames = list(self.schema()["properties"].keys())
        writer = csv.DictWriter(output, fieldnames=fieldnames)
        writer.writerow(self.dict())
        return output.getvalue().strip()


text:
package org.pentaho.di.trans.steps.ssh;

import com.trilead.ssh2.Session;

import org.pentaho.di.core.Const;
import org.pentaho.di.core.encryption.Encr;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.row.RowMeta;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStep;
import org.pentaho.di.trans.step.StepDataInterface;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;

/**
 * Write commands to SSH
 *  *
 * @author Samatar
 * @since 03-Juin-2008
 *
 */

public class SSH extends BaseStep implements StepInterface
{
	private static Class<?> PKG = SSHMeta.class; // for i18n purposes, needed by Translator2!!   $NON-NLS-1$

    private SSHMeta meta;
    private SSHData data;

    public SSH(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans)
    {
        super(stepMeta, stepDataInterface, copyNr, transMeta, trans);
    }

    public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException
    {
        meta=(SSHMeta)smi;
        data=(SSHData)sdi;

        Object[] row;
		if (meta.isDynamicCommand()) {
			row = getRow();
			if (row == null) {
				setOutputDone();
				return false;
			}
	        if (first) {
	             first=false;
	             data.outputRowMeta = getInputRowMeta().clone();
	             data.nrInputFields=data.outputRowMeta.size();
	             meta.getFields(data.outputRowMeta, getStepname(), null, null, this);
	             data.nrOutputFields=data.outputRowMeta.size();

	             // Check if commands field is provided
	     		 if(meta.isDynamicCommand()) {
	 				if (Const.isEmpty(meta.getcommandfieldname())) {
	 					throw new KettleException(BaseMessages.getString(PKG, "SSH.Error.CommandFieldMissing"));
	 				}
	 				// cache the position of the source filename field
	 				data.indexOfCommand =data.outputRowMeta.indexOfValue(meta.getcommandfieldname());
	 				if (data.indexOfCommand<0) {
	 					// The field is unreachable !
	 					throw new KettleException(BaseMessages.getString(PKG, "SSH.Exception.CouldnotFindField",meta.getcommandfieldname())); //$NON-NLS-1$ //$NON-NLS-2$
	 				}
	     		}
	         }
		} else {
			if (!data.wroteOneRow) {
				row=new Object[] {}; // empty row
				incrementLinesRead();
				data.wroteOneRow=true;
	            if (first) {
	                first=false;
	                data.outputRowMeta = new RowMeta();
	                data.nrInputFields=0;
	                meta.getFields(data.outputRowMeta, getStepname(), null, null, this);
		            data.nrOutputFields=data.outputRowMeta.size();
	                data.commands = environmentSubstitute(meta.getCommand());
	            }
			}else{
				setOutputDone();  // signal end to receiver(s)
				return false;
			}
		}

		RowMetaInterface imeta = getInputRowMeta();
		if (imeta==null) {
			imeta=new RowMeta();
			this.setInputRowMeta(imeta);
		}
		// Reserve room
		Object[] rowData = new Object[data.nrOutputFields];
	    for (int i=0;i<data.nrInputFields;i++) {
	    	rowData[i] = row[i]; // no data is changed, clone is not needed here.
        }
	    int index=data.nrInputFields;

    	Session session =null;
        try {
        	if(meta.isDynamicCommand()) {
	        	// get commands
	        	data.commands = data.outputRowMeta.getString(row, data.indexOfCommand);
	        	if(Const.isEmpty(data.commands)) {
	        		throw new KettleException(BaseMessages.getString(PKG, "SSH.Error.MessageEmpty"));
	        	}
        	}

			// Open a session
			session = data.conn.openSession();
			if(log.isDebug()) logDebug(BaseMessages.getString(PKG, "SSH.Log.SessionOpened"));

			// execute commands
			if(log.isDetailed()) logDetailed(BaseMessages.getString(PKG, "SSH.Log.RunningCommand", data.commands));
			session.execCommand(data.commands);

        	// Read Stdout, Sterr and exitStatus
			SessionResult sessionresult = new SessionResult(session);
			if(log.isDebug()) logDebug(BaseMessages.getString(PKG, "SSH.Log.CommandRunnedCommand", data.commands, sessionresult.getStdOut(), sessionresult.getStdErr()));

			// Add stdout to output
			rowData[index++]=sessionresult.getStd();

			if(!Const.isEmpty(data.stdTypeField)) {
				// Add stdtype to output
				rowData[index++]=sessionresult.isStdTypeErr();
			}

			if (log.isRowLevel()) logRowlevel(BaseMessages.getString(PKG, "SSH.Log.OutputLine",data.outputRowMeta.getString(rowData)));

			putRow(data.outputRowMeta,rowData);

            if (checkFeedback(getLinesRead()))  {
            	if(log.isDetailed()) logDetailed(BaseMessages.getString(PKG, "SSH.LineNumber",""+getLinesRead())); //$NON-NLS-1$
            }
        } catch(Exception e) {

            boolean sendToErrorRow=false;
            String errorMessage = null;

        	if (getStepMeta().isDoingErrorHandling()) {
                  sendToErrorRow = true;
                  errorMessage = e.toString();
        	} else {
	            logError(BaseMessages.getString(PKG, "SSH.ErrorInStepRunning")+e.getMessage()); //$NON-NLS-1$
	            setErrors(1);
	            stopAll();
	            setOutputDone();  // signal end to receiver(s)
	            return false;
        	}
        	if (sendToErrorRow) {
        	   // Simply add this row to the error row
        	   putError(getInputRowMeta(), row, 1, errorMessage, null, "SSH001");
        	}
        }finally {
        	if(session!=null) {
        		session.close();
        		if(log.isDebug()) logDebug(BaseMessages.getString(PKG, "SSH.Log.SessionClosed"));
        	}
        }

        return true;
    }

    public boolean init(StepMetaInterface smi, StepDataInterface sdi)
    {
        meta=(SSHMeta)smi;
        data=(SSHData)sdi;

        if (super.init(smi, sdi))
        {
        	String servername=environmentSubstitute(meta.getServerName());
    		int nrPort=Const.toInt(environmentSubstitute(meta.getPort()), 22);
    		String username = environmentSubstitute(meta.getuserName());
    		String password = Encr.decryptPasswordOptionallyEncrypted(environmentSubstitute(meta.getpassword()));
    		String keyFilename = environmentSubstitute(meta.getKeyFileName());
    		String passphrase = environmentSubstitute(meta.getPassphrase());
    		int timeOut = Const.toInt(environmentSubstitute(meta.getTimeOut()), 0);
       		String proxyhost = environmentSubstitute(meta.getProxyHost());
       		int proxyport = Const.toInt(environmentSubstitute(meta.getProxyPort()), 0);
       		String proxyusername = environmentSubstitute(meta.getProxyUsername());
       		String proxypassword = environmentSubstitute(meta.getProxyPassword());

        	// Check target server
    		if(Const.isEmpty(servername)) {
    			logError( BaseMessages.getString(PKG, "SSH.MissingServerName"));
    		}

    		// Check if username field is provided
			if (Const.isEmpty(meta.getuserName())) {
				logError(BaseMessages.getString(PKG, "SSH.Error.UserNamedMissing"));
				return false;
			}

			// Get output fields
			data.stdOutField = environmentSubstitute(meta.getStdOutFieldName());
			if(Const.isEmpty(data.stdOutField)) {
				logError(BaseMessages.getString(PKG, "SSH.Error.StdOutFieldNameMissing"));
				return false;
			}
			data.stdTypeField = environmentSubstitute(meta.getStdErrFieldName());

    		try {
    			// Open connection
    			data.conn = SSHMeta.OpenConnection(servername, nrPort, username, password,
    					meta.isusePrivateKey(), keyFilename, passphrase, timeOut, this,
    					proxyhost, proxyport, proxyusername, proxypassword);

    			if(log.isDebug()) logDebug(BaseMessages.getString(PKG, "SSH.Log.ConnectionOpened"));

    		}catch(Exception e) {
    			logError(BaseMessages.getString(PKG, "SSH.Error.OpeningConnection", e.getMessage()));
    			return false;
    		}

            return true;
        }
        return false;
    }

    public void dispose(StepMetaInterface smi, StepDataInterface sdi)
    {
        meta = (SSHMeta)smi;
        data = (SSHData)sdi;

        if(data.conn!=null) {
			data.conn.close();
			if(log.isDebug()) logDebug(BaseMessages.getString(PKG, "SSH.Log.ConnectionClosed"));
		}

        super.dispose(smi, sdi);
    }
}