text:
<!doctype html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>Keyboard | p1 wiki</title>
	<meta name="description" content="">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="../assets/css/main.css">

						Search
						<input id="tsd-search-field" type="text" />

Preparing search index...

The search index is not available

					p1 wiki

						Options

								All

Public

Public/Protected

All

							<input type="checkbox" id="tsd-filter-inherited" checked />
							Inherited
							<input type="checkbox" id="tsd-filter-externals" checked />
							Externals
							<input type="checkbox" id="tsd-filter-only-exported" />
							Only exported

					Menu

					Globals

					"enum/Keyboard"

					Keyboard

Enumeration Keyboard

本类为键盘常用的key值枚举

Index

Enumeration members

A

ALT

B

BACKSPACE

C

CAPSLOCK

CTRL

D

DELETE

DOWN

E

END

ENTER

ESC

F

F1

F10

F11

F12

F2

F3

F4

F5

F6

F7

F8

F9

G

H

HOME

I

INSERT

J

K

L

LEFT

M

N

NUMPAD_<wbr>0

NUMPAD_<wbr>1

NUMPAD_<wbr>2

NUMPAD_<wbr>3

NUMPAD_<wbr>4

NUMPAD_<wbr>5

NUMPAD_<wbr>6

NUMPAD_<wbr>7

NUMPAD_<wbr>8

NUMPAD_<wbr>9

NUM_<wbr>0

NUM_<wbr>1

NUM_<wbr>2

NUM_<wbr>3

NUM_<wbr>4

NUM_<wbr>5

NUM_<wbr>6

NUM_<wbr>7

NUM_<wbr>8

NUM_<wbr>9

O

P

PAGEDOWN

PAGEUP

Q

R

RIGHT

S

SHIFT

SPACE

T

TAB

U

UP

V

W

X

Y

Z

Enumeration members

A

A:  = 65

Defined in enum/Keyboard.ts:34

ALT

ALT:  = 18

Defined in enum/Keyboard.ts:10

B

B:  = 66

Defined in enum/Keyboard.ts:35

BACKSPACE

BACKSPACE:  = 8

Defined in enum/Keyboard.ts:5

C

C:  = 67

Defined in enum/Keyboard.ts:36

CAPSLOCK

CAPSLOCK:  = 20

Defined in enum/Keyboard.ts:11

CTRL

CTRL:  = 17

Defined in enum/Keyboard.ts:9

D

D:  = 68

Defined in enum/Keyboard.ts:37

DELETE

DELETE:  = 46

Defined in enum/Keyboard.ts:23

DOWN

DOWN:  = 40

Defined in enum/Keyboard.ts:21

E

E:  = 69

Defined in enum/Keyboard.ts:38

END

END:  = 35

Defined in enum/Keyboard.ts:16

ENTER

ENTER:  = 13

Defined in enum/Keyboard.ts:7

ESC

ESC:  = 27

Defined in enum/Keyboard.ts:12

F

F:  = 70

Defined in enum/Keyboard.ts:39

F1

F1:  = 112

Defined in enum/Keyboard.ts:70

F10

F10:  = 121

Defined in enum/Keyboard.ts:79

F11

F11:  = 122

Defined in enum/Keyboard.ts:80

F12

F12:  = 123

Defined in enum/Keyboard.ts:81

F2

F2:  = 113

Defined in enum/Keyboard.ts:71

F3

F3:  = 114

Defined in enum/Keyboard.ts:72

F4

F4:  = 115

Defined in enum/Keyboard.ts:73

F5

F5:  = 116

Defined in enum/Keyboard.ts:74

F6

F6:  = 117

Defined in enum/Keyboard.ts:75

F7

F7:  = 118

Defined in enum/Keyboard.ts:76

F8

F8:  = 119

Defined in enum/Keyboard.ts:77

F9

F9:  = 120

Defined in enum/Keyboard.ts:78

G

G:  = 71

Defined in enum/Keyboard.ts:40

H

H:  = 72

Defined in enum/Keyboard.ts:41

HOME

HOME:  = 36

Defined in enum/Keyboard.ts:17

I

I:  = 73

Defined in enum/Keyboard.ts:42

INSERT

INSERT:  = 45

Defined in enum/Keyboard.ts:22

J

J:  = 74

Defined in enum/Keyboard.ts:43

K

K:  = 75

Defined in enum/Keyboard.ts:44

L

L:  = 76

Defined in enum/Keyboard.ts:45

LEFT

LEFT:  = 37

Defined in enum/Keyboard.ts:18

M

M:  = 77

Defined in enum/Keyboard.ts:46

N

N:  = 78

Defined in enum/Keyboard.ts:47

NUMPAD_<wbr>0

NUMPAD_<wbr>0:  = 96

Defined in enum/Keyboard.ts:60

NUMPAD_<wbr>1

NUMPAD_<wbr>1:  = 97

Defined in enum/Keyboard.ts:61

NUMPAD_<wbr>2

NUMPAD_<wbr>2:  = 98

Defined in enum/Keyboard.ts:62

NUMPAD_<wbr>3

NUMPAD_<wbr>3:  = 99

Defined in enum/Keyboard.ts:63

NUMPAD_<wbr>4

NUMPAD_<wbr>4:  = 100

Defined in enum/Keyboard.ts:64

NUMPAD_<wbr>5

NUMPAD_<wbr>5:  = 101

Defined in enum/Keyboard.ts:65

NUMPAD_<wbr>6

NUMPAD_<wbr>6:  = 102

Defined in enum/Keyboard.ts:66

NUMPAD_<wbr>7

NUMPAD_<wbr>7:  = 103

Defined in enum/Keyboard.ts:67

NUMPAD_<wbr>8

NUMPAD_<wbr>8:  = 104

Defined in enum/Keyboard.ts:68

NUMPAD_<wbr>9

NUMPAD_<wbr>9:  = 105

Defined in enum/Keyboard.ts:69

NUM_<wbr>0

NUM_<wbr>0:  = 48

Defined in enum/Keyboard.ts:24

NUM_<wbr>1

NUM_<wbr>1:  = 49

Defined in enum/Keyboard.ts:25

NUM_<wbr>2

NUM_<wbr>2:  = 50

Defined in enum/Keyboard.ts:26

NUM_<wbr>3

NUM_<wbr>3:  = 51

Defined in enum/Keyboard.ts:27

NUM_<wbr>4

NUM_<wbr>4:  = 52

Defined in enum/Keyboard.ts:28

NUM_<wbr>5

NUM_<wbr>5:  = 53

Defined in enum/Keyboard.ts:29

NUM_<wbr>6

NUM_<wbr>6:  = 54

Defined in enum/Keyboard.ts:30

NUM_<wbr>7

NUM_<wbr>7:  = 55

Defined in enum/Keyboard.ts:31

NUM_<wbr>8

NUM_<wbr>8:  = 56

Defined in enum/Keyboard.ts:32

NUM_<wbr>9

NUM_<wbr>9:  = 57

Defined in enum/Keyboard.ts:33

O

O:  = 79

Defined in enum/Keyboard.ts:48

P

P:  = 80

Defined in enum/Keyboard.ts:49

PAGEDOWN

PAGEDOWN:  = 34

Defined in enum/Keyboard.ts:15

PAGEUP

PAGEUP:  = 33

Defined in enum/Keyboard.ts:14

Q

Q:  = 81

Defined in enum/Keyboard.ts:50

R

R:  = 82

Defined in enum/Keyboard.ts:51

RIGHT

RIGHT:  = 39

Defined in enum/Keyboard.ts:20

S

S:  = 83

Defined in enum/Keyboard.ts:52

SHIFT

SHIFT:  = 16

Defined in enum/Keyboard.ts:8

SPACE

SPACE:  = 32

Defined in enum/Keyboard.ts:13

T

T:  = 84

Defined in enum/Keyboard.ts:53

TAB

TAB:  = 9

Defined in enum/Keyboard.ts:6

U

U:  = 85

Defined in enum/Keyboard.ts:54

UP

UP:  = 38

Defined in enum/Keyboard.ts:19

V

V:  = 86

Defined in enum/Keyboard.ts:55

W

W:  = 87

Defined in enum/Keyboard.ts:56

X

X:  = 88

Defined in enum/Keyboard.ts:57

Y

Y:  = 89

Defined in enum/Keyboard.ts:58

Z

Z:  = 90

Defined in enum/Keyboard.ts:59

						Globals

						"enum/<wbr>Keyboard"

						Keyboard

								A

								ALT

								B

								BACKSPACE

								C

								CAPSLOCK

								CTRL

								D

								DELETE

								DOWN

								E

								END

								ENTER

								ESC

								F

								F1

								F10

								F11

								F12

								F2

								F3

								F4

								F5

								F6

								F7

								F8

								F9

								G

								H

								HOME

								I

								INSERT

								J

								K

								L

								LEFT

								M

								N

								NUMPAD_<wbr>0

								NUMPAD_<wbr>1

								NUMPAD_<wbr>2

								NUMPAD_<wbr>3

								NUMPAD_<wbr>4

								NUMPAD_<wbr>5

								NUMPAD_<wbr>6

								NUMPAD_<wbr>7

								NUMPAD_<wbr>8

								NUMPAD_<wbr>9

								NUM_<wbr>0

								NUM_<wbr>1

								NUM_<wbr>2

								NUM_<wbr>3

								NUM_<wbr>4

								NUM_<wbr>5

								NUM_<wbr>6

								NUM_<wbr>7

								NUM_<wbr>8

								NUM_<wbr>9

								O

								P

								PAGEDOWN

								PAGEUP

								Q

								R

								RIGHT

								S

								SHIFT

								SPACE

								T

								TAB

								U

								UP

								V

								W

								X

								Y

								Z

Legend

Module

Object literal

Variable

Function

Function with type parameter

Index signature

Type alias

Enumeration

Enumeration member

Property

Method

Interface

Interface with type parameter

Constructor

Property

Method

Index signature

Class

Class with type parameter

Constructor

Property

Method

Accessor

Index signature

Inherited constructor

Inherited property

Inherited method

Inherited accessor

Protected property

Protected method

Protected accessor

Private property

Private method

Private accessor

Static property

Static method

Generated using TypeDoc


text:
package org.apache.derbyTesting.perf.basic.jdbc;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import junit.framework.Test;
import org.apache.derbyTesting.functionTests.util.streams.LoopingAlphabetReader;
import org.apache.derbyTesting.junit.BaseTestSuite;
import org.apache.derbyTesting.junit.CleanDatabaseTestSetup;
import org.apache.derbyTesting.junit.JDBCPerfTestCase;
import org.apache.derbyTesting.perf.clients.BackToBackLoadGenerator;
import org.apache.derbyTesting.perf.clients.Client;
import org.apache.derbyTesting.perf.clients.DBFiller;
import org.apache.derbyTesting.perf.clients.LoadGenerator;
import org.apache.derbyTesting.perf.clients.SingleRecordFiller;
import org.apache.derbyTesting.perf.clients.SingleRecordSelectClient;

/**
 * A series of tests accessing Clobs in various ways.
 *

 * These tests are intended to detect Clob performance regressions. Before
 * committing a patch that might change the Clob performance characteristics,
 * first run these tests on a clean build and then with the patch applied. The
 * results can only be compared when both runs are done on the same machine.
 *

 * The results are time taken to execute the test. Lower duration is better
 * (improvement). Currently the results are printed to standard out. There is
 * one exception, which is {@code testConcurrency}. For this test, the
 * throughput is printed and it will always run for a fixed amount of time.
 *

 * The tests are written with two axis in mind: read-only vs update and small vs
 * large. These axis were chosen based on the Clob implementation at the time.
 * In the context of this test, small means the Clob is represented as a string
 * by the Derby store and large means the Clob is represtend as a stream into
 * the Derby store. When a Clob is modified, an in-memory or on disk temporary
 * copy is created. The performance of these temporary representations are
 * tested with the tests that modify the Clob content.
 *

 * System properties controlling test behavior:
 *

 *
derby.tests.disableSmallClobs

 *
Whether or not to disable the testing of small Clobs.

 *
derby.tests.disableLargeClobs

 *
Whether or not to disable the testing of large Clobs.

 *
derby.tests.disableConcurrencyTest

 *
Whether or not to disable the concurrency test.

 *
derby.tests.largeClobSize

 *
Size of the large Clobs in MB, 15 MB is the default.

 *
derby.tests.runLargeClobTests

 *
A list of one or more tests to run. Only tests using large Clobs
 *          should be specified, but this is not enforced. Example:
 *          <tt>testFetchLargeClobPieceByPiece,testLargeClobGetLength</tt>

 *

 *
 *

 * NOTE: Currently there are no tests for the client driver (network)
 * or for encrypted Clobs.
 */
public class ClobAccessTest
        extends JDBCPerfTestCase {

    private static final boolean disableSmallClobs =
            Boolean.getBoolean("derby.tests.disableSmallClobs");
    private static final boolean disableLargeClobs =
            Boolean.getBoolean("derby.tests.disableLargeClobs");
    private static final boolean disableConcurrencyTest =
            Boolean.getBoolean("derby.tests.disableConcurrencyTest");
    /**
     * A list of one or more tests to be run. Only tests using a large Clob
     * should be specified.
     */
    private static final String runLargeClobTests =
            System.getProperty("derby.tests.runLargeClobTests", null);
    private static final int largeClobSizeMB =
            Integer.getInteger("derby.tests.largeClobSize", 15).intValue();

    /** Maximum buffer size to use. */
    private static final int MAX_BSIZE = 32676;

    /**
     * Instantiates a new test that will be run the specified number of
     * iterations and repeated as specified.
     *
     * @param name name of the test to instantiate
     * @param iterations number of iterations per repetition
     * @param repeats number of repetitions
     */
    public ClobAccessTest(String name, int iterations, int repeats) {
        super(name, iterations, repeats);
    }

    /**
     * Set autocommit to false by default.
     */
    public void initializeConnection(Connection conn)
            throws SQLException {
        conn.setAutoCommit(false);
    }

    public static Test suite() {
        BaseTestSuite mainSuite = new BaseTestSuite("ClobAccessTest suite");
        if (!disableSmallClobs) {
            int iters = 50;
            int reps = 1;
            println("Adding small Clob tests.");
            BaseTestSuite smallSuite = new BaseTestSuite("Small Clob suite");
            smallSuite.addTest(new ClobAccessTest(
                    "testFetchSmallClobs", iters, reps));
            smallSuite.addTest(new ClobAccessTest(
                    "testFetchSmallClobsInaccurateLength", iters, reps));
            smallSuite.addTest(new ClobAccessTest(
                    "testModifySmallClobs", iters, reps));
            mainSuite.addTest(smallSuite);
        }
        if (!disableLargeClobs) {
            int iters = 5;
            int reps = 1;
            String[] tests = new String[] {
                    "testFetchLargeClobs",
                    "testFetchLargeClobsModified",
                    "testFetchLargeClobWithStream",
                    "testFetchLargeClobOneByOneCharBaseline",
                    "testFetchLargeClobOneByOneCharModified",
                    "testFetchLargeClobOneByOneChar",
                    "testFetchLargeClobPieceByPiece",
                    "testFetchLargeClobPieceByPieceModified",
                    "testLargeClobGetLength",
                    "testLargeClobGetLengthModified",
                    "testLargeClobTruncateLengthMinusOne",
                    "testFetchLargeClobPieceByPieceBackwards",
                };
            // See if the user has overridden which tests to run.
            if (runLargeClobTests != null) {
                String[] specifiedTests = runLargeClobTests.split(",");
                if (specifiedTests.length > 0) {
                    tests = specifiedTests;
                }
            }
            println("Adding " + tests.length + " large Clob tests.");
            BaseTestSuite largeSuite = new BaseTestSuite("Large Clob suite");
            for (int i=0; i < tests.length; i++) {
                largeSuite.addTest(new ClobAccessTest(tests[i] , iters, reps));
            }
            mainSuite.addTest(largeSuite);
        }
        if (!disableConcurrencyTest) {
            mainSuite.addTest(new ClobAccessTest("testConcurrency", 1, 1));
        }
        return new CleanDatabaseTestSetup(mainSuite) {
            protected void decorateSQL(Statement stmt)
                    throws SQLException {
                initializeClobData(stmt);
            }
        };
    }

    /**
     * Fetches a number of small Clobs, getting the content using getSubString.
     *

     * The exact length of the clob is used when getting the string.
     */
    public void testFetchSmallClobs()
            throws SQLException {
        PreparedStatement ps = prepareStatement(
                "select dClob, length from smallClobs");
        ResultSet rs = ps.executeQuery();
        while (rs.next()) {
            Clob clob = rs.getClob(1);
            int clobLength = rs.getInt(2);
            String content = clob.getSubString(1, clobLength);
        }
        rs.close();
    }

    /**
     * Fetches a number of small Clobs, getting the content using getSubString.
     *

     * A too long length of the clob is used when getting the string.
     */
    public void testFetchSmallClobsInaccurateLength()
            throws SQLException {
        PreparedStatement ps = prepareStatement(
                "select dClob, length from smallClobs");
        ResultSet rs = ps.executeQuery();
        while (rs.next()) {
            Clob clob = rs.getClob(1);
            int unusedLength = rs.getInt(2);
            String content = clob.getSubString(1, 100);
        }
        rs.close();
    }

    /**
     * Test fetching the content after adding a single character at the end.
     */
    public void testModifySmallClobs()
            throws SQLException {
        PreparedStatement ps = prepareStatement(
                "select dClob, length from smallClobs");
        ResultSet rs = ps.executeQuery();
        while (rs.next()) {
            Clob clob = rs.getClob(1);
            int length = rs.getInt(2);
            clob.setString(length, "X");
            String content = clob.getSubString(1, 100);
        }
        rs.close();
    }

    public void testFetchLargeClobs()
            throws IOException, SQLException {
        PreparedStatement ps = prepareStatement(
                "select dClob, length from largeClobs");
        ResultSet rs = ps.executeQuery();
        char[] charBuf = new char[16*1024]; // 16 KB
        while (rs.next()) {
            Clob clob = rs.getClob(1);
            Reader content = clob.getCharacterStream();
            long remaining = rs.getInt(2);
            while (remaining > 0) {
                remaining -= content.read(charBuf);
            }
            content.close();
        }
        rs.close();
    }

    public void testFetchLargeClobsModified()
            throws IOException, SQLException {
        PreparedStatement ps = prepareStatement(
                "select dClob, length from largeClobs");
        ResultSet rs = ps.executeQuery();
        char[] charBuf = new char[16*1024]; // 16 KB
        while (rs.next()) {
            Clob clob = rs.getClob(1);
            clob.setString(1, "X");
            Reader content = clob.getCharacterStream();
            long remaining = rs.getInt(2);
            while (remaining > 0) {
                remaining -= content.read(charBuf);
            }
            content.close();
        }
        rs.close();
    }

    /**
     * Fetches a single Clob and reads it char by char, but utilizing a
     * buffered stream to get a lower time bound on the read operation.
     */
    public void testFetchLargeClobOneByOneCharBaseline()
            throws IOException, SQLException {
        // Select just one Clob.
        PreparedStatement ps = prepareStatement(
                "select dClob, length from largeClobs where id = 4");
        ResultSet rs = ps.executeQuery();
        while (rs.next()) {
            Clob clob = rs.getClob(1);
            Reader content = clob.getCharacterStream();
            BufferedReader bufferedContent = new BufferedReader(content);
            long remaining = rs.getInt(2);
            while (bufferedContent.read() != -1) {
                remaining--;
            }
            content.close();
            assertEquals(0, remaining);
        }
        rs.close();
    }

    public void testFetchLargeClobOneByOneChar()
            throws IOException, SQLException {
        // Select just one Clob.
        PreparedStatement ps = prepareStatement(
                "select dClob, length from largeClobs where id = 4");
        ResultSet rs = ps.executeQuery();
        while (rs.next()) {
            Clob clob = rs.getClob(1);
            Reader content = clob.getCharacterStream();
            long remaining = rs.getInt(2);
            while (content.read() != -1) {
                remaining--;
            }
            content.close();
            assertEquals(0, remaining);
        }
        rs.close();
    }

    public void testFetchLargeClobOneByOneCharModified()
            throws IOException, SQLException {
        // Select just one Clob.
        PreparedStatement ps = prepareStatement(
                "select dClob, length from largeClobs where id = 4");
        ResultSet rs = ps.executeQuery();
        while (rs.next()) {
            Clob clob = rs.getClob(1);
            long remaining = rs.getInt(2);
            clob.setString(++remaining, "X");
            Reader content = clob.getCharacterStream();
            while (content.read() != -1) {
                remaining --;
            }
            content.close();
            assertEquals(0, remaining);
        }
        rs.close();
    }

    /**
     * Tests that repositioning within the current internal character buffer is
     * cheap.
     *

     * Note that the positions used in this test have been chosen based on the
     * internal buffer size (8KB), which is an implementation detail.
     *
     * @throws SQLException if the test fails
     */
    public void testFetchLargeClobPieceByPieceBackwards()
            throws IOException, SQLException {
        boolean modifyClob = false;
        final int intBufSize = 8192; // Implementation detail.
        // Select just one Clob.
        PreparedStatement ps = prepareStatement(
                "select dClob, length from largeClobs where id = 4");
        ResultSet rs = ps.executeQuery();
        while (rs.next()) {
            Clob clob = rs.getClob(1);
            int remaining = rs.getInt(2);
            if (modifyClob) {
                // Modify the Clob to create a temporary copy in memory or on
                // disk (depends on the Clob size).
                long modifyStart = System.currentTimeMillis();
                clob.setString(++remaining, "X");
                println("Clob modification duration: " +
                        (System.currentTimeMillis() - modifyStart) + " ms");
            }
            // Go close to the middle of the Clob on a buffer border, then
            // subtract the piece size to avoid repositioning.
            final int pieceSize = 10;
            final long pos = (remaining / 2 / intBufSize) *
                    intBufSize - pieceSize;
            for (int i=0; i < intBufSize; i += pieceSize) {
                String str = clob.getSubString(
                        pos -i, pieceSize);
            }
        }
        rs.close();
    }

    /**
     * Fetches a "large" Clob piece by piece using getSubString.
     */
    public void testFetchLargeClobPieceByPiece()
            throws IOException, SQLException {
        fetchPieceByPiece(false);
    }

    /**
     * Fetches a "large" Clob piece by piece using getSubString.
     *

     * The Clob is modified before fetched to create a temporary Clob
     * representation in memory / on disk.
     */
    public void testFetchLargeClobPieceByPieceModified()
            throws IOException, SQLException {
        fetchPieceByPiece(true);
    }

    /**
     * Fetches a "large" Clob piece by piece using getSubString.
     *
     * @param modifyClob whether to modify the Clob before fetching it
     *      (determines the internal Derby Clob representation)
     */
    private void fetchPieceByPiece(final boolean modifyClob)
            throws IOException, SQLException {
        // Select just one Clob.
        PreparedStatement ps = prepareStatement(
                "select dClob, length from largeClobs where id = 4");
        ResultSet rs = ps.executeQuery();
        while (rs.next()) {
            Clob clob = rs.getClob(1);
            int remaining = rs.getInt(2);
            Reader myReader = new LoopingAlphabetReader(remaining);
            if (modifyClob) {
                // Modify the Clob to create a temporary copy in memory or on
                // disk (depends on the Clob size).
                long modifyStart = System.currentTimeMillis();
                clob.setString(++remaining, "X");
                println("Clob modification duration: " +
                        (System.currentTimeMillis() - modifyStart) + " ms");
            }
            long pos = 1;
            while (remaining > 0) {
                String str = clob.getSubString(
                        pos, Math.min(MAX_BSIZE, remaining));
                myReader.skip(Math.min(MAX_BSIZE, remaining) -1);
                pos += str.length();
                remaining -= str.length();
                // Avoid failure on the last char when Clob is modified.
                if (!modifyClob || remaining != 0) {
                    assertEquals(myReader.read(), str.charAt(str.length() -1));
                }
            }
        }
        rs.close();
    }

    public void testFetchLargeClobWithStream()
            throws IOException, SQLException {
        boolean modifyClob = false;
        // Select just one Clob.
        PreparedStatement ps = prepareStatement(
                "select dClob, length from largeClobs where id = 5");
        ResultSet rs = ps.executeQuery();
        while (rs.next()) {
            Clob clob = rs.getClob(1);
            int remaining = rs.getInt(2);
            Reader myReader = new LoopingAlphabetReader(remaining);
            if (modifyClob) {
                // Modify the Clob to create a temporary copy in memory or on
                // disk (depends on the Clob size).
                long modifyStart = System.currentTimeMillis();
                clob.setString(++remaining, "X");
                println("Clob modification duration: " +
                        (System.currentTimeMillis() - modifyStart) + " ms");
            }
            Reader clobReader = clob.getCharacterStream();
            char[] buf = new char[MAX_BSIZE];
            while (remaining > 0) {
                int read = clobReader.read(buf, 0, Math.min(MAX_BSIZE, remaining));
                myReader.skip(read -1);
                remaining -= read;
                assertEquals(myReader.read(), buf[read -1]);
            }
        }
        rs.close();

    }

    /**
     * Tests if the Clob length is cached.
     */
    public void testLargeClobGetLength() throws SQLException {
        // Select just one Clob.
        PreparedStatement ps = prepareStatement(
                "select dClob, length from largeClobs where id = 7");
        ResultSet rs = ps.executeQuery();
        while (rs.next()) {
            Clob clob = rs.getClob(1);
            long remaining = rs.getInt(2);
            // This should be cached. Lots of data have to be skipped otherwise.
            for (int i=0; i < 50; i++) {
                assertEquals(remaining, clob.length());
            }
        }
        rs.close();
    }

    /**
     * Tests if the Clob length is cached.
     */
    public void testLargeClobGetLengthModified() throws SQLException {
        // Select just one Clob.
        PreparedStatement ps = prepareStatement(
                "select dClob, length from largeClobs where id = 7");
        ResultSet rs = ps.executeQuery();
        while (rs.next()) {
            Clob clob = rs.getClob(1);
            clob.setString(1, "X");
            long remaining = rs.getInt(2);
            // This should be cached. Lots of data have to be skipped otherwise.
            for (int i=0; i < 50; i++) {
                assertEquals(remaining, clob.length());
            }
        }
        rs.close();
    }

    /**
     * Tests the speed of transferring data from the store to local temporary
     * storage as part of the truncate operation.
     */
    public void testLargeClobTruncateLengthMinusOne()
            throws SQLException {
        // Select just one Clob.
        PreparedStatement ps = prepareStatement(
                "select dClob, length from largeClobs where id = 8");
        ResultSet rs = ps.executeQuery();
        while (rs.next()) {
            Clob clob = rs.getClob(1);
            int length = rs.getInt(2);
            clob.truncate(length -1);
        }
    }

    /**
     * Runs a test using multiple threads.
     *

     * This test intends to detect problems with small Clobs and general
     * problems with concurrency.
     *

     * NOTE: To produce more reliable numbers, please run the performance
     * client independently outside this JUnit test framework. Performance also
     * suffers greatly with SANE builds.
     */
    public void testConcurrency()
            throws InterruptedException, SQLException {

        final int records = 100000;
        final int tables = 1;
        final int threads = 16;
        DBFiller filler = new SingleRecordFiller(
                records, tables, java.sql.Types.CLOB, false, false);
        Connection conn = getConnection();
        println("initializing database...");
        filler.fill(conn);
        conn.close();

        Client[] clients = new Client[threads];
        for (int i = 0; i < clients.length; i++) {
            Connection c = openDefaultConnection();
            c.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
            clients[i] = new SingleRecordSelectClient(
                    records, tables, java.sql.Types.CLOB, false, false);
            clients[i].init(c);
        }

        final int warmupSec = 30;
        final int steadySec = 60;
        LoadGenerator gen = new BackToBackLoadGenerator();
        gen.init(clients);
        println("starting warmup...");
        gen.startWarmup();
        Thread.sleep(1000L * warmupSec);
        println("entering steady state...");
        gen.startSteadyState();
        Thread.sleep(1000L * steadySec);
        println("stopping threads...");
        gen.stop();
        // Should get the printstream used by the test harness here.
        gen.printReport(System.out);
    }

    /**
     * Generates test data.
     */
    private static void initializeClobData(Statement stmt)
            throws SQLException {
        Connection con = stmt.getConnection();
        con.setAutoCommit(false);
        if (!disableSmallClobs) {
            println("Generating small Clobs test data.");
            // Insert small Clob data.
            try {
                stmt.executeUpdate("drop table smallClobs");
            } catch (SQLException sqle) {
                assertSQLState("42Y55", sqle);
            }
            stmt.executeUpdate(
                    "create table smallClobs (dClob clob, length int)");
            PreparedStatement smallClobInsert = con.prepareStatement(
                    "insert into smallClobs values (?,?)");
            // Insert 15 000 small clobs.
            for (int clobCounter = 1; clobCounter < 15001; clobCounter++) {
                String content = Integer.toString(clobCounter);
                smallClobInsert.setString(1, content);
                smallClobInsert.setInt(2, content.length());
                smallClobInsert.executeUpdate();
                if (clobCounter % 1000 == 0) {
                    con.commit();
                }
            }
            con.commit();
        }

        if (!disableLargeClobs) {
            println("Generating large Clobs test data.");
            // Insert large Clob data.
            try {
                stmt.executeUpdate("drop table largeClobs");
            } catch (SQLException sqle) {
                assertSQLState("42Y55", sqle);
            }
            stmt.executeUpdate("create table largeClobs (" +
                    "id int unique not null, dClob clob, length int)");
            PreparedStatement largeClobInsert = con.prepareStatement(
                    "insert into largeClobs values (?,?,?)");
            // Insert some large Clobs.
            final int size = largeClobSizeMB*1024*1024; // 15 MB default
            for (int clobCounter = 1; clobCounter < 11; clobCounter++) {
                largeClobInsert.setInt(1, clobCounter);
                largeClobInsert.setCharacterStream(
                        2, new LoopingAlphabetReader(size), size);
                largeClobInsert.setInt(3, size);
                largeClobInsert.executeUpdate();
                println("Inserted large Clob #" + (clobCounter -1));
            }
            con.commit();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
//// [nonNullReferenceMatching.ts]
type ElementRef = (element: HTMLElement | null) => void;

type ThumbProps = {
    elementRef?: ElementRef;
}

type ComponentProps = {
    thumbYProps?: ThumbProps;
    thumbXProps: ThumbProps;
}

class Component {
    props!: ComponentProps;
    public thumbYElementRef = (ref: HTMLElement | null) => {
        typeof this.props.thumbYProps!.elementRef === 'function' && this.props.thumbYProps!.elementRef(ref);

        typeof (this.props.thumbYProps!.elementRef) === 'function' && this.props.thumbYProps!.elementRef(ref);

        typeof ((this.props).thumbYProps!.elementRef)! === 'function' && this.props.thumbYProps!.elementRef(ref);

        typeof this.props.thumbXProps.elementRef === 'function' && this.props.thumbXProps.elementRef(ref);

        typeof this.props.thumbXProps.elementRef === 'function' && (this.props).thumbXProps.elementRef(ref);

        typeof this.props.thumbXProps.elementRef === 'function' && (this.props.thumbXProps).elementRef(ref);

        typeof this.props.thumbXProps.elementRef === 'function' && ((this.props)!.thumbXProps)!.elementRef(ref);

        typeof (this.props.thumbXProps).elementRef === 'function' && ((this.props)!.thumbXProps)!.elementRef(ref);

        typeof this.props!.thumbXProps!.elementRef === 'function' && ((this.props)!.thumbXProps)!.elementRef(ref);
    };
}

//// [nonNullReferenceMatching.js]
"use strict";
var Component = /** @class */ (function () {
    function Component() {
        var _this = this;
        this.thumbYElementRef = function (ref) {
            typeof _this.props.thumbYProps.elementRef === 'function' && _this.props.thumbYProps.elementRef(ref);
            typeof (_this.props.thumbYProps.elementRef) === 'function' && _this.props.thumbYProps.elementRef(ref);
            typeof ((_this.props).thumbYProps.elementRef) === 'function' && _this.props.thumbYProps.elementRef(ref);
            typeof _this.props.thumbXProps.elementRef === 'function' && _this.props.thumbXProps.elementRef(ref);
            typeof _this.props.thumbXProps.elementRef === 'function' && (_this.props).thumbXProps.elementRef(ref);
            typeof _this.props.thumbXProps.elementRef === 'function' && (_this.props.thumbXProps).elementRef(ref);
            typeof _this.props.thumbXProps.elementRef === 'function' && ((_this.props).thumbXProps).elementRef(ref);
            typeof (_this.props.thumbXProps).elementRef === 'function' && ((_this.props).thumbXProps).elementRef(ref);
            typeof _this.props.thumbXProps.elementRef === 'function' && ((_this.props).thumbXProps).elementRef(ref);
        };
    }
    return Component;
}());


text:
use strict;
use Data::Dumper;
use Carp;

#
# This is a SAS Component
#

=head1 NAME

roles_to_fids

=head1 SYNOPSIS

roles_to_fids [arguments] < input > output

=head1 DESCRIPTION

            You often wish to find the fids in one or more genomes that
            implement specific functional roles.  To do this, you can use
            roles_to_fids.

Example:

    roles_to_fids [arguments] < input > output

The standard input should be a tab-separated table (i.e., each line
is a tab-separated set of fields).  Normally, the last field in each
line would contain the identifer. If another column contains the identifier
use

    -c N

where N is the column (from 1) that contains the subsystem.

This is a pipe command. The input is taken from the standard input, and the
output is to the standard output.

=head1 COMMAND-LINE OPTIONS

Usage: roles_to_fids [arguments] < input > output

    -c num        Select the identifier from column num
    -i filename   Use filename rather than stdin for input

=head1 AUTHORS

L<The SEED Project|http://www.theseed.org>

=cut

our $usage = "usage: roles_to_fids [-c column genomes] < input > output";

use Bio::KBase::CDMI::CDMIClient;
use Bio::KBase::Utilities::ScriptThing;

my $column;

my $input_file;

my $kbO = Bio::KBase::CDMI::CDMIClient->new_for_script('c=i' => \$column,
				      'i=s' => \$input_file);
if (! $kbO) { print STDERR $usage; exit }

my $ih;
if ($input_file)
{
    open $ih, "<", $input_file or die "Cannot open input file $input_file: $!";
}
else
{
    $ih = \*STDIN;
}

while (my @tuples = Bio::KBase::Utilities::ScriptThing::GetBatch($ih, 1, $column)) {
    my @h = map { $_->[0] } @tuples;
    my $h = $kbO->roles_to_fids(\@h, \@ARGV);
    for my $tuple (@tuples) {
        #
        # Process output here and print.
        #
        my ($id, $line) = @$tuple;
        my $v = $h->{$id};

        if (! defined($v))
        {
            print STDERR $line,"\n";
        }
        elsif (ref($v) eq 'ARRAY')
        {
            foreach $_ (@$v)
            {
                print "$line\t$_\n";
            }
        }
        else
        {
            print "$line\t$v\n";
        }
    }
}

__DATA__


text:
title: "Dictionary'i güzel yazdırmak"
date: Apr 28, 2016 14:39
tags: python
external_url: http://python.gelistiriciyiz.biz/2016/04/28/dictionaryi-guzel-yazdirmak/
---


text:
<?php

class Rss extends ModelBase {

    public $rss_id;
    public $title;
    public $link;
    public $category_type;
    public $view_count;
    public $readed_at;
    public $created_at;
    public $updated_at;

    public function save($data = null, $whiteList = null)
    {
        if(!$this->rss_id) {
            $this->created_at = time();
        }
        $this->updated_at = time();
        return parent::save($data, $whiteList);
    }

    /**
     * @param null $parameters
     * @return \Phalcon\Mvc\Model\ResultsetInterface|Attend[]
     */
    public static function find($parameters=null) {
        return parent::find($parameters);
    }

    /**sour
     * @param null $parameters
     * @return \Phalcon\Mvc\Model|Attend
     */
    public static function findFirst($parameters=null) {
        return parent::findFirst($parameters);
    }

}


text:
require 'sequel'
require 'sequel-seek-pagination'

require 'graphql'
require 'graphql/relay'

Sequel::Database.extension :seek_pagination

module Prelay
  class Error < StandardError; end
  class DefinitionError < Error; end

  # Frozen empty objects, mostly for use as argument defaults. Makes sure that
  # we don't accidentally modify arguments passed to our methods, and cuts
  # down on the number of allocated objects.
  EMPTY_ARRAY = [].freeze
  EMPTY_HASH  = {}.freeze

  # Array of all permanent Prelay schemas that have been instantiated.
  SCHEMAS = []

  class << self
    def primary_schema
      SCHEMAS.first ||
        (block_given? ? yield : raise(Error, "Tried to access the primary Prelay schema when none has been defined."))
    end

    %w(Type Interface Query Mutation).each do |subclassable|
      eval <<-RUBY
        def #{subclassable}(schema:)
          c = Class.new(#{subclassable})
          c.schema = schema
          c
        end
      RUBY
    end
  end
end

require 'prelay/subclassable'

require 'prelay/type'
require 'prelay/interface'
require 'prelay/query'
require 'prelay/mutation'

require 'prelay/schema'

require 'prelay/graphql_processor'
require 'prelay/graphql_selection'
require 'prelay/relay_processor'
require 'prelay/relay_selection'
require 'prelay/relay_selection/connection_selection'
require 'prelay/relay_selection/edge_selection'
require 'prelay/relay_selection/field_selection'

require 'prelay/result_array'
require 'prelay/dataset_resolver'
require 'prelay/sequel_connection'

require 'prelay/connection'
require 'prelay/id'
require 'prelay/time_type'

require 'prelay/version'

GraphQL::Relay::BaseConnection.register_connection_implementation Prelay::ResultArray, Prelay::SequelConnection


text:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Categories on Nicholas Tinsley's Homepage</title>
    <link>https://sturmen.github.io/categories/</link>
    <description>Recent content in Categories on Nicholas Tinsley's Homepage</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en-us</language><atom:link href="https://sturmen.github.io/categories/index.xml" rel="self" type="application/rss+xml" />
  </channel>
</rss>


text:
package org.beckoning.web.loading.springboot;

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

import org.apache.commons.lang.StringUtils;
import org.beckoning.web.loading.constant.Constants;
import org.beckoning.web.loading.util.SessionUtil;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class SessionInterceptor extends HandlerInterceptorAdapter {
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String url = request.getRequestURL().toString();
		String path = request.getServletPath();
		if (!StringUtils.equals("/", path) && !StringUtils.contains(url, "login")
				&& !StringUtils.contains(url, "index")) {
			if (null == SessionUtil.getSessionAttribute(Constants.SESSION_USER_KEY)) {
				request.setAttribute("result", false);
				request.setAttribute("errorMsg", "登陆信息无效,请重新进行登陆。");
				String mainUrl = SessionUtil.getRealPath();
				response.sendRedirect(mainUrl);
				return false;
			}
		}
		return true;
	}

}


text:
#include <drm/drmP.h>
#include <drm/drm_crtc_helper.h>
#include <drm/drm_fb_helper.h>
#include <drm/drm_gem.h>
#include <linux/dma-buf.h>
#include <linux/reservation.h>

#include "mtk_drm_drv.h"
#include "mtk_drm_fb.h"
#include "mtk_drm_gem.h"

/*
 * mtk specific framebuffer structure.
 *
 * @fb: drm framebuffer object.
 * @gem_obj: array of gem objects.
 */
struct mtk_drm_fb {
	struct drm_framebuffer	base;
	/* For now we only support a single plane */
	struct drm_gem_object	*gem_obj;
};

#define to_mtk_fb(x) container_of(x, struct mtk_drm_fb, base)

struct drm_gem_object *mtk_fb_get_gem_obj(struct drm_framebuffer *fb)
{
	struct mtk_drm_fb *mtk_fb = to_mtk_fb(fb);

	return mtk_fb->gem_obj;
}

static int mtk_drm_fb_create_handle(struct drm_framebuffer *fb,
				    struct drm_file *file_priv,
				    unsigned int *handle)
{
	struct mtk_drm_fb *mtk_fb = to_mtk_fb(fb);

	return drm_gem_handle_create(file_priv, mtk_fb->gem_obj, handle);
}

static void mtk_drm_fb_destroy(struct drm_framebuffer *fb)
{
	struct mtk_drm_fb *mtk_fb = to_mtk_fb(fb);

	drm_framebuffer_cleanup(fb);

	drm_gem_object_unreference_unlocked(mtk_fb->gem_obj);

	kfree(mtk_fb);
}

static const struct drm_framebuffer_funcs mtk_drm_fb_funcs = {
	.create_handle = mtk_drm_fb_create_handle,
	.destroy = mtk_drm_fb_destroy,
};

static struct mtk_drm_fb *mtk_drm_framebuffer_init(struct drm_device *dev,
					const struct drm_mode_fb_cmd2 *mode,
					struct drm_gem_object *obj)
{
	struct mtk_drm_fb *mtk_fb;
	int ret;

	if (drm_format_num_planes(mode->pixel_format) != 1)
		return ERR_PTR(-EINVAL);

	mtk_fb = kzalloc(sizeof(*mtk_fb), GFP_KERNEL);
	if (!mtk_fb)
		return ERR_PTR(-ENOMEM);

	drm_helper_mode_fill_fb_struct(&mtk_fb->base, mode);

	mtk_fb->gem_obj = obj;

	ret = drm_framebuffer_init(dev, &mtk_fb->base, &mtk_drm_fb_funcs);
	if (ret) {
		DRM_ERROR("failed to initialize framebuffer\n");
		kfree(mtk_fb);
		return ERR_PTR(ret);
	}

	return mtk_fb;
}

/*
 * Wait for any exclusive fence in fb's gem object's reservation object.
 *
 * Returns -ERESTARTSYS if interrupted, else 0.
 */
int mtk_fb_wait(struct drm_framebuffer *fb)
{
	struct drm_gem_object *gem;
	struct reservation_object *resv;
	long ret;

	if (!fb)
		return 0;

	gem = mtk_fb_get_gem_obj(fb);
	if (!gem || !gem->dma_buf || !gem->dma_buf->resv)
		return 0;

	resv = gem->dma_buf->resv;
	ret = reservation_object_wait_timeout_rcu(resv, false, true,
						  MAX_SCHEDULE_TIMEOUT);
	/* MAX_SCHEDULE_TIMEOUT on success, -ERESTARTSYS if interrupted */
	if (WARN_ON(ret < 0))
		return ret;

	return 0;
}

struct drm_framebuffer *mtk_drm_mode_fb_create(struct drm_device *dev,
					       struct drm_file *file,
					       const struct drm_mode_fb_cmd2 *cmd)
{
	struct mtk_drm_fb *mtk_fb;
	struct drm_gem_object *gem;
	unsigned int width = cmd->width;
	unsigned int height = cmd->height;
	unsigned int size, bpp;
	int ret;

	if (drm_format_num_planes(cmd->pixel_format) != 1)
		return ERR_PTR(-EINVAL);

	gem = drm_gem_object_lookup(file, cmd->handles[0]);
	if (!gem)
		return ERR_PTR(-ENOENT);

	bpp = drm_format_plane_cpp(cmd->pixel_format, 0);
	size = (height - 1) * cmd->pitches[0] + width * bpp;
	size += cmd->offsets[0];

	if (gem->size < size) {
		ret = -EINVAL;
		goto unreference;
	}

	mtk_fb = mtk_drm_framebuffer_init(dev, cmd, gem);
	if (IS_ERR(mtk_fb)) {
		ret = PTR_ERR(mtk_fb);
		goto unreference;
	}

	return &mtk_fb->base;

unreference:
	drm_gem_object_unreference_unlocked(gem);
	return ERR_PTR(ret);
}


text:
<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rv_share_apps"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.tooploox.training.sample.sharingexample.activity.CustomShareActivity" />


text:
import { expectType, expectError } from 'tsd';
import { WebClient, WebAPICallResult } from '../../';
import { ChatPostMessageResponse } from '../../src/response/ChatPostMessageResponse';
import { ChatScheduleMessageResponse } from '../../src/response/ChatScheduleMessageResponse';
import { ChatPostEphemeralResponse } from '../../src/response/ChatPostEphemeralResponse';
import { ChatUpdateResponse } from '../../src/response/ChatUpdateResponse';

const web = new WebClient('TOKEN');

const chatPostMesssageResult: ChatPostMessageResponse = { ok: true };
const result: WebAPICallResult = chatPostMesssageResult;
expectType<WebAPICallResult>(result);

// calling a method directly with arbitrary arguments should work
expectType<Promise<ChatPostMessageResponse>>(web.chat.postMessage({
  channel: 'CHANNEL',
  text: 'TEXT',
  key: 'VALUE',
}));
expectType<Promise<ChatPostMessageResponse>>(web.chat.postMessage({
  channel: 'CHANNEL',
  blocks: [
    {
      type: 'section',
      text: {
        type: 'mrkdwn',
        text:
          'text',
      },
    },
  ],
  key: 'VALUE',
}));

// calling a method directly with under-specified arguments should not work
expectError(web.chat.postMessage({
  text: 'TEXT',
}));

// assigning an object with a specific type that includes arbitrary arguments should not work
// TODO: can typescript even reliably do that? ^
// expectError(web.chat.postMessage({
//   text: 'TEXT',
//   channel: 'CHANNEL',
//   key: 'VALUE',
// }));

expectType<Promise<ChatPostMessageResponse>>(web.chat.postMessage({
  channel: 'C111',
  blocks: [],
  // no text should be accepted
}));
expectType<Promise<ChatUpdateResponse>>(web.chat.update({
  channel: 'C111',
  ts: '111.222',
  blocks: [],
  // no text should be accepted
}));

expectType<Promise<ChatScheduleMessageResponse>>(web.chat.scheduleMessage({
  channel: 'C111',
  post_at: '11111',
  blocks: [],
  // no text should be accepted
}));
expectType<Promise<ChatScheduleMessageResponse>>(web.chat.scheduleMessage({
  channel: 'C111',
  post_at: '11111',
  text: 'Hi there!',
  blocks: [],
}));
expectType<Promise<ChatPostEphemeralResponse>>(web.chat.postEphemeral({
  channel: 'C111',
  user: 'U111',
  blocks: [],
  // no text should be accepted
}));
expectType<Promise<ChatPostEphemeralResponse>>(web.chat.postEphemeral({
  channel: 'C111',
  user: 'U111',
  text: 'Hi there!',
  blocks: [],
}));


text:
class MultipleTransitionsThatDifferOnlyByGuard
  include AASM

  attr_accessor :executed_second

  aasm do
    state :start, :initial => true
    state :gone

    event :go do
      transitions :from => :start, :to => :gone, :guard => :returns_false, :after => :this_should_not_execute
      transitions :from => :start, :to => :gone, :guard => :returns_true, :after => :this_should_execute
    end
  end

  def returns_false
    false
  end

  def returns_true
    true
  end

  def this_should_not_execute
    raise RuntimeError, "This should not execute"
  end

  def this_should_execute
    self.executed_second = true
  end
end


text:
namespace ElmahLogAnalyzer.Core.Common
{
	public class NameValuePair
	{
		public NameValuePair(string name, string value)
		{
			Name = name;
			Value = value;
		}

		public string Name { get; private set; }

		public string Value { get; private set; }

		public override string ToString()
		{
			return Name;
		}
	}
}


text:
<?php

namespace Phalcon;

/**
 * Phalcon\Flash
 *
 * Shows HTML notifications related to different circumstances. Classes can be stylized using CSS
 *
 *
 * $flash->success("The record was successfully deleted");
 * $flash->error("Cannot open the file");
 *
 */
abstract class Flash implements \Phalcon\FlashInterface, \Phalcon\Di\InjectionAwareInterface
{

    protected $_cssClasses;

    protected $_implicitFlush = true;

    protected $_automaticHtml = true;

    protected $_escaperService = null;

    protected $_autoescape = true;

    protected $_dependencyInjector = null;

    protected $_messages;

    /**
     * Phalcon\Flash constructor
     *
     * @param mixed $cssClasses
     */
    public function __construct($cssClasses = null) {}

    /**
     * Returns the autoescape mode in generated html
     *
     * @return bool
     */
    public function getAutoescape() {}

    /**
     * Set the autoescape mode in generated html
     *
     * @param bool $autoescape
     * @return Flash
     */
    public function setAutoescape($autoescape) {}

    /**
     * Returns the Escaper Service
     *
     * @return EscaperInterface
     */
    public function getEscaperService() {}

    /**
     * Sets the Escaper Service
     *
     * @param EscaperInterface $escaperService
     * @return Flash
     */
    public function setEscaperService(EscaperInterface $escaperService) {}

    /**
     * Sets the dependency injector
     *
     * @param DiInterface $dependencyInjector
     * @return Flash
     */
    public function setDI(DiInterface $dependencyInjector) {}

    /**
     * Returns the internal dependency injector
     *
     * @return DiInterface
     */
    public function getDI() {}

    /**
     * Set whether the output must be implicitly flushed to the output or returned as string
     *
     * @param bool $implicitFlush
     * @return FlashInterface
     */
    public function setImplicitFlush($implicitFlush) {}

    /**
     * Set if the output must be implicitly formatted with HTML
     *
     * @param bool $automaticHtml
     * @return FlashInterface
     */
    public function setAutomaticHtml($automaticHtml) {}

    /**
     * Set an array with CSS classes to format the messages
     *
     * @param array $cssClasses
     * @return FlashInterface
     */
    public function setCssClasses(array $cssClasses) {}

    /**
     * Shows a HTML error message
     *
     *
     * $flash->error("This is an error");
     *
     *
     * @param mixed $message
     * @return string
     */
    public function error($message) {}

    /**
     * Shows a HTML notice/information message
     *
     *
     * $flash->notice("This is an information");
     *
     *
     * @param mixed $message
     * @return string
     */
    public function notice($message) {}

    /**
     * Shows a HTML success message
     *
     *
     * $flash->success("The process was finished successfully");
     *
     *
     * @param mixed $message
     * @return string
     */
    public function success($message) {}

    /**
     * Shows a HTML warning message
     *
     *
     * $flash->warning("Hey, this is important");
     *
     *
     * @param mixed $message
     * @return string
     */
    public function warning($message) {}

    /**
     * Outputs a message formatting it with HTML
     *
     *
     * $flash->outputMessage("error", $message);
     *
     *
     * @param string $type
     * @param string|array $message
     * @return string|void
     */
    public function outputMessage($type, $message) {}

    /**
     * Clears accumulated messages when implicit flush is disabled
     */
    public function clear() {}

}


text:
package org.railsschool.tiramisu.models.dao.interfaces;

import org.railsschool.tiramisu.models.dao.DayNotificationPreference;
import org.railsschool.tiramisu.models.dao.TwoHourNotificationPreference;

/**
 * @class IPreferenceDAO
 * @brief
 */
public interface IPreferenceDAO {
    TwoHourNotificationPreference getTwoHourNotificationPreference();

    void setTwoHourNotificationPreference(TwoHourNotificationPreference value);

    DayNotificationPreference getDayNotificationPreference();

    void setDayNotificationPreference(DayNotificationPreference value);

    boolean getLessonAlertPreference();

    void setLessonAlertPreference(boolean value);
}


text:
.class public final Lcom/aps/be;
.super Ljava/lang/Object;

# static fields
.field private static a:Ljava/lang/String;

# direct methods
.method static constructor <clinit>()V
    .locals 1

    const-string v0, ""

    sput-object v0, Lcom/aps/be;->a:Ljava/lang/String;

    return-void
.end method

.method protected static a(Ljava/lang/String;)V
    .locals 1

    const-string v0, "GPS_SATELLITE"

    invoke-virtual {p0, v0}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v0

    if-eqz v0, :cond_0

    :cond_0
    return-void
.end method

.method protected static a(Landroid/content/Context;)Z
    .locals 2

    if-eqz p0, :cond_0

    invoke-virtual {p0}, Landroid/content/Context;->getPackageName()Ljava/lang/String;

    move-result-object v0

    sput-object v0, Lcom/aps/be;->a:Ljava/lang/String;

    const/4 v0, 0x1

    :goto_0
    return v0

    :cond_0
    sget-object v0, Lcom/aps/be;->a:Ljava/lang/String;

    const-string v1, "Error: No SD Card!"

    invoke-static {v0, v1}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I

    const/4 v0, 0x0

    goto :goto_0
.end method


text:
page_title: "Plugins"
sidebar_current: "plugins"
---

# Plugins

Vagrant comes with many great features out of the box to get your environments up
and running. Sometimes, however, you want to change the way Vagrant does something
or add additional functionality to Vagrant. This can be done via Vagrant
_plugins_.

Plugins are powerful, first-class citizens that extend Vagrant using a
well-documented, stable API that can withstand major version upgrades.

In fact, most of the core of Vagrant is [implemented using plugins](https://github.com/mitchellh/vagrant/tree/master/plugins).
Since Vagrant [dogfoods](http://en.wikipedia.org/wiki/Eating_your_own_dog_food) its own
plugin API, you can be confident that the interface is stable and well supported.

Use the navigation on the left below the "Plugins" section to learn more
about how to use and build your own plugins.


text:
var amqp = require('amqp'),
    express = require('express'),
    app = express(),
    http = require('http').Server(app),
    io = require('socket.io')(http),
    path = require('path');

var connection = amqp.createConnection({ host: 'localhost' });

connection.on('ready', function () {

  console.log('connected to the RabbitMQ server on localhost');

  connection.queue('demo-queue', function(queue){
    queue.bind('#');

    queue.subscribe(function (message) {

      // need to decode from the raw buffer
      var encoded_payload = decodeURI(message.data);

      console.log('sending', encoded_payload);

      io.emit('demo', encoded_payload);
    });
  });
});

app.use(express.static(path.resolve(__dirname, '../', 'client')));
app.get('/', function(req, res){
  res.sendFile('index.html');
});

io.on('connection', function(socket){
  console.log('a user connected');
});

http.listen(3000, function(){
  console.log('listening on localhost:3000');
});


text:
A jQuery plugin for custom select elements.

* [Use](#use)
* [Options](#options)
* [Methods](#methods)
* [CSS](#css)

## Use

#### Main

```markup
dropdown.js
dropdown.css
```

#### Dependencies

```markup
core.js
touch.js
```

### Basic

To customize a select element, simply apply the plugin to the target element:

```javascript
$("select").dropdown();
```

```markup
<select>
	<option value="1">One</option>
	<option value="2">Two</option>
	<option value="3">Three</option>
</select>
```

### Events

React to changes to the element's value by listening for the standard `change` event:

```javascript
$("select").on("change", function() {
	var value = $(this).val();
});
```

Updated the element's value externally by triggering the standard `change` event:

```javascript
$("select").val(1).trigger("change");
```

Note: If the select is too close to the bottom edge of the `body` tag, the dropdown options will "flip" and display above the handle.

## Options

Set instance options by passing a valid object at initialization, or to the public `defaults` method. Custom options for a specific instance can also be set by attaching a `data-dropdown-options` attribute to the target elment. This attribute should contain the properly formatted JSON object representing the custom options.

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `cover` | `boolean` | `false` | Cover handle with option set |
| `customClass` | `string` | `''` | Class applied to instance |
| `label` | `string` | `''` | Label displayed before selection |
| `external` | `boolean` | `false` | Open options as links in new window |
| `links` | `boolean` | `false` | Open options as links in same window |
| `mobile` | `boolean` | `false` | Force desktop interaction on mobile |
| `trim` | `int` | `0` |   |

## Methods

Methods are publicly available to all active instances, unless otherwise stated.

### close

Closes target instance.

```javascript
$(".target").dropdown("close");
```

### defaults

Extends plugin default settings; effects instances created hereafter.

```javascript
$.dropdown("defaults", { ... });
```

#### Parameters

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `options` | `object` | `{}` | New plugin defaults |

### destroy

Removes plugin instance.

```javascript
$(".target").dropdown("destroy");
```

### disable

Disables target instance or option.

```javascript
$(".target").dropdown("disable", "1");
```

#### Parameters

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `option` | `string` | `null` | Target option value |

### enable

Enables target instance or option.

```javascript
$(".target").dropdown("enable", "1");
```

#### Parameters

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `option` | `string` | `null` | Target option value |

### open

Opens target instance.

```javascript
$(".target").dropdown("open");
```

### update

Updates instance.

```javascript
$(".target").dropdown("update");
```

## CSS

| Class | Type | Description |
| --- | --- | --- |
| `.fs-dropdown-element` | `element` | Target element |
| `.fs-dropdown` | `element` | Base widget class |
| `.fs-dropdown.fs-dropdown-multiple` | `modifer` | Indicates multi-selected element |
| `.fs-dropdown.fs-dropdown-cover` | `modifer` | Indicates cover positioning |
| `.fs-dropdown.fs-dropdown-bottom` | `modifer` | Indicates bottom positioning |
| `.fs-dropdown.fs-dropdown-disabled` | `modifer` | Indicates disabled state |
| `.fs-dropdown.fs-dropdown-open` | `modifer` | Indicates open state |
| `.fs-dropdown.fs-dropdown-focus` | `modifer` | Indicates focus state |
| `.fs-dropdown-selected` | `element` | Handle item |
| `.fs-dropdown-options` | `element` | Options container |
| `.fs-dropdown-group` | `element` | Option group label |
| `.fs-dropdown-item` | `element` | Option item |
| `.fs-dropdown-item.fs-dropdown-item_placeholder` | `modifier` | Indicates placeholder item |
| `.fs-dropdown-item.fs-dropdown-item_selected` | `modifier` | Indicates selected item |
| `.fs-dropdown-item.fs-dropdown-item_disabled` | `modifier` | Indicates disabled item |


text:
all: test

test: build/CMakeFiles
	cmake --build build --target tests
	bin/tests

build/CMakeFiles:
	mkdir -p build
	cd build && cmake ..


text:
package org.elasticsearch.index.reindex;

import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.util.concurrent.AbstractRunnable;
import org.elasticsearch.tasks.TaskId;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.threadpool.TestThreadPool;
import org.elasticsearch.threadpool.ThreadPool;
import org.junit.Before;

import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import static org.elasticsearch.common.unit.TimeValue.timeValueSeconds;
import static org.hamcrest.Matchers.both;
import static org.hamcrest.Matchers.closeTo;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.lessThanOrEqualTo;

public class WorkerBulkByScrollTaskStateTests extends ESTestCase {
    private BulkByScrollTask task;
    private WorkerBulkByScrollTaskState workerState;

    @Before
    public void createTask() {
        task = new BulkByScrollTask(1, "test_type", "test_action", "test", TaskId.EMPTY_TASK_ID, Collections.emptyMap());
        task.setWorker(Float.POSITIVE_INFINITY, null);
        workerState = task.getWorkerState();
    }

    public void testBasicData() {
        assertEquals(1, task.getId());
        assertEquals("test_type", task.getType());
        assertEquals("test_action", task.getAction());
        assertEquals("test", task.getDescription());
    }

    public void testProgress() {
        long created = 0;
        long updated = 0;
        long deleted = 0;
        long versionConflicts = 0;
        long noops = 0;
        int batch = 0;
        BulkByScrollTask.Status status = task.getStatus();
        assertEquals(0, status.getTotal());
        assertEquals(created, status.getCreated());
        assertEquals(updated, status.getUpdated());
        assertEquals(deleted, status.getDeleted());
        assertEquals(versionConflicts, status.getVersionConflicts());
        assertEquals(batch, status.getBatches());
        assertEquals(noops, status.getNoops());

        long totalHits = randomIntBetween(10, 1000);
        workerState.setTotal(totalHits);
        for (long p = 0; p < totalHits; p++) {
            status = task.getStatus();
            assertEquals(totalHits, status.getTotal());
            assertEquals(created, status.getCreated());
            assertEquals(updated, status.getUpdated());
            assertEquals(deleted, status.getDeleted());
            assertEquals(versionConflicts, status.getVersionConflicts());
            assertEquals(batch, status.getBatches());
            assertEquals(noops, status.getNoops());

            if (randomBoolean()) {
                created++;
                workerState.countCreated();
            } else if (randomBoolean()) {
                updated++;
                workerState.countUpdated();
            } else {
                deleted++;
                workerState.countDeleted();
            }

            if (rarely()) {
                versionConflicts++;
                workerState.countVersionConflict();
            }

            if (rarely()) {
                batch++;
                workerState.countBatch();
            }

            if (rarely()) {
                noops++;
                workerState.countNoop();
            }
        }
        status = task.getStatus();
        assertEquals(totalHits, status.getTotal());
        assertEquals(created, status.getCreated());
        assertEquals(updated, status.getUpdated());
        assertEquals(deleted, status.getDeleted());
        assertEquals(versionConflicts, status.getVersionConflicts());
        assertEquals(batch, status.getBatches());
        assertEquals(noops, status.getNoops());
    }

    /**
     * Furiously rethrottles a delayed request to make sure that we never run it twice.
     */
    public void testDelayAndRethrottle() throws IOException, InterruptedException {
        List<Throwable> errors = new CopyOnWriteArrayList<>();
        AtomicBoolean done = new AtomicBoolean();
        int threads = between(1, 10);
        CyclicBarrier waitForShutdown = new CyclicBarrier(threads);

        /*
         * We never end up waiting this long because the test rethrottles over and over again, ratcheting down the delay a random amount
         * each time.
         */
        float originalRequestsPerSecond = (float) randomDoubleBetween(1, 10000, true);
        workerState.rethrottle(originalRequestsPerSecond);
        TimeValue maxDelay = timeValueSeconds(between(1, 5));
        assertThat(maxDelay.nanos(), greaterThanOrEqualTo(0L));
        int batchSizeForMaxDelay = (int) (maxDelay.seconds() * originalRequestsPerSecond);
        ThreadPool threadPool = new TestThreadPool(getTestName()) {
            @Override
            public ScheduledCancellable schedule(Runnable command, TimeValue delay, String name) {
                assertThat(delay.nanos(), both(greaterThanOrEqualTo(0L)).and(lessThanOrEqualTo(maxDelay.nanos())));
                return super.schedule(command, delay, name);
            }
        };
        try {
            workerState.delayPrepareBulkRequest(threadPool, System.nanoTime(), batchSizeForMaxDelay,
                new AbstractRunnable() {
                    @Override
                    protected void doRun() throws Exception {
                        boolean oldValue = done.getAndSet(true);
                        if (oldValue) {
                            throw new RuntimeException("Ran twice oh no!");
                        }
                    }

                    @Override
                    public void onFailure(Exception e) {
                        errors.add(e);
                    }
                }
            );

            // Rethrottle on a random number of threads, one of which is this thread.
            Runnable test = () -> {
                try {
                    int rethrottles = 0;
                    while (false == done.get()) {
                        float requestsPerSecond = (float) randomDoubleBetween(0, originalRequestsPerSecond * 2, true);
                        workerState.rethrottle(requestsPerSecond);
                        rethrottles += 1;
                    }
                    logger.info("Rethrottled [{}] times", rethrottles);
                    waitForShutdown.await();
                } catch (Exception e) {
                    errors.add(e);
                }
            };
            for (int i = 1; i < threads; i++) {
                threadPool.generic().execute(test);
            }
            test.run();
        } finally {
            // Other threads should finish up quickly as they are checking the same AtomicBoolean.
            threadPool.shutdown();
            threadPool.awaitTermination(10, TimeUnit.SECONDS);
        }
        assertThat(errors, empty());
    }

    public void testDelayNeverNegative() throws IOException {
        // Thread pool that returns a ScheduledFuture that claims to have a negative delay
        ThreadPool threadPool = new TestThreadPool("test") {
            public ScheduledCancellable schedule(Runnable command, TimeValue delay, String name) {
                return new ScheduledCancellable() {
                    @Override
                    public long getDelay(TimeUnit unit) {
                        return -1;
                    }

                    @Override
                    public int compareTo(Delayed o) {
                        throw new UnsupportedOperationException();
                    }

                    @Override
                    public boolean cancel() {
                        throw new UnsupportedOperationException();
                    }

                    @Override
                    public boolean isCancelled() {
                        throw new UnsupportedOperationException();
                    }
                };
            }
        };
        try {
            // Have the task use the thread pool to delay a task that does nothing
            workerState.delayPrepareBulkRequest(threadPool, 0, 1, new AbstractRunnable() {
                @Override
                protected void doRun() throws Exception {
                }
                @Override
                public void onFailure(Exception e) {
                    throw new UnsupportedOperationException();
                }
            });
            // Even though the future returns a negative delay we just return 0 because the time is up.
            assertEquals(timeValueSeconds(0), task.getStatus().getThrottledUntil());
        } finally {
            threadPool.shutdown();
        }
    }

    public void testPerfectlyThrottledBatchTime() {
        workerState.rethrottle(Float.POSITIVE_INFINITY);
        assertThat((double) workerState.perfectlyThrottledBatchTime(randomInt()), closeTo(0f, 0f));

        int total = between(0, 1000000);
        workerState.rethrottle(1);
        assertThat((double) workerState.perfectlyThrottledBatchTime(total),
                closeTo(TimeUnit.SECONDS.toNanos(total), TimeUnit.SECONDS.toNanos(1)));
    }
}


text:
package adapp.controle.mvc;

import javax.servlet.http.*;
import java.util.*;

/**
 *
 * @author Gilberto Hiragi
 */
public class Acao {

    protected Executar controller;
    protected HttpServletRequest request;
    protected HttpServletResponse response;
    protected HttpSession session;
    protected HashMap dados;

    /**
     * Creates a new instance of Acao
     */
    public Acao() {
        this.dados = new HashMap();
    }

    public void setAmbiente(Executar controller, HttpServletRequest request,
            HttpServletResponse response, HttpSession session) {
        this.controller = controller;
        this.request = request;
        this.response = response;
        this.session = session;
    }

}


text:
package mclama.com;

import java.awt.Toolkit;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Random;

import javax.net.ssl.HttpsURLConnection;
import javax.swing.table.DefaultTableModel;

import static to.us.harha.twitchai.util.Globals.*;
import static to.us.harha.twitchai.util.FileUtils.*;

public class SMMHandler {

	private static LevelCode current_level  = new LevelCode("none","none", null);
	private static LevelCode previous_level = new LevelCode("none","none", null);

	private static ArrayList<LevelCode> levels = new ArrayList<LevelCode>();

	public static int getLevelCount(){
		return levels.size();
	}

	public static String getUserNextLevelPlace(String sender){
		for(int i=0; i<levels.size(); i++)
		{
			LevelCode cur_lvl = levels.get(i);
			if(cur_lvl.getAuthor().equals(sender))
			{
				return i+1+"";
			}
		}
		return "no code found!!";
	}

	public static int getUserLevelCount(String sender){
		int count=0;
		for(int i=0; i<levels.size(); i++)
		{
			LevelCode cur_lvl = levels.get(i);
			if(cur_lvl.getAuthor().equals(sender))
			{
				count++;
			}
		}
		return count;
	}

	public static void addLevel(String sender, String code, String response){
		levels.add(new LevelCode(sender, code, response));

		if(current_level.getLevel().equals("none")){
			current_level = levels.get(0);
			if(g_smm_play_beep_sound_on_first_level){
				try { Toolkit.getDefaultToolkit().beep();
				} catch (Exception e) {e.printStackTrace();}
			}
			if(g_gui.getChckbxRemoveLevelOn())
			{
				levels.remove(0);
			} else
				cycleLevels();
		}
		else
		{
			DefaultTableModel model = (DefaultTableModel) g_gui.getGui_queue_list().getTable().getModel();
			model.addRow(new Object[]{code, sender});
		}

		g_gui.updateNewLevel(levels.size(),current_level, g_BOT.isUserInChat(current_level.getAuthor()));
	}

	public static boolean getNext(){
		if(levels.size()>0)
		{
			if(g_gui.getChckbxExportToComplete())
			{
				sendPost(g_forms_completed_url, true, current_level.getLevel(), current_level.getAuthor());
			}

			previous_level = current_level;
			current_level = levels.get(0);

			if(g_gui.getChckbxRemoveLevelOn())
			{
				levels.remove(0);
			} else
				cycleLevels();

			g_gui.updateNewLevel(levels.size(),current_level, g_BOT.isUserInChat(current_level.getAuthor()));
			updateCurrentFile();
			g_gui.getLblLevelcount().setText("Levels: " + levels.size());
			return true;
		}
		g_gui.getLblLevelcount().setText("Levels: " + levels.size());
		return false;
	}

	public static void sendPost(String url, boolean useCompleted, String level, String submit){
		try {
			URL obj = new URL(url);
			HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

			//add reuqest header
			con.setRequestMethod("POST");
			con.setRequestProperty("User-Agent", "Mozilla/7.0");
			con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

			String urlParameters = "";
			if(useCompleted)
			{
				if(g_gui_timing) g_gui.endTimer();
				urlParameters += (g_forms_completed_submit_entry + "=" + submit + "&");
				urlParameters += (g_forms_completed_level_entry + "=" + level + "&");
				urlParameters += (g_forms_completed_time_entry + "=" + (g_gui_ended_time.replace("null", "00:00:00")) + "&");
				urlParameters += (g_forms_completed_deaths_entry + "=" + g_gui.getTxtDeaths().getText());
			}
			else
			{
				urlParameters += (g_forms_submit_entry + "=" + submit + "&");
				urlParameters += (g_forms_level_entry + "=" + level);
			}

			// Send post request
			con.setDoOutput(true);
			DataOutputStream wr = new DataOutputStream(con.getOutputStream());
			wr.writeBytes(urlParameters);
			wr.flush();
			wr.close();

			int responseCode = con.getResponseCode();
//			System.out.println("\nSending 'POST' request to URL : " + url);
//			System.out.println("Post parameters : " + urlParameters);
//			System.out.println("Response Code : " + responseCode);

			BufferedReader in = new BufferedReader(
			        new InputStreamReader(con.getInputStream()));
			String inputLine;
			StringBuffer response = new StringBuffer();

			while ((inputLine = in.readLine()) != null) {
				response.append(inputLine);
			}
			in.close();

			//print result
			//System.out.println(response.toString());
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private static void cycleLevels() {
		ArrayList<LevelCode> levelClone = (ArrayList<LevelCode>) levels.clone();

		levels.clear();
		for(int i=1;i<levelClone.size();i++){
			levels.add(levelClone.get(i));
		}
		levels.add(levelClone.get(0));
	}

	private static void updateCurrentFile() {
		if(g_smm_record_levels_played)
		{
			writeTextFile("data/files/", "current_level.txt", current_level.getLevel());
			writeTextFile("data/files/", "current_level_author.txt", current_level.getAuthor());
		}

		if(g_smm_record_previous_levels_played)
		{
			writeTextFile("data/files/", "previous_level.txt", previous_level.getLevel());
			writeTextFile("data/files/", "previous_level_author.txt", previous_level.getAuthor());
		}
	}

	public static boolean getRandom(){
		if(levels.size()>0)
		{
			previous_level = current_level;
			Random gen = new Random();
			int i = gen.nextInt(levels.size());
			current_level = levels.get(i);

			if(g_smm_remove_after_nextrandom)
			{
				levels.remove(i);
			}

			g_gui.updateNewLevel(levels.size(),current_level, g_BOT.isUserInChat(current_level.getAuthor()));
			updateCurrentFile();
			g_gui.getLblLevelcount().setText("Levels: " + levels.size());
			return true;
		}
		g_gui.getLblLevelcount().setText("Levels: " + levels.size());
		return false;
	}

	public static boolean removeLevelFromQueue(String code, String sender){
		for(int i=0; i<levels.size(); i++)
		{
			LevelCode cur_lvl = levels.get(i);
			if(cur_lvl.getLevel().equals(code) && cur_lvl.getAuthor().equals(sender))
			{
				levels.remove(i);
				g_gui.updateViewLevels();
				return true;
			}
		}
		return false;
	}

	public static LevelCode getCurrent_level() {
		return current_level;
	}

	public static LevelCode getPrevious_level() {
		return previous_level;
	}

	public static ArrayList<LevelCode> getLevels() {
		return levels;
	}

	public static boolean isCodeDuplicate(String code) {
		if(g_smm_allow_duplicate_submissions) return false;
		for(int i=0; i<levels.size(); i++)
		{
			LevelCode cur_lvl = levels.get(i);
			if(cur_lvl.getLevel().equals(code))
			{
				return true;
			}
		}
		return false;
	}

	public static boolean removeAllMyLevelsFromQueue(String sender) {
		boolean foundLevel = false;
		for(int i=0; i<levels.size(); i++)
		{
			LevelCode cur_lvl = levels.get(i);
			if(cur_lvl.getAuthor().equals(sender))
			{
				levels.remove(i);
				foundLevel = true;
				g_gui.updateViewLevels();
			}
		}
		return foundLevel;
	}

	public static String getNextFewLevels() {
		String str = ml_queuelist_syntax;
		if(levels.size()>0)
		{
			str = str.replace("{next_level1}", levels.get(0).getLevel());
			str = str.replace("{next_level_user1}", levels.get(0).getAuthor());
		}
		else
		{
			str = str.replace("{next_level1}", "Empty!");
			str = str.replace("{next_level_user1}", "none");
		}
		if(levels.size()>1)
		{
			str = str.replace("{next_level2}", levels.get(1).getLevel());
			str = str.replace("{next_level_user2}", levels.get(1).getAuthor());
		}
		else
		{
			str = str.replace("{next_level2}", "Empty!");
			str = str.replace("{next_level_user2}", "none");
		}
		if(levels.size()>2)
		{
			str = str.replace("{next_level3}", levels.get(2).getLevel());
			str = str.replace("{next_level_user3}", levels.get(2).getAuthor());
		}
		else
		{
			str = str.replace("{next_level3}", "Empty!");
			str = str.replace("{next_level_user3}", "none");
		}
		return str;
	}

}


text:
package org.spongepowered.vanilla.mixin.block;

import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.world.IBlockAccess;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.common.interfaces.block.IMixinBlock;

@Mixin(Block.class)
public abstract class MixinBlock implements IMixinBlock {

    @Override
    public boolean isFlammable(IBlockAccess blockAccess, BlockPos pos, EnumFacing facing) {
        return Blocks.fire.getFlammability((Block) (Object) this) > 0;
    }
}


text:
import { newMutation } from 'meteor/vulcan:core';
import moment from 'moment';
import Posts from "meteor/vulcan:posts";
import Comments from "meteor/vulcan:comments";
import Users from 'meteor/vulcan:users';
import Events from "meteor/vulcan:events";

const feedFlag = {
  fieldName: 'isFeed',
  fieldSchema: {
    type: Boolean,
    optional: true,
    hidden: true
  }
}

Users.addField(feedFlag);
Posts.addField(feedFlag);

var toTitleCase = function (str) {
  return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
};

var createFeedUsers = function () {
  console.log("*** Creating Feed Accounts ***");
  Accounts.createUser({
    username: 'GameMaster',
    email: 'gamesmaster@nodepeep.com',
    profile: {
      isFeed: true
    },
  });
  Accounts.createUser({
    username: 'NewsMaster',
    email: 'newsmaster@nodepeep.com',
    profile: {
      isFeed: true
    },
  });
  Accounts.createUser({
    username: 'WorldNewsMaster',
    email: 'worldnewsmaster@nodepeep.com',
    profile: {
      isFeed: true
    },
  });
  Accounts.createUser({
    username: 'SportsMaster',
    email: 'sportsmaster@nodepeep.com',
    profile: {
      isFeed: true
    },
  });
  Accounts.createUser({
    username: 'ScienceMaster',
    email: 'science@nodepeep.com',
    profile: {
      isFeed: true
    },
  });
  Accounts.createUser({
    username: 'TechMaster',
    email: 'techmaster@nodepeep.com',
    profile: {
      isFeed: true
    },
  });
  Accounts.createUser({
    username: 'ArtsMaster',
    email: 'artsmaster@nodepeep.com',
    profile: {
      isFeed: true
    },
  });
  Accounts.createUser({
    username: 'PoliticsMaster',
    email: 'politicsmaster@nodepeep.com',
    profile: {
      isFeed: true
    },
  });
  Accounts.createUser({
    username: 'HealthMaster',
    email: 'healthmaster@nodepeep.com',
    profile: {
      isFeed: true
    },
  });
};

const deleteFeedContent = function () {
  Users.remove({'profile.isFeed': true});
  Posts.remove({isFeed: true});
};

Meteor.startup(function () {
  // insert dummy content only if createFeedContent hasn't happened and there aren't any posts or users in the db
  if (!Users.find().count()) {
    createFeedUsers();
  }

});


text:
package org.railwaystations.rsapi.adapter.out.photostorage;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.railwaystations.rsapi.core.model.InboxEntry;
import org.railwaystations.rsapi.core.model.Station;
import org.railwaystations.rsapi.core.ports.out.PhotoStorage;
import org.springframework.stereotype.Repository;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;

import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;

@Repository
@Slf4j
public class PhotoFileStorage implements PhotoStorage {

    private static final long MAX_SIZE = 20_000_000L;

    private final WorkDir workDir;

    public PhotoFileStorage(WorkDir workDir) {
        this.workDir = workDir;
    }

    @Override
    public boolean isProcessed(String filename) {
        return filename != null && Files.exists(workDir.getInboxProcessedDir().resolve(filename));
    }

    @Override
    public String importPhoto(InboxEntry inboxEntry, Station station) throws IOException {
        var uploadedFile = getUploadFile(inboxEntry.getFilename());
        var processedFile = workDir.getInboxProcessedDir().resolve(inboxEntry.getFilename());
        var destinationDir = workDir.getPhotosDir().resolve(station.getKey().getCountry());
        Files.createDirectories(destinationDir);
        var destinationFile = getDestinationFile(destinationDir, station.getKey().getId(), inboxEntry.getExtension());
        if (Files.exists(processedFile)) {
            Files.move(processedFile, destinationFile, REPLACE_EXISTING);
        } else {
            Files.copy(uploadedFile, destinationFile, REPLACE_EXISTING);
        }
        try {
            Files.move(uploadedFile, workDir.getInboxDoneDir().resolve(uploadedFile.getFileName()), REPLACE_EXISTING);
        } catch (Exception e) {
            log.warn("Couldn't move original file {} to done dir", uploadedFile, e);
        }
        return String.format("/%s/%s", destinationDir.getFileName(), destinationFile.getFileName());
    }

    private Path getDestinationFile(Path destinationDir, String stationId, String extension) {
        for (int sequence = 1; sequence < 100; sequence++) {
            var destinationFile = destinationDir.resolve(sanitizeFilename(stationId + "_" + sequence + "." + extension));
            if (Files.notExists(destinationFile)) {
                return destinationFile;
            }
        }
        throw new RuntimeException(String.format("Number of photos per station %s/%s exceeded", destinationDir.getFileName(), stationId));
    }

    @Override
    public void reject(InboxEntry inboxEntry) throws IOException {
        if (inboxEntry.getFilename() != null) {
            var file = getUploadFile(inboxEntry.getFilename());
            Files.move(file, workDir.getInboxRejectedDir().resolve(file.getFileName()), REPLACE_EXISTING);
            Files.deleteIfExists(workDir.getInboxToProcessDir().resolve(inboxEntry.getFilename()));
            Files.deleteIfExists(workDir.getInboxProcessedDir().resolve(inboxEntry.getFilename()));
        }
    }

    @Override
    public Long storeUpload(InputStream body, String filename) throws PhotoStorage.PhotoTooLargeException, IOException {
        var file = getUploadFile(filename);
        log.info("Writing photo to {}", file);

        // write the file to the inbox directory
        var cos = new CheckedOutputStream(Files.newOutputStream(file), new CRC32());
        var bytesRead = IOUtils.copyLarge(body, cos, 0L, MAX_SIZE);
        if (bytesRead == MAX_SIZE) {
            Files.deleteIfExists(file);
            throw new PhotoStorage.PhotoTooLargeException(MAX_SIZE);
        }
        cos.close();

        // additionally write the file to the input directory for Vsion.AI
        Files.copy(file, workDir.getInboxToProcessDir().resolve(file.getFileName()), REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);
        return cos.getChecksum().getValue();
    }

    @Override
    public Path getUploadFile(String filename) {
        return workDir.getInboxDir().resolve(filename);
    }

    @Override
    public Path getPhotoFile(String countryCode, String filename) {
        return workDir.getPhotosDir().resolve(sanitizeFilename(countryCode)).resolve(sanitizeFilename(filename));
    }

    @Override
    public Path getInboxFile(String filename) {
        return workDir.getInboxDir().resolve(sanitizeFilename(filename));
    }

    @Override
    public Path getInboxProcessedFile(String filename) {
        return workDir.getInboxProcessedDir().resolve(sanitizeFilename(filename));
    }

    @Override
    public Path getInboxToProcessFile(String filename) {
        return workDir.getInboxToProcessDir().resolve(sanitizeFilename(filename));
    }

    @Override
    public void cleanupOldCopies() {
        var maxAge = Instant.now().minus(workDir.getKeepFileCopiesInDays(), ChronoUnit.DAYS);
        cleanupOldCopiesFrom(workDir.getInboxDoneDir(), maxAge);
        cleanupOldCopiesFrom(workDir.getInboxRejectedDir(), maxAge);
    }

    static void cleanupOldCopiesFrom(Path dir, Instant maxAge) {
        try (var pathStream = Files.list(dir)) {
            pathStream
                    .filter(Files::isRegularFile)
                    .filter(f -> isOlderThan(f, maxAge))
                    .forEach(PhotoFileStorage::deleteSilently);
        } catch (Exception e) {
            log.error("Failed to cleanup old copies from {}", dir, e);
        }
    }

    static void deleteSilently(Path path) {
        try {
            Files.delete(path);
            log.info("Deleted {}", path);
        } catch (IOException e) {
            log.warn("Unable to delete {}", path);
        }
    }

    static boolean isOlderThan(Path path, Instant maxAge) {
        try {
            return Files.getLastModifiedTime(path).toInstant().isBefore(maxAge);
        } catch (IOException e) {
            log.warn("Unable to getLastModifiedTime of {}", path.getFileName());
        }
        return false;
    }

    static String sanitizeFilename(String fileName) {
        if (fileName == null) {
            return null;
        }

        return fileName.replace(" ", "_")
                .replace("/", "_")
                .replace(":", "_")
                .replace("\"", "_")
                .replace("|", "_")
                .replace("*", "_")
                .replace("?", "_")
                .replace("<", "_")
                .replace(">", "_")
                .replace('\\', '_');
    }

}


text:
package org.wso2.carbon.identity.oauth2.authz.validators;

import org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthRequestException;
import org.wso2.carbon.identity.oauth2.dto.OAuth2ClientValidationResponseDTO;

import javax.servlet.http.HttpServletRequest;

/**
 * Validator interface for OAuth 2 response types. This will validate the inputs from the client.
 */
public interface ResponseTypeRequestValidator {

    /**
     * Get the response type.
     *
     * @return  Response type.
     */
    String getResponseType();

    /**
     * Check Whether the provided inputs from the client satisfy the response type validation
     *
     * @param request      The HttpServletRequest front the client.
     * @throws InvalidOAuthRequestException InvalidOAuthRequestException.
     */
    void validateInputParameters(HttpServletRequest request) throws InvalidOAuthRequestException;

    /**
     * Check Whether the provided client information satisfy the response type validation
     *
     * @param request      The HttpServletRequest front the client.
     * @return OAuth2ClientValidationResponseDTO bean with validity information,
     * callback, App Name, Error Code and Error Message when appropriate.
     */
    OAuth2ClientValidationResponseDTO validateClientInfo(HttpServletRequest request);
}


text:
NSUserDefaults-AESEncryptor is a NSUserDefaults category. Its purpose to encrypt/decrypt keys and values with AES encryptor.

[![Build Status](https://api.travis-ci.org/NZN/NSUserDefaults-AESEncryptor.png)](https://api.travis-ci.org/NZN/NSUserDefaults-AESEncryptor.png)
[![Cocoapods](https://cocoapod-badges.herokuapp.com/v/NSUserDefaults-AESEncryptor/badge.png)](http://beta.cocoapods.org/?q=name%3Ansuserdefaults%20name%3Aaesencryptor%2A)
[![Cocoapods](https://cocoapod-badges.herokuapp.com/p/NSUserDefaults-AESEncryptor/badge.png)](http://beta.cocoapods.org/?q=name%3Ansuserdefaults%20name%3Aaesencryptor%2A)

## Requirements

NSUserDefaults-AESEncryptor works on iOS 5.0+ version and is compatible with ARC projects. It depends on the following Apple frameworks, which should already be included with most Xcode templates:

* Foundation.framework

You will need LLVM 3.0 or later in order to build NSUserDefaults-AESEncryptor.

NSUserDefaults-AESEncryptor uses [CocoaSecurity](https://github.com/kelp404/CocoaSecurity) to encrypt/decrypt.

## Adding NSUserDefaults-AESEncryptor to your project

### Cocoapods

[CocoaPods](http://cocoapods.org) is the recommended way to add `NSUserDefaults-AESEncryptor` to your project.

* Add a pod entry for NSUserDefaults-AESEncryptor to your Podfile `pod 'NSUserDefaults-AESEncryptor'`
* Install the pod(s) by running `pod install`.

### Source files

Alternatively you can directly add source files to your project.

1. Download the [latest code version](https://github.com/NZN/NSUserDefaults-AESEncryptor/archive/master.zip) or add the repository as a git submodule to your git-tracked project.
2. Open your project in Xcode, then drag and drop all files at NSUserDefaults-AESEncryptor folder onto your project (use the "Product Navigator view"). Make sure to select Copy items when asked if you extracted the code archive outside of your project.
2. Install [CocoaSecurity](https://github.com/kelp404/CocoaSecurity).

## Usage

* Import `NSUserDefaults+AESEncryptor.h` and add this to `Prefix.pch`

```objective-c
// Set a key. (If no key is set, a default key will be used)
[[NSUserDefaults standardUserDefaults] setAESKey:@"World Cup 2014"];

// Encrypt
[[NSUserDefaults standardUserDefaults] encryptValue:@"Brazil" withKey:@"country"];

// Decrypt
NSString value = [[NSUserDefaults standardUserDefaults] decryptedValueForKey:@"country"];

// Remove object
[[NSUserDefaults standardUserDefaults] removeObjectForAESKey:@"country"];
```

## License

This code is distributed under the terms and conditions of the [MIT license](LICENSE).

## Change-log

A brief summary of each NSUserDefaults-AESEncryptor release can be found on the [wiki](https://github.com/NZN/NSUserDefaults-AESEncryptor/wiki/Change-log).


text:
package net.airvantage.sched.quartz.job;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.airvantage.sched.app.ServiceLocator;
import net.airvantage.sched.dao.JobWakeupDao;
import net.airvantage.sched.model.JobWakeup;
import net.airvantage.sched.services.tech.JobExecutionHelper;
import net.airvantage.sched.services.tech.RetryPolicyHelper;
import net.airvantage.sched.services.tech.hystrix.WakeupCommand;
import net.airvantage.sched.services.tech.hystrix.WakeupResult;

/**
 * This job processes all currently pending wakeups for the groupName which is passed in the jobs data map
 */
@DisallowConcurrentExecution
public class WakeupByGroupJob implements Job {

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

    private static final int QUERY_LIMIT = 1_500;

    public static final String JOBDATAKEY_GROUPNAME = "groupName";

    private JobExecutionHelper jobExecutionHelper;
    private JobWakeupDao jobWakeupDao;
    private int threadPoolSize;
    private RetryPolicyHelper retryPolicyHelper;

    // ------------------------------------------------- Constructors -------------------------------------------------

    /**
     * Constructor used by Quartz to load the job.
     */
    public WakeupByGroupJob() {
        this(ServiceLocator.getInstance().geJobExecutionHelper(), ServiceLocator.getInstance().getJobWakeupDao(),
                ServiceLocator.getInstance().getWakeupJobThreadPoolSize(),
                ServiceLocator.getInstance().getRetryPolicyHelper());
    }

    protected WakeupByGroupJob(JobExecutionHelper jobExecutionHelper, JobWakeupDao jobWakeupDao, int threadPoolSize,
            RetryPolicyHelper retryPolicyHelper) {

        this.jobExecutionHelper = jobExecutionHelper;
        this.jobWakeupDao = jobWakeupDao;
        this.threadPoolSize = threadPoolSize;
        this.retryPolicyHelper = retryPolicyHelper;
    }

    // ------------------------------------------------- Public Methods -----------------------------------------------

    /**
     * {@inheritDoc}
     */
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        LOG.debug("execute : context={}", context);

        JobKey key = context.getJobDetail().getKey();

        String groupName = context.getJobDetail().getJobDataMap().getString(JOBDATAKEY_GROUPNAME);
        LOG.debug("wakeup job starting for groupName={}", groupName);

        try {
            long now = System.currentTimeMillis();
            boolean processing = true;

            while (processing) {
                long start = System.currentTimeMillis();
                List<JobWakeup> wakeups = jobWakeupDao.find(now, QUERY_LIMIT, groupName);

                if (wakeups != null && !wakeups.isEmpty()) {
                    processWakeups(wakeups, groupName);

                    if (LOG.isDebugEnabled()) {
                        LOG.debug("{} wakeups have been processed in {} ms", wakeups.size(),
                                (System.currentTimeMillis() - start));
                    }
                } else {
                    processing = false;
                }
            }

        } catch (Exception ex) {
            LOG.error("Unable to execute WAKEUP by group job " + key, ex);
            throw new JobExecutionException("Unable to execute WAKEUP by group job " + key, ex);
        }
    }

    /**
     * Process the list of {@link JobWakeup}.
     */
    private void processWakeups(List<JobWakeup> wakeups, String groupName)
            throws InterruptedException, ExecutionException {

        long lagSum = 0;
        int count = wakeups.size();

        List<Future<WakeupResult>> futures = new ArrayList<>();
        for (JobWakeup wakeup : wakeups) {
            futures.add(new WakeupCommand(wakeup, jobExecutionHelper, retryPolicyHelper, threadPoolSize).queue());
        }

        for (Future<WakeupResult> future : futures) {
            WakeupResult result = future.get(); // Wait for completion
            LOG.debug("finished waiting for wakeup to complete: {}", result);
            if (result != null) {
                lagSum += result.getWakeupLag();
            }

        }

        // Trace wakeups lag > 30 sec
        if (lagSum / count / 1000 > 30) {
            LOG.info("Wakeups processing stats : nb={}, lag={}s, group={}", count, lagSum / count / 1000, groupName);
        }
    }

}


text:
//
//  SKRightSideViewController.m
//  Skim
//
//  Created by Christiaan Hofman on 3/28/10.

#import "SKRightSideViewController.h"
#import "SKMainWindowController.h"
#import "SKMainWindowController_Actions.h"
#import "SKMainWindowController_UI.h"
#import "NSMenu_SKExtensions.h"
#import "NSSegmentedControl_SKExtensions.h"
#import "SKColorCell.h"
#import "SKTypeSelectHelper.h"
#import "SKNoteOutlineView.h"

#define COLOR_COLUMNID @"color"

@implementation SKRightSideViewController

@synthesize noteArrayController, noteOutlineView, snapshotArrayController, snapshotTableView;

- (void)dealloc {
    [snapshotTableView setDelegate:nil];
    [snapshotTableView setDataSource:nil];
    [noteOutlineView setDelegate:nil];
    [noteOutlineView setDataSource:nil];
    SKDESTROY(noteArrayController);
    SKDESTROY(snapshotArrayController);
    SKDESTROY(noteOutlineView);
    SKDESTROY(snapshotTableView);
    [super dealloc];
}

- (NSString *)nibName {
    return @"RightSideView";
}

- (void)loadView {
    [super loadView];

    [button setToolTip:NSLocalizedString(@"View Notes", @"Tool tip message") forSegment:SKNoteSidePaneState];
    [button setToolTip:NSLocalizedString(@"View Snapshots", @"Tool tip message") forSegment:SKSnapshotSidePaneState];

    NSMenu *menu = [[[NSMenu allocWithZone:[NSMenu menuZone]] init] autorelease];
    [menu addItemWithTitle:NSLocalizedString(@"Ignore Case", @"Menu item title") action:@selector(toggleCaseInsensitiveNoteSearch:) target:mainController];
    [[searchField cell] setSearchMenuTemplate:menu];
    [[searchField cell] setPlaceholderString:NSLocalizedString(@"Search", @"placeholder")];

    [[noteOutlineView tableColumnWithIdentifier:COLOR_COLUMNID] setDataCell:[[[SKColorCell alloc] init] autorelease]];
    [noteOutlineView setAutoresizesOutlineColumn: NO];

    [noteOutlineView setDelegate:mainController];
    [noteOutlineView setDataSource:mainController];
    [snapshotTableView setDelegate:mainController];
    [snapshotTableView setDataSource:mainController];
    [[noteOutlineView menu] setDelegate:mainController];
    [[snapshotTableView menu] setDelegate:mainController];

    [noteOutlineView setTypeSelectHelper:[SKTypeSelectHelper typeSelectHelperWithMatchOption:SKSubstringMatch]];
}

@end