text:
package org.ejml.alg.block;

import org.ejml.data.D1Submatrix64F;

import static org.ejml.alg.block.BlockInnerMultiplication.blockMultMinus;

/**
 *

 * Contains triangular solvers for {@link org.ejml.data.BlockMatrix64F} block aligned sub-matrices.
 *

 *
 *

 * For a more detailed description of a similar algorithm see:
 * Page 30 in "Fundamentals of Matrix Computations" 2nd Ed. by David S. Watkins
 * or any description of a block triangular solver in any other computational linear algebra book.
 *

 *
 * @author Peter Abeles
 */
public class BlockTriangularSolver {

    /**
     * Inverts an upper or lower triangular block submatrix.
     *
     * @param blockLength
     * @param upper Is it upper or lower triangular.
     * @param T Triangular matrix that is to be inverted.  Must be block aligned.  Not Modified.
     * @param T_inv Where the inverse is stored.  This can be the same as T.  Modified.
     * @param temp Work space variable that is size blockLength*blockLength.
     */
    public static void invert( final int blockLength ,
                               final boolean upper ,
                               final D1Submatrix64F T ,
                               final D1Submatrix64F T_inv ,
                               final double temp[] )
    {
        if( upper )
            throw new IllegalArgumentException("Upper triangular matrices not supported yet");

        if( temp.length < blockLength*blockLength )
            throw new IllegalArgumentException("Temp must be at least blockLength*blockLength long.");

        if( T.row0 != T_inv.row0 || T.row1 != T_inv.row1 || T.col0 != T_inv.col0 || T.col1 != T_inv.col1)
            throw new IllegalArgumentException("T and T_inv must be at the same elements in the matrix");

        final int M = T.row1-T.row0;

        final double dataT[] = T.original.data;
        final double dataX[] = T_inv.original.data;

        final int offsetT = T.row0*T.original.numCols+M*T.col0;

        for( int i = 0; i < M; i += blockLength ) {
            int heightT = Math.min(T.row1-(i+T.row0),blockLength);

            int indexII = offsetT + T.original.numCols*(i+T.row0) + heightT*(i+T.col0);

            for( int j = 0; j < i; j += blockLength ) {
                int widthX = Math.min(T.col1-(j+T.col0),blockLength);

                for( int w = 0; w < temp.length; w++ ) {
                    temp[w] = 0;
                }

                for( int k = j; k < i; k += blockLength ) {
                    int widthT = Math.min(T.col1-(k+T.col0),blockLength);

                    int indexL = offsetT + T.original.numCols*(i+T.row0) + heightT*(k+T.col0);
                    int indexX = offsetT + T.original.numCols*(k+T.row0) + widthT*(j+T.col0);

                    blockMultMinus(dataT,dataX,temp,indexL,indexX,0,heightT,widthT,widthX);
                }

                int indexX = offsetT + T.original.numCols*(i+T.row0) + heightT*(j+T.col0);

                BlockInnerTriangularSolver.solveL(dataT,temp,heightT,widthX,heightT,indexII,0);
                System.arraycopy(temp,0,dataX,indexX,widthX*heightT);
            }
            BlockInnerTriangularSolver.invertLower(dataT,dataX,heightT,indexII,indexII);
        }
    }

    /**
     * Inverts an upper or lower triangular block submatrix.
     *
     * @param blockLength
     * @param upper Is it upper or lower triangular.
     * @param T Triangular matrix that is to be inverted.  Overwritten with solution.  Modified.
     * @param temp Work space variable that is size blockLength*blockLength.
     */
    public static void invert( final int blockLength ,
                               final boolean upper ,
                               final D1Submatrix64F T ,
                               final double temp[] )
    {
        if( upper )
            throw new IllegalArgumentException("Upper triangular matrices not supported yet");

        if( temp.length < blockLength*blockLength )
            throw new IllegalArgumentException("Temp must be at least blockLength*blockLength long.");

        final int M = T.row1-T.row0;

        final double dataT[] = T.original.data;
        final int offsetT = T.row0*T.original.numCols+M*T.col0;

        for( int i = 0; i < M; i += blockLength ) {
            int heightT = Math.min(T.row1-(i+T.row0),blockLength);

            int indexII = offsetT + T.original.numCols*(i+T.row0) + heightT*(i+T.col0);

            for( int j = 0; j < i; j += blockLength ) {
                int widthX = Math.min(T.col1-(j+T.col0),blockLength);

                for( int w = 0; w < temp.length; w++ ) {
                    temp[w] = 0;
                }

                for( int k = j; k < i; k += blockLength ) {
                    int widthT = Math.min(T.col1-(k+T.col0),blockLength);

                    int indexL = offsetT + T.original.numCols*(i+T.row0) + heightT*(k+T.col0);
                    int indexX = offsetT + T.original.numCols*(k+T.row0) + widthT*(j+T.col0);

                    blockMultMinus(dataT,dataT,temp,indexL,indexX,0,heightT,widthT,widthX);
                }

                int indexX = offsetT + T.original.numCols*(i+T.row0) + heightT*(j+T.col0);

                BlockInnerTriangularSolver.solveL(dataT,temp,heightT,widthX,heightT,indexII,0);
                System.arraycopy(temp,0,dataT,indexX,widthX*heightT);
            }
            BlockInnerTriangularSolver.invertLower(dataT,heightT,indexII);
        }
    }

    /**
     *

     * Performs an in-place solve operation on the provided block aligned sub-matrices.

     *

     * B = T-1 B

     *

     * where T is a triangular matrix. T or B can be transposed.  T is a square matrix of arbitrary
     * size and B has the same number of rows as T and an arbitrary number of columns.
     *

     *
     * @param blockLength Size of the inner blocks.
     * @param upper If T is upper or lower triangular.
     * @param T An upper or lower triangular matrix. Not modified.
     * @param B A matrix whose height is the same as T's width. Solution is written here. Modified.
     */
    public static void solve( final int blockLength ,
                              final boolean upper ,
                              final D1Submatrix64F T ,
                              final D1Submatrix64F B ,
                              final boolean transT ) {

        if( upper ) {
            solveR(blockLength,T,B,transT);
        } else {
            solveL(blockLength,T,B,transT);
        }
    }

    /**
     *

     * Performs an in-place solve operation where T is contained in a single block.

     *

     * B = T-1 B

     *

     * where T is a triangular matrix contained in an inner block. T or B can be transposed.  T must be a single complete inner block
     * and B is either a column block vector or row block vector.
     *

     *
     * @param blockLength Size of the inner blocks in the block matrix.
     * @param upper If T is upper or lower triangular.
     * @param T An upper or lower triangular matrix that is contained in an inner block. Not modified.
     * @param B A block aligned row or column submatrix. Modified.
     * @param transT If T is transposed or not.
     * @param transB If B is transposed or not.
     */
    public static void solveBlock( final int blockLength ,
                                   final boolean upper , final D1Submatrix64F T ,
                                   final D1Submatrix64F B ,
                                   final boolean transT ,final boolean transB )
    {
        int Trows = T.row1-T.row0;
        if( Trows > blockLength )
            throw new IllegalArgumentException("T can be at most the size of a block");
        // number of rows in a block.  The submatrix can be smaller than a block
        final int blockT_rows = Math.min(blockLength,T.original.numRows-T.row0);
        final int blockT_cols = Math.min(blockLength,T.original.numCols-T.col0);

        int offsetT = T.row0*T.original.numCols+blockT_rows*T.col0;

        final double dataT[] = T.original.data;
        final double dataB[] = B.original.data;

        if( transB ) {
            if( upper ) {
                if ( transT ) {
                    throw new IllegalArgumentException("Operation not yet supported");
                } else {
                    throw new IllegalArgumentException("Operation not yet supported");
                }
            } else {
                if ( transT ) {
                    throw new IllegalArgumentException("Operation not yet supported");
                } else {
                    for( int i = B.row0; i < B.row1; i += blockLength ) {
                        int N = Math.min(B.row1 , i + blockLength ) - i;

                        int offsetB = i*B.original.numCols + N*B.col0;

                        BlockInnerTriangularSolver.solveLTransB(dataT,dataB,blockT_rows,N,blockT_rows,offsetT,offsetB);
                    }
                }
            }
        } else {
            if( Trows != B.row1-B.row0 )
                throw new IllegalArgumentException("T and B must have the same number of rows.");

            if( upper ) {
                if ( transT ) {
                    for( int i = B.col0; i < B.col1; i += blockLength ) {
                        int offsetB = B.row0*B.original.numCols + Trows*i;

                        int N = Math.min(B.col1 , i + blockLength ) - i;
                        BlockInnerTriangularSolver.solveTransU(dataT,dataB,Trows,N,Trows,offsetT,offsetB);
                    }
                } else {
                    for( int i = B.col0; i < B.col1; i += blockLength ) {
                        int offsetB = B.row0*B.original.numCols + Trows*i;

                        int N = Math.min(B.col1 , i + blockLength ) - i;
                        BlockInnerTriangularSolver.solveU(dataT,dataB,Trows,N,Trows,offsetT,offsetB);
                    }
                }
            } else {
                if ( transT ) {
                    for( int i = B.col0; i < B.col1; i += blockLength ) {
                        int offsetB = B.row0*B.original.numCols + Trows*i;

                        int N = Math.min(B.col1 , i + blockLength ) - i;
                        BlockInnerTriangularSolver.solveTransL(dataT,dataB,Trows,N,blockT_cols,offsetT,offsetB);
                    }
                } else {
                    for( int i = B.col0; i < B.col1; i += blockLength ) {
                        int offsetB = B.row0*B.original.numCols + Trows*i;

                        int N = Math.min(B.col1 , i + blockLength ) - i;
                        BlockInnerTriangularSolver.solveL(dataT,dataB,Trows,N,blockT_cols,offsetT,offsetB);
                    }
                }
            }
        }
    }

    /**
     *

     * Solves lower triangular systems:

     *

     * B = L-1 B

     *

     *

     *
     *
 Reverse or forward substitution is used depending upon L being transposed or not.

     *
     * @param blockLength
     * @param L Lower triangular with dimensions m by m.  Not modified.
     * @param B A matrix with dimensions m by n.  Solution is written into here. Modified.
     * @param transL Is the triangular matrix transposed?
     */
    public static void solveL( final int blockLength ,
                               final D1Submatrix64F L,
                               final D1Submatrix64F B ,
                               boolean transL ) {

        D1Submatrix64F Y = new D1Submatrix64F(B.original);

        D1Submatrix64F Linner = new D1Submatrix64F(L.original);
        D1Submatrix64F Binner = new D1Submatrix64F(B.original);

        int lengthL = B.row1 - B.row0;

        int startI,stepI;

        if( transL ) {
            startI = lengthL - lengthL % blockLength;
            if( startI == lengthL && lengthL >= blockLength )
                startI -= blockLength;

            stepI = -blockLength;
        } else {
            startI = 0;
            stepI = blockLength;
        }

        for( int i = startI; ; i += stepI ) {
            if( transL ) {
                if( i < 0 ) break;
            } else {
                if( i >= lengthL ) break;
            }

            // width and height of the inner T(i,i) block
            int widthT = Math.min(blockLength, lengthL-i);

            Linner.col0 = L.col0 + i;    Linner.col1 = Linner.col0 + widthT;
            Linner.row0 = L.row0 + i;    Linner.row1 = Linner.row0 + widthT;

            Binner.col0 = B.col0;       Binner.col1 = B.col1;
            Binner.row0 = B.row0 + i;   Binner.row1 = Binner.row0 + widthT;

            // solve the top row block
            // B(i,:) = T(i,i)^-1 Y(i,:)
            solveBlock(blockLength,false, Linner,Binner,transL,false);

            boolean updateY;
            if( transL ) {
                updateY = Linner.row0 > 0;
            } else {
                updateY = Linner.row1 < L.row1;
            }
            if( updateY ) {
                // Y[i,:] = Y[i,:] - sum j=1:i-1 { T[i,j] B[j,i] }
                // where i is the next block down
                // The summation is a block inner product
                if( transL ) {
                    Linner.col1 = Linner.col0;
                    Linner.col0 = Linner.col1 - blockLength;
                    Linner.row1 = L.row1;
                    //Tinner.col1 = Tinner.col1;

//                    Binner.row0 = Binner.row0;
                    Binner.row1 = B.row1;

                    Y.row0 = Binner.row0-blockLength;
                    Y.row1 = Binner.row0;
                } else {
                    Linner.row0 = Linner.row1;
                    Linner.row1 = Math.min(Linner.row0+blockLength, L.row1);
                    Linner.col0 = L.col0;
                    //Tinner.col1 = Tinner.col1;

                    Binner.row0 = B.row0;
                    //Binner.row1 = Binner.row1;

                    Y.row0 = Binner.row1;
                    Y.row1 = Math.min(Y.row0+blockLength,B.row1);
                }

                // step through each block column
                for( int k = B.col0; k < B.col1; k += blockLength ) {

                    Binner.col0 = k;
                    Binner.col1 = Math.min(k+blockLength,B.col1);

                    Y.col0 = Binner.col0;
                    Y.col1 = Binner.col1;

                    if( transL ) {
                        // Y = Y - T^T * B
                        BlockMultiplication.multMinusTransA(blockLength, Linner,Binner,Y);
                    } else {

                        // Y = Y - T * B
                        BlockMultiplication.multMinus(blockLength, Linner,Binner,Y);
                    }
                }
            }
        }
    }

    /**
     *

     * Solves upper triangular systems:

     *

     * B = R-1 B

     *

     *

     *
     *
Only the first B.numRows rows in R will be processed.  Lower triangular elements are ignored.

     *
     *
 Reverse or forward substitution is used depending upon L being transposed or not.

     *
     * @param blockLength
     * @param R Upper triangular with dimensions m by m.  Not modified.
     * @param B A matrix with dimensions m by n.  Solution is written into here. Modified.
     * @param transR Is the triangular matrix transposed?
     */
    public static void solveR( final int blockLength ,
                               final D1Submatrix64F R,
                               final D1Submatrix64F B ,
                               boolean transR ) {

        int lengthR = B.row1 - B.row0;
        if( R.getCols() != lengthR ) {
            throw new IllegalArgumentException("Number of columns in R must be equal to the number of rows in B");
        } else if( R.getRows() != lengthR ) {
            throw new IllegalArgumentException("Number of rows in R must be equal to the number of rows in B");
        }

        D1Submatrix64F Y = new D1Submatrix64F(B.original);

        D1Submatrix64F Rinner = new D1Submatrix64F(R.original);
        D1Submatrix64F Binner = new D1Submatrix64F(B.original);

        int startI,stepI;

        if( transR ) {
            startI = 0;
            stepI = blockLength;
        } else {
            startI = lengthR - lengthR % blockLength;
            if( startI == lengthR && lengthR >= blockLength )
                startI -= blockLength;

            stepI = -blockLength;
        }

        for( int i = startI; ; i += stepI ) {
            if( transR ) {
                if( i >= lengthR ) break;
            } else {
                if( i < 0 ) break;
            }

            // width and height of the inner T(i,i) block
            int widthT = Math.min(blockLength, lengthR-i);

            Rinner.col0 = R.col0 + i;    Rinner.col1 = Rinner.col0 + widthT;
            Rinner.row0 = R.row0 + i;    Rinner.row1 = Rinner.row0 + widthT;

            Binner.col0 = B.col0;       Binner.col1 = B.col1;
            Binner.row0 = B.row0 + i;   Binner.row1 = Binner.row0 + widthT;

            // solve the top row block
            // B(i,:) = T(i,i)^-1 Y(i,:)
            solveBlock(blockLength,true, Rinner,Binner,transR,false);

            boolean updateY;
            if( transR ) {
                updateY = Rinner.row1 < R.row1;
            } else {
                updateY = Rinner.row0 > 0;
            }
            if( updateY ) {
                // Y[i,:] = Y[i,:] - sum j=1:i-1 { T[i,j] B[j,i] }
                // where i is the next block down
                // The summation is a block inner product
                if( transR ) {
                    Rinner.col0 = Rinner.col1;
                    Rinner.col1 = Math.min(Rinner.col0+blockLength, R.col1);
                    Rinner.row0 = R.row0;
                    //Rinner.row1 = Rinner.row1;

                    Binner.row0 = B.row0;
                    //Binner.row1 = Binner.row1;

                    Y.row0 = Binner.row1;
                    Y.row1 = Math.min(Y.row0+blockLength,B.row1);
                } else {
                    Rinner.row1 = Rinner.row0;
                    Rinner.row0 = Rinner.row1 - blockLength;
                    Rinner.col1 = R.col1;

//                    Binner.row0 = Binner.row0;
                    Binner.row1 = B.row1;

                    Y.row0 = Binner.row0-blockLength;
                    Y.row1 = Binner.row0;
                }

                // step through each block column
                for( int k = B.col0; k < B.col1; k += blockLength ) {

                    Binner.col0 = k;
                    Binner.col1 = Math.min(k+blockLength,B.col1);

                    Y.col0 = Binner.col0;
                    Y.col1 = Binner.col1;

                    if( transR ) {
                        // Y = Y - T^T * B
                        BlockMultiplication.multMinusTransA(blockLength, Rinner,Binner,Y);
                    } else {
                        // Y = Y - T * B
                        BlockMultiplication.multMinus(blockLength, Rinner,Binner,Y);
                    }
                }
            }
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using DbShell.Driver.Common.CommonDataLayer;
using DbShell.Driver.Common.Structure;
using DbShell.Driver.Common.Utility;

namespace DbShell.Xml
{
    internal class XmlDocumentReader : ArrayDataRecord, ICdlReader
    {
        private XmlDocument _doc;
        private TableInfo _rowFormat;
        private List<XmlReadInstructions> _instructions;
        private IEnumerator<Record> _enumerator;
        private bool _isCanceled;

        internal class Record
        {
            internal XmlNode Node;
            internal XmlReadInstructions Instruction;
            internal Dictionary<string, int> ColDict;
        }

        public XmlDocumentReader(XmlDocument doc, TableInfo rowFormat, List<XmlReadInstructions> instructions)
            : base(rowFormat)
        {
            _doc = doc;
            _rowFormat = rowFormat;
            _instructions = instructions;
            _enumerator = GetRecords().GetEnumerator();
        }

        public void Dispose()
        {
            if (Disposing != null) Disposing();
            Disposing = null;
        }

        public event Action Disposing;

        private IEnumerable<Record> GetRecords()
        {
            foreach(var instruction in _instructions)
            {
                var nodeList = _doc.SelectNodes(instruction.XPath);
                var colDict = new Dictionary<string, int>();
                foreach(var col in instruction.Columns)
                {
                    colDict[col.Name] = _rowFormat.Columns.IndexOfIf(x => x.Name == col.Name);
                }

                for(int i = 0; i < nodeList.Count; i++)
                {
                    yield return new Record
                    {
                        Instruction = instruction,
                        Node = nodeList[i],
                        ColDict = colDict,
                    };
                }
            }
        }

        public bool Read()
        {
            if (_isCanceled)
                return false;

            if (_enumerator.MoveNext())
            {
                var current = _enumerator.Current;

                for (int i = 0; i < _values.Length; i++) _values[i] = null;

                foreach(var col in current.Instruction.Columns)
                {
                    int index = current.ColDict[col.Name];

                    SeekValue(index);
                    var elem = current.Node.SelectSingleNode(col.XPath);
                    if (elem != null) SetString(elem.InnerText);
                }
                return true;
            }

            return false;
        }

        public bool NextResult()
        {
            return false;
        }

        public void Cancel()
        {
            _isCanceled = true;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text: just trying gitflow


text:
package org.wso2.am.integration.tests.publisher;

import org.json.JSONObject;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Factory;
import org.testng.annotations.Test;
import org.wso2.am.integration.test.utils.base.APIMIntegrationBaseTest;
import org.wso2.am.integration.test.utils.bean.APICreationRequestBean;
import org.wso2.am.integration.test.utils.clients.APIPublisherRestClient;
import org.wso2.carbon.automation.engine.context.TestUserMode;
import org.wso2.carbon.automation.test.utils.http.client.HttpResponse;

import javax.ws.rs.core.Response;
import java.net.URL;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;

/**
 * Create an API through the Publisher Rest API and validate the API
 * APIM2-18 / APIM2-538
 */
public class APIM18CreateAnAPIThroughThePublisherRestAPITestCase extends APIMIntegrationBaseTest {
    private final String apiNameTest = "APIM18PublisherTest";
    private final String apiVersion = "1.0.0";
    private APIPublisherRestClient apiPublisher;
    private String apiProviderName;
    private String apiProductionEndPointUrl;

    @Factory(dataProvider = "userModeDataProvider")
    public APIM18CreateAnAPIThroughThePublisherRestAPITestCase(TestUserMode userMode) {
        this.userMode = userMode;
    }

    @DataProvider
    public static Object[][] userModeDataProvider() {
        return new Object[][]{
                new Object[]{TestUserMode.SUPER_TENANT_ADMIN},
//                new Object[]{TestUserMode.TENANT_ADMIN},
        };
    }

    @BeforeClass(alwaysRun = true)
    public void setEnvironment() throws Exception {
        super.init(userMode);

        String apiProductionEndpointPostfixUrl = "jaxrs_basic/services/customers/" +
                "customerservice/customers/123";

        String publisherURLHttp = publisherUrls.getWebAppURLHttp();

        apiPublisher = new APIPublisherRestClient(publisherURLHttp);
        apiPublisher.login(publisherContext.getContextTenant().getContextUser().getUserName(),
                publisherContext.getContextTenant().getContextUser().getPassword());

        apiProductionEndPointUrl = gatewayUrlsWrk.getWebAppURLHttp() +
                apiProductionEndpointPostfixUrl;
        apiProviderName = publisherContext.getContextTenant().getContextUser().getUserName();

    }

    @Test(groups = {"wso2.am"}, description = "Create an API Through the Publisher Rest API")
    public void testCreateAnAPIThroughThePublisherRest() throws Exception {

        String apiContextTest = "apim18PublisherTestAPI";
        String apiDescription = "This is Test API Created by API Manager Integration Test";
        String apiTag = "tag18-1, tag18-2, tag18-3";

        APICreationRequestBean apiCreationRequestBean =
                new APICreationRequestBean(apiNameTest, apiContextTest, apiVersion, apiProviderName,
                        new URL(apiProductionEndPointUrl));
        apiCreationRequestBean.setTags(apiTag);
        apiCreationRequestBean.setDescription(apiDescription);
        apiCreationRequestBean.setTiersCollection("Gold,Bronze");
        apiCreationRequestBean.setDefaultVersion("default_version");
        apiCreationRequestBean.setDefaultVersionChecked("default_version");
        apiCreationRequestBean.setBizOwner("api18b");
        apiCreationRequestBean.setBizOwnerMail("api18b@ee.com");
        apiCreationRequestBean.setTechOwner("api18t");
        apiCreationRequestBean.setTechOwnerMail("api18t@ww.com");

        HttpResponse apiCreationResponse = apiPublisher.addAPI(apiCreationRequestBean);
        JSONObject apiResponse = new JSONObject(apiCreationResponse.getData());

        assertEquals(apiCreationResponse.getResponseCode(), Response.Status.OK.getStatusCode(),
                "Response Code miss matched when creating the API");
        assertFalse(apiResponse.getBoolean("error"), apiNameTest + "is not created as expected");

        //Check the availability of an API in Publisher
        HttpResponse response = apiPublisher.getApi(apiNameTest, apiProviderName, apiVersion);
        assertEquals(response.getResponseCode(), Response.Status.OK.getStatusCode(),
                "Response Code miss matched when creating the API");
        assertTrue(response.getData().contains(apiNameTest), "Invalid API Name");
        assertTrue(response.getData().contains(apiVersion), "Invalid API Version");
        assertTrue(response.getData().contains(apiContextTest), "Invalid API Context");

    }

    @Test(groups = {"wso2.am"}, description = "Remove an API Through the Publisher Rest API",
            dependsOnMethods = "testCreateAnAPIThroughThePublisherRest")
    public void testRemoveAnAPIThroughThePublisherRest() throws Exception {

        //Remove an API and validate the Response
        HttpResponse removeApiResponse = apiPublisher.deleteAPI
                (apiNameTest, apiVersion, apiProviderName);
        JSONObject jsonObjectRemoveApi = new JSONObject(removeApiResponse.getData());
        assertEquals(removeApiResponse.getResponseCode(), Response.Status.OK.getStatusCode(),
                "Response Code miss matched when removing an API");
        assertFalse(jsonObjectRemoveApi.getBoolean("error"),
                "Error when removing the " + apiNameTest);

        //Check the availability of an API  after removing
        HttpResponse response = apiPublisher.getApi(apiNameTest, apiProviderName, apiVersion);
        JSONObject jsonObjectGettingApi = new JSONObject(response.getData());
        assertEquals(response.getResponseCode(), Response.Status.OK.getStatusCode(),
                "Response Code miss matched when getting an API");
        assertTrue(jsonObjectGettingApi.getBoolean("error"),
                "Publisher Rest API allow to get deleted API ");
        assertEquals(jsonObjectGettingApi.getString("message"), " Cannot find the requested API- "
                + apiNameTest + "-" + apiVersion, "Invalid error " +
                "message populated when trying to get deleted API through the publisher");

    }

    @AfterClass(alwaysRun = true)
    public void destroyAPIs() throws Exception {
        apiPublisher.deleteAPI(apiNameTest, apiVersion, apiProviderName);
    }

}


text:
CC = g++

# define any compile-time flags
CFLAGS = -Wall -g

# define any directories containing header files other than /usr/include
#
INCLUDES =
#-I/home/newhall/include  -I../usr/include

# define library paths in addition to /usr/lib
#   if I wanted to include libraries not in /usr/lib I'd specify
#   their path using -Lpath, something like:
LFLAGS = -L./lib

# define any libraries to link into executable:
#   if I want to link in libraries (libx.so or libx.a) I use the -llibname
#   option, something like (this will link in libmylib.so and libm.so:
LIBS = -lctegaki

# define the C source files
SRCS = main.c

# define the C object files
#
# This uses Suffix Replacement within a macro:
#   $(name:string1=string2)
#         For each word in 'name' replace 'string1' with 'string2'
# Below we are replacing the suffix .c of all words in the macro SRCS
# with the .o suffix
#
OBJS = $(SRCS:.c=.o)

# define the executable file
MAIN = tegaki

#
# The following part of the makefile is generic; it can be used to
# build any executable just by changing the definitions above and by
# deleting dependencies appended to the file from 'make depend'
#

.PHONY: depend clean

all:	$(MAIN)
	@echo	compilation finished

$(MAIN): $(OBJS)
		$(CC) $(CFLAGS) $(INCLUDES) -o $(MAIN) $(OBJS) $(LFLAGS) $(LIBS)

# this is a suffix replacement rule for building .o's from .c's
# it uses automatic variables $<: the name of the prerequisite of
# the rule(a .c file) and $@: the name of the target of the rule (a .o file)
# (see the gnu make manual section about automatic variables)
.c.o:
	$(CC) $(CFLAGS) $(INCLUDES) -c $<  -o $@

clean:
	$(RM) *.o *~ $(MAIN)

depend: $(SRCS)
	makedepend $(INCLUDES) $^

# DO NOT DELETE THIS LINE -- make depend needs it


text:
package enumeratum

import java.util
import java.util.concurrent.TimeUnit

import org.openjdk.jmh.annotations._
import org.openjdk.jmh.infra.Blackhole
import testing._

/** Compares performance of Java's EnumSet, Scala's Set for JavaEnums and Enumeratum Enums
  */
@State(Scope.Thread)
@BenchmarkMode(Array(Mode.AverageTime))
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@SuppressWarnings(Array("org.wartremover.warts.Var"))
class SetComparisons {

  private val jEnumEnumSet = util.EnumSet.allOf(classOf[JAgeGroup])

  private val jEnumEnumsetSmall = util.EnumSet.of(JAgeGroup.Adult)
  private val jEnumEnumsetMedium =
    util.EnumSet.of(JAgeGroup.Adult, JAgeGroup.Baby, JAgeGroup.Senior)

  private val jEnumScalaSet = Set(JAgeGroup.values(): _*)

  private val enumeratumScalaSet = Set(AgeGroup.values: _*)

  // Don't reuse the previous set for All because subsetOf optimises w/ referential eq check :p
  private val enumeratumScalaAll                  = Set(AgeGroup.values: _*)
  private val enumeratumScalaSmall: Set[AgeGroup] = Set(AgeGroup.Adult)
  private val enumeratumScalaMedium: Set[AgeGroup] =
    Set(AgeGroup.Adult, AgeGroup.Baby, AgeGroup.Senior)

  private def randomFrom[A](seq: Seq[A]): A = {
    seq(scala.util.Random.nextInt(seq.size))
  }

  private var jAgeGroupEnum: JAgeGroup = _
  private var ageGroupEnum: AgeGroup   = _

  @Setup(Level.Trial)
  def setup(): Unit = {
    jAgeGroupEnum = randomFrom(JAgeGroup.values())
    ageGroupEnum = randomFrom(AgeGroup.values)
  }

  @Benchmark
  def jEnumEnumSetContains(bh: Blackhole): Unit = bh.consume {
    jEnumEnumSet.contains(jAgeGroupEnum)
  }

  @Benchmark
  def jEnumEnumSetContainsAllSmall(bh: Blackhole): Unit = bh.consume {
    jEnumEnumSet.containsAll(jEnumEnumsetSmall)
  }

  @Benchmark
  def jEnumEnumSetContainsAllMedium(bh: Blackhole): Unit = bh.consume {
    jEnumEnumSet.containsAll(jEnumEnumsetMedium)
  }

  @Benchmark
  def jEnumEnumSetContainsAllAll(bh: Blackhole): Unit = bh.consume {
    jEnumEnumSet.containsAll(jEnumEnumSet)
  }

  @Benchmark
  def jEnumScalaSetContains(bh: Blackhole): Unit = bh.consume {
    jEnumScalaSet.contains(jAgeGroupEnum)
  }

  @Benchmark
  def enumeratumScalaSetContains(bh: Blackhole): Unit = bh.consume {
    enumeratumScalaSet.contains(ageGroupEnum)
  }

  @Benchmark
  def enumeratumScalaSetSubsetOfSmall(bh: Blackhole): Unit = bh.consume {
    enumeratumScalaSmall.subsetOf(enumeratumScalaSet)
  }

  @Benchmark
  def enumeratumScalaSetSubsetOfMedium(bh: Blackhole): Unit = bh.consume {
    enumeratumScalaMedium.subsetOf(enumeratumScalaSet)
  }

  @Benchmark
  def enumeratumScalaSetSubsetOfAll(bh: Blackhole): Unit = bh.consume {
    enumeratumScalaAll.subsetOf(enumeratumScalaSet)
  }

}


text:
layout: page
title: Jenkins Family Reunion
date: 2016-05-24
author: Amber Hansen
tags: weekly links, java
status: published
summary: Mauris hendrerit, purus in consequat.
banner: images/banner/leisure-02.jpg
booking:
  startDate: 09/04/2018
  endDate: 09/05/2018
  ctyhocn: MHOIDHX
  groupCode: JFR
published: true
---
Duis quis eros eu arcu finibus lobortis eget in dui. Vestibulum vulputate, ante a condimentum sodales, est mi consectetur erat, non bibendum metus massa at urna. In vel efficitur risus. Aenean egestas fermentum massa a suscipit. Vestibulum quis egestas orci. Nam rhoncus augue eget dignissim luctus. Cras et elit eget nunc molestie tincidunt.
Nunc ultrices nulla quis velit pretium dictum. Vivamus eu imperdiet lorem. Curabitur ut auctor erat. Donec iaculis ante eu vulputate iaculis. Donec et augue pellentesque diam varius varius id non purus. Duis blandit dapibus tempor. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Integer sit amet aliquet arcu, vitae tincidunt enim. Nullam dictum, quam ut blandit molestie, elit magna scelerisque nisl, sed vehicula tortor ante ac urna.

* Pellentesque pulvinar felis quis scelerisque ullamcorper
* Nam eget lectus ac nunc condimentum ultrices in eget ipsum.

Donec lacinia hendrerit eros vel convallis. Donec eget felis massa. Morbi eu imperdiet leo. Mauris volutpat feugiat mi, sit amet tempus quam pretium ut. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec sed ex lectus. Vestibulum rutrum pulvinar ex, eget tincidunt ex molestie vel. Nunc fermentum enim est, vitae tincidunt mauris efficitur in.


text:
package com.github.lukaszkusek.xml.comparator.document;

import javax.xml.transform.TransformerException;
import java.io.IOException;
import java.io.StringReader;
import java.util.Collection;
import java.util.Map;

import com.github.lukaszkusek.xml.comparator.node.Node;
import com.google.common.base.Predicate;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.google.common.io.CharStreams;

public class XMLDocument {

    private Node rootNode;

    private XMLDocument(String xml, boolean ignoreNamespace) throws TransformerException, IOException {
        rootNode =
                findRootNode(
                        buildNodeTree(
                                createNodeMap(
                                        createNodeMultiMap(
                                                extractXPathLines(xml, ignoreNamespace)))));
    }

    private Collection<XPathLine> extractXPathLines(String xml, boolean ignoreNamespace)
            throws IOException, TransformerException {

        return CharStreams.readLines(
                new StringInputSupplier(
                        new StringReader(
                                XMLToXPathsTransformer.translate(xml))),
                new XPathLineProcessor(ignoreNamespace));
    }

    private Multimap<String, Node> createNodeMultiMap(Collection<XPathLine> xPathLines) {
        return Multimaps.transformValues(
                FluentIterable.from(xPathLines).index(XPathLine::getXPath),
                xPathLine -> {
                    Node node = new Node(xPathLine.getIndex(), xPathLine.getXPath());
                    node.setValue(xPathLine.getValue());
                    node.putAttribute(xPathLine.getAttributeName(), xPathLine.getAttributeValue());

                    return node;
                });
    }

    private Map<String, Node> createNodeMap(Multimap<String, Node> xpathToNodeMultimap) {
        return Maps.newHashMap(
                Maps.transformEntries(
                        xpathToNodeMultimap.asMap(),
                        (key, nodes) -> nodes.stream().reduce(Node::merge).get()));
    }

    private Collection<Node> buildNodeTree(Map<String, Node> xpathToNodeMap) {
        xpathToNodeMap.forEach(
                (xPath, child) -> {
                    String parentKey = extractParentXPath(xPath);

                    if (hasParent(parentKey)) {
                        Node parent = xpathToNodeMap.get(parentKey);

                        linkChildWithParent(parent, child, xPath);
                    }
                });

        return xpathToNodeMap.values();
    }

    private Node findRootNode(Collection<Node> nodes) {
        return FluentIterable.from(nodes).filter(isRoot()).first().get();
    }

    private Predicate<Node> isRoot() {
        return node -> node.getParent() == null;
    }

    private void linkChildWithParent(Node parent, Node child, String childKey) {
        child.setParent(parent);

        parent.addChild(childKey, child);
    }

    private boolean hasParent(String parentKey) {
        return !parentKey.isEmpty();
    }

    private String extractParentXPath(String xPath) {
        return xPath.replaceAll("/[^/]+$", "");
    }

    public static XMLDocument fromXML(String xml, boolean ignoreNamespace) throws TransformerException, IOException {
        return new XMLDocument(xml, ignoreNamespace);
    }

    public static XMLDocument fromXML(String xml) throws TransformerException, IOException {
        return new XMLDocument(xml, true);
    }

    public Node getRootNode() {
        return rootNode;
    }

}


text:
package com.mossle.disk.persistence.manager;

import com.mossle.core.hibernate.HibernateEntityDao;

import com.mossle.disk.persistence.domain.DiskDownload;

import org.springframework.stereotype.Service;

@Service
public class DiskDownloadManager extends HibernateEntityDao<DiskDownload> {
}


text:
require 'rails_helper'

describe UsersController do

  describe "POST create" do

    context 'when valid parameters are passed' do
      it 'creates a new user' do
        expect {
          post :create, { user: {username: "fakefake", email: "fake@fake.com", password: "12345678"} }
        }.to change{User.count}.by(1)
      end
      it 'assigns a newly created user as a user' do
        post :create, { user: {username: "fakefake", email: "fake@fake.com", password: "12345678"} }
        expect(assigns(:user)).to be_a User
      end

      it 'redirects to the root' do
        expect(
          post :create, { user: {username: "fakefake", email: "fake@fake.com", password: "12345678"} }
        ).to redirect_to root_path
      end
    end

    context 'when invalid parameters are passed' do
      let!(:user_test) { User.create(username: "fakeyfakey", email: "fake2@fake2.com", password: "123456789012345678901437")}

      let!(:user_test_2) { User.create(username: "fakeyfakey2", email: "fake2@fake2.com", password: "123456789012345678901437")}

      it 'assigns a newly created user but unsaved' do
        post :create, { user: { username: '1' } }
        expect(assigns(:user)).to be_a_new User
      end

      it 'does not allow a user to create with a missing username' do
        post :create, { user: {email: "fake@fake.com", password: "12345678"} }
        expect(assigns(:errors)).to_not be_nil
      end

      it 'does not allow a user to create with a missing email' do
        post :create, { user: {username: "fakefake", password: "12345678"} }
        expect(assigns(:errors)).to_not be_nil
      end

      it 'does not allow a user to create with a missing password' do
        post :create, { user: {username: "fakefake", email: "fake@fake.com"} }
        expect(assigns(:errors)).to_not be_nil
      end

      it 'does not allow a user to create with a password less than 6 characters' do
        post :create, { user: {username: "fakefake", email: "fake@fake.com", password: "12345"} }
        expect(assigns(:errors)).to_not be_nil
      end

      it 'does not allow a user to create with a username less than 6 characters' do
        post :create, { user: {username: "fake", email: "fake@fake.com", password: "123456789012345678901437"} }
        expect(assigns(:errors)).to_not be_nil
      end

      it 'does not allow a user to create with an invalid email' do
        post :create, { user: {username: "fakefake", email: "fakefake.com", password: "123456789012345678901437"} }
        expect(assigns(:errors)).to_not be_nil
      end

      it 'does not allow a user to create without a unique username' do
        post :create, { user: {username: "fakeyfakey", email: "fake@fake.com", password: "123456789012345678901437"} }
        expect(assigns(:errors)).to_not be_nil
      end

      it 'does not allow a user to create without a unique email' do
        post :create, { user: {username: "fakeyfakey3", email: "fake2@fake2.com", password: "123456789012345678901437"} }
        expect(assigns(:errors)).to_not be_nil
      end

      it 'does not allow a user to create with an invalid username' do
        post :create, { user: {username: "*$&%^%^", email: "fakefake.com", password: "123456789012345678901437"} }
        expect(assigns(:errors)).to_not be_nil
      end

      it "re-renders the 'new' template" do
        expect(
          post :create, { user: { username: '1' } }
        ).to render_template(:new)
      end
    end
  end

end


text:
package io.deepsense.commons.utils

import java.math.{MathContext, RoundingMode}

object DoubleUtils {
  private val significantFigures = 6
  private val mathContext = new MathContext(significantFigures, RoundingMode.HALF_UP)
  def double2String(d: Double): String = {
    if (d.isNaN || d.isInfinity) {
      d.toString
    } else {
      val decimal = BigDecimal(d)
        .round(mathContext)
        .toString()
      if (decimal.contains("E")) {
        decimal.replaceAll("\\.?0*E", "e")
      } else if (decimal.contains(".")) {
        decimal.replaceAll("\\.?0*$", "")
      } else {
        decimal
      }
    }
  }
}


text:
package org.supercsv.cellprocessor;

import org.supercsv.cellprocessor.ift.LongCellProcessor;
import org.supercsv.cellprocessor.ift.StringCellProcessor;
import org.supercsv.exception.SuperCsvCellProcessorException;
import org.supercsv.util.CsvContext;

/**
 * Converts a String to an Integer.
 *
 * @author Kasper B. Graversen
 */
public class ParseInt extends CellProcessorAdaptor implements StringCellProcessor {

	/**
	 * Constructs a new <tt>ParseInt</tt> processor, which converts a String to an Integer.
	 */
	public ParseInt() {
		super();
	}

	/**
	 * Constructs a new <tt>ParseInt</tt> processor, which converts a String to an Integer, then calls the next
	 * processor in the chain.
	 *
	 * @param next
	 *            the next processor in the chain
	 * @throws NullPointerException
	 *             if next is null
	 */
	public ParseInt(final LongCellProcessor next) {
		super(next);
	}

	/**
	 * {@inheritDoc}
	 *
	 * @throws SuperCsvCellProcessorException
	 *             if value is null, isn't an Integer or String, or can't be parsed as an Integer
	 */
	public Object execute(final Object value, final CsvContext context) {
		validateInputNotNull(value, context);

		final Integer result;
		if( value instanceof Integer ) {
			result = (Integer) value;
		} else if( value instanceof String ) {
			try {
				result = Integer.valueOf((String) value);
			}
			catch(final NumberFormatException e) {
				throw new SuperCsvCellProcessorException(
					String.format("'%s' could not be parsed as an Integer", value), context, this, e);
			}
		} else {
			final String actualClassName = value.getClass().getName();
			throw new SuperCsvCellProcessorException(String.format(
				"the input value should be of type Integer or String but is of type %s", actualClassName), context,
				this);
		}

		return next.execute(result, context);
	}
}


text:
package com.sun.java.swing.plaf.windows.resources;

import java.util.ListResourceBundle;

public final class windows_de extends ListResourceBundle {
    protected final Object[][] getContents() {
        return new Object[][] {
            { "FileChooser.detailsViewActionLabel.textAndMnemonic", "Details" },
            { "FileChooser.detailsViewButtonAccessibleName", "Details" },
            { "FileChooser.detailsViewButtonToolTip.textAndMnemonic", "Details" },
            { "FileChooser.fileAttrHeader.textAndMnemonic", "Attribute" },
            { "FileChooser.fileDateHeader.textAndMnemonic", "Ge\u00E4ndert" },
            { "FileChooser.fileNameHeader.textAndMnemonic", "Name" },
            { "FileChooser.fileNameLabel.textAndMnemonic", "Dateiname:" },
            { "FileChooser.fileSizeHeader.textAndMnemonic", "Gr\u00F6\u00DFe" },
            { "FileChooser.fileTypeHeader.textAndMnemonic", "Typ" },
            { "FileChooser.filesOfTypeLabel.textAndMnemonic", "Dateityp:" },
            { "FileChooser.folderNameLabel.textAndMnemonic", "Ordnername:" },
            { "FileChooser.homeFolderAccessibleName", "Home" },
            { "FileChooser.homeFolderToolTip.textAndMnemonic", "Home" },
            { "FileChooser.listViewActionLabel.textAndMnemonic", "Liste" },
            { "FileChooser.listViewButtonAccessibleName", "Liste" },
            { "FileChooser.listViewButtonToolTip.textAndMnemonic", "Liste" },
            { "FileChooser.lookInLabel.textAndMnemonic", "Suchen in:" },
            { "FileChooser.newFolderAccessibleName", "Neuer Ordner" },
            { "FileChooser.newFolderActionLabel.textAndMnemonic", "Neuer Ordner" },
            { "FileChooser.newFolderToolTip.textAndMnemonic", "Neuen Ordner erstellen" },
            { "FileChooser.refreshActionLabel.textAndMnemonic", "Aktualisieren" },
            { "FileChooser.saveInLabel.textAndMnemonic", "Speichern in:" },
            { "FileChooser.upFolderAccessibleName", "Nach oben" },
            { "FileChooser.upFolderToolTip.textAndMnemonic", "Eine Ebene h\u00F6her" },
            { "FileChooser.viewMenuButtonAccessibleName", "Ansichtsmen\u00FC" },
            { "FileChooser.viewMenuButtonToolTipText", "Ansichtsmen\u00FC" },
            { "FileChooser.viewMenuLabel.textAndMnemonic", "Ansicht" },
        };
    }
}


text:
angular.module("app").service("ChatService", function($q, $timeout) {

    var service = {}, listener = $q.defer(), socket = {
        client: null,
        stomp: null
    }, messageIds = [];

    service.RECONNECT_TIMEOUT = 30000;
    service.SOCKET_URL = "/stomp";//"/spring-ng-chat/chat";
    service.CHAT_TOPIC = "/topic/message";
    service.CHAT_BROKER = "/app/chat";

    service.receive = function() {
        return listener.promise;
    };

    service.send = function(message) {
        var id = Math.floor(Math.random() * 1000000);
        socket.stomp.send(service.CHAT_BROKER, {
            priority: 9
        }, JSON.stringify({
            message: message,
            id: id
        }));
        messageIds.push(id);
    };

    var reconnect = function() {
        $timeout(function() {
            initialize();
        }, this.RECONNECT_TIMEOUT);
    };

    var getMessage = function(data) {
        // var message = JSON.parse(data), out = {};
        // out.message = message.message;
        // out.time = new Date(message.time);
        // if (_.contains(messageIds, message.id)) {
        //     out.self = true;
        //     messageIds = _.remove(messageIds, message.id);
        // }
        return data;
    };

    var startListener = function() {
        socket.stomp.subscribe(service.CHAT_TOPIC, function(data) {
            listener.notify(getMessage(data.body));
        });
    };

    var initialize = function() {
        socket.client = new SockJS(service.SOCKET_URL);
        socket.stomp = Stomp.over(socket.client);
        socket.stomp.connect({}, startListener);
        socket.stomp.debug = function (str) {};
        socket.stomp.onclose = reconnect;
    };

    initialize();
    return service;
});


text:
package org.xnio.nio;

import static org.xnio.nio.Log.log;

import java.io.IOException;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.channels.CancelledKeyException;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.FileChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import org.xnio.Bits;
import org.xnio.Xnio;
import org.xnio.XnioIoThread;
import org.xnio.XnioWorker;
import org.xnio.channels.ReadTimeoutException;
import org.xnio.channels.StreamSinkChannel;
import org.xnio.channels.StreamSourceChannel;
import org.xnio.channels.WriteTimeoutException;
import org.xnio.conduits.Conduits;
import org.xnio.conduits.ReadReadyHandler;
import org.xnio.conduits.StreamSinkConduit;
import org.xnio.conduits.StreamSourceConduit;
import org.xnio.conduits.WriteReadyHandler;

final class NioSocketConduit extends NioHandle implements StreamSourceConduit, StreamSinkConduit {
    private final SocketChannel socketChannel;
    private final NioSocketStreamConnection connection;
    private ReadReadyHandler readReadyHandler;
    private WriteReadyHandler writeReadyHandler;

    @SuppressWarnings("unused")
    private volatile int readTimeout;
    private long lastRead;

    @SuppressWarnings("rawtypes")
    private static final AtomicIntegerFieldUpdater<NioSocketConduit> readTimeoutUpdater = AtomicIntegerFieldUpdater.newUpdater(NioSocketConduit.class, "readTimeout");

    @SuppressWarnings("unused")
    private volatile int writeTimeout;
    private long lastWrite;

    @SuppressWarnings("rawtypes")
    private static final AtomicIntegerFieldUpdater<NioSocketConduit> writeTimeoutUpdater = AtomicIntegerFieldUpdater.newUpdater(NioSocketConduit.class, "writeTimeout");

    NioSocketConduit(final WorkerThread workerThread, final SelectionKey selectionKey, final NioSocketStreamConnection connection) {
        super(workerThread, selectionKey);
        this.connection = connection;
        this.socketChannel = (SocketChannel) selectionKey.channel();
    }

    void handleReady(int ops) {
        try {
            if (ops == 0) {
                // the dreaded bug
                final SelectionKey key = getSelectionKey();
                final int interestOps = key.interestOps();
                if (interestOps != 0) {
                    ops = interestOps;
                } else {
                    // urp
                    forceTermination();
                    return;
                }
            }
            if (Bits.allAreSet(ops, SelectionKey.OP_READ)) try {
                if (isReadShutdown()) suspendReads();
                readReadyHandler.readReady();
            } catch (Throwable ignored) {
            }
            if (Bits.allAreSet(ops, SelectionKey.OP_WRITE)) try {
                if (isWriteShutdown()) suspendWrites();
                writeReadyHandler.writeReady();
            } catch (Throwable ignored) {
            }
        } catch (CancelledKeyException ignored) {}
    }

    public XnioWorker getWorker() {
        return getWorkerThread().getWorker();
    }

    void forceTermination() {
        final ReadReadyHandler read = readReadyHandler;
        if (read != null) read.forceTermination();
        final WriteReadyHandler write = writeReadyHandler;
        if (write != null) write.forceTermination();
    }

    void terminated() {
        final ReadReadyHandler read = readReadyHandler;
        if (read != null) read.terminated();
        final WriteReadyHandler write = writeReadyHandler;
        if (write != null) write.terminated();
    }

    // Write methods

    int getAndSetWriteTimeout(int newVal) {
        return writeTimeoutUpdater.getAndSet(this, newVal);
    }

    int getWriteTimeout() {
        return writeTimeout;
    }

    private void checkWriteTimeout(final boolean xfer) throws WriteTimeoutException {
        int timeout = writeTimeout;
        if (timeout > 0) {
            if (xfer) {
                lastWrite = System.nanoTime();
            } else {
                long lastRead = this.lastWrite;
                if (lastRead > 0L && ((System.nanoTime() - lastRead) / 1000000L) > (long) timeout) {
                    throw log.writeTimeout();
                }
            }
        }
    }

    public final long transferFrom(final FileChannel src, final long position, final long count) throws IOException {
        long res = src.transferTo(position, count, socketChannel);
        checkWriteTimeout(res > 0L);
        return res;
    }

    public long transferFrom(final StreamSourceChannel source, final long count, final ByteBuffer throughBuffer) throws IOException {
        return Conduits.transfer(source, count, throughBuffer, this);
    }

    public int write(final ByteBuffer src) throws IOException {
        int res = socketChannel.write(src);
        checkWriteTimeout(res > 0);
        return res;
    }

    public long write(final ByteBuffer[] srcs, final int offset, final int length) throws IOException {
        if (length == 1) {
            return write(srcs[offset]);
        }
        long res = socketChannel.write(srcs, offset, length);
        checkWriteTimeout(res > 0L);
        return res;
    }

    @Override
    public int writeFinal(ByteBuffer src) throws IOException {
        return Conduits.writeFinalBasic(this, src);
    }

    @Override
    public long writeFinal(ByteBuffer[] srcs, int offset, int length) throws IOException {
        return Conduits.writeFinalBasic(this, srcs, offset, length);
    }

    public boolean flush() throws IOException {
        return true;
    }

    public void terminateWrites() throws IOException {
        if (connection.writeClosed()) try {
            if (getSelectionKey().isValid()) {
                suspend(SelectionKey.OP_WRITE);
            }
            if (socketChannel.isOpen()) try {
                socketChannel.socket().shutdownOutput();
            } catch (SocketException ignored) {
                // IBM incorrectly throws this exception on ENOTCONN; it's probably less harmful just to swallow it
            }
        } catch (ClosedChannelException ignored) {
        } finally {
            writeTerminated();
        }
    }

    public void truncateWrites() throws IOException {
        terminateWrites();
    }

    void writeTerminated() {
        final WriteReadyHandler writeReadyHandler = this.writeReadyHandler;
        if (writeReadyHandler != null) try {
            writeReadyHandler.terminated();
        } catch (Throwable ignored) {}
    }

    public boolean isWriteShutdown() {
        return connection.isWriteShutdown();
    }

    public void resumeWrites() {
        resume(SelectionKey.OP_WRITE);
    }

    public void suspendWrites() {
        suspend(SelectionKey.OP_WRITE);
    }

    public void wakeupWrites() {
        wakeup(SelectionKey.OP_WRITE);
    }

    public boolean isWriteResumed() {
        return isResumed(SelectionKey.OP_WRITE);
    }

    public void awaitWritable() throws IOException {
        Xnio.checkBlockingAllowed();
        if (isWriteShutdown()) {
            return;
        }
        SelectorUtils.await((NioXnio)getWorker().getXnio(), socketChannel, SelectionKey.OP_WRITE);
    }

    public void awaitWritable(final long time, final TimeUnit timeUnit) throws IOException {
        Xnio.checkBlockingAllowed();
        if (isWriteShutdown()) {
            return;
        }
        SelectorUtils.await((NioXnio)getWorker().getXnio(), socketChannel, SelectionKey.OP_WRITE, time, timeUnit);
    }

    public XnioIoThread getWriteThread() {
        return getWorkerThread();
    }

    public void setWriteReadyHandler(final WriteReadyHandler handler) {
        writeReadyHandler = handler;
    }

    // Read methods

    int getAndSetReadTimeout(int newVal) {
        return readTimeoutUpdater.getAndSet(this, newVal);
    }

    int getReadTimeout() {
        return readTimeout;
    }

    private void checkReadTimeout(final boolean xfer) throws ReadTimeoutException {
        int timeout = readTimeout;
        if (timeout > 0) {
            if (xfer) {
                lastRead = System.nanoTime();
            } else {
                long lastRead = this.lastRead;
                if (lastRead > 0L && ((System.nanoTime() - lastRead) / 1000000L) > (long) timeout) {
                    throw log.readTimeout();
                }
            }
        }
    }

    public long transferTo(final long position, final long count, final FileChannel target) throws IOException {
        long res = target.transferFrom(socketChannel, position, count);
        checkReadTimeout(res > 0L);
        return res;
    }

    public long transferTo(final long count, final ByteBuffer throughBuffer, final StreamSinkChannel target) throws IOException {
        return Conduits.transfer(this, count, throughBuffer, target);
    }

    public int read(final ByteBuffer dst) throws IOException {
        int res;
        try {
            res = socketChannel.read(dst);
        } catch (ClosedChannelException e) {
            return -1;
        }
        if (res != -1) checkReadTimeout(res > 0);
        else terminateReads();
        return res;
    }

    public long read(final ByteBuffer[] dsts, final int offset, final int length) throws IOException {
        if (length == 1) {
            return read(dsts[offset]);
        }
        long res;
        try {
            res = socketChannel.read(dsts, offset, length);
        } catch (ClosedChannelException e) {
            return -1L;
        }
        if (res != -1L) checkReadTimeout(res > 0L);
        else terminateReads();
        return res;
    }

    public void terminateReads() throws IOException {
        if (connection.readClosed()) try {
            if (getSelectionKey().isValid()) {
                suspend(SelectionKey.OP_READ);
            }
            if (socketChannel.isOpen()) try {
                socketChannel.socket().shutdownInput();
            } catch (SocketException ignored) {
                // IBM incorrectly throws this exception on ENOTCONN; it's probably less harmful just to swallow it
            }
        } catch (ClosedChannelException ignored) {
        } finally {
            readTerminated();
        }
    }

    void readTerminated() {
        final ReadReadyHandler readReadyHandler = this.readReadyHandler;
        if (readReadyHandler != null) try {
            readReadyHandler.terminated();
        } catch (Throwable ignored) {}
    }

    public boolean isReadShutdown() {
        return connection.isReadShutdown();
    }

    public void resumeReads() {
        resume(SelectionKey.OP_READ);
    }

    public void suspendReads() {
        suspend(SelectionKey.OP_READ);
    }

    public void wakeupReads() {
        wakeup(SelectionKey.OP_READ);
    }

    public boolean isReadResumed() {
        return isResumed(SelectionKey.OP_READ);
    }

    public void awaitReadable() throws IOException {
        Xnio.checkBlockingAllowed();
        SelectorUtils.await((NioXnio)getWorker().getXnio(), socketChannel, SelectionKey.OP_READ);
    }

    public void awaitReadable(final long time, final TimeUnit timeUnit) throws IOException {
        Xnio.checkBlockingAllowed();
        SelectorUtils.await((NioXnio)getWorker().getXnio(), socketChannel, SelectionKey.OP_READ, time, timeUnit);
    }

    public XnioIoThread getReadThread() {
        return getWorkerThread();
    }

    public void setReadReadyHandler(final ReadReadyHandler handler) {
        this.readReadyHandler = handler;
    }

    SocketChannel getSocketChannel() {
        return socketChannel;
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1"/>

  <title>Gênios do Crime</title>
  <meta name="author" content="" />
  <meta name="description"
        content="Quando assistimos a um filme, seja drama ou comédia, é normal nos preocuparmos com os personagens, de uma forma positiva ou negativa. Isso é vital para o funcionamento da narrativa. Quando isso não..."/>

  <meta name="yandex-verification" content="48a8210fc043c5e8" />

  <meta name="generator" content="Hugo 0.54.0" />

  <meta itemprop="name" content="Gênios do Crime"/>
  <meta itemprop="description"
        content="Quando assistimos a um filme, seja drama ou comédia, é normal nos preocuparmos com os personagens, de uma forma positiva ou negativa. Isso é vital para o funcionamento da narrativa. Quando isso não..."/>
  <meta itemprop="image"
        content="/img/logo.svg"/>

  <meta property="og:title" content="Gênios do Crime"/>
  <meta property="og:type"
        content="article"/>
  <meta property="og:url" content="http://www.cinetenisverde.com.br/genios-do-crime/"/>
  <meta property="og:image"
        content="/img/logo.svg"/>
  <meta property="og:description"
        content="Quando assistimos a um filme, seja drama ou comédia, é normal nos preocuparmos com os personagens, de uma forma positiva ou negativa. Isso é vital para o funcionamento da narrativa. Quando isso não..."/>
  <meta property="og:site_name" content="Cine Tênis Verde"/>
  <meta property="article:published_time"
        content="2016-08-12T00:00:00+00:00"/>
  <meta property="article:section" content="post"/>

  <meta name="twitter:card" content="summary"/>
  <meta name="twitter:site"
        content=""/>
  <meta name="twitter:title" content="Gênios do Crime"/>
  <meta name="twitter:description"
        content="Quando assistimos a um filme, seja drama ou comédia, é normal nos preocuparmos com os personagens, de uma forma positiva ou negativa. Isso é vital para o funcionamento da narrativa. Quando isso não..."/>
  <meta name="twitter:creator"
        content=""/>
  <meta name="twitter:image:src"
        content="/img/logo.svg"/>

  <link rel="stylesheet" type="text/css" href="/css/capsule.min.css"/>
  <link rel="stylesheet" type="text/css" href="/css/custom.css"/>

  <link rel="apple-touch-icon" href="/img/apple-touch-icon.png"/>
  <link rel="icon" href="/img/favicon.ico"/>

 Cine Tênis Verde

    <input type="checkbox" id="navbar-burger-state"/>

      search

      twitter

      rss

Gênios do Crime

    ★★★☆☆

 Wanderley Caloni, August 12, 2016

Quando assistimos a um filme, seja drama ou comédia, é normal nos preocuparmos com os personagens, de uma forma positiva ou negativa. Isso é vital para o funcionamento da narrativa. Quando isso não acontece o resultado são os milhares de filmes os quais não damos a mínima para as pessoas que nele habitam. Não que elas não sejam divertidas ou interessantes. É que elas simplesmente não fazem qualquer diferença para a história que estamos vendo.

É mais ou menos dessa forma que se comporta Gênios do Crime, que insiste em jogar diferentes situações e diálogos aleatórios ditas por esse ou aquele personagem e que seriam engraçados por si só. O problema é que precisa-se de pessoas para dizer aquelas falas, viver aquelas situações. Dessa forma, contrata-se um grupo de atores divertidos para colocá-los nessa função. De quebra, utiliza um roteiro planejado em torno de eventos reais, fazendo questão de citar isso sem pudor ou medo nenhum que o espectador perceba que não faz sentido aquelas pessoas existirem na vida real.

O irônico é: talvez elas existam mesmo. Talvez quase tudo no filme tenha acontecido de verdade. A questão é que não importa. Os personagens já sabem disso, e estão sendo engraçadinhos porque… bom, é isso o que esse elenco faz de melhor, certo?

Mas ao usar o elenco errado construindo personagens absurdos, o filme queima a fita duplamente. Primeiro em desperdiçar ótimos atores em um filme que não compete a eles. Segundo em desperdiçar uma bela história a recheando de gracinhas gratuitas.

Não é assim que se constrói uma comédia, fazendo rir? Sem dúvida algumas pessoas poderão achar a história engraçada, irônica e talvez com um final poético. Porém, há uma forma muito mais eficaz de utilizar uma história absurda dessas que é muito simples: simplesmente a contando. Ela teria o mesmo efeito sem o gosto de sessão da tarde.

O que incomoda é que se trata de uma ótima trama. Contém reviravoltas eficazes e que faz pensar em uma coisa ou outra. O que incomoda é perder essa chance com piadas que incomodam. Não por serem racistas. Não por serem sexistas. Apenas por estarem sendo usadas para alavancar uma história já premiada.

Não precisamos de alguém que defeca na piscina ou atira na própria bunda. Não precisamos do falsete da sedução ridícula (embora Wiig esteja perfeita no papel). Não precisamos do assassino profissional que mata por prazer e faz comentários inoportunos. Não precisamos, enfim, de novos-ricos provando que o sonho americano pode ser conquistado por idiotas. Basta que “saiam por aí conseguindo seus 17 milhões”.

Só precisamos entender como alguém procurado pelo FBI consegue ser tão agradável e simpático. Isso por si só seria algo muito bem-vindo. Infelizmente nem isso o filme te trará, pois Galifianakis nem de perto é uma escolha que traga essa simpatia.

Isso remete ao grande problema do filme: empatia. Resolva isso e teríamos mais Golpista do Ano. Ou seja, um filme absurdo baseado em eventos reais e que ainda assim consegue abduzir um público torcendo por criminosos gays vivendo um grande romance dentro e fora da prisão. Que diria que isso pode funcionar?

           Imagens e créditos no IMDB. O texto de estreia será publicado no CinemAqui.

    ★★★☆☆

 Gênios do Crime ● Gênios do Crime. Masterminds (USA, 2016). Dirigido por Jared Hess. Escrito por Chris Bowman, Hubbel Palmer, Emily Spivey, Emily Spivey, Chris Bowman, Hubbel Palmer. Com Kate McKinnon, Kristen Wiig, Jason Sudeikis, Zach Galifianakis, Owen Wilson, Leslie Jones, Mary Elizabeth Ellis, Jon Daly, Ken Marino. ● Nota: 3/5. Categoria: movies.  Visto em cabine de imprensa pelo cinemaqui. Publicado em 2016-08-12.  Texto escrito por Wanderley Caloni.

Quer comentar?

      Share


text:
using System.Linq;
using System.Collections.Generic;
using System.Xml.Linq;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;

using Faseway.GameLibrary.Components;
using Faseway.GameLibrary.Logging;

namespace Faseway.GameLibrary.Rendering
{
    public class TextureSheet
    {
        // Properties
        public Dictionary<string, Rectangle> Clips { get; set; }
        public Texture2D BaseTexture { get; set; }

        public string TexturePath { get; set; }

        private ContentManager Content
        {
            get { return Seed.Components.GetAndRequire<XnaReference>().GetAndRequire<ContentManager>(); }
        }

        // Constants
        public const string FILE_VERSION = "1.0";

        // Constructor
        public TextureSheet()
        {
            Clips = new Dictionary<string, Rectangle>();
        }

        // Methods
        public void Load(string path)
        {
            var document = XDocument.Load(Content.RootDirectory + "\\" + path);

            if (document.Root.Attribute("version").Value != FILE_VERSION)
            {
                Logger.Log("TextureSheet version is invalid ({0})", path);
                return;
            }

            TexturePath = document.Root.Attribute("texture").Value;
            //Logger.Log("TextureSheet base texture {0}", TexturePath);

            foreach (XElement element in document.Root.Descendants())
            {
                if (element.Name == "sprite")
                {
                    var x = int.Parse(element.Attribute("x").Value);
                    var y = int.Parse(element.Attribute("y").Value);
                    var width = int.Parse(element.Attribute("width").Value);
                    var height = int.Parse(element.Attribute("height").Value);

                    //Logger.Log("TextureSheet add texture clip {0}", element.Attribute("name").Value);

                    Clips.Add(element.Attribute("name").Value, new Rectangle(x, y, width, height));
                }
            }

            BaseTexture = Seed.Components.GetAndRequire<XnaReference>().GetAndRequire<ContentManager>().Load<Texture2D>(TexturePath);
        }

        public Rectangle GetTextureRectangle(string name)
        {
            return Clips[name];
        }
    }

    public class Sprite
    {
        // Properties
        public Rectangle Rectangle { get; set; }
        public int X
        {
            get { return Rectangle.X; }
        }
        public int Y
        {
            get { return Rectangle.Y; }
        }
        public int Width
        {
            get { return Rectangle.Width; }
        }
        public int Height
        {
            get { return Rectangle.Height; }
        }
        public string Name { get; set; }

        // Constructor
        public Sprite()
            : this(0, 0, 0, 0)
        {
        }

        public Sprite(int x, int y)
            : this(x, y, 0, 0)
        {
        }

        public Sprite(int x, int y, int width, int height)
        {
            Rectangle = new Rectangle(x, y, width, height);
        }
    }
}


text:
package web

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/mail"
	"net/url"
	"regexp"
	"sort"
	"strconv"
	"strings"
	"sync"
	"time"

	"bosun.org/cmd/bosun/cache"
	"bosun.org/cmd/bosun/conf"
	"bosun.org/cmd/bosun/conf/rule"
	"bosun.org/cmd/bosun/expr"
	"bosun.org/cmd/bosun/sched"
	"bosun.org/models"
	"bosun.org/opentsdb"
	"github.com/MiniProfiler/go/miniprofiler"
	"github.com/bradfitz/slice"
)

// for executing expressions/rules via the web UI, we use a cache that we retain during the lifetime of bosun
// Matt and I decided not to expire the cache at given points (such as reloading rule page), but I forgot why. ?
// the only risk is that if you query your store for data -5m to now and your store doesn't have the latest points up to date,
// and then 5m from now you query -10min to -5m you'll get the same cached data, including the incomplete last points
var cacheObj = cache.New(100)

func Expr(t miniprofiler.Timer, w http.ResponseWriter, r *http.Request) (v interface{}, err error) {
	defer func() {
		if pan := recover(); pan != nil {
			v = nil
			err = fmt.Errorf("%v", pan)
		}
	}()
	text, err := ioutil.ReadAll(r.Body)
	if err != nil {
		return nil, err
	}

	lines := strings.Split(strings.TrimSpace(string(text)), "\n")
	var expression string
	vars := map[string]string{}
	varRegex := regexp.MustCompile(`(\$\w+)\s*=(.*)`)
	for i, line := range lines {
		line = strings.TrimSpace(line)
		if line == "" || strings.HasPrefix(line, "#") {
			continue
		}
		// last line is expression we care about
		if i == len(lines)-1 {
			expression = schedule.RuleConf.Expand(line, vars, false)
		} else { // must be a variable declatation
			matches := varRegex.FindStringSubmatch(line)
			if len(matches) == 0 {
				return nil, fmt.Errorf("Expect all lines before final expression to be variable declarations of form `$foo = something`")
			}
			name := strings.TrimSpace(matches[1])
			value := strings.TrimSpace(matches[2])
			vars[name] = schedule.RuleConf.Expand(value, vars, false)
		}
	}
	e, err := expr.New(expression, schedule.RuleConf.GetFuncs(schedule.SystemConf.EnabledBackends()))
	if err != nil {
		return nil, err
	}
	now, err := getTime(r)
	if err != nil {
		return nil, err
	}
	// it may not strictly be necessary to recreate the contexts each time, but we do to be safe
	backends := &expr.Backends{
		TSDBContext:     schedule.SystemConf.GetTSDBContext(),
		GraphiteContext: schedule.SystemConf.GetGraphiteContext(),
		InfluxConfig:    schedule.SystemConf.GetInfluxContext(),
		ElasticHosts:    schedule.SystemConf.GetElasticContext(),
	}
	providers := &expr.BosunProviders{
		Cache:     cacheObj,
		Search:    schedule.Search,
		Squelched: nil,
		History:   nil,
		Annotate:  AnnotateBackend,
	}
	res, queries, err := e.Execute(backends, providers, t, now, 0, false)
	if err != nil {
		return nil, err
	}
	for _, r := range res.Results {
		if r.Computations == nil {
			r.Computations = make(models.Computations, 0)
		}
	}
	ret := struct {
		Type    string
		Results []*expr.Result
		Queries map[string]opentsdb.Request
	}{
		e.Tree.Root.Return().String(),
		res.Results,
		make(map[string]opentsdb.Request),
	}
	for _, q := range queries {
		if e, err := url.QueryUnescape(q.String()); err == nil {
			ret.Queries[e] = q
		}
	}
	return ret, nil
}

func getTime(r *http.Request) (now time.Time, err error) {
	now = time.Now().UTC()
	if fd := r.FormValue("date"); len(fd) > 0 {
		if ft := r.FormValue("time"); len(ft) > 0 {
			fd += " " + ft
		} else {
			fd += " " + now.Format("15:04:05")
		}
		now, err = time.Parse("2006-01-02 15:04:05", fd)
		if err != nil {
			now, err = time.Parse("2006-01-02 15:04", fd)
		}
	}
	return
}

type Res struct {
	*models.Event
	Key models.AlertKey
}

func procRule(t miniprofiler.Timer, ruleConf conf.RuleConfProvider, a *conf.Alert, now time.Time, summary bool, email string, template_group string, incidentID int) (*ruleResult, error) {
	s := &sched.Schedule{}
	s.Search = schedule.Search
	if err := s.Init(schedule.SystemConf, ruleConf, schedule.DataAccess, AnnotateBackend, false, false); err != nil {
		return nil, err
	}
	rh := s.NewRunHistory(now, cacheObj)
	if _, err, _ := s.CheckExpr(t, rh, a, a.Warn, models.StWarning, nil); err != nil {
		return nil, err
	}
	if _, err, _ := s.CheckExpr(t, rh, a, a.Crit, models.StCritical, nil); err != nil {
		return nil, err
	}
	keys := make(models.AlertKeys, len(rh.Events))
	criticals, warnings, normals := make([]models.AlertKey, 0), make([]models.AlertKey, 0), make([]models.AlertKey, 0)
	i := 0
	for k, v := range rh.Events {
		v.Time = now
		keys[i] = k
		i++
		switch v.Status {
		case models.StNormal:
			normals = append(normals, k)
		case models.StWarning:
			warnings = append(warnings, k)
		case models.StCritical:
			criticals = append(criticals, k)
		default:
			return nil, fmt.Errorf("unknown state type %v", v.Status)
		}
	}
	sort.Sort(keys)
	var rt *models.RenderedTemplates
	var data interface{}
	var nots map[string]*conf.PreparedNotifications
	var aNots map[string]map[string]*conf.PreparedNotifications
	warning := make([]string, 0)

	if !summary && len(keys) > 0 {
		var primaryIncident *models.IncidentState
		if template_group != "" {
			ts, err := opentsdb.ParseTags(template_group)
			if err != nil {
				return nil, err
			}
			for _, ak := range keys {
				if ak.Group().Subset(ts) {
					primaryIncident = sched.NewIncident(ak)
					primaryIncident.Events = []models.Event{*rh.Events[ak]}
					break
				}
			}
		}
		if primaryIncident == nil {
			primaryIncident = sched.NewIncident(keys[0])
			primaryIncident.Events = []models.Event{*rh.Events[keys[0]]}
			if template_group != "" {
				warning = append(warning, fmt.Sprintf("template group %s was not a subset of any result", template_group))
			}
		}
		e := primaryIncident.Events[0]
		if e.Crit != nil {
			primaryIncident.Result = e.Crit
		} else if e.Warn != nil {
			primaryIncident.Result = e.Warn
		}
		var errs []error
		primaryIncident.Id = int64(incidentID)
		primaryIncident.Start = time.Now().UTC()
		primaryIncident.CurrentStatus = e.Status
		primaryIncident.LastAbnormalStatus = e.Status
		primaryIncident.LastAbnormalTime = models.Epoch{Time: time.Now().UTC()}
		func() {
			defer func() {
				if err := recover(); err != nil {
					s := fmt.Sprint(err)
					warning = append(warning, s)
					errs = append(errs, fmt.Errorf("panic rendering templates: %s", err))
				}
			}()
			rt, errs = s.ExecuteAll(rh, a, primaryIncident, false)
		}()
		for _, err := range errs {
			warning = append(warning, err.Error())
		}
		if rt == nil {
			rt = &models.RenderedTemplates{}
		}

		if len(errs) > 0 {
			var err error
			rt.Subject, rt.Body, err = s.ExecuteBadTemplate(errs, rh, a, primaryIncident)
			if err != nil {
				rt.Subject = fmt.Sprintf("unable to create tempalate error notification: %v", err)
			}
		} else if email != "" {
			m, err := mail.ParseAddress(email)
			if err != nil {
				return nil, err
			}
			n := conf.Notification{
				Email: []*mail.Address{m},
			}
			n.PrepareAlert(rt, string(primaryIncident.AlertKey), rt.Attachments...).Send(s.SystemConf)
		}
		nots, aNots = buildNotificationPreviews(a, rt, primaryIncident, s.SystemConf)
		data = s.Data(rh, primaryIncident, a, false)
	}

	rr := &ruleResult{
		Criticals:           criticals,
		Warnings:            warnings,
		Normals:             normals,
		Time:                now,
		Data:                data,
		Result:              rh.Events,
		Warning:             warning,
		RenderedTemplates:   rt,
		Notifications:       nots,
		ActionNotifications: aNots,
	}
	return rr, nil
}

func buildNotificationPreviews(a *conf.Alert, rt *models.RenderedTemplates, incident *models.IncidentState, c conf.SystemConfProvider, attachments ...*models.Attachment) (map[string]*conf.PreparedNotifications, map[string]map[string]*conf.PreparedNotifications) {
	previews := map[string]*conf.PreparedNotifications{}
	actionPreviews := map[string]map[string]*conf.PreparedNotifications{}
	nots := map[string]*conf.Notification{}
	for name, not := range a.CritNotification.GetAllChained() {
		nots[name] = not
	}
	for name, not := range a.WarnNotification.GetAllChained() {
		nots[name] = not
	}

	for name, not := range nots {
		previews[name] = not.PrepareAlert(rt, string(incident.AlertKey), attachments...)
		actions := map[string]*conf.PreparedNotifications{}
		actionPreviews[name] = actions
		// for all action types. just loop through known range. Update this if any get added
		for at := models.ActionAcknowledge; at <= models.ActionCancelClose; at++ {
			if !not.RunOnActionType(at) {
				continue
			}
			incidents := []*models.IncidentState{incident}
			actions[at.String()] = not.PrepareAction(at, a.Template, c, incidents, "somebody", "I took care of this")
		}
	}
	return previews, actionPreviews
}

type ruleResult struct {
	Criticals []models.AlertKey
	Warnings  []models.AlertKey
	Normals   []models.AlertKey
	Time      time.Time
	*models.RenderedTemplates
	Notifications       map[string]*conf.PreparedNotifications
	ActionNotifications map[string]map[string]*conf.PreparedNotifications
	Data                interface{}
	Result              map[models.AlertKey]*models.Event
	Warning             []string
}

func TestHTTPNotification(t miniprofiler.Timer, w http.ResponseWriter, r *http.Request) (interface{}, error) {
	prep := &conf.PreparedHttp{}
	dec := json.NewDecoder(r.Body)
	if err := dec.Decode(prep); err != nil {
		return nil, err
	}
	code, err := prep.Send()
	dat := &struct {
		Error  string
		Status int
	}{"", code}
	if err != nil {
		dat.Error = err.Error()
	}
	return dat, nil
}

func Rule(t miniprofiler.Timer, w http.ResponseWriter, r *http.Request) (interface{}, error) {
	var from, to time.Time
	var err error
	if f := r.FormValue("from"); len(f) > 0 {
		from, err = time.Parse(tsdbFormatSecs, f)
		if err != nil {
			return nil, err
		}
	}
	if f := r.FormValue("to"); len(f) > 0 {
		to, err = time.Parse(tsdbFormatSecs, f)
		if err != nil {
			return nil, err
		}
	}
	intervals := 1
	if i := r.FormValue("intervals"); len(i) > 0 {
		intervals, err = strconv.Atoi(r.FormValue("intervals"))
		if err != nil {
			return nil, err
		}
		if intervals < 1 {
			return nil, fmt.Errorf("must be > 0 intervals")
		}
	}
	incidentID := 42
	if incident := r.FormValue("incidentId"); len(incident) > 0 {
		incidentID, err = strconv.Atoi(incident)
		if err != nil {
			return nil, err
		}
	}
	if fz, tz := from.IsZero(), to.IsZero(); fz && tz {
		from = time.Now()
	} else if fz && !tz {
		return nil, fmt.Errorf("cannot specify to without from")
	} else if !fz && tz && intervals > 1 {
		return nil, fmt.Errorf("cannot specify intervals without from and to")
	}

	c, a, hash, err := buildConfig(r)
	if err != nil {
		return nil, err
	}

	ch := make(chan int)
	errch := make(chan error, intervals)
	resch := make(chan *ruleResult, intervals)
	var wg sync.WaitGroup
	diff := -from.Sub(to)
	if intervals > 1 {
		diff /= time.Duration(intervals - 1)
	}
	worker := func() {
		wg.Add(1)
		for interval := range ch {
			t.Step(fmt.Sprintf("interval %v", interval), func(t miniprofiler.Timer) {
				now := from.Add(diff * time.Duration(interval))
				res, err := procRule(t, c, a, now, interval != 0, r.FormValue("email"), r.FormValue("template_group"), incidentID)
				resch <- res
				errch <- err
			})
		}
		defer wg.Done()
	}
	for i := 0; i < 20; i++ {
		go worker()
	}
	for i := 0; i < intervals; i++ {
		ch <- i
	}
	close(ch)
	wg.Wait()
	close(errch)
	close(resch)
	type Result struct {
		Group  models.AlertKey
		Result *models.Event
	}
	type Set struct {
		Critical, Warning, Normal int
		Time                      string
		Results                   []*Result `json:",omitempty"`
	}
	type History struct {
		Time, EndTime time.Time
		Status        string
	}
	type Histories struct {
		History []*History
	}

	ret := struct {
		Errors       []string `json:",omitempty"`
		Warnings     []string `json:",omitempty"`
		Sets         []*Set
		AlertHistory map[models.AlertKey]*Histories
		*models.RenderedTemplates
		Notifications       map[string]*conf.PreparedNotifications
		ActionNotifications map[string]map[string]*conf.PreparedNotifications
		Data                interface{} `json:",omitempty"`
		Hash                string
	}{
		AlertHistory: make(map[models.AlertKey]*Histories),
		Hash:         hash,
	}
	for err := range errch {
		if err == nil {
			continue
		}
		ret.Errors = append(ret.Errors, err.Error())
	}
	for res := range resch {
		if res == nil {
			continue
		}
		set := Set{
			Critical: len(res.Criticals),
			Warning:  len(res.Warnings),
			Normal:   len(res.Normals),
			Time:     res.Time.Format(tsdbFormatSecs),
		}
		if res.Data != nil {
			ret.RenderedTemplates = res.RenderedTemplates
			ret.Notifications = res.Notifications
			ret.ActionNotifications = res.ActionNotifications
			ret.Data = res.Data
			for k, v := range res.Result {
				set.Results = append(set.Results, &Result{
					Group:  k,
					Result: v,
				})
			}
			slice.Sort(set.Results, func(i, j int) bool {
				a := set.Results[i]
				b := set.Results[j]
				if a.Result.Status != b.Result.Status {
					return a.Result.Status > b.Result.Status
				}
				return a.Group < b.Group
			})
		}
		for k, v := range res.Result {
			if ret.AlertHistory[k] == nil {
				ret.AlertHistory[k] = new(Histories)
			}
			h := ret.AlertHistory[k]
			h.History = append(h.History, &History{
				Time:   v.Time,
				Status: v.Status.String(),
			})
		}
		ret.Sets = append(ret.Sets, &set)
		ret.Warnings = append(ret.Warnings, res.Warning...)
	}
	slice.Sort(ret.Sets, func(i, j int) bool {
		return ret.Sets[i].Time < ret.Sets[j].Time
	})
	for _, histories := range ret.AlertHistory {
		hist := histories.History
		slice.Sort(hist, func(i, j int) bool {
			return hist[i].Time.Before(hist[j].Time)
		})
		for i := 1; i < len(hist); i++ {
			if i < len(hist)-1 && hist[i].Status == hist[i-1].Status {
				hist = append(hist[:i], hist[i+1:]...)
				i--
			}
		}
		for i, h := range hist[:len(hist)-1] {
			h.EndTime = hist[i+1].Time
		}
		histories.History = hist[:len(hist)-1]
	}
	return &ret, nil
}

func buildConfig(r *http.Request) (c conf.RuleConfProvider, a *conf.Alert, hash string, err error) {
	config, err := ioutil.ReadAll(r.Body)
	if err != nil {
		return nil, nil, "", err
	}
	c, err = rule.NewConf("Test Config", schedule.SystemConf.EnabledBackends(), schedule.SystemConf.GetRuleVars(), string(config))
	if err != nil {
		return nil, nil, "", err
	}
	hash, err = sched.DefaultSched.DataAccess.Configs().SaveTempConfig(string(config))
	if err != nil {
		return nil, nil, "", err
	}
	alertName := r.FormValue("alert")
	if alertName == "" {
		return nil, nil, "", fmt.Errorf("must supply alert to run")
	}
	a = c.GetAlert(alertName)
	if a == nil {
		return nil, nil, "", fmt.Errorf("alert %s not found", alertName)
	}
	return c, a, hash, nil

}


text:
(function() {
  async function one(x) {
    await two(x);
  }

  async function two(x) {
    await x;
    throw new Error();
  }

  async function test(f) {
    try {
      await f(1);
      assertUnreachable();
    } catch (e) {
      assertInstanceof(e, Error);
      assertMatches(/Error.+at two.+at async one.+at async test/ms, e.stack);
    }
  }

  assertPromiseResult((async () => {
    %PrepareFunctionForOptimization(one);
    %PrepareFunctionForOptimization(two);
    await test(one);
    await test(one);
    %OptimizeFunctionOnNextCall(two);
    await test(one);
    %OptimizeFunctionOnNextCall(one);
    await test(one);
  })());
})();

// Basic test with an implicit throw (via ToNumber on Symbol).
(function() {
  async function one(x) {
    return await two(x);
  }

  async function two(x) {
    await x;
    return +x;  // This will raise a TypeError.
  }

  async function test(f) {
    try {
      await f(Symbol());
      assertUnreachable();
    } catch (e) {
      assertInstanceof(e, TypeError);
      assertMatches(/TypeError.+at two.+at async one.+at async test/ms, e.stack);
    }
  }

  assertPromiseResult((async() => {
    %PrepareFunctionForOptimization(one);
    %PrepareFunctionForOptimization(two);
    await test(one);
    await test(one);
    %OptimizeFunctionOnNextCall(two);
    await test(one);
    %OptimizeFunctionOnNextCall(one);
    await test(one);
  })());
})();

// Basic test with throw in inlined function.
(function() {
  function throwError() {
    throw new Error();
  }

  async function one(x) {
    return await two(x);
  }

  async function two(x) {
    await x;
    return throwError();
  }

  async function test(f) {
    try {
      await f(1);
      assertUnreachable();
    } catch (e) {
      assertInstanceof(e, Error);
      assertMatches(/Error.+at two.+at async one.+at async test/ms, e.stack);
    }
  }

  assertPromiseResult((async() => {
    %PrepareFunctionForOptimization(one);
    %PrepareFunctionForOptimization(two);
    await test(one);
    await test(one);
    %OptimizeFunctionOnNextCall(two);
    await test(one);
    %OptimizeFunctionOnNextCall(one);
    await test(one);
  })());
})();

// Basic test with async function inlined into sync function.
(function() {
  function callOne(x) {
    return one(x);
  }

  function callTwo(x) {
    return two(x);
  }

  async function one(x) {
    return await callTwo(x);
  }

  async function two(x) {
    await x;
    throw new Error();
  }

  async function test(f) {
    try {
      await f(1);
      assertUnreachable();
    } catch (e) {
      assertInstanceof(e, Error);
      assertMatches(/Error.+at two.+at async one.+at async test/ms, e.stack);
    }
  }

  assertPromiseResult((async() => {
    %PrepareFunctionForOptimization(callOne);
    %PrepareFunctionForOptimization(callTwo);
    await test(callOne);
    await test(callOne);
    %OptimizeFunctionOnNextCall(callTwo);
    await test(callOne);
    %OptimizeFunctionOnNextCall(callOne);
    await test(callOne);
  })());
})();

// Basic test with async functions and promises chained via
// Promise.prototype.then(), which should still work following
// the generic chain upwards.
(function() {
  async function one(x) {
    return await two(x).then(x => x);
  }

  async function two(x) {
    await x.then(x => x);
    throw new Error();
  }

  async function test(f) {
    try {
      await f(Promise.resolve(1));
      assertUnreachable();
    } catch (e) {
      assertInstanceof(e, Error);
      assertMatches(/Error.+at two.+at async one.+at async test/ms, e.stack);
    }
  }

  assertPromiseResult((async() => {
    %PrepareFunctionForOptimization(one);
    %PrepareFunctionForOptimization(two);
    await test(one);
    await test(one);
    %OptimizeFunctionOnNextCall(two);
    await test(one);
    %OptimizeFunctionOnNextCall(one);
    await test(one);
  })());
})();

// Basic test for async generators called from async
// functions with an explicit throw.
(function() {
  async function one(x) {
    for await (const y of two(x)) {}
  }

  async function* two(x) {
    await x;
    throw new Error();
  }

  async function test(f) {
    try {
      await f(1);
      assertUnreachable();
    } catch (e) {
      assertInstanceof(e, Error);
      assertMatches(/Error.+at two.+at async one.+at async test/ms, e.stack);
    }
  }

  assertPromiseResult((async () => {
    %PrepareFunctionForOptimization(one);
    %PrepareFunctionForOptimization(two);
    await test(one);
    await test(one);
    %OptimizeFunctionOnNextCall(two);
    await test(one);
    %OptimizeFunctionOnNextCall(one);
    await test(one);
  })());
})();

// Basic test for async functions called from async
// generators with an explicit throw.
(function() {
  async function* one(x) {
    await two(x);
  }

  async function two(x) {
    await x;
    throw new Error();
  }

  async function test(f) {
    try {
      for await (const x of f(1)) {}
      assertUnreachable();
    } catch (e) {
      assertInstanceof(e, Error);
      assertMatches(/Error.+at two.+at async one.+at async test/ms, e.stack);
    }
  }

  assertPromiseResult((async () => {
    %PrepareFunctionForOptimization(one);
    %PrepareFunctionForOptimization(two);
    await test(one);
    await test(one);
    %OptimizeFunctionOnNextCall(two);
    await test(one);
    %OptimizeFunctionOnNextCall(one);
    await test(one);
  })());
})();

// Basic test for async functions called from async
// generators with an explicit throw (with yield).
(function() {
  async function* one(x) {
    yield two(x);
  }

  async function two(x) {
    await x;
    throw new Error();
  }

  async function test(f) {
    try {
      for await (const x of f(1)) {}
      assertUnreachable();
    } catch (e) {
      assertInstanceof(e, Error);
      assertMatches(/Error.+at two.+at async one.+at async test/ms, e.stack);
    }
  }

  assertPromiseResult((async () => {
    %PrepareFunctionForOptimization(one);
    %PrepareFunctionForOptimization(two);
    await test(one);
    await test(one);
    %OptimizeFunctionOnNextCall(two);
    await test(one);
    %OptimizeFunctionOnNextCall(one);
    await test(one);
  })());
})();

// Basic test to check that we also follow initial
// promise chains created via Promise#then().
(function() {
  async function one(p) {
    return await p.then(two);
  }

  function two() {
    throw new Error();
  }

  async function test(f) {
    try {
      await f(Promise.resolve());
      assertUnreachable();
    } catch (e) {
      assertInstanceof(e, Error);
      assertMatches(/Error.+at two.+at async one.+at async test/ms, e.stack);
    }
  }

  assertPromiseResult((async () => {
    %PrepareFunctionForOptimization(one);
    %PrepareFunctionForOptimization(two);
    await test(one);
    await test(one);
    %OptimizeFunctionOnNextCall(two);
    await test(one);
    %OptimizeFunctionOnNextCall(one);
    await test(one);
  })());
})();


text:
<?xml version="1.0" encoding="UTF-8"?>

<channel name="xfce4-power-manager" version="1.0">
  <property name="xfce4-power-manager" type="empty">
    <property name="critical-power-action" type="uint" value="4"/>
    <property name="lid-action-on-battery" type="uint" value="3"/>
    <property name="inactivity-on-battery" type="uint" value="14"/>
    <property name="dpms-on-battery-sleep" type="uint" value="1"/>
    <property name="dpms-on-battery-off" type="uint" value="2"/>
    <property name="brightness-on-battery" type="uint" value="11"/>
    <property name="dpms-on-ac-sleep" type="uint" value="0"/>
    <property name="dpms-on-ac-off" type="uint" value="0"/>
    <property name="brightness-on-ac" type="uint" value="120"/>
    <property name="lock-screen-suspend-hibernate" type="bool" value="true"/>
    <property name="brightness-level-on-ac" type="uint" value="1"/>
    <property name="brightness-level-on-battery" type="uint" value="1"/>
    <property name="show-tray-icon" type="int" value="1"/>
    <property name="power-button-action" type="uint" value="3"/>
    <property name="critical-power-level" type="uint" value="7"/>
    <property name="presentation-mode" type="bool" value="false"/>
    <property name="dpms-enabled" type="bool" value="true"/>
    <property name="inactivity-sleep-mode" type="string" value="Suspend"/>
    <property name="power-save-on-battery" type="bool" value="true"/>
    <property name="brightness-switch-restore-on-exit" type="int" value="-1"/>
    <property name="brightness-switch" type="int" value="0"/>
    <property name="blank-on-ac" type="int" value="0"/>
  </property>
</channel>


text:
class Categories
  class Category
    attr_reader :id, :name

    def initialize(id, name)
      @id = id
      @name = name
    end
  end

  ALL = [
    HEREANDNOW = Category.new("hereandnow", "Here & Now"),
    LIFE = Category.new("life", "Life"),
    ART = Category.new("art", "Art"),
    SCIENCE = Category.new("science", "Science"),
    FILM = Category.new("film", "Film"),
    THEATRE = Category.new("theatre", "Theatre")
  ]

  def self.fetch(id)
    ALL.select { |c| c.id == id }.first
  end
end


text:
/**
 * https://github.com/gruntjs/grunt-contrib-copy
 *
 * Copy files from src to dist folder if they need not be altered (like font files).
 */

'use strict';
module.exports = {

	fonts: {
		expand: true,
		cwd: '<%= package.basedir %>/assets/src/fonts/',
		src: '**',
		dest: '<%= package.basedir %>/assets/dist/fonts/',
		flatten: false,
		filter: 'isFile',
	}
};


text:
package com.cassianetworks.fall.views;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Rect;
import android.os.Build;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.TranslateAnimation;
import android.widget.ScrollView;

/**
 * Created by on 2015/7/24./
 */
public class DampScrollView extends ScrollView {
    //scrollView下的控件
    private View inner;

    private float y;

    //保存状态的矩形框
    private Rect normal = new Rect();

    //是否要计算
    private boolean isCount = false;

    @SuppressLint("NewApi")
    public DampScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
        delEdge();
    }

    //加载完布局文件之后调用
    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        if (getChildCount() > 0) {
            //获取控件
            inner = getChildAt(0);
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if (inner != null) {
            commOnTouchEvent(ev);
        }
        return super.onTouchEvent(ev);
    }

    //处理触摸事件
    public void commOnTouchEvent(MotionEvent ev) {
        int action = ev.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                break;
            case MotionEvent.ACTION_UP:
                //是不是需要动画
                if (isNeedAnimation()) {
                    animation();
                    isCount = false;
                }
                break;
            case MotionEvent.ACTION_MOVE:
                final float preY = y;
                float nowY = ev.getY();
                int deltaY = (int) (preY - nowY);
                if (!isCount) {
                    deltaY = 0;
                }

                y = nowY;
                if (isNeedMove()) {
                    if (normal.isEmpty()) {
                        normal.set(inner.getLeft(), inner.getTop(), inner.getRight(), inner.getBottom());
                    }
                    inner.layout(inner.getLeft(), inner.getTop() - deltaY / 2, inner.getRight(), inner.getBottom() - deltaY / 2);
                }
                isCount = true;
                break;

            default:
                break;
        }
    }

    public void animation() {
        TranslateAnimation ta = new TranslateAnimation(0, 0, inner.getTop(), normal.top);
        ta.setDuration(200);
        inner.startAnimation(ta);
        inner.layout(normal.left, normal.top, normal.right, normal.bottom);
        normal.setEmpty();

    }

    // return left >= right || top >= bottom;
    public boolean isNeedAnimation() {
        return !normal.isEmpty();
    }

    public boolean isNeedMove() {
        int offset = inner.getMeasuredHeight() - getHeight();
        int scrollY = getScrollY();
        return scrollY == 0 || scrollY == offset;
    }

    @Override
    protected int computeScrollDeltaToGetChildRectOnScreen(Rect rect) {
        return 0;
    }

    private void delEdge() {
        if (Build.VERSION.SDK_INT >= 9) {
            this.setOverScrollMode(View.OVER_SCROLL_NEVER);
        }
    }
}


text:
/* your app css goes here */

body {

}