repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
tomtor/QGIS
src/core/qgsogcutils.cpp
127592
/*************************************************************************** qgsogcutils.cpp --------------------- begin : March 2013 copyright : (C) 2013 by Martin Dobias email : wonder dot sk at gmail dot com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "qgsogcutils.h" #include "qgsexpression.h" #include "qgsexpressionnodeimpl.h" #include "qgsexpressionfunction.h" #include "qgsexpression_p.h" #include "qgsgeometry.h" #include "qgswkbptr.h" #include "qgscoordinatereferencesystem.h" #include "qgsrectangle.h" #include "qgsvectorlayer.h" #include "qgsexpressioncontextutils.h" #include "qgslogger.h" #include "qgsstringutils.h" #include <QColor> #include <QStringList> #include <QTextStream> #include <QObject> #include <QRegularExpression> #ifndef Q_OS_WIN #include <netinet/in.h> #else #include <winsock.h> #endif #define GML_NAMESPACE QStringLiteral( "http://www.opengis.net/gml" ) #define GML32_NAMESPACE QStringLiteral( "http://www.opengis.net/gml/3.2" ) #define OGC_NAMESPACE QStringLiteral( "http://www.opengis.net/ogc" ) #define FES_NAMESPACE QStringLiteral( "http://www.opengis.net/fes/2.0" ) QgsOgcUtilsExprToFilter::QgsOgcUtilsExprToFilter( QDomDocument &doc, QgsOgcUtils::GMLVersion gmlVersion, QgsOgcUtils::FilterVersion filterVersion, const QString &geometryName, const QString &srsName, bool honourAxisOrientation, bool invertAxisOrientation ) : mDoc( doc ) , mGMLUsed( false ) , mGMLVersion( gmlVersion ) , mFilterVersion( filterVersion ) , mGeometryName( geometryName ) , mSrsName( srsName ) , mInvertAxisOrientation( invertAxisOrientation ) , mFilterPrefix( ( filterVersion == QgsOgcUtils::FILTER_FES_2_0 ) ? "fes" : "ogc" ) , mPropertyName( ( filterVersion == QgsOgcUtils::FILTER_FES_2_0 ) ? "ValueReference" : "PropertyName" ) , mGeomId( 1 ) { QgsCoordinateReferenceSystem crs; if ( !mSrsName.isEmpty() ) crs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( mSrsName ); if ( crs.isValid() ) { if ( honourAxisOrientation && crs.hasAxisInverted() ) { mInvertAxisOrientation = !mInvertAxisOrientation; } } } QgsGeometry QgsOgcUtils::geometryFromGML( const QDomNode &geometryNode, const Context &context ) { QDomElement geometryTypeElement = geometryNode.toElement(); QString geomType = geometryTypeElement.tagName(); QgsGeometry geometry; if ( !( geomType == QLatin1String( "Point" ) || geomType == QLatin1String( "LineString" ) || geomType == QLatin1String( "Polygon" ) || geomType == QLatin1String( "MultiPoint" ) || geomType == QLatin1String( "MultiLineString" ) || geomType == QLatin1String( "MultiPolygon" ) || geomType == QLatin1String( "Box" ) || geomType == QLatin1String( "Envelope" ) ) ) { const QDomNode geometryChild = geometryNode.firstChild(); if ( geometryChild.isNull() ) { return geometry; } geometryTypeElement = geometryChild.toElement(); geomType = geometryTypeElement.tagName(); } if ( !( geomType == QLatin1String( "Point" ) || geomType == QLatin1String( "LineString" ) || geomType == QLatin1String( "Polygon" ) || geomType == QLatin1String( "MultiPoint" ) || geomType == QLatin1String( "MultiLineString" ) || geomType == QLatin1String( "MultiPolygon" ) || geomType == QLatin1String( "Box" ) || geomType == QLatin1String( "Envelope" ) ) ) return QgsGeometry(); if ( geomType == QLatin1String( "Point" ) ) { geometry = geometryFromGMLPoint( geometryTypeElement ); } else if ( geomType == QLatin1String( "LineString" ) ) { geometry = geometryFromGMLLineString( geometryTypeElement ); } else if ( geomType == QLatin1String( "Polygon" ) ) { geometry = geometryFromGMLPolygon( geometryTypeElement ); } else if ( geomType == QLatin1String( "MultiPoint" ) ) { geometry = geometryFromGMLMultiPoint( geometryTypeElement ); } else if ( geomType == QLatin1String( "MultiLineString" ) ) { geometry = geometryFromGMLMultiLineString( geometryTypeElement ); } else if ( geomType == QLatin1String( "MultiPolygon" ) ) { geometry = geometryFromGMLMultiPolygon( geometryTypeElement ); } else if ( geomType == QLatin1String( "Box" ) ) { geometry = QgsGeometry::fromRect( rectangleFromGMLBox( geometryTypeElement ) ); } else if ( geomType == QLatin1String( "Envelope" ) ) { geometry = QgsGeometry::fromRect( rectangleFromGMLEnvelope( geometryTypeElement ) ); } else //unknown type { return geometry; } // Handle srsName if context has information about the layer and the transformation context if ( context.layer ) { QgsCoordinateReferenceSystem geomSrs; if ( geometryTypeElement.hasAttribute( QStringLiteral( "srsName" ) ) ) { QString srsName { geometryTypeElement.attribute( QStringLiteral( "srsName" ) ) }; // The logic here follows WFS GeoServer conventions from https://docs.geoserver.org/latest/en/user/services/wfs/axis_order.html const bool ignoreAxisOrientation { srsName.startsWith( QLatin1String( "http://www.opengis.net/gml/srs/" ) ) || srsName.startsWith( QLatin1String( "EPSG:" ) ) }; // GDAL does not recognise http://www.opengis.net/gml/srs/epsg.xml#4326 but it does // http://www.opengis.net/def/crs/EPSG/0/4326 so, let's try that if ( srsName.startsWith( QLatin1String( "http://www.opengis.net/gml/srs/" ) ) ) { const auto parts { srsName.split( QRegularExpression( QStringLiteral( R"raw(/|#|\.)raw" ) ) ) }; if ( parts.length() == 10 ) { srsName = QStringLiteral( "http://www.opengis.net/def/crs/%1/0/%2" ).arg( parts[ 7 ].toUpper(), parts[ 9 ] ); } } geomSrs.createFromUserInput( srsName ); if ( geomSrs.isValid() && geomSrs != context.layer->crs() ) { if ( geomSrs.hasAxisInverted() && ! ignoreAxisOrientation ) { geometry.get()->swapXy(); } const QgsCoordinateTransform transformer { geomSrs, context.layer->crs(), context.transformContext }; try { const Qgis::GeometryOperationResult result = geometry.transform( transformer ); if ( result != Qgis::GeometryOperationResult::Success ) { QgsDebugMsgLevel( QStringLiteral( "Error transforming geometry: %1" ).arg( qgsEnumValueToKey( result ) ), 2 ); } } catch ( QgsCsException & ) { QgsDebugMsgLevel( QStringLiteral( "CS error transforming geometry" ), 2 ); } } } } return geometry; } QgsGeometry QgsOgcUtils::geometryFromGML( const QString &xmlString, const Context &context ) { // wrap the string into a root tag to have "gml" namespace (and also as a default namespace) const QString xml = QStringLiteral( "<tmp xmlns=\"%1\" xmlns:gml=\"%1\">%2</tmp>" ).arg( GML_NAMESPACE, xmlString ); QDomDocument doc; if ( !doc.setContent( xml, true ) ) return QgsGeometry(); return geometryFromGML( doc.documentElement().firstChildElement(), context ); } QgsGeometry QgsOgcUtils::geometryFromGMLPoint( const QDomElement &geometryElement ) { QgsPolylineXY pointCoordinate; const QDomNodeList coordList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "coordinates" ) ); if ( !coordList.isEmpty() ) { const QDomElement coordElement = coordList.at( 0 ).toElement(); if ( readGMLCoordinates( pointCoordinate, coordElement ) != 0 ) { return QgsGeometry(); } } else { const QDomNodeList posList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "pos" ) ); if ( posList.size() < 1 ) { return QgsGeometry(); } const QDomElement posElement = posList.at( 0 ).toElement(); if ( readGMLPositions( pointCoordinate, posElement ) != 0 ) { return QgsGeometry(); } } if ( pointCoordinate.empty() ) { return QgsGeometry(); } QgsPolylineXY::const_iterator point_it = pointCoordinate.constBegin(); char e = htonl( 1 ) != 1; double x = point_it->x(); double y = point_it->y(); const int size = 1 + sizeof( int ) + 2 * sizeof( double ); QgsWkbTypes::Type type = QgsWkbTypes::Point; unsigned char *wkb = new unsigned char[size]; int wkbPosition = 0; //current offset from wkb beginning (in bytes) memcpy( &( wkb )[wkbPosition], &e, 1 ); wkbPosition += 1; memcpy( &( wkb )[wkbPosition], &type, sizeof( int ) ); wkbPosition += sizeof( int ); memcpy( &( wkb )[wkbPosition], &x, sizeof( double ) ); wkbPosition += sizeof( double ); memcpy( &( wkb )[wkbPosition], &y, sizeof( double ) ); QgsGeometry g; g.fromWkb( wkb, size ); return g; } QgsGeometry QgsOgcUtils::geometryFromGMLLineString( const QDomElement &geometryElement ) { QgsPolylineXY lineCoordinates; const QDomNodeList coordList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "coordinates" ) ); if ( !coordList.isEmpty() ) { const QDomElement coordElement = coordList.at( 0 ).toElement(); if ( readGMLCoordinates( lineCoordinates, coordElement ) != 0 ) { return QgsGeometry(); } } else { const QDomNodeList posList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "posList" ) ); if ( posList.size() < 1 ) { return QgsGeometry(); } const QDomElement posElement = posList.at( 0 ).toElement(); if ( readGMLPositions( lineCoordinates, posElement ) != 0 ) { return QgsGeometry(); } } char e = htonl( 1 ) != 1; const int size = 1 + 2 * sizeof( int ) + lineCoordinates.size() * 2 * sizeof( double ); QgsWkbTypes::Type type = QgsWkbTypes::LineString; unsigned char *wkb = new unsigned char[size]; int wkbPosition = 0; //current offset from wkb beginning (in bytes) double x, y; int nPoints = lineCoordinates.size(); //fill the contents into *wkb memcpy( &( wkb )[wkbPosition], &e, 1 ); wkbPosition += 1; memcpy( &( wkb )[wkbPosition], &type, sizeof( int ) ); wkbPosition += sizeof( int ); memcpy( &( wkb )[wkbPosition], &nPoints, sizeof( int ) ); wkbPosition += sizeof( int ); QgsPolylineXY::const_iterator iter; for ( iter = lineCoordinates.constBegin(); iter != lineCoordinates.constEnd(); ++iter ) { x = iter->x(); y = iter->y(); memcpy( &( wkb )[wkbPosition], &x, sizeof( double ) ); wkbPosition += sizeof( double ); memcpy( &( wkb )[wkbPosition], &y, sizeof( double ) ); wkbPosition += sizeof( double ); } QgsGeometry g; g.fromWkb( wkb, size ); return g; } QgsGeometry QgsOgcUtils::geometryFromGMLPolygon( const QDomElement &geometryElement ) { //read all the coordinates (as QgsPoint) into memory. Each linear ring has an entry in the vector QgsMultiPolylineXY ringCoordinates; //read coordinates for outer boundary QgsPolylineXY exteriorPointList; const QDomNodeList outerBoundaryList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "outerBoundaryIs" ) ); if ( !outerBoundaryList.isEmpty() ) //outer ring is necessary { QDomElement coordinatesElement = outerBoundaryList.at( 0 ).firstChild().firstChild().toElement(); if ( coordinatesElement.isNull() ) { return QgsGeometry(); } if ( readGMLCoordinates( exteriorPointList, coordinatesElement ) != 0 ) { return QgsGeometry(); } ringCoordinates.push_back( exteriorPointList ); //read coordinates for inner boundary const QDomNodeList innerBoundaryList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "innerBoundaryIs" ) ); for ( int i = 0; i < innerBoundaryList.size(); ++i ) { QgsPolylineXY interiorPointList; coordinatesElement = innerBoundaryList.at( i ).firstChild().firstChild().toElement(); if ( coordinatesElement.isNull() ) { return QgsGeometry(); } if ( readGMLCoordinates( interiorPointList, coordinatesElement ) != 0 ) { return QgsGeometry(); } ringCoordinates.push_back( interiorPointList ); } } else { //read coordinates for exterior const QDomNodeList exteriorList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "exterior" ) ); if ( exteriorList.size() < 1 ) //outer ring is necessary { return QgsGeometry(); } const QDomElement posElement = exteriorList.at( 0 ).firstChild().firstChild().toElement(); if ( posElement.isNull() ) { return QgsGeometry(); } if ( readGMLPositions( exteriorPointList, posElement ) != 0 ) { return QgsGeometry(); } ringCoordinates.push_back( exteriorPointList ); //read coordinates for inner boundary const QDomNodeList interiorList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "interior" ) ); for ( int i = 0; i < interiorList.size(); ++i ) { QgsPolylineXY interiorPointList; const QDomElement posElement = interiorList.at( i ).firstChild().firstChild().toElement(); if ( posElement.isNull() ) { return QgsGeometry(); } // Note: readGMLPositions returns true on errors and false on success if ( readGMLPositions( interiorPointList, posElement ) ) { return QgsGeometry(); } ringCoordinates.push_back( interiorPointList ); } } //calculate number of bytes to allocate int nrings = ringCoordinates.size(); if ( nrings < 1 ) return QgsGeometry(); int npoints = 0;//total number of points for ( QgsMultiPolylineXY::const_iterator it = ringCoordinates.constBegin(); it != ringCoordinates.constEnd(); ++it ) { npoints += it->size(); } const int size = 1 + 2 * sizeof( int ) + nrings * sizeof( int ) + 2 * npoints * sizeof( double ); QgsWkbTypes::Type type = QgsWkbTypes::Polygon; unsigned char *wkb = new unsigned char[size]; //char e = QgsApplication::endian(); char e = htonl( 1 ) != 1; int wkbPosition = 0; //current offset from wkb beginning (in bytes) int nPointsInRing = 0; double x, y; //fill the contents into *wkb memcpy( &( wkb )[wkbPosition], &e, 1 ); wkbPosition += 1; memcpy( &( wkb )[wkbPosition], &type, sizeof( int ) ); wkbPosition += sizeof( int ); memcpy( &( wkb )[wkbPosition], &nrings, sizeof( int ) ); wkbPosition += sizeof( int ); for ( QgsMultiPolylineXY::const_iterator it = ringCoordinates.constBegin(); it != ringCoordinates.constEnd(); ++it ) { nPointsInRing = it->size(); memcpy( &( wkb )[wkbPosition], &nPointsInRing, sizeof( int ) ); wkbPosition += sizeof( int ); //iterate through the string list converting the strings to x-/y- doubles QgsPolylineXY::const_iterator iter; for ( iter = it->begin(); iter != it->end(); ++iter ) { x = iter->x(); y = iter->y(); //qWarning("currentCoordinate: " + QString::number(x) + " // " + QString::number(y)); memcpy( &( wkb )[wkbPosition], &x, sizeof( double ) ); wkbPosition += sizeof( double ); memcpy( &( wkb )[wkbPosition], &y, sizeof( double ) ); wkbPosition += sizeof( double ); } } QgsGeometry g; g.fromWkb( wkb, size ); return g; } QgsGeometry QgsOgcUtils::geometryFromGMLMultiPoint( const QDomElement &geometryElement ) { QgsPolylineXY pointList; QgsPolylineXY currentPoint; const QDomNodeList pointMemberList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "pointMember" ) ); if ( pointMemberList.size() < 1 ) { return QgsGeometry(); } QDomNodeList pointNodeList; // coordinates or pos element QDomNodeList coordinatesList; QDomNodeList posList; for ( int i = 0; i < pointMemberList.size(); ++i ) { //<Point> element pointNodeList = pointMemberList.at( i ).toElement().elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "Point" ) ); if ( pointNodeList.size() < 1 ) { continue; } //<coordinates> element coordinatesList = pointNodeList.at( 0 ).toElement().elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "coordinates" ) ); if ( !coordinatesList.isEmpty() ) { currentPoint.clear(); if ( readGMLCoordinates( currentPoint, coordinatesList.at( 0 ).toElement() ) != 0 ) { continue; } if ( currentPoint.empty() ) { continue; } pointList.push_back( ( *currentPoint.begin() ) ); continue; } else { //<pos> element posList = pointNodeList.at( 0 ).toElement().elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "pos" ) ); if ( posList.size() < 1 ) { continue; } currentPoint.clear(); if ( readGMLPositions( currentPoint, posList.at( 0 ).toElement() ) != 0 ) { continue; } if ( currentPoint.empty() ) { continue; } pointList.push_back( ( *currentPoint.begin() ) ); } } int nPoints = pointList.size(); //number of points if ( nPoints < 1 ) return QgsGeometry(); //calculate the required wkb size const int size = 1 + 2 * sizeof( int ) + pointList.size() * ( 2 * sizeof( double ) + 1 + sizeof( int ) ); QgsWkbTypes::Type type = QgsWkbTypes::MultiPoint; unsigned char *wkb = new unsigned char[size]; //fill the wkb content char e = htonl( 1 ) != 1; int wkbPosition = 0; //current offset from wkb beginning (in bytes) double x, y; memcpy( &( wkb )[wkbPosition], &e, 1 ); wkbPosition += 1; memcpy( &( wkb )[wkbPosition], &type, sizeof( int ) ); wkbPosition += sizeof( int ); memcpy( &( wkb )[wkbPosition], &nPoints, sizeof( int ) ); wkbPosition += sizeof( int ); type = QgsWkbTypes::Point; for ( QgsPolylineXY::const_iterator it = pointList.constBegin(); it != pointList.constEnd(); ++it ) { memcpy( &( wkb )[wkbPosition], &e, 1 ); wkbPosition += 1; memcpy( &( wkb )[wkbPosition], &type, sizeof( int ) ); wkbPosition += sizeof( int ); x = it->x(); memcpy( &( wkb )[wkbPosition], &x, sizeof( double ) ); wkbPosition += sizeof( double ); y = it->y(); memcpy( &( wkb )[wkbPosition], &y, sizeof( double ) ); wkbPosition += sizeof( double ); } QgsGeometry g; g.fromWkb( wkb, size ); return g; } QgsGeometry QgsOgcUtils::geometryFromGMLMultiLineString( const QDomElement &geometryElement ) { //geoserver has //<gml:MultiLineString> //<gml:lineStringMember> //<gml:LineString> //mapserver has directly //<gml:MultiLineString //<gml:LineString QList< QgsPolylineXY > lineCoordinates; //first list: lines, second list: points of one line QDomElement currentLineStringElement; QDomNodeList currentCoordList; QDomNodeList currentPosList; const QDomNodeList lineStringMemberList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "lineStringMember" ) ); if ( !lineStringMemberList.isEmpty() ) //geoserver { for ( int i = 0; i < lineStringMemberList.size(); ++i ) { const QDomNodeList lineStringNodeList = lineStringMemberList.at( i ).toElement().elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "LineString" ) ); if ( lineStringNodeList.size() < 1 ) { return QgsGeometry(); } currentLineStringElement = lineStringNodeList.at( 0 ).toElement(); currentCoordList = currentLineStringElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "coordinates" ) ); if ( !currentCoordList.isEmpty() ) { QgsPolylineXY currentPointList; if ( readGMLCoordinates( currentPointList, currentCoordList.at( 0 ).toElement() ) != 0 ) { return QgsGeometry(); } lineCoordinates.push_back( currentPointList ); } else { currentPosList = currentLineStringElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "posList" ) ); if ( currentPosList.size() < 1 ) { return QgsGeometry(); } QgsPolylineXY currentPointList; if ( readGMLPositions( currentPointList, currentPosList.at( 0 ).toElement() ) != 0 ) { return QgsGeometry(); } lineCoordinates.push_back( currentPointList ); } } } else { const QDomNodeList lineStringList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "LineString" ) ); if ( !lineStringList.isEmpty() ) //mapserver { for ( int i = 0; i < lineStringList.size(); ++i ) { currentLineStringElement = lineStringList.at( i ).toElement(); currentCoordList = currentLineStringElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "coordinates" ) ); if ( !currentCoordList.isEmpty() ) { QgsPolylineXY currentPointList; if ( readGMLCoordinates( currentPointList, currentCoordList.at( 0 ).toElement() ) != 0 ) { return QgsGeometry(); } lineCoordinates.push_back( currentPointList ); return QgsGeometry(); } else { currentPosList = currentLineStringElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "posList" ) ); if ( currentPosList.size() < 1 ) { return QgsGeometry(); } QgsPolylineXY currentPointList; if ( readGMLPositions( currentPointList, currentPosList.at( 0 ).toElement() ) != 0 ) { return QgsGeometry(); } lineCoordinates.push_back( currentPointList ); } } } else { return QgsGeometry(); } } int nLines = lineCoordinates.size(); if ( nLines < 1 ) return QgsGeometry(); //calculate the required wkb size int size = ( lineCoordinates.size() + 1 ) * ( 1 + 2 * sizeof( int ) ); for ( QList< QgsPolylineXY >::const_iterator it = lineCoordinates.constBegin(); it != lineCoordinates.constEnd(); ++it ) { size += it->size() * 2 * sizeof( double ); } QgsWkbTypes::Type type = QgsWkbTypes::MultiLineString; unsigned char *wkb = new unsigned char[size]; //fill the wkb content char e = htonl( 1 ) != 1; int wkbPosition = 0; //current offset from wkb beginning (in bytes) int nPoints; //number of points in a line double x, y; memcpy( &( wkb )[wkbPosition], &e, 1 ); wkbPosition += 1; memcpy( &( wkb )[wkbPosition], &type, sizeof( int ) ); wkbPosition += sizeof( int ); memcpy( &( wkb )[wkbPosition], &nLines, sizeof( int ) ); wkbPosition += sizeof( int ); type = QgsWkbTypes::LineString; for ( QList< QgsPolylineXY >::const_iterator it = lineCoordinates.constBegin(); it != lineCoordinates.constEnd(); ++it ) { memcpy( &( wkb )[wkbPosition], &e, 1 ); wkbPosition += 1; memcpy( &( wkb )[wkbPosition], &type, sizeof( int ) ); wkbPosition += sizeof( int ); nPoints = it->size(); memcpy( &( wkb )[wkbPosition], &nPoints, sizeof( int ) ); wkbPosition += sizeof( int ); for ( QgsPolylineXY::const_iterator iter = it->begin(); iter != it->end(); ++iter ) { x = iter->x(); y = iter->y(); // QgsDebugMsg( QStringLiteral( "x, y is %1,%2" ).arg( x, 'f' ).arg( y, 'f' ) ); memcpy( &( wkb )[wkbPosition], &x, sizeof( double ) ); wkbPosition += sizeof( double ); memcpy( &( wkb )[wkbPosition], &y, sizeof( double ) ); wkbPosition += sizeof( double ); } } QgsGeometry g; g.fromWkb( wkb, size ); return g; } QgsGeometry QgsOgcUtils::geometryFromGMLMultiPolygon( const QDomElement &geometryElement ) { //first list: different polygons, second list: different rings, third list: different points QgsMultiPolygonXY multiPolygonPoints; QDomElement currentPolygonMemberElement; QDomNodeList polygonList; QDomElement currentPolygonElement; // rings in GML2 QDomNodeList outerBoundaryList; QDomElement currentOuterBoundaryElement; const QDomNodeList innerBoundaryList; QDomElement currentInnerBoundaryElement; // rings in GML3 QDomNodeList exteriorList; QDomElement currentExteriorElement; QDomElement currentInteriorElement; const QDomNodeList interiorList; // lienar ring QDomNodeList linearRingNodeList; QDomElement currentLinearRingElement; // Coordinates or position list QDomNodeList currentCoordinateList; QDomNodeList currentPosList; const QDomNodeList polygonMemberList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "polygonMember" ) ); QgsPolygonXY currentPolygonList; for ( int i = 0; i < polygonMemberList.size(); ++i ) { currentPolygonList.resize( 0 ); // preserve capacity - don't use clear currentPolygonMemberElement = polygonMemberList.at( i ).toElement(); polygonList = currentPolygonMemberElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "Polygon" ) ); if ( polygonList.size() < 1 ) { continue; } currentPolygonElement = polygonList.at( 0 ).toElement(); //find exterior ring outerBoundaryList = currentPolygonElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "outerBoundaryIs" ) ); if ( !outerBoundaryList.isEmpty() ) { currentOuterBoundaryElement = outerBoundaryList.at( 0 ).toElement(); QgsPolylineXY ringCoordinates; linearRingNodeList = currentOuterBoundaryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "LinearRing" ) ); if ( linearRingNodeList.size() < 1 ) { continue; } currentLinearRingElement = linearRingNodeList.at( 0 ).toElement(); currentCoordinateList = currentLinearRingElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "coordinates" ) ); if ( currentCoordinateList.size() < 1 ) { continue; } if ( readGMLCoordinates( ringCoordinates, currentCoordinateList.at( 0 ).toElement() ) != 0 ) { continue; } currentPolygonList.push_back( ringCoordinates ); //find interior rings const QDomNodeList innerBoundaryList = currentPolygonElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "innerBoundaryIs" ) ); for ( int j = 0; j < innerBoundaryList.size(); ++j ) { QgsPolylineXY ringCoordinates; currentInnerBoundaryElement = innerBoundaryList.at( j ).toElement(); linearRingNodeList = currentInnerBoundaryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "LinearRing" ) ); if ( linearRingNodeList.size() < 1 ) { continue; } currentLinearRingElement = linearRingNodeList.at( 0 ).toElement(); currentCoordinateList = currentLinearRingElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "coordinates" ) ); if ( currentCoordinateList.size() < 1 ) { continue; } if ( readGMLCoordinates( ringCoordinates, currentCoordinateList.at( 0 ).toElement() ) != 0 ) { continue; } currentPolygonList.push_back( ringCoordinates ); } } else { //find exterior ring exteriorList = currentPolygonElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "exterior" ) ); if ( exteriorList.size() < 1 ) { continue; } currentExteriorElement = exteriorList.at( 0 ).toElement(); QgsPolylineXY ringPositions; linearRingNodeList = currentExteriorElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "LinearRing" ) ); if ( linearRingNodeList.size() < 1 ) { continue; } currentLinearRingElement = linearRingNodeList.at( 0 ).toElement(); currentPosList = currentLinearRingElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "posList" ) ); if ( currentPosList.size() < 1 ) { continue; } if ( readGMLPositions( ringPositions, currentPosList.at( 0 ).toElement() ) != 0 ) { continue; } currentPolygonList.push_back( ringPositions ); //find interior rings const QDomNodeList interiorList = currentPolygonElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "interior" ) ); for ( int j = 0; j < interiorList.size(); ++j ) { QgsPolylineXY ringPositions; currentInteriorElement = interiorList.at( j ).toElement(); linearRingNodeList = currentInteriorElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "LinearRing" ) ); if ( linearRingNodeList.size() < 1 ) { continue; } currentLinearRingElement = linearRingNodeList.at( 0 ).toElement(); currentPosList = currentLinearRingElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "posList" ) ); if ( currentPosList.size() < 1 ) { continue; } if ( readGMLPositions( ringPositions, currentPosList.at( 0 ).toElement() ) != 0 ) { continue; } currentPolygonList.push_back( ringPositions ); } } multiPolygonPoints.push_back( currentPolygonList ); } int nPolygons = multiPolygonPoints.size(); if ( nPolygons < 1 ) return QgsGeometry(); int size = 1 + 2 * sizeof( int ); //calculate the wkb size for ( QgsMultiPolygonXY::const_iterator it = multiPolygonPoints.constBegin(); it != multiPolygonPoints.constEnd(); ++it ) { size += 1 + 2 * sizeof( int ); for ( QgsPolygonXY::const_iterator iter = it->begin(); iter != it->end(); ++iter ) { size += sizeof( int ) + 2 * iter->size() * sizeof( double ); } } QgsWkbTypes::Type type = QgsWkbTypes::MultiPolygon; unsigned char *wkb = new unsigned char[size]; char e = htonl( 1 ) != 1; int wkbPosition = 0; //current offset from wkb beginning (in bytes) double x, y; int nRings; int nPointsInRing; //fill the contents into *wkb memcpy( &( wkb )[wkbPosition], &e, 1 ); wkbPosition += 1; memcpy( &( wkb )[wkbPosition], &type, sizeof( int ) ); wkbPosition += sizeof( int ); memcpy( &( wkb )[wkbPosition], &nPolygons, sizeof( int ) ); wkbPosition += sizeof( int ); type = QgsWkbTypes::Polygon; for ( QgsMultiPolygonXY::const_iterator it = multiPolygonPoints.constBegin(); it != multiPolygonPoints.constEnd(); ++it ) { memcpy( &( wkb )[wkbPosition], &e, 1 ); wkbPosition += 1; memcpy( &( wkb )[wkbPosition], &type, sizeof( int ) ); wkbPosition += sizeof( int ); nRings = it->size(); memcpy( &( wkb )[wkbPosition], &nRings, sizeof( int ) ); wkbPosition += sizeof( int ); for ( QgsPolygonXY::const_iterator iter = it->begin(); iter != it->end(); ++iter ) { nPointsInRing = iter->size(); memcpy( &( wkb )[wkbPosition], &nPointsInRing, sizeof( int ) ); wkbPosition += sizeof( int ); for ( QgsPolylineXY::const_iterator iterator = iter->begin(); iterator != iter->end(); ++iterator ) { x = iterator->x(); y = iterator->y(); memcpy( &( wkb )[wkbPosition], &x, sizeof( double ) ); wkbPosition += sizeof( double ); memcpy( &( wkb )[wkbPosition], &y, sizeof( double ) ); wkbPosition += sizeof( double ); } } } QgsGeometry g; g.fromWkb( wkb, size ); return g; } bool QgsOgcUtils::readGMLCoordinates( QgsPolylineXY &coords, const QDomElement &elem ) { QString coordSeparator = QStringLiteral( "," ); QString tupelSeparator = QStringLiteral( " " ); //"decimal" has to be "." coords.clear(); if ( elem.hasAttribute( QStringLiteral( "cs" ) ) ) { coordSeparator = elem.attribute( QStringLiteral( "cs" ) ); } if ( elem.hasAttribute( QStringLiteral( "ts" ) ) ) { tupelSeparator = elem.attribute( QStringLiteral( "ts" ) ); } #if QT_VERSION < QT_VERSION_CHECK(5, 15, 0) QStringList tupels = elem.text().split( tupelSeparator, QString::SkipEmptyParts ); #else const QStringList tupels = elem.text().split( tupelSeparator, Qt::SkipEmptyParts ); #endif QStringList tuple_coords; double x, y; bool conversionSuccess; QStringList::const_iterator it; for ( it = tupels.constBegin(); it != tupels.constEnd(); ++it ) { #if QT_VERSION < QT_VERSION_CHECK(5, 15, 0) tuple_coords = ( *it ).split( coordSeparator, QString::SkipEmptyParts ); #else tuple_coords = ( *it ).split( coordSeparator, Qt::SkipEmptyParts ); #endif if ( tuple_coords.size() < 2 ) { continue; } x = tuple_coords.at( 0 ).toDouble( &conversionSuccess ); if ( !conversionSuccess ) { return true; } y = tuple_coords.at( 1 ).toDouble( &conversionSuccess ); if ( !conversionSuccess ) { return true; } coords.push_back( QgsPointXY( x, y ) ); } return false; } QgsRectangle QgsOgcUtils::rectangleFromGMLBox( const QDomNode &boxNode ) { QgsRectangle rect; const QDomElement boxElem = boxNode.toElement(); if ( boxElem.tagName() != QLatin1String( "Box" ) ) return rect; const QDomElement bElem = boxElem.firstChild().toElement(); QString coordSeparator = QStringLiteral( "," ); QString tupelSeparator = QStringLiteral( " " ); if ( bElem.hasAttribute( QStringLiteral( "cs" ) ) ) { coordSeparator = bElem.attribute( QStringLiteral( "cs" ) ); } if ( bElem.hasAttribute( QStringLiteral( "ts" ) ) ) { tupelSeparator = bElem.attribute( QStringLiteral( "ts" ) ); } const QString bString = bElem.text(); bool ok1, ok2, ok3, ok4; const double xmin = bString.section( tupelSeparator, 0, 0 ).section( coordSeparator, 0, 0 ).toDouble( &ok1 ); const double ymin = bString.section( tupelSeparator, 0, 0 ).section( coordSeparator, 1, 1 ).toDouble( &ok2 ); const double xmax = bString.section( tupelSeparator, 1, 1 ).section( coordSeparator, 0, 0 ).toDouble( &ok3 ); const double ymax = bString.section( tupelSeparator, 1, 1 ).section( coordSeparator, 1, 1 ).toDouble( &ok4 ); if ( ok1 && ok2 && ok3 && ok4 ) { rect = QgsRectangle( xmin, ymin, xmax, ymax ); rect.normalize(); } return rect; } bool QgsOgcUtils::readGMLPositions( QgsPolylineXY &coords, const QDomElement &elem ) { coords.clear(); #if QT_VERSION < QT_VERSION_CHECK(5, 15, 0) QStringList pos = elem.text().split( ' ', QString::SkipEmptyParts ); #else const QStringList pos = elem.text().split( ' ', Qt::SkipEmptyParts ); #endif double x, y; bool conversionSuccess; const int posSize = pos.size(); int srsDimension = 2; if ( elem.hasAttribute( QStringLiteral( "srsDimension" ) ) ) { srsDimension = elem.attribute( QStringLiteral( "srsDimension" ) ).toInt( &conversionSuccess ); if ( !conversionSuccess ) { srsDimension = 2; } } else if ( elem.hasAttribute( QStringLiteral( "dimension" ) ) ) { srsDimension = elem.attribute( QStringLiteral( "dimension" ) ).toInt( &conversionSuccess ); if ( !conversionSuccess ) { srsDimension = 2; } } for ( int i = 0; i < posSize / srsDimension; i++ ) { x = pos.at( i * srsDimension ).toDouble( &conversionSuccess ); if ( !conversionSuccess ) { return true; } y = pos.at( i * srsDimension + 1 ).toDouble( &conversionSuccess ); if ( !conversionSuccess ) { return true; } coords.push_back( QgsPointXY( x, y ) ); } return false; } QgsRectangle QgsOgcUtils::rectangleFromGMLEnvelope( const QDomNode &envelopeNode ) { QgsRectangle rect; const QDomElement envelopeElem = envelopeNode.toElement(); if ( envelopeElem.tagName() != QLatin1String( "Envelope" ) ) return rect; const QDomNodeList lowerCornerList = envelopeElem.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "lowerCorner" ) ); if ( lowerCornerList.size() < 1 ) return rect; const QDomNodeList upperCornerList = envelopeElem.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "upperCorner" ) ); if ( upperCornerList.size() < 1 ) return rect; bool conversionSuccess; int srsDimension = 2; QDomElement elem = lowerCornerList.at( 0 ).toElement(); if ( elem.hasAttribute( QStringLiteral( "srsDimension" ) ) ) { srsDimension = elem.attribute( QStringLiteral( "srsDimension" ) ).toInt( &conversionSuccess ); if ( !conversionSuccess ) { srsDimension = 2; } } else if ( elem.hasAttribute( QStringLiteral( "dimension" ) ) ) { srsDimension = elem.attribute( QStringLiteral( "dimension" ) ).toInt( &conversionSuccess ); if ( !conversionSuccess ) { srsDimension = 2; } } QString bString = elem.text(); const double xmin = bString.section( ' ', 0, 0 ).toDouble( &conversionSuccess ); if ( !conversionSuccess ) return rect; const double ymin = bString.section( ' ', 1, 1 ).toDouble( &conversionSuccess ); if ( !conversionSuccess ) return rect; elem = upperCornerList.at( 0 ).toElement(); if ( elem.hasAttribute( QStringLiteral( "srsDimension" ) ) ) { srsDimension = elem.attribute( QStringLiteral( "srsDimension" ) ).toInt( &conversionSuccess ); if ( !conversionSuccess ) { srsDimension = 2; } } else if ( elem.hasAttribute( QStringLiteral( "dimension" ) ) ) { srsDimension = elem.attribute( QStringLiteral( "dimension" ) ).toInt( &conversionSuccess ); if ( !conversionSuccess ) { srsDimension = 2; } } Q_UNUSED( srsDimension ) bString = elem.text(); const double xmax = bString.section( ' ', 0, 0 ).toDouble( &conversionSuccess ); if ( !conversionSuccess ) return rect; const double ymax = bString.section( ' ', 1, 1 ).toDouble( &conversionSuccess ); if ( !conversionSuccess ) return rect; rect = QgsRectangle( xmin, ymin, xmax, ymax ); rect.normalize(); return rect; } QDomElement QgsOgcUtils::rectangleToGMLBox( QgsRectangle *box, QDomDocument &doc, int precision ) { return rectangleToGMLBox( box, doc, QString(), false, precision ); } QDomElement QgsOgcUtils::rectangleToGMLBox( QgsRectangle *box, QDomDocument &doc, const QString &srsName, bool invertAxisOrientation, int precision ) { if ( !box ) { return QDomElement(); } QDomElement boxElem = doc.createElement( QStringLiteral( "gml:Box" ) ); if ( !srsName.isEmpty() ) { boxElem.setAttribute( QStringLiteral( "srsName" ), srsName ); } QDomElement coordElem = doc.createElement( QStringLiteral( "gml:coordinates" ) ); coordElem.setAttribute( QStringLiteral( "cs" ), QStringLiteral( "," ) ); coordElem.setAttribute( QStringLiteral( "ts" ), QStringLiteral( " " ) ); QString coordString; coordString += qgsDoubleToString( invertAxisOrientation ? box->yMinimum() : box->xMinimum(), precision ); coordString += ','; coordString += qgsDoubleToString( invertAxisOrientation ? box->xMinimum() : box->yMinimum(), precision ); coordString += ' '; coordString += qgsDoubleToString( invertAxisOrientation ? box->yMaximum() : box->xMaximum(), precision ); coordString += ','; coordString += qgsDoubleToString( invertAxisOrientation ? box->xMaximum() : box->yMaximum(), precision ); const QDomText coordText = doc.createTextNode( coordString ); coordElem.appendChild( coordText ); boxElem.appendChild( coordElem ); return boxElem; } QDomElement QgsOgcUtils::rectangleToGMLEnvelope( QgsRectangle *env, QDomDocument &doc, int precision ) { return rectangleToGMLEnvelope( env, doc, QString(), false, precision ); } QDomElement QgsOgcUtils::rectangleToGMLEnvelope( QgsRectangle *env, QDomDocument &doc, const QString &srsName, bool invertAxisOrientation, int precision ) { if ( !env ) { return QDomElement(); } QDomElement envElem = doc.createElement( QStringLiteral( "gml:Envelope" ) ); if ( !srsName.isEmpty() ) { envElem.setAttribute( QStringLiteral( "srsName" ), srsName ); } QString posList; QDomElement lowerCornerElem = doc.createElement( QStringLiteral( "gml:lowerCorner" ) ); posList = qgsDoubleToString( invertAxisOrientation ? env->yMinimum() : env->xMinimum(), precision ); posList += ' '; posList += qgsDoubleToString( invertAxisOrientation ? env->xMinimum() : env->yMinimum(), precision ); const QDomText lowerCornerText = doc.createTextNode( posList ); lowerCornerElem.appendChild( lowerCornerText ); envElem.appendChild( lowerCornerElem ); QDomElement upperCornerElem = doc.createElement( QStringLiteral( "gml:upperCorner" ) ); posList = qgsDoubleToString( invertAxisOrientation ? env->yMaximum() : env->xMaximum(), precision ); posList += ' '; posList += qgsDoubleToString( invertAxisOrientation ? env->xMaximum() : env->yMaximum(), precision ); const QDomText upperCornerText = doc.createTextNode( posList ); upperCornerElem.appendChild( upperCornerText ); envElem.appendChild( upperCornerElem ); return envElem; } QDomElement QgsOgcUtils::geometryToGML( const QgsGeometry &geometry, QDomDocument &doc, const QString &format, int precision ) { return geometryToGML( geometry, doc, ( format == QLatin1String( "GML2" ) ) ? GML_2_1_2 : GML_3_2_1, QString(), false, QString(), precision ); } QDomElement QgsOgcUtils::geometryToGML( const QgsGeometry &geometry, QDomDocument &doc, GMLVersion gmlVersion, const QString &srsName, bool invertAxisOrientation, const QString &gmlIdBase, int precision ) { if ( geometry.isNull() ) return QDomElement(); // coordinate separator QString cs = QStringLiteral( "," ); // tuple separator const QString ts = QStringLiteral( " " ); // coord element tagname QDomElement baseCoordElem; bool hasZValue = false; const QByteArray wkb( geometry.asWkb() ); QgsConstWkbPtr wkbPtr( wkb ); try { wkbPtr.readHeader(); } catch ( const QgsWkbException &e ) { Q_UNUSED( e ) // WKB exception while reading header return QDomElement(); } if ( gmlVersion != GML_2_1_2 ) { switch ( geometry.wkbType() ) { case QgsWkbTypes::Point25D: case QgsWkbTypes::Point: case QgsWkbTypes::MultiPoint25D: case QgsWkbTypes::MultiPoint: baseCoordElem = doc.createElement( QStringLiteral( "gml:pos" ) ); break; default: baseCoordElem = doc.createElement( QStringLiteral( "gml:posList" ) ); break; } baseCoordElem.setAttribute( QStringLiteral( "srsDimension" ), QStringLiteral( "2" ) ); cs = ' '; } else { baseCoordElem = doc.createElement( QStringLiteral( "gml:coordinates" ) ); baseCoordElem.setAttribute( QStringLiteral( "cs" ), cs ); baseCoordElem.setAttribute( QStringLiteral( "ts" ), ts ); } try { switch ( geometry.wkbType() ) { case QgsWkbTypes::Point25D: case QgsWkbTypes::Point: { QDomElement pointElem = doc.createElement( QStringLiteral( "gml:Point" ) ); if ( gmlVersion == GML_3_2_1 && !gmlIdBase.isEmpty() ) pointElem.setAttribute( QStringLiteral( "gml:id" ), gmlIdBase ); if ( !srsName.isEmpty() ) pointElem.setAttribute( QStringLiteral( "srsName" ), srsName ); QDomElement coordElem = baseCoordElem.cloneNode().toElement(); double x, y; if ( invertAxisOrientation ) wkbPtr >> y >> x; else wkbPtr >> x >> y; const QDomText coordText = doc.createTextNode( qgsDoubleToString( x, precision ) + cs + qgsDoubleToString( y, precision ) ); coordElem.appendChild( coordText ); pointElem.appendChild( coordElem ); return pointElem; } case QgsWkbTypes::MultiPoint25D: hasZValue = true; //intentional fall-through FALLTHROUGH case QgsWkbTypes::MultiPoint: { QDomElement multiPointElem = doc.createElement( QStringLiteral( "gml:MultiPoint" ) ); if ( gmlVersion == GML_3_2_1 && !gmlIdBase.isEmpty() ) multiPointElem.setAttribute( QStringLiteral( "gml:id" ), gmlIdBase ); if ( !srsName.isEmpty() ) multiPointElem.setAttribute( QStringLiteral( "srsName" ), srsName ); int nPoints; wkbPtr >> nPoints; for ( int idx = 0; idx < nPoints; ++idx ) { QDomElement pointMemberElem = doc.createElement( QStringLiteral( "gml:pointMember" ) ); QDomElement pointElem = doc.createElement( QStringLiteral( "gml:Point" ) ); if ( gmlVersion == GML_3_2_1 && !gmlIdBase.isEmpty() ) pointElem.setAttribute( QStringLiteral( "gml:id" ), gmlIdBase + QStringLiteral( ".%1" ).arg( idx + 1 ) ); QDomElement coordElem = baseCoordElem.cloneNode().toElement(); wkbPtr.readHeader(); double x = 0; double y = 0; if ( invertAxisOrientation ) wkbPtr >> y >> x; else wkbPtr >> x >> y; const QDomText coordText = doc.createTextNode( qgsDoubleToString( x, precision ) + cs + qgsDoubleToString( y, precision ) ); coordElem.appendChild( coordText ); pointElem.appendChild( coordElem ); if ( hasZValue ) { wkbPtr += sizeof( double ); } pointMemberElem.appendChild( pointElem ); multiPointElem.appendChild( pointMemberElem ); } return multiPointElem; } case QgsWkbTypes::LineString25D: hasZValue = true; //intentional fall-through FALLTHROUGH case QgsWkbTypes::LineString: { QDomElement lineStringElem = doc.createElement( QStringLiteral( "gml:LineString" ) ); if ( gmlVersion == GML_3_2_1 && !gmlIdBase.isEmpty() ) lineStringElem.setAttribute( QStringLiteral( "gml:id" ), gmlIdBase ); if ( !srsName.isEmpty() ) lineStringElem.setAttribute( QStringLiteral( "srsName" ), srsName ); // get number of points in the line int nPoints; wkbPtr >> nPoints; QDomElement coordElem = baseCoordElem.cloneNode().toElement(); QString coordString; for ( int idx = 0; idx < nPoints; ++idx ) { if ( idx != 0 ) { coordString += ts; } double x = 0; double y = 0; if ( invertAxisOrientation ) wkbPtr >> y >> x; else wkbPtr >> x >> y; coordString += qgsDoubleToString( x, precision ) + cs + qgsDoubleToString( y, precision ); if ( hasZValue ) { wkbPtr += sizeof( double ); } } const QDomText coordText = doc.createTextNode( coordString ); coordElem.appendChild( coordText ); lineStringElem.appendChild( coordElem ); return lineStringElem; } case QgsWkbTypes::MultiLineString25D: hasZValue = true; //intentional fall-through FALLTHROUGH case QgsWkbTypes::MultiLineString: { QDomElement multiLineStringElem = doc.createElement( QStringLiteral( "gml:MultiLineString" ) ); if ( gmlVersion == GML_3_2_1 && !gmlIdBase.isEmpty() ) multiLineStringElem.setAttribute( QStringLiteral( "gml:id" ), gmlIdBase ); if ( !srsName.isEmpty() ) multiLineStringElem.setAttribute( QStringLiteral( "srsName" ), srsName ); int nLines; wkbPtr >> nLines; for ( int jdx = 0; jdx < nLines; jdx++ ) { QDomElement lineStringMemberElem = doc.createElement( QStringLiteral( "gml:lineStringMember" ) ); QDomElement lineStringElem = doc.createElement( QStringLiteral( "gml:LineString" ) ); if ( gmlVersion == GML_3_2_1 && !gmlIdBase.isEmpty() ) lineStringElem.setAttribute( QStringLiteral( "gml:id" ), gmlIdBase + QStringLiteral( ".%1" ).arg( jdx + 1 ) ); wkbPtr.readHeader(); int nPoints; wkbPtr >> nPoints; QDomElement coordElem = baseCoordElem.cloneNode().toElement(); QString coordString; for ( int idx = 0; idx < nPoints; idx++ ) { if ( idx != 0 ) { coordString += ts; } double x = 0; double y = 0; if ( invertAxisOrientation ) wkbPtr >> y >> x; else wkbPtr >> x >> y; coordString += qgsDoubleToString( x, precision ) + cs + qgsDoubleToString( y, precision ); if ( hasZValue ) { wkbPtr += sizeof( double ); } } const QDomText coordText = doc.createTextNode( coordString ); coordElem.appendChild( coordText ); lineStringElem.appendChild( coordElem ); lineStringMemberElem.appendChild( lineStringElem ); multiLineStringElem.appendChild( lineStringMemberElem ); } return multiLineStringElem; } case QgsWkbTypes::Polygon25D: hasZValue = true; //intentional fall-through FALLTHROUGH case QgsWkbTypes::Polygon: { QDomElement polygonElem = doc.createElement( QStringLiteral( "gml:Polygon" ) ); if ( gmlVersion == GML_3_2_1 && !gmlIdBase.isEmpty() ) polygonElem.setAttribute( QStringLiteral( "gml:id" ), gmlIdBase ); if ( !srsName.isEmpty() ) polygonElem.setAttribute( QStringLiteral( "srsName" ), srsName ); // get number of rings in the polygon int numRings; wkbPtr >> numRings; if ( numRings == 0 ) // sanity check for zero rings in polygon return QDomElement(); for ( int idx = 0; idx < numRings; idx++ ) { QString boundaryName = ( gmlVersion == GML_2_1_2 ) ? "gml:outerBoundaryIs" : "gml:exterior"; if ( idx != 0 ) { boundaryName = ( gmlVersion == GML_2_1_2 ) ? "gml:innerBoundaryIs" : "gml:interior"; } QDomElement boundaryElem = doc.createElement( boundaryName ); QDomElement ringElem = doc.createElement( QStringLiteral( "gml:LinearRing" ) ); // get number of points in the ring int nPoints = 0; wkbPtr >> nPoints; QDomElement coordElem = baseCoordElem.cloneNode().toElement(); QString coordString; for ( int jdx = 0; jdx < nPoints; jdx++ ) { if ( jdx != 0 ) { coordString += ts; } double x = 0; double y = 0; if ( invertAxisOrientation ) wkbPtr >> y >> x; else wkbPtr >> x >> y; coordString += qgsDoubleToString( x, precision ) + cs + qgsDoubleToString( y, precision ); if ( hasZValue ) { wkbPtr += sizeof( double ); } } const QDomText coordText = doc.createTextNode( coordString ); coordElem.appendChild( coordText ); ringElem.appendChild( coordElem ); boundaryElem.appendChild( ringElem ); polygonElem.appendChild( boundaryElem ); } return polygonElem; } case QgsWkbTypes::MultiPolygon25D: hasZValue = true; //intentional fall-through FALLTHROUGH case QgsWkbTypes::MultiPolygon: { QDomElement multiPolygonElem = doc.createElement( QStringLiteral( "gml:MultiPolygon" ) ); if ( gmlVersion == GML_3_2_1 && !gmlIdBase.isEmpty() ) multiPolygonElem.setAttribute( QStringLiteral( "gml:id" ), gmlIdBase ); if ( !srsName.isEmpty() ) multiPolygonElem.setAttribute( QStringLiteral( "srsName" ), srsName ); int numPolygons; wkbPtr >> numPolygons; for ( int kdx = 0; kdx < numPolygons; kdx++ ) { QDomElement polygonMemberElem = doc.createElement( QStringLiteral( "gml:polygonMember" ) ); QDomElement polygonElem = doc.createElement( QStringLiteral( "gml:Polygon" ) ); if ( gmlVersion == GML_3_2_1 && !gmlIdBase.isEmpty() ) polygonElem.setAttribute( QStringLiteral( "gml:id" ), gmlIdBase + QStringLiteral( ".%1" ).arg( kdx + 1 ) ); wkbPtr.readHeader(); int numRings; wkbPtr >> numRings; for ( int idx = 0; idx < numRings; idx++ ) { QString boundaryName = ( gmlVersion == GML_2_1_2 ) ? "gml:outerBoundaryIs" : "gml:exterior"; if ( idx != 0 ) { boundaryName = ( gmlVersion == GML_2_1_2 ) ? "gml:innerBoundaryIs" : "gml:interior"; } QDomElement boundaryElem = doc.createElement( boundaryName ); QDomElement ringElem = doc.createElement( QStringLiteral( "gml:LinearRing" ) ); int nPoints; wkbPtr >> nPoints; QDomElement coordElem = baseCoordElem.cloneNode().toElement(); QString coordString; for ( int jdx = 0; jdx < nPoints; jdx++ ) { if ( jdx != 0 ) { coordString += ts; } double x = 0; double y = 0; if ( invertAxisOrientation ) wkbPtr >> y >> x; else wkbPtr >> x >> y; coordString += qgsDoubleToString( x, precision ) + cs + qgsDoubleToString( y, precision ); if ( hasZValue ) { wkbPtr += sizeof( double ); } } const QDomText coordText = doc.createTextNode( coordString ); coordElem.appendChild( coordText ); ringElem.appendChild( coordElem ); boundaryElem.appendChild( ringElem ); polygonElem.appendChild( boundaryElem ); polygonMemberElem.appendChild( polygonElem ); multiPolygonElem.appendChild( polygonMemberElem ); } } return multiPolygonElem; } default: return QDomElement(); } } catch ( const QgsWkbException &e ) { Q_UNUSED( e ) return QDomElement(); } } QDomElement QgsOgcUtils::geometryToGML( const QgsGeometry &geometry, QDomDocument &doc, int precision ) { return geometryToGML( geometry, doc, QStringLiteral( "GML2" ), precision ); } QDomElement QgsOgcUtils::createGMLCoordinates( const QgsPolylineXY &points, QDomDocument &doc ) { QDomElement coordElem = doc.createElement( QStringLiteral( "gml:coordinates" ) ); coordElem.setAttribute( QStringLiteral( "cs" ), QStringLiteral( "," ) ); coordElem.setAttribute( QStringLiteral( "ts" ), QStringLiteral( " " ) ); QString coordString; QVector<QgsPointXY>::const_iterator pointIt = points.constBegin(); for ( ; pointIt != points.constEnd(); ++pointIt ) { if ( pointIt != points.constBegin() ) { coordString += ' '; } coordString += qgsDoubleToString( pointIt->x() ); coordString += ','; coordString += qgsDoubleToString( pointIt->y() ); } const QDomText coordText = doc.createTextNode( coordString ); coordElem.appendChild( coordText ); return coordElem; } QDomElement QgsOgcUtils::createGMLPositions( const QgsPolylineXY &points, QDomDocument &doc ) { QDomElement posElem = doc.createElement( QStringLiteral( "gml:pos" ) ); if ( points.size() > 1 ) posElem = doc.createElement( QStringLiteral( "gml:posList" ) ); posElem.setAttribute( QStringLiteral( "srsDimension" ), QStringLiteral( "2" ) ); QString coordString; QVector<QgsPointXY>::const_iterator pointIt = points.constBegin(); for ( ; pointIt != points.constEnd(); ++pointIt ) { if ( pointIt != points.constBegin() ) { coordString += ' '; } coordString += qgsDoubleToString( pointIt->x() ); coordString += ' '; coordString += qgsDoubleToString( pointIt->y() ); } const QDomText coordText = doc.createTextNode( coordString ); posElem.appendChild( coordText ); return posElem; } // ----------------------------------------- QColor QgsOgcUtils::colorFromOgcFill( const QDomElement &fillElement ) { if ( fillElement.isNull() || !fillElement.hasChildNodes() ) { return QColor(); } QString cssName; QString elemText; QColor color; QDomElement cssElem = fillElement.firstChildElement( QStringLiteral( "CssParameter" ) ); while ( !cssElem.isNull() ) { cssName = cssElem.attribute( QStringLiteral( "name" ), QStringLiteral( "not_found" ) ); if ( cssName != QLatin1String( "not_found" ) ) { elemText = cssElem.text(); if ( cssName == QLatin1String( "fill" ) ) { color.setNamedColor( elemText ); } else if ( cssName == QLatin1String( "fill-opacity" ) ) { bool ok; const double opacity = elemText.toDouble( &ok ); if ( ok ) { color.setAlphaF( opacity ); } } } cssElem = cssElem.nextSiblingElement( QStringLiteral( "CssParameter" ) ); } return color; } QgsExpression *QgsOgcUtils::expressionFromOgcFilter( const QDomElement &element, QgsVectorLayer *layer ) { return expressionFromOgcFilter( element, QgsOgcUtils::FILTER_OGC_1_0, layer ); } QgsExpression *QgsOgcUtils::expressionFromOgcFilter( const QDomElement &element, const FilterVersion version, QgsVectorLayer *layer ) { if ( element.isNull() || !element.hasChildNodes() ) return nullptr; QgsExpression *expr = new QgsExpression(); // check if it is a single string value not having DOM elements // that express OGC operators if ( element.firstChild().nodeType() == QDomNode::TextNode ) { expr->setExpression( element.firstChild().nodeValue() ); return expr; } QgsOgcUtilsExpressionFromFilter utils( version, layer ); // then check OGC DOM elements that contain OGC tags specifying // OGC operators. QDomElement childElem = element.firstChildElement(); while ( !childElem.isNull() ) { QgsExpressionNode *node = utils.nodeFromOgcFilter( childElem ); if ( !node ) { // invalid expression, parser error expr->d->mParserErrorString = utils.errorMessage(); return expr; } // use the concat binary operator to append to the root node if ( !expr->d->mRootNode ) { expr->d->mRootNode = node; } else { expr->d->mRootNode = new QgsExpressionNodeBinaryOperator( QgsExpressionNodeBinaryOperator::boConcat, expr->d->mRootNode, node ); } childElem = childElem.nextSiblingElement(); } // update expression string expr->d->mExp = expr->dump(); return expr; } typedef QMap<QString, int> IntMap; Q_GLOBAL_STATIC_WITH_ARGS( IntMap, BINARY_OPERATORS_TAG_NAMES_MAP, ( { // logical { QLatin1String( "Or" ), QgsExpressionNodeBinaryOperator::boOr }, { QLatin1String( "And" ), QgsExpressionNodeBinaryOperator::boAnd }, // comparison { QLatin1String( "PropertyIsEqualTo" ), QgsExpressionNodeBinaryOperator::boEQ }, { QLatin1String( "PropertyIsNotEqualTo" ), QgsExpressionNodeBinaryOperator::boNE }, { QLatin1String( "PropertyIsLessThanOrEqualTo" ), QgsExpressionNodeBinaryOperator::boLE }, { QLatin1String( "PropertyIsGreaterThanOrEqualTo" ), QgsExpressionNodeBinaryOperator::boGE }, { QLatin1String( "PropertyIsLessThan" ), QgsExpressionNodeBinaryOperator::boLT }, { QLatin1String( "PropertyIsGreaterThan" ), QgsExpressionNodeBinaryOperator::boGT }, { QLatin1String( "PropertyIsLike" ), QgsExpressionNodeBinaryOperator::boLike }, // arithmetic { QLatin1String( "Add" ), QgsExpressionNodeBinaryOperator::boPlus }, { QLatin1String( "Sub" ), QgsExpressionNodeBinaryOperator::boMinus }, { QLatin1String( "Mul" ), QgsExpressionNodeBinaryOperator::boMul }, { QLatin1String( "Div" ), QgsExpressionNodeBinaryOperator::boDiv }, } ) ) static int binaryOperatorFromTagName( const QString &tagName ) { return BINARY_OPERATORS_TAG_NAMES_MAP()->value( tagName, -1 ); } static QString binaryOperatorToTagName( QgsExpressionNodeBinaryOperator::BinaryOperator op ) { if ( op == QgsExpressionNodeBinaryOperator::boILike ) { return QStringLiteral( "PropertyIsLike" ); } return BINARY_OPERATORS_TAG_NAMES_MAP()->key( op, QString() ); } static bool isBinaryOperator( const QString &tagName ) { return binaryOperatorFromTagName( tagName ) >= 0; } static bool isSpatialOperator( const QString &tagName ) { static QStringList spatialOps; if ( spatialOps.isEmpty() ) { spatialOps << QStringLiteral( "BBOX" ) << QStringLiteral( "Intersects" ) << QStringLiteral( "Contains" ) << QStringLiteral( "Crosses" ) << QStringLiteral( "Equals" ) << QStringLiteral( "Disjoint" ) << QStringLiteral( "Overlaps" ) << QStringLiteral( "Touches" ) << QStringLiteral( "Within" ); } return spatialOps.contains( tagName ); } QgsExpressionNode *QgsOgcUtils::nodeFromOgcFilter( QDomElement &element, QString &errorMessage, QgsVectorLayer *layer ) { QgsOgcUtilsExpressionFromFilter utils( QgsOgcUtils::FILTER_OGC_1_0, layer ); QgsExpressionNode *node = utils.nodeFromOgcFilter( element ); errorMessage = utils.errorMessage(); return node; } QgsExpressionNodeBinaryOperator *QgsOgcUtils::nodeBinaryOperatorFromOgcFilter( QDomElement &element, QString &errorMessage, QgsVectorLayer *layer ) { QgsOgcUtilsExpressionFromFilter utils( QgsOgcUtils::FILTER_OGC_1_0, layer ); QgsExpressionNodeBinaryOperator *node = utils.nodeBinaryOperatorFromOgcFilter( element ); errorMessage = utils.errorMessage(); return node; } QgsExpressionNodeFunction *QgsOgcUtils::nodeSpatialOperatorFromOgcFilter( QDomElement &element, QString &errorMessage ) { QgsOgcUtilsExpressionFromFilter utils( QgsOgcUtils::FILTER_OGC_1_0 ); QgsExpressionNodeFunction *node = utils.nodeSpatialOperatorFromOgcFilter( element ); errorMessage = utils.errorMessage(); return node; } QgsExpressionNodeUnaryOperator *QgsOgcUtils::nodeNotFromOgcFilter( QDomElement &element, QString &errorMessage ) { QgsOgcUtilsExpressionFromFilter utils( QgsOgcUtils::FILTER_OGC_1_0 ); QgsExpressionNodeUnaryOperator *node = utils.nodeNotFromOgcFilter( element ); errorMessage = utils.errorMessage(); return node; } QgsExpressionNodeFunction *QgsOgcUtils::nodeFunctionFromOgcFilter( QDomElement &element, QString &errorMessage ) { QgsOgcUtilsExpressionFromFilter utils( QgsOgcUtils::FILTER_OGC_1_0 ); QgsExpressionNodeFunction *node = utils.nodeFunctionFromOgcFilter( element ); errorMessage = utils.errorMessage(); return node; } QgsExpressionNode *QgsOgcUtils::nodeLiteralFromOgcFilter( QDomElement &element, QString &errorMessage, QgsVectorLayer *layer ) { QgsOgcUtilsExpressionFromFilter utils( QgsOgcUtils::FILTER_OGC_1_0, layer ); QgsExpressionNode *node = utils.nodeLiteralFromOgcFilter( element ); errorMessage = utils.errorMessage(); return node; } QgsExpressionNodeColumnRef *QgsOgcUtils::nodeColumnRefFromOgcFilter( QDomElement &element, QString &errorMessage ) { QgsOgcUtilsExpressionFromFilter utils( QgsOgcUtils::FILTER_OGC_1_0 ); QgsExpressionNodeColumnRef *node = utils.nodeColumnRefFromOgcFilter( element ); errorMessage = utils.errorMessage(); return node; } QgsExpressionNode *QgsOgcUtils::nodeIsBetweenFromOgcFilter( QDomElement &element, QString &errorMessage ) { QgsOgcUtilsExpressionFromFilter utils( QgsOgcUtils::FILTER_OGC_1_0 ); QgsExpressionNode *node = utils.nodeIsBetweenFromOgcFilter( element ); errorMessage = utils.errorMessage(); return node; } QgsExpressionNodeBinaryOperator *QgsOgcUtils::nodePropertyIsNullFromOgcFilter( QDomElement &element, QString &errorMessage ) { QgsOgcUtilsExpressionFromFilter utils( QgsOgcUtils::FILTER_OGC_1_0 ); QgsExpressionNodeBinaryOperator *node = utils.nodePropertyIsNullFromOgcFilter( element ); errorMessage = utils.errorMessage(); return node; } ///////////////// QDomElement QgsOgcUtils::expressionToOgcFilter( const QgsExpression &exp, QDomDocument &doc, QString *errorMessage ) { return expressionToOgcFilter( exp, doc, GML_2_1_2, FILTER_OGC_1_0, QStringLiteral( "geometry" ), QString(), false, false, errorMessage ); } QDomElement QgsOgcUtils::expressionToOgcExpression( const QgsExpression &exp, QDomDocument &doc, QString *errorMessage ) { return expressionToOgcExpression( exp, doc, GML_2_1_2, FILTER_OGC_1_0, QStringLiteral( "geometry" ), QString(), false, false, errorMessage ); } QDomElement QgsOgcUtils::expressionToOgcFilter( const QgsExpression &expression, QDomDocument &doc, GMLVersion gmlVersion, FilterVersion filterVersion, const QString &geometryName, const QString &srsName, bool honourAxisOrientation, bool invertAxisOrientation, QString *errorMessage ) { if ( !expression.rootNode() ) return QDomElement(); QgsExpression exp = expression; QgsExpressionContext context; context << QgsExpressionContextUtils::globalScope(); QgsOgcUtilsExprToFilter utils( doc, gmlVersion, filterVersion, geometryName, srsName, honourAxisOrientation, invertAxisOrientation ); const QDomElement exprRootElem = utils.expressionNodeToOgcFilter( exp.rootNode(), &exp, &context ); if ( errorMessage ) *errorMessage = utils.errorMessage(); if ( exprRootElem.isNull() ) return QDomElement(); QDomElement filterElem = ( filterVersion == FILTER_FES_2_0 ) ? doc.createElementNS( FES_NAMESPACE, QStringLiteral( "fes:Filter" ) ) : doc.createElementNS( OGC_NAMESPACE, QStringLiteral( "ogc:Filter" ) ); if ( utils.GMLNamespaceUsed() ) { QDomAttr attr = doc.createAttribute( QStringLiteral( "xmlns:gml" ) ); if ( gmlVersion == GML_3_2_1 ) attr.setValue( GML32_NAMESPACE ); else attr.setValue( GML_NAMESPACE ); filterElem.setAttributeNode( attr ); } filterElem.appendChild( exprRootElem ); return filterElem; } QDomElement QgsOgcUtils::expressionToOgcExpression( const QgsExpression &expression, QDomDocument &doc, GMLVersion gmlVersion, FilterVersion filterVersion, const QString &geometryName, const QString &srsName, bool honourAxisOrientation, bool invertAxisOrientation, QString *errorMessage ) { QgsExpressionContext context; context << QgsExpressionContextUtils::globalScope(); QgsExpression exp = expression; const QgsExpressionNode *node = exp.rootNode(); if ( !node ) return QDomElement(); switch ( node->nodeType() ) { case QgsExpressionNode::ntFunction: case QgsExpressionNode::ntLiteral: case QgsExpressionNode::ntColumnRef: { QgsOgcUtilsExprToFilter utils( doc, gmlVersion, filterVersion, geometryName, srsName, honourAxisOrientation, invertAxisOrientation ); const QDomElement exprRootElem = utils.expressionNodeToOgcFilter( node, &exp, &context ); if ( errorMessage ) *errorMessage = utils.errorMessage(); if ( !exprRootElem.isNull() ) { return exprRootElem; } break; } default: { if ( errorMessage ) *errorMessage = QObject::tr( "Node type not supported in expression translation: %1" ).arg( node->nodeType() ); } } // got an error return QDomElement(); } QDomElement QgsOgcUtils::SQLStatementToOgcFilter( const QgsSQLStatement &statement, QDomDocument &doc, GMLVersion gmlVersion, FilterVersion filterVersion, const QList<LayerProperties> &layerProperties, bool honourAxisOrientation, bool invertAxisOrientation, const QMap< QString, QString> &mapUnprefixedTypenameToPrefixedTypename, QString *errorMessage ) { if ( !statement.rootNode() ) return QDomElement(); QgsOgcUtilsSQLStatementToFilter utils( doc, gmlVersion, filterVersion, layerProperties, honourAxisOrientation, invertAxisOrientation, mapUnprefixedTypenameToPrefixedTypename ); const QDomElement exprRootElem = utils.toOgcFilter( statement.rootNode() ); if ( errorMessage ) *errorMessage = utils.errorMessage(); if ( exprRootElem.isNull() ) return QDomElement(); QDomElement filterElem = ( filterVersion == FILTER_FES_2_0 ) ? doc.createElementNS( FES_NAMESPACE, QStringLiteral( "fes:Filter" ) ) : doc.createElementNS( OGC_NAMESPACE, QStringLiteral( "ogc:Filter" ) ); if ( utils.GMLNamespaceUsed() ) { QDomAttr attr = doc.createAttribute( QStringLiteral( "xmlns:gml" ) ); if ( gmlVersion == GML_3_2_1 ) attr.setValue( GML32_NAMESPACE ); else attr.setValue( GML_NAMESPACE ); filterElem.setAttributeNode( attr ); } QSet<QString> setNamespaceURI; for ( const LayerProperties &props : layerProperties ) { if ( !props.mNamespacePrefix.isEmpty() && !props.mNamespaceURI.isEmpty() && !setNamespaceURI.contains( props.mNamespaceURI ) ) { setNamespaceURI.insert( props.mNamespaceURI ); QDomAttr attr = doc.createAttribute( QStringLiteral( "xmlns:" ) + props.mNamespacePrefix ); attr.setValue( props.mNamespaceURI ); filterElem.setAttributeNode( attr ); } } filterElem.appendChild( exprRootElem ); return filterElem; } // QDomElement QgsOgcUtilsExprToFilter::expressionNodeToOgcFilter( const QgsExpressionNode *node, QgsExpression *expression, const QgsExpressionContext *context ) { switch ( node->nodeType() ) { case QgsExpressionNode::ntUnaryOperator: return expressionUnaryOperatorToOgcFilter( static_cast<const QgsExpressionNodeUnaryOperator *>( node ), expression, context ); case QgsExpressionNode::ntBinaryOperator: return expressionBinaryOperatorToOgcFilter( static_cast<const QgsExpressionNodeBinaryOperator *>( node ), expression, context ); case QgsExpressionNode::ntInOperator: return expressionInOperatorToOgcFilter( static_cast<const QgsExpressionNodeInOperator *>( node ), expression, context ); case QgsExpressionNode::ntFunction: return expressionFunctionToOgcFilter( static_cast<const QgsExpressionNodeFunction *>( node ), expression, context ); case QgsExpressionNode::ntLiteral: return expressionLiteralToOgcFilter( static_cast<const QgsExpressionNodeLiteral *>( node ), expression, context ); case QgsExpressionNode::ntColumnRef: return expressionColumnRefToOgcFilter( static_cast<const QgsExpressionNodeColumnRef *>( node ), expression, context ); default: mErrorMessage = QObject::tr( "Node type not supported: %1" ).arg( node->nodeType() ); return QDomElement(); } } QDomElement QgsOgcUtilsExprToFilter::expressionUnaryOperatorToOgcFilter( const QgsExpressionNodeUnaryOperator *node, QgsExpression *expression, const QgsExpressionContext *context ) { const QDomElement operandElem = expressionNodeToOgcFilter( node->operand(), expression, context ); if ( !mErrorMessage.isEmpty() ) return QDomElement(); QDomElement uoElem; switch ( node->op() ) { case QgsExpressionNodeUnaryOperator::uoMinus: uoElem = mDoc.createElement( mFilterPrefix + ":Literal" ); if ( node->operand()->nodeType() == QgsExpressionNode::ntLiteral ) { // operand expression already created a Literal node: // take the literal value, prepend - and remove old literal node uoElem.appendChild( mDoc.createTextNode( "-" + operandElem.text() ) ); mDoc.removeChild( operandElem ); } else { mErrorMessage = QObject::tr( "This use of unary operator not implemented yet" ); return QDomElement(); } break; case QgsExpressionNodeUnaryOperator::uoNot: uoElem = mDoc.createElement( mFilterPrefix + ":Not" ); uoElem.appendChild( operandElem ); break; default: mErrorMessage = QObject::tr( "Unary operator '%1' not implemented yet" ).arg( node->text() ); return QDomElement(); } return uoElem; } QDomElement QgsOgcUtilsExprToFilter::expressionBinaryOperatorToOgcFilter( const QgsExpressionNodeBinaryOperator *node, QgsExpression *expression, const QgsExpressionContext *context ) { const QDomElement leftElem = expressionNodeToOgcFilter( node->opLeft(), expression, context ); if ( !mErrorMessage.isEmpty() ) return QDomElement(); QgsExpressionNodeBinaryOperator::BinaryOperator op = node->op(); // before right operator is parsed: to allow NULL handling if ( op == QgsExpressionNodeBinaryOperator::boIs || op == QgsExpressionNodeBinaryOperator::boIsNot ) { if ( node->opRight()->nodeType() == QgsExpressionNode::ntLiteral ) { const QgsExpressionNodeLiteral *rightLit = static_cast<const QgsExpressionNodeLiteral *>( node->opRight() ); if ( rightLit->value().isNull() ) { QDomElement elem = mDoc.createElement( mFilterPrefix + ":PropertyIsNull" ); elem.appendChild( leftElem ); if ( op == QgsExpressionNodeBinaryOperator::boIsNot ) { QDomElement notElem = mDoc.createElement( mFilterPrefix + ":Not" ); notElem.appendChild( elem ); return notElem; } return elem; } // continue with equal / not equal operator once the null case is handled op = ( op == QgsExpressionNodeBinaryOperator::boIs ? QgsExpressionNodeBinaryOperator::boEQ : QgsExpressionNodeBinaryOperator::boNE ); } } const QDomElement rightElem = expressionNodeToOgcFilter( node->opRight(), expression, context ); if ( !mErrorMessage.isEmpty() ) return QDomElement(); const QString opText = binaryOperatorToTagName( op ); if ( opText.isEmpty() ) { // not implemented binary operators // TODO: regex, % (mod), ^ (pow) are not supported yet mErrorMessage = QObject::tr( "Binary operator %1 not implemented yet" ).arg( node->text() ); return QDomElement(); } QDomElement boElem = mDoc.createElement( mFilterPrefix + ":" + opText ); if ( op == QgsExpressionNodeBinaryOperator::boLike || op == QgsExpressionNodeBinaryOperator::boILike ) { if ( op == QgsExpressionNodeBinaryOperator::boILike ) boElem.setAttribute( QStringLiteral( "matchCase" ), QStringLiteral( "false" ) ); // setup wildCards to <ogc:PropertyIsLike> boElem.setAttribute( QStringLiteral( "wildCard" ), QStringLiteral( "%" ) ); boElem.setAttribute( QStringLiteral( "singleChar" ), QStringLiteral( "_" ) ); if ( mFilterVersion == QgsOgcUtils::FILTER_OGC_1_0 ) boElem.setAttribute( QStringLiteral( "escape" ), QStringLiteral( "\\" ) ); else boElem.setAttribute( QStringLiteral( "escapeChar" ), QStringLiteral( "\\" ) ); } boElem.appendChild( leftElem ); boElem.appendChild( rightElem ); return boElem; } QDomElement QgsOgcUtilsExprToFilter::expressionLiteralToOgcFilter( const QgsExpressionNodeLiteral *node, QgsExpression *expression, const QgsExpressionContext *context ) { Q_UNUSED( expression ) Q_UNUSED( context ) QString value; switch ( node->value().type() ) { case QVariant::Int: value = QString::number( node->value().toInt() ); break; case QVariant::Double: value = qgsDoubleToString( node->value().toDouble() ); break; case QVariant::String: value = node->value().toString(); break; case QVariant::Date: value = node->value().toDate().toString( Qt::ISODate ); break; case QVariant::DateTime: value = node->value().toDateTime().toString( Qt::ISODate ); break; default: mErrorMessage = QObject::tr( "Literal type not supported: %1" ).arg( node->value().type() ); return QDomElement(); } QDomElement litElem = mDoc.createElement( mFilterPrefix + ":Literal" ); litElem.appendChild( mDoc.createTextNode( value ) ); return litElem; } QDomElement QgsOgcUtilsExprToFilter::expressionColumnRefToOgcFilter( const QgsExpressionNodeColumnRef *node, QgsExpression *expression, const QgsExpressionContext *context ) { Q_UNUSED( expression ) Q_UNUSED( context ) QDomElement propElem = mDoc.createElement( mFilterPrefix + ":" + mPropertyName ); propElem.appendChild( mDoc.createTextNode( node->name() ) ); return propElem; } QDomElement QgsOgcUtilsExprToFilter::expressionInOperatorToOgcFilter( const QgsExpressionNodeInOperator *node, QgsExpression *expression, const QgsExpressionContext *context ) { if ( node->list()->list().size() == 1 ) return expressionNodeToOgcFilter( node->list()->list()[0], expression, context ); QDomElement orElem = mDoc.createElement( mFilterPrefix + ":Or" ); const QDomElement leftNode = expressionNodeToOgcFilter( node->node(), expression, context ); const auto constList = node->list()->list(); for ( QgsExpressionNode *n : constList ) { const QDomElement listNode = expressionNodeToOgcFilter( n, expression, context ); if ( !mErrorMessage.isEmpty() ) return QDomElement(); QDomElement eqElem = mDoc.createElement( mFilterPrefix + ":PropertyIsEqualTo" ); eqElem.appendChild( leftNode.cloneNode() ); eqElem.appendChild( listNode ); orElem.appendChild( eqElem ); } if ( node->isNotIn() ) { QDomElement notElem = mDoc.createElement( mFilterPrefix + ":Not" ); notElem.appendChild( orElem ); return notElem; } return orElem; } Q_GLOBAL_STATIC_WITH_ARGS( QgsStringMap, BINARY_SPATIAL_OPS_MAP, ( { { QLatin1String( "disjoint" ), QLatin1String( "Disjoint" ) }, { QLatin1String( "intersects" ), QLatin1String( "Intersects" )}, { QLatin1String( "touches" ), QLatin1String( "Touches" ) }, { QLatin1String( "crosses" ), QLatin1String( "Crosses" ) }, { QLatin1String( "contains" ), QLatin1String( "Contains" ) }, { QLatin1String( "overlaps" ), QLatin1String( "Overlaps" ) }, { QLatin1String( "within" ), QLatin1String( "Within" ) } } ) ) static bool isBinarySpatialOperator( const QString &fnName ) { return BINARY_SPATIAL_OPS_MAP()->contains( fnName ); } static QString tagNameForSpatialOperator( const QString &fnName ) { return BINARY_SPATIAL_OPS_MAP()->value( fnName ); } static bool isGeometryColumn( const QgsExpressionNode *node ) { if ( node->nodeType() != QgsExpressionNode::ntFunction ) return false; const QgsExpressionNodeFunction *fn = static_cast<const QgsExpressionNodeFunction *>( node ); QgsExpressionFunction *fd = QgsExpression::Functions()[fn->fnIndex()]; return fd->name() == QLatin1String( "$geometry" ); } static QgsGeometry geometryFromConstExpr( const QgsExpressionNode *node ) { // Right now we support only geomFromWKT(' ..... ') // Ideally we should support any constant sub-expression (not dependent on feature's geometry or attributes) if ( node->nodeType() == QgsExpressionNode::ntFunction ) { const QgsExpressionNodeFunction *fnNode = static_cast<const QgsExpressionNodeFunction *>( node ); QgsExpressionFunction *fnDef = QgsExpression::Functions()[fnNode->fnIndex()]; if ( fnDef->name() == QLatin1String( "geom_from_wkt" ) ) { const QList<QgsExpressionNode *> &args = fnNode->args()->list(); if ( args[0]->nodeType() == QgsExpressionNode::ntLiteral ) { const QString wkt = static_cast<const QgsExpressionNodeLiteral *>( args[0] )->value().toString(); return QgsGeometry::fromWkt( wkt ); } } } return QgsGeometry(); } QDomElement QgsOgcUtilsExprToFilter::expressionFunctionToOgcFilter( const QgsExpressionNodeFunction *node, QgsExpression *expression, const QgsExpressionContext *context ) { QgsExpressionFunction *fd = QgsExpression::Functions()[node->fnIndex()]; if ( fd->name() == QLatin1String( "intersects_bbox" ) ) { QList<QgsExpressionNode *> argNodes = node->args()->list(); Q_ASSERT( argNodes.count() == 2 ); // binary spatial ops must have two args const QgsGeometry geom = geometryFromConstExpr( argNodes[1] ); if ( !geom.isNull() && isGeometryColumn( argNodes[0] ) ) { QgsRectangle rect = geom.boundingBox(); mGMLUsed = true; const QDomElement elemBox = ( mGMLVersion == QgsOgcUtils::GML_2_1_2 ) ? QgsOgcUtils::rectangleToGMLBox( &rect, mDoc, mSrsName, mInvertAxisOrientation ) : QgsOgcUtils::rectangleToGMLEnvelope( &rect, mDoc, mSrsName, mInvertAxisOrientation ); QDomElement geomProperty = mDoc.createElement( mFilterPrefix + ":" + mPropertyName ); geomProperty.appendChild( mDoc.createTextNode( mGeometryName ) ); QDomElement funcElem = mDoc.createElement( mFilterPrefix + ":BBOX" ); funcElem.appendChild( geomProperty ); funcElem.appendChild( elemBox ); return funcElem; } else { mErrorMessage = QObject::tr( "<BBOX> is currently supported only in form: bbox($geometry, geomFromWKT('…'))" ); return QDomElement(); } } if ( isBinarySpatialOperator( fd->name() ) ) { QList<QgsExpressionNode *> argNodes = node->args()->list(); Q_ASSERT( argNodes.count() == 2 ); // binary spatial ops must have two args QgsExpressionNode *otherNode = nullptr; if ( isGeometryColumn( argNodes[0] ) ) otherNode = argNodes[1]; else if ( isGeometryColumn( argNodes[1] ) ) otherNode = argNodes[0]; else { mErrorMessage = QObject::tr( "Unable to translate spatial operator: at least one must refer to geometry." ); return QDomElement(); } QDomElement otherGeomElem; // the other node must be a geometry constructor if ( otherNode->nodeType() != QgsExpressionNode::ntFunction ) { mErrorMessage = QObject::tr( "spatial operator: the other operator must be a geometry constructor function" ); return QDomElement(); } const QgsExpressionNodeFunction *otherFn = static_cast<const QgsExpressionNodeFunction *>( otherNode ); QgsExpressionFunction *otherFnDef = QgsExpression::Functions()[otherFn->fnIndex()]; if ( otherFnDef->name() == QLatin1String( "geom_from_wkt" ) ) { QgsExpressionNode *firstFnArg = otherFn->args()->list()[0]; if ( firstFnArg->nodeType() != QgsExpressionNode::ntLiteral ) { mErrorMessage = QObject::tr( "geom_from_wkt: argument must be string literal" ); return QDomElement(); } const QString wkt = static_cast<const QgsExpressionNodeLiteral *>( firstFnArg )->value().toString(); const QgsGeometry geom = QgsGeometry::fromWkt( wkt ); otherGeomElem = QgsOgcUtils::geometryToGML( geom, mDoc, mGMLVersion, mSrsName, mInvertAxisOrientation, QStringLiteral( "qgis_id_geom_%1" ).arg( mGeomId ) ); mGeomId ++; } else if ( otherFnDef->name() == QLatin1String( "geom_from_gml" ) ) { QgsExpressionNode *firstFnArg = otherFn->args()->list()[0]; if ( firstFnArg->nodeType() != QgsExpressionNode::ntLiteral ) { mErrorMessage = QObject::tr( "geom_from_gml: argument must be string literal" ); return QDomElement(); } QDomDocument geomDoc; const QString gml = static_cast<const QgsExpressionNodeLiteral *>( firstFnArg )->value().toString(); if ( !geomDoc.setContent( gml, true ) ) { mErrorMessage = QObject::tr( "geom_from_gml: unable to parse XML" ); return QDomElement(); } const QDomNode geomNode = mDoc.importNode( geomDoc.documentElement(), true ); otherGeomElem = geomNode.toElement(); } else { mErrorMessage = QObject::tr( "spatial operator: unknown geometry constructor function" ); return QDomElement(); } mGMLUsed = true; QDomElement funcElem = mDoc.createElement( mFilterPrefix + ":" + tagNameForSpatialOperator( fd->name() ) ); QDomElement geomProperty = mDoc.createElement( mFilterPrefix + ":" + mPropertyName ); geomProperty.appendChild( mDoc.createTextNode( mGeometryName ) ); funcElem.appendChild( geomProperty ); funcElem.appendChild( otherGeomElem ); return funcElem; } if ( fd->isStatic( node, expression, context ) ) { const QVariant result = fd->run( node->args(), context, expression, node ); const QgsExpressionNodeLiteral literal( result ); return expressionLiteralToOgcFilter( &literal, expression, context ); } if ( fd->params() == 0 ) { mErrorMessage = QObject::tr( "Special columns/constants are not supported." ); return QDomElement(); } // this is somehow wrong - we are just hoping that the other side supports the same functions as we do... QDomElement funcElem = mDoc.createElement( mFilterPrefix + ":Function" ); funcElem.setAttribute( QStringLiteral( "name" ), fd->name() ); const auto constList = node->args()->list(); for ( QgsExpressionNode *n : constList ) { const QDomElement childElem = expressionNodeToOgcFilter( n, expression, context ); if ( !mErrorMessage.isEmpty() ) return QDomElement(); funcElem.appendChild( childElem ); } return funcElem; } // QgsOgcUtilsSQLStatementToFilter::QgsOgcUtilsSQLStatementToFilter( QDomDocument &doc, QgsOgcUtils::GMLVersion gmlVersion, QgsOgcUtils::FilterVersion filterVersion, const QList<QgsOgcUtils::LayerProperties> &layerProperties, bool honourAxisOrientation, bool invertAxisOrientation, const QMap< QString, QString> &mapUnprefixedTypenameToPrefixedTypename ) : mDoc( doc ) , mGMLUsed( false ) , mGMLVersion( gmlVersion ) , mFilterVersion( filterVersion ) , mLayerProperties( layerProperties ) , mHonourAxisOrientation( honourAxisOrientation ) , mInvertAxisOrientation( invertAxisOrientation ) , mFilterPrefix( ( filterVersion == QgsOgcUtils::FILTER_FES_2_0 ) ? "fes" : "ogc" ) , mPropertyName( ( filterVersion == QgsOgcUtils::FILTER_FES_2_0 ) ? "ValueReference" : "PropertyName" ) , mGeomId( 1 ) , mMapUnprefixedTypenameToPrefixedTypename( mapUnprefixedTypenameToPrefixedTypename ) { } QDomElement QgsOgcUtilsSQLStatementToFilter::toOgcFilter( const QgsSQLStatement::Node *node ) { switch ( node->nodeType() ) { case QgsSQLStatement::ntUnaryOperator: return toOgcFilter( static_cast<const QgsSQLStatement::NodeUnaryOperator *>( node ) ); case QgsSQLStatement::ntBinaryOperator: return toOgcFilter( static_cast<const QgsSQLStatement::NodeBinaryOperator *>( node ) ); case QgsSQLStatement::ntInOperator: return toOgcFilter( static_cast<const QgsSQLStatement::NodeInOperator *>( node ) ); case QgsSQLStatement::ntBetweenOperator: return toOgcFilter( static_cast<const QgsSQLStatement::NodeBetweenOperator *>( node ) ); case QgsSQLStatement::ntFunction: return toOgcFilter( static_cast<const QgsSQLStatement::NodeFunction *>( node ) ); case QgsSQLStatement::ntLiteral: return toOgcFilter( static_cast<const QgsSQLStatement::NodeLiteral *>( node ) ); case QgsSQLStatement::ntColumnRef: return toOgcFilter( static_cast<const QgsSQLStatement::NodeColumnRef *>( node ) ); case QgsSQLStatement::ntSelect: return toOgcFilter( static_cast<const QgsSQLStatement::NodeSelect *>( node ) ); default: mErrorMessage = QObject::tr( "Node type not supported: %1" ).arg( node->nodeType() ); return QDomElement(); } } QDomElement QgsOgcUtilsSQLStatementToFilter::toOgcFilter( const QgsSQLStatement::NodeUnaryOperator *node ) { const QDomElement operandElem = toOgcFilter( node->operand() ); if ( !mErrorMessage.isEmpty() ) return QDomElement(); QDomElement uoElem; switch ( node->op() ) { case QgsSQLStatement::uoMinus: uoElem = mDoc.createElement( mFilterPrefix + ":Literal" ); if ( node->operand()->nodeType() == QgsSQLStatement::ntLiteral ) { // operand expression already created a Literal node: // take the literal value, prepend - and remove old literal node uoElem.appendChild( mDoc.createTextNode( "-" + operandElem.text() ) ); mDoc.removeChild( operandElem ); } else { mErrorMessage = QObject::tr( "This use of unary operator not implemented yet" ); return QDomElement(); } break; case QgsSQLStatement::uoNot: uoElem = mDoc.createElement( mFilterPrefix + ":Not" ); uoElem.appendChild( operandElem ); break; default: mErrorMessage = QObject::tr( "Unary operator %1 not implemented yet" ).arg( QgsSQLStatement::UNARY_OPERATOR_TEXT[node->op()] ); return QDomElement(); } return uoElem; } QDomElement QgsOgcUtilsSQLStatementToFilter::toOgcFilter( const QgsSQLStatement::NodeBinaryOperator *node ) { const QDomElement leftElem = toOgcFilter( node->opLeft() ); if ( !mErrorMessage.isEmpty() ) return QDomElement(); QgsSQLStatement::BinaryOperator op = node->op(); // before right operator is parsed: to allow NULL handling if ( op == QgsSQLStatement::boIs || op == QgsSQLStatement::boIsNot ) { if ( node->opRight()->nodeType() == QgsSQLStatement::ntLiteral ) { const QgsSQLStatement::NodeLiteral *rightLit = static_cast<const QgsSQLStatement::NodeLiteral *>( node->opRight() ); if ( rightLit->value().isNull() ) { QDomElement elem = mDoc.createElement( mFilterPrefix + ":PropertyIsNull" ); elem.appendChild( leftElem ); if ( op == QgsSQLStatement::boIsNot ) { QDomElement notElem = mDoc.createElement( mFilterPrefix + ":Not" ); notElem.appendChild( elem ); return notElem; } return elem; } // continue with equal / not equal operator once the null case is handled op = ( op == QgsSQLStatement::boIs ? QgsSQLStatement::boEQ : QgsSQLStatement::boNE ); } } const QDomElement rightElem = toOgcFilter( node->opRight() ); if ( !mErrorMessage.isEmpty() ) return QDomElement(); QString opText; if ( op == QgsSQLStatement::boOr ) opText = QStringLiteral( "Or" ); else if ( op == QgsSQLStatement::boAnd ) opText = QStringLiteral( "And" ); else if ( op == QgsSQLStatement::boEQ ) opText = QStringLiteral( "PropertyIsEqualTo" ); else if ( op == QgsSQLStatement::boNE ) opText = QStringLiteral( "PropertyIsNotEqualTo" ); else if ( op == QgsSQLStatement::boLE ) opText = QStringLiteral( "PropertyIsLessThanOrEqualTo" ); else if ( op == QgsSQLStatement::boGE ) opText = QStringLiteral( "PropertyIsGreaterThanOrEqualTo" ); else if ( op == QgsSQLStatement::boLT ) opText = QStringLiteral( "PropertyIsLessThan" ); else if ( op == QgsSQLStatement::boGT ) opText = QStringLiteral( "PropertyIsGreaterThan" ); else if ( op == QgsSQLStatement::boLike ) opText = QStringLiteral( "PropertyIsLike" ); else if ( op == QgsSQLStatement::boILike ) opText = QStringLiteral( "PropertyIsLike" ); if ( opText.isEmpty() ) { // not implemented binary operators mErrorMessage = QObject::tr( "Binary operator %1 not implemented yet" ).arg( QgsSQLStatement::BINARY_OPERATOR_TEXT[op] ); return QDomElement(); } QDomElement boElem = mDoc.createElement( mFilterPrefix + ":" + opText ); if ( op == QgsSQLStatement::boLike || op == QgsSQLStatement::boILike ) { if ( op == QgsSQLStatement::boILike ) boElem.setAttribute( QStringLiteral( "matchCase" ), QStringLiteral( "false" ) ); // setup wildCards to <ogc:PropertyIsLike> boElem.setAttribute( QStringLiteral( "wildCard" ), QStringLiteral( "%" ) ); boElem.setAttribute( QStringLiteral( "singleChar" ), QStringLiteral( "_" ) ); if ( mFilterVersion == QgsOgcUtils::FILTER_OGC_1_0 ) boElem.setAttribute( QStringLiteral( "escape" ), QStringLiteral( "\\" ) ); else boElem.setAttribute( QStringLiteral( "escapeChar" ), QStringLiteral( "\\" ) ); } boElem.appendChild( leftElem ); boElem.appendChild( rightElem ); return boElem; } QDomElement QgsOgcUtilsSQLStatementToFilter::toOgcFilter( const QgsSQLStatement::NodeLiteral *node ) { QString value; switch ( node->value().type() ) { case QVariant::Int: value = QString::number( node->value().toInt() ); break; case QVariant::LongLong: value = QString::number( node->value().toLongLong() ); break; case QVariant::Double: value = qgsDoubleToString( node->value().toDouble() ); break; case QVariant::String: value = node->value().toString(); break; default: mErrorMessage = QObject::tr( "Literal type not supported: %1" ).arg( node->value().type() ); return QDomElement(); } QDomElement litElem = mDoc.createElement( mFilterPrefix + ":Literal" ); litElem.appendChild( mDoc.createTextNode( value ) ); return litElem; } QDomElement QgsOgcUtilsSQLStatementToFilter::toOgcFilter( const QgsSQLStatement::NodeColumnRef *node ) { QDomElement propElem = mDoc.createElement( mFilterPrefix + ":" + mPropertyName ); if ( node->tableName().isEmpty() || mLayerProperties.size() == 1 ) { if ( mLayerProperties.size() == 1 && !mLayerProperties[0].mNamespacePrefix.isEmpty() ) propElem.appendChild( mDoc.createTextNode( mLayerProperties[0].mNamespacePrefix + QStringLiteral( ":" ) + node->name() ) ); else propElem.appendChild( mDoc.createTextNode( node->name() ) ); } else { QString tableName( mMapTableAliasToNames[node->tableName()] ); if ( mMapUnprefixedTypenameToPrefixedTypename.contains( tableName ) ) tableName = mMapUnprefixedTypenameToPrefixedTypename[tableName]; propElem.appendChild( mDoc.createTextNode( tableName + "/" + node->name() ) ); } return propElem; } QDomElement QgsOgcUtilsSQLStatementToFilter::toOgcFilter( const QgsSQLStatement::NodeInOperator *node ) { if ( node->list()->list().size() == 1 ) return toOgcFilter( node->list()->list()[0] ); QDomElement orElem = mDoc.createElement( mFilterPrefix + ":Or" ); const QDomElement leftNode = toOgcFilter( node->node() ); const auto constList = node->list()->list(); for ( QgsSQLStatement::Node *n : constList ) { const QDomElement listNode = toOgcFilter( n ); if ( !mErrorMessage.isEmpty() ) return QDomElement(); QDomElement eqElem = mDoc.createElement( mFilterPrefix + ":PropertyIsEqualTo" ); eqElem.appendChild( leftNode.cloneNode() ); eqElem.appendChild( listNode ); orElem.appendChild( eqElem ); } if ( node->isNotIn() ) { QDomElement notElem = mDoc.createElement( mFilterPrefix + ":Not" ); notElem.appendChild( orElem ); return notElem; } return orElem; } QDomElement QgsOgcUtilsSQLStatementToFilter::toOgcFilter( const QgsSQLStatement::NodeBetweenOperator *node ) { QDomElement elem = mDoc.createElement( mFilterPrefix + ":PropertyIsBetween" ); elem.appendChild( toOgcFilter( node->node() ) ); QDomElement lowerBoundary = mDoc.createElement( mFilterPrefix + ":LowerBoundary" ); lowerBoundary.appendChild( toOgcFilter( node->minVal() ) ); elem.appendChild( lowerBoundary ); QDomElement upperBoundary = mDoc.createElement( mFilterPrefix + ":UpperBoundary" ); upperBoundary.appendChild( toOgcFilter( node->maxVal() ) ); elem.appendChild( upperBoundary ); if ( node->isNotBetween() ) { QDomElement notElem = mDoc.createElement( mFilterPrefix + ":Not" ); notElem.appendChild( elem ); return notElem; } return elem; } static QString mapBinarySpatialToOgc( const QString &name ) { QString nameCompare( name ); #if QT_VERSION < QT_VERSION_CHECK(5, 15, 2) if ( name.size() > 3 && name.midRef( 0, 3 ).compare( QLatin1String( "ST_" ), Qt::CaseInsensitive ) == 0 ) nameCompare = name.mid( 3 ); #else if ( name.size() > 3 && QStringView {name}.mid( 0, 3 ).toString().compare( QLatin1String( "ST_" ), Qt::CaseInsensitive ) == 0 ) nameCompare = name.mid( 3 ); #endif QStringList spatialOps; spatialOps << QStringLiteral( "BBOX" ) << QStringLiteral( "Intersects" ) << QStringLiteral( "Contains" ) << QStringLiteral( "Crosses" ) << QStringLiteral( "Equals" ) << QStringLiteral( "Disjoint" ) << QStringLiteral( "Overlaps" ) << QStringLiteral( "Touches" ) << QStringLiteral( "Within" ); const auto constSpatialOps = spatialOps; for ( QString op : constSpatialOps ) { if ( nameCompare.compare( op, Qt::CaseInsensitive ) == 0 ) return op; } return QString(); } static QString mapTernarySpatialToOgc( const QString &name ) { QString nameCompare( name ); #if QT_VERSION < QT_VERSION_CHECK(5, 15, 2) if ( name.size() > 3 && name.midRef( 0, 3 ).compare( QLatin1String( "ST_" ), Qt::CaseInsensitive ) == 0 ) nameCompare = name.mid( 3 ); #else if ( name.size() > 3 && QStringView {name}.mid( 0, 3 ).compare( QLatin1String( "ST_" ), Qt::CaseInsensitive ) == 0 ) nameCompare = name.mid( 3 ); #endif if ( nameCompare.compare( QLatin1String( "DWithin" ), Qt::CaseInsensitive ) == 0 ) return QStringLiteral( "DWithin" ); if ( nameCompare.compare( QLatin1String( "Beyond" ), Qt::CaseInsensitive ) == 0 ) return QStringLiteral( "Beyond" ); return QString(); } QString QgsOgcUtilsSQLStatementToFilter::getGeometryColumnSRSName( const QgsSQLStatement::Node *node ) { if ( node->nodeType() != QgsSQLStatement::ntColumnRef ) return QString(); const QgsSQLStatement::NodeColumnRef *col = static_cast<const QgsSQLStatement::NodeColumnRef *>( node ); if ( !col->tableName().isEmpty() ) { const auto constMLayerProperties = mLayerProperties; for ( const QgsOgcUtils::LayerProperties &prop : constMLayerProperties ) { if ( prop.mName.compare( mMapTableAliasToNames[col->tableName()], Qt::CaseInsensitive ) == 0 && prop.mGeometryAttribute.compare( col->name(), Qt::CaseInsensitive ) == 0 ) { return prop.mSRSName; } } } if ( !mLayerProperties.empty() && mLayerProperties.at( 0 ).mGeometryAttribute.compare( col->name(), Qt::CaseInsensitive ) == 0 ) { return mLayerProperties.at( 0 ).mSRSName; } return QString(); } bool QgsOgcUtilsSQLStatementToFilter::processSRSName( const QgsSQLStatement::NodeFunction *mainNode, QList<QgsSQLStatement::Node *> args, bool lastArgIsSRSName, QString &srsName, bool &axisInversion ) { srsName = mCurrentSRSName; axisInversion = mInvertAxisOrientation; if ( lastArgIsSRSName ) { QgsSQLStatement::Node *lastArg = args[ args.size() - 1 ]; if ( lastArg->nodeType() != QgsSQLStatement::ntLiteral ) { mErrorMessage = QObject::tr( "%1: Last argument must be string or integer literal" ).arg( mainNode->name() ); return false; } const QgsSQLStatement::NodeLiteral *lit = static_cast<const QgsSQLStatement::NodeLiteral *>( lastArg ); if ( lit->value().type() == QVariant::Int ) { if ( mFilterVersion == QgsOgcUtils::FILTER_OGC_1_0 ) { srsName = "EPSG:" + QString::number( lit->value().toInt() ); } else { srsName = "urn:ogc:def:crs:EPSG::" + QString::number( lit->value().toInt() ); } } else { srsName = lit->value().toString(); if ( srsName.startsWith( QLatin1String( "EPSG:" ), Qt::CaseInsensitive ) ) return true; } } QgsCoordinateReferenceSystem crs; if ( !srsName.isEmpty() ) crs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( srsName ); if ( crs.isValid() ) { if ( mHonourAxisOrientation && crs.hasAxisInverted() ) { axisInversion = !axisInversion; } } return true; } QDomElement QgsOgcUtilsSQLStatementToFilter::toOgcFilter( const QgsSQLStatement::NodeFunction *node ) { // ST_GeometryFromText if ( node->name().compare( QLatin1String( "ST_GeometryFromText" ), Qt::CaseInsensitive ) == 0 ) { QList<QgsSQLStatement::Node *> args = node->args()->list(); if ( args.size() != 1 && args.size() != 2 ) { mErrorMessage = QObject::tr( "Function %1 should have 1 or 2 arguments" ).arg( node->name() ); return QDomElement(); } QgsSQLStatement::Node *firstFnArg = args[0]; if ( firstFnArg->nodeType() != QgsSQLStatement::ntLiteral ) { mErrorMessage = QObject::tr( "%1: First argument must be string literal" ).arg( node->name() ); return QDomElement(); } QString srsName; bool axisInversion; if ( ! processSRSName( node, args, args.size() == 2, srsName, axisInversion ) ) { return QDomElement(); } const QString wkt = static_cast<const QgsSQLStatement::NodeLiteral *>( firstFnArg )->value().toString(); const QgsGeometry geom = QgsGeometry::fromWkt( wkt ); const QDomElement geomElem = QgsOgcUtils::geometryToGML( geom, mDoc, mGMLVersion, srsName, axisInversion, QStringLiteral( "qgis_id_geom_%1" ).arg( mGeomId ) ); mGeomId ++; if ( geomElem.isNull() ) { mErrorMessage = QObject::tr( "%1: invalid WKT" ).arg( node->name() ); return QDomElement(); } mGMLUsed = true; return geomElem; } // ST_MakeEnvelope if ( node->name().compare( QLatin1String( "ST_MakeEnvelope" ), Qt::CaseInsensitive ) == 0 ) { QList<QgsSQLStatement::Node *> args = node->args()->list(); if ( args.size() != 4 && args.size() != 5 ) { mErrorMessage = QObject::tr( "Function %1 should have 4 or 5 arguments" ).arg( node->name() ); return QDomElement(); } QgsRectangle rect; for ( int i = 0; i < 4; i++ ) { QgsSQLStatement::Node *arg = args[i]; if ( arg->nodeType() != QgsSQLStatement::ntLiteral ) { mErrorMessage = QObject::tr( "%1: Argument %2 must be numeric literal" ).arg( node->name() ).arg( i + 1 ); return QDomElement(); } const QgsSQLStatement::NodeLiteral *lit = static_cast<const QgsSQLStatement::NodeLiteral *>( arg ); double val = 0.0; if ( lit->value().type() == QVariant::Int ) val = lit->value().toInt(); else if ( lit->value().type() == QVariant::LongLong ) val = lit->value().toLongLong(); else if ( lit->value().type() == QVariant::Double ) val = lit->value().toDouble(); else { mErrorMessage = QObject::tr( "%1 Argument %2 must be numeric literal" ).arg( node->name() ).arg( i + 1 ); return QDomElement(); } if ( i == 0 ) rect.setXMinimum( val ); else if ( i == 1 ) rect.setYMinimum( val ); else if ( i == 2 ) rect.setXMaximum( val ); else rect.setYMaximum( val ); } QString srsName; bool axisInversion; if ( ! processSRSName( node, args, args.size() == 5, srsName, axisInversion ) ) { return QDomElement(); } mGMLUsed = true; return ( mGMLVersion == QgsOgcUtils::GML_2_1_2 ) ? QgsOgcUtils::rectangleToGMLBox( &rect, mDoc, srsName, axisInversion, 15 ) : QgsOgcUtils::rectangleToGMLEnvelope( &rect, mDoc, srsName, axisInversion, 15 ); } // ST_GeomFromGML if ( node->name().compare( QLatin1String( "ST_GeomFromGML" ), Qt::CaseInsensitive ) == 0 ) { QList<QgsSQLStatement::Node *> args = node->args()->list(); if ( args.size() != 1 ) { mErrorMessage = QObject::tr( "Function %1 should have 1 argument" ).arg( node->name() ); return QDomElement(); } QgsSQLStatement::Node *firstFnArg = args[0]; if ( firstFnArg->nodeType() != QgsSQLStatement::ntLiteral ) { mErrorMessage = QObject::tr( "%1: Argument must be string literal" ).arg( node->name() ); return QDomElement(); } QDomDocument geomDoc; const QString gml = static_cast<const QgsSQLStatement::NodeLiteral *>( firstFnArg )->value().toString(); if ( !geomDoc.setContent( gml, true ) ) { mErrorMessage = QObject::tr( "ST_GeomFromGML: unable to parse XML" ); return QDomElement(); } const QDomNode geomNode = mDoc.importNode( geomDoc.documentElement(), true ); mGMLUsed = true; return geomNode.toElement(); } // Binary geometry operators QString ogcName( mapBinarySpatialToOgc( node->name() ) ); if ( !ogcName.isEmpty() ) { QList<QgsSQLStatement::Node *> args = node->args()->list(); if ( args.size() != 2 ) { mErrorMessage = QObject::tr( "Function %1 should have 2 arguments" ).arg( node->name() ); return QDomElement(); } for ( int i = 0; i < 2; i ++ ) { if ( args[i]->nodeType() == QgsSQLStatement::ntFunction && ( static_cast<const QgsSQLStatement::NodeFunction *>( args[i] )->name().compare( QLatin1String( "ST_GeometryFromText" ), Qt::CaseInsensitive ) == 0 || static_cast<const QgsSQLStatement::NodeFunction *>( args[i] )->name().compare( QLatin1String( "ST_MakeEnvelope" ), Qt::CaseInsensitive ) == 0 ) ) { mCurrentSRSName = getGeometryColumnSRSName( args[1 - i] ); break; } } //if( ogcName == "Intersects" && mFilterVersion == QgsOgcUtils::FILTER_OGC_1_0 ) // ogcName = "Intersect"; QDomElement funcElem = mDoc.createElement( mFilterPrefix + ":" + ogcName ); const auto constArgs = args; for ( QgsSQLStatement::Node *n : constArgs ) { const QDomElement childElem = toOgcFilter( n ); if ( !mErrorMessage.isEmpty() ) { mCurrentSRSName.clear(); return QDomElement(); } funcElem.appendChild( childElem ); } mCurrentSRSName.clear(); return funcElem; } ogcName = mapTernarySpatialToOgc( node->name() ); if ( !ogcName.isEmpty() ) { QList<QgsSQLStatement::Node *> args = node->args()->list(); if ( args.size() != 3 ) { mErrorMessage = QObject::tr( "Function %1 should have 3 arguments" ).arg( node->name() ); return QDomElement(); } for ( int i = 0; i < 2; i ++ ) { if ( args[i]->nodeType() == QgsSQLStatement::ntFunction && ( static_cast<const QgsSQLStatement::NodeFunction *>( args[i] )->name().compare( QLatin1String( "ST_GeometryFromText" ), Qt::CaseInsensitive ) == 0 || static_cast<const QgsSQLStatement::NodeFunction *>( args[i] )->name().compare( QLatin1String( "ST_MakeEnvelope" ), Qt::CaseInsensitive ) == 0 ) ) { mCurrentSRSName = getGeometryColumnSRSName( args[1 - i] ); break; } } QDomElement funcElem = mDoc.createElement( mFilterPrefix + ":" + node->name().mid( 3 ) ); for ( int i = 0; i < 2; i++ ) { const QDomElement childElem = toOgcFilter( args[i] ); if ( !mErrorMessage.isEmpty() ) { mCurrentSRSName.clear(); return QDomElement(); } funcElem.appendChild( childElem ); } mCurrentSRSName.clear(); QgsSQLStatement::Node *distanceNode = args[2]; if ( distanceNode->nodeType() != QgsSQLStatement::ntLiteral ) { mErrorMessage = QObject::tr( "Function %1 3rd argument should be a numeric value or a string made of a numeric value followed by a string" ).arg( node->name() ); return QDomElement(); } const QgsSQLStatement::NodeLiteral *lit = static_cast<const QgsSQLStatement::NodeLiteral *>( distanceNode ); if ( lit->value().isNull() ) { mErrorMessage = QObject::tr( "Function %1 3rd argument should be a numeric value or a string made of a numeric value followed by a string" ).arg( node->name() ); return QDomElement(); } QString distance; QString unit( QStringLiteral( "m" ) ); switch ( lit->value().type() ) { case QVariant::Int: distance = QString::number( lit->value().toInt() ); break; case QVariant::LongLong: distance = QString::number( lit->value().toLongLong() ); break; case QVariant::Double: distance = qgsDoubleToString( lit->value().toDouble() ); break; case QVariant::String: { distance = lit->value().toString(); for ( int i = 0; i < distance.size(); i++ ) { if ( !( ( distance[i] >= '0' && distance[i] <= '9' ) || distance[i] == '-' || distance[i] == '.' || distance[i] == 'e' || distance[i] == 'E' ) ) { unit = distance.mid( i ).trimmed(); distance = distance.mid( 0, i ); break; } } break; } default: mErrorMessage = QObject::tr( "Literal type not supported: %1" ).arg( lit->value().type() ); return QDomElement(); } QDomElement distanceElem = mDoc.createElement( mFilterPrefix + ":Distance" ); if ( mFilterVersion == QgsOgcUtils::FILTER_FES_2_0 ) distanceElem.setAttribute( QStringLiteral( "uom" ), unit ); else distanceElem.setAttribute( QStringLiteral( "unit" ), unit ); distanceElem.appendChild( mDoc.createTextNode( distance ) ); funcElem.appendChild( distanceElem ); return funcElem; } // Other function QDomElement funcElem = mDoc.createElement( mFilterPrefix + ":Function" ); funcElem.setAttribute( QStringLiteral( "name" ), node->name() ); const auto constList = node->args()->list(); for ( QgsSQLStatement::Node *n : constList ) { const QDomElement childElem = toOgcFilter( n ); if ( !mErrorMessage.isEmpty() ) return QDomElement(); funcElem.appendChild( childElem ); } return funcElem; } QDomElement QgsOgcUtilsSQLStatementToFilter::toOgcFilter( const QgsSQLStatement::NodeJoin *node, const QString &leftTable ) { QgsSQLStatement::Node *onExpr = node->onExpr(); if ( onExpr ) { return toOgcFilter( onExpr ); } QList<QDomElement> listElem; const auto constUsingColumns = node->usingColumns(); for ( const QString &columnName : constUsingColumns ) { QDomElement eqElem = mDoc.createElement( mFilterPrefix + ":PropertyIsEqualTo" ); QDomElement propElem1 = mDoc.createElement( mFilterPrefix + ":" + mPropertyName ); propElem1.appendChild( mDoc.createTextNode( leftTable + "/" + columnName ) ); eqElem.appendChild( propElem1 ); QDomElement propElem2 = mDoc.createElement( mFilterPrefix + ":" + mPropertyName ); propElem2.appendChild( mDoc.createTextNode( node->tableDef()->name() + "/" + columnName ) ); eqElem.appendChild( propElem2 ); listElem.append( eqElem ); } if ( listElem.size() == 1 ) { return listElem[0]; } else if ( listElem.size() > 1 ) { QDomElement andElem = mDoc.createElement( mFilterPrefix + ":And" ); const auto constListElem = listElem; for ( const QDomElement &elem : constListElem ) { andElem.appendChild( elem ); } return andElem; } return QDomElement(); } void QgsOgcUtilsSQLStatementToFilter::visit( const QgsSQLStatement::NodeTableDef *node ) { if ( node->alias().isEmpty() ) { mMapTableAliasToNames[ node->name()] = node->name(); } else { mMapTableAliasToNames[ node->alias()] = node->name(); } } QDomElement QgsOgcUtilsSQLStatementToFilter::toOgcFilter( const QgsSQLStatement::NodeSelect *node ) { QList<QDomElement> listElem; if ( mFilterVersion != QgsOgcUtils::FILTER_FES_2_0 && ( node->tables().size() != 1 || !node->joins().empty() ) ) { mErrorMessage = QObject::tr( "Joins are only supported with WFS 2.0" ); return QDomElement(); } // Register all table name aliases const auto constTables = node->tables(); for ( QgsSQLStatement::NodeTableDef *table : constTables ) { visit( table ); } const auto constJoins = node->joins(); for ( QgsSQLStatement::NodeJoin *join : constJoins ) { visit( join->tableDef() ); } // Process JOIN conditions const QList< QgsSQLStatement::NodeTableDef *> nodeTables = node->tables(); QString leftTable = nodeTables.at( nodeTables.length() - 1 )->name(); for ( QgsSQLStatement::NodeJoin *join : constJoins ) { const QDomElement joinElem = toOgcFilter( join, leftTable ); if ( !mErrorMessage.isEmpty() ) return QDomElement(); listElem.append( joinElem ); leftTable = join->tableDef()->name(); } // Process WHERE conditions if ( node->where() ) { const QDomElement whereElem = toOgcFilter( node->where() ); if ( !mErrorMessage.isEmpty() ) return QDomElement(); listElem.append( whereElem ); } // Concatenate all conditions if ( listElem.size() == 1 ) { return listElem[0]; } else if ( listElem.size() > 1 ) { QDomElement andElem = mDoc.createElement( mFilterPrefix + ":And" ); const auto constListElem = listElem; for ( const QDomElement &elem : constListElem ) { andElem.appendChild( elem ); } return andElem; } return QDomElement(); } QgsOgcUtilsExpressionFromFilter::QgsOgcUtilsExpressionFromFilter( const QgsOgcUtils::FilterVersion version, const QgsVectorLayer *layer ) : mLayer( layer ) { mPropertyName = QStringLiteral( "PropertyName" ); mPrefix = QStringLiteral( "ogc" ); if ( version == QgsOgcUtils::FILTER_FES_2_0 ) { mPropertyName = QStringLiteral( "ValueReference" ); mPrefix = QStringLiteral( "fes" ); } } QgsExpressionNode *QgsOgcUtilsExpressionFromFilter::nodeFromOgcFilter( const QDomElement &element ) { if ( element.isNull() ) return nullptr; // check for binary operators if ( isBinaryOperator( element.tagName() ) ) { return nodeBinaryOperatorFromOgcFilter( element ); } // check for spatial operators if ( isSpatialOperator( element.tagName() ) ) { return nodeSpatialOperatorFromOgcFilter( element ); } // check for other OGC operators, convert them to expressions if ( element.tagName() == QLatin1String( "Not" ) ) { return nodeNotFromOgcFilter( element ); } else if ( element.tagName() == QLatin1String( "PropertyIsNull" ) ) { return nodePropertyIsNullFromOgcFilter( element ); } else if ( element.tagName() == QLatin1String( "Literal" ) ) { return nodeLiteralFromOgcFilter( element ); } else if ( element.tagName() == QLatin1String( "Function" ) ) { return nodeFunctionFromOgcFilter( element ); } else if ( element.tagName() == mPropertyName ) { return nodeColumnRefFromOgcFilter( element ); } else if ( element.tagName() == QLatin1String( "PropertyIsBetween" ) ) { return nodeIsBetweenFromOgcFilter( element ); } mErrorMessage += QObject::tr( "unable to convert '%1' element to a valid expression: it is not supported yet or it has invalid arguments" ).arg( element.tagName() ); return nullptr; } QgsExpressionNodeBinaryOperator *QgsOgcUtilsExpressionFromFilter::nodeBinaryOperatorFromOgcFilter( const QDomElement &element ) { if ( element.isNull() ) return nullptr; int op = binaryOperatorFromTagName( element.tagName() ); if ( op < 0 ) { mErrorMessage = QObject::tr( "'%1' binary operator not supported." ).arg( element.tagName() ); return nullptr; } if ( op == QgsExpressionNodeBinaryOperator::boLike && element.hasAttribute( QStringLiteral( "matchCase" ) ) && element.attribute( QStringLiteral( "matchCase" ) ) == QLatin1String( "false" ) ) { op = QgsExpressionNodeBinaryOperator::boILike; } QDomElement operandElem = element.firstChildElement(); std::unique_ptr<QgsExpressionNode> expr( nodeFromOgcFilter( operandElem ) ); if ( !expr ) { mErrorMessage = QObject::tr( "invalid left operand for '%1' binary operator" ).arg( element.tagName() ); return nullptr; } const std::unique_ptr<QgsExpressionNode> leftOp( expr->clone() ); for ( operandElem = operandElem.nextSiblingElement(); !operandElem.isNull(); operandElem = operandElem.nextSiblingElement() ) { std::unique_ptr<QgsExpressionNode> opRight( nodeFromOgcFilter( operandElem ) ); if ( !opRight ) { mErrorMessage = QObject::tr( "invalid right operand for '%1' binary operator" ).arg( element.tagName() ); return nullptr; } if ( op == QgsExpressionNodeBinaryOperator::boLike || op == QgsExpressionNodeBinaryOperator::boILike ) { QString wildCard; if ( element.hasAttribute( QStringLiteral( "wildCard" ) ) ) { wildCard = element.attribute( QStringLiteral( "wildCard" ) ); } QString singleChar; if ( element.hasAttribute( QStringLiteral( "singleChar" ) ) ) { singleChar = element.attribute( QStringLiteral( "singleChar" ) ); } QString escape = QStringLiteral( "\\" ); if ( element.hasAttribute( QStringLiteral( "escape" ) ) ) { escape = element.attribute( QStringLiteral( "escape" ) ); } if ( element.hasAttribute( QStringLiteral( "escapeChar" ) ) ) { escape = element.attribute( QStringLiteral( "escapeChar" ) ); } // replace QString oprValue = static_cast<const QgsExpressionNodeLiteral *>( opRight.get() )->value().toString(); if ( !wildCard.isEmpty() && wildCard != QLatin1String( "%" ) ) { oprValue.replace( '%', QLatin1String( "\\%" ) ); if ( oprValue.startsWith( wildCard ) ) { oprValue.replace( 0, 1, QStringLiteral( "%" ) ); } const QRegularExpression rx( "[^" + QgsStringUtils::qRegExpEscape( escape ) + "](" + QgsStringUtils::qRegExpEscape( wildCard ) + ")" ); QRegularExpressionMatch match = rx.match( oprValue ); int pos; while ( match.hasMatch() ) { pos = match.capturedStart(); oprValue.replace( pos + 1, 1, QStringLiteral( "%" ) ); pos += 1; match = rx.match( oprValue, pos ); } oprValue.replace( escape + wildCard, wildCard ); } if ( !singleChar.isEmpty() && singleChar != QLatin1String( "_" ) ) { oprValue.replace( '_', QLatin1String( "\\_" ) ); if ( oprValue.startsWith( singleChar ) ) { oprValue.replace( 0, 1, QStringLiteral( "_" ) ); } const QRegularExpression rx( "[^" + QgsStringUtils::qRegExpEscape( escape ) + "](" + QgsStringUtils::qRegExpEscape( singleChar ) + ")" ); QRegularExpressionMatch match = rx.match( oprValue ); int pos; while ( match.hasMatch() ) { pos = match.capturedStart(); oprValue.replace( pos + 1, 1, QStringLiteral( "_" ) ); pos += 1; match = rx.match( oprValue, pos ); } oprValue.replace( escape + singleChar, singleChar ); } if ( !escape.isEmpty() && escape != QLatin1String( "\\" ) ) { oprValue.replace( escape + escape, escape ); } opRight.reset( new QgsExpressionNodeLiteral( oprValue ) ); } expr.reset( new QgsExpressionNodeBinaryOperator( static_cast< QgsExpressionNodeBinaryOperator::BinaryOperator >( op ), expr.release(), opRight.release() ) ); } if ( expr == leftOp ) { mErrorMessage = QObject::tr( "only one operand for '%1' binary operator" ).arg( element.tagName() ); return nullptr; } return dynamic_cast< QgsExpressionNodeBinaryOperator * >( expr.release() ); } QgsExpressionNodeFunction *QgsOgcUtilsExpressionFromFilter::nodeSpatialOperatorFromOgcFilter( const QDomElement &element ) { // we are exploiting the fact that our function names are the same as the XML tag names const int opIdx = QgsExpression::functionIndex( element.tagName().toLower() ); std::unique_ptr<QgsExpressionNode::NodeList> gml2Args( new QgsExpressionNode::NodeList() ); QDomElement childElem = element.firstChildElement(); QString gml2Str; while ( !childElem.isNull() && gml2Str.isEmpty() ) { if ( childElem.tagName() != mPropertyName ) { QTextStream gml2Stream( &gml2Str ); childElem.save( gml2Stream, 0 ); } childElem = childElem.nextSiblingElement(); } if ( !gml2Str.isEmpty() ) { gml2Args->append( new QgsExpressionNodeLiteral( QVariant( gml2Str.remove( '\n' ) ) ) ); } else { mErrorMessage = QObject::tr( "No OGC Geometry found" ); return nullptr; } std::unique_ptr<QgsExpressionNode::NodeList> opArgs( new QgsExpressionNode::NodeList() ); opArgs->append( new QgsExpressionNodeFunction( QgsExpression::functionIndex( QStringLiteral( "$geometry" ) ), new QgsExpressionNode::NodeList() ) ); opArgs->append( new QgsExpressionNodeFunction( QgsExpression::functionIndex( QStringLiteral( "geomFromGML" ) ), gml2Args.release() ) ); return new QgsExpressionNodeFunction( opIdx, opArgs.release() ); } QgsExpressionNodeColumnRef *QgsOgcUtilsExpressionFromFilter::nodeColumnRefFromOgcFilter( const QDomElement &element ) { if ( element.isNull() || element.tagName() != mPropertyName ) { mErrorMessage = QObject::tr( "%1:PropertyName expected, got %2" ).arg( mPrefix, element.tagName() ); return nullptr; } return new QgsExpressionNodeColumnRef( element.firstChild().nodeValue() ); } QgsExpressionNode *QgsOgcUtilsExpressionFromFilter::nodeLiteralFromOgcFilter( const QDomElement &element ) { if ( element.isNull() || element.tagName() != QLatin1String( "Literal" ) ) { mErrorMessage = QObject::tr( "%1:Literal expected, got %2" ).arg( mPrefix, element.tagName() ); return nullptr; } std::unique_ptr<QgsExpressionNode> root; // the literal content can have more children (e.g. CDATA section, text, ...) QDomNode childNode = element.firstChild(); while ( !childNode.isNull() ) { std::unique_ptr<QgsExpressionNode> operand; if ( childNode.nodeType() == QDomNode::ElementNode ) { // found a element node (e.g. PropertyName), convert it const QDomElement operandElem = childNode.toElement(); operand.reset( nodeFromOgcFilter( operandElem ) ); if ( !operand ) { mErrorMessage = QObject::tr( "'%1' is an invalid or not supported content for %2:Literal" ).arg( operandElem.tagName(), mPrefix ); return nullptr; } } else { // probably a text/CDATA node QVariant value = childNode.nodeValue(); bool converted = false; // try to convert the node content to corresponding field type if possible if ( mLayer ) { QDomElement propertyNameElement = element.previousSiblingElement( mPropertyName ); if ( propertyNameElement.isNull() || propertyNameElement.tagName() != mPropertyName ) { propertyNameElement = element.nextSiblingElement( mPropertyName ); } if ( !propertyNameElement.isNull() || propertyNameElement.tagName() == mPropertyName ) { const int fieldIndex = mLayer->fields().indexOf( propertyNameElement.firstChild().nodeValue() ); if ( fieldIndex != -1 ) { const QgsField field = mLayer->fields().field( propertyNameElement.firstChild().nodeValue() ); field.convertCompatible( value ); converted = true; } } } if ( !converted ) { // try to convert the node content to number if possible, // otherwise let's use it as string bool ok; const double d = value.toDouble( &ok ); if ( ok ) value = d; } operand.reset( new QgsExpressionNodeLiteral( value ) ); if ( !operand ) continue; } // use the concat operator to merge the ogc:Literal children if ( !root ) { root = std::move( operand ); } else { root.reset( new QgsExpressionNodeBinaryOperator( QgsExpressionNodeBinaryOperator::boConcat, root.release(), operand.release() ) ); } childNode = childNode.nextSibling(); } if ( root ) return root.release(); return nullptr; } QgsExpressionNodeUnaryOperator *QgsOgcUtilsExpressionFromFilter::nodeNotFromOgcFilter( const QDomElement &element ) { if ( element.tagName() != QLatin1String( "Not" ) ) return nullptr; const QDomElement operandElem = element.firstChildElement(); std::unique_ptr<QgsExpressionNode> operand( nodeFromOgcFilter( operandElem ) ); if ( !operand ) { mErrorMessage = QObject::tr( "invalid operand for '%1' unary operator" ).arg( element.tagName() ); return nullptr; } return new QgsExpressionNodeUnaryOperator( QgsExpressionNodeUnaryOperator::uoNot, operand.release() ); } QgsExpressionNodeBinaryOperator *QgsOgcUtilsExpressionFromFilter::nodePropertyIsNullFromOgcFilter( const QDomElement &element ) { // convert ogc:PropertyIsNull to IS operator with NULL right operand if ( element.tagName() != QLatin1String( "PropertyIsNull" ) ) { return nullptr; } const QDomElement operandElem = element.firstChildElement(); std::unique_ptr<QgsExpressionNode> opLeft( nodeFromOgcFilter( operandElem ) ); if ( !opLeft ) return nullptr; std::unique_ptr<QgsExpressionNode> opRight( new QgsExpressionNodeLiteral( QVariant() ) ); return new QgsExpressionNodeBinaryOperator( QgsExpressionNodeBinaryOperator::boIs, opLeft.release(), opRight.release() ); } QgsExpressionNodeFunction *QgsOgcUtilsExpressionFromFilter::nodeFunctionFromOgcFilter( const QDomElement &element ) { if ( element.isNull() || element.tagName() != QLatin1String( "Function" ) ) { mErrorMessage = QObject::tr( "%1:Function expected, got %2" ).arg( mPrefix, element.tagName() ); return nullptr; } for ( int i = 0; i < QgsExpression::Functions().size(); i++ ) { const QgsExpressionFunction *funcDef = QgsExpression::Functions()[i]; if ( element.attribute( QStringLiteral( "name" ) ) != funcDef->name() ) continue; std::unique_ptr<QgsExpressionNode::NodeList> args( new QgsExpressionNode::NodeList() ); QDomElement operandElem = element.firstChildElement(); while ( !operandElem.isNull() ) { std::unique_ptr<QgsExpressionNode> op( nodeFromOgcFilter( operandElem ) ); if ( !op ) { return nullptr; } args->append( op.release() ); operandElem = operandElem.nextSiblingElement(); } return new QgsExpressionNodeFunction( i, args.release() ); } return nullptr; } QgsExpressionNode *QgsOgcUtilsExpressionFromFilter::nodeIsBetweenFromOgcFilter( const QDomElement &element ) { // <ogc:PropertyIsBetween> encode a Range check std::unique_ptr<QgsExpressionNode> operand; std::unique_ptr<QgsExpressionNode> lowerBound; std::unique_ptr<QgsExpressionNode> upperBound; QDomElement operandElem = element.firstChildElement(); while ( !operandElem.isNull() ) { if ( operandElem.tagName() == QLatin1String( "LowerBoundary" ) ) { const QDomElement lowerBoundElem = operandElem.firstChildElement(); lowerBound.reset( nodeFromOgcFilter( lowerBoundElem ) ); } else if ( operandElem.tagName() == QLatin1String( "UpperBoundary" ) ) { const QDomElement upperBoundElem = operandElem.firstChildElement(); upperBound.reset( nodeFromOgcFilter( upperBoundElem ) ); } else { // <ogc:expression> operand.reset( nodeFromOgcFilter( operandElem ) ); } if ( operand && lowerBound && upperBound ) break; operandElem = operandElem.nextSiblingElement(); } if ( !operand || !lowerBound || !upperBound ) { mErrorMessage = QObject::tr( "missing some required sub-elements in %1:PropertyIsBetween" ).arg( mPrefix ); return nullptr; } std::unique_ptr<QgsExpressionNode> leOperator( new QgsExpressionNodeBinaryOperator( QgsExpressionNodeBinaryOperator::boLE, operand->clone(), upperBound.release() ) ); std::unique_ptr<QgsExpressionNode> geOperator( new QgsExpressionNodeBinaryOperator( QgsExpressionNodeBinaryOperator::boGE, operand.release(), lowerBound.release() ) ); return new QgsExpressionNodeBinaryOperator( QgsExpressionNodeBinaryOperator::boAnd, geOperator.release(), leOperator.release() ); } QString QgsOgcUtilsExpressionFromFilter::errorMessage() const { return mErrorMessage; }
gpl-2.0
xdajog/samsung_sources_i927
external/webkit/Tools/Scripts/webkitpy/tool/steps/updatechangelogswithreviewer.py
3469
# Copyright (C) 2010 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import os from webkitpy.common.checkout.changelog import ChangeLog from webkitpy.tool.grammar import pluralize from webkitpy.tool.steps.abstractstep import AbstractStep from webkitpy.tool.steps.options import Options from webkitpy.common.system.deprecated_logging import log, error class UpdateChangeLogsWithReviewer(AbstractStep): @classmethod def options(cls): return AbstractStep.options() + [ Options.git_commit, Options.reviewer, ] def _guess_reviewer_from_bug(self, bug_id): patches = self._tool.bugs.fetch_bug(bug_id).reviewed_patches() if len(patches) != 1: log("%s on bug %s, cannot infer reviewer." % (pluralize("reviewed patch", len(patches)), bug_id)) return None patch = patches[0] log("Guessing \"%s\" as reviewer from attachment %s on bug %s." % (patch.reviewer().full_name, patch.id(), bug_id)) return patch.reviewer().full_name def run(self, state): bug_id = state.get("bug_id") if not bug_id and state.get("patch"): bug_id = state.get("patch").bug_id() reviewer = self._options.reviewer if not reviewer: if not bug_id: log("No bug id provided and --reviewer= not provided. Not updating ChangeLogs with reviewer.") return reviewer = self._guess_reviewer_from_bug(bug_id) if not reviewer: log("Failed to guess reviewer from bug %s and --reviewer= not provided. Not updating ChangeLogs with reviewer." % bug_id) return # cached_lookup("changelogs") is always absolute paths. for changelog_path in self.cached_lookup(state, "changelogs"): ChangeLog(changelog_path).set_reviewer(reviewer) # Tell the world that we just changed something on disk so that the cached diff is invalidated. self.did_modify_checkout(state)
gpl-2.0
pplatek/adempiere
base/src/org/compiere/model/MTree_NodeBP.java
3425
/****************************************************************************** * Product: Adempiere ERP & CRM Smart Business Solution * * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * * This program is free software; you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * * by the Free Software Foundation. This program is distributed in the hope * * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * * with this program; if not, write to the Free Software Foundation, Inc., * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * For the text or an alternative of this public license, you may reach us * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * or via info@compiere.org or http://www.compiere.org/license.html * *****************************************************************************/ package org.compiere.model; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Properties; import java.util.logging.Level; import org.compiere.util.CLogger; import org.compiere.util.DB; /** * (Disk) Tree Node Model BPartner * * @author Jorg Janke * @version $Id: MTree_NodeBP.java,v 1.3 2006/07/30 00:58:38 jjanke Exp $ */ public class MTree_NodeBP extends X_AD_TreeNodeBP { /** * */ private static final long serialVersionUID = 5103486471442008006L; /** * Get Tree Node * @param tree tree * @param Node_ID node * @return node or null */ public static MTree_NodeBP get (MTree_Base tree, int Node_ID) { MTree_NodeBP retValue = null; String sql = "SELECT * FROM AD_TreeNodeBP WHERE AD_Tree_ID=? AND Node_ID=?"; PreparedStatement pstmt = null; try { pstmt = DB.prepareStatement (sql, tree.get_TrxName()); pstmt.setInt (1, tree.getAD_Tree_ID()); pstmt.setInt (2, Node_ID); ResultSet rs = pstmt.executeQuery (); if (rs.next ()) retValue = new MTree_NodeBP (tree.getCtx(), rs, tree.get_TrxName()); rs.close (); pstmt.close (); pstmt = null; } catch (Exception e) { s_log.log(Level.SEVERE, "get", e); } try { if (pstmt != null) pstmt.close (); pstmt = null; } catch (Exception e) { pstmt = null; } return retValue; } // get /** Static Logger */ private static CLogger s_log = CLogger.getCLogger (MTree_NodeBP.class); /** * Load Constructor * @param ctx context * @param rs result set * @param trxName transaction */ public MTree_NodeBP(Properties ctx, ResultSet rs, String trxName) { super(ctx, rs, trxName); } // MTree_NodeBP /** * Full Constructor * @param tree tree * @param Node_ID node */ public MTree_NodeBP (MTree_Base tree, int Node_ID) { super (tree.getCtx(), 0, tree.get_TrxName()); setClientOrg(tree); setAD_Tree_ID (tree.getAD_Tree_ID()); setNode_ID(Node_ID); // Add to root setParent_ID(0); setSeqNo (0); } // MTree_NodeBP } // MTree_NodeBP
gpl-2.0
PrasadG193/gcc_gimple_fe
libstdc++-v3/testsuite/experimental/filesystem/path/modifiers/replace_filename.cc
1347
// { dg-options "-std=gnu++11 -lstdc++fs" } // { dg-require-filesystem-ts "" } // Copyright (C) 2014-2016 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. // 8.4.5 path modifiers [path.modifiers] #include <experimental/filesystem> #include <testsuite_fs.h> #include <testsuite_hooks.h> using std::experimental::filesystem::path; void test01() { VERIFY( path("/foo").replace_filename("bar") == "/bar" ); VERIFY( path("/").replace_filename("bar") == "bar" ); } void test02() { for (const path& p : __gnu_test::test_paths) { path p2(p); p2.replace_filename(p.filename()); VERIFY( p2 == p ); } } int main() { test01(); test02(); }
gpl-2.0
erpcya/adempierePOS
posterita/posterita/src/main/org/posterita/struts/admin/CheckSequenceAction.java
2231
/** * Product: Posterita Web-Based POS and Adempiere Plugin * Copyright (C) 2007 Posterita Ltd * This file is part of POSterita * * POSterita is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * Created on 09-Feb-2006 */ package org.posterita.struts.admin; import java.util.Properties; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.posterita.core.TmkJSPEnv; import org.posterita.businesslogic.administration.CheckSequenceManager; import org.posterita.exceptions.SequenceUpdateException; import org.posterita.struts.core.BaseDispatchAction; public class CheckSequenceAction extends BaseDispatchAction { public static final String CHECK_SEQUENCE="checkSequence"; public ActionForward checkSequence(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) throws Exception { ActionForward fwd = init(mapping,form,request,response); if (fwd!=null) return fwd; Properties ctx = TmkJSPEnv.getCtx(request); try { CheckSequenceManager.runProcess(ctx); } catch(SequenceUpdateException e) { postGlobalError("error.update.sequence",request); return mapping.getInputForward(); } return mapping.findForward(CHECK_SEQUENCE); } }
gpl-2.0
aserna3/dolphin
Source/Core/Core/MemTools.cpp
9525
// Copyright 2008 Dolphin Emulator Project // Licensed under GPLv2+ // Refer to the license.txt file included. #include "Core/MemTools.h" #include <cstdio> #include <cstdlib> #include <cstring> #include <vector> #include "Common/CommonFuncs.h" #include "Common/CommonTypes.h" #include "Common/MsgHandler.h" #include "Common/Thread.h" #include "Core/MachineContext.h" #include "Core/PowerPC/JitInterface.h" #ifdef __FreeBSD__ #include <signal.h> #endif #ifndef _WIN32 #include <unistd.h> // Needed for _POSIX_VERSION #endif namespace EMM { #ifdef _WIN32 static LONG NTAPI Handler(PEXCEPTION_POINTERS pPtrs) { switch (pPtrs->ExceptionRecord->ExceptionCode) { case EXCEPTION_ACCESS_VIOLATION: { int accessType = (int)pPtrs->ExceptionRecord->ExceptionInformation[0]; if (accessType == 8) // Rule out DEP { return (DWORD)EXCEPTION_CONTINUE_SEARCH; } // virtual address of the inaccessible data uintptr_t badAddress = (uintptr_t)pPtrs->ExceptionRecord->ExceptionInformation[1]; CONTEXT* ctx = pPtrs->ContextRecord; if (JitInterface::HandleFault(badAddress, ctx)) { return (DWORD)EXCEPTION_CONTINUE_EXECUTION; } else { // Let's not prevent debugging. return (DWORD)EXCEPTION_CONTINUE_SEARCH; } } case EXCEPTION_STACK_OVERFLOW: if (JitInterface::HandleStackFault()) return EXCEPTION_CONTINUE_EXECUTION; else return EXCEPTION_CONTINUE_SEARCH; case EXCEPTION_ILLEGAL_INSTRUCTION: // No SSE support? Or simply bad codegen? return EXCEPTION_CONTINUE_SEARCH; case EXCEPTION_PRIV_INSTRUCTION: // okay, dynarec codegen is obviously broken. return EXCEPTION_CONTINUE_SEARCH; case EXCEPTION_IN_PAGE_ERROR: // okay, something went seriously wrong, out of memory? return EXCEPTION_CONTINUE_SEARCH; case EXCEPTION_BREAKPOINT: // might want to do something fun with this one day? return EXCEPTION_CONTINUE_SEARCH; default: return EXCEPTION_CONTINUE_SEARCH; } } void InstallExceptionHandler() { // Make sure this is only called once per process execution // Instead, could make a Uninstall function, but whatever.. static bool handlerInstalled = false; if (handlerInstalled) return; AddVectoredExceptionHandler(TRUE, Handler); handlerInstalled = true; } void UninstallExceptionHandler() { } #elif defined(__APPLE__) && !defined(USE_SIGACTION_ON_APPLE) static void CheckKR(const char* name, kern_return_t kr) { if (kr) { PanicAlert("%s failed: kr=%x", name, kr); } } static void ExceptionThread(mach_port_t port) { Common::SetCurrentThreadName("Mach exception thread"); #pragma pack(4) struct { mach_msg_header_t Head; NDR_record_t NDR; exception_type_t exception; mach_msg_type_number_t codeCnt; int64_t code[2]; int flavor; mach_msg_type_number_t old_stateCnt; natural_t old_state[x86_THREAD_STATE64_COUNT]; mach_msg_trailer_t trailer; } msg_in; struct { mach_msg_header_t Head; NDR_record_t NDR; kern_return_t RetCode; int flavor; mach_msg_type_number_t new_stateCnt; natural_t new_state[x86_THREAD_STATE64_COUNT]; } msg_out; #pragma pack() memset(&msg_in, 0xee, sizeof(msg_in)); memset(&msg_out, 0xee, sizeof(msg_out)); mach_msg_header_t* send_msg = nullptr; mach_msg_size_t send_size = 0; mach_msg_option_t option = MACH_RCV_MSG; while (true) { // If this isn't the first run, send the reply message. Then, receive // a message: either a mach_exception_raise_state RPC due to // thread_set_exception_ports, or MACH_NOTIFY_NO_SENDERS due to // mach_port_request_notification. CheckKR("mach_msg_overwrite", mach_msg_overwrite(send_msg, option, send_size, sizeof(msg_in), port, MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL, &msg_in.Head, 0)); if (msg_in.Head.msgh_id == MACH_NOTIFY_NO_SENDERS) { // the other thread exited mach_port_destroy(mach_task_self(), port); return; } if (msg_in.Head.msgh_id != 2406) { PanicAlert("unknown message received"); return; } if (msg_in.flavor != x86_THREAD_STATE64) { PanicAlert("unknown flavor %d (expected %d)", msg_in.flavor, x86_THREAD_STATE64); return; } x86_thread_state64_t* state = (x86_thread_state64_t*)msg_in.old_state; bool ok = JitInterface::HandleFault((uintptr_t)msg_in.code[1], state); // Set up the reply. msg_out.Head.msgh_bits = MACH_MSGH_BITS(MACH_MSGH_BITS_REMOTE(msg_in.Head.msgh_bits), 0); msg_out.Head.msgh_remote_port = msg_in.Head.msgh_remote_port; msg_out.Head.msgh_local_port = MACH_PORT_NULL; msg_out.Head.msgh_id = msg_in.Head.msgh_id + 100; msg_out.NDR = msg_in.NDR; if (ok) { msg_out.RetCode = KERN_SUCCESS; msg_out.flavor = x86_THREAD_STATE64; msg_out.new_stateCnt = x86_THREAD_STATE64_COUNT; memcpy(msg_out.new_state, msg_in.old_state, x86_THREAD_STATE64_COUNT * sizeof(natural_t)); } else { // Pass the exception to the next handler (debugger or crash). msg_out.RetCode = KERN_FAILURE; msg_out.flavor = 0; msg_out.new_stateCnt = 0; } msg_out.Head.msgh_size = offsetof(__typeof__(msg_out), new_state) + msg_out.new_stateCnt * sizeof(natural_t); send_msg = &msg_out.Head; send_size = msg_out.Head.msgh_size; option |= MACH_SEND_MSG; } } void InstallExceptionHandler() { mach_port_t port; CheckKR("mach_port_allocate", mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &port)); std::thread exc_thread(ExceptionThread, port); exc_thread.detach(); // Obtain a send right for thread_set_exception_ports to copy... CheckKR("mach_port_insert_right", mach_port_insert_right(mach_task_self(), port, port, MACH_MSG_TYPE_MAKE_SEND)); // Mach tries the following exception ports in order: thread, task, host. // Debuggers set the task port, so we grab the thread port. CheckKR("thread_set_exception_ports", thread_set_exception_ports(mach_thread_self(), EXC_MASK_BAD_ACCESS, port, EXCEPTION_STATE | MACH_EXCEPTION_CODES, x86_THREAD_STATE64)); // ...and get rid of our copy so that MACH_NOTIFY_NO_SENDERS works. CheckKR("mach_port_mod_refs", mach_port_mod_refs(mach_task_self(), port, MACH_PORT_RIGHT_SEND, -1)); mach_port_t previous; CheckKR("mach_port_request_notification", mach_port_request_notification(mach_task_self(), port, MACH_NOTIFY_NO_SENDERS, 0, port, MACH_MSG_TYPE_MAKE_SEND_ONCE, &previous)); } void UninstallExceptionHandler() { } #elif defined(_POSIX_VERSION) && !defined(_M_GENERIC) static struct sigaction old_sa_segv; static struct sigaction old_sa_bus; static void sigsegv_handler(int sig, siginfo_t* info, void* raw_context) { if (sig != SIGSEGV && sig != SIGBUS) { // We are not interested in other signals - handle it as usual. return; } ucontext_t* context = (ucontext_t*)raw_context; int sicode = info->si_code; if (sicode != SEGV_MAPERR && sicode != SEGV_ACCERR) { // Huh? Return. return; } uintptr_t bad_address = (uintptr_t)info->si_addr; // Get all the information we can out of the context. #ifdef __OpenBSD__ ucontext_t* ctx = context; #else mcontext_t* ctx = &context->uc_mcontext; #endif // assume it's not a write if (!JitInterface::HandleFault(bad_address, #ifdef __APPLE__ *ctx #else ctx #endif )) { // retry and crash // According to the sigaction man page, if sa_flags "SA_SIGINFO" is set to the sigaction // function pointer, otherwise sa_handler contains one of: // SIG_DEF: The 'default' action is performed // SIG_IGN: The signal is ignored // Any other value is a function pointer to a signal handler struct sigaction* old_sa; if (sig == SIGSEGV) { old_sa = &old_sa_segv; } else { old_sa = &old_sa_bus; } if (old_sa->sa_flags & SA_SIGINFO) { old_sa->sa_sigaction(sig, info, raw_context); return; } if (old_sa->sa_handler == SIG_DFL) { signal(sig, SIG_DFL); return; } if (old_sa->sa_handler == SIG_IGN) { // Ignore signal return; } old_sa->sa_handler(sig); } } void InstallExceptionHandler() { stack_t signal_stack; #ifdef __FreeBSD__ signal_stack.ss_sp = (char*)malloc(SIGSTKSZ); #else signal_stack.ss_sp = malloc(SIGSTKSZ); #endif signal_stack.ss_size = SIGSTKSZ; signal_stack.ss_flags = 0; if (sigaltstack(&signal_stack, nullptr)) PanicAlert("sigaltstack failed"); struct sigaction sa; sa.sa_handler = nullptr; sa.sa_sigaction = &sigsegv_handler; sa.sa_flags = SA_SIGINFO; sigemptyset(&sa.sa_mask); sigaction(SIGSEGV, &sa, &old_sa_segv); #ifdef __APPLE__ sigaction(SIGBUS, &sa, &old_sa_bus); #endif } void UninstallExceptionHandler() { stack_t signal_stack, old_stack; signal_stack.ss_flags = SS_DISABLE; if (!sigaltstack(&signal_stack, &old_stack) && !(old_stack.ss_flags & SS_DISABLE)) { free(old_stack.ss_sp); } sigaction(SIGSEGV, &old_sa_segv, nullptr); #ifdef __APPLE__ sigaction(SIGBUS, &old_sa_bus, nullptr); #endif } #else // _M_GENERIC or unsupported platform void InstallExceptionHandler() { } void UninstallExceptionHandler() { } #endif } // namespace
gpl-2.0
haffenloher/TextSecure
src/org/thoughtcrime/securesms/scribbles/viewmodel/Layer.java
3415
/** * Copyright (c) 2016 UPTech * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.thoughtcrime.securesms.scribbles.viewmodel; import android.support.annotation.FloatRange; import android.util.Log; public class Layer { /** * rotation relative to the layer center, in degrees */ @FloatRange(from = 0.0F, to = 360.0F) private float rotationInDegrees; private float scale; /** * top left X coordinate, relative to parent canvas */ private float x; /** * top left Y coordinate, relative to parent canvas */ private float y; /** * is layer flipped horizontally (by X-coordinate) */ private boolean isFlipped; public Layer() { reset(); } protected void reset() { this.rotationInDegrees = 0.0F; this.scale = 1.0F; this.isFlipped = false; this.x = 0.0F; this.y = 0.0F; } public void postScale(float scaleDiff) { Log.w("Layer", "ScaleDiff: " + scaleDiff); float newVal = scale + scaleDiff; if (newVal >= getMinScale() && newVal <= getMaxScale()) { scale = newVal; } } protected float getMaxScale() { return Limits.MAX_SCALE; } protected float getMinScale() { return Limits.MIN_SCALE; } public void postRotate(float rotationInDegreesDiff) { this.rotationInDegrees += rotationInDegreesDiff; this.rotationInDegrees %= 360.0F; } public void postTranslate(float dx, float dy) { this.x += dx; this.y += dy; } public void flip() { this.isFlipped = !isFlipped; } public float initialScale() { return Limits.INITIAL_ENTITY_SCALE; } public float getRotationInDegrees() { return rotationInDegrees; } public void setRotationInDegrees(@FloatRange(from = 0.0, to = 360.0) float rotationInDegrees) { this.rotationInDegrees = rotationInDegrees; } public float getScale() { return scale; } public void setScale(float scale) { this.scale = scale; } public float getX() { return x; } public void setX(float x) { this.x = x; } public float getY() { return y; } public void setY(float y) { this.y = y; } public boolean isFlipped() { return isFlipped; } public void setFlipped(boolean flipped) { isFlipped = flipped; } interface Limits { float MIN_SCALE = 0.06F; float MAX_SCALE = 4.0F; float INITIAL_ENTITY_SCALE = 0.4F; } }
gpl-3.0
hacklex/OpenRA
OpenRA.Platforms.Null/NullSound.cs
1565
#region Copyright & License Information /* * Copyright 2007-2015 The OpenRA Developers (see AUTHORS) * This file is part of OpenRA, which is free software. It is made * available to you under the terms of the GNU General Public License * as published by the Free Software Foundation. For more information, * see COPYING. */ #endregion using System; namespace OpenRA.Platforms.Null { sealed class NullSoundEngine : ISoundEngine { public SoundDevice[] AvailableDevices() { return new[] { new SoundDevice("Null", null, "Output Disabled") }; } public NullSoundEngine() { Console.WriteLine("Using Null sound engine which disables SFX completely"); } public ISoundSource AddSoundSourceFromMemory(byte[] data, int channels, int sampleBits, int sampleRate) { return new NullSoundSource(); } public ISound Play2D(ISoundSource sound, bool loop, bool relative, WPos pos, float volume, bool attenuateVolume) { return new NullSound(); } public void PauseSound(ISound sound, bool paused) { } public void StopSound(ISound sound) { } public void SetAllSoundsPaused(bool paused) { } public void StopAllSounds() { } public void SetListenerPosition(WPos position) { } public void SetSoundVolume(float volume, ISound music, ISound video) { } public float Volume { get; set; } public void Dispose() { } } class NullSoundSource : ISoundSource { } class NullSound : ISound { public float Volume { get; set; } public float SeekPosition { get { return 0; } } public bool Playing { get { return false; } } } }
gpl-3.0
georchestra/georchestra
mapfishapp/src/main/webapp/lib/proj4js/lib/defs/EPSG2742.js
117
Proj4js.defs["EPSG:2742"] = "+proj=tmerc +lat_0=0 +lon_0=144 +k=1 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs";
gpl-3.0
alachaum/dolibarr
htdocs/compta/salaries/info.php
1984
<?php /* Copyright (C) 2005-2015 Laurent Destailleur <eldy@users.sourceforge.net> * Copyright (C) 2015 Charlie BENKE <charlie@patas-monkey.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * \file htdocs/compta/salaries/info.php * \ingroup salaries * \brief Page with info about salaries contribution */ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/compta/salaries/class/paymentsalary.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/salaries.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; $langs->load("compta"); $langs->load("bills"); $langs->load("salaries"); $id=GETPOST('id','int'); $action=GETPOST("action"); // Security check $socid = GETPOST('socid','int'); if ($user->societe_id) $socid=$user->societe_id; $result = restrictedArea($user, 'salaries', '', '', ''); /* * View */ $help_url='EN:Module_Salaries|FR:Module Fiche de paie|ES:M&oacute;dulo Salarios'; llxHeader("",$langs->trans("Salaries"),$help_url); $salpayment = new PaymentSalary($db); $result = $salpayment->fetch($id); $salpayment->info($id); $head = salaries_prepare_head($salpayment); dol_fiche_head($head, 'info', $langs->trans("SalaryPayment"), 0, 'payment'); print '<table width="100%"><tr><td>'; dol_print_object_info($salpayment); print '</td></tr></table>'; print '</div>'; llxFooter(); $db->close();
gpl-3.0
mqueme/mautic
app/bundles/PointBundle/Entity/TriggerEvent.php
6433
<?php /** * @package Mautic * @copyright 2014 Mautic Contributors. All rights reserved. * @author Mautic * @link http://mautic.org * @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html */ namespace Mautic\PointBundle\Entity; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ORM\Mapping as ORM; use Mautic\ApiBundle\Serializer\Driver\ApiMetadataDriver; use Mautic\CoreBundle\Doctrine\Mapping\ClassMetadataBuilder; use Symfony\Component\Validator\Constraints as Assert; /** * Class TriggerEvent * * @package Mautic\PointBundle\Entity */ class TriggerEvent { /** * @var int */ private $id; /** * @var string */ private $name; /** * @var string */ private $description; /** * @var string */ private $type; /** * @var int */ private $order = 0; /** * @var array */ private $properties = array(); /** * @var Trigger */ private $trigger; /** * @var ArrayCollection */ private $log; /** * @var array */ private $changes; /** * Construct */ public function __construct () { $this->log = new ArrayCollection(); } /** * @param ORM\ClassMetadata $metadata */ public static function loadMetadata (ORM\ClassMetadata $metadata) { $builder = new ClassMetadataBuilder($metadata); $builder->setTable('point_trigger_events') ->setCustomRepositoryClass('Mautic\PointBundle\Entity\TriggerEventRepository') ->addIndex(array('type'), 'trigger_type_search'); $builder->addIdColumns(); $builder->createField('type', 'string') ->length(50) ->build(); $builder->createField('order', 'integer') ->columnName('action_order') ->build(); $builder->addField('properties', 'array'); $builder->createManyToOne('trigger', 'Trigger') ->inversedBy('events') ->addJoinColumn('trigger_id', 'id', false, false, 'CASCADE') ->build(); $builder->createOneToMany('log', 'LeadTriggerLog') ->mappedBy('event') ->cascadePersist() ->cascadeRemove() ->fetchExtraLazy() ->build(); } /** * Prepares the metadata for API usage * * @param $metadata */ public static function loadApiMetadata(ApiMetadataDriver $metadata) { $metadata->setGroupPrefix('trigger') ->addProperties( array( 'id', 'name', 'description', 'type', 'order', 'properties' ) ) ->build(); } /** * @param $prop * @param $val */ private function isChanged ($prop, $val) { if ($this->$prop != $val) { $this->changes[$prop] = array($this->$prop, $val); } } /** * @return array */ public function getChanges () { return $this->changes; } /** * Get id * * @return integer */ public function getId () { return $this->id; } /** * Set order * * @param integer $order * * @return TriggerEvent */ public function setOrder ($order) { $this->isChanged('order', $order); $this->order = $order; return $this; } /** * Get order * * @return integer */ public function getOrder () { return $this->order; } /** * Set properties * * @param array $properties * * @return TriggerEvent */ public function setProperties ($properties) { $this->isChanged('properties', $properties); $this->properties = $properties; return $this; } /** * Get properties * * @return array */ public function getProperties () { return $this->properties; } /** * Set trigger * * @param Trigger $trigger * * @return TriggerTriggerEvent */ public function setTrigger (Trigger $trigger) { $this->trigger = $trigger; return $this; } /** * Get trigger * * @return Trigger */ public function getTrigger () { return $this->trigger; } /** * Set type * * @param string $type * * @return TriggerEvent */ public function setType ($type) { $this->isChanged('type', $type); $this->type = $type; return $this; } /** * Get type * * @return string */ public function getType () { return $this->type; } /** * @return array */ public function convertToArray () { return get_object_vars($this); } /** * Set description * * @param string $description * * @return TriggerEvent */ public function setDescription ($description) { $this->isChanged('description', $description); $this->description = $description; return $this; } /** * Get description * * @return string */ public function getDescription () { return $this->description; } /** * Set name * * @param string $name * * @return TriggerEvent */ public function setName ($name) { $this->isChanged('name', $name); $this->name = $name; return $this; } /** * Get name * * @return string */ public function getName () { return $this->name; } /** * Add log * * @param LeadTriggerLog $log * * @return Log */ public function addLog (LeadTriggerLog $log) { $this->log[] = $log; return $this; } /** * Remove log * * @param LeadTriggerLog $log */ public function removeLog (LeadTriggerLog $log) { $this->log->removeElement($log); } /** * Get log * * @return \Doctrine\Common\Collections\Collection */ public function getLog () { return $this->log; } }
gpl-3.0
mm3/shattered-pixel-dungeon
src/com/shatteredpixel/shatteredpixeldungeon/items/weapon/melee/Spear.java
1104
/* * Pixel Dungeon * Copyright (C) 2012-2014 Oleg Dolya * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.shatteredpixel.shatteredpixeldungeon.items.weapon.melee; import com.shatteredpixel.shatteredpixeldungeon.sprites.ItemSpriteSheet; public class Spear extends MeleeWeapon { { name = "spear"; image = ItemSpriteSheet.SPEAR; } public Spear() { super( 2, 1f, 1.5f ); } @Override public String desc() { return "A slender wooden rod tipped with sharpened iron."; } }
gpl-3.0
xforce/glaucium
vendor/gopkg.in/olivere/elastic.v5/search_queries_geo_distance_test.go
1850
// Copyright 2012-present Oliver Eilhard. All rights reserved. // Use of this source code is governed by a MIT-license. // See http://olivere.mit-license.org/license.txt for details. package elastic import ( "encoding/json" "testing" ) func TestGeoDistanceQuery(t *testing.T) { q := NewGeoDistanceQuery("pin.location") q = q.Lat(40) q = q.Lon(-70) q = q.Distance("200km") q = q.DistanceType("plane") q = q.OptimizeBbox("memory") src, err := q.Source() if err != nil { t.Fatal(err) } data, err := json.Marshal(src) if err != nil { t.Fatalf("marshaling to JSON failed: %v", err) } got := string(data) expected := `{"geo_distance":{"distance":"200km","distance_type":"plane","optimize_bbox":"memory","pin.location":{"lat":40,"lon":-70}}}` if got != expected { t.Errorf("expected\n%s\n,got:\n%s", expected, got) } } func TestGeoDistanceQueryWithGeoPoint(t *testing.T) { q := NewGeoDistanceQuery("pin.location") q = q.GeoPoint(GeoPointFromLatLon(40, -70)) q = q.Distance("200km") src, err := q.Source() if err != nil { t.Fatal(err) } data, err := json.Marshal(src) if err != nil { t.Fatalf("marshaling to JSON failed: %v", err) } got := string(data) expected := `{"geo_distance":{"distance":"200km","pin.location":{"lat":40,"lon":-70}}}` if got != expected { t.Errorf("expected\n%s\n,got:\n%s", expected, got) } } func TestGeoDistanceQueryWithGeoHash(t *testing.T) { q := NewGeoDistanceQuery("pin.location") q = q.GeoHash("drm3btev3e86") q = q.Distance("12km") src, err := q.Source() if err != nil { t.Fatal(err) } data, err := json.Marshal(src) if err != nil { t.Fatalf("marshaling to JSON failed: %v", err) } got := string(data) expected := `{"geo_distance":{"distance":"12km","pin.location":"drm3btev3e86"}}` if got != expected { t.Errorf("expected\n%s\n,got:\n%s", expected, got) } }
mpl-2.0
Aravinthu/odoo
addons/mail/tests/test_invite.py
2347
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.mail.tests.common import TestMail from odoo.tools import mute_logger class TestInvite(TestMail): @mute_logger('odoo.addons.mail.models.mail_mail') def test_invite_email(self): mail_invite = self.env['mail.wizard.invite'].with_context({ 'default_res_model': 'mail.test', 'default_res_id': self.test_pigs.id }).sudo(self.user_employee.id).create({ 'partner_ids': [(4, self.user_portal.partner_id.id), (4, self.partner_1.id)], 'send_mail': True}) mail_invite.add_followers() # Test: Pigs followers should contain Admin, Bert self.assertEqual(self.test_pigs.message_partner_ids, self.user_portal.partner_id | self.partner_1, 'invite wizard: Pigs followers after invite is incorrect, should be Admin + added follower') self.assertEqual(self.test_pigs.message_follower_ids.mapped('channel_id'), self.env['mail.channel'], 'invite wizard: Pigs followers after invite is incorrect, should not have channels') # Test: (pretend to) send email and check subject, body self.assertEqual(len(self._mails), 2, 'invite wizard: sent email number incorrect, should be only for Bert') self.assertEqual(self._mails[0].get('subject'), 'Invitation to follow %s: Pigs' % self.env['mail.test']._description, 'invite wizard: subject of invitation email is incorrect') self.assertEqual(self._mails[1].get('subject'), 'Invitation to follow %s: Pigs' % self.env['mail.test']._description, 'invite wizard: subject of invitation email is incorrect') self.assertIn('%s invited you to follow %s document: Pigs' % (self.user_employee.name, self.env['mail.test']._description), self._mails[0].get('body'), 'invite wizard: body of invitation email is incorrect') self.assertIn('%s invited you to follow %s document: Pigs' % (self.user_employee.name, self.env['mail.test']._description), self._mails[1].get('body'), 'invite wizard: body of invitation email is incorrect')
agpl-3.0
ciniutek/cmslaravel
vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/WhoopsHandler.php
2065
<?php namespace Illuminate\Foundation\Exceptions; use Illuminate\Support\Arr; use Illuminate\Filesystem\Filesystem; use Whoops\Handler\PrettyPageHandler; class WhoopsHandler { /** * Create a new Whoops handler for debug mode. * * @return \Whoops\Handler\PrettyPageHandler */ public function forDebug() { return tap(new PrettyPageHandler, function ($handler) { $handler->handleUnconditionally(true); $this->registerApplicationPaths($handler) ->registerBlacklist($handler) ->registerEditor($handler); }); } /** * Register the application paths with the handler. * * @param \Whoops\Handler\PrettyPageHandler $handler * @return $this */ protected function registerApplicationPaths($handler) { $handler->setApplicationPaths( array_flip($this->directoriesExceptVendor()) ); return $this; } /** * Get the application paths except for the "vendor" directory. * * @return array */ protected function directoriesExceptVendor() { return Arr::except( array_flip((new Filesystem)->directories(base_path())), [base_path('vendor')] ); } /** * Register the blacklist with the handler. * * @param \Whoops\Handler\PrettyPageHandler $handler * @return $this */ protected function registerBlacklist($handler) { foreach (config('app.debug_blacklist', []) as $key => $secrets) { foreach ($secrets as $secret) { $handler->blacklist($key, $secret); } } return $this; } /** * Register the editor with the handler. * * @param \Whoops\Handler\PrettyPageHandler $handler * @return $this */ protected function registerEditor($handler) { if (config('app.editor', false)) { $handler->setEditor(config('app.editor')); } return $this; } }
unlicense
esi-mineset/spark
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/socket.scala
7894
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.sql.execution.streaming import java.io.{BufferedReader, InputStreamReader, IOException} import java.net.Socket import java.sql.Timestamp import java.text.SimpleDateFormat import java.util.{Calendar, Locale} import javax.annotation.concurrent.GuardedBy import scala.collection.mutable.ListBuffer import scala.util.{Failure, Success, Try} import org.apache.spark.internal.Logging import org.apache.spark.sql._ import org.apache.spark.sql.catalyst.InternalRow import org.apache.spark.sql.sources.{DataSourceRegister, StreamSourceProvider} import org.apache.spark.sql.types.{StringType, StructField, StructType, TimestampType} import org.apache.spark.unsafe.types.UTF8String object TextSocketSource { val SCHEMA_REGULAR = StructType(StructField("value", StringType) :: Nil) val SCHEMA_TIMESTAMP = StructType(StructField("value", StringType) :: StructField("timestamp", TimestampType) :: Nil) val DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US) } /** * A source that reads text lines through a TCP socket, designed only for tutorials and debugging. * This source will *not* work in production applications due to multiple reasons, including no * support for fault recovery and keeping all of the text read in memory forever. */ class TextSocketSource(host: String, port: Int, includeTimestamp: Boolean, sqlContext: SQLContext) extends Source with Logging { @GuardedBy("this") private var socket: Socket = null @GuardedBy("this") private var readThread: Thread = null /** * All batches from `lastCommittedOffset + 1` to `currentOffset`, inclusive. * Stored in a ListBuffer to facilitate removing committed batches. */ @GuardedBy("this") protected val batches = new ListBuffer[(String, Timestamp)] @GuardedBy("this") protected var currentOffset: LongOffset = new LongOffset(-1) @GuardedBy("this") protected var lastOffsetCommitted : LongOffset = new LongOffset(-1) initialize() private def initialize(): Unit = synchronized { socket = new Socket(host, port) val reader = new BufferedReader(new InputStreamReader(socket.getInputStream)) readThread = new Thread(s"TextSocketSource($host, $port)") { setDaemon(true) override def run(): Unit = { try { while (true) { val line = reader.readLine() if (line == null) { // End of file reached logWarning(s"Stream closed by $host:$port") return } TextSocketSource.this.synchronized { val newData = (line, Timestamp.valueOf( TextSocketSource.DATE_FORMAT.format(Calendar.getInstance().getTime())) ) currentOffset = currentOffset + 1 batches.append(newData) } } } catch { case e: IOException => } } } readThread.start() } /** Returns the schema of the data from this source */ override def schema: StructType = if (includeTimestamp) TextSocketSource.SCHEMA_TIMESTAMP else TextSocketSource.SCHEMA_REGULAR override def getOffset: Option[Offset] = synchronized { if (currentOffset.offset == -1) { None } else { Some(currentOffset) } } /** Returns the data that is between the offsets (`start`, `end`]. */ override def getBatch(start: Option[Offset], end: Offset): DataFrame = synchronized { val startOrdinal = start.flatMap(LongOffset.convert).getOrElse(LongOffset(-1)).offset.toInt + 1 val endOrdinal = LongOffset.convert(end).getOrElse(LongOffset(-1)).offset.toInt + 1 // Internal buffer only holds the batches after lastOffsetCommitted val rawList = synchronized { val sliceStart = startOrdinal - lastOffsetCommitted.offset.toInt - 1 val sliceEnd = endOrdinal - lastOffsetCommitted.offset.toInt - 1 batches.slice(sliceStart, sliceEnd) } val rdd = sqlContext.sparkContext .parallelize(rawList) .map { case (v, ts) => InternalRow(UTF8String.fromString(v), ts.getTime) } sqlContext.internalCreateDataFrame(rdd, schema, isStreaming = true) } override def commit(end: Offset): Unit = synchronized { val newOffset = LongOffset.convert(end).getOrElse( sys.error(s"TextSocketStream.commit() received an offset ($end) that did not " + s"originate with an instance of this class") ) val offsetDiff = (newOffset.offset - lastOffsetCommitted.offset).toInt if (offsetDiff < 0) { sys.error(s"Offsets committed out of order: $lastOffsetCommitted followed by $end") } batches.trimStart(offsetDiff) lastOffsetCommitted = newOffset } /** Stop this source. */ override def stop(): Unit = synchronized { if (socket != null) { try { // Unfortunately, BufferedReader.readLine() cannot be interrupted, so the only way to // stop the readThread is to close the socket. socket.close() } catch { case e: IOException => } socket = null } } override def toString: String = s"TextSocketSource[host: $host, port: $port]" } class TextSocketSourceProvider extends StreamSourceProvider with DataSourceRegister with Logging { private def parseIncludeTimestamp(params: Map[String, String]): Boolean = { Try(params.getOrElse("includeTimestamp", "false").toBoolean) match { case Success(bool) => bool case Failure(_) => throw new AnalysisException("includeTimestamp must be set to either \"true\" or \"false\"") } } /** Returns the name and schema of the source that can be used to continually read data. */ override def sourceSchema( sqlContext: SQLContext, schema: Option[StructType], providerName: String, parameters: Map[String, String]): (String, StructType) = { logWarning("The socket source should not be used for production applications! " + "It does not support recovery.") if (!parameters.contains("host")) { throw new AnalysisException("Set a host to read from with option(\"host\", ...).") } if (!parameters.contains("port")) { throw new AnalysisException("Set a port to read from with option(\"port\", ...).") } if (schema.nonEmpty) { throw new AnalysisException("The socket source does not support a user-specified schema.") } val sourceSchema = if (parseIncludeTimestamp(parameters)) { TextSocketSource.SCHEMA_TIMESTAMP } else { TextSocketSource.SCHEMA_REGULAR } ("textSocket", sourceSchema) } override def createSource( sqlContext: SQLContext, metadataPath: String, schema: Option[StructType], providerName: String, parameters: Map[String, String]): Source = { val host = parameters("host") val port = parameters("port").toInt new TextSocketSource(host, port, parseIncludeTimestamp(parameters), sqlContext) } /** String that represents the format that this data source provider uses. */ override def shortName(): String = "socket" }
apache-2.0
nmoghadam/jbpm
jbpm-flow/src/main/java/org/jbpm/process/core/validation/impl/ProcessValidationErrorImpl.java
1313
/** * Copyright 2010 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jbpm.process.core.validation.impl; import org.kie.api.definition.process.Process; import org.jbpm.process.core.validation.ProcessValidationError; public class ProcessValidationErrorImpl implements ProcessValidationError { private Process process; private String message; public ProcessValidationErrorImpl(Process process, String message) { this.process = process; this.message = message; } public String getMessage() { return message; } public Process getProcess() { return process; } public String toString() { return "Process '" + process.getName() + "' [" + process.getId() + "]: " + getMessage(); } }
apache-2.0
alivecor/tensorflow
tensorflow/python/keras/_impl/keras/datasets/boston_housing.py
2052
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Boston housing price regression dataset. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python.keras._impl.keras.utils.data_utils import get_file def load_data(path='boston_housing.npz', seed=113, test_split=0.2): """Loads the Boston Housing dataset. Arguments: path: path where to cache the dataset locally (relative to ~/.keras/datasets). seed: Random seed for shuffling the data before computing the test split. test_split: fraction of the data to reserve as test set. Returns: Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`. """ assert 0 <= test_split < 1 fh = 'f553886a1f8d56431e820c5b82552d9d95cfcb96d1e678153f8839538947dff5' path = get_file( path, origin='https://s3.amazonaws.com/keras-datasets/boston_housing.npz', file_hash=fh) f = np.load(path) x = f['x'] y = f['y'] f.close() np.random.seed(seed) np.random.shuffle(x) np.random.seed(seed) np.random.shuffle(y) x_train = np.array(x[:int(len(x) * (1 - test_split))]) y_train = np.array(y[:int(len(x) * (1 - test_split))]) x_test = np.array(x[int(len(x) * (1 - test_split)):]) y_test = np.array(y[int(len(x) * (1 - test_split)):]) return (x_train, y_train), (x_test, y_test)
apache-2.0
shangyi0102/spring-boot
spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfoTests.java
4387
/* * Copyright 2012-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.gradle.tasks.buildinfo; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.Properties; import org.gradle.api.Project; import org.gradle.testfixtures.ProjectBuilder; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link BuildInfo}. * * @author Andy Wilkinson */ public class BuildInfoTests { @Rule public TemporaryFolder temp = new TemporaryFolder(); @Test public void basicExecution() { Properties properties = buildInfoProperties(createTask(createProject("test"))); assertThat(properties).containsKey("build.time"); assertThat(properties).containsEntry("build.artifact", "unspecified"); assertThat(properties).containsEntry("build.group", ""); assertThat(properties).containsEntry("build.name", "test"); assertThat(properties).containsEntry("build.version", "unspecified"); } @Test public void customArtifactIsReflectedInProperties() { BuildInfo task = createTask(createProject("test")); task.getProperties().setArtifact("custom"); assertThat(buildInfoProperties(task)).containsEntry("build.artifact", "custom"); } @Test public void projectGroupIsReflectedInProperties() { BuildInfo task = createTask(createProject("test")); task.getProject().setGroup("com.example"); assertThat(buildInfoProperties(task)).containsEntry("build.group", "com.example"); } @Test public void customGroupIsReflectedInProperties() { BuildInfo task = createTask(createProject("test")); task.getProperties().setGroup("com.example"); assertThat(buildInfoProperties(task)).containsEntry("build.group", "com.example"); } @Test public void customNameIsReflectedInProperties() { BuildInfo task = createTask(createProject("test")); task.getProperties().setName("Example"); assertThat(buildInfoProperties(task)).containsEntry("build.name", "Example"); } @Test public void projectVersionIsReflectedInProperties() { BuildInfo task = createTask(createProject("test")); task.getProject().setVersion("1.2.3"); assertThat(buildInfoProperties(task)).containsEntry("build.version", "1.2.3"); } @Test public void customVersionIsReflectedInProperties() { BuildInfo task = createTask(createProject("test")); task.getProperties().setVersion("2.3.4"); assertThat(buildInfoProperties(task)).containsEntry("build.version", "2.3.4"); } @Test public void additionalPropertiesAreReflectedInProperties() { BuildInfo task = createTask(createProject("test")); task.getProperties().getAdditional().put("a", "alpha"); task.getProperties().getAdditional().put("b", "bravo"); assertThat(buildInfoProperties(task)).containsEntry("build.a", "alpha"); assertThat(buildInfoProperties(task)).containsEntry("build.b", "bravo"); } private Project createProject(String projectName) { try { File projectDir = this.temp.newFolder(projectName); return ProjectBuilder.builder().withProjectDir(projectDir) .withName(projectName).build(); } catch (IOException ex) { throw new RuntimeException(ex); } } private BuildInfo createTask(Project project) { return project.getTasks().create("testBuildInfo", BuildInfo.class); } private Properties buildInfoProperties(BuildInfo task) { task.generateBuildProperties(); return buildInfoProperties( new File(task.getDestinationDir(), "build-info.properties")); } private Properties buildInfoProperties(File file) { assertThat(file).isFile(); Properties properties = new Properties(); try (FileReader reader = new FileReader(file)) { properties.load(reader); return properties; } catch (IOException ex) { throw new RuntimeException(ex); } } }
apache-2.0
usc-isi/horizon-old
horizon/horizon/tests/views.py
1083
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2011 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from django import http def fakeView(request): resp = http.HttpResponse() resp.write('<html><body><p>' 'This is a fake httpresponse from a fake view for testing ' ' purposes only' '</p></body></html>') return resp
apache-2.0
pkit/hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/mover/TestStorageMover.java
27023
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hdfs.server.mover; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.StorageType; import org.apache.hadoop.hdfs.protocol.BlockStoragePolicy; import org.apache.hadoop.hdfs.DFSConfigKeys; import org.apache.hadoop.hdfs.DFSOutputStream; import org.apache.hadoop.hdfs.DFSTestUtil; import org.apache.hadoop.hdfs.DFSUtil; import org.apache.hadoop.hdfs.DistributedFileSystem; import org.apache.hadoop.hdfs.HdfsConfiguration; import org.apache.hadoop.hdfs.MiniDFSCluster; import org.apache.hadoop.hdfs.protocol.DirectoryListing; import org.apache.hadoop.hdfs.protocol.HdfsConstants; import org.apache.hadoop.hdfs.protocol.HdfsFileStatus; import org.apache.hadoop.hdfs.protocol.HdfsLocatedFileStatus; import org.apache.hadoop.hdfs.protocol.LocatedBlock; import org.apache.hadoop.hdfs.protocol.LocatedBlocks; import org.apache.hadoop.hdfs.protocol.datatransfer.DataTransferProtocol; import org.apache.hadoop.hdfs.server.balancer.Dispatcher; import org.apache.hadoop.hdfs.server.balancer.ExitStatus; import org.apache.hadoop.hdfs.server.balancer.TestBalancer; import org.apache.hadoop.hdfs.server.blockmanagement.BlockPlacementPolicy; import org.apache.hadoop.hdfs.server.blockmanagement.BlockStoragePolicySuite; import org.apache.hadoop.hdfs.server.datanode.DataNode; import org.apache.hadoop.hdfs.server.datanode.DataNodeTestUtils; import org.apache.hadoop.hdfs.server.datanode.fsdataset.FsDatasetSpi; import org.apache.hadoop.hdfs.server.datanode.fsdataset.FsVolumeSpi; import org.apache.hadoop.hdfs.server.datanode.fsdataset.impl.FsVolumeImpl; import org.apache.hadoop.hdfs.server.namenode.snapshot.SnapshotTestHelper; import org.apache.hadoop.io.IOUtils; import org.apache.hadoop.test.GenericTestUtils; import org.apache.log4j.Level; import org.junit.Assert; import org.junit.Test; import com.google.common.base.Preconditions; import com.google.common.collect.Maps; /** * Test the data migration tool (for Archival Storage) */ public class TestStorageMover { static final Log LOG = LogFactory.getLog(TestStorageMover.class); static { GenericTestUtils.setLogLevel(LogFactory.getLog(BlockPlacementPolicy.class), Level.ALL); GenericTestUtils.setLogLevel(LogFactory.getLog(Dispatcher.class), Level.ALL); GenericTestUtils.setLogLevel(DataTransferProtocol.LOG, Level.ALL); } private static final int BLOCK_SIZE = 1024; private static final short REPL = 3; private static final int NUM_DATANODES = 6; private static final Configuration DEFAULT_CONF = new HdfsConfiguration(); private static final BlockStoragePolicySuite DEFAULT_POLICIES; private static final BlockStoragePolicy HOT; private static final BlockStoragePolicy WARM; private static final BlockStoragePolicy COLD; static { DEFAULT_CONF.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, BLOCK_SIZE); DEFAULT_CONF.setLong(DFSConfigKeys.DFS_HEARTBEAT_INTERVAL_KEY, 1L); DEFAULT_CONF.setLong(DFSConfigKeys.DFS_NAMENODE_REPLICATION_INTERVAL_KEY, 2L); DEFAULT_CONF.setLong(DFSConfigKeys.DFS_MOVER_MOVEDWINWIDTH_KEY, 2000L); DEFAULT_POLICIES = BlockStoragePolicySuite.createDefaultSuite(); HOT = DEFAULT_POLICIES.getPolicy(HdfsConstants.HOT_STORAGE_POLICY_NAME); WARM = DEFAULT_POLICIES.getPolicy(HdfsConstants.WARM_STORAGE_POLICY_NAME); COLD = DEFAULT_POLICIES.getPolicy(HdfsConstants.COLD_STORAGE_POLICY_NAME); TestBalancer.initTestSetup(); Dispatcher.setDelayAfterErrors(1000L); } /** * This scheme defines files/directories and their block storage policies. It * also defines snapshots. */ static class NamespaceScheme { final List<Path> dirs; final List<Path> files; final long fileSize; final Map<Path, List<String>> snapshotMap; final Map<Path, BlockStoragePolicy> policyMap; NamespaceScheme(List<Path> dirs, List<Path> files, long fileSize, Map<Path,List<String>> snapshotMap, Map<Path, BlockStoragePolicy> policyMap) { this.dirs = dirs == null? Collections.<Path>emptyList(): dirs; this.files = files == null? Collections.<Path>emptyList(): files; this.fileSize = fileSize; this.snapshotMap = snapshotMap == null ? Collections.<Path, List<String>>emptyMap() : snapshotMap; this.policyMap = policyMap; } /** * Create files/directories/snapshots. */ void prepare(DistributedFileSystem dfs, short repl) throws Exception { for (Path d : dirs) { dfs.mkdirs(d); } for (Path file : files) { DFSTestUtil.createFile(dfs, file, fileSize, repl, 0L); } for (Map.Entry<Path, List<String>> entry : snapshotMap.entrySet()) { for (String snapshot : entry.getValue()) { SnapshotTestHelper.createSnapshot(dfs, entry.getKey(), snapshot); } } } /** * Set storage policies according to the corresponding scheme. */ void setStoragePolicy(DistributedFileSystem dfs) throws Exception { for (Map.Entry<Path, BlockStoragePolicy> entry : policyMap.entrySet()) { dfs.setStoragePolicy(entry.getKey(), entry.getValue().getName()); } } } /** * This scheme defines DataNodes and their storage, including storage types * and remaining capacities. */ static class ClusterScheme { final Configuration conf; final int numDataNodes; final short repl; final StorageType[][] storageTypes; final long[][] storageCapacities; ClusterScheme() { this(DEFAULT_CONF, NUM_DATANODES, REPL, genStorageTypes(NUM_DATANODES), null); } ClusterScheme(Configuration conf, int numDataNodes, short repl, StorageType[][] types, long[][] capacities) { Preconditions.checkArgument(types == null || types.length == numDataNodes); Preconditions.checkArgument(capacities == null || capacities.length == numDataNodes); this.conf = conf; this.numDataNodes = numDataNodes; this.repl = repl; this.storageTypes = types; this.storageCapacities = capacities; } } class MigrationTest { private final ClusterScheme clusterScheme; private final NamespaceScheme nsScheme; private final Configuration conf; private MiniDFSCluster cluster; private DistributedFileSystem dfs; private final BlockStoragePolicySuite policies; MigrationTest(ClusterScheme cScheme, NamespaceScheme nsScheme) { this.clusterScheme = cScheme; this.nsScheme = nsScheme; this.conf = clusterScheme.conf; this.policies = DEFAULT_POLICIES; } /** * Set up the cluster and start NameNode and DataNodes according to the * corresponding scheme. */ void setupCluster() throws Exception { cluster = new MiniDFSCluster.Builder(conf).numDataNodes(clusterScheme .numDataNodes).storageTypes(clusterScheme.storageTypes) .storageCapacities(clusterScheme.storageCapacities).build(); cluster.waitActive(); dfs = cluster.getFileSystem(); } private void runBasicTest(boolean shutdown) throws Exception { setupCluster(); try { prepareNamespace(); verify(true); setStoragePolicy(); migrate(ExitStatus.SUCCESS); verify(true); } finally { if (shutdown) { shutdownCluster(); } } } void shutdownCluster() throws Exception { IOUtils.cleanup(null, dfs); if (cluster != null) { cluster.shutdown(); } } /** * Create files/directories and set their storage policies according to the * corresponding scheme. */ void prepareNamespace() throws Exception { nsScheme.prepare(dfs, clusterScheme.repl); } void setStoragePolicy() throws Exception { nsScheme.setStoragePolicy(dfs); } /** * Run the migration tool. */ void migrate(ExitStatus expectedExitCode) throws Exception { runMover(expectedExitCode); Thread.sleep(5000); // let the NN finish deletion } /** * Verify block locations after running the migration tool. */ void verify(boolean verifyAll) throws Exception { for (DataNode dn : cluster.getDataNodes()) { DataNodeTestUtils.triggerBlockReport(dn); } if (verifyAll) { verifyNamespace(); } } private void runMover(ExitStatus expectedExitCode) throws Exception { Collection<URI> namenodes = DFSUtil.getNsServiceRpcUris(conf); Map<URI, List<Path>> nnMap = Maps.newHashMap(); for (URI nn : namenodes) { nnMap.put(nn, null); } int result = Mover.run(nnMap, conf); Assert.assertEquals(expectedExitCode.getExitCode(), result); } private void verifyNamespace() throws Exception { HdfsFileStatus status = dfs.getClient().getFileInfo("/"); verifyRecursively(null, status); } private void verifyRecursively(final Path parent, final HdfsFileStatus status) throws Exception { if (status.isDir()) { Path fullPath = parent == null ? new Path("/") : status.getFullPath(parent); DirectoryListing children = dfs.getClient().listPaths( fullPath.toString(), HdfsFileStatus.EMPTY_NAME, true); for (HdfsFileStatus child : children.getPartialListing()) { verifyRecursively(fullPath, child); } } else if (!status.isSymlink()) { // is file verifyFile(parent, status, null); } } void verifyFile(final Path file, final Byte expectedPolicyId) throws Exception { final Path parent = file.getParent(); DirectoryListing children = dfs.getClient().listPaths( parent.toString(), HdfsFileStatus.EMPTY_NAME, true); for (HdfsFileStatus child : children.getPartialListing()) { if (child.getLocalName().equals(file.getName())) { verifyFile(parent, child, expectedPolicyId); return; } } Assert.fail("File " + file + " not found."); } private void verifyFile(final Path parent, final HdfsFileStatus status, final Byte expectedPolicyId) throws Exception { HdfsLocatedFileStatus fileStatus = (HdfsLocatedFileStatus) status; byte policyId = fileStatus.getStoragePolicy(); BlockStoragePolicy policy = policies.getPolicy(policyId); if (expectedPolicyId != null) { Assert.assertEquals((byte)expectedPolicyId, policy.getId()); } final List<StorageType> types = policy.chooseStorageTypes( status.getReplication()); for(LocatedBlock lb : fileStatus.getBlockLocations().getLocatedBlocks()) { final Mover.StorageTypeDiff diff = new Mover.StorageTypeDiff(types, lb.getStorageTypes()); Assert.assertTrue(fileStatus.getFullName(parent.toString()) + " with policy " + policy + " has non-empty overlap: " + diff + ", the corresponding block is " + lb.getBlock().getLocalBlock(), diff.removeOverlap(true)); } } Replication getReplication(Path file) throws IOException { return getOrVerifyReplication(file, null); } Replication verifyReplication(Path file, int expectedDiskCount, int expectedArchiveCount) throws IOException { final Replication r = new Replication(); r.disk = expectedDiskCount; r.archive = expectedArchiveCount; return getOrVerifyReplication(file, r); } private Replication getOrVerifyReplication(Path file, Replication expected) throws IOException { final List<LocatedBlock> lbs = dfs.getClient().getLocatedBlocks( file.toString(), 0).getLocatedBlocks(); Assert.assertEquals(1, lbs.size()); LocatedBlock lb = lbs.get(0); StringBuilder types = new StringBuilder(); final Replication r = new Replication(); for(StorageType t : lb.getStorageTypes()) { types.append(t).append(", "); if (t == StorageType.DISK) { r.disk++; } else if (t == StorageType.ARCHIVE) { r.archive++; } else { Assert.fail("Unexpected storage type " + t); } } if (expected != null) { final String s = "file = " + file + "\n types = [" + types + "]"; Assert.assertEquals(s, expected, r); } return r; } } static class Replication { int disk; int archive; @Override public int hashCode() { return disk ^ archive; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } else if (obj == null || !(obj instanceof Replication)) { return false; } final Replication that = (Replication)obj; return this.disk == that.disk && this.archive == that.archive; } @Override public String toString() { return "[disk=" + disk + ", archive=" + archive + "]"; } } private static StorageType[][] genStorageTypes(int numDataNodes) { return genStorageTypes(numDataNodes, 0, 0, 0); } private static StorageType[][] genStorageTypes(int numDataNodes, int numAllDisk, int numAllArchive, int numRamDisk) { Preconditions.checkArgument( (numAllDisk + numAllArchive + numRamDisk) <= numDataNodes); StorageType[][] types = new StorageType[numDataNodes][]; int i = 0; for (; i < numRamDisk; i++) { types[i] = new StorageType[]{StorageType.RAM_DISK, StorageType.DISK}; } for (; i < numRamDisk + numAllDisk; i++) { types[i] = new StorageType[]{StorageType.DISK, StorageType.DISK}; } for (; i < numRamDisk + numAllDisk + numAllArchive; i++) { types[i] = new StorageType[]{StorageType.ARCHIVE, StorageType.ARCHIVE}; } for (; i < types.length; i++) { types[i] = new StorageType[]{StorageType.DISK, StorageType.ARCHIVE}; } return types; } private static class PathPolicyMap { final Map<Path, BlockStoragePolicy> map = Maps.newHashMap(); final Path hot = new Path("/hot"); final Path warm = new Path("/warm"); final Path cold = new Path("/cold"); final List<Path> files; PathPolicyMap(int filesPerDir){ map.put(hot, HOT); map.put(warm, WARM); map.put(cold, COLD); files = new ArrayList<Path>(); for(Path dir : map.keySet()) { for(int i = 0; i < filesPerDir; i++) { files.add(new Path(dir, "file" + i)); } } } NamespaceScheme newNamespaceScheme() { return new NamespaceScheme(Arrays.asList(hot, warm, cold), files, BLOCK_SIZE/2, null, map); } /** * Move hot files to warm and cold, warm files to hot and cold, * and cold files to hot and warm. */ void moveAround(DistributedFileSystem dfs) throws Exception { for(Path srcDir : map.keySet()) { int i = 0; for(Path dstDir : map.keySet()) { if (!srcDir.equals(dstDir)) { final Path src = new Path(srcDir, "file" + i++); final Path dst = new Path(dstDir, srcDir.getName() + "2" + dstDir.getName()); LOG.info("rename " + src + " to " + dst); dfs.rename(src, dst); } } } } } /** * A normal case for Mover: move a file into archival storage */ @Test public void testMigrateFileToArchival() throws Exception { LOG.info("testMigrateFileToArchival"); final Path foo = new Path("/foo"); Map<Path, BlockStoragePolicy> policyMap = Maps.newHashMap(); policyMap.put(foo, COLD); NamespaceScheme nsScheme = new NamespaceScheme(null, Arrays.asList(foo), 2*BLOCK_SIZE, null, policyMap); ClusterScheme clusterScheme = new ClusterScheme(DEFAULT_CONF, NUM_DATANODES, REPL, genStorageTypes(NUM_DATANODES), null); new MigrationTest(clusterScheme, nsScheme).runBasicTest(true); } /** * Print a big banner in the test log to make debug easier. */ static void banner(String string) { LOG.info("\n\n\n\n================================================\n" + string + "\n" + "==================================================\n\n"); } /** * Run Mover with arguments specifying files and directories */ @Test public void testMoveSpecificPaths() throws Exception { LOG.info("testMoveSpecificPaths"); final Path foo = new Path("/foo"); final Path barFile = new Path(foo, "bar"); final Path foo2 = new Path("/foo2"); final Path bar2File = new Path(foo2, "bar2"); Map<Path, BlockStoragePolicy> policyMap = Maps.newHashMap(); policyMap.put(foo, COLD); policyMap.put(foo2, WARM); NamespaceScheme nsScheme = new NamespaceScheme(Arrays.asList(foo, foo2), Arrays.asList(barFile, bar2File), BLOCK_SIZE, null, policyMap); ClusterScheme clusterScheme = new ClusterScheme(DEFAULT_CONF, NUM_DATANODES, REPL, genStorageTypes(NUM_DATANODES), null); MigrationTest test = new MigrationTest(clusterScheme, nsScheme); test.setupCluster(); try { test.prepareNamespace(); test.setStoragePolicy(); Map<URI, List<Path>> map = Mover.Cli.getNameNodePathsToMove(test.conf, "-p", "/foo/bar", "/foo2"); int result = Mover.run(map, test.conf); Assert.assertEquals(ExitStatus.SUCCESS.getExitCode(), result); Thread.sleep(5000); test.verify(true); } finally { test.shutdownCluster(); } } /** * Move an open file into archival storage */ @Test public void testMigrateOpenFileToArchival() throws Exception { LOG.info("testMigrateOpenFileToArchival"); final Path fooDir = new Path("/foo"); Map<Path, BlockStoragePolicy> policyMap = Maps.newHashMap(); policyMap.put(fooDir, COLD); NamespaceScheme nsScheme = new NamespaceScheme(Arrays.asList(fooDir), null, BLOCK_SIZE, null, policyMap); ClusterScheme clusterScheme = new ClusterScheme(DEFAULT_CONF, NUM_DATANODES, REPL, genStorageTypes(NUM_DATANODES), null); MigrationTest test = new MigrationTest(clusterScheme, nsScheme); test.setupCluster(); // create an open file banner("writing to file /foo/bar"); final Path barFile = new Path(fooDir, "bar"); DFSTestUtil.createFile(test.dfs, barFile, BLOCK_SIZE, (short) 1, 0L); FSDataOutputStream out = test.dfs.append(barFile); out.writeBytes("hello, "); ((DFSOutputStream) out.getWrappedStream()).hsync(); try { banner("start data migration"); test.setStoragePolicy(); // set /foo to COLD test.migrate(ExitStatus.SUCCESS); // make sure the under construction block has not been migrated LocatedBlocks lbs = test.dfs.getClient().getLocatedBlocks( barFile.toString(), BLOCK_SIZE); LOG.info("Locations: " + lbs); List<LocatedBlock> blks = lbs.getLocatedBlocks(); Assert.assertEquals(1, blks.size()); Assert.assertEquals(1, blks.get(0).getLocations().length); banner("finish the migration, continue writing"); // make sure the writing can continue out.writeBytes("world!"); ((DFSOutputStream) out.getWrappedStream()).hsync(); IOUtils.cleanup(LOG, out); lbs = test.dfs.getClient().getLocatedBlocks( barFile.toString(), BLOCK_SIZE); LOG.info("Locations: " + lbs); blks = lbs.getLocatedBlocks(); Assert.assertEquals(1, blks.size()); Assert.assertEquals(1, blks.get(0).getLocations().length); banner("finish writing, starting reading"); // check the content of /foo/bar FSDataInputStream in = test.dfs.open(barFile); byte[] buf = new byte[13]; // read from offset 1024 in.readFully(BLOCK_SIZE, buf, 0, buf.length); IOUtils.cleanup(LOG, in); Assert.assertEquals("hello, world!", new String(buf)); } finally { test.shutdownCluster(); } } /** * Test directories with Hot, Warm and Cold polices. */ @Test public void testHotWarmColdDirs() throws Exception { LOG.info("testHotWarmColdDirs"); PathPolicyMap pathPolicyMap = new PathPolicyMap(3); NamespaceScheme nsScheme = pathPolicyMap.newNamespaceScheme(); ClusterScheme clusterScheme = new ClusterScheme(); MigrationTest test = new MigrationTest(clusterScheme, nsScheme); try { test.runBasicTest(false); pathPolicyMap.moveAround(test.dfs); test.migrate(ExitStatus.SUCCESS); test.verify(true); } finally { test.shutdownCluster(); } } private void waitForAllReplicas(int expectedReplicaNum, Path file, DistributedFileSystem dfs) throws Exception { for (int i = 0; i < 5; i++) { LocatedBlocks lbs = dfs.getClient().getLocatedBlocks(file.toString(), 0, BLOCK_SIZE); LocatedBlock lb = lbs.get(0); if (lb.getLocations().length >= expectedReplicaNum) { return; } else { Thread.sleep(1000); } } } private void setVolumeFull(DataNode dn, StorageType type) { try (FsDatasetSpi.FsVolumeReferences refs = dn.getFSDataset() .getFsVolumeReferences()) { for (FsVolumeSpi fvs : refs) { FsVolumeImpl volume = (FsVolumeImpl) fvs; if (volume.getStorageType() == type) { LOG.info("setCapacity to 0 for [" + volume.getStorageType() + "]" + volume.getStorageID()); volume.setCapacityForTesting(0); } } } catch (IOException e) { LOG.error("Unexpected exception by closing FsVolumeReference", e); } } /** * Test DISK is running out of spaces. */ @Test public void testNoSpaceDisk() throws Exception { LOG.info("testNoSpaceDisk"); final PathPolicyMap pathPolicyMap = new PathPolicyMap(0); final NamespaceScheme nsScheme = pathPolicyMap.newNamespaceScheme(); Configuration conf = new Configuration(DEFAULT_CONF); final ClusterScheme clusterScheme = new ClusterScheme(conf, NUM_DATANODES, REPL, genStorageTypes(NUM_DATANODES), null); final MigrationTest test = new MigrationTest(clusterScheme, nsScheme); try { test.runBasicTest(false); // create 2 hot files with replication 3 final short replication = 3; for (int i = 0; i < 2; i++) { final Path p = new Path(pathPolicyMap.hot, "file" + i); DFSTestUtil.createFile(test.dfs, p, BLOCK_SIZE, replication, 0L); waitForAllReplicas(replication, p, test.dfs); } // set all the DISK volume to full for (DataNode dn : test.cluster.getDataNodes()) { setVolumeFull(dn, StorageType.DISK); DataNodeTestUtils.triggerHeartbeat(dn); } // test increasing replication. Since DISK is full, // new replicas should be stored in ARCHIVE as a fallback storage. final Path file0 = new Path(pathPolicyMap.hot, "file0"); final Replication r = test.getReplication(file0); final short newReplication = (short) 5; test.dfs.setReplication(file0, newReplication); Thread.sleep(10000); test.verifyReplication(file0, r.disk, newReplication - r.disk); // test creating a cold file and then increase replication final Path p = new Path(pathPolicyMap.cold, "foo"); DFSTestUtil.createFile(test.dfs, p, BLOCK_SIZE, replication, 0L); test.verifyReplication(p, 0, replication); test.dfs.setReplication(p, newReplication); Thread.sleep(10000); test.verifyReplication(p, 0, newReplication); //test move a hot file to warm final Path file1 = new Path(pathPolicyMap.hot, "file1"); test.dfs.rename(file1, pathPolicyMap.warm); test.migrate(ExitStatus.NO_MOVE_BLOCK); test.verifyFile(new Path(pathPolicyMap.warm, "file1"), WARM.getId()); } finally { test.shutdownCluster(); } } /** * Test ARCHIVE is running out of spaces. */ @Test public void testNoSpaceArchive() throws Exception { LOG.info("testNoSpaceArchive"); final PathPolicyMap pathPolicyMap = new PathPolicyMap(0); final NamespaceScheme nsScheme = pathPolicyMap.newNamespaceScheme(); final ClusterScheme clusterScheme = new ClusterScheme(DEFAULT_CONF, NUM_DATANODES, REPL, genStorageTypes(NUM_DATANODES), null); final MigrationTest test = new MigrationTest(clusterScheme, nsScheme); try { test.runBasicTest(false); // create 2 hot files with replication 3 final short replication = 3; for (int i = 0; i < 2; i++) { final Path p = new Path(pathPolicyMap.cold, "file" + i); DFSTestUtil.createFile(test.dfs, p, BLOCK_SIZE, replication, 0L); waitForAllReplicas(replication, p, test.dfs); } // set all the ARCHIVE volume to full for (DataNode dn : test.cluster.getDataNodes()) { setVolumeFull(dn, StorageType.ARCHIVE); DataNodeTestUtils.triggerHeartbeat(dn); } { // test increasing replication but new replicas cannot be created // since no more ARCHIVE space. final Path file0 = new Path(pathPolicyMap.cold, "file0"); final Replication r = test.getReplication(file0); Assert.assertEquals(0, r.disk); final short newReplication = (short) 5; test.dfs.setReplication(file0, newReplication); Thread.sleep(10000); test.verifyReplication(file0, 0, r.archive); } { // test creating a hot file final Path p = new Path(pathPolicyMap.hot, "foo"); DFSTestUtil.createFile(test.dfs, p, BLOCK_SIZE, (short) 3, 0L); } { //test move a cold file to warm final Path file1 = new Path(pathPolicyMap.cold, "file1"); test.dfs.rename(file1, pathPolicyMap.warm); test.migrate(ExitStatus.SUCCESS); test.verify(true); } } finally { test.shutdownCluster(); } } }
apache-2.0
cloudfoundry-community/asp.net5-buildpack
fixtures/angular_msbuild_dotnet_2.1/ClientApp/node_modules/domino/test/w3c/level1/html/area03.js
2740
/* Copyright © 2001-2004 World Wide Web Consortium, (Massachusetts Institute of Technology, European Research Consortium for Informatics and Mathematics, Keio University). All Rights Reserved. This work is distributed under the W3C® Software License [1] in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. [1] http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231 */ /** * Gets URI that identifies the test. * @return uri identifier of test */ function getTargetURI() { return "http://www.w3.org/2001/DOM-Test-Suite/level1/html/area03"; } var docsLoaded = -1000000; var builder = null; // // This function is called by the testing framework before // running the test suite. // // If there are no configuration exceptions, asynchronous // document loading is started. Otherwise, the status // is set to complete and the exception is immediately // raised when entering the body of the test. // function setUpPage() { setUpPageStatus = 'running'; try { // // creates test document builder, may throw exception // builder = createConfiguredBuilder(); docsLoaded = 0; var docRef = null; if (typeof(this.doc) != 'undefined') { docRef = this.doc; } docsLoaded += preload(docRef, "doc", "area"); if (docsLoaded == 1) { setUpPageStatus = 'complete'; } } catch(ex) { catchInitializationError(builder, ex); setUpPageStatus = 'complete'; } } // // This method is called on the completion of // each asychronous load started in setUpTests. // // When every synchronous loaded document has completed, // the page status is changed which allows the // body of the test to be executed. function loadComplete() { if (++docsLoaded == 1) { setUpPageStatus = 'complete'; } } /** * * @author Netscape * @author Sivakiran Tummala * @see http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-html#ID-8722121 */ function area03() { var success; if(checkInitialization(builder, "area03") != null) return; var nodeList; var testNode; var vtabindex; var doc; var docRef = null; if (typeof(this.doc) != 'undefined') { docRef = this.doc; } doc = load(docRef, "doc", "area"); nodeList = doc.getElementsByTagName("area"); assertSize("Asize",1,nodeList); testNode = nodeList.item(0); vtabindex = testNode.tabIndex; assertEquals("tabIndexLink",10,vtabindex); } function runTest() { area03(); }
apache-2.0
Eyas/TypeScript
tests/cases/fourslash/extract-method11.ts
833
/// <reference path='fourslash.ts' /> // Nonexhaustive list of things it should be illegal to be extract-method on // * Import declarations // * Super calls // * Function body blocks // * try/catch blocks //// /*1a*/import * as x from 'y';/*1b*/ //// namespace N { //// /*oka*/class C extends B { //// constructor() { //// /*2a*/super();/*2b*/ //// } //// }/*okb*/ //// } //// function f() /*3a*/{ return 0 }/*3b*/ //// try /*4a*/{ console.log }/*4b*/ catch (e) /*5a*/{ console.log; }/*5b*/ for (const m of ['1', '2', '3', '4', '5']) { goTo.select(m + 'a', m + 'b'); verify.not.refactorAvailable('Extract Symbol'); } // Verify we can still extract the entire class goTo.select('oka', 'okb'); verify.refactorAvailable('Extract Symbol', 'function_scope_0');
apache-2.0
irudyak/ignite
modules/core/src/test/java/org/apache/ignite/internal/managers/communication/GridIoManagerSelfTest.java
9088
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.internal.managers.communication; import java.nio.ByteBuffer; import java.util.Collection; import java.util.UUID; import java.util.concurrent.Callable; import org.apache.commons.collections.CollectionUtils; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.cluster.ClusterNode; import org.apache.ignite.internal.GridKernalContext; import org.apache.ignite.internal.GridTopic; import org.apache.ignite.internal.managers.discovery.GridDiscoveryManager; import org.apache.ignite.internal.util.typedef.F; import org.apache.ignite.marshaller.jdk.JdkMarshaller; import org.apache.ignite.plugin.extensions.communication.Message; import org.apache.ignite.plugin.extensions.communication.MessageReader; import org.apache.ignite.plugin.extensions.communication.MessageWriter; import org.apache.ignite.spi.communication.tcp.TcpCommunicationSpi; import org.apache.ignite.testframework.GridTestNode; import org.apache.ignite.testframework.GridTestUtils; import org.apache.ignite.testframework.junits.GridTestKernalContext; import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest; import org.mockito.ArgumentMatcher; import org.mockito.Mockito; import static org.mockito.Matchers.any; import static org.mockito.Mockito.argThat; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * Test for {@link GridIoManager}. */ public class GridIoManagerSelfTest extends GridCommonAbstractTest { /** Grid test context. */ private GridTestKernalContext ctx; /** Test local node. */ private GridTestNode locNode = new GridTestNode(UUID.randomUUID()); /** Test remote node. */ private GridTestNode rmtNode = new GridTestNode(UUID.randomUUID()); /** * @throws IgniteCheckedException In case of error. */ public GridIoManagerSelfTest() throws IgniteCheckedException { ctx = new GridTestKernalContext(log); } /** {@inheritDoc} */ @Override protected void beforeTest() throws Exception { ctx.config().setCommunicationSpi(new TcpCommunicationSpi()); ctx.config().setMarshaller(new JdkMarshaller()); // Turn off peer class loading to simplify mocking. ctx.config().setPeerClassLoadingEnabled(false); // Register local and remote nodes in discovery manager. GridDiscoveryManager mockedDiscoveryMgr = Mockito.mock(GridDiscoveryManager.class); when(mockedDiscoveryMgr.localNode()).thenReturn(locNode); when(mockedDiscoveryMgr.remoteNodes()).thenReturn(F.<ClusterNode>asList(rmtNode)); ctx.add(mockedDiscoveryMgr); } /** * @throws Exception If failed. */ public void testSendIfOneOfNodesIsLocalAndTopicIsEnum() throws Exception { GridTestUtils.assertThrows(log, new Callable<Object>() { @Override public Object call() throws Exception { new GridIoManager(ctx).sendToGridTopic(F.asList(locNode, rmtNode), GridTopic.TOPIC_CACHE, new TestMessage(), GridIoPolicy.P2P_POOL); return null; } }, AssertionError.class, "Internal Ignite code should never call the method with local node in a node list."); } /** * @throws Exception If failed. */ public void testSendUserMessageThinVersionIfOneOfNodesIsLocal() throws Exception { Object msg = new Object(); GridIoManager ioMgr = spy(new TestGridIoManager(ctx)); try { ioMgr.sendUserMessage(F.asList(locNode, rmtNode), msg, null, false, 0, false); } catch (IgniteCheckedException ignored) { // No-op. We are using mocks so real sending is impossible. } verify(ioMgr).sendToGridTopic(eq(locNode), eq(GridTopic.TOPIC_COMM_USER), any(GridIoUserMessage.class), eq(GridIoPolicy.PUBLIC_POOL)); Collection<? extends ClusterNode> rmtNodes = F.view(F.asList(rmtNode), F.remoteNodes(locNode.id())); verify(ioMgr).sendToGridTopic(argThat(new IsEqualCollection(rmtNodes)), eq(GridTopic.TOPIC_COMM_USER), any(GridIoUserMessage.class), eq(GridIoPolicy.PUBLIC_POOL)); } /** * @throws Exception If failed. */ public void testSendUserMessageUnorderedThickVersionIfOneOfNodesIsLocal() throws Exception { Object msg = new Object(); GridIoManager ioMgr = spy(new TestGridIoManager(ctx)); try { ioMgr.sendUserMessage(F.asList(locNode, rmtNode), msg, GridTopic.TOPIC_IGFS, false, 123L, false); } catch (IgniteCheckedException ignored) { // No-op. We are using mocks so real sending is impossible. } verify(ioMgr).sendToGridTopic(eq(locNode), eq(GridTopic.TOPIC_COMM_USER), any(GridIoUserMessage.class), eq(GridIoPolicy.PUBLIC_POOL)); Collection<? extends ClusterNode> rmtNodes = F.view(F.asList(rmtNode), F.remoteNodes(locNode.id())); verify(ioMgr).sendToGridTopic(argThat(new IsEqualCollection(rmtNodes)), eq(GridTopic.TOPIC_COMM_USER), any(GridIoUserMessage.class), eq(GridIoPolicy.PUBLIC_POOL)); } /** * @throws Exception If failed. */ public void testSendUserMessageOrderedThickVersionIfOneOfNodesIsLocal() throws Exception { Object msg = new Object(); GridIoManager ioMgr = spy(new TestGridIoManager(ctx)); try { ioMgr.sendUserMessage(F.asList(locNode, rmtNode), msg, GridTopic.TOPIC_IGFS, true, 123L, false); } catch (Exception ignored) { // No-op. We are using mocks so real sending is impossible. } verify(ioMgr).sendOrderedMessageToGridTopic( argThat(new IsEqualCollection(F.asList(locNode, rmtNode))), eq(GridTopic.TOPIC_COMM_USER), any(GridIoUserMessage.class), eq(GridIoPolicy.PUBLIC_POOL), eq(123L), false); } /** * Test-purposed extension of {@code GridIoManager} with no-op {@code send(...)} methods. */ private static class TestGridIoManager extends GridIoManager { /** * @param ctx Grid kernal context. */ TestGridIoManager(GridKernalContext ctx) { super(ctx); } /** {@inheritDoc} */ @Override public void sendToGridTopic(ClusterNode node, GridTopic topic, Message msg, byte plc) throws IgniteCheckedException { // No-op. } } /** * Mockito argument matcher to compare collections produced by {@code F.view()} methods. */ private static class IsEqualCollection extends ArgumentMatcher<Collection<? extends ClusterNode>> { /** Expected collection. */ private final Collection<? extends ClusterNode> expCol; /** * Default constructor. * * @param expCol Expected collection. */ IsEqualCollection(Collection<? extends ClusterNode> expCol) { this.expCol = expCol; } /** * Matches a given collection to the specified in constructor expected one * with Apache {@code CollectionUtils.isEqualCollection()}. * * @param colToCheck Collection to be matched against the expected one. * @return True if collections matches. */ @Override public boolean matches(Object colToCheck) { return CollectionUtils.isEqualCollection(expCol, (Collection)colToCheck); } } /** */ private static class TestMessage implements Message { /** {@inheritDoc} */ @Override public void onAckReceived() { // No-op. } /** {@inheritDoc} */ @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) { return true; } /** {@inheritDoc} */ @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) { return true; } /** {@inheritDoc} */ @Override public short directType() { return 0; } /** {@inheritDoc} */ @Override public byte fieldsCount() { return 0; } } }
apache-2.0
xuanyuanking/spark
core/src/test/scala/org/apache/spark/storage/DiskBlockManagerSuite.scala
5683
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.storage import java.io.{File, FileWriter} import java.nio.file.{Files, Paths} import java.nio.file.attribute.PosixFilePermissions import java.util.HashMap import com.fasterxml.jackson.core.`type`.TypeReference import com.fasterxml.jackson.databind.ObjectMapper import org.apache.commons.io.FileUtils import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach} import org.apache.spark.{SparkConf, SparkFunSuite} import org.apache.spark.internal.config import org.apache.spark.util.Utils class DiskBlockManagerSuite extends SparkFunSuite with BeforeAndAfterEach with BeforeAndAfterAll { private val testConf = new SparkConf(false) private var rootDir0: File = _ private var rootDir1: File = _ private var rootDirs: String = _ var diskBlockManager: DiskBlockManager = _ override def beforeAll(): Unit = { super.beforeAll() rootDir0 = Utils.createTempDir() rootDir1 = Utils.createTempDir() rootDirs = rootDir0.getAbsolutePath + "," + rootDir1.getAbsolutePath } override def afterAll(): Unit = { try { Utils.deleteRecursively(rootDir0) Utils.deleteRecursively(rootDir1) } finally { super.afterAll() } } override def beforeEach(): Unit = { super.beforeEach() val conf = testConf.clone conf.set("spark.local.dir", rootDirs) diskBlockManager = new DiskBlockManager(conf, deleteFilesOnStop = true, isDriver = false) } override def afterEach(): Unit = { try { diskBlockManager.stop() } finally { super.afterEach() } } test("basic block creation") { val blockId = new TestBlockId("test") val newFile = diskBlockManager.getFile(blockId) writeToFile(newFile, 10) assert(diskBlockManager.containsBlock(blockId)) newFile.delete() assert(!diskBlockManager.containsBlock(blockId)) } test("enumerating blocks") { val ids = (1 to 100).map(i => TestBlockId("test_" + i)) val files = ids.map(id => diskBlockManager.getFile(id)) files.foreach(file => writeToFile(file, 10)) assert(diskBlockManager.getAllBlocks.toSet === ids.toSet) } test("SPARK-22227: non-block files are skipped") { val file = diskBlockManager.getFile("unmanaged_file") writeToFile(file, 10) assert(diskBlockManager.getAllBlocks().isEmpty) } test("should still create merge directories if one already exists under a local dir") { val mergeDir0 = new File(rootDir0, DiskBlockManager.MERGE_DIRECTORY) if (!mergeDir0.exists()) { Files.createDirectories(mergeDir0.toPath) } val mergeDir1 = new File(rootDir1, DiskBlockManager.MERGE_DIRECTORY) if (mergeDir1.exists()) { Utils.deleteRecursively(mergeDir1) } testConf.set("spark.local.dir", rootDirs) testConf.set("spark.shuffle.push.enabled", "true") testConf.set(config.Tests.IS_TESTING, true) diskBlockManager = new DiskBlockManager(testConf, deleteFilesOnStop = true, isDriver = false) assert(Utils.getConfiguredLocalDirs(testConf).map( rootDir => new File(rootDir, DiskBlockManager.MERGE_DIRECTORY)) .filter(mergeDir => mergeDir.exists()).length === 2) // mergeDir0 will be skipped as it already exists assert(mergeDir0.list().length === 0) // Sub directories get created under mergeDir1 assert(mergeDir1.list().length === testConf.get(config.DISKSTORE_SUB_DIRECTORIES)) } test("Test dir creation with permission 770") { val testDir = new File("target/testDir"); FileUtils.deleteQuietly(testDir) diskBlockManager = new DiskBlockManager(testConf, deleteFilesOnStop = true, isDriver = false) diskBlockManager.createDirWithPermission770(testDir) assert(testDir.exists && testDir.isDirectory) val permission = PosixFilePermissions.toString( Files.getPosixFilePermissions(Paths.get("target/testDir"))) assert(permission.equals("rwxrwx---")) FileUtils.deleteQuietly(testDir) } test("Encode merged directory name and attemptId in shuffleManager field") { testConf.set(config.APP_ATTEMPT_ID, "1"); diskBlockManager = new DiskBlockManager(testConf, deleteFilesOnStop = true, isDriver = false) val mergedShuffleMeta = diskBlockManager.getMergeDirectoryAndAttemptIDJsonString(); val mapper: ObjectMapper = new ObjectMapper val typeRef: TypeReference[HashMap[String, String]] = new TypeReference[HashMap[String, String]]() {} val metaMap: HashMap[String, String] = mapper.readValue(mergedShuffleMeta, typeRef) val mergeDir = metaMap.get(DiskBlockManager.MERGE_DIR_KEY) assert(mergeDir.equals(DiskBlockManager.MERGE_DIRECTORY + "_1")) val attemptId = metaMap.get(DiskBlockManager.ATTEMPT_ID_KEY) assert(attemptId.equals("1")) } def writeToFile(file: File, numBytes: Int): Unit = { val writer = new FileWriter(file, true) for (i <- 0 until numBytes) writer.write(i) writer.close() } }
apache-2.0
KalicyZhou/incubator-weex
test/js-framework/case/basic/dynamic-id.source.js
2156
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ define('@weex-component/id', function (require, exports, module) { ; module.exports = { ready: function () { if (this.$el('x')) { this.$el('x').setAttr('a', 1) } if (this.$el('y')) { this.$el('y').setAttr('a', 1) } if (this.$el('')) { this.$el('').setAttr('a', 1) } if (this.$el('0')) { this.$el('0').setAttr('a', 1) } if (this.$el(0)) { this.$el(0).setAttr('b', 1) } } } ;module.exports.template = { "type": "div", "children": [ { "type": "text", "id": function () { return "x" }, "attr": { "value": "Hello" } }, { "type": "text", "id": function () { return 0 }, "attr": { "value": "Hello" } }, { "type": "text", "id": function () { return '' }, "attr": { "value": "Hello" } }, { "type": "text", "id": function () { return null }, "attr": { "value": "Hello" } }, { "type": "text", "id": function () { return NaN }, "attr": { "value": "Hello" } }, { "type": "text", "id": function () { return }, "attr": { "value": "Hello" } } ] } ;}) // require module bootstrap('@weex-component/id')
apache-2.0
nightvixen/openfire
src/java/org/jivesoftware/util/ParamUtils.java
12294
/** * $RCSfile$ * $Revision$ * $Date$ * * Copyright (C) 2004-2008 Jive Software. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jivesoftware.util; import javax.servlet.http.HttpServletRequest; /** * Assists JSP writers in getting parameters and attributes. */ public class ParamUtils { /** * Returns a parameter as a string. * * @param request the HttpServletRequest object, known as "request" in a * JSP page. * @param name the name of the parameter you want to get * @return the value of the parameter or null if the parameter was not * found or if the parameter is a zero-length string. */ public static String getParameter(HttpServletRequest request, String name) { return getParameter(request, name, false); } /** * Returns a parameter as a string. * * @param request the HttpServletRequest object, known as "request" in a * JSP page. * @param name the name of the parameter you want to get * @param emptyStringsOK return the parameter values even if it is an empty string. * @return the value of the parameter or null if the parameter was not * found. */ public static String getParameter(HttpServletRequest request, String name, boolean emptyStringsOK) { String temp = request.getParameter(name); if (temp != null) { if (temp.equals("") && !emptyStringsOK) { return null; } else { return temp; } } else { return null; } } /** * Returns a list of parameters of the same name * * @param request an HttpServletRequest object. * @return an array of non-null, non-blank strings of the same name. This * method will return an empty array if no parameters were found. */ public static String[] getParameters(HttpServletRequest request, String name) { if (name == null) { return new String[0]; } String[] paramValues = request.getParameterValues(name); if (paramValues == null || paramValues.length == 0) { return new String[0]; } else { java.util.List values = new java.util.ArrayList(paramValues.length); for (int i = 0; i < paramValues.length; i++) { if (paramValues[i] != null && !"".equals(paramValues[i])) { values.add(paramValues[i]); } } return (String[])values.toArray(new String[]{}); } } /** * Returns a parameter as a boolean. * * @param request the HttpServletRequest object, known as "request" in a * JSP page. * @param name the name of the parameter you want to get * @return true if the value of the parameter was "true", false otherwise. */ public static boolean getBooleanParameter(HttpServletRequest request, String name) { return getBooleanParameter(request, name, false); } /** * Returns a parameter as a boolean. * * @param request the HttpServletRequest object, known as "request" in a * JSP page. * @param name the name of the parameter you want to get * @return true if the value of the parameter was "true", false otherwise. */ public static boolean getBooleanParameter(HttpServletRequest request, String name, boolean defaultVal) { String temp = request.getParameter(name); if ("true".equals(temp) || "on".equals(temp)) { return true; } else if ("false".equals(temp) || "off".equals(temp)) { return false; } else { return defaultVal; } } /** * Returns a parameter as an int. * * @param request the HttpServletRequest object, known as "request" in a * JSP page. * @param name the name of the parameter you want to get * @return the int value of the parameter specified or the default value if * the parameter is not found. */ public static int getIntParameter(HttpServletRequest request, String name, int defaultNum) { String temp = request.getParameter(name); if (temp != null && !temp.equals("")) { int num = defaultNum; try { num = Integer.parseInt(temp); } catch (Exception ignored) { } return num; } else { return defaultNum; } } /** * Returns a list of int parameters. * * @param request the HttpServletRequest object, known as "request" in a * JSP page. * @param name the name of the parameter you want to get * @param defaultNum the default value of a parameter, if the parameter * can't be converted into an int. */ public static int[] getIntParameters(HttpServletRequest request, String name, int defaultNum) { String[] paramValues = request.getParameterValues(name); if (paramValues == null || paramValues.length == 0) { return new int[0]; } int[] values = new int[paramValues.length]; for (int i = 0; i < paramValues.length; i++) { try { values[i] = Integer.parseInt(paramValues[i]); } catch (Exception e) { values[i] = defaultNum; } } return values; } /** * Returns a parameter as a double. * * @param request the HttpServletRequest object, known as "request" in a * JSP page. * @param name the name of the parameter you want to get * @return the double value of the parameter specified or the default value * if the parameter is not found. */ public static double getDoubleParameter(HttpServletRequest request, String name, double defaultNum) { String temp = request.getParameter(name); if (temp != null && !temp.equals("")) { double num = defaultNum; try { num = Double.parseDouble(temp); } catch (Exception ignored) { } return num; } else { return defaultNum; } } /** * Returns a parameter as a long. * * @param request the HttpServletRequest object, known as "request" in a * JSP page. * @param name the name of the parameter you want to get * @return the long value of the parameter specified or the default value if * the parameter is not found. */ public static long getLongParameter(HttpServletRequest request, String name, long defaultNum) { String temp = request.getParameter(name); if (temp != null && !temp.equals("")) { long num = defaultNum; try { num = Long.parseLong(temp); } catch (Exception ignored) { } return num; } else { return defaultNum; } } /** * Returns a list of long parameters. * * @param request the HttpServletRequest object, known as "request" in a * JSP page. * @param name the name of the parameter you want to get * @param defaultNum the default value of a parameter, if the parameter * can't be converted into a long. */ public static long[] getLongParameters(HttpServletRequest request, String name, long defaultNum) { String[] paramValues = request.getParameterValues(name); if (paramValues == null || paramValues.length == 0) { return new long[0]; } long[] values = new long[paramValues.length]; for (int i = 0; i < paramValues.length; i++) { try { values[i] = Long.parseLong(paramValues[i]); } catch (Exception e) { values[i] = defaultNum; } } return values; } /** * Returns an attribute as a string. * * @param request the HttpServletRequest object, known as "request" in a JSP page. * @param name the name of the parameter you want to get * @return the value of the parameter or null if the parameter was not * found or if the parameter is a zero-length string. */ public static String getAttribute(HttpServletRequest request, String name) { return getAttribute(request, name, false); } /** * Returns an attribute as a string. * * @param request the HttpServletRequest object, known as "request" in a JSP page. * @param name the name of the parameter you want to get. * @param emptyStringsOK return the parameter values even if it is an empty string. * @return the value of the parameter or null if the parameter was not * found. */ public static String getAttribute(HttpServletRequest request, String name, boolean emptyStringsOK) { String temp = (String)request.getAttribute(name); if (temp != null) { if (temp.equals("") && !emptyStringsOK) { return null; } else { return temp; } } else { return null; } } /** * Returns an attribute as a boolean. * * @param request the HttpServletRequest object, known as "request" in a JSP page. * @param name the name of the attribute you want to get. * @return true if the value of the attribute is "true", false otherwise. */ public static boolean getBooleanAttribute(HttpServletRequest request, String name) { String temp = (String)request.getAttribute(name); if (temp != null && temp.equals("true")) { return true; } else { return false; } } /** * Returns an attribute as a int. * * @param request the HttpServletRequest object, known as "request" in a JSP page. * @param name the name of the attribute you want to get. * @return the int value of the attribute or the default value if the * attribute is not found or is a zero length string. */ public static int getIntAttribute(HttpServletRequest request, String name, int defaultNum) { String temp = (String)request.getAttribute(name); if (temp != null && !temp.equals("")) { int num = defaultNum; try { num = Integer.parseInt(temp); } catch (Exception ignored) { } return num; } else { return defaultNum; } } /** * Returns an attribute as a long. * * @param request the HttpServletRequest object, known as "request" in a JSP page. * @param name the name of the attribute you want to get. * @return the long value of the attribute or the default value if the * attribute is not found or is a zero length string. */ public static long getLongAttribute(HttpServletRequest request, String name, long defaultNum) { String temp = (String)request.getAttribute(name); if (temp != null && !temp.equals("")) { long num = defaultNum; try { num = Long.parseLong(temp); } catch (Exception ignored) { } return num; } else { return defaultNum; } } }
apache-2.0
zhimin711/openstack-java-sdk
keystone-client/src/main/java/com/woorea/openstack/keystone/v3/api/ProjectGroupRolesResource.java
919
package com.woorea.openstack.keystone.v3.api; import com.woorea.openstack.base.client.OpenStackClient; import com.woorea.openstack.base.client.OpenStackRequest; import com.woorea.openstack.keystone.model.Role; import com.woorea.openstack.keystone.model.Roles; public class ProjectGroupRolesResource extends GenericResource<Role, Roles> { public ProjectGroupRolesResource(OpenStackClient client, String path) { super(client, path, Role.class, Roles.class); } @Override public OpenStackRequest<Role> create(Role one) { throw new UnsupportedOperationException(); } @Override public OpenStackRequest<Role> show(String id) { throw new UnsupportedOperationException(); } @Override public OpenStackRequest<Role> update(String id, Role one) { throw new UnsupportedOperationException(); } @Override public OpenStackRequest<Role> delete(String id) { throw new UnsupportedOperationException(); } }
apache-2.0
weexext/ucar-weex-core
platforms/android/weex-sdk16/src/main/java/com/taobao/weex/http/Status.java
3682
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.taobao.weex.http; import java.util.HashMap; import java.util.Map; /** * Created by sospartan on 5/26/16. */ public class Status { public static final String UNKNOWN_STATUS = "unknown status"; public static final String ERR_INVALID_REQUEST = "ERR_INVALID_REQUEST"; public static final String ERR_CONNECT_FAILED = "ERR_CONNECT_FAILED"; private static Map<String,String> statusMap = new HashMap<>(); static { statusMap.put("100","Continue"); statusMap.put("101","Switching Protocol"); statusMap.put("200","OK"); statusMap.put("201","Created"); statusMap.put("202","Accepted"); statusMap.put("203","Non-Authoritative Information"); statusMap.put("204","No Content"); statusMap.put("205","Reset Content"); statusMap.put("206","Partial Content"); statusMap.put("300","Multiple Choice"); statusMap.put("301","Moved Permanently"); statusMap.put("302","Found"); statusMap.put("303","See Other"); statusMap.put("304","Not Modified"); statusMap.put("305","Use Proxy"); statusMap.put("306","unused"); statusMap.put("307","Temporary Redirect"); statusMap.put("308","Permanent Redirect"); statusMap.put("400","Bad Request"); statusMap.put("401","Unauthorized"); statusMap.put("402","Payment Required"); statusMap.put("403","Forbidden"); statusMap.put("404","Not Found"); statusMap.put("405","Method Not Allowed"); statusMap.put("406","Not Acceptable"); statusMap.put("407","Proxy Authentication Required"); statusMap.put("408","Request Timeout"); statusMap.put("409","Conflict"); statusMap.put("410","Gone"); statusMap.put("411","Length Required"); statusMap.put("412","Precondition Failed"); statusMap.put("413","Payload Too Large"); statusMap.put("414","URI Too Long"); statusMap.put("415","Unsupported Media Type"); statusMap.put("416","Requested Range Not Satisfiable"); statusMap.put("417","Expectation Failed"); statusMap.put("418","I'm a teapot"); statusMap.put("421","Misdirected Request"); statusMap.put("426","Upgrade Required"); statusMap.put("428","Precondition Required"); statusMap.put("429","Too Many Requests"); statusMap.put("431","Request Header Fields Too Large"); statusMap.put("500","Internal Server Error"); statusMap.put("501","Not Implemented"); statusMap.put("502","Bad Gateway"); statusMap.put("503","Service Unavailable"); statusMap.put("504","Gateway Timeout"); statusMap.put("505","HTTP Version Not Supported"); statusMap.put("506","Variant Also Negotiates"); statusMap.put("507","Variant Also Negotiates"); statusMap.put("511","Network Authentication Required"); } public static String getStatusText(String code){ if(!statusMap.containsKey(code)) return UNKNOWN_STATUS; return statusMap.get(code); } }
apache-2.0
irudyak/ignite
modules/spring-data-2.0/src/main/java/org/apache/ignite/springdata20/repository/support/package-info.java
976
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * <!-- Package description. --> * Package contains supporting files required by Spring Data framework. */ package org.apache.ignite.springdata20.repository.support;
apache-2.0
BITechnologies/boo
src/Boo.Lang.Compiler/Ast/Impl/NullLiteralExpressionImpl.cs
3892
#region license // Copyright (c) 2009 Rodrigo B. de Oliveira (rbo@acm.org) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Rodrigo B. de Oliveira nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion // // DO NOT EDIT THIS FILE! // // This file was generated automatically by astgen.boo. // namespace Boo.Lang.Compiler.Ast { using System.Collections; using System.Runtime.Serialization; [System.Serializable] public partial class NullLiteralExpression : LiteralExpression { [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] new public NullLiteralExpression CloneNode() { return (NullLiteralExpression)Clone(); } /// <summary> /// <see cref="Node.CleanClone"/> /// </summary> [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] new public NullLiteralExpression CleanClone() { return (NullLiteralExpression)base.CleanClone(); } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public NodeType NodeType { get { return NodeType.NullLiteralExpression; } } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public void Accept(IAstVisitor visitor) { visitor.OnNullLiteralExpression(this); } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public bool Matches(Node node) { if (node == null) return false; if (NodeType != node.NodeType) return false; var other = ( NullLiteralExpression)node; return true; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public bool Replace(Node existing, Node newNode) { if (base.Replace(existing, newNode)) { return true; } return false; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public object Clone() { NullLiteralExpression clone = new NullLiteralExpression(); clone._lexicalInfo = _lexicalInfo; clone._endSourceLocation = _endSourceLocation; clone._documentation = _documentation; clone._isSynthetic = _isSynthetic; clone._entity = _entity; if (_annotations != null) clone._annotations = (Hashtable)_annotations.Clone(); clone._expressionType = _expressionType; return clone; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override internal void ClearTypeSystemBindings() { _annotations = null; _entity = null; _expressionType = null; } } }
bsd-3-clause
slawosz/rubinius
mspec/spec/matchers/include_spec.rb
1347
require File.dirname(__FILE__) + '/../spec_helper' require 'mspec/expectations/expectations' require 'mspec/matchers/include' describe IncludeMatcher do it "matches when actual includes expected" do IncludeMatcher.new(2).matches?([1,2,3]).should == true IncludeMatcher.new("b").matches?("abc").should == true end it "does not match when actual does not include expected" do IncludeMatcher.new(4).matches?([1,2,3]).should == false IncludeMatcher.new("d").matches?("abc").should == false end it "matches when actual includes all expected" do IncludeMatcher.new(3, 2, 1).matches?([1,2,3]).should == true IncludeMatcher.new("a", "b", "c").matches?("abc").should == true end it "does not match when actual does not include all expected" do IncludeMatcher.new(3, 2, 4).matches?([1,2,3]).should == false IncludeMatcher.new("a", "b", "c", "d").matches?("abc").should == false end it "provides a useful failure message" do matcher = IncludeMatcher.new(5, 2) matcher.matches?([1,2,3]) matcher.failure_message.should == ["Expected [1, 2, 3]", "to include 5"] end it "provides a useful negative failure message" do matcher = IncludeMatcher.new(1, 2, 3) matcher.matches?([1,2,3]) matcher.negative_failure_message.should == ["Expected [1, 2, 3]", "not to include 3"] end end
bsd-3-clause
seogi1004/cdnjs
ajax/libs/emojionearea/2.1.4/js/emojionearea.js
41824
/*! * EmojioneArea v2.1.4 * https://github.com/mervick/emojionearea * Copyright Andrey Izman and other contributors * Released under the MIT license * Date: 2016-05-24T20:06Z */ (function(document, window, $) { 'use strict'; var unique = 0; var eventStorage = {}; var emojione = window.emojione; var readyCallbacks = []; function emojioneReady (fn) { if (emojione) { fn(); } else { readyCallbacks.push(fn); } }; var blankImg = 'data:image/gif;base64,R0lGODlhAQABAJH/AP///wAAAMDAwAAAACH5BAEAAAIALAAAAAABAAEAAAICVAEAOw=='; var setInterval = window.setInterval; var clearInterval = window.clearInterval; function trigger(self, event, args) { var result = true, j = 1; if (event) { event = event.toLowerCase(); do { var _event = j==1 ? '@' + event : event; if (eventStorage[self.id][_event] && eventStorage[self.id][_event].length) { $.each(eventStorage[self.id][_event], function (i, fn) { return result = fn.apply(self, args|| []) !== false; }); } } while (result && !!j--); } return result; } var slice = [].slice; function attach(self, element, events, target) { target = target || function (event, callerEvent) { return $(callerEvent.currentTarget) }; $.each($.isArray(element) ? element : [element], function(i, el) { $.each(events, function(event, handler) { $(el).on(event = $.isArray(events) ? handler : event, function() { var _target = $.isFunction(target) ? target.apply(self, [event].concat(slice.call(arguments))) : target; if (_target) { trigger(self, handler, [_target].concat(slice.call(arguments))); } }); }); }); } var emojioneList = []; var emojioneVersion = window.emojioneVersion || '1.5.2'; var emojioneSupportMode = 0; function getTemplate(template, unicode, shortname) { return template .replace('{name}', shortname || '') .replace('{img}', emojione.imagePathPNG + (emojioneSupportMode !== 1 ? unicode.toUpperCase() : unicode) + '.png'/* + emojione.cacheBustParam*/) .replace('{uni}', emojioneSupportMode < 1 ? unicode.toUpperCase() : unicode) .replace('{alt}', emojione.convert(unicode)); } function shortnameTo(str, template) { return str.replace(/:?[\w_]+:?/g, function(shortname) { shortname = ":" + shortname.replace(/:$/,'').replace(/^:/,'') + ":"; if (shortname in emojioneList) { return getTemplate(template, emojioneList[shortname][emojioneList[shortname].length-1], shortname); } return shortname; }); }; function pasteHtmlAtCaret(html) { var sel, range; if (window.getSelection) { sel = window.getSelection(); if (sel.getRangeAt && sel.rangeCount) { range = sel.getRangeAt(0); range.deleteContents(); var el = document.createElement("div"); el.innerHTML = html; var frag = document.createDocumentFragment(), node, lastNode; while ( (node = el.firstChild) ) { lastNode = frag.appendChild(node); } range.insertNode(frag); if (lastNode) { range = range.cloneRange(); range.setStartAfter(lastNode); range.collapse(true); sel.removeAllRanges(); sel.addRange(range); } } } else if (document.selection && document.selection.type != "Control") { document.selection.createRange().pasteHTML(html); } } var default_options = { template : "<editor/><filters/><tabs/>", dir : "ltr", spellcheck : false, autocomplete : "off", autocorrect : "off", autocapitalize : "off", placeholder : null, container : null, hideSource : true, autoHideFilters : false, shortnames : false, useSprite : true, standalone : false, filters: { people: { icon: "yum", emoji: "grinning,grin,joy,smiley,smile,sweat_smile,laughing,innocent,smiling_imp,imp,wink,blush," + "relaxed,yum,relieved,heart_eyes,sunglasses,smirk,neutral_face,expressionless,unamused,sweat," + "pensive,confused,confounded,kissing,kissing_heart,kissing_smiling_eyes,kissing_closed_eyes," + "stuck_out_tongue,stuck_out_tongue_winking_eye,stuck_out_tongue_closed_eyes,disappointed,worried," + "angry,rage,cry,persevere,triumph,disappointed_relieved,frowning,anguished,fearful,weary," + "sleepy,tired_face,grimacing,sob,open_mouth,hushed,cold_sweat,scream,astonished,flushed," + "sleeping,dizzy_face,no_mouth,mask,slight_frown,slight_smile,smile_cat,joy_cat,smiley_cat," + "heart_eyes_cat,smirk_cat,kissing_cat,pouting_cat,crying_cat_face,scream_cat,footprints," + "bust_in_silhouette,busts_in_silhouette,levitate,spy,baby,boy,girl,man,woman,family," + "family_mwg,family_mwgb,family_mwbb,family_mwgg,family_wwb,family_wwg,family_wwgb,family_wwbb," + "family_wwgg,family_mmb,family_mmg,family_mmgb,family_mmbb,family_mmgg,couple,two_men_holding_hands," + "two_women_holding_hands,dancers,bride_with_veil,person_with_blond_hair,man_with_gua_pi_mao," + "man_with_turban,older_man,older_woman,cop,construction_worker,princess,guardsman,angel," + "santa,ghost,japanese_ogre,japanese_goblin,poop,skull,alien,space_invader,bow," + "information_desk_person,no_good,ok_woman,raising_hand,person_with_pouting_face,person_frowning," + "massage,haircut,couple_with_heart,couple_ww,couple_mm,couplekiss,kiss_ww,kiss_mm,raised_hands," + "clap,ear,eye,eyes,nose,lips,kiss,tongue,nail_care,wave,thumbsup,thumbsdown," + "point_up,point_up_2,point_down,point_left,point_right,ok_hand,v,punch,fist,raised_hand," + "muscle,open_hands,writing_hand,hand_splayed,middle_finger,vulcan,pray" }, nature: { icon: "whale", emoji: "seedling,evergreen_tree,deciduous_tree,palm_tree,cactus,tulip,cherry_blossom,rose,hibiscus," + "sunflower,blossom,bouquet,ear_of_rice,herb,four_leaf_clover,maple_leaf,fallen_leaf,leaves," + "mushroom,chestnut,rat,mouse2,mouse,hamster,ox,water_buffalo,cow2,cow,tiger2,leopard," + "tiger,chipmunk,rabbit2,rabbit,cat2,cat,racehorse,horse,ram,sheep,goat,rooster,chicken," + "baby_chick,hatching_chick,hatched_chick,bird,penguin,elephant,dromedary_camel,camel,boar,pig2," + "pig,pig_nose,dog2,poodle,dog,wolf,bear,koala,panda_face,monkey_face,see_no_evil,hear_no_evil," + "speak_no_evil,monkey,dragon,dragon_face,crocodile,snake,turtle,frog,whale2,whale,dolphin," + "octopus,fish,tropical_fish,blowfish,shell,snail,bug,ant,bee,beetle,spider,spider_web,feet," + "zap,fire,crescent_moon,sunny,partly_sunny,cloud,cloud_rain,cloud_snow,cloud_lightning,cloud_tornado," + "droplet,sweat_drops,umbrella,fog,dash,snowflake,star2,star,stars,sunrise_over_mountains,sunrise," + "rainbow,ocean,volcano,milky_way,mount_fuji,japan,globe_with_meridians,earth_africa,earth_americas," + "earth_asia,new_moon,waxing_crescent_moon,first_quarter_moon,waxing_gibbous_moon,full_moon," + "waning_gibbous_moon,last_quarter_moon,waning_crescent_moon,new_moon_with_face,full_moon_with_face," + "first_quarter_moon_with_face,last_quarter_moon_with_face,sun_with_face,wind_blowing_face" }, food_drink: { icon: "cherries", emoji: "tomato,eggplant,corn,sweet_potato,hot_pepper,grapes,melon,watermelon,tangerine,lemon," + "banana,pineapple,apple,green_apple,pear,peach,cherries,strawberry,hamburger,pizza,meat_on_bone," + "poultry_leg,rice_cracker,rice_ball,rice,curry,ramen,spaghetti,bread,fries,dango,oden,sushi," + "fried_shrimp,fish_cake,icecream,shaved_ice,ice_cream,doughnut,cookie,chocolate_bar,candy," + "lollipop,custard,honey_pot,cake,bento,stew,egg,fork_and_knife,tea,coffee,sake,wine_glass," + "cocktail,tropical_drink,beer,beers,baby_bottle" }, celebration: { icon: "tada", emoji: "ribbon,gift,birthday,jack_o_lantern,christmas_tree,tanabata_tree,bamboo,rice_scene," + "fireworks,sparkler,tada,confetti_ball,balloon,dizzy,sparkles,boom,mortar_board,crown," + "reminder_ribbon,military_medal,dolls,flags,wind_chime,crossed_flags,izakaya_lantern,ring," + "heart,broken_heart,love_letter,two_hearts,revolving_hearts,heartbeat,heartpulse,sparkling_heart," + "cupid,gift_heart,heart_decoration,purple_heart,yellow_heart,green_heart,blue_heart" }, activity: { icon: "trophy", emoji: "runner,walking,dancer,lifter,golfer,rowboat,swimmer,surfer,bath,snowboarder,ski," + "snowman,bicyclist,mountain_bicyclist,motorcycle,race_car,horse_racing,tent,fishing_pole_and_fish," + "soccer,basketball,football,baseball,tennis,rugby_football,golf,trophy,medal,running_shirt_with_sash," + "checkered_flag,musical_keyboard,guitar,violin,saxophone,trumpet,musical_note,notes,musical_score," + "headphones,microphone,performing_arts,ticket,tophat,circus_tent,clapper,film_frames,tickets," + "art,dart,8ball,bowling,slot_machine,game_die,video_game,flower_playing_cards,black_joker," + "mahjong,carousel_horse,ferris_wheel,roller_coaster" }, travel: { icon: "rocket", emoji: "railway_car,mountain_railway,steam_locomotive,train,monorail,bullettrain_side," + "bullettrain_front,train2,metro,light_rail,station,tram,railway_track,bus,oncoming_bus," + "trolleybus,minibus,ambulance,fire_engine,police_car,oncoming_police_car,rotating_light,taxi," + "oncoming_taxi,red_car,oncoming_automobile,blue_car,truck,articulated_lorry,tractor,bike," + "motorway,busstop,fuelpump,construction,vertical_traffic_light,traffic_light,rocket,helicopter," + "airplane,airplane_small,airplane_departure,airplane_arriving,seat,anchor,ship,cruise_ship," + "motorboat,speedboat,sailboat,aerial_tramway,mountain_cableway,suspension_railway," + "passport_control,customs,baggage_claim,left_luggage,yen,euro,pound,dollar,bellhop,bed," + "couch,fork_knife_plate,shopping_bags,statue_of_liberty,moyai,foggy,tokyo_tower,fountain," + "european_castle,japanese_castle,classical_building,stadium,mountain_snow,camping,beach," + "desert,island,park,cityscape,city_sunset,city_dusk,night_with_stars,bridge_at_night,house," + "homes,house_with_garden,house_abandoned,contruction_site,office,department_store,factory," + "post_office,european_post_office,hospital,bank,hotel,love_hotel,wedding,church," + "convenience_store,school,map" }, objects_symbols: { icon: "paperclips", emoji: "watch,iphone,calling,computer,desktop,keyboard,trackball,printer,alarm_clock,clock," + "hourglass_flowing_sand,hourglass,camera,camera_with_flash,video_camera,movie_camera,projector," + "tv,microphone2,level_slider,control_knobs,radio,pager,joystick,telephone_receiver,telephone," + "fax,minidisc,floppy_disk,cd,dvd,vhs,battery,electric_plug,bulb,flashlight,candle,satellite," + "satellite_orbital,credit_card,money_with_wings,moneybag,gem,closed_umbrella,pouch,purse," + "handbag,briefcase,school_satchel,lipstick,eyeglasses,dark_sunglasses,womans_hat,sandal," + "high_heel,boot,mans_shoe,athletic_shoe,bikini,dress,kimono,womans_clothes,shirt,necktie," + "jeans,door,shower,bathtub,toilet,barber,syringe,pill,microscope,telescope,crystal_ball," + "wrench,knife,dagger,nut_and_bolt,hammer,tools,oil,bomb,smoking,gun,bookmark,newspaper," + "newspaper2,thermometer,label,key,key2,envelope,envelope_with_arrow,incoming_envelope,email," + "inbox_tray,outbox_tray,package,postal_horn,postbox,mailbox_closed,mailbox,mailbox_with_no_mail," + "mailbox_with_mail,page_facing_up,page_with_curl,bookmark_tabs,wastebasket,notepad_spiral," + "chart_with_upwards_trend,chart_with_downwards_trend,bar_chart,date,calendar,calendar_spiral," + "ballot_box,low_brightness,high_brightness,compression,frame_photo,scroll,clipboard,book," + "notebook,notebook_with_decorative_cover,ledger,closed_book,green_book,blue_book,orange_book," + "books,card_index,dividers,card_box,link,paperclip,paperclips,pushpin,scissors," + "triangular_ruler,round_pushpin,straight_ruler,triangular_flag_on_post,flag_white,flag_black," + "hole,file_folder,open_file_folder,file_cabinet,black_nib,pencil2,pen_ballpoint,pen_fountain," + "paintbrush,crayon,pencil,lock_with_ink_pen,closed_lock_with_key,lock,unlock,mega,loudspeaker," + "speaker,sound,loud_sound,mute,zzz,bell,no_bell,cross_heavy,om_symbol,dove,thought_balloon," + "speech_balloon,anger_right,children_crossing,shield,mag,mag_right,speaking_head," + "sleeping_accommodation,no_entry_sign,no_entry,name_badge,no_pedestrians,do_not_litter," + "no_bicycles,non_potable_water,no_mobile_phones,underage,sparkle,eight_spoked_asterisk," + "negative_squared_cross_mark,white_check_mark,eight_pointed_black_star,vibration_mode," + "mobile_phone_off,vs,a,b,ab,cl,o2,sos,id,parking,wc,cool,free,new,ng,ok,up,atm," + "aries,taurus,gemini,cancer,leo,virgo,libra,scorpius,sagittarius,capricorn,aquarius," + "pisces,restroom,mens,womens,baby_symbol,wheelchair,potable_water,no_smoking," + "put_litter_in_its_place,arrow_forward,arrow_backward,arrow_up_small,arrow_down_small," + "fast_forward,rewind,arrow_double_up,arrow_double_down,arrow_right,arrow_left,arrow_up," + "arrow_down,arrow_upper_right,arrow_lower_right,arrow_lower_left,arrow_upper_left,arrow_up_down," + "left_right_arrow,arrows_counterclockwise,arrow_right_hook,leftwards_arrow_with_hook," + "arrow_heading_up,arrow_heading_down,twisted_rightwards_arrows,repeat,repeat_one,hash," + "zero,one,two,three,four,five,six,seven,eight,nine,keycap_ten,1234,abc,abcd,capital_abcd," + "information_source,signal_strength,cinema,symbols,heavy_plus_sign,heavy_minus_sign,wavy_dash," + "heavy_division_sign,heavy_multiplication_x,heavy_check_mark,arrows_clockwise,tm,copyright," + "registered,currency_exchange,heavy_dollar_sign,curly_loop,loop,part_alternation_mark," + "exclamation,question,grey_exclamation,grey_question,bangbang,interrobang,x,o,100,end," + "back,on,top,soon,cyclone,m,ophiuchus,six_pointed_star,beginner,trident,warning," + "hotsprings,rosette,recycle,anger,diamond_shape_with_a_dot_inside,spades,clubs,hearts," + "diamonds,ballot_box_with_check,white_circle,black_circle,radio_button,red_circle," + "large_blue_circle,small_red_triangle,small_red_triangle_down,small_orange_diamond," + "small_blue_diamond,large_orange_diamond,large_blue_diamond,black_small_square," + "white_small_square,black_large_square,white_large_square,black_medium_square,white_medium_square," + "black_medium_small_square,white_medium_small_square,black_square_button,white_square_button," + "clock1,clock2,clock3,clock4,clock5,clock6,clock7,clock8,clock9,clock10,clock11," + "clock12,clock130,clock230,clock330,clock430,clock530,clock630,clock730,clock830,clock930," + "clock1030,clock1130,clock1230" }, flags: { icon: "triangular_flag_on_post", emoji: "au,at,be,br,ca,flag_cl,cn,co,dk,fi,fr,de,hk,in,flag_id,ie,il,it,jp,kr,mo," + "my,mx,nl,nz,no,ph,pl,pt,pr,ru,flag_sa,sg,za,es,se,ch,tr,gb,us,ae,vn,af,al,dz," + "ad,ao,ai,ag,ar,am,aw,ac,az,bs,bh,bd,bb,by,bz,bj,bm,bt,bo,ba,bw,bn,bg,bf,bi," + "kh,cm,cv,ky,cf,km,flag_cd,cg,td,cr,ci,hr,cu,cy,cz,dj,dm,do,tl,ec,eg,sv,gq,er," + "ee,et,fk,fo,fj,pf,ga,gm,ge,gh,gi,gr,gl,gd,gu,gt,gn,gw,gy,ht,hn,hu,is,ir,iq,jm," + "je,jo,kz,ke,ki,xk,kw,kg,la,lv,lb,ls,lr,ly,li,lt,lu,mk,mg,mw,mv,ml,mt,mh,mr,mu," + "fm,md,mc,mn,me,ms,ma,mz,mm,na,nr,np,nc,ni,ne,flag_ng,nu,kp,om,pk,pw,ps,pa,pg," + "py,pe,qa,ro,rw,sh,kn,lc,vc,ws,sm,st,sn,rs,sc,sl,sk,si,sb,so,lk,sd,sr,sz,sy,tw,tj," + "tz,th,tg,to,tt,tn,flag_tm,flag_tv,vi,ug,ua,uy,uz,vu,va,ve,wf,eh,ye,zm,zw" } } }; function getOptions(options) { options = $.extend({}, default_options, options); if (emojioneSupportMode > 0) { options.filters.people.emoji = options.filters.people.emoji .replace(",writing_hand,", ","); options.filters.travel.emoji = options.filters.travel.emoji .replace(",contruction_site,", ",construction_site,"); options.filters.objects_symbols.emoji = options.filters.objects_symbols.emoji .replace(",keycap_ten,", ",ten,") .replace(",cross_heavy,", ",cross,"); } return options; } var saveSelection, restoreSelection; if (window.getSelection && document.createRange) { saveSelection = function(el) { var range = window.getSelection().getRangeAt(0); var preSelectionRange = range.cloneRange(); preSelectionRange.selectNodeContents(el); preSelectionRange.setEnd(range.startContainer, range.startOffset); return preSelectionRange.toString().length; }; restoreSelection = function(el, sel) { var charIndex = 0, range = document.createRange(); range.setStart(el, 0); range.collapse(true); var nodeStack = [el], node, foundStart = false, stop = false; while (!stop && (node = nodeStack.pop())) { if (node.nodeType == 3) { var nextCharIndex = charIndex + node.length; if (!foundStart && sel >= charIndex && sel <= nextCharIndex) { range.setStart(node, sel - charIndex); range.setEnd(node, sel - charIndex); stop = true; } charIndex = nextCharIndex; } else { var i = node.childNodes.length; while (i--) { nodeStack.push(node.childNodes[i]); } } } sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range); } } else if (document.selection && document.body.createTextRange) { saveSelection = function(el) { var selectedTextRange = document.selection.createRange(), preSelectionTextRange = document.body.createTextRange(); preSelectionTextRange.moveToElementText(el); preSelectionTextRange.setEndPoint("EndToStart", selectedTextRange); var start = preSelectionTextRange.text.length; return start + selectedTextRange.text.length; }; restoreSelection = function(el, sel) { var textRange = document.body.createTextRange(); textRange.moveToElementText(el); textRange.collapse(true); textRange.moveEnd("character", sel); textRange.moveStart("character", sel); textRange.select(); }; } var uniRegexp = 0; var cdn_base = "https://cdnjs.cloudflare.com/ajax/libs/emojione/"; function detectSupportMode() { return (typeof emojione['jsEscapeMap']).toLowerCase() === 'object' ? emojione.cacheBustParam === "?v=1.2.4" ? 2 : 1 : 0; } if (!emojione) { $.getScript(cdn_base + emojioneVersion + "/lib/js/emojione.min.js", function () { emojione = window.emojione; emojioneSupportMode = detectSupportMode(); cdn_base += emojioneVersion + "/assets"; var sprite = cdn_base +"/sprites/emojione.sprites.css"; if (document.createStyleSheet) { document.createStyleSheet(sprite); } else { $('<link/>', {rel: 'stylesheet', href: sprite}).appendTo('head'); } while (readyCallbacks.length) { readyCallbacks.shift().call(); } }); } else { emojioneSupportMode = detectSupportMode(); cdn_base += (emojioneSupportMode > 0 ? emojioneSupportMode > 1 ? '2.0.0' : '2.1.1' : '1.5.2') + "/assets"; } emojioneReady(function() { emojione.imagePathPNG = cdn_base + "/png/"; emojione.imagePathSVG = cdn_base + "/svg/"; emojione.imagePathSVGSprites = cdn_base + "/sprites/emojione.sprites.svg"; $.each(emojione.emojioneList, function (shortname, keys) { // fix shortnames for emojione v1.5.0 emojioneList[shortname.replace('-', '_')] = keys; }); uniRegexp = new RegExp("<object[^>]*>.*?<\/object>|<span[^>]*>.*?<\/span>|<(?:object|embed|svg|img|div|span|p|a)[^>]*>|("+ emojione.unicodeRegexp+")", "gi"); }); function unicodeTo(str, template) { return str.replace(uniRegexp, function(unicodeChar) { var map = emojione[(emojioneSupportMode < 1 ? 'jsecapeMap' : 'jsEscapeMap')]; if (typeof unicodeChar !== 'undefined' && unicodeChar in map) { return getTemplate(template, map[unicodeChar]); } return unicodeChar; }); } function htmlFromText(str, self) { str = str .replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') .replace(/'/g, '&#x27;') .replace(/`/g, '&#x60;') .replace(/(?:\r\n|\r|\n)/g, '\n') .replace(/(\n+)/g, '<div>$1</div>') .replace(/\n/g, '<br/>') .replace(/<br\/><\/div>/g, '</div>'); if (self.shortnames) { str = emojione.shortnameToUnicode(str); } return unicodeTo(str, '<img alt="{alt}" class="emojione' + (self.sprite ? '-{uni}" src="' + blankImg + '">' : '" src="{img}">')) .replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;') .replace(/ /g, '&nbsp;&nbsp;'); } function textFromHtml(str, self) { str = str .replace(/<img[^>]*alt="([^"]+)"[^>]*>/ig, '$1') .replace(/\n|\r/g, '') .replace(/<br[^>]*>/ig, '\n') .replace(/(?:<(?:div|p|ol|ul|li|pre|code|object)[^>]*>)+/ig, '<div>') .replace(/(?:<\/(?:div|p|ol|ul|li|pre|code|object)>)+/ig, '</div>') .replace(/\n<div><\/div>/ig, '\n') .replace(/<div><\/div>\n/ig, '\n') .replace(/(?:<div>)+<\/div>/ig, '\n') .replace(/([^\n])<\/div><div>/ig, '$1\n') .replace(/(?:<\/div>)+/ig, '</div>') .replace(/([^\n])<\/div>([^\n])/ig, '$1\n$2') .replace(/<\/div>/ig, '') .replace(/([^\n])<div>/ig, '$1\n') .replace(/\n<div>/ig, '\n') .replace(/<div>\n/ig, '\n\n') .replace(/<(?:[^>]+)?>/g, '') .replace(/&#8291;/g, '') .replace(/&nbsp;/g, ' ') .replace(/&lt;/g, '<') .replace(/&gt;/g, '>') .replace(/&quot;/g, '"') .replace(/&#x27;/g, "'") .replace(/&#x60;/g, '`') .replace(/&amp;/g, '&'); return self && self.shortnames ? emojione.toShort(str) : str; } function init(self, source, options) { options = getOptions(options); var sourceValFunc = source.is("INPUT") ? "val" : "text", app = options.template, stayFocused = false, container = !!options.container ? $(options.container) : false, editor, filters, tabs, button, scrollArea, filtersBtns, filtersArrowLeft, filtersArrowRight, filtersWidth, scrollLeft = 0, scrollAreaWidth = 0, filterWidth, resizeHandler = function() { var width = filters.width(); if (width !== filtersWidth) { filtersWidth = width; trigger(self, 'resize', [editor]); } }, resizeHandlerID, hide = function(e) { return e.addClass("ea-hidden"); }, show = function(e) { return e.removeClass("ea-hidden"); }; self.sprite = options.useSprite; self.shortnames = options.shortnames; self.standalone = options.standalone; // in standalone mode we're using css for positioning so fix order if (self.standalone) { app = "<button/><filters/><tabs/>"; } var els = ["filters", "tabs"]; if (self.standalone) { els.push("button"); } else { els.push("editor"); } for (var el = els, i=0; i<3; i++) { app = app.replace(new RegExp('<' + el[i] + '/?>' ,'i'), '<div class="emojionearea-' + el[i] + '"></div>'); } app = $('<div/>', {"class" : source.attr("class"), role: "application"}).addClass("emojionearea").html(app); if (self.standalone) { button = self.button = app.find(".emojionearea-button"); app.addClass("has-button"); } else { editor = self.editor = app.find(".emojionearea-editor") .attr({ contenteditable: true, placeholder: options["placeholder"] || source.data("placeholder") || source.attr("placeholder") || "", tabindex: 0 }); for (var attr = ["dir", "spellcheck", "autocomplete", "autocorrect", "autocapitalize"], j=0; j<5; j++) { editor.attr(attr[j], options[attr[j]]); } } filters = app.find(".emojionearea-filters"); if (options.autoHideFilters || self.standalone) { hide(filters); } tabs = app.find(".emojionearea-tabs"); hide(tabs); $.each(options.filters, function(filter, params) { $("<i/>", {"class": "emojionearea-filter", "data-filter": filter}) .wrapInner(shortnameTo(params.icon, self.sprite ? '<i class="emojione-{uni}"/>' : '<img class="emojione" src="{img}"/>')) .appendTo(filters); hide($("<div/>", {"class": "emojionearea-tab emojionearea-tab-" + filter})) .data("items", shortnameTo(params.emoji, '<i class="emojibtn" role="button"><' + (self.sprite ? 'i class="emojione-{uni}"' : 'img class="emojione" src="{img}"') + ' data-name="{name}"/></i>')) .appendTo(tabs); }); filters.wrapInner('<div class="emojionearea-filters-scroll"/>'); filtersArrowLeft = $('<i class="emojionearea-filter-arrow-left"/>', {role: "button"}).appendTo(filters); filtersArrowRight = $('<i class="emojionearea-filter-arrow-right"/>', {role: "button"}).appendTo(filters); filtersBtns = filters.find(".emojionearea-filter"); scrollArea = filters.children(".emojionearea-filters-scroll"); if (!!container) { container.wrapInner(app); } else { app.insertAfter(source); } if (options.hideSource) { source.hide(); } var initial = source[sourceValFunc](); var placeholder = false; // if there's no initial value try and fetch a placeholder if (!initial && self.standalone) { placeholder = true; initial = source.data("placeholder") || ":smile:"; } self.setText(initial, placeholder); attach(self, [filters, tabs], {mousedown: "area.mousedown"}, editor); attach(self, editor, {paste :"editor.paste"}, editor); attach(self, editor, ["focus", "blur"], function() { return !!stayFocused ? false : editor; }); attach(self, [editor, filters, tabs], ["mousedown", "mouseup", "click", "keyup", "keydown", "keypress"], editor); attach(self, filters.find(".emojionearea-filter"), {click: "filter.click"}); attach(self, filtersArrowLeft, {click: "arrowLeft.click", mousedown: "arrowLeft.mousedown", mouseup: "arrowLeft.mouseup"}); attach(self, filtersArrowRight, {click: "arrowRight.click", mousedown: "arrowRight.mousedown", mouseup: "arrowRight.mouseup"}); attach(self, button, { click: "button.click" }); var mousedownInterval; function clearMousedownInterval() { if (mousedownInterval) { clearInterval(mousedownInterval); } } function scrollFilters() { if (!scrollAreaWidth) { $.each(filtersBtns, function (i, e) { scrollAreaWidth += $(e).outerWidth(true); }); filterWidth = filtersBtns.eq(0).outerWidth(true); } if (scrollAreaWidth > filtersWidth) { filtersArrowRight.addClass("active"); filtersArrowLeft.addClass("active"); if (scrollLeft + scrollAreaWidth <= filtersWidth) { scrollLeft = filtersWidth - scrollAreaWidth; filtersArrowRight.removeClass("active"); clearMousedownInterval(); } else if (scrollLeft >= 0) { scrollLeft = 0; filtersArrowLeft.removeClass("active"); clearMousedownInterval(); } scrollArea.css("left", scrollLeft); } else { clearMousedownInterval(); if (scrollLeft !== 0) { scrollLeft = 0; scrollArea.css("left", scrollLeft); } filtersArrowRight.removeClass("active"); filtersArrowLeft.removeClass("active"); } } function filterScrollLeft(val) { val = val | filterWidth; scrollLeft += val; scrollFilters(); } function filterScrollRight(val) { val = val | filterWidth; scrollLeft -= val; scrollFilters(); } if (typeof options.events === 'object' && !$.isEmptyObject(options.events)) { $.each(options.events, function(event, handler) { self.on(event.replace(/_/g, '.'), handler); }); } self.on("@filter.click", function(element) { if (element.is(".active")) { element.removeClass("active"); hide(tabs); } else { filtersBtns.filter(".active").removeClass("active"); element.addClass("active"); var i, timer, tab = show(hide(show(tabs).children()) .filter(".emojionearea-tab-" + element.data("filter"))), items = tab.data("items"), event = {click: "emojibtn.click"}; if (items) { tab.data("items", false); items = items.split(','); if (self.sprite) { tab.html(items.join('')); attach(self, tab.find(".emojibtn"), event); } else { timer = setInterval(function () { for (i = 0; i < 20 && items.length; i++) { tab.append(items.shift()); } attach(self, tab.find(".emojibtn").not(".handled").addClass("handled"), event); if (!items.length) clearInterval(timer); }, 5); } } } }) .on("@resize", function() { scrollFilters(); }) .on("@arrowLeft.click", filterScrollLeft) .on("@arrowRight.click", filterScrollRight) .on("@arrowLeft.mousedown", function() { mousedownInterval = setInterval(function() {filterScrollLeft(5);}, 50); }) .on("@arrowRight.mousedown", function() { mousedownInterval = setInterval(function() {filterScrollRight(5);}, 50); }) .on("@arrowLeft.mouseup @arrowRight.mouseup",clearMousedownInterval) .on("@editor.paste", function(element) { stayFocused = true; // inserts invisible character for fix caret pasteHtmlAtCaret('<span>&#8291;</span>'); var sel = saveSelection(element[0]), editorScrollTop = element.scrollTop(), clipboard = $("<div/>", {contenteditable: true}) .css({position: "fixed", left: "-999px", width: "1px", height: "1px", top: "20px", overflow: "hidden"}) .appendTo($("BODY")) .focus(); window.setTimeout(function() { var caretID = "caret-" + (new Date()).getTime(); element.focus(); restoreSelection(element[0], sel); var text = textFromHtml(clipboard.html().replace(/\r\n|\n|\r/g, '<br>'), self), html = htmlFromText(text, self); pasteHtmlAtCaret(html); clipboard.remove(); pasteHtmlAtCaret('<i id="' + caretID +'"></i>'); element.scrollTop(editorScrollTop); var caret = $("#" + caretID), top = caret.offset().top - element.offset().top, height = element.height(); if (editorScrollTop + top >= height || editorScrollTop > top) { element.scrollTop(editorScrollTop + top - 2 * height/3); } caret.remove(); stayFocused = false; trigger(self, 'paste', [element, text, html]); }, 200); }) .on("@emojibtn.click", function(element) { var img = shortnameTo(element.children().data("name"), '<img alt="{alt}" class="emojione' + (self.sprite ? '-{uni}" src="'+blankImg+'">' : '" src="{img}">')); if (self.standalone) { self.button.html(img); self.button.removeClass("placeholder"); app.find(".emojionearea-filter.active").trigger("click"); hide(filters); } else { saveSelection(editor[0]); pasteHtmlAtCaret(img); } }) .on("@area.mousedown", function(element, event) { if (!options.autoHideFilters && !app.is(".focused")) { element.focus(); } event.preventDefault(); return false; }) .on("@change", function(element) { var html = element.html().replace(/<\/?(?:div|span|p)[^>]*>/ig, ''); // clear input, fix: chrome add <br> on contenteditable is empty if (!html.length || /^<br[^>]*>$/i.test(html)) { self.setText('', false); } source[sourceValFunc](self.getText()); }) .on("@focus", function() { resizeHandler(); resizeHandlerID = setInterval(resizeHandler, 500); app.addClass("focused"); if (options.autoHideFilters) { show(filters); } }) .on("@blur", function(element) { scrollLeft = 0; scrollFilters(); app.removeClass("focused"); clearInterval(resizeHandlerID); if (options.autoHideFilters) { hide(filters); } filtersBtns.filter(".active").removeClass("active"); hide(tabs); var content = element.html(); if (self.content !== content) { self.content = content; trigger(self, 'change', [editor]); source.blur().trigger("change"); } else { source.blur(); } }) .on("@button.click", function(element) { if (app.find(".emojionearea-filters").hasClass("ea-hidden")) { resizeHandler(); resizeHandlerID = setInterval(resizeHandler, 500); scrollFilters(); show(filters); app.find(".emojionearea-filter:first").trigger("click"); } else { app.find(".emojionearea-filter.active").trigger("click"); hide(filters); scrollFilters(); clearInterval(resizeHandlerID); } }); trigger(self, 'ready', [editor]); }; var EmojioneArea = function(element, options) { var self = this; eventStorage[self.id = ++unique] = {}; emojioneReady(function() { init(self, element, options); }); }; EmojioneArea.prototype.on = function(events, handler) { if (events && $.isFunction(handler)) { var id = this.id; $.each(events.toLowerCase().split(' '), function(i, event) { (eventStorage[id][event] || (eventStorage[id][event] = [])).push(handler); }); } return this; }; EmojioneArea.prototype.off = function(events, handler) { if (events) { var id = this.id; $.each(events.toLowerCase().replace(/_/g, '.').split(' '), function(i, event) { if (eventStorage[id][event] && !/^@/.test(event)) { if (handler) { $.each(eventStorage[id][event], function(j, fn) { if (fn === handler) { eventStorage[id][event] = eventStorage[id][event].splice(j, 1); } }); } else { eventStorage[id][event] = []; } } }); } return this; }; EmojioneArea.prototype.setText = function (str, placeholder) { var self = this, args = arguments; emojioneReady(function () { if (self.standalone) { self.button.html(htmlFromText(str, self)); self.content = self.button.html(); self.button.toggleClass("placeholder", placeholder); if (args.length === 1) { trigger(self, 'change', [self.button]); } } else { self.editor.html(htmlFromText(str, self)); self.content = self.editor.html(); if (args.length === 1) { trigger(self, 'change', [self.editor]); } } }); } EmojioneArea.prototype.getText = function() { var el = (this.standalone) ? "button" : "editor"; return textFromHtml(this[el].html(), this); } $.fn.emojioneArea = function(options) { return this.each(function() { if (!!this.emojioneArea) return this.emojioneArea; $.data(this, 'emojioneArea', this.emojioneArea = new EmojioneArea($(this), options)); return this.emojioneArea; }); }; }) (document, window, jQuery);
mit
gentlemans/gentlemanly_engine
deps/boost/boost/move/iterator.hpp
10696
////////////////////////////////////////////////////////////////////////////// // // (C) Copyright Ion Gaztanaga 2012-2012. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/move for documentation. // ////////////////////////////////////////////////////////////////////////////// //! \file #ifndef BOOST_MOVE_ITERATOR_HPP #define BOOST_MOVE_ITERATOR_HPP #ifndef BOOST_CONFIG_HPP # include <boost/config.hpp> #endif # #if defined(BOOST_HAS_PRAGMA_ONCE) # pragma once #endif #include <boost/move/detail/config_begin.hpp> #include <boost/move/detail/workaround.hpp> //forceinline #include <boost/move/detail/iterator_traits.hpp> #include <boost/move/utility_core.hpp> namespace boost { ////////////////////////////////////////////////////////////////////////////// // // move_iterator // ////////////////////////////////////////////////////////////////////////////// //! Class template move_iterator is an iterator adaptor with the same behavior //! as the underlying iterator except that its dereference operator implicitly //! converts the value returned by the underlying iterator's dereference operator //! to an rvalue reference. Some generic algorithms can be called with move //! iterators to replace copying with moving. template <class It> class move_iterator { public: typedef It iterator_type; typedef typename boost::movelib::iterator_traits<iterator_type>::value_type value_type; #if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES) || defined(BOOST_MOVE_DOXYGEN_INVOKED) typedef value_type && reference; #else typedef typename ::boost::move_detail::if_ < ::boost::has_move_emulation_enabled<value_type> , ::boost::rv<value_type>& , value_type & >::type reference; #endif typedef It pointer; typedef typename boost::movelib::iterator_traits<iterator_type>::difference_type difference_type; typedef typename boost::movelib::iterator_traits<iterator_type>::iterator_category iterator_category; BOOST_MOVE_FORCEINLINE move_iterator() : m_it() {} BOOST_MOVE_FORCEINLINE explicit move_iterator(const It &i) : m_it(i) {} template <class U> BOOST_MOVE_FORCEINLINE move_iterator(const move_iterator<U>& u) : m_it(u.m_it) {} BOOST_MOVE_FORCEINLINE reference operator*() const { #if defined(BOOST_NO_CXX11_RVALUE_REFERENCES) || defined(BOOST_MOVE_OLD_RVALUE_REF_BINDING_RULES) return *m_it; #else return ::boost::move(*m_it); #endif } BOOST_MOVE_FORCEINLINE pointer operator->() const { return m_it; } BOOST_MOVE_FORCEINLINE move_iterator& operator++() { ++m_it; return *this; } BOOST_MOVE_FORCEINLINE move_iterator<iterator_type> operator++(int) { move_iterator<iterator_type> tmp(*this); ++(*this); return tmp; } BOOST_MOVE_FORCEINLINE move_iterator& operator--() { --m_it; return *this; } BOOST_MOVE_FORCEINLINE move_iterator<iterator_type> operator--(int) { move_iterator<iterator_type> tmp(*this); --(*this); return tmp; } move_iterator<iterator_type> operator+ (difference_type n) const { return move_iterator<iterator_type>(m_it + n); } BOOST_MOVE_FORCEINLINE move_iterator& operator+=(difference_type n) { m_it += n; return *this; } BOOST_MOVE_FORCEINLINE move_iterator<iterator_type> operator- (difference_type n) const { return move_iterator<iterator_type>(m_it - n); } BOOST_MOVE_FORCEINLINE move_iterator& operator-=(difference_type n) { m_it -= n; return *this; } BOOST_MOVE_FORCEINLINE reference operator[](difference_type n) const { #if defined(BOOST_NO_CXX11_RVALUE_REFERENCES) || defined(BOOST_MOVE_OLD_RVALUE_REF_BINDING_RULES) return m_it[n]; #else return ::boost::move(m_it[n]); #endif } BOOST_MOVE_FORCEINLINE friend bool operator==(const move_iterator& x, const move_iterator& y) { return x.m_it == y.m_it; } BOOST_MOVE_FORCEINLINE friend bool operator!=(const move_iterator& x, const move_iterator& y) { return x.m_it != y.m_it; } BOOST_MOVE_FORCEINLINE friend bool operator< (const move_iterator& x, const move_iterator& y) { return x.m_it < y.m_it; } BOOST_MOVE_FORCEINLINE friend bool operator<=(const move_iterator& x, const move_iterator& y) { return x.m_it <= y.m_it; } BOOST_MOVE_FORCEINLINE friend bool operator> (const move_iterator& x, const move_iterator& y) { return x.m_it > y.m_it; } BOOST_MOVE_FORCEINLINE friend bool operator>=(const move_iterator& x, const move_iterator& y) { return x.m_it >= y.m_it; } BOOST_MOVE_FORCEINLINE friend difference_type operator-(const move_iterator& x, const move_iterator& y) { return x.m_it - y.m_it; } BOOST_MOVE_FORCEINLINE friend move_iterator operator+(difference_type n, const move_iterator& x) { return move_iterator(x.m_it + n); } private: It m_it; }; //is_move_iterator namespace move_detail { template <class I> struct is_move_iterator { static const bool value = false; }; template <class I> struct is_move_iterator< ::boost::move_iterator<I> > { static const bool value = true; }; } //namespace move_detail { ////////////////////////////////////////////////////////////////////////////// // // move_iterator // ////////////////////////////////////////////////////////////////////////////// //! //! <b>Returns</b>: move_iterator<It>(i). template<class It> inline move_iterator<It> make_move_iterator(const It &it) { return move_iterator<It>(it); } ////////////////////////////////////////////////////////////////////////////// // // back_move_insert_iterator // ////////////////////////////////////////////////////////////////////////////// //! A move insert iterator that move constructs elements at the //! back of a container template <typename C> // C models Container class back_move_insert_iterator { C* container_m; public: typedef C container_type; typedef typename C::value_type value_type; typedef typename C::reference reference; typedef typename C::pointer pointer; typedef typename C::difference_type difference_type; typedef std::output_iterator_tag iterator_category; explicit back_move_insert_iterator(C& x) : container_m(&x) { } back_move_insert_iterator& operator=(reference x) { container_m->push_back(boost::move(x)); return *this; } back_move_insert_iterator& operator=(BOOST_RV_REF(value_type) x) { reference rx = x; return this->operator=(rx); } back_move_insert_iterator& operator*() { return *this; } back_move_insert_iterator& operator++() { return *this; } back_move_insert_iterator& operator++(int) { return *this; } }; //! //! <b>Returns</b>: back_move_insert_iterator<C>(x). template <typename C> // C models Container inline back_move_insert_iterator<C> back_move_inserter(C& x) { return back_move_insert_iterator<C>(x); } ////////////////////////////////////////////////////////////////////////////// // // front_move_insert_iterator // ////////////////////////////////////////////////////////////////////////////// //! A move insert iterator that move constructs elements int the //! front of a container template <typename C> // C models Container class front_move_insert_iterator { C* container_m; public: typedef C container_type; typedef typename C::value_type value_type; typedef typename C::reference reference; typedef typename C::pointer pointer; typedef typename C::difference_type difference_type; typedef std::output_iterator_tag iterator_category; explicit front_move_insert_iterator(C& x) : container_m(&x) { } front_move_insert_iterator& operator=(reference x) { container_m->push_front(boost::move(x)); return *this; } front_move_insert_iterator& operator=(BOOST_RV_REF(value_type) x) { reference rx = x; return this->operator=(rx); } front_move_insert_iterator& operator*() { return *this; } front_move_insert_iterator& operator++() { return *this; } front_move_insert_iterator& operator++(int) { return *this; } }; //! //! <b>Returns</b>: front_move_insert_iterator<C>(x). template <typename C> // C models Container inline front_move_insert_iterator<C> front_move_inserter(C& x) { return front_move_insert_iterator<C>(x); } ////////////////////////////////////////////////////////////////////////////// // // insert_move_iterator // ////////////////////////////////////////////////////////////////////////////// template <typename C> // C models Container class move_insert_iterator { C* container_m; typename C::iterator pos_; public: typedef C container_type; typedef typename C::value_type value_type; typedef typename C::reference reference; typedef typename C::pointer pointer; typedef typename C::difference_type difference_type; typedef std::output_iterator_tag iterator_category; explicit move_insert_iterator(C& x, typename C::iterator pos) : container_m(&x), pos_(pos) {} move_insert_iterator& operator=(reference x) { pos_ = container_m->insert(pos_, ::boost::move(x)); ++pos_; return *this; } move_insert_iterator& operator=(BOOST_RV_REF(value_type) x) { reference rx = x; return this->operator=(rx); } move_insert_iterator& operator*() { return *this; } move_insert_iterator& operator++() { return *this; } move_insert_iterator& operator++(int) { return *this; } }; //! //! <b>Returns</b>: move_insert_iterator<C>(x, it). template <typename C> // C models Container inline move_insert_iterator<C> move_inserter(C& x, typename C::iterator it) { return move_insert_iterator<C>(x, it); } } //namespace boost { #include <boost/move/detail/config_end.hpp> #endif //#ifndef BOOST_MOVE_ITERATOR_HPP
mit
zhuyue1314/z3
src/test/main.cpp
5879
#include<iostream> #include<time.h> #include<string> #include<cstring> #include"util.h" #include"trace.h" #include"debug.h" #include"timeit.h" #include"warning.h" #include "memory_manager.h" // // Unit tests fail by asserting. // If they return, we assume the unit test succeeds // and print "PASS" to indicate success. // #define TST(MODULE) { \ std::string s("test "); \ s += #MODULE; \ void tst_##MODULE(); \ if (do_display_usage) \ std::cout << #MODULE << "\n"; \ for (int i = 0; i < argc; i++) \ if (test_all || strcmp(argv[i], #MODULE) == 0) { \ enable_trace(#MODULE); \ enable_debug(#MODULE); \ timeit timeit(true, s.c_str()); \ tst_##MODULE(); \ std::cout << "PASS" << std::endl; \ } \ } #define TST_ARGV(MODULE) { \ std::string s("test "); \ s += #MODULE; \ void tst_##MODULE(char** argv, int argc, int& i); \ if (do_display_usage) \ std::cout << #MODULE << "\n"; \ for (int i = 0; i < argc; i++) \ if (strcmp(argv[i], #MODULE) == 0) { \ enable_trace(#MODULE); \ enable_debug(#MODULE); \ timeit timeit(true, s.c_str()); \ tst_##MODULE(argv, argc, i); \ std::cout << "PASS" << std::endl; \ } \ } void error(const char * msg) { std::cerr << "Error: " << msg << "\n"; std::cerr << "For usage information: test /h\n"; exit(1); } void display_usage() { std::cout << "Z3 unit tests [version 1.0]. (C) Copyright 2006 Microsoft Corp.\n"; std::cout << "Usage: test [options] [module names]\n"; std::cout << "\nMisc.:\n"; std::cout << " /h prints this message.\n"; std::cout << " /v:level be verbose, where <level> is the verbosity level.\n"; std::cout << " /w enable warning messages.\n"; std::cout << " /a run all unit tests that don't require arguments.\n"; #if defined(Z3DEBUG) || defined(_TRACE) std::cout << "\nDebugging support:\n"; #endif #ifdef _TRACE std::cout << " /tr:tag enable trace messages tagged with <tag>.\n"; #endif #ifdef Z3DEBUG std::cout << " /dbg:tag enable assertions tagged with <tag>.\n"; #endif } void parse_cmd_line_args(int argc, char ** argv, bool& do_display_usage, bool& test_all) { int i = 1; while (i < argc) { char * arg = argv[i]; if (arg[0] == '-' || arg[0] == '/') { char * opt_name = arg + 1; char * opt_arg = 0; char * colon = strchr(arg, ':'); if (colon) { opt_arg = colon + 1; *colon = 0; } if (strcmp(opt_name, "h") == 0 || strcmp(opt_name, "?") == 0) { display_usage(); do_display_usage = true; return; } else if (strcmp(opt_name, "v") == 0) { if (!opt_arg) error("option argument (/v:level) is missing."); long lvl = strtol(opt_arg, 0, 10); set_verbosity_level(lvl); } else if (strcmp(opt_name, "w") == 0) { enable_warning_messages(true); } else if (strcmp(opt_name, "a") == 0) { test_all = true; } #ifdef _TRACE else if (strcmp(opt_name, "tr") == 0) { if (!opt_arg) error("option argument (/tr:tag) is missing."); enable_trace(opt_arg); } #endif #ifdef Z3DEBUG else if (strcmp(opt_name, "dbg") == 0) { if (!opt_arg) error("option argument (/dbg:tag) is missing."); enable_debug(opt_arg); } #endif } i++; } } int main(int argc, char ** argv) { memory::initialize(0); bool do_display_usage = false; bool test_all = false; parse_cmd_line_args(argc, argv, do_display_usage, test_all); TST(random); TST(vector); TST(symbol_table); TST(region); TST(symbol); TST(heap); TST(hashtable); TST(rational); TST(inf_rational); TST(ast); TST(optional); TST(bit_vector); TST(string_buffer); TST(map); TST(diff_logic); TST(uint_set); TST_ARGV(expr_rand); TST(list); TST(small_object_allocator); TST(timeout); TST(proof_checker); TST(simplifier); TST(bv_simplifier_plugin); TST(bit_blaster); TST(var_subst); TST(simple_parser); TST(api); TST(old_interval); TST(get_implied_equalities); TST(arith_simplifier_plugin); TST(matcher); TST(object_allocator); TST(mpz); TST(mpq); TST(mpf); TST(total_order); TST(dl_table); TST(dl_context); TST(dl_util); TST(dl_product_relation); TST(dl_relation); TST(parray); TST(stack); TST(escaped); TST(buffer); TST(chashtable); TST(ex); TST(nlarith_util); TST(api_bug); TST(arith_rewriter); TST(check_assumptions); TST(smt_context); TST(theory_dl); TST(model_retrieval); TST(factor_rewriter); TST(smt2print_parse); TST(substitution); TST(polynomial); TST(upolynomial); TST(algebraic); TST(polynomial_factorization); TST(prime_generator); TST(permutation); TST(nlsat); TST(ext_numeral); TST(interval); TST(f2n); TST(hwf); TST(trigo); TST(bits); TST(mpbq); TST(mpfx); TST(mpff); TST(horn_subsume_model_converter); TST(model2expr); TST(hilbert_basis); TST(heap_trie); TST(karr); TST(no_overflow); TST(memory); TST(datalog_parser); TST_ARGV(datalog_parser_file); TST(dl_query); TST(quant_solve); TST(rcf); TST(polynorm); TST(qe_arith); TST(expr_substitution); } void initialize_mam() {} void finalize_mam() {}
mit
mocsy/coreclr
tests/src/CoreMangLib/cti/system/convert/converttostring15.cs
10505
using System; using System.Globalization; using System.Runtime.CompilerServices; /// <summary> /// Convert.ToString(System.Int16,System.Int32) /// </summary> public class ConvertToString14 { public static int Main() { ConvertToString14 testObj = new ConvertToString14(); TestLibrary.TestFramework.BeginTestCase("for method: Convert.ToString(System.Int16,System.Int32)"); if (testObj.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; return retVal; } #region Positive tests public bool PosTest1() { bool retVal = true; string c_TEST_DESC = "PosTest1: Verify value is 323 and radix is 2,8,10 or 16... "; string c_TEST_ID = "P001"; Int16 int16Value =-123; int radix; String actualValue; string errorDesc; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { actualValue = "1111111110000101"; radix = 2; String resValue = Convert.ToString(int16Value, radix); if (actualValue != resValue) { errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += DataString(int16Value, radix); TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } radix = 8; actualValue = "177605"; errorDesc = ""; resValue = Convert.ToString(int16Value, radix); if (actualValue != resValue) { errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += DataString(int16Value, radix); TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } radix = 10; actualValue = "-123"; errorDesc = ""; resValue = Convert.ToString(int16Value, radix); if (actualValue != resValue) { errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += DataString(int16Value, radix); TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } radix = 16; actualValue = "ff85"; errorDesc = ""; resValue = Convert.ToString(int16Value, radix); if (actualValue != resValue) { errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += DataString(int16Value, radix); TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("005", "unexpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; string c_TEST_DESC = "PosTest2: Verify value is Int16.MaxValue and radix is 2,8,10 or 16... "; string c_TEST_ID = "P002"; Int16 int16Value = Int16.MaxValue; int radix; String actualValue; string errorDesc; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { actualValue = "111111111111111"; radix = 2; String resValue = Convert.ToString(int16Value, radix); if (actualValue != resValue) { errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += DataString(int16Value, radix); TestLibrary.TestFramework.LogError("006" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } radix = 8; actualValue = "77777"; errorDesc = ""; resValue = Convert.ToString(int16Value, radix); if (actualValue != resValue) { errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += DataString(int16Value, radix); TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } radix = 10; actualValue = "32767"; errorDesc = ""; resValue = Convert.ToString(int16Value, radix); if (actualValue != resValue) { errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += DataString(int16Value, radix); TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } radix = 16; actualValue = "7fff"; errorDesc = ""; resValue = Convert.ToString(int16Value, radix); if (actualValue != resValue) { errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += DataString(int16Value, radix); TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "unexpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; string c_TEST_DESC = "PosTest3: Verify value is Int16.MinValue and radix is 2,8,10 or 16... "; string c_TEST_ID = "P003"; Int16 int16Value = Int16.MinValue; int radix; String actualValue; string errorDesc; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { actualValue = "1000000000000000"; radix = 2; String resValue = Convert.ToString(int16Value, radix); if (actualValue != resValue) { errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += DataString(int16Value, radix); TestLibrary.TestFramework.LogError("011" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } radix = 8; actualValue = "100000"; errorDesc = ""; resValue = Convert.ToString(int16Value, radix); if (actualValue != resValue) { errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += DataString(int16Value, radix); TestLibrary.TestFramework.LogError("012" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } radix = 10; actualValue = "-32768"; errorDesc = ""; resValue = Convert.ToString(int16Value, radix); if (actualValue != resValue) { errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += DataString(int16Value, radix); TestLibrary.TestFramework.LogError("013" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } radix = 16; actualValue = "8000"; errorDesc = ""; resValue = Convert.ToString(int16Value, radix); if (actualValue != resValue) { errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += DataString(int16Value, radix); TestLibrary.TestFramework.LogError("014" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("015", "unexpected exception occurs :" + e); retVal = false; } return retVal; } #endregion #region NegativeTesting public bool NegTest1() { bool retVal = true; const string c_TEST_DESC = "NegTest1: the radix is 32..."; const string c_TEST_ID = "N001"; Int16 int16Value = TestLibrary.Generator.GetInt16(-55); int radix = 32; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { Convert.ToString(int16Value, radix); TestLibrary.TestFramework.LogError("013" + " TestId-" + c_TEST_ID, "ArgumentException is not thrown as expected ." + DataString(int16Value, radix)); retVal = false; } catch (ArgumentException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("014" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + DataString(int16Value, radix)); retVal = false; } return retVal; } #endregion #region Help Methods private string DataString(Int16 int16Value, int radix) { string str; str = string.Format("\n[int16Value value]\n \"{0}\"", int16Value); str += string.Format("\n[radix value ]\n {0}", radix); return str; } #endregion }
mit
triplei/concrete5-8
concrete/src/File/Set/SavedSearch.php
550
<?php namespace Concrete\Core\File\Set; use Database; use FileSet; class SavedSearch extends Set { public static function add($name, $searchRequest, $searchColumnsObject) { $fs = parent::createAndGetSet($name, FileSet::TYPE_SAVED_SEARCH); $db = Database::connection(); $v = array($fs->getFileSetID(), serialize($searchRequest), serialize($searchColumnsObject)); $db->executeQuery('INSERT INTO FileSetSavedSearches (fsID, fsSearchRequest, fsResultColumns) VALUES (?, ?, ?)', $v); return $fs; } }
mit
mono/referencesource
System.IdentityModel/System/IdentityModel/Tokens/SecurityTokenHandlerCollectionManager.cs
6189
//----------------------------------------------------------------------- // <copyright file="SecurityTokenHandlerCollectionManager.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace System.IdentityModel.Tokens { using System; using System.Collections.Generic; using System.IdentityModel.Configuration; using System.IdentityModel.Selectors; using System.Linq; using System.Text; /// <summary> /// A class which manages multiple named <see cref="SecurityTokenHandlerCollection"/>. /// </summary> public class SecurityTokenHandlerCollectionManager { private Dictionary<string, SecurityTokenHandlerCollection> collections = new Dictionary<string, SecurityTokenHandlerCollection>(); private string serviceName = ConfigurationStrings.DefaultServiceName; /// <summary> /// Initialize an instance of <see cref="SecurityTokenHandlerCollectionManager"/> for a given named service. /// </summary> /// <param name="serviceName">A <see cref="String"/> indicating the name of the associated service.</param> public SecurityTokenHandlerCollectionManager(string serviceName) { if (serviceName == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("serviceName"); } this.serviceName = serviceName; } /// <summary> /// Initialized with default service configuration. /// </summary> private SecurityTokenHandlerCollectionManager() : this(ConfigurationStrings.DefaultServiceName) { } /// <summary> /// Gets a count of the number of SecurityTokenHandlerCollections in this /// SecurityTokenHandlerCollectionManager. /// </summary> public int Count { get { return this.collections.Count; } } /// <summary> /// Gets the service name. /// </summary> public string ServiceName { get { return this.serviceName; } } /// <summary> /// Gets an enumeration over the SecurityTokenHandlerCollection list. /// </summary> public IEnumerable<SecurityTokenHandlerCollection> SecurityTokenHandlerCollections { get { return this.collections.Values; } } /// <summary> /// The SecurityTokenHandlerCollection for the specified usage. /// </summary> /// <param name="usage">The usage name for the SecurityTokenHandlerCollection.</param> /// <returns>A SecurityTokenHandlerCollection</returns> /// <remarks> /// Behaves like a dictionary in that it will throw an exception if there is no /// value for the specified key. /// </remarks> public SecurityTokenHandlerCollection this[string usage] { get { // Empty String is valid (Usage.Default) if (null == usage) { throw DiagnosticUtility.ThrowHelperArgumentNullOrEmptyString("usage"); } return this.collections[usage]; } set { // Empty String is valid (Usage.Default) if (null == usage) { throw DiagnosticUtility.ThrowHelperArgumentNullOrEmptyString("usage"); } this.collections[usage] = value; } } /// <summary> /// No token handlers are created. /// </summary> /// <returns>An empty token handler collection manager.</returns> public static SecurityTokenHandlerCollectionManager CreateEmptySecurityTokenHandlerCollectionManager() { return new SecurityTokenHandlerCollectionManager(ConfigurationStrings.DefaultConfigurationElementName); } /// <summary> /// Creates the default set of SecurityTokenHandlers. /// </summary> /// <returns>A SecurityTokenHandlerCollectionManager with a default collection of token handlers.</returns> public static SecurityTokenHandlerCollectionManager CreateDefaultSecurityTokenHandlerCollectionManager() { SecurityTokenHandlerCollection defaultHandlers = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection(); SecurityTokenHandlerCollectionManager defaultManager = new SecurityTokenHandlerCollectionManager(ConfigurationStrings.DefaultServiceName); defaultManager.collections.Clear(); defaultManager.collections.Add(SecurityTokenHandlerCollectionManager.Usage.Default, defaultHandlers); return defaultManager; } /// <summary> /// Checks if a SecurityTokenHandlerCollection exists for the given usage. /// </summary> /// <param name="usage">A string that represents the usage of the SecurityTokenHandlerCollection.</param> /// <returns>Whether or not a token handler collection exists for the given usage.</returns> public bool ContainsKey(string usage) { return this.collections.ContainsKey(usage); } /// <summary> /// Defines standard collection names used by the framework. /// </summary> public static class Usage { /// <summary> /// Used to reference the default collection of handlers. /// </summary> public const string Default = ""; /// <summary> /// Used to reference a collection of handlers for ActAs element processing. /// </summary> public const string ActAs = "ActAs"; /// <summary> /// Used to reference a collection of handlers for OnBehalfOf element processing. /// </summary> public const string OnBehalfOf = "OnBehalfOf"; } } }
mit
Noders/Noders_WebApp
node_modules/webpack/lib/IgnorePlugin.js
1036
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ function IgnorePlugin(resourceRegExp, contextRegExp) { this.resourceRegExp = resourceRegExp; this.contextRegExp = contextRegExp; } module.exports = IgnorePlugin; IgnorePlugin.prototype.apply = function(compiler) { var resourceRegExp = this.resourceRegExp; var contextRegExp = this.contextRegExp; compiler.plugin("normal-module-factory", function(nmf) { nmf.plugin("before-resolve", function(result, callback) { if(!result) return callback(); if(resourceRegExp.test(result.request) && (!contextRegExp || contextRegExp.test(result.context))) { return callback(); } return callback(null, result); }); }); compiler.plugin("context-module-factory", function(cmf) { cmf.plugin("before-resolve", function(result, callback) { if(!result) return callback(); if(resourceRegExp.test(result.request)) { return callback(); } return callback(null, result); }); }); };
mit
chrisanderton/magento-heroku
app/code/core/Mage/XmlConnect/Block/Catalog/Category.php
5090
<?php /** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@magentocommerce.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magentocommerce.com for more information. * * @category Mage * @package Mage_XmlConnect * @copyright Copyright (c) 2014 Magento Inc. (http://www.magentocommerce.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ /** * Category list xml renderer * * @category Mage * @package Mage_XmlConnect * @author Magento Core Team <core@magentocommerce.com> */ class Mage_XmlConnect_Block_Catalog_Category extends Mage_XmlConnect_Block_Catalog { /** * Render block HTML * * @return string */ protected function _toHtml() { /** @var $categoryXmlObj Mage_XmlConnect_Model_Simplexml_Element */ $categoryXmlObj = Mage::getModel('xmlconnect/simplexml_element', '<category></category>'); $categoryId = $this->getRequest()->getParam('id', null); $rootCategoryId = Mage::app()->getStore()->getRootCategoryId(); if (null === $categoryId) { $categoryId = $rootCategoryId; } $productsXmlObj = $productListBlock = false; /** @var $categoryModel Mage_Catalog_Model_Category */ $categoryModel = Mage::getModel('catalog/category')->load($categoryId); if ($categoryModel->getId()) { $hasMoreProductItems = 0; $productListBlock = $this->getChild('product_list'); if ($productListBlock && $categoryModel->getLevel() > 1) { $layer = Mage::getSingleton('catalog/layer'); $productsXmlObj = $productListBlock->setCategory($categoryModel)->setLayer($layer) ->getProductsXmlObject(); $hasMoreProductItems = (int)$productListBlock->getHasProductItems(); } $infoBlock = $this->getChild('category_info'); if ($infoBlock) { $categoryInfoXmlObj = $infoBlock->setCategory($categoryModel)->getCategoryInfoXmlObject(); $categoryInfoXmlObj->addChild('has_more_items', $hasMoreProductItems); $categoryXmlObj->appendChild($categoryInfoXmlObj); } } $categoryCollection = $this->getCurrentChildCategories(); // subcategories are exists if (sizeof($categoryCollection)) { $itemsXmlObj = $categoryXmlObj->addChild('items'); $categoryImageSize = Mage::getModel('xmlconnect/images')->getImageLimitParam('content/category'); foreach ($categoryCollection as $item) { /** @var $item Mage_Catalog_Model_Category */ $item = Mage::getModel('catalog/category')->load($item->getId()); if ($categoryId == $rootCategoryId && !$item->getIncludeInMenu()) { continue; } $itemXmlObj = $itemsXmlObj->addChild('item'); $itemXmlObj->addChild('label', $categoryXmlObj->escapeXml($item->getName())); $itemXmlObj->addChild('entity_id', $item->getId()); $itemXmlObj->addChild('content_type', $item->hasChildren() ? 'categories' : 'products'); if (!is_null($categoryId)) { $itemXmlObj->addChild('parent_id', $item->getParentId()); } $icon = Mage::helper('xmlconnect/catalog_category_image')->initialize($item, 'thumbnail') ->resize($categoryImageSize); $iconXml = $itemXmlObj->addChild('icon', $icon); $iconXml->addAttribute('modification_time', filemtime($icon->getNewFile())); } } if ($productListBlock && $productsXmlObj) { $categoryXmlObj->appendChild($productsXmlObj); } return $categoryXmlObj->asNiceXml(); } /** * Retrieve child categories of current category * * @return Varien_Data_Tree_Node_Collection */ public function getCurrentChildCategories() { $layer = Mage::getSingleton('catalog/layer'); $category = $layer->getCurrentCategory(); /* @var $category Mage_Catalog_Model_Category */ $categories = $category->getChildrenCategories(); $productCollection = Mage::getResourceModel('catalog/product_collection'); $layer->prepareProductCollection($productCollection); $productCollection->addCountToCategories($categories); return $categories; } }
mit
thomsonreuters/electron
spec/fixtures/module/preload-node-off-wrapper.js
69
setImmediate(function () { require('./preload-required-module') })
mit
bscoleman-psu/plymouth-webapp
external/Zend/Tool/Project/Context/Zf/ApplicationDirectory.php
1511
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Tool * @subpackage Framework * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ /** * @see Zend_Tool_Project_Context_Filesystem_Directory */ require_once 'Zend/Tool/Project/Context/Filesystem/Directory.php'; /** * This class is the front most class for utilizing Zend_Tool_Project * * A profile is a hierarchical set of resources that keep track of * items within a specific project. * * @category Zend * @package Zend_Tool * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Tool_Project_Context_Zf_ApplicationDirectory extends Zend_Tool_Project_Context_Filesystem_Directory { protected $_filesystemName = 'application'; public function getName() { return 'ApplicationDirectory'; } }
mit
localheinz/composer
src/Composer/Package/Archiver/GitExcludeFilter.php
2105
<?php /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Package\Archiver; /** * An exclude filter that processes gitignore and gitattributes * * It respects export-ignore git attributes * * @author Nils Adermann <naderman@naderman.de> */ class GitExcludeFilter extends BaseExcludeFilter { /** * Parses .gitignore and .gitattributes files if they exist * * @param string $sourcePath */ public function __construct($sourcePath) { parent::__construct($sourcePath); if (file_exists($sourcePath.'/.gitignore')) { $this->excludePatterns = $this->parseLines( file($sourcePath.'/.gitignore'), array($this, 'parseGitIgnoreLine') ); } if (file_exists($sourcePath.'/.gitattributes')) { $this->excludePatterns = array_merge( $this->excludePatterns, $this->parseLines( file($sourcePath.'/.gitattributes'), array($this, 'parseGitAttributesLine') ) ); } } /** * Callback line parser which process gitignore lines * * @param string $line A line from .gitignore * * @return array An exclude pattern for filter() */ public function parseGitIgnoreLine($line) { return $this->generatePattern($line); } /** * Callback parser which finds export-ignore rules in git attribute lines * * @param string $line A line from .gitattributes * * @return array|null An exclude pattern for filter() */ public function parseGitAttributesLine($line) { $parts = preg_split('#\s+#', $line); if (count($parts) == 2 && $parts[1] === 'export-ignore') { return $this->generatePattern($parts[0]); } return null; } }
mit
ggoforth/wp-boilerplate
wp-content/themes/NatureWPTheme_v1.9/mail/newsletter.php
811
<?php global $nature_mt; $absolute_path = __FILE__; $path_to_file = explode( 'wp-content', $absolute_path ); $path_to_wp = $path_to_file[0]; // Access WordPress require_once( $path_to_wp . '/wp-load.php' ); if(!$_POST) exit; $nature_mt = get_option('nature_mt'); $email = esc_html($_POST['nemail']); $msg = esc_attr('E-mail Subscriber: ', 'nature') . $email; $to = $nature_mt['n-email']; $sitename = get_bloginfo('name'); $subject = '[' . $sitename . ']' . ' New Message'; $headers = 'From: <' . $email . '>' . PHP_EOL; if( wp_mail( $to, $subject, $msg, $headers)); // wp_mail($to, $subject, $msg, $headers); ?>
gpl-2.0
erikvarga/gcc
libstdc++-v3/src/c++11/hash_c++0x.cc
2005
// std::hash definitions -*- C++ -*- // Copyright (C) 2010-2016 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // <http://www.gnu.org/licenses/>. #if __cplusplus < 201103L # error "hash_c++0x.cc must be compiled with -std=gnu++0x" #endif #include <type_traits> #include <bits/functional_hash.h> namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_PURE size_t hash<long double>::operator()(long double __val) const noexcept { // 0 and -0 both hash to zero. if (__val == 0.0L) return 0; int __exponent; __val = __builtin_frexpl(__val, &__exponent); __val = __val < 0.0l ? -(__val + 0.5l) : __val; const long double __mult = __SIZE_MAX__ + 1.0l; __val *= __mult; // Try to use all the bits of the mantissa (really necessary only // on 32-bit targets, at least for 80-bit floating point formats). const size_t __hibits = (size_t)__val; __val = (__val - (long double)__hibits) * __mult; const size_t __coeff = __SIZE_MAX__ / __LDBL_MAX_EXP__; return __hibits + (size_t)__val + __coeff * __exponent; } }
gpl-2.0
PrasadG193/gcc_gimple_fe
libstdc++-v3/testsuite/tr1/5_numerical_facilities/special_functions/17_hyperg/check_nan.cc
4411
// { dg-require-c-std "" } // { dg-add-options ieee } // 2007-01-10 Edward Smith-Rowland <3dw4rd@verizon.net> // // Copyright (C) 2007-2016 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. // 5.2.1.17 hyperg #include <tr1/cmath> #include <testsuite_hooks.h> void test01() { float af = std::numeric_limits<float>::quiet_NaN(); double ad = std::numeric_limits<double>::quiet_NaN(); long double al = std::numeric_limits<long double>::quiet_NaN(); float bf = 10.0F; double bd = 10.0; long double bl = 10.0L; float cf = 3.0F; double cd = 3.0; long double cl = 3.0L; float xf = 0.5F; double xd = 0.5; long double xl = 0.5L; float a = std::tr1::hyperg(af, bf, cf, xf); float b = std::tr1::hypergf(af, bf, cf, xf); double c = std::tr1::hyperg(ad, bd, cd, xd); long double d = std::tr1::hyperg(al, bl, cl, xl); long double e = std::tr1::hypergl(al, bl, cl, xl); VERIFY(std::tr1::isnan<float>(a)); VERIFY(std::tr1::isnan<float>(b)); VERIFY(std::tr1::isnan<double>(c)); VERIFY(std::tr1::isnan<long double>(d)); VERIFY(std::tr1::isnan<long double>(e)); return; } void test02() { float af = 2.0F; double ad = 2.0; long double al = 2.0L; float bf = std::numeric_limits<float>::quiet_NaN(); double bd = std::numeric_limits<double>::quiet_NaN(); long double bl = std::numeric_limits<long double>::quiet_NaN(); float cf = 3.0F; double cd = 3.0; long double cl = 3.0L; float xf = 0.5F; double xd = 0.5; long double xl = 0.5L; float a = std::tr1::hyperg(af, bf, cf, xf); float b = std::tr1::hypergf(af, bf, cf, xf); double c = std::tr1::hyperg(ad, bd, cd, xd); long double d = std::tr1::hyperg(al, bl, cl, xl); long double e = std::tr1::hypergl(al, bl, cl, xl); VERIFY(std::tr1::isnan<float>(a)); VERIFY(std::tr1::isnan<float>(b)); VERIFY(std::tr1::isnan<double>(c)); VERIFY(std::tr1::isnan<long double>(d)); VERIFY(std::tr1::isnan<long double>(e)); return; } void test03() { float af = 2.0F; double ad = 2.0; long double al = 2.0L; float bf = 10.0F; double bd = 10.0; long double bl = 10.0L; float cf = std::numeric_limits<float>::quiet_NaN(); double cd = std::numeric_limits<double>::quiet_NaN(); long double cl = std::numeric_limits<long double>::quiet_NaN(); float xf = 0.5F; double xd = 0.5; long double xl = 0.5L; float a = std::tr1::hyperg(af, bf, cf, xf); float b = std::tr1::hypergf(af, bf, cf, xf); double c = std::tr1::hyperg(ad, bd, cd, xd); long double d = std::tr1::hyperg(al, bl, cl, xl); long double e = std::tr1::hypergl(al, bl, cl, xl); VERIFY(std::tr1::isnan<float>(a)); VERIFY(std::tr1::isnan<float>(b)); VERIFY(std::tr1::isnan<double>(c)); VERIFY(std::tr1::isnan<long double>(d)); VERIFY(std::tr1::isnan<long double>(e)); return; } void test04() { float af = 2.0F; double ad = 2.0; long double al = 2.0L; float bf = 10.0F; double bd = 10.0; long double bl = 10.0L; float cf = 3.0F; double cd = 3.0; long double cl = 3.0L; float xf = std::numeric_limits<float>::quiet_NaN(); double xd = std::numeric_limits<double>::quiet_NaN(); long double xl = std::numeric_limits<long double>::quiet_NaN(); float a = std::tr1::hyperg(af, bf, cf, xf); float b = std::tr1::hypergf(af, bf, cf, xf); double c = std::tr1::hyperg(ad, bd, cd, xd); long double d = std::tr1::hyperg(al, bl, cl, xl); long double e = std::tr1::hypergl(al, bl, cl, xl); VERIFY(std::tr1::isnan<float>(a)); VERIFY(std::tr1::isnan<float>(b)); VERIFY(std::tr1::isnan<double>(c)); VERIFY(std::tr1::isnan<long double>(d)); VERIFY(std::tr1::isnan<long double>(e)); return; } int main() { test01(); test02(); test03(); test04(); return 0; }
gpl-2.0
shiftorga/symfony-shift-backend
db/update.d/16_admin_user_angeltypes.php
695
<?php // create admin_user_angeltypes permission/privilege and assign it to the archangel usergroup. if (sql_num_query("SELECT * FROM `Privileges` WHERE `name`='admin_user_angeltypes'") == 0) { sql_query("INSERT INTO `Privileges` (`id`, `name`, `desc`) VALUES ( NULL , 'admin_user_angeltypes', 'Confirm restricted angel types' );"); $id = sql_id(); sql_query("INSERT INTO `GroupPrivileges` SET `group_id`=-5, `privilege_id`='" . sql_escape($id) . "'"); sql_query("INSERT INTO `Sprache` ( `TextID` , `Sprache` , `Text` ) VALUES ( 'admin_user_angeltypes', 'DE', 'Engeltypen freischalten' ), ( 'admin_user_angeltypes', 'EN', 'Confirm angeltypes' );"); $applied = true; } ?>
gpl-2.0
ElunaLuaEngine/ElunaTrinityCata
src/server/authserver/Main.cpp
7530
/* * Copyright (C) 2008-2014 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * @file main.cpp * @brief Authentication Server main program * * This file contains the main program for the * authentication server */ #include "AuthSocketMgr.h" #include "Common.h" #include "Config.h" #include "DatabaseEnv.h" #include "Log.h" #include "ProcessPriority.h" #include "RealmList.h" #include "SystemConfig.h" #include "Util.h" #include <cstdlib> #include <iostream> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/program_options.hpp> #include <openssl/opensslv.h> #include <openssl/crypto.h> using boost::asio::ip::tcp; using namespace boost::program_options; #ifndef _TRINITY_REALM_CONFIG # define _TRINITY_REALM_CONFIG "authserver.conf" #endif bool StartDB(); void StopDB(); void SignalHandler(const boost::system::error_code& error, int signalNumber); void KeepDatabaseAliveHandler(const boost::system::error_code& error); variables_map GetConsoleArguments(int argc, char** argv, std::string& configFile); boost::asio::io_service _ioService; boost::asio::deadline_timer _dbPingTimer(_ioService); uint32 _dbPingInterval; LoginDatabaseWorkerPool LoginDatabase; int main(int argc, char** argv) { std::string configFile = _TRINITY_REALM_CONFIG; auto vm = GetConsoleArguments(argc, argv, configFile); // exit if help is enabled if (vm.count("help")) return 0; std::string configError; if (!sConfigMgr->LoadInitial(configFile, configError)) { printf("Error in config file: %s\n", configError.c_str()); return 1; } TC_LOG_INFO("server.authserver", "%s (authserver)", _FULLVERSION); TC_LOG_INFO("server.authserver", "<Ctrl-C> to stop.\n"); TC_LOG_INFO("server.authserver", "Using configuration file %s.", configFile.c_str()); TC_LOG_INFO("server.authserver", "Using SSL version: %s (library: %s)", OPENSSL_VERSION_TEXT, SSLeay_version(SSLEAY_VERSION)); TC_LOG_INFO("server.authserver", "Using Boost version: %i.%i.%i", BOOST_VERSION / 100000, BOOST_VERSION / 100 % 1000, BOOST_VERSION % 100); // authserver PID file creation std::string pidFile = sConfigMgr->GetStringDefault("PidFile", ""); if (!pidFile.empty()) { if (uint32 pid = CreatePIDFile(pidFile)) TC_LOG_INFO("server.authserver", "Daemon PID: %u\n", pid); else { TC_LOG_ERROR("server.authserver", "Cannot create PID file %s.\n", pidFile.c_str()); return 1; } } // Initialize the database connection if (!StartDB()) return 1; // Get the list of realms for the server sRealmList->Initialize(_ioService, sConfigMgr->GetIntDefault("RealmsStateUpdateDelay", 20)); if (sRealmList->size() == 0) { TC_LOG_ERROR("server.authserver", "No valid realms specified."); StopDB(); return 1; } // Start the listening port (acceptor) for auth connections int32 port = sConfigMgr->GetIntDefault("RealmServerPort", 3724); if (port < 0 || port > 0xFFFF) { TC_LOG_ERROR("server.authserver", "Specified port out of allowed range (1-65535)"); StopDB(); return 1; } std::string bindIp = sConfigMgr->GetStringDefault("BindIP", "0.0.0.0"); sAuthSocketMgr.StartNetwork(_ioService, bindIp, port); // Set signal handlers boost::asio::signal_set signals(_ioService, SIGINT, SIGTERM); #if PLATFORM == PLATFORM_WINDOWS signals.add(SIGBREAK); #endif signals.async_wait(SignalHandler); // Set process priority according to configuration settings SetProcessPriority("server.authserver"); // Enabled a timed callback for handling the database keep alive ping _dbPingInterval = sConfigMgr->GetIntDefault("MaxPingTime", 30); _dbPingTimer.expires_from_now(boost::posix_time::minutes(_dbPingInterval)); _dbPingTimer.async_wait(KeepDatabaseAliveHandler); // Start the io service worker loop _ioService.run(); // Close the Database Pool and library StopDB(); TC_LOG_INFO("server.authserver", "Halting process..."); return 0; } /// Initialize connection to the database bool StartDB() { MySQL::Library_Init(); std::string dbstring = sConfigMgr->GetStringDefault("LoginDatabaseInfo", ""); if (dbstring.empty()) { TC_LOG_ERROR("server.authserver", "Database not specified"); return false; } int32 worker_threads = sConfigMgr->GetIntDefault("LoginDatabase.WorkerThreads", 1); if (worker_threads < 1 || worker_threads > 32) { TC_LOG_ERROR("server.authserver", "Improper value specified for LoginDatabase.WorkerThreads, defaulting to 1."); worker_threads = 1; } int32 synch_threads = sConfigMgr->GetIntDefault("LoginDatabase.SynchThreads", 1); if (synch_threads < 1 || synch_threads > 32) { TC_LOG_ERROR("server.authserver", "Improper value specified for LoginDatabase.SynchThreads, defaulting to 1."); synch_threads = 1; } // NOTE: While authserver is singlethreaded you should keep synch_threads == 1. Increasing it is just silly since only 1 will be used ever. if (!LoginDatabase.Open(dbstring, uint8(worker_threads), uint8(synch_threads))) { TC_LOG_ERROR("server.authserver", "Cannot connect to database"); return false; } TC_LOG_INFO("server.authserver", "Started auth database connection pool."); sLog->SetRealmId(0); // Enables DB appenders when realm is set. return true; } /// Close the connection to the database void StopDB() { LoginDatabase.Close(); MySQL::Library_End(); } void SignalHandler(const boost::system::error_code& error, int /*signalNumber*/) { if (!error) _ioService.stop(); } void KeepDatabaseAliveHandler(const boost::system::error_code& error) { if (!error) { TC_LOG_INFO("server.authserver", "Ping MySQL to keep connection alive"); LoginDatabase.KeepAlive(); _dbPingTimer.expires_from_now(boost::posix_time::minutes(_dbPingInterval)); _dbPingTimer.async_wait(KeepDatabaseAliveHandler); } } variables_map GetConsoleArguments(int argc, char** argv, std::string& configFile) { options_description all("Allowed options"); all.add_options() ("help,h", "print usage message") ("config,c", value<std::string>(&configFile)->default_value(_TRINITY_REALM_CONFIG), "use <arg> as configuration file") ; variables_map variablesMap; try { store(command_line_parser(argc, argv).options(all).allow_unregistered().run(), variablesMap); notify(variablesMap); } catch (std::exception& e) { std::cerr << e.what() << "\n"; } if (variablesMap.count("help")) { std::cout << all << "\n"; } return variablesMap; }
gpl-2.0
google/desugar_jdk_libs
jdk11/src/java.base/share/classes/javax/net/ssl/package-info.java
1739
/* * Copyright (c) 1999, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /** * Provides classes for the secure socket package. Using the secure * socket classes, you can communicate using SSL or a related security * protocol to reliably detect any errors introduced into the network * byte stream and to optionally encrypt the data and/or authenticate * the communicating peers. * * <ul> * <li><a href="{@docRoot}/../specs/security/standard-names.html"> * <b>Java&trade; Security Standard Algorithm Names Specification * </b></a></li> * </ul> * * @since 1.4 */ package javax.net.ssl;
gpl-2.0
leaubout/P2
src/public/app/code/core/Mage/Paypal/sql/paypal_setup/mysql4-upgrade-1.4.0.1-1.4.0.2.php
1611
<?php /** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@magentocommerce.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magentocommerce.com for more information. * * @category Mage * @package Mage_Paypal * @copyright Copyright (c) 2014 Magento Inc. (http://www.magentocommerce.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ /* @var $installer Mage_Paypal_Model_Mysql4_Setup */ $installer = $this; $installer->run(" CREATE TABLE `{$installer->getTable('paypal/cert')}` ( `cert_id` SMALLINT(5) UNSIGNED NOT NULL AUTO_INCREMENT, `website_id` SMALLINT(5) UNSIGNED NOT NULL DEFAULT '0', `content` MEDIUMBLOB NOT NULL, `updated_at` datetime default NULL, PRIMARY KEY (`cert_id`), KEY `IDX_PAYPAL_CERT_WEBSITE` (`website_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; "); $installer->getConnection()->addConstraint( 'FK_PAYPAL_CERT_WEBSITE', $this->getTable('paypal/cert'), 'website_id', $this->getTable('core/website'), 'website_id' );
gpl-2.0
gorbachiov/multisite
sites/all/libraries/ckeditor/plugins/widget/dev/console.js
3698
/** * @license Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ /* global CKCONSOLE */ 'use strict'; ( function() { CKCONSOLE.add( 'widget', { panels: [ { type: 'box', content: '<ul class="ckconsole_list ckconsole_value" data-value="instances"></ul>', refresh: function( editor ) { var instances = obj2Array( editor.widgets.instances ); return { header: 'Instances (' + instances.length + ')', instances: generateInstancesList( instances ) }; }, refreshOn: function( editor, refresh ) { editor.widgets.on( 'instanceCreated', function( evt ) { refresh(); evt.data.on( 'data', refresh ); } ); editor.widgets.on( 'instanceDestroyed', refresh ); } }, { type: 'box', content: '<ul class="ckconsole_list">' + '<li>focused: <span class="ckconsole_value" data-value="focused"></span></li>' + '<li>selected: <span class="ckconsole_value" data-value="selected"></span></li>' + '</ul>', refresh: function( editor ) { var focused = editor.widgets.focused, selected = editor.widgets.selected, selectedIds = []; for ( var i = 0; i < selected.length; ++i ) selectedIds.push( selected[ i ].id ); return { header: 'Focus &amp; selection', focused: focused ? 'id: ' + focused.id : '-', selected: selectedIds.length ? 'id: ' + selectedIds.join( ', id: ' ) : '-' }; }, refreshOn: function( editor, refresh ) { editor.on( 'selectionCheck', refresh, null, null, 999 ); } }, { type: 'log', on: function( editor, log, logFn ) { // Add all listeners with high priorities to log // messages in the correct order when one event depends on another. // E.g. selectionChange triggers widget selection - if this listener // for selectionChange will be executed later than that one, then order // will be incorrect. editor.on( 'selectionChange', function( evt ) { var msg = 'selection change', sel = evt.data.selection, el = sel.getSelectedElement(), widget; if ( el && ( widget = editor.widgets.getByElement( el, true ) ) ) msg += ' (id: ' + widget.id + ')'; log( msg ); }, null, null, 1 ); editor.widgets.on( 'instanceDestroyed', function( evt ) { log( 'instance destroyed (id: ' + evt.data.id + ')' ); }, null, null, 1 ); editor.widgets.on( 'instanceCreated', function( evt ) { log( 'instance created (id: ' + evt.data.id + ')' ); }, null, null, 1 ); editor.widgets.on( 'widgetFocused', function( evt ) { log( 'widget focused (id: ' + evt.data.widget.id + ')' ); }, null, null, 1 ); editor.widgets.on( 'widgetBlurred', function( evt ) { log( 'widget blurred (id: ' + evt.data.widget.id + ')' ); }, null, null, 1 ); editor.widgets.on( 'checkWidgets', logFn( 'checking widgets' ), null, null, 1 ); editor.widgets.on( 'checkSelection', logFn( 'checking selection' ), null, null, 1 ); } } ] } ); function generateInstancesList( instances ) { var html = '', instance; for ( var i = 0; i < instances.length; ++i ) { instance = instances[ i ]; html += itemTpl.output( { id: instance.id, name: instance.name, data: JSON.stringify( instance.data ) } ); } return html; } function obj2Array( obj ) { var arr = []; for ( var id in obj ) arr.push( obj[ id ] ); return arr; } var itemTpl = new CKEDITOR.template( '<li>id: <code>{id}</code>, name: <code>{name}</code>, data: <code>{data}</code></li>' ); } )();
gpl-2.0
kiwi3685/kiwitrees
library/Carbon/src/Carbon/Lang/en_IN.php
667
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* * Authors: * - IBM Globalization Center of Competency, Yamato Software Laboratory bug-glibc-locales@gnu.org */ return array_replace_recursive(require __DIR__.'/en.php', [ 'formats' => [ 'LT' => 'HH:mm', 'LTS' => 'HH:mm:ss', 'L' => 'DD/MM/YY', 'LL' => 'MMMM DD, YYYY', 'LLL' => 'DD MMM HH:mm', 'LLLL' => 'MMMM DD, YYYY HH:mm', ], 'day_of_first_week_of_year' => 1, ]);
gpl-3.0
mbarcia/drupsible-org
core/modules/migrate_drupal/src/Tests/d6/MigrateFieldInstanceTest.php
6187
<?php /** * @file * Contains \Drupal\migrate_drupal\Tests\d6\MigrateFieldInstanceTest. */ namespace Drupal\migrate_drupal\Tests\d6; use Drupal\field\Entity\FieldConfig; use Drupal\link\LinkItemInterface; /** * Migrate field instances. * * @group migrate_drupal */ class MigrateFieldInstanceTest extends MigrateDrupal6TestBase { /** * Modules to enable. * * @var array */ public static $modules = array( 'telephone', 'link', 'file', 'image', 'datetime', 'node', 'field', 'text', ); /** * {@inheritdoc} */ protected function setUp() { parent::setUp(); // Add some id mappings for the dependant migrations. $id_mappings = array( 'd6_field' => array( array(array('field_test'), array('node', 'field_test')), array(array('field_test_two'), array('node', 'field_test_two')), array(array('field_test_three'), array('node', 'field_test_three')), array(array('field_test_four'), array('node', 'field_test_four')), array(array('field_test_email'), array('node', 'field_test_email')), array(array('field_test_link'), array('node', 'field_test_link')), array(array('field_test_filefield'), array('node', 'field_test_filefield')), array(array('field_test_imagefield'), array('node', 'field_test_imagefield')), array(array('field_test_phone'), array('node', 'field_test_phone')), array(array('field_test_date'), array('node', 'field_test_date')), array(array('field_test_datestamp'), array('node', 'field_test_datestamp')), array(array('field_test_datetime'), array('node', 'field_test_datetime')), ), 'd6_node_type' => array( array(array('page'), array('page')), array(array('story'), array('story')), array(array('test_page'), array('test_page')), ), ); $this->prepareMigrations($id_mappings); entity_create('node_type', array('type' => 'page'))->save(); entity_create('node_type', array('type' => 'story'))->save(); entity_create('node_type', array('type' => 'test_page'))->save(); $this->loadDumps([ 'ContentNodeFieldInstance.php', 'ContentNodeField.php', 'ContentFieldTest.php', 'ContentFieldTestTwo.php', 'ContentFieldMultivalue.php', ]); $this->createFields(); $this->executeMigration('d6_field_instance'); } /** * Tests migration of file variables to file.settings.yml. */ public function testFieldInstanceSettings() { $entity = entity_create('node', array('type' => 'story')); // Test a text field. $field = FieldConfig::load('node.story.field_test'); $this->assertIdentical('Text Field', $field->label()); $expected = array('max_length' => 255); $this->assertIdentical($expected, $field->getSettings()); $this->assertIdentical('text for default value', $entity->field_test->value); // Test a number field. $field = FieldConfig::load('node.story.field_test_two'); $this->assertIdentical('Integer Field', $field->label()); $expected = array( 'min' => 10, 'max' => 100, 'prefix' => 'pref', 'suffix' => 'suf', 'unsigned' => FALSE, 'size' => 'normal', ); $this->assertIdentical($expected, $field->getSettings()); $field = FieldConfig::load('node.story.field_test_four'); $this->assertIdentical('Float Field', $field->label()); $expected = array( 'min' => 100.0, 'max' => 200.0, 'prefix' => 'id-', 'suffix' => '', ); $this->assertIdentical($expected, $field->getSettings()); // Test email field. $field = FieldConfig::load('node.story.field_test_email'); $this->assertIdentical('Email Field', $field->label()); $this->assertIdentical('benjy@example.com', $entity->field_test_email->value); // Test a filefield. $field = FieldConfig::load('node.story.field_test_filefield'); $this->assertIdentical('File Field', $field->label()); $expected = array( 'file_extensions' => 'txt pdf doc', 'file_directory' => 'images', 'description_field' => TRUE, 'max_filesize' => '200KB', 'target_type' => 'file', 'display_field' => FALSE, 'display_default' => FALSE, 'uri_scheme' => 'public', // This value should be 'default:file' but the test does not migrate field // storages so we end up with the default value for this setting. 'handler' => 'default:node', 'handler_settings' => array(), 'target_bundle' => NULL, ); $field_settings = $field->getSettings(); ksort($expected); ksort($field_settings); // This is the only way to compare arrays. $this->assertIdentical($expected, $field_settings); // Test a link field. $field = FieldConfig::load('node.story.field_test_link'); $this->assertIdentical('Link Field', $field->label()); $expected = array('title' => 2, 'link_type' => LinkItemInterface::LINK_GENERIC); $this->assertIdentical($expected, $field->getSettings()); $this->assertIdentical('default link title', $entity->field_test_link->title, 'Field field_test_link default title is correct.'); $this->assertIdentical('https://www.drupal.org', $entity->field_test_link->url, 'Field field_test_link default title is correct.'); $this->assertIdentical([], $entity->field_test_link->options['attributes']); } /** * Helper to create fields. */ protected function createFields() { $fields = array( 'field_test' => 'text', 'field_test_two' => 'integer', 'field_test_three' => 'decimal', 'field_test_four' => 'float', 'field_test_email' => 'email', 'field_test_link' => 'link', 'field_test_filefield' => 'file', 'field_test_imagefield' => 'image', 'field_test_phone' => 'telephone', 'field_test_date' => 'datetime', 'field_test_datestamp' => 'datetime', 'field_test_datetime' => 'datetime', ); foreach ($fields as $name => $type) { entity_create('field_storage_config', array( 'field_name' => $name, 'entity_type' => 'node', 'type' => $type, ))->save(); } } }
gpl-3.0
mailcow/mailcow-dockerized
data/web/inc/lib/vendor/nesbot/carbon/src/Carbon/Lang/sw_TZ.php
1019
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* * Authors: * - Kamusi Project Martin Benjamin locales@kamusi.org */ return array_replace_recursive(require __DIR__.'/sw.php', [ 'formats' => [ 'L' => 'DD/MM/YYYY', ], 'months' => ['Januari', 'Februari', 'Machi', 'Aprili', 'Mei', 'Juni', 'Julai', 'Agosti', 'Septemba', 'Oktoba', 'Novemba', 'Desemba'], 'months_short' => ['Jan', 'Feb', 'Mac', 'Apr', 'Mei', 'Jun', 'Jul', 'Ago', 'Sep', 'Okt', 'Nov', 'Des'], 'weekdays' => ['Jumapili', 'Jumatatu', 'Jumanne', 'Jumatano', 'Alhamisi', 'Ijumaa', 'Jumamosi'], 'weekdays_short' => ['J2', 'J3', 'J4', 'J5', 'Alh', 'Ij', 'J1'], 'weekdays_min' => ['J2', 'J3', 'J4', 'J5', 'Alh', 'Ij', 'J1'], 'first_day_of_week' => 1, 'day_of_first_week_of_year' => 1, 'meridiem' => ['asubuhi', 'alasiri'], ]);
gpl-3.0
RCAProduction/The-Powder-Toy
src/simulation/elements/SPAWN2.cpp
930
#include "simulation/Elements.h" //#TPT-Directive ElementClass Element_SPAWN2 PT_SPAWN2 117 Element_SPAWN2::Element_SPAWN2() { Identifier = "DEFAULT_PT_SPAWN2"; Name = "SPWN2"; Colour = PIXPACK(0xAAAAAA); MenuVisible = 0; MenuSection = SC_SOLIDS; Enabled = 1; Advection = 0.0f; AirDrag = 0.00f * CFDS; AirLoss = 1.00f; Loss = 0.00f; Collision = 0.0f; Gravity = 0.0f; Diffusion = 0.00f; HotAir = 0.000f * CFDS; Falldown = 0; Flammable = 0; Explosive = 0; Meltable = 0; Hardness = 1; Weight = 100; Temperature = R_TEMP+273.15f; HeatConduct = 0; Description = "STK2 spawn point."; State = ST_SOLID; Properties = TYPE_SOLID; LowPressure = IPL; LowPressureTransition = NT; HighPressure = IPH; HighPressureTransition = NT; LowTemperature = ITL; LowTemperatureTransition = NT; HighTemperature = ITH; HighTemperatureTransition = NT; Update = NULL; } Element_SPAWN2::~Element_SPAWN2() {}
gpl-3.0
mcolula/vidis
src/vidis/data/sim/AComponent.java
13837
/* VIDIS is a simulation and visualisation framework for distributed systems. Copyright (C) 2009 Dominik Psenner, Christoph Caks This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. */ package vidis.data.sim; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.ConcurrentModificationException; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import javax.vecmath.Point3d; import org.apache.log4j.Logger; import vidis.data.annotation.ComponentColor; import vidis.data.annotation.ComponentInfo; import vidis.data.annotation.Display; import vidis.data.annotation.DisplayColor; import vidis.data.mod.IUserComponent; import vidis.data.var.IVariableChangeListener; import vidis.data.var.vars.AVariable; import vidis.data.var.vars.DefaultVariable; import vidis.data.var.vars.FieldVariable; import vidis.data.var.vars.MethodVariable; import vidis.data.var.vars.AVariable.COMMON_IDENTIFIERS; import vidis.data.var.vars.AVariable.COMMON_SCOPES; import vidis.sim.Simulator; /** * this is the abstract component superclass that implements * all basic functionality for a simulator component like node, * packet and link. the concrete implementations can be found * at referenced locations * @author Dominik * @see SimLink * @see SimNode * @see SimPacket */ public abstract class AComponent implements IComponent, IAComponentCon, IVariableChangeListener { private Logger logger = Logger.getLogger(AComponent.class); // -- IVariableContainer fields -- // private List<IVariableChangeListener> variableChangeListeners; private Map<String, AVariable> vars; private int sleep = -1; /** * public constructor; all subclasses should call super() at * the beginning of their constructor! */ public AComponent() { // vars instanzieren init(); } /** * initializes the internal variables and containers */ private void init() { if (this.vars == null) this.vars = new ConcurrentHashMap<String, AVariable>(); if (this.variableChangeListeners == null) this.variableChangeListeners = new ArrayList<IVariableChangeListener>(); } /** * causes this object to clean all its references to other * objects in order that it may be collected by GC */ public void kill() { this.vars.clear(); this.variableChangeListeners.clear(); killVisObject(); } /** * abstract function that should return the user logic * @return a concrete implementation of IUserComponent */ protected abstract IUserComponent getUserLogic(); /** * kills the vis object safely */ protected abstract void killVisObject(); /** * initialize all method variables */ private void initVarsMethods() { for (Method m : getUserLogic().getClass().getMethods()) { initVarsMethods(m); } } /** * initialize a concrete method variable for a given method * @param m the method to check for */ private void initVarsMethods(Method m) { for (Annotation a : m.getAnnotations()) { if (a.annotationType().equals(Display.class)) { // add variable for this method Display t = (Display) a; String id = COMMON_SCOPES.USER + "." + t.name(); if (hasVariable(id)) { try { // only update ((MethodVariable)getVariableById(id)).update(getUserLogic(), m); } catch(ClassCastException e) { // variable is not a method variable; override it with a method variable registerVariable(new MethodVariable(id, getUserLogic(), m)); } } else { registerVariable(new MethodVariable(id, getUserLogic(), m)); } } else if ( a.annotationType().equals( DisplayColor.class ) ) { // DisplayColor displayColor = (DisplayColor)a; String id = COMMON_IDENTIFIERS.COLOR; try { ((MethodVariable)getVariableById(id)).update(getUserLogic(), m); } catch (ClassCastException e) { registerVariable(new MethodVariable(id, getUserLogic(), m)); } catch (NullPointerException e) { registerVariable(new MethodVariable(id, getUserLogic(), m)); } } else { //Logger.output(LogLevel.WARN, this, "unknown method-annotation " //+ a + " encountered!"); } } } /** * initialize all class variables */ private void initVarsClass() { if (getUserLogic().getClass().getAnnotations().length > 0) { for (Annotation a : getUserLogic().getClass().getAnnotations()) { if (a.annotationType().equals(ComponentColor.class)) { ComponentColor aa = (ComponentColor) a; String id = AVariable.COMMON_IDENTIFIERS.COLOR; if (hasVariable(id)) { try { ((DefaultVariable)getVariableById(id)).update(aa.color()); } catch(ClassCastException e) { registerVariable(new DefaultVariable(id, aa.color())); } } else { registerVariable(new DefaultVariable(id, aa.color())); } } else if (a.annotationType().equals(ComponentInfo.class)) { ComponentInfo aa = (ComponentInfo) a; String id = COMMON_SCOPES.USER + ".header1"; if (hasVariable(id)) { try { ((DefaultVariable)getVariableById(id)).update(aa.name()); } catch(ClassCastException e) { registerVariable(new DefaultVariable(id, aa.name())); } } else { registerVariable(new DefaultVariable(id, aa.name())); } } else { //Logger.output(LogLevel.WARN, this, // "unknown class-annotation " + a // + " encountered!"); } } } } /** * initialize all field variables */ private void initVarsFields() { for (Field f : getUserLogic().getClass().getDeclaredFields()) { for (Annotation a : f.getAnnotations()) { if (a.annotationType().equals(Display.class)) { Display d = (Display) a; String ns = ""; if (Modifier.isPublic(f.getModifiers())) { ns = COMMON_SCOPES.USER + "."; } else { ns = COMMON_SCOPES.SYSTEM + "."; } String id = ns + d.name(); if (hasVariable(id)) { try { // only update ((FieldVariable)getVariableById(id)).update(getUserLogic(), f); } catch(ClassCastException e) { registerVariable(new FieldVariable(id, getUserLogic(), f)); } } else { registerVariable(new FieldVariable(id, getUserLogic(), f)); } } else if ( a.annotationType().equals( DisplayColor.class ) ) { // DisplayColor displayColor = (DisplayColor)a; String id = COMMON_IDENTIFIERS.COLOR; try { ((FieldVariable)getVariableById(id)).update(getUserLogic(), f); } catch (ClassCastException e) { registerVariable(new FieldVariable(id, getUserLogic(), f)); } catch (NullPointerException e) { registerVariable(new FieldVariable(id, getUserLogic(), f)); } } else { // Logger.output(LogLevel.WARN, this, // "unknown field-annotation " + a // + " encountered!"); } } } } /** * initialize all variables * * this initializes method-, fields- and class-variables */ protected void initVars() { // vars initialisieren initVarsClass(); initVarsMethods(); initVarsFields(); if(!hasVariable(AVariable.COMMON_IDENTIFIERS.POSITION)) { logger.debug("set a far position"); // set a distant position in order to not spawn at 0,0,0 registerVariable(new DefaultVariable(AVariable.COMMON_IDENTIFIERS.POSITION, new Point3d(1000,1000,1000))); } else { logger.debug("DID NOT set a far position"); } } public final void registerVariable(AVariable var) { String id = var.getIdentifier(); AVariable old = vars.put(id, var); if (old == null) { // new variable var.addVariableChangeListener(this); variableAdded(id); } else { old.removeVariableChangeListener(this); variableChanged(id); } // if (hasVariable(var.getIdentifier())) { // getVariableById(Object.class, var.getIdentifier()).update(var.getData()); // } else { // Variable<?> old = vars.put(var.getIdentifier(), var); // if (old != null) { // if (!old.equals(var)) { // Logger.output(LogLevel.WARN, this, "setVar() ==> obj changed ref-id"); // // changed ref! // synchronized (this.variableChangeListeners) { // for (IVariableChangeListener l : this.variableChangeListeners) { // l.variableChanged(var.getIdentifier()); // } // } // } // } else { // // added // synchronized (this.variableChangeListeners) { // for (IVariableChangeListener l : this.variableChangeListeners) { // l.variableAdded(var.getIdentifier()); // } // } // } // } } public final boolean hasVariable(String identifier) { return this.vars.containsKey(identifier); } public String toString() { if (hasVariable(AVariable.COMMON_IDENTIFIERS.ID)) { AVariable varA = getVariableById(AVariable.COMMON_IDENTIFIERS.ID); if(varA instanceof DefaultVariable) { return ((DefaultVariable)varA).getData().toString(); } else if(varA instanceof FieldVariable) { return ((FieldVariable)varA).getData().toString(); } else if(varA instanceof MethodVariable) { return ((MethodVariable)varA).getData().toString(); } } return getUserLogic().toString(); } public AVariable getVariableById(String id) throws ClassCastException { return this.vars.get(id); } public final AVariable getScopedVariable(String scope, String identifier) { return getVariableById(scope + "." + identifier); } public final boolean hasScopedVariable(String scope, String identifier) { return hasVariable(scope + "." + identifier); } public Set<String> getScopedVariableIdentifiers(String scope) { Set<String> ids = getVariableIds(); Set<String> ssids = new HashSet<String>(); for(String id : ids) { if(id.startsWith(scope)) ssids.add(id); } return ssids; } public Set<String> getVariableIds() { return this.vars.keySet(); } public void addVariableChangeListener(IVariableChangeListener l) { synchronized (variableChangeListeners) { if (!variableChangeListeners.contains(l)) { variableChangeListeners.add(l); } } } public void removeVariableChangeListener(IVariableChangeListener l) { variableChangeListeners.remove(l); } public void variableAdded(String id) { // System.out.println("AComponent.variableAdded()"); synchronized (variableChangeListeners) { for (IVariableChangeListener l : variableChangeListeners) l.variableAdded(id); } } public void variableChanged(String id) { // System.out.println("AComponent.variableChanged()"); synchronized (variableChangeListeners) { try { for (IVariableChangeListener l : variableChangeListeners) l.variableChanged(id); } catch (ConcurrentModificationException e) { logger.fatal(e); } } } public void variableRemoved(String id) { // System.out.println("AComponent.variableRemoved()"); synchronized (variableChangeListeners) { for (IVariableChangeListener l : variableChangeListeners) l.variableRemoved(id); } } public List<IVariableChangeListener> getVariableChangeListeners() { return variableChangeListeners; } public void execute() { // variableChanged call for every variable that changed since last step // at the moment it is called for every variable, since it would cost more // time and memory to evaluate which variables state changed synchronized (vars) { for (String varId : vars.keySet()) { variableChanged(varId); } } // Logger.output(LogLevel.DEBUG, this, "vars[" + vars.size() + "], // varsListener["+variableChangeListeners.size()+"]"); if (isSleeping()) sleep--; } /** * this function checks all variables of this component * and informs everybody about changes of the variables */ protected void checkVariablesChanged() { initVarsFields(); } public void sleep(int steps) { sleep = steps; } public void interrupt() { sleep = -1; } /** * retrieve if this component is sleeping * @return true or false */ protected boolean isSleeping() { return sleep >= 0; } protected boolean isConnectedTo(SimNode simNode) { for(AComponent c : Simulator.getInstance().getSimulatorComponents()) { if( c instanceof SimLink) { SimLink l = (SimLink) c; if(l.isConnectedTo(simNode)) return true; } } return false; } }
gpl-3.0
antonbabenko/terraform
command/e2etest/primary_test.go
4206
package e2etest import ( "path/filepath" "reflect" "sort" "strings" "testing" "github.com/davecgh/go-spew/spew" "github.com/hashicorp/terraform/e2e" ) // The tests in this file are for the "primary workflow", which includes // variants of the following sequence, with different details: // terraform init // terraform plan // terraform apply // terraform destroy func TestPrimarySeparatePlan(t *testing.T) { t.Parallel() // This test reaches out to releases.hashicorp.com to download the // template and null providers, so it can only run if network access is // allowed. skipIfCannotAccessNetwork(t) fixturePath := filepath.Join("test-fixtures", "full-workflow-null") tf := e2e.NewBinary(terraformBin, fixturePath) defer tf.Close() //// INIT stdout, stderr, err := tf.Run("init") if err != nil { t.Fatalf("unexpected init error: %s\nstderr:\n%s", err, stderr) } // Make sure we actually downloaded the plugins, rather than picking up // copies that might be already installed globally on the system. if !strings.Contains(stdout, "- Downloading plugin for provider \"template\"") { t.Errorf("template provider download message is missing from init output:\n%s", stdout) t.Logf("(this can happen if you have a copy of the plugin in one of the global plugin search dirs)") } if !strings.Contains(stdout, "- Downloading plugin for provider \"null\"") { t.Errorf("null provider download message is missing from init output:\n%s", stdout) t.Logf("(this can happen if you have a copy of the plugin in one of the global plugin search dirs)") } //// PLAN stdout, stderr, err = tf.Run("plan", "-out=tfplan") if err != nil { t.Fatalf("unexpected plan error: %s\nstderr:\n%s", err, stderr) } if !strings.Contains(stdout, "1 to add, 0 to change, 0 to destroy") { t.Errorf("incorrect plan tally; want 1 to add:\n%s", stdout) } if !strings.Contains(stdout, "This plan was saved to: tfplan") { t.Errorf("missing \"This plan was saved to...\" message in plan output\n%s", stdout) } if !strings.Contains(stdout, "terraform apply \"tfplan\"") { t.Errorf("missing next-step instruction in plan output\n%s", stdout) } plan, err := tf.Plan("tfplan") if err != nil { t.Fatalf("failed to read plan file: %s", err) } stateResources := plan.State.RootModule().Resources diffResources := plan.Diff.RootModule().Resources if len(stateResources) != 1 || stateResources["data.template_file.test"] == nil { t.Errorf("incorrect state in plan; want just data.template_file.test to have been rendered, but have:\n%s", spew.Sdump(stateResources)) } if len(diffResources) != 1 || diffResources["null_resource.test"] == nil { t.Errorf("incorrect diff in plan; want just null_resource.test to have been rendered, but have:\n%s", spew.Sdump(diffResources)) } //// APPLY stdout, stderr, err = tf.Run("apply", "tfplan") if err != nil { t.Fatalf("unexpected apply error: %s\nstderr:\n%s", err, stderr) } if !strings.Contains(stdout, "Resources: 1 added, 0 changed, 0 destroyed") { t.Errorf("incorrect apply tally; want 1 added:\n%s", stdout) } state, err := tf.LocalState() if err != nil { t.Fatalf("failed to read state file: %s", err) } stateResources = state.RootModule().Resources var gotResources []string for n := range stateResources { gotResources = append(gotResources, n) } sort.Strings(gotResources) wantResources := []string{ "data.template_file.test", "null_resource.test", } if !reflect.DeepEqual(gotResources, wantResources) { t.Errorf("wrong resources in state\ngot: %#v\nwant: %#v", gotResources, wantResources) } //// DESTROY stdout, stderr, err = tf.Run("destroy", "-force") if err != nil { t.Fatalf("unexpected destroy error: %s\nstderr:\n%s", err, stderr) } if !strings.Contains(stdout, "Resources: 1 destroyed") { t.Errorf("incorrect destroy tally; want 1 destroyed:\n%s", stdout) } state, err = tf.LocalState() if err != nil { t.Fatalf("failed to read state file after destroy: %s", err) } stateResources = state.RootModule().Resources if len(stateResources) != 0 { t.Errorf("wrong resources in state after destroy; want none, but still have:%s", spew.Sdump(stateResources)) } }
mpl-2.0
chenyayi/shopizer
shopizer/sm-core-model/src/main/java/com/salesmanager/core/business/catalog/product/model/review/ProductReview.java
3977
package com.salesmanager.core.business.catalog.product.model.review; import java.util.Date; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Embedded; import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.TableGenerator; import javax.persistence.Temporal; import javax.persistence.TemporalType; import com.salesmanager.core.business.catalog.product.model.Product; import com.salesmanager.core.business.common.model.audit.AuditListener; import com.salesmanager.core.business.common.model.audit.AuditSection; import com.salesmanager.core.business.common.model.audit.Auditable; import com.salesmanager.core.business.customer.model.Customer; import com.salesmanager.core.business.generic.model.SalesManagerEntity; import com.salesmanager.core.constants.SchemaConstant; @Entity @EntityListeners(value = AuditListener.class) @Table(name = "PRODUCT_REVIEW", schema=SchemaConstant.SALESMANAGER_SCHEMA) public class ProductReview extends SalesManagerEntity<Long, ProductReview> implements Auditable { private static final long serialVersionUID = -7509351278087554383L; @Id @Column(name = "PRODUCT_REVIEW_ID", unique=true, nullable=false) @TableGenerator(name = "TABLE_GEN", table = "SM_SEQUENCER", pkColumnName = "SEQ_NAME", valueColumnName = "SEQ_COUNT", pkColumnValue = "PRODUCT_REVIEW_SEQ_NEXT_VAL") @GeneratedValue(strategy = GenerationType.TABLE, generator = "TABLE_GEN") private Long id; @Embedded private AuditSection audit = new AuditSection(); @Column(name = "REVIEWS_RATING") private Double reviewRating; @Column(name = "REVIEWS_READ") private Long reviewRead; @Temporal(TemporalType.TIMESTAMP) @Column(name = "REVIEW_DATE") private Date reviewDate; @Column(name = "STATUS") private Integer status; @ManyToOne @JoinColumn(name="CUSTOMERS_ID") private Customer customer; @OneToOne @JoinColumn(name="PRODUCT_ID") private Product product; @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "productReview") private Set<ProductReviewDescription> descriptions = new HashSet<ProductReviewDescription>(); public ProductReview() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Double getReviewRating() { return reviewRating; } public void setReviewRating(Double reviewRating) { this.reviewRating = reviewRating; } public Long getReviewRead() { return reviewRead; } public void setReviewRead(Long reviewRead) { this.reviewRead = reviewRead; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public Customer getCustomer() { return customer; } public void setCustomer(Customer customer) { this.customer = customer; } public Product getProduct() { return product; } public void setProduct(Product product) { this.product = product; } public Set<ProductReviewDescription> getDescriptions() { return descriptions; } public void setDescriptions(Set<ProductReviewDescription> descriptions) { this.descriptions = descriptions; } @Override public AuditSection getAuditSection() { return audit; } @Override public void setAuditSection(AuditSection audit) { this.audit = audit; } public Date getReviewDate() { return reviewDate; } public void setReviewDate(Date reviewDate) { this.reviewDate = reviewDate; } }
lgpl-2.1
abhinavmoudgil95/root
tutorials/unfold/testUnfold4.C
6849
/// \file /// \ingroup tutorial_unfold /// \notebook /// Test program for the class TUnfoldSys. /// /// Simple toy tests of the TUnfold package /// /// Pseudo data (5000 events) are unfolded into three components /// The unfolding is performed once without and once with area constraint /// /// Ideally, the pulls may show that the result is biased if no constraint /// is applied. This is expected because the true data errors are not known, /// and instead the sqrt(data) errors are used. /// /// \macro_output /// \macro_code /// /// **Version 17.6, in parallel to changes in TUnfold** /// /// #### History: /// - Version 17.5, in parallel to changes in TUnfold /// - Version 17.4, in parallel to changes in TUnfold /// - Version 17.3, in parallel to changes in TUnfold /// - Version 17.2, in parallel to changes in TUnfold /// - Version 17.1, in parallel to changes in TUnfold /// - Version 16.1, parallel to changes in TUnfold /// - Version 16.0, parallel to changes in TUnfold /// - Version 15, use L-curve scan to scan the average correlation /// /// This file is part of TUnfold. /// /// TUnfold is free software: you can redistribute it and/or modify /// it under the terms of the GNU General Public License as published by /// the Free Software Foundation, either version 3 of the License, or /// (at your option) any later version. /// /// TUnfold is distributed in the hope that it will be useful, /// but WITHOUT ANY WARRANTY; without even the implied warranty of /// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /// GNU General Public License for more details. /// /// You should have received a copy of the GNU General Public License /// along with TUnfold. If not, see <http://www.gnu.org/licenses/>. /// /// \author Stefan Schmitt DESY, 14.10.2008 #include <TMath.h> #include <TCanvas.h> #include <TRandom3.h> #include <TFitter.h> #include <TF1.h> #include <TStyle.h> #include <TVector.h> #include <TGraph.h> #include "TUnfoldDensity.h" using namespace std; TRandom *rnd=0; Int_t GenerateGenEvent(Int_t nmax,const Double_t *probability) { // choose an integer random number in the range [0,nmax] // (the generator level bin) // depending on the probabilities // probability[0],probability[1],...probability[nmax-1] Double_t f=rnd->Rndm(); Int_t r=0; while((r<nmax)&&(f>=probability[r])) { f -= probability[r]; r++; } return r; } Double_t GenerateRecEvent(const Double_t *shapeParm) { // return a coordinate (the reconstructed variable) // depending on shapeParm[] // shapeParm[0]: fraction of events with Gaussian distribution // shapeParm[1]: mean of Gaussian // shapeParm[2]: width of Gaussian // (1-shapeParm[0]): fraction of events with flat distribution // shapeParm[3]: minimum of flat component // shapeParm[4]: maximum of flat component Double_t f=rnd->Rndm(); Double_t r; if(f<shapeParm[0]) { r=rnd->Gaus(shapeParm[1],shapeParm[2]); } else { r=rnd->Rndm()*(shapeParm[4]-shapeParm[3])+shapeParm[3]; } return r; } void testUnfold4() { // switch on histogram errors TH1::SetDefaultSumw2(); // random generator rnd=new TRandom3(); // data and MC number of events Double_t const nData0= 500.0; Double_t const nMC0 = 50000.0; // Binning // reconstructed variable (0-10) Int_t const nDet=15; Double_t const xminDet=0.0; Double_t const xmaxDet=15.0; // signal binning (three shapes: 0,1,2) Int_t const nGen=3; Double_t const xminGen=-0.5; Double_t const xmaxGen= 2.5; // parameters // fraction of events per signal shape static const Double_t genFrac[]={0.3,0.6,0.1}; // signal shapes static const Double_t genShape[][5]= {{1.0,2.0,1.5,0.,15.}, {1.0,7.0,2.5,0.,15.}, {0.0,0.0,0.0,0.,15.}}; // define DATA histograms // observed data distribution TH1D *histDetDATA=new TH1D("Yrec",";DATA(Yrec)",nDet,xminDet,xmaxDet); // define MC histograms // matrix of migrations TH2D *histGenDetMC=new TH2D("Yrec%Xgen","MC(Xgen,Yrec)", nGen,xminGen,xmaxGen,nDet,xminDet,xmaxDet); TH1D *histUnfold=new TH1D("Xgen",";DATA(Xgen)",nGen,xminGen,xmaxGen); TH1D **histPullNC=new TH1D* [nGen]; TH1D **histPullArea=new TH1D* [nGen]; for(int i=0;i<nGen;i++) { histPullNC[i]=new TH1D(TString::Format("PullNC%d",i),"pull",15,-3.,3.); histPullArea[i]=new TH1D(TString::Format("PullArea%d",i),"pull",15,-3.,3.); } // this method is new in version 16 of TUnfold cout<<"TUnfold version is "<<TUnfold::GetTUnfoldVersion()<<"\n"; for(int itoy=0;itoy<1000;itoy++) { if(!(itoy %10)) cout<<"toy iteration: "<<itoy<<"\n"; histDetDATA->Reset(); histGenDetMC->Reset(); Int_t nData=rnd->Poisson(nData0); for(Int_t i=0;i<nData;i++) { Int_t iGen=GenerateGenEvent(nGen,genFrac); Double_t yObs=GenerateRecEvent(genShape[iGen]); histDetDATA->Fill(yObs); } Int_t nMC=rnd->Poisson(nMC0); for(Int_t i=0;i<nMC;i++) { Int_t iGen=GenerateGenEvent(nGen,genFrac); Double_t yObs=GenerateRecEvent(genShape[iGen]); histGenDetMC->Fill(iGen,yObs); } /* for(Int_t ix=0;ix<=histGenDetMC->GetNbinsX()+1;ix++) { for(Int_t iy=0;iy<=histGenDetMC->GetNbinsY()+1;iy++) { cout<<ix<<iy<<" : "<<histGenDetMC->GetBinContent(ix,iy)<<"\n"; } } */ //======================== // unfolding TUnfoldSys unfold(histGenDetMC,TUnfold::kHistMapOutputHoriz, TUnfold::kRegModeSize,TUnfold::kEConstraintNone); // define the input vector (the measured data distribution) unfold.SetInput(histDetDATA,0.0,1.0); // run the unfolding unfold.ScanLcurve(50,0.,0.,0,0,0); // fill pull distributions without constraint unfold.GetOutput(histUnfold); for(int i=0;i<nGen;i++) { histPullNC[i]->Fill((histUnfold->GetBinContent(i+1)-genFrac[i]*nData0)/ histUnfold->GetBinError(i+1)); } // repeat unfolding on the same data, now with Area constraint unfold.SetConstraint(TUnfold::kEConstraintArea); // run the unfolding unfold.ScanLcurve(50,0.,0.,0,0,0); // fill pull distributions with constraint unfold.GetOutput(histUnfold); for(int i=0;i<nGen;i++) { histPullArea[i]->Fill((histUnfold->GetBinContent(i+1)-genFrac[i]*nData0)/ histUnfold->GetBinError(i+1)); } } TCanvas output; output.Divide(3,2); gStyle->SetOptFit(1111); for(int i=0;i<nGen;i++) { output.cd(i+1); histPullNC[i]->Fit("gaus"); histPullNC[i]->Draw(); } for(int i=0;i<nGen;i++) { output.cd(i+4); histPullArea[i]->Fit("gaus"); histPullArea[i]->Draw(); } output.SaveAs("testUnfold4.ps"); }
lgpl-2.1
sonamuthu/rice-1
rice-middleware/edl/impl/src/main/java/org/kuali/rice/edl/impl/components/VersioningPreprocessor.java
3648
/** * Copyright 2005-2015 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl2.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.rice.edl.impl.components; import java.util.ArrayList; import java.util.List; import org.kuali.rice.edl.impl.EDLContext; import org.kuali.rice.edl.impl.EDLModelComponent; import org.kuali.rice.edl.impl.EDLXmlUtils; import org.kuali.rice.edl.impl.RequestParser; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * Versions the data element if necessary by checking 'currentVersion' param on request. If this request is * a doc handler request this will configure the dom so the next request will cause the data to be incremented. * * @author Kuali Rice Team (rice.collab@kuali.org) * */ public class VersioningPreprocessor implements EDLModelComponent { private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(VersioningPreprocessor.class); public void updateDOM(Document dom, Element configElement, EDLContext edlContext) { RequestParser requestParser = edlContext.getRequestParser(); boolean incrementVersion = edlContext.getUserAction().isIncrementVersionAction(); boolean replaceVersion = edlContext.getUserAction().isReplaceVersionAction(); Element edlContentElement = EDLXmlUtils.getEDLContent(dom, false); Element dataElement = EDLXmlUtils.getDataFromEDLDocument(edlContentElement, false); Element currentVersion = findCurrentVersion(dom); if (currentVersion == null) { Integer currentVersionCount = new Integer(0); currentVersion = EDLXmlUtils.getVersionFromData(dataElement, currentVersionCount); } else if (incrementVersion) { currentVersion.getAttributeNode("current").setNodeValue("false"); int currentVersionCount = new Integer(currentVersion.getAttribute("version")).intValue() + 1; EDLXmlUtils.getVersionFromData(dataElement, new Integer(currentVersionCount)); } else if (replaceVersion) { NodeList children = currentVersion.getChildNodes(); // important to store these in the last for removal later because we can't safely removeChild in the first for-loop below List<Node> childrenToRemove = new ArrayList<Node>(); for (int index = 0; index < children.getLength(); index++) { childrenToRemove.add(children.item(index)); } for (Node childToRemove : childrenToRemove) { currentVersion.removeChild(childToRemove); } } requestParser.setAttribute("currentVersion", currentVersion.getAttribute("currentVersion")); } public static Element findCurrentVersion(Document dom) { Element edlContentElement = EDLXmlUtils.getEDLContent(dom, false); Element dataElement = EDLXmlUtils.getDataFromEDLDocument(edlContentElement, false); NodeList versionElements = dataElement.getElementsByTagName(EDLXmlUtils.VERSION_E); for (int i = 0; i < versionElements.getLength(); i++) { Element version = (Element) versionElements.item(i); Boolean currentVersion = new Boolean(version.getAttribute("current")); if (currentVersion.booleanValue()) { return version; } } return null; } }
apache-2.0
cmontezano/google-maps-services-java
src/main/java/com/google/maps/internal/ExceptionResult.java
1246
/* * Copyright 2014 Google Inc. All rights reserved. * * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF * ANY KIND, either express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.google.maps.internal; import com.google.maps.PendingResult; /** * This class centralizes failure handling, independent of the calling style. */ public class ExceptionResult<T> implements PendingResult<T> { private final Exception exception; public ExceptionResult(Exception exception) { this.exception = exception; } @Override public void setCallback(Callback<T> callback) { callback.onFailure(exception); } @Override public T await() throws Exception { throw exception; } @Override public T awaitIgnoreError() { return null; } @Override public void cancel() { } }
apache-2.0
ashetty1/kompose
vendor/k8s.io/kubernetes/pkg/kubectl/resource/result.go
9763
/* Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package resource import ( "fmt" "reflect" "github.com/golang/glog" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/meta" "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/apimachinery/registered" "k8s.io/kubernetes/pkg/apis/extensions" "k8s.io/kubernetes/pkg/runtime" utilerrors "k8s.io/kubernetes/pkg/util/errors" "k8s.io/kubernetes/pkg/util/sets" "k8s.io/kubernetes/pkg/watch" ) // ErrMatchFunc can be used to filter errors that may not be true failures. type ErrMatchFunc func(error) bool // Result contains helper methods for dealing with the outcome of a Builder. type Result struct { err error visitor Visitor sources []Visitor singular bool ignoreErrors []utilerrors.Matcher // populated by a call to Infos info []*Info } // IgnoreErrors will filter errors that occur when by visiting the result // (but not errors that occur by creating the result in the first place), // eliminating any that match fns. This is best used in combination with // Builder.ContinueOnError(), where the visitors accumulate errors and return // them after visiting as a slice of errors. If no errors remain after // filtering, the various visitor methods on Result will return nil for // err. func (r *Result) IgnoreErrors(fns ...ErrMatchFunc) *Result { for _, fn := range fns { r.ignoreErrors = append(r.ignoreErrors, utilerrors.Matcher(fn)) } return r } // Err returns one or more errors (via a util.ErrorList) that occurred prior // to visiting the elements in the visitor. To see all errors including those // that occur during visitation, invoke Infos(). func (r *Result) Err() error { return r.err } // Visit implements the Visitor interface on the items described in the Builder. // Note that some visitor sources are not traversable more than once, or may // return different results. If you wish to operate on the same set of resources // multiple times, use the Infos() method. func (r *Result) Visit(fn VisitorFunc) error { if r.err != nil { return r.err } err := r.visitor.Visit(fn) return utilerrors.FilterOut(err, r.ignoreErrors...) } // IntoSingular sets the provided boolean pointer to true if the Builder input // reflected a single item, or multiple. func (r *Result) IntoSingular(b *bool) *Result { *b = r.singular return r } // Infos returns an array of all of the resource infos retrieved via traversal. // Will attempt to traverse the entire set of visitors only once, and will return // a cached list on subsequent calls. func (r *Result) Infos() ([]*Info, error) { if r.err != nil { return nil, r.err } if r.info != nil { return r.info, nil } infos := []*Info{} err := r.visitor.Visit(func(info *Info, err error) error { if err != nil { return err } infos = append(infos, info) return nil }) err = utilerrors.FilterOut(err, r.ignoreErrors...) r.info, r.err = infos, err return infos, err } // Object returns a single object representing the output of a single visit to all // found resources. If the Builder was a singular context (expected to return a // single resource by user input) and only a single resource was found, the resource // will be returned as is. Otherwise, the returned resources will be part of an // api.List. The ResourceVersion of the api.List will be set only if it is identical // across all infos returned. func (r *Result) Object() (runtime.Object, error) { infos, err := r.Infos() if err != nil { return nil, err } versions := sets.String{} objects := []runtime.Object{} for _, info := range infos { if info.Object != nil { objects = append(objects, info.Object) versions.Insert(info.ResourceVersion) } } if len(objects) == 1 { if r.singular { return objects[0], nil } // if the item is a list already, don't create another list if meta.IsListType(objects[0]) { return objects[0], nil } } version := "" if len(versions) == 1 { version = versions.List()[0] } return &api.List{ ListMeta: unversioned.ListMeta{ ResourceVersion: version, }, Items: objects, }, err } // ResourceMapping returns a single meta.RESTMapping representing the // resources located by the builder, or an error if more than one // mapping was found. func (r *Result) ResourceMapping() (*meta.RESTMapping, error) { if r.err != nil { return nil, r.err } mappings := map[string]*meta.RESTMapping{} for i := range r.sources { m, ok := r.sources[i].(ResourceMapping) if !ok { return nil, fmt.Errorf("a resource mapping could not be loaded from %v", reflect.TypeOf(r.sources[i])) } mapping := m.ResourceMapping() mappings[mapping.Resource] = mapping } if len(mappings) != 1 { return nil, fmt.Errorf("expected only a single resource type") } for _, mapping := range mappings { return mapping, nil } return nil, nil } // Watch retrieves changes that occur on the server to the specified resource. // It currently supports watching a single source - if the resource source // (selectors or pure types) can be watched, they will be, otherwise the list // will be visited (equivalent to the Infos() call) and if there is a single // resource present, it will be watched, otherwise an error will be returned. func (r *Result) Watch(resourceVersion string) (watch.Interface, error) { if r.err != nil { return nil, r.err } if len(r.sources) != 1 { return nil, fmt.Errorf("you may only watch a single resource or type of resource at a time") } w, ok := r.sources[0].(Watchable) if !ok { info, err := r.Infos() if err != nil { return nil, err } if len(info) != 1 { return nil, fmt.Errorf("watch is only supported on individual resources and resource collections - %d resources were found", len(info)) } return info[0].Watch(resourceVersion) } return w.Watch(resourceVersion) } // AsVersionedObject converts a list of infos into a single object - either a List containing // the objects as children, or if only a single Object is present, as that object. The provided // version will be preferred as the conversion target, but the Object's mapping version will be // used if that version is not present. func AsVersionedObject(infos []*Info, forceList bool, version unversioned.GroupVersion, encoder runtime.Encoder) (runtime.Object, error) { objects, err := AsVersionedObjects(infos, version, encoder) if err != nil { return nil, err } var object runtime.Object if len(objects) == 1 && !forceList { object = objects[0] } else { object = &api.List{Items: objects} converted, err := TryConvert(api.Scheme, object, version, registered.GroupOrDie(api.GroupName).GroupVersion) if err != nil { return nil, err } object = converted } // validSpecifiedVersion resolves to true if the version passed to this function matches the // version assigned to the converted object actualVersion := object.GetObjectKind().GroupVersionKind() if actualVersion.Version != version.Version { defaultVersionInfo := "" if len(actualVersion.Version) > 0 { defaultVersionInfo = fmt.Sprintf("Defaulting to %q", actualVersion.Version) } glog.V(1).Infof(" info: the output version specified is invalid. %s\n", defaultVersionInfo) } return object, nil } // AsVersionedObjects converts a list of infos into versioned objects. The provided // version will be preferred as the conversion target, but the Object's mapping version will be // used if that version is not present. func AsVersionedObjects(infos []*Info, version unversioned.GroupVersion, encoder runtime.Encoder) ([]runtime.Object, error) { objects := []runtime.Object{} for _, info := range infos { if info.Object == nil { continue } // TODO: use info.VersionedObject as the value? switch obj := info.Object.(type) { case *extensions.ThirdPartyResourceData: objects = append(objects, &runtime.Unknown{Raw: obj.Data}) continue } // objects that are not part of api.Scheme must be converted to JSON // TODO: convert to map[string]interface{}, attach to runtime.Unknown? if !version.Empty() { if _, _, err := api.Scheme.ObjectKinds(info.Object); runtime.IsNotRegisteredError(err) { // TODO: ideally this would encode to version, but we don't expose multiple codecs here. data, err := runtime.Encode(encoder, info.Object) if err != nil { return nil, err } // TODO: Set ContentEncoding and ContentType. objects = append(objects, &runtime.Unknown{Raw: data}) continue } } converted, err := TryConvert(info.Mapping.ObjectConvertor, info.Object, version, info.Mapping.GroupVersionKind.GroupVersion()) if err != nil { return nil, err } objects = append(objects, converted) } return objects, nil } // TryConvert attempts to convert the given object to the provided versions in order. This function assumes // the object is in internal version. func TryConvert(converter runtime.ObjectConvertor, object runtime.Object, versions ...unversioned.GroupVersion) (runtime.Object, error) { var last error for _, version := range versions { if version.Empty() { return object, nil } obj, err := converter.ConvertToVersion(object, version) if err != nil { last = err continue } return obj, nil } return nil, last }
apache-2.0
topicusonderwijs/wicket
wicket-core/src/test/java/org/apache/wicket/markup/resolver/SimplePage_5.java
1145
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.wicket.markup.resolver; import org.apache.wicket.markup.html.WebPage; /** * Mock page for testing. * * @author Chris Turner */ public class SimplePage_5 extends WebPage { private static final long serialVersionUID = 1L; /** * Construct. */ public SimplePage_5() { } }
apache-2.0
nmoghadam/jbpm
jbpm-case-mgmt/src/test/java/org/jbpm/casemgmt/CaseMgmtDescriptionTest.java
1158
package org.jbpm.casemgmt; import java.util.HashMap; import java.util.Map; import org.jbpm.casemgmt.role.Role; import org.jbpm.test.JbpmJUnitBaseTestCase; import org.junit.Test; import org.kie.api.runtime.manager.RuntimeEngine; import org.kie.api.runtime.process.ProcessInstance; public class CaseMgmtDescriptionTest extends JbpmJUnitBaseTestCase { public CaseMgmtDescriptionTest() { super(true, true); } @Test public void testDescription() { createRuntimeManager("CaseUserTask.bpmn2"); RuntimeEngine runtimeEngine = getRuntimeEngine(); CaseMgmtService caseMgmtService = new CaseMgmtUtil(runtimeEngine); Map<String, Object> params = new HashMap<String, Object>(); params.put("s", "'My example case'"); ProcessInstance processInstance = runtimeEngine.getKieSession().startProcess("CaseUserTask", params); String description = caseMgmtService.getProcessInstanceDescription(processInstance.getId()); System.out.println("Process instance description: " + description); assertEquals("Case 'My example case'", description); } }
apache-2.0
Intellifora/graphbuilder
src/com/intel/hadoop/graphbuilder/partition/mapreduce/edge/EdgeIngressMR.java
10238
/* Copyright (C) 2012 Intel Corporation. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more about this software visit: * http://www.01.org/GraphBuilder */ package com.intel.hadoop.graphbuilder.partition.mapreduce.edge; import java.io.IOException; import org.apache.commons.lang.StringUtils; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.compress.GzipCodec; import org.apache.hadoop.mapred.FileInputFormat; import org.apache.hadoop.mapred.FileOutputFormat; import org.apache.hadoop.mapred.JobClient; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.TextInputFormat; import org.apache.hadoop.mapred.TextOutputFormat; import org.apache.log4j.Logger; import com.intel.hadoop.graphbuilder.graph.GraphOutput; import com.intel.hadoop.graphbuilder.graph.simplegraph.SimpleGraphOutput; import com.intel.hadoop.graphbuilder.parser.FieldParser; import com.intel.hadoop.graphbuilder.parser.GraphParser; import com.intel.hadoop.graphbuilder.partition.mapreduce.keyvalue.IngressKeyType; import com.intel.hadoop.graphbuilder.partition.mapreduce.keyvalue.IngressValueType; /** * The MapRedue class takes from input directory a list of edges and vertices, * and output 2 parts: partitioned graphs and a list of distributed vertex * records. * <p> * Input directory: Can take multiple input directories containing list of * edges. Output directory structure: * <ul> * <li>$outputdir/partition{$i}/subpart{$j}/edata for edge data.</li> * <li>Metafile: $outputdir/partition{$i}/subpart{$j} for meta info.</li> * <li>Graph structure: $outputdir/partition{$i}/subpart{$j}/edgelist for * adjacency structure.</li> * <li>VertexRecords: $outputdir/vrecord list of vertex records.</li> * </ul> * </p> * */ public class EdgeIngressMR { private static final Logger LOG = Logger.getLogger(EdgeIngressMR.class); /** MapReduce Job Counters. */ public static enum COUNTER { NUM_VERTICES, NUM_EDGES }; /** * Default constructor, initialize with parsers. * * @param graphparser * @param vidparser * @param vdataparser * @param edataparser */ public EdgeIngressMR(Class graphparser, Class vidparser, Class vdataparser, Class edataparser) { gzip = false; jobName = "Ingress Mapreduce Driver"; setParser(graphparser, vidparser, vdataparser, edataparser); conf = new JobConf(EdgeIngressMR.class); } /** * Set the parser class. * * @param parser */ public void setParser(Class graphparser, Class vidparser, Class vdataparser, Class edataparser) { try { this.graphparser = (GraphParser) graphparser.newInstance(); this.vidparser = (FieldParser) vidparser.newInstance(); this.vdataparser = (FieldParser) vdataparser.newInstance(); this.edataparser = (FieldParser) edataparser.newInstance(); } catch (InstantiationException e) { e.printStackTrace(); LOG.fatal("Parser classes: \n" + graphparser + "\n" + vidparser + "\n" + vdataparser + "\n" + edataparser + " do not exist."); } catch (IllegalAccessException e) { e.printStackTrace(); LOG.fatal("Parser classes: \n" + graphparser + "\n" + vidparser + "\n" + vdataparser + "\n" + edataparser + " do not exist."); } } /** * Set the job name. * * @param name */ public void setJobName(String name) { this.jobName = name; } /** * Set option for using gzip compression in output. * * @param gzip */ public void useGzip(boolean gzip) { this.gzip = gzip; } /** * Set the ingress strategy {random, oblivious}. * * @see {ObliviousIngress} * @see {RandomIngress} * @param ingress */ public void setIngress(String ingress) { if (ingress.equals("random") || ingress.equals("greedy")) this.ingress = ingress; else { LOG.error("Unknown ingress method: " + ingress + "\n Supported ingress methods: oblivious, random"); LOG.error("Use the default oblivious ingress"); this.ingress = "greedy"; } } /** * Set the intermediate key value class. * * @param keyClass * @param valClass */ public void setKeyValueClass(Class keyClass, Class valClass) { try { this.mapkeytype = (IngressKeyType) keyClass.newInstance(); this.mapvaltype = (IngressValueType) valClass.newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } /** * @return JobConf of the current job. */ public JobConf getConf() { return conf; } /** * @param inputpath * @param outputpath * @param numProcs * @param ingress * @throws IOException */ public void run(String[] inputpaths, String outputpath, int numProcs, String ingress) throws IOException { this.setIngress(ingress); conf.setJobName(jobName); if (this.subpartPerPartition <= 0) this.subpartPerPartition = 8; LOG.info("===== Job: Partition edges and create vertex records ========="); LOG.info("input: " + StringUtils.join(inputpaths, ",")); LOG.info("output: " + outputpath); LOG.info("numProc = " + numProcs); LOG.info("subpartPerPartition = " + subpartPerPartition); LOG.info("keyclass = " + this.mapkeytype.getClass().getName()); LOG.info("valclass = " + this.mapvaltype.getClass().getName()); LOG.debug("graphparser = " + this.graphparser.getClass().getName()); LOG.debug("vidparser = " + this.vidparser.getClass().getName()); LOG.debug("vdataparser = " + this.vdataparser.getClass().getName()); LOG.debug("edataparser = " + this.edataparser.getClass().getName()); LOG.info("ingress = " + this.ingress); LOG.info("gzip = " + Boolean.toString(gzip)); LOG.info("==============================================================="); conf.set("ingress", this.ingress); conf.setInt("numProcs", numProcs); conf.set("GraphParser", graphparser.getClass().getName()); conf.set("VidParser", vidparser.getClass().getName()); conf.set("VdataParser", vdataparser.getClass().getName()); conf.set("EdataParser", edataparser.getClass().getName()); conf.setInt("subpartPerPartition", subpartPerPartition); conf.setMapOutputKeyClass(this.mapkeytype.getClass()); conf.setMapOutputValueClass(this.mapvaltype.getClass()); conf.setOutputKeyClass(IntWritable.class); conf.setOutputValueClass(Text.class); conf.setMapperClass(EdgeIngressMapper.class); conf.setCombinerClass(EdgeIngressCombiner.class); conf.setReducerClass(EdgeIngressReducer.class); // GraphOutput output = new GLGraphOutput(numProcs); GraphOutput output = new SimpleGraphOutput(); output.init(conf); conf.setInputFormat(TextInputFormat.class); // conf.setOutputFormat(PartitionedGraphOutputFormat.class); if (gzip) { TextOutputFormat.setCompressOutput(conf, true); TextOutputFormat.setOutputCompressorClass(conf, GzipCodec.class); } for (String path : inputpaths) FileInputFormat.addInputPath(conf, new Path(path)); FileOutputFormat.setOutputPath(conf, new Path(outputpath)); if (!checkTypes()) { LOG.fatal("Type check failed." + "Please check the parsers are consistent with key/val types."); return; } JobClient.runJob(conf); LOG.info("================== Done ====================================\n"); } /** * Ensure the keytype, valuetype are consistent with the parser type. * @return true if type check. */ private boolean checkTypes() { boolean check = true; if (!(mapkeytype.createVid().getClass()).equals(mapvaltype .getGraphTypeFactory().createVid().getClass())) { LOG.fatal("VidType is not consistant between MapKeyType: " + mapkeytype.createVid().getClass().getName() + " and MapValueType: " + mapvaltype.getGraphTypeFactory().createVid().getClass().getName()); check = false; } if (!(vidparser.getType()).equals(mapkeytype.createVid().getClass())) { LOG.fatal("VidType is not consistant between MapKeyType: " + mapkeytype.createVid().getClass().getName() + " and Parser: " + vidparser.getType().getName()); check = false; } if (!(vdataparser.getType().equals(mapvaltype.getGraphTypeFactory() .createVdata().getClass()))) { LOG.fatal("VertexDataType is not consistant between MapValueType: " + mapvaltype.getGraphTypeFactory().createVdata().getClass().getName() + " and Parser: " + vdataparser.getType().getName()); check = false; } if (!(edataparser.getType().equals(mapvaltype.getGraphTypeFactory() .createEdata().getClass()))) { LOG.fatal("EdgeDataType is not consistant between MapValueType: " + mapvaltype.getGraphTypeFactory().createEdata().getClass().getName() + " and Parser: " + edataparser.getType().getName()); check = false; } return check; } /** * Set the number of subpartitions per real partition. * @param n number of subpartitions per real partition. */ public void setTotalSubPartition(int n) { this.subpartPerPartition = n; } private JobConf conf; private GraphParser graphparser; private FieldParser vidparser; private FieldParser vdataparser; private FieldParser edataparser; private boolean gzip; private String jobName; private String ingress; private int subpartPerPartition; private IngressKeyType mapkeytype; private IngressValueType mapvaltype; }
apache-2.0
vmuzikar/keycloak
adapters/oidc/spring-security/src/main/java/org/keycloak/adapters/springsecurity/authentication/KeycloakLogoutHandler.java
3636
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.keycloak.adapters.springsecurity.authentication; import org.keycloak.adapters.AdapterDeploymentContext; import org.keycloak.adapters.KeycloakDeployment; import org.keycloak.adapters.RefreshableKeycloakSecurityContext; import org.keycloak.adapters.spi.HttpFacade; import org.keycloak.adapters.springsecurity.facade.SimpleHttpFacade; import org.keycloak.adapters.springsecurity.token.AdapterTokenStoreFactory; import org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken; import org.keycloak.adapters.springsecurity.token.SpringSecurityAdapterTokenStoreFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.logout.LogoutHandler; import org.springframework.util.Assert; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Logs the current user out of Keycloak. * * @author <a href="mailto:srossillo@smartling.com">Scott Rossillo</a> * @version $Revision: 1 $ */ public class KeycloakLogoutHandler implements LogoutHandler { private static final Logger log = LoggerFactory.getLogger(KeycloakLogoutHandler.class); private AdapterDeploymentContext adapterDeploymentContext; private AdapterTokenStoreFactory adapterTokenStoreFactory = new SpringSecurityAdapterTokenStoreFactory(); public KeycloakLogoutHandler(AdapterDeploymentContext adapterDeploymentContext) { Assert.notNull(adapterDeploymentContext); this.adapterDeploymentContext = adapterDeploymentContext; } public void setAdapterTokenStoreFactory(AdapterTokenStoreFactory adapterTokenStoreFactory) { this.adapterTokenStoreFactory = adapterTokenStoreFactory; } @Override public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { if (authentication == null) { log.warn("Cannot log out without authentication"); return; } else if (!KeycloakAuthenticationToken.class.isAssignableFrom(authentication.getClass())) { log.warn("Cannot log out a non-Keycloak authentication: {}", authentication); return; } handleSingleSignOut(request, response, (KeycloakAuthenticationToken) authentication); } protected void handleSingleSignOut(HttpServletRequest request, HttpServletResponse response, KeycloakAuthenticationToken authenticationToken) { HttpFacade facade = new SimpleHttpFacade(request, response); KeycloakDeployment deployment = adapterDeploymentContext.resolveDeployment(facade); adapterTokenStoreFactory.createAdapterTokenStore(deployment, request, response).logout(); RefreshableKeycloakSecurityContext session = (RefreshableKeycloakSecurityContext) authenticationToken.getAccount().getKeycloakSecurityContext(); session.logout(deployment); } }
apache-2.0
ptkool/spark
launcher/src/test/java/org/apache/spark/launcher/SparkSubmitCommandBuilderSuite.java
15818
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.launcher; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import static org.junit.Assert.*; public class SparkSubmitCommandBuilderSuite extends BaseSuite { private static File dummyPropsFile; private static SparkSubmitOptionParser parser; @Rule public ExpectedException expectedException = ExpectedException.none(); @BeforeClass public static void setUp() throws Exception { dummyPropsFile = File.createTempFile("spark", "properties"); parser = new SparkSubmitOptionParser(); } @AfterClass public static void cleanUp() throws Exception { dummyPropsFile.delete(); } @Test public void testDriverCmdBuilder() throws Exception { testCmdBuilder(true, true); testCmdBuilder(true, false); } @Test public void testClusterCmdBuilder() throws Exception { testCmdBuilder(false, true); testCmdBuilder(false, false); } @Test public void testCliHelpAndNoArg() throws Exception { List<String> helpArgs = Arrays.asList(parser.HELP); Map<String, String> env = new HashMap<>(); List<String> cmd = buildCommand(helpArgs, env); assertTrue("--help should be contained in the final cmd.", cmd.contains(parser.HELP)); List<String> sparkEmptyArgs = Collections.emptyList(); cmd = buildCommand(sparkEmptyArgs, env); assertTrue( "org.apache.spark.deploy.SparkSubmit should be contained in the final cmd of empty input.", cmd.contains("org.apache.spark.deploy.SparkSubmit")); } @Test public void testCliKillAndStatus() throws Exception { List<String> params = Arrays.asList("driver-20160531171222-0000"); testCLIOpts(null, parser.STATUS, params); testCLIOpts(null, parser.KILL_SUBMISSION, params); testCLIOpts(SparkSubmitCommandBuilder.RUN_EXAMPLE, parser.STATUS, params); testCLIOpts(SparkSubmitCommandBuilder.RUN_EXAMPLE, parser.KILL_SUBMISSION, params); } @Test public void testCliParser() throws Exception { List<String> sparkSubmitArgs = Arrays.asList( parser.MASTER, "local", parser.DRIVER_MEMORY, "42g", parser.DRIVER_CLASS_PATH, "/driverCp", parser.DRIVER_JAVA_OPTIONS, "extraJavaOpt", parser.CONF, "spark.randomOption=foo", parser.CONF, SparkLauncher.DRIVER_EXTRA_LIBRARY_PATH + "=/driverLibPath", SparkLauncher.NO_RESOURCE); Map<String, String> env = new HashMap<>(); List<String> cmd = buildCommand(sparkSubmitArgs, env); assertTrue(findInStringList(env.get(CommandBuilderUtils.getLibPathEnvName()), File.pathSeparator, "/driverLibPath")); assertTrue(findInStringList(findArgValue(cmd, "-cp"), File.pathSeparator, "/driverCp")); assertTrue("Driver -Xmx should be configured.", cmd.contains("-Xmx42g")); assertTrue("Command should contain user-defined conf.", Collections.indexOfSubList(cmd, Arrays.asList(parser.CONF, "spark.randomOption=foo")) > 0); } @Test public void testShellCliParser() throws Exception { List<String> sparkSubmitArgs = Arrays.asList( parser.CLASS, "org.apache.spark.repl.Main", parser.MASTER, "foo", "--app-arg", "bar", "--app-switch", parser.FILES, "baz", parser.NAME, "appName"); List<String> args = newCommandBuilder(sparkSubmitArgs).buildSparkSubmitArgs(); List<String> expected = Arrays.asList("spark-shell", "--app-arg", "bar", "--app-switch"); assertEquals(expected, args.subList(args.size() - expected.size(), args.size())); } @Test public void testAlternateSyntaxParsing() throws Exception { List<String> sparkSubmitArgs = Arrays.asList( parser.CLASS + "=org.my.Class", parser.MASTER + "=foo", parser.DEPLOY_MODE + "=bar", SparkLauncher.NO_RESOURCE); List<String> cmd = newCommandBuilder(sparkSubmitArgs).buildSparkSubmitArgs(); assertEquals("org.my.Class", findArgValue(cmd, parser.CLASS)); assertEquals("foo", findArgValue(cmd, parser.MASTER)); assertEquals("bar", findArgValue(cmd, parser.DEPLOY_MODE)); } @Test public void testPySparkLauncher() throws Exception { List<String> sparkSubmitArgs = Arrays.asList( SparkSubmitCommandBuilder.PYSPARK_SHELL, "--master=foo", "--deploy-mode=bar"); Map<String, String> env = new HashMap<>(); List<String> cmd = buildCommand(sparkSubmitArgs, env); assertTrue(Arrays.asList("python", "python2", "python3").contains(cmd.get(cmd.size() - 1))); assertEquals( String.format("\"%s\" \"foo\" \"%s\" \"bar\" \"%s\"", parser.MASTER, parser.DEPLOY_MODE, SparkSubmitCommandBuilder.PYSPARK_SHELL_RESOURCE), env.get("PYSPARK_SUBMIT_ARGS")); } @Test public void testPySparkFallback() throws Exception { List<String> sparkSubmitArgs = Arrays.asList( "--master=foo", "--deploy-mode=bar", "script.py", "arg1"); Map<String, String> env = new HashMap<>(); List<String> cmd = buildCommand(sparkSubmitArgs, env); assertEquals("foo", findArgValue(cmd, "--master")); assertEquals("bar", findArgValue(cmd, "--deploy-mode")); assertEquals("script.py", cmd.get(cmd.size() - 2)); assertEquals("arg1", cmd.get(cmd.size() - 1)); } @Test public void testSparkRShell() throws Exception { List<String> sparkSubmitArgs = Arrays.asList( SparkSubmitCommandBuilder.SPARKR_SHELL, "--master=foo", "--deploy-mode=bar", "--conf", "spark.r.shell.command=/usr/bin/R"); Map<String, String> env = new HashMap<>(); List<String> cmd = buildCommand(sparkSubmitArgs, env); assertEquals("/usr/bin/R", cmd.get(cmd.size() - 1)); assertEquals( String.format( "\"%s\" \"foo\" \"%s\" \"bar\" \"--conf\" \"spark.r.shell.command=/usr/bin/R\" \"%s\"", parser.MASTER, parser.DEPLOY_MODE, SparkSubmitCommandBuilder.SPARKR_SHELL_RESOURCE), env.get("SPARKR_SUBMIT_ARGS")); } @Test(expected = IllegalArgumentException.class) public void testExamplesRunnerNoArg() throws Exception { List<String> sparkSubmitArgs = Arrays.asList(SparkSubmitCommandBuilder.RUN_EXAMPLE); Map<String, String> env = new HashMap<>(); buildCommand(sparkSubmitArgs, env); } @Test public void testExamplesRunnerNoMainClass() throws Exception { testCLIOpts(SparkSubmitCommandBuilder.RUN_EXAMPLE, parser.HELP, null); testCLIOpts(SparkSubmitCommandBuilder.RUN_EXAMPLE, parser.USAGE_ERROR, null); testCLIOpts(SparkSubmitCommandBuilder.RUN_EXAMPLE, parser.VERSION, null); } @Test public void testExamplesRunnerWithMasterNoMainClass() throws Exception { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("Missing example class name."); List<String> sparkSubmitArgs = Arrays.asList( SparkSubmitCommandBuilder.RUN_EXAMPLE, parser.MASTER + "=foo" ); Map<String, String> env = new HashMap<>(); buildCommand(sparkSubmitArgs, env); } @Test public void testExamplesRunner() throws Exception { List<String> sparkSubmitArgs = Arrays.asList( SparkSubmitCommandBuilder.RUN_EXAMPLE, parser.MASTER + "=foo", parser.DEPLOY_MODE + "=bar", "SparkPi", "42"); Map<String, String> env = new HashMap<>(); List<String> cmd = buildCommand(sparkSubmitArgs, env); assertEquals("foo", findArgValue(cmd, parser.MASTER)); assertEquals("bar", findArgValue(cmd, parser.DEPLOY_MODE)); assertEquals(SparkSubmitCommandBuilder.EXAMPLE_CLASS_PREFIX + "SparkPi", findArgValue(cmd, parser.CLASS)); assertEquals("42", cmd.get(cmd.size() - 1)); } @Test(expected = IllegalArgumentException.class) public void testMissingAppResource() { new SparkSubmitCommandBuilder().buildSparkSubmitArgs(); } @Test public void testIsClientMode() { // Default master is "local[*]" SparkSubmitCommandBuilder builder = newCommandBuilder(Collections.emptyList()); assertTrue("By default application run in local mode", builder.isClientMode(Collections.emptyMap())); // --master yarn or it can be any RM List<String> sparkSubmitArgs = Arrays.asList(parser.MASTER, "yarn"); builder = newCommandBuilder(sparkSubmitArgs); assertTrue("By default deploy mode is client", builder.isClientMode(Collections.emptyMap())); // --master yarn and set spark.submit.deployMode to client Map<String, String> userProps = new HashMap<>(); userProps.put("spark.submit.deployMode", "client"); assertTrue(builder.isClientMode(userProps)); // --master mesos --deploy-mode cluster sparkSubmitArgs = Arrays.asList(parser.MASTER, "mesos", parser.DEPLOY_MODE, "cluster"); builder = newCommandBuilder(sparkSubmitArgs); assertFalse(builder.isClientMode(Collections.emptyMap())); } private void testCmdBuilder(boolean isDriver, boolean useDefaultPropertyFile) throws Exception { final String DRIVER_DEFAULT_PARAM = "-Ddriver-default"; final String DRIVER_EXTRA_PARAM = "-Ddriver-extra"; String deployMode = isDriver ? "client" : "cluster"; SparkSubmitCommandBuilder launcher = newCommandBuilder(Collections.emptyList()); launcher.childEnv.put(CommandBuilderUtils.ENV_SPARK_HOME, System.getProperty("spark.test.home")); launcher.master = "yarn"; launcher.deployMode = deployMode; launcher.appResource = "/foo"; launcher.appName = "MyApp"; launcher.mainClass = "my.Class"; launcher.appArgs.add("foo"); launcher.appArgs.add("bar"); launcher.conf.put("spark.foo", "foo"); // either set the property through "--conf" or through default property file if (!useDefaultPropertyFile) { launcher.setPropertiesFile(dummyPropsFile.getAbsolutePath()); launcher.conf.put(SparkLauncher.DRIVER_MEMORY, "1g"); launcher.conf.put(SparkLauncher.DRIVER_EXTRA_CLASSPATH, "/driver"); launcher.conf.put(SparkLauncher.DRIVER_DEFAULT_JAVA_OPTIONS, DRIVER_DEFAULT_PARAM); launcher.conf.put(SparkLauncher.DRIVER_EXTRA_JAVA_OPTIONS, DRIVER_EXTRA_PARAM); launcher.conf.put(SparkLauncher.DRIVER_EXTRA_LIBRARY_PATH, "/native"); } else { launcher.childEnv.put("SPARK_CONF_DIR", System.getProperty("spark.test.home") + "/launcher/src/test/resources"); } Map<String, String> env = new HashMap<>(); List<String> cmd = launcher.buildCommand(env); // Checks below are different for driver and non-driver mode. if (isDriver) { assertTrue("Driver -Xmx should be configured.", cmd.contains("-Xmx1g")); assertTrue("Driver default options should be configured.", cmd.contains(DRIVER_DEFAULT_PARAM)); assertTrue("Driver extra options should be configured.", cmd.contains(DRIVER_EXTRA_PARAM)); } else { boolean found = false; for (String arg : cmd) { if (arg.startsWith("-Xmx")) { found = true; break; } } assertFalse("Memory arguments should not be set.", found); assertFalse("Driver default options should not be configured.", cmd.contains(DRIVER_DEFAULT_PARAM)); assertFalse("Driver extra options should not be configured.", cmd.contains(DRIVER_EXTRA_PARAM)); } String[] cp = findArgValue(cmd, "-cp").split(Pattern.quote(File.pathSeparator)); if (isDriver) { assertTrue("Driver classpath should contain provided entry.", contains("/driver", cp)); } else { assertFalse("Driver classpath should not be in command.", contains("/driver", cp)); } String libPath = env.get(CommandBuilderUtils.getLibPathEnvName()); if (isDriver) { assertNotNull("Native library path should be set.", libPath); assertTrue("Native library path should contain provided entry.", contains("/native", libPath.split(Pattern.quote(File.pathSeparator)))); } else { assertNull("Native library should not be set.", libPath); } // Checks below are the same for both driver and non-driver mode. if (!useDefaultPropertyFile) { assertEquals(dummyPropsFile.getAbsolutePath(), findArgValue(cmd, parser.PROPERTIES_FILE)); } assertEquals("yarn", findArgValue(cmd, parser.MASTER)); assertEquals(deployMode, findArgValue(cmd, parser.DEPLOY_MODE)); assertEquals("my.Class", findArgValue(cmd, parser.CLASS)); assertEquals("MyApp", findArgValue(cmd, parser.NAME)); boolean appArgsOk = false; for (int i = 0; i < cmd.size(); i++) { if (cmd.get(i).equals("/foo")) { assertEquals("foo", cmd.get(i + 1)); assertEquals("bar", cmd.get(i + 2)); assertEquals(cmd.size(), i + 3); appArgsOk = true; break; } } assertTrue("App resource and args should be added to command.", appArgsOk); Map<String, String> conf = parseConf(cmd, parser); assertEquals("foo", conf.get("spark.foo")); } private boolean contains(String needle, String[] haystack) { for (String entry : haystack) { if (entry.equals(needle)) { return true; } } return false; } private Map<String, String> parseConf(List<String> cmd, SparkSubmitOptionParser parser) { Map<String, String> conf = new HashMap<>(); for (int i = 0; i < cmd.size(); i++) { if (cmd.get(i).equals(parser.CONF)) { String[] val = cmd.get(i + 1).split("=", 2); conf.put(val[0], val[1]); i += 1; } } return conf; } private String findArgValue(List<String> cmd, String name) { for (int i = 0; i < cmd.size(); i++) { if (cmd.get(i).equals(name)) { return cmd.get(i + 1); } } fail(String.format("arg '%s' not found", name)); return null; } private boolean findInStringList(String list, String sep, String needle) { return contains(needle, list.split(sep)); } private SparkSubmitCommandBuilder newCommandBuilder(List<String> args) { SparkSubmitCommandBuilder builder = new SparkSubmitCommandBuilder(args); builder.childEnv.put(CommandBuilderUtils.ENV_SPARK_HOME, System.getProperty("spark.test.home")); return builder; } private List<String> buildCommand(List<String> args, Map<String, String> env) throws Exception { return newCommandBuilder(args).buildCommand(env); } private void testCLIOpts(String appResource, String opt, List<String> params) throws Exception { List<String> args = new ArrayList<>(); if (appResource != null) { args.add(appResource); } args.add(opt); if (params != null) { args.addAll(params); } Map<String, String> env = new HashMap<>(); List<String> cmd = buildCommand(args, env); assertTrue(opt + " should be contained in the final cmd.", cmd.contains(opt)); } }
apache-2.0
jonathands/closure-templates
java/src/com/google/template/soy/jssrc/restricted/JsExpr.java
2632
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.template.soy.jssrc.restricted; import com.google.common.base.Objects; /** * Value class to represent a JS expression. Includes the text of the expression as well as the * precedence of the top-most operator. * * <p> Important: This class may only be used in implementing plugins (e.g. functions, directives). * * <p> Note that even though the precedence numbers we use are for Soy (see * {@link com.google.template.soy.exprtree.Operator#getPrecedence}), the precedence ordering of * the Soy expression operators matches that of JS (as well as Java), so the precedence numbers are * correct when used for generating JS code as well. * * @author Kai Huang */ public class JsExpr { /** The JS expression text. */ private final String text; /** The precedence of the top-most operator, or Integer.MAX_VALUE. */ private final int precedence; /** * @param text The JS expression text. * @param precedence The precedence of the top-most operator. Or Integer.MAX_VALUE. */ public JsExpr(String text, int precedence) { this.text = text; this.precedence = precedence; } /** Returns the JS expression text. */ public String getText() { return text; } /** Returns the precedence of the top-most operator, or Integer.MAX_VALUE. */ public int getPrecedence() { return precedence; } @Override public String toString() { return Objects.toStringHelper(this).add("text", text).add("precedence", precedence).toString(); } @Override public boolean equals(Object other) { if (other == null || this.getClass() != other.getClass()) { return false; } JsExpr otherCast = (JsExpr) other; if (this.text.equals(otherCast.text)) { if (this.precedence != otherCast.precedence) { throw new AssertionError(); // if text is equal, precedence should also be equal } return true; } else { return false; } } @Override public int hashCode() { return Objects.hashCode(text, precedence); } }
apache-2.0
graydon/rust
src/test/rustdoc/primitive/primitive-generic-impl.rs
68
#[doc(primitive = "i32")] /// Some useless docs, wouhou! mod i32 {}
apache-2.0
fengshao0907/gdata-java-client
java/src/com/google/gdata/data/docs/ChangelogFeed.java
2607
/* Copyright (c) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gdata.data.docs; import com.google.gdata.data.BaseFeed; import com.google.gdata.data.ExtensionProfile; import com.google.gdata.data.Kind; /** * Describes a feed for retrieving a list of changed documents. * * */ @Kind.Term(ChangelogEntry.KIND) public class ChangelogFeed extends BaseFeed<ChangelogFeed, ChangelogEntry> { /** * Default mutable constructor. */ public ChangelogFeed() { super(ChangelogEntry.class); getCategories().add(ChangelogEntry.CATEGORY); } /** * Constructs a new instance by doing a shallow copy of data from an existing * {@link BaseFeed} instance. * * @param sourceFeed source feed */ public ChangelogFeed(BaseFeed<?, ?> sourceFeed) { super(ChangelogEntry.class, sourceFeed); } @Override public void declareExtensions(ExtensionProfile extProfile) { if (extProfile.isDeclared(ChangelogFeed.class)) { return; } super.declareExtensions(extProfile); extProfile.declare(ChangelogFeed.class, LargestChangestamp.getDefaultDescription(true, false)); } /** * Returns the largest changestamp. * * @return largest changestamp */ public LargestChangestamp getLargestChangestamp() { return getExtension(LargestChangestamp.class); } /** * Sets the largest changestamp. * * @param largestChangestamp largest changestamp or <code>null</code> to reset */ public void setLargestChangestamp(LargestChangestamp largestChangestamp) { if (largestChangestamp == null) { removeExtension(LargestChangestamp.class); } else { setExtension(largestChangestamp); } } /** * Returns whether it has the largest changestamp. * * @return whether it has the largest changestamp */ public boolean hasLargestChangestamp() { return hasExtension(LargestChangestamp.class); } @Override protected void validate() { } @Override public String toString() { return "{ChangelogFeed " + super.toString() + "}"; } }
apache-2.0
YuanZhewei/docker
integration-cli/docker_api_volumes_test.go
3346
package main import ( "encoding/json" "net/http" "path/filepath" "github.com/docker/docker/api/types" "github.com/docker/docker/pkg/integration/checker" "github.com/go-check/check" ) func (s *DockerSuite) TestVolumesApiList(c *check.C) { prefix := "" if daemonPlatform == "windows" { prefix = "c:" testRequires(c, WindowsDaemonSupportsVolumes) } dockerCmd(c, "run", "-d", "-v", prefix+"/foo", "busybox") status, b, err := sockRequest("GET", "/volumes", nil) c.Assert(err, checker.IsNil) c.Assert(status, checker.Equals, http.StatusOK) var volumes types.VolumesListResponse c.Assert(json.Unmarshal(b, &volumes), checker.IsNil) c.Assert(len(volumes.Volumes), checker.Equals, 1, check.Commentf("\n%v", volumes.Volumes)) } func (s *DockerSuite) TestVolumesApiCreate(c *check.C) { if daemonPlatform == "windows" { testRequires(c, WindowsDaemonSupportsVolumes) } config := types.VolumeCreateRequest{ Name: "test", } status, b, err := sockRequest("POST", "/volumes/create", config) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusCreated, check.Commentf(string(b))) var vol types.Volume err = json.Unmarshal(b, &vol) c.Assert(err, checker.IsNil) c.Assert(filepath.Base(filepath.Dir(vol.Mountpoint)), checker.Equals, config.Name) } func (s *DockerSuite) TestVolumesApiRemove(c *check.C) { prefix := "" if daemonPlatform == "windows" { testRequires(c, WindowsDaemonSupportsVolumes) prefix = "c:" } dockerCmd(c, "run", "-d", "-v", prefix+"/foo", "--name=test", "busybox") status, b, err := sockRequest("GET", "/volumes", nil) c.Assert(err, checker.IsNil) c.Assert(status, checker.Equals, http.StatusOK) var volumes types.VolumesListResponse c.Assert(json.Unmarshal(b, &volumes), checker.IsNil) c.Assert(len(volumes.Volumes), checker.Equals, 1, check.Commentf("\n%v", volumes.Volumes)) v := volumes.Volumes[0] status, _, err = sockRequest("DELETE", "/volumes/"+v.Name, nil) c.Assert(err, checker.IsNil) c.Assert(status, checker.Equals, http.StatusConflict, check.Commentf("Should not be able to remove a volume that is in use")) dockerCmd(c, "rm", "-f", "test") status, data, err := sockRequest("DELETE", "/volumes/"+v.Name, nil) c.Assert(err, checker.IsNil) c.Assert(status, checker.Equals, http.StatusNoContent, check.Commentf(string(data))) } func (s *DockerSuite) TestVolumesApiInspect(c *check.C) { if daemonPlatform == "windows" { testRequires(c, WindowsDaemonSupportsVolumes) } config := types.VolumeCreateRequest{ Name: "test", } status, b, err := sockRequest("POST", "/volumes/create", config) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusCreated, check.Commentf(string(b))) status, b, err = sockRequest("GET", "/volumes", nil) c.Assert(err, checker.IsNil) c.Assert(status, checker.Equals, http.StatusOK, check.Commentf(string(b))) var volumes types.VolumesListResponse c.Assert(json.Unmarshal(b, &volumes), checker.IsNil) c.Assert(len(volumes.Volumes), checker.Equals, 1, check.Commentf("\n%v", volumes.Volumes)) var vol types.Volume status, b, err = sockRequest("GET", "/volumes/"+config.Name, nil) c.Assert(err, checker.IsNil) c.Assert(status, checker.Equals, http.StatusOK, check.Commentf(string(b))) c.Assert(json.Unmarshal(b, &vol), checker.IsNil) c.Assert(vol.Name, checker.Equals, config.Name) }
apache-2.0
kevinleturc/querydsl
querydsl-core/src/test/java/com/querydsl/core/domain/query3/QTCompanyPK.java
1061
package com.querydsl.core.domain.query3; import static com.querydsl.core.types.PathMetadataFactory.forVariable; import javax.annotation.Generated; import com.querydsl.core.domain.CompanyPK; import com.querydsl.core.types.Path; import com.querydsl.core.types.PathMetadata; import com.querydsl.core.types.dsl.BeanPath; import com.querydsl.core.types.dsl.StringPath; /** * QCompanyPK is a Querydsl query type for CompanyPK */ @Generated("com.querydsl.codegen.EmbeddableSerializer") public class QTCompanyPK extends BeanPath<CompanyPK> { private static final long serialVersionUID = 124567939; public static final QTCompanyPK companyPK = new QTCompanyPK("companyPK"); public final StringPath id = createString("id"); public QTCompanyPK(String variable) { super(CompanyPK.class, forVariable(variable)); } public QTCompanyPK(Path<? extends CompanyPK> entity) { super(entity.getType(), entity.getMetadata()); } public QTCompanyPK(PathMetadata metadata) { super(CompanyPK.class, metadata); } }
apache-2.0
lukemarsden/kubernetes
pkg/kubelet/kuberuntime/kuberuntime_gc.go
12439
/* Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package kuberuntime import ( "fmt" "os" "path/filepath" "sort" "time" "github.com/golang/glog" "k8s.io/apimachinery/pkg/types" internalapi "k8s.io/kubernetes/pkg/kubelet/apis/cri" runtimeapi "k8s.io/kubernetes/pkg/kubelet/apis/cri/v1alpha1/runtime" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" ) // containerGC is the manager of garbage collection. type containerGC struct { client internalapi.RuntimeService manager *kubeGenericRuntimeManager podDeletionProvider podDeletionProvider } // NewContainerGC creates a new containerGC. func NewContainerGC(client internalapi.RuntimeService, podDeletionProvider podDeletionProvider, manager *kubeGenericRuntimeManager) *containerGC { return &containerGC{ client: client, manager: manager, podDeletionProvider: podDeletionProvider, } } // containerGCInfo is the internal information kept for containers being considered for GC. type containerGCInfo struct { // The ID of the container. id string // The name of the container. name string // Creation time for the container. createTime time.Time } // sandboxGCInfo is the internal information kept for sandboxes being considered for GC. type sandboxGCInfo struct { // The ID of the sandbox. id string // Creation time for the sandbox. createTime time.Time // If true, the sandbox is ready or still has containers. active bool } // evictUnit is considered for eviction as units of (UID, container name) pair. type evictUnit struct { // UID of the pod. uid types.UID // Name of the container in the pod. name string } type containersByEvictUnit map[evictUnit][]containerGCInfo type sandboxesByPodUID map[types.UID][]sandboxGCInfo // NumContainers returns the number of containers in this map. func (cu containersByEvictUnit) NumContainers() int { num := 0 for key := range cu { num += len(cu[key]) } return num } // NumEvictUnits returns the number of pod in this map. func (cu containersByEvictUnit) NumEvictUnits() int { return len(cu) } // Newest first. type byCreated []containerGCInfo func (a byCreated) Len() int { return len(a) } func (a byCreated) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a byCreated) Less(i, j int) bool { return a[i].createTime.After(a[j].createTime) } // Newest first. type sandboxByCreated []sandboxGCInfo func (a sandboxByCreated) Len() int { return len(a) } func (a sandboxByCreated) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a sandboxByCreated) Less(i, j int) bool { return a[i].createTime.After(a[j].createTime) } // enforceMaxContainersPerEvictUnit enforces MaxPerPodContainer for each evictUnit. func (cgc *containerGC) enforceMaxContainersPerEvictUnit(evictUnits containersByEvictUnit, MaxContainers int) { for key := range evictUnits { toRemove := len(evictUnits[key]) - MaxContainers if toRemove > 0 { evictUnits[key] = cgc.removeOldestN(evictUnits[key], toRemove) } } } // removeOldestN removes the oldest toRemove containers and returns the resulting slice. func (cgc *containerGC) removeOldestN(containers []containerGCInfo, toRemove int) []containerGCInfo { // Remove from oldest to newest (last to first). numToKeep := len(containers) - toRemove for i := len(containers) - 1; i >= numToKeep; i-- { if err := cgc.manager.removeContainer(containers[i].id); err != nil { glog.Errorf("Failed to remove container %q: %v", containers[i].id, err) } } // Assume we removed the containers so that we're not too aggressive. return containers[:numToKeep] } // removeOldestNSandboxes removes the oldest inactive toRemove sandboxes and // returns the resulting slice. func (cgc *containerGC) removeOldestNSandboxes(sandboxes []sandboxGCInfo, toRemove int) { // Remove from oldest to newest (last to first). numToKeep := len(sandboxes) - toRemove for i := len(sandboxes) - 1; i >= numToKeep; i-- { if !sandboxes[i].active { cgc.removeSandbox(sandboxes[i].id) } } } // removeSandbox removes the sandbox by sandboxID. func (cgc *containerGC) removeSandbox(sandboxID string) { glog.V(4).Infof("Removing sandbox %q", sandboxID) // In normal cases, kubelet should've already called StopPodSandbox before // GC kicks in. To guard against the rare cases where this is not true, try // stopping the sandbox before removing it. if err := cgc.client.StopPodSandbox(sandboxID); err != nil { glog.Errorf("Failed to stop sandbox %q before removing: %v", sandboxID, err) return } if err := cgc.client.RemovePodSandbox(sandboxID); err != nil { glog.Errorf("Failed to remove sandbox %q: %v", sandboxID, err) } } // evictableContainers gets all containers that are evictable. Evictable containers are: not running // and created more than MinAge ago. func (cgc *containerGC) evictableContainers(minAge time.Duration) (containersByEvictUnit, error) { containers, err := cgc.manager.getKubeletContainers(true) if err != nil { return containersByEvictUnit{}, err } evictUnits := make(containersByEvictUnit) newestGCTime := time.Now().Add(-minAge) for _, container := range containers { // Prune out running containers. if container.State == runtimeapi.ContainerState_CONTAINER_RUNNING { continue } createdAt := time.Unix(0, container.CreatedAt) if newestGCTime.Before(createdAt) { continue } labeledInfo := getContainerInfoFromLabels(container.Labels) containerInfo := containerGCInfo{ id: container.Id, name: container.Metadata.Name, createTime: createdAt, } key := evictUnit{ uid: labeledInfo.PodUID, name: containerInfo.name, } evictUnits[key] = append(evictUnits[key], containerInfo) } // Sort the containers by age. for uid := range evictUnits { sort.Sort(byCreated(evictUnits[uid])) } return evictUnits, nil } // evict all containers that are evictable func (cgc *containerGC) evictContainers(gcPolicy kubecontainer.ContainerGCPolicy, allSourcesReady bool, evictNonDeletedPods bool) error { // Separate containers by evict units. evictUnits, err := cgc.evictableContainers(gcPolicy.MinAge) if err != nil { return err } // Remove deleted pod containers if all sources are ready. if allSourcesReady { for key, unit := range evictUnits { if cgc.podDeletionProvider.IsPodDeleted(key.uid) || evictNonDeletedPods { cgc.removeOldestN(unit, len(unit)) // Remove all. delete(evictUnits, key) } } } // Enforce max containers per evict unit. if gcPolicy.MaxPerPodContainer >= 0 { cgc.enforceMaxContainersPerEvictUnit(evictUnits, gcPolicy.MaxPerPodContainer) } // Enforce max total number of containers. if gcPolicy.MaxContainers >= 0 && evictUnits.NumContainers() > gcPolicy.MaxContainers { // Leave an equal number of containers per evict unit (min: 1). numContainersPerEvictUnit := gcPolicy.MaxContainers / evictUnits.NumEvictUnits() if numContainersPerEvictUnit < 1 { numContainersPerEvictUnit = 1 } cgc.enforceMaxContainersPerEvictUnit(evictUnits, numContainersPerEvictUnit) // If we still need to evict, evict oldest first. numContainers := evictUnits.NumContainers() if numContainers > gcPolicy.MaxContainers { flattened := make([]containerGCInfo, 0, numContainers) for key := range evictUnits { flattened = append(flattened, evictUnits[key]...) } sort.Sort(byCreated(flattened)) cgc.removeOldestN(flattened, numContainers-gcPolicy.MaxContainers) } } return nil } // evictSandboxes remove all evictable sandboxes. An evictable sandbox must // meet the following requirements: // 1. not in ready state // 2. contains no containers. // 3. belong to a non-existent (i.e., already removed) pod, or is not the // most recently created sandbox for the pod. func (cgc *containerGC) evictSandboxes(evictNonDeletedPods bool) error { containers, err := cgc.manager.getKubeletContainers(true) if err != nil { return err } sandboxes, err := cgc.manager.getKubeletSandboxes(true) if err != nil { return err } sandboxesByPod := make(sandboxesByPodUID) for _, sandbox := range sandboxes { podUID := types.UID(sandbox.Metadata.Uid) sandboxInfo := sandboxGCInfo{ id: sandbox.Id, createTime: time.Unix(0, sandbox.CreatedAt), } // Set ready sandboxes to be active. if sandbox.State == runtimeapi.PodSandboxState_SANDBOX_READY { sandboxInfo.active = true } // Set sandboxes that still have containers to be active. hasContainers := false sandboxID := sandbox.Id for _, container := range containers { if container.PodSandboxId == sandboxID { hasContainers = true break } } if hasContainers { sandboxInfo.active = true } sandboxesByPod[podUID] = append(sandboxesByPod[podUID], sandboxInfo) } // Sort the sandboxes by age. for uid := range sandboxesByPod { sort.Sort(sandboxByCreated(sandboxesByPod[uid])) } for podUID, sandboxes := range sandboxesByPod { if cgc.podDeletionProvider.IsPodDeleted(podUID) || evictNonDeletedPods { // Remove all evictable sandboxes if the pod has been removed. // Note that the latest dead sandbox is also removed if there is // already an active one. cgc.removeOldestNSandboxes(sandboxes, len(sandboxes)) } else { // Keep latest one if the pod still exists. cgc.removeOldestNSandboxes(sandboxes, len(sandboxes)-1) } } return nil } // evictPodLogsDirectories evicts all evictable pod logs directories. Pod logs directories // are evictable if there are no corresponding pods. func (cgc *containerGC) evictPodLogsDirectories(allSourcesReady bool) error { osInterface := cgc.manager.osInterface if allSourcesReady { // Only remove pod logs directories when all sources are ready. dirs, err := osInterface.ReadDir(podLogsRootDirectory) if err != nil { return fmt.Errorf("failed to read podLogsRootDirectory %q: %v", podLogsRootDirectory, err) } for _, dir := range dirs { name := dir.Name() podUID := types.UID(name) if !cgc.podDeletionProvider.IsPodDeleted(podUID) { continue } err := osInterface.RemoveAll(filepath.Join(podLogsRootDirectory, name)) if err != nil { glog.Errorf("Failed to remove pod logs directory %q: %v", name, err) } } } // Remove dead container log symlinks. // TODO(random-liu): Remove this after cluster logging supports CRI container log path. logSymlinks, _ := osInterface.Glob(filepath.Join(legacyContainerLogsDir, fmt.Sprintf("*.%s", legacyLogSuffix))) for _, logSymlink := range logSymlinks { if _, err := osInterface.Stat(logSymlink); os.IsNotExist(err) { err := osInterface.Remove(logSymlink) if err != nil { glog.Errorf("Failed to remove container log dead symlink %q: %v", logSymlink, err) } } } return nil } // GarbageCollect removes dead containers using the specified container gc policy. // Note that gc policy is not applied to sandboxes. Sandboxes are only removed when they are // not ready and containing no containers. // // GarbageCollect consists of the following steps: // * gets evictable containers which are not active and created more than gcPolicy.MinAge ago. // * removes oldest dead containers for each pod by enforcing gcPolicy.MaxPerPodContainer. // * removes oldest dead containers by enforcing gcPolicy.MaxContainers. // * gets evictable sandboxes which are not ready and contains no containers. // * removes evictable sandboxes. func (cgc *containerGC) GarbageCollect(gcPolicy kubecontainer.ContainerGCPolicy, allSourcesReady bool, evictNonDeletedPods bool) error { // Remove evictable containers if err := cgc.evictContainers(gcPolicy, allSourcesReady, evictNonDeletedPods); err != nil { return err } // Remove sandboxes with zero containers if err := cgc.evictSandboxes(evictNonDeletedPods); err != nil { return err } // Remove pod sandbox log directory return cgc.evictPodLogsDirectories(allSourcesReady) }
apache-2.0
sarvex/tensorflow
tensorflow/lite/delegates/gpu/common/transformations/make_fully_connected.cc
2920
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/delegates/gpu/common/transformations/make_fully_connected.h" #include <memory> #include <string> #include <vector> #include "absl/memory/memory.h" #include "absl/types/any.h" #include "tensorflow/lite/delegates/gpu/common/model.h" #include "tensorflow/lite/delegates/gpu/common/model_transformer.h" #include "tensorflow/lite/delegates/gpu/common/operations.h" #include "tensorflow/lite/delegates/gpu/common/shape.h" #include "tensorflow/lite/delegates/gpu/common/tensor.h" namespace tflite { namespace gpu { namespace { bool IsConvEquivalentToFullyConnected(const Convolution2DAttributes& attr) { return attr.weights.shape.w == 1 && // attr.weights.shape.h == 1 && // attr.strides == HW(1, 1) && // attr.dilations == HW(1, 1) && // attr.padding.prepended == HW(0, 0) && // attr.padding.appended == HW(0, 0); } class MakeFullyConnectedFromConvolution : public NodeTransformation { public: TransformResult ApplyToNode(Node* node, GraphFloat32* graph) final { if (node->operation.type != ToString(OperationType::CONVOLUTION_2D)) { return {TransformStatus::SKIPPED, ""}; } auto inputs = graph->FindInputs(node->id); if (inputs.size() != 1) { return {TransformStatus::SKIPPED, ""}; } const auto& input_shape = inputs[0]->tensor.shape; if (input_shape.w != 1 || input_shape.h != 1) { return {TransformStatus::SKIPPED, ""}; } const auto& conv_attr = absl::any_cast<const Convolution2DAttributes&>( node->operation.attributes); if (!IsConvEquivalentToFullyConnected(conv_attr)) { return {TransformStatus::SKIPPED, ""}; } FullyConnectedAttributes fc_attr; fc_attr.weights = conv_attr.weights; fc_attr.bias = conv_attr.bias; node->operation.attributes = fc_attr; node->operation.type = ToString(OperationType::FULLY_CONNECTED); return {TransformStatus::APPLIED, "Replaced convolution with fully connected."}; } }; } // namespace std::unique_ptr<NodeTransformation> NewMakeFullyConnectedFromConvolution() { return absl::make_unique<MakeFullyConnectedFromConvolution>(); } } // namespace gpu } // namespace tflite
apache-2.0
chromium/chromium
chrome/tools/build/mac/archive_symbols.py
690
# Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import subprocess import sys # This script creates a BZ2-compressed TAR file for archiving Chrome symbols. def Main(args): if len(args) < 2: print >> sys.stderr, "Usage: python archive_symbols.py file.tar.bz2 file..." return 1 _RemoveIfExists(args[0]) try: return subprocess.check_call(['tar', '-cjf'] + args) except: _RemoveIfExists(args[0]) raise def _RemoveIfExists(path): if os.path.exists(path): os.unlink(path) if __name__ == '__main__': sys.exit(Main(sys.argv[1:]))
bsd-3-clause
mediathread/mdtprint
app/bower_components/phantom/src/qt/src/gui/kernel/qboxlayout.cpp
45226
/**************************************************************************** ** ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qboxlayout.h" #include "qapplication.h" #include "qwidget.h" #include "qlist.h" #include "qsizepolicy.h" #include "qvector.h" #include "qlayoutengine_p.h" #include "qlayout_p.h" QT_BEGIN_NAMESPACE /* Returns true if the \a widget can be added to the \a layout; otherwise returns false. */ static bool checkWidget(QLayout *layout, QWidget *widget) { if (!widget) { qWarning("QLayout: Cannot add null widget to %s/%s", layout->metaObject()->className(), layout->objectName().toLocal8Bit().data()); return false; } return true; } struct QBoxLayoutItem { QBoxLayoutItem(QLayoutItem *it, int stretch_ = 0) : item(it), stretch(stretch_), magic(false) { } ~QBoxLayoutItem() { delete item; } int hfw(int w) { if (item->hasHeightForWidth()) { return item->heightForWidth(w); } else { return item->sizeHint().height(); } } int mhfw(int w) { if (item->hasHeightForWidth()) { return item->heightForWidth(w); } else { return item->minimumSize().height(); } } int hStretch() { if (stretch == 0 && item->widget()) { return item->widget()->sizePolicy().horizontalStretch(); } else { return stretch; } } int vStretch() { if (stretch == 0 && item->widget()) { return item->widget()->sizePolicy().verticalStretch(); } else { return stretch; } } QLayoutItem *item; int stretch; bool magic; }; class QBoxLayoutPrivate : public QLayoutPrivate { Q_DECLARE_PUBLIC(QBoxLayout) public: QBoxLayoutPrivate() : hfwWidth(-1), dirty(true), spacing(-1) { } ~QBoxLayoutPrivate(); void setDirty() { geomArray.clear(); hfwWidth = -1; hfwHeight = -1; dirty = true; } QList<QBoxLayoutItem *> list; QVector<QLayoutStruct> geomArray; int hfwWidth; int hfwHeight; int hfwMinHeight; QSize sizeHint; QSize minSize; QSize maxSize; int leftMargin, topMargin, rightMargin, bottomMargin; Qt::Orientations expanding; uint hasHfw : 1; uint dirty : 1; QBoxLayout::Direction dir; int spacing; inline void deleteAll() { while (!list.isEmpty()) delete list.takeFirst(); } void setupGeom(); void calcHfw(int); void effectiveMargins(int *left, int *top, int *right, int *bottom) const; }; QBoxLayoutPrivate::~QBoxLayoutPrivate() { } static inline bool horz(QBoxLayout::Direction dir) { return dir == QBoxLayout::RightToLeft || dir == QBoxLayout::LeftToRight; } /** * The purpose of this function is to make sure that widgets are not laid out outside its layout. * E.g. the layoutItemRect margins are only meant to take of the surrounding margins/spacings. * However, if the margin is 0, it can easily cover the area of a widget above it. */ void QBoxLayoutPrivate::effectiveMargins(int *left, int *top, int *right, int *bottom) const { int l = leftMargin; int t = topMargin; int r = rightMargin; int b = bottomMargin; #ifdef Q_WS_MAC Q_Q(const QBoxLayout); if (horz(dir)) { QBoxLayoutItem *leftBox = 0; QBoxLayoutItem *rightBox = 0; if (left || right) { leftBox = list.value(0); rightBox = list.value(list.count() - 1); if (dir == QBoxLayout::RightToLeft) qSwap(leftBox, rightBox); int leftDelta = 0; int rightDelta = 0; if (leftBox) { QLayoutItem *itm = leftBox->item; if (QWidget *w = itm->widget()) leftDelta = itm->geometry().left() - w->geometry().left(); } if (rightBox) { QLayoutItem *itm = rightBox->item; if (QWidget *w = itm->widget()) rightDelta = w->geometry().right() - itm->geometry().right(); } QWidget *w = q->parentWidget(); Qt::LayoutDirection layoutDirection = w ? w->layoutDirection() : QApplication::layoutDirection(); if (layoutDirection == Qt::RightToLeft) qSwap(leftDelta, rightDelta); l = qMax(l, leftDelta); r = qMax(r, rightDelta); } int count = top || bottom ? list.count() : 0; for (int i = 0; i < count; ++i) { QBoxLayoutItem *box = list.at(i); QLayoutItem *itm = box->item; QWidget *w = itm->widget(); if (w) { QRect lir = itm->geometry(); QRect wr = w->geometry(); if (top) t = qMax(t, lir.top() - wr.top()); if (bottom) b = qMax(b, wr.bottom() - lir.bottom()); } } } else { // vertical layout QBoxLayoutItem *topBox = 0; QBoxLayoutItem *bottomBox = 0; if (top || bottom) { topBox = list.value(0); bottomBox = list.value(list.count() - 1); if (dir == QBoxLayout::BottomToTop) { qSwap(topBox, bottomBox); } if (top && topBox) { QLayoutItem *itm = topBox->item; QWidget *w = itm->widget(); if (w) t = qMax(t, itm->geometry().top() - w->geometry().top()); } if (bottom && bottomBox) { QLayoutItem *itm = bottomBox->item; QWidget *w = itm->widget(); if (w) b = qMax(b, w->geometry().bottom() - itm->geometry().bottom()); } } int count = left || right ? list.count() : 0; for (int i = 0; i < count; ++i) { QBoxLayoutItem *box = list.at(i); QLayoutItem *itm = box->item; QWidget *w = itm->widget(); if (w) { QRect lir = itm->geometry(); QRect wr = w->geometry(); if (left) l = qMax(l, lir.left() - wr.left()); if (right) r = qMax(r, wr.right() - lir.right()); } } } #endif if (left) *left = l; if (top) *top = t; if (right) *right = r; if (bottom) *bottom = b; } /* Initializes the data structure needed by qGeomCalc and recalculates max/min and size hint. */ void QBoxLayoutPrivate::setupGeom() { if (!dirty) return; Q_Q(QBoxLayout); int maxw = horz(dir) ? 0 : QLAYOUTSIZE_MAX; int maxh = horz(dir) ? QLAYOUTSIZE_MAX : 0; int minw = 0; int minh = 0; int hintw = 0; int hinth = 0; bool horexp = false; bool verexp = false; hasHfw = false; int n = list.count(); geomArray.clear(); QVector<QLayoutStruct> a(n); QSizePolicy::ControlTypes controlTypes1; QSizePolicy::ControlTypes controlTypes2; int fixedSpacing = q->spacing(); int previousNonEmptyIndex = -1; QStyle *style = 0; if (fixedSpacing < 0) { if (QWidget *parentWidget = q->parentWidget()) style = parentWidget->style(); } for (int i = 0; i < n; i++) { QBoxLayoutItem *box = list.at(i); QSize max = box->item->maximumSize(); QSize min = box->item->minimumSize(); QSize hint = box->item->sizeHint(); Qt::Orientations exp = box->item->expandingDirections(); bool empty = box->item->isEmpty(); int spacing = 0; if (!empty) { if (fixedSpacing >= 0) { spacing = (previousNonEmptyIndex >= 0) ? fixedSpacing : 0; #ifdef Q_WS_MAC if (!horz(dir) && previousNonEmptyIndex >= 0) { QBoxLayoutItem *sibling = (dir == QBoxLayout::TopToBottom ? box : list.at(previousNonEmptyIndex)); if (sibling) { QWidget *wid = sibling->item->widget(); if (wid) spacing = qMax(spacing, sibling->item->geometry().top() - wid->geometry().top()); } } #endif } else { controlTypes1 = controlTypes2; controlTypes2 = box->item->controlTypes(); if (previousNonEmptyIndex >= 0) { QSizePolicy::ControlTypes actual1 = controlTypes1; QSizePolicy::ControlTypes actual2 = controlTypes2; if (dir == QBoxLayout::RightToLeft || dir == QBoxLayout::BottomToTop) qSwap(actual1, actual2); if (style) { spacing = style->combinedLayoutSpacing(actual1, actual2, horz(dir) ? Qt::Horizontal : Qt::Vertical, 0, q->parentWidget()); if (spacing < 0) spacing = 0; } } } if (previousNonEmptyIndex >= 0) a[previousNonEmptyIndex].spacing = spacing; previousNonEmptyIndex = i; } bool ignore = empty && box->item->widget(); // ignore hidden widgets bool dummy = true; if (horz(dir)) { bool expand = (exp & Qt::Horizontal || box->stretch > 0); horexp = horexp || expand; maxw += spacing + max.width(); minw += spacing + min.width(); hintw += spacing + hint.width(); if (!ignore) qMaxExpCalc(maxh, verexp, dummy, max.height(), exp & Qt::Vertical, box->item->isEmpty()); minh = qMax(minh, min.height()); hinth = qMax(hinth, hint.height()); a[i].sizeHint = hint.width(); a[i].maximumSize = max.width(); a[i].minimumSize = min.width(); a[i].expansive = expand; a[i].stretch = box->stretch ? box->stretch : box->hStretch(); } else { bool expand = (exp & Qt::Vertical || box->stretch > 0); verexp = verexp || expand; maxh += spacing + max.height(); minh += spacing + min.height(); hinth += spacing + hint.height(); if (!ignore) qMaxExpCalc(maxw, horexp, dummy, max.width(), exp & Qt::Horizontal, box->item->isEmpty()); minw = qMax(minw, min.width()); hintw = qMax(hintw, hint.width()); a[i].sizeHint = hint.height(); a[i].maximumSize = max.height(); a[i].minimumSize = min.height(); a[i].expansive = expand; a[i].stretch = box->stretch ? box->stretch : box->vStretch(); } a[i].empty = empty; a[i].spacing = 0; // might be be initialized with a non-zero value in a later iteration hasHfw = hasHfw || box->item->hasHeightForWidth(); } geomArray = a; expanding = (Qt::Orientations) ((horexp ? Qt::Horizontal : 0) | (verexp ? Qt::Vertical : 0)); minSize = QSize(minw, minh); maxSize = QSize(maxw, maxh).expandedTo(minSize); sizeHint = QSize(hintw, hinth).expandedTo(minSize).boundedTo(maxSize); q->getContentsMargins(&leftMargin, &topMargin, &rightMargin, &bottomMargin); int left, top, right, bottom; effectiveMargins(&left, &top, &right, &bottom); QSize extra(left + right, top + bottom); minSize += extra; maxSize += extra; sizeHint += extra; dirty = false; } /* Calculates and stores the preferred height given the width \a w. */ void QBoxLayoutPrivate::calcHfw(int w) { QVector<QLayoutStruct> &a = geomArray; int n = a.count(); int h = 0; int mh = 0; Q_ASSERT(n == list.size()); if (horz(dir)) { qGeomCalc(a, 0, n, 0, w); for (int i = 0; i < n; i++) { QBoxLayoutItem *box = list.at(i); h = qMax(h, box->hfw(a.at(i).size)); mh = qMax(mh, box->mhfw(a.at(i).size)); } } else { for (int i = 0; i < n; ++i) { QBoxLayoutItem *box = list.at(i); int spacing = a.at(i).spacing; h += box->hfw(w); mh += box->mhfw(w); h += spacing; mh += spacing; } } hfwWidth = w; hfwHeight = h; hfwMinHeight = mh; } /*! \class QBoxLayout \brief The QBoxLayout class lines up child widgets horizontally or vertically. \ingroup geomanagement QBoxLayout takes the space it gets (from its parent layout or from the parentWidget()), divides it up into a row of boxes, and makes each managed widget fill one box. \image qhboxlayout-with-5-children.png Horizontal box layout with five child widgets If the QBoxLayout's orientation is Qt::Horizontal the boxes are placed in a row, with suitable sizes. Each widget (or other box) will get at least its minimum size and at most its maximum size. Any excess space is shared according to the stretch factors (more about that below). \image qvboxlayout-with-5-children.png Vertical box layout with five child widgets If the QBoxLayout's orientation is Qt::Vertical, the boxes are placed in a column, again with suitable sizes. The easiest way to create a QBoxLayout is to use one of the convenience classes, e.g. QHBoxLayout (for Qt::Horizontal boxes) or QVBoxLayout (for Qt::Vertical boxes). You can also use the QBoxLayout constructor directly, specifying its direction as LeftToRight, RightToLeft, TopToBottom, or BottomToTop. If the QBoxLayout is not the top-level layout (i.e. it is not managing all of the widget's area and children), you must add it to its parent layout before you can do anything with it. The normal way to add a layout is by calling parentLayout-\>addLayout(). Once you have done this, you can add boxes to the QBoxLayout using one of four functions: \list \o addWidget() to add a widget to the QBoxLayout and set the widget's stretch factor. (The stretch factor is along the row of boxes.) \o addSpacing() to create an empty box; this is one of the functions you use to create nice and spacious dialogs. See below for ways to set margins. \o addStretch() to create an empty, stretchable box. \o addLayout() to add a box containing another QLayout to the row and set that layout's stretch factor. \endlist Use insertWidget(), insertSpacing(), insertStretch() or insertLayout() to insert a box at a specified position in the layout. QBoxLayout also includes two margin widths: \list \o setContentsMargins() sets the width of the outer border on each side of the widget. This is the width of the reserved space along each of the QBoxLayout's four sides. \o setSpacing() sets the width between neighboring boxes. (You can use addSpacing() to get more space at a particular spot.) \endlist The margin default is provided by the style. The default margin most Qt styles specify is 9 for child widgets and 11 for windows. The spacing defaults to the same as the margin width for a top-level layout, or to the same as the parent layout. To remove a widget from a layout, call removeWidget(). Calling QWidget::hide() on a widget also effectively removes the widget from the layout until QWidget::show() is called. You will almost always want to use QVBoxLayout and QHBoxLayout rather than QBoxLayout because of their convenient constructors. \sa QGridLayout, QStackedLayout, {Layout Management} */ /*! \enum QBoxLayout::Direction This type is used to determine the direction of a box layout. \value LeftToRight Horizontal from left to right. \value RightToLeft Horizontal from right to left. \value TopToBottom Vertical from top to bottom. \value BottomToTop Vertical from bottom to top. \omitvalue Down \omitvalue Up */ /*! Constructs a new QBoxLayout with direction \a dir and parent widget \a parent. \sa direction() */ QBoxLayout::QBoxLayout(Direction dir, QWidget *parent) : QLayout(*new QBoxLayoutPrivate, 0, parent) { Q_D(QBoxLayout); d->dir = dir; } #ifdef QT3_SUPPORT /*! Constructs a new QBoxLayout with direction \a dir and main widget \a parent. \a parent may not be 0. The \a margin is the number of pixels between the edge of the widget and its managed children. The \a spacing is the default number of pixels between neighboring children. If \a spacing is -1 the value of \a margin is used for \a spacing. \a name is the internal object name. \sa direction() */ QBoxLayout::QBoxLayout(QWidget *parent, Direction dir, int margin, int spacing, const char *name) : QLayout(*new QBoxLayoutPrivate, 0, parent) { Q_D(QBoxLayout); d->dir = dir; setMargin(margin); setObjectName(QString::fromAscii(name)); setSpacing(spacing<0 ? margin : spacing); } /*! Constructs a new QBoxLayout called \a name, with direction \a dir, and inserts it into \a parentLayout. The \a spacing is the default number of pixels between neighboring children. If \a spacing is -1, the layout will inherit its parent's spacing(). */ QBoxLayout::QBoxLayout(QLayout *parentLayout, Direction dir, int spacing, const char *name) : QLayout(*new QBoxLayoutPrivate, parentLayout, 0) { Q_D(QBoxLayout); d->dir = dir; setObjectName(QString::fromAscii(name)); setSpacing(spacing); } /*! Constructs a new QBoxLayout called \a name, with direction \a dir. If \a spacing is -1, the layout will inherit its parent's spacing(); otherwise \a spacing is used. You must insert this box into another layout. */ QBoxLayout::QBoxLayout(Direction dir, int spacing, const char *name) : QLayout(*new QBoxLayoutPrivate,0, 0) { Q_D(QBoxLayout); d->dir = dir; setObjectName(QString::fromAscii(name)); setSpacing(spacing); } #endif // QT3_SUPPORT /*! Destroys this box layout. The layout's widgets aren't destroyed. */ QBoxLayout::~QBoxLayout() { Q_D(QBoxLayout); d->deleteAll(); // must do it before QObject deletes children, so can't be in ~QBoxLayoutPrivate } /*! Reimplements QLayout::spacing(). If the spacing property is valid, that value is returned. Otherwise, a value for the spacing property is computed and returned. Since layout spacing in a widget is style dependent, if the parent is a widget, it queries the style for the (horizontal or vertical) spacing of the layout. Otherwise, the parent is a layout, and it queries the parent layout for the spacing(). \sa QLayout::spacing(), setSpacing() */ int QBoxLayout::spacing() const { Q_D(const QBoxLayout); if (d->spacing >=0) { return d->spacing; } else { return qSmartSpacing(this, d->dir == LeftToRight || d->dir == RightToLeft ? QStyle::PM_LayoutHorizontalSpacing : QStyle::PM_LayoutVerticalSpacing); } } /*! Reimplements QLayout::setSpacing(). Sets the spacing property to \a spacing. \sa QLayout::setSpacing(), spacing() */ void QBoxLayout::setSpacing(int spacing) { Q_D(QBoxLayout); d->spacing = spacing; invalidate(); } /*! \reimp */ QSize QBoxLayout::sizeHint() const { Q_D(const QBoxLayout); if (d->dirty) const_cast<QBoxLayout*>(this)->d_func()->setupGeom(); return d->sizeHint; } /*! \reimp */ QSize QBoxLayout::minimumSize() const { Q_D(const QBoxLayout); if (d->dirty) const_cast<QBoxLayout*>(this)->d_func()->setupGeom(); return d->minSize; } /*! \reimp */ QSize QBoxLayout::maximumSize() const { Q_D(const QBoxLayout); if (d->dirty) const_cast<QBoxLayout*>(this)->d_func()->setupGeom(); QSize s = d->maxSize.boundedTo(QSize(QLAYOUTSIZE_MAX, QLAYOUTSIZE_MAX)); if (alignment() & Qt::AlignHorizontal_Mask) s.setWidth(QLAYOUTSIZE_MAX); if (alignment() & Qt::AlignVertical_Mask) s.setHeight(QLAYOUTSIZE_MAX); return s; } /*! \reimp */ bool QBoxLayout::hasHeightForWidth() const { Q_D(const QBoxLayout); if (d->dirty) const_cast<QBoxLayout*>(this)->d_func()->setupGeom(); return d->hasHfw; } /*! \reimp */ int QBoxLayout::heightForWidth(int w) const { Q_D(const QBoxLayout); if (!hasHeightForWidth()) return -1; int left, top, right, bottom; d->effectiveMargins(&left, &top, &right, &bottom); w -= left + right; if (w != d->hfwWidth) const_cast<QBoxLayout*>(this)->d_func()->calcHfw(w); return d->hfwHeight + top + bottom; } /*! \reimp */ int QBoxLayout::minimumHeightForWidth(int w) const { Q_D(const QBoxLayout); (void) heightForWidth(w); int top, bottom; d->effectiveMargins(0, &top, 0, &bottom); return d->hasHfw ? (d->hfwMinHeight + top + bottom) : -1; } /*! Resets cached information. */ void QBoxLayout::invalidate() { Q_D(QBoxLayout); d->setDirty(); QLayout::invalidate(); } /*! \reimp */ int QBoxLayout::count() const { Q_D(const QBoxLayout); return d->list.count(); } /*! \reimp */ QLayoutItem *QBoxLayout::itemAt(int index) const { Q_D(const QBoxLayout); return index >= 0 && index < d->list.count() ? d->list.at(index)->item : 0; } /*! \reimp */ QLayoutItem *QBoxLayout::takeAt(int index) { Q_D(QBoxLayout); if (index < 0 || index >= d->list.count()) return 0; QBoxLayoutItem *b = d->list.takeAt(index); QLayoutItem *item = b->item; b->item = 0; delete b; invalidate(); return item; } /*! \reimp */ Qt::Orientations QBoxLayout::expandingDirections() const { Q_D(const QBoxLayout); if (d->dirty) const_cast<QBoxLayout*>(this)->d_func()->setupGeom(); return d->expanding; } /*! \reimp */ void QBoxLayout::setGeometry(const QRect &r) { Q_D(QBoxLayout); if (d->dirty || r != geometry()) { QRect oldRect = geometry(); QLayout::setGeometry(r); if (d->dirty) d->setupGeom(); QRect cr = alignment() ? alignmentRect(r) : r; int left, top, right, bottom; d->effectiveMargins(&left, &top, &right, &bottom); QRect s(cr.x() + left, cr.y() + top, cr.width() - (left + right), cr.height() - (top + bottom)); QVector<QLayoutStruct> a = d->geomArray; int pos = horz(d->dir) ? s.x() : s.y(); int space = horz(d->dir) ? s.width() : s.height(); int n = a.count(); if (d->hasHfw && !horz(d->dir)) { for (int i = 0; i < n; i++) { QBoxLayoutItem *box = d->list.at(i); if (box->item->hasHeightForWidth()) { int width = qBound(box->item->minimumSize().width(), s.width(), box->item->maximumSize().width()); a[i].sizeHint = a[i].minimumSize = box->item->heightForWidth(width); } } } Direction visualDir = d->dir; QWidget *parent = parentWidget(); if (parent && parent->isRightToLeft()) { if (d->dir == LeftToRight) visualDir = RightToLeft; else if (d->dir == RightToLeft) visualDir = LeftToRight; } qGeomCalc(a, 0, n, pos, space); bool reverse = (horz(visualDir) ? ((r.right() > oldRect.right()) != (visualDir == RightToLeft)) : r.bottom() > oldRect.bottom()); for (int j = 0; j < n; j++) { int i = reverse ? n-j-1 : j; QBoxLayoutItem *box = d->list.at(i); switch (visualDir) { case LeftToRight: box->item->setGeometry(QRect(a.at(i).pos, s.y(), a.at(i).size, s.height())); break; case RightToLeft: box->item->setGeometry(QRect(s.left() + s.right() - a.at(i).pos - a.at(i).size + 1, s.y(), a.at(i).size, s.height())); break; case TopToBottom: box->item->setGeometry(QRect(s.x(), a.at(i).pos, s.width(), a.at(i).size)); break; case BottomToTop: box->item->setGeometry(QRect(s.x(), s.top() + s.bottom() - a.at(i).pos - a.at(i).size + 1, s.width(), a.at(i).size)); } } } } /*! \reimp */ void QBoxLayout::addItem(QLayoutItem *item) { Q_D(QBoxLayout); QBoxLayoutItem *it = new QBoxLayoutItem(item); d->list.append(it); invalidate(); } /*! Inserts \a item into this box layout at position \a index. If \a index is negative, the item is added at the end. \sa addItem(), insertWidget(), insertLayout(), insertStretch(), insertSpacing() */ void QBoxLayout::insertItem(int index, QLayoutItem *item) { Q_D(QBoxLayout); if (index < 0) // append index = d->list.count(); QBoxLayoutItem *it = new QBoxLayoutItem(item); d->list.insert(index, it); invalidate(); } /*! Inserts a non-stretchable space (a QSpacerItem) at position \a index, with size \a size. If \a index is negative the space is added at the end. The box layout has default margin and spacing. This function adds additional space. \sa addSpacing(), insertItem(), QSpacerItem */ void QBoxLayout::insertSpacing(int index, int size) { Q_D(QBoxLayout); if (index < 0) // append index = d->list.count(); QLayoutItem *b; if (horz(d->dir)) b = QLayoutPrivate::createSpacerItem(this, size, 0, QSizePolicy::Fixed, QSizePolicy::Minimum); else b = QLayoutPrivate::createSpacerItem(this, 0, size, QSizePolicy::Minimum, QSizePolicy::Fixed); QT_TRY { QBoxLayoutItem *it = new QBoxLayoutItem(b); it->magic = true; d->list.insert(index, it); } QT_CATCH(...) { delete b; QT_RETHROW; } invalidate(); } /*! Inserts a stretchable space (a QSpacerItem) at position \a index, with zero minimum size and stretch factor \a stretch. If \a index is negative the space is added at the end. \sa addStretch(), insertItem(), QSpacerItem */ void QBoxLayout::insertStretch(int index, int stretch) { Q_D(QBoxLayout); if (index < 0) // append index = d->list.count(); QLayoutItem *b; if (horz(d->dir)) b = QLayoutPrivate::createSpacerItem(this, 0, 0, QSizePolicy::Expanding, QSizePolicy::Minimum); else b = QLayoutPrivate::createSpacerItem(this, 0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding); QBoxLayoutItem *it = new QBoxLayoutItem(b, stretch); it->magic = true; d->list.insert(index, it); invalidate(); } /*! \since 4.4 Inserts \a spacerItem at position \a index, with zero minimum size and stretch factor. If \a index is negative the space is added at the end. \sa addSpacerItem(), insertStretch(), insertSpacing() */ void QBoxLayout::insertSpacerItem(int index, QSpacerItem *spacerItem) { Q_D(QBoxLayout); if (index < 0) // append index = d->list.count(); QBoxLayoutItem *it = new QBoxLayoutItem(spacerItem); it->magic = true; d->list.insert(index, it); invalidate(); } /*! Inserts \a layout at position \a index, with stretch factor \a stretch. If \a index is negative, the layout is added at the end. \a layout becomes a child of the box layout. \sa addLayout(), insertItem() */ void QBoxLayout::insertLayout(int index, QLayout *layout, int stretch) { Q_D(QBoxLayout); addChildLayout(layout); if (index < 0) // append index = d->list.count(); QBoxLayoutItem *it = new QBoxLayoutItem(layout, stretch); d->list.insert(index, it); invalidate(); } /*! Inserts \a widget at position \a index, with stretch factor \a stretch and alignment \a alignment. If \a index is negative, the widget is added at the end. The stretch factor applies only in the \l{direction()}{direction} of the QBoxLayout, and is relative to the other boxes and widgets in this QBoxLayout. Widgets and boxes with higher stretch factors grow more. If the stretch factor is 0 and nothing else in the QBoxLayout has a stretch factor greater than zero, the space is distributed according to the QWidget:sizePolicy() of each widget that's involved. The alignment is specified by \a alignment. The default alignment is 0, which means that the widget fills the entire cell. \sa addWidget(), insertItem() */ void QBoxLayout::insertWidget(int index, QWidget *widget, int stretch, Qt::Alignment alignment) { Q_D(QBoxLayout); if (!checkWidget(this, widget)) return; addChildWidget(widget); if (index < 0) // append index = d->list.count(); QWidgetItem *b = QLayoutPrivate::createWidgetItem(this, widget); b->setAlignment(alignment); QBoxLayoutItem *it; QT_TRY{ it = new QBoxLayoutItem(b, stretch); } QT_CATCH(...) { delete b; QT_RETHROW; } QT_TRY{ d->list.insert(index, it); } QT_CATCH(...) { delete it; QT_RETHROW; } invalidate(); } /*! Adds a non-stretchable space (a QSpacerItem) with size \a size to the end of this box layout. QBoxLayout provides default margin and spacing. This function adds additional space. \sa insertSpacing(), addItem(), QSpacerItem */ void QBoxLayout::addSpacing(int size) { insertSpacing(-1, size); } /*! Adds a stretchable space (a QSpacerItem) with zero minimum size and stretch factor \a stretch to the end of this box layout. \sa insertStretch(), addItem(), QSpacerItem */ void QBoxLayout::addStretch(int stretch) { insertStretch(-1, stretch); } /*! \since 4.4 Adds \a spacerItem to the end of this box layout. \sa addSpacing(), addStretch() */ void QBoxLayout::addSpacerItem(QSpacerItem *spacerItem) { insertSpacerItem(-1, spacerItem); } /*! Adds \a widget to the end of this box layout, with a stretch factor of \a stretch and alignment \a alignment. The stretch factor applies only in the \l{direction()}{direction} of the QBoxLayout, and is relative to the other boxes and widgets in this QBoxLayout. Widgets and boxes with higher stretch factors grow more. If the stretch factor is 0 and nothing else in the QBoxLayout has a stretch factor greater than zero, the space is distributed according to the QWidget:sizePolicy() of each widget that's involved. The alignment is specified by \a alignment. The default alignment is 0, which means that the widget fills the entire cell. \sa insertWidget(), addItem(), addLayout(), addStretch(), addSpacing(), addStrut() */ void QBoxLayout::addWidget(QWidget *widget, int stretch, Qt::Alignment alignment) { insertWidget(-1, widget, stretch, alignment); } /*! Adds \a layout to the end of the box, with serial stretch factor \a stretch. \sa insertLayout(), addItem(), addWidget() */ void QBoxLayout::addLayout(QLayout *layout, int stretch) { insertLayout(-1, layout, stretch); } /*! Limits the perpendicular dimension of the box (e.g. height if the box is \l LeftToRight) to a minimum of \a size. Other constraints may increase the limit. \sa addItem() */ void QBoxLayout::addStrut(int size) { Q_D(QBoxLayout); QLayoutItem *b; if (horz(d->dir)) b = QLayoutPrivate::createSpacerItem(this, 0, size, QSizePolicy::Fixed, QSizePolicy::Minimum); else b = QLayoutPrivate::createSpacerItem(this, size, 0, QSizePolicy::Minimum, QSizePolicy::Fixed); QBoxLayoutItem *it = new QBoxLayoutItem(b); it->magic = true; d->list.append(it); invalidate(); } /*! \fn int QBoxLayout::findWidget(QWidget *widget) Use indexOf(\a widget) instead. */ /*! Sets the stretch factor for \a widget to \a stretch and returns true if \a widget is found in this layout (not including child layouts); otherwise returns false. \sa setAlignment() */ bool QBoxLayout::setStretchFactor(QWidget *widget, int stretch) { Q_D(QBoxLayout); if (!widget) return false; for (int i = 0; i < d->list.size(); ++i) { QBoxLayoutItem *box = d->list.at(i); if (box->item->widget() == widget) { box->stretch = stretch; invalidate(); return true; } } return false; } /*! \overload Sets the stretch factor for the layout \a layout to \a stretch and returns true if \a layout is found in this layout (not including child layouts); otherwise returns false. */ bool QBoxLayout::setStretchFactor(QLayout *layout, int stretch) { Q_D(QBoxLayout); for (int i = 0; i < d->list.size(); ++i) { QBoxLayoutItem *box = d->list.at(i); if (box->item->layout() == layout) { if (box->stretch != stretch) { box->stretch = stretch; invalidate(); } return true; } } return false; } /*! Sets the stretch factor at position \a index. to \a stretch. \since 4.5 */ void QBoxLayout::setStretch(int index, int stretch) { Q_D(QBoxLayout); if (index >= 0 && index < d->list.size()) { QBoxLayoutItem *box = d->list.at(index); if (box->stretch != stretch) { box->stretch = stretch; invalidate(); } } } /*! Returns the stretch factor at position \a index. \since 4.5 */ int QBoxLayout::stretch(int index) const { Q_D(const QBoxLayout); if (index >= 0 && index < d->list.size()) return d->list.at(index)->stretch; return -1; } /*! Sets the direction of this layout to \a direction. */ void QBoxLayout::setDirection(Direction direction) { Q_D(QBoxLayout); if (d->dir == direction) return; if (horz(d->dir) != horz(direction)) { //swap around the spacers (the "magic" bits) //#### a bit yucky, knows too much. //#### probably best to add access functions to spacerItem //#### or even a QSpacerItem::flip() for (int i = 0; i < d->list.size(); ++i) { QBoxLayoutItem *box = d->list.at(i); if (box->magic) { QSpacerItem *sp = box->item->spacerItem(); if (sp) { if (sp->expandingDirections() == Qt::Orientations(0) /*No Direction*/) { //spacing or strut QSize s = sp->sizeHint(); sp->changeSize(s.height(), s.width(), horz(direction) ? QSizePolicy::Fixed:QSizePolicy::Minimum, horz(direction) ? QSizePolicy::Minimum:QSizePolicy::Fixed); } else { //stretch if (horz(direction)) sp->changeSize(0, 0, QSizePolicy::Expanding, QSizePolicy::Minimum); else sp->changeSize(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding); } } } } } d->dir = direction; invalidate(); } /*! \fn QBoxLayout::Direction QBoxLayout::direction() const Returns the direction of the box. addWidget() and addSpacing() work in this direction; the stretch stretches in this direction. \sa QBoxLayout::Direction addWidget() addSpacing() */ QBoxLayout::Direction QBoxLayout::direction() const { Q_D(const QBoxLayout); return d->dir; } /*! \class QHBoxLayout \brief The QHBoxLayout class lines up widgets horizontally. \ingroup geomanagement This class is used to construct horizontal box layout objects. See QBoxLayout for details. The simplest use of the class is like this: \snippet doc/src/snippets/layouts/layouts.cpp 0 \snippet doc/src/snippets/layouts/layouts.cpp 1 \snippet doc/src/snippets/layouts/layouts.cpp 2 \codeline \snippet doc/src/snippets/layouts/layouts.cpp 3 \snippet doc/src/snippets/layouts/layouts.cpp 4 \snippet doc/src/snippets/layouts/layouts.cpp 5 First, we create the widgets we want in the layout. Then, we create the QHBoxLayout object and add the widgets into the layout. Finally, we call QWidget::setLayout() to install the QHBoxLayout object onto the widget. At that point, the widgets in the layout are reparented to have \c window as their parent. \image qhboxlayout-with-5-children.png Horizontal box layout with five child widgets \sa QVBoxLayout, QGridLayout, QStackedLayout, {Layout Management}, {Basic Layouts Example} */ /*! Constructs a new top-level horizontal box with parent \a parent. */ QHBoxLayout::QHBoxLayout(QWidget *parent) : QBoxLayout(LeftToRight, parent) { } /*! Constructs a new horizontal box. You must add it to another layout. */ QHBoxLayout::QHBoxLayout() : QBoxLayout(LeftToRight) { } #ifdef QT3_SUPPORT /*! Constructs a new top-level horizontal box called \a name, with parent \a parent. The \a margin is the number of pixels between the edge of the widget and its managed children. The \a spacing is the default number of pixels between neighboring children. If \a spacing is -1 the value of \a margin is used for \a spacing. */ QHBoxLayout::QHBoxLayout(QWidget *parent, int margin, int spacing, const char *name) : QBoxLayout(LeftToRight, parent) { setMargin(margin); setSpacing(spacing<0 ? margin : spacing); setObjectName(QString::fromAscii(name)); } /*! Constructs a new horizontal box called name \a name and adds it to \a parentLayout. The \a spacing is the default number of pixels between neighboring children. If \a spacing is -1, this QHBoxLayout will inherit its parent's spacing(). */ QHBoxLayout::QHBoxLayout(QLayout *parentLayout, int spacing, const char *name) : QBoxLayout(LeftToRight) { setSpacing(spacing); setObjectName(QString::fromAscii(name)); if (parentLayout) { setParent(parentLayout); parentLayout->addItem(this); } } /*! Constructs a new horizontal box called name \a name. You must add it to another layout. The \a spacing is the default number of pixels between neighboring children. If \a spacing is -1, this QHBoxLayout will inherit its parent's spacing(). */ QHBoxLayout::QHBoxLayout(int spacing, const char *name) : QBoxLayout(LeftToRight) { setSpacing(spacing); setObjectName(QString::fromAscii(name)); } #endif /*! Destroys this box layout. The layout's widgets aren't destroyed. */ QHBoxLayout::~QHBoxLayout() { } /*! \class QVBoxLayout \brief The QVBoxLayout class lines up widgets vertically. \ingroup geomanagement This class is used to construct vertical box layout objects. See QBoxLayout for details. The simplest use of the class is like this: \snippet doc/src/snippets/layouts/layouts.cpp 6 \snippet doc/src/snippets/layouts/layouts.cpp 7 \snippet doc/src/snippets/layouts/layouts.cpp 8 \codeline \snippet doc/src/snippets/layouts/layouts.cpp 9 \snippet doc/src/snippets/layouts/layouts.cpp 10 \snippet doc/src/snippets/layouts/layouts.cpp 11 First, we create the widgets we want in the layout. Then, we create the QVBoxLayout object and add the widgets into the layout. Finally, we call QWidget::setLayout() to install the QVBoxLayout object onto the widget. At that point, the widgets in the layout are reparented to have \c window as their parent. \image qvboxlayout-with-5-children.png Horizontal box layout with five child widgets \sa QHBoxLayout, QGridLayout, QStackedLayout, {Layout Management}, {Basic Layouts Example} */ /*! Constructs a new top-level vertical box with parent \a parent. */ QVBoxLayout::QVBoxLayout(QWidget *parent) : QBoxLayout(TopToBottom, parent) { } /*! Constructs a new vertical box. You must add it to another layout. */ QVBoxLayout::QVBoxLayout() : QBoxLayout(TopToBottom) { } #ifdef QT3_SUPPORT /*! Constructs a new top-level vertical box called \a name, with parent \a parent. The \a margin is the number of pixels between the edge of the widget and its managed children. The \a spacing is the default number of pixels between neighboring children. If \a spacing is -1 the value of \a margin is used for \a spacing. */ QVBoxLayout::QVBoxLayout(QWidget *parent, int margin, int spacing, const char *name) : QBoxLayout(TopToBottom, parent) { setMargin(margin); setSpacing(spacing<0 ? margin : spacing); setObjectName(QString::fromAscii(name)); } /*! Constructs a new vertical box called name \a name and adds it to \a parentLayout. The \a spacing is the default number of pixels between neighboring children. If \a spacing is -1, this QVBoxLayout will inherit its parent's spacing(). */ QVBoxLayout::QVBoxLayout(QLayout *parentLayout, int spacing, const char *name) : QBoxLayout(TopToBottom) { setSpacing(spacing); setObjectName(QString::fromAscii(name)); if (parentLayout) { setParent(parentLayout); parentLayout->addItem(this); } } /*! Constructs a new vertical box called name \a name. You must add it to another layout. The \a spacing is the default number of pixels between neighboring children. If \a spacing is -1, this QVBoxLayout will inherit its parent's spacing(). */ QVBoxLayout::QVBoxLayout(int spacing, const char *name) : QBoxLayout(TopToBottom) { setSpacing(spacing); setObjectName(QString::fromAscii(name)); } #endif /*! Destroys this box layout. The layout's widgets aren't destroyed. */ QVBoxLayout::~QVBoxLayout() { } /*! \fn QWidget *QLayout::mainWidget() const Use parentWidget() instead. */ /*! \fn void QLayout::remove(QWidget *widget) Use removeWidget(\a widget) instead. */ /*! \fn void QLayout::add(QWidget *widget) Use addWidget(\a widget) instead. */ /*! \fn QLayoutIterator QLayout::iterator() Use a QLayoutIterator() constructor instead. */ /*! \fn int QLayout::defaultBorder() const Use spacing() instead. */ QT_END_NAMESPACE
mit
ralzate/Produccion
vendor/bundle/ruby/2.2.0/gems/fog-storm_on_demand-0.1.1/lib/fog/monitoring/storm_on_demand/models/load.rb
266
module Fog module Monitoring class StormOnDemand class Load < Fog::Model attribute :disk attribute :domain attribute :loadavg attribute :memory attribute :proc attribute :uptime end end end end
mit
ycavatars/flux-react-router-example
scripts/utils/PaginatedStoreUtils.js
2499
import { createStore } from './StoreUtils'; import PaginatedList from '../utils/PaginatedList'; import invariant from 'react/lib/invariant'; const PROXIED_PAGINATED_LIST_METHODS = [ 'getIds', 'getPageCount', 'getNextPageUrl', 'isExpectingPage', 'isLastPage' ]; function createListStoreSpec({ getList, callListMethod }) { const spec = { getList }; PROXIED_PAGINATED_LIST_METHODS.forEach(method => { spec[method] = (...args) => { return callListMethod(method, args); }; }); return spec; } /** * Creates a simple paginated store that represents a global list (e.g. feed). */ export function createListStore(spec) { const list = new PaginatedList(); const getList = () => list; const callListMethod = (method, args) => { return list[method].call(list, args); }; return createStore( Object.assign(createListStoreSpec({ getList, callListMethod }), spec) ); } /** * Creates an indexed paginated store that represents a one-many * relationship (e.g. user's posts). Expects foreign key ID to be * passed as first parameter to store methods. */ export function createIndexedListStore(spec) { const lists = {}; const prefix = 'ID_'; const getList = (id) => { const key = prefix + id; if (!lists[key]) { lists[key] = new PaginatedList(); } return lists[key]; }; const callListMethod = (method, args) => { const id = args.shift(); invariant( typeof id !== 'undefined', 'Indexed pagination store methods expect ID as first parameter.' ); const list = getList(id); return list[method].call(list, args); }; return createStore( Object.assign(createListStoreSpec({ getList, callListMethod }), spec) ); } /** * Creates a handler that responds to list store pagination actions. */ export function createListActionHandler(types) { const { request, failure, success } = types; invariant(request, 'Pass a valid request action type.'); invariant(failure, 'Pass a valid failure action type.'); invariant(success, 'Pass a valid success action type.'); return (action, list, emitChange) => { switch (action.type) { case request: list.expectPage(); emitChange(); break; case failure: list.cancelPage(); emitChange(); break; case success: list.receivePage( action.response.result, action.response.nextPageUrl ); emitChange(); break; } }; }
mit
mprobst/angular
packages/core/src/di/reflective_key.ts
1896
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {stringify} from '../util/stringify'; import {resolveForwardRef} from './forward_ref'; /** * A unique object used for retrieving items from the {@link ReflectiveInjector}. * * Keys have: * - a system-wide unique `id`. * - a `token`. * * `Key` is used internally by {@link ReflectiveInjector} because its system-wide unique `id` allows * the * injector to store created objects in a more efficient way. * * `Key` should not be created directly. {@link ReflectiveInjector} creates keys automatically when * resolving * providers. * * @deprecated No replacement * @publicApi */ export class ReflectiveKey { public readonly displayName: string; /** * Private */ constructor(public token: Object, public id: number) { if (!token) { throw new Error('Token must be defined!'); } this.displayName = stringify(this.token); } /** * Retrieves a `Key` for a token. */ static get(token: Object): ReflectiveKey { return _globalKeyRegistry.get(resolveForwardRef(token)); } /** * @returns the number of keys registered in the system. */ static get numberOfKeys(): number { return _globalKeyRegistry.numberOfKeys; } } export class KeyRegistry { private _allKeys = new Map<Object, ReflectiveKey>(); get(token: Object): ReflectiveKey { if (token instanceof ReflectiveKey) return token; if (this._allKeys.has(token)) { return this._allKeys.get(token) !; } const newKey = new ReflectiveKey(token, ReflectiveKey.numberOfKeys); this._allKeys.set(token, newKey); return newKey; } get numberOfKeys(): number { return this._allKeys.size; } } const _globalKeyRegistry = new KeyRegistry();
mit
etix/mirrorbits
vendor/google.golang.org/grpc/balancer_v1_wrapper.go
8557
/* * * Copyright 2017 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package grpc import ( "context" "strings" "sync" "google.golang.org/grpc/balancer" "google.golang.org/grpc/connectivity" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/resolver" ) type balancerWrapperBuilder struct { b Balancer // The v1 balancer. } func (bwb *balancerWrapperBuilder) Build(cc balancer.ClientConn, opts balancer.BuildOptions) balancer.Balancer { targetAddr := cc.Target() targetSplitted := strings.Split(targetAddr, ":///") if len(targetSplitted) >= 2 { targetAddr = targetSplitted[1] } bwb.b.Start(targetAddr, BalancerConfig{ DialCreds: opts.DialCreds, Dialer: opts.Dialer, }) _, pickfirst := bwb.b.(*pickFirst) bw := &balancerWrapper{ balancer: bwb.b, pickfirst: pickfirst, cc: cc, targetAddr: targetAddr, startCh: make(chan struct{}), conns: make(map[resolver.Address]balancer.SubConn), connSt: make(map[balancer.SubConn]*scState), csEvltr: &balancer.ConnectivityStateEvaluator{}, state: connectivity.Idle, } cc.UpdateBalancerState(connectivity.Idle, bw) go bw.lbWatcher() return bw } func (bwb *balancerWrapperBuilder) Name() string { return "wrapper" } type scState struct { addr Address // The v1 address type. s connectivity.State down func(error) } type balancerWrapper struct { balancer Balancer // The v1 balancer. pickfirst bool cc balancer.ClientConn targetAddr string // Target without the scheme. mu sync.Mutex conns map[resolver.Address]balancer.SubConn connSt map[balancer.SubConn]*scState // This channel is closed when handling the first resolver result. // lbWatcher blocks until this is closed, to avoid race between // - NewSubConn is created, cc wants to notify balancer of state changes; // - Build hasn't return, cc doesn't have access to balancer. startCh chan struct{} // To aggregate the connectivity state. csEvltr *balancer.ConnectivityStateEvaluator state connectivity.State } // lbWatcher watches the Notify channel of the balancer and manages // connections accordingly. func (bw *balancerWrapper) lbWatcher() { <-bw.startCh notifyCh := bw.balancer.Notify() if notifyCh == nil { // There's no resolver in the balancer. Connect directly. a := resolver.Address{ Addr: bw.targetAddr, Type: resolver.Backend, } sc, err := bw.cc.NewSubConn([]resolver.Address{a}, balancer.NewSubConnOptions{}) if err != nil { grpclog.Warningf("Error creating connection to %v. Err: %v", a, err) } else { bw.mu.Lock() bw.conns[a] = sc bw.connSt[sc] = &scState{ addr: Address{Addr: bw.targetAddr}, s: connectivity.Idle, } bw.mu.Unlock() sc.Connect() } return } for addrs := range notifyCh { grpclog.Infof("balancerWrapper: got update addr from Notify: %v\n", addrs) if bw.pickfirst { var ( oldA resolver.Address oldSC balancer.SubConn ) bw.mu.Lock() for oldA, oldSC = range bw.conns { break } bw.mu.Unlock() if len(addrs) <= 0 { if oldSC != nil { // Teardown old sc. bw.mu.Lock() delete(bw.conns, oldA) delete(bw.connSt, oldSC) bw.mu.Unlock() bw.cc.RemoveSubConn(oldSC) } continue } var newAddrs []resolver.Address for _, a := range addrs { newAddr := resolver.Address{ Addr: a.Addr, Type: resolver.Backend, // All addresses from balancer are all backends. ServerName: "", Metadata: a.Metadata, } newAddrs = append(newAddrs, newAddr) } if oldSC == nil { // Create new sc. sc, err := bw.cc.NewSubConn(newAddrs, balancer.NewSubConnOptions{}) if err != nil { grpclog.Warningf("Error creating connection to %v. Err: %v", newAddrs, err) } else { bw.mu.Lock() // For pickfirst, there should be only one SubConn, so the // address doesn't matter. All states updating (up and down) // and picking should all happen on that only SubConn. bw.conns[resolver.Address{}] = sc bw.connSt[sc] = &scState{ addr: addrs[0], // Use the first address. s: connectivity.Idle, } bw.mu.Unlock() sc.Connect() } } else { bw.mu.Lock() bw.connSt[oldSC].addr = addrs[0] bw.mu.Unlock() oldSC.UpdateAddresses(newAddrs) } } else { var ( add []resolver.Address // Addresses need to setup connections. del []balancer.SubConn // Connections need to tear down. ) resAddrs := make(map[resolver.Address]Address) for _, a := range addrs { resAddrs[resolver.Address{ Addr: a.Addr, Type: resolver.Backend, // All addresses from balancer are all backends. ServerName: "", Metadata: a.Metadata, }] = a } bw.mu.Lock() for a := range resAddrs { if _, ok := bw.conns[a]; !ok { add = append(add, a) } } for a, c := range bw.conns { if _, ok := resAddrs[a]; !ok { del = append(del, c) delete(bw.conns, a) // Keep the state of this sc in bw.connSt until its state becomes Shutdown. } } bw.mu.Unlock() for _, a := range add { sc, err := bw.cc.NewSubConn([]resolver.Address{a}, balancer.NewSubConnOptions{}) if err != nil { grpclog.Warningf("Error creating connection to %v. Err: %v", a, err) } else { bw.mu.Lock() bw.conns[a] = sc bw.connSt[sc] = &scState{ addr: resAddrs[a], s: connectivity.Idle, } bw.mu.Unlock() sc.Connect() } } for _, c := range del { bw.cc.RemoveSubConn(c) } } } } func (bw *balancerWrapper) HandleSubConnStateChange(sc balancer.SubConn, s connectivity.State) { bw.mu.Lock() defer bw.mu.Unlock() scSt, ok := bw.connSt[sc] if !ok { return } if s == connectivity.Idle { sc.Connect() } oldS := scSt.s scSt.s = s if oldS != connectivity.Ready && s == connectivity.Ready { scSt.down = bw.balancer.Up(scSt.addr) } else if oldS == connectivity.Ready && s != connectivity.Ready { if scSt.down != nil { scSt.down(errConnClosing) } } sa := bw.csEvltr.RecordTransition(oldS, s) if bw.state != sa { bw.state = sa } bw.cc.UpdateBalancerState(bw.state, bw) if s == connectivity.Shutdown { // Remove state for this sc. delete(bw.connSt, sc) } } func (bw *balancerWrapper) HandleResolvedAddrs([]resolver.Address, error) { bw.mu.Lock() defer bw.mu.Unlock() select { case <-bw.startCh: default: close(bw.startCh) } // There should be a resolver inside the balancer. // All updates here, if any, are ignored. } func (bw *balancerWrapper) Close() { bw.mu.Lock() defer bw.mu.Unlock() select { case <-bw.startCh: default: close(bw.startCh) } bw.balancer.Close() } // The picker is the balancerWrapper itself. // Pick should never return ErrNoSubConnAvailable. // It either blocks or returns error, consistent with v1 balancer Get(). func (bw *balancerWrapper) Pick(ctx context.Context, opts balancer.PickOptions) (balancer.SubConn, func(balancer.DoneInfo), error) { failfast := true // Default failfast is true. if ss, ok := rpcInfoFromContext(ctx); ok { failfast = ss.failfast } a, p, err := bw.balancer.Get(ctx, BalancerGetOptions{BlockingWait: !failfast}) if err != nil { return nil, nil, err } var done func(balancer.DoneInfo) if p != nil { done = func(i balancer.DoneInfo) { p() } } var sc balancer.SubConn bw.mu.Lock() defer bw.mu.Unlock() if bw.pickfirst { // Get the first sc in conns. for _, sc = range bw.conns { break } } else { var ok bool sc, ok = bw.conns[resolver.Address{ Addr: a.Addr, Type: resolver.Backend, ServerName: "", Metadata: a.Metadata, }] if !ok && failfast { return nil, nil, balancer.ErrTransientFailure } if s, ok := bw.connSt[sc]; failfast && (!ok || s.s != connectivity.Ready) { // If the returned sc is not ready and RPC is failfast, // return error, and this RPC will fail. return nil, nil, balancer.ErrTransientFailure } } return sc, done, nil }
mit
Kotpes/kateoleshova
web/app/plugins/advanced-custom-fields-pro/admin/install.php
7015
<?php if( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly if( ! class_exists('acf_admin_install') ) : class acf_admin_install { // vars var $db_updates = array( '5.0.0' => 'acf_update_500', '5.5.0' => 'acf_update_550' ); /* * __construct * * This function will setup the class functionality * * @type function * @date 5/03/2014 * @since 5.0.0 * * @param n/a * @return n/a */ function __construct() { // actions add_action('admin_menu', array($this,'admin_menu'), 20); add_action('wp_upgrade', array($this,'wp_upgrade'), 10, 2); // ajax add_action('wp_ajax_acf/admin/db_update', array($this, 'ajax_db_update')); } /* * admin_menu * * This function will chck for available updates and add actions if needed * * @type function * @date 19/02/2014 * @since 5.0.0 * * @param n/a * @return n/a */ function admin_menu() { // vars $updates = acf_get_db_updates(); // bail early if no updates available if( !$updates ) return; // actions add_action('admin_notices', array($this, 'admin_notices'), 1); // add page $page = add_submenu_page('index.php', __('Upgrade Database','acf'), __('Upgrade Database','acf'), acf_get_setting('capability'), 'acf-upgrade', array($this,'html') ); // actions add_action('load-' . $page, array($this,'load')); } /* * load * * This function will look at the $_POST data and run any functions if needed * * @type function * @date 7/01/2014 * @since 5.0.0 * * @param n/a * @return n/a */ function load() { // hide upgrade remove_action('admin_notices', array($this, 'admin_notices'), 1); // load acf scripts acf_enqueue_scripts(); } /* * admin_notices * * This function will render the DB Upgrade notice * * @type function * @date 17/10/13 * @since 5.0.0 * * @param n/a * @return n/a */ function admin_notices() { // view $view = array( 'button_text' => __("Upgrade Database", 'acf'), 'button_url' => admin_url('index.php?page=acf-upgrade') ); // load view acf_get_view('install-notice', $view); } /* * html * * description * * @type function * @date 19/02/2014 * @since 5.0.0 * * @param $post_id (int) * @return $post_id (int) */ function html() { // view $view = array( 'updates' => acf_get_db_updates(), 'plugin_version' => acf_get_setting('version') ); // load view acf_get_view('install', $view); } /* * ajax_db_update * * description * * @type function * @date 24/10/13 * @since 5.0.0 * * @param $post_id (int) * @return $post_id (int) */ function ajax_db_update() { // options $options = wp_parse_args( $_POST, array( 'nonce' => '', 'blog_id' => '', )); // validate if( !wp_verify_nonce($options['nonce'], 'acf_db_update') ) { wp_send_json_error(array( 'message' => __('Error validating request', 'acf') )); } // switch blog if( $options['blog_id'] ) { switch_to_blog( $options['blog_id'] ); } // vars $updates = acf_get_db_updates(); $message = ''; // bail early if no updates if( empty($updates) ) { wp_send_json_error(array( 'message' => __('No updates available.', 'acf') )); } // install updates foreach( $updates as $version => $callback ) { $message .= $this->run_update( $callback ); } // updates complete acf_update_db_version(); // return wp_send_json_success(array( 'message' => $message )); } /* * run_db_update * * This function will perform a db upgrade * * @type function * @date 10/09/2016 * @since 5.4.0 * * @param $post_id (int) * @return $post_id (int) */ function run_update( $callback = '' ) { // include update functions acf_include('admin/install-updates.php'); // bail early if not found if( !function_exists($callback) ) return false; // load any errors / feedback from update ob_start(); // include call_user_func($callback); // get feedback $message = ob_get_clean(); // return return $message; } /* * wp_upgrade * * This function will run when the WP database is updated * * @type function * @date 10/09/2016 * @since 5.4.0 * * @param $wp_db_version (string) The new $wp_db_version * @return $wp_current_db_version (string) The old (current) $wp_db_version */ function wp_upgrade( $wp_db_version, $wp_current_db_version ) { // vars $acf_db_version = acf_get_db_version(); // termmeta was added in WP 4.4 (34370) // if website has already updated to ACF 5.5.0, termmeta will not have yet been migrated if( $wp_db_version >= 34370 && $wp_current_db_version < 34370 && acf_version_compare($acf_db_version, '>=', '5.5.0') ) { $this->run_update('acf_update_550_termmeta'); } } } // initialize acf()->admin->install = new acf_admin_install(); endif; // class_exists check /* * acf_get_db_version * * This function will return the current ACF DB version * * @type function * @date 10/09/2016 * @since 5.4.0 * * @param $post_id (int) * @return $post_id (int) */ function acf_get_db_version() { return get_option('acf_version'); } /* * acf_update_db_version * * This function will update the current ACF DB version * * @type function * @date 10/09/2016 * @since 5.4.0 * * @param $post_id (int) * @return $post_id (int) */ function acf_update_db_version( $version = '' ) { // default to latest if( !$version ) { $version = acf_get_setting('version'); } // update update_option('acf_version', $version ); } /* * acf_get_db_updates * * This function will return available db updates * * @type function * @date 12/05/2014 * @since 5.0.0 * * @param $post_id (int) * @return $post_id (int) */ function acf_get_db_updates() { // vars $available = array(); $db_updates = acf()->admin->install->db_updates; $acf_version = acf_get_setting('version'); $db_version = acf_get_db_version(); // bail early if is fresh install if( !$db_version ) { acf_update_db_version($acf_version); return false; } // bail early if is up to date if( acf_version_compare($db_version, '>=', $acf_version)) return false; // loop foreach( $db_updates as $version => $callback ) { // ignore if update is for a future version (may exist for testing) if( acf_version_compare( $version, '>', $acf_version ) ) continue; // ignore if update has already been run if( acf_version_compare( $version, '<=', $db_version ) ) continue; // append $available[ $version ] = $callback; } // bail early if no updates available // - also update DB to current version if( empty($available) ) { acf_update_db_version($acf_version); return false; } // return return $available; } ?>
mit
ammarkhann/FinalSeniorCode
lib/python2.7/site-packages/IPython/utils/process.py
2937
# encoding: utf-8 """ Utilities for working with external processes. """ # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. from __future__ import print_function import os import sys if sys.platform == 'win32': from ._process_win32 import system, getoutput, arg_split, check_pid elif sys.platform == 'cli': from ._process_cli import system, getoutput, arg_split, check_pid else: from ._process_posix import system, getoutput, arg_split, check_pid from ._process_common import getoutputerror, get_output_error_code, process_handler from . import py3compat class FindCmdError(Exception): pass def find_cmd(cmd): """Find absolute path to executable cmd in a cross platform manner. This function tries to determine the full path to a command line program using `which` on Unix/Linux/OS X and `win32api` on Windows. Most of the time it will use the version that is first on the users `PATH`. Warning, don't use this to find IPython command line programs as there is a risk you will find the wrong one. Instead find those using the following code and looking for the application itself:: from IPython.utils.path import get_ipython_module_path from IPython.utils.process import pycmd2argv argv = pycmd2argv(get_ipython_module_path('IPython.terminal.ipapp')) Parameters ---------- cmd : str The command line program to look for. """ path = py3compat.which(cmd) if path is None: raise FindCmdError('command could not be found: %s' % cmd) return path def is_cmd_found(cmd): """Check whether executable `cmd` exists or not and return a bool.""" try: find_cmd(cmd) return True except FindCmdError: return False def pycmd2argv(cmd): r"""Take the path of a python command and return a list (argv-style). This only works on Python based command line programs and will find the location of the ``python`` executable using ``sys.executable`` to make sure the right version is used. For a given path ``cmd``, this returns [cmd] if cmd's extension is .exe, .com or .bat, and [, cmd] otherwise. Parameters ---------- cmd : string The path of the command. Returns ------- argv-style list. """ ext = os.path.splitext(cmd)[1] if ext in ['.exe', '.com', '.bat']: return [cmd] else: return [sys.executable, cmd] def abbrev_cwd(): """ Return abbreviated version of cwd, e.g. d:mydir """ cwd = py3compat.getcwd().replace('\\','/') drivepart = '' tail = cwd if sys.platform == 'win32': if len(cwd) < 4: return cwd drivepart,tail = os.path.splitdrive(cwd) parts = tail.split('/') if len(parts) > 2: tail = '/'.join(parts[-2:]) return (drivepart + ( cwd == '/' and '/' or tail))
mit
topameng/mGUI
Assets/NGUI/Scripts/Editor/UIColorPickerEditor.cs
841
//---------------------------------------------- // NGUI: Next-Gen UI kit // Copyright © 2011-2016 Tasharen Entertainment //---------------------------------------------- using UnityEngine; using UnityEditor; [CanEditMultipleObjects] [CustomEditor(typeof(UIColorPicker))] public class UIColorPickerEditor : Editor { public override void OnInspectorGUI () { serializedObject.Update(); NGUIEditorTools.SetLabelWidth(100f); UIColorPicker picker = target as UIColorPicker; GUILayout.Space(6f); GUI.changed = false; NGUIEditorTools.DrawProperty(serializedObject, "value"); NGUIEditorTools.DrawProperty(serializedObject, "selectionWidget"); GUILayout.Space(6f); GUI.changed = false; NGUIEditorTools.DrawEvents("On Value Change", picker, picker.onChange); serializedObject.ApplyModifiedProperties(); } }
mit
mlzummo/dimple
src/objects/chart/methods/_xPixels.js
383
// Copyright: 2015 AlignAlytics // License: "https://github.com/PMSI-AlignAlytics/dimple/blob/master/MIT-LICENSE.txt" // Source: /src/objects/chart/methods/_xPixels.js // Access the pixel position of the x co-ordinate of the plot area this._xPixels = function () { return dimple._parseXPosition(this.x, this.svg.node()); };
mit
ychaim/nxt
src/java/nxt/Phaser.java
293
package nxt; public final class Phaser { /* private static final Set<Long> phasedTransactionIds = Collections.newSetFromMap(new ConcurrentHashMap<Long, Boolean>()); public static void processTransaction(TransactionImpl transaction) { transaction.apply(); } */ }
mit
ahartz1/python_koans
python3/koans/about_lambdas.py
860
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Based slightly on the lambdas section of AboutBlocks in the Ruby Koans # from runner.koan import * class AboutLambdas(Koan): def test_lambdas_can_be_assigned_to_variables_and_called_explicitly(self): add_one = lambda n: n + 1 self.assertEqual(11, add_one(10)) # ------------------------------------------------------------------ def make_order(self, order): return lambda qty: str(qty) + " " + order + "s" def test_accessing_lambda_via_assignment(self): sausages = self.make_order('sausage') eggs = self.make_order('egg') self.assertEqual('3 sausages', sausages(3)) self.assertEqual('2 eggs', eggs(2)) def test_accessing_lambda_without_assignment(self): self.assertEqual('39823 spams', self.make_order('spam')(39823))
mit
agencja-acclaim/gulp-bower-webapp
wp-admin/includes/image.php
22259
<?php /** * File contains all the administration image manipulation functions. * * @package WordPress * @subpackage Administration */ /** * Crop an Image to a given size. * * @since 2.1.0 * * @param string|int $src The source file or Attachment ID. * @param int $src_x The start x position to crop from. * @param int $src_y The start y position to crop from. * @param int $src_w The width to crop. * @param int $src_h The height to crop. * @param int $dst_w The destination width. * @param int $dst_h The destination height. * @param int $src_abs Optional. If the source crop points are absolute. * @param string $dst_file Optional. The destination file to write to. * @return string|WP_Error New filepath on success, WP_Error on failure. */ function wp_crop_image( $src, $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h, $src_abs = false, $dst_file = false ) { $src_file = $src; if ( is_numeric( $src ) ) { // Handle int as attachment ID $src_file = get_attached_file( $src ); if ( ! file_exists( $src_file ) ) { // If the file doesn't exist, attempt a URL fopen on the src link. // This can occur with certain file replication plugins. $src = _load_image_to_edit_path( $src, 'full' ); } else { $src = $src_file; } } $editor = wp_get_image_editor( $src ); if ( is_wp_error( $editor ) ) return $editor; $src = $editor->crop( $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h, $src_abs ); if ( is_wp_error( $src ) ) return $src; if ( ! $dst_file ) $dst_file = str_replace( basename( $src_file ), 'cropped-' . basename( $src_file ), $src_file ); /* * The directory containing the original file may no longer exist when * using a replication plugin. */ wp_mkdir_p( dirname( $dst_file ) ); $dst_file = dirname( $dst_file ) . '/' . wp_unique_filename( dirname( $dst_file ), basename( $dst_file ) ); $result = $editor->save( $dst_file ); if ( is_wp_error( $result ) ) return $result; return $dst_file; } /** * Generate post thumbnail attachment meta data. * * @since 2.1.0 * * @param int $attachment_id Attachment Id to process. * @param string $file Filepath of the Attached image. * @return mixed Metadata for attachment. */ function wp_generate_attachment_metadata( $attachment_id, $file ) { $attachment = get_post( $attachment_id ); $metadata = array(); $support = false; $mime_type = get_post_mime_type( $attachment ); if ( preg_match( '!^image/!', $mime_type ) && file_is_displayable_image( $file ) ) { $imagesize = getimagesize( $file ); $metadata['width'] = $imagesize[0]; $metadata['height'] = $imagesize[1]; // Make the file path relative to the upload dir. $metadata['file'] = _wp_relative_upload_path($file); // Make thumbnails and other intermediate sizes. $_wp_additional_image_sizes = wp_get_additional_image_sizes(); $sizes = array(); foreach ( get_intermediate_image_sizes() as $s ) { $sizes[$s] = array( 'width' => '', 'height' => '', 'crop' => false ); if ( isset( $_wp_additional_image_sizes[$s]['width'] ) ) { // For theme-added sizes $sizes[$s]['width'] = intval( $_wp_additional_image_sizes[$s]['width'] ); } else { // For default sizes set in options $sizes[$s]['width'] = get_option( "{$s}_size_w" ); } if ( isset( $_wp_additional_image_sizes[$s]['height'] ) ) { // For theme-added sizes $sizes[$s]['height'] = intval( $_wp_additional_image_sizes[$s]['height'] ); } else { // For default sizes set in options $sizes[$s]['height'] = get_option( "{$s}_size_h" ); } if ( isset( $_wp_additional_image_sizes[$s]['crop'] ) ) { // For theme-added sizes $sizes[$s]['crop'] = $_wp_additional_image_sizes[$s]['crop']; } else { // For default sizes set in options $sizes[$s]['crop'] = get_option( "{$s}_crop" ); } } /** * Filters the image sizes automatically generated when uploading an image. * * @since 2.9.0 * @since 4.4.0 Added the `$metadata` argument. * * @param array $sizes An associative array of image sizes. * @param array $metadata An associative array of image metadata: width, height, file. */ $sizes = apply_filters( 'intermediate_image_sizes_advanced', $sizes, $metadata ); if ( $sizes ) { $editor = wp_get_image_editor( $file ); if ( ! is_wp_error( $editor ) ) $metadata['sizes'] = $editor->multi_resize( $sizes ); } else { $metadata['sizes'] = array(); } // Fetch additional metadata from EXIF/IPTC. $image_meta = wp_read_image_metadata( $file ); if ( $image_meta ) $metadata['image_meta'] = $image_meta; } elseif ( wp_attachment_is( 'video', $attachment ) ) { $metadata = wp_read_video_metadata( $file ); $support = current_theme_supports( 'post-thumbnails', 'attachment:video' ) || post_type_supports( 'attachment:video', 'thumbnail' ); } elseif ( wp_attachment_is( 'audio', $attachment ) ) { $metadata = wp_read_audio_metadata( $file ); $support = current_theme_supports( 'post-thumbnails', 'attachment:audio' ) || post_type_supports( 'attachment:audio', 'thumbnail' ); } if ( $support && ! empty( $metadata['image']['data'] ) ) { // Check for existing cover. $hash = md5( $metadata['image']['data'] ); $posts = get_posts( array( 'fields' => 'ids', 'post_type' => 'attachment', 'post_mime_type' => $metadata['image']['mime'], 'post_status' => 'inherit', 'posts_per_page' => 1, 'meta_key' => '_cover_hash', 'meta_value' => $hash ) ); $exists = reset( $posts ); if ( ! empty( $exists ) ) { update_post_meta( $attachment_id, '_thumbnail_id', $exists ); } else { $ext = '.jpg'; switch ( $metadata['image']['mime'] ) { case 'image/gif': $ext = '.gif'; break; case 'image/png': $ext = '.png'; break; } $basename = str_replace( '.', '-', basename( $file ) ) . '-image' . $ext; $uploaded = wp_upload_bits( $basename, '', $metadata['image']['data'] ); if ( false === $uploaded['error'] ) { $image_attachment = array( 'post_mime_type' => $metadata['image']['mime'], 'post_type' => 'attachment', 'post_content' => '', ); /** * Filters the parameters for the attachment thumbnail creation. * * @since 3.9.0 * * @param array $image_attachment An array of parameters to create the thumbnail. * @param array $metadata Current attachment metadata. * @param array $uploaded An array containing the thumbnail path and url. */ $image_attachment = apply_filters( 'attachment_thumbnail_args', $image_attachment, $metadata, $uploaded ); $sub_attachment_id = wp_insert_attachment( $image_attachment, $uploaded['file'] ); add_post_meta( $sub_attachment_id, '_cover_hash', $hash ); $attach_data = wp_generate_attachment_metadata( $sub_attachment_id, $uploaded['file'] ); wp_update_attachment_metadata( $sub_attachment_id, $attach_data ); update_post_meta( $attachment_id, '_thumbnail_id', $sub_attachment_id ); } } } // Try to create image thumbnails for PDFs else if ( 'application/pdf' === $mime_type ) { $fallback_sizes = array( 'thumbnail', 'medium', 'large', ); /** * Filters the image sizes generated for non-image mime types. * * @since 4.7.0 * * @param array $fallback_sizes An array of image size names. * @param array $metadata Current attachment metadata. */ $fallback_sizes = apply_filters( 'fallback_intermediate_image_sizes', $fallback_sizes, $metadata ); $sizes = array(); $_wp_additional_image_sizes = wp_get_additional_image_sizes(); foreach ( $fallback_sizes as $s ) { if ( isset( $_wp_additional_image_sizes[ $s ]['width'] ) ) { $sizes[ $s ]['width'] = intval( $_wp_additional_image_sizes[ $s ]['width'] ); } else { $sizes[ $s ]['width'] = get_option( "{$s}_size_w" ); } if ( isset( $_wp_additional_image_sizes[ $s ]['height'] ) ) { $sizes[ $s ]['height'] = intval( $_wp_additional_image_sizes[ $s ]['height'] ); } else { $sizes[ $s ]['height'] = get_option( "{$s}_size_h" ); } if ( isset( $_wp_additional_image_sizes[ $s ]['crop'] ) ) { $sizes[ $s ]['crop'] = $_wp_additional_image_sizes[ $s ]['crop']; } else { // Force thumbnails to be soft crops. if ( 'thumbnail' !== $s ) { $sizes[ $s ]['crop'] = get_option( "{$s}_crop" ); } } } // Only load PDFs in an image editor if we're processing sizes. if ( ! empty( $sizes ) ) { $editor = wp_get_image_editor( $file ); if ( ! is_wp_error( $editor ) ) { // No support for this type of file /* * PDFs may have the same file filename as JPEGs. * Ensure the PDF preview image does not overwrite any JPEG images that already exist. */ $dirname = dirname( $file ) . '/'; $ext = '.' . pathinfo( $file, PATHINFO_EXTENSION ); $preview_file = $dirname . wp_unique_filename( $dirname, wp_basename( $file, $ext ) . '-pdf.jpg' ); $uploaded = $editor->save( $preview_file, 'image/jpeg' ); unset( $editor ); // Resize based on the full size image, rather than the source. if ( ! is_wp_error( $uploaded ) ) { $editor = wp_get_image_editor( $uploaded['path'] ); unset( $uploaded['path'] ); if ( ! is_wp_error( $editor ) ) { $metadata['sizes'] = $editor->multi_resize( $sizes ); $metadata['sizes']['full'] = $uploaded; } } } } } // Remove the blob of binary data from the array. if ( $metadata ) { unset( $metadata['image']['data'] ); } /** * Filters the generated attachment meta data. * * @since 2.1.0 * * @param array $metadata An array of attachment meta data. * @param int $attachment_id Current attachment ID. */ return apply_filters( 'wp_generate_attachment_metadata', $metadata, $attachment_id ); } /** * Convert a fraction string to a decimal. * * @since 2.5.0 * * @param string $str * @return int|float */ function wp_exif_frac2dec($str) { @list( $n, $d ) = explode( '/', $str ); if ( !empty($d) ) return $n / $d; return $str; } /** * Convert the exif date format to a unix timestamp. * * @since 2.5.0 * * @param string $str * @return int */ function wp_exif_date2ts($str) { @list( $date, $time ) = explode( ' ', trim($str) ); @list( $y, $m, $d ) = explode( ':', $date ); return strtotime( "{$y}-{$m}-{$d} {$time}" ); } /** * Get extended image metadata, exif or iptc as available. * * Retrieves the EXIF metadata aperture, credit, camera, caption, copyright, iso * created_timestamp, focal_length, shutter_speed, and title. * * The IPTC metadata that is retrieved is APP13, credit, byline, created date * and time, caption, copyright, and title. Also includes FNumber, Model, * DateTimeDigitized, FocalLength, ISOSpeedRatings, and ExposureTime. * * @todo Try other exif libraries if available. * @since 2.5.0 * * @param string $file * @return bool|array False on failure. Image metadata array on success. */ function wp_read_image_metadata( $file ) { if ( ! file_exists( $file ) ) return false; list( , , $image_type ) = @getimagesize( $file ); /* * EXIF contains a bunch of data we'll probably never need formatted in ways * that are difficult to use. We'll normalize it and just extract the fields * that are likely to be useful. Fractions and numbers are converted to * floats, dates to unix timestamps, and everything else to strings. */ $meta = array( 'aperture' => 0, 'credit' => '', 'camera' => '', 'caption' => '', 'created_timestamp' => 0, 'copyright' => '', 'focal_length' => 0, 'iso' => 0, 'shutter_speed' => 0, 'title' => '', 'orientation' => 0, 'keywords' => array(), ); $iptc = array(); /* * Read IPTC first, since it might contain data not available in exif such * as caption, description etc. */ if ( is_callable( 'iptcparse' ) ) { @getimagesize( $file, $info ); if ( ! empty( $info['APP13'] ) ) { $iptc = @iptcparse( $info['APP13'] ); // Headline, "A brief synopsis of the caption." if ( ! empty( $iptc['2#105'][0] ) ) { $meta['title'] = trim( $iptc['2#105'][0] ); /* * Title, "Many use the Title field to store the filename of the image, * though the field may be used in many ways." */ } elseif ( ! empty( $iptc['2#005'][0] ) ) { $meta['title'] = trim( $iptc['2#005'][0] ); } if ( ! empty( $iptc['2#120'][0] ) ) { // description / legacy caption $caption = trim( $iptc['2#120'][0] ); mbstring_binary_safe_encoding(); $caption_length = strlen( $caption ); reset_mbstring_encoding(); if ( empty( $meta['title'] ) && $caption_length < 80 ) { // Assume the title is stored in 2:120 if it's short. $meta['title'] = $caption; } $meta['caption'] = $caption; } if ( ! empty( $iptc['2#110'][0] ) ) // credit $meta['credit'] = trim( $iptc['2#110'][0] ); elseif ( ! empty( $iptc['2#080'][0] ) ) // creator / legacy byline $meta['credit'] = trim( $iptc['2#080'][0] ); if ( ! empty( $iptc['2#055'][0] ) && ! empty( $iptc['2#060'][0] ) ) // created date and time $meta['created_timestamp'] = strtotime( $iptc['2#055'][0] . ' ' . $iptc['2#060'][0] ); if ( ! empty( $iptc['2#116'][0] ) ) // copyright $meta['copyright'] = trim( $iptc['2#116'][0] ); if ( ! empty( $iptc['2#025'][0] ) ) { // keywords array $meta['keywords'] = array_values( $iptc['2#025'] ); } } } $exif = array(); /** * Filters the image types to check for exif data. * * @since 2.5.0 * * @param array $image_types Image types to check for exif data. */ $exif_image_types = apply_filters( 'wp_read_image_metadata_types', array( IMAGETYPE_JPEG, IMAGETYPE_TIFF_II, IMAGETYPE_TIFF_MM ) ); if ( is_callable( 'exif_read_data' ) && in_array( $image_type, $exif_image_types ) ) { $exif = @exif_read_data( $file ); if ( ! empty( $exif['ImageDescription'] ) ) { mbstring_binary_safe_encoding(); $description_length = strlen( $exif['ImageDescription'] ); reset_mbstring_encoding(); if ( empty( $meta['title'] ) && $description_length < 80 ) { // Assume the title is stored in ImageDescription $meta['title'] = trim( $exif['ImageDescription'] ); } if ( empty( $meta['caption'] ) && ! empty( $exif['COMPUTED']['UserComment'] ) ) { $meta['caption'] = trim( $exif['COMPUTED']['UserComment'] ); } if ( empty( $meta['caption'] ) ) { $meta['caption'] = trim( $exif['ImageDescription'] ); } } elseif ( empty( $meta['caption'] ) && ! empty( $exif['Comments'] ) ) { $meta['caption'] = trim( $exif['Comments'] ); } if ( empty( $meta['credit'] ) ) { if ( ! empty( $exif['Artist'] ) ) { $meta['credit'] = trim( $exif['Artist'] ); } elseif ( ! empty($exif['Author'] ) ) { $meta['credit'] = trim( $exif['Author'] ); } } if ( empty( $meta['copyright'] ) && ! empty( $exif['Copyright'] ) ) { $meta['copyright'] = trim( $exif['Copyright'] ); } if ( ! empty( $exif['FNumber'] ) ) { $meta['aperture'] = round( wp_exif_frac2dec( $exif['FNumber'] ), 2 ); } if ( ! empty( $exif['Model'] ) ) { $meta['camera'] = trim( $exif['Model'] ); } if ( empty( $meta['created_timestamp'] ) && ! empty( $exif['DateTimeDigitized'] ) ) { $meta['created_timestamp'] = wp_exif_date2ts( $exif['DateTimeDigitized'] ); } if ( ! empty( $exif['FocalLength'] ) ) { $meta['focal_length'] = (string) wp_exif_frac2dec( $exif['FocalLength'] ); } if ( ! empty( $exif['ISOSpeedRatings'] ) ) { $meta['iso'] = is_array( $exif['ISOSpeedRatings'] ) ? reset( $exif['ISOSpeedRatings'] ) : $exif['ISOSpeedRatings']; $meta['iso'] = trim( $meta['iso'] ); } if ( ! empty( $exif['ExposureTime'] ) ) { $meta['shutter_speed'] = (string) wp_exif_frac2dec( $exif['ExposureTime'] ); } if ( ! empty( $exif['Orientation'] ) ) { $meta['orientation'] = $exif['Orientation']; } } foreach ( array( 'title', 'caption', 'credit', 'copyright', 'camera', 'iso' ) as $key ) { if ( $meta[ $key ] && ! seems_utf8( $meta[ $key ] ) ) { $meta[ $key ] = utf8_encode( $meta[ $key ] ); } } foreach ( $meta['keywords'] as $key => $keyword ) { if ( ! seems_utf8( $keyword ) ) { $meta['keywords'][ $key ] = utf8_encode( $keyword ); } } $meta = wp_kses_post_deep( $meta ); /** * Filters the array of meta data read from an image's exif data. * * @since 2.5.0 * @since 4.4.0 The `$iptc` parameter was added. * @since 5.0.0 The `$exif` parameter was added. * * @param array $meta Image meta data. * @param string $file Path to image file. * @param int $image_type Type of image, one of the `IMAGETYPE_XXX` constants. * @param array $iptc IPTC data. * @param array $exif EXIF data. */ return apply_filters( 'wp_read_image_metadata', $meta, $file, $image_type, $iptc, $exif ); } /** * Validate that file is an image. * * @since 2.5.0 * * @param string $path File path to test if valid image. * @return bool True if valid image, false if not valid image. */ function file_is_valid_image($path) { $size = @getimagesize($path); return !empty($size); } /** * Validate that file is suitable for displaying within a web page. * * @since 2.5.0 * * @param string $path File path to test. * @return bool True if suitable, false if not suitable. */ function file_is_displayable_image($path) { $displayable_image_types = array( IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_BMP ); $info = @getimagesize( $path ); if ( empty( $info ) ) { $result = false; } elseif ( ! in_array( $info[2], $displayable_image_types ) ) { $result = false; } else { $result = true; } /** * Filters whether the current image is displayable in the browser. * * @since 2.5.0 * * @param bool $result Whether the image can be displayed. Default true. * @param string $path Path to the image. */ return apply_filters( 'file_is_displayable_image', $result, $path ); } /** * Load an image resource for editing. * * @since 2.9.0 * * @param string $attachment_id Attachment ID. * @param string $mime_type Image mime type. * @param string $size Optional. Image size, defaults to 'full'. * @return resource|false The resulting image resource on success, false on failure. */ function load_image_to_edit( $attachment_id, $mime_type, $size = 'full' ) { $filepath = _load_image_to_edit_path( $attachment_id, $size ); if ( empty( $filepath ) ) return false; switch ( $mime_type ) { case 'image/jpeg': $image = imagecreatefromjpeg($filepath); break; case 'image/png': $image = imagecreatefrompng($filepath); break; case 'image/gif': $image = imagecreatefromgif($filepath); break; default: $image = false; break; } if ( is_resource($image) ) { /** * Filters the current image being loaded for editing. * * @since 2.9.0 * * @param resource $image Current image. * @param string $attachment_id Attachment ID. * @param string $size Image size. */ $image = apply_filters( 'load_image_to_edit', $image, $attachment_id, $size ); if ( function_exists('imagealphablending') && function_exists('imagesavealpha') ) { imagealphablending($image, false); imagesavealpha($image, true); } } return $image; } /** * Retrieve the path or url of an attachment's attached file. * * If the attached file is not present on the local filesystem (usually due to replication plugins), * then the url of the file is returned if url fopen is supported. * * @since 3.4.0 * @access private * * @param string $attachment_id Attachment ID. * @param string $size Optional. Image size, defaults to 'full'. * @return string|false File path or url on success, false on failure. */ function _load_image_to_edit_path( $attachment_id, $size = 'full' ) { $filepath = get_attached_file( $attachment_id ); if ( $filepath && file_exists( $filepath ) ) { if ( 'full' != $size && ( $data = image_get_intermediate_size( $attachment_id, $size ) ) ) { /** * Filters the path to the current image. * * The filter is evaluated for all image sizes except 'full'. * * @since 3.1.0 * * @param string $path Path to the current image. * @param string $attachment_id Attachment ID. * @param string $size Size of the image. */ $filepath = apply_filters( 'load_image_to_edit_filesystempath', path_join( dirname( $filepath ), $data['file'] ), $attachment_id, $size ); } } elseif ( function_exists( 'fopen' ) && true == ini_get( 'allow_url_fopen' ) ) { /** * Filters the image URL if not in the local filesystem. * * The filter is only evaluated if fopen is enabled on the server. * * @since 3.1.0 * * @param string $image_url Current image URL. * @param string $attachment_id Attachment ID. * @param string $size Size of the image. */ $filepath = apply_filters( 'load_image_to_edit_attachmenturl', wp_get_attachment_url( $attachment_id ), $attachment_id, $size ); } /** * Filters the returned path or URL of the current image. * * @since 2.9.0 * * @param string|bool $filepath File path or URL to current image, or false. * @param string $attachment_id Attachment ID. * @param string $size Size of the image. */ return apply_filters( 'load_image_to_edit_path', $filepath, $attachment_id, $size ); } /** * Copy an existing image file. * * @since 3.4.0 * @access private * * @param string $attachment_id Attachment ID. * @return string|false New file path on success, false on failure. */ function _copy_image_file( $attachment_id ) { $dst_file = $src_file = get_attached_file( $attachment_id ); if ( ! file_exists( $src_file ) ) $src_file = _load_image_to_edit_path( $attachment_id ); if ( $src_file ) { $dst_file = str_replace( basename( $dst_file ), 'copy-' . basename( $dst_file ), $dst_file ); $dst_file = dirname( $dst_file ) . '/' . wp_unique_filename( dirname( $dst_file ), basename( $dst_file ) ); /* * The directory containing the original file may no longer * exist when using a replication plugin. */ wp_mkdir_p( dirname( $dst_file ) ); if ( ! @copy( $src_file, $dst_file ) ) $dst_file = false; } else { $dst_file = false; } return $dst_file; }
mit
akoeplinger/referencesource
System.ServiceModel/System/ServiceModel/Security/MessageSecurityException.cs
1868
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Security { using System.Collections; using System.ServiceModel.Channels; using System.ServiceModel; using System.IO; using System.Runtime.Serialization; using System.Security.Cryptography; using System.Security.Permissions; using System.Text; using System.Xml; using System.Security; using System.Runtime; [Serializable] public class MessageSecurityException : CommunicationException { MessageFault fault; bool isReplay = false; public MessageSecurityException() : base() { } public MessageSecurityException(String message) : base(message) { } public MessageSecurityException(String message, Exception innerException) : base(message, innerException) { } protected MessageSecurityException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } internal MessageSecurityException(string message, Exception innerException, MessageFault fault) : base(message, innerException) { this.fault = fault; } internal MessageSecurityException(String message, bool isReplay) : base(message) { this.isReplay = isReplay; } internal bool ReplayDetected { get { return this.isReplay; } } internal MessageFault Fault { get { return this.fault; } } } }
mit
srini2174/codelite
Plugin/EnvVarImporterDlg.cpp
1055
#include "EnvVarImporterDlg.h" EnvVarImporterDlg::EnvVarImporterDlg(wxWindow* parent, const wxString& projectName, const wxString& cfgName, std::set<wxString> listEnvVar, BuildConfigPtr le_conf, bool* showDlg) : EnvVarImporterDlgBase(parent) , le_conf(le_conf) , showDlg(showDlg) { wxString value = wxT(""); for(wxString envVar : listEnvVar) { value += envVar + wxT("=?") + wxT("\n"); } m_projectName->SetLabel(projectName); m_confName->SetLabel(cfgName); m_envVars->SetValue(value); } EnvVarImporterDlg::~EnvVarImporterDlg() { } void EnvVarImporterDlg::OnImport(wxCommandEvent& event) { le_conf->SetEnvvars(m_envVars->GetValue()); Close(); } void EnvVarImporterDlg::OnContinue(wxCommandEvent& event) { Close(); } void EnvVarImporterDlg::OnSkip(wxCommandEvent& event) { *showDlg = false; Close(); }
gpl-2.0
Unrepentant-Atheist/mame
3rdparty/genie/src/actions/cmake/cmake_workspace.lua
302
-- -- _cmake.lua -- Define the CMake action(s). -- Copyright (c) 2015 Miodrag Milanovic -- function premake.cmake.workspace(sln) _p('cmake_minimum_required(VERSION 2.8.4)') _p('') for i,prj in ipairs(sln.projects) do local name = premake.esc(prj.name) _p('add_subdirectory(%s)', name) end end
gpl-2.0
MaxYaroshenko/3rdarea
app/code/core/Mage/Checkout/Model/Cart/Shipping/Api/V2.php
1208
<?php /** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@magentocommerce.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magentocommerce.com for more information. * * @category Mage * @package Mage_Checkout * @copyright Copyright (c) 2013 Magento Inc. (http://www.magentocommerce.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ /** * Shopping cart api * * @category Mage * @package Mage_Checkout * @author Magento Core Team <core@magentocommerce.com> */ class Mage_Checkout_Model_Cart_Shipping_Api_V2 extends Mage_Checkout_Model_Cart_Shipping_Api { }
gpl-2.0
Sunella/Jupiter
wp-content/themes/jupiter/woocommerce/single-product/add-to-cart/quantity.php
696
<?php /** * Single product quantity inputs * * @author WooThemes * @package WooCommerce/Templates * @version 2.0.0 */ if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly ?> <div class="quantity"><input type="number" step="<?php echo esc_attr( $step ); ?>" <?php if ( is_numeric( $min_value ) ) : ?>min="<?php echo esc_attr( $min_value ); ?>"<?php endif; ?> <?php if ( is_numeric( $max_value ) ) : ?>max="<?php echo esc_attr( $max_value ); ?>"<?php endif; ?> name="<?php echo esc_attr( $input_name ); ?>" value="<?php echo esc_attr( $input_value ); ?>" title="<?php _ex( 'Qty', 'Product quantity input tooltip', 'mk_framework' ) ?>" class="input-text qty text" /></div>
gpl-2.0
dmlloyd/openjdk-modules
jaxp/test/javax/xml/jaxp/unittest/transform/Bug6565260.java
2525
/* * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package transform; import java.io.StringWriter; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.testng.Assert; import org.testng.annotations.Listeners; import org.testng.annotations.Test; /* * @test * @bug 6565260 * @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest * @run testng/othervm -DrunSecMngr=true transform.Bug6565260 * @run testng/othervm transform.Bug6565260 * @summary Test use-attribute-sets attribute is not used for the root node. */ @Listeners({jaxp.library.FilePolicy.class}) public class Bug6565260 { @Test public void test() { try { String xmlFile = "attribset27.xml"; String xslFile = "attribset27.xsl"; TransformerFactory tFactory = TransformerFactory.newInstance(); // tFactory.setAttribute("generate-translet", Boolean.TRUE); Transformer t = tFactory.newTransformer(new StreamSource(getClass().getResourceAsStream(xslFile))); StringWriter sw = new StringWriter(); t.transform(new StreamSource(getClass().getResourceAsStream(xmlFile)), new StreamResult(sw)); String s = sw.getBuffer().toString(); Assert.assertFalse(s.contains("color") || s.contains("font-size")); } catch (Exception e) { Assert.fail(e.getMessage()); } } }
gpl-2.0
drupal-ukraine/csua_d8
drupal/core/modules/system/src/Tests/Entity/EntityQueryTest.php
16555
<?php /** * @file * Definition of Drupal\system\Tests\Entity\EntityQueryTest. */ namespace Drupal\system\Tests\Entity; use Drupal\Core\Entity\EntityStorageInterface; use Drupal\language\Entity\ConfigurableLanguage; use Symfony\Component\HttpFoundation\Request; /** * Tests Entity Query functionality. * * @group Entity */ class EntityQueryTest extends EntityUnitTestBase { /** * Modules to enable. * * @var array */ public static $modules = array('field_test', 'language'); /** * @var array */ protected $queryResults; /** * @var \Drupal\Core\Entity\Query\QueryFactory */ protected $factory; /** * Field name for the greetings field. * * @var string */ public $greetings; /** * Field name for the greetings field. * * @var string */ public $figures; protected function setUp() { parent::setUp(); $this->installEntitySchema('entity_test_mulrev'); $this->installConfig(array('language')); $figures = drupal_strtolower($this->randomMachineName()); $greetings = drupal_strtolower($this->randomMachineName()); foreach (array($figures => 'shape', $greetings => 'text') as $field_name => $field_type) { $field_storage = entity_create('field_storage_config', array( 'field_name' => $field_name, 'entity_type' => 'entity_test_mulrev', 'type' => $field_type, 'cardinality' => 2, 'translatable' => TRUE, )); $field_storage->save(); $field_storages[] = $field_storage; } $bundles = array(); for ($i = 0; $i < 2; $i++) { // For the sake of tablesort, make sure the second bundle is higher than // the first one. Beware: MySQL is not case sensitive. do { $bundle = $this->randomMachineName(); } while ($bundles && strtolower($bundles[0]) >= strtolower($bundle)); entity_test_create_bundle($bundle); foreach ($field_storages as $field_storage) { entity_create('field_config', array( 'field_storage' => $field_storage, 'bundle' => $bundle, ))->save(); } $bundles[] = $bundle; } // Each unit is a list of field name, langcode and a column-value array. $units[] = array($figures, 'en', array( 'color' => 'red', 'shape' => 'triangle', )); $units[] = array($figures, 'en', array( 'color' => 'blue', 'shape' => 'circle', )); // To make it easier to test sorting, the greetings get formats according // to their langcode. $units[] = array($greetings, 'tr', array( 'value' => 'merhaba', 'format' => 'format-tr' )); $units[] = array($greetings, 'pl', array( 'value' => 'siema', 'format' => 'format-pl' )); // Make these languages available to the greetings field. ConfigurableLanguage::createFromLangcode('tr')->save(); ConfigurableLanguage::createFromLangcode('pl')->save(); // Calculate the cartesian product of the unit array by looking at the // bits of $i and add the unit at the bits that are 1. For example, // decimal 13 is binary 1101 so unit 3,2 and 0 will be added to the // entity. for ($i = 1; $i <= 15; $i++) { $entity = entity_create('entity_test_mulrev', array( 'type' => $bundles[$i & 1], 'name' => $this->randomMachineName(), 'langcode' => 'en', )); // Make sure the name is set for every language that we might create. foreach (array('tr', 'pl') as $langcode) { $entity->getTranslation($langcode)->name = $this->randomMachineName(); } foreach (array_reverse(str_split(decbin($i))) as $key => $bit) { if ($bit) { list($field_name, $langcode, $values) = $units[$key]; $entity->getTranslation($langcode)->{$field_name}[] = $values; } } $entity->save(); } $this->figures = $figures; $this->greetings = $greetings; $this->factory = \Drupal::service('entity.query'); } /** * Test basic functionality. */ function testEntityQuery() { $greetings = $this->greetings; $figures = $this->figures; $this->queryResults = $this->factory->get('entity_test_mulrev') ->exists($greetings, 'tr') ->condition("$figures.color", 'red') ->sort('id') ->execute(); // As unit 0 was the red triangle and unit 2 was the turkish greeting, // bit 0 and bit 2 needs to be set. $this->assertResult(5, 7, 13, 15); $query = $this->factory->get('entity_test_mulrev', 'OR') ->exists($greetings, 'tr') ->condition("$figures.color", 'red') ->sort('id'); $count_query = clone $query; $this->assertEqual(12, $count_query->count()->execute()); $this->queryResults = $query->execute(); // Now bit 0 (1, 3, 5, 7, 9, 11, 13, 15) or bit 2 (4, 5, 6, 7, 12, 13, 14, // 15) needs to be set. $this->assertResult(1, 3, 4, 5, 6, 7, 9, 11, 12, 13, 14, 15); // Test cloning of query conditions. $query = $this->factory->get('entity_test_mulrev') ->condition("$figures.color", 'red') ->sort('id'); $cloned_query = clone $query; $cloned_query ->condition("$figures.shape", 'circle'); // Bit 0 (1, 3, 5, 7, 9, 11, 13, 15) needs to be set. $this->queryResults = $query->execute(); $this->assertResult(1, 3, 5, 7, 9, 11, 13, 15); // No red color has a circle shape. $this->queryResults = $cloned_query->execute(); $this->assertResult(); $query = $this->factory->get('entity_test_mulrev'); $group = $query->orConditionGroup() ->exists($greetings, 'tr') ->condition("$figures.color", 'red'); $this->queryResults = $query ->condition($group) ->condition("$greetings.value", 'sie', 'STARTS_WITH') ->sort('revision_id') ->execute(); // Bit 3 and (bit 0 or 2) -- the above 8 part of the above. $this->assertResult(9, 11, 12, 13, 14, 15); // No figure has both the colors blue and red at the same time. $this->queryResults = $this->factory->get('entity_test_mulrev') ->condition("$figures.color", 'blue') ->condition("$figures.color", 'red') ->sort('id') ->execute(); $this->assertResult(); // But an entity might have a red and a blue figure both. $query = $this->factory->get('entity_test_mulrev'); $group_blue = $query->andConditionGroup()->condition("$figures.color", 'blue'); $group_red = $query->andConditionGroup()->condition("$figures.color", 'red'); $this->queryResults = $query ->condition($group_blue) ->condition($group_red) ->sort('revision_id') ->execute(); // Unit 0 and unit 1, so bits 0 1. $this->assertResult(3, 7, 11, 15); $this->queryResults = $this->factory->get('entity_test_mulrev') ->exists("$figures.color") ->notExists("$greetings.value") ->sort('id') ->execute(); // Bit 0 or 1 is on but 2 and 3 are not. $this->assertResult(1, 2, 3); // Now update the 'merhaba' string to xsiemax which is not a meaningful // word but allows us to test revisions and string operations. $ids = $this->factory->get('entity_test_mulrev') ->condition("$greetings.value", 'merhaba') ->sort('id') ->execute(); $entities = entity_load_multiple('entity_test_mulrev', $ids); foreach ($entities as $entity) { $entity->setNewRevision(); $entity->getTranslation('tr')->$greetings->value = 'xsiemax'; $entity->save(); } // When querying current revisions, this string is no longer found. $this->queryResults = $this->factory->get('entity_test_mulrev') ->condition("$greetings.value", 'merhaba') ->execute(); $this->assertResult(); $this->queryResults = $this->factory->get('entity_test_mulrev') ->condition("$greetings.value", 'merhaba') ->age(EntityStorageInterface::FIELD_LOAD_REVISION) ->sort('revision_id') ->execute(); // Bit 2 needs to be set. // The keys must be 16-23 because the first batch stopped at 15 so the // second started at 16 and eight entities were saved. $assert = $this->assertRevisionResult(range(16, 23), array(4, 5, 6, 7, 12, 13, 14, 15)); $results = $this->factory->get('entity_test_mulrev') ->condition("$greetings.value", 'siema', 'CONTAINS') ->sort('id') ->execute(); // This is the same as the previous one because xsiemax replaced merhaba // but also it contains the entities that siema originally but not // merhaba. $assert = array_slice($assert, 0, 4, TRUE) + array(8 => '8', 9 => '9', 10 => '10', 11 => '11') + array_slice($assert, 4, 4, TRUE); $this->assertIdentical($results, $assert); $results = $this->factory->get('entity_test_mulrev') ->condition("$greetings.value", 'siema', 'STARTS_WITH') ->sort('revision_id') ->execute(); // Now we only get the ones that originally were siema, entity id 8 and // above. $this->assertIdentical($results, array_slice($assert, 4, 8, TRUE)); $results = $this->factory->get('entity_test_mulrev') ->condition("$greetings.value", 'a', 'ENDS_WITH') ->sort('revision_id') ->execute(); // It is very important that we do not get the ones which only have // xsiemax despite originally they were merhaba, ie. ended with a. $this->assertIdentical($results, array_slice($assert, 4, 8, TRUE)); $results = $this->factory->get('entity_test_mulrev') ->condition("$greetings.value", 'a', 'ENDS_WITH') ->age(EntityStorageInterface::FIELD_LOAD_REVISION) ->sort('id') ->execute(); // Now we get everything. $this->assertIdentical($results, $assert); } /** * Test sort(). * * Warning: this is complicated. */ function testSort() { $greetings = $this->greetings; $figures = $this->figures; // Order up and down on a number. $this->queryResults = $this->factory->get('entity_test_mulrev') ->sort('id') ->execute(); $this->assertResult(range(1, 15)); $this->queryResults = $this->factory->get('entity_test_mulrev') ->sort('id', 'DESC') ->execute(); $this->assertResult(range(15, 1)); $query = $this->factory->get('entity_test_mulrev') ->sort("$figures.color") ->sort("$greetings.format") ->sort('id'); // As we do not have any conditions, here are the possible colors and // language codes, already in order, with the first occurrence of the // entity id marked with *: // 8 NULL pl * // 12 NULL pl * // 4 NULL tr * // 12 NULL tr // 2 blue NULL * // 3 blue NULL * // 10 blue pl * // 11 blue pl * // 14 blue pl * // 15 blue pl * // 6 blue tr * // 7 blue tr * // 14 blue tr // 15 blue tr // 1 red NULL // 3 red NULL // 9 red pl * // 11 red pl // 13 red pl * // 15 red pl // 5 red tr * // 7 red tr // 13 red tr // 15 red tr $count_query = clone $query; $this->assertEqual(15, $count_query->count()->execute()); $this->queryResults = $query->execute(); $this->assertResult(8, 12, 4, 2, 3, 10, 11, 14, 15, 6, 7, 1, 9, 13, 5); // Test the pager by setting element #1 to page 2 with a page size of 4. // Results will be #8-12 from above. $request = Request::createFromGlobals(); $request->query->replace(array( 'page' => '0,2', )); \Drupal::getContainer()->get('request_stack')->push($request); $this->queryResults = $this->factory->get('entity_test_mulrev') ->sort("$figures.color") ->sort("$greetings.format") ->sort('id') ->pager(4, 1) ->execute(); $this->assertResult(15, 6, 7, 1); // Now test the reversed order. $query = $this->factory->get('entity_test_mulrev') ->sort("$figures.color", 'DESC') ->sort("$greetings.format", 'DESC') ->sort('id', 'DESC'); $count_query = clone $query; $this->assertEqual(15, $count_query->count()->execute()); $this->queryResults = $query->execute(); $this->assertResult(15, 13, 7, 5, 11, 9, 3, 1, 14, 6, 10, 2, 12, 4, 8); } /** * Test tablesort(). */ public function testTableSort() { // While ordering on bundles do not give us a definite order, we can still // assert that all entities from one bundle are after the other as the // order dictates. $request = Request::createFromGlobals(); $request->query->replace(array( 'sort' => 'asc', 'order' => 'Type', )); \Drupal::getContainer()->get('request_stack')->push($request); $header = array( 'id' => array('data' => 'Id', 'specifier' => 'id'), 'type' => array('data' => 'Type', 'specifier' => 'type'), ); $this->queryResults = array_values($this->factory->get('entity_test_mulrev') ->tableSort($header) ->execute()); $this->assertBundleOrder('asc'); $request->query->add(array( 'sort' => 'desc', )); \Drupal::getContainer()->get('request_stack')->push($request); $header = array( 'id' => array('data' => 'Id', 'specifier' => 'id'), 'type' => array('data' => 'Type', 'specifier' => 'type'), ); $this->queryResults = array_values($this->factory->get('entity_test_mulrev') ->tableSort($header) ->execute()); $this->assertBundleOrder('desc'); // Ordering on ID is definite, however. $request->query->add(array( 'order' => 'Id', )); \Drupal::getContainer()->get('request_stack')->push($request); $this->queryResults = $this->factory->get('entity_test_mulrev') ->tableSort($header) ->execute(); $this->assertResult(range(15, 1)); } /** * Test that count queries are separated across entity types. */ public function testCount() { // Create a field with the same name in a different entity type. $field_name = $this->figures; $field_storage = entity_create('field_storage_config', array( 'field_name' => $field_name, 'entity_type' => 'entity_test', 'type' => 'shape', 'cardinality' => 2, 'translatable' => TRUE, )); $field_storage->save(); $bundle = $this->randomMachineName(); entity_create('field_config', array( 'field_storage' => $field_storage, 'bundle' => $bundle, ))->save(); $entity = entity_create('entity_test', array( 'id' => 1, 'type' => $bundle, )); $entity->enforceIsNew(); $entity->save(); // As the single entity of this type we just saved does not have a value // in the color field, the result should be 0. $count = $this->factory->get('entity_test') ->exists("$field_name.color") ->count() ->execute(); $this->assertFalse($count); } protected function assertResult() { $assert = array(); $expected = func_get_args(); if ($expected && is_array($expected[0])) { $expected = $expected[0]; } foreach ($expected as $binary) { $assert[$binary] = strval($binary); } $this->assertIdentical($this->queryResults, $assert); } protected function assertRevisionResult($keys, $expected) { $assert = array(); foreach ($expected as $key => $binary) { $assert[$keys[$key]] = strval($binary); } $this->assertIdentical($this->queryResults, $assert); return $assert; } protected function assertBundleOrder($order) { // This loop is for bundle1 entities. for ($i = 1; $i <= 15; $i +=2) { $ok = TRUE; $index1 = array_search($i, $this->queryResults); $this->assertNotIdentical($index1, FALSE, "$i found at $index1."); // This loop is for bundle2 entities. for ($j = 2; $j <= 15; $j += 2) { if ($ok) { if ($order == 'asc') { $ok = $index1 > array_search($j, $this->queryResults); } else { $ok = $index1 < array_search($j, $this->queryResults); } } } $this->assertTrue($ok, format_string("$i is after all entities in bundle2")); } } /** * Test adding a tag and metadata to the Entity query object. * * The tags and metadata should propagate to the SQL query object. */ function testMetaData() { $query = \Drupal::entityQuery('entity_test_mulrev'); $query ->addTag('efq_metadata_test') ->addMetaData('foo', 'bar') ->execute(); global $efq_test_metadata; $this->assertEqual($efq_test_metadata, 'bar', 'Tag and metadata propagated to the SQL query object.'); } }
gpl-2.0
bbqchickenrobot/de4dot
de4dot.code/deobfuscators/Goliath_NET/IntegerDecrypter.cs
1646
/* Copyright (C) 2011-2012 de4dot@gmail.com This file is part of de4dot. de4dot is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. de4dot is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with de4dot. If not, see <http://www.gnu.org/licenses/>. */ using System; using Mono.Cecil; using de4dot.blocks; namespace de4dot.code.deobfuscators.Goliath_NET { class IntegerDecrypter : DecrypterBase { public IntegerDecrypter(ModuleDefinition module) : base(module) { } static string[] requiredFields = new string[] { "System.Byte[]", "System.Collections.Generic.Dictionary`2<System.Int32,System.Object>", }; protected override bool checkDecrypterType(TypeDefinition type) { return new FieldTypes(type).exactly(requiredFields); } protected override bool checkDelegateInvokeMethod(MethodDefinition invokeMethod) { return DotNetUtils.isMethod(invokeMethod, "System.Object", "(System.Int32)"); } public int decrypt(MethodDefinition method) { var info = getInfo(method); decryptedReader.BaseStream.Position = info.offset; int len = decryptedReader.ReadInt32(); return BitConverter.ToInt32(decryptedReader.ReadBytes(len), 0); } } }
gpl-3.0
ngvoice/android-client
phone/jni/webrtc/sources/test/fuzz/peerconnection/peerconnection_fuzz.py
5989
#!/usr/bin/env python # Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. # # Use of this source code is governed by a BSD-style license # that can be found in the LICENSE file in the root of the source # tree. An additional intellectual property rights grant can be found # in the file PATENTS. All contributing project authors may # be found in the AUTHORS file in the root of the source tree. import random import re import string import unicodedata from common.fuzz_parameters import FillInParameter, MissingParameterException from common.random_javascript import * def _ArrayOfRandomRolls(num_rolls): return str([random.random() for x in xrange(num_rolls)]) def _RandomAudioOrVideo(): roll = random.random() if roll < 0.5: return '{ video: true, audio:true }' elif roll < 0.7: return '{ video: true, audio: false }' elif roll < 0.9: return '{ video: false, audio: true }' else: return '{ video: false, audio: true }' def _ReturnFirstArgument(): return 'function(arg) { return arg; }' def _ReturnRandomUtf8String(): unicode_glyphs = ''.join(unichr(char) for char in xrange(0x10ffff + 1) if unicodedata.category(unichr(char))[0] in ('LMNPSZ')) oh_dear = random.sample(unicode_glyphs, random.randint(50, 1500)) return 'function(arg) { return "%s"; }' % ''.join(oh_dear) def _ReturnFuzzedSdp(): return 'function(arg) { return fuzzSdp(arg); }' def _RandomSdpTransform(): roll = random.random() if roll < 0.1: return _ReturnRandomUtf8String() elif roll < 0.5: return _ReturnFuzzedSdp() else: return _ReturnFirstArgument() def _InsertRandomLocationReload(list_of_lines, num_to_insert): length = len(list_of_lines) assert length > num_to_insert # Randomly choose insertion points to insert at (if # num_to_insert == length - 1, all will be replaced). lines_to_insert_behind = sorted(random.sample(xrange(length - 1), num_to_insert)) result = list(list_of_lines) num_inserted = 0 for i in lines_to_insert_behind: # We're just guessing the indentation the reloads will be at, but that's # just cosmetic anyway. result.insert(num_inserted + i + 1, ' location.reload()') num_inserted += 1 return result def _InsertRandomLocationReloads(file_data, replace_all): lines = file_data.split(';\n') if replace_all: lines = _InsertRandomLocationReload(lines, len(lines) - 1) else: num_lines_to_insert = random.randint(1, 3) lines = _InsertRandomLocationReload(lines, num_lines_to_insert) return ';\n'.join(lines) def _InsertRandomLocationReloadsWithinMarkers(file_data, insert_everywhere=False): """Inserts random location.reload() statements in the file. We can insert statements after other statements (e.g. after ; and newline). We only consider the text between the "reload injection markers" so that we can avoid injecting location.reload()s into the HTML or after variable declarations, for instance. Therefore, the markers must be present in the file data passed into this function. Args: file_data: The template file data as a string. insert_everywhere: If true, will replace at all possible injection points. If false, we will randomly choose 1-3 injection points. """ start_marker = '// START_OF_POSSIBLE_INJECTED_LOCATION_RELOADS' end_marker = '// END_OF_POSSIBLE_INJECTED_LOCATION_RELOADS' within_markers_regex = re.compile(start_marker + '(.+)' + end_marker, re.DOTALL) within_markers = within_markers_regex.search(file_data) if not within_markers: raise MissingParameterException( 'Missing %s and/or %s in template.' % (start_marker, end_marker)) # Now insert the location.reload()s. modified_data = _InsertRandomLocationReloads( within_markers.group(1), insert_everywhere) return within_markers_regex.sub(modified_data, file_data) def Fuzz(file_data): """Fuzzes the passed in template.""" file_data = file_data.decode('utf-8') # Generate a bunch of random numbers and encode them into the page. Since the # values get hard-coded into the page the page's choices will be reproducible. file_data = FillInParameter('ARRAY_OF_RANDOM_ROLLS', _ArrayOfRandomRolls(500), file_data) # Randomly decide how to fuzz SDP data. file_data = FillInParameter('REQUEST_AUDIO_AND_VIDEO', _RandomAudioOrVideo(), file_data) file_data = FillInParameter('TRANSFORM_OFFER_SDP', _RandomSdpTransform(), file_data) file_data = FillInParameter('TRANSFORM_ANSWER_SDP', _RandomSdpTransform(), file_data) # Random location.reload() calls in the call sequence can be challenging for # the code to deal with, so insert some here and there. if random.random() < 0.3: file_data = _InsertRandomLocationReloadsWithinMarkers(file_data) return file_data def MakeWorkingFile(file_data): """Fills in arguments to make a basic working file. Used for ensuring that the basic template is standards-compliant. """ file_data = file_data.decode('utf-8') file_data = FillInParameter('ARRAY_OF_RANDOM_ROLLS', _ArrayOfRandomRolls(500), file_data) file_data = FillInParameter('REQUEST_AUDIO_AND_VIDEO', '{ video: true, audio: true }', file_data) file_data = FillInParameter('TRANSFORM_OFFER_SDP', _ReturnFirstArgument(), file_data) file_data = FillInParameter('TRANSFORM_ANSWER_SDP', _ReturnFirstArgument(), file_data) return file_data
gpl-3.0
maestrano/sugarcrm_dev
tests/modules/Meetings/Bug46294Test.php
4720
<?php /********************************************************************************* * SugarCRM Community Edition is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road, * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * SugarCRM" logo. If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by SugarCRM". ********************************************************************************/ require_once 'modules/Meetings/Meeting.php'; class Bug46294Test extends Sugar_PHPUnit_Framework_TestCase { var $dictionaryOptionsNotSet = array('Meeting' => array( 'fields' => array( 'type' => array( 'options' => '' ) ) ) ); var $dictionaryOptionsEmpty = array('Meeting' => array( 'fields' => array( 'type' => array() //empty ) ) ); var $dictionaryOptionsSet = array('Meeting' => array( 'fields' => array( 'type' => array( 'options' => 'type_list' ) ) ) ); var $dictionaryTypeListNotExists = array('Meeting' => array( 'fields' => array( 'type' => array( 'options' => 'type_not_exists' ) ) ) ); var $appListStrings = array('type_list' => array( 'breakfast' => 'breakfast', 'lunch' => 'lunch', 'dinner' => 'dinner' ) ); var $appListStringsEmpty = array('type_list' => array()); /** * @dataProvider provider */ public function testGetMeetingTypeOptions($dictionary, $appList, $isEmpty) { $result = getMeetingTypeOptions($dictionary, $appList, $isEmpty); $this->assertEquals($isEmpty, empty($result)); } public function provider() { return array( array($this->dictionaryOptionsSet, $this->appListStrings, false), array($this->dictionaryOptionsNotSet, $this->appListStrings, true), array($this->dictionaryOptionsEmpty, $this->appListStrings, true), array($this->dictionaryTypeListNotExists, $this->appListStrings, true), array($this->dictionaryOptionsSet, $this->appListStringsEmpty, true) ); } }
agpl-3.0
trongtri0705/exam
tests/include/utils/Bug41003Test.php
3227
<?php /********************************************************************************* * SugarCRM Community Edition is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road, * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * SugarCRM" logo. If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by SugarCRM". ********************************************************************************/ require_once 'include/utils.php'; class Bug41003Test extends Sugar_PHPUnit_Framework_TestCase { public function providerVerifyStrippingOfBrInBr2nlFunction() { return array( array("here is my text with no newline", "here is my text with no newline"), array("here is my text with a newline lowercased\n", "here is my text with a newline lowercased<br>"), array("here is my text with a newline mixed case\n", "here is my text with a newline mixed case<Br>"), array("here is my text with a newline mixed case with /\n", "here is my text with a newline mixed case with /<Br />"), array("here is my text with a newline uppercase\n", "here is my text with a newline uppercase<BR />"), array("here is my crappy text éèçàô$*%ù§!#with a newline\n in the middle", "here is my crappy text éèçàô$*%ù§!#with a newline<bR> in the middle"), ); } /** * @dataProvider providerVerifyStrippingOfBrInBr2nlFunction */ public function testVerifyStrippingOfBrInBr2nlFunction($expectedResult,$testString) { $this->assertEquals($expectedResult, br2nl($testString)); } }
agpl-3.0
abhinavmoudgil95/root
interpreter/llvm/src/tools/clang/lib/CodeGen/CodeGenPGO.cpp
31280
//===--- CodeGenPGO.cpp - PGO Instrumentation for LLVM CodeGen --*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Instrumentation-based profile-guided optimization // //===----------------------------------------------------------------------===// #include "CodeGenPGO.h" #include "CodeGenFunction.h" #include "CoverageMappingGen.h" #include "clang/AST/RecursiveASTVisitor.h" #include "clang/AST/StmtVisitor.h" #include "llvm/IR/Intrinsics.h" #include "llvm/IR/MDBuilder.h" #include "llvm/Support/Endian.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/MD5.h" static llvm::cl::opt<bool> EnableValueProfiling( "enable-value-profiling", llvm::cl::ZeroOrMore, llvm::cl::desc("Enable value profiling"), llvm::cl::init(false)); using namespace clang; using namespace CodeGen; void CodeGenPGO::setFuncName(StringRef Name, llvm::GlobalValue::LinkageTypes Linkage) { llvm::IndexedInstrProfReader *PGOReader = CGM.getPGOReader(); FuncName = llvm::getPGOFuncName( Name, Linkage, CGM.getCodeGenOpts().MainFileName, PGOReader ? PGOReader->getVersion() : llvm::IndexedInstrProf::Version); // If we're generating a profile, create a variable for the name. if (CGM.getCodeGenOpts().hasProfileClangInstr()) FuncNameVar = llvm::createPGOFuncNameVar(CGM.getModule(), Linkage, FuncName); } void CodeGenPGO::setFuncName(llvm::Function *Fn) { setFuncName(Fn->getName(), Fn->getLinkage()); // Create PGOFuncName meta data. llvm::createPGOFuncNameMetadata(*Fn, FuncName); } namespace { /// \brief Stable hasher for PGO region counters. /// /// PGOHash produces a stable hash of a given function's control flow. /// /// Changing the output of this hash will invalidate all previously generated /// profiles -- i.e., don't do it. /// /// \note When this hash does eventually change (years?), we still need to /// support old hashes. We'll need to pull in the version number from the /// profile data format and use the matching hash function. class PGOHash { uint64_t Working; unsigned Count; llvm::MD5 MD5; static const int NumBitsPerType = 6; static const unsigned NumTypesPerWord = sizeof(uint64_t) * 8 / NumBitsPerType; static const unsigned TooBig = 1u << NumBitsPerType; public: /// \brief Hash values for AST nodes. /// /// Distinct values for AST nodes that have region counters attached. /// /// These values must be stable. All new members must be added at the end, /// and no members should be removed. Changing the enumeration value for an /// AST node will affect the hash of every function that contains that node. enum HashType : unsigned char { None = 0, LabelStmt = 1, WhileStmt, DoStmt, ForStmt, CXXForRangeStmt, ObjCForCollectionStmt, SwitchStmt, CaseStmt, DefaultStmt, IfStmt, CXXTryStmt, CXXCatchStmt, ConditionalOperator, BinaryOperatorLAnd, BinaryOperatorLOr, BinaryConditionalOperator, // Keep this last. It's for the static assert that follows. LastHashType }; static_assert(LastHashType <= TooBig, "Too many types in HashType"); // TODO: When this format changes, take in a version number here, and use the // old hash calculation for file formats that used the old hash. PGOHash() : Working(0), Count(0) {} void combine(HashType Type); uint64_t finalize(); }; const int PGOHash::NumBitsPerType; const unsigned PGOHash::NumTypesPerWord; const unsigned PGOHash::TooBig; /// A RecursiveASTVisitor that fills a map of statements to PGO counters. struct MapRegionCounters : public RecursiveASTVisitor<MapRegionCounters> { /// The next counter value to assign. unsigned NextCounter; /// The function hash. PGOHash Hash; /// The map of statements to counters. llvm::DenseMap<const Stmt *, unsigned> &CounterMap; MapRegionCounters(llvm::DenseMap<const Stmt *, unsigned> &CounterMap) : NextCounter(0), CounterMap(CounterMap) {} // Blocks and lambdas are handled as separate functions, so we need not // traverse them in the parent context. bool TraverseBlockExpr(BlockExpr *BE) { return true; } bool TraverseLambdaBody(LambdaExpr *LE) { return true; } bool TraverseCapturedStmt(CapturedStmt *CS) { return true; } bool VisitDecl(const Decl *D) { switch (D->getKind()) { default: break; case Decl::Function: case Decl::CXXMethod: case Decl::CXXConstructor: case Decl::CXXDestructor: case Decl::CXXConversion: case Decl::ObjCMethod: case Decl::Block: case Decl::Captured: CounterMap[D->getBody()] = NextCounter++; break; } return true; } bool VisitStmt(const Stmt *S) { auto Type = getHashType(S); if (Type == PGOHash::None) return true; CounterMap[S] = NextCounter++; Hash.combine(Type); return true; } PGOHash::HashType getHashType(const Stmt *S) { switch (S->getStmtClass()) { default: break; case Stmt::LabelStmtClass: return PGOHash::LabelStmt; case Stmt::WhileStmtClass: return PGOHash::WhileStmt; case Stmt::DoStmtClass: return PGOHash::DoStmt; case Stmt::ForStmtClass: return PGOHash::ForStmt; case Stmt::CXXForRangeStmtClass: return PGOHash::CXXForRangeStmt; case Stmt::ObjCForCollectionStmtClass: return PGOHash::ObjCForCollectionStmt; case Stmt::SwitchStmtClass: return PGOHash::SwitchStmt; case Stmt::CaseStmtClass: return PGOHash::CaseStmt; case Stmt::DefaultStmtClass: return PGOHash::DefaultStmt; case Stmt::IfStmtClass: return PGOHash::IfStmt; case Stmt::CXXTryStmtClass: return PGOHash::CXXTryStmt; case Stmt::CXXCatchStmtClass: return PGOHash::CXXCatchStmt; case Stmt::ConditionalOperatorClass: return PGOHash::ConditionalOperator; case Stmt::BinaryConditionalOperatorClass: return PGOHash::BinaryConditionalOperator; case Stmt::BinaryOperatorClass: { const BinaryOperator *BO = cast<BinaryOperator>(S); if (BO->getOpcode() == BO_LAnd) return PGOHash::BinaryOperatorLAnd; if (BO->getOpcode() == BO_LOr) return PGOHash::BinaryOperatorLOr; break; } } return PGOHash::None; } }; /// A StmtVisitor that propagates the raw counts through the AST and /// records the count at statements where the value may change. struct ComputeRegionCounts : public ConstStmtVisitor<ComputeRegionCounts> { /// PGO state. CodeGenPGO &PGO; /// A flag that is set when the current count should be recorded on the /// next statement, such as at the exit of a loop. bool RecordNextStmtCount; /// The count at the current location in the traversal. uint64_t CurrentCount; /// The map of statements to count values. llvm::DenseMap<const Stmt *, uint64_t> &CountMap; /// BreakContinueStack - Keep counts of breaks and continues inside loops. struct BreakContinue { uint64_t BreakCount; uint64_t ContinueCount; BreakContinue() : BreakCount(0), ContinueCount(0) {} }; SmallVector<BreakContinue, 8> BreakContinueStack; ComputeRegionCounts(llvm::DenseMap<const Stmt *, uint64_t> &CountMap, CodeGenPGO &PGO) : PGO(PGO), RecordNextStmtCount(false), CountMap(CountMap) {} void RecordStmtCount(const Stmt *S) { if (RecordNextStmtCount) { CountMap[S] = CurrentCount; RecordNextStmtCount = false; } } /// Set and return the current count. uint64_t setCount(uint64_t Count) { CurrentCount = Count; return Count; } void VisitStmt(const Stmt *S) { RecordStmtCount(S); for (const Stmt *Child : S->children()) if (Child) this->Visit(Child); } void VisitFunctionDecl(const FunctionDecl *D) { // Counter tracks entry to the function body. uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody())); CountMap[D->getBody()] = BodyCount; Visit(D->getBody()); } // Skip lambda expressions. We visit these as FunctionDecls when we're // generating them and aren't interested in the body when generating a // parent context. void VisitLambdaExpr(const LambdaExpr *LE) {} void VisitCapturedDecl(const CapturedDecl *D) { // Counter tracks entry to the capture body. uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody())); CountMap[D->getBody()] = BodyCount; Visit(D->getBody()); } void VisitObjCMethodDecl(const ObjCMethodDecl *D) { // Counter tracks entry to the method body. uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody())); CountMap[D->getBody()] = BodyCount; Visit(D->getBody()); } void VisitBlockDecl(const BlockDecl *D) { // Counter tracks entry to the block body. uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody())); CountMap[D->getBody()] = BodyCount; Visit(D->getBody()); } void VisitReturnStmt(const ReturnStmt *S) { RecordStmtCount(S); if (S->getRetValue()) Visit(S->getRetValue()); CurrentCount = 0; RecordNextStmtCount = true; } void VisitCXXThrowExpr(const CXXThrowExpr *E) { RecordStmtCount(E); if (E->getSubExpr()) Visit(E->getSubExpr()); CurrentCount = 0; RecordNextStmtCount = true; } void VisitGotoStmt(const GotoStmt *S) { RecordStmtCount(S); CurrentCount = 0; RecordNextStmtCount = true; } void VisitLabelStmt(const LabelStmt *S) { RecordNextStmtCount = false; // Counter tracks the block following the label. uint64_t BlockCount = setCount(PGO.getRegionCount(S)); CountMap[S] = BlockCount; Visit(S->getSubStmt()); } void VisitBreakStmt(const BreakStmt *S) { RecordStmtCount(S); assert(!BreakContinueStack.empty() && "break not in a loop or switch!"); BreakContinueStack.back().BreakCount += CurrentCount; CurrentCount = 0; RecordNextStmtCount = true; } void VisitContinueStmt(const ContinueStmt *S) { RecordStmtCount(S); assert(!BreakContinueStack.empty() && "continue stmt not in a loop!"); BreakContinueStack.back().ContinueCount += CurrentCount; CurrentCount = 0; RecordNextStmtCount = true; } void VisitWhileStmt(const WhileStmt *S) { RecordStmtCount(S); uint64_t ParentCount = CurrentCount; BreakContinueStack.push_back(BreakContinue()); // Visit the body region first so the break/continue adjustments can be // included when visiting the condition. uint64_t BodyCount = setCount(PGO.getRegionCount(S)); CountMap[S->getBody()] = CurrentCount; Visit(S->getBody()); uint64_t BackedgeCount = CurrentCount; // ...then go back and propagate counts through the condition. The count // at the start of the condition is the sum of the incoming edges, // the backedge from the end of the loop body, and the edges from // continue statements. BreakContinue BC = BreakContinueStack.pop_back_val(); uint64_t CondCount = setCount(ParentCount + BackedgeCount + BC.ContinueCount); CountMap[S->getCond()] = CondCount; Visit(S->getCond()); setCount(BC.BreakCount + CondCount - BodyCount); RecordNextStmtCount = true; } void VisitDoStmt(const DoStmt *S) { RecordStmtCount(S); uint64_t LoopCount = PGO.getRegionCount(S); BreakContinueStack.push_back(BreakContinue()); // The count doesn't include the fallthrough from the parent scope. Add it. uint64_t BodyCount = setCount(LoopCount + CurrentCount); CountMap[S->getBody()] = BodyCount; Visit(S->getBody()); uint64_t BackedgeCount = CurrentCount; BreakContinue BC = BreakContinueStack.pop_back_val(); // The count at the start of the condition is equal to the count at the // end of the body, plus any continues. uint64_t CondCount = setCount(BackedgeCount + BC.ContinueCount); CountMap[S->getCond()] = CondCount; Visit(S->getCond()); setCount(BC.BreakCount + CondCount - LoopCount); RecordNextStmtCount = true; } void VisitForStmt(const ForStmt *S) { RecordStmtCount(S); if (S->getInit()) Visit(S->getInit()); uint64_t ParentCount = CurrentCount; BreakContinueStack.push_back(BreakContinue()); // Visit the body region first. (This is basically the same as a while // loop; see further comments in VisitWhileStmt.) uint64_t BodyCount = setCount(PGO.getRegionCount(S)); CountMap[S->getBody()] = BodyCount; Visit(S->getBody()); uint64_t BackedgeCount = CurrentCount; BreakContinue BC = BreakContinueStack.pop_back_val(); // The increment is essentially part of the body but it needs to include // the count for all the continue statements. if (S->getInc()) { uint64_t IncCount = setCount(BackedgeCount + BC.ContinueCount); CountMap[S->getInc()] = IncCount; Visit(S->getInc()); } // ...then go back and propagate counts through the condition. uint64_t CondCount = setCount(ParentCount + BackedgeCount + BC.ContinueCount); if (S->getCond()) { CountMap[S->getCond()] = CondCount; Visit(S->getCond()); } setCount(BC.BreakCount + CondCount - BodyCount); RecordNextStmtCount = true; } void VisitCXXForRangeStmt(const CXXForRangeStmt *S) { RecordStmtCount(S); Visit(S->getLoopVarStmt()); Visit(S->getRangeStmt()); Visit(S->getBeginStmt()); Visit(S->getEndStmt()); uint64_t ParentCount = CurrentCount; BreakContinueStack.push_back(BreakContinue()); // Visit the body region first. (This is basically the same as a while // loop; see further comments in VisitWhileStmt.) uint64_t BodyCount = setCount(PGO.getRegionCount(S)); CountMap[S->getBody()] = BodyCount; Visit(S->getBody()); uint64_t BackedgeCount = CurrentCount; BreakContinue BC = BreakContinueStack.pop_back_val(); // The increment is essentially part of the body but it needs to include // the count for all the continue statements. uint64_t IncCount = setCount(BackedgeCount + BC.ContinueCount); CountMap[S->getInc()] = IncCount; Visit(S->getInc()); // ...then go back and propagate counts through the condition. uint64_t CondCount = setCount(ParentCount + BackedgeCount + BC.ContinueCount); CountMap[S->getCond()] = CondCount; Visit(S->getCond()); setCount(BC.BreakCount + CondCount - BodyCount); RecordNextStmtCount = true; } void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) { RecordStmtCount(S); Visit(S->getElement()); uint64_t ParentCount = CurrentCount; BreakContinueStack.push_back(BreakContinue()); // Counter tracks the body of the loop. uint64_t BodyCount = setCount(PGO.getRegionCount(S)); CountMap[S->getBody()] = BodyCount; Visit(S->getBody()); uint64_t BackedgeCount = CurrentCount; BreakContinue BC = BreakContinueStack.pop_back_val(); setCount(BC.BreakCount + ParentCount + BackedgeCount + BC.ContinueCount - BodyCount); RecordNextStmtCount = true; } void VisitSwitchStmt(const SwitchStmt *S) { RecordStmtCount(S); Visit(S->getCond()); CurrentCount = 0; BreakContinueStack.push_back(BreakContinue()); Visit(S->getBody()); // If the switch is inside a loop, add the continue counts. BreakContinue BC = BreakContinueStack.pop_back_val(); if (!BreakContinueStack.empty()) BreakContinueStack.back().ContinueCount += BC.ContinueCount; // Counter tracks the exit block of the switch. setCount(PGO.getRegionCount(S)); RecordNextStmtCount = true; } void VisitSwitchCase(const SwitchCase *S) { RecordNextStmtCount = false; // Counter for this particular case. This counts only jumps from the // switch header and does not include fallthrough from the case before // this one. uint64_t CaseCount = PGO.getRegionCount(S); setCount(CurrentCount + CaseCount); // We need the count without fallthrough in the mapping, so it's more useful // for branch probabilities. CountMap[S] = CaseCount; RecordNextStmtCount = true; Visit(S->getSubStmt()); } void VisitIfStmt(const IfStmt *S) { RecordStmtCount(S); uint64_t ParentCount = CurrentCount; Visit(S->getCond()); // Counter tracks the "then" part of an if statement. The count for // the "else" part, if it exists, will be calculated from this counter. uint64_t ThenCount = setCount(PGO.getRegionCount(S)); CountMap[S->getThen()] = ThenCount; Visit(S->getThen()); uint64_t OutCount = CurrentCount; uint64_t ElseCount = ParentCount - ThenCount; if (S->getElse()) { setCount(ElseCount); CountMap[S->getElse()] = ElseCount; Visit(S->getElse()); OutCount += CurrentCount; } else OutCount += ElseCount; setCount(OutCount); RecordNextStmtCount = true; } void VisitCXXTryStmt(const CXXTryStmt *S) { RecordStmtCount(S); Visit(S->getTryBlock()); for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I) Visit(S->getHandler(I)); // Counter tracks the continuation block of the try statement. setCount(PGO.getRegionCount(S)); RecordNextStmtCount = true; } void VisitCXXCatchStmt(const CXXCatchStmt *S) { RecordNextStmtCount = false; // Counter tracks the catch statement's handler block. uint64_t CatchCount = setCount(PGO.getRegionCount(S)); CountMap[S] = CatchCount; Visit(S->getHandlerBlock()); } void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) { RecordStmtCount(E); uint64_t ParentCount = CurrentCount; Visit(E->getCond()); // Counter tracks the "true" part of a conditional operator. The // count in the "false" part will be calculated from this counter. uint64_t TrueCount = setCount(PGO.getRegionCount(E)); CountMap[E->getTrueExpr()] = TrueCount; Visit(E->getTrueExpr()); uint64_t OutCount = CurrentCount; uint64_t FalseCount = setCount(ParentCount - TrueCount); CountMap[E->getFalseExpr()] = FalseCount; Visit(E->getFalseExpr()); OutCount += CurrentCount; setCount(OutCount); RecordNextStmtCount = true; } void VisitBinLAnd(const BinaryOperator *E) { RecordStmtCount(E); uint64_t ParentCount = CurrentCount; Visit(E->getLHS()); // Counter tracks the right hand side of a logical and operator. uint64_t RHSCount = setCount(PGO.getRegionCount(E)); CountMap[E->getRHS()] = RHSCount; Visit(E->getRHS()); setCount(ParentCount + RHSCount - CurrentCount); RecordNextStmtCount = true; } void VisitBinLOr(const BinaryOperator *E) { RecordStmtCount(E); uint64_t ParentCount = CurrentCount; Visit(E->getLHS()); // Counter tracks the right hand side of a logical or operator. uint64_t RHSCount = setCount(PGO.getRegionCount(E)); CountMap[E->getRHS()] = RHSCount; Visit(E->getRHS()); setCount(ParentCount + RHSCount - CurrentCount); RecordNextStmtCount = true; } }; } // end anonymous namespace void PGOHash::combine(HashType Type) { // Check that we never combine 0 and only have six bits. assert(Type && "Hash is invalid: unexpected type 0"); assert(unsigned(Type) < TooBig && "Hash is invalid: too many types"); // Pass through MD5 if enough work has built up. if (Count && Count % NumTypesPerWord == 0) { using namespace llvm::support; uint64_t Swapped = endian::byte_swap<uint64_t, little>(Working); MD5.update(llvm::makeArrayRef((uint8_t *)&Swapped, sizeof(Swapped))); Working = 0; } // Accumulate the current type. ++Count; Working = Working << NumBitsPerType | Type; } uint64_t PGOHash::finalize() { // Use Working as the hash directly if we never used MD5. if (Count <= NumTypesPerWord) // No need to byte swap here, since none of the math was endian-dependent. // This number will be byte-swapped as required on endianness transitions, // so we will see the same value on the other side. return Working; // Check for remaining work in Working. if (Working) MD5.update(Working); // Finalize the MD5 and return the hash. llvm::MD5::MD5Result Result; MD5.final(Result); using namespace llvm::support; return endian::read<uint64_t, little, unaligned>(Result); } void CodeGenPGO::assignRegionCounters(GlobalDecl GD, llvm::Function *Fn) { const Decl *D = GD.getDecl(); bool InstrumentRegions = CGM.getCodeGenOpts().hasProfileClangInstr(); llvm::IndexedInstrProfReader *PGOReader = CGM.getPGOReader(); if (!InstrumentRegions && !PGOReader) return; if (D->isImplicit()) return; // Constructors and destructors may be represented by several functions in IR. // If so, instrument only base variant, others are implemented by delegation // to the base one, it would be counted twice otherwise. if (CGM.getTarget().getCXXABI().hasConstructorVariants() && ((isa<CXXConstructorDecl>(GD.getDecl()) && GD.getCtorType() != Ctor_Base) || (isa<CXXDestructorDecl>(GD.getDecl()) && GD.getDtorType() != Dtor_Base))) { return; } CGM.ClearUnusedCoverageMapping(D); setFuncName(Fn); mapRegionCounters(D); if (CGM.getCodeGenOpts().CoverageMapping) emitCounterRegionMapping(D); if (PGOReader) { SourceManager &SM = CGM.getContext().getSourceManager(); loadRegionCounts(PGOReader, SM.isInMainFile(D->getLocation())); computeRegionCounts(D); applyFunctionAttributes(PGOReader, Fn); } } void CodeGenPGO::mapRegionCounters(const Decl *D) { RegionCounterMap.reset(new llvm::DenseMap<const Stmt *, unsigned>); MapRegionCounters Walker(*RegionCounterMap); if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) Walker.TraverseDecl(const_cast<FunctionDecl *>(FD)); else if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D)) Walker.TraverseDecl(const_cast<ObjCMethodDecl *>(MD)); else if (const BlockDecl *BD = dyn_cast_or_null<BlockDecl>(D)) Walker.TraverseDecl(const_cast<BlockDecl *>(BD)); else if (const CapturedDecl *CD = dyn_cast_or_null<CapturedDecl>(D)) Walker.TraverseDecl(const_cast<CapturedDecl *>(CD)); assert(Walker.NextCounter > 0 && "no entry counter mapped for decl"); NumRegionCounters = Walker.NextCounter; FunctionHash = Walker.Hash.finalize(); } void CodeGenPGO::emitCounterRegionMapping(const Decl *D) { if (SkipCoverageMapping) return; // Don't map the functions inside the system headers auto Loc = D->getBody()->getLocStart(); if (CGM.getContext().getSourceManager().isInSystemHeader(Loc)) return; std::string CoverageMapping; llvm::raw_string_ostream OS(CoverageMapping); CoverageMappingGen MappingGen(*CGM.getCoverageMapping(), CGM.getContext().getSourceManager(), CGM.getLangOpts(), RegionCounterMap.get()); MappingGen.emitCounterMapping(D, OS); OS.flush(); if (CoverageMapping.empty()) return; CGM.getCoverageMapping()->addFunctionMappingRecord( FuncNameVar, FuncName, FunctionHash, CoverageMapping); } void CodeGenPGO::emitEmptyCounterMapping(const Decl *D, StringRef Name, llvm::GlobalValue::LinkageTypes Linkage) { if (SkipCoverageMapping) return; // Don't map the functions inside the system headers auto Loc = D->getBody()->getLocStart(); if (CGM.getContext().getSourceManager().isInSystemHeader(Loc)) return; std::string CoverageMapping; llvm::raw_string_ostream OS(CoverageMapping); CoverageMappingGen MappingGen(*CGM.getCoverageMapping(), CGM.getContext().getSourceManager(), CGM.getLangOpts()); MappingGen.emitEmptyMapping(D, OS); OS.flush(); if (CoverageMapping.empty()) return; setFuncName(Name, Linkage); CGM.getCoverageMapping()->addFunctionMappingRecord( FuncNameVar, FuncName, FunctionHash, CoverageMapping, false); } void CodeGenPGO::computeRegionCounts(const Decl *D) { StmtCountMap.reset(new llvm::DenseMap<const Stmt *, uint64_t>); ComputeRegionCounts Walker(*StmtCountMap, *this); if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) Walker.VisitFunctionDecl(FD); else if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D)) Walker.VisitObjCMethodDecl(MD); else if (const BlockDecl *BD = dyn_cast_or_null<BlockDecl>(D)) Walker.VisitBlockDecl(BD); else if (const CapturedDecl *CD = dyn_cast_or_null<CapturedDecl>(D)) Walker.VisitCapturedDecl(const_cast<CapturedDecl *>(CD)); } void CodeGenPGO::applyFunctionAttributes(llvm::IndexedInstrProfReader *PGOReader, llvm::Function *Fn) { if (!haveRegionCounts()) return; uint64_t FunctionCount = getRegionCount(nullptr); Fn->setEntryCount(FunctionCount); } void CodeGenPGO::emitCounterIncrement(CGBuilderTy &Builder, const Stmt *S) { if (!CGM.getCodeGenOpts().hasProfileClangInstr() || !RegionCounterMap) return; if (!Builder.GetInsertBlock()) return; unsigned Counter = (*RegionCounterMap)[S]; auto *I8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext()); Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::instrprof_increment), {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy), Builder.getInt64(FunctionHash), Builder.getInt32(NumRegionCounters), Builder.getInt32(Counter)}); } // This method either inserts a call to the profile run-time during // instrumentation or puts profile data into metadata for PGO use. void CodeGenPGO::valueProfile(CGBuilderTy &Builder, uint32_t ValueKind, llvm::Instruction *ValueSite, llvm::Value *ValuePtr) { if (!EnableValueProfiling) return; if (!ValuePtr || !ValueSite || !Builder.GetInsertBlock()) return; if (isa<llvm::Constant>(ValuePtr)) return; bool InstrumentValueSites = CGM.getCodeGenOpts().hasProfileClangInstr(); if (InstrumentValueSites && RegionCounterMap) { auto BuilderInsertPoint = Builder.saveIP(); Builder.SetInsertPoint(ValueSite); llvm::Value *Args[5] = { llvm::ConstantExpr::getBitCast(FuncNameVar, Builder.getInt8PtrTy()), Builder.getInt64(FunctionHash), Builder.CreatePtrToInt(ValuePtr, Builder.getInt64Ty()), Builder.getInt32(ValueKind), Builder.getInt32(NumValueSites[ValueKind]++) }; Builder.CreateCall( CGM.getIntrinsic(llvm::Intrinsic::instrprof_value_profile), Args); Builder.restoreIP(BuilderInsertPoint); return; } llvm::IndexedInstrProfReader *PGOReader = CGM.getPGOReader(); if (PGOReader && haveRegionCounts()) { // We record the top most called three functions at each call site. // Profile metadata contains "VP" string identifying this metadata // as value profiling data, then a uint32_t value for the value profiling // kind, a uint64_t value for the total number of times the call is // executed, followed by the function hash and execution count (uint64_t) // pairs for each function. if (NumValueSites[ValueKind] >= ProfRecord->getNumValueSites(ValueKind)) return; llvm::annotateValueSite(CGM.getModule(), *ValueSite, *ProfRecord, (llvm::InstrProfValueKind)ValueKind, NumValueSites[ValueKind]); NumValueSites[ValueKind]++; } } void CodeGenPGO::loadRegionCounts(llvm::IndexedInstrProfReader *PGOReader, bool IsInMainFile) { CGM.getPGOStats().addVisited(IsInMainFile); RegionCounts.clear(); llvm::Expected<llvm::InstrProfRecord> RecordExpected = PGOReader->getInstrProfRecord(FuncName, FunctionHash); if (auto E = RecordExpected.takeError()) { auto IPE = llvm::InstrProfError::take(std::move(E)); if (IPE == llvm::instrprof_error::unknown_function) CGM.getPGOStats().addMissing(IsInMainFile); else if (IPE == llvm::instrprof_error::hash_mismatch) CGM.getPGOStats().addMismatched(IsInMainFile); else if (IPE == llvm::instrprof_error::malformed) // TODO: Consider a more specific warning for this case. CGM.getPGOStats().addMismatched(IsInMainFile); return; } ProfRecord = llvm::make_unique<llvm::InstrProfRecord>(std::move(RecordExpected.get())); RegionCounts = ProfRecord->Counts; } /// \brief Calculate what to divide by to scale weights. /// /// Given the maximum weight, calculate a divisor that will scale all the /// weights to strictly less than UINT32_MAX. static uint64_t calculateWeightScale(uint64_t MaxWeight) { return MaxWeight < UINT32_MAX ? 1 : MaxWeight / UINT32_MAX + 1; } /// \brief Scale an individual branch weight (and add 1). /// /// Scale a 64-bit weight down to 32-bits using \c Scale. /// /// According to Laplace's Rule of Succession, it is better to compute the /// weight based on the count plus 1, so universally add 1 to the value. /// /// \pre \c Scale was calculated by \a calculateWeightScale() with a weight no /// greater than \c Weight. static uint32_t scaleBranchWeight(uint64_t Weight, uint64_t Scale) { assert(Scale && "scale by 0?"); uint64_t Scaled = Weight / Scale + 1; assert(Scaled <= UINT32_MAX && "overflow 32-bits"); return Scaled; } llvm::MDNode *CodeGenFunction::createProfileWeights(uint64_t TrueCount, uint64_t FalseCount) { // Check for empty weights. if (!TrueCount && !FalseCount) return nullptr; // Calculate how to scale down to 32-bits. uint64_t Scale = calculateWeightScale(std::max(TrueCount, FalseCount)); llvm::MDBuilder MDHelper(CGM.getLLVMContext()); return MDHelper.createBranchWeights(scaleBranchWeight(TrueCount, Scale), scaleBranchWeight(FalseCount, Scale)); } llvm::MDNode * CodeGenFunction::createProfileWeights(ArrayRef<uint64_t> Weights) { // We need at least two elements to create meaningful weights. if (Weights.size() < 2) return nullptr; // Check for empty weights. uint64_t MaxWeight = *std::max_element(Weights.begin(), Weights.end()); if (MaxWeight == 0) return nullptr; // Calculate how to scale down to 32-bits. uint64_t Scale = calculateWeightScale(MaxWeight); SmallVector<uint32_t, 16> ScaledWeights; ScaledWeights.reserve(Weights.size()); for (uint64_t W : Weights) ScaledWeights.push_back(scaleBranchWeight(W, Scale)); llvm::MDBuilder MDHelper(CGM.getLLVMContext()); return MDHelper.createBranchWeights(ScaledWeights); } llvm::MDNode *CodeGenFunction::createProfileWeightsForLoop(const Stmt *Cond, uint64_t LoopCount) { if (!PGO.haveRegionCounts()) return nullptr; Optional<uint64_t> CondCount = PGO.getStmtCount(Cond); assert(CondCount.hasValue() && "missing expected loop condition count"); if (*CondCount == 0) return nullptr; return createProfileWeights(LoopCount, std::max(*CondCount, LoopCount) - LoopCount); }
lgpl-2.1
jason-lang/apps
jason-team-2013/teams/r2m/src/java/ia/setMaxEdges.java
555
// Internal action code for project smadasMAPC2012 package ia; import env.MixedAgentArch; import graphLib.Graph; import jason.*; import jason.asSemantics.*; import jason.asSyntax.*; public class setMaxEdges extends DefaultInternalAction { @Override public Object execute(TransitionSystem ts, Unifier un, Term[] terms) throws Exception { MixedAgentArch arch = (MixedAgentArch)ts.getUserAgArch(); Graph graph = arch.getGraph(); graph.setMaxEdges((int) ((NumberTerm) terms[0]).solve()); return true; } }
lgpl-3.0