blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
201
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 7
100
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 260
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 11.4k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 17
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 80
values | src_encoding
stringclasses 28
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 8
9.86M
| extension
stringclasses 52
values | content
stringlengths 8
9.86M
| authors
sequencelengths 1
1
| author
stringlengths 0
119
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
93904eeb10f86176ba730f7b6c46932c04c8d350 | aa7e4152d89159eed2d234782087af1a90f5111f | /wordvector.h | 858a81d72a0a698c292fe6ebbcc154812cf0d5d4 | [] | no_license | EmbolismSoil/ShortTextClassfier | 271917460cf942f91262c519b2a595dc967a3583 | 53e22cbaad0fb8199809524b9ad06a68001b57fe | refs/heads/master | 2021-05-03T07:27:19.496571 | 2018-03-05T11:24:02 | 2018-03-05T11:24:02 | 120,608,655 | 7 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,261 | h | #ifndef WORDVECTOR_H
#define WORDVECTOR_H
#include <vector>
#include <stdexcept>
#include <exception>
#include <sstream>
#include <boost/algorithm/string.hpp>
#include <boost/format.hpp>
#include <stdio.h>
#include <math.h>
template<class T>
class WordVector
{
public:
WordVector(int dim);
WordVector(std::vector<T> const& vec);
WordVector operator + (WordVector const& rhs);
WordVector& operator += (WordVector const& rhs);
WordVector operator - (WordVector const& rhs);
WordVector operator * (typename std::vector<T>::value_type num);
typename std::vector<T>::value_type operator * (WordVector const& rhs);
T distance(WordVector const& rhs);
T cosine(WordVector & rhs);
T mod();
std::string const to_string();
private:
std::vector<T> _vec;
WordVector(){}
};
template<class T>
T WordVector<T>::mod()
{
typename std::vector<T>::const_iterator pos = _vec.begin();
T sum = 0;
for (; pos != _vec.end(); ++pos){
T d = *pos;
sum += (d * d);
}
return ::sqrt(sum);
}
template<class T>
T WordVector<T>::cosine(WordVector & rhs)
{
if (rhs._vec.size() != _vec.size() || _vec.empty()){
throw std::invalid_argument("Dim error");
}
WordVector<T> &lhs = *this;
return (lhs * rhs) / (lhs.mod() * rhs.mod());
}
template<class T>
T WordVector<T>::distance(WordVector const& rhs)
{
if (rhs._vec.size() != _vec.size() || _vec.empty()){
throw std::invalid_argument("Dim error");
}
T sum = 0;
for (typename std::vector<T>::size_type pos = 0; pos != _vec.size(); ++pos){
T d = _vec[pos] - rhs._vec[pos];
sum += (d*d);
}
return ::sqrt(sum);
}
template<class T>
WordVector<T>::WordVector(int dim):
_vec(dim, 0)
{
if (dim <= 0)
{
throw std::invalid_argument("Dim error");
}
}
template<class T>
WordVector<T>::WordVector(const std::vector<T> &vec):
_vec(vec)
{
}
template<class T>
WordVector<T> WordVector<T>::operator+(const WordVector &rhs)
{
if (rhs._vec.size() != _vec.size() || _vec.empty()){
throw std::invalid_argument("Dim error");
}
WordVector<T> vec;
for (typename std::vector<T>::size_type pos = 0; pos != _vec.size(); ++pos)
{
vec._vec.push_back(_vec[pos] + rhs._vec[pos]);
}
return vec;
}
template<class T>
WordVector<T> &WordVector<T>::operator +=(const WordVector &rhs)
{
if (rhs._vec.size() != _vec.size() || _vec.empty()){
throw std::invalid_argument("Dim error");
}
WordVector<T>& vec = *this;
for (typename std::vector<T>::size_type pos = 0; pos != _vec.size(); ++pos)
{
vec._vec[pos] = (_vec[pos] + rhs._vec[pos]);
}
return vec;
}
template<class T>
WordVector<T> WordVector<T>::operator- (const WordVector &rhs)
{
if (rhs._vec.size() != _vec.size() || _vec.empty()){
throw std::invalid_argument("Dim error");
}
WordVector<T> vec;
for (typename std::vector<T>::size_type pos = 0; pos != _vec.size(); ++pos)
{
vec._vec.push_back(_vec[pos] - rhs._vec[pos]);
}
return vec;
}
template<class T>
WordVector<T> WordVector<T>::operator *(typename std::vector<T>::value_type num)
{
WordVector<T> vec;
for (typename std::vector<T>::const_iterator pos = _vec.begin(); pos != _vec.end(); ++pos){
vec._vec.push_back(*pos * num);
}
return vec;
}
template<class T>
typename std::vector<T>::value_type WordVector<T>::operator *(const WordVector &rhs)
{
if (rhs._vec.size() != _vec.size() || _vec.empty()){
throw std::invalid_argument("Dim error");
}
typename std::vector<T>::value_type dot = 0;
for (typename std::vector<T>::size_type pos = 0; pos != _vec.size(); ++pos)
{
dot += _vec[pos] * rhs._vec[pos];
}
return dot;
}
template<class T>
const std::string WordVector<T>::to_string()
{
std::stringstream ss;
std::vector<std::string> s_vec;
for (typename std::vector<T>::const_iterator pos = _vec.begin(); pos != _vec.end(); ++pos){
ss << *pos;
s_vec.push_back(ss.str());
ss.str("");
}
std::string vec = boost::join(s_vec, ", ");
boost::format fmt("[%s]");
fmt % vec;
return fmt.str();
}
#endif // WORDVECTOR_H
| [
"[email protected]"
] | |
bf2d315235dd9751ca0e8a5641e1506e0a5f8584 | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5744014401732608_1/C++/yuukiAsuna/practice.cpp | f11741392c4f8b8d90fe06e26755001f71ff59ab | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 1,205 | cpp | #include <bits/stdc++.h>
#define PB push_back
#define FT first
#define SD second
#define MP make_pair
#define INF 0x3f3f3f3f
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int,int> P;
const int N = 55,MOD = 7+1e9;
int G[N][N];
int main()
{
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
int T, ca = 0;
scanf("%d", &T);
while(T --)
{
int n;
LL m;
scanf("%d%lld", &n, &m);
LL MAX = 1LL<<(n-2);
printf("Case #%d: ", ++ca);
if(m > MAX)
{
puts("IMPOSSIBLE");
continue;
}
memset(G, 0, sizeof G);
puts("POSSIBLE");
m --, G[1][n] = 1;
for(int i = 1;i <= n;i ++)
{
for(int j = i + 1;j < n;j ++) G[i][j] = 1;
}
for(int i = 2;i < n;i ++)
{
if((m&1LL) != 0)
{
G[i][n] = 1;
}
m >>= 1;
}
for(int i = 1;i <= n;i ++)
{
for(int j = 1;j <= n;j ++) printf("%d", G[i][j]);
printf("\n");
}
}
return 0;
} | [
"[email protected]"
] | |
296f78f0a53e90c255c7aa9d979bd96fb83ff0c4 | 789ec1a342e7ba9e571e240696d62f998c0efe65 | /apps/ogr2ogr_lib.cpp | 2de843f9e0f0317525682e992dd5893c6de4241b | [
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-warranty-disclaimer",
"MIT",
"SunPro",
"LicenseRef-scancode-info-zip-2005-02",
"BSD-3-Clause"
] | permissive | speakeasy/gdal | a76384f3e3862f6a5d1e2067357e0d10fdcb61f4 | 294b6b399f93e1d9403859cf64fba80c95156cd1 | refs/heads/master | 2020-03-08T00:11:19.509823 | 2018-04-02T19:02:55 | 2018-04-02T19:02:55 | 127,800,245 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 185,986 | cpp | /******************************************************************************
* $Id: ogr2ogr_lib.cpp 39041 2017-06-09 21:44:01Z rouault $
*
* Project: OpenGIS Simple Features Reference Implementation
* Purpose: Simple client for translating between formats.
* Author: Frank Warmerdam, [email protected]
*
******************************************************************************
* Copyright (c) 1999, Frank Warmerdam
* Copyright (c) 2008-2015, Even Rouault <even dot rouault at mines-paris dot org>
* Copyright (c) 2015, Faza Mahamood
*
* 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.
****************************************************************************/
#include "ogrsf_frmts.h"
#include "ogr_p.h"
#include "cpl_conv.h"
#include "cpl_string.h"
#include "cpl_error.h"
#include "ogr_api.h"
#include "gdal.h"
#include "gdal_utils_priv.h"
#include "gdal_alg.h"
#include "commonutils.h"
#include <map>
#include <vector>
CPL_CVSID("$Id: ogr2ogr_lib.cpp 39041 2017-06-09 21:44:01Z rouault $");
typedef enum
{
GEOMOP_NONE,
GEOMOP_SEGMENTIZE,
GEOMOP_SIMPLIFY_PRESERVE_TOPOLOGY,
} GeomOperation;
typedef enum
{
GTC_DEFAULT,
GTC_PROMOTE_TO_MULTI,
GTC_CONVERT_TO_LINEAR,
GTC_CONVERT_TO_CURVE,
} GeomTypeConversion;
#define GEOMTYPE_UNCHANGED -2
#define COORD_DIM_UNCHANGED -1
#define COORD_DIM_LAYER_DIM -2
#define COORD_DIM_XYM -3
/************************************************************************/
/* GDALVectorTranslateOptions */
/************************************************************************/
/** Options for use with GDALVectorTranslate(). GDALVectorTranslateOptions* must be allocated and
* freed with GDALVectorTranslateOptionsNew() and GDALVectorTranslateOptionsFree() respectively.
*/
struct GDALVectorTranslateOptions
{
/*! continue after a failure, skipping the failed feature */
bool bSkipFailures;
/*! use layer level transaction. If set to FALSE, then it is interpreted as dataset level transaction. */
int nLayerTransaction;
/*! force the use of particular transaction type based on GDALVectorTranslate::nLayerTransaction */
bool bForceTransaction;
/*! group nGroupTransactions features per transaction (default 20000). Increase the value for better
performance when writing into DBMS drivers that have transaction support. nGroupTransactions can
be set to -1 to load the data into a single transaction */
int nGroupTransactions;
/*! If provided, only the feature with this feature id will be reported. Operates exclusive of
the spatial or attribute queries. Note: if you want to select several features based on their
feature id, you can also use the fact the 'fid' is a special field recognized by OGR SQL.
So GDALVectorTranslateOptions::pszWHERE = "fid in (1,3,5)" would select features 1, 3 and 5. */
GIntBig nFIDToFetch;
/*! allow or suppress progress monitor and other non-error output */
bool bQuiet;
/*! output file format name (default is ESRI Shapefile) */
char *pszFormat;
/*! list of layers of the source dataset which needs to be selected */
char **papszLayers;
/*! dataset creation option (format specific) */
char **papszDSCO;
/*! layer creation option (format specific) */
char **papszLCO;
/*! access modes */
GDALVectorTranslateAccessMode eAccessMode;
/*! It has the effect of adding, to existing target layers, the new fields found in source layers.
This option is useful when merging files that have non-strictly identical structures. This might
not work for output formats that don't support adding fields to existing non-empty layers. */
bool bAddMissingFields;
/*! It must be set to true to trigger reprojection, otherwise only SRS assignment is done. */
bool bTransform;
/*! output SRS. GDALVectorTranslateOptions::bTransform must be set to true to trigger reprojection,
otherwise only SRS assignment is done. */
char *pszOutputSRSDef;
/*! override source SRS */
char *pszSourceSRSDef;
bool bNullifyOutputSRS;
/*! If set to false, then field name matching between source and existing target layer is done
in a more relaxed way if the target driver has an implementation for it. */
bool bExactFieldNameMatch;
/*! an alternate name to the new layer */
char *pszNewLayerName;
/*! attribute query (like SQL WHERE) */
char *pszWHERE;
/*! name of the geometry field on which the spatial filter operates on. */
char *pszGeomField;
/*! list of fields from input layer to copy to the new layer. A field is skipped if
mentioned previously in the list even if the input layer has duplicate field names.
(Defaults to all; any field is skipped if a subsequent field with same name is
found.) Geometry fields can also be specified in the list. */
char **papszSelFields;
/*! SQL statement to execute. The resulting table/layer will be saved to the output. */
char *pszSQLStatement;
/*! SQL dialect. In some cases can be used to use (unoptimized) OGR SQL instead of the
native SQL of an RDBMS by using "OGRSQL". The "SQLITE" dialect can also be used with
any datasource. */
char *pszDialect;
/*! the geometry type for the created layer */
int eGType;
GeomTypeConversion eGeomTypeConversion;
/*! Geometric operation to perform */
GeomOperation eGeomOp;
/*! the parameter to geometric operation */
double dfGeomOpParam;
/*! list of field types to convert to a field of type string in the destination layer.
Valid types are: Integer, Integer64, Real, String, Date, Time, DateTime, Binary,
IntegerList, Integer64List, RealList, StringList. Special value "All" can be
used to convert all fields to strings. This is an alternate way to using the CAST
operator of OGR SQL, that may avoid typing a long SQL query. Note that this does
not influence the field types used by the source driver, and is only an afterwards
conversion. */
char **papszFieldTypesToString;
/*! list of field types and the field type after conversion in the destination layer.
("srctype1=dsttype1","srctype2=dsttype2",...).
Valid types are : Integer, Integer64, Real, String, Date, Time, DateTime, Binary,
IntegerList, Integer64List, RealList, StringList. Types can also include subtype
between parenthesis, such as Integer(Boolean), Real(Float32), ... Special value
"All" can be used to convert all fields to another type. This is an alternate way to
using the CAST operator of OGR SQL, that may avoid typing a long SQL query.
This is a generalization of GDALVectorTranslateOptions::papszFieldTypeToString. Note that this does not influence
the field types used by the source driver, and is only an afterwards conversion. */
char **papszMapFieldType;
/*! set field width and precision to 0 */
bool bUnsetFieldWidth;
/*! display progress on terminal. Only works if input layers have the "fast feature count"
capability */
bool bDisplayProgress;
/*! split geometries crossing the dateline meridian */
bool bWrapDateline;
/*! offset from dateline in degrees (default long. = +/- 10deg, geometries
within 170deg to -170deg will be split) */
double dfDateLineOffset;
/*! clip geometries when it is set to true */
bool bClipSrc;
OGRGeometryH hClipSrc;
/*! clip datasource */
char *pszClipSrcDS;
/*! select desired geometries using an SQL query */
char *pszClipSrcSQL;
/*! selected named layer from the source clip datasource */
char *pszClipSrcLayer;
/*! restrict desired geometries based on attribute query */
char *pszClipSrcWhere;
OGRGeometryH hClipDst;
/*! destination clip datasource */
char *pszClipDstDS;
/*! select desired geometries using an SQL query */
char *pszClipDstSQL;
/*! selected named layer from the destination clip datasource */
char *pszClipDstLayer;
/*! restrict desired geometries based on attribute query */
char *pszClipDstWhere;
/*! split fields of type StringList, RealList or IntegerList into as many fields
of type String, Real or Integer as necessary. */
bool bSplitListFields;
/*! limit the number of subfields created for each split field. */
int nMaxSplitListSubFields;
/*! produce one feature for each geometry in any kind of geometry collection in the
source file */
bool bExplodeCollections;
/*! uses the specified field to fill the Z coordinates of geometries */
char *pszZField;
/*! the list of field indexes to be copied from the source to the destination. The (n)th value
specified in the list is the index of the field in the target layer definition in which the
n(th) field of the source layer must be copied. Index count starts at zero. There must be
exactly as many values in the list as the count of the fields in the source layer.
We can use the "identity" option to specify that the fields should be transferred by using
the same order. This option should be used along with the
GDALVectorTranslateOptions::eAccessMode = ACCESS_APPEND option. */
char **papszFieldMap;
/*! force the coordinate dimension to nCoordDim (valid values are 2 or 3). This affects both
the layer geometry type, and feature geometries. */
int nCoordDim;
/*! destination dataset open option (format specific), only valid in update mode */
char **papszDestOpenOptions;
/*! If set to true, does not propagate not-nullable constraints to target layer if they exist
in source layer */
bool bForceNullable;
/*! If set to true, does not propagate default field values to target layer if they exist in
source layer */
bool bUnsetDefault;
/*! to prevent the new default behaviour that consists in, if the output driver has a FID layer
creation option and we are not in append mode, to preserve the name of the source FID column
and source feature IDs */
bool bUnsetFid;
/*! use the FID of the source features instead of letting the output driver to automatically
assign a new one. If not in append mode, this behaviour becomes the default if the output
driver has a FID layer creation option. In which case the name of the source FID column will
be used and source feature IDs will be attempted to be preserved. This behaviour can be
disabled by option GDALVectorTranslateOptions::bUnsetFid */
bool bPreserveFID;
/*! set it to false to disable copying of metadata from source dataset and layers into target dataset and
layers, when supported by output driver. */
bool bCopyMD;
/*! list of metadata key and value to set on the output dataset, when supported by output driver.
("META-TAG1=VALUE1","META-TAG2=VALUE2") */
char **papszMetadataOptions;
/*! override spatial filter SRS */
char *pszSpatSRSDef;
/*! size of the list GDALVectorTranslateOptions::pasGCPs */
int nGCPCount;
/*! list of ground control points to be added */
GDAL_GCP *pasGCPs;
/*! order of polynomial used for warping (1 to 3). The default is to select a polynomial
order based on the number of GCPs */
int nTransformOrder;
/*! spatial query extents, in the SRS of the source layer(s) (or the one specified with
GDALVectorTranslateOptions::pszSpatSRSDef). Only features whose geometry intersects the extents
will be selected. The geometries will not be clipped unless GDALVectorTranslateOptions::bClipSrc
is true. */
OGRGeometryH hSpatialFilter;
/*! the progress function to use */
GDALProgressFunc pfnProgress;
/*! pointer to the progress data variable */
void *pProgressData;
/*! Whether layer and feature native data must be transferred. */
bool bNativeData;
};
typedef struct
{
OGRLayer * poSrcLayer;
GIntBig nFeaturesRead;
bool bPerFeatureCT;
OGRLayer *poDstLayer;
OGRCoordinateTransformation **papoCT; // size: poDstLayer->GetLayerDefn()->GetFieldCount();
char ***papapszTransformOptions; // size: poDstLayer->GetLayerDefn()->GetFieldCount();
int *panMap;
int iSrcZField;
int iSrcFIDField;
int iRequestedSrcGeomField;
bool bPreserveFID;
} TargetLayerInfo;
typedef struct
{
OGRLayer *poSrcLayer;
TargetLayerInfo *psInfo;
} AssociatedLayers;
class SetupTargetLayer
{
public:
GDALDataset *m_poDstDS;
char **m_papszLCO;
OGRSpatialReference *m_poOutputSRS;
bool m_bNullifyOutputSRS;
char **m_papszSelFields;
bool m_bAppend;
bool m_bAddMissingFields;
int m_eGType;
GeomTypeConversion m_eGeomTypeConversion;
int m_nCoordDim;
bool m_bOverwrite;
char **m_papszFieldTypesToString;
char **m_papszMapFieldType;
bool m_bUnsetFieldWidth;
bool m_bExplodeCollections;
const char *m_pszZField;
char **m_papszFieldMap;
const char *m_pszWHERE;
bool m_bExactFieldNameMatch;
bool m_bQuiet;
bool m_bForceNullable;
bool m_bUnsetDefault;
bool m_bUnsetFid;
bool m_bPreserveFID;
bool m_bCopyMD;
bool m_bNativeData;
bool m_bNewDataSource;
TargetLayerInfo* Setup(OGRLayer * poSrcLayer,
const char *pszNewLayerName,
GDALVectorTranslateOptions *psOptions);
};
class LayerTranslator
{
public:
GDALDataset *m_poSrcDS;
GDALDataset *m_poODS;
bool m_bTransform;
bool m_bWrapDateline;
CPLString m_osDateLineOffset;
OGRSpatialReference *m_poOutputSRS;
bool m_bNullifyOutputSRS;
OGRSpatialReference *m_poUserSourceSRS;
OGRCoordinateTransformation *m_poGCPCoordTrans;
int m_eGType;
GeomTypeConversion m_eGeomTypeConversion;
int m_nCoordDim;
GeomOperation m_eGeomOp;
double m_dfGeomOpParam;
OGRGeometry *m_poClipSrc;
OGRGeometry *m_poClipDst;
bool m_bExplodeCollections;
vsi_l_offset m_nSrcFileSize;
bool m_bNativeData;
int Translate(TargetLayerInfo* psInfo,
GIntBig nCountLayerFeatures,
GIntBig* pnReadFeatureCount,
GDALProgressFunc pfnProgress,
void *pProgressArg,
GDALVectorTranslateOptions *psOptions);
};
static OGRLayer* GetLayerAndOverwriteIfNecessary(GDALDataset *poDstDS,
const char* pszNewLayerName,
bool bOverwrite,
bool* pbErrorOccurred);
static void FreeTargetLayerInfo(TargetLayerInfo* psInfo);
/************************************************************************/
/* LoadGeometry() */
/************************************************************************/
static OGRGeometry* LoadGeometry( const char* pszDS,
const char* pszSQL,
const char* pszLyr,
const char* pszWhere)
{
GDALDataset *poDS = (GDALDataset*) OGROpen( pszDS, FALSE, NULL );
if (poDS == NULL)
return NULL;
OGRLayer *poLyr;
if (pszSQL != NULL)
poLyr = poDS->ExecuteSQL( pszSQL, NULL, NULL );
else if (pszLyr != NULL)
poLyr = poDS->GetLayerByName(pszLyr);
else
poLyr = poDS->GetLayer(0);
if (poLyr == NULL)
{
CPLError( CE_Failure, CPLE_AppDefined, "Failed to identify source layer from datasource." );
GDALClose(( GDALDatasetH) poDS);
return NULL;
}
if (pszWhere)
poLyr->SetAttributeFilter(pszWhere);
OGRGeometry *poGeom = NULL;
OGRFeature *poFeat;
while ((poFeat = poLyr->GetNextFeature()) != NULL)
{
OGRGeometry* poSrcGeom = poFeat->GetGeometryRef();
if (poSrcGeom)
{
OGRwkbGeometryType eType = wkbFlatten( poSrcGeom->getGeometryType() );
if (poGeom == NULL)
poGeom = OGRGeometryFactory::createGeometry( wkbMultiPolygon );
if( eType == wkbPolygon )
((OGRGeometryCollection*)poGeom)->addGeometry( poSrcGeom );
else if( eType == wkbMultiPolygon )
{
int iGeom;
int nGeomCount = OGR_G_GetGeometryCount( (OGRGeometryH)poSrcGeom );
for( iGeom = 0; iGeom < nGeomCount; iGeom++ )
{
((OGRGeometryCollection*)poGeom)->addGeometry(
((OGRGeometryCollection*)poSrcGeom)->getGeometryRef(iGeom) );
}
}
else
{
CPLError( CE_Failure, CPLE_AppDefined, "Geometry not of polygon type." );
OGRGeometryFactory::destroyGeometry(poGeom);
OGRFeature::DestroyFeature(poFeat);
if( pszSQL != NULL )
poDS->ReleaseResultSet( poLyr );
GDALClose(( GDALDatasetH) poDS);
return NULL;
}
}
OGRFeature::DestroyFeature(poFeat);
}
if( pszSQL != NULL )
poDS->ReleaseResultSet( poLyr );
GDALClose(( GDALDatasetH) poDS);
return poGeom;
}
/************************************************************************/
/* OGRSplitListFieldLayer */
/************************************************************************/
typedef struct
{
int iSrcIndex;
OGRFieldType eType;
int nMaxOccurrences;
int nWidth;
} ListFieldDesc;
class OGRSplitListFieldLayer : public OGRLayer
{
OGRLayer *poSrcLayer;
OGRFeatureDefn *poFeatureDefn;
ListFieldDesc *pasListFields;
int nListFieldCount;
int nMaxSplitListSubFields;
OGRFeature *TranslateFeature(OGRFeature* poSrcFeature);
public:
OGRSplitListFieldLayer(OGRLayer* poSrcLayer,
int nMaxSplitListSubFields);
~OGRSplitListFieldLayer();
bool BuildLayerDefn(GDALProgressFunc pfnProgress,
void *pProgressArg);
virtual OGRFeature *GetNextFeature();
virtual OGRFeature *GetFeature(GIntBig nFID);
virtual OGRFeatureDefn *GetLayerDefn();
virtual void ResetReading() { poSrcLayer->ResetReading(); }
virtual int TestCapability(const char*) { return FALSE; }
virtual GIntBig GetFeatureCount( int bForce = TRUE )
{
return poSrcLayer->GetFeatureCount(bForce);
}
virtual OGRSpatialReference *GetSpatialRef()
{
return poSrcLayer->GetSpatialRef();
}
virtual OGRGeometry *GetSpatialFilter()
{
return poSrcLayer->GetSpatialFilter();
}
virtual OGRStyleTable *GetStyleTable()
{
return poSrcLayer->GetStyleTable();
}
virtual void SetSpatialFilter( OGRGeometry *poGeom )
{
poSrcLayer->SetSpatialFilter(poGeom);
}
virtual void SetSpatialFilter( int iGeom, OGRGeometry *poGeom )
{
poSrcLayer->SetSpatialFilter(iGeom, poGeom);
}
virtual void SetSpatialFilterRect( double dfMinX, double dfMinY,
double dfMaxX, double dfMaxY )
{
poSrcLayer->SetSpatialFilterRect(dfMinX, dfMinY, dfMaxX, dfMaxY);
}
virtual void SetSpatialFilterRect( int iGeom,
double dfMinX, double dfMinY,
double dfMaxX, double dfMaxY )
{
poSrcLayer->SetSpatialFilterRect(iGeom, dfMinX, dfMinY, dfMaxX, dfMaxY);
}
virtual OGRErr SetAttributeFilter( const char *pszFilter )
{
return poSrcLayer->SetAttributeFilter(pszFilter);
}
};
/************************************************************************/
/* OGRSplitListFieldLayer() */
/************************************************************************/
OGRSplitListFieldLayer::OGRSplitListFieldLayer(OGRLayer* poSrcLayerIn,
int nMaxSplitListSubFieldsIn)
{
poSrcLayer = poSrcLayerIn;
nMaxSplitListSubFields = nMaxSplitListSubFieldsIn;
if (nMaxSplitListSubFields < 0)
nMaxSplitListSubFields = INT_MAX;
poFeatureDefn = NULL;
pasListFields = NULL;
nListFieldCount = 0;
}
/************************************************************************/
/* ~OGRSplitListFieldLayer() */
/************************************************************************/
OGRSplitListFieldLayer::~OGRSplitListFieldLayer()
{
if( poFeatureDefn )
poFeatureDefn->Release();
CPLFree(pasListFields);
}
/************************************************************************/
/* BuildLayerDefn() */
/************************************************************************/
bool OGRSplitListFieldLayer::BuildLayerDefn(GDALProgressFunc pfnProgress,
void *pProgressArg)
{
CPLAssert(poFeatureDefn == NULL);
OGRFeatureDefn* poSrcFieldDefn = poSrcLayer->GetLayerDefn();
int nSrcFields = poSrcFieldDefn->GetFieldCount();
pasListFields =
(ListFieldDesc*)CPLCalloc(sizeof(ListFieldDesc), nSrcFields);
nListFieldCount = 0;
/* Establish the list of fields of list type */
for( int i=0; i<nSrcFields; ++i )
{
OGRFieldType eType = poSrcFieldDefn->GetFieldDefn(i)->GetType();
if (eType == OFTIntegerList ||
eType == OFTInteger64List ||
eType == OFTRealList ||
eType == OFTStringList)
{
pasListFields[nListFieldCount].iSrcIndex = i;
pasListFields[nListFieldCount].eType = eType;
if (nMaxSplitListSubFields == 1)
pasListFields[nListFieldCount].nMaxOccurrences = 1;
nListFieldCount++;
}
}
if (nListFieldCount == 0)
return false;
/* No need for full scan if the limit is 1. We just to have to create */
/* one and a single one field */
if (nMaxSplitListSubFields != 1)
{
poSrcLayer->ResetReading();
OGRFeature* poSrcFeature;
GIntBig nFeatureCount = 0;
if (poSrcLayer->TestCapability(OLCFastFeatureCount))
nFeatureCount = poSrcLayer->GetFeatureCount();
GIntBig nFeatureIndex = 0;
/* Scan the whole layer to compute the maximum number of */
/* items for each field of list type */
while( (poSrcFeature = poSrcLayer->GetNextFeature()) != NULL )
{
for( int i=0; i<nListFieldCount; ++i )
{
int nCount = 0;
OGRField* psField =
poSrcFeature->GetRawFieldRef(pasListFields[i].iSrcIndex);
switch(pasListFields[i].eType)
{
case OFTIntegerList:
nCount = psField->IntegerList.nCount;
break;
case OFTRealList:
nCount = psField->RealList.nCount;
break;
case OFTStringList:
{
nCount = psField->StringList.nCount;
char** paList = psField->StringList.paList;
int j;
for(j=0;j<nCount;j++)
{
int nWidth = static_cast<int>(strlen(paList[j]));
if (nWidth > pasListFields[i].nWidth)
pasListFields[i].nWidth = nWidth;
}
break;
}
default:
CPLAssert(0);
break;
}
if (nCount > pasListFields[i].nMaxOccurrences)
{
if (nCount > nMaxSplitListSubFields)
nCount = nMaxSplitListSubFields;
pasListFields[i].nMaxOccurrences = nCount;
}
}
OGRFeature::DestroyFeature(poSrcFeature);
nFeatureIndex ++;
if (pfnProgress != NULL && nFeatureCount != 0)
pfnProgress(nFeatureIndex * 1.0 / nFeatureCount, "", pProgressArg);
}
}
/* Now let's build the target feature definition */
poFeatureDefn =
OGRFeatureDefn::CreateFeatureDefn( poSrcFieldDefn->GetName() );
poFeatureDefn->Reference();
poFeatureDefn->SetGeomType( wkbNone );
for( int i=0; i < poSrcFieldDefn->GetGeomFieldCount(); ++i )
{
poFeatureDefn->AddGeomFieldDefn(poSrcFieldDefn->GetGeomFieldDefn(i));
}
int iListField = 0;
for( int i=0;i<nSrcFields; ++i)
{
OGRFieldType eType = poSrcFieldDefn->GetFieldDefn(i)->GetType();
if (eType == OFTIntegerList ||
eType == OFTInteger64List ||
eType == OFTRealList ||
eType == OFTStringList)
{
int nMaxOccurrences = pasListFields[iListField].nMaxOccurrences;
int nWidth = pasListFields[iListField].nWidth;
iListField ++;
int j;
if (nMaxOccurrences == 1)
{
OGRFieldDefn oFieldDefn(poSrcFieldDefn->GetFieldDefn(i)->GetNameRef(),
(eType == OFTIntegerList) ? OFTInteger :
(eType == OFTInteger64List) ? OFTInteger64 :
(eType == OFTRealList) ? OFTReal :
OFTString);
poFeatureDefn->AddFieldDefn(&oFieldDefn);
}
else
{
for(j=0;j<nMaxOccurrences;j++)
{
CPLString osFieldName;
osFieldName.Printf("%s%d",
poSrcFieldDefn->GetFieldDefn(i)->GetNameRef(), j+1);
OGRFieldDefn oFieldDefn(osFieldName.c_str(),
(eType == OFTIntegerList) ? OFTInteger :
(eType == OFTInteger64List) ? OFTInteger64 :
(eType == OFTRealList) ? OFTReal :
OFTString);
oFieldDefn.SetWidth(nWidth);
poFeatureDefn->AddFieldDefn(&oFieldDefn);
}
}
}
else
{
poFeatureDefn->AddFieldDefn(poSrcFieldDefn->GetFieldDefn(i));
}
}
return true;
}
/************************************************************************/
/* OGR2OGRSpatialReferenceHolder */
/************************************************************************/
class OGR2OGRSpatialReferenceHolder
{
OGRSpatialReference* m_poSRS;
public:
OGR2OGRSpatialReferenceHolder() : m_poSRS(NULL) {}
~OGR2OGRSpatialReferenceHolder() { if( m_poSRS) m_poSRS->Release(); }
void assignNoRefIncrease(OGRSpatialReference* poSRS) {
CPLAssert(m_poSRS == NULL);
m_poSRS = poSRS;
}
OGRSpatialReference* get() { return m_poSRS; }
};
/************************************************************************/
/* TranslateFeature() */
/************************************************************************/
OGRFeature *OGRSplitListFieldLayer::TranslateFeature(OGRFeature* poSrcFeature)
{
if (poSrcFeature == NULL)
return NULL;
if (poFeatureDefn == NULL)
return poSrcFeature;
OGRFeature* poFeature = OGRFeature::CreateFeature(poFeatureDefn);
poFeature->SetFID(poSrcFeature->GetFID());
for(int i=0;i<poFeature->GetGeomFieldCount();i++)
{
poFeature->SetGeomFieldDirectly(i, poSrcFeature->StealGeometry(i));
}
poFeature->SetStyleString(poFeature->GetStyleString());
OGRFeatureDefn* poSrcFieldDefn = poSrcLayer->GetLayerDefn();
int nSrcFields = poSrcFeature->GetFieldCount();
int iDstField = 0;
int iListField = 0;
for( int iSrcField=0; iSrcField < nSrcFields; ++iSrcField)
{
const OGRFieldType eType = poSrcFieldDefn->GetFieldDefn(iSrcField)->GetType();
OGRField* psField = poSrcFeature->GetRawFieldRef(iSrcField);
switch(eType)
{
case OFTIntegerList:
{
int nCount = psField->IntegerList.nCount;
if (nCount > nMaxSplitListSubFields)
nCount = nMaxSplitListSubFields;
int* paList = psField->IntegerList.paList;
for( int j=0;j<nCount; ++j)
poFeature->SetField(iDstField + j, paList[j]);
iDstField += pasListFields[iListField].nMaxOccurrences;
iListField++;
break;
}
case OFTInteger64List:
{
int nCount = psField->Integer64List.nCount;
if (nCount > nMaxSplitListSubFields)
nCount = nMaxSplitListSubFields;
GIntBig* paList = psField->Integer64List.paList;
for( int j=0; j < nCount; ++j )
poFeature->SetField(iDstField + j, paList[j]);
iDstField += pasListFields[iListField].nMaxOccurrences;
iListField++;
break;
}
case OFTRealList:
{
int nCount = psField->RealList.nCount;
if (nCount > nMaxSplitListSubFields)
nCount = nMaxSplitListSubFields;
double* paList = psField->RealList.paList;
for( int j=0; j < nCount; ++j )
poFeature->SetField(iDstField + j, paList[j]);
iDstField += pasListFields[iListField].nMaxOccurrences;
iListField++;
break;
}
case OFTStringList:
{
int nCount = psField->StringList.nCount;
if (nCount > nMaxSplitListSubFields)
nCount = nMaxSplitListSubFields;
char** paList = psField->StringList.paList;
for( int j=0; j < nCount; ++j )
poFeature->SetField(iDstField + j, paList[j]);
iDstField += pasListFields[iListField].nMaxOccurrences;
iListField++;
break;
}
default:
poFeature->SetField(iDstField, psField);
iDstField ++;
break;
}
}
OGRFeature::DestroyFeature(poSrcFeature);
return poFeature;
}
/************************************************************************/
/* GetNextFeature() */
/************************************************************************/
OGRFeature *OGRSplitListFieldLayer::GetNextFeature()
{
return TranslateFeature(poSrcLayer->GetNextFeature());
}
/************************************************************************/
/* GetFeature() */
/************************************************************************/
OGRFeature *OGRSplitListFieldLayer::GetFeature(GIntBig nFID)
{
return TranslateFeature(poSrcLayer->GetFeature(nFID));
}
/************************************************************************/
/* GetLayerDefn() */
/************************************************************************/
OGRFeatureDefn* OGRSplitListFieldLayer::GetLayerDefn()
{
if (poFeatureDefn == NULL)
return poSrcLayer->GetLayerDefn();
return poFeatureDefn;
}
/************************************************************************/
/* GCPCoordTransformation() */
/* */
/* Apply GCP Transform to points */
/************************************************************************/
class GCPCoordTransformation : public OGRCoordinateTransformation
{
public:
void *hTransformArg;
bool bUseTPS;
OGRSpatialReference* poSRS;
GCPCoordTransformation( int nGCPCount,
const GDAL_GCP *pasGCPList,
int nReqOrder,
OGRSpatialReference* poSRSIn)
{
if( nReqOrder < 0 )
{
bUseTPS = true;
hTransformArg =
GDALCreateTPSTransformer( nGCPCount, pasGCPList, FALSE );
}
else
{
bUseTPS = false;
hTransformArg =
GDALCreateGCPTransformer( nGCPCount, pasGCPList, nReqOrder, FALSE );
}
poSRS = poSRSIn;
if( poSRS)
poSRS->Reference();
}
bool IsValid() const { return hTransformArg != NULL; }
virtual ~GCPCoordTransformation()
{
if( hTransformArg != NULL )
{
if( bUseTPS )
GDALDestroyTPSTransformer(hTransformArg);
else
GDALDestroyGCPTransformer(hTransformArg);
}
if( poSRS)
poSRS->Dereference();
}
virtual OGRSpatialReference *GetSourceCS() { return poSRS; }
virtual OGRSpatialReference *GetTargetCS() { return poSRS; }
virtual int Transform( int nCount,
double *x, double *y, double *z = NULL )
{
int *pabSuccess = (int *) CPLMalloc(sizeof(int) * nCount );
bool bOverallSuccess = CPL_TO_BOOL(TransformEx( nCount, x, y, z, pabSuccess ));
for( int i = 0; i < nCount; ++i )
{
if( !pabSuccess[i] )
{
bOverallSuccess = false;
break;
}
}
CPLFree( pabSuccess );
return bOverallSuccess;
}
virtual int TransformEx( int nCount,
double *x, double *y, double *z = NULL,
int *pabSuccess = NULL )
{
if( bUseTPS )
return GDALTPSTransform( hTransformArg, FALSE,
nCount, x, y, z, pabSuccess );
else
return GDALGCPTransform( hTransformArg, FALSE,
nCount, x, y, z, pabSuccess );
}
};
/************************************************************************/
/* CompositeCT */
/************************************************************************/
class CompositeCT : public OGRCoordinateTransformation
{
public:
OGRCoordinateTransformation* poCT1;
OGRCoordinateTransformation* poCT2;
CompositeCT( OGRCoordinateTransformation* poCT1In, /* will not be deleted */
OGRCoordinateTransformation* poCT2In /* deleted with OGRCoordinateTransformation::DestroyCT() */ )
{
poCT1 = poCT1In;
poCT2 = poCT2In;
}
virtual ~CompositeCT()
{
OGRCoordinateTransformation::DestroyCT(poCT2);
}
virtual OGRSpatialReference *GetSourceCS()
{
return poCT1 ? poCT1->GetSourceCS() :
poCT2 ? poCT2->GetSourceCS() : NULL;
}
virtual OGRSpatialReference *GetTargetCS()
{
return poCT2 ? poCT2->GetTargetCS() :
poCT1 ? poCT1->GetTargetCS() : NULL;
}
virtual int Transform( int nCount,
double *x, double *y, double *z = NULL )
{
int nResult = TRUE;
if( poCT1 )
nResult = poCT1->Transform(nCount, x, y, z);
if( nResult && poCT2 )
nResult = poCT2->Transform(nCount, x, y, z);
return nResult;
}
virtual int TransformEx( int nCount,
double *x, double *y, double *z = NULL,
int *pabSuccess = NULL )
{
int nResult = TRUE;
if( poCT1 )
nResult = poCT1->TransformEx(nCount, x, y, z, pabSuccess);
if( nResult && poCT2 )
nResult = poCT2->TransformEx(nCount, x, y, z, pabSuccess);
return nResult;
}
};
/************************************************************************/
/* ApplySpatialFilter() */
/************************************************************************/
static
void ApplySpatialFilter(OGRLayer* poLayer, OGRGeometry* poSpatialFilter,
OGRSpatialReference* poSpatSRS,
const char* pszGeomField,
OGRSpatialReference* poSourceSRS)
{
if( poSpatialFilter != NULL )
{
OGRGeometry* poSpatialFilterReprojected = NULL;
if( poSpatSRS )
{
poSpatialFilterReprojected = poSpatialFilter->clone();
poSpatialFilterReprojected->assignSpatialReference(poSpatSRS);
OGRSpatialReference* poSpatialFilterTargetSRS = poSourceSRS ? poSourceSRS : poLayer->GetSpatialRef();
if( poSpatialFilterTargetSRS )
poSpatialFilterReprojected->transformTo(poSpatialFilterTargetSRS);
else
CPLError(CE_Warning, CPLE_AppDefined, "cannot determine layer SRS for %s.", poLayer->GetDescription());
}
if( pszGeomField != NULL )
{
int iGeomField = poLayer->GetLayerDefn()->GetGeomFieldIndex(pszGeomField);
if( iGeomField >= 0 )
poLayer->SetSpatialFilter( iGeomField,
poSpatialFilterReprojected ? poSpatialFilterReprojected : poSpatialFilter );
else
CPLError( CE_Warning, CPLE_AppDefined,"Cannot find geometry field %s.",
pszGeomField);
}
else
poLayer->SetSpatialFilter( poSpatialFilterReprojected ? poSpatialFilterReprojected : poSpatialFilter );
delete poSpatialFilterReprojected;
}
}
/************************************************************************/
/* GetFieldType() */
/************************************************************************/
static int GetFieldType(const char* pszArg, int* pnSubFieldType)
{
*pnSubFieldType = OFSTNone;
int nLengthBeforeParenthesis = static_cast<int>(strlen(pszArg));
const char* pszOpenParenthesis = strchr(pszArg, '(');
if( pszOpenParenthesis )
nLengthBeforeParenthesis = static_cast<int>(pszOpenParenthesis - pszArg);
for( int iType = 0; iType <= (int) OFTMaxType; iType++ )
{
const char* pszFieldTypeName = OGRFieldDefn::GetFieldTypeName(
(OGRFieldType)iType);
if( EQUALN(pszArg,pszFieldTypeName,nLengthBeforeParenthesis) &&
pszFieldTypeName[nLengthBeforeParenthesis] == '\0' )
{
if( pszOpenParenthesis != NULL )
{
*pnSubFieldType = -1;
CPLString osArgSubType = pszOpenParenthesis + 1;
if( osArgSubType.size() && osArgSubType[osArgSubType.size()-1] == ')' )
osArgSubType.resize(osArgSubType.size()-1);
for( int iSubType = 0; iSubType <= (int) OFSTMaxSubType; iSubType++ )
{
const char* pszFieldSubTypeName = OGRFieldDefn::GetFieldSubTypeName(
(OGRFieldSubType)iSubType);
if( EQUAL( pszFieldSubTypeName, osArgSubType ) )
{
*pnSubFieldType = iSubType;
break;
}
}
}
return iType;
}
}
return -1;
}
/************************************************************************/
/* IsNumber() */
/************************************************************************/
static bool IsNumber(const char* pszStr)
{
if (*pszStr == '-' || *pszStr == '+')
pszStr ++;
if (*pszStr == '.')
pszStr ++;
return (*pszStr >= '0' && *pszStr <= '9');
}
/************************************************************************/
/* IsFieldType() */
/************************************************************************/
static bool IsFieldType(const char* pszArg)
{
int iSubType;
return GetFieldType(pszArg, &iSubType) >= 0 && iSubType >= 0;
}
/************************************************************************/
/* GDALVectorTranslateOptionsClone() */
/************************************************************************/
static
GDALVectorTranslateOptions* GDALVectorTranslateOptionsClone(const GDALVectorTranslateOptions *psOptionsIn)
{
GDALVectorTranslateOptions* psOptions = (GDALVectorTranslateOptions*) CPLMalloc(sizeof(GDALVectorTranslateOptions));
memcpy(psOptions, psOptionsIn, sizeof(GDALVectorTranslateOptions));
psOptions->pszFormat = CPLStrdup(psOptionsIn->pszFormat);
if( psOptionsIn->pszOutputSRSDef ) psOptions->pszOutputSRSDef = CPLStrdup(psOptionsIn->pszOutputSRSDef);
if( psOptionsIn->pszSourceSRSDef ) psOptions->pszSourceSRSDef = CPLStrdup(psOptionsIn->pszSourceSRSDef);
if( psOptionsIn->pszNewLayerName ) psOptions->pszNewLayerName = CPLStrdup(psOptionsIn->pszNewLayerName);
if( psOptionsIn->pszWHERE ) psOptions->pszWHERE = CPLStrdup(psOptionsIn->pszWHERE);
if( psOptionsIn->pszGeomField ) psOptions->pszGeomField = CPLStrdup(psOptionsIn->pszGeomField);
if( psOptionsIn->pszSQLStatement ) psOptions->pszSQLStatement = CPLStrdup(psOptionsIn->pszSQLStatement);
if( psOptionsIn->pszDialect ) psOptions->pszDialect = CPLStrdup(psOptionsIn->pszDialect);
if( psOptionsIn->pszClipSrcDS ) psOptions->pszClipSrcDS = CPLStrdup(psOptionsIn->pszClipSrcDS);
if( psOptionsIn->pszClipSrcSQL ) psOptions->pszClipSrcSQL = CPLStrdup(psOptionsIn->pszClipSrcSQL);
if( psOptionsIn->pszClipSrcLayer ) psOptions->pszClipSrcLayer = CPLStrdup(psOptionsIn->pszClipSrcLayer);
if( psOptionsIn->pszClipSrcWhere ) psOptions->pszClipSrcWhere = CPLStrdup(psOptionsIn->pszClipSrcWhere);
if( psOptionsIn->pszClipDstDS ) psOptions->pszClipDstDS = CPLStrdup(psOptionsIn->pszClipDstDS);
if( psOptionsIn->pszClipDstSQL ) psOptions->pszClipDstSQL = CPLStrdup(psOptionsIn->pszClipDstSQL);
if( psOptionsIn->pszClipDstLayer ) psOptions->pszClipDstLayer = CPLStrdup(psOptionsIn->pszClipDstLayer);
if( psOptionsIn->pszClipDstWhere ) psOptions->pszClipDstWhere = CPLStrdup(psOptionsIn->pszClipDstWhere);
if( psOptionsIn->pszZField ) psOptions->pszZField = CPLStrdup(psOptionsIn->pszZField);
if( psOptionsIn->pszSpatSRSDef ) psOptions->pszSpatSRSDef = CPLStrdup(psOptionsIn->pszSpatSRSDef);
psOptions->papszSelFields = CSLDuplicate(psOptionsIn->papszSelFields);
psOptions->papszFieldMap = CSLDuplicate(psOptionsIn->papszFieldMap);
psOptions->papszMapFieldType = CSLDuplicate(psOptionsIn->papszMapFieldType);
psOptions->papszLayers = CSLDuplicate(psOptionsIn->papszLayers);
psOptions->papszDSCO = CSLDuplicate(psOptionsIn->papszDSCO);
psOptions->papszLCO = CSLDuplicate(psOptionsIn->papszLCO);
psOptions->papszDestOpenOptions = CSLDuplicate(psOptionsIn->papszDestOpenOptions);
psOptions->papszFieldTypesToString = CSLDuplicate(psOptionsIn->papszFieldTypesToString);
psOptions->papszMetadataOptions = CSLDuplicate(psOptionsIn->papszMetadataOptions);
if( psOptionsIn->nGCPCount )
psOptions->pasGCPs = GDALDuplicateGCPs( psOptionsIn->nGCPCount, psOptionsIn->pasGCPs );
psOptions->hClipSrc = ( psOptionsIn->hClipSrc != NULL ) ? OGR_G_Clone(psOptionsIn->hClipSrc) : NULL;
psOptions->hClipDst = ( psOptionsIn->hClipDst != NULL ) ? OGR_G_Clone(psOptionsIn->hClipDst) : NULL;
psOptions->hSpatialFilter = ( psOptionsIn->hSpatialFilter != NULL ) ? OGR_G_Clone(psOptionsIn->hSpatialFilter) : NULL;
return psOptions;
}
/************************************************************************/
/* GDALVectorTranslate() */
/************************************************************************/
/**
* Converts vector data between file formats.
*
* This is the equivalent of the <a href="ogr2ogr.html">ogr2ogr</a> utility.
*
* GDALVectorTranslateOptions* must be allocated and freed with GDALVectorTranslateOptionsNew()
* and GDALVectorTranslateOptionsFree() respectively.
* pszDest and hDstDS cannot be used at the same time.
*
* @param pszDest the destination dataset path or NULL.
* @param hDstDS the destination dataset or NULL.
* @param nSrcCount the number of input datasets (only 1 supported currently)
* @param pahSrcDS the list of input datasets.
* @param psOptionsIn the options struct returned by GDALVectorTranslateOptionsNew() or NULL.
* @param pbUsageError the pointer to int variable to determine any usage error has occurred
* @return the output dataset (new dataset that must be closed using GDALClose(), or hDstDS is not NULL) or NULL in case of error.
*
* @since GDAL 2.1
*/
GDALDatasetH GDALVectorTranslate( const char *pszDest, GDALDatasetH hDstDS, int nSrcCount,
GDALDatasetH *pahSrcDS,
const GDALVectorTranslateOptions *psOptionsIn, int *pbUsageError )
{
OGR2OGRSpatialReferenceHolder oOutputSRSHolder;
OGRSpatialReference oSourceSRS;
OGRSpatialReference oSpatSRS;
OGRSpatialReference *poSourceSRS = NULL;
OGRSpatialReference* poSpatSRS = NULL;
bool bAppend = false;
bool bUpdate = false;
bool bOverwrite = false;
CPLString osDateLineOffset;
int nRetCode = 0;
if( pszDest == NULL && hDstDS == NULL )
{
CPLError( CE_Failure, CPLE_AppDefined, "pszDest == NULL && hDstDS == NULL");
if(pbUsageError)
*pbUsageError = TRUE;
return NULL;
}
if( nSrcCount != 1 )
{
CPLError( CE_Failure, CPLE_AppDefined, "nSrcCount != 1");
if(pbUsageError)
*pbUsageError = TRUE;
return NULL;
}
GDALDatasetH hSrcDS = pahSrcDS[0];
if( hSrcDS == NULL )
{
CPLError( CE_Failure, CPLE_AppDefined, "hSrcDS == NULL");
if(pbUsageError)
*pbUsageError = TRUE;
return NULL;
}
GDALVectorTranslateOptions* psOptions =
(psOptionsIn) ? GDALVectorTranslateOptionsClone(psOptionsIn) :
GDALVectorTranslateOptionsNew(NULL, NULL);
if( psOptions->eAccessMode == ACCESS_UPDATE )
{
bUpdate = true;
}
else if ( psOptions->eAccessMode == ACCESS_APPEND )
{
bAppend = true;
bUpdate = true;
}
else if ( psOptions->eAccessMode == ACCESS_OVERWRITE )
{
bOverwrite = true;
bUpdate = true;
}
else if( hDstDS != NULL )
{
bUpdate = true;
}
osDateLineOffset = CPLOPrintf("%g", psOptions->dfDateLineOffset);
if( psOptions->bPreserveFID && psOptions->bExplodeCollections )
{
CPLError( CE_Failure, CPLE_IllegalArg, "cannot use -preserve_fid and -explodecollections at the same time.");
if(pbUsageError)
*pbUsageError = TRUE;
GDALVectorTranslateOptionsFree(psOptions);
return NULL;
}
if (psOptions->papszFieldMap && !bAppend)
{
CPLError( CE_Failure, CPLE_IllegalArg, "if -fieldmap is specified, -append must also be specified");
if(pbUsageError)
*pbUsageError = TRUE;
GDALVectorTranslateOptionsFree(psOptions);
return NULL;
}
if (psOptions->papszFieldMap && psOptions->bAddMissingFields)
{
CPLError( CE_Failure, CPLE_IllegalArg, "if -addfields is specified, -fieldmap cannot be used.");
if(pbUsageError)
*pbUsageError = TRUE;
GDALVectorTranslateOptionsFree(psOptions);
return NULL;
}
if( psOptions->papszFieldTypesToString && psOptions->papszMapFieldType )
{
CPLError( CE_Failure, CPLE_IllegalArg, "-fieldTypeToString and -mapFieldType are exclusive.");
if(pbUsageError)
*pbUsageError = TRUE;
GDALVectorTranslateOptionsFree(psOptions);
return NULL;
}
if( psOptions->pszSourceSRSDef != NULL && psOptions->pszOutputSRSDef == NULL && psOptions->pszSpatSRSDef == NULL )
{
CPLError( CE_Failure, CPLE_IllegalArg, "if -s_srs is specified, -t_srs and/or -spat_srs must also be specified.");
if(pbUsageError)
*pbUsageError = TRUE;
GDALVectorTranslateOptionsFree(psOptions);
return NULL;
}
if( psOptions->bClipSrc && psOptions->pszClipSrcDS != NULL)
{
psOptions->hClipSrc = (OGRGeometryH) LoadGeometry(psOptions->pszClipSrcDS, psOptions->pszClipSrcSQL, psOptions->pszClipSrcLayer, psOptions->pszClipSrcWhere);
if (psOptions->hClipSrc == NULL)
{
CPLError( CE_Failure,CPLE_IllegalArg, "cannot load source clip geometry");
GDALVectorTranslateOptionsFree(psOptions);
return NULL;
}
}
else if( psOptions->bClipSrc && psOptions->hClipSrc == NULL )
{
if (psOptions->hSpatialFilter)
psOptions->hClipSrc = (OGRGeometryH)((OGRGeometry *)(psOptions->hSpatialFilter))->clone();
if (psOptions->hClipSrc == NULL)
{
CPLError( CE_Failure, CPLE_IllegalArg, "-clipsrc must be used with -spat option or a\n"
"bounding box, WKT string or datasource must be specified");
if(pbUsageError)
*pbUsageError = TRUE;
GDALVectorTranslateOptionsFree(psOptions);
return NULL;
}
}
if( psOptions->pszClipDstDS != NULL)
{
psOptions->hClipDst = (OGRGeometryH) LoadGeometry(psOptions->pszClipDstDS, psOptions->pszClipDstSQL, psOptions->pszClipDstLayer, psOptions->pszClipDstWhere);
if (psOptions->hClipDst == NULL)
{
CPLError( CE_Failure, CPLE_IllegalArg, "cannot load dest clip geometry");
GDALVectorTranslateOptionsFree(psOptions);
return NULL;
}
}
GDALDataset *poDS = (GDALDataset *) hSrcDS;
GDALDataset *poODS = NULL;
GDALDriver *poDriver = NULL;
CPLString osDestFilename;
if(hDstDS)
{
poODS = (GDALDataset *) hDstDS;
osDestFilename = poODS->GetDescription();
}
else
osDestFilename = pszDest;
/* Various tests to avoid overwriting the source layer(s) */
/* or to avoid appending a layer to itself */
if( bUpdate && strcmp(osDestFilename, poDS->GetDescription()) == 0 &&
(bOverwrite || bAppend) )
{
bool bError = false;
if (psOptions->pszNewLayerName == NULL)
bError = true;
else if (CSLCount(psOptions->papszLayers) == 1)
bError = strcmp(psOptions->pszNewLayerName, psOptions->papszLayers[0]) == 0;
else if (psOptions->pszSQLStatement == NULL)
bError = true;
if (bError)
{
CPLError( CE_Failure, CPLE_IllegalArg,
"-nln name must be specified combined with "
"a single source layer name,\nor a -sql statement, and "
"name must be different from an existing layer.");
GDALVectorTranslateOptionsFree(psOptions);
return NULL;
}
}
/* -------------------------------------------------------------------- */
/* Try opening the output datasource as an existing, writable */
/* -------------------------------------------------------------------- */
if( bUpdate && poODS == NULL )
{
poODS = (GDALDataset*) GDALOpenEx( osDestFilename,
GDAL_OF_UPDATE | GDAL_OF_VECTOR, NULL, psOptions->papszDestOpenOptions, NULL );
if( poODS == NULL )
{
if (bOverwrite || bAppend)
{
poODS = (GDALDataset*) GDALOpenEx( osDestFilename,
GDAL_OF_VECTOR, NULL, psOptions->papszDestOpenOptions, NULL );
if (poODS == NULL)
{
/* OK the datasource doesn't exist at all */
bUpdate = false;
}
else
{
if( poODS != NULL )
poDriver = poODS->GetDriver();
GDALClose( (GDALDatasetH) poODS );
poODS = NULL;
}
}
if (bUpdate)
{
CPLError( CE_Failure, CPLE_AppDefined,
"Unable to open existing output datasource `%s'.",
osDestFilename.c_str() );
GDALVectorTranslateOptionsFree(psOptions);
return NULL;
}
}
else if( CSLCount(psOptions->papszDSCO) > 0 )
{
CPLError( CE_Warning, CPLE_AppDefined, "Datasource creation options ignored since an existing datasource\n"
" being updated." );
}
}
if( poODS )
poDriver = poODS->GetDriver();
/* -------------------------------------------------------------------- */
/* Find the output driver. */
/* -------------------------------------------------------------------- */
bool bNewDataSource = false;
if( !bUpdate )
{
OGRSFDriverRegistrar *poR = OGRSFDriverRegistrar::GetRegistrar();
poDriver = poR->GetDriverByName(psOptions->pszFormat);
if( poDriver == NULL )
{
CPLError( CE_Failure, CPLE_AppDefined, "Unable to find driver `%s'.", psOptions->pszFormat );
fprintf( stderr, "The following drivers are available:\n" );
for( int iDriver = 0; iDriver < poR->GetDriverCount(); iDriver++ )
{
fprintf( stderr, " -> `%s'\n", poR->GetDriver(iDriver)->GetDescription() );
}
GDALVectorTranslateOptionsFree(psOptions);
return NULL;
}
if( !CPLTestBool( CSLFetchNameValueDef(poDriver->GetMetadata(), GDAL_DCAP_CREATE, "FALSE") ) )
{
CPLError( CE_Failure, CPLE_AppDefined, "%s driver does not support data source creation.",
psOptions->pszFormat );
GDALVectorTranslateOptionsFree(psOptions);
return NULL;
}
if( psOptions->papszDestOpenOptions != NULL )
{
CPLError(CE_Warning, CPLE_AppDefined, "-doo ignored when creating the output datasource.");
}
/* -------------------------------------------------------------------- */
/* Special case to improve user experience when translating */
/* a datasource with multiple layers into a shapefile. If the */
/* user gives a target datasource with .shp and it does not exist, */
/* the shapefile driver will try to create a file, but this is not */
/* appropriate because here we have several layers, so create */
/* a directory instead. */
/* -------------------------------------------------------------------- */
VSIStatBufL sStat;
if (EQUAL(poDriver->GetDescription(), "ESRI Shapefile") &&
psOptions->pszSQLStatement == NULL &&
(CSLCount(psOptions->papszLayers) > 1 ||
(CSLCount(psOptions->papszLayers) == 0 && poDS->GetLayerCount() > 1)) &&
psOptions->pszNewLayerName == NULL &&
EQUAL(CPLGetExtension(osDestFilename), "SHP") &&
VSIStatL(osDestFilename, &sStat) != 0)
{
if (VSIMkdir(osDestFilename, 0755) != 0)
{
CPLError( CE_Failure, CPLE_AppDefined,
"Failed to create directory %s\n"
"for shapefile datastore.",
osDestFilename.c_str() );
GDALVectorTranslateOptionsFree(psOptions);
return NULL;
}
}
/* -------------------------------------------------------------------- */
/* Create the output data source. */
/* -------------------------------------------------------------------- */
poODS = poDriver->Create( osDestFilename, 0, 0, 0, GDT_Unknown, psOptions->papszDSCO );
if( poODS == NULL )
{
CPLError( CE_Failure, CPLE_AppDefined, "%s driver failed to create %s",
psOptions->pszFormat, osDestFilename.c_str() );
GDALVectorTranslateOptionsFree(psOptions);
return NULL;
}
bNewDataSource = true;
if( psOptions->bCopyMD )
{
char** papszDomains = poDS->GetMetadataDomainList();
for(char** papszIter = papszDomains; papszIter && *papszIter; ++papszIter )
{
char** papszMD = poDS->GetMetadata(*papszIter);
if( papszMD )
poODS->SetMetadata(papszMD, *papszIter);
}
CSLDestroy(papszDomains);
}
for(char** papszIter = psOptions->papszMetadataOptions; papszIter && *papszIter; ++papszIter )
{
char *pszKey = NULL;
const char *pszValue = CPLParseNameValue( *papszIter, &pszKey );
if( pszKey )
{
poODS->SetMetadataItem(pszKey,pszValue);
CPLFree( pszKey );
}
}
}
if( psOptions->nLayerTransaction < 0 )
psOptions->nLayerTransaction = !poODS->TestCapability(ODsCTransactions);
/* -------------------------------------------------------------------- */
/* Parse the output SRS definition if possible. */
/* -------------------------------------------------------------------- */
if( psOptions->pszOutputSRSDef != NULL )
{
oOutputSRSHolder.assignNoRefIncrease(new OGRSpatialReference());
if( oOutputSRSHolder.get()->
SetFromUserInput( psOptions->pszOutputSRSDef ) != OGRERR_NONE )
{
CPLError( CE_Failure, CPLE_AppDefined, "Failed to process SRS definition: %s",
psOptions->pszOutputSRSDef );
GDALVectorTranslateOptionsFree(psOptions);
if( hDstDS == NULL ) GDALClose( poODS );
return NULL;
}
}
/* -------------------------------------------------------------------- */
/* Parse the source SRS definition if possible. */
/* -------------------------------------------------------------------- */
if( psOptions->pszSourceSRSDef != NULL )
{
if( oSourceSRS.SetFromUserInput( psOptions->pszSourceSRSDef ) != OGRERR_NONE )
{
CPLError( CE_Failure, CPLE_AppDefined, "Failed to process SRS definition: %s",
psOptions->pszSourceSRSDef );
GDALVectorTranslateOptionsFree(psOptions);
if( hDstDS == NULL ) GDALClose( poODS );
return NULL;
}
poSourceSRS = &oSourceSRS;
}
/* -------------------------------------------------------------------- */
/* Parse spatial filter SRS if needed. */
/* -------------------------------------------------------------------- */
if( psOptions->hSpatialFilter != NULL && psOptions->pszSpatSRSDef != NULL )
{
if( psOptions->pszSQLStatement )
{
CPLError( CE_Failure, CPLE_IllegalArg, "-spat_srs not compatible with -sql.");
GDALVectorTranslateOptionsFree(psOptions);
if( hDstDS == NULL ) GDALClose( poODS );
return NULL;
}
OGREnvelope sEnvelope;
((OGRGeometry*)psOptions->hSpatialFilter)->getEnvelope(&sEnvelope);
if( oSpatSRS.SetFromUserInput( psOptions->pszSpatSRSDef ) != OGRERR_NONE )
{
CPLError( CE_Failure, CPLE_AppDefined, "Failed to process SRS definition: %s",
psOptions->pszSpatSRSDef );
GDALVectorTranslateOptionsFree(psOptions);
if( hDstDS == NULL ) GDALClose( poODS );
return NULL;
}
poSpatSRS = &oSpatSRS;
}
/* -------------------------------------------------------------------- */
/* Create a transformation object from the source to */
/* destination coordinate system. */
/* -------------------------------------------------------------------- */
GCPCoordTransformation *poGCPCoordTrans = NULL;
if( psOptions->nGCPCount > 0 )
{
poGCPCoordTrans = new GCPCoordTransformation( psOptions->nGCPCount, psOptions->pasGCPs,
psOptions->nTransformOrder,
poSourceSRS ? poSourceSRS : oOutputSRSHolder.get() );
if( !(poGCPCoordTrans->IsValid()) )
{
delete poGCPCoordTrans;
poGCPCoordTrans = NULL;
}
}
/* -------------------------------------------------------------------- */
/* For OSM file. */
/* -------------------------------------------------------------------- */
int bSrcIsOSM = (strcmp(poDS->GetDriverName(), "OSM") == 0);
vsi_l_offset nSrcFileSize = 0;
if( bSrcIsOSM && strcmp(poDS->GetDescription(), "/vsistdin/") != 0)
{
VSIStatBufL sStat;
if( VSIStatL(poDS->GetDescription(), &sStat) == 0 )
nSrcFileSize = sStat.st_size;
}
/* -------------------------------------------------------------------- */
/* Create layer setup and transformer objects. */
/* -------------------------------------------------------------------- */
SetupTargetLayer oSetup;
oSetup.m_poDstDS = poODS;
oSetup.m_papszLCO = psOptions->papszLCO;
oSetup.m_poOutputSRS = oOutputSRSHolder.get();
oSetup.m_bNullifyOutputSRS = psOptions->bNullifyOutputSRS;
oSetup.m_papszSelFields = psOptions->papszSelFields;
oSetup.m_bAppend = bAppend;
oSetup.m_bAddMissingFields = psOptions->bAddMissingFields;
oSetup.m_eGType = psOptions->eGType;
oSetup.m_eGeomTypeConversion = psOptions->eGeomTypeConversion;
oSetup.m_nCoordDim = psOptions->nCoordDim;
oSetup.m_bOverwrite = bOverwrite;
oSetup.m_papszFieldTypesToString = psOptions->papszFieldTypesToString;
oSetup.m_papszMapFieldType = psOptions->papszMapFieldType;
oSetup.m_bUnsetFieldWidth = psOptions->bUnsetFieldWidth;
oSetup.m_bExplodeCollections = psOptions->bExplodeCollections;
oSetup.m_pszZField = psOptions->pszZField;
oSetup.m_papszFieldMap = psOptions->papszFieldMap;
oSetup.m_pszWHERE = psOptions->pszWHERE;
oSetup.m_bExactFieldNameMatch = psOptions->bExactFieldNameMatch;
oSetup.m_bQuiet = psOptions->bQuiet;
oSetup.m_bForceNullable = psOptions->bForceNullable;
oSetup.m_bUnsetDefault = psOptions->bUnsetDefault;
oSetup.m_bUnsetFid = psOptions->bUnsetFid;
oSetup.m_bPreserveFID = psOptions->bPreserveFID;
oSetup.m_bCopyMD = psOptions->bCopyMD;
oSetup.m_bNativeData = psOptions->bNativeData;
oSetup.m_bNewDataSource = bNewDataSource;
LayerTranslator oTranslator;
oTranslator.m_poSrcDS = poDS;
oTranslator.m_poODS = poODS;
oTranslator.m_bTransform = psOptions->bTransform;
oTranslator.m_bWrapDateline = psOptions->bWrapDateline;
oTranslator.m_osDateLineOffset = osDateLineOffset;
oTranslator.m_poOutputSRS = oOutputSRSHolder.get();
oTranslator.m_bNullifyOutputSRS = psOptions->bNullifyOutputSRS;
oTranslator.m_poUserSourceSRS = poSourceSRS;
oTranslator.m_poGCPCoordTrans = poGCPCoordTrans;
oTranslator.m_eGType = psOptions->eGType;
oTranslator.m_eGeomTypeConversion = psOptions->eGeomTypeConversion;
oTranslator.m_nCoordDim = psOptions->nCoordDim;
oTranslator.m_eGeomOp = psOptions->eGeomOp;
oTranslator.m_dfGeomOpParam = psOptions->dfGeomOpParam;
oTranslator.m_poClipSrc = (OGRGeometry *)psOptions->hClipSrc;
oTranslator.m_poClipDst = (OGRGeometry *)psOptions->hClipDst;
oTranslator.m_bExplodeCollections = psOptions->bExplodeCollections;
oTranslator.m_nSrcFileSize = nSrcFileSize;
oTranslator.m_bNativeData = psOptions->bNativeData;
if( psOptions->nGroupTransactions )
{
if( !psOptions->nLayerTransaction )
poODS->StartTransaction(psOptions->bForceTransaction);
}
/* -------------------------------------------------------------------- */
/* Special case for -sql clause. No source layers required. */
/* -------------------------------------------------------------------- */
if( psOptions->pszSQLStatement != NULL )
{
/* Special case: if output=input, then we must likely destroy the */
/* old table before to avoid transaction issues. */
if( poDS == poODS && psOptions->pszNewLayerName != NULL && bOverwrite )
GetLayerAndOverwriteIfNecessary(poODS, psOptions->pszNewLayerName, bOverwrite, NULL);
if( psOptions->pszWHERE != NULL )
CPLError( CE_Warning, CPLE_AppDefined, "-where clause ignored in combination with -sql." );
if( CSLCount(psOptions->papszLayers) > 0 )
CPLError( CE_Warning, CPLE_AppDefined, "layer names ignored in combination with -sql." );
OGRLayer *poResultSet
= poDS->ExecuteSQL( psOptions->pszSQLStatement,
(psOptions->pszGeomField == NULL) ? (OGRGeometry*)psOptions->hSpatialFilter : NULL,
psOptions->pszDialect );
if( poResultSet != NULL )
{
if( psOptions->hSpatialFilter != NULL && psOptions->pszGeomField != NULL )
{
int iGeomField = poResultSet->GetLayerDefn()->GetGeomFieldIndex(psOptions->pszGeomField);
if( iGeomField >= 0 )
poResultSet->SetSpatialFilter( iGeomField, (OGRGeometry*)psOptions->hSpatialFilter );
else
CPLError( CE_Warning, CPLE_AppDefined, "Cannot find geometry field %s.",
psOptions->pszGeomField);
}
GIntBig nCountLayerFeatures = 0;
GDALProgressFunc pfnProgress = NULL;
void *pProgressArg = NULL;
if (psOptions->bDisplayProgress)
{
if (bSrcIsOSM)
{
pfnProgress = psOptions->pfnProgress;
pProgressArg = psOptions->pProgressData;
}
else if (!poResultSet->TestCapability(OLCFastFeatureCount))
{
CPLError( CE_Warning, CPLE_AppDefined, "Progress turned off as fast feature count is not available.");
psOptions->bDisplayProgress = false;
}
else
{
nCountLayerFeatures = poResultSet->GetFeatureCount();
pfnProgress = psOptions->pfnProgress;
pProgressArg = psOptions->pProgressData;
}
}
OGRLayer* poPassedLayer = poResultSet;
if (psOptions->bSplitListFields)
{
poPassedLayer = new OGRSplitListFieldLayer(poPassedLayer, psOptions->nMaxSplitListSubFields);
int nRet = ((OGRSplitListFieldLayer*)poPassedLayer)->BuildLayerDefn(NULL, NULL);
if (!nRet)
{
delete poPassedLayer;
poPassedLayer = poResultSet;
}
}
/* -------------------------------------------------------------------- */
/* Special case to improve user experience when translating into */
/* single file shapefile and source has only one layer, and that */
/* the layer name isn't specified */
/* -------------------------------------------------------------------- */
VSIStatBufL sStat;
if (EQUAL(poDriver->GetDescription(), "ESRI Shapefile") &&
psOptions->pszNewLayerName == NULL &&
VSIStatL(osDestFilename, &sStat) == 0 && VSI_ISREG(sStat.st_mode))
{
psOptions->pszNewLayerName = CPLStrdup(CPLGetBasename(osDestFilename));
}
TargetLayerInfo* psInfo = oSetup.Setup(poPassedLayer,
psOptions->pszNewLayerName,
psOptions);
poPassedLayer->ResetReading();
if( psInfo == NULL ||
!oTranslator.Translate( psInfo,
nCountLayerFeatures, NULL,
pfnProgress, pProgressArg, psOptions ))
{
CPLError( CE_Failure, CPLE_AppDefined,
"Terminating translation prematurely after failed\n"
"translation from sql statement." );
nRetCode = 1;
}
FreeTargetLayerInfo(psInfo);
if (poPassedLayer != poResultSet)
delete poPassedLayer;
poDS->ReleaseResultSet( poResultSet );
}
else
{
if( CPLGetLastErrorNo() != 0 )
nRetCode = 1;
}
}
/* -------------------------------------------------------------------- */
/* Special case for layer interleaving mode. */
/* -------------------------------------------------------------------- */
else if( bSrcIsOSM &&
CPLTestBool(CPLGetConfigOption("OGR_INTERLEAVED_READING", "YES")) )
{
CPLSetConfigOption("OGR_INTERLEAVED_READING", "YES");
if (psOptions->bSplitListFields)
{
CPLError( CE_Failure, CPLE_AppDefined, "-splitlistfields not supported in this mode" );
GDALVectorTranslateOptionsFree(psOptions);
if( hDstDS == NULL ) GDALClose( poODS );
delete poGCPCoordTrans;
return NULL;
}
int nSrcLayerCount = poDS->GetLayerCount();
AssociatedLayers* pasAssocLayers =
(AssociatedLayers* ) CPLCalloc(nSrcLayerCount, sizeof(AssociatedLayers));
/* -------------------------------------------------------------------- */
/* Special case to improve user experience when translating into */
/* single file shapefile and source has only one layer, and that */
/* the layer name isn't specified */
/* -------------------------------------------------------------------- */
VSIStatBufL sStat;
if (EQUAL(poDriver->GetDescription(), "ESRI Shapefile") &&
(CSLCount(psOptions->papszLayers) == 1 || nSrcLayerCount == 1) && psOptions->pszNewLayerName == NULL &&
VSIStatL(osDestFilename, &sStat) == 0 && VSI_ISREG(sStat.st_mode))
{
psOptions->pszNewLayerName = CPLStrdup(CPLGetBasename(osDestFilename));
}
GDALProgressFunc pfnProgress = NULL;
void *pProgressArg = NULL;
if ( psOptions->bDisplayProgress && bSrcIsOSM )
{
pfnProgress = psOptions->pfnProgress;
pProgressArg = psOptions->pProgressData;
}
/* -------------------------------------------------------------------- */
/* If no target layer specified, use all source layers. */
/* -------------------------------------------------------------------- */
int iLayer;
if ( CSLCount(psOptions->papszLayers) == 0)
{
psOptions->papszLayers = (char**) CPLCalloc(sizeof(char*), nSrcLayerCount + 1);
for( iLayer = 0; iLayer < nSrcLayerCount; iLayer++ )
{
OGRLayer *poLayer = poDS->GetLayer(iLayer);
if( poLayer == NULL )
{
CPLError( CE_Failure, CPLE_AppDefined, "Couldn't fetch advertised layer %d!",
iLayer );
GDALVectorTranslateOptionsFree(psOptions);
if( hDstDS == NULL ) GDALClose( poODS );
delete poGCPCoordTrans;
return NULL;
}
psOptions->papszLayers[iLayer] = CPLStrdup(poLayer->GetName());
}
}
else
{
if ( bSrcIsOSM )
{
CPLString osInterestLayers = "SET interest_layers =";
for( iLayer = 0; psOptions->papszLayers[iLayer] != NULL; iLayer++ )
{
if( iLayer != 0 ) osInterestLayers += ",";
osInterestLayers += psOptions->papszLayers[iLayer];
}
poDS->ExecuteSQL(osInterestLayers.c_str(), NULL, NULL);
}
}
/* -------------------------------------------------------------------- */
/* First pass to set filters and create target layers. */
/* -------------------------------------------------------------------- */
for( iLayer = 0; iLayer < nSrcLayerCount; iLayer++ )
{
OGRLayer *poLayer = poDS->GetLayer(iLayer);
if( poLayer == NULL )
{
CPLError( CE_Failure, CPLE_AppDefined, "Couldn't fetch advertised layer %d!",
iLayer );
GDALVectorTranslateOptionsFree(psOptions);
if( hDstDS == NULL ) GDALClose( poODS );
delete poGCPCoordTrans;
return NULL;
}
pasAssocLayers[iLayer].poSrcLayer = poLayer;
if( CSLFindString(psOptions->papszLayers, poLayer->GetName()) >= 0 )
{
if( psOptions->pszWHERE != NULL )
{
if( poLayer->SetAttributeFilter( psOptions->pszWHERE ) != OGRERR_NONE )
{
CPLError( CE_Failure, CPLE_AppDefined, "SetAttributeFilter(%s) on layer '%s' failed.",
psOptions->pszWHERE, poLayer->GetName() );
if (!psOptions->bSkipFailures)
{
GDALVectorTranslateOptionsFree(psOptions);
if( hDstDS == NULL ) GDALClose( poODS );
delete poGCPCoordTrans;
return NULL;
}
}
}
ApplySpatialFilter(poLayer, (OGRGeometry*)psOptions->hSpatialFilter, poSpatSRS, psOptions->pszGeomField, poSourceSRS );
TargetLayerInfo* psInfo = oSetup.Setup(poLayer,
psOptions->pszNewLayerName,
psOptions);
if( psInfo == NULL && !psOptions->bSkipFailures )
{
GDALVectorTranslateOptionsFree(psOptions);
if( hDstDS == NULL ) GDALClose( poODS );
delete poGCPCoordTrans;
return NULL;
}
pasAssocLayers[iLayer].psInfo = psInfo;
}
else
{
pasAssocLayers[iLayer].psInfo = NULL;
}
}
/* -------------------------------------------------------------------- */
/* Second pass to process features in a interleaved layer mode. */
/* -------------------------------------------------------------------- */
bool bHasLayersNonEmpty;
do
{
bHasLayersNonEmpty = false;
for( iLayer = 0; iLayer < nSrcLayerCount; iLayer++ )
{
OGRLayer *poLayer = pasAssocLayers[iLayer].poSrcLayer;
TargetLayerInfo *psInfo = pasAssocLayers[iLayer].psInfo;
GIntBig nReadFeatureCount = 0;
if( psInfo )
{
if( !oTranslator.Translate( psInfo,
0, &nReadFeatureCount,
pfnProgress, pProgressArg, psOptions )
&& !psOptions->bSkipFailures )
{
CPLError( CE_Failure, CPLE_AppDefined,
"Terminating translation prematurely after failed\n"
"translation of layer %s (use -skipfailures to skip errors)",
poLayer->GetName() );
nRetCode = 1;
break;
}
}
else
{
/* No matching target layer : just consumes the features */
OGRFeature* poFeature;
while( (poFeature = poLayer->GetNextFeature()) != NULL )
{
nReadFeatureCount ++;
OGRFeature::DestroyFeature(poFeature);
}
}
if( nReadFeatureCount != 0 )
bHasLayersNonEmpty = true;
}
}
while( bHasLayersNonEmpty );
if (pfnProgress)
{
pfnProgress(1.0, "", pProgressArg);
}
/* -------------------------------------------------------------------- */
/* Cleanup. */
/* -------------------------------------------------------------------- */
for( iLayer = 0; iLayer < nSrcLayerCount; iLayer++ )
{
if( pasAssocLayers[iLayer].psInfo )
FreeTargetLayerInfo(pasAssocLayers[iLayer].psInfo);
}
CPLFree(pasAssocLayers);
}
else
{
int nLayerCount = 0;
OGRLayer** papoLayers = NULL;
/* -------------------------------------------------------------------- */
/* Process each data source layer. */
/* -------------------------------------------------------------------- */
if ( CSLCount(psOptions->papszLayers) == 0)
{
nLayerCount = poDS->GetLayerCount();
papoLayers = (OGRLayer**)CPLMalloc(sizeof(OGRLayer*) * nLayerCount);
for( int iLayer = 0;
iLayer < nLayerCount;
iLayer++ )
{
OGRLayer *poLayer = poDS->GetLayer(iLayer);
if( poLayer == NULL )
{
CPLError( CE_Failure, CPLE_AppDefined, "Couldn't fetch advertised layer %d!",
iLayer );
GDALVectorTranslateOptionsFree(psOptions);
if( hDstDS == NULL ) GDALClose( poODS );
delete poGCPCoordTrans;
return NULL;
}
papoLayers[iLayer] = poLayer;
}
}
/* -------------------------------------------------------------------- */
/* Process specified data source layers. */
/* -------------------------------------------------------------------- */
else
{
nLayerCount = CSLCount(psOptions->papszLayers);
papoLayers = (OGRLayer**)CPLMalloc(sizeof(OGRLayer*) * nLayerCount);
for( int iLayer = 0;
psOptions->papszLayers[iLayer] != NULL;
iLayer++ )
{
OGRLayer *poLayer = poDS->GetLayerByName(psOptions->papszLayers[iLayer]);
if( poLayer == NULL )
{
CPLError( CE_Failure, CPLE_AppDefined, "Couldn't fetch requested layer '%s'!",
psOptions->papszLayers[iLayer] );
if (!psOptions->bSkipFailures)
{
GDALVectorTranslateOptionsFree(psOptions);
if( hDstDS == NULL ) GDALClose( poODS );
delete poGCPCoordTrans;
return NULL;
}
}
papoLayers[iLayer] = poLayer;
}
}
/* -------------------------------------------------------------------- */
/* Special case to improve user experience when translating into */
/* single file shapefile and source has only one layer, and that */
/* the layer name isn't specified */
/* -------------------------------------------------------------------- */
VSIStatBufL sStat;
if (EQUAL(poDriver->GetDescription(), "ESRI Shapefile") &&
nLayerCount == 1 && psOptions->pszNewLayerName == NULL &&
VSIStatL(osDestFilename, &sStat) == 0 && VSI_ISREG(sStat.st_mode))
{
psOptions->pszNewLayerName = CPLStrdup(CPLGetBasename(osDestFilename));
}
GIntBig* panLayerCountFeatures = (GIntBig*) CPLCalloc(sizeof(GIntBig), nLayerCount);
GIntBig nCountLayersFeatures = 0;
GIntBig nAccCountFeatures = 0;
int iLayer;
/* First pass to apply filters and count all features if necessary */
for( iLayer = 0;
iLayer < nLayerCount;
iLayer++ )
{
OGRLayer *poLayer = papoLayers[iLayer];
if (poLayer == NULL)
continue;
if( psOptions->pszWHERE != NULL )
{
if( poLayer->SetAttributeFilter( psOptions->pszWHERE ) != OGRERR_NONE )
{
CPLError( CE_Failure, CPLE_AppDefined, "SetAttributeFilter(%s) on layer '%s' failed.",
psOptions->pszWHERE, poLayer->GetName() );
if (!psOptions->bSkipFailures)
{
GDALVectorTranslateOptionsFree(psOptions);
if( hDstDS == NULL ) GDALClose( poODS );
delete poGCPCoordTrans;
return NULL;
}
}
}
ApplySpatialFilter(poLayer, (OGRGeometry*)psOptions->hSpatialFilter, poSpatSRS, psOptions->pszGeomField, poSourceSRS);
if (psOptions->bDisplayProgress && !bSrcIsOSM)
{
if (!poLayer->TestCapability(OLCFastFeatureCount))
{
CPLError(CE_Warning, CPLE_NotSupported, "Progress turned off as fast feature count is not available.");
psOptions->bDisplayProgress = false;
}
else
{
panLayerCountFeatures[iLayer] = poLayer->GetFeatureCount();
nCountLayersFeatures += panLayerCountFeatures[iLayer];
}
}
}
/* Second pass to do the real job */
for( iLayer = 0;
iLayer < nLayerCount && nRetCode == 0;
iLayer++ )
{
OGRLayer *poLayer = papoLayers[iLayer];
if (poLayer == NULL)
continue;
GDALProgressFunc pfnProgress = NULL;
void *pProgressArg = NULL;
OGRLayer* poPassedLayer = poLayer;
if (psOptions->bSplitListFields)
{
poPassedLayer = new OGRSplitListFieldLayer(poPassedLayer, psOptions->nMaxSplitListSubFields);
if (psOptions->bDisplayProgress && psOptions->nMaxSplitListSubFields != 1 &&
nCountLayersFeatures != 0)
{
pfnProgress = GDALScaledProgress;
pProgressArg =
GDALCreateScaledProgress(nAccCountFeatures * 1.0 / nCountLayersFeatures,
(nAccCountFeatures + panLayerCountFeatures[iLayer] / 2) * 1.0 / nCountLayersFeatures,
psOptions->pfnProgress,
psOptions->pProgressData);
}
else
{
pfnProgress = NULL;
pProgressArg = NULL;
}
int nRet = ((OGRSplitListFieldLayer*)poPassedLayer)->BuildLayerDefn(pfnProgress, pProgressArg);
if (!nRet)
{
delete poPassedLayer;
poPassedLayer = poLayer;
}
if (psOptions->bDisplayProgress)
GDALDestroyScaledProgress(pProgressArg);
pfnProgress = NULL;
pProgressArg = NULL;
}
if (psOptions->bDisplayProgress)
{
if ( bSrcIsOSM )
{
pfnProgress = psOptions->pfnProgress;
pProgressArg = psOptions->pProgressData;
}
else if( nCountLayersFeatures != 0 )
{
pfnProgress = GDALScaledProgress;
GIntBig nStart = 0;
if (poPassedLayer != poLayer && psOptions->nMaxSplitListSubFields != 1)
nStart = panLayerCountFeatures[iLayer] / 2;
pProgressArg =
GDALCreateScaledProgress((nAccCountFeatures + nStart) * 1.0 / nCountLayersFeatures,
(nAccCountFeatures + panLayerCountFeatures[iLayer]) * 1.0 / nCountLayersFeatures,
psOptions->pfnProgress,
psOptions->pProgressData);
}
}
nAccCountFeatures += panLayerCountFeatures[iLayer];
TargetLayerInfo* psInfo = oSetup.Setup(poPassedLayer,
psOptions->pszNewLayerName,
psOptions);
poPassedLayer->ResetReading();
if( (psInfo == NULL ||
!oTranslator.Translate( psInfo,
panLayerCountFeatures[iLayer], NULL,
pfnProgress, pProgressArg, psOptions ))
&& !psOptions->bSkipFailures )
{
CPLError( CE_Failure, CPLE_AppDefined,
"Terminating translation prematurely after failed\n"
"translation of layer %s (use -skipfailures to skip errors)",
poLayer->GetName() );
nRetCode = 1;
}
FreeTargetLayerInfo(psInfo);
if (poPassedLayer != poLayer)
delete poPassedLayer;
if (psOptions->bDisplayProgress && !bSrcIsOSM)
GDALDestroyScaledProgress(pProgressArg);
}
CPLFree(panLayerCountFeatures);
CPLFree(papoLayers);
}
/* -------------------------------------------------------------------- */
/* Process DS style table */
/* -------------------------------------------------------------------- */
poODS->SetStyleTable( poDS->GetStyleTable () );
if( psOptions->nGroupTransactions )
{
if( !psOptions->nLayerTransaction )
{
if( nRetCode != 0 && !psOptions->bSkipFailures )
poODS->RollbackTransaction();
else
poODS->CommitTransaction();
}
}
delete poGCPCoordTrans;
GDALVectorTranslateOptionsFree(psOptions);
if(nRetCode == 0)
return (GDALDatasetH) poODS;
else
{
if( hDstDS == NULL ) GDALClose( poODS );
return NULL;
}
}
/************************************************************************/
/* SetZ() */
/************************************************************************/
static void SetZ (OGRGeometry* poGeom, double dfZ )
{
if (poGeom == NULL)
return;
switch (wkbFlatten(poGeom->getGeometryType()))
{
case wkbPoint:
((OGRPoint*)poGeom)->setZ(dfZ);
break;
case wkbLineString:
case wkbLinearRing:
{
int i;
OGRLineString* poLS = (OGRLineString*) poGeom;
for(i=0;i<poLS->getNumPoints();i++)
poLS->setPoint(i, poLS->getX(i), poLS->getY(i), dfZ);
break;
}
case wkbPolygon:
{
int i;
OGRPolygon* poPoly = (OGRPolygon*) poGeom;
SetZ(poPoly->getExteriorRing(), dfZ);
for(i=0;i<poPoly->getNumInteriorRings();i++)
SetZ(poPoly->getInteriorRing(i), dfZ);
break;
}
case wkbMultiPoint:
case wkbMultiLineString:
case wkbMultiPolygon:
case wkbGeometryCollection:
{
int i;
OGRGeometryCollection* poGeomColl = (OGRGeometryCollection*) poGeom;
for(i=0;i<poGeomColl->getNumGeometries();i++)
SetZ(poGeomColl->getGeometryRef(i), dfZ);
break;
}
default:
break;
}
}
/************************************************************************/
/* ForceCoordDimension() */
/************************************************************************/
static int ForceCoordDimension(int eGType, int nCoordDim)
{
if( nCoordDim == 2 && eGType != wkbNone )
return wkbFlatten(eGType);
else if( nCoordDim == 3 && eGType != wkbNone )
return wkbSetZ(wkbFlatten((OGRwkbGeometryType)eGType));
else if( nCoordDim == COORD_DIM_XYM && eGType != wkbNone )
return wkbSetM(wkbFlatten((OGRwkbGeometryType)eGType));
else if( nCoordDim == 4 && eGType != wkbNone )
return OGR_GT_SetModifier((OGRwkbGeometryType)eGType, TRUE, TRUE);
else
return eGType;
}
/************************************************************************/
/* GetLayerAndOverwriteIfNecessary() */
/************************************************************************/
static OGRLayer* GetLayerAndOverwriteIfNecessary(GDALDataset *poDstDS,
const char* pszNewLayerName,
bool bOverwrite,
bool* pbErrorOccurred)
{
if( pbErrorOccurred )
*pbErrorOccurred = false;
/* GetLayerByName() can instantiate layers that would have been */
/* 'hidden' otherwise, for example, non-spatial tables in a */
/* PostGIS-enabled database, so this apparently useless command is */
/* not useless. (#4012) */
CPLPushErrorHandler(CPLQuietErrorHandler);
OGRLayer* poDstLayer = poDstDS->GetLayerByName(pszNewLayerName);
CPLPopErrorHandler();
CPLErrorReset();
int iLayer = -1;
if (poDstLayer != NULL)
{
int nLayerCount = poDstDS->GetLayerCount();
for( iLayer = 0; iLayer < nLayerCount; iLayer++ )
{
OGRLayer *poLayer = poDstDS->GetLayer(iLayer);
if (poLayer == poDstLayer)
break;
}
if (iLayer == nLayerCount)
/* should not happen with an ideal driver */
poDstLayer = NULL;
}
/* -------------------------------------------------------------------- */
/* If the user requested overwrite, and we have the layer in */
/* question we need to delete it now so it will get recreated */
/* (overwritten). */
/* -------------------------------------------------------------------- */
if( poDstLayer != NULL && bOverwrite )
{
if( poDstDS->DeleteLayer( iLayer ) != OGRERR_NONE )
{
CPLError( CE_Failure, CPLE_AppDefined,
"DeleteLayer() failed when overwrite requested." );
if( pbErrorOccurred )
*pbErrorOccurred = true;
}
poDstLayer = NULL;
}
return poDstLayer;
}
/************************************************************************/
/* ConvertType() */
/************************************************************************/
static OGRwkbGeometryType ConvertType(GeomTypeConversion eGeomTypeConversion,
OGRwkbGeometryType eGType)
{
OGRwkbGeometryType eRetType = eGType;
if ( eGeomTypeConversion == GTC_PROMOTE_TO_MULTI )
{
if( !OGR_GT_IsSubClassOf(eGType, wkbGeometryCollection) )
eRetType = OGR_GT_GetCollection(eGType);
}
else if ( eGeomTypeConversion == GTC_CONVERT_TO_LINEAR )
eRetType = OGR_GT_GetLinear(eGType);
if ( eGeomTypeConversion == GTC_CONVERT_TO_CURVE )
eRetType = OGR_GT_GetCurve(eGType);
return eRetType;
}
/************************************************************************/
/* DoFieldTypeConversion() */
/************************************************************************/
static
void DoFieldTypeConversion(GDALDataset* poDstDS, OGRFieldDefn& oFieldDefn,
char** papszFieldTypesToString,
char** papszMapFieldType,
bool bUnsetFieldWidth,
bool bQuiet,
bool bForceNullable,
bool bUnsetDefault)
{
if (papszFieldTypesToString != NULL )
{
CPLString osLookupString;
osLookupString.Printf("%s(%s)",
OGRFieldDefn::GetFieldTypeName(oFieldDefn.GetType()),
OGRFieldDefn::GetFieldSubTypeName(oFieldDefn.GetSubType()));
int iIdx = CSLFindString(papszFieldTypesToString, osLookupString);
if( iIdx < 0 )
iIdx = CSLFindString(papszFieldTypesToString,
OGRFieldDefn::GetFieldTypeName(oFieldDefn.GetType()));
if( iIdx < 0 )
iIdx = CSLFindString(papszFieldTypesToString, "All");
if( iIdx >= 0 )
{
oFieldDefn.SetSubType(OFSTNone);
oFieldDefn.SetType(OFTString);
}
}
else if (papszMapFieldType != NULL)
{
CPLString osLookupString;
osLookupString.Printf("%s(%s)",
OGRFieldDefn::GetFieldTypeName(oFieldDefn.GetType()),
OGRFieldDefn::GetFieldSubTypeName(oFieldDefn.GetSubType()));
const char* pszType = CSLFetchNameValue(papszMapFieldType, osLookupString);
if( pszType == NULL )
pszType = CSLFetchNameValue(papszMapFieldType,
OGRFieldDefn::GetFieldTypeName(oFieldDefn.GetType()));
if( pszType == NULL )
pszType = CSLFetchNameValue(papszMapFieldType, "All");
if( pszType != NULL )
{
int iSubType;
int iType = GetFieldType(pszType, &iSubType);
if( iType >= 0 && iSubType >= 0 )
{
oFieldDefn.SetSubType(OFSTNone);
oFieldDefn.SetType((OGRFieldType)iType);
oFieldDefn.SetSubType((OGRFieldSubType)iSubType);
if( iType == OFTInteger )
oFieldDefn.SetWidth(0);
}
}
}
if( bUnsetFieldWidth )
{
oFieldDefn.SetWidth(0);
oFieldDefn.SetPrecision(0);
}
if( bForceNullable )
oFieldDefn.SetNullable(TRUE);
if( bUnsetDefault )
oFieldDefn.SetDefault(NULL);
if( poDstDS->GetDriver() != NULL &&
poDstDS->GetDriver()->GetMetadataItem(GDAL_DMD_CREATIONFIELDDATATYPES) != NULL &&
strstr(poDstDS->GetDriver()->GetMetadataItem(GDAL_DMD_CREATIONFIELDDATATYPES),
OGRFieldDefn::GetFieldTypeName(oFieldDefn.GetType())) == NULL )
{
if( oFieldDefn.GetType() == OFTInteger64 )
{
if( !bQuiet )
{
CPLError(CE_Warning, CPLE_AppDefined,
"The output driver does not seem to natively support %s "
"type for field %s. Converting it to Real instead. "
"-mapFieldType can be used to control field type conversion.",
OGRFieldDefn::GetFieldTypeName(oFieldDefn.GetType()),
oFieldDefn.GetNameRef());
}
oFieldDefn.SetType(OFTReal);
}
else if( !bQuiet )
{
CPLError(CE_Warning, CPLE_AppDefined,
"The output driver does not natively support %s type for "
"field %s. Misconversion can happen. "
"-mapFieldType can be used to control field type conversion.",
OGRFieldDefn::GetFieldTypeName(oFieldDefn.GetType()),
oFieldDefn.GetNameRef());
}
}
else if( poDstDS->GetDriver() != NULL &&
poDstDS->GetDriver()->GetMetadataItem(GDAL_DMD_CREATIONFIELDDATATYPES) == NULL )
{
// All drivers supporting OFTInteger64 should advertise it theoretically
if( oFieldDefn.GetType() == OFTInteger64 )
{
if( !bQuiet )
{
CPLError(CE_Warning, CPLE_AppDefined,
"The output driver does not seem to natively support %s type "
"for field %s. Converting it to Real instead. "
"-mapFieldType can be used to control field type conversion.",
OGRFieldDefn::GetFieldTypeName(oFieldDefn.GetType()),
oFieldDefn.GetNameRef());
}
oFieldDefn.SetType(OFTReal);
}
}
}
/************************************************************************/
/* SetupTargetLayer::Setup() */
/************************************************************************/
TargetLayerInfo* SetupTargetLayer::Setup(OGRLayer* poSrcLayer,
const char* pszNewLayerName,
GDALVectorTranslateOptions *psOptions)
{
OGRLayer *poDstLayer;
OGRFeatureDefn *poSrcFDefn;
OGRFeatureDefn *poDstFDefn = NULL;
int eGType = m_eGType;
bool bPreserveFID = m_bPreserveFID;
bool bAppend = m_bAppend;
if( pszNewLayerName == NULL )
pszNewLayerName = poSrcLayer->GetName();
/* -------------------------------------------------------------------- */
/* Get other info. */
/* -------------------------------------------------------------------- */
poSrcFDefn = poSrcLayer->GetLayerDefn();
/* -------------------------------------------------------------------- */
/* Find requested geometry fields. */
/* -------------------------------------------------------------------- */
std::vector<int> anRequestedGeomFields;
int nSrcGeomFieldCount = poSrcFDefn->GetGeomFieldCount();
if (m_papszSelFields && !bAppend )
{
for( int iField=0; m_papszSelFields[iField] != NULL; iField++)
{
int iSrcField = poSrcFDefn->GetFieldIndex(m_papszSelFields[iField]);
if (iSrcField >= 0)
{
/* do nothing */
}
else
{
iSrcField = poSrcFDefn->GetGeomFieldIndex(m_papszSelFields[iField]);
if( iSrcField >= 0)
{
anRequestedGeomFields.push_back(iSrcField);
}
else
{
CPLError( CE_Failure, CPLE_AppDefined, "Field '%s' not found in source layer.",
m_papszSelFields[iField] );
if( !psOptions->bSkipFailures )
return NULL;
}
}
}
if( anRequestedGeomFields.size() > 1 &&
!m_poDstDS->TestCapability(ODsCCreateGeomFieldAfterCreateLayer) )
{
CPLError( CE_Failure, CPLE_AppDefined, "Several geometry fields requested, but output "
"datasource does not support multiple geometry "
"fields." );
if( !psOptions->bSkipFailures )
return NULL;
else
anRequestedGeomFields.resize(0);
}
}
OGRSpatialReference* poOutputSRS = m_poOutputSRS;
if( poOutputSRS == NULL && !m_bNullifyOutputSRS )
{
if( nSrcGeomFieldCount == 1 || anRequestedGeomFields.size() == 0 )
poOutputSRS = poSrcLayer->GetSpatialRef();
else if( anRequestedGeomFields.size() == 1 )
{
int iSrcGeomField = anRequestedGeomFields[0];
poOutputSRS = poSrcFDefn->GetGeomFieldDefn(iSrcGeomField)->
GetSpatialRef();
}
}
int iSrcZField = -1;
if (m_pszZField != NULL)
{
iSrcZField = poSrcFDefn->GetFieldIndex(m_pszZField);
if( iSrcZField < 0 )
{
CPLError(CE_Warning, CPLE_AppDefined,
"zfield '%s' does not exist in layer %s",
m_pszZField, poSrcLayer->GetName());
}
}
/* -------------------------------------------------------------------- */
/* Find the layer. */
/* -------------------------------------------------------------------- */
bool bErrorOccurred;
poDstLayer = GetLayerAndOverwriteIfNecessary(m_poDstDS,
pszNewLayerName,
m_bOverwrite,
&bErrorOccurred);
if( bErrorOccurred )
return NULL;
/* -------------------------------------------------------------------- */
/* If the layer does not exist, then create it. */
/* -------------------------------------------------------------------- */
if( poDstLayer == NULL )
{
if( !m_poDstDS->TestCapability( ODsCCreateLayer ) )
{
CPLError( CE_Failure, CPLE_AppDefined,
"Layer %s not found, and CreateLayer not supported by driver.",
pszNewLayerName );
return NULL;
}
bool bForceGType = ( eGType != GEOMTYPE_UNCHANGED );
if( !bForceGType )
{
if( anRequestedGeomFields.size() == 0 )
{
eGType = poSrcFDefn->GetGeomType();
}
else if( anRequestedGeomFields.size() == 1 )
{
int iSrcGeomField = anRequestedGeomFields[0];
eGType = poSrcFDefn->GetGeomFieldDefn(iSrcGeomField)->GetType();
}
else
eGType = wkbNone;
bool bHasZ = CPL_TO_BOOL(wkbHasZ((OGRwkbGeometryType)eGType));
eGType = ConvertType(m_eGeomTypeConversion, (OGRwkbGeometryType)eGType);
if ( m_bExplodeCollections )
{
OGRwkbGeometryType eFGType = wkbFlatten(eGType);
if (eFGType == wkbMultiPoint)
{
eGType = wkbPoint;
}
else if (eFGType == wkbMultiLineString)
{
eGType = wkbLineString;
}
else if (eFGType == wkbMultiPolygon)
{
eGType = wkbPolygon;
}
else if (eFGType == wkbGeometryCollection ||
eFGType == wkbMultiCurve ||
eFGType == wkbMultiSurface)
{
eGType = wkbUnknown;
}
}
if ( bHasZ || (iSrcZField >= 0 && eGType != wkbNone) )
eGType = wkbSetZ((OGRwkbGeometryType)eGType);
}
eGType = ForceCoordDimension(eGType, m_nCoordDim);
CPLErrorReset();
char** papszLCOTemp = CSLDuplicate(m_papszLCO);
int eGCreateLayerType = eGType;
if( anRequestedGeomFields.size() == 0 &&
nSrcGeomFieldCount > 1 &&
m_poDstDS->TestCapability(ODsCCreateGeomFieldAfterCreateLayer) )
{
eGCreateLayerType = wkbNone;
}
else if( anRequestedGeomFields.size() == 1 &&
m_poDstDS->TestCapability(ODsCCreateGeomFieldAfterCreateLayer) )
{
eGCreateLayerType = wkbNone;
}
// If the source feature has a single geometry column that is not nullable
// and that ODsCCreateGeomFieldAfterCreateLayer is available, use it
// so as to be able to set the not null constraint (if the driver supports it)
else if( anRequestedGeomFields.size() == 0 &&
nSrcGeomFieldCount == 1 &&
m_poDstDS->TestCapability(ODsCCreateGeomFieldAfterCreateLayer) &&
!poSrcFDefn->GetGeomFieldDefn(0)->IsNullable() &&
!m_bForceNullable)
{
anRequestedGeomFields.push_back(0);
eGCreateLayerType = wkbNone;
}
// If the source feature first geometry column is not nullable
// and that GEOMETRY_NULLABLE creation option is available, use it
// so as to be able to set the not null constraint (if the driver supports it)
else if( anRequestedGeomFields.size() == 0 &&
nSrcGeomFieldCount >= 1 &&
!poSrcFDefn->GetGeomFieldDefn(0)->IsNullable() &&
m_poDstDS->GetDriver()->GetMetadataItem(GDAL_DS_LAYER_CREATIONOPTIONLIST) != NULL &&
strstr(m_poDstDS->GetDriver()->GetMetadataItem(GDAL_DS_LAYER_CREATIONOPTIONLIST), "GEOMETRY_NULLABLE") != NULL &&
CSLFetchNameValue(m_papszLCO, "GEOMETRY_NULLABLE") == NULL&&
!m_bForceNullable )
{
papszLCOTemp = CSLSetNameValue(papszLCOTemp, "GEOMETRY_NULLABLE", "NO");
CPLDebug("GDALVectorTranslate", "Using GEOMETRY_NULLABLE=NO");
}
// Force FID column as 64 bit if the source feature has a 64 bit FID,
// the target driver supports 64 bit FID and the user didn't set it
// manually.
if( poSrcLayer->GetMetadataItem(OLMD_FID64) != NULL &&
EQUAL(poSrcLayer->GetMetadataItem(OLMD_FID64), "YES") &&
m_poDstDS->GetDriver()->GetMetadataItem(GDAL_DS_LAYER_CREATIONOPTIONLIST) != NULL &&
strstr(m_poDstDS->GetDriver()->GetMetadataItem(GDAL_DS_LAYER_CREATIONOPTIONLIST), "FID64") != NULL &&
CSLFetchNameValue(m_papszLCO, "FID64") == NULL )
{
papszLCOTemp = CSLSetNameValue(papszLCOTemp, "FID64", "YES");
CPLDebug("GDALVectorTranslate", "Using FID64=YES");
}
// If output driver supports FID layer creation option, set it with
// the FID column name of the source layer
if( !m_bUnsetFid && !bAppend &&
poSrcLayer->GetFIDColumn() != NULL &&
!EQUAL(poSrcLayer->GetFIDColumn(), "") &&
m_poDstDS->GetDriver()->GetMetadataItem(GDAL_DS_LAYER_CREATIONOPTIONLIST) != NULL &&
strstr(m_poDstDS->GetDriver()->GetMetadataItem(GDAL_DS_LAYER_CREATIONOPTIONLIST), "='FID'") != NULL &&
CSLFetchNameValue(m_papszLCO, "FID") == NULL )
{
papszLCOTemp = CSLSetNameValue(papszLCOTemp, "FID", poSrcLayer->GetFIDColumn());
CPLDebug("GDALVectorTranslate", "Using FID=%s and -preserve_fid", poSrcLayer->GetFIDColumn());
bPreserveFID = true;
}
if( m_bNativeData &&
poSrcLayer->GetMetadataItem("NATIVE_DATA", "NATIVE_DATA") != NULL &&
poSrcLayer->GetMetadataItem("NATIVE_MEDIA_TYPE", "NATIVE_DATA") != NULL &&
m_poDstDS->GetDriver()->GetMetadataItem(GDAL_DS_LAYER_CREATIONOPTIONLIST) != NULL &&
strstr(m_poDstDS->GetDriver()->GetMetadataItem(GDAL_DS_LAYER_CREATIONOPTIONLIST), "NATIVE_DATA") != NULL &&
strstr(m_poDstDS->GetDriver()->GetMetadataItem(GDAL_DS_LAYER_CREATIONOPTIONLIST), "NATIVE_MEDIA_TYPE") != NULL )
{
papszLCOTemp = CSLSetNameValue(papszLCOTemp, "NATIVE_DATA",
poSrcLayer->GetMetadataItem("NATIVE_DATA", "NATIVE_DATA"));
papszLCOTemp = CSLSetNameValue(papszLCOTemp, "NATIVE_MEDIA_TYPE",
poSrcLayer->GetMetadataItem("NATIVE_MEDIA_TYPE", "NATIVE_DATA"));
CPLDebug("GDALVectorTranslate", "Transferring layer NATIVE_DATA");
}
OGRSpatialReference* poOutputSRSClone = NULL;
if( poOutputSRS != NULL )
{
poOutputSRSClone = poOutputSRS->Clone();
}
poDstLayer = m_poDstDS->CreateLayer( pszNewLayerName, poOutputSRSClone,
(OGRwkbGeometryType) eGCreateLayerType,
papszLCOTemp );
CSLDestroy(papszLCOTemp);
if( poOutputSRSClone != NULL )
{
poOutputSRSClone->Release();
}
if( poDstLayer == NULL )
{
return NULL;
}
if( m_bCopyMD )
{
char** papszDomains = poSrcLayer->GetMetadataDomainList();
for(char** papszIter = papszDomains; papszIter && *papszIter; ++papszIter )
{
if( !EQUAL(*papszIter, "IMAGE_STRUCTURE") &&
!EQUAL(*papszIter, "SUBDATASETS") )
{
char** papszMD = poSrcLayer->GetMetadata(*papszIter);
if( papszMD )
poDstLayer->SetMetadata(papszMD, *papszIter);
}
}
CSLDestroy(papszDomains);
}
if( anRequestedGeomFields.size() == 0 &&
nSrcGeomFieldCount > 1 &&
m_poDstDS->TestCapability(ODsCCreateGeomFieldAfterCreateLayer) )
{
for(int i = 0; i < nSrcGeomFieldCount; i ++)
{
anRequestedGeomFields.push_back(i);
}
}
if( anRequestedGeomFields.size() > 1 ||
(anRequestedGeomFields.size() == 1 &&
m_poDstDS->TestCapability(ODsCCreateGeomFieldAfterCreateLayer)) )
{
for(int i = 0; i < (int)anRequestedGeomFields.size(); i ++)
{
int iSrcGeomField = anRequestedGeomFields[i];
OGRGeomFieldDefn oGFldDefn
(poSrcFDefn->GetGeomFieldDefn(iSrcGeomField));
if( m_poOutputSRS != NULL )
{
poOutputSRSClone = m_poOutputSRS->Clone();
oGFldDefn.SetSpatialRef(poOutputSRSClone);
poOutputSRSClone->Release();
}
if( bForceGType )
oGFldDefn.SetType((OGRwkbGeometryType) eGType);
else
{
eGType = oGFldDefn.GetType();
eGType = ConvertType(m_eGeomTypeConversion, (OGRwkbGeometryType)eGType);
eGType = ForceCoordDimension(eGType, m_nCoordDim);
oGFldDefn.SetType((OGRwkbGeometryType) eGType);
}
if( m_bForceNullable )
oGFldDefn.SetNullable(TRUE);
poDstLayer->CreateGeomField(&oGFldDefn);
}
}
bAppend = false;
}
/* -------------------------------------------------------------------- */
/* Otherwise we will append to it, if append was requested. */
/* -------------------------------------------------------------------- */
else if( !bAppend && !m_bNewDataSource )
{
CPLError( CE_Failure, CPLE_AppDefined, "Layer %s already exists, and -append not specified.\n"
" Consider using -append, or -overwrite.",
pszNewLayerName );
return NULL;
}
else
{
if( CSLCount(m_papszLCO) > 0 )
{
CPLError( CE_Warning, CPLE_AppDefined, "Layer creation options ignored since an existing layer is\n"
" being appended to." );
}
}
/* -------------------------------------------------------------------- */
/* Process Layer style table */
/* -------------------------------------------------------------------- */
poDstLayer->SetStyleTable( poSrcLayer->GetStyleTable () );
/* -------------------------------------------------------------------- */
/* Add fields. Default to copy all field. */
/* If only a subset of all fields requested, then output only */
/* the selected fields, and in the order that they were */
/* selected. */
/* -------------------------------------------------------------------- */
int nSrcFieldCount = poSrcFDefn->GetFieldCount();
int iSrcFIDField = -1;
// Initialize the index-to-index map to -1's
int *panMap = (int *) VSIMalloc( sizeof(int) * nSrcFieldCount );
for( int iField=0; iField < nSrcFieldCount; iField++)
panMap[iField] = -1;
/* Caution : at the time of writing, the MapInfo driver */
/* returns NULL until a field has been added */
poDstFDefn = poDstLayer->GetLayerDefn();
if (m_papszFieldMap && bAppend)
{
bool bIdentity = false;
if (EQUAL(m_papszFieldMap[0], "identity"))
bIdentity = true;
else if (CSLCount(m_papszFieldMap) != nSrcFieldCount)
{
CPLError( CE_Failure, CPLE_AppDefined, "Field map should contain the value 'identity' or "
"the same number of integer values as the source field count.");
VSIFree(panMap);
return NULL;
}
for( int iField=0; iField < nSrcFieldCount; iField++)
{
panMap[iField] = bIdentity? iField : atoi(m_papszFieldMap[iField]);
if (panMap[iField] >= poDstFDefn->GetFieldCount())
{
CPLError( CE_Failure, CPLE_AppDefined, "Invalid destination field index %d.", panMap[iField]);
VSIFree(panMap);
return NULL;
}
}
}
else if (m_papszSelFields && !bAppend )
{
int nDstFieldCount = 0;
if (poDstFDefn)
nDstFieldCount = poDstFDefn->GetFieldCount();
for( int iField=0; m_papszSelFields[iField] != NULL; iField++)
{
int iSrcField = poSrcFDefn->GetFieldIndex(m_papszSelFields[iField]);
if (iSrcField >= 0)
{
OGRFieldDefn* poSrcFieldDefn = poSrcFDefn->GetFieldDefn(iSrcField);
OGRFieldDefn oFieldDefn( poSrcFieldDefn );
DoFieldTypeConversion(m_poDstDS, oFieldDefn,
m_papszFieldTypesToString,
m_papszMapFieldType,
m_bUnsetFieldWidth,
psOptions->bQuiet,
m_bForceNullable,
m_bUnsetDefault);
/* The field may have been already created at layer creation */
int iDstField = -1;
if (poDstFDefn)
iDstField = poDstFDefn->GetFieldIndex(oFieldDefn.GetNameRef());
if (iDstField >= 0)
{
panMap[iSrcField] = iDstField;
}
else if (poDstLayer->CreateField( &oFieldDefn ) == OGRERR_NONE)
{
/* now that we've created a field, GetLayerDefn() won't return NULL */
if (poDstFDefn == NULL)
poDstFDefn = poDstLayer->GetLayerDefn();
/* Sanity check : if it fails, the driver is buggy */
if (poDstFDefn != NULL &&
poDstFDefn->GetFieldCount() != nDstFieldCount + 1)
{
CPLError(CE_Warning, CPLE_AppDefined,
"The output driver has claimed to have added the %s field, but it did not!",
oFieldDefn.GetNameRef() );
}
else
{
panMap[iSrcField] = nDstFieldCount;
nDstFieldCount ++;
}
}
}
}
/* -------------------------------------------------------------------- */
/* Use SetIgnoredFields() on source layer if available */
/* -------------------------------------------------------------------- */
if (poSrcLayer->TestCapability(OLCIgnoreFields))
{
int iSrcField;
char** papszIgnoredFields = NULL;
bool bUseIgnoredFields = true;
char** papszWHEREUsedFields = NULL;
if (m_pszWHERE)
{
/* We must not ignore fields used in the -where expression (#4015) */
OGRFeatureQuery oFeatureQuery;
if ( oFeatureQuery.Compile( poSrcLayer->GetLayerDefn(), m_pszWHERE, FALSE, NULL ) == OGRERR_NONE )
{
papszWHEREUsedFields = oFeatureQuery.GetUsedFields();
}
else
{
bUseIgnoredFields = false;
}
}
for(iSrcField=0;bUseIgnoredFields && iSrcField<poSrcFDefn->GetFieldCount();iSrcField++)
{
const char* pszFieldName =
poSrcFDefn->GetFieldDefn(iSrcField)->GetNameRef();
bool bFieldRequested = false;
for( int iField=0; m_papszSelFields[iField] != NULL; iField++)
{
if (EQUAL(pszFieldName, m_papszSelFields[iField]))
{
bFieldRequested = true;
break;
}
}
bFieldRequested |= CSLFindString(papszWHEREUsedFields, pszFieldName) >= 0;
bFieldRequested |= (m_pszZField != NULL && EQUAL(pszFieldName, m_pszZField));
/* If source field not requested, add it to ignored files list */
if (!bFieldRequested)
papszIgnoredFields = CSLAddString(papszIgnoredFields, pszFieldName);
}
if (bUseIgnoredFields)
poSrcLayer->SetIgnoredFields((const char**)papszIgnoredFields);
CSLDestroy(papszIgnoredFields);
CSLDestroy(papszWHEREUsedFields);
}
}
else if( !bAppend || m_bAddMissingFields )
{
int nDstFieldCount = 0;
if (poDstFDefn)
nDstFieldCount = poDstFDefn->GetFieldCount();
/* Save the map of existing fields, before creating new ones */
/* This helps when converting a source layer that has duplicated field names */
/* which is a bad idea */
std::map<CPLString, int> oMapExistingFields;
for( int iField = 0; iField < nDstFieldCount; iField++ )
{
const char* pszFieldName = poDstFDefn->GetFieldDefn(iField)->GetNameRef();
CPLString osUpperFieldName(CPLString(pszFieldName).toupper());
if( oMapExistingFields.find(osUpperFieldName) == oMapExistingFields.end() )
oMapExistingFields[osUpperFieldName] = iField;
/*else
CPLError(CE_Warning, CPLE_AppDefined,
"The target layer has already a duplicated field name '%s' before "
"adding the fields of the source layer", pszFieldName); */
}
const char* pszFIDColumn = poDstLayer->GetFIDColumn();
for( int iField = 0; iField < nSrcFieldCount; iField++ )
{
OGRFieldDefn* poSrcFieldDefn = poSrcFDefn->GetFieldDefn(iField);
OGRFieldDefn oFieldDefn( poSrcFieldDefn );
// Avoid creating a field with the same name as the FID column
if( pszFIDColumn != NULL && EQUAL(pszFIDColumn, oFieldDefn.GetNameRef()) &&
(oFieldDefn.GetType() == OFTInteger || oFieldDefn.GetType() == OFTInteger64) )
{
iSrcFIDField = iField;
continue;
}
DoFieldTypeConversion(m_poDstDS, oFieldDefn,
m_papszFieldTypesToString,
m_papszMapFieldType,
m_bUnsetFieldWidth,
psOptions->bQuiet,
m_bForceNullable,
m_bUnsetDefault);
/* The field may have been already created at layer creation */
std::map<CPLString, int>::iterator oIter =
oMapExistingFields.find(CPLString(oFieldDefn.GetNameRef()).toupper());
if( oIter != oMapExistingFields.end() )
{
panMap[iField] = oIter->second;
continue;
}
bool bHasRenamed = false;
/* In case the field name already exists in the target layer, */
/* build a unique field name */
if( poDstFDefn != NULL &&
poDstFDefn->GetFieldIndex(oFieldDefn.GetNameRef()) >= 0 )
{
int nTry = 1;
while( true )
{
++nTry;
CPLString osTmpName;
osTmpName.Printf("%s%d", oFieldDefn.GetNameRef(), nTry);
/* Check that the proposed name doesn't exist either in the already */
/* created fields or in the source fields */
if( poDstFDefn->GetFieldIndex(osTmpName) < 0 &&
poSrcFDefn->GetFieldIndex(osTmpName) < 0 )
{
bHasRenamed = true;
oFieldDefn.SetName(osTmpName);
break;
}
}
}
if (poDstLayer->CreateField( &oFieldDefn ) == OGRERR_NONE)
{
/* now that we've created a field, GetLayerDefn() won't return NULL */
if (poDstFDefn == NULL)
poDstFDefn = poDstLayer->GetLayerDefn();
/* Sanity check : if it fails, the driver is buggy */
if (poDstFDefn != NULL &&
poDstFDefn->GetFieldCount() != nDstFieldCount + 1)
{
CPLError(CE_Warning, CPLE_AppDefined,
"The output driver has claimed to have added the %s field, but it did not!",
oFieldDefn.GetNameRef() );
}
else
{
if( bHasRenamed )
{
const char* pszNewFieldName =
poDstFDefn->GetFieldDefn(nDstFieldCount)->GetNameRef();
CPLError(CE_Warning, CPLE_AppDefined,
"Field '%s' already exists. Renaming it as '%s'",
poSrcFieldDefn->GetNameRef(), pszNewFieldName);
}
panMap[iField] = nDstFieldCount;
nDstFieldCount ++;
}
}
}
}
else
{
/* For an existing layer, build the map by fetching the index in the destination */
/* layer for each source field */
if (poDstFDefn == NULL)
{
CPLError( CE_Failure, CPLE_AppDefined, "poDstFDefn == NULL." );
VSIFree(panMap);
return NULL;
}
for( int iField = 0; iField < nSrcFieldCount; iField++ )
{
OGRFieldDefn* poSrcFieldDefn = poSrcFDefn->GetFieldDefn(iField);
int iDstField = poDstLayer->FindFieldIndex(poSrcFieldDefn->GetNameRef(), m_bExactFieldNameMatch);
if (iDstField >= 0)
panMap[iField] = iDstField;
else
CPLDebug("GDALVectorTranslate", "Skipping field '%s' not found in destination layer '%s'.",
poSrcFieldDefn->GetNameRef(), poDstLayer->GetName() );
}
}
TargetLayerInfo* psInfo = (TargetLayerInfo*)
CPLMalloc(sizeof(TargetLayerInfo));
psInfo->nFeaturesRead = 0;
psInfo->bPerFeatureCT = false;
psInfo->poSrcLayer = poSrcLayer;
psInfo->poDstLayer = poDstLayer;
psInfo->papoCT = (OGRCoordinateTransformation**)
CPLCalloc(poDstLayer->GetLayerDefn()->GetGeomFieldCount(),
sizeof(OGRCoordinateTransformation*));
psInfo->papapszTransformOptions = (char***)
CPLCalloc(poDstLayer->GetLayerDefn()->GetGeomFieldCount(),
sizeof(char**));
psInfo->panMap = panMap;
psInfo->iSrcZField = iSrcZField;
psInfo->iSrcFIDField = iSrcFIDField;
if( anRequestedGeomFields.size() == 1 )
psInfo->iRequestedSrcGeomField = anRequestedGeomFields[0];
else
psInfo->iRequestedSrcGeomField = -1;
psInfo->bPreserveFID = bPreserveFID;
return psInfo;
}
/************************************************************************/
/* FreeTargetLayerInfo() */
/************************************************************************/
static void FreeTargetLayerInfo(TargetLayerInfo* psInfo)
{
if( psInfo == NULL )
return;
for(int i=0;i<psInfo->poDstLayer->GetLayerDefn()->GetGeomFieldCount();i++)
{
delete psInfo->papoCT[i];
CSLDestroy(psInfo->papapszTransformOptions[i]);
}
CPLFree(psInfo->papoCT);
CPLFree(psInfo->papapszTransformOptions);
CPLFree(psInfo->panMap);
CPLFree(psInfo);
}
/************************************************************************/
/* SetupCT() */
/************************************************************************/
static bool SetupCT( TargetLayerInfo* psInfo,
OGRLayer* poSrcLayer,
bool bTransform,
bool bWrapDateline,
const CPLString& osDateLineOffset,
OGRSpatialReference* poUserSourceSRS,
OGRFeature* poFeature,
OGRSpatialReference* poOutputSRS,
OGRCoordinateTransformation* poGCPCoordTrans)
{
OGRLayer *poDstLayer = psInfo->poDstLayer;
int nDstGeomFieldCount = poDstLayer->GetLayerDefn()->GetGeomFieldCount();
for( int iGeom = 0; iGeom < nDstGeomFieldCount; iGeom ++ )
{
/* -------------------------------------------------------------------- */
/* Setup coordinate transformation if we need it. */
/* -------------------------------------------------------------------- */
OGRSpatialReference* poSourceSRS = NULL;
OGRCoordinateTransformation* poCT = NULL;
char** papszTransformOptions = NULL;
int iSrcGeomField;
if( psInfo->iRequestedSrcGeomField >= 0 )
iSrcGeomField = psInfo->iRequestedSrcGeomField;
else
{
iSrcGeomField = poSrcLayer->GetLayerDefn()->GetGeomFieldIndex(
poDstLayer->GetLayerDefn()->GetGeomFieldDefn(iGeom)->GetNameRef());
if( iSrcGeomField < 0 )
{
if( nDstGeomFieldCount == 1 &&
poSrcLayer->GetLayerDefn()->GetGeomFieldCount() > 0 )
{
iSrcGeomField = 0;
}
else
continue;
}
}
if( bTransform || bWrapDateline )
{
if( psInfo->nFeaturesRead == 0 )
{
poSourceSRS = poUserSourceSRS;
if( poSourceSRS == NULL )
{
if( iSrcGeomField > 0 )
poSourceSRS = poSrcLayer->GetLayerDefn()->
GetGeomFieldDefn(iSrcGeomField)->GetSpatialRef();
else
poSourceSRS = poSrcLayer->GetSpatialRef();
}
}
if( poSourceSRS == NULL )
{
OGRGeometry* poSrcGeometry =
poFeature->GetGeomFieldRef(iSrcGeomField);
if( poSrcGeometry )
poSourceSRS = poSrcGeometry->getSpatialReference();
psInfo->bPerFeatureCT = true;
}
}
if( bTransform )
{
if( poSourceSRS == NULL )
{
CPLError( CE_Failure, CPLE_AppDefined, "Can't transform coordinates, source layer has no\n"
"coordinate system. Use -s_srs to set one." );
return false;
}
CPLAssert( NULL != poSourceSRS );
CPLAssert( NULL != poOutputSRS );
if( psInfo->papoCT[iGeom] != NULL &&
psInfo->papoCT[iGeom]->GetSourceCS() == poSourceSRS )
{
poCT = psInfo->papoCT[iGeom];
}
else
{
poCT = OGRCreateCoordinateTransformation( poSourceSRS, poOutputSRS );
if( poCT == NULL )
{
char *pszWKT = NULL;
CPLError( CE_Failure, CPLE_AppDefined, "Failed to create coordinate transformation between the\n"
"following coordinate systems. This may be because they\n"
"are not transformable, or because projection services\n"
"(PROJ.4 DLL/.so) could not be loaded." );
poSourceSRS->exportToPrettyWkt( &pszWKT, FALSE );
CPLError( CE_Failure, CPLE_AppDefined, "Source:\n%s", pszWKT );
CPLFree(pszWKT);
poOutputSRS->exportToPrettyWkt( &pszWKT, FALSE );
CPLError( CE_Failure, CPLE_AppDefined, "Target:\n%s", pszWKT );
CPLFree(pszWKT);
return false;
}
if( poGCPCoordTrans != NULL )
poCT = new CompositeCT( poGCPCoordTrans, poCT );
}
if( poCT != psInfo->papoCT[iGeom] )
{
delete psInfo->papoCT[iGeom];
psInfo->papoCT[iGeom] = poCT;
}
}
else
{
poCT = poGCPCoordTrans;
}
if (bWrapDateline)
{
if (bTransform && poCT != NULL && poOutputSRS != NULL && poOutputSRS->IsGeographic())
{
papszTransformOptions =
CSLAddString(papszTransformOptions, "WRAPDATELINE=YES");
if( osDateLineOffset.size() )
{
CPLString soOffset("DATELINEOFFSET=");
soOffset += osDateLineOffset;
papszTransformOptions =
CSLAddString(papszTransformOptions, soOffset);
}
}
else if (poSourceSRS != NULL && poSourceSRS->IsGeographic())
{
papszTransformOptions =
CSLAddString(papszTransformOptions, "WRAPDATELINE=YES");
if( osDateLineOffset.size() )
{
CPLString soOffset("DATELINEOFFSET=");
soOffset += osDateLineOffset;
papszTransformOptions =
CSLAddString(papszTransformOptions, soOffset);
}
}
else
{
static bool bHasWarned = false;
if( !bHasWarned )
CPLError( CE_Failure, CPLE_IllegalArg, "-wrapdateline option only works when reprojecting to a geographic SRS");
bHasWarned = true;
}
CSLDestroy(psInfo->papapszTransformOptions[iGeom]);
psInfo->papapszTransformOptions[iGeom] = papszTransformOptions;
}
}
return true;
}
/************************************************************************/
/* LayerTranslator::Translate() */
/************************************************************************/
int LayerTranslator::Translate( TargetLayerInfo* psInfo,
GIntBig nCountLayerFeatures,
GIntBig* pnReadFeatureCount,
GDALProgressFunc pfnProgress,
void *pProgressArg,
GDALVectorTranslateOptions *psOptions )
{
OGRLayer *poSrcLayer;
OGRLayer *poDstLayer;
const int eGType = m_eGType;
OGRSpatialReference* poOutputSRS = m_poOutputSRS;
poSrcLayer = psInfo->poSrcLayer;
poDstLayer = psInfo->poDstLayer;
int* const panMap = psInfo->panMap;
const int iSrcZField = psInfo->iSrcZField;
const bool bPreserveFID = psInfo->bPreserveFID;
const int nSrcGeomFieldCount = poSrcLayer->GetLayerDefn()->GetGeomFieldCount();
const int nDstGeomFieldCount = poDstLayer->GetLayerDefn()->GetGeomFieldCount();
const bool bExplodeCollections = m_bExplodeCollections && nDstGeomFieldCount <= 1;
if( poOutputSRS == NULL && !m_bNullifyOutputSRS )
{
if( nSrcGeomFieldCount == 1 )
{
poOutputSRS = poSrcLayer->GetSpatialRef();
}
else if( psInfo->iRequestedSrcGeomField > 0 )
{
poOutputSRS = poSrcLayer->GetLayerDefn()->GetGeomFieldDefn(
psInfo->iRequestedSrcGeomField)->GetSpatialRef();
}
}
/* -------------------------------------------------------------------- */
/* Transfer features. */
/* -------------------------------------------------------------------- */
OGRFeature *poFeature;
int nFeaturesInTransaction = 0;
GIntBig nCount = 0; /* written + failed */
GIntBig nFeaturesWritten = 0;
if( psOptions->nGroupTransactions )
{
if( psOptions->nLayerTransaction )
{
if( poDstLayer->StartTransaction() != OGRERR_NONE )
return false;
}
}
bool bRet = true;
while( true )
{
OGRFeature *poDstFeature = NULL;
if( psOptions->nFIDToFetch != OGRNullFID )
poFeature = poSrcLayer->GetFeature(psOptions->nFIDToFetch);
else
poFeature = poSrcLayer->GetNextFeature();
if( poFeature == NULL )
break;
if( psInfo->nFeaturesRead == 0 || psInfo->bPerFeatureCT )
{
if( !SetupCT( psInfo, poSrcLayer, m_bTransform, m_bWrapDateline,
m_osDateLineOffset, m_poUserSourceSRS,
poFeature, poOutputSRS, m_poGCPCoordTrans) )
{
OGRFeature::DestroyFeature( poFeature );
return false;
}
}
psInfo->nFeaturesRead ++;
int nParts = 0;
int nIters = 1;
if (bExplodeCollections)
{
OGRGeometry* poSrcGeometry;
if( psInfo->iRequestedSrcGeomField >= 0 )
poSrcGeometry = poFeature->GetGeomFieldRef(
psInfo->iRequestedSrcGeomField);
else
poSrcGeometry = poFeature->GetGeometryRef();
if (poSrcGeometry &&
OGR_GT_IsSubClassOf(poSrcGeometry->getGeometryType(), wkbGeometryCollection) )
{
nParts = ((OGRGeometryCollection*)poSrcGeometry)->getNumGeometries();
nIters = nParts;
if (nIters == 0)
nIters = 1;
}
}
for(int iPart = 0; iPart < nIters; iPart++)
{
if( ++nFeaturesInTransaction == psOptions->nGroupTransactions )
{
if( psOptions->nLayerTransaction )
{
if( poDstLayer->CommitTransaction() != OGRERR_NONE ||
poDstLayer->StartTransaction() != OGRERR_NONE )
{
OGRFeature::DestroyFeature( poFeature );
return false;
}
}
else
{
if( m_poODS->CommitTransaction() != OGRERR_NONE ||
m_poODS->StartTransaction(psOptions->bForceTransaction) != OGRERR_NONE )
{
OGRFeature::DestroyFeature( poFeature );
return false;
}
}
nFeaturesInTransaction = 0;
}
CPLErrorReset();
poDstFeature = OGRFeature::CreateFeature( poDstLayer->GetLayerDefn() );
/* Optimization to avoid duplicating the source geometry in the */
/* target feature : we steal it from the source feature for now... */
OGRGeometry* poStolenGeometry = NULL;
if( !bExplodeCollections && nSrcGeomFieldCount == 1 &&
nDstGeomFieldCount == 1 )
{
poStolenGeometry = poFeature->StealGeometry();
}
else if( !bExplodeCollections &&
psInfo->iRequestedSrcGeomField >= 0 )
{
poStolenGeometry = poFeature->StealGeometry(
psInfo->iRequestedSrcGeomField);
}
if( poDstFeature->SetFrom( poFeature, panMap, TRUE ) != OGRERR_NONE )
{
if( psOptions->nGroupTransactions )
{
if( psOptions->nLayerTransaction )
{
if( poDstLayer->CommitTransaction() != OGRERR_NONE )
{
OGRFeature::DestroyFeature( poFeature );
OGRFeature::DestroyFeature( poDstFeature );
OGRGeometryFactory::destroyGeometry( poStolenGeometry );
return false;
}
}
}
CPLError( CE_Failure, CPLE_AppDefined,
"Unable to translate feature " CPL_FRMT_GIB " from layer %s.",
poFeature->GetFID(), poSrcLayer->GetName() );
OGRFeature::DestroyFeature( poFeature );
OGRFeature::DestroyFeature( poDstFeature );
OGRGeometryFactory::destroyGeometry( poStolenGeometry );
return false;
}
/* ... and now we can attach the stolen geometry */
if( poStolenGeometry )
{
poDstFeature->SetGeometryDirectly(poStolenGeometry);
}
if( bPreserveFID )
poDstFeature->SetFID( poFeature->GetFID() );
else if( psInfo->iSrcFIDField >= 0 &&
poFeature->IsFieldSet(psInfo->iSrcFIDField))
poDstFeature->SetFID( poFeature->GetFieldAsInteger64(psInfo->iSrcFIDField) );
/* Erase native data if asked explicitly */
if( !m_bNativeData )
{
poDstFeature->SetNativeData(NULL);
poDstFeature->SetNativeMediaType(NULL);
}
for( int iGeom = 0; iGeom < nDstGeomFieldCount; iGeom ++ )
{
OGRGeometry* poDstGeometry = poDstFeature->StealGeometry(iGeom);
if (poDstGeometry == NULL)
continue;
if (nParts > 0)
{
/* For -explodecollections, extract the iPart(th) of the geometry */
OGRGeometry* poPart = ((OGRGeometryCollection*)poDstGeometry)->getGeometryRef(iPart);
((OGRGeometryCollection*)poDstGeometry)->removeGeometry(iPart, FALSE);
delete poDstGeometry;
poDstGeometry = poPart;
}
if (iSrcZField != -1)
{
SetZ(poDstGeometry, poFeature->GetFieldAsDouble(iSrcZField));
/* This will correct the coordinate dimension to 3 */
OGRGeometry* poDupGeometry = poDstGeometry->clone();
delete poDstGeometry;
poDstGeometry = poDupGeometry;
}
if (m_nCoordDim == 2 || m_nCoordDim == 3)
poDstGeometry->setCoordinateDimension( m_nCoordDim );
else if (m_nCoordDim == 4)
{
poDstGeometry->set3D( TRUE );
poDstGeometry->setMeasured( TRUE );
}
else if (m_nCoordDim == COORD_DIM_XYM)
{
poDstGeometry->set3D( FALSE );
poDstGeometry->setMeasured( TRUE );
}
else if ( m_nCoordDim == COORD_DIM_LAYER_DIM )
{
const OGRwkbGeometryType eDstLayerGeomType =
poDstLayer->GetLayerDefn()->GetGeomFieldDefn(iGeom)->GetType();
poDstGeometry->set3D( wkbHasZ(eDstLayerGeomType) );
poDstGeometry->setMeasured( wkbHasM(eDstLayerGeomType) );
}
if (m_eGeomOp == GEOMOP_SEGMENTIZE)
{
if (m_dfGeomOpParam > 0)
poDstGeometry->segmentize(m_dfGeomOpParam);
}
else if (m_eGeomOp == GEOMOP_SIMPLIFY_PRESERVE_TOPOLOGY)
{
if (m_dfGeomOpParam > 0)
{
OGRGeometry* poNewGeom = poDstGeometry->SimplifyPreserveTopology(m_dfGeomOpParam);
if (poNewGeom)
{
delete poDstGeometry;
poDstGeometry = poNewGeom;
}
}
}
if (m_poClipSrc)
{
OGRGeometry* poClipped = poDstGeometry->Intersection(m_poClipSrc);
delete poDstGeometry;
if (poClipped == NULL || poClipped->IsEmpty())
{
delete poClipped;
goto end_loop;
}
poDstGeometry = poClipped;
}
OGRCoordinateTransformation* poCT = psInfo->papoCT[iGeom];
if( !m_bTransform )
poCT = m_poGCPCoordTrans;
char** papszTransformOptions = psInfo->papapszTransformOptions[iGeom];
if( poCT != NULL || papszTransformOptions != NULL)
{
OGRGeometry* poReprojectedGeom =
OGRGeometryFactory::transformWithOptions(poDstGeometry, poCT, papszTransformOptions);
if( poReprojectedGeom == NULL )
{
if( psOptions->nGroupTransactions )
{
if( psOptions->nLayerTransaction )
{
if( poDstLayer->CommitTransaction() != OGRERR_NONE &&
!psOptions->bSkipFailures )
{
OGRFeature::DestroyFeature( poFeature );
OGRFeature::DestroyFeature( poDstFeature );
delete poDstGeometry;
return false;
}
}
}
CPLError( CE_Failure, CPLE_AppDefined, "Failed to reproject feature " CPL_FRMT_GIB " (geometry probably out of source or destination SRS).",
poFeature->GetFID() );
if( !psOptions->bSkipFailures )
{
OGRFeature::DestroyFeature( poFeature );
OGRFeature::DestroyFeature( poDstFeature );
delete poDstGeometry;
return false;
}
}
delete poDstGeometry;
poDstGeometry = poReprojectedGeom;
}
else if (poOutputSRS != NULL)
{
poDstGeometry->assignSpatialReference(poOutputSRS);
}
if (m_poClipDst)
{
if( poDstGeometry == NULL )
goto end_loop;
OGRGeometry* poClipped = poDstGeometry->Intersection(m_poClipDst);
delete poDstGeometry;
if (poClipped == NULL || poClipped->IsEmpty())
{
delete poClipped;
goto end_loop;
}
poDstGeometry = poClipped;
}
if( eGType != GEOMTYPE_UNCHANGED )
{
poDstGeometry = OGRGeometryFactory::forceTo(
poDstGeometry, (OGRwkbGeometryType)eGType);
}
else if( m_eGeomTypeConversion == GTC_PROMOTE_TO_MULTI ||
m_eGeomTypeConversion == GTC_CONVERT_TO_LINEAR ||
m_eGeomTypeConversion == GTC_CONVERT_TO_CURVE )
{
if( poDstGeometry != NULL )
{
OGRwkbGeometryType eTargetType = poDstGeometry->getGeometryType();
eTargetType = ConvertType(m_eGeomTypeConversion, eTargetType);
poDstGeometry = OGRGeometryFactory::forceTo(poDstGeometry, eTargetType);
}
}
poDstFeature->SetGeomFieldDirectly(iGeom, poDstGeometry);
}
CPLErrorReset();
if( poDstLayer->CreateFeature( poDstFeature ) == OGRERR_NONE )
{
nFeaturesWritten ++;
if( (bPreserveFID && poDstFeature->GetFID() != poFeature->GetFID()) ||
(!bPreserveFID && psInfo->iSrcFIDField >= 0 && poFeature->IsFieldSet(psInfo->iSrcFIDField) &&
poDstFeature->GetFID() != poFeature->GetFieldAsInteger64(psInfo->iSrcFIDField)) )
{
CPLError( CE_Warning, CPLE_AppDefined,
"Feature id not preserved");
}
}
else if( !psOptions->bSkipFailures )
{
if( psOptions->nGroupTransactions )
{
if( psOptions->nLayerTransaction )
poDstLayer->RollbackTransaction();
}
CPLError( CE_Failure, CPLE_AppDefined,
"Unable to write feature " CPL_FRMT_GIB " from layer %s.",
poFeature->GetFID(), poSrcLayer->GetName() );
OGRFeature::DestroyFeature( poFeature );
OGRFeature::DestroyFeature( poDstFeature );
return false;
}
else
{
CPLDebug( "GDALVectorTranslate", "Unable to write feature " CPL_FRMT_GIB " into layer %s.",
poFeature->GetFID(), poSrcLayer->GetName() );
if( psOptions->nGroupTransactions )
{
if( psOptions->nLayerTransaction )
{
poDstLayer->RollbackTransaction();
CPL_IGNORE_RET_VAL(poDstLayer->StartTransaction());
}
else
{
m_poODS->RollbackTransaction();
m_poODS->StartTransaction(psOptions->bForceTransaction);
}
}
}
end_loop:
OGRFeature::DestroyFeature( poDstFeature );
}
OGRFeature::DestroyFeature( poFeature );
/* Report progress */
nCount ++;
bool bGoOn = true;
if (pfnProgress)
{
if (m_nSrcFileSize != 0)
{
if ((nCount % 1000) == 0)
{
OGRLayer* poFCLayer = m_poSrcDS->ExecuteSQL("GetBytesRead()", NULL, NULL);
if( poFCLayer != NULL )
{
OGRFeature* poFeat = poFCLayer->GetNextFeature();
if( poFeat )
{
const char* pszReadSize = poFeat->GetFieldAsString(0);
GUIntBig nReadSize = CPLScanUIntBig( pszReadSize, 32 );
bGoOn = pfnProgress(nReadSize * 1.0 / m_nSrcFileSize, "", pProgressArg) != FALSE;
OGRFeature::DestroyFeature( poFeat );
}
}
m_poSrcDS->ReleaseResultSet(poFCLayer);
}
}
else
{
bGoOn = pfnProgress(nCount * 1.0 / nCountLayerFeatures, "", pProgressArg) != FALSE;
}
}
if( !bGoOn )
{
bRet = false;
break;
}
if (pnReadFeatureCount)
*pnReadFeatureCount = nCount;
if( psOptions->nFIDToFetch != OGRNullFID )
break;
}
if( psOptions->nGroupTransactions )
{
if( psOptions->nLayerTransaction )
{
if( poDstLayer->CommitTransaction() != OGRERR_NONE )
bRet = false;
}
}
CPLDebug("GDALVectorTranslate", CPL_FRMT_GIB " features written in layer '%s'",
nFeaturesWritten, poDstLayer->GetName());
return bRet;
}
/************************************************************************/
/* RemoveBOM() */
/************************************************************************/
/* Remove potential UTF-8 BOM from data (must be NUL terminated) */
static void RemoveBOM(GByte* pabyData)
{
if( pabyData[0] == 0xEF && pabyData[1] == 0xBB && pabyData[2] == 0xBF )
{
memmove(pabyData, pabyData + 3, strlen((const char*)pabyData + 3) + 1);
}
}
/************************************************************************/
/* GDALVectorTranslateOptionsNew() */
/************************************************************************/
/**
* allocates a GDALVectorTranslateOptions struct.
*
* @param papszArgv NULL terminated list of options (potentially including filename and open options too), or NULL.
* The accepted options are the ones of the <a href="ogr2ogr.html">ogr2ogr</a> utility.
* @param psOptionsForBinary (output) may be NULL (and should generally be NULL),
* otherwise (gdal_translate_bin.cpp use case) must be allocated with
* GDALVectorTranslateOptionsForBinaryNew() prior to this function. Will be
* filled with potentially present filename, open options,...
* @return pointer to the allocated GDALVectorTranslateOptions struct. Must be freed with GDALVectorTranslateOptionsFree().
*
* @since GDAL 2.1
*/
GDALVectorTranslateOptions *GDALVectorTranslateOptionsNew(char** papszArgv,
GDALVectorTranslateOptionsForBinary* psOptionsForBinary)
{
GDALVectorTranslateOptions *psOptions = (GDALVectorTranslateOptions *) CPLCalloc( 1, sizeof(GDALVectorTranslateOptions) );
psOptions->eAccessMode = ACCESS_CREATION;
psOptions->bSkipFailures = false;
psOptions->nLayerTransaction = -1;
psOptions->bForceTransaction = false;
psOptions->nGroupTransactions = 20000;
psOptions->nFIDToFetch = OGRNullFID;
psOptions->bQuiet = false;
psOptions->pszFormat = CPLStrdup("ESRI Shapefile");
psOptions->papszLayers = NULL;
psOptions->papszDSCO = NULL;
psOptions->papszLCO = NULL;
psOptions->bTransform = false;
psOptions->bAddMissingFields = false;
psOptions->pszOutputSRSDef = NULL;
psOptions->pszSourceSRSDef = NULL;
psOptions->bNullifyOutputSRS = false;
psOptions->bExactFieldNameMatch = true;
psOptions->pszNewLayerName = NULL;
psOptions->pszWHERE = NULL;
psOptions->pszGeomField = NULL;
psOptions->papszSelFields = NULL;
psOptions->pszSQLStatement = NULL;
psOptions->pszDialect = NULL;
psOptions->eGType = GEOMTYPE_UNCHANGED;
psOptions->eGeomTypeConversion = GTC_DEFAULT;
psOptions->eGeomOp = GEOMOP_NONE;
psOptions->dfGeomOpParam = 0;
psOptions->papszFieldTypesToString = NULL;
psOptions->papszMapFieldType = NULL;
psOptions->bUnsetFieldWidth = false;
psOptions->bDisplayProgress = false;
psOptions->bWrapDateline = false;
psOptions->dfDateLineOffset = 10.0;
psOptions->bClipSrc = false;
psOptions->hClipSrc = NULL;
psOptions->pszClipSrcDS = NULL;
psOptions->pszClipSrcSQL = NULL;
psOptions->pszClipSrcLayer = NULL;
psOptions->pszClipSrcWhere = NULL;
psOptions->hClipDst = NULL;
psOptions->pszClipDstDS = NULL;
psOptions->pszClipDstSQL = NULL;
psOptions->pszClipDstLayer = NULL;
psOptions->pszClipDstWhere = NULL;
psOptions->bSplitListFields = false;
psOptions->nMaxSplitListSubFields = -1;
psOptions->bExplodeCollections = false;
psOptions->pszZField = NULL;
psOptions->papszFieldMap = NULL;
psOptions->nCoordDim = COORD_DIM_UNCHANGED;
psOptions->papszDestOpenOptions = NULL;
psOptions->bForceNullable = false;
psOptions->bUnsetDefault = false;
psOptions->bUnsetFid = false;
psOptions->bPreserveFID = false;
psOptions->bCopyMD = true;
psOptions->papszMetadataOptions = NULL;
psOptions->pszSpatSRSDef = NULL;
psOptions->nGCPCount = 0;
psOptions->pasGCPs = NULL;
psOptions->nTransformOrder = 0; /* Default to 0 for now... let the lib decide */
psOptions->hSpatialFilter = NULL;
psOptions->bNativeData = true;
int nArgc = CSLCount(papszArgv);
for( int i = 0; i < nArgc; i++ )
{
if( EQUAL(papszArgv[i],"-q") || EQUAL(papszArgv[i],"-quiet") )
{
if( psOptionsForBinary )
psOptionsForBinary->bQuiet = TRUE;
}
else if( EQUAL(papszArgv[i],"-f") && i+1 < nArgc )
{
CPLFree(psOptions->pszFormat);
psOptions->pszFormat = CPLStrdup(papszArgv[++i]);
if( psOptionsForBinary )
{
psOptionsForBinary->bFormatExplicitlySet = TRUE;
}
}
else if( EQUAL(papszArgv[i],"-dsco") && i+1 < nArgc )
{
psOptions->papszDSCO = CSLAddString(psOptions->papszDSCO, papszArgv[++i] );
}
else if( EQUAL(papszArgv[i],"-lco") && i+1 < nArgc )
{
psOptions->papszLCO = CSLAddString(psOptions->papszLCO, papszArgv[++i] );
}
else if( EQUAL(papszArgv[i],"-oo") && i+1 < nArgc )
{
++i;
if( psOptionsForBinary )
{
psOptionsForBinary->papszOpenOptions = CSLAddString(psOptionsForBinary->papszOpenOptions, papszArgv[i] );
}
}
else if( EQUAL(papszArgv[i],"-doo") && i+1 < nArgc )
{
++i;
psOptions->papszDestOpenOptions = CSLAddString(psOptions->papszDestOpenOptions, papszArgv[i] );
}
else if( EQUAL(papszArgv[i],"-preserve_fid") )
{
psOptions->bPreserveFID = true;
}
else if( STARTS_WITH_CI(papszArgv[i], "-skip") )
{
psOptions->bSkipFailures = true;
psOptions->nGroupTransactions = 1; /* #2409 */
}
else if( EQUAL(papszArgv[i],"-append") )
{
psOptions->eAccessMode = ACCESS_APPEND;
}
else if( EQUAL(papszArgv[i],"-overwrite") )
{
psOptions->eAccessMode = ACCESS_OVERWRITE;
}
else if( EQUAL(papszArgv[i],"-addfields") )
{
psOptions->bAddMissingFields = true;
psOptions->eAccessMode = ACCESS_APPEND;
}
else if( EQUAL(papszArgv[i],"-update") )
{
/* Don't reset -append or -overwrite */
if( psOptions->eAccessMode != ACCESS_APPEND && psOptions->eAccessMode != ACCESS_OVERWRITE )
psOptions->eAccessMode = ACCESS_UPDATE;
}
else if( EQUAL(papszArgv[i],"-relaxedFieldNameMatch") )
{
psOptions->bExactFieldNameMatch = false;
}
else if( EQUAL(papszArgv[i],"-fid") && i+1 < nArgc )
{
psOptions->nFIDToFetch = CPLAtoGIntBig(papszArgv[++i]);
}
else if( EQUAL(papszArgv[i],"-sql") && i+1 < nArgc )
{
i++;
CPLFree(psOptions->pszSQLStatement);
GByte* pabyRet = NULL;
if( papszArgv[i][0] == '@' &&
VSIIngestFile( NULL, papszArgv[i] + 1, &pabyRet, NULL, 1024*1024) )
{
RemoveBOM(pabyRet);
psOptions->pszSQLStatement = (char*)pabyRet;
}
else
{
psOptions->pszSQLStatement = CPLStrdup(papszArgv[i]);
}
}
else if( EQUAL(papszArgv[i],"-dialect") && i+1 < nArgc )
{
CPLFree(psOptions->pszDialect);
psOptions->pszDialect = CPLStrdup(papszArgv[++i]);
}
else if( EQUAL(papszArgv[i],"-nln") && i+1 < nArgc )
{
CPLFree(psOptions->pszNewLayerName);
psOptions->pszNewLayerName = CPLStrdup(papszArgv[++i]);
}
else if( EQUAL(papszArgv[i],"-nlt") && i+1 < nArgc )
{
bool bIs3D = false;
CPLString osGeomName = papszArgv[i+1];
if (strlen(papszArgv[i+1]) > 3 &&
STARTS_WITH_CI(papszArgv[i+1] + strlen(papszArgv[i+1]) - 3, "25D"))
{
bIs3D = true;
osGeomName.resize(osGeomName.size() - 3);
}
else if (strlen(papszArgv[i+1]) > 1 &&
STARTS_WITH_CI(papszArgv[i+1] + strlen(papszArgv[i+1]) - 1, "Z"))
{
bIs3D = true;
osGeomName.resize(osGeomName.size() - 1);
}
if( EQUAL(osGeomName,"NONE") )
psOptions->eGType = wkbNone;
else if( EQUAL(osGeomName,"GEOMETRY") )
psOptions->eGType = wkbUnknown;
else if( EQUAL(osGeomName,"PROMOTE_TO_MULTI") )
psOptions->eGeomTypeConversion = GTC_PROMOTE_TO_MULTI;
else if( EQUAL(osGeomName,"CONVERT_TO_LINEAR") )
psOptions->eGeomTypeConversion = GTC_CONVERT_TO_LINEAR;
else if( EQUAL(osGeomName,"CONVERT_TO_CURVE") )
psOptions->eGeomTypeConversion = GTC_CONVERT_TO_CURVE;
else
{
psOptions->eGType = OGRFromOGCGeomType(osGeomName);
if (psOptions->eGType == wkbUnknown)
{
CPLError(CE_Failure, CPLE_IllegalArg,
"-nlt %s: type not recognised.",
papszArgv[i+1] );
GDALVectorTranslateOptionsFree(psOptions);
return NULL;
}
}
if (psOptions->eGType != GEOMTYPE_UNCHANGED && psOptions->eGType != wkbNone && bIs3D)
psOptions->eGType = wkbSetZ((OGRwkbGeometryType)psOptions->eGType);
i++;
}
else if( EQUAL(papszArgv[i],"-dim") && i+1 < nArgc )
{
if( EQUAL(papszArgv[i+1], "layer_dim") )
psOptions->nCoordDim = COORD_DIM_LAYER_DIM;
else if( EQUAL(papszArgv[i+1], "XY") || EQUAL(papszArgv[i+1], "2") )
psOptions->nCoordDim = 2;
else if( EQUAL(papszArgv[i+1], "XYZ") || EQUAL(papszArgv[i+1], "3") )
psOptions->nCoordDim = 3;
else if( EQUAL(papszArgv[i+1], "XYM") )
psOptions->nCoordDim = COORD_DIM_XYM;
else if( EQUAL(papszArgv[i+1], "XYZM") )
psOptions->nCoordDim = 4;
else
{
CPLError(CE_Failure, CPLE_IllegalArg,"-dim %s: value not handled.",
papszArgv[i+1] );
GDALVectorTranslateOptionsFree(psOptions);
return NULL;
}
i++;
}
else if( (EQUAL(papszArgv[i],"-tg") ||
EQUAL(papszArgv[i],"-gt")) && i+1 < nArgc )
{
++i;
/* If skipfailures is already set we should not
modify nGroupTransactions = 1 #2409 */
if ( !psOptions->bSkipFailures )
{
if( EQUAL(papszArgv[i], "unlimited") )
psOptions->nGroupTransactions = -1;
else
psOptions->nGroupTransactions = atoi(papszArgv[i]);
}
}
else if ( EQUAL(papszArgv[i],"-ds_transaction") )
{
psOptions->nLayerTransaction = FALSE;
psOptions->bForceTransaction = true;
}
/* Undocumented. Just a provision. Default behaviour should be OK */
else if ( EQUAL(papszArgv[i],"-lyr_transaction") )
{
psOptions->nLayerTransaction = TRUE;
}
else if( EQUAL(papszArgv[i],"-s_srs") && i+1 < nArgc )
{
CPLFree(psOptions->pszSourceSRSDef);
psOptions->pszSourceSRSDef = CPLStrdup(papszArgv[++i]);
}
else if( EQUAL(papszArgv[i],"-a_srs") && i+1 < nArgc )
{
CPLFree(psOptions->pszOutputSRSDef);
psOptions->pszOutputSRSDef = CPLStrdup(papszArgv[++i]);
if (EQUAL(psOptions->pszOutputSRSDef, "NULL") ||
EQUAL(psOptions->pszOutputSRSDef, "NONE"))
{
psOptions->pszOutputSRSDef = NULL;
psOptions->bNullifyOutputSRS = true;
}
}
else if( EQUAL(papszArgv[i],"-t_srs") && i+1 < nArgc )
{
CPLFree(psOptions->pszOutputSRSDef);
psOptions->pszOutputSRSDef = CPLStrdup(papszArgv[++i]);
psOptions->bTransform = true;
}
else if( EQUAL(papszArgv[i],"-spat") && i+4 < nArgc )
{
OGRLinearRing oRing;
oRing.addPoint( CPLAtof(papszArgv[i+1]), CPLAtof(papszArgv[i+2]) );
oRing.addPoint( CPLAtof(papszArgv[i+1]), CPLAtof(papszArgv[i+4]) );
oRing.addPoint( CPLAtof(papszArgv[i+3]), CPLAtof(papszArgv[i+4]) );
oRing.addPoint( CPLAtof(papszArgv[i+3]), CPLAtof(papszArgv[i+2]) );
oRing.addPoint( CPLAtof(papszArgv[i+1]), CPLAtof(papszArgv[i+2]) );
OGRPolygon* poSpatialFilter = (OGRPolygon*) OGRGeometryFactory::createGeometry(wkbPolygon);
poSpatialFilter->addRing( &oRing );
OGR_G_DestroyGeometry(psOptions->hSpatialFilter);
psOptions->hSpatialFilter = (OGRGeometryH) poSpatialFilter;
i += 4;
}
else if( EQUAL(papszArgv[i],"-spat_srs") && i+1 < nArgc )
{
CPLFree(psOptions->pszSpatSRSDef);
psOptions->pszSpatSRSDef = CPLStrdup(papszArgv[++i]);
}
else if( EQUAL(papszArgv[i],"-geomfield") && i+1 < nArgc )
{
CPLFree(psOptions->pszGeomField);
psOptions->pszGeomField = CPLStrdup(papszArgv[++i]);
}
else if( EQUAL(papszArgv[i],"-where") && i+1 < nArgc )
{
i++;
CPLFree(psOptions->pszWHERE);
GByte* pabyRet = NULL;
if( papszArgv[i][0] == '@' &&
VSIIngestFile( NULL, papszArgv[i] + 1, &pabyRet, NULL, 1024*1024) )
{
RemoveBOM(pabyRet);
psOptions->pszWHERE = (char*)pabyRet;
}
else
{
psOptions->pszWHERE = CPLStrdup(papszArgv[i]);
}
}
else if( EQUAL(papszArgv[i],"-select") && i+1 < nArgc )
{
const char* pszSelect = papszArgv[++i];
CSLDestroy(psOptions->papszSelFields);
psOptions->papszSelFields = CSLTokenizeStringComplex(pszSelect, " ,",
FALSE, FALSE );
}
else if( EQUAL(papszArgv[i],"-segmentize") && i+1 < nArgc )
{
psOptions->eGeomOp = GEOMOP_SEGMENTIZE;
psOptions->dfGeomOpParam = CPLAtof(papszArgv[++i]);
}
else if( EQUAL(papszArgv[i],"-simplify") && i+1 < nArgc )
{
psOptions->eGeomOp = GEOMOP_SIMPLIFY_PRESERVE_TOPOLOGY;
psOptions->dfGeomOpParam = CPLAtof(papszArgv[++i]);
}
else if( EQUAL(papszArgv[i],"-fieldTypeToString") && i+1 < nArgc )
{
CSLDestroy(psOptions->papszFieldTypesToString);
psOptions->papszFieldTypesToString =
CSLTokenizeStringComplex(papszArgv[++i], " ,",
FALSE, FALSE );
char** iter = psOptions->papszFieldTypesToString;
while(*iter)
{
if (IsFieldType(*iter))
{
/* Do nothing */
}
else if (EQUAL(*iter, "All"))
{
CSLDestroy(psOptions->papszFieldTypesToString);
psOptions->papszFieldTypesToString = NULL;
psOptions->papszFieldTypesToString = CSLAddString(psOptions->papszFieldTypesToString, "All");
break;
}
else
{
CPLError(CE_Failure, CPLE_IllegalArg,
"Unhandled type for fieldTypeToString option : %s",
*iter);
GDALVectorTranslateOptionsFree(psOptions);
return NULL;
}
iter ++;
}
}
else if( EQUAL(papszArgv[i],"-mapFieldType") && i+1 < nArgc )
{
CSLDestroy(psOptions->papszMapFieldType);
psOptions->papszMapFieldType =
CSLTokenizeStringComplex(papszArgv[++i], " ,",
FALSE, FALSE );
char** iter = psOptions->papszMapFieldType;
while(*iter)
{
char* pszKey = NULL;
const char* pszValue = CPLParseNameValue(*iter, &pszKey);
if( pszKey && pszValue)
{
if( !((IsFieldType(pszKey) || EQUAL(pszKey, "All")) && IsFieldType(pszValue)) )
{
CPLError(CE_Failure, CPLE_IllegalArg,
"Invalid value for -mapFieldType : %s",
*iter);
CPLFree(pszKey);
GDALVectorTranslateOptionsFree(psOptions);
return NULL;
}
}
CPLFree(pszKey);
iter ++;
}
}
else if( EQUAL(papszArgv[i],"-unsetFieldWidth") )
{
psOptions->bUnsetFieldWidth = true;
}
else if( EQUAL(papszArgv[i],"-progress") )
{
psOptions->bDisplayProgress = true;
}
else if( EQUAL(papszArgv[i],"-wrapdateline") )
{
psOptions->bWrapDateline = true;
}
else if( EQUAL(papszArgv[i],"-datelineoffset") && i < nArgc-1 )
{
psOptions->dfDateLineOffset = CPLAtof(papszArgv[++i]);
}
else if( EQUAL(papszArgv[i],"-clipsrc") )
{
if (i + 1 >= nArgc)
{
CPLError(CE_Failure, CPLE_IllegalArg, "%s option requires 1 or 4 arguments", papszArgv[i]);
GDALVectorTranslateOptionsFree(psOptions);
return NULL;
}
VSIStatBufL sStat;
psOptions->bClipSrc = true;
if ( IsNumber(papszArgv[i+1])
&& papszArgv[i+2] != NULL
&& papszArgv[i+3] != NULL
&& papszArgv[i+4] != NULL)
{
OGRLinearRing oRing;
oRing.addPoint( CPLAtof(papszArgv[i+1]), CPLAtof(papszArgv[i+2]) );
oRing.addPoint( CPLAtof(papszArgv[i+1]), CPLAtof(papszArgv[i+4]) );
oRing.addPoint( CPLAtof(papszArgv[i+3]), CPLAtof(papszArgv[i+4]) );
oRing.addPoint( CPLAtof(papszArgv[i+3]), CPLAtof(papszArgv[i+2]) );
oRing.addPoint( CPLAtof(papszArgv[i+1]), CPLAtof(papszArgv[i+2]) );
OGR_G_DestroyGeometry(psOptions->hClipSrc);
psOptions->hClipSrc = (OGRGeometryH) OGRGeometryFactory::createGeometry(wkbPolygon);
((OGRPolygon *) psOptions->hClipSrc)->addRing( &oRing );
i += 4;
}
else if ((STARTS_WITH_CI(papszArgv[i+1], "POLYGON") ||
STARTS_WITH_CI(papszArgv[i+1], "MULTIPOLYGON")) &&
VSIStatL(papszArgv[i+1], &sStat) != 0)
{
char* pszTmp = (char*) papszArgv[i+1];
OGR_G_DestroyGeometry(psOptions->hClipSrc);
OGRGeometryFactory::createFromWkt(&pszTmp, NULL, (OGRGeometry **)&psOptions->hClipSrc);
if (psOptions->hClipSrc == NULL)
{
CPLError(CE_Failure, CPLE_IllegalArg,
"Invalid geometry. Must be a valid POLYGON or MULTIPOLYGON WKT");
GDALVectorTranslateOptionsFree(psOptions);
return NULL;
}
i ++;
}
else if (EQUAL(papszArgv[i+1], "spat_extent") )
{
i ++;
}
else
{
CPLFree(psOptions->pszClipSrcDS);
psOptions->pszClipSrcDS = CPLStrdup(papszArgv[i+1]);
i ++;
}
}
else if( EQUAL(papszArgv[i],"-clipsrcsql") && i+1 < nArgc )
{
CPLFree(psOptions->pszClipSrcSQL);
psOptions->pszClipSrcSQL = CPLStrdup(papszArgv[i+1]);
i ++;
}
else if( EQUAL(papszArgv[i],"-clipsrclayer") && i+1 < nArgc )
{
CPLFree(psOptions->pszClipSrcLayer);
psOptions->pszClipSrcLayer = CPLStrdup(papszArgv[i+1]);
i ++;
}
else if( EQUAL(papszArgv[i],"-clipsrcwhere") && i+1 < nArgc )
{
CPLFree(psOptions->pszClipSrcWhere);
psOptions->pszClipSrcWhere = CPLStrdup(papszArgv[i+1]);
i ++;
}
else if( EQUAL(papszArgv[i],"-clipdst") )
{
if (i + 1 >= nArgc)
{
CPLError(CE_Failure, CPLE_IllegalArg, "%s option requires 1 or 4 arguments", papszArgv[i]);
GDALVectorTranslateOptionsFree(psOptions);
return NULL;
}
VSIStatBufL sStat;
if ( IsNumber(papszArgv[i+1])
&& papszArgv[i+2] != NULL
&& papszArgv[i+3] != NULL
&& papszArgv[i+4] != NULL)
{
OGRLinearRing oRing;
oRing.addPoint( CPLAtof(papszArgv[i+1]), CPLAtof(papszArgv[i+2]) );
oRing.addPoint( CPLAtof(papszArgv[i+1]), CPLAtof(papszArgv[i+4]) );
oRing.addPoint( CPLAtof(papszArgv[i+3]), CPLAtof(papszArgv[i+4]) );
oRing.addPoint( CPLAtof(papszArgv[i+3]), CPLAtof(papszArgv[i+2]) );
oRing.addPoint( CPLAtof(papszArgv[i+1]), CPLAtof(papszArgv[i+2]) );
OGR_G_DestroyGeometry(psOptions->hClipDst);
psOptions->hClipDst = (OGRGeometryH) OGRGeometryFactory::createGeometry(wkbPolygon);
((OGRPolygon *) psOptions->hClipDst)->addRing( &oRing );
i += 4;
}
else if ((STARTS_WITH_CI(papszArgv[i+1], "POLYGON") ||
STARTS_WITH_CI(papszArgv[i+1], "MULTIPOLYGON")) &&
VSIStatL(papszArgv[i+1], &sStat) != 0)
{
char* pszTmp = (char*) papszArgv[i+1];
OGR_G_DestroyGeometry(psOptions->hClipDst);
OGRGeometryFactory::createFromWkt(&pszTmp, NULL, (OGRGeometry **)&psOptions->hClipDst);
if (psOptions->hClipDst == NULL)
{
CPLError(CE_Failure, CPLE_IllegalArg,
"Invalid geometry. Must be a valid POLYGON or MULTIPOLYGON WKT");
GDALVectorTranslateOptionsFree(psOptions);
return NULL;
}
i ++;
}
else
{
CPLFree(psOptions->pszClipDstDS);
psOptions->pszClipDstDS = CPLStrdup(papszArgv[i+1]);
i ++;
}
}
else if( EQUAL(papszArgv[i],"-clipdstsql") && i+1 < nArgc )
{
CPLFree(psOptions->pszClipDstSQL);
psOptions->pszClipDstSQL = CPLStrdup(papszArgv[i+1]);
i ++;
}
else if( EQUAL(papszArgv[i],"-clipdstlayer") && i+1 < nArgc )
{
CPLFree(psOptions->pszClipDstLayer);
psOptions->pszClipDstLayer = CPLStrdup(papszArgv[i+1]);
i ++;
}
else if( EQUAL(papszArgv[i],"-clipdstwhere") && i+1 < nArgc )
{
CPLFree(psOptions->pszClipDstWhere);
psOptions->pszClipDstWhere = CPLStrdup(papszArgv[i+1]);
i ++;
}
else if( EQUAL(papszArgv[i],"-splitlistfields") )
{
psOptions->bSplitListFields = true;
}
else if ( EQUAL(papszArgv[i],"-maxsubfields") && i+1 < nArgc )
{
if (IsNumber(papszArgv[i+1]))
{
int nTemp = atoi(papszArgv[i+1]);
if (nTemp > 0)
{
psOptions->nMaxSplitListSubFields = nTemp;
i ++;
}
}
}
else if( EQUAL(papszArgv[i],"-explodecollections") )
{
psOptions->bExplodeCollections = true;
}
else if( EQUAL(papszArgv[i],"-zfield") && i+1 < nArgc )
{
CPLFree(psOptions->pszZField);
psOptions->pszZField = CPLStrdup(papszArgv[i+1]);
i ++;
}
else if( EQUAL(papszArgv[i],"-gcp") && i+4 < nArgc )
{
char* endptr = NULL;
/* -gcp pixel line easting northing [elev] */
psOptions->nGCPCount++;
psOptions->pasGCPs = (GDAL_GCP *)
CPLRealloc( psOptions->pasGCPs, sizeof(GDAL_GCP) * psOptions->nGCPCount );
GDALInitGCPs( 1, psOptions->pasGCPs + psOptions->nGCPCount - 1 );
psOptions->pasGCPs[psOptions->nGCPCount-1].dfGCPPixel = CPLAtof(papszArgv[++i]);
psOptions->pasGCPs[psOptions->nGCPCount-1].dfGCPLine = CPLAtof(papszArgv[++i]);
psOptions->pasGCPs[psOptions->nGCPCount-1].dfGCPX = CPLAtof(papszArgv[++i]);
psOptions->pasGCPs[psOptions->nGCPCount-1].dfGCPY = CPLAtof(papszArgv[++i]);
if( papszArgv[i+1] != NULL
&& (CPLStrtod(papszArgv[i+1], &endptr) != 0.0 || papszArgv[i+1][0] == '0') )
{
/* Check that last argument is really a number and not a filename */
/* looking like a number (see ticket #863) */
if (endptr && *endptr == 0)
psOptions->pasGCPs[psOptions->nGCPCount-1].dfGCPZ = CPLAtof(papszArgv[++i]);
}
/* should set id and info? */
}
else if( EQUAL(papszArgv[i],"-tps") )
{
psOptions->nTransformOrder = -1;
}
else if( EQUAL(papszArgv[i],"-order") && i+1 < nArgc )
{
psOptions->nTransformOrder = atoi( papszArgv[++i] );
}
else if( EQUAL(papszArgv[i],"-fieldmap") && i+1 < nArgc )
{
CSLDestroy(psOptions->papszFieldMap);
psOptions->papszFieldMap = CSLTokenizeStringComplex(papszArgv[++i], ",",
FALSE, FALSE );
}
else if( EQUAL(papszArgv[i],"-forceNullable") )
{
psOptions->bForceNullable = true;
}
else if( EQUAL(papszArgv[i],"-unsetDefault") )
{
psOptions->bUnsetDefault = true;
}
else if( EQUAL(papszArgv[i],"-unsetFid") )
{
psOptions->bUnsetFid = true;
}
else if( EQUAL(papszArgv[i],"-nomd") )
{
psOptions->bCopyMD = false;
}
else if( EQUAL(papszArgv[i],"-noNativeData") )
{
psOptions->bNativeData = false;
}
else if( EQUAL(papszArgv[i],"-mo") && i+1 < nArgc )
{
psOptions->papszMetadataOptions = CSLAddString( psOptions->papszMetadataOptions,
papszArgv[++i] );
}
else if( papszArgv[i][0] == '-' )
{
CPLError(CE_Failure, CPLE_NotSupported,
"Unknown option name '%s'", papszArgv[i]);
GDALVectorTranslateOptionsFree(psOptions);
return NULL;
}
else if( psOptionsForBinary && psOptionsForBinary->pszDestDataSource == NULL )
psOptionsForBinary->pszDestDataSource = CPLStrdup(papszArgv[i]);
else if( psOptionsForBinary && psOptionsForBinary->pszDataSource == NULL )
psOptionsForBinary->pszDataSource = CPLStrdup(papszArgv[i]);
else
psOptions->papszLayers = CSLAddString( psOptions->papszLayers, papszArgv[i] );
}
if( psOptionsForBinary )
{
psOptionsForBinary->pszFormat = CPLStrdup(psOptions->pszFormat);
psOptionsForBinary->eAccessMode = psOptions->eAccessMode;
if( !(CPLTestBool(CSLFetchNameValueDef(
psOptionsForBinary->papszOpenOptions, "NATIVE_DATA",
CSLFetchNameValueDef(
psOptionsForBinary->papszOpenOptions, "@NATIVE_DATA", "TRUE")))) )
{
psOptions->bNativeData = false;
}
if( psOptions->bNativeData &&
CSLFetchNameValue(psOptionsForBinary->papszOpenOptions,
"NATIVE_DATA") == NULL &&
CSLFetchNameValue(psOptionsForBinary->papszOpenOptions,
"@NATIVE_DATA") == NULL )
{
psOptionsForBinary->papszOpenOptions = CSLAddString(
psOptionsForBinary->papszOpenOptions, "@NATIVE_DATA=YES" );
}
}
return psOptions;
}
/************************************************************************/
/* GDALVectorTranslateOptionsFree() */
/************************************************************************/
/**
* Frees the GDALVectorTranslateOptions struct.
*
* @param psOptions the options struct for GDALVectorTranslate().
* @since GDAL 2.1
*/
void GDALVectorTranslateOptionsFree( GDALVectorTranslateOptions *psOptions )
{
if( psOptions == NULL )
return;
CPLFree( psOptions->pszFormat );
CPLFree( psOptions->pszOutputSRSDef);
CPLFree( psOptions->pszSourceSRSDef);
CPLFree( psOptions->pszNewLayerName);
CPLFree( psOptions->pszWHERE );
CPLFree( psOptions->pszGeomField );
CPLFree( psOptions->pszSQLStatement );
CPLFree( psOptions->pszDialect );
CPLFree( psOptions->pszClipSrcDS );
CPLFree( psOptions->pszClipSrcSQL );
CPLFree( psOptions->pszClipSrcLayer );
CPLFree( psOptions->pszClipSrcWhere );
CPLFree( psOptions->pszClipDstDS );
CPLFree( psOptions->pszClipDstSQL );
CPLFree( psOptions->pszClipDstLayer );
CPLFree( psOptions->pszClipDstWhere );
CPLFree( psOptions->pszZField );
CPLFree( psOptions->pszSpatSRSDef );
CSLDestroy(psOptions->papszSelFields);
CSLDestroy( psOptions->papszFieldMap );
CSLDestroy( psOptions->papszMapFieldType );
CSLDestroy( psOptions->papszLayers );
CSLDestroy( psOptions->papszDSCO );
CSLDestroy( psOptions->papszLCO );
CSLDestroy( psOptions->papszDestOpenOptions );
CSLDestroy( psOptions->papszFieldTypesToString );
CSLDestroy( psOptions->papszMetadataOptions );
if( psOptions->pasGCPs != NULL )
{
GDALDeinitGCPs( psOptions->nGCPCount, psOptions->pasGCPs );
CPLFree( psOptions->pasGCPs );
}
if( psOptions->hClipSrc != NULL )
OGR_G_DestroyGeometry( psOptions->hClipSrc );
if( psOptions->hClipDst != NULL )
OGR_G_DestroyGeometry( psOptions->hClipDst );
if( psOptions->hSpatialFilter != NULL )
OGR_G_DestroyGeometry( psOptions->hSpatialFilter );
CPLFree(psOptions);
}
/************************************************************************/
/* GDALVectorTranslateOptionsSetProgress() */
/************************************************************************/
/**
* Set a progress function.
*
* @param psOptions the options struct for GDALVectorTranslate().
* @param pfnProgress the progress callback.
* @param pProgressData the user data for the progress callback.
*
* @since GDAL 2.1
*/
void GDALVectorTranslateOptionsSetProgress( GDALVectorTranslateOptions *psOptions,
GDALProgressFunc pfnProgress, void *pProgressData )
{
psOptions->pfnProgress = pfnProgress ? pfnProgress : GDALDummyProgress;
psOptions->pProgressData = pProgressData;
if( pfnProgress == GDALTermProgress )
psOptions->bQuiet = false;
}
| [
"[email protected]"
] | |
f16498f14ee08375f648d6cc55c9b21a5b118a92 | a070de8c140f9c1fad2ca69cf2cdacc9466332d5 | /LeetCodePractice/LeetCodePractice/Q175_Combine_Two_Tables.cpp | dbc578a05daa43717178dc16ed2b8b6f141ecea7 | [] | no_license | semkilljaeden/LeetCodePractice | 124df40e2b84be1f27e7c8256bcfafa7154ef387 | c15e790eae4b59c7af3e572e20fed3a7aee01a48 | refs/heads/master | 2023-03-28T23:28:13.049182 | 2021-03-31T21:17:48 | 2021-03-31T21:17:48 | 272,928,992 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11 | cpp | //skip, SQL | [
"[email protected]"
] | |
b30efc6e2c71eafb8a1e57d5da867afeff3772ab | a1df6d44dc67599d20ce5aa98a41938c43cc57da | /bit_mani.cpp | d6a6989043d4fdbf2c6a37ea4dae751725922ea3 | [] | no_license | Git-Pratik97/bit_challenges | a1f9ccfd8fac0d5e97ea84839c101e2985f28e63 | 7031de15fe6a0dcccf02cb4a2f499a416c9d069d | refs/heads/main | 2023-06-04T16:26:23.098183 | 2021-06-14T16:07:12 | 2021-06-14T16:07:12 | 376,882,465 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 781 | cpp | #include<iostream>
using namespace std;
int get_bit(int n, int pos)
{
return ((n & (1 << pos)) != 0);
}
int set_bit(int n, int pos)
{
return (n | (1 << pos));
}
int clear_bit (int n, int pos)
{
int mask = ~(1 << pos);
return(n & mask);
}
int update_bit(int n, int pos, int value)
{
int mask = ~(1 << pos);
n = n & mask;
return (n | (value << pos));
}
int main()
{
// cout << get_bit(5, 2) <<endl;
// // int k = 1 << 5;
// // cout << k <<endl;
// // int m = 5 << 1;
// // cout << m <<endl;
// cout << set_bit(5, 1) <<endl;
// cout << clear_bit(5, 2) << endl;
cout << update_bit(5, 1, 1) <<endl;
// int k = 8 << 4;
// cout << k <<endl;
return 0;
} | [
"[email protected]"
] | |
b6b54f4e92f33df6b45600613fe92b0c828feda2 | c7204f8930f6b6618d67b5e59e5bec375ef5caef | /Source/PluginProcessor.cpp | 1a156d6a8163be44873790e29d4aaba4d55af6ef | [] | no_license | smacla200/AmbiEncoder | caaf9c0c6280546a4a7d5e0440141d40a9e05838 | 4bc383ee4f4783599483c3ab0dd256c98bfefe96 | refs/heads/master | 2021-01-22T10:56:27.782866 | 2017-02-15T13:45:46 | 2017-02-15T13:45:46 | 82,054,533 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,156 | cpp | /*
==============================================================================
This file was auto-generated!
It contains the basic framework code for a JUCE plugin processor.
==============================================================================
*/
#include "PluginProcessor.h"
#include "PluginEditor.h"
//==============================================================================
AmbiEncoderAudioProcessor::AmbiEncoderAudioProcessor()
#ifndef JucePlugin_PreferredChannelConfigurations
: AudioProcessor (BusesProperties()
#if ! JucePlugin_IsMidiEffect
#if ! JucePlugin_IsSynth
.withInput ("Input", AudioChannelSet::mono(), true)
#endif
.withOutput ("Output", AudioChannelSet::ambisonic(), true)
#endif
)
#endif
{
}
AmbiEncoderAudioProcessor::~AmbiEncoderAudioProcessor()
{
}
//==============================================================================
const String AmbiEncoderAudioProcessor::getName() const
{
return JucePlugin_Name;
}
bool AmbiEncoderAudioProcessor::acceptsMidi() const
{
#if JucePlugin_WantsMidiInput
return true;
#else
return false;
#endif
}
bool AmbiEncoderAudioProcessor::producesMidi() const
{
#if JucePlugin_ProducesMidiOutput
return true;
#else
return false;
#endif
}
double AmbiEncoderAudioProcessor::getTailLengthSeconds() const
{
return 0.0;
}
int AmbiEncoderAudioProcessor::getNumPrograms()
{
return 1; // NB: some hosts don't cope very well if you tell them there are 0 programs,
// so this should be at least 1, even if you're not really implementing programs.
}
int AmbiEncoderAudioProcessor::getCurrentProgram()
{
return 0;
}
void AmbiEncoderAudioProcessor::setCurrentProgram (int index)
{
}
const String AmbiEncoderAudioProcessor::getProgramName (int index)
{
return String();
}
void AmbiEncoderAudioProcessor::changeProgramName (int index, const String& newName)
{
}
//==============================================================================
void AmbiEncoderAudioProcessor::prepareToPlay (double sampleRate, int samplesPerBlock)
{
// Use this method as the place to do any pre-playback
// initialisation that you need..
}
void AmbiEncoderAudioProcessor::releaseResources()
{
// When playback stops, you can use this as an opportunity to free up any
// spare memory, etc.
}
#ifndef JucePlugin_PreferredChannelConfigurations
bool AmbiEncoderAudioProcessor::isBusesLayoutSupported (const BusesLayout& layouts) const
{
#if JucePlugin_IsMidiEffect
ignoreUnused (layouts);
return true;
#else
// This is the place where you check if the layout is supported.
if (layouts.getMainOutputChannelSet() != AudioChannelSet::mono()
&& layouts.getMainOutputChannelSet() != AudioChannelSet::ambisonic())
return false;
// This checks if the input layout matches the output layout
#if ! JucePlugin_IsSynth
if (layouts.getMainOutputChannelSet() != layouts.getMainInputChannelSet())
return false;
#endif
return true;
#endif
}
#endif
void AmbiEncoderAudioProcessor::processBlock (AudioSampleBuffer& buffer, MidiBuffer&
midiMessages)
{
const int totalNumInputChannels = getTotalNumInputChannels();
const int totalNumOutputChannels = getTotalNumOutputChannels();
const int numSamples = buffer.getNumSamples();
// In case we have more outputs than inputs, this code clears any output
// channels that didn't contain input data, (because these aren't
// guaranteed to be empty - they may contain garbage).
// This is here to avoid people getting screaming feedback
// when they first compile a plugin, but obviously you don't need to keep
// this code if your algorithm always overwrites all the output channels.
for (int i = totalNumInputChannels; i < totalNumOutputChannels; ++i)
buffer.clear (i, 0, buffer.getNumSamples());
// Convert pan position in degrees to radians
float azimuth = (M_PI/180.f) * panPosition;
// Get a pointer to each of the Ambisonic channels
float* channelDataW = buffer.getWritePointer (0);
float* channelDataX = buffer.getWritePointer (1);
float* channelDataY = buffer.getWritePointer (2);
float* channelDataZ = buffer.getWritePointer (3); // Not used
// Loop through each sample
for (int i = 0; i < numSamples; i++)
{
float audioIn = channelDataW[i]; // Store input in temp variable
// Do the encoding (horizontal only)
channelDataW[i] = audioIn * 0.707;
channelDataX[i] = audioIn * cos(azimuth);
channelDataY[i] = audioIn * sin(azimuth);
}
}
//==============================================================================
bool AmbiEncoderAudioProcessor::hasEditor() const
{
return true; // (change this to false if you choose to not supply an editor)
}
AudioProcessorEditor* AmbiEncoderAudioProcessor::createEditor()
{
return new AmbiEncoderAudioProcessorEditor (*this);
}
//==============================================================================
void AmbiEncoderAudioProcessor::getStateInformation (MemoryBlock& destData)
{
// You should use this method to store your parameters in the memory block.
// You could do that either as raw data, or use the XML or ValueTree classes
// as intermediaries to make it easy to save and load complex data.
}
void AmbiEncoderAudioProcessor::setStateInformation (const void* data, int sizeInBytes)
{
// You should use this method to restore your parameters from this memory block,
// whose contents will have been created by the getStateInformation() call.
}
//==============================================================================
// This creates new instances of the plugin..
AudioProcessor* JUCE_CALLTYPE createPluginFilter()
{
return new AmbiEncoderAudioProcessor();
}
| [
"[email protected]"
] | |
0dc0848408183e18e81af461fdb9443ef6dbf494 | 3570f72209e2776a57d40c3fe8c44375bc2d3dc8 | /cpp/ClassA.h | e5125d315192a6cf64620c7fe7efe2c2b1ea9ec9 | [] | no_license | wjfsanhe/programBF | 072da4e4e43e7e5986ec8ca97e3376146b4f65aa | f17fbf4b76852e9e304c95831383d68c0c775451 | refs/heads/master | 2021-01-13T05:00:32.069598 | 2017-02-07T05:44:56 | 2017-02-07T05:44:56 | 81,170,802 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 192 | h | #include <stdio.h>
#include <stdlib.h>
class A {
public:
int ttt;
virtual void func_pub(){}//{printf("public func a\n");}
private:
int aaa;
void func_pri(){printf("private func b\n");}
};
| [
"[email protected]"
] | |
1175ac6ba349d990c3a00bbbdd5087f78c025f21 | 26c8107be3d1a212c2e426fc8fe7892a8db98b5a | /mountainpaths.cpp | f18e891800fdaddd629eb7236f0877aabe2eb301 | [] | no_license | mikeyroush/mountain-paths | a50c21337b15f435e24712469d37d0166e293d3b | 0f0af6f3c2a2961bb5d68c999989008bb773f07b | refs/heads/master | 2020-12-02T15:09:26.728220 | 2020-01-02T23:56:16 | 2020-01-02T23:56:16 | 231,044,919 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,395 | cpp | //
// main.cpp
// mountain paths
//
// Created by Mikey Roush on 9/28/17.
// Copyright © 2017 Michael Roush. All rights reserved.
//
#include "functions.h"
int main() {
//Initializing variables and asking for user inputs.
//**********************************************************************
string inFilename;
int rows, columns;
cout << "Enter number of rows: ";
cin >> rows;
cout << "Enter number of columns: ";
cin >> columns;
cout << "Enter input filename: ";
cin >> inFilename;
string outFilename = inFilename;
outFilename += ".ppm";
vector<vector<double>> mapData(rows,vector<double>(columns));
//Attempting to open input file and checking for error
//**********************************************************************
ifstream fileIn;
fileIn.open(inFilename);
if(!fileIn.is_open()){
cerr << "Error: Could not open input file" << endl;
return 1;
}
//Assigning the elements of the input file to their corresponding
//index in a matrix and then closing the input file
//**********************************************************************
int x;
for (unsigned int i = 0; i < rows; ++i){
for (unsigned int j = 0; j < columns && fileIn >> x; ++j)
mapData.at(i).at(j)=x;
}
fileIn.close();
//display(mapData);
//Finding the min and max values in the matrix
//**********************************************************************
double min = mapData.at(0).at(0);
double max = mapData.at(0).at(0);
for (unsigned int i = 0; i < mapData.size(); ++i) {
for (unsigned int j = 0; j < mapData[0].size(); ++j) {
if (mapData.at(i).at(j) < min) min = mapData.at(i).at(j);
if (mapData.at(i).at(j) > max) max = mapData.at(i).at(j);
}
}
cout << "min value: " << min << endl << "max value: " << max << endl;
//Putting the corresponding grey scale values into a new matrix
//then into corresponding red, blue and green matrices
//**********************************************************************
vector<vector<double>> greyScale = mapData;
for (unsigned int i = 0; i < greyScale.size(); ++i) {
for (unsigned int j = 0; j < greyScale[0].size(); ++j)
greyScale.at(i).at(j) = (greyScale.at(i).at(j) - min)/(max-min)*255;
}
vector<vector<double>> red = greyScale;
vector<vector<double>> green = greyScale;
vector<vector<double>> blue = greyScale;
//Finding greedy paths and highlighting the best of the greedy paths
//**********************************************************************
int greediestPath = rows * columns;
int greediestRow = 0;
for (unsigned int i = 0; i < mapData.size(); ++i){
red.at(i).at(0) = 252;
green.at(i).at(0) = 25;
blue.at(i).at(0) = 63;
int greedyPath = colorPath(mapData, red, green, blue, 252, 25, 63, i, max);
if (greedyPath < greediestPath) {
greediestPath = greedyPath;
greediestRow = i;
}
}
red.at(greediestRow).at(0) = 31;
green.at(greediestRow).at(0) = 253;
blue.at(greediestRow).at(0) = 13;
greediestPath = colorPath(mapData, red, green, blue, 31, 253, 13, greediestRow, max);
cout << "greediest path: " << greediestPath << endl;
//Finding greedy paths to the 4 edges of the map from a give point
//**********************************************************************
int ec_row, ec_column;
if (cin >> ec_row >> ec_column){
//int direction = 2;
for (int direction = 1; direction < 5; ++direction)
colorCross(mapData, red, green, blue, 19, 254, 253, ec_row, ec_column, max, direction);
}
//Attempting to open output file and checking for error
//then printing greyscale values to the output file
//**********************************************************************
ofstream fileOut;
fileOut.open(outFilename);
if (!fileOut.is_open()){
cerr << "Error: Could not open output file" << endl;
return 1;
}
//fileOut << fixed << setprecision(0);
fileOut << "P3" << endl;
fileOut << columns << " " << rows << endl;
fileOut << "255" << endl;
display(red, green, blue, fileOut);
fileOut.close();
return 0;
}
| [
"[email protected]"
] | |
99d6661de88d434e5d16276edf3ff0b756db917a | 051fdf2715925ea6752a053f2bc828ed7bfe0233 | /Engine/Source/Helper/Camera.h | 2255b95bba21c4a8c3a25174b43fe54eca39a3c3 | [] | no_license | SizzlingCalamari/fs12-engine | f6607461bd66fceb5c2a8a446bbe5e4228791d1d | 22bf3763f7dd09cae56f58881def6421cc64c933 | refs/heads/master | 2016-08-12T12:26:54.771382 | 2012-03-16T22:49:38 | 2012-03-16T22:49:38 | 51,328,555 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,885 | h | /*=====================================================================
Camera.h : Declaration of the CCamera class.
Author : Christopher Baptiste
Version: v1.0a
Licence : GNU GENERAL PUBLIC LICENSE
Copywrite (C) 2006, 2007
Christopher Baptiste
Full Sail, Inc.
3300 University Blvd. Ste 160
Winter Park, Florida 32792
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
//===================================================================*/
#ifndef _CAMERA_H_
#define _CAMERA_H_
/*=====================================================================
Header Includes:
//===================================================================*/
#include <d3d9.h>
#include <d3dx9.h>
/*=====================================================================
Class Declaration:
//===================================================================*/
class CCamera
{
private:
D3DXMATRIX m_mProjectionMatrix;
D3DXMATRIX m_mViewMatrix;
public:
CCamera(void);
~CCamera(void);
/*=====================================================================
Projection Matrix Functions
//===================================================================*/
D3DXMATRIX GetProjectionMatrix(void);
void SetProjectionMatrix(D3DXMATRIX *_mMatrix);
void BuildPerspective(float _fFieldOfView,
float _fAspect,
float _fZNear,
float _fZFar);
/*=====================================================================
View Matrix Functions
//===================================================================*/
D3DXMATRIX GetViewMatrix(bool _bTranslate = true);
void SetViewMatrix(D3DXMATRIX *_mMatrix);
void NormalizeViewMatrix(void);
D3DXVECTOR3 GetViewXAxis(void);
void SetViewXAxis(D3DXVECTOR3 _vPosition);
void SetViewXAxis(float _fX,
float _fY,
float _fZ);
D3DXVECTOR3 GetViewYAxis(void);
void SetViewYAxis(D3DXVECTOR3 _vPosition);
void SetViewYAxis(float _fX,
float _fY,
float _fZ);
D3DXVECTOR3 GetViewZAxis(void);
void SetViewZAxis(D3DXVECTOR3 _vPosition);
void SetViewZAxis(float _fX,
float _fY,
float _fZ);
D3DXVECTOR3 GetViewPosition(void);
void SetViewPosition(D3DXVECTOR3 _vPosition);
void SetViewPosition(float _fX,
float _fY,
float _fZ);
/*=================================================================
Local Transform Functions
//===============================================================*/
void ViewRotateLocalX(float _fAngle);
void ViewRotateLocalY(float _fAngle);
void ViewRotateLocalZ(float _fAngle);
void ViewTranslateLocal(D3DXVECTOR3 _vAxis, bool _bFPS = false);
void ViewTranslateLocalX(float _fScale, bool _bFPS = false);
void ViewTranslateLocalY(float _fScale, bool _bFPS = false);
void ViewTranslateLocalZ(float _fScale, bool _bFPS = false);
/*=================================================================
Global Transform Functions
//===============================================================*/
void ViewRotateGlobalX(float _fAngle);
void ViewRotateGlobalY(float _fAngle);
void ViewRotateGlobalZ(float _fAngle);
void ViewTranslateGlobal(D3DXVECTOR3 _vAxis);
void ViewTranslateGlobalX(float _fScale);
void ViewTranslateGlobalY(float _fScale);
void ViewTranslateGlobalZ(float _fScale);
};
#endif //_CAMERA_H_ | [
"[email protected]"
] | |
d56647bed1bfdff6848058142a1de7031769b9c9 | b97934b847014836a26b558ff06b8d784f78315f | /source/warlords.cpp | 1280124904e87499cf34c7050d9bf637a2ceeda5 | [] | no_license | ChrisPierce-StuphLabs/Warlords | 2d494e3823339523b2519febfeff18e396e5b99a | 5f6f4052dced7067c1d43f25a7d8b5cfe8b61702 | refs/heads/master | 2020-04-10T14:05:29.153021 | 2012-08-12T21:09:28 | 2012-08-12T21:09:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,302 | cpp | /*
Christopher Pierce
Warlords game
Written 08/01/2012
Last Modified 08/01/2012
Game pits zues vs poseidon vs hades in a
pokemon-like text based fighter game
*/
#include <iostream>
#include <iomanip>
#include <stdlib.h>
using namespace std;
struct warlord
{
string name;
string type;
string weakness;
unsigned int attackDamage;
unsigned int defenceValue;
int totalHealth;
int currentHealth;
bool isTurn;
} zues, poseidon, hades, chosen, challenger;
//functions for the player to use
//offence
int attack(warlord chosen, warlord challenger, int weakMultiplier)
{
if(challenger.weakness == chosen.type){ weakMultiplier = 2; }
else weakMultiplier = 1;
return(((chosen.attackDamage - challenger.defenceValue) * weakMultiplier) + (rand() % 6));
}
//defence
int defend(warlord &chosen, warlord &challenger, int weakMultiplier)
{
if (chosen.defenceValue > 10) { return 0; }
else chosen.defenceValue += 1;
return(0);
}
//what the player can do, and what happens next
int chooseMenu(int selection, int weakMultiplier, warlord &chosen, warlord &challenger)
{
if(selection == 1)
{
cout << "You did: " << attack(chosen, challenger, weakMultiplier);
cout <<" Damage to " << challenger.name << endl;
challenger.currentHealth -= attack(chosen, challenger, weakMultiplier);
}
else if (selection == 2)
{
defend(chosen, challenger, weakMultiplier);
cout << chosen.name << "'s defence value is: " << chosen.defenceValue << endl;
}
else if (selection == 3)
{
cout << "You forfit. That means your both a coward, and a loser. I'm sure your mother is proud. \n";
exit(0);
}
else cout << "You didnt enter a 1 or a 2 or a 3! Bad user!!! you should go cry in shame! " << endl;
}
//end of player's functions
//begining of "ai's" functions
int challengersChoice(int aiSelection, int weakMultiplier, int aiDamageDone, warlord &chosen, warlord &challenger)
{
//call to random to give 0 or a 1.
aiSelection = rand() % 2;
cout << "The computer decided to: ";
if(aiSelection == 0)
{
cout << " Attack \n";
aiDamageDone = (((chosen.currentHealth -= (challenger.attackDamage - chosen.defenceValue)) * weakMultiplier) + (rand() %6));
cout << challenger.name << " did " << aiDamageDone << " damage " << "to: " << chosen.name << endl;
return(aiDamageDone);
}
else if(aiSelection == 1)
{
cout << " Defend \n";
cout << " Computer's defence value is: " << challenger.defenceValue << endl;
if(challenger.defenceValue > 10)
{
return 0;
}
else return(challenger.defenceValue += 1);
}
else cout <<"challengersChoice() messed up somehow.. \n";
}
//end of the "ai's" functions
int main()
{
int weakMultiplier=0;
int warlordSelection=0;
int selection=0;
int aiSelection=0;
int aiDamageDone=0;
int random = rand() % 6;
bool isValid=0;
warlord();
warlord zues;
zues.name="zues";
zues.type="electric";
zues.weakness="fire";
zues.attackDamage=27;
zues.defenceValue=8;
zues.totalHealth=500;
zues.currentHealth=500;
zues.isTurn=0;
warlord poseidon;
poseidon.name="poseidon";
poseidon.type="water";
poseidon.weakness="electric";
poseidon.attackDamage=23;
poseidon.defenceValue=4;
poseidon.totalHealth=620;
poseidon.currentHealth=620;
poseidon.isTurn=0;
warlord hades;
hades.name="hades";
hades.type="fire";
hades.weakness="water";
hades.attackDamage=29;
hades.defenceValue=3;
hades.totalHealth=570;
hades.currentHealth=670;
hades.isTurn=0;
warlord choosen;
chosen.name=" ";
chosen.type=" ";
chosen.weakness=" ";
chosen.attackDamage=0;
chosen.defenceValue=0;
chosen.totalHealth=0;
chosen.currentHealth=0;
chosen.isTurn=0;
warlord challenger;
challenger.name=" ";
challenger.type=" ";
challenger.weakness=" ";
challenger.attackDamage=0;
challenger.defenceValue=0;
challenger.totalHealth=0;
challenger.currentHealth=0;
challenger.isTurn=0;
cout << "Welcome to warlords. Please select your character. 1 for Zues, 2 for Poseidon, and 3 for Hades.\n"
<< "Anthing else is garbage, and you will be yelled at for inputting garbage.\n";
checkWarlordSelection:
do
{
cout << "Enter Selection. " << endl;
try
{
cin >> warlordSelection;
if(warlordSelection == 1)
{
cout << "You chose Zues.\n";
chosen = zues;
chosen.isTurn = 1;
challenger = poseidon;
isValid=1;
}
else if(warlordSelection == 2)
{
cout << "You chose Poseidon. \n";
chosen = poseidon;
chosen.isTurn = 1;
challenger = hades;
isValid=1;
}
else if(warlordSelection == 3)
{
cout << "You chose Hades. \n";
chosen = hades;
chosen.isTurn = 1;
challenger = zues;
isValid=1;
}
else throw warlordSelection;
}
catch (string warlordSelection)
{
cout << "Please enter valid data! " << "You entered: " << "a character. " << endl;
isValid = 0;
goto checkWarlordSelection;
}
catch (char warlordSelection)
{
cout << "Please enter valid data! " << "You entered: " << "a character. " << endl;
isValid = 0;
goto checkWarlordSelection;
}
catch (double warlordSelection)
{
cout << "Please enter valid data! " << "You entered: " << "a double. " << endl;
isValid = 0;
goto checkWarlordSelection;
}
}//end do
while(isValid = 0);
cout << "Type: " << chosen.type << " Weakness: " << chosen.weakness << endl;
cout << "Attack: " << chosen.attackDamage << " Defence value: " << chosen.defenceValue << endl;
cout << "Total Health: " << chosen.totalHealth << " currentHealth " << chosen.currentHealth << endl;
cout << endl;
cout << "Your challenger today is: " << challenger.name << endl;
//control loop so the warlords fight to the death!
do
{
cout << "It's your turn! Enter 1 to attack, 2 to defend, or 3 to give up! " << endl;
cin >> selection;
cout << endl;
if(selection > 0 && selection < 4) {isValid=1; }
else isValid=0;
chooseMenu(selection, weakMultiplier, chosen, challenger);
cout << "Enemy " << challenger.name << " has only: " << challenger.currentHealth << " health remaining! " << endl;
challengersChoice(aiSelection, weakMultiplier, aiDamageDone, chosen, challenger);
cout << "Your warlord: " << chosen.name << " has only: " << chosen.currentHealth << " health remaining! " << endl;
}
while(chosen.currentHealth > 0 && challenger.currentHealth > 0);
if(challenger.currentHealth <= 0) { cout << "You win! Congradulations." << endl; }
else cout << "You were born a looser, and now you have gone and earned your reputation. " << "GAME OVER " << endl;
return 0;
}
| [
"[email protected]"
] | |
d7dc30bed94d52a7479794578bc5b668cc942486 | 85a2d8f6565fb8c55fa1cf2c2dc9e3ebff6093b8 | /factory/libpainter/Painter.h | 24136325aa7a4af497784062ca5df4b7d0bebabc | [] | no_license | klwxsrx/ood-course | eeaa2002b66deeb886d4a718bca437439da39a37 | 449b3e8c62fc2d9f73b7829170826ea83e20b5f5 | refs/heads/master | 2021-09-22T05:05:38.934710 | 2018-06-21T16:13:32 | 2018-06-21T16:13:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 156 | h | #pragma once
#include "IPainter.h"
class CPainter : public IPainter
{
public:
void DrawPicture(IPictureDraft const& draft, ICanvas& canvas) override;
};
| [
"[email protected]"
] | |
b6f08e1d4bdc2aa65adf534fd60a1b22f9719a6d | e39a0354db4013d2a8aec4a4565cfb5f6443ae8f | /UVa/UVa674.cpp | 3c1169adb929206cbb7f9528ff0494bc31805bc7 | [] | no_license | YimingPan/UVa-Solution | 8afd41673ff3aeebcedbfbf379247af5e2a6eca4 | 92862dcfc49baed97ea72f4467f12f8d588a9010 | refs/heads/master | 2021-09-09T21:52:13.645907 | 2018-03-19T22:48:06 | 2018-03-19T22:48:06 | 116,416,034 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 697 | cpp | #include <cstdio>
#include <cstring>
int dp[7500][6];
int m[6] = {0,1,5,10,25,50};
int dfs_dp(int n, int k)
{
if(dp[n][k]>0)
return dp[n][k];
if(k == 0 && n == 0)
return dp[n][k] = 1;
if(k == 1 || n == 1)
return dp[n][k] = 1;
if(n < m[k])
return dp[n][k] = dfs_dp(n,k-1);
return dp[n][k] = dfs_dp(n-m[k], k)+dfs_dp(n, k-1);
}
int main()
{
#ifdef LOCAL
freopen("in.txt","r",stdin);
#endif
int money;
for(int i=1;i<=7489;i++)
for(int j=1;j<=5;j++)
dfs_dp(i,j);
while(scanf("%d",&money)!=EOF)
{
if(money == 0) printf("1\n");
else printf("%d\n",dp[money][5]);
}
return 0;
}
| [
"[email protected]"
] | |
340a110a9c1f8629ea77039e0ac72fe4f55a6a35 | eb3a61fe2726650416e9957469d9bb62454360c5 | /src/vm/misc/Utils.cpp | fd21841cd831a6fa42b82a7d57012ce46044be14 | [
"MIT"
] | permissive | 215559085/ccvm | 2d237089c877da29eac21f66a6b0d4cc69b170cd | 483a3ea4081f3ed9513d6811bfa1573e8eb52ad2 | refs/heads/master | 2020-12-14T14:07:23.072431 | 2020-02-12T07:08:00 | 2020-02-12T07:08:00 | 234,766,806 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,043 | cpp | //
// Created by Admin on 2020/1/20.
//
#include "Utils.h"
#include "../Runtime/JavaTypes/JType.h"
#include "../Runtime/JRuntiemEnv/JRuntimeEnv.h"
#include <typeinfo>
JType* cloneValue(JType* value) {
if (value == nullptr) {
return nullptr;
}
JType* dupvalue{};
if (typeid(*value) == typeid(JDouble)) {
dupvalue = new JDouble();
dynamic_cast<JDouble*>(dupvalue)->i =
dynamic_cast<JDouble*>(value)->i;
} else if (typeid(*value) == typeid(JFloat)) {
dupvalue = new JFloat();
dynamic_cast<JFloat*>(dupvalue)->i =
dynamic_cast<JFloat*>(value)->i;
} else if (typeid(*value) == typeid(JInt)) {
dupvalue = new JInt();
dynamic_cast<JInt*>(dupvalue)->i = dynamic_cast<JInt*>(value)->i;
} else if (typeid(*value) == typeid(JLong)) {
dupvalue = new JDouble();
dynamic_cast<JDouble*>(dupvalue)->i =
dynamic_cast<JDouble*>(value)->i;
} else if (typeid(*value) == typeid(JObject)) {
dupvalue = new JObject();
dynamic_cast<JObject*>(dupvalue)->javaClassFile =
dynamic_cast<JObject*>(value)->javaClassFile;
dynamic_cast<JObject*>(dupvalue)->offset =
dynamic_cast<JObject*>(value)->offset;
} else if (typeid(*value) == typeid(JArray)) {
dupvalue = new JArray();
dynamic_cast<JArray*>(dupvalue)->len =
dynamic_cast<JArray*>(value)->len;
dynamic_cast<JArray*>(dupvalue)->offset =
dynamic_cast<JArray*>(value)->offset;
} else {
}
return dupvalue;
}
JType* determineBasicType(const std::string& type) {
if (IS_FIELD_INT(type) || IS_FIELD_BYTE(type) || IS_FIELD_CHAR(type) ||
IS_FIELD_SHORT(type) || IS_FIELD_BOOL(type)) {
return new JInt;
}
if (IS_FIELD_DOUBLE(type)) {
return new JDouble;
}
if (IS_FIELD_FLOAT(type)) {
return new JFloat;
}
if (IS_FIELD_LONG(type)) {
return new JLong;
}
return nullptr;
} | [
"[email protected]"
] | |
ae6aaf6c3bc8d80c912e00f605f165b1aba73778 | b2b4147268b2b3bedef9ba0e8dc42392ae00c520 | /source/models/performance_model/link_activity_trace_manager.cc | 6058020101827c5e4b20db0fd82fc0321c2417b2 | [] | no_license | allenhsin/ThermalSimulator | 3730b5097e49da6f5876dbed668e2a9902f424eb | f045aff7a97fabe0d280d62d4145d992574d6ef7 | refs/heads/master | 2021-01-10T14:24:10.884642 | 2015-02-10T02:36:44 | 2015-02-10T02:36:44 | 8,466,636 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,610 | cc |
#include <cassert>
#include <cstring>
#include <string>
#include "source/models/performance_model/link_activity_trace_manager.h"
#include "source/models/performance_model/performance_constants.h"
#include "source/models/performance_model/bit_sequence.h"
#include "source/models/performance_model/random_bit_sequence.h"
#include "source/system/event_scheduler.h"
#include "source/models/model_type.h"
#include "source/misc/misc.h"
#include "source/data/data.h"
#include "libutil/LibUtil.h"
using std::string;
namespace Thermal
{
LinkActivityTraceManager::LinkActivityTraceManager()
: PerformanceModel()
, _latrace_file (NULL)
, _latrace_file_read_over (false)
, _latrace_sampling_interval (0)
, _current_latrace_line_number (0)
{
_bit_sequence_driver_names.clear();
_bit_sequence_driver_names_set.clear();
_bit_sequence_drver_activity_factor.clear();
_bit_sequence_drver_bit_ratio.clear();
}
LinkActivityTraceManager::~LinkActivityTraceManager()
{}
void LinkActivityTraceManager::loadBitSequenceDriverNamesFromLatrace()
{
char line[LINE_SIZE];
char temp[LINE_SIZE];
char* src;
char name[STR_SIZE];
int i;
assert(_bit_sequence_driver_names.size()==0);
assert(_bit_sequence_driver_names_set.size()==0);
assert(_bit_sequence_drver_activity_factor.size()==0);
assert(_bit_sequence_drver_bit_ratio.size()==0);
_latrace_file = fopen(_config->getString("latrace_manager/latrace_file").c_str(), "r");
if (!_latrace_file)
LibUtil::Log::printFatalLine(std::cerr, "\nERROR: cannot open latrace file.\n");
do
{
// read the entire line
fgets(line, LINE_SIZE, _latrace_file);
if (feof(_latrace_file))
LibUtil::Log::printFatalLine(std::cerr, "\nERROR: No bit sequence driver names in link activity trace file.\n");
strcpy(temp, line);
src = strtok(temp, " \r\t\n");
// skip empty lines
} while (!src || src[0]=='#');
// if the latrace name line is too long
if(line[strlen(line)-1] != '\n')
LibUtil::Log::printFatalLine(std::cerr, "\nERROR: latrace bit sequence driver name line too long.\n");
// chop the names from the line read
for(i=0,src=line; *src; i++)
{
if(!sscanf(src, "%s", name))
LibUtil::Log::printFatalLine(std::cerr, "\nERROR: Invalid bit sequence driver names format in latrace file.\n");
src += strlen(name);
if(_bit_sequence_driver_names_set.count( (string) name ))
LibUtil::Log::printFatalLine(std::cerr, "\nERROR: Duplicated bit sequence driver names in latrace file.\n");
_bit_sequence_driver_names.push_back( (string) name );
_bit_sequence_driver_names_set.insert( (string) name );
while (isspace((int)*src))
src++;
}
assert(_bit_sequence_driver_names.size()== (unsigned int) i);
_bit_sequence_drver_activity_factor.resize(i);
_bit_sequence_drver_bit_ratio.resize(i);
} // loadBitSequenceDriverNamesFromLatrace
bool LinkActivityTraceManager::loadBitSequenceDriverActivityFromLatrace()
{
char line[LINE_SIZE];
char temp[LINE_SIZE];
char* src;
unsigned int i;
const unsigned int number_drivers = _bit_sequence_driver_names.size();
if (_latrace_file_read_over)
return false;
if (!_latrace_file)
LibUtil::Log::printFatalLine(std::cerr, "\nERROR: Cannot open latrace file.\n");
// skip empty lines
do
{
// read the entire line
fgets(line, LINE_SIZE, _latrace_file);
if (feof(_latrace_file))
{
fclose(_latrace_file);
_latrace_file_read_over = true;
return false;
}
strcpy(temp, line);
src = strtok(temp, " \r\t\n");
} while (!src || src[0]=='#');
// new line not read yet
if(line[strlen(line)-1] != '\n')
LibUtil::Log::printFatalLine(std::cerr, "\nERROR: latrace bit sequence driver name line too long.\n");
// chop the activity values from the line read
for(i=0,src=line; *src && i < number_drivers; i++) {
if(!sscanf(src, "%s", temp) || !sscanf(src, "%lf-%lf", &_bit_sequence_drver_activity_factor[i], &_bit_sequence_drver_bit_ratio[i]))
LibUtil::Log::printFatalLine(std::cerr, "\nERROR: Invalid activity format in latrace file.\n");
src += strlen(temp);
while (isspace((int)*src))
src++;
}
if( (i != number_drivers) || *src )
LibUtil::Log::printFatalLine(std::cerr, "\nERROR: Number of units exceeds limit.\n");
return true;
}
void LinkActivityTraceManager::setBitSequenceDriverNamesInBitSequenceData()
{
const unsigned int number_drivers = _bit_sequence_driver_names.size();
for(unsigned int i=0; i<number_drivers; ++i)
Data::getSingleton()->addBitSequenceData( _bit_sequence_driver_names[i], new RandomBitSequence() );
}
bool LinkActivityTraceManager::startupManager()
{
assert(_config);
// check if manager is enabled --------------------------------------------
if(!_config->getBool("latrace_manager/enable"))
{
LibUtil::Log::printLine( " Link Activity Trace Manager not enabled" );
return false;
}
// ------------------------------------------------------------------------
// set latrace constants --------------------------------------------------
_latrace_sampling_interval = _config->getFloat("latrace_manager/sampling_intvl");
_current_latrace_line_number = 0;
// ------------------------------------------------------------------------
// Read bit sequence driver names from latrace ----------------------------
// read latrace file
loadBitSequenceDriverNamesFromLatrace();
// initialize data structure
setBitSequenceDriverNamesInBitSequenceData();
// ------------------------------------------------------------------------
// Schedule the first physical model execution event ----------------------
EventScheduler::getSingleton()->enqueueEvent(0, LINK_ACTIVITY_TRACE_MANAGER);
// ------------------------------------------------------------------------
return true;
}
void LinkActivityTraceManager::executeManager(Time scheduled_time)
{
// only execute latrace when the schduled execution time matches the latrace sampling time
_current_latrace_line_number++;
if( !Misc::eqTime(scheduled_time, ((_current_latrace_line_number-1) * _latrace_sampling_interval) ) )
{
_current_latrace_line_number--;
LibUtil::Log::printLine(" Link Activity Trace new line not read");
return;
}
// Read single line of power trace ----------------------------------------
bool valid_line = false;
valid_line = loadBitSequenceDriverActivityFromLatrace();
// ------------------------------------------------------------------------
// Update bit sequence data structure -------------------------------------
// only update when there's a new valid line in the latrace file
// otherwise it will set activity to zero
if(valid_line)
{
const unsigned int number_drivers = _bit_sequence_driver_names.size();
for(unsigned int i=0; i<number_drivers; ++i)
{
Data::getSingleton()->getBitSequenceData(_bit_sequence_driver_names[i])->setActivityFactor(_bit_sequence_drver_activity_factor[i]);
Data::getSingleton()->getBitSequenceData(_bit_sequence_driver_names[i])->setBitRatio(_bit_sequence_drver_bit_ratio[i]);
}
// schedule the next event
EventScheduler::getSingleton()->enqueueEvent( (scheduled_time + _latrace_sampling_interval), LINK_ACTIVITY_TRACE_MANAGER);
}
else
// schedule the next event
EventScheduler::getSingleton()->finish();
// ------------------------------------------------------------------------
}
} // namespace Thermal
| [
"[email protected]"
] | |
f9bf834195002699dc24cacded70a6d88316b36e | 463c3b62132d215e245a097a921859ecb498f723 | /lib/dlib/sockstreambuf/sockstreambuf_kernel_abstract.h | 04c337e5cfc4677ca8bd1bcda5f70a487012d426 | [
"LicenseRef-scancode-unknown-license-reference",
"BSL-1.0"
] | permissive | athulan/cppagent | 58f078cee55b68c08297acdf04a5424c2308cfdc | 9027ec4e32647e10c38276e12bcfed526a7e27dd | refs/heads/master | 2021-01-18T23:34:34.691846 | 2009-05-05T00:19:54 | 2009-05-05T00:19:54 | 197,038 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,545 | h | // Copyright (C) 2003 Davis E. King ([email protected])
// License: Boost Software License See LICENSE.txt for the full license.
#undef DLIB_SOCKSTREAMBUF_KERNEl_ABSTRACT_
#ifdef DLIB_SOCKSTREAMBUF_KERNEl_ABSTRACT_
#include <iosfwd>
#include <streambuf>
#include "../sockets/sockets_kernel_abstract.h"
namespace dlib
{
// ----------------------------------------------------------------------------------------
class sockstreambuf : public std::streambuf
{
/*!
WHAT THIS OBJECT REPRESENTS
This object represents a stream buffer capable of writing to and
reading from TCP connections.
NOTE:
For a sockstreambuf EOF is when the connection has closed or otherwise
returned some kind of error.
Also note that any data written to the streambuf may be buffered
internally. So if you need to ensure that data is actually sent then you
should flush the stream.
A read operation is guaranteed to block until the number of bytes
requested has arrived on the connection. It will never keep blocking
once enough data has arrived.
THREADING
generally speaking, this object has the same kind of threading
restrictions as a connection object. those being:
- do not try to write to a sockstreambuf from more than one thread
- do not try to read from a sockstreambuf from more than one thread
- you may call shutdown() on the connection object and this will
cause any reading or writing calls to end. To the sockstreambuf it
will appear the same as hitting EOF. (note that EOF for a sockstreambuf
means that the connection has closed)
- it is safe to read from and write to the sockstreambuf at the same time
- it is not safe to try to putback a char and read from the stream from
different threads
!*/
public:
sockstreambuf (
connection* con
);
/*!
requires
- con == a valid connection object
ensures
- *this will read from and write to con
throws
- std::bad_alloc
!*/
sockstreambuf (
const scoped_ptr<connection>& con
);
/*!
requires
- con == a valid connection object
ensures
- *this will read from and write to con
throws
- std::bad_alloc
!*/
~sockstreambuf (
);
/*!
requires
- get_connection() object has not been deleted
ensures
- sockstream buffer is destructed but the connection object will
NOT be closed.
- Any buffered data is flushed to the connection.
!*/
connection* get_connection (
);
/*!
ensures
- returns a pointer to the connection object which this buffer
reads from and writes to
!*/
};
// ----------------------------------------------------------------------------------------
}
#endif // DLIB_SOCKSTREAMBUF_KERNEl_ABSTRACT_
| [
"jimmy@DGJ3X3B1.(none)"
] | jimmy@DGJ3X3B1.(none) |
85b6390ee1ac5147725fd4b0df9b25a07f23cd48 | 9fdf8ef1498e64fdfebb0313e0152707efb92e8c | /src/dpp/events/guild_update.cpp | 311ad6f74850b32d08efafcfe92bbf78550bcde7 | [
"Apache-2.0"
] | permissive | michaelschuff/DPP | b6d56b4cb73f6d349860021a905a8368816b075c | 3ce5716502bb527b5e3b806a2376929cc9c16cab | refs/heads/master | 2023-08-16T23:46:34.148048 | 2021-09-20T21:51:33 | 2021-09-20T21:51:33 | 408,591,593 | 0 | 0 | Apache-2.0 | 2021-09-20T20:31:21 | 2021-09-20T20:31:20 | null | UTF-8 | C++ | false | false | 2,303 | cpp | /************************************************************************************
*
* D++, A Lightweight C++ library for Discord
*
* Copyright 2021 Craig Edwards and D++ contributors
* (https://github.com/brainboxdotcc/DPP/graphs/contributors)
*
* 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 <dpp/discord.h>
#include <dpp/event.h>
#include <string>
#include <iostream>
#include <fstream>
#include <dpp/discordclient.h>
#include <dpp/discord.h>
#include <dpp/cache.h>
#include <dpp/stringops.h>
#include <dpp/nlohmann/json.hpp>
using json = nlohmann::json;
namespace dpp { namespace events {
using namespace dpp;
/**
* @brief Handle event
*
* @param client Websocket client (current shard)
* @param j JSON data for the event
* @param raw Raw JSON string
*/
void guild_update::handle(discord_client* client, json &j, const std::string &raw) {
json& d = j["d"];
dpp::guild* g = dpp::find_guild(from_string<uint64_t>(d["id"].get<std::string>(), std::dec));
if (g) {
g->fill_from_json(client, &d);
if (!g->is_unavailable()) {
if (client->creator->cache_policy.role_policy != dpp::cp_none && d.find("roles") != d.end()) {
for (int rc = 0; rc < g->roles.size(); ++rc) {
dpp::role* oldrole = dpp::find_role(g->roles[rc]);
dpp::get_role_cache()->remove(oldrole);
}
g->roles.clear();
for (auto & role : d["roles"]) {
dpp::role *r = new dpp::role();
r->fill_from_json(g->id, &role);
dpp::get_role_cache()->store(r);
g->roles.push_back(r->id);
}
}
}
if (client->creator->dispatch.guild_update) {
dpp::guild_update_t gu(client, raw);
gu.updated = g;
client->creator->dispatch.guild_update(gu);
}
}
}
}}; | [
"[email protected]"
] | |
4768b9e4aaf3fa302ef2141cf198e782f51496cb | d524724bee969c8c698daf61a3a047ad834f3543 | /src/PathCompare.cxx | 410ca1c67867da36d769991069de90a24968733f | [] | no_license | michelamichela/ITK-TubularGeodesics | 69f59120c5bc3ebd64b8bb62ce07eb403f7513ba | 426edc6b82fc4384da04f1f50d54f9874a56fa1d | refs/heads/master | 2020-12-25T20:09:13.895887 | 2013-04-07T02:53:50 | 2013-04-07T02:53:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,661 | cxx | //**********************************************************
//Copyright 2012 Fethallah Benmansour
//
//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.
//**********************************************************
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include <itkImageFileReader.h>
// stl includes
#include <iostream>
#include<iterator>
#include <vector>
#include <string>
const unsigned int Dimension = 3;
typedef itk::Point<float, Dimension+1> TubularPointType;
typedef std::vector<TubularPointType> TubularPathType;
template <typename Point>
bool readTubeFromSWCFile(const char *filename,
std::vector<Point> &cl,
unsigned int nrElementsPerLine = 7)
{
std::ifstream input(filename);
//std::cout << filename<< std::endl;
int linenr = 0;
while (input)
{
++linenr;
std::string line;
//Read line from file
if (!std::getline(input, line)) break;
if (line[0] == '#') continue;
std::istringstream linestream(line.c_str());
std::vector<double> nrs;
//Split line on spaces/tabs/newlines
std::copy(std::istream_iterator<double>(linestream),
std::istream_iterator<double>(), std::back_inserter(nrs));
//Check input: skip empty lines ...
if (nrs.size() == 0) continue;
// Check input: count number of elements on line ...
if (nrs.size() != nrElementsPerLine)
{
std::cerr << "Error reading reconstruction: line " << linenr << " from file "
<< filename << std::endl;
return false;
}
//Add point to centerline
//here the radius is not included
Point pt;
unsigned int swc_offset = 2;
for (unsigned int i = swc_offset; i < swc_offset+ Dimension+1; i++)
{
pt[i] = nrs[i];
}
cl.push_back(pt);
}
return true;
}
void Usage(char* argv[])
{
std::cerr << "Usage:" << std::endl;
std::cerr << argv[0] << std::endl
<< "<testPath> <baselinePath> <meanDitanceThreshold>" << std::endl
<< std::endl << std::endl;
}
int main ( int argc, char* argv[] )
{
if(argc < 4)
{
Usage( argv );
return EXIT_FAILURE;
}
unsigned int argumentOffset = 1;
std::string testPathFileName = argv[argumentOffset++];
std::string bsPathFileName = argv[argumentOffset++];
double meanDistanceThrsh = atof(argv[argumentOffset++]);
TubularPathType testPath, bsPath;
testPath.clear();
bsPath.clear();
readTubeFromSWCFile<TubularPointType>(testPathFileName.c_str(), testPath);
readTubeFromSWCFile<TubularPointType>(bsPathFileName.c_str(), bsPath);
if(testPath.size() != bsPath.size())
{
std::cerr << "Paths don't have the same length" << std::endl;
return EXIT_FAILURE;
}
double distance = 0.0;
for(unsigned int i = 0; i < testPath.size(); i++)
{
double d = 0.0;
for (unsigned int j = 0; j < Dimension+1; j++)
{
d+= (testPath[i][j] - bsPath[i][j])*(testPath[i][j] - bsPath[i][j]);
}
d = sqrt(d);
distance += d;
}
distance /= double(testPath.size());
if(distance > meanDistanceThrsh)
{
std::cerr << "mean distance greater than the threshold !!" << std::endl;
std::cout << "mean distance point by point is " << distance << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| [
"[email protected]"
] | |
825c76065629a593b20169f8be58bf6a1c42a847 | 157c466d9577b48400bd00bf4f3c4d7a48f71e20 | /Source/ProjectR/GameState/Tutorial/TutorialState.h | 126d7b86732634727bead1408f1707c5c12af064 | [] | no_license | SeungyulOh/OverlordSource | 55015d357297393c7315c798f6813a9daba28b15 | 2e2339183bf847663d8f1722ed0f932fed6c7516 | refs/heads/master | 2020-04-19T16:00:25.346619 | 2019-01-30T06:41:12 | 2019-01-30T06:41:12 | 168,291,223 | 8 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 399 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameState/IGameState.h"
#include "TutorialState.generated.h"
/**
*
*/
UCLASS()
class PROJECTR_API UTutorialState : public UIGameState
{
GENERATED_BODY()
public:
UTutorialState();
void Enter() override;
void Leave() override;
void BeginState() override;
};
| [
"[email protected]"
] | |
a8e24863950bcff5b5470a01e7390bd7cf580b8f | a81c07a5663d967c432a61d0b4a09de5187be87b | /ash/wm/workspace/backdrop_controller.h | 55934106f04b0ce298c5a9d740bc5dc48174672a | [
"BSD-3-Clause"
] | permissive | junxuezheng/chromium | c401dec07f19878501801c9e9205a703e8643031 | 381ce9d478b684e0df5d149f59350e3bc634dad3 | refs/heads/master | 2023-02-28T17:07:31.342118 | 2019-09-03T01:42:42 | 2019-09-03T01:42:42 | 205,967,014 | 2 | 0 | BSD-3-Clause | 2019-09-03T01:48:23 | 2019-09-03T01:48:23 | null | UTF-8 | C++ | false | false | 5,111 | h | // Copyright 2014 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.
#ifndef ASH_WM_WORKSPACE_BACKDROP_CONTROLLER_H_
#define ASH_WM_WORKSPACE_BACKDROP_CONTROLLER_H_
#include <memory>
#include "ash/accessibility/accessibility_observer.h"
#include "ash/ash_export.h"
#include "ash/public/cpp/split_view.h"
#include "ash/public/cpp/tablet_mode_observer.h"
#include "ash/public/cpp/wallpaper_controller_observer.h"
#include "ash/shell_observer.h"
#include "ash/wm/overview/overview_observer.h"
#include "base/macros.h"
#include "ui/gfx/geometry/rect.h"
namespace aura {
class Window;
}
namespace views {
class Widget;
}
namespace ui {
class EventHandler;
}
namespace ash {
// A backdrop which gets created for a container |window| and which gets
// stacked behind the top level, activatable window that meets the following
// criteria.
//
// 1) Has a aura::client::kHasBackdrop property = true.
// 2) Active ARC window when the spoken feedback is enabled.
// 3) In tablet mode:
// - Bottom-most snapped window in splitview,
// - Top-most activatable window if splitview is inactive.
class ASH_EXPORT BackdropController : public AccessibilityObserver,
public ShellObserver,
public OverviewObserver,
public SplitViewObserver,
public WallpaperControllerObserver,
public TabletModeObserver {
public:
explicit BackdropController(aura::Window* container);
~BackdropController() override;
void OnWindowAddedToLayout();
void OnWindowRemovedFromLayout();
void OnChildWindowVisibilityChanged();
void OnWindowStackingChanged();
void OnPostWindowStateTypeChange();
void OnDisplayMetricsChanged();
// Called when the desk content is changed in order to update the state of the
// backdrop even if overview mode is active.
void OnDeskContentChanged();
// Update the visibility of, and restack the backdrop relative to
// the other windows in the container.
void UpdateBackdrop();
// Returns the current visible top level window in the container.
aura::Window* GetTopmostWindowWithBackdrop();
aura::Window* backdrop_window() { return backdrop_window_; }
// ShellObserver:
void OnSplitViewModeStarting() override;
void OnSplitViewModeEnded() override;
// OverviewObserver:
void OnOverviewModeStarting() override;
void OnOverviewModeEnding(OverviewSession* overview_session) override;
void OnOverviewModeEndingAnimationComplete(bool canceled) override;
// AccessibilityObserver:
void OnAccessibilityStatusChanged() override;
// SplitViewObserver:
void OnSplitViewStateChanged(SplitViewState previous_state,
SplitViewState state) override;
void OnSplitViewDividerPositionChanged() override;
// WallpaperControllerObserver:
void OnWallpaperPreviewStarted() override;
// TabletModeObserver:
void OnTabletModeStarted() override;
void OnTabletModeEnded() override;
private:
friend class WorkspaceControllerTestApi;
void UpdateBackdropInternal();
void EnsureBackdropWidget();
void UpdateAccessibilityMode();
void Layout();
bool WindowShouldHaveBackdrop(aura::Window* window);
// Show the backdrop window.
void Show();
// Hide the backdrop window. If |destroy| is true, the backdrop widget will be
// destroyed, otherwise it'll be just hidden.
void Hide(bool destroy, bool animate = true);
// Returns true if the backdrop window should be fullscreen. It should not be
// fullscreen only if 1) split view is active and 2) there is only one snapped
// window and 3) the snapped window is the topmost window which should have
// the backdrop.
bool BackdropShouldFullscreen();
// Gets the bounds for the backdrop window if it should not be fullscreen.
// It's the case for splitview mode, if there is only one snapped window, the
// backdrop should not cover the non-snapped side of the screen, thus the
// backdrop bounds should be the bounds of the snapped window.
gfx::Rect GetBackdropBounds();
// Sets the animtion type of |backdrop_window_| to |type|.
void SetBackdropAnimationType(int type);
// The backdrop which covers the rest of the screen.
std::unique_ptr<views::Widget> backdrop_;
// aura::Window for |backdrop_|.
aura::Window* backdrop_window_ = nullptr;
// The container of the window that should have a backdrop.
aura::Window* container_;
// Event hanlder used to implement actions for accessibility.
std::unique_ptr<ui::EventHandler> backdrop_event_handler_;
ui::EventHandler* original_event_handler_ = nullptr;
// If true, skip updating background. Used to avoid recursive update
// when updating the window stack, or delay hiding the backdrop
// in overview mode.
bool pause_update_ = false;
DISALLOW_COPY_AND_ASSIGN(BackdropController);
};
} // namespace ash
#endif // ASH_WM_WORKSPACE_BACKDROP_CONTROLLER_H_
| [
"[email protected]"
] | |
5d5f1d38972a784ba303c4b9a08f68264d7aaa24 | 3e24f8a6c68bdb0a863ac4a430ccc781df37be5f | /multibody/multibody_tree/math/test/transform_test.cc | a4c6409d50082a999a97def40b51b50947b4d906 | [
"BSD-3-Clause"
] | permissive | BachiLi/drake-distro | dd4bfd2eb19a16b7a762ca7525564d7b487c9a1d | 100d08731818a204337207de59fc20251b17b642 | refs/heads/master | 2021-09-06T16:57:58.175967 | 2018-02-08T18:55:32 | 2018-02-08T18:55:32 | 109,608,467 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,589 | cc | #include "drake/multibody/multibody_tree/math/transform.h"
#include <gtest/gtest.h>
namespace drake {
namespace multibody {
namespace math {
namespace {
using Eigen::Matrix3d;
using Eigen::Vector3d;
constexpr double kEpsilon = std::numeric_limits<double>::epsilon();
// Helper function to create a rotation matrix associated with a BodyXYZ
// rotation by angles q1, q2, q3.
// Note: These matrices must remain BodyXYZ matrices with the specified angles
// q1, q2, q3, as these matrices are used in conjunction with MotionGenesis
// pre-computed solutions based on these exact matrices.
RotationMatrix<double> GetRotationMatrixA() {
const double q1 = 0.2, q2 = 0.3, q3 = 0.4;
const double c1 = std::cos(q1), c2 = std::cos(q2), c3 = std::cos(q3);
const double s1 = std::sin(q1), s2 = std::sin(q2), s3 = std::sin(q3);
Matrix3d m;
m << c2 * c3,
s3 * c1 + s1 * s2 * c3,
s1 * s3 - s2 * c1 * c3,
-s3 * c2,
c1 * c3 - s1 * s2 * s3,
s1 * c3 + s2 * s3 * c1,
s2,
-s1 * c2,
c1 * c2;
return RotationMatrix<double>(m);
}
// Helper function to create a rotation matrix associated with a BodyXYX
// rotation by angles r1, r2, r3.
// Note: These matrices must remain BodyXYX matrices with the specified angles
// r1, r2, r3, as these matrices are used in conjunction with MotionGenesis
// pre-computed solutions based on these exact matrices.
RotationMatrix<double> GetRotationMatrixB() {
const double r1 = 0.5, r2 = 0.5, r3 = 0.7;
const double c1 = std::cos(r1), c2 = std::cos(r2), c3 = std::cos(r3);
const double s1 = std::sin(r1), s2 = std::sin(r2), s3 = std::sin(r3);
Matrix3d m;
m << c2,
s1 * s2,
-s2 * c1,
s2 * s3,
c1 * c3 - s1 * s3 * c2,
s1 * c3 + s3 * c1 * c2,
s2 * c3,
-s3 * c1 - s1 * c2 * c3,
c1 * c2 * c3 - s1 * s3;
return RotationMatrix<double>(m);
}
#ifdef DRAKE_ASSERT_IS_ARMED
// Helper function to create an invalid rotation matrix.
Matrix3d GetBadRotationMatrix() {
const double theta = 0.5;
const double cos_theta = std::cos(theta), sin_theta = std::sin(theta);
Matrix3d m;
m << 1, 9000*kEpsilon, 9000*kEpsilon,
0, cos_theta, sin_theta,
0, -sin_theta, cos_theta;
return m;
}
#endif
// Helper functions to create generic position vectors.
Vector3d GetPositionVectorA() { return Vector3d(2, 3, 4); }
Vector3d GetPositionVectorB() { return Vector3d(5, 6, 7); }
// Helper function to create generic transforms.
Transform<double> GetTransformA() {
return Transform<double>(GetRotationMatrixA(), GetPositionVectorA());
}
Transform<double> GetTransformB() {
return Transform<double>(GetRotationMatrixB(), GetPositionVectorB());
}
// Tests default constructor - should be identity transform.
GTEST_TEST(Transform, DefaultTransformIsIdentity) {
const Transform<double> X;
EXPECT_TRUE(X.IsExactlyIdentity());
}
// Tests constructing a Transform from a RotationMatrix and Vector3.
GTEST_TEST(Transform, TransformConstructor) {
const RotationMatrix<double> R1 = GetRotationMatrixB();
const Matrix3d m = R1.matrix();
const Vector3<double> p(4, 5, 6);
const Transform<double> X(R1, p);
const Matrix3d zero_rotation = m - X.rotation().matrix();
const Vector3d zero_position = p - X.translation();
EXPECT_TRUE((zero_rotation.array() == 0).all());
EXPECT_TRUE((zero_position.array() == 0).all());
#ifdef DRAKE_ASSERT_IS_ARMED
// Bad rotation matrix should throw exception.
// Note: Although this test seems redundant with similar tests for the
// RotationMatrix class, it is here due to the bug (mentioned below) in
// EXPECT_THROW. Contrast the use here of EXPECT_THROW (which does not have
// an extra set of parentheses around its first argument) with the use of
// EXPECT_THROW((Transform<double>(isometryC)), std::logic_error); below.
const Matrix3d bad = GetBadRotationMatrix();
EXPECT_THROW(Transform<double>(RotationMatrix<double>(bad), p),
std::logic_error);
#endif
}
// Tests getting a 4x4 matrix from a Transform.
GTEST_TEST(Transform, Matrix44) {
const RotationMatrix<double> R = GetRotationMatrixB();
const Vector3<double> p(4, 5, 6);
const Transform<double> X(R, p);
const Matrix4<double> Y = X.GetAsMatrix();
const Matrix3d m = R.matrix();
EXPECT_EQ(Y(0, 0), m(0, 0));
EXPECT_EQ(Y(0, 1), m(0, 1));
EXPECT_EQ(Y(0, 2), m(0, 2));
EXPECT_EQ(Y(0, 3), p(0));
EXPECT_EQ(Y(1, 0), m(1, 0));
EXPECT_EQ(Y(1, 1), m(1, 1));
EXPECT_EQ(Y(1, 2), m(1, 2));
EXPECT_EQ(Y(1, 3), p(1));
EXPECT_EQ(Y(2, 0), m(2, 0));
EXPECT_EQ(Y(2, 1), m(2, 1));
EXPECT_EQ(Y(2, 2), m(2, 2));
EXPECT_EQ(Y(2, 3), p(2));
EXPECT_EQ(Y(3, 0), 0);
EXPECT_EQ(Y(3, 1), 0);
EXPECT_EQ(Y(3, 2), 0);
EXPECT_EQ(Y(3, 3), 1);
}
// Tests set/get a Transform with an Isometry3.
GTEST_TEST(Transform, Isometry3) {
const RotationMatrix<double> R = GetRotationMatrixB();
const Matrix3d m = R.matrix();
const Vector3<double> p(4, 5, 6);
Isometry3<double> isometryA;
isometryA.linear() = m;
isometryA.translation() = p;
const Transform<double> X(isometryA);
Matrix3d zero_rotation = m - X.rotation().matrix();
Vector3d zero_position = p - X.translation();
EXPECT_TRUE((zero_rotation.array() == 0).all());
EXPECT_TRUE((zero_position.array() == 0).all());
// Tests making an Isometry3 from a Transform.
const Isometry3<double> isometryB = X.GetAsIsometry3();
zero_rotation = m - isometryB.linear();
zero_position = p - isometryB.translation();
EXPECT_TRUE((zero_rotation.array() == 0).all());
EXPECT_TRUE((zero_position.array() == 0).all());
#ifdef DRAKE_ASSERT_IS_ARMED
// Bad matrix should throw exception.
const Matrix3d bad = GetBadRotationMatrix();
Isometry3<double> isometryC;
isometryC.linear() = bad;
// Note: As of December 2017, there seems to be a bug in EXPECT_THROW.
// The next line incorrectly calls the default Transform constructor.
// The default Transform constructor does not throw an exception which means
// the EXPECT_THROW fails. The fix (credit Sherm) was to add an extra set
// set of parentheses around the first argument of EXPECT_THROW.
EXPECT_THROW((Transform<double>(isometryC)), std::logic_error);
#endif
}
// Tests method Identity (identity rotation matrix and zero vector).
GTEST_TEST(Transform, Identity) {
const Transform<double>& X = Transform<double>::Identity();
EXPECT_TRUE(X.IsExactlyIdentity());
}
// Tests method SetIdentity.
GTEST_TEST(Transform, SetIdentity) {
const RotationMatrix<double> R = GetRotationMatrixA();
const Vector3d p(2, 3, 4);
Transform<double> X(R, p);
X.SetIdentity();
EXPECT_TRUE(X.IsExactlyIdentity());
}
// Tests whether or not a Transform is an identity transform.
GTEST_TEST(Transform, IsIdentity) {
// Test whether it is an identity matrix multiple ways.
Transform<double> X1;
EXPECT_TRUE(X1.IsExactlyIdentity());
EXPECT_TRUE(X1.IsIdentityToEpsilon(0.0));
EXPECT_TRUE(X1.rotation().IsExactlyIdentity());
EXPECT_TRUE((X1.translation().array() == 0).all());
// Test non-identity matrix.
const RotationMatrix<double> R = GetRotationMatrixA();
const Vector3d p(2, 3, 4);
Transform<double> X2(R, p);
EXPECT_FALSE(X2.IsExactlyIdentity());
// Change rotation matrix to identity, but leave non-zero position vector.
X2.set_rotation(RotationMatrix<double>::Identity());
EXPECT_FALSE(X2.IsExactlyIdentity());
EXPECT_FALSE(X2.IsIdentityToEpsilon(3.99));
EXPECT_TRUE(X2.IsIdentityToEpsilon(4.01));
// Change position vector to zero vector.
const Vector3d zero_vector(0, 0, 0);
X2.set_translation(zero_vector);
EXPECT_TRUE(X2.IsExactlyIdentity());
}
// Tests calculating the inverse of a Transform.
GTEST_TEST(Transform, Inverse) {
const RotationMatrix<double> R_AB = GetRotationMatrixA();
const Vector3d p_AoBo_A(2, 3, 4);
const Transform<double> X(R_AB, p_AoBo_A);
const Transform<double> I = X * X.inverse();
const Transform<double> X_identity = Transform<double>::Identity();
// As documented in IsNearlyEqualTo(), 8 * epsilon was chosen because it is
// slightly larger than the characteristic length |p_AoBo_A| = 5.4
// Note: The square-root of the condition number for a Transform is roughly
// the magnitude of the position vector. The accuracy of the calculation for
// the inverse of a Transform drops off with the sqrt condition number.
EXPECT_TRUE(I.IsNearlyEqualTo(X_identity, 8 * kEpsilon));
}
// Tests Transform multiplied by another Transform
GTEST_TEST(Transform, OperatorMultiplyByTransform) {
const Transform<double> X_BA = GetTransformA();
const Transform<double> X_CB = GetTransformB();
const Transform<double> X_CA = X_CB * X_BA;
// Check accuracy of rotation calculations.
const RotationMatrix<double> R_CA = X_CA.rotation();
const RotationMatrix<double> R_BA = GetRotationMatrixA();
const RotationMatrix<double> R_CB = GetRotationMatrixB();
const RotationMatrix<double> R_CA_expected = R_CB * R_BA;
EXPECT_TRUE(R_CA.IsNearlyEqualTo(R_CA_expected, 0));
// Expected position vector (from MotionGenesis).
const double x_expected = 5.761769695362743;
const double y_expected = 11.26952907288644;
const double z_expected = 6.192677089863299;
const Vector3d p_CoAo_C_expected(x_expected, y_expected, z_expected);
// Check accuracy of translation calculations.
const Vector3d p_CoAo_C_actual = X_CA.translation();
EXPECT_TRUE(p_CoAo_C_actual.isApprox(p_CoAo_C_expected, 32 * kEpsilon));
// Expected transform (with position vector from MotionGenesis).
// As documented in IsNearlyEqualTo(), 32 * epsilon was chosen because it is
// slightly larger than the characteristic length |p_CoAo_C| = 14.2
const Transform<double> X_CA_expected(R_CA_expected, p_CoAo_C_expected);
EXPECT_TRUE(X_CA.IsNearlyEqualTo(X_CA_expected, 32 * kEpsilon));
}
// Tests Transform multiplied by a position vector.
GTEST_TEST(Transform, OperatorMultiplyByPositionVector) {
const Transform<double> X_CB = GetTransformB();
// Calculate position vector from Co to Q, expressed in C.
const Vector3d p_BoQ_B = GetPositionVectorA();
const Vector3d p_CoQ_C = X_CB * p_BoQ_B;
// Expected position vector (from MotionGenesis).
const double x_expected = 5.761769695362743;
const double y_expected = 11.26952907288644;
const double z_expected = 6.192677089863299;
const Vector3d p_CoQ_C_expected(x_expected, y_expected, z_expected);
// Check accuracy of translation calculations.
EXPECT_TRUE(p_CoQ_C.isApprox(p_CoQ_C_expected, 32 * kEpsilon));
}
} // namespace
} // namespace math
} // namespace multibody
} // namespace drake
| [
"[email protected]"
] | |
aa397f95f3882699ff4e8632a42875db1191fba2 | 1644ef09ef48aaa4f1b87ad115596d0789085d58 | /MyExercises/c++primer/5.18textin3.cpp | 39e41012bcfb50d2ae62f5a33317b6212e3947d8 | [
"Apache-2.0"
] | permissive | smilliy/fairy | 4ed7ec0ab097017bddcf5a1162b36f4dbd8a6691 | c104beb35d2329787b3264a9102c44b2bafb973f | refs/heads/master | 2021-05-23T01:59:20.748129 | 2020-04-25T08:43:08 | 2020-04-25T08:43:08 | 253,183,168 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 342 | cpp | // textin3.cpp -- reading chars to end of file
#include <iostream>
int main()
{
using namespace std;
char ch;
int count = 0;
cin.get(ch);
while(cin.fail() == false) // test for EOF
{
cout << ch;
++count;
cin.get(ch);
}
cout << endl << count << " characters read.\n";
return 0;
}
| [
"[email protected]"
] | |
66b85f06760cff5c320a813cd41adcc898cdba82 | 05b5fbf24c6cc8046b7e9807089aff58a344c4d5 | /CBSocket.cpp | 21bacf33d1f7ab983004de6d0fe271f500fdadff | [] | no_license | xiamingxing/maya | 50687354706d3fd041fb362b06eb705e838eed04 | ffb2e6583a75c894884fea46b19bea8ed1a590a5 | refs/heads/master | 2020-04-02T04:42:44.355405 | 2016-07-19T04:42:59 | 2016-07-19T04:42:59 | 63,661,214 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 6,209 | cpp | ///////////////////////////////////////////////////////////////////////////////
// CBase Socket Class define Part : implementation file
//
#include "stdafx.h"
#include "SCDefine.h"
#include "Cbsocket.h"
#include "Poolbase.h"
#include "IocpBase.h"
#include "SockDataList.h"
CBSocket::CBSocket()
{
m_SockFlag = FALSE;
m_iSidMod = 0;
m_BufHead = 0;
m_BufTail = 0;
m_BufCount = 0;
m_sizeSendBuffer = SOCKET_BUF_SIZE; // SERVER 는 20 KBYTE.
m_socket_buffer_size_kiro = 32;
m_pIocpBase = NULL;
}
CBSocket::CBSocket(int nBufSize )
{
m_SockFlag = FALSE;
m_iSidMod = 0;
m_BufHead = 0;
m_BufTail = 0;
m_BufCount = 0;
if ( nBufSize == -1 )
m_sizeSendBuffer = SOCKET_BUF_SIZE; // SERVER 는 20 KBYTE.
else
m_sizeSendBuffer = nBufSize;
m_socket_buffer_size_kiro = 32;
m_pIocpBase = NULL;
}
CBSocket::~CBSocket()
{
}
int CBSocket::Init( int bufCreateFlag )
{
m_SockFlag = TRUE;
if ( m_pIocpBase )
m_iSidMod = m_Sid % m_pIocpBase->m_ThreadCount;
else
m_iSidMod = 0;
m_SockAliveFlag = 0;
m_iWsaReadIOPendFlag = 0;
m_iWsaWriteIOPendFlag = 0;
m_iWsaWouldBlockFlag = 0;
m_nIoPendingCount = 0;
m_BufHead = 0;
m_BufTail = 0;
m_BufCount = 0;
m_ActivatedFlag = 0;
return 1;
}
int CBSocket::DxSend(int length, char* pBuf)
{
if ( m_SockFlag != 1 ) return -2;
long ret, nSendBufferData;
nSendBufferData = length;
ret = CIOCPSocket::IOCP_Send( pBuf, nSendBufferData, 0 );
if ( ret == -2 ) // 죽은 소켓...
{
m_SockFlag = 0;
return -1;
}
else if ( ret == 0 || ret == SOCKET_ERROR )
{
int err = GetIOCPLastError();
if ( err == WSAEWOULDBLOCK )
{
m_SockFlag = 0;
return -1;
}
if ( err == WSA_IO_PENDING )
{
m_SockFlag = 0;
return -1;
}
switch ( err )
{
case WSAENETDOWN:
case WSAEINPROGRESS:
case WSAENETRESET:
case WSAENOBUFS:
case WSAESHUTDOWN:
break;
case WSAENOTCONN:
case WSAECONNABORTED:
break;
case WSAENOTSOCK:
case WSAECONNRESET:
break;
};
m_SockFlag = 0;
return -1;
}
m_nIoPendingCount = 0;
return nSendBufferData;
}
int CBSocket::B_Send(int length, char *pBuf)
{
if ( m_SockFlag != 1 ) return -1;
int retValue;
retValue = DxSend( length, pBuf );
if ( retValue == -1 && m_SockFlag != 1 )
{
SendSockCloseProcess();
return -1;
}
return length;
}
void CBSocket::B_OnSend( int nErrorCode )
{
if ( m_SockFlag != 1 ) return;
if ( m_iWsaWouldBlockFlag == 0 && m_iWsaWriteIOPendFlag == 0 ) return;
CIOCPSocket::IOCP_OnSend(nErrorCode);
}
void CBSocket::B_OnClose(int nErrorCode)
{
CIOCPSocket::IOCP_OnClose(nErrorCode);
}
void CBSocket::ParseCommand(int rBytes)
{
char pBuf[SOCKET_BUF_SIZE+1];
if ( rBytes )
{
m_rByte = rBytes;
memcpy( pBuf, m_RecvBuf, m_rByte );
ReceiveData( pBuf, m_rByte );
}
}
void CBSocket::ReceiveData(char *pBuf, int nByte)
{
if ( m_SockFlag != 1 ) return;
if ( nByte == 0 ) return;
BYTE *pdata = NULL;
try
{
pdata = new BYTE[nByte+1];
}
catch(...)
{
TRACE("]MEMORY ALLOC STEP1 FAILED AND RETRY...\n");
try
{
pdata = new BYTE[nByte+1];
}
catch(...)
{
TRACE("]MEMORY ALLOC STEP1 FAILED AND IGNORE...\n");
return;
}
}
memcpy( pdata, pBuf, nByte );
WAIT_RECV_DATA *wrd;
try
{
wrd = new WAIT_RECV_DATA;
}
catch(...)
{
TRACE("]MEMORY ALLOC STEP2 FAILED AND RETRY...\n");
try
{
wrd = new WAIT_RECV_DATA;
}
catch(...)
{
TRACE("]MEMORY ALLOC STEP2 FAILED AND RETURN...\n");
if ( pdata )
delete pdata;
return;
}
}
wrd->pData = pdata;
wrd->dcount = nByte;
wrd->usn = m_Sid;
wrd->m_Type = m_Type;
// IKING 2002.7.3
EnterCriticalSection(&m_pIocpBase->m_CS_ReceiveData[m_iSidMod]);
m_pIocpBase->m_pRecvData[m_iSidMod][m_pIocpBase->m_nHeadPtr[m_iSidMod]] = wrd;
if ( m_pIocpBase->m_nHeadPtr[m_iSidMod] >= WAIT_RECV_DATA_BUFFER-1)
m_pIocpBase->m_nHeadPtr[m_iSidMod] = 0;
else
{
m_pIocpBase->m_nHeadPtr[m_iSidMod]++;
}
LeaveCriticalSection(&m_pIocpBase->m_CS_ReceiveData[m_iSidMod]);
}
int CBSocket::RecycleRead()
{
return CIOCPSocket::IOCP_RecycleRead();
}
int CBSocket::SockCloseProcess(int nError)
{
B_Close();
return 1;
}
int CBSocket::SendSockCloseProcess(int nError)
{
B_SoftClose();
return 1;
}
void CBSocket::B_Close()
{
if ( m_pIocpBase == NULL )
{
m_SockFlag = FALSE;
m_ActivatedFlag = 1;
return;
}
if ( m_SockAliveFlag == -1 ) return;
// IKING 2002.6.29
EnterCriticalSection(&m_CS_CloseTime);
if ( m_SockAliveFlag == -1 )
{
LeaveCriticalSection(&m_CS_CloseTime);
return;
}
LeaveCriticalSection(&m_CS_CloseTime);
m_SockFlag = FALSE;
m_ActivatedFlag = 1;
CIOCPSocket::IOCP_Close();
RHANDLE *pHandle;
pHandle = m_pIocpBase->m_pPBM->m_pResources->GetHandle( m_Sid );
if ( pHandle )
m_pIocpBase->m_pPBM->ReleaseResource(pHandle);
else
{
TRACE("]Iocp closed : sid[%d] Handle Error...\n", m_Sid );
}
}
int CBSocket::PostSendData()
{
if ( m_SockFlag != 1 ) return -2;
if ( m_pIocpBase == NULL ) return -1;
SetEvent(m_pIocpBase->m_CreateSignalEvent);
return 0;
}
int CBSocket::SocketDisConnect()
{
return 1;
}
void CBSocket::B_SoftClose()
{
if ( m_pIocpBase == NULL ) return;
if ( m_SockAliveFlag == -1 ) return;
// IKING 2002.6.29
EnterCriticalSection(&m_CS_CloseTime);
if ( m_SockAliveFlag == -1 )
{
LeaveCriticalSection(&m_CS_CloseTime);
return;
}
LeaveCriticalSection(&m_CS_CloseTime);
OVERLAPPED *pOvl;
pOvl = &m_RecvOverlap;
pOvl->Offset = OVL_RECEIVE;
int retValue;
retValue = PostQueuedCompletionStatus( m_pIocpBase->m_hIOCPort, (DWORD)0, (DWORD)m_Sid, pOvl );
if ( !retValue )
{
int errValue;
errValue = GetLastError();
TRACE("]PostQueuedCompletionStatus Error := %d\n", errValue);
switch ( errValue )
{
case ERROR_IO_PENDING:
TRACE(">>PQCS : ERROR_IO_PENDING\n");
break;
default :
break;
};
return;
}
}
void CBSocket::SessionLogOut()
{
return;
}
| [
"[email protected]"
] | |
9354af605e044b8ae52b76d9d914793c6c4773bf | 36183993b144b873d4d53e7b0f0dfebedcb77730 | /GameDevelopment/Ultimate 3D Game Engine Design and Architecture/BuildingBlocksEngine/source/temp/RigidBox.cpp | 4b5a63b139321ad8dd8d2378ee446b27dffdf1c1 | [] | no_license | alecnunn/bookresources | b95bf62dda3eb9b0ba0fb4e56025c5c7b6d605c0 | 4562f6430af5afffde790c42d0f3a33176d8003b | refs/heads/master | 2020-04-12T22:28:54.275703 | 2018-12-22T09:00:31 | 2018-12-22T09:00:31 | 162,790,540 | 20 | 14 | null | null | null | null | UTF-8 | C++ | false | false | 2,076 | cpp | /*
Building Blocks Engine
Ultimate Game Engine Design and Architecture (2006)
Created by Allen Sherrod
*/
#include<RigidBox.h>
DECLARE_ENGINE_NAMESPACE
RigidBox::RigidBox()
{
m_width = 0.0f;
m_height = 0.0f;
m_depth = 0.0f;
m_obb.SetAxis1(Vector3D(1.0f, 0.0f, 0.0f));
m_obb.SetAxis2(Vector3D(0.0f, 1.0f, 0.0f));
m_obb.SetAxis3(Vector3D(0.0f, 0.0f, 1.0f));
m_obb.SetCenter(Vector3D(0.0f, 0.0f, 0.0f));
}
RigidBox::RigidBox(float width, float height, float depth)
{
m_width = width;
m_height = height;
m_depth = depth;
m_obb.SetAxis1(Vector3D(1.0f, 0.0f, 0.0f));
m_obb.SetAxis2(Vector3D(0.0f, 1.0f, 0.0f));
m_obb.SetAxis3(Vector3D(0.0f, 0.0f, 1.0f));
m_obb.SetCenter(Vector3D(0.0f, 0.0f, 0.0f));
}
RigidBox::~RigidBox()
{
}
void RigidBox::SetDimensions(float width, float height, float depth)
{
m_width = width;
m_height = height;
m_depth = depth;
m_volume = m_width * m_height * m_depth;
Vector3D half(width * 0.5f, height * 0.5f, depth * 0.5f);
m_radiusSqr = half.Magnitude();
m_obb.SetHalfAxis1(width * 0.5f);
m_obb.SetHalfAxis2(height * 0.5f);
m_obb.SetHalfAxis3(depth * 0.5f);
m_recalInertiaTensor = true;
}
OBB RigidBox::GetOBBWorldSpace()
{
OBB obb;
obb.ObjectTransform(m_obb, m_worldMat);
return obb;
}
scalar RigidBox::GetDragArea()
{
//
return 0;
}
scalar RigidBox::GetDragCoefficient()
{
return 0.95f;
}
scalar RigidBox::GetLiftCoefficient()
{
return 0;
}
scalar RigidBox::GetVolumeUnderHeight(float height)
{
//
return 0;
}
void RigidBox::CalcInertiaTensor()
{
scalar w2 = m_width * m_width;
scalar h2 = m_height * m_height;
scalar d2 = m_depth * m_depth;
m_inertiaTensor.matrix[0] = m_mass * (h2 + d2);
m_inertiaTensor.matrix[5] = m_mass * (w2 + d2);
m_inertiaTensor.matrix[10] = m_mass * (w2 + h2);
m_inertiaTensorInv.matrix[0] = 1 / m_inertiaTensor.matrix[0];
m_inertiaTensorInv.matrix[5] = 1 / m_inertiaTensor.matrix[5];
m_inertiaTensorInv.matrix[10] = 1 / m_inertiaTensor.matrix[10];
}
END_ENGINE_NAMESPACE | [
"[email protected]"
] | |
1be7c5b95e4835ed3264bb692794f8d94d2deb6b | 20b49a6ef1fa417d67abef2d29a598c9e41c478e | /CodeForces/Contests/CF Edu Round 104/E.cpp | 8d2f8beb4fbaa07d67104a864fafaf2504420760 | [] | no_license | switchpiggy/Competitive_Programming | 956dac4a71fdf65de2959dd142a2032e2f0710e1 | beaaae4ece70889b0af1494d68c630a6e053558a | refs/heads/master | 2023-04-15T19:13:12.348433 | 2021-04-04T06:12:29 | 2021-04-04T06:12:29 | 290,905,106 | 1 | 3 | null | 2020-10-05T20:16:53 | 2020-08-27T23:38:48 | C++ | UTF-8 | C++ | false | false | 2,764 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef long double ld;
#define benq queue
#define pbenq priority_queue
#define all(x) x.begin(), x.end()
#define sz(x) (ll)x.size()
#define m1(x) memset(x, 1, sizeof(x))
#define m0(x) memset(x, 0, sizeof(x))
#define inf(x) memset(x, 0x3f, sizeof(x))
#define MOD 1000000007
#define INF 0x3f3f3f3f3f3f3f3f
#define PI 3.14159265358979323846264338
#define flout cout << fixed << setprecision(12)
ll n1, n2, n3, n4;
pair<ll, ll> a[200007], b[200007], c[200007], d[200007];
set<ll> x[200007], y[200007], z[200007];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n1 >> n2 >> n3 >> n4;
for(ll i = 1; i <= n1; ++i) cin >> a[i].first, a[i].second = i;
for(ll i = 1; i <= n2; ++i) cin >> b[i].first, b[i].second = i;
for(ll i = 1; i <= n3; ++i) cin >> c[i].first, c[i].second = i;
for(ll i = 1; i <= n4; ++i) cin >> d[i].first, d[i].second = i;
sort(a + 1, a + n1 + 1);
sort(b + 1, b + n2 + 1);
sort(c + 1, c + n3 + 1);
sort(d + 1, d + n4 + 1);
auto no = []() {
cout << "-1\n";
exit(0);
};
ll m;
cin >> m;
for(ll i = 0; i < m; ++i) {
ll u, v;
cin >> u >> v;
x[v].insert(u);
}
cin >> m;
for(ll i = 0; i < m; ++i) {
ll u, v;
cin >> u >> v;
y[u].insert(v);
}
cin >> m;
for(ll i = 0; i < m; ++i) {
ll u, v;
cin >> u >> v;
z[u].insert(v);
}
for(ll i = 1; i <= n2; ++i) {
ll res = -1;
for(ll j = 1; j <= n1; ++j) {
if(x[b[i].second].find(a[j].second) == x[b[i].second].end()) {
res = j;
break;
}
}
if(res == -1) {
b[i].first = -1;
continue;
}
b[i].first += a[res].first;
}
for(ll i = 1; i <= n3; ++i) {
ll res = -1;
for(ll j = 1; j <= n4; ++j) {
if(z[c[i].second].find(d[j].second) == z[c[i].second].end()) {
res = j;
break;
}
}
if(res == -1) {
c[i].first = -1;
continue;
}
c[i].first += d[res].first;
}
vector<pair<ll, ll>> cc;
for(ll i = 1; i <= n3; ++i) if(c[i].first != -1) cc.push_back(c[i]);
sort(all(cc));
ll ans = LLONG_MAX;
for(ll i = 1; i <= n2; ++i) {
if(b[i].first == -1) continue;
for(ll j = 0; j < sz(cc); ++j) {
if(y[b[i].second].find(cc[j].second) == y[b[i].second].end()) {
ans = min(ans, cc[j].first + b[i].first);
break;
}
}
}
if(ans == LLONG_MAX) ans = -1;
cout << ans << '\n';
return 0;
} | [
"[email protected]"
] | |
4f07b8f2a4f04cea60ef5253345ef71eec689d37 | c120f72a42d2f202fc50e3569ae217220359a49c | /.history/src/main_20210723162804.cpp | c537f59613f84b70dd1b64d1461b07fd18cecf60 | [] | no_license | zlatkovnik/Crius | c5888fca8c2c572ce5b151adf6073f965b3914d6 | 414fb380823c5a38e33dd47818487290405ecde7 | refs/heads/main | 2023-07-07T04:35:12.126132 | 2021-08-09T14:51:03 | 2021-08-09T14:51:03 | 388,804,001 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,624 | cpp | #include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <iostream>
#include "shader.h"
#include "mesh.h"
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void processInput(GLFWwindow *window);
// settings
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT = 600;
int main()
{
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#ifdef __APPLE__
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif
// glfw window creation
// --------------------
GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", NULL, NULL);
if (window == NULL)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to initialize GLAD" << std::endl;
return -1;
}
{
float vertices[] = {
-0.5f, -0.5f, 0.0f, // left
0.5f, -0.5f, 0.0f, // right
0.0f, 0.5f, 0.0f // top
};
Mesh cube(vertices);
Shader basicShader("./src/res/shaders/basic.vert", "./src/res/shaders/basic.frag");
while (!glfwWindowShouldClose(window))
{
//Input
processInput(window);
//Render
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glm::mat4 model = glm::mat4(1.0f);
model = glm::rotate(model, glm::radians(90.0f), glm::vec3(0.0f, 0.0f, 1.0f));
glm::mat4 view = glm::mat4(1.0f);
view = glm::translate(view, glm::vec3(0.0f, 0.0f, 2.0f));
glm::mat4 projection = glm::mat4(1.0f);
glm::mat4 mvp = projection * view * model;
basicShader.setMat4("mvp", mvp);
cube.draw(basicShader);
//Swap poll
glfwSwapBuffers(window);
glfwPollEvents();
}
}
glfwTerminate();
return 0;
}
void processInput(GLFWwindow *window)
{
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
}
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
glViewport(0, 0, width, height);
} | [
"[email protected]"
] | |
847fe44fe5251f4f8116d894edc681b00027d259 | 9427126563527b81f1c4d3fb60c38bdc29e810d0 | /leetcode/456-132-pattern.cpp | 834426cab572ac21c1d0f2e5d9745d4f10895ddb | [] | no_license | gongzhitaao/oj | afe217753f112e445f2b75a5800c0fc2862688b2 | fbc771a3b239616be48b1b2fcaa39da9d8ce2a14 | refs/heads/master | 2021-01-17T02:59:56.456256 | 2018-03-07T01:59:01 | 2018-03-07T01:59:01 | 16,234,097 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 427 | cpp | class Solution
{
public:
bool find132pattern(vector<int>& nums)
{
const int n = nums.size();
stack<int> stk;
for (int i = n - 1, s3 = -1; i >= 0; --i) {
if (s3 >= 0 && nums[i] < nums[s3])
return true;
for (; stk.size() && nums[i] > nums[stk.top()]; stk.pop())
if (s3 < 0 || nums[stk.top()] > nums[s3])
s3 = stk.top();
stk.push(i);
}
return false;
}
};
| [
"[email protected]"
] | |
3f28fdcdd049ec06895b3ffc7e0a9946ca85cc02 | 7e167301a49a7b7ac6ff8b23dc696b10ec06bd4b | /prev_work/opensource/fMRI/FSL/fsl/extras/include/boost/boost/mpl/replace_if.hpp | a284442392c0538f95c3fb780143637ed0f92ca0 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | Sejik/SignalAnalysis | 6c6245880b0017e9f73b5a343641065eb49e5989 | c04118369dbba807d99738accb8021d77ff77cb6 | refs/heads/master | 2020-06-09T12:47:30.314791 | 2019-09-06T01:31:16 | 2019-09-06T01:31:16 | 193,439,385 | 5 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 1,891 | hpp |
#ifndef BOOST_MPL_REPLACE_IF_HPP_INCLUDED
#define BOOST_MPL_REPLACE_IF_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2000-2004
// Copyright John R. Bandela 2000-2002
// Copyright David Abrahams 2003-2004
//
// 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/mpl for documentation.
// $Source: /usr/local/share/sources/boost/boost/mpl/replace_if.hpp,v $
// $Date: 2007/06/12 15:03:23 $
// $Revision: 1.1.1.1 $
#include <boost/mpl/transform.hpp>
#include <boost/mpl/apply.hpp>
#include <boost/mpl/if.hpp>
#include <boost/mpl/aux_/inserter_algorithm.hpp>
#include <boost/mpl/aux_/config/forwarding.hpp>
namespace boost { namespace mpl {
namespace aux {
template< typename Predicate, typename T >
struct replace_if_op
{
template< typename U > struct apply
#if !defined(BOOST_MPL_CFG_NO_NESTED_FORWARDING)
: if_<
typename apply1<Predicate,U>::type
, T
, U
>
{
#else
{
typedef typename if_<
typename apply1<Predicate,U>::type
, T
, U
>::type type;
#endif
};
};
template<
typename Sequence
, typename Predicate
, typename T
, typename Inserter
>
struct replace_if_impl
: transform1_impl<
Sequence
, protect< aux::replace_if_op<Predicate,T> >
, Inserter
>
{
};
template<
typename Sequence
, typename Predicate
, typename T
, typename Inserter
>
struct reverse_replace_if_impl
: reverse_transform1_impl<
Sequence
, protect< aux::replace_if_op<Predicate,T> >
, Inserter
>
{
};
} // namespace aux
BOOST_MPL_AUX_INSERTER_ALGORITHM_DEF(4, replace_if)
}}
#endif // BOOST_MPL_REPLACE_IF_HPP_INCLUDED
| [
"[email protected]"
] | |
3c8ccfbf6866e88d63740e0c5ae101e36a3070b7 | 8bee6c7e6613a87b1e78572f49b8b04411a51974 | /4pheptinhcoban.cpp | 84f3ac006fa3c3015d5a1307ec715b7c4b877343 | [] | no_license | Tanphong15987532/BT-GIT2 | 59480da4b3b701f4223b4d119811bc04addba48c | 21f9a68a9988bdb11166ef347025706a9e87b0df | refs/heads/master | 2023-01-02T01:35:42.626991 | 2020-10-30T16:06:06 | 2020-10-30T16:06:06 | 308,634,009 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 789 | cpp | #include <iostream>
using namespace std;
int tong(int a, int b);
int hieu(int a, int b);
int tich(int a, int b);
float thuong(int a, int b);
int main()
{
cout << "DAY LA CHUONG TRINH DE THUC HANH GIT";
int a = 10;
int b = 2;
int tongab= tong(a,b);
int tichab= tich(a,b);
float thuongab= thuong(a,b);
cout<<"tong a + b = "<<tongab;
cout<<"tich a * b = "<tichab;
cout<<"thuong a / b = "<thuongab;
int hieuab = hieu(a,b);
cout <<"Hieu a - b = " << hieuab << endl;
system("pause");
return 0;
}
int tong(int a, int b)
{
int tong=0;
tong=a+b;
return tong;
}
int tich(int a, int b)
{
int tich=0;
tich=a*b;
return tich;
int hieu(int a, int b){
int sum = 0;
sum = a - b;
return b;
}
float thuong(int a, int b)
{
float thuong=0;
thuong=a/b;
return thuong;
} | [
"[email protected]"
] | |
e2de38bd80bf2cfa5e38ca90f4721f5caee5acb0 | 04d0e82e894777fa64303627804af494275f39bb | /common/errutils.hpp | c312e8eb4695597146dc5846cbcd00e46e90956e | [
"MIT"
] | permissive | avtomaton/toolchain-cpp | 1723d6e3f92327457dab54f9ef67d21c035f2318 | 69868a2b8328f5cf30f134303210d0306f76901e | refs/heads/master | 2020-05-22T03:57:08.290711 | 2017-09-14T18:15:36 | 2017-09-14T18:15:36 | 53,838,481 | 1 | 1 | null | 2016-06-07T10:53:34 | 2016-03-14T08:18:15 | C++ | UTF-8 | C++ | false | false | 3,405 | hpp | #ifndef AIFIL_UTILS_ERRUTILS_H
#define AIFIL_UTILS_ERRUTILS_H
#include <string>
#include <sstream>
#include <stdexcept>
#include <mutex>
#include <atomic>
#include <csignal>
#include "c_attribs.hpp"
#include "logging.hpp"
#include "errstream.hpp"
#ifdef __GNUC__
#define FUNC_SIGNATURE __PRETTY_FUNCTION__
#elif defined(_MSC_VER)
#define FUNC_SIGNATURE __FUNCSIG__
#else
#define FUNC_SIGNATURE __func__
#endif
#define af_assert(exp) (void)( (exp) || (aifil::assertion_failed(#exp, __FILE__, __LINE__), 0) )
#ifdef _MSC_VER
// use inline lambda instead of compound statement, seems working
#define af_exception(msg) \
[](){\
std::stringstream message; \
message << msg; \
std::stringstream ss; \
ss << "Exception in file: " << __FILE__ \
<< ", function: " << FUNC_SIGNATURE \
<< ", line: " << __LINE__; \
throw aifil::Exception(message.str(), ss.str());\
}()
#else
// seems working in clang too, but not sure
#define af_exception(msg) \
({\
std::stringstream message; \
message << msg; \
std::stringstream ss; \
ss << "Exception in file: " << __FILE__ \
<< ", function: " << FUNC_SIGNATURE \
<< ", line: " << __LINE__; \
throw aifil::Exception(message.str(), ss.str());\
})
#endif
namespace aifil
{
void assertion_failed(const char* cond, const char* file, unsigned lineno);
// enable core dumps for debug builds
void core_dump_enable();
#ifdef __GNUC__
/**
* @brief Signal handler for printing backtrace into logs.
* Prints backtrace and terminates application.
* Should be set with the following:
* @code
* struct sigaction sa;
* sa.sa_sigaction = aifil::signal_set_exit_with_backtrace;
* // possibly set some flags
* sigaction(SIGSEGV, &sa, NULL);
* // sigaction(<some other signal>, %sa, NULL);
* @endcode
* @param sig [in] signal code (SIGSEGV, SIGILL etc.)
* @param info [in] Some additional info added by sigaction.
* @param ucontext [in] Signal context added by sigaction.
*/
void signal_set_exit_with_backtrace(int sig, siginfo_t *info, void *ucontext);
#endif
/**
* @brief Return current backtrace with demangled calls.
* @param max_frames [in] maximal frames in trace.
* @param caller_addr [in] optional caller address for replacing signal handler.
* @return Backtrace content.
*/
std::string pretty_backtrace(int max_frames = 50, void *caller_addr = 0);
inline void except(bool condition, const std::string &error_message = "")
{
if (!condition)
throw std::runtime_error(error_message);
}
// check condition
inline void check(
bool condition, const std::string &error_message = "", bool exception = false)
{
if (condition)
return;
if (exception)
throw std::runtime_error(error_message);
else
log_error(error_message.c_str());
}
class Exception : public std::exception
{
public:
Exception(int code = -1, const std::string &message_ = "Description inaccessible",
const std::string &debug_message = "") noexcept :
err(code), message(message_), debug(debug_message)
{}
Exception(const std::string &message_, const std::string &debug_message = "") noexcept :
Exception(-1, message_, debug_message)
{}
const char *what() const noexcept
{
return message.c_str();
}
const char *debug_info() const noexcept
{
return debug.c_str();
}
int errcode() const noexcept
{
return err;
}
private:
protected:
int err;
std::string message;
std::string debug;
};
} //namespace aifil
#endif //AIFIL_UTILS_ERRUTILS_H
| [
"[email protected]"
] | |
ade6fdf199fdc32fa273b647b39296c30eb068ab | 24ce143a62abc3292c858fc17964c753106c8e3f | /closestInBST.cpp | 9525fded17ab0b559c3713e2b14acac0b372e7f6 | [] | no_license | code-ayush07/Daily-DSA | 5249ce654b4bbe0d7f3beded3bfa0b6844299fbe | 3f4f69266b40141bc683c553a735bf58f3aef8ae | refs/heads/master | 2023-02-22T09:18:08.279554 | 2021-01-28T16:00:31 | 2021-01-28T16:00:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 305 | cpp | int ans;
int k;
void inOrder(Node* root)
{
if(root == NULL)
{
return;
}
inOrder(root->left);
ans = min(ans, abs(root->data - k));
inOrder(root->right);
}
int minDiff(Node *root, int K)
{
ans = INT_MAX;
k =K;
inOrder(root);
return ans;
}
| [
"[email protected]"
] | |
0e33dac51ab2a0a71c3c19bf58387115bcca2a9d | bdb1e24f0a0be7fd2d1c1a202fdb6f33b0b23dac | /Source/Utility/MythForest/Component/EnvCube/EnvCubeComponent.cpp | 4ec6bcd2c3570b8c6d68f559116ae96a11f6a53a | [
"MIT"
] | permissive | paintdream/PaintsNow | 42f297b9596d6f825017945d6ba24321fab0946e | 71581a89585594c3b898959cea5ee9c52c9249ed | refs/heads/master | 2023-08-17T13:52:49.714004 | 2023-08-07T14:21:01 | 2023-08-07T14:21:01 | 162,007,217 | 11 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 923 | cpp | #include "EnvCubeComponent.h"
#include "../../Entity.h"
using namespace PaintsNow;
EnvCubeComponent::EnvCubeComponent() : range(1.0f, 1.0f, 1.0f), strength(1.0f) {}
EnvCubeComponent::~EnvCubeComponent() {}
Tiny::FLAG EnvCubeComponent::GetEntityFlagMask() const {
return Entity::ENTITY_HAS_RENDERCONTROL | RenderableComponent::GetEntityFlagMask();
}
uint32_t EnvCubeComponent::CollectDrawCalls(std::vector<OutputRenderData, DrawCallAllocator>& outputDrawCalls, const InputRenderData& inputRenderData, BytesCache& bytesCache, CollectOption option) {
return 0;
}
TObject<IReflect>& EnvCubeComponent::operator () (IReflect& reflect) {
BaseClass::operator () (reflect);
if (reflect.IsReflectProperty()) {
ReflectProperty(cubeMapTexture);
}
return *this;
}
void EnvCubeComponent::UpdateBoundingBox(Engine& engine, Float3Pair& box, bool recursive) {
Math::Union(box, Float3(-range));
Math::Union(box, range);
}
| [
"[email protected]"
] | |
4f956d128ed55e3cb2b61688a8b3cfe0d8ba024f | 33691f66e73fdfe7d90caebf51bc39b60ffd8a38 | /UserInterface/EntityOperation.cpp | be6b0b123dbb59768ea8a5f58f855d193930186b | [] | no_license | Frenor/CCCP | 9bc494dc5ed0bc049dc71a3735897ea33e663bbf | 91994c73af62aa6f3c1b7a812ee1ae6f8092a30a | refs/heads/master | 2020-05-07T09:23:06.667397 | 2014-11-24T16:30:43 | 2014-11-24T16:30:43 | 25,698,291 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,376 | cpp | #include "EntityOperation.h"
EntityOperation::EntityOperation(QObject* model, QObject *parent) : QObject(parent)
{
resetOperation();
connect(model, SIGNAL(activeEntityChanged(Entity*)), this, SLOT(newSelection(Entity*)));
connect(model, SIGNAL(entityDeleted(Entity*)), this, SLOT(removeEntity(Entity*)));
connect(this, SIGNAL(execute(EntityOperation*)), model, SLOT(executeEntityOperation(EntityOperation*)));
}
void EntityOperation::resetOperation()
{
entity1 = NULL;
entity2 = NULL;
operation = -1;
locked = false;
}
void EntityOperation::setEntityOperation(int operation)
{
this->operation = operation;
execute();
}
void EntityOperation::removeEntity(Entity* entity)
{
if(entity1 == entity)
{
entity1 = NULL;
}
if(entity2 == entity)
{
entity2 = NULL;
}
}
void EntityOperation::newSelection(Entity * entity)
{
if(!locked)
{
if(!entity)
{
resetOperation();
return;
}
else if(!entity->isEmpty())
{
if(!this->entity1)
{
this->entity1 = entity;
}
else if(this->entity1 != entity)
{
this->entity2 = entity;
execute();
}
}
}
}
void EntityOperation::execute()
{
if(hasValidOperation())
{
locked = true;
emit execute(this);
resetOperation();
}
}
bool EntityOperation::hasValidOperation()
{
if(!locked)
{
if(entity1 && entity2 && operation >= 0)
{
return true;
}
}
return false;
}
| [
"[email protected]"
] | |
691066a9f3540b8b2cb04b881c98f4216da53080 | 22f801ef0ad614dfe3584cc88e8ee9af4423d504 | /MbedQuadCopter/SystemCalibrators/CalibrationControllers/IMUSensors/SensorCalibrationControllers/XYZAxisCalController/XYZAxisCalController.h | fa0a9760bc533581e405f10caf52925ff9046bc3 | [] | no_license | Scubaboy/MbedQuad | 007ee11a7dd5be4daea306a6f955c5a866a3c2e4 | 5a02ce4d27cc66224c20403d99a941a4245755b5 | refs/heads/master | 2021-01-10T15:36:52.590917 | 2015-11-06T15:46:54 | 2015-11-06T15:46:54 | 45,548,575 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,786 | h | #ifndef XYZAxisCalController_H
#define XYZAxisCalController_H
#include "BaseCalibrationController.h"
#include "BaseDataStorageController.h"
#include "UserResponce.h"
#include "SensorBase.h"
#include "BaseThreeAxisFlightData.h"
#include "XYZAxisMinMax.h"
#include "XYZAxisCalCtrlTypes.h"
class XYZAxisCalController : public BaseCalibrationController
{
public:
XYZAxisCalController (BaseDataStorageController* dataStorageController,
XYZAxisMinMax::XYZAxisMinMaxCalData *calData,
BaseThreeAxisFlightData::BaseThreeAxisFlightDataStruct* flightData,
UserResponce::UserResponceStruct* userResponce,
SensorBase* sensor,
const XYZAxisCalCtrlTypes::AxisCalNameLookup* lookUp);
virtual bool RunCalibration();
virtual bool CheckAndUseStoredCalData() = 0;
virtual bool WriteCalDataToDataStore() = 0;
private:
void CompileRequest(const char* msg, int len, bool reSend);
bool CalibrateAxis();
bool RunAxisCalibration(XYZAxisCalCtrlTypes::Axis axis, XYZAxisCalCtrlTypes::AxisMinMax minMax);
float AverageReading(XYZAxisCalCtrlTypes::Axis axis);
void SendInstruction(XYZAxisCalCtrlTypes::Axis axis, XYZAxisCalCtrlTypes::AxisMinMax minMax);
virtual bool SendRequest(char* msg, int len, bool reSend = true);
public:
template <class ClassT>
void SendRequest(ClassT *ptr, bool(ClassT::*pFunc)(char* data, const int DataLength, bool confRequired))
{
this->sendRequestrptr = (FunctionPtrInternal*)ptr;
this->methodCallbackSendRequest = (bool (FunctionPtrInternal::*)(char* data, const int DataLength, bool confRequired))pFunc;
}
public:
CalStructure::CalMemStructure calibrationData;
private:
FunctionPtrInternal* sendRequestrptr;
bool (FunctionPtrInternal::*methodCallbackSendRequest)(char* data, const int DataLength, bool confRequired);
XYZAxisMinMax::XYZAxisMinMaxCalData *calData;
BaseThreeAxisFlightData::BaseThreeAxisFlightDataStruct* flightData;
SensorBase* sensor;
bool calComplete;
XYZAxisCalCtrlTypes::Stages calStage;
XYZAxisCalCtrlTypes::Axis axisUnderCal;
XYZAxisCalCtrlTypes::AxisMinMax axisMag;
XYZAxisCalCtrlTypes::AxisCalStages axisCalStage;
BaseDataStorageController* dataStorageController;
UserResponce::UserResponceStruct* userResponce;
int samplesTaken;
DigitalOut test;
bool waitingLastSend;
float lastReading;
const XYZAxisCalCtrlTypes::AxisCalNameLookup* lookUp;
};
#endif | [
"[email protected]"
] | |
fcc1a4741856cc3171b6d10e86fd1f1907cece2b | 39c885e8a20b9e7146f351fa43513837630f1ded | /webpagetest/agent/browser/ie/pagetest/PagetestReporting.h | 56b071b4f9dea415ef11b0cae585b63787b1d69a | [] | no_license | youleiy/di | 3f95ccef08708a48e7c265249b445bf1e80bdb06 | a82782560b22df665575e662ea4c888d22e79f96 | refs/heads/master | 2021-01-14T09:41:57.667390 | 2014-01-01T04:27:20 | 2014-01-01T04:27:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,723 | h | /*
Copyright (c) 2005-2007, AOL, LLC.
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 the company 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.
*/
#pragma once
#include "ScriptEngine.h"
namespace pagespeed {
class PagespeedInput;
class Results;
}
class CCDNEntry
{
public:
CCDNEntry(void):isCDN(false){}
CCDNEntry(const CCDNEntry& src){ *this = src; }
~CCDNEntry(void){}
const CCDNEntry& operator =(const CCDNEntry& src)
{
name = src.name;
isCDN = src.isCDN;
provider = src.provider;
return src;
}
CString name;
CString provider;
bool isCDN;
};
class CPagetestReporting :
public CScriptEngine
{
public:
CPagetestReporting(void);
virtual ~CPagetestReporting(void);
enum _report_state
{
NONE,
QUIT,
QUIT_NOEND,
DOC_END,
TIMER,
DOC_DONE
};
double tmDoc; // calculated time to doc complete
double tmLoad; // calculated load time
double tmActivity; // calculated time to fully loaded
double tmFirstByte; // calculated time to first byte
double tmStartRender; // calculated time to render start
double tmDOMElement; // calculated time to DOM Element
double tmLastActivity; // time to last activity
double tmBasePage; // time to the base page being complete
int reportSt; // Done Reporting?
DWORD basePageResult; // result of the base page
CString basePageCDN; // CDN used by the base page (if any)
CString basePageRTT; // RTT for the base page
DWORD basePageAddressCount;
DWORD msAFT; // AFT Time (if we're capturing it)
DWORD msVisualComplete; // Visually complete time (only available with video capture)
DWORD nDns; // number of DNS lookups
DWORD nConnect; // number of connects
DWORD nRequest; // number of requests
DWORD nReq200; // number of requests OK
DWORD nReq302; // number of redirects
DWORD nReq304; // number of "Not Modified"
DWORD nReq404; // number of "Not Found"
DWORD nReqOther; // number of other reequests
DWORD nDns_doc; // number of DNS lookups
DWORD nConnect_doc; // number of connects
DWORD nRequest_doc; // number of requests
DWORD nReq200_doc; // number of requests OK
DWORD nReq302_doc; // number of redirects
DWORD nReq304_doc; // number of "Not Modified"
DWORD nReq404_doc; // number of "Not Found"
DWORD nReqOther_doc; // number of other reequests
DWORD measurementType; // is the page web 1.0 or 2.0?
CString logFile; // base file name for the log file
CString linksFile; // location where we should save all links found on the page to
CString s404File; // location where we should save all 404's from the page
CString htmlFile; // location where we should save the page html out to
CString cookiesFile; // location where we should save the cookies out to
DWORD saveEverything; // Do we save out a waterfall image, reports and everything we have?
DWORD captureVideo; // do we save out the images necessary to construct a video?
DWORD checkOpt; // Do we run the optimization checks?
DWORD noHeaders;
DWORD noImages;
CString somEventName; // name for the current web test
MIB_TCPSTATS tcpStatsStart; // TCP stats at the start of the document
MIB_TCPSTATS tcpStats; // TCP stats calculated
double tcpRetrans; // rate of TCP retransmits (basically packet loss)
DWORD labID;
DWORD dialerID;
DWORD connectionType;
TCHAR descriptor[100];
TCHAR logUrl[1000];
DWORD build;
CString version;
DWORD experimental;
DWORD screenShotErrors;
DWORD includeHeader;
DWORD includeObjectData;
DWORD includeObjectData_Now;
CString guid;
CString pageUrl;
SOCKADDR_IN pageIP; // IP address for the page (first IP address used basically)
DWORD totalFlagged; // total number of flagged connections on the page
DWORD maxSimFlagged; // Maximum number of simultaneous flagged connections
DWORD flaggedRequests; // number of flagged requests
CAtlList<CString> blockedRequests; // list of requests that were blocked
CAtlList<CString> blockedAdRequests; // list of ad requests that were blocked
// optimization aggregates
DWORD gzipTotal;
DWORD gzipTarget;
DWORD minifyTotal;
DWORD minifyTarget;
DWORD compressTotal;
DWORD compressTarget;
virtual void Reset(void);
virtual void ProcessResults(void);
virtual void FlushResults(void);
// database-friendly report
virtual void GenerateLabReport(bool fIncludeHeader, CString &szLogFile);
// detailed reporting information
virtual void ReportRequest(CString & szReport, CWinInetRequest * r);
virtual void GenerateReport(CString &szReport);
virtual void ReportPageData(CString & buff, bool fIncludeHeader);
virtual void ReportObjectData(CString & buff, bool fIncludeHeader);
// internal helpers
virtual void GenerateGUID(void);
void cdnLookupThread(DWORD index);
protected:
CString GenerateSummaryStats(void);
// optimization checks
void CheckOptimization(void);
void CheckGzip();
void CheckKeepAlive();
void CheckCDN();
void CheckCache();
void CheckCombine();
void CheckCookie();
void CheckMinify();
void CheckImageCompression();
void CheckEtags();
void CheckPageSpeed();
void ProtectedCheckPageSpeed();
void CheckCustomRules();
void SaveHTML(void);
void SaveCookies(void);
void Log404s(void);
void PopulatePageSpeedInput(pagespeed::PagespeedInput* input);
void StartCDNLookups(void);
CRITICAL_SECTION csCDN;
CAtlArray<CWinInetRequest *> cdnRequests;
CAtlArray<HANDLE> hCDNThreads;
CAtlList<DWORD> otherResponseCodes;
CStringA html;
pagespeed::Results* pagespeedResults;
bool IsCDN(CWinInetRequest * w, CString &provider);
CAtlList<CCDNEntry> cdnLookups;
private:
void SaveUrls(void);
void GetLinks(CComQIPtr<IHTMLDocument2> &doc, CAtlList<CStringA> &urls);
void SaveProgressImage(CxImage &img, CString file, bool resize, DWORD quality);
void SaveStatusUpdates(CString file);
void SaveBodies(CString file);
void SaveCustomMatches(CString file);
void SortEvents();
DWORD CalculateAFT();
void SaveVideo();
bool ImagesAreDifferent(CxImage * img1, CxImage* img2);
void SaveHistogram(CxImage& image, CString file);
CStringA JSONEscape(CStringA src);
};
| [
"[email protected]"
] | |
eb057c0b8c8db23e12d52edcb12c9324b6fef22b | b64d20711fa857b1a5149fb1bbfdda2a627cdde6 | /cerberus_anymal_c_control_1/include/cerberus_anymal_c_control_1/controller/cpgController_j.hpp | e0c16f5aef205bd6e34e54ee205ce7f2bd54ec39 | [
"BSD-3-Clause"
] | permissive | zdkhit/cerberus_anymal_locomotion | 179c7423c2f4fa58f866e5c59c43ebc7ae5b6c28 | 0af0fe9cd26a8e80f729e031aee43da0b7062310 | refs/heads/master | 2023-02-25T12:04:17.240281 | 2021-02-01T12:38:48 | 2021-02-01T12:38:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,047 | hpp | #ifndef RAI_QUADRUPEDCONTROLLER_HPP
#define RAI_QUADRUPEDCONTROLLER_HPP
#include <ros/console.h>
#include <Eigen/Core>
#include "string"
#include "cerberus_anymal_utils/SimpleMLPLayer.hpp"
#include "cerberus_anymal_utils/IK.hpp"
#include "cerberus_anymal_utils/GraphLoader.hpp"
# define M_PI 3.14159265358979323846 /* pi */
# define M_PI_2 1.57079632679489661923 /* pi/2 */
namespace RAI {
class QuadrupedController {
using Dtype = float;
static constexpr int EstimationDim = 4;
static constexpr int ObservationDim = 60;
static constexpr int HistoryLength = 128;
static constexpr int jointHistoryLength = 20;
static constexpr unsigned int actionDimension = 16;
static constexpr int stateDimension = 133;
typedef typename Eigen::Matrix<double, 3, 1> AngularVelocity;
typedef typename Eigen::Matrix<double, 3, 1> LinearVelocity;
typedef typename Eigen::Matrix<double, 4, 1> Quaternion;
typedef typename Eigen::Matrix<double, 3, 3> RotationMatrix;
typedef typename Eigen::Matrix<double, 4, 1> Vector4d;
typedef typename Eigen::Matrix<double, actionDimension, 1> Action;
typedef typename Eigen::Matrix<Dtype, ObservationDim, 1> Observation;
typedef typename Eigen::Matrix<Dtype, stateDimension, 1> State;
typedef typename Eigen::VectorXd VectorXd;
typedef typename Eigen::Matrix<Dtype, -1, 1> VectorXD;
public:
QuadrupedController() {
footPositionOffset_ <<
0.3 + 0.1, 0.2, h0_,
0.3 + 0.1, -0.2, h0_,
-0.3 - 0.1, 0.2, h0_,
-0.3 - 0.1, -0.2, h0_;
jointNominalConfig_.setZero(12);
Eigen::Vector3d sol;
for (int i = 0; i < 4; i++) {
IK_.solveIK(sol, footPositionOffset_.segment(3 * i, 3), i);
jointNominalConfig_.segment(3 * i, 3) = sol;
}
observationOffset_ << 0.0, 0.0, 0.0,
0.0, 0.0, 1.0, /// gravity axis
VectorXD::Constant(6, 0.0),
jointNominalConfig_.template cast<Dtype>(),
VectorXD::Constant(12, 0.0),
VectorXD::Constant(12, 0.0),
VectorXD::Constant(8, 0.0),
VectorXD::Constant(4, 0.0);
observationScale_ <<
1.5, 1.5, 1.5, /// command
5.0, 5.0, 5.0, /// gravity axis
VectorXD::Constant(3, 2.0),
VectorXD::Constant(3, 2.0),
VectorXD::Constant(12, 2.0), /// joint angles
0.5, 0.4, 0.3,
0.5, 0.4, 0.3,
0.5, 0.4, 0.3,
0.5, 0.4, 0.3,
6.5, 4.5, 3.5,
6.5, 4.5, 3.5,
6.5, 4.5, 3.5,
6.5, 4.5, 3.5,
VectorXD::Constant(8, 1.5),
VectorXD::Constant(4, 2.0 / freqScale_);
/// state params
stateOffset_ << 0.0, 0.0, 0.0, /// command
0.0, 0.0, 1.0, /// gravity axis
VectorXD::Constant(6, 0.0), /// body lin/ang vel
jointNominalConfig_.template cast<Dtype>(), /// joint position
VectorXD::Constant(12, 0.0), /// position error
VectorXD::Constant(12, 0.0), /// position error
VectorXD::Constant(4, 0.0),
VectorXD::Constant(8, 0.0),
VectorXD::Constant(24, 0.0),
VectorXD::Constant(24, 0.0),
jointNominalConfig_.template cast<Dtype>(),
jointNominalConfig_.template cast<Dtype>(),
0.0;
stateScale_ << 1.5, 1.5, 1.5, /// command
5.0, 5.0, 5.0, /// gravity axis
VectorXD::Constant(3, 2.0),
VectorXD::Constant(3, 2.0),
VectorXD::Constant(12, 2.0), /// joint angles
0.5, 0.4, 0.3,
0.5, 0.4, 0.3,
0.5, 0.4, 0.3,
0.5, 0.4, 0.3,
6.5, 4.5, 3.5,
6.5, 4.5, 3.5,
6.5, 4.5, 3.5,
6.5, 4.5, 3.5,
VectorXD::Constant(4, 2.0 / freqScale_),
VectorXD::Constant(8, 1.5),
VectorXD::Constant(24, 5.0), /// joint position errors
0.5, 0.4, 0.3,
0.5, 0.4, 0.3,
0.5, 0.4, 0.3,
0.5, 0.4, 0.3,
0.5, 0.4, 0.3,
0.5, 0.4, 0.3,
0.5, 0.4, 0.3,
0.5, 0.4, 0.3,
VectorXD::Constant(12, 2.0),
VectorXD::Constant(12, 2.0),
2.0 / freqScale_;
double amp1 = 0.5 * freqScale_, amp2 = 0.0;
baseFreq_ = 1.3 * freqScale_;
actionScale_ <<
amp1, amp1, amp1, amp1,
VectorXd::Constant(12, 0.2);
actionOffset_ <<
amp2, amp2, amp2, amp2,
VectorXd::Constant(12, 0.0);
for (size_t i = 0; i < 4; i++) {
clearance_[i] = 0.2;
}
footPos_Target.resize(4);
prevfootPos_Target.resize(4);
prevfootPos_Target2.resize(4);
//tensor config
state_dims_inv.AddDim(1);
state_dims_inv.AddDim(1);
state_dims_inv.AddDim(stateDimension);
state_tf_tensor = tensorflow::Tensor(tensorflow::DataType::DT_FLOAT, state_dims_inv);
for (size_t i = 0; i < 4; i++) {
piD_[i] = 0.0;
footPos_Target[i] = footPositionOffset_.template segment<3>(3 * i);
prevfootPos_Target[i] = footPositionOffset_.template segment<3>(3 * i);
prevfootPos_Target2[i] = footPositionOffset_.template segment<3>(3 * i);
}
pi_[0] = 0.0;
pi_[1] = M_PI;
pi_[2] = M_PI;
pi_[3] = 0.0;
controlCounter = 0;
stopCounter = 1000;
baseFreq_ = 0.0;
historyUpdateCounter = 0;
scaledAction_ = actionOffset_;
jointVelHist_.setZero();
jointPosHist_.setZero();
historyBuffer_.setZero();
jointPositionTarget_ = jointNominalConfig_;
previousjointPositionTarget_ = jointPositionTarget_;
previousjointPositionTarget2_ = jointPositionTarget_;
command_.setZero();
}
~QuadrupedController() {}
void reset(GraphLoader<Dtype> *graph,
const Eigen::Matrix<double, 19, 1> &generalizedCoordinates,
const Eigen::Matrix<double, 18, 1> &generalizedVelocities) { // = init()
graph_ = graph;
if (history_dims_inv.dims() != 3) {
history_dims_inv.AddDim(1);
history_dims_inv.AddDim(nStack_);
history_dims_inv.AddDim(ObservationDim);
history_tf_tensor = tensorflow::Tensor(tensorflow::DataType::DT_FLOAT, history_dims_inv);
historyBuffer_.resize(ObservationDim, nStack_);
}
for (size_t i = 0; i < 4; i++) {
piD_[i] = 0.0;
footPos_Target[i] = footPositionOffset_.template segment<3>(3 * i);
prevfootPos_Target[i] = footPositionOffset_.template segment<3>(3 * i);
prevfootPos_Target2[i] = footPositionOffset_.template segment<3>(3 * i);
}
pi_[0] = 0.0;
pi_[1] = M_PI;
pi_[2] = M_PI;
pi_[3] = 0.0;
controlCounter = 0;
stopCounter = 1000;
baseFreq_ = 0.0;
historyUpdateCounter = 0;
scaledAction_ = actionOffset_;
jointVelHist_.setZero();
jointPosHist_.setZero();
historyBuffer_.setZero();
jointPositionTarget_ = jointNominalConfig_;
previousjointPositionTarget_ = jointPositionTarget_;
previousjointPositionTarget2_ = jointPositionTarget_;
observation_unscaled_.setZero();
state_unscaled_.setZero();
command_.setZero();
///dummy call for memory allocation
std::vector<tensorflow::Tensor> outputs;
graph_->run({std::make_pair("state", state_tf_tensor), std::make_pair("history", history_tf_tensor)},
{"policy/actionDist"},
{},
outputs);
/// fill in history buffer
updateHistory(generalizedCoordinates,
generalizedVelocities);
for (int i = 1; i < nStack_; i++) {
historyBuffer_.col(i) = historyBuffer_.col(0);
}
}
void updateAction(Action action_in) {
/// update buffer
for (size_t i = 0; i < 4; i++) {
prevfootPos_Target2[i] = prevfootPos_Target[i];
prevfootPos_Target[i] = footPos_Target[i];
}
previousjointPositionTarget2_ = previousjointPositionTarget_;
previousjointPositionTarget_ = jointPositionTarget_;
scaledAction_ = action_in.cwiseProduct(actionScale_) + actionOffset_;
/// update cpg
for (size_t j = 0; j < 4; j++) {
piD_[j] = scaledAction_[j] + baseFreq_;
pi_[j] += piD_[j] * decimation;
pi_[j] = anglemod(pi_[j]);
}
y_ << 0.0, e_g[2], -e_g[1];
y_.normalize();
x_ = y_.cross(e_g); // e_g cross y_;
x_.normalize();
for (size_t i = 0; i < 4; i++) {
double dh = 0.0;
if (pi_[i] > 0.0) {
double t = pi_[i] / M_PI_2;
if (t < 1.0) {
double t2 = t * t;
double t3 = t2 * t;
dh = (-2 * t3 + 3 * t2);
} else {
t = t - 1;
double t2 = t * t;
double t3 = t2 * t;
dh = (2 * t3 - 3 * t2 + 1.0);
}
dh *= clearance_[i];
}
footPos_Target[i][0] = footPositionOffset_.tail(12)[3 * i];
footPos_Target[i][1] = footPositionOffset_.tail(12)[3 * i + 1];
footPos_Target[i][2] = 0.0;
footPos_Target[i] += e_g * (footPositionOffset_.tail(12)[3 * i + 2] + dh);
// footPos_Target[i] += e_g * scaledAction_.tail(12)[3 * i + 2];
// footPos_Target[i] += x_ * scaledAction_.tail(12)[3 * i];
// footPos_Target[i] += y_ * scaledAction_.tail(12)[3 * i + 1];
Eigen::Vector3d target;
Eigen::Vector3d sol;
target = footPos_Target[i];
//
IK_.solveIK(sol, target, i);
jointPositionTarget_.segment<3>(3 * i) = sol;
jointPositionTarget_(3 * i) += scaledAction_.tail(12)[3 * i];;
jointPositionTarget_(3 * i + 1) += scaledAction_.tail(12)[3 * i + 1];
jointPositionTarget_(3 * i + 2) += scaledAction_.tail(12)[3 * i + 2];;
}
}
void getDesJointPos(Eigen::Matrix<double, 12, 1> &output,
const Eigen::Matrix<double, 19, 1> &generalizedCoordinates,
const Eigen::Matrix<double, 18, 1> &generalizedVelocities,
double headingVel, double lateralVel, double yawrate) {
double norm = std::sqrt(headingVel * headingVel + lateralVel * lateralVel + yawrate * yawrate);
if (norm < 0.05) {
command_.setZero();
} else {
double linvelNorm = std::sqrt(headingVel * headingVel + lateralVel * lateralVel);
command_.setZero();
if (linvelNorm > 0.2) {
double command_dir = std::atan2(lateralVel, headingVel);
command_[0] = std::cos(command_dir);
command_[1] = std::sin(command_dir);
}
command_[2] = std::max(std::min(yawrate, 0.8), -0.8);
}
if (command_.norm() > 0.1 || generalizedVelocities.head(2).norm() > 0.3 || e_g[2] < 0.5) {
if (stopCounter > 1200) { // While standin -> reset phase to react faster (unsmooth)
pi_[0] = 0.0;
pi_[1] = M_PI;
pi_[2] = M_PI;
pi_[3] = 0.0;
}
stopCounter = 0;
} else {
stopCounter++;
}
if (historyUpdateCounter % ObservationStride_ == 0) {
updateHistory(generalizedCoordinates,
generalizedVelocities);
historyUpdateCounter = 0;
}
if (controlCounter % decimation == 0) { // 8: 50 Hz
// FSM
if (stopCounter > 75) {
bool check = true;
for (int i = 0; i < 4; i++) {// Hack for nice looking stop
if ((pi_[i] > -0.1 * M_PI) && (pi_[i] < 0.5 * M_PI)) check = false;
}
if (check || baseFreq_ < 1.3 * freqScale_) {
// baseFreq_ = std::max(baseFreq_ - 0.05 * freqScale_, 0.0);
baseFreq_ = 0.0;
}
} else {
// baseFreq_ = std::min(baseFreq_ + 0.05 * freqScale_, 1.3 * freqScale_);
baseFreq_ = 1.3 * freqScale_;
}
/// Get state
conversion_GeneralizedState2LearningState(state_,
generalizedCoordinates,
generalizedVelocities);
Eigen::Matrix<Dtype, actionDimension, 1> action_f_;
std::memcpy(state_tf_tensor.template flat<Dtype>().data(),
state_.data(),
sizeof(Dtype) * stateDimension);
std::memcpy(history_tf_tensor.template flat<Dtype>().data(),
historyBuffer_.data(),
sizeof(Dtype) * history_tf_tensor.NumElements());
std::vector<tensorflow::Tensor> outputs;
graph_->run({std::make_pair("state", state_tf_tensor), std::make_pair("history", history_tf_tensor)},
{"policy/actionDist"},
{},
outputs);
std::memcpy(action_f_.data(),
outputs[0].template flat<Dtype>().data(),
sizeof(Dtype) * actionDimension);
action_ = action_f_.template cast<double>();
// std::cout << action_ << std::endl;
/// update action
updateAction(action_);
controlCounter = 0;
}
// for (size_t i = 0; i < 4; i++) {
// Eigen::Vector3d target = (controlCounter + 1) * footPos_Target[i];
// target += (decimation - 1 - controlCounter) * prevfootPos_Target[i];
// target *= 0.125;
// Eigen::Vector3d sol;
// IK_.solveIK(sol, target, i);
// jointPositionTarget_.segment<3>(3 * i) = sol;
// }
output = jointPositionTarget_;
tempHist_ = jointVelHist_;
jointVelHist_.head(jointHistoryLength * 12 - 12) = tempHist_.tail(jointHistoryLength * 12 - 12);
jointVelHist_.tail(12) = generalizedVelocities.tail(12).template cast<Dtype>();
tempHist_ = jointPosHist_;
jointPosHist_.head(jointHistoryLength * 12 - 12) = tempHist_.tail(jointHistoryLength * 12 - 12);
jointPosHist_.tail(12) = (jointPositionTarget_ - generalizedCoordinates.tail(12)).template cast<Dtype>();
controlCounter++;
historyUpdateCounter++;
};
void updateHistory(const VectorXd &q,
const VectorXd &u) {
Observation observation_scaled;
Quaternion quat = q.template segment<4>(3);
RotationMatrix R_b = quatToRotMat(quat);
e_g = R_b.row(2).transpose();
/// velocity in body coordinate
LinearVelocity bodyVel = R_b.transpose() * u.template segment<3>(0);
AngularVelocity bodyAngVel = u.template segment<3>(3);
VectorXd jointVel = u.template segment<12>(6);
observation_unscaled_[0] = command_[0];
observation_unscaled_[1] = command_[1];
observation_unscaled_[2] = command_[2];
observation_unscaled_.template segment<3>(3) = e_g.template cast<Dtype>();;
observation_unscaled_.template segment<3>(6) = bodyVel.template cast<Dtype>();
observation_unscaled_.template segment<3>(9) = bodyAngVel.template cast<Dtype>();
observation_unscaled_.template segment<12>(12) = q.tail(12).
template cast<Dtype>(); /// position
observation_unscaled_.template segment<12>(24) = jointVel.template cast<Dtype>();
observation_unscaled_.template segment<12>(36) = (jointPositionTarget_ - q.tail(12)).template cast<Dtype>();
for (size_t i = 0; i < 4; i++) {
observation_unscaled_[48 + 2 * i] = std::sin(pi_[i]);
observation_unscaled_[49 + 2 * i] = std::cos(pi_[i]);
observation_unscaled_[56 + i] = piD_[i];
}
observation_scaled = (observation_unscaled_ - observationOffset_).cwiseProduct(observationScale_);
Eigen::Matrix<Dtype, ObservationDim, -1> temp;
temp = historyBuffer_;
historyBuffer_.block(0, 1, ObservationDim, nStack_ - 1) = temp.block(0, 0, ObservationDim, nStack_ - 1);
historyBuffer_.col(0) = observation_scaled.template cast<Dtype>();
}
static inline void QuattoEuler(const Quaternion &q, double &roll, double &pitch, double &yaw) {
double ysqr = q[2] * q[2];
// roll (x-axis rotation)
double t0 = +2.0 * (q[0] * q[1] + q[2] * q[3]);
double t1 = +1.0 - 2.0 * (q[1] * q[1] + ysqr);
roll = std::atan2(t0, t1);
// pitch (y-axis rotation)
double t2 = +2.0 * (q[0] * q[2] - q[3] * q[1]);
t2 = t2 > 1.0 ? 1.0 : t2;
t2 = t2 < -1.0 ? -1.0 : t2;
pitch = std::asin(t2);
// yaw (z-axis rotation)
double t3 = +2.0 * (q[0] * q[3] + q[1] * q[2]);
double t4 = +1.0 - 2.0 * (ysqr + q[3] * q[3]);
yaw = std::atan2(t3, t4);
}
private:
inline double anglediff(double target, double source) {
//https://stackoverflow.com/questions/1878907/the-smallest-difference-between-2-angles
return anglemod(target - source);
}
inline double anglemod(double a) {
return wrapAngle((a + M_PI)) - M_PI;
}
inline double wrapAngle(double a) {
double twopi = 2.0 * M_PI;
return a - twopi * fastfloor(a / twopi);
}
inline int fastfloor(double a) {
int i = int(a);
if (i > a) i--;
return i;
}
inline void conversion_GeneralizedState2LearningState(State &state,
const VectorXd &q,
const VectorXd &u) {
Quaternion quat = q.template segment<4>(3);
RotationMatrix R_b = quatToRotMat(quat);
e_g = R_b.row(2).transpose();
/// velocity in body coordinate
LinearVelocity bodyVel = R_b.transpose() * u.template segment<3>(0);
AngularVelocity bodyAngVel = u.template segment<3>(3);
VectorXd jointVel = u.template segment<12>(6);
/// command slots
state_unscaled_[0] = command_[0];
state_unscaled_[1] = command_[1];
state_unscaled_[2] = command_[2];
/// gravity vector
state_unscaled_.template segment<3>(3) = e_g.template cast<Dtype>();
/// velocities
state_unscaled_.template segment<3>(6) = bodyVel.template cast<Dtype>();
state_unscaled_.template segment<3>(9) = bodyAngVel.template cast<Dtype>();
state_unscaled_.template segment<12>(12) = q.template segment<12>(7).
template cast<Dtype>();
state_unscaled_.template segment<12>(24) = jointVel.template cast<Dtype>();
state_unscaled_.template segment<12>(36) = jointPosHist_.template segment<12>((jointHistoryLength - 1) * 12);
for (size_t i = 0; i < 4; i++) {
state_unscaled_[48 + i] = piD_[i];
}
int pos = 52;
for (size_t i = 0; i < 4; i++) {
state_unscaled_[pos + 2 * i] = std::sin(pi_[i]);
state_unscaled_[pos + 1 + 2 * i] = std::cos(pi_[i]);
}
pos += 8;
state_unscaled_.template segment<12>(pos) =
jointPosHist_.template segment<12>((jointHistoryLength - 4) * 12);
pos += 12;
state_unscaled_.template segment<12>(pos) =
jointPosHist_.template segment<12>((jointHistoryLength - 9) * 12);
pos += 12;
state_unscaled_.template segment<12>(pos) =
jointVelHist_.template segment<12>((jointHistoryLength - 4) * 12);
pos += 12;
state_unscaled_.template segment<12>(pos) =
jointVelHist_.template segment<12>((jointHistoryLength - 9) * 12);
pos += 12;
state_unscaled_.template segment<12>(pos) = previousjointPositionTarget_.template cast<Dtype>();
pos += 12;
state_unscaled_.template segment<12>(pos) = previousjointPositionTarget2_.template cast<Dtype>();
pos += 12;
state_unscaled_[pos] = baseFreq_;
state = (state_unscaled_ - stateOffset_).cwiseProduct(stateScale_);
}
inline RotationMatrix quatToRotMat(Quaternion &q) {
RotationMatrix R;
R << q(0) * q(0) + q(1) * q(1) - q(2) * q(2) - q(3) * q(3), 2 * q(1) * q(2) - 2 * q(0) * q(3), 2 * q(0) * q(2)
+ 2 * q(1) * q(3),
2 * q(0) * q(3) + 2 * q(1) * q(2), q(0) * q(0) - q(1) * q(1) + q(2) * q(2) - q(3) * q(3), 2 * q(2) * q(3)
- 2 * q(0) * q(1),
2 * q(1) * q(3) - 2 * q(0) * q(2), 2 * q(0) * q(1) + 2 * q(2) * q(3), q(0) * q(0) - q(1) * q(1) - q(2) * q(2)
+ q(3) * q(3);
return R;
}
template<typename T>
int sgn(T val) {
return (T(0) < val) - (val < T(0));
}
Eigen::Matrix<double, 12, 1> jointNominalConfig_;
State stateOffset_;
State stateScale_;
Action actionOffset_;
Action actionScale_;
Action scaledAction_;
Eigen::Matrix<double, 3, 1> e_g;
Eigen::Matrix<double, 3, 1> x_, y_;
Eigen::Matrix<Dtype, 3, 1> command_;
Eigen::Matrix<Dtype, 12 * jointHistoryLength, 1> jointVelHist_, jointPosHist_, tempHist_;
Observation observationScale_;
Observation observationOffset_;
std::vector<Eigen::Matrix<double, 3, 1>> footPos_Target;
std::vector<Eigen::Matrix<double, 3, 1>> prevfootPos_Target;
std::vector<Eigen::Matrix<double, 3, 1>> prevfootPos_Target2;
Eigen::Matrix<double, 12, 1> footPositionOffset_;
Eigen::Matrix<float, ObservationDim, -1> historyBuffer_;
double h0_ = -0.55;
double clearance_[4];
double freqScale_ = 0.0025 * 2.0 * M_PI;
double baseFreq_ = 0.0;
unsigned long int controlCounter = 0;
unsigned long int stopCounter = 0;
unsigned long int historyUpdateCounter = 0;
unsigned long int decimation = 8;
InverseKinematics IK_;
tensorflow::TensorShape state_dims_inv;
tensorflow::Tensor state_tf_tensor;
tensorflow::TensorShape history_dims_inv;
tensorflow::Tensor history_tf_tensor;
GraphLoader<float> *graph_;
public:
double pi_[4];
double piD_[4];
Action action_;
State state_;
Observation observation_unscaled_;
State state_unscaled_;
Eigen::Matrix<double, 12, 1> jointPositionTarget_;
Eigen::Matrix<double, 12, 1> previousjointPositionTarget_;
Eigen::Matrix<double, 12, 1> previousjointPositionTarget2_;
int ObservationStride_ = 8;
int nStack_ = 100;
};
}
#endif //RAI_QUADRUPEDCONTROLLER_HPP
| [
"[email protected]"
] | |
deef0a636bb23f51076b93f2a5f0a46138902010 | 4a6aebfe469914a52001400d7c05717207f82133 | /Scrabble.cpp | 13b8b496185fa350d884283db71627f47a66def4 | [] | no_license | jonathan-elize/ScrabbleBoard | bf77e028cd3e7b8ac983d5f5b358039b4eede717 | 4ffe8e3453c76d1e5536bea5036d98993f34a3ea | refs/heads/master | 2021-07-22T03:52:25.188676 | 2017-10-27T20:58:54 | 2017-10-27T20:58:54 | 108,594,749 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,622 | cpp | //-| --------------------------------------------------------------------------
//-| File name: Scrabble.cpp
//-| Assign ID: PROG2
//-| Due Date: September 16, 2017
//-|
//-| Purpose: Display gameboard based on data file
//-|
//-| Author: (c) 2017, jelize Jonathan Elize
//-|
//-| --------------------------------------------------------------------------
#include "ScrabbleFunctions.h"
int main(){
//----------------------------------
//Declare and Initialize variables
//----------------------------------
const int BOARD_CAP = 9; //max width and height of the board
ifstream inF; //file handler to make board from
string filename; //name of the file to be used
int boardSize; //size of the board from the file
char board[BOARD_CAP][BOARD_CAP]; //2d array corresponding to the board
//intitialize each board space to ' '
for(int i = 0; i < BOARD_CAP; i++)
{
for(int j = 0; j < BOARD_CAP; j++)
board[i][j] = ' ';
}
//---------------------
//prompt for file name
//---------------------
cout << "Enter name of input file: ";
cin >> filename;
//---------------------
//open file for input
//---------------------
inF.open(filename.c_str());
//If file failes
if(!inF)
cout << "FATAL ERROR: Can not open file '" << filename << "'" << endl;
//else
else
{
//-----------------------------
//prompt for boardSize
//-----------------------------
cout << "Enter board size [1-9]: ";
cin >> boardSize;
//-----------------------------
//loadBoard
//-----------------------------
loadBoard(board, boardSize, inF);
//close file
inF.close();
//-----------------------------------
//Display number of tiles on board
//-----------------------------------
cout << numTiles(board, boardSize) << " TILES on Scrabble Board"
<< endl;
//---------------------------------------------
//output boardSize x boardSize SCRABBLE BOARD
//---------------------------------------------
cout << boardSize << " x " << boardSize << " SCRABBLE BOARD" << endl
<< endl;
showBoard(board, boardSize);
//----------------------
//Display Specs
//----------------------
showWords(board, boardSize);
}
//---------------------
//Display Copyright
//---------------------
cout << endl << "(c) 2017, jelize Jonathan Elize" << endl << endl;
return 0;
}
| [
"[email protected]"
] | |
83916b8d2be0d97d432fb5fb255a39970e8b2bfc | 5504604c135cc7d171c6cfedb055416fd24e98ab | /Snake from NOKIA 3310/TTT_Menu.cpp | 6e16ce3146f2fd0cc4081efbb4c3d81f39554354 | [] | no_license | hakerg/Snake-from-NOKIA-3310 | 5732c5bada6f74b795be39b2d34f2effc8afc388 | 384e9e2ea1db6a1ea49ddf7bede35e900c604f9b | refs/heads/master | 2020-03-22T05:53:12.468756 | 2018-07-03T20:40:23 | 2018-07-03T20:40:23 | 139,597,010 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 406 | cpp | #include "TTT_Menu.h"
#include "Scene_Manager.h"
#include "TTT_New_Select.h"
#include "TTT_Gameplay.h"
TTT_Menu::TTT_Menu() : Menu({ 0 }, { "Nowa gra", "Demo" })
{
}
TTT_Menu::~TTT_Menu()
{
}
void TTT_Menu::item_selected(int id)
{
switch (id)
{
case 0:
Scene_Manager::go_to_scene(new TTT_New_Select);
break;
case 1:
Scene_Manager::go_to_scene(new TTT_Gameplay(false, false));
break;
}
} | [
"[email protected]"
] | |
b6b6f3c8d997005fe16894cf66792289ccbca038 | aa07db86d2abb542f04f3652dbff85c2d3aecdbd | /Chimera/AlertSystem.h | bfd3531f384994717daaccdb1fcdaaf5c924ff70 | [] | no_license | KaufmanLabJILA/Chimera-Control-Master | 3604ed5be843388e113ffe47aee48b4d41c2c0bf | 8ae17f4f562ca899838f6fbea71fc431981efe98 | refs/heads/master | 2023-08-21T10:24:30.614463 | 2022-01-18T22:42:35 | 2022-01-18T22:42:35 | 105,817,176 | 6 | 3 | null | 2019-08-15T16:57:10 | 2017-10-04T20:52:16 | C++ | UTF-8 | C++ | false | false | 1,280 | h | #pragma once
#include "Control.h"
#include <Mmsystem.h>
#include <mciapi.h>
#include "cameraPositions.h"
#pragma comment(lib, "Winmm.lib")
class AlertSystem
{
public:
AlertSystem() : alertMessageID{ 0 }
{
// load the music!
mciSendString( cstr( str( "open \"" ) + MUSIC_LOCATION + "\" type mpegvideo alias mp3" ), NULL, 0, NULL );
}
~AlertSystem()
{
mciSendString( "close mp3", NULL, 0, NULL );
}
void initialize( cameraPositions& positions, CWnd* parent, bool isTriggerModeSensitive, int& id,
cToolTips& tooltips );
void alertMainThread( int level );
void soundAlert();
void rearrange( std::string cameraMode, std::string triggerMode, int width, int height, fontMap fonts );
UINT getAlertThreshold();
UINT getAlertMessageID();
void setAlertThreshold();
bool alertsAreToBeUsed();
bool soundIsToBePlayed();
void playSound();
void stopSound();
bool wantsAutoPause( );
private:
Control<CStatic> title;
Control<CButton> alertsActiveCheckBox;
Control<CStatic> alertThresholdText;
Control<CEdit> alertThresholdEdit;
Control<CButton> soundAtFinshCheck;
Control<CButton> autoPauseAtAlert;
int alertThreshold;
bool useAlerts;
bool autoPause;
UINT alertMessageID = 0;
};
| [
"[email protected]"
] | |
e5bdd92e7966080572b7fee3ae33d01bec2dae1b | c3c96be8ae1142460034c2aea83dff5f5bb8cb98 | /11742.cpp | 5ebffbf0e85959abb6e28b803c5eb34100699020 | [] | no_license | shakilaust/Uva-Solve | 332016f01499e7c06e467efe6fb9422c3b8bd2de | a9bd40fe9e44547f920538fb2f142bb927216e8c | refs/heads/master | 2020-04-06T07:03:33.488459 | 2018-08-15T11:24:34 | 2018-08-15T11:24:34 | 15,436,062 | 5 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 3,627 | cpp | //BISMILLAHIRRAHMANIRRAHIM
/*
manus tar shopner soman boro
all my suceesses are dedicated to my parents
The true test of a man's character is what he does when no one is watching.
Author :: Shakil Ahmed
.............AUST_CSE27.........
prob ::
Type ::
verdict::
*/
#include <bits/stdc++.h>
#define pb push_back
#define mp make_pair
// Macro
#define eps 1e-9
#define pi acos(-1.0)
#define ff first
#define ss second
#define re return
#define QI queue<int>
#define SI stack<int>
#define SZ(x) ((int) (x).size())
#define all(x) (x).begin(), (x).end()
#define sq(a) ((a)*(a))
#define distance(a,b) (sq(a.x-b.x) + sq(a.y-b.y))
#define iseq(a,b) (fabs(a-b)<eps)
#define eq(a,b) iseq(a,b)
#define ms(a,b) memset((a),(b),sizeof(a))
#define G() getchar()
#define MAX3(a,b,c) max(a,max(b,c))
#define II ( { int a ; read(a) ; a; } )
#define LL ( { Long a ; read(a) ; a; } )
#define DD ({double a; scanf("%lf", &a); a;})
double const EPS=3e-8;
using namespace std;
#define FI freopen ("input.txt", "r", stdin)
#define FO freopen ("output.txt", "w", stdout)
typedef long long Long;
typedef long long int64;
typedef unsigned long long ull;
typedef vector<int> vi ;
typedef set<int> si;
typedef vector<Long>vl;
typedef pair<int,int>pii;
typedef pair<string,int>psi;
typedef pair<Long,Long>pll;
typedef pair<double,double>pdd;
typedef vector<pii> vpii;
// For loop
#define forab(i, a, b) for (__typeof (b) i = (a) ; i <= b ; ++i)
#define rep(i, n) forab (i, 0, (n) - 1)
#define For(i, n) forab (i, 1, n)
#define rofba(i, a, b) for (__typeof (b)i = (b) ; i >= a ; --i)
#define per(i, n) rofba (i, 0, (n) - 1)
#define rof(i, n) rofba (i, 1, n)
#define forstl(i, s) for (__typeof ((s).end ()) i = (s).begin (); i != (s).end (); ++i)
template< class T > T gcd(T a, T b) { return (b != 0 ? gcd<T>(b, a%b) : a); }
template< class T > T lcm(T a, T b) { return (a / gcd<T>(a, b) * b); }
//Fast Reader
template<class T>inline bool read(T &x){int c=getchar();int sgn=1;while(~c&&c<'0'||c>'9'){if(c=='-')sgn=-1;c=getchar();}for(x=0;~c&&'0'<=c&&c<='9';c=getchar())x=x*10+c-'0'; x*=sgn; return ~c;}
//int dx[]={1,0,-1,0};int dy[]={0,1,0,-1}; //4 Direction
//int dx[]={1,1,0,-1,-1,-1,0,1};int dy[]={0,1,1,1,0,-1,-1,-1};//8 direction
//int dx[]={2,1,-1,-2,-2,-1,1,2};int dy[]={1,2,2,1,-1,-2,-2,-1};//Knight Direction
//int dx[]={2,1,-1,-2,-1,1};int dy[]={0,1,1,0,-1,-1}; //Hexagonal Direction
/* ************************************** My code start here ****************************************** */
int permu[ 10 ] , n , inp[25][3] , m , pos[ 10 ];
int main()
{
// I will always use scanf and printf
// May be i won't be a good programmer but i will be a good human being
while( scanf("%d %d",&n,&m) == 2 )
{
if( n == 0 && m == 0 ) break ;
rep ( i , m ) rep( j , 3 ) inp[i][j] = II ;
rep( i , n ) permu[i] = i ;
int ans = 0 ;
do
{
bool ok = 1 ;
rep( i , n ) pos[ permu[i] ] = i ;
for ( int i = 0 ; i < m && ok ; i++ )
{
int pos1 = pos[ inp[i][0] ] ;
int pos2 = pos[ inp[i][1] ];
if( inp[i][2] > 0 )
{
if( abs( pos1 - pos2 ) > inp[i][2] ) // they must need to seat between at least inp[i][2]
ok = 0 ;
}
if( inp[i][2] < 0 )
{
if( abs( pos1 - pos2 ) < -inp[i][2] ) ok = 0 ;
}
}
ans += ok ;
}while( next_permutation( permu , permu + n ) );
printf("%d\n",ans);
}
return 0;
}
| [
"[email protected]"
] | |
010b2a206cf4438d16b9ec7cb4224892be35a8ac | f753c6173870b72768fe106715b5cbe8496b9a89 | /private/src/avb_streamhandler/IasAvbClockDomain.cpp | 274f972846f9b20b773cb2c5a5d8d2d7a6661fff | [
"BSL-1.0",
"BSD-3-Clause"
] | permissive | intel/AVBStreamHandler | 3615b97a799a544b2b3847ad9f5f69902fbcab6e | 45558f68e84cc85fa38c8314a513b876090943bd | refs/heads/master | 2023-09-02T13:13:49.643816 | 2022-08-04T22:47:26 | 2022-08-04T22:47:26 | 145,041,581 | 17 | 24 | NOASSERTION | 2019-04-11T23:04:57 | 2018-08-16T21:38:32 | C++ | UTF-8 | C++ | false | false | 7,885 | cpp | /*
* Copyright (C) 2018 Intel Corporation. All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
/**
* @file IasAvbClockDomain.cpp
* @brief The implementation of the IasAvbClockDomain class.
* @date 2013
*/
#include "avb_streamhandler/IasAvbClockDomain.hpp"
#include "avb_streamhandler/IasAvbStreamHandlerEnvironment.hpp"
#include <cmath>
#include <dlt_cpp_extension.hpp>
namespace IasMediaTransportAvb {
static const std::string cClassName = "IasAvbClockDomain::";
#define LOG_PREFIX cClassName + __func__ + "(" + std::to_string(__LINE__) + "):"
/*
* Constructor.
*/
IasAvbClockDomain::IasAvbClockDomain(DltContext &dltContext, IasAvbClockDomainType type)
: mType(type)
, mTimeConstant(0.0)
, mAvgCallsPerSec(1)
, mRateRatio(1.0)
, mCompensation(1.0)
, mEventCount(0u)
, mEventRate(0u)
, mEventTimeStamp(0u)
, mRateRatioSlow(1.0)
, mRateRatioFast(1.0)
, mCoeffSlowLocked(0.0)
, mCoeffSlowUnlocked(0.0)
, mCoeffFastLocked(0.0)
, mCoeffFastUnlocked(0.0)
, mThresholdSlowLow(0.0)
, mThresholdSlowHigh(0.0)
, mThresholdFastLow(0.0)
, mThresholdFastHigh(0.0)
, mInitialValue(1.0)
, mDerivationFactorUnlock(1.0)
, mDerivationFactorLongTerm(1.0)
, mLockState(eIasAvbLockStateInit)
, mLock()
, mDebugCount(0u)
, mDebugUnlockCount(0u)
, mDebugLockedPercentage(1.0)
, mDebugMinRatio(1.0/0.0)
, mDebugMaxRatio(0.0)
, mDebugOver(0u)
, mDebugUnder(0u)
, mDebugIn(0u)
, mClient(NULL)
, mDebugLogInterval(5u)
, mResetRequest(false)
, mClockId(-1)
, mLog(&dltContext)
{
(void) IasAvbStreamHandlerEnvironment::getConfigValue(IasRegKeys::cDebugClkDomainIntvl, mDebugLogInterval);
}
/*
* Destructor.
*/
IasAvbClockDomain::~IasAvbClockDomain()
{
// do nothing
}
void IasAvbClockDomain::updateRateRatio(double newRatio)
{
// sanity check, needed for ptp epoch changes
if ((newRatio < 0.0) || (newRatio > 10.0))
{
return;
}
const bool locked1high = (newRatio < (mThresholdFastHigh * mRateRatioFast));
const bool locked1low = (newRatio > (mThresholdFastLow * mRateRatioFast));
const bool locked1 = locked1high && locked1low;
if (eIasAvbLockStateLocked == mLockState)
{
smooth(mRateRatioSlow, newRatio, mCoeffSlowLocked);
smooth(mRateRatioFast, newRatio, mCoeffFastLocked);
}
else
{
smooth(mRateRatioSlow, newRatio, mCoeffSlowUnlocked);
smooth(mRateRatioFast, newRatio, mCoeffFastUnlocked);
}
mDebugMinRatio = newRatio < mDebugMinRatio ? newRatio : mDebugMinRatio;
mDebugMaxRatio = newRatio > mDebugMaxRatio ? newRatio : mDebugMaxRatio;
smooth( mDebugLockedPercentage, locked1 ? 1.0 : 0.0, mCoeffFastUnlocked );
mDebugOver += locked1high ? 0 : 1;
mDebugUnder += locked1low ? 0 : 1;
mDebugIn += locked1 ? 1 : 0;
const double rateRatioMax = mThresholdSlowHigh * mRateRatioSlow;
const double rateRatioMin = mThresholdSlowLow * mRateRatioSlow;
const bool locked2 = (mRateRatioFast < rateRatioMax) && (mRateRatioFast > rateRatioMin);
if (mDebugCount++ > (mAvgCallsPerSec * mDebugLogInterval))
{
mDebugCount = 0u;
DLT_LOG_CXX(*mLog, DLT_LOG_DEBUG, LOG_PREFIX, "clock[", int32_t(mType),
"/", uint64_t(this), "]:", newRatio, mRateRatioFast, mRateRatioSlow, (locked1 ? "1" : "-"),
(locked2 ? "2" : "-"), (mLockState == eIasAvbLockStateLocked ? "L" : "-"), mDebugUnlockCount);
DLT_LOG_CXX(*mLog, DLT_LOG_VERBOSE, LOG_PREFIX, "clock[", int32_t(mType),
"/", uint64_t(this), "]: max", mDebugMaxRatio, "min", mDebugMinRatio, "locked1", mDebugLockedPercentage, mDebugOver,
"/", mDebugIn, "/", mDebugUnder, float( mDebugOver ) / float( mDebugUnder ));
mDebugMinRatio = 1.0/0.0;
mDebugMaxRatio = 0.0;
}
if (NULL != mClient)
{
mClient->notifyUpdateRatio(this);
}
switch (mLockState)
{
case eIasAvbLockStateInit:
mRateRatioSlow = mInitialValue;
mRateRatioFast = mInitialValue;
// fall-through
case eIasAvbLockStateUnlocked:
mLockState = eIasAvbLockStateLocking;
// fall-through
case eIasAvbLockStateLocking:
if (locked1 && locked2)
{
mLockState = eIasAvbLockStateLocked;
lockStateChanged();
}
break;
case eIasAvbLockStateLocked:
if (!locked2)
{
mLockState = eIasAvbLockStateUnlocked;
lockStateChanged();
mDebugUnlockCount++;
}
break;
default:
break;
}
mRateRatio = mRateRatioFast > rateRatioMax ? rateRatioMax : (mRateRatioFast < rateRatioMin ? rateRatioMin : mRateRatioFast);
mRateRatio *= mCompensation;
}
IasAvbProcessingResult IasAvbClockDomain::setDriftCompensation(int32_t val)
{
IasAvbProcessingResult ret = eIasAvbProcOK;
/*
* The following is a simple linear approximation of pow(mRatioBendMax, -relFillLevel) within the required range
*/
if ((val >= 0) && (val <= 1000000))
{
mCompensation = 1.0 / (1.0 + (double(val) * 1e-6));
}
else if ((val < 0) && (val >= -1000000))
{
mCompensation = 1.0 + (double(-val) * 1e-6);
}
else
{
// relFillLevel out of range
ret = eIasAvbProcInvalidParam;
}
return ret;
}
void IasAvbClockDomain::lockStateChanged()
{
if (NULL != mClient)
{
mClient->notifyUpdateLockState(this);
}
else
{
/**
* @log Change in the clock domain lock state but the client is null, unable to notify.
*/
DLT_LOG_CXX(*mLog, DLT_LOG_VERBOSE, LOG_PREFIX, "no client");
}
}
void IasAvbClockDomain::setInitialValue(double initVal)
{
if (initVal >= 0.0)
{
mInitialValue = initVal;
}
}
void IasAvbClockDomain::setFilter(double timeConstant, uint32_t avgCallsPerSec)
{
if (timeConstant >= 0.0)
{
mTimeConstant = timeConstant;
mAvgCallsPerSec = avgCallsPerSec;
const double tc = timeConstant * double(avgCallsPerSec);
mCoeffFastLocked = calculateCoefficient(tc);
mCoeffFastUnlocked = calculateCoefficient(tc * mDerivationFactorUnlock);
mCoeffSlowLocked = calculateCoefficient(tc * mDerivationFactorLongTerm);
mCoeffSlowUnlocked = calculateCoefficient(tc * mDerivationFactorLongTerm * mDerivationFactorUnlock);
DLT_LOG_CXX(*mLog, DLT_LOG_DEBUG, LOG_PREFIX, "[IasAvbClockDomain::setFilter] tc=", mTimeConstant,
mAvgCallsPerSec, "call/sec (", mCoeffFastLocked,
"/", mCoeffFastUnlocked, "/", mCoeffSlowLocked,
"/", mCoeffSlowUnlocked);
if (mLockState > eIasAvbLockStateUnlocked)
{
mLockState = eIasAvbLockStateUnlocked;
lockStateChanged();
}
}
}
void IasAvbClockDomain::setDerivationFactors(double factorLongTerm, double factorUnlock)
{
mDerivationFactorLongTerm = factorLongTerm;
mDerivationFactorUnlock = factorUnlock;
setFilter(mTimeConstant, mAvgCallsPerSec);
}
void IasAvbClockDomain::setLockThreshold1( uint32_t ppm )
{
if (ppm > 0u)
{
mThresholdFastHigh = 1.0 + (1e-6 * double(ppm));
mThresholdFastLow = 1.0 / mThresholdFastHigh;
}
}
void IasAvbClockDomain::setLockThreshold2(uint32_t ppm)
{
if (ppm > 0u)
{
mThresholdSlowHigh = 1.0 + (1e-6 * double(ppm));
mThresholdSlowLow = 1.0 / mThresholdSlowHigh;
}
}
double IasAvbClockDomain::calculateCoefficient(double timeConstant)
{
return (0.0 == timeConstant) ? 0.0 : (std::exp(-1.0 / timeConstant));
}
IasAvbProcessingResult IasAvbClockDomain::registerClient(IasAvbClockDomainClientInterface * const client)
{
IasAvbProcessingResult ret = eIasAvbProcInvalidParam;
if (NULL != client)
{
if (NULL != mClient)
{
ret = eIasAvbProcAlreadyInUse;
}
else
{
ret = eIasAvbProcOK;
mClient = client;
}
}
return ret;
}
IasAvbProcessingResult IasAvbClockDomain::unregisterClient(IasAvbClockDomainClientInterface * const client)
{
IasAvbProcessingResult ret = eIasAvbProcInvalidParam;
if (client == mClient)
{
ret = eIasAvbProcOK;
mClient = NULL;
}
return ret;
}
} // namespace IasMediaTransportAvb
| [
"[email protected]"
] | |
32d6f31bf94eb4f4ac23fab93e7b985097b6d724 | 03af5552b327510cd100fc2f5aa0ca9f867a40a4 | /log_test.cpp | 3423616125985f91d1384315462837bb71285264 | [] | no_license | ICKelin/clog | 424b8fc5daff750f071aae3ae63fb764ed279b41 | 7600864382819f07319dbb9991286a425fd025fc | refs/heads/master | 2021-01-19T17:28:14.454224 | 2017-04-11T16:05:34 | 2017-04-11T16:05:34 | 88,324,831 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,468 | cpp | #ifdef _WIN32
#include <windows.h>
#else
#include <stdio.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/syscall.h>
#include "printlog.h"
#endif
#ifdef _WIN32
DWORD WINAPI thread_func(LPVOID param) {
#else
void *thread_func(void *args) {
#endif
for (int i = 0; i < 100; i++) {
_printlog(__FILE__, __LINE__, PRIORITY_UNKNOWN, "test tid %d",i);
}
return 0;
}
int main() {
initlogs("", 1000, "./", 1, 1024);
_printlog(__FILE__, __LINE__, PRIORITY_UNKNOWN, "test");
_printlog(__FILE__, __LINE__, PRIORITY_NOTSET, "test");
_printlog(__FILE__, __LINE__, PRIORITY_TRACE, "test");
_printlog(__FILE__, __LINE__, PRIORITY_DEBUG, "test");
_printlog(__FILE__, __LINE__, PRIORITY_INFO, "test");
_printlog(__FILE__, __LINE__, PRIORITY_NOTICE, "test");
_printlog(__FILE__, __LINE__, PRIORITY_WARN, "test");
_printlog(__FILE__, __LINE__, PRIORITY_ERROR, "test");
_printlog(__FILE__, __LINE__, PRIORITY_CRIT, "test");
_printlog(__FILE__, __LINE__, PRIORITY_ALERT, "test");
_printlog(__FILE__, __LINE__, PRIORITY_FATAL, "test");
// 多线程测试
#ifdef _WIN32
HANDLE tids[4];
#else
pthread_t tids[4];
#endif
for (int i = 0; i < 4; i++) {
#ifdef _WIN32
tids[i] = CreateThread(NULL, 0, thread_func, NULL, 0, NULL);
#else
pthread_create(&tids[i], NULL, thread_func, NULL);
#endif
}
for (int i = 0; i < 4; i++) {
#ifdef _WIN32
while(WaitForSingleObject(handle, INFINITE) != WAIT_OBJECT_0);
#else
pthread_join(tids[i], NULL);
#endif
}
}
| [
"[email protected]"
] | |
93482662ca763e7f1d7e5131a36e03717eaca188 | 82cf52765e312da0860a601076addbbccabfd0ba | /Demo2.ino | cc35040400763b1490c033b2c3a824c3f7e884d3 | [] | no_license | Seed-lab-team-8/Demo2Final | 5ba0e727907a616b0c78928e16ad356d4e15f3b7 | 3c979072d35460209f0709e9bfa20aa5258d5424 | refs/heads/main | 2023-04-21T08:18:41.426619 | 2021-05-03T18:52:03 | 2021-05-03T18:52:03 | 361,867,109 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,072 | ino | #include <Wire.h>
#include <Encoder.h>
#define SLAVE_ADDRESS 0x04
byte data[32];
void forward(int dist);
void turn(int angle);
void circle();
////////////////////MOTOR DRIVER PINS/////////////////////////
//Left Wheel Encoder
#define L_CHAN_A 3 //encoder channel a
#define L_CHAN_B 6 //encoder channel b
//Right Wheel Encoder
#define R_CHAN_A 2 //encoder channel a
#define R_CHAN_B 5 //encoder channel b
//Enable Pin
#define ENABLE 4
//Right Control
#define R_DRIVE 9
#define R_DIR 7
//Left Control
#define L_DRIVE 10
#define L_DIR 8
//Encoders, See Encoder.h for ref
Encoder leftEncoder(L_CHAN_A, L_CHAN_B);
Encoder rightEncoder(R_CHAN_A, R_CHAN_B);
//////////////////Speed and Control Globals////////////////////
const double BASE_SPEED = 150;
const double MIN_SPEED = 70;
uint8_t LDutyCycle; //8-bit PWM duty
uint8_t RDutyCycle; //8-bit PWM duty
double currentPositionR = 0; //position in feet
double currentPositionL = 0;
double finalPositionR = 0; //destination in feet
double finalPositionL = 0;
double delta = .01; //acceptable variation in arrival point
double gamma = .5; //slow down point 6in from target
int beta = 50; //catchup adjustment threshold
bool movementEnabled = false;
const double WHEEL_RADIUS = .164;
int distanceDetected, angleDirection;
double distanceConverted, angleConverted;
long int angle, angleDetected;
long int turningAngle;
void setup() {
Serial.begin(115200);
//////////////////Pin setup//////////////////
pinMode(ENABLE, OUTPUT); //MUST BE SET HIGH to enable driver board
pinMode(L_DRIVE, OUTPUT);
pinMode(L_DIR, OUTPUT);
pinMode(R_DRIVE, OUTPUT);
pinMode(R_DIR, OUTPUT);
digitalWrite(ENABLE, HIGH); //Enable driver board
leftEncoder.write(0);
rightEncoder.write(0);
analogWrite(L_DRIVE, 0);
analogWrite(R_DRIVE, 0);
delay(1000); //delay 10sec to let you place the robot on track
Serial.println("Starting");
leftEncoder.write(0); //reset the encoders
rightEncoder.write(0);
movementEnabled = true;
//i2c setup
pinMode(13, OUTPUT);
Serial.begin(115200); // start serial for output
// initialize i2c as slave
Wire.begin(SLAVE_ADDRESS);
// define callbacks for i2c communication
Wire.onReceive(receiveData);
Wire.onRequest(sendData);
}
void loop() {
data[1] = 0;
//detect marker
while(data[1] == 0){
turn(10,1);
}
angleDetected = data[1];
angleConverted = angle/100;
distanceDetected = data[2];
distanceConverted = (double)distanceDetected/1000-1;
angleDirection = data[3];
if(movementEnabled){
turn(angleConverted, 1); //1 indicates direction
delay(1000);
forward(distanceConverted);
delay(1000);
turn(90, 0);
delay(1000);
circle();
delay(1000);
movementEnabled = false;
}
}
void forward(int dist){
finalPositionR = dist;
finalPositionL = dist;
digitalWrite(L_DIR, LOW); //L-H is forward
digitalWrite(R_DIR, HIGH);
while(finalPositionR-currentPositionR > delta){
Serial.println(currentPositionR);
currentPositionR = (rightEncoder.read()/3200.0)*2*3.14*WHEEL_RADIUS*1.51;
currentPositionL = (leftEncoder.read()/3215.0)*2*3.14*WHEEL_RADIUS*1.51;
LDutyCycle = BASE_SPEED+2;
RDutyCycle = BASE_SPEED;
double drift = currentPositionR-currentPositionL;
if(abs(drift) > .005){
LDutyCycle+= drift*10;
RDutyCycle+= -1.0*drift*10;
}
analogWrite(L_DRIVE, LDutyCycle); //actually write the motors
analogWrite(R_DRIVE, RDutyCycle);
}
analogWrite(L_DRIVE, 0);
analogWrite(R_DRIVE, 0);
rightEncoder.write(0);
leftEncoder.write(0);
currentPositionR = 0;
currentPositionL = 0;
}
void turn(int dest, bool dir){
angle = 0;
turningAngle = dest*10*2;
if(dir){
digitalWrite(L_DIR, HIGH); //L-H is forward
digitalWrite(R_DIR, HIGH);
}else{
digitalWrite(L_DIR, LOW); //L-H is forward
digitalWrite(R_DIR, LOW);
}
while(angle < turningAngle){
//Serial.println("Turning");
analogWrite(L_DRIVE, 90);
analogWrite(R_DRIVE, 90);
angle=abs(rightEncoder.read());
Serial.println(angle);
}
analogWrite(L_DRIVE, 0);
analogWrite(R_DRIVE, 0);
rightEncoder.write(0);
leftEncoder.write(0);
currentPositionR = 0;
currentPositionL = 0;
}
void circle(){
digitalWrite(L_DIR, LOW); //L-H is forward
digitalWrite(R_DIR, HIGH);
while(rightEncoder.read()<29350){
analogWrite(L_DRIVE, 200*.55); //actually write the motors
analogWrite(R_DRIVE, 200);
}
analogWrite(L_DRIVE, 0);
analogWrite(R_DRIVE, 0);
rightEncoder.write(0);
leftEncoder.write(0);
}
// callback for received data
void receiveData(int byteCount) {
int i=0;
while (Wire.available()) {
data[i] = Wire.read();
i++;
}
}
void sendData() {
Wire.write(data[1] +5);
}
| [
"[email protected]"
] | |
78a550f4822f0a0e0583076d65a93a601575e1bf | 2109eb2c8d56abd83376401b21cafe6815c49ff2 | /HP3d/CellIdTests.cpp | b1dc4756210e200153bc1d7dc14d20c7fd64ebd6 | [] | no_license | cosmi/hp3d2 | d89d5d0ff9791d6f2e1a721f7519916ce7d69629 | 7a5e3b831fef9d32176def9456488cbf1c73ce2d | refs/heads/master | 2020-04-06T03:40:58.988383 | 2015-11-21T12:17:24 | 2015-11-21T12:17:24 | 37,082,413 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 859 | cpp | //
// CellIdTests.c
// HP3d
//
// Created by Marcin on 03.08.2015.
// Copyright (c) 2015 Marcin. All rights reserved.
//
#include "CellIdTests.h"
#include "TestCommons.h"
void testCellIdOperations() {
CHECK_EQ("Valid half", CellId<2>::getForSize({4, 4}), CellId<2>::getForSize({4, 8}).getHalf());
CHECK_EQ("Valid half", CellId<2>::getForSize({4, 4}), CellId<2>::getForSize({8, 4}).getHalf());
}
void testCellIdRelations() {
CHECK("Is boundary 1", !CellId<2>({0,0}, {2,2}).isSideOf(CellId<2>({0,0}, {2,2})));
CHECK("Is boundary 2", CellId<2>({0,2}, {2,2}).isSideOf(CellId<2>({0,0}, {2,2})));
CHECK("Is boundary 3", !CellId<2>({0,0}, {3,2}).isSideOf(CellId<2>({0,0}, {2,2})));
}
void runCellIdTests() {
TEST("Test CellId Operations", testCellIdOperations());
TEST("Test CellId Relations", testCellIdRelations());
} | [
"[email protected]"
] | |
94153731d76f1513dab682e97b9ae0e3f18903a4 | c5a921726a3805663d26a2dbaa47e49497931d4e | /Accelerated_C++/chap6/urls/urls.cpp | 7e8eb42052d837e5f45860d30182ccdabb36134b | [] | no_license | snowdj/cs_course | a50d07548198b4202e8abde01ec572e2cce38ab3 | fa6504cb5145d10952f4615478fa745f4b35ba13 | refs/heads/master | 2020-03-17T15:18:52.190747 | 2018-05-13T08:08:51 | 2018-05-13T08:08:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,312 | cpp |
#include <string>
#include <vector>
#include <cctype>
#include <algorithm>
#include "urls.h"
using namespace std;
vector<string> find_urls(const string& s)
{
vector<string> ret;
typedef string::const_iterator iter;
iter b = s.begin(), e = s.end();
while (b != e)
{
b = url_beg(b,e);
if (b!= e)
{
iter after = url_end(b,e);
ret.push_back(string(b,after));
b = after;
}
}
return ret;
}
string::const_iterator url_end(string::const_iterator b, string::const_iterator e)
{
return find_if(b,e, not_url_char);
}
bool not_url_char(char c)
{
static const string url_ch = "~;/?:@=&$-_.+!*'(),";
return !(isalnum(c) || find(url_ch.begin(), url_ch.end(), c) != url_ch.end());
}
string::const_iterator url_beg(string::const_iterator b, string::const_iterator e)
{
static const string sep = "://";
typedef string::const_iterator iter;
iter i = b;
while ((i = search(i, e, sep.begin(), sep.end())) != e)
{
if (i != b && i + sep.size()!=e){
iter beg = i;
while (beg != b && isalpha(beg[-1]))
--beg;
if (beg != i && !not_url_char(i[sep.size()]))
return beg;
}
i += sep.size();
}
return e;
}
| [
"[email protected]"
] | |
8dae3eeb3ff8fd7cf65c33ed1f270de98e9dbdb2 | bb55fde74de1a0afc42f76475ec63db26e7ec085 | /Chapter_04/trainOCR.cpp | 51fcd558d75d12abbc05be656297ba9f5e62c13b | [
"MIT"
] | permissive | royshil/Mastering-OpenCV-4-Third-Edition | 1dcd583f4c81477ccc335ae140cccf1173d1996d | b9757bbf8556c2a4c9f6d102bc8b356f4ce079f6 | refs/heads/master | 2020-04-24T17:13:15.834168 | 2018-12-24T08:33:34 | 2018-12-24T08:33:34 | 172,139,005 | 0 | 1 | MIT | 2019-02-22T21:46:33 | 2019-02-22T21:46:33 | null | ISO-8859-3 | C++ | false | false | 2,866 | cpp | /*****************************************************************************
* Number Plate Recognition using SVM and Neural Networks
******************************************************************************
* by David Millán Escrivá, 5th Dec 2012
* http://blog.damiles.com
******************************************************************************
* Ch5 of the book "Mastering OpenCV with Practical Computer Vision Projects"
* Copyright Packt Publishing 2012.
* http://www.packtpub.com/cool-projects-with-opencv/book
*****************************************************************************/
// Main entry code OpenCV
#include <cv.h>
#include <highgui.h>
#include <cvaux.h>
#include "OCR.h"
#include <iostream>
#include <vector>
using namespace std;
using namespace cv;
const int numFilesChars[]={35, 40, 42, 41, 42, 33, 30, 31, 49, 44, 30, 24, 21, 20, 34, 9, 10, 3, 11, 3, 15, 4, 9, 12, 10, 21, 18, 8, 15, 7};
int main ( int argc, char** argv )
{
cout << "OpenCV Training OCR Automatic Number Plate Recognition\n";
cout << "\n";
char* path;
//Check if user specify image to process
if(argc >= 1 )
{
path= argv[1];
}else{
cout << "Usage:\n" << argv[0] << " <path to chars folders files> \n";
return 0;
}
Mat classes;
Mat trainingDataf5;
Mat trainingDataf10;
Mat trainingDataf15;
Mat trainingDataf20;
vector<int> trainingLabels;
OCR ocr;
for(int i=0; i< OCR::numCharacters; i++)
{
int numFiles=numFilesChars[i];
for(int j=0; j< numFiles; j++){
cout << "Character "<< OCR::strCharacters[i] << " file: " << j << "\n";
stringstream ss(stringstream::in | stringstream::out);
ss << path << OCR::strCharacters[i] << "/" << j << ".jpg";
Mat img=imread(ss.str(), 0);
Mat f5=ocr.features(img, 5);
Mat f10=ocr.features(img, 10);
Mat f15=ocr.features(img, 15);
Mat f20=ocr.features(img, 20);
trainingDataf5.push_back(f5);
trainingDataf10.push_back(f10);
trainingDataf15.push_back(f15);
trainingDataf20.push_back(f20);
trainingLabels.push_back(i);
}
}
trainingDataf5.convertTo(trainingDataf5, CV_32FC1);
trainingDataf10.convertTo(trainingDataf10, CV_32FC1);
trainingDataf15.convertTo(trainingDataf15, CV_32FC1);
trainingDataf20.convertTo(trainingDataf20, CV_32FC1);
Mat(trainingLabels).copyTo(classes);
FileStorage fs("OCR.xml", FileStorage::WRITE);
fs << "TrainingDataF5" << trainingDataf5;
fs << "TrainingDataF10" << trainingDataf10;
fs << "TrainingDataF15" << trainingDataf15;
fs << "TrainingDataF20" << trainingDataf20;
fs << "classes" << classes;
fs.release();
return 0;
}
| [
"[email protected]"
] | |
ab1b0f78db0607d3feb3ea39e41b755cc63a43bb | 2f86f968f01a99b4b9fd69d3f6e889ac4fe53d44 | /queue.cpp | bd3d0d539e715db385ea498adeb492ea8c48e8fa | [] | no_license | sundarsaravanan/CPP-Programs | 97cd1b5efacef89c0264e95cba18f06b601ed280 | 6017256065c92be0b769b0d6553e75ac3155a1bf | refs/heads/master | 2021-01-12T05:37:39.569301 | 2017-01-23T17:28:26 | 2017-01-23T17:28:26 | 77,149,877 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 481 | cpp | #include<iostream>
using namespace std;
int f,r;
class queue
{
public:
char a[20];
queue()
{
f=0;
r=-1;
}
void deq()
{
int i=1;
while(f<=r)
{
cout<<i<<"."<<a[f++];
i++;
}
}
void enq(char x)
{
a[++r]=x;
}
};
int main()
{
int no,i;
char a;
queue q;
cout<<"Enter total number of processes\n";
cin>>no;
cout<<"Enter the processes one by one";
for(i=0;i<no;i++)
{
cin>>a;
q.enq(a);
}
cout<<"The Order of processes:\n";
q.deq();
return 0;
}
| [
"[email protected]"
] | |
6baa7990d08206e2730541953041bcd4967f61fc | d168daf4c99413cc344eb6d7bd7d66123c3ce6ae | /IntakeTest/IntakeTest.ino | 8ac0a963be80e19977df16dfb3d5c64fff380d25 | [] | no_license | SoonerRobotics/IEEE-2018-Test | cbb3a488795e54b6a12820dd68380b7d9e7a91e9 | 91d696d351d779694443da4ce9a445552255cfc0 | refs/heads/master | 2021-09-11T00:18:11.754466 | 2018-04-04T22:35:00 | 2018-04-04T22:35:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 798 | ino | #include <RobotLib.h>
#include <IEEErobot2018.h>
void setup()
{
robotSetup();
}
void loop()
{
// DO NOT RUN UNTIL INTAKE_CONSTATNS HAVE BEEN TESTED FOR AND ADDED TO INTAKECONSTANTS.H !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
while (!intake.getLowSwitch())
{
Serial.println("Reseting");
iMotor.output(-.4);
}
//updateColorSensor();
while (!intake.coinDetected())
{
Serial.print(intake.getStateString());
Serial.print("LOOKING FOR COIN\n");
}
while (intake.getIntakeReturn() != 2)
{
Serial.println(intake.getStateString());
intake.pickUpSequence(currentColor, colorScanned);
if(intake.getIntakeReturn() == 1)
{
colorScanned = true;
}
else
{
delay(50);
}
}
colorScanned = false;
//intake.dropOffSequence(currentColor);
delay(1000);
}
| [
"[email protected]"
] | |
1380248cff6e2bc32b905a9b50c5d533e553ea92 | 90047daeb462598a924d76ddf4288e832e86417c | /third_party/WebKit/Source/web/AnimationWorkletProxyClientImpl.h | 147b9d12be926a16dd309f7f423b19480c5b1a53 | [
"BSD-3-Clause",
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"MIT",
"Apache-2.0"
] | permissive | massbrowser/android | 99b8c21fa4552a13c06bbedd0f9c88dd4a4ad080 | a9c4371682c9443d6e1d66005d4db61a24a9617c | refs/heads/master | 2022-11-04T21:15:50.656802 | 2017-06-08T12:31:39 | 2017-06-08T12:31:39 | 93,747,579 | 2 | 2 | BSD-3-Clause | 2022-10-31T10:34:25 | 2017-06-08T12:36:07 | null | UTF-8 | C++ | false | false | 1,638 | h | // 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.
#ifndef AnimationWorkletProxyClientImpl_h
#define AnimationWorkletProxyClientImpl_h
#include "core/dom/AnimationWorkletProxyClient.h"
#include "platform/heap/Handle.h"
#include "platform/wtf/Noncopyable.h"
#include "web/CompositorAnimator.h"
#include "web/CompositorProxyClientImpl.h"
namespace blink {
class CompositorMutatorImpl;
// Mediates between one Animator and the associated CompositorMutatorImpl. There
// is one AnimationWorkletProxyClientImpl per Animator but there may be multiple
// for a given mutator and animatorWorklet.
//
// This is constructed on the main thread but it is used in the worklet backing
// thread i.e., compositor thread.
class AnimationWorkletProxyClientImpl final
: public GarbageCollectedFinalized<AnimationWorkletProxyClientImpl>,
public AnimationWorkletProxyClient,
public CompositorAnimator {
WTF_MAKE_NONCOPYABLE(AnimationWorkletProxyClientImpl);
USING_GARBAGE_COLLECTED_MIXIN(AnimationWorkletProxyClientImpl);
public:
explicit AnimationWorkletProxyClientImpl(CompositorMutatorImpl*);
DECLARE_VIRTUAL_TRACE();
// CompositorAnimator:
// This method is invoked in compositor thread
bool Mutate(double monotonic_time_now,
CompositorMutableStateProvider*) override;
private:
CrossThreadPersistent<CompositorMutatorImpl> mutator_;
CrossThreadPersistent<CompositorProxyClientImpl> compositor_proxy_client_;
};
} // namespace blink
#endif // AnimationWorkletProxyClientImpl_h
| [
"[email protected]"
] | |
c99b346ef3b6940f71b16acb16ee13d56e4c836e | 2e6c469d50a58b57f2b9941939ca0974756c1308 | /cpp/flipgameii.cpp | 648aed8572d4fa4e32a5d613c7e2a4127329d271 | [] | no_license | john15518513/leetcode | 53ed07667f234a858291789ba0d60b46b5a11a51 | 43bf3c594a71535a3f4ee9154cc72344b92b0608 | refs/heads/master | 2021-01-13T04:29:47.247101 | 2018-10-08T02:12:56 | 2018-10-08T02:12:56 | 79,729,551 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 357 | cpp | class Solution {
public:
bool canWin(string s) {
if (s == "" or s.size() <2) return false;
for (int i = 0; i < s.size()-1; i++) {
if (s.substr(i,2) == "++") {
string t = s.substr(0, i) + "--" + s.substr(i+2);
if (!canWin(t)) return true;
}
}
return false;
}
};
| [
"[email protected]"
] | |
82a5805681d4cf4032ab573512ea5dd4ff1d745d | fd2395ea3e33f64c791368519263b7b74cc2be78 | /parsec/facesim/src/Public_Library/Read_Write/READ_WRITE_FUNCTIONS.h | 41088a220d42ff00e40eb792af7461c71ebf6afa | [] | no_license | lucashmorais/taskdep-suit | ca127a6ed864cbebac6181c39e311523a63f9337 | 66ca8115ae1084516f30e52f56eabad542639e5a | refs/heads/master | 2022-09-29T11:26:36.310892 | 2022-04-04T14:15:26 | 2022-04-04T14:15:26 | 175,003,350 | 0 | 0 | null | 2021-04-13T20:33:57 | 2019-03-11T13:13:56 | C | UTF-8 | C++ | false | false | 18,288 | h | //#####################################################################
// Copyright 2004, Eran Guendelman, Igor Neverov, Andrew Selle, Eftychios Sifakis.
// This file is part of PhysBAM whose distribution is governed by the license contained in the accompanying file PHYSBAM_COPYRIGHT.txt.
//#####################################################################
// Class READ_WRITE_FUNCTIONS
//#####################################################################
//
// Functions for reading and writing which do the correct thing for objects, pointers, primitive types, etc. In general, use Read/Write_Binary (and Read/Write_Binary_Array) using T for the type
// of the object you're reading/writing and RW the underlying floating point scalar type (float/double).
//
//#####################################################################
#ifndef __READ_WRITE_FUNCTIONS__
#define __READ_WRITE_FUNCTIONS__
#include <iostream>
#include <assert.h>
#include <stdlib.h>
namespace PhysBAM
{
//#####################################################################
// Function isLittleEndian
//#####################################################################
static inline int isLittleEndian()
{
union
{
unsigned short int word;
unsigned char byte;
} endian_test;
endian_test.word = 0x00FF;
return (endian_test.byte == 0xFF);
}
//#####################################################################
// Function Swap_Endianity
//#####################################################################
template<class T>
inline void Swap_Endianity (T& x)
{
assert (sizeof (T) <= 8);
if (sizeof (T) > 1)
{
T old = x;
for (unsigned int k = 1; k <= sizeof (T); k++) ( (char*) &x) [k - 1] = ( (char*) &old) [sizeof (T) - k];
}
}
//#####################################################################
// Read/Write_Primitive (handles endianness)
//#####################################################################
#ifdef __sparc__
void sparc_seg_fault_prevent_dummy (void *ptr);
#endif
template<class T>
inline void Read_Primitive (std::istream& input_stream, T& d)
{
input_stream.read ( (char*) &d, sizeof (T));
if (!isLittleEndian()) Swap_Endianity (d);
#ifdef __sparc__
/* For unknown reasons I am getting a segfault on my sparc box compiling
with -O3, unless I place a dummy use of the value just read here.
Might just be an issue with a particular gcc version. Unfortunately,
this function call does affect the region of interest. */
sparc_seg_fault_prevent_dummy ( (void *) &d);
#endif
}
template<class T>
inline void Write_Primitive (std::ostream& output_stream, const T& d)
{
T d2 = d;
if (!isLittleEndian()) Swap_Endianity (d2);
output_stream.write ( (const char*) &d2, sizeof (T));
}
#ifdef __APPLE__ // PhysBAM data formats assume sizeof(bool)==1 but the Mac apparently has bool==int with sizeof(bool)==4, so need to specialize these
template<>
inline void Read_Primitive<bool> (std::istream& input_stream, bool& d)
{
char c;
input_stream.read (&c, 1);
d = (bool) c;
}
template<>
inline void Write_Primitive<bool> (std::ostream& output_stream, const bool& d)
{
char c = (char) d;
output_stream.write (&c, 1);
}
#endif
//#####################################################################
// Read/Write_Float_Or_Double
//#####################################################################
template<class T, class RW>
inline void Read_Float_Or_Double (std::istream& input_stream, T& d)
{
std::cerr << "Read_Float_Or_Double called with bad types" << std::endl;
exit (1);
}
template<class T, class RW>
inline void Write_Float_Or_Double (std::ostream& output_stream, T d)
{
std::cerr << "Write_Float_Or_Double called with bad types" << std::endl;
exit (1);
}
template<> inline void Read_Float_Or_Double<float, float> (std::istream& input_stream, float& d)
{
Read_Primitive (input_stream, d); // no conversion
}
template<> inline void Read_Float_Or_Double<double, double> (std::istream& input_stream, double& d)
{
Read_Primitive (input_stream, d); // no conversion
}
template<> inline void Read_Float_Or_Double<float, double> (std::istream& input_stream, float& d)
{
double tmp; // convert types
Read_Primitive (input_stream, tmp);
d = (float) tmp;
}
template<> inline void Read_Float_Or_Double<double, float> (std::istream& input_stream, double& d)
{
float tmp; // convert types
Read_Primitive (input_stream, tmp);
d = (double) tmp;
}
template<> inline void Write_Float_Or_Double<float, float> (std::ostream& output_stream, float d)
{
Write_Primitive (output_stream, d); // no conversion
}
template<> inline void Write_Float_Or_Double<double, double> (std::ostream& output_stream, double d)
{
Write_Primitive (output_stream, d); // no conversion
}
template<> inline void Write_Float_Or_Double<float, double> (std::ostream& output_stream, float d)
{
Write_Primitive (output_stream, (double) d); // convert types
}
template<> inline void Write_Float_Or_Double<double, float> (std::ostream& output_stream, double d)
{
Write_Primitive (output_stream, (float) d); // convert types
}
//#####################################################################
// Read_Write for objects
//#####################################################################
template<class T>
struct Read_Write
{
template<class RW>
static void Read (std::istream& input_stream, T& d)
{
d.template Read<RW> (input_stream);
}
template<class RW>
static void Write (std::ostream& output_stream, const T& d)
{
d.template Write<RW> (output_stream);
}
};
//#####################################################################
// Read_Write for primitive types (other than float and double)
//#####################################################################
#define DEFINE_READ_WRITE_FOR_PRIMITIVE_TYPE(TYPE) \
template<> struct Read_Write<TYPE> { \
template<class RW> static void Read(std::istream& input_stream,TYPE& d){Read_Primitive(input_stream,d);} \
template<class RW> static void Write(std::ostream& output_stream,const TYPE& d) {Write_Primitive(output_stream,d);} \
};
DEFINE_READ_WRITE_FOR_PRIMITIVE_TYPE (bool);
DEFINE_READ_WRITE_FOR_PRIMITIVE_TYPE (char);
DEFINE_READ_WRITE_FOR_PRIMITIVE_TYPE (unsigned char);
DEFINE_READ_WRITE_FOR_PRIMITIVE_TYPE (short);
DEFINE_READ_WRITE_FOR_PRIMITIVE_TYPE (unsigned short);
DEFINE_READ_WRITE_FOR_PRIMITIVE_TYPE (int);
DEFINE_READ_WRITE_FOR_PRIMITIVE_TYPE (unsigned int);
//#####################################################################
// Specializations for float and double
//#####################################################################
template<> struct Read_Write<float>
{
template<class RW>
static void Read (std::istream& input_stream, float& d)
{
Read_Float_Or_Double<float, RW> (input_stream, d);
}
template<class RW>
static void Write (std::ostream& output_stream, const float& d)
{
Write_Float_Or_Double<float, RW> (output_stream, d);
}
};
template<> struct Read_Write<double>
{
template<class RW>
static void Read (std::istream& input_stream, double& d)
{
Read_Float_Or_Double<double, RW> (input_stream, d);
}
template<class RW>
static void Write (std::ostream& output_stream, const double& d)
{
Write_Float_Or_Double<double, RW> (output_stream, d);
}
};
//#####################################################################
// Read_Write for pointers to data
//#####################################################################
template<class T>
struct Read_Write<T*>
{
template<class RW>
static void Read (std::istream& input_stream, T*& d)
{
bool data_exists;
Read_Write<bool>::template Read<RW> (input_stream, data_exists);
if (data_exists)
{
d = new T(); // potential memory leak if d pointed elsewhere
Read_Write<T>::template Read<RW> (input_stream, *d);
}
else d = 0;
}
template<class RW>
static void Write (std::ostream& output_stream, T* const& d)
{
Read_Write<bool>::template Write<RW> (output_stream, d != 0); // Write a bool tag indicating whether pointer's data follows
if (d) Read_Write<T>::template Write<RW> (output_stream, *d);
}
};
//#####################################################################
// Read_Write for std::string's
//#####################################################################
template<>
struct Read_Write<std::string>
{
template<class RW>
static void Read (std::istream& input_stream, std::string& d)
{
int n;
Read_Write<int>::template Read<RW> (input_stream, n);
char* buffer = new char[n];
input_stream.read (buffer, n);
d.assign (buffer, buffer + n);
delete buffer;
}
template<class RW>
static void Write (std::ostream& output_stream, const std::string& d)
{
int n = int (d.size());
Read_Write<int>::template Write<RW> (output_stream, n);
const char* s = d.c_str();
output_stream.write (s, n);
}
};
//#####################################################################
// Read_Binary
//#####################################################################
template<class RW, class T1>
inline void Read_Binary (std::istream& input_stream, T1& d1)
{
Read_Write<T1>::template Read<RW> (input_stream, d1);
}
template<class RW, class T1, class T2>
inline void Read_Binary (std::istream& input_stream, T1& d1, T2& d2)
{
Read_Write<T1>::template Read<RW> (input_stream, d1);
Read_Write<T2>::template Read<RW> (input_stream, d2);
}
template<class RW, class T1, class T2, class T3>
inline void Read_Binary (std::istream& input_stream, T1& d1, T2& d2, T3& d3)
{
Read_Write<T1>::template Read<RW> (input_stream, d1);
Read_Write<T2>::template Read<RW> (input_stream, d2);
Read_Write<T3>::template Read<RW> (input_stream, d3);
}
template<class RW, class T1, class T2, class T3, class T4>
inline void Read_Binary (std::istream& input_stream, T1& d1, T2& d2, T3& d3, T4& d4)
{
Read_Write<T1>::template Read<RW> (input_stream, d1);
Read_Write<T2>::template Read<RW> (input_stream, d2);
Read_Write<T3>::template Read<RW> (input_stream, d3);
Read_Write<T4>::template Read<RW> (input_stream, d4);
}
template<class RW, class T1, class T2, class T3, class T4, class T5>
inline void Read_Binary (std::istream& input_stream, T1& d1, T2& d2, T3& d3, T4& d4, T5& d5)
{
Read_Write<T1>::template Read<RW> (input_stream, d1);
Read_Write<T2>::template Read<RW> (input_stream, d2);
Read_Write<T3>::template Read<RW> (input_stream, d3);
Read_Write<T4>::template Read<RW> (input_stream, d4);
Read_Write<T5>::template Read<RW> (input_stream, d5);
}
template<class RW, class T1, class T2, class T3, class T4, class T5, class T6>
inline void Read_Binary (std::istream& input_stream, T1& d1, T2& d2, T3& d3, T4& d4, T5& d5, T6& d6)
{
Read_Write<T1>::template Read<RW> (input_stream, d1);
Read_Write<T2>::template Read<RW> (input_stream, d2);
Read_Write<T3>::template Read<RW> (input_stream, d3);
Read_Write<T4>::template Read<RW> (input_stream, d4);
Read_Write<T5>::template Read<RW> (input_stream, d5);
Read_Write<T6>::template Read<RW> (input_stream, d6);
}
template<class RW, class T1, class T2, class T3, class T4, class T5, class T6, class T7>
inline void Read_Binary (std::istream& input_stream, T1& d1, T2& d2, T3& d3, T4& d4, T5& d5, T6& d6, T7& d7)
{
Read_Write<T1>::template Read<RW> (input_stream, d1);
Read_Write<T2>::template Read<RW> (input_stream, d2);
Read_Write<T3>::template Read<RW> (input_stream, d3);
Read_Write<T4>::template Read<RW> (input_stream, d4);
Read_Write<T5>::template Read<RW> (input_stream, d5);
Read_Write<T6>::template Read<RW> (input_stream, d6);
Read_Write<T7>::template Read<RW> (input_stream, d7);
}
template<class RW, class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8>
inline void Read_Binary (std::istream& input_stream, T1& d1, T2& d2, T3& d3, T4& d4, T5& d5, T6& d6, T7& d7, T8& d8)
{
Read_Write<T1>::template Read<RW> (input_stream, d1);
Read_Write<T2>::template Read<RW> (input_stream, d2);
Read_Write<T3>::template Read<RW> (input_stream, d3);
Read_Write<T4>::template Read<RW> (input_stream, d4);
Read_Write<T5>::template Read<RW> (input_stream, d5);
Read_Write<T6>::template Read<RW> (input_stream, d6);
Read_Write<T7>::template Read<RW> (input_stream, d7);
Read_Write<T8>::template Read<RW> (input_stream, d8);
}
template<class RW, class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9>
inline void Read_Binary (std::istream& input_stream, T1& d1, T2& d2, T3& d3, T4& d4, T5& d5, T6& d6, T7& d7, T8& d8, T9& d9)
{
Read_Write<T1>::template Read<RW> (input_stream, d1);
Read_Write<T2>::template Read<RW> (input_stream, d2);
Read_Write<T3>::template Read<RW> (input_stream, d3);
Read_Write<T4>::template Read<RW> (input_stream, d4);
Read_Write<T5>::template Read<RW> (input_stream, d5);
Read_Write<T6>::template Read<RW> (input_stream, d6);
Read_Write<T7>::template Read<RW> (input_stream, d7);
Read_Write<T8>::template Read<RW> (input_stream, d8);
Read_Write<T9>::template Read<RW> (input_stream, d9);
}
//#####################################################################
// Write_Binary
//#####################################################################
template<class RW, class T1>
inline void Write_Binary (std::ostream& output_stream, const T1& d1)
{
Read_Write<T1>::template Write<RW> (output_stream, d1);
}
template<class RW, class T1, class T2>
inline void Write_Binary (std::ostream& output_stream, const T1& d1, const T2& d2)
{
Read_Write<T1>::template Write<RW> (output_stream, d1);
Read_Write<T2>::template Write<RW> (output_stream, d2);
}
template<class RW, class T1, class T2, class T3>
inline void Write_Binary (std::ostream& output_stream, const T1& d1, const T2& d2, const T3& d3)
{
Read_Write<T1>::template Write<RW> (output_stream, d1);
Read_Write<T2>::template Write<RW> (output_stream, d2);
Read_Write<T3>::template Write<RW> (output_stream, d3);
}
template<class RW, class T1, class T2, class T3, class T4>
inline void Write_Binary (std::ostream& output_stream, const T1& d1, const T2& d2, const T3& d3, const T4& d4)
{
Read_Write<T1>::template Write<RW> (output_stream, d1);
Read_Write<T2>::template Write<RW> (output_stream, d2);
Read_Write<T3>::template Write<RW> (output_stream, d3);
Read_Write<T4>::template Write<RW> (output_stream, d4);
}
template<class RW, class T1, class T2, class T3, class T4, class T5>
inline void Write_Binary (std::ostream& output_stream, const T1& d1, const T2& d2, const T3& d3, const T4& d4, const T5& d5)
{
Read_Write<T1>::template Write<RW> (output_stream, d1);
Read_Write<T2>::template Write<RW> (output_stream, d2);
Read_Write<T3>::template Write<RW> (output_stream, d3);
Read_Write<T4>::template Write<RW> (output_stream, d4);
Read_Write<T5>::template Write<RW> (output_stream, d5);
}
template<class RW, class T1, class T2, class T3, class T4, class T5, class T6>
inline void Write_Binary (std::ostream& output_stream, const T1& d1, const T2& d2, const T3& d3, const T4& d4, const T5& d5, const T6& d6)
{
Read_Write<T1>::template Write<RW> (output_stream, d1);
Read_Write<T2>::template Write<RW> (output_stream, d2);
Read_Write<T3>::template Write<RW> (output_stream, d3);
Read_Write<T4>::template Write<RW> (output_stream, d4);
Read_Write<T5>::template Write<RW> (output_stream, d5);
Read_Write<T6>::template Write<RW> (output_stream, d6);
}
template<class RW, class T1, class T2, class T3, class T4, class T5, class T6, class T7>
inline void Write_Binary (std::ostream& output_stream, const T1& d1, const T2& d2, const T3& d3, const T4& d4, const T5& d5, const T6& d6, const T7& d7)
{
Read_Write<T1>::template Write<RW> (output_stream, d1);
Read_Write<T2>::template Write<RW> (output_stream, d2);
Read_Write<T3>::template Write<RW> (output_stream, d3);
Read_Write<T4>::template Write<RW> (output_stream, d4);
Read_Write<T5>::template Write<RW> (output_stream, d5);
Read_Write<T6>::template Write<RW> (output_stream, d6);
Read_Write<T7>::template Write<RW> (output_stream, d7);
}
template<class RW, class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8>
inline void Write_Binary (std::ostream& output_stream, const T1& d1, const T2& d2, const T3& d3, const T4& d4, const T5& d5, const T6& d6, const T7& d7, const T8& d8)
{
Read_Write<T1>::template Write<RW> (output_stream, d1);
Read_Write<T2>::template Write<RW> (output_stream, d2);
Read_Write<T3>::template Write<RW> (output_stream, d3);
Read_Write<T4>::template Write<RW> (output_stream, d4);
Read_Write<T5>::template Write<RW> (output_stream, d5);
Read_Write<T6>::template Write<RW> (output_stream, d6);
Read_Write<T7>::template Write<RW> (output_stream, d7);
Read_Write<T8>::template Write<RW> (output_stream, d8);
}
template<class RW, class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9>
inline void Write_Binary (std::ostream& output_stream, const T1& d1, const T2& d2, const T3& d3, const T4& d4, const T5& d5, const T6& d6, const T7& d7, const T8& d8, const T9& d9)
{
Read_Write<T1>::template Write<RW> (output_stream, d1);
Read_Write<T2>::template Write<RW> (output_stream, d2);
Read_Write<T3>::template Write<RW> (output_stream, d3);
Read_Write<T4>::template Write<RW> (output_stream, d4);
Read_Write<T5>::template Write<RW> (output_stream, d5);
Read_Write<T6>::template Write<RW> (output_stream, d6);
Read_Write<T7>::template Write<RW> (output_stream, d7);
Read_Write<T8>::template Write<RW> (output_stream, d8);
Read_Write<T9>::template Write<RW> (output_stream, d9);
}
//#####################################################################
// Read/Write_Binary_Array
//#####################################################################
// array is C-style (zero-based) array
template<class RW, class T>
inline void Read_Binary_Array (std::istream& input_stream, T* array, const int number_of_elements)
{
for (int i = 0; i < number_of_elements; i++) Read_Write<T>::template Read<RW> (input_stream, array[i]);
}
template<class RW, class T>
inline void Write_Binary_Array (std::ostream& output_stream, const T* array, const int number_of_elements)
{
for (int i = 0; i < number_of_elements; i++) Read_Write<T>::template Write<RW> (output_stream, array[i]);
}
//#####################################################################
}
#endif
| [
"[email protected]"
] | |
11c27b4e9ebcddcab3371cacaf69fcb4017c0eae | d743b2d40957a3c07e8bfc03ea69e459c96ace56 | /271 Encode and Decode Strings/271.cpp | bc0c3b450c24003266376041211cf5e8931a6bb2 | [] | no_license | TakuyaKimura/Leetcode | f126e72458f7a1b6eb8af9dd874fc2ee77eefe01 | 6f68ed674a3de7d2277c256583c67dda73092dc0 | refs/heads/master | 2021-01-10T21:39:48.227089 | 2016-02-06T11:08:29 | 2016-02-06T11:08:29 | 40,781,363 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,070 | cpp | /*
Design an algorithm to encode a list of strings to a string.
The encoded string is then sent over the network and is decoded back to the original list of strings.
Machine 1 (sender) has the function:
string encode(vector<string> strs) {
// ... your code
return encoded_string;
}
Machine 2 (receiver) has the function:
vector<string> decode(string s) {
//... your code
return strs;
}
So Machine 1 does:
string encoded_string = encode(strs);
and Machine 2 does:
vector<string> strs2 = decode(encoded_string);
strs2 in Machine 2 should be the same as strs in Machine 1.
Implement the encode and decode methods.
Note:
1. The string may contain any possible characters out of 256 valid ascii characters.
Your algorithm should be generalized enough to work on any possible characters.
2. Do not use class member/global/static variables to store states.
Your encode and decode algorithms should be stateless.
3. Do not rely on any library method such as eval or serialize methods.
You should implement your own encode/decode algorithm.
*/
#include <vector>
#include <string>
#include <sstream>
using namespace std;
// There are other methods not using length
// e.g., replace all "|" with "||" in each string, and use " | " as delimiter
class Codec {
public:
// Encodes a list of strings to a single string.
string encode(vector<string>& strs) {
ostringstream ss;
for (string& str : strs)
ss << str.length() << ':' << str;
return ss.str();
}
// Decodes a single string to a list of strings.
vector<string> decode(string s) {
vector<string> result;
for (int i = 0; i < s.length();)
{
int len = atoi(&s[i]); // note how atoi is used
i = s.find(':', i) + 1;
result.push_back(s.substr(i, len));
i += len;
}
return result;
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.decode(codec.encode(strs)); | [
"[email protected]"
] | |
e0e177deef27292d1b920bd8c7d02ea7828d33e5 | 8be1a777adcd1c80d828e87a3f70c13566d73f43 | /Analyser/Machines.hpp | cd64edd33602330497592e9f18637a03cfa203e5 | [
"MIT"
] | permissive | ajacocks/CLK | d42249c12afae6bbc1253cb1a556b6c6a9f22be5 | 5f39938a192f976f51f54e4bbaf6d5cded03d48d | refs/heads/master | 2022-07-30T03:58:53.285448 | 2020-05-11T04:52:51 | 2020-05-11T04:52:51 | 262,941,152 | 0 | 0 | MIT | 2020-05-11T04:48:30 | 2020-05-11T04:48:30 | null | UTF-8 | C++ | false | false | 379 | hpp | //
// Machines.h
// Clock Signal
//
// Created by Thomas Harte on 24/01/2018.
// Copyright 2018 Thomas Harte. All rights reserved.
//
#ifndef Machines_h
#define Machines_h
namespace Analyser {
enum class Machine {
AmstradCPC,
AppleII,
Atari2600,
AtariST,
ColecoVision,
Electron,
Macintosh,
MasterSystem,
MSX,
Oric,
Vic20,
ZX8081
};
}
#endif /* Machines_h */
| [
"[email protected]"
] | |
fa5de7bc27a93e6cae4aa5e33048ed83580af072 | be0282afa8dd436619c71d6118c9db455eaf1a29 | /Intermediate/Build/Win64/Design3D/Inc/Engine/AnimNode_SaveCachedPose.generated.h | a7e2126f3329473bf36b46773bc2f98c2376c499 | [] | no_license | Quant2017/Design3D | 0f915580b222af40ab911021cceef5c26375d7f9 | 94a22386be4aa37aa0f546354cc62958820a4bf6 | refs/heads/master | 2022-04-23T10:44:12.398772 | 2020-04-22T01:02:39 | 2020-04-22T01:02:39 | 262,966,755 | 1 | 0 | null | 2020-05-11T07:12:37 | 2020-05-11T07:12:36 | null | UTF-8 | C++ | false | false | 1,168 | h | // Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "UObject/ObjectMacros.h"
#include "UObject/ScriptMacros.h"
PRAGMA_DISABLE_DEPRECATION_WARNINGS
#ifdef ENGINE_AnimNode_SaveCachedPose_generated_h
#error "AnimNode_SaveCachedPose.generated.h already included, missing '#pragma once' in AnimNode_SaveCachedPose.h"
#endif
#define ENGINE_AnimNode_SaveCachedPose_generated_h
#define Engine_Source_Runtime_Engine_Classes_Animation_AnimNode_SaveCachedPose_h_16_GENERATED_BODY \
friend struct Z_Construct_UScriptStruct_FAnimNode_SaveCachedPose_Statics; \
static class UScriptStruct* StaticStruct(); \
typedef FAnimNode_Base Super;
template<> ENGINE_API UScriptStruct* StaticStruct<struct FAnimNode_SaveCachedPose>();
#undef CURRENT_FILE_ID
#define CURRENT_FILE_ID Engine_Source_Runtime_Engine_Classes_Animation_AnimNode_SaveCachedPose_h
PRAGMA_ENABLE_DEPRECATION_WARNINGS
| [
"[email protected]"
] | |
4cb060f20cfff41f9a0713e2a1535746c526be00 | 8b4aca4180d5cf53f54c3c9bf39802902351cd34 | /easy/rightmostChar/rightmostChar.cpp | da693af3dee735cfa4477af6c5c4c8864c36ead1 | [] | no_license | p-lots/codeeval | 31d3b38560ea513a872b83f5eb702dda0a3346aa | aea06e6fd955920c9ba019599035796bda5a0ca6 | refs/heads/master | 2020-05-21T14:40:04.395429 | 2019-05-11T05:04:12 | 2019-05-11T05:04:12 | 186,086,439 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 693 | cpp | // https://www.codeeval.com/open_challenges/31/
// Submitted November 25, 2015
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
int main(int argc, char *argv[])
{
ifstream file(argv[1]);
string line;
while (getline(file, line)) {
stringstream ss(line);
string temp;
string search;
string toBeSearched;
bool firstTime = true;
while (getline(ss, temp, ',')) {
if (firstTime) {
firstTime = false;
search = temp;
}
else
toBeSearched = temp;
}
string::size_type pos = search.find_last_of(toBeSearched);
if (pos != string::npos)
cout << pos << endl;
else
cout << "-1" << endl;
}
return 0;
} | [
"[email protected]"
] | |
3328dd9c0dc5f1cd4c38155b05a2c213db218818 | 4dbb45758447dcfa13c0be21e4749d62588aab70 | /iOS/Classes/Native/mscorlib_System_Collections_Generic_Dictionary_2_g3327233862.h | 7506ed0b1a5a7180a7a9242859ebd885fb8bad71 | [
"MIT"
] | permissive | mopsicus/unity-share-plugin-ios-android | 6dd6ccd2fa05c73f0bf5e480a6f2baecb7e7a710 | 3ee99aef36034a1e4d7b156172953f9b4dfa696f | refs/heads/master | 2020-12-25T14:38:03.861759 | 2016-07-19T10:06:04 | 2016-07-19T10:06:04 | 63,676,983 | 12 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,931 | h | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
// System.Int32[]
struct Int32U5BU5D_t3230847821;
// System.Collections.Generic.Link[]
struct LinkU5BU5D_t375419643;
// UnityEngine.Canvas[]
struct CanvasU5BU5D_t2903919733;
// UnityEngine.UI.Collections.IndexedSet`1<UnityEngine.UI.Graphic>[]
struct IndexedSet_1U5BU5D_t1435227950;
// System.Collections.Generic.IEqualityComparer`1<UnityEngine.Canvas>
struct IEqualityComparer_1_t3518175168;
// System.Runtime.Serialization.SerializationInfo
struct SerializationInfo_t2185721892;
// System.Collections.Generic.Dictionary`2/Transform`1<UnityEngine.Canvas,UnityEngine.UI.Collections.IndexedSet`1<UnityEngine.UI.Graphic>,System.Collections.DictionaryEntry>
struct Transform_1_t2913242161;
#include "mscorlib_System_Object4170816371.h"
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Collections.Generic.Dictionary`2<UnityEngine.Canvas,UnityEngine.UI.Collections.IndexedSet`1<UnityEngine.UI.Graphic>>
struct Dictionary_2_t3327233862 : public Il2CppObject
{
public:
// System.Int32[] System.Collections.Generic.Dictionary`2::table
Int32U5BU5D_t3230847821* ___table_4;
// System.Collections.Generic.Link[] System.Collections.Generic.Dictionary`2::linkSlots
LinkU5BU5D_t375419643* ___linkSlots_5;
// TKey[] System.Collections.Generic.Dictionary`2::keySlots
CanvasU5BU5D_t2903919733* ___keySlots_6;
// TValue[] System.Collections.Generic.Dictionary`2::valueSlots
IndexedSet_1U5BU5D_t1435227950* ___valueSlots_7;
// System.Int32 System.Collections.Generic.Dictionary`2::touchedSlots
int32_t ___touchedSlots_8;
// System.Int32 System.Collections.Generic.Dictionary`2::emptySlot
int32_t ___emptySlot_9;
// System.Int32 System.Collections.Generic.Dictionary`2::count
int32_t ___count_10;
// System.Int32 System.Collections.Generic.Dictionary`2::threshold
int32_t ___threshold_11;
// System.Collections.Generic.IEqualityComparer`1<TKey> System.Collections.Generic.Dictionary`2::hcp
Il2CppObject* ___hcp_12;
// System.Runtime.Serialization.SerializationInfo System.Collections.Generic.Dictionary`2::serialization_info
SerializationInfo_t2185721892 * ___serialization_info_13;
// System.Int32 System.Collections.Generic.Dictionary`2::generation
int32_t ___generation_14;
public:
inline static int32_t get_offset_of_table_4() { return static_cast<int32_t>(offsetof(Dictionary_2_t3327233862, ___table_4)); }
inline Int32U5BU5D_t3230847821* get_table_4() const { return ___table_4; }
inline Int32U5BU5D_t3230847821** get_address_of_table_4() { return &___table_4; }
inline void set_table_4(Int32U5BU5D_t3230847821* value)
{
___table_4 = value;
Il2CppCodeGenWriteBarrier(&___table_4, value);
}
inline static int32_t get_offset_of_linkSlots_5() { return static_cast<int32_t>(offsetof(Dictionary_2_t3327233862, ___linkSlots_5)); }
inline LinkU5BU5D_t375419643* get_linkSlots_5() const { return ___linkSlots_5; }
inline LinkU5BU5D_t375419643** get_address_of_linkSlots_5() { return &___linkSlots_5; }
inline void set_linkSlots_5(LinkU5BU5D_t375419643* value)
{
___linkSlots_5 = value;
Il2CppCodeGenWriteBarrier(&___linkSlots_5, value);
}
inline static int32_t get_offset_of_keySlots_6() { return static_cast<int32_t>(offsetof(Dictionary_2_t3327233862, ___keySlots_6)); }
inline CanvasU5BU5D_t2903919733* get_keySlots_6() const { return ___keySlots_6; }
inline CanvasU5BU5D_t2903919733** get_address_of_keySlots_6() { return &___keySlots_6; }
inline void set_keySlots_6(CanvasU5BU5D_t2903919733* value)
{
___keySlots_6 = value;
Il2CppCodeGenWriteBarrier(&___keySlots_6, value);
}
inline static int32_t get_offset_of_valueSlots_7() { return static_cast<int32_t>(offsetof(Dictionary_2_t3327233862, ___valueSlots_7)); }
inline IndexedSet_1U5BU5D_t1435227950* get_valueSlots_7() const { return ___valueSlots_7; }
inline IndexedSet_1U5BU5D_t1435227950** get_address_of_valueSlots_7() { return &___valueSlots_7; }
inline void set_valueSlots_7(IndexedSet_1U5BU5D_t1435227950* value)
{
___valueSlots_7 = value;
Il2CppCodeGenWriteBarrier(&___valueSlots_7, value);
}
inline static int32_t get_offset_of_touchedSlots_8() { return static_cast<int32_t>(offsetof(Dictionary_2_t3327233862, ___touchedSlots_8)); }
inline int32_t get_touchedSlots_8() const { return ___touchedSlots_8; }
inline int32_t* get_address_of_touchedSlots_8() { return &___touchedSlots_8; }
inline void set_touchedSlots_8(int32_t value)
{
___touchedSlots_8 = value;
}
inline static int32_t get_offset_of_emptySlot_9() { return static_cast<int32_t>(offsetof(Dictionary_2_t3327233862, ___emptySlot_9)); }
inline int32_t get_emptySlot_9() const { return ___emptySlot_9; }
inline int32_t* get_address_of_emptySlot_9() { return &___emptySlot_9; }
inline void set_emptySlot_9(int32_t value)
{
___emptySlot_9 = value;
}
inline static int32_t get_offset_of_count_10() { return static_cast<int32_t>(offsetof(Dictionary_2_t3327233862, ___count_10)); }
inline int32_t get_count_10() const { return ___count_10; }
inline int32_t* get_address_of_count_10() { return &___count_10; }
inline void set_count_10(int32_t value)
{
___count_10 = value;
}
inline static int32_t get_offset_of_threshold_11() { return static_cast<int32_t>(offsetof(Dictionary_2_t3327233862, ___threshold_11)); }
inline int32_t get_threshold_11() const { return ___threshold_11; }
inline int32_t* get_address_of_threshold_11() { return &___threshold_11; }
inline void set_threshold_11(int32_t value)
{
___threshold_11 = value;
}
inline static int32_t get_offset_of_hcp_12() { return static_cast<int32_t>(offsetof(Dictionary_2_t3327233862, ___hcp_12)); }
inline Il2CppObject* get_hcp_12() const { return ___hcp_12; }
inline Il2CppObject** get_address_of_hcp_12() { return &___hcp_12; }
inline void set_hcp_12(Il2CppObject* value)
{
___hcp_12 = value;
Il2CppCodeGenWriteBarrier(&___hcp_12, value);
}
inline static int32_t get_offset_of_serialization_info_13() { return static_cast<int32_t>(offsetof(Dictionary_2_t3327233862, ___serialization_info_13)); }
inline SerializationInfo_t2185721892 * get_serialization_info_13() const { return ___serialization_info_13; }
inline SerializationInfo_t2185721892 ** get_address_of_serialization_info_13() { return &___serialization_info_13; }
inline void set_serialization_info_13(SerializationInfo_t2185721892 * value)
{
___serialization_info_13 = value;
Il2CppCodeGenWriteBarrier(&___serialization_info_13, value);
}
inline static int32_t get_offset_of_generation_14() { return static_cast<int32_t>(offsetof(Dictionary_2_t3327233862, ___generation_14)); }
inline int32_t get_generation_14() const { return ___generation_14; }
inline int32_t* get_address_of_generation_14() { return &___generation_14; }
inline void set_generation_14(int32_t value)
{
___generation_14 = value;
}
};
struct Dictionary_2_t3327233862_StaticFields
{
public:
// System.Collections.Generic.Dictionary`2/Transform`1<TKey,TValue,System.Collections.DictionaryEntry> System.Collections.Generic.Dictionary`2::<>f__am$cacheB
Transform_1_t2913242161 * ___U3CU3Ef__amU24cacheB_15;
public:
inline static int32_t get_offset_of_U3CU3Ef__amU24cacheB_15() { return static_cast<int32_t>(offsetof(Dictionary_2_t3327233862_StaticFields, ___U3CU3Ef__amU24cacheB_15)); }
inline Transform_1_t2913242161 * get_U3CU3Ef__amU24cacheB_15() const { return ___U3CU3Ef__amU24cacheB_15; }
inline Transform_1_t2913242161 ** get_address_of_U3CU3Ef__amU24cacheB_15() { return &___U3CU3Ef__amU24cacheB_15; }
inline void set_U3CU3Ef__amU24cacheB_15(Transform_1_t2913242161 * value)
{
___U3CU3Ef__amU24cacheB_15 = value;
Il2CppCodeGenWriteBarrier(&___U3CU3Ef__amU24cacheB_15, value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| [
"[email protected]"
] | |
9c1b888b6022e5e0b9f347e4043794c721d7b2e1 | c74a1ee91fb94c3d99f577b35bc35db15adf1dc3 | /src/qt/aboutdialog.cpp | 9684102338664a8227f3014d7ed8b2b30119d9bc | [
"MIT"
] | permissive | blackgldsaw/dazzlecoin-test | 37603810069099218dd87f9cedadb87a55b68120 | 2a1670bc769473e337e35cc2d6c3798647ef469f | refs/heads/master | 2021-01-13T07:11:54.111099 | 2017-06-22T14:13:11 | 2017-06-22T14:13:11 | 95,122,791 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,116 | cpp | // Copyright (c) 2011-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "aboutdialog.h"
#include "ui_aboutdialog.h"
#include "clientmodel.h"
#include "clientversion.h"
// Copyright year (2009-this)
// Todo: update this when changing our copyright comments in the source
const int ABOUTDIALOG_COPYRIGHT_YEAR = 2014;
AboutDialog::AboutDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::AboutDialog)
{
ui->setupUi(this);
// Set current copyright year
ui->copyrightLabel->setText(tr("Copyright") + QString(" © 2009-%1 ").arg(COPYRIGHT_YEAR) + tr("The Bitcoin developers") + QString("<br>") + tr("Copyright") + QString(" © ") + tr("2011-%1 The Dazzlecoin developers").arg(ABOUTDIALOG_COPYRIGHT_YEAR));
}
void AboutDialog::setModel(ClientModel *model)
{
if(model)
{
ui->versionLabel->setText(model->formatFullVersion());
}
}
AboutDialog::~AboutDialog()
{
delete ui;
}
void AboutDialog::on_buttonBox_accepted()
{
close();
}
| [
"[email protected]"
] | |
e40c4aae168215a429317f0bba9d87a5b0afa640 | 43ea51859b6ae1b91417289e30979dd7f9f055d8 | /Source/GameDevTVJam/GameDevTVJamCharacter.cpp | 2282752d9de618b2fa2395608f126d08978dd06e | [] | no_license | TheCodingRook/GameDevTVJam | e8b47f8d3307c0ac08644f2d4cb8913388e05261 | be69855c5c26ac8f2a003c6a27e5f20f46c05629 | refs/heads/master | 2022-12-08T19:14:12.663993 | 2020-09-04T20:47:03 | 2020-09-04T20:47:03 | 262,843,075 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,020 | cpp | // Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
#include "GameDevTVJamCharacter.h"
#include "Camera/CameraComponent.h"
#include "Components/CapsuleComponent.h"
#include "Components/InputComponent.h"
#include "GameFramework/SpringArmComponent.h"
#include "GameFramework/CharacterMovementComponent.h"
#include "GrabbingAbility.h"
#include "ClimbingAbility.h"
#include "InteractionComponentBase.h"
#include "MyGameInstance.h"
#include "Kismet/GameplayStatics.h"
#include "GameDevTVJamGameMode.h"
#include "GameHUDWidget.h"
AGameDevTVJamCharacter::AGameDevTVJamCharacter()
{
// Set size for collision capsule
GetCapsuleComponent()->InitCapsuleSize(42.f, 96.0f);
// Don't rotate when the controller rotates.
bUseControllerRotationPitch = false;
bUseControllerRotationYaw = false;
bUseControllerRotationRoll = false;
// Create a camera boom attached to the root (capsule)
CameraBoom = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom"));
CameraBoom->SetupAttachment(RootComponent);
CameraBoom->SetUsingAbsoluteRotation(true); // Rotation of the character should not affect rotation of boom
CameraBoom->bDoCollisionTest = false;
CameraBoom->TargetArmLength = 500.f;
CameraBoom->SocketOffset = FVector(0.f,0.f,75.f);
CameraBoom->SetRelativeRotation(FRotator(0.f,180.f,0.f));
// Create a camera and attach to boom
SideViewCameraComponent = CreateDefaultSubobject<UCameraComponent>(TEXT("SideViewCamera"));
SideViewCameraComponent->SetupAttachment(CameraBoom, USpringArmComponent::SocketName);
SideViewCameraComponent->bUsePawnControlRotation = false; // We don't want the controller rotating the camera
// Configure character movement
GetCharacterMovement()->bOrientRotationToMovement = true; // Face in the direction we are moving..
GetCharacterMovement()->RotationRate = FRotator(0.0f, 720.0f, 0.0f); // ...at this rotation rate
GetCharacterMovement()->GravityScale = 2.f;
GetCharacterMovement()->AirControl = 0.80f;
GetCharacterMovement()->JumpZVelocity = 1000.f;
GetCharacterMovement()->GroundFriction = 3.f;
GetCharacterMovement()->MaxWalkSpeed = 600.f;
GetCharacterMovement()->MaxFlySpeed = 600.f;
// Note: The skeletal mesh and anim blueprint references on the Mesh component (inherited from Character)
// are set in the derived blueprint asset named MyCharacter (to avoid direct content references in C++)
// Create the custom physics handle component for grabbing objects
Grabber = CreateDefaultSubobject<UGrabbingAbility>(TEXT("Grabber"));
// Create the custom climbing ability component to enable climbing
ClimbingAbility = CreateDefaultSubobject<UClimbingAbility>(TEXT("Climbing Ability"));
}
float AGameDevTVJamCharacter::TakeDamage(float DamageAmount, FDamageEvent const& DamageEvent, AController* EventInstigator, AActor* DamageCauser)
{
if(!bIsDead)
{
GetCharacterMovement()->SetMovementMode(EMovementMode::MOVE_Walking);
if (bWasMeshAdjusted)
{
GetCapsuleComponent()->SetCapsuleHalfHeight(98.f);
GetCapsuleComponent()->SetCapsuleRadius(42.f);
GetMesh()->AddLocalOffset(GetClimbingAbility()->GetManualMeshOffset() * (-1));
}
SetIsDead(true);
UGameplayStatics::PlaySoundAtLocation(this, DeathSound, GetActorLocation());
DisableInput(Cast<APlayerController>(GetController()));
OnPlayerDied.Broadcast();
Cast<AGameDevTVJamGameMode>(UGameplayStatics::GetGameMode(this))->GetGameHUD()->PlayDeathAnimations();
}
return Super::TakeDamage(DamageAmount, DamageEvent, EventInstigator, DamageCauser);
}
void AGameDevTVJamCharacter::SetCanClimb(bool NewClimbSetting)
{
bCanClimb = NewClimbSetting;
}
void AGameDevTVJamCharacter::SetIsClimbing(bool NewClimbingState)
{
bIsClimbing = NewClimbingState;
}
void AGameDevTVJamCharacter::SetIsClimbingLedge(bool NewClimbingLedgeState)
{
if (NewClimbingLedgeState)
{
bIsClimbing = false;
}
bIsClimbingLedge = NewClimbingLedgeState;
}
void AGameDevTVJamCharacter::SetIsDroppingFromLedge(bool NewDroppingFromLedgeState)
{
bIsDroppingFromLedge = NewDroppingFromLedgeState;
}
void AGameDevTVJamCharacter::SetWasMeshAdjusted(bool NewMeshAdjustedFlag)
{
bWasMeshAdjusted = NewMeshAdjustedFlag;
}
void AGameDevTVJamCharacter::SetIsDead(bool DeathStatus)
{
bIsDead = DeathStatus;
}
void AGameDevTVJamCharacter::SetIsVictorious(bool VictoryStatus)
{
bIsVictorious = VictoryStatus;
}
void AGameDevTVJamCharacter::SetEncumbered(bool NewState)
{
bIsEncumbered = NewState;
}
//////////////////////////////////////////////////////////////////////////
// Input
void AGameDevTVJamCharacter::SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent)
{
// set up gameplay key bindings
PlayerInputComponent->BindAction("Jump", IE_Pressed, this, &AGameDevTVJamCharacter::AttemptJump);
PlayerInputComponent->BindAction("Jump", IE_Released, this, &ACharacter::StopJumping);
PlayerInputComponent->BindAxis("MoveRight", this, &AGameDevTVJamCharacter::MoveRight);
PlayerInputComponent->BindAction("Crouch", IE_Pressed, this, &AGameDevTVJamCharacter::PerformCrouch);
PlayerInputComponent->BindAction("Crouch", IE_Released, this, &AGameDevTVJamCharacter::PerformUnCrouch);
PlayerInputComponent->BindAction("Interact", IE_Pressed, this, &AGameDevTVJamCharacter::Interact);
PlayerInputComponent->BindAction("Interact", IE_Released, this, &AGameDevTVJamCharacter::StopInteracting);
PlayerInputComponent->BindAction("Pause", IE_Pressed, this, &AGameDevTVJamCharacter::PauseGame);
PlayerInputComponent->BindTouch(IE_Pressed, this, &AGameDevTVJamCharacter::TouchStarted);
PlayerInputComponent->BindTouch(IE_Released, this, &AGameDevTVJamCharacter::TouchStopped);
}
void AGameDevTVJamCharacter::SetInventoryKeyList(TArray<AActor*> NewList)
{
InventoryKeyList = NewList;
}
void AGameDevTVJamCharacter::AddKeyToInventory()
{
NumberOfKeys++;
}
void AGameDevTVJamCharacter::RemoveKeyFromInventory()
{
if (NumberOfKeys > 0)
{
NumberOfKeys--;
}
}
void AGameDevTVJamCharacter::VictoryAnimation()
{
bIsVictorious = true;
SetActorRotation(FRotator(0.f, 0.f, 0.f));
DisableInput(Cast<APlayerController>(GetController()));
}
void AGameDevTVJamCharacter::AttemptJump()
{
if (bIsClimbing)
{
bIsClimbing = false;
bIsClimbingLedge = true;
}
else if (!bIsEncumbered)
{
if (JumpSound && !GetMovementComponent()->IsFalling())
{
UGameplayStatics::PlaySoundAtLocation(this, JumpSound, GetActorLocation());
}
Jump();
}
}
void AGameDevTVJamCharacter::MoveRight(float Value)
{
if (!bIsClimbing)
{
// add movement in that direction
AddMovementInput(FVector(0.f, -1.f, 0.f), Value);
}
}
void AGameDevTVJamCharacter::TouchStarted(const ETouchIndex::Type FingerIndex, const FVector Location)
{
// jump on any touch
if (bIsClimbing)
{
bIsClimbing = false;
bIsClimbingLedge = true;
}
else if (!bIsEncumbered)
{
Jump();
}
}
void AGameDevTVJamCharacter::TouchStopped(const ETouchIndex::Type FingerIndex, const FVector Location)
{
StopJumping();
}
void AGameDevTVJamCharacter::PerformCrouch()
{
if (!bIsEncumbered && !GetMovementComponent()->IsFalling())
{
if (bIsClimbing)
{
// Let the player fall from the hanging position
bIsDroppingFromLedge = true;
ClimbingAbility->FinishClimbing();
}
else
{
// Use ACharacter's interface
Crouch();
}
}
}
void AGameDevTVJamCharacter::PerformUnCrouch()
{
// Use ACharacter's interface
UnCrouch();
}
void AGameDevTVJamCharacter::Interact()
{
if (!bIsClimbing)
{
if (UInteractionComponentBase* InteractionToExecute = Cast<UMyGameInstance>(GetGameInstance())->GetLatestInteractionCommand())
{
InteractionToExecute->ExecuteInteraction(this);
}
}
}
void AGameDevTVJamCharacter::StopInteracting()
{
if (UInteractionComponentBase* InteractionToExecute = Cast<UMyGameInstance>(GetGameInstance())->GetLatestInteractionCommand())
{
InteractionToExecute->StopInteraction(this);
}
}
void AGameDevTVJamCharacter::PauseGame()
{
AGameDevTVJamGameMode* GameMode = Cast<AGameDevTVJamGameMode>(UGameplayStatics::GetGameMode(this));
GameMode->PauseGame();
} | [
""
] | |
b8bc38d200f8dbc4b424062ed37b1d9f39ea6c2d | a54e2ee8f7ed398098505342e40c9b74a40a7985 | /OpenMP_NumIntegr/OpenMP_NumIntegr/OpenMP_NumIntegr.cpp | b7b1ee26a3d8db366584c39fd1ad029b1fd4f583 | [] | no_license | olikomarov/CuncurrentProgramming | 39f00ff9b643c7dc266eae779d8871729d9e6956 | 3b101060b85ae2c8bdc494d82cabdd2bcbad67df | refs/heads/master | 2020-04-07T05:36:20.186541 | 2018-12-31T16:38:57 | 2018-12-31T16:38:57 | 158,102,552 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,577 | cpp | #include <stdio.h>
#include <conio.h>
#include <iostream>
#include <iomanip>
#include <omp.h>
#include <list>
#include <utility>
#include <exception>
using namespace std;
struct Result
{
double timestamp, area;
};
double f(const double x);
const Result method_rectangle(const double, const double, const double, const int);
int main()
{
const short maxThreads = 10;
short method;
double x1, x2, dx;
cout << fixed << setprecision(8) << endl;
try
{
while (true)
{
cout << " x1: ";
cin >> x1;
cout << " x2: ";
cin >> x2;
cout << " dx: ";
cin >> dx;
list<pair<short, Result>> results;
for (int i = 0; i < maxThreads; i++)
{
Result result= method_rectangle(x1, x2, dx, i + 1);
pair<short, Result> s_result(i + 1, result);
results.push_back(s_result);
}
cout << endl << " Results:" << endl;
for (auto & result : results)
{
cout << " Threads: " << result.first;
cout << ", timestamp: " << result.second.timestamp;
cout << ", area: " << result.second.area << endl;
}
cout << endl;
}
}
catch (exception & e)
{
cout << e.what() << endl;
}
cin.get();
return 0;
}
const Result method_rectangle(const double x1, const double x2, const double dx, const int nThreads)
{
const int N = static_cast<int>((x2 - x1) / dx);
double now = omp_get_wtime();
double s = 0;
#pragma omp parallel for num_threads(nThreads) reduction(+: s)
for (int i = 1; i <= N; i++) s += f(x1 + i * dx);
s *= dx;
return { omp_get_wtime() - now, s };
}
double f(const double x)
{
return sin(x);
} | [
"[email protected]"
] | |
19770e81fdf4f96667f86897cf783e8ff9ed7f69 | 6c18626c9bce92960a632d5fa9fde3764b3c1be5 | /database-struct/链表/链表/普通单链表.cpp | 63e276dc1941f7ab9a1c2da8d388677504c3cc36 | [] | no_license | 520MianXiangDuiXiang520/C | 992242f55f7ab5e912dfa9063a85e1be0cec0451 | cb771bf1948e72d1b8161b7b06765971b7cc6cee | refs/heads/master | 2020-04-08T04:09:57.016559 | 2019-01-07T04:51:16 | 2019-01-07T04:51:16 | 159,005,573 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,249 | cpp | /*普通单链表的创建 creat() */
/*输出单链表中个节点的值 display() */
/*在单链表中查找第i个节点的值 find() */
/*插入 add() */
/*删除 dele() */
#include<stdio.h>
#include<stdlib.h>
typedef struct link{
int info;
link *next;
}link;
/*建立一个空的单链表*/
link *none()
{
return NULL;
}
/*前插法创建单链表*/
link * creat_q()
{
link *head,*s;
int info,num,i;
i = 0;
head = NULL;
printf("\n请输入要创建的单链表的节点数:\n");
scanf("%d", &num);
printf("\n请输入单链表节点! 反向!!\n");
while (i<num)
{
scanf("%d", &info);
s = (link*)malloc(sizeof(link));
s->info = info;
s->next = head;
head = s;
i++;
}
return head;
}
/*后插法创建单链表*/
link * creat_h()
{
link *head, *s,*p=NULL;
int info, num, i;
i = 0;
head = NULL;
printf("\n请输入要创建的单链表的节点数:\n");
scanf("%d", &num);
printf("\n请输入单链表节点! 正向!!\n");
while (i < num)
{
scanf("%d", &info);
s = (link*)malloc(sizeof(link));
s->info = info;
if (head == NULL)
{
head = s;
}
else
{
p->next = s;
}
p = s;
if (p != NULL)
p->next = NULL;
i++;
}
return head;
}
/*输出*/
void display(link *head)
{
link *p;
p = head;//定义一个副本,输出相当于删除,故使用副本进行
if (!p)
{
printf("\n空链表!\n");
}
else
{
printf("\n单链表为:\n");
while (p)
{
printf("%d->", p->info);
p = p->next;
}
}
}
link * find(link * head,int i)
{
link * p;
p = head;
int count = 0;
while (count != i)
{
p = p->next;
count++;
}
return p;
}
//插入
link * add(link * head)
{
link * p;
link * s;
int i;
printf("\n请输入要插入的位置:");
scanf("%d", &i);
p = find(head, i);
printf("\n请输入要插入的值:\n");
int info;
scanf("%d", &info);
s = (link*)malloc(sizeof(link));
s->info = info;
if (i == 0)
{
s->next = head;
head = s;
}
else
{
s->next = p->next;
p->next = s;
}
return head;
}
//删除
link * dele(link * head)
{
link * p;
printf("\n请输入要删除的值的位置:");
int i = scanf("%d", &i);
p = find(head, i-1);
if (i == 0)
{
head = head->next;
}
else
{
p->next = p->next->next;
}
return head;
}
link * dele_info(link * head)
{
link * p=NULL;
link * s=head;
printf("\n请输入你要i删除的值:");
int info;
scanf("%d", &info);
while (s&&s->info != info)
{
p = s;
s = s->next;
}
if (s)
{
if (!p)
head = head->next;
else
p->next = s->next;
free(s);
}
return head;
}
//change
link * change(link * head)
{
int change;
printf("\n请输入你要修改的值:");
scanf("%d", &change);
printf("\n请输入改正值:");
int tur;
scanf("%d", &tur);
link * p = head;
while (p&&p->info != change)
{
p = p->next;
}
if (p)
{
p->info = tur;
}
return head;
}
int main()
{
link *head;
link * p;
int i;
head=creat_h();
display(head);
printf("\n请输入要查找的位置:");
scanf("%d", &i);
link * w=find(head,i);
printf("\n您要查找的位置上的值为:%d\n", w->info);
head=add(head);
display(head);
head = dele_info(head);
display(head);
head = change(head);
display(head);
system("pause");
return 0;
} | [
"[email protected]"
] | |
9372ab017561f58564eb5ff0d515e9785f977825 | daffb5f31e4f2e1690f4725fad5df9f2382416e3 | /Template/FFT_2D.h | 132a166e329dbde3c350db5a56357371522fd3ce | [] | no_license | cuom1999/CP | 1ad159819fedf21a94c102d7089d12d22bb6bfa2 | 4e37e0d35c91545b3d916bfa1de5076a18f29a75 | refs/heads/master | 2023-06-02T01:57:00.252932 | 2021-06-21T03:41:34 | 2021-06-21T03:41:34 | 242,620,572 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,235 | h | typedef complex<double> base;
namespace FFT_2D {
vector<int> inv_fft;
vector<base> roots;
void preCalcFFT(int n, bool inv) {
inv_fft.resize(n);
int j = 0;
for(int i=1; i<n; i++)
{
int bit = (n >> 1);
while(j >= bit)
{
j -= bit;
bit >>= 1;
}
j += bit;
inv_fft[i] = j;
}
roots.resize(n / 2);
double ang = 2 * acos(-1) / n * (inv ? -1 : 1);
for(int i=0; i<n/2; i++)
{
roots[i] = base(cos(ang * i), sin(ang * i));
}
}
void fft(vector<base> &a, bool inv)
{
int n = a.size();
for(int i=1; i<n; i++)
{
if(i < inv_fft[i]) swap(a[i], a[inv_fft[i]]);
}
for(int i=2; i<=n; i<<=1)
{
int step = n / i;
for(int j=0; j<n; j+=i)
{
for(int k=0; k<i/2; k++)
{
base u = a[j+k], v = a[j+k+i/2] * roots[step * k];
a[j+k] = u+v;
a[j+k+i/2] = u-v;
}
}
}
if(inv) for(int i=0; i<n; i++) a[i] /= n;
}
void fft2D(vector<vector<base>> &a, bool inv) {
// fft rows
preCalcFFT(a[0].size(), inv);
for (int _row = 0; _row < a.size(); _row++) {
fft(a[_row], inv);
}
// fft columns
preCalcFFT(a.size(), inv);
for (int _col = 0; _col < a[0].size(); _col++) {
vector<base> tmp;
for (int i = 0; i < a.size(); i++) {
tmp.push_back(a[i][_col]);
}
fft(tmp, inv);
for (int i = 0; i < a.size(); i++) {
a[i][_col] = tmp[i];
}
}
}
vector<vector<base>> multiply(vector<vector<base>> &v, vector<vector<base>> &w)
{
int _row = 1;
while (_row < v.size() + w.size()) _row <<= 1;
vector<vector<base>> fv(_row), fw(_row);
int _colv = 1, _colw = 1;
for (int i = 0; i <= _row - 1; i++) {
if (i < v.size()) fv[i] = vector<base>(v[i].begin(), v[i].end()), _colv = max(_colv, (int) v[i].size());
if (i < w.size()) fw[i] = vector<base>(w[i].begin(), w[i].end()), _colw = max(_colw, (int) w[i].size());
}
int _col = 1;
while(_col < _colv + _colw) _col <<= 1;
for (int i = 0; i <= _row - 1; i++) {
fv[i].resize(_col);
fw[i].resize(_col);
}
fft2D(fv, 0);
fft2D(fw, 0);
for (int i = 0; i <= _row - 1; i++) {
for (int j = 0; j <= _col - 1; j++) {
fv[i][j] *= fw[i][j];
}
}
fft2D(fv, 1);
return fv;
}
vector<vector<long long>> multiply(vector<vector<long long>> &v, vector<vector<long long>> &w, long long mod)
{
int _row = 1, _colv = 1, _colw = 1, _col = 1;
for (int i = 0; i < v.size(); i++) _colv = max(_colv, (int) v[i].size());
for (int i = 0; i < w.size(); i++) _colw = max(_colw, (int) w[i].size());
while (_row < v.size() + w.size()) _row <<= 1;
while (_col < _colw + _colv) _col <<= 1;
vector<vector<base>> v1(_row), v2(_row), r1(_row), r2(_row);
for (int i = 0; i <= _row - 1; i++) {
v1[i].resize(_col);
r1[i].resize(_col);
v2[i].resize(_col);
r2[i].resize(_col);
}
for (int i = 0; i < v.size(); i++) {
for (int j = 0; j < v[i].size(); j++) {
v1[i][j] = base(v[i][j] >> 15, v[i][j] & 32767);
}
}
for (int i = 0; i < w.size(); i++) {
for (int j = 0; j < w[i].size(); j++) {
v2[i][j] = base(w[i][j] >> 15, w[i][j] & 32767);
}
}
fft2D(v1, 0);
fft2D(v2, 0);
// multiply 2 ffts
for(int i=0; i<_row; i++)
{
for (int j = 0; j < _col; j++) {
int i1 = (i ? (_row - i) : i);
int j1 = (j ? (_col - j) : j);
base ans1 = (v1[i][j] + conj(v1[i1][j1])) * base(0.5, 0);
base ans2 = (v1[i][j] - conj(v1[i1][j1])) * base(0, -0.5);
base ans3 = (v2[i][j] + conj(v2[i1][j1])) * base(0.5, 0);
base ans4 = (v2[i][j] - conj(v2[i1][j1])) * base(0, -0.5);
r1[i][j] = (ans1 * ans3) + (ans1 * ans4) * base(0, 1);
r2[i][j] = (ans2 * ans3) + (ans2 * ans4) * base(0, 1);
}
}
fft2D(r1, 1);
fft2D(r2, 1);
_col = _colv + _colw - 1;
_row = v.size() + w.size() - 1;
vector<vector<long long>> ret(_row);
for(int i=0; i<_row; i++)
{
ret[i].resize(_col);
for (int j = 0; j < _col; j++) {
long long av = (long long)round(r1[i][j].real());
long long bv = (long long)round(r1[i][j].imag()) + (long long)round(r2[i][j].real());
long long cv = (long long)round(r2[i][j].imag());
av %= mod, bv %= mod, cv %= mod;
ret[i][j] = (av << 30) + (bv << 15) + cv;
ret[i][j] = (ret[i][j] % mod + mod) % mod;
}
}
return ret;
}
}
| [
"[email protected]"
] | |
ddbc6c0862ac2669bfad6f046136e173b95b1825 | 77958210b82b9dd8ec38431156901c01afafff71 | /GTEngine/Source/Graphics/GteDirectionalLightTextureEffect.cpp | 1a6d736e612aa524aa3e4fb01996cea29631a6e6 | [] | no_license | spockthegray/gtengine | b0e6d73eb84c6ea01595da49052832a69b623203 | 2115fbced08e716aa2146530369fdcfb29c8dfbe | refs/heads/master | 2021-09-09T17:27:02.553547 | 2018-03-18T13:35:47 | 2018-03-18T13:35:47 | 125,728,146 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,396 | cpp | // David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2018
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// File Version: 3.0.0 (2016/06/19)
#include <GTEnginePCH.h>
#include <Graphics/GteDirectionalLightTextureEffect.h>
using namespace gte;
DirectionalLightTextureEffect::DirectionalLightTextureEffect(std::shared_ptr<ProgramFactory> const& factory,
BufferUpdater const& updater, std::shared_ptr<Material> const& material,
std::shared_ptr<Lighting> const& lighting, std::shared_ptr<LightCameraGeometry> const& geometry,
std::shared_ptr<Texture2> const& texture, SamplerState::Filter filter, SamplerState::Mode mode0,
SamplerState::Mode mode1)
:
LightingEffect(factory, updater, msVSSource, msPSSource, material, lighting, geometry),
mTexture(texture)
{
mSampler = std::make_shared<SamplerState>();
mSampler->filter = filter;
mSampler->mode[0] = mode0;
mSampler->mode[1] = mode1;
mMaterialConstant = std::make_shared<ConstantBuffer>(sizeof(InternalMaterial), true);
UpdateMaterialConstant();
mLightingConstant = std::make_shared<ConstantBuffer>(sizeof(InternalLighting), true);
UpdateLightingConstant();
mGeometryConstant = std::make_shared<ConstantBuffer>(sizeof(InternalGeometry), true);
UpdateGeometryConstant();
mProgram->GetPShader()->Set("Material", mMaterialConstant);
mProgram->GetPShader()->Set("Lighting", mLightingConstant);
mProgram->GetPShader()->Set("LightCameraGeometry", mGeometryConstant);
#if defined(GTE_DEV_OPENGL)
mProgram->GetPShader()->Set("baseSampler", mTexture);
#else
mProgram->GetPShader()->Set("baseTexture", mTexture);
#endif
mProgram->GetPShader()->Set("baseSampler", mSampler);
}
void DirectionalLightTextureEffect::UpdateMaterialConstant()
{
InternalMaterial* internalMaterial = mMaterialConstant->Get<InternalMaterial>();
internalMaterial->emissive = mMaterial->emissive;
internalMaterial->ambient = mMaterial->ambient;
internalMaterial->diffuse = mMaterial->diffuse;
internalMaterial->specular = mMaterial->specular;
LightingEffect::UpdateMaterialConstant();
}
void DirectionalLightTextureEffect::UpdateLightingConstant()
{
InternalLighting* internalLighting = mLightingConstant->Get<InternalLighting>();
internalLighting->ambient = mLighting->ambient;
internalLighting->diffuse = mLighting->diffuse;
internalLighting->specular = mLighting->specular;
internalLighting->attenuation = mLighting->attenuation;
LightingEffect::UpdateLightingConstant();
}
void DirectionalLightTextureEffect::UpdateGeometryConstant()
{
InternalGeometry* internalGeometry = mGeometryConstant->Get<InternalGeometry>();
internalGeometry->lightModelDirection = mGeometry->lightModelDirection;
internalGeometry->cameraModelPosition = mGeometry->cameraModelPosition;
LightingEffect::UpdateGeometryConstant();
}
std::string const DirectionalLightTextureEffect::msGLSLVSSource =
"uniform PVWMatrix\n"
"{\n"
" mat4 pvwMatrix;\n"
"};\n"
"\n"
"layout(location = 0) in vec3 modelPosition;\n"
"layout(location = 1) in vec3 modelNormal;\n"
"layout(location = 2) in vec2 modelTCoord;\n"
"\n"
"layout(location = 0) out vec3 vertexPosition;\n"
"layout(location = 1) out vec3 vertexNormal;\n"
"layout(location = 2) out vec2 vertexTCoord;\n"
"\n"
"void main()\n"
"{\n"
" vertexPosition = modelPosition;\n"
" vertexNormal = modelNormal;\n"
" vertexTCoord = modelTCoord;\n"
"#if GTE_USE_MAT_VEC\n"
" gl_Position = pvwMatrix * vec4(modelPosition, 1.0f);\n"
"#else\n"
" gl_Position = vec4(modelPosition, 1.0f) * pvwMatrix;\n"
"#endif\n"
"}\n";
std::string const DirectionalLightTextureEffect::msGLSLPSSource =
GetShaderSourceLitFunctionGLSL() +
"uniform Material\n"
"{\n"
" vec4 materialEmissive;\n"
" vec4 materialAmbient;\n"
" vec4 materialDiffuse;\n"
" vec4 materialSpecular;\n"
"};\n"
"\n"
"uniform Lighting\n"
"{\n"
" vec4 lightingAmbient;\n"
" vec4 lightingDiffuse;\n"
" vec4 lightingSpecular;\n"
" vec4 lightingAttenuation;\n"
"};\n"
"\n"
"uniform LightCameraGeometry\n"
"{\n"
" vec4 lightModelDirection;\n"
" vec4 cameraModelPosition;\n"
"};\n"
"\n"
"uniform sampler2D baseSampler;\n"
"\n"
"layout(location = 0) in vec3 vertexPosition;\n"
"layout(location = 1) in vec3 vertexNormal;\n"
"layout(location = 2) in vec2 vertexTCoord;\n"
"\n"
"layout(location = 0) out vec4 pixelColor0;\n"
"\n"
"void main()\n"
"{\n"
" vec3 normal = normalize(vertexNormal);\n"
" float NDotL = -dot(normal, lightModelDirection.xyz);\n"
" vec3 viewVector = normalize(cameraModelPosition.xyz - vertexPosition);\n"
" vec3 halfVector = normalize(viewVector - lightModelDirection.xyz);\n"
" float NDotH = dot(normal, halfVector);\n"
" vec4 lighting = lit(NDotL, NDotH, materialSpecular.a);\n"
" vec3 lightingColor = materialAmbient.rgb * lightingAmbient.rgb +\n"
" lighting.y * materialDiffuse.rgb * lightingDiffuse.rgb +\n"
" lighting.z * materialSpecular.rgb * lightingSpecular.rgb;\n"
"\n"
" vec4 textureColor = texture(baseSampler, vertexTCoord);\n"
"\n"
" vec3 color = lightingColor * textureColor.rgb;\n"
" pixelColor0.rgb = materialEmissive.rgb + lightingAttenuation.w * color;\n"
" pixelColor0.a = materialDiffuse.a * textureColor.a;\n"
"}\n";
std::string const DirectionalLightTextureEffect::msHLSLSource =
"cbuffer PVWMatrix\n"
"{\n"
" float4x4 pvwMatrix;\n"
"};\n"
"\n"
"struct VS_INPUT\n"
"{\n"
" float3 modelPosition : POSITION;\n"
" float3 modelNormal : NORMAL;\n"
" float2 modelTCoord : TEXCOORD0;\n"
"};\n"
"\n"
"struct VS_OUTPUT\n"
"{\n"
" float3 vertexPosition : TEXCOORD0;\n"
" float3 vertexNormal : TEXCOORD1;\n"
" float2 vertexTCoord : TEXCOORD2;\n"
" float4 clipPosition : SV_POSITION;\n"
"};\n"
"\n"
"VS_OUTPUT VSMain(VS_INPUT input)\n"
"{\n"
" VS_OUTPUT output;\n"
"\n"
" output.vertexPosition = input.modelPosition;\n"
" output.vertexNormal = input.modelNormal;\n"
" output.vertexTCoord = input.modelTCoord;\n"
"#if GTE_USE_MAT_VEC\n"
" output.clipPosition = mul(pvwMatrix, float4(input.modelPosition, 1.0f));\n"
"#else\n"
" output.clipPosition = mul(float4(input.modelPosition, 1.0f), pvwMatrix);\n"
"#endif\n"
" return output;\n"
"}\n"
"\n"
"cbuffer Material\n"
"{\n"
" float4 materialEmissive;\n"
" float4 materialAmbient;\n"
" float4 materialDiffuse;\n"
" float4 materialSpecular;\n"
"};\n"
"\n"
"cbuffer Lighting\n"
"{\n"
" float4 lightingAmbient;\n"
" float4 lightingDiffuse;\n"
" float4 lightingSpecular;\n"
" float4 lightingAttenuation;\n"
"};\n"
"\n"
"cbuffer LightCameraGeometry\n"
"{\n"
" float4 lightModelDirection;\n"
" float4 cameraModelPosition;\n"
"};\n"
"\n"
"Texture2D<float4> baseTexture;\n"
"SamplerState baseSampler;\n"
"\n"
"struct PS_INPUT\n"
"{\n"
" float3 vertexPosition : TEXCOORD0;\n"
" float3 vertexNormal : TEXCOORD1;\n"
" float2 vertexTCoord : TEXCOORD2;\n"
"};\n"
"\n"
"struct PS_OUTPUT\n"
"{\n"
" float4 pixelColor0 : SV_TARGET0;\n"
"};\n"
"\n"
"PS_OUTPUT PSMain(PS_INPUT input)\n"
"{\n"
" PS_OUTPUT output;\n"
"\n"
" float3 normal = normalize(input.vertexNormal);\n"
" float NDotL = -dot(normal, lightModelDirection.xyz);\n"
" float3 viewVector = normalize(cameraModelPosition.xyz - input.vertexPosition);\n"
" float3 halfVector = normalize(viewVector - lightModelDirection.xyz);\n"
" float NDotH = dot(normal, halfVector);\n"
" float4 lighting = lit(NDotL, NDotH, materialSpecular.a);\n"
" float3 lightingColor = materialAmbient.rgb * lightingAmbient.rgb +\n"
" lighting.y * materialDiffuse.rgb * lightingDiffuse.rgb +\n"
" lighting.z * materialSpecular.rgb * lightingSpecular.rgb;\n"
"\n"
" float4 textureColor = baseTexture.Sample(baseSampler, input.vertexTCoord);\n"
"\n"
" float3 color = lightingColor * textureColor.rgb;\n"
" output.pixelColor0.rgb = materialEmissive.rgb + lightingAttenuation.w * color;\n"
" output.pixelColor0.a = materialDiffuse.a * textureColor.a;\n"
" return output;\n"
"}\n";
std::string const* DirectionalLightTextureEffect::msVSSource[] =
{
&msGLSLVSSource,
&msHLSLSource
};
std::string const* DirectionalLightTextureEffect::msPSSource[] =
{
&msGLSLPSSource,
&msHLSLSource
};
| [
"[email protected]"
] | |
a502b3f55fb813e2adc4101111f45d5411ea1e42 | 5af910371e4763fe4d1d9519fec12c0e2ad14188 | /class/herramientas_proyecto/tabla_sprites.cpp | d6297624cc1094db1a208d48f555ef1d545a0bd8 | [
"Unlicense"
] | permissive | TheMarlboroMan/recomposed-platformer | c329c2b7ab04939c89b9c2d9a1851a29f0f099a9 | 2b2e2a7a659e1571dedbadf981fc1707be72b4b2 | refs/heads/master | 2022-10-04T09:38:33.400114 | 2022-09-13T07:27:28 | 2022-09-13T07:27:28 | 119,906,270 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,387 | cpp | #include "tabla_sprites.h"
#include <class/lector_txt.h>
#include <source/string_utilidades.h>
Tabla_sprites::Tabla_sprites(const std::string& ruta)
{
cargar(ruta);
}
Tabla_sprites::Tabla_sprites()
{
}
const Frame_sprites& Tabla_sprites::obtener(unsigned int indice) const
{
return mapa.at(indice);
}
Frame_sprites Tabla_sprites::obtener(unsigned int indice)
{
if(mapa.count(indice)) return mapa[indice];
else return Frame_sprites();
}
void Tabla_sprites::cargar(const std::string& ruta)
{
Herramientas_proyecto::Lector_txt L(ruta, '#');
if(!L)
{
LOG<<"ERROR: Para Tabla_sprites no se ha podido abrir el archivo "<<ruta<<std::endl;
}
else
{
std::string linea;
const char separador='\t';
while(true)
{
linea=L.leer_linea();
if(!L) break;
std::vector<std::string> valores=Herramientas_proyecto::explotar(linea, separador);
if(valores.size()==7)
{
Frame_sprites f;
unsigned int indice=std::atoi(valores[0].c_str());
f.x=std::atoi(valores[1].c_str());
f.y=std::atoi(valores[2].c_str());
f.w=std::atoi(valores[3].c_str());
f.h=std::atoi(valores[4].c_str());
f.desp_x=std::atoi(valores[5].c_str());
f.desp_y=std::atoi(valores[6].c_str());
mapa[indice]=f;
}
else
{
LOG<<"ERROR: En tabla sprites, la línea "<<L.obtener_numero_linea()<<" no está bien formada. Ignorando"<<std::endl;
}
}
}
}
| [
"[email protected]"
] | |
534c6160d88f37fd72bf0146c6f8314cc0df33d0 | aab3ae5bb8ce591d29599f51f5fb4cd9c5b05f38 | /SourceCode/Physics/Support/BSP.cpp | 822eae925e40c35e22938cf5767679aefb7527d7 | [] | no_license | S-V/Lollipop | b720ef749e599deaf3fbf48b1e883338dcb573c3 | eca4bfe6115437dc87f638af54a69de09956cbfb | refs/heads/master | 2022-02-09T04:59:17.474909 | 2022-01-25T20:20:20 | 2022-01-25T20:20:20 | 43,964,835 | 11 | 1 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 19,342 | cpp | /*
=============================================================================
File: BSP.cpp
Desc:
=============================================================================
*/
#include <Physics_PCH.h>
#pragma hdrstop
#include <Physics.h>
#include <Physics/Collide/Shape/pxShape_Convex.h>
#include <Physics/Collide/Shape/pxShape_Sphere.h>
#include <Physics/Support/BSP.h>
#include <Physics/Support/pxUtilities.h>
enum { MAX_TRACE_PLANES = 32 };
typedef TStaticList<Plane3D,MAX_TRACE_PLANES> PlaneStack;
// keep 1/8 unit away to keep the position valid before network snapping
// and to avoid various numeric issues
//#define SURFACE_CLIP_EPSILON (0.125)
#define SURFACE_CLIP_EPSILON (1/32.0f)
FORCEINLINE
F4 CalcAabbEffectiveRadius( const Vec3D& boxHalfSize, const Plane3D& plane )
{
return
mxFabs( boxHalfSize[0] * plane.Normal()[0] ) +
mxFabs( boxHalfSize[1] * plane.Normal()[1] ) +
mxFabs( boxHalfSize[2] * plane.Normal()[2] );
}
/*
-----------------------------------------------------------------------------
BSP_Tree
-----------------------------------------------------------------------------
*/
BSP_Tree::BSP_Tree()
: m_nodes(EMemHeap::HeapPhysics)
, m_planes(EMemHeap::HeapPhysics)
{
}
#if MX_EDITOR
typedef TList< idFixedWinding > PolygonList;
/*
-----------------------------------------------------------------------------
SBspStats
-----------------------------------------------------------------------------
*/
SBspStats::SBspStats()
{
this->Reset();
}
void SBspStats::Reset()
{
ZERO_OUT( *this );
m_beginTimeMS = mxGetMilliseconds();
}
void SBspStats::Stop()
{
m_elapsedTimeMS = mxGetMilliseconds() - m_beginTimeMS;
}
void SBspStats::Print()
{
DBGOUT( "\n=== BSP statistics ========\n" );
DBGOUT( "Num. Polys(Begin): %d\n", m_numOrigPolygons );
//DBGOUT( "Num. Polys(End): %d\n", m_numPolygons );
DBGOUT( "Num. Splits: %d\n", m_numSplits );
DBGOUT( "Num. Inner Nodes: %d\n", m_numInternalNodes );
DBGOUT( "Num. Solid Leaves: %d\n", m_numSolidLeaves );
DBGOUT( "Num. Empty Leaves: %d\n", m_numEmptyLeaves );
//DBGOUT( "Tree Depth: %d\n", depth );
DBGOUT( "Time elapsed: %d msec\n", m_elapsedTimeMS );
DBGOUT( "==== End ====================\n" );
}
static
EPolyStatus F_ClassifyPolygon(
const Plane3D& plane,
const Vec3D* verts, const UINT numVerts,
const FLOAT epsilon = 0.013f )
{
UINT numPointsInFront = 0;
UINT numPointsInBack = 0;
UINT numPointsOnPlane = 0;
for( UINT iVertex = 0; iVertex < numVerts; iVertex++ )
{
const Vec3D& point = verts[ iVertex ];
const EPlaneSide ePlaneSide = plane.Side( point, epsilon );
if( ePlaneSide == EPlaneSide::PLANESIDE_FRONT )
{
numPointsInFront++;
}
if( ePlaneSide == EPlaneSide::PLANESIDE_BACK )
{
numPointsInBack++;
}
if( ePlaneSide == EPlaneSide::PLANESIDE_ON )
{
numPointsOnPlane++;
}
}
if( numVerts == numPointsInFront ) {
return Poly_Front;
}
if( numVerts == numPointsInBack ) {
return Poly_Back;
}
if( numVerts == numPointsOnPlane ) {
return Poly_Coplanar;
}
return Poly_Split;
}
/*
The selection of the base polygon and the partitioning plane
is the crucial part of the BSP-tree construction. Depend-
ing on criteria for the base polygon selection different BSP-
trees can be obtained. In our work we use two different ap-
proaches: "naive" selection, where the polygon is randomly
selected from the polygon list, and "optimized" selection.
The optimization means using selection criteria that allow
for obtaining a tree with the following properties:
• Minimization of polygon splitting operations to reduce
the total number of nodes and the number of operations
in the function evaluation
• Minimization of computational errors during the function
evaluation and BSP-tree construction;
• Balancing the BSP tree, i.e., minimization of difference
between positive and negative list for the minimization of
the depth of the tree.
*/
// function for picking an optimal partitioning plane.
// we have two conflicting goals:
// 1) keep the tree balanced
// 2) avoid splitting the polygons
// and avoid introducing new partitioning planes
//
static
UINT F_FindBestSplitterIndex( const PolygonList& polygons
, const SBuildBspArgs& options = SBuildBspArgs() )
{
INT numFrontFaces = 0;
INT numBackFaces = 0;
INT numSplitFaces = 0;
INT numCoplanarFaces = 0;
UINT bestSplitter = 0;
FLOAT bestScore = 1e6f; // the less value the better
for(UINT iPolyA = 0;
iPolyA < polygons.Num();
iPolyA++)
{
// select potential splitter
const idFixedWinding& polyA = polygons[ iPolyA ];
// potential splitting plane
Plane3D planeA;
polyA.GetPlane( planeA );
// test other polygons against the potential splitter
for(UINT iPolyB = 0;
iPolyB < polygons.Num();
iPolyB++)
{
if( iPolyA == iPolyB ) {
continue;
}
const idFixedWinding& polyB = polygons[ iPolyB ];
// evaluate heuristic cost and select the best candidate
const int planeSide = polyB.PlaneSide( planeA, options.planeEpsilon );
switch( planeSide )
{
case PLANESIDE_FRONT : numFrontFaces++; break;
case PLANESIDE_BACK : numBackFaces++; break;
case PLANESIDE_ON : numCoplanarFaces++; break;
case PLANESIDE_CROSS : numSplitFaces++; break;
default: Unreachable;
}
// diff == 0 => tree is perfectly balanced
const UINT diff = Abs<INT>( numFrontFaces - numBackFaces );
F4 score = (diff * options.balanceVsCuts)
+ (numSplitFaces * options.splitCost) * (1.0f - options.balanceVsCuts)
;
if( planeA.Type() < PLANETYPE_TRUEAXIAL )
{
score *= 0.8f; // axial is better
}
// A smaller score will yield a better tree.
if( score < bestScore )
{
bestScore = score;
bestSplitter = iPolyA;
}
}//for all tested polygons
}//for all potential splitters
return bestSplitter;
}
#define NORMAL_EPSILON 0.00001f
#define DIST_EPSILON 0.01f
static
UINT GetPlaneIndex(
BSP_Tree & tree, const Plane3D& plane,
const float normalEps = NORMAL_EPSILON,
const float distEps = DIST_EPSILON
)
{
Plane3D normalizedPlane = plane;
normalizedPlane.FixDegeneracies( distEps );
Assert( distEps <= 0.125f );
const UINT numExistingPlanes = tree.m_planes.Num();
for( UINT iPlane = 0; iPlane < numExistingPlanes; iPlane++ )
{
const Plane3D existingPlane = tree.m_planes[ iPlane ];
if( existingPlane.Compare( normalizedPlane, normalEps, distEps ) )
{
return iPlane;
}
}
const UINT newPlaneIndex = numExistingPlanes;
Assert( newPlaneIndex <= BSP_MAX_PLANES );
tree.m_planes.Add( normalizedPlane );
return newPlaneIndex;
}
// returns index of the splitting plane
//
static
UINT PartitionPolygons(
BSP_Tree & tree,
PolygonList & polygons,
PolygonList & frontPolys,
PolygonList & backPolys,
const FLOAT epsilon = 0.13f
)
{
// select the best partitioner
SBuildBspArgs settings;
// we don't need polygons for collision detection
settings.splitCost = 0;
settings.balanceVsCuts = 1;
settings.planeEpsilon = 0.1f;
const UINT bestSplitter = F_FindBestSplitterIndex( polygons, settings );
Plane3D partitioner;
polygons[ bestSplitter ].GetPlane( partitioner );
//polygons.RemoveAt_Fast( bestSplitter );
// partition the list
for( UINT iPoly = 0; iPoly < polygons.Num(); iPoly++ )
{
if( iPoly == bestSplitter ) {
continue;
}
idFixedWinding & polygon = polygons[ iPoly ];
idFixedWinding backPoly;
const int planeSide = polygon.Split( &backPoly, partitioner, epsilon );
if( planeSide == PLANESIDE_FRONT )
{
frontPolys.Add( polygon );
continue;
}
if( planeSide == PLANESIDE_BACK )
{
backPolys.Add( polygon );
continue;
}
if( planeSide == PLANESIDE_CROSS )
{
frontPolys.Add( polygon );
backPolys.Add( backPoly );
tree.m_stats.m_numSplits++;
continue;
}
Assert( planeSide == PLANESIDE_ON );
// continue
}
return GetPlaneIndex( tree, partitioner );
}
#if 0
static
void Dbg_ValidateNode_R( BSP_Tree & tree, UINT nodeIndex )
{
const BspNode& node = tree.m_nodes[ nodeIndex ];
if( node.IsInternal() )
{
Assert( tree.m_planes.IsValidIndex( node.node.plane ) );
Assert( tree.m_nodes.IsValidIndex( node.node.pos ) );
Assert( tree.m_nodes.IsValidIndex( node.node.neg ) );
Dbg_ValidateNode_R( tree, node.node.pos );
Dbg_ValidateNode_R( tree, node.node.neg );
}
}
static
void Dbg_DumpNode_R( BSP_Tree & tree, UINT nodeIndex, UINT depth = 0 )
{
const BspNode& node = tree.m_nodes[ nodeIndex ];
for(UINT i=0; i<depth; i++)
{
DBGOUT(" ");
}
if( node.IsInternal() )
{
DBGOUT("Inner node@%u: plane=%u, neg=%u, pos=%u\n"
,nodeIndex,(UINT)node.node.plane,(UINT)node.node.neg,(UINT)node.node.pos
);
Dbg_DumpNode_R( tree, node.node.pos, depth+1 );
Dbg_DumpNode_R( tree, node.node.neg, depth+1 );
}
else
{
DBGOUT("%s leaf@%u\n",
node.type==BN_Solid ? "Solid" : "Empty", nodeIndex);
}
}
#endif
static
inline
UINT F_AllocateNode( BSP_Tree & tree )
{
const UINT newNodeIndex = tree.m_nodes.Num();
Assert( newNodeIndex <= BSP_MAX_NODES );
BspNode & newNode = tree.m_nodes.Add();
#if MX_DEBUG
MemSet(&newNode,-1,sizeof BspNode);
//DBGOUT("! creating node %u\n",newNodeIndex);
#endif //MX_DEBUG
return newNodeIndex;
}
static
FORCEINLINE
BspNode* GetNodeByIndex( BSP_Tree & tree, UINT nodeIndex )
{
return &tree.m_nodes[ nodeIndex ];
}
static
inline
UINT F_NewInternalNode( BSP_Tree & tree )
{
const UINT newNodeIndex = F_AllocateNode( tree );
BspNode & newNode = tree.m_nodes[ newNodeIndex ];
{
(void)newNode;
//newNode.type = BN_Polys;
}
tree.m_stats.m_numInternalNodes++;
return newNodeIndex;
}
// returns index of new node
//
static
inline
UINT F_NewEmptyLeaf( BSP_Tree & tree )
{
tree.m_stats.m_numEmptyLeaves++;
#if 0
const UINT newNodeIndex = F_AllocateNode( tree );
BspNode & newNode = tree.m_nodes[ newNodeIndex ];
{
newNode.type = BN_Empty;
}
#else
const UINT newNodeIndex = BSP_EMPTY_LEAF;
#endif
return newNodeIndex;
}
// returns index of new node
//
static
inline
UINT F_NewSolidLeaf( BSP_Tree & tree )
{
tree.m_stats.m_numSolidLeaves++;
#if 0
const UINT newNodeIndex = F_AllocateNode( tree );
BspNode & newNode = tree.m_nodes[ newNodeIndex ];
{
newNode.type = BN_Solid;
}
#else
const UINT newNodeIndex = BSP_SOLID_LEAF;
#endif
return newNodeIndex;
}
// returns index of new node
//
static
UINT BuildTree_R( BSP_Tree & tree, PolygonList & polygons )
{
Assert( polygons.NonEmpty() );
// allocate a new internal node
const UINT newNodeIndex = F_NewInternalNode( tree );
// partition the list
PolygonList frontPolys(EMemHeap::HeapTemp);
PolygonList backPolys(EMemHeap::HeapTemp);
const UINT splitPlane = PartitionPolygons( tree, polygons, frontPolys, backPolys );
GetNodeByIndex( tree, newNodeIndex )->node.plane = splitPlane;
// recursively process children
if( frontPolys.Num() )
{
GetNodeByIndex( tree, newNodeIndex )->node.pos = BuildTree_R( tree, frontPolys );
}
else
{
GetNodeByIndex( tree, newNodeIndex )->node.pos = F_NewEmptyLeaf( tree );
}
if( backPolys.Num() )
{
GetNodeByIndex( tree, newNodeIndex )->node.neg = BuildTree_R( tree, backPolys );
}
else
{
GetNodeByIndex( tree, newNodeIndex )->node.neg = F_NewSolidLeaf( tree );
}
return newNodeIndex;
}
struct pxPolygonCollector : pxTriangleIndexCallback
{
PolygonList & m_polygons;
pxPolygonCollector( PolygonList & polygons )
: m_polygons( polygons )
{
}
virtual void ProcessTriangle( const Vec3D& p0, const Vec3D& p1, const Vec3D& p2 ) override
{
idFixedWinding & newPolygon = m_polygons.Add();
// need to reverse winding (different culling in D3D11 renderer and id's winding)
#if 0
newPolygon.AddPoint( p0 );
newPolygon.AddPoint( p1 );
newPolygon.AddPoint( p2 );
#else
newPolygon.AddPoint( p2 );
newPolygon.AddPoint( p1 );
newPolygon.AddPoint( p0 );
#endif
}
};
void BSP_Tree::Build( pxTriangleMeshInterface* triangleMesh )
{
PolygonList polygons(EMemHeap::HeapTemp);
pxPolygonCollector collectPolys( polygons );
triangleMesh->ProcessAllTriangles( &collectPolys );
m_stats.Reset();
m_stats.m_numOrigPolygons = polygons.Num();
BuildTree_R( *this, polygons );
//Dbg_ValidateNode_R( *this, BSP_ROOT_NODE );
m_nodes.Shrink();
m_planes.Shrink();
m_stats.Stop();
m_stats.Print();
DBGOUT("BSP tree: memory used = %u (%u planes)\n",
(UINT)this->GetMemoryUsed(),m_planes.Num());
}
#endif // MX_EDITOR
struct SOverlapArgs
{
UINT prevNode; // index of parent (internal) BSP node
UINT currNode; // index of current BSP node
pxVec3 closestPt;
F4 minDist; // distance from the convex to the previous node's plane
public:
SOverlapArgs()
{
currNode = BSP_ROOT_NODE;
prevNode = INDEX_NONE;
closestPt.SetAll(PX_LARGE_FLOAT);
minDist = PX_LARGE_FLOAT;
}
};
bool BSP_Tree::PointInSolid( const Vec3D& point ) const
{
TStaticList<UINT,BSP_MAX_DEPTH> nodeStack;
nodeStack.Add( BSP_ROOT_NODE );
while( true )
{
const UINT nodeId = nodeStack.GetLast();
nodeStack.PopBack();
if( nodeId == BSP_EMPTY_LEAF ) {
return false;
}
if( nodeId == BSP_SOLID_LEAF ) {
return true;
}
const BspNode& node = m_nodes[ nodeId ];
const Plane3D& plane = m_planes[ node.node.plane ];
const F4 dist = plane.Distance( point );
if( dist >= 0.0f )
{
nodeStack.Add( node.node.pos );
continue;
}
else//if( dist < 0 )
{
nodeStack.Add( node.node.neg );
continue;
}
}
}
F4 BSP_Tree::DistanceToPoint( const Vec3D& point ) const
{
TStaticList<UINT,BSP_MAX_DEPTH> nodeStack;
nodeStack.Add( BSP_ROOT_NODE );
TStaticList<F4,BSP_MAX_DEPTH> distStack;
while( true )
{
const UINT nodeId = nodeStack.GetLast();
nodeStack.PopBack();
MX_UNDONE("this is incorrect, find distance to convex hull");
// if point is outside the brush
if( nodeId == BSP_EMPTY_LEAF ) {
// we need to find the closest point
// on the convex hull formed by intersection of planes
Unimplemented;
return 0.0f;
}
// if point is inside the brush
if( nodeId == BSP_SOLID_LEAF ) {
// take minimum distance from point to planes
F4 minDist = -PX_LARGE_FLOAT;
for( UINT i = 0; i < distStack.Num(); i++ )
{
// take maximum because the point is behind all planes
minDist = maxf( minDist, distStack[i] );
}
return minDist;
}
const BspNode& node = m_nodes[ nodeId ];
const Plane3D& plane = m_planes[ node.node.plane ];
const F4 dist = plane.Distance( point );
distStack.Add( dist );
if( dist >= 0.0f )
{
nodeStack.Add( node.node.pos );
continue;
}
else//if( dist < 0 )
{
nodeStack.Add( node.node.neg );
continue;
}
}
Unreachable;
return PX_LARGE_FLOAT;
}
struct STraceIn
{
Vec3D start;
Vec3D end;
F4 radius;
UINT currNode;
};
struct STraceOut
{
F4 fraction;
};
struct STraceWorks
{
//Vec3D start;
//Vec3D end;
//F4 radius;
AABB boxsize;// size of the box being swept through the model
Vec3D extents;// half size of the box
Vec3D normal;// surface normal at impact, transformed to world space
F4 planeDist;
F4 fraction; // time completed, 1.0 = didn't hit anything
bool startsolid;
bool allsolid;
public:
STraceWorks()
{
// fill in a default trace
//radius = 0;
boxsize.SetZero();
extents.SetZero();
normal.SetZero();
planeDist = 0.0f;
// assume it goes the entire distance until shown otherwise
fraction = 1;
startsolid = false;
allsolid = false;
}
};
enum ETraceResult
{
Trace_Empty,
Trace_Solid,
Trace_Done,
};
enum {
PlaneSide_Front = 0,
PlaneSide_Back = 1,
};
// NOTE: portions of code taken and modified from quake/darkplaces engine sources
// this is not 100% correct (esp. edge collisions) (should use beveling planes)
//
static
ETraceResult TraceBox_R( STraceWorks & tw, const BSP_Tree& t, /*const*/ UINT nodeId, const Vec3D& start, const Vec3D& end, const F4 f1, const F4 f2 )
{
L_Start:
// check if this is a leaf node
if( BSP_EMPTY_LEAF == nodeId )
{
return Trace_Empty;
}
if( BSP_SOLID_LEAF == nodeId )
{
return Trace_Solid;
}
const BspNode& node = t.m_nodes[ nodeId ];
Plane3D plane = t.m_planes[ node.node.plane ];
// calculate offset for the size of the box and
// adjust the plane distance appropriately for mins/maxs
plane.d -= CalcAabbEffectiveRadius( tw.extents, plane );
// distance from plane for trace start and end
const F4 d1 = plane.Distance( start );
const F4 d2 = plane.Distance( end );
// see which sides we need to consider
int planeSide; // 0 - check front side first, 1 - check back side first
// if start point in air
if( d1 >= 0.0f )
{
if( d2 >= 0.0f )// endpoint in air
{
// completely in front of plane
nodeId = node.node.pos;
goto L_Start;
}
// d1 >= 0 && d2 < 0
planeSide = PlaneSide_Front;
}
else // d1 < 0
{
// start point in solid
if( d2 < 0.0f )// endpoint in solid
{
// completely behind plane
nodeId = node.node.neg;
goto L_Start;
}
// endpoint in air
// d1 < 0 && d2 >= 0
planeSide = PlaneSide_Back;
}
// intersecting the plane, split the line segment into two
// and check both sides, starting from 'planeSide'
const F4 midf = clampf( d1 / (d1 - d2), f1, f2 );
Assert( midf >= 0.0f && midf <= 1.0f );
const Vec3D midp = start + (end - start) * midf;
// we're interested in case where 'start' is in empty space
// and 'end' is in solid region.
//
ETraceResult ret;
// check the nearest side first
ret = TraceBox_R( tw, t, node.node.kids[planeSide], start, midp, f1, midf );
// if this side is not empty, return what it is (solid or done)
if( ret != Trace_Empty ) {
return ret;
}
// good, 'start' point is in empty space
ret = TraceBox_R( tw, t, node.node.kids[planeSide^1], midp, end, midf, f2 );
// if other side is not solid, return what it is (empty or done)
if( ret != Trace_Solid ) {
return ret;
}
// now 'end' point is in solid space
// front is air and back is solid, this is the impact point
#if 0
tw.normal = plane.Normal();
tw.planeDist = plane.d;
tw.fraction = midf;
#else
// calculate the return fraction which is nudged off the surface a bit
const float real_midf = clampf( (d1 - DIST_EPSILON) / (d1 - d2), 0.0f, 1.0f );
tw.normal = plane.Normal();
tw.planeDist = plane.d;
tw.fraction = real_midf;
#endif
return Trace_Done;
}
void BSP_Tree::TraceAABB(
const AABB& boxsize, const Vec3D& start, const Vec3D& end,
FLOAT & fraction, Vec3D & normal
) const
{
STraceWorks tw;
tw.boxsize = boxsize;
tw.extents = boxsize.GetHalfSize();
TraceBox_R( tw, *this, BSP_ROOT_NODE, start, end, 0, 1 );
fraction = tw.fraction;
normal = tw.normal;
}
pxVec3 BSP_Tree::CalcSupportingVertex( const pxVec3& dir ) const
{
UNDONE;
return pxVec3();
}
SizeT BSP_Tree::GetMemoryUsed() const
{
return m_nodes.GetAllocatedMemory()
+ m_planes.GetAllocatedMemory()
+ sizeof(*this)
;
}
void BSP_Tree::Serialize( mxArchive& archive )
{
archive && m_nodes;
archive && m_planes;
//@todo: optimize the tree during saving/loading?
if( archive.IsReading() )
{
//
}
}
// @todo:
// weld coplanar polygon faces
//
NO_EMPTY_FILE
//--------------------------------------------------------------//
// End Of File. //
//--------------------------------------------------------------//
| [
"[email protected]"
] | |
c354f48ed99e95b7f55d93cfedb3bf69278876c5 | 933f154b469178fb9c3dd648bc985960c19290db | /initial/111_MinDepthOfBinaryTree/Solution.cpp | 60a016d93105ce6252c4e0f157a2dca40a307466 | [] | no_license | zywangzy/LeetCode | c5468ea8b108e9c1dec125fb07a5841348693f96 | df2cba28ed47938073ab1ffc984af158e3de7611 | refs/heads/master | 2021-09-29T13:39:58.151078 | 2018-11-24T22:35:04 | 2018-11-24T22:35:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 785 | cpp | #include "../IOLib.hpp"
using namespace std;
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int minDepth(TreeNode* root) {
if(root == NULL) return 0;
if(root->left == NULL || root->right == NULL){
if(root->left != NULL) return minDepth(root->left)+1;
if(root->right != NULL) return minDepth(root->right)+1;
}
return min(minDepth(root->left), minDepth(root->right)) + 1;
}
};
int main(){
TreeNode* root = readBinaryTree();
Solution solution;
cout << "The minimum depth of this tree is " << solution.minDepth(root) << "." << endl;
return 0;
} | [
"[email protected]"
] | |
abb0546a19321df5418d26c2ac48176d225a217d | a3a363c4a5cd807147d88db04439f25bc2444033 | /poseidon/src/singletons/magic_daemon.hpp | 2382d3e1f7a747a2a6a92cd1ca72f9543cf55bf1 | [
"Apache-2.0"
] | permissive | nail-lian/poseidon | 2fb93a3d2b85f74e090cc08259832fe44eab106a | 2110e7fd3069ba3d3570a264d5a7d9f57853f201 | refs/heads/master | 2020-04-17T16:57:06.746847 | 2018-10-29T02:49:13 | 2018-10-29T02:49:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 443 | hpp | // 这个文件是 Poseidon 服务器应用程序框架的一部分。
// Copyleft 2014 - 2018, LH_Mouse. All wrongs reserved.
#ifndef POSEIDON_SYSTEM_MAGIC_DAEMON_HPP_
#define POSEIDON_SYSTEM_MAGIC_DAEMON_HPP_
#include <cstddef>
namespace Poseidon {
class Magic_daemon {
private:
Magic_daemon();
public:
static void start();
static void stop();
static const char * guess_mime_type(const void *data, std::size_t size);
};
}
#endif
| [
"[email protected]"
] | |
0b1f4ff8b872db93f5c0bc97a85a61ac35f6a430 | c629cdda40748f35341e9da53faa210c90b21f89 | /src/batteries/seq/inner_reduce.hpp | fc8c7988cd61ecf5cea7cbbd15e9b667599abd02 | [
"Apache-2.0"
] | permissive | tonyastolfi/batteries | e2c9b590e620b78e03449893206ac79900d340a1 | acea1f4e10e9f7fbf97c3ab3cf30766b19130ece | refs/heads/main | 2023-08-20T01:56:24.076281 | 2023-02-06T19:32:33 | 2023-02-06T19:32:33 | 228,197,783 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,216 | hpp | //######=###=##=#=#=#=#=#==#==#====#+==#+==============+==+==+==+=+==+=+=+=+=+=+=+
// Copyright 2022 Anthony Paul Astolfi
//
#pragma once
#ifndef BATTERIES_SEQ_INNER_REDUCE_HPP
#define BATTERIES_SEQ_INNER_REDUCE_HPP
#include <batteries/config.hpp>
//
#include <batteries/optional.hpp>
#include <batteries/seq/reduce.hpp>
#include <batteries/seq/seq_item.hpp>
#include <batteries/utility.hpp>
#include <type_traits>
#include <utility>
namespace batt {
namespace seq {
//==#==========+==+=+=++=+++++++++++-+-+--+----- --- -- - - - -
// inner_reduce
//
template <typename ReduceFn>
struct InnerReduceBinder {
ReduceFn reduce_fn;
};
template <typename ReduceFn>
InnerReduceBinder<ReduceFn> inner_reduce(ReduceFn&& reduce_fn)
{
return {BATT_FORWARD(reduce_fn)};
}
template <typename Seq, typename ReduceFn>
[[nodiscard]] Optional<std::decay_t<SeqItem<Seq>>> operator|(Seq&& seq, InnerReduceBinder<ReduceFn> binder)
{
Optional<std::decay_t<SeqItem<Seq>>> state = seq.next();
if (!state) {
return state;
}
return BATT_FORWARD(seq) | reduce(std::move(*state), BATT_FORWARD(binder.reduce_fn));
}
} // namespace seq
} // namespace batt
#endif // BATTERIES_SEQ_INNER_REDUCE_HPP
| [
"[email protected]"
] | |
45bc42cf40087e23e86ecb976d4190b9e551397b | b951d03be7c20bd4d9d923bbf6cc551e8a074f37 | /display/concrete/DataIndexWrapperDisplay.h | 81e4c56d1da263ba2eb755a8ba2b0dff46aef45e | [
"BSD-3-Clause"
] | permissive | michaelmurphybrown/MinVR2 | 1cefd97fa014ed6a1f81d6200cc637b3aa64758e | 517c8a345efebb068f298cba02b6b799634135a8 | refs/heads/master | 2021-01-15T16:04:30.870858 | 2016-03-01T23:12:29 | 2016-03-01T23:12:29 | 51,666,198 | 0 | 0 | null | 2016-03-01T23:12:50 | 2016-02-13T21:15:27 | C++ | UTF-8 | C++ | false | false | 857 | h | /*
* Copyright Regents of the University of Minnesota, 2016. This software is released under the following license: http://opensource.org/licenses/GPL-2.0
* Source code originally developed at the University of Minnesota Interactive Visualization Lab (http://ivlab.cs.umn.edu).
*
* Code author(s):
* Dan Orban (dtorban)
*/
#ifndef DATAINDEXWRAPPERDISPLAY_H_
#define DATAINDEXWRAPPERDISPLAY_H_
#include "display/concrete/BaseDisplayDevice.h"
namespace MinVR {
class DataIndexWrapperDisplay : public BaseDisplayDevice {
public:
DataIndexWrapperDisplay(VRDisplayDevice* device, VRDataIndex* index);
virtual ~DataIndexWrapperDisplay();
void finishRendering();
protected:
void startRendering(const VRRenderer& renderer, VRRenderState& state);
private:
VRDataIndex* index;
};
} /* namespace MinVR */
#endif /* DATAINDEXWRAPPERDISPLAY_H_ */
| [
"[email protected]"
] | |
0935a6fe5f0baecbf2cd76fd9a54de1b9c0f6423 | 2656294d1e697f43291d40ea25487cc6dc1de3b0 | /Parser.h | 740c6b79aafdc0da27c0c8ae5f398946b5dbe7db | [] | no_license | valkovsa/Console-expression-calc-RPN- | 2b03bd047f5f65bffde9abc746e370fea1720904 | f3c6ca5e6f3b691b3e86836bc8ea833b02aaafd6 | refs/heads/master | 2021-01-09T06:27:40.887616 | 2017-02-05T11:52:45 | 2017-02-05T11:52:45 | 80,989,478 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 2,310 | h | #pragma once
#include "Header.h"
class Parser
{
private:
bool delim(char c)
{
if (c == ' ')
return true;
else
return false;
}
bool is_op(char c)
{
if (c == '+' || c == '-' || c == '*' || c == '/' || c == '%')
return true;
else
return false;
}
int priority(char op)
{
if (op == '+' || op == '-')
return 1;
else if (op == '*' || op == '/' || op == '%')
return 2;
else
return -1;
}
void process_op(stack<int>& st, char op)
{
int r = st.top(); // Правый операнд
st.pop();
int l = st.top(); // Левый операнд
st.pop();
switch (op)
{
case '+':
st.push(l + r);
break;
case '-':
st.push(l - r);
break;
case '*':
st.push(l * r);
break;
case '/':
st.push(l / r);
break;
case '%':
st.push(l % r);
break;
}
}
public:
Parser()
{
}
int calc(string& s)
{
stack<int> st; // Стек с операндами
stack<char> op; // Стек с операторами
for (int i = 0; i < s.length(); ++i)
{
if (!delim(s[i]))
{
if (s[i] == '(')
op.push('(');
else if (s[i] == ')') // Если найдена закрывающая скобка, просматриваем выражение до открывающей скобки
{
while (op.top() != '(')
{
process_op(st, op.top());
op.pop();
}
op.pop(); // Убираем открывающую скобку
}
else if (is_op(s[i])) // Если найден оператор
{
char curop = s[i];
while (!op.empty() && priority(op.top()) >= priority(s[i])) // Если приоритет найденного оператора больше либо равен сохраненному, проводим вычисления
{
process_op(st, op.top());
op.pop();
}
op.push(curop);
}
else
{
string operand;
while (i < s.length() && isalnum(s[i]))
{
operand += s[i++];
}
--i;
if (isdigit(operand[0]))
{
st.push(atoi(operand.c_str()));
}
}
}
}
while (!op.empty())
{
process_op(st, op.top());
op.pop();
}
return st.top();
}
};
| [
"[email protected]"
] | |
985b6e3224dff19bcb16d14686d01d02189083e9 | e68cb3d4fa89451d7cc93f1829561a81648767de | /daylight_server/server.cpp | fc7242d0ced4e448c143b3141346ce669b3ada9d | [] | no_license | jandro1111/tp5 | 0ca8b6d4a2c510fe88ce8df77b30560e66391481 | eebb9d297da116411d5c346efc3c22501935b166 | refs/heads/master | 2023-04-10T00:14:06.147039 | 2021-04-14T23:55:28 | 2021-04-14T23:55:28 | 356,311,720 | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 5,300 | cpp | #include "server.h"
#include <iostream>
#include <string>
#include <boost\bind.hpp>
using boost::asio::ip::tcp;
std::string make_response_string(std::string aux);
AsyncDaytimeServer::AsyncDaytimeServer(boost::asio::io_context& io_context)
: context_(io_context),
acceptor_(io_context, tcp::endpoint(tcp::v4(), 80)),//ese de ahi es el numero del puerto
socket_(io_context)
{
}
AsyncDaytimeServer::~AsyncDaytimeServer()
{
}
void AsyncDaytimeServer::start()
{
if (socket_.is_open())
{
socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both);
socket_.close();
}
start_waiting_connection();
}
void AsyncDaytimeServer::start_waiting_connection()
{
std::cout << "start_waiting_connection()" << std::endl;
if (socket_.is_open())
{
std::cout << "Error: Can't accept new connection from an open socket" << std::endl;
return;
}
acceptor_.async_accept( //solo recibe socket que va a administrar la nueva conexion y el callback
socket_,
boost::bind(
&AsyncDaytimeServer::connection_received_cb,
this,
boost::asio::placeholders::error
)
);
}
void AsyncDaytimeServer::start_answering(std::string aux)
{
std::cout << "start_answering()" << std::endl;
msg = make_response_string(aux);
boost::asio::async_write(//make_daytime_string()
socket_,
boost::asio::buffer(msg),
boost::bind(
&AsyncDaytimeServer::response_sent_cb,
this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred
)
);
socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both);
socket_.close();
}
void AsyncDaytimeServer::connection_received_cb(const boost::system::error_code& error)//aca hacemos lo de buscar e interpretar el mensaje
{
std::ofstream handler;//abro/creo si no esta/ el archivo para poner lo que reciba del server
handler.open("handler.txt", std::ios::trunc);//borro lo que habia antes
for (;;)//recibo lo del cliente y lo interpreto
{
boost::array<char, 128> buf;
boost::system::error_code error;
size_t len = socket_.read_some(boost::asio::buffer(buf), error);
if (error == boost::asio::error::eof)
break; // Connection closed cleanly by peer.
else if (error)
throw boost::system::system_error(error); // Some other error.
std::cout.write(buf.data(), len);
handler.write(buf.data(), len);//guardo en el archivo que se llama handler, para interpretar mas adelante
handler.close();
break;
}
using namespace std;
string nombreArchivo = "handler.txt";
ifstream archivo(nombreArchivo.c_str());
string linea;
string aux = "";
// Obtener línea de archivo, y almacenar contenido en "linea"
while (getline(archivo, linea)) {
// Lo vamos imprimiendo
bool fin = false;
bool ini = false;
for (int i = 0; fin == false; ++i) {//aislo el archivo a buscar
if (linea[i] == '/'||ini==true) {//encontre el inicio
if (ini == false) {
}
else {
aux += linea[i];
}
ini = true;
}
if (ini == true) {
if (linea[i] == ' ') {//encontre el final
fin = true;
}
}
}
if (fin == true) {
break;
}
}
handler.close();
//en aux tengo el path a buscar
std::cout << "connection_received_cb()" << std::endl;
if (!error) {
start_answering(aux);
start_waiting_connection();
}
else {
std::cout << error.message() << std::endl;
}
}
void AsyncDaytimeServer::response_sent_cb(const boost::system::error_code& error,
size_t bytes_sent)
{
std::cout << "response_sent_cb()" << std::endl;
if (!error) {
std::cout << "Response sent. " << bytes_sent << " bytes." << std::endl;
}
}
std::string make_response_string(std::string aux)//aca armamos el mensaje en aux tengo el path a buscar
{
#pragma warning(disable : 4996)
std::string res;
std::ifstream info(aux);
std::ifstream archivo(aux.c_str());
std::string linea;
if (info.is_open()) {
std::cout << "lo encontre" << std::endl;//200 found
res += "HTTP/1.1 200 OK";
res += "\r\n";
res += "Date: Date(Ej : Tue, 04 Sep 2018 18 : 21 : 19 GMT)";
res += "\r\n";
res += "Cache-Control : public, max - age = 30";
res += "\r\n";
res += "Expires:Date + 30s(Ej : Tue, 04 Sep 2018 18 : 21 : 49 GMT)";
res += "\r\n";
res += "Content-Length : 1";
res += "\r\n";
res += "Content-Type : text / html; charset = iso - 8859 - 1";
res += "\r\n";
res += "\r\n";
while (getline(archivo, linea)) {
// Lo vamos imprimiendo
res += linea;
}
res += "\r\n";
res += "\r\n";
}
else {
std::cout << "no lo encontre" << std::endl;//404 not found
res += "HTTP/1.1 404 Not Found";
res += "\r\n";
res += "Date: Date(Ej : Tue, 04 Sep 2018 18 : 21 : 19 GMT)";
res += "\r\n";
res += "Cache - Control : public, max - age = 30";
res += "\r\n";
res += "Expires : Date + 30s(Ej : Tue, 04 Sep 2018 18 : 21 : 49 GMT)";
res += "\r\n";
res += "Content - Length : 0";
res += "\r\n";
res += "Content - Type : text / html; charset = iso - 8859 - 1";
res += "\r\n";//404
}
std::cout << aux << std::endl;
using namespace std; // For time_t, time and ctime;
time_t now = time(0);
return res;
}
/*
HTTP/1.1 200 OK
Date: Date (Ej: Tue, 04 Sep 2018 18:21:19 GMT)
Location: 127.0.0.1/path/filename
Cache-Control: max-age=30
Expires: Date + 30s (Ej: Tue, 04 Sep 2018 18:21:49 GMT)
Content-Length: 1
Content-Type: text/html; charset=iso-8859-1
a
*/ | [
"[email protected]"
] | |
3b96c499db119a401a909912e84ba48b322dc5e4 | 3d6aa8fe2a687ec4da38c72b2ef490ea429d1f0f | /example/snippets/juliet1.1/89_CWE762_Mismatched_Memory_Management_Routines__new_free_struct_21.cpp | f303add7f6b235a8d1c4e61748ce289abebc1afb | [] | no_license | SEDS/mangrove | 116579ad3c70ee5a0b8ae67920752514851bad17 | a7c0be6268ac87ee60a69aa9664d7c5d39aae499 | refs/heads/master | 2022-12-11T12:03:52.927574 | 2020-07-30T15:39:42 | 2020-07-30T15:39:42 | 291,787,979 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 256 | cpp | #include "std_testcase.h"
namespace CWE762_Mismatched_Memory_Management_Routines__new_free_struct_21
{
#ifndef OMITGOOD
static void goodB2G1_sink(twoints * data)
{
{
free(data);
}
data = new twoints;
goodB2G1_sink(data);
}
#endif
}
| [
"[email protected]"
] | |
d7ea052b9475ba48d0544f4bffddcf04eb27d0be | 91a882547e393d4c4946a6c2c99186b5f72122dd | /Source/XPSP1/NT/sdktools/checksym/symbolverification.cpp | 2d329f83ed23a063851dafcda5630acaabf57c01 | [] | no_license | IAmAnubhavSaini/cryptoAlgorithm-nt5src | 94f9b46f101b983954ac6e453d0cf8d02aa76fc7 | d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2 | refs/heads/master | 2023-09-02T10:14:14.795579 | 2021-11-20T13:47:06 | 2021-11-20T13:47:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,261 | cpp | //+-------------------------------------------------------------------------
//
// Microsoft Windows
//
// Copyright (C) Microsoft Corporation, 1999 - 2000
//
// File: symbolverification.cpp
//
//--------------------------------------------------------------------------
// SymbolVerification.cpp: implementation of the CSymbolVerification class.
//
//////////////////////////////////////////////////////////////////////
#ifndef NO_STRICT
#ifndef STRICT
#define STRICT 1
#endif
#endif /* NO_STRICT */
#include <WINDOWS.H>
#include <TCHAR.H>
#include <STDIO.H>
#include "globals.h"
#include "SymbolVerification.h"
#include "ModuleInfo.h"
#include "UtilityFunctions.h"
#pragma warning (push)
#pragma warning ( disable : 4710)
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CSymbolVerification::CSymbolVerification()
{
m_fComInitialized = false;
m_fSQLServerConnectionAttempted = false;
m_fSQLServerConnectionInitialized = false;
// SQL2 - mjl 12/14/99
m_fSQLServerConnectionAttempted2 = false;
m_fSQLServerConnectionInitialized2 = false;
// Initialize ADO Connection Object to NULL
m_lpConnectionPointer = NULL;
m_lpConnectionPointer2 = NULL; // SQL2 - mjl 12/14/99
}
CSymbolVerification::~CSymbolVerification()
{
if (SQLServerConnectionInitialized())
{
TerminateSQLServerConnection();
}
if (SQLServerConnectionInitialized2())
{
TerminateSQLServerConnection2();
}
if (m_fComInitialized)
::CoUninitialize();
}
bool CSymbolVerification::Initialize()
{
HRESULT hr = S_OK;
// Initialize COM
hr = ::CoInitialize(NULL);
if (FAILED(hr))
{
_tprintf(TEXT("Failed Initializing COM!\n"));
return false;
}
// Com is initialized!
m_fComInitialized = true;
return true;
}
bool CSymbolVerification::InitializeSQLServerConnection(LPTSTR tszSQLServerName)
{
HRESULT hr = S_OK;
TCHAR tszConnectionString[256];
m_fSQLServerConnectionAttempted = true;
_tprintf(TEXT("\nAttempting connection to SQL Server [%s]..."), tszSQLServerName);
// Compose the Connection String
// ie. "driver={SQL Server};server=<servername>;database=Symbols"
_tcscpy(tszConnectionString, TEXT("driver={SQL Server};server="));
_tcscat(tszConnectionString, tszSQLServerName);
_tcscat(tszConnectionString, TEXT(";uid=GUEST;pwd=guest;database=Symbols"));
try
{
// Okay, we need a BSTR
_bstr_t bstrConnectionString( tszConnectionString );
// Okay, let's try and actually create this Connection Pointer...
hr = m_lpConnectionPointer.CreateInstance( __uuidof( Connection ) );
if (FAILED(hr))
goto error;
// Now, let's use the Connection Pointer object to actually get connected...
hr = m_lpConnectionPointer->Open( bstrConnectionString, "", "", -1);
if (FAILED(hr))
goto error;
// Now, let's create a RecordSet for use later...
hr = m_lpRecordSetPointer.CreateInstance( __uuidof( Recordset ) );
if (FAILED(hr))
goto error;
m_fSQLServerConnectionInitialized = true;
_tprintf(TEXT("SUCCESS!\n\n"));
}
catch (_com_error &e )
{
_tprintf( TEXT("FAILURE!\n\n") );
DumpCOMException(e);
goto error;
}
catch (...)
{
_tprintf( TEXT("FAILURE!\n\n") );
_tprintf( TEXT("Caught an exception of unknown type\n" ) );
goto error;
}
goto cleanup;
error:
if (m_lpConnectionPointer)
m_lpConnectionPointer = NULL;
_tprintf(TEXT("\nFAILURE Attempting SQL Server Connection! Error = 0x%x\n"), hr);
switch (hr)
{
case E_NOINTERFACE:
case REGDB_E_CLASSNOTREG:
_tprintf(TEXT("\nThe most likely reason for this is that your system does not have\n"));
_tprintf(TEXT("the necessary ADO components installed. You should install the\n"));
_tprintf(TEXT("latest Microsoft Data Access Component (MDAC) release available on\n"));
_tprintf(TEXT("http://www.microsoft.com/data/download.htm\n"));
break;
}
cleanup:
return m_fSQLServerConnectionInitialized;
}
void CSymbolVerification::DumpCOMException(_com_error &e)
{
_tprintf( TEXT("\tCode = %08lx\n"), e.Error());
_tprintf( TEXT("\tCode meaning = %s\n"), e.ErrorMessage());
_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());
_tprintf( TEXT("\tSource = %s\n"), (LPCSTR) bstrSource);
_tprintf( TEXT("\tDescription = %s\n"), (LPCSTR) bstrDescription);
}
bool CSymbolVerification::TerminateSQLServerConnection()
{
// Free the Connection
if (m_lpConnectionPointer)
m_lpConnectionPointer = NULL;
if (m_lpRecordSetPointer)
m_lpRecordSetPointer = NULL;
m_fSQLServerConnectionInitialized = false;
return true;
}
bool CSymbolVerification::SearchForDBGFileUsingSQLServer(LPTSTR tszPEImageModuleName, DWORD dwPEImageTimeDateStamp, CModuleInfo *lpModuleInfo)
{
HRESULT hr = S_OK;
FieldPtr lpFieldSymbolPath = NULL;
_variant_t vSymbolPath;
wchar_t wszSymbolPath[_MAX_PATH+1];
wchar_t wszReturnedDBGFile[_MAX_FNAME];
wchar_t wszReturnedDBGFileExtension[_MAX_EXT];
TCHAR tszCommandText[256];
TCHAR tszLinkerDate[64]; // Plenty big...
TCHAR tszDBGFileName[_MAX_FNAME];
HANDLE hFileHandle;
_tsplitpath(tszPEImageModuleName, NULL, NULL, tszDBGFileName, NULL);
#ifdef _UNICODE
LPTSTR wszDBGFileName = tszDBGFileName;
#else
wchar_t wszDBGFileName[_MAX_FNAME];
MultiByteToWideChar( CP_ACP,
MB_PRECOMPOSED,
tszDBGFileName,
-1,
wszDBGFileName,
_MAX_FNAME);
#endif
// Compose the Connection String
// ie. "driver={SQL Server};server=<servername>;database=Symbols"
_tcscpy(tszCommandText, TEXT("SELECT FILENAME FROM Symbols WHERE TIMESTAMP = '"));
_stprintf(tszLinkerDate, TEXT("%x"), dwPEImageTimeDateStamp);
_tcscat(tszCommandText, tszLinkerDate);
_tcscat(tszCommandText, TEXT("'"));
try {
_bstr_t bstrCommandText( tszCommandText );
m_lpRecordSetPointer = m_lpConnectionPointer->Execute(bstrCommandText, NULL, adCmdText);
lpFieldSymbolPath = m_lpRecordSetPointer->Fields->GetItem(_variant_t( "FILENAME" ));
#ifdef _DEBUG
_tprintf(TEXT("Searching SQL Server for matching symbol for [%s]\n"), tszPEImageModuleName);
#endif
while (VARIANT_FALSE == m_lpRecordSetPointer->EndOfFile)
{
vSymbolPath.Clear();
vSymbolPath = lpFieldSymbolPath->Value;
wcscpy(wszSymbolPath, vSymbolPath.bstrVal);
_wsplitpath(wszSymbolPath, NULL, NULL, wszReturnedDBGFile, wszReturnedDBGFileExtension);
//
if ( (_wcsicmp(wszReturnedDBGFile, wszDBGFileName) == 0 ) &&
(_wcsicmp(wszReturnedDBGFileExtension, L".DBG") == 0 )
)
{
#ifdef _DEBUG
wprintf(L"Module path = %s\n", wszSymbolPath);
#endif
#ifdef _UNICODE
wchar_t * tszSymbolPath = wszSymbolPath;
#else
char tszSymbolPath[_MAX_PATH+1];
WideCharToMultiByte(CP_ACP,
0,
wszSymbolPath,
-1,
tszSymbolPath,
_MAX_PATH+1,
NULL,
NULL);
#endif
// Okay, let's validate the DBG file we are pointing to...
hFileHandle = CreateFile( tszSymbolPath,
GENERIC_READ,
(FILE_SHARE_READ | FILE_SHARE_WRITE),
NULL,
OPEN_EXISTING,
0,
NULL);
// Does the returned handle look good?
if (hFileHandle != INVALID_HANDLE_VALUE)
{
lpModuleInfo->VerifyDBGFile(hFileHandle, tszSymbolPath, lpModuleInfo);
} else
{
_tprintf(TEXT("\nERROR: Searching for [%s]!\n"), tszSymbolPath);
CUtilityFunctions::PrintMessageString(GetLastError());
}
CloseHandle(hFileHandle);
if (lpModuleInfo->GetDBGSymbolModuleStatus() == CModuleInfo::SymbolModuleStatus::SYMBOL_MATCH)
{
// Cool... it really does match...
hr = m_lpRecordSetPointer->Close();
goto cleanup;
}
}
m_lpRecordSetPointer->MoveNext();
}
hr = m_lpRecordSetPointer->Close();
if (FAILED(hr))
goto error;
}
catch (_com_error &e )
{
_tprintf( TEXT("FAILURE Attempting SQL Server Connection!\n") );
DumpCOMException(e);
goto cleanup;
}
catch (...)
{
_tprintf( TEXT("FAILURE Attempting SQL Server Connection!\n") );
_tprintf( TEXT("Caught an exception of unknown type\n" ) );
goto cleanup;
}
goto cleanup;
error:
TerminateSQLServerConnection();
_tprintf(TEXT("FAILURE Attempting to query the SQL Server!\n"));
cleanup:
return true;
}
/////////////////////////// mjl //////////////////////////////////////////
bool CSymbolVerification::InitializeSQLServerConnection2(LPTSTR tszSQLServerName)
{
HRESULT hr = S_OK;
TCHAR tszConnectionString[256];
m_fSQLServerConnectionAttempted2 = true;
_tprintf(TEXT("\nAttempting connection to SQL Server [%s]..."), tszSQLServerName);
// Compose the Connection String
// ie. "driver={SQL Server};server=<servername>;database=Symbols"
_tcscpy(tszConnectionString, TEXT("driver={SQL Server};server="));
_tcscat(tszConnectionString, tszSQLServerName);
_tcscat(tszConnectionString, TEXT(";uid=GUEST;pwd=guest;database=Symbols2"));
try
{
// Okay, we need a BSTR
_bstr_t bstrConnectionString( tszConnectionString );
// Okay, let's try and actually create this Connection Pointer...
hr = m_lpConnectionPointer2.CreateInstance( __uuidof( Connection ) );
if (FAILED(hr))
goto error;
// Now, let's use the Connection Pointer object to actually get connected...
hr = m_lpConnectionPointer2->Open( bstrConnectionString, "", "", -1);
if (FAILED(hr))
goto error;
// Now, let's create a RecordSet for use later...
hr = m_lpRecordSetPointer2.CreateInstance( __uuidof( Recordset ) );
if (FAILED(hr))
goto error;
_tprintf(TEXT("Complete\n"));
m_fSQLServerConnectionInitialized2 = true;
}
catch (_com_error &e )
{
_tprintf( TEXT("FAILURE Attempting SQL Server Connection!\n") );
DumpCOMException(e);
goto error;
}
catch (...)
{
_tprintf( TEXT("FAILURE Attempting SQL Server Connection!\n") );
_tprintf( TEXT("Caught an exception of unknown type\n" ) );
goto error;
}
goto cleanup;
error:
if (m_lpConnectionPointer2)
m_lpConnectionPointer2 = NULL;
_tprintf(TEXT("\nFAILURE Attempting SQL Server Connection! Error = 0x%x\n"), hr);
switch (hr)
{
case E_NOINTERFACE:
case REGDB_E_CLASSNOTREG:
_tprintf(TEXT("\nThe most likely reason for this is that your system does not have\n"));
_tprintf(TEXT("the necessary ADO components installed. You should install the\n"));
_tprintf(TEXT("latest Microsoft Data Access Component (MDAC) release available on\n"));
_tprintf(TEXT("http://www.microsoft.com/data/download.htm\n"));
break;
}
cleanup:
return m_fSQLServerConnectionInitialized2;
}
bool CSymbolVerification::TerminateSQLServerConnection2()
{
// Free the Connection
if (m_lpConnectionPointer2)
m_lpConnectionPointer2 = NULL;
if (m_lpRecordSetPointer2)
m_lpRecordSetPointer2 = NULL;
m_fSQLServerConnectionInitialized2 = false;
return true;
}
bool CSymbolVerification::SearchForDBGFileUsingSQLServer2(LPTSTR tszPEImageModuleName, DWORD dwPEImageTimeDateStamp, CModuleInfo *lpModuleInfo)
{
HRESULT hr = S_OK;
FieldPtr lpFieldSymbolPath = NULL;
_variant_t vSymbolPath;
_bstr_t sFieldSymbolPath;
wchar_t wszSymbolPath[_MAX_PATH+1];
wchar_t wszReturnedDBGFile[_MAX_FNAME];
wchar_t wszReturnedDBGFileExtension[_MAX_EXT];
TCHAR tszCommandText[512];
TCHAR tszDBGFileName[_MAX_FNAME];
HANDLE hFileHandle;
_tsplitpath(tszPEImageModuleName, NULL, NULL, tszDBGFileName, NULL);
#ifdef _UNICODE
LPTSTR wszDBGFileName = tszDBGFileName;
#else
wchar_t wszDBGFileName[_MAX_FNAME];
MultiByteToWideChar( CP_ACP,
MB_PRECOMPOSED,
tszDBGFileName,
-1,
wszDBGFileName,
_MAX_FNAME);
#endif
// Compose the Query String
_stprintf(tszCommandText, TEXT("SELECT tblDBGModulePaths.DBGModulePath FROM tblDBGModules,tblDBGModulePaths WHERE tblDBGModules.DBGFilename='%s.DBG' AND tblDBGModules.TimeDateStamp='%d' AND tblDBGModules.DBGModuleID = tblDBGModulePaths.DBGModuleID"),tszDBGFileName,dwPEImageTimeDateStamp);
try {
_bstr_t bstrCommandText( tszCommandText );
m_lpRecordSetPointer2 = m_lpConnectionPointer2->Execute(bstrCommandText, NULL, adCmdText);
while ( !m_lpRecordSetPointer2->EndOfFile )
{
vSymbolPath = m_lpRecordSetPointer2->Fields->GetItem("DBGModulePath")->Value;
lpFieldSymbolPath = m_lpRecordSetPointer2->Fields->GetItem(_variant_t( "DBGModulePath" ));
#ifdef _DEBUG
_tprintf(TEXT("Searching SQL Server for matching symbol for [%s]\n"), tszPEImageModuleName);
#endif
vSymbolPath.Clear();
vSymbolPath = lpFieldSymbolPath->Value;
wcscpy(wszSymbolPath, vSymbolPath.bstrVal);
_wsplitpath(wszSymbolPath, NULL, NULL, wszReturnedDBGFile, wszReturnedDBGFileExtension);
//
if ( (_wcsicmp(wszReturnedDBGFile, wszDBGFileName) == 0 ) &&
(_wcsicmp(wszReturnedDBGFileExtension, L".DBG") == 0 )
)
{
#ifdef _DEBUG
wprintf(L"Module path = %s\n", wszSymbolPath);
#endif
#ifdef _UNICODE
wchar_t * tszSymbolPath = wszSymbolPath;
#else
char tszSymbolPath[_MAX_PATH+1];
WideCharToMultiByte(CP_ACP,
0,
wszSymbolPath,
-1,
tszSymbolPath,
_MAX_PATH+1,
NULL,
NULL);
#endif
// Okay, let's validate the DBG file we are pointing to...
hFileHandle = CreateFile( tszSymbolPath,
GENERIC_READ,
(FILE_SHARE_READ | FILE_SHARE_WRITE),
NULL,
OPEN_EXISTING,
0,
NULL);
// Does the returned handle look good?
if (hFileHandle != INVALID_HANDLE_VALUE)
{
lpModuleInfo->VerifyDBGFile(hFileHandle, tszSymbolPath, lpModuleInfo);
} else
{
_tprintf(TEXT("\nERROR: Searching for [%s]!\n"), tszSymbolPath);
CUtilityFunctions::PrintMessageString(GetLastError());
}
CloseHandle(hFileHandle);
if (lpModuleInfo->GetDBGSymbolModuleStatus() == CModuleInfo::SymbolModuleStatus::SYMBOL_MATCH)
{
// Cool... it really does match...
hr = m_lpRecordSetPointer2->Close();
goto cleanup;
}
}
m_lpRecordSetPointer2->MoveNext();
}
hr = m_lpRecordSetPointer2->Close();
if (FAILED(hr))
goto error;
}
catch (_com_error &e )
{
_tprintf( TEXT("FAILURE Attempting SQL Server Connection!\n") );
DumpCOMException(e);
goto cleanup;
}
catch (...)
{
_tprintf( TEXT("FAILURE Attempting SQL Server Connection!\n") );
_tprintf( TEXT("Caught an exception of unknown type\n" ) );
goto cleanup;
}
goto cleanup;
error:
TerminateSQLServerConnection();
_tprintf(TEXT("FAILURE Attempting to query the SQL Server!\n"));
cleanup:
return true;
}
bool CSymbolVerification::SearchForPDBFileUsingSQLServer2(LPTSTR tszPEImageModuleName, DWORD dwPDBSignature, CModuleInfo *lpModuleInfo)
{
HRESULT hr = S_OK;
FieldPtr lpFieldSymbolPath = NULL;
_variant_t vSymbolPath;
_bstr_t sFieldSymbolPath;
wchar_t wszSymbolPath[_MAX_PATH+1];
wchar_t wszReturnedPDBFile[_MAX_FNAME];
wchar_t wszReturnedPDBFileExtension[_MAX_EXT];
TCHAR tszCommandText[512];
TCHAR tszPDBFileName[_MAX_FNAME];
HANDLE hFileHandle;
_tsplitpath(tszPEImageModuleName, NULL, NULL, tszPDBFileName, NULL);
#ifdef _UNICODE
LPTSTR wszPDBFileName = tszPDBFileName;
#else
wchar_t wszPDBFileName[_MAX_FNAME];
MultiByteToWideChar( CP_ACP,
MB_PRECOMPOSED,
tszPDBFileName,
-1,
wszPDBFileName,
_MAX_FNAME);
#endif
// Compose the Query String
_stprintf(tszCommandText, TEXT("SELECT tblPDBModulePaths.PDBModulePath FROM tblPDBModules,tblPDBModulePaths WHERE tblPDBModules.PDBFilename='%s.PDB' AND tblPDBModules.PDBSignature='%d' AND tblPDBModules.PDBModuleID = tblPDBModulePaths.PDBModuleID"),tszPDBFileName,dwPDBSignature);
try {
_bstr_t bstrCommandText( tszCommandText );
m_lpRecordSetPointer2 = m_lpConnectionPointer2->Execute(bstrCommandText, NULL, adCmdText);
while ( !m_lpRecordSetPointer2->EndOfFile )
{
vSymbolPath = m_lpRecordSetPointer2->Fields->GetItem("PDBModulePath")->Value;
lpFieldSymbolPath = m_lpRecordSetPointer2->Fields->GetItem(_variant_t( "PDBModulePath" ));
#ifdef _DEBUG
_tprintf(TEXT("Searching SQL Server for matching symbol for [%s]\n"), tszPEImageModuleName);
#endif
vSymbolPath.Clear();
vSymbolPath = lpFieldSymbolPath->Value;
wcscpy(wszSymbolPath, vSymbolPath.bstrVal);
_wsplitpath(wszSymbolPath, NULL, NULL, wszReturnedPDBFile, wszReturnedPDBFileExtension);
if ( (_wcsicmp(wszReturnedPDBFile, wszPDBFileName) == 0 ) &&
(_wcsicmp(wszReturnedPDBFileExtension, L".PDB") == 0 )
)
{
#ifdef _DEBUG
wprintf(L"Module path = %s\n", wszSymbolPath);
#endif
#ifdef _UNICODE
wchar_t * tszSymbolPath = wszSymbolPath;
#else
char tszSymbolPath[_MAX_PATH+1];
WideCharToMultiByte(CP_ACP,
0,
wszSymbolPath,
-1,
tszSymbolPath,
_MAX_PATH+1,
NULL,
NULL);
#endif
// Okay, let's validate the DBG file we are pointing to...
hFileHandle = CreateFile( tszSymbolPath,
GENERIC_READ,
(FILE_SHARE_READ | FILE_SHARE_WRITE),
NULL,
OPEN_EXISTING,
0,
NULL);
// Does the returned handle look good?
if (hFileHandle != INVALID_HANDLE_VALUE)
{
lpModuleInfo->VerifyPDBFile(hFileHandle, tszSymbolPath, lpModuleInfo);
} else
{
_tprintf(TEXT("\nERROR: Searching for [%s]!\n"), tszSymbolPath);
CUtilityFunctions::PrintMessageString(GetLastError());
}
CloseHandle(hFileHandle);
if (lpModuleInfo->GetPDBSymbolModuleStatus() == CModuleInfo::SymbolModuleStatus::SYMBOL_MATCH)
{
// Cool... it really does match...
hr = m_lpRecordSetPointer2->Close();
goto cleanup;
}
}
m_lpRecordSetPointer2->MoveNext();
}
hr = m_lpRecordSetPointer2->Close();
if (FAILED(hr))
goto error;
}
catch (_com_error &e )
{
_tprintf( TEXT("\nFAILURE Attempting SQL2 Server Connection!\n") );
DumpCOMException(e);
goto cleanup;
}
catch (...)
{
_tprintf( TEXT("FAILURE Attempting SQL2 Server Connection!\n") );
_tprintf( TEXT("Caught an exception of unknown type\n" ) );
goto cleanup;
}
goto cleanup;
error:
TerminateSQLServerConnection2();
_tprintf(TEXT("FAILURE Attempting to query the SQL Server!\n"));
cleanup:
return true;
}
#pragma warning (pop)
| [
"[email protected]"
] | |
71c419350f0585d552bb5e126b5531b265388401 | 027102cc45a255b3e4f818c28c7627487ae01dcb | /examples/UAlbertaBot with StarAlgo/SparCraft/source/GameState.h | 2341bc22fa6cc66c515955715c3d05cd552fc098 | [
"MIT"
] | permissive | Games-and-Simulations/StarAlgo | d5f77be45ecee2d2a0851456a5c8ce8b81cbca0a | ca0bc389db5a698de862ce2d1b14d2ae293e18b8 | refs/heads/master | 2020-04-13T15:14:56.313740 | 2019-01-01T21:29:58 | 2019-01-01T21:29:58 | 163,285,524 | 15 | 3 | MIT | 2018-12-27T11:17:00 | 2018-12-27T11:16:59 | null | UTF-8 | C++ | false | false | 7,061 | h | #pragma once
#include "Common.h"
#include <algorithm>
#include "MoveArray.h"
#include "Hash.h"
#include "Map.hpp"
#include "Unit.h"
#include "GraphViz.hpp"
#include "Array.hpp"
#include "Logger.h"
#include <memory>
typedef std::shared_ptr<SparCraft::Map> MapPtr;
namespace SparCraft
{
class GameState
{
Map * _map;
std::vector<Unit> _units[Constants::Num_Players];
std::vector<int> _unitIndex[Constants::Num_Players];
Array2D<Unit, Constants::Num_Players, Constants::Max_Units> _units2;
Array2D<int, Constants::Num_Players, Constants::Max_Units> _unitIndex2;
Array<Unit, 1> _neutralUnits;
Array<UnitCountType, Constants::Num_Players> _numUnits;
Array<UnitCountType, Constants::Num_Players> _prevNumUnits;
Array<float, Constants::Num_Players> _totalLTD;
Array<float, Constants::Num_Players> _totalSumSQRT;
Array<int, Constants::Num_Players> _numMovements;
Array<int, Constants::Num_Players> _prevHPSum;
TimeType _currentTime;
size_t _maxUnits;
TimeType _sameHPFrames;
// checks to see if the unit array is full before adding a unit to the state
const bool checkFull(const IDType & player) const;
const bool checkUniqueUnitIDs() const;
void performAction(const Action & theMove);
public:
GameState();
GameState(const std::string & filename);
// misc functions
void finishedMoving();
void updateGameTime();
const bool playerDead(const IDType & player) const;
const bool isTerminal() const;
// unit data functions
const size_t numUnits(const IDType & player) const;
const size_t prevNumUnits(const IDType & player) const;
const size_t numNeutralUnits() const;
const size_t closestEnemyUnitDistance(const Unit & unit) const;
// Unit functions
void sortUnits();
void addUnit(const Unit & u);
void addUnit(const BWAPI::UnitType unitType, const IDType playerID, const Position & pos);
void addUnitWithID(const Unit & u);
void addNeutralUnit(const Unit & unit);
const Unit & getUnit(const IDType & player, const UnitCountType & unitIndex) const;
const Unit & getUnitByID(const IDType & unitID) const;
Unit & getUnit(const IDType & player, const UnitCountType & unitIndex);
const Unit & getUnitByID(const IDType & player, const IDType & unitID) const;
Unit & getUnitByID(const IDType & player, const IDType & unitID);
const Unit & getClosestEnemyUnit(const IDType & player, const IDType & unitIndex, bool checkCloaked=false);
const Unit & getClosestOurUnit(const IDType & player, const IDType & unitIndex);
const Unit & getUnitDirect(const IDType & player, const IDType & unit) const;
const Unit & getNeutralUnit(const size_t & u) const;
// game time functions
void setTime(const TimeType & time);
const TimeType getTime() const;
// evaluation functions
const StateEvalScore eval( const IDType & player, const IDType & evalMethod,
const IDType p1Script = PlayerModels::NOKDPS,
const IDType p2Script = PlayerModels::NOKDPS) const;
const ScoreType evalLTD(const IDType & player) const;
const ScoreType evalLTD2(const IDType & player) const;
const ScoreType LTD(const IDType & player) const;
const ScoreType LTD2(const IDType & player) const;
const StateEvalScore evalSim(const IDType & player, const IDType & p1, const IDType & p2) const;
const IDType getEnemy(const IDType & player) const;
// unit hitpoint calculations, needed for LTD2 evaluation
void calculateStartingHealth();
void setTotalLTD(const float & p1, const float & p2);
void setTotalLTD2(const float & p1, const float & p2);
const float & getTotalLTD(const IDType & player) const;
const float & getTotalLTD2(const IDType & player) const;
// move related functions
void generateMoves(MoveArray & moves, const IDType & playerIndex) const;
void makeMoves(const std::vector<Action> & moves);
const int & getNumMovements(const IDType & player) const;
const IDType whoCanMove() const;
const bool bothCanMove() const;
// map-related functions
void setMap(Map * map);
Map * getMap() const;
const bool isWalkable(const Position & pos) const;
const bool isFlyable(const Position & pos) const;
// hashing functions
const HashType calculateHash(const size_t & hashNum) const;
// state i/o functions
void print(int indent = 0) const;
std::string toString() const;
std::string toStringCompact() const;
void write(const std::string & filename) const;
void read(const std::string & filename);
};
}
| [
"[email protected]"
] | |
95fb10a90355e705b11e66918dbbaa10c362c719 | e1700081b3e9fa1c74e6dd903da767a3fdeca7f5 | /libs/geodata/polygon/private/geodatapolygonproxy_displaysetting.h | aa7fa3cba41ee89cae5b94a46a1ef9858e2a0961 | [
"MIT"
] | permissive | i-RIC/prepost-gui | 2fdd727625751e624245c3b9c88ca5aa496674c0 | 8de8a3ef8366adc7d489edcd500a691a44d6fdad | refs/heads/develop_v4 | 2023-08-31T09:10:21.010343 | 2023-08-31T06:54:26 | 2023-08-31T06:54:26 | 67,224,522 | 8 | 12 | MIT | 2023-08-29T23:04:45 | 2016-09-02T13:24:00 | C++ | UTF-8 | C++ | false | false | 633 | h | #ifndef GEODATAPOLYGONPROXY_DISPLAYSETTING_H
#define GEODATAPOLYGONPROXY_DISPLAYSETTING_H
#include "geodatapolygon_displaysetting.h"
#include "../geodatapolygonproxy.h"
#include <misc/boolcontainer.h>
#include <misc/compositecontainer.h>
class GeoDataPolygonProxy::DisplaySetting : public CompositeContainer
{
public:
DisplaySetting();
DisplaySetting(const DisplaySetting& s);
DisplaySetting& operator=(const DisplaySetting& s);
XmlAttributeContainer& operator=(const XmlAttributeContainer& s);
BoolContainer usePreSetting;
GeoDataPolygon::DisplaySetting displaySetting;
};
#endif // GEODATAPOLYGONPROXY_DISPLAYSETTING_H
| [
"[email protected]"
] | |
4ef853182624957acf06ee882e1c5e690ef8d852 | 1d0163d142aa6c64dc7c0e1f5cfa2b6dfa4d538d | /src/patterns.cpp | 5e3a0c24ddf5844aca449ff2e1bb27fdcc9a2703 | [] | no_license | bwlewis/rchk | 9a280f5df8bf153dd15b0b3975117e407e8a216c | bc479a2a3de00af81147567928f116956ab23b1b | refs/heads/master | 2021-05-06T04:55:57.782495 | 2018-04-18T00:49:46 | 2018-04-18T00:49:46 | 115,020,991 | 0 | 0 | null | 2017-12-21T15:37:26 | 2017-12-21T15:37:24 | null | UTF-8 | C++ | false | false | 13,479 | cpp |
#include "patterns.h"
#include <llvm/IR/CallSite.h>
#include <llvm/IR/Constants.h>
#include <llvm/IR/Instructions.h>
#include <llvm/Support/raw_ostream.h>
using namespace llvm;
bool isAllocVectorOfKnownType(Value *inst, unsigned& type) {
CallSite cs(inst);
if (!cs) {
return false;
}
Function *tgt = cs.getCalledFunction();
if (!tgt || tgt->getName() != "Rf_allocVector") {
return false;
}
Value *arg = cs.getArgument(0);
if (!ConstantInt::classof(arg)) {
return false;
}
ConstantInt *ctype = cast<ConstantInt>(arg);
type = ctype->getZExtValue();
return true;
}
bool isCallPassingVar(Value *inst, AllocaInst*& var, std::string& fname) {
CallSite cs(inst);
if (!cs) {
return false;
}
Function *tgt = cs.getCalledFunction();
if (!tgt) {
return false;
}
Value *lval = cs.getArgument(0);
if (!LoadInst::classof(lval)) {
return false;
}
Value *lvar = cast<LoadInst>(lval)->getPointerOperand();
if (!AllocaInst::classof(lvar)) {
return false;
}
var = cast<AllocaInst>(lvar);
fname = tgt->getName();
return true;
}
bool isBitCastOfVar(Value *inst, AllocaInst*& var, Type*& type) {
if (!BitCastInst::classof(inst)) {
return false;
}
BitCastInst* bc = cast<BitCastInst>(inst);
Value *lvar = bc->getOperand(0);
if (!LoadInst::classof(lvar)) {
return false;
}
Value *avar = cast<LoadInst>(lvar)->getPointerOperand();
if (!AllocaInst::classof(avar)) {
return false;
}
var = cast<AllocaInst>(avar);
type = cast<Type>(bc->getDestTy());
return true;
}
// this is useful e.g. for detecting when a variable is stored into the node stack
// isStoreToStructureElement(in, "struct.R_bcstack_t", "union.ieee_double", protectedVar)
bool isStoreToStructureElement(Value *inst, std::string structType, std::string elementType, AllocaInst*& var) {
// [] %431 = load %struct.SEXPREC** %__v__7, align 8, !dbg !152225 ; [#uses=1 type=%struct.SEXPREC*] [debug line = 4610:5]
// %432 = load %struct.R_bcstack_t** %3, align 8, !dbg !152225 ; [#uses=1 type=%struct.R_bcstack_t*] [debug line = 4610:5]
// %433 = getelementptr inbounds %struct.R_bcstack_t* %432, i32 0, i32 1, !dbg !152225 ; [#uses=1 type=%union.ieee_double*] [debug line = 4610:5]
// %434 = bitcast %union.ieee_double* %433 to %struct.SEXPREC**, !dbg !152225 ; [#uses=1 type=%struct.SEXPREC**] [debug line = 4610:5]
// store %struct.SEXPREC* %431, %struct.SEXPREC** %434, align 8, !dbg !152225 ; [debug line = 4610:5]
StoreInst *si = dyn_cast<StoreInst>(inst);
if (!si) {
return false;
}
LoadInst *li = dyn_cast<LoadInst>(si->getValueOperand());
if (!li) {
return false;
}
AllocaInst *pvar = dyn_cast<AllocaInst>(li->getPointerOperand());
if (!pvar) {
return false;
}
BitCastInst *bc = dyn_cast<BitCastInst>(si->getPointerOperand());
if (!bc) {
return false;
}
if (!isPointerToStruct(bc->getSrcTy(), elementType)) {
return false;
}
GetElementPtrInst* gep = dyn_cast<GetElementPtrInst>(bc->getOperand(0));
if (!gep || !gep->isInBounds() || !isPointerToStruct(gep->getPointerOperandType(), structType)) {
return false;
}
var = pvar;
return true;
}
// detect if variable proxyVar when used at instruction "useInst" has the same value as
// some other variable origVar
//
// this is very primitive form of alias analysis, intended for cases like
//
// #define SETSTACK_PTR(s, v) do {
// SEXP __v__ = (v);
// (s)->tag = 0;
// (s)->u.sxpval = __v__;
// } while (0)
//
// when we need to know the real name of variable "v"
bool aliasesVariable(Value *useInst, AllocaInst *proxyVar, AllocaInst*& origVar) {
StoreInst *si = NULL;
if (!findOnlyStoreTo(proxyVar, si)) {
return false;
}
LoadInst *li = dyn_cast<LoadInst>(si->getValueOperand());
if (!li) {
return false;
}
AllocaInst *ovar = dyn_cast<AllocaInst>(li->getPointerOperand());
if (!ovar) {
return false;
}
// ovar may be the original variable...
// but we need to check that ovar is not overwritten between the store (si) and the use (useInst)
Instruction *ui = dyn_cast<Instruction>(useInst);
if (!ui) {
return false;
}
BasicBlock *bb = si->getParent();
if (bb != ui->getParent()) {
return false;
}
bool reachedStore = false;
for(BasicBlock::iterator ii = bb->begin(), ie = bb->end(); ii != ie; ++ii) {
Instruction *in = &*ii;
if (in == si) {
reachedStore = true;
continue;
}
if (in == ui) {
if (reachedStore) {
origVar = ovar;
return true;
}
return false;
}
// FIXME: check if the variable(s) have address taken
if (reachedStore) {
if (StoreInst *s = dyn_cast<StoreInst>(in)) {
if (s->getPointerOperand() == ovar) {
// detected interleacing write
return false;
}
}
}
}
// not reached really
return false;
}
bool findOnlyStoreTo(AllocaInst* var, StoreInst*& definingStore) {
StoreInst *si = NULL;
for(Value::user_iterator ui = var->user_begin(), ue = var->user_end(); ui != ue; ++ui) {
User *u = *ui;
if (StoreInst *s = dyn_cast<StoreInst>(u)) {
if (s->getPointerOperand() == var) {
if (si == NULL) {
si = s;
} else {
// more than one store
return false;
}
}
}
}
if (si == NULL) {
return false;
}
definingStore = si;
return true;
}
// just does part of a type check
static bool isTypeExtraction(Value *inst, AllocaInst*& var) {
// %33 = load %struct.SEXPREC** %2, align 8, !dbg !21240 ; [#uses=1 type=%struct.SEXPREC*] [debug line = 1097:0]
// %34 = getelementptr inbounds %struct.SEXPREC* %33, i32 0, i32 0, !dbg !21240 ; [#uses=1 type=%struct.sxpinfo_struct*] [debug line = 1097:0]
// %35 = bitcast %struct.sxpinfo_struct* %34 to i32*, !dbg !21240 ; [#uses=1 type=i32*] [debug line = 1097:0]
// %36 = load i32* %35, align 4, !dbg !21240 ; [#uses=1 type=i32] [debug line = 1097:0]
// %37 = and i32 %36, 31, !dbg !21240 ; [#uses=1 type=i32] [debug line = 1097:0]
BinaryOperator* andv = dyn_cast<BinaryOperator>(inst);
if (!andv) {
return false;
}
if (andv->getOpcode() != Instruction::And) {
return false;
}
LoadInst* bitsLoad;
ConstantInt* cmask;
if (LoadInst::classof(andv->getOperand(0)) && ConstantInt::classof(andv->getOperand(1))) {
bitsLoad = cast<LoadInst>(andv->getOperand(0));
cmask = cast<ConstantInt>(andv->getOperand(1));
} else if (LoadInst::classof(andv->getOperand(1)) && ConstantInt::classof(andv->getOperand(0))) {
bitsLoad = cast<LoadInst>(andv->getOperand(0));
cmask = cast<ConstantInt>(andv->getOperand(1));
} else {
return false;
}
if (cmask->getZExtValue() != 31) {
return false;
}
if (!BitCastInst::classof(bitsLoad->getPointerOperand())) {
return false;
}
Value *gepv = cast<BitCastInst>(bitsLoad->getPointerOperand())->getOperand(0);
if (!GetElementPtrInst::classof(gepv)) {
return false;
}
GetElementPtrInst *gep = cast<GetElementPtrInst>(gepv);
if (!gep->isInBounds() || !gep->hasAllZeroIndices() || !isSEXP(gep->getPointerOperandType())) {
return false;
}
if (!LoadInst::classof(gep->getPointerOperand())) {
return false;
}
Value *varv = cast<LoadInst>(gep->getPointerOperand())->getPointerOperand();
if (!AllocaInst::classof(varv)) {
return false;
}
var = cast<AllocaInst>(varv);
return true;
}
bool isTypeCheck(Value *inst, bool& positive, AllocaInst*& var, unsigned& type) {
// %33 = load %struct.SEXPREC** %2, align 8, !dbg !21240 ; [#uses=1 type=%struct.SEXPREC*] [debug line = 1097:0]
// %34 = getelementptr inbounds %struct.SEXPREC* %33, i32 0, i32 0, !dbg !21240 ; [#uses=1 type=%struct.sxpinfo_struct*] [debug line = 1097:0]
// %35 = bitcast %struct.sxpinfo_struct* %34 to i32*, !dbg !21240 ; [#uses=1 type=i32*] [debug line = 1097:0]
// %36 = load i32* %35, align 4, !dbg !21240 ; [#uses=1 type=i32] [debug line = 1097:0]
// %37 = and i32 %36, 31, !dbg !21240 ; [#uses=1 type=i32] [debug line = 1097:0]
// %38 = icmp eq i32 %37, 22, !dbg !21240 ; [#uses=1 type=i1] [debug line = 1097:0]
// but since ALTREP header changes, the pattern is
// %42 = load %struct.SEXPREC*, %struct.SEXPREC** %5, align 8, !dbg !44519 ; [#uses=1 type=%struct.SEXPREC*] [debug line = 164:9]
// %43 = getelementptr inbounds %struct.SEXPREC, %struct.SEXPREC* %42, i32 0, i32 0, !dbg !44519 ; [#uses=1 type=%struct.sxpinfo_struct*] [debug line = 164:9]
// %44 = bitcast %struct.sxpinfo_struct* %43 to i64*, !dbg !44519 ; [#uses=1 type=i64*] [debug line = 164:9]
// %45 = load i64, i64* %44, align 8, !dbg !44519 ; [#uses=1 type=i64] [debug line = 164:9]
// %46 = and i64 %45, 31, !dbg !44519 ; [#uses=1 type=i64] [debug line = 164:9]
// %47 = trunc i64 %46 to i32, !dbg !44519 ; [#uses=1 type=i32] [debug line = 164:9] <===== extra truncate
// %48 = icmp eq i32 %47, 16, !dbg !44519 ; [#uses=1 type=i1] [debug line = 164:9]
// br i1 %48, label %49, label %53, !dbg !44521 ; [debug line = 164:9]
if (!CmpInst::classof(inst)) {
return false;
}
CmpInst *ci = cast<CmpInst>(inst);
if (!ci->isEquality()) {
return false;
}
positive = ci->isTrueWhenEqual();
ConstantInt* ctype;
Value *other;
if (ConstantInt::classof(ci->getOperand(0))) {
ctype = cast<ConstantInt>(ci->getOperand(0));
other = ci->getOperand(1);
} else if (ConstantInt::classof(ci->getOperand(1))) {
ctype = cast<ConstantInt>(ci->getOperand(1));
other = ci->getOperand(0);
} else {
return false;
}
if (TruncInst::classof(other)) {
other = (cast<TruncInst>(other))->getOperand(0);
}
BinaryOperator* andv;
if (BinaryOperator::classof(other)) {
andv = cast<BinaryOperator>(other);
} else {
return false;
}
if (isTypeExtraction(andv, var)) {
type = ctype->getZExtValue();
return true;
}
return false;
}
bool isTypeSwitch(Value *inst, AllocaInst*& var, BasicBlock*& defaultSucc, TypeSwitchInfoTy& info) {
// switch (TYPEOF(var)) {
// case ...
// case ....
// %187 = load %struct.SEXPREC** %4, align 8, !dbg !195121 ; [#uses=1 type=%struct.SEXPREC*] [debug line = 407:13]
// %188 = getelementptr inbounds %struct.SEXPREC* %187, i32 0, i32 0, !dbg !195121 ; [#uses=1 type=%struct.sxpinfo_struct*] [debug line = 407:13]
// %189 = bitcast %struct.sxpinfo_struct* %188 to i32*, !dbg !195121 ; [#uses=1 type=i32*] [debug line = 407:13]
// %190 = load i32* %189, align 4, !dbg !195121 ; [#uses=1 type=i32] [debug line = 407:13]
// %191 = and i32 %190, 31, !dbg !195121 ; [#uses=1 type=i32] [debug line = 407:13]
// switch i32 %191, label %224 [
// i32 0, label %192 <==== NILSXP
// i32 2, label %192 <==== LISTSXP
// i32 19, label %193 <=== VECSXP
// ], !dbg !195122 ; [debug line = 407:5]
SwitchInst *si = dyn_cast<SwitchInst>(inst);
if (!si) {
return false;
}
if (!isTypeExtraction(si->getCondition(), var)) {
return false;
}
info.clear();
for(SwitchInst::CaseIt ci = si->case_begin(), ce = si->case_end(); ci != ce; ++ci) {
ConstantInt *val = ci.getCaseValue();
BasicBlock *succ = ci.getCaseSuccessor();
info.insert({succ, val->getZExtValue()});
}
defaultSucc = si->getDefaultDest();
return true;
}
bool isCallThroughPointer(Value *inst) {
if (CallInst* ci = dyn_cast<CallInst>(inst)) {
return LoadInst::classof(ci->getCalledValue());
} else {
return false;
}
}
ValuesSetTy valueOrigins(Value *inst) {
ValuesSetTy origins;
origins.insert(inst);
bool insertedValue = true;
while(insertedValue) {
insertedValue = false;
for(ValuesSetTy::iterator vi = origins.begin(), ve = origins.end(); vi != ve; ++vi) {
Value *v = *vi;
if (!Instruction::classof(v) || CallInst::classof(v) || InvokeInst::classof(v) || AllocaInst::classof(v)) {
continue;
}
Instruction *inst = cast<Instruction>(v);
for(Instruction::op_iterator oi = inst->op_begin(), oe = inst->op_end(); oi != oe; ++oi) {
Value *op = *oi;
auto vinsert = origins.insert(op);
if (vinsert.second) {
insertedValue = true;
}
}
}
}
return origins;
}
// check if value inst origins from a load of variable var
// it may directly be the load of var
// but it may also be a result of a number of non-load and non-call instructions
AllocaInst* originsOnlyFromLoad(Value *inst) {
if (LoadInst *l = dyn_cast<LoadInst>(inst)) {
if (AllocaInst *lv = dyn_cast<AllocaInst>(l->getPointerOperand())) { // fast path
return lv;
}
}
ValuesSetTy origins = valueOrigins(inst);
AllocaInst* onlyVar = NULL;
for(ValuesSetTy::iterator vi = origins.begin(), ve = origins.end(); vi != ve; ++vi) {
Value *v = *vi;
if (CallInst::classof(v) || InvokeInst::classof(v)) {
return NULL;
}
if (AllocaInst *curVar = dyn_cast<AllocaInst>(v)) {
if (!onlyVar) {
onlyVar = curVar;
} else {
if (onlyVar != curVar) {
// multiple origins
return NULL;
}
}
}
// FIXME: need to handle anything more?
}
return onlyVar;
}
| [
"[email protected]"
] | |
a55f1b5f5ee7a9af04ac4d3c78620960e2a97243 | 6fffa3ff4c26e55c71bc3a9f2c062335beff2d40 | /third_party/blink/renderer/core/layout/ng/inline/ng_inline_cursor.h | bf8cc15a8df5cf7a7e28ad6983865eb1110e63c7 | [
"BSD-3-Clause",
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"MIT",
"Apache-2.0"
] | permissive | vasilyt/chromium | f69c311d0866090f187494fc7e335d8d08c9f264 | aa7cd16211bca96985a7149783a82c3d20984a85 | refs/heads/master | 2022-12-23T22:47:24.086201 | 2019-10-31T18:39:35 | 2019-10-31T18:39:35 | 219,038,538 | 0 | 0 | BSD-3-Clause | 2019-11-01T18:10:04 | 2019-11-01T18:10:04 | null | UTF-8 | C++ | false | false | 11,393 | h | // Copyright 2019 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.
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_INLINE_NG_INLINE_CURSOR_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_INLINE_NG_INLINE_CURSOR_H_
#include "base/containers/span.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/platform/text/text_direction.h"
#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
class ComputedStyle;
class LayoutBlockFlow;
class LayoutInline;
class LayoutObject;
class LayoutUnit;
class NGFragmentItem;
class NGFragmentItems;
class NGInlineBreakToken;
class NGPaintFragment;
class NGPhysicalBoxFragment;
class Node;
struct PhysicalOffset;
struct PhysicalRect;
struct PhysicalSize;
class ShapeResultView;
// This class traverses fragments in an inline formatting context.
//
// When constructed, the initial position is empty. Call |MoveToNext()| to move
// to the first fragment.
//
// TODO(kojii): |NGPaintFragment| should be gone when |NGPaintFragment| is
// deprecated and all its uses are removed.
class CORE_EXPORT NGInlineCursor {
STACK_ALLOCATED();
public:
using ItemsSpan = base::span<const std::unique_ptr<NGFragmentItem>>;
explicit NGInlineCursor(const LayoutBlockFlow& block_flow);
explicit NGInlineCursor(const NGFragmentItems& items);
explicit NGInlineCursor(const NGFragmentItems& fragment_items,
ItemsSpan items);
explicit NGInlineCursor(const NGPaintFragment& root_paint_fragment);
NGInlineCursor(const NGInlineCursor& other);
// Creates an |NGInlineCursor| without the root. Even when callers don't know
// the root of the inline formatting context, this cursor can |MoveTo()|
// specific |LayoutObject|.
NGInlineCursor();
bool operator==(const NGInlineCursor& other) const;
bool operator!=(const NGInlineCursor& other) const {
return !operator==(other);
}
bool IsItemCursor() const { return fragment_items_; }
bool IsPaintFragmentCursor() const { return root_paint_fragment_; }
// True if this cursor has the root to traverse. Only the default constructor
// creates a cursor without the root.
bool HasRoot() const { return IsItemCursor() || IsPaintFragmentCursor(); }
const NGFragmentItems& Items() const {
DCHECK(fragment_items_);
return *fragment_items_;
}
// Returns the |LayoutBlockFlow| containing this cursor.
const LayoutBlockFlow* GetLayoutBlockFlow() const;
//
// Functions to query the current position.
//
// Returns true if cursor is out of fragment tree, e.g. before first fragment
// or after last fragment in tree.
bool IsNull() const { return !current_item_ && !current_paint_fragment_; }
bool IsNotNull() const { return !IsNull(); }
explicit operator bool() const { return !IsNull(); }
// True if fragment at the current position can have children.
bool CanHaveChildren() const;
// True if fragment at the current position has children.
bool HasChildren() const;
// Returns a new |NGInlineCursor| whose root is the current item. The returned
// cursor can traverse descendants of the current item. If the current item
// has no children, returns an empty cursor.
NGInlineCursor CursorForDescendants() const;
// True if current position has soft wrap to next line. It is error to call
// other than line.
bool HasSoftWrapToNextLine() const;
// True if the current position is a atomic inline. It is error to call at
// end.
bool IsAtomicInline() const;
// True if the current position is before soft line break. It is error to call
// at end.
bool IsBeforeSoftLineBreak() const;
// True if the current position is an ellipsis. It is error to call at end.
bool IsEllipsis() const;
// True if the current position is an empty line box. It is error to call
// other then line box.
bool IsEmptyLineBox() const;
// True if the current position is a generatd text. It is error to call at
// end.
bool IsGeneratedText() const;
// True if fragment is |NGFragmentItem::kGeneratedText| or
// |NGPhysicalTextFragment::kGeneratedText|.
// TODO(yosin): We should rename |IsGeneratedTextType()| to another name.
bool IsGeneratedTextType() const;
// True if the current position is hidden for paint. It is error to call at
// end.
bool IsHiddenForPaint() const;
// True if the current position is text or atomic inline box.
bool IsInlineLeaf() const;
// True if the current position is a line box. It is error to call at end.
bool IsLineBox() const;
// True if the current position is a line break. It is error to call at end.
bool IsLineBreak() const;
// True if the current position is a list marker.
bool IsListMarker() const;
// True if the current position is a text. It is error to call at end.
bool IsText() const;
// |Current*| functions return an object for the current position.
const NGFragmentItem* CurrentItem() const { return current_item_; }
const NGPaintFragment* CurrentPaintFragment() const {
return current_paint_fragment_;
}
// Returns text direction of current line. It is error to call at other than
// line.
TextDirection CurrentBaseDirection() const;
const NGPhysicalBoxFragment* CurrentBoxFragment() const;
const LayoutObject* CurrentLayoutObject() const;
Node* CurrentNode() const;
// Returns text direction of current text or atomic inline. It is error to
// call at other than text or atomic inline. Note: <span> doesn't have
// reserved direction.
TextDirection CurrentResolvedDirection() const;
const ComputedStyle& CurrentStyle() const;
// InkOverflow of itself, including contents if they contribute to the ink
// overflow of this object (e.g. when not clipped,) in the local coordinate.
const PhysicalRect CurrentInkOverflow() const;
// The offset relative to the root of the inline formatting context.
const PhysicalOffset CurrentOffset() const;
const PhysicalRect CurrentRect() const;
const PhysicalSize CurrentSize() const;
// Returns start/end of offset in text content of current text fragment.
// It is error when this cursor doesn't point to text fragment.
unsigned CurrentTextStartOffset() const;
unsigned CurrentTextEndOffset() const;
// Returns |ShapeResultView| of the current position. It is error to call
// other than text.
const ShapeResultView* CurrentTextShapeResult() const;
// The layout box of text in (start, end) range in local coordinate.
// Start and end offsets must be between |CurrentTextStartOffset()| and
// |CurrentTextEndOffset()|. It is error to call other than text.
PhysicalRect CurrentLocalRect(unsigned start_offset,
unsigned end_offset) const;
// Relative to fragment of the current position. It is error to call other
// than text.
LayoutUnit InlinePositionForOffset(unsigned offset) const;
//
// Functions to move the current position.
//
// Move the current posint at |paint_fragment|.
void MoveTo(const NGPaintFragment& paint_fragment);
// Move to first |NGFragmentItem| or |NGPaintFragment| associated to
// |layout_object|. When |layout_object| has no associated fragments, this
// cursor points nothing.
void MoveTo(const LayoutObject& layout_object);
// Move to containing line box. It is error if the current position is line.
void MoveToContainingLine();
// Move to first child of current container box. If the current position is
// at fragment without children, this cursor points nothing.
// See also |TryToMoveToFirstChild()|.
void MoveToFirstChild();
// Move to first logical leaf of current line box. If current line box has
// no children, curosr becomes null.
void MoveToFirstLogicalLeaf();
// Move to last child of current container box. If the current position is
// at fragment without children, this cursor points nothing.
// See also |TryToMoveToFirstChild()|.
void MoveToLastChild();
// Move to last logical leaf of current line box. If current line box has
// no children, curosr becomes null.
void MoveToLastLogicalLeaf();
// Move the current position to the next fragment in pre-order DFS. When
// the current position is at last fragment, this cursor points nothing.
void MoveToNext();
// Move the current position to next fragment on same layout object.
void MoveToNextForSameLayoutObject();
// Move the current position to next line. It is error to call other than line
// box.
void MoveToNextLine();
// Move the current position to next sibling fragment.
void MoveToNextSibling();
// Same as |MoveToNext| except that this skips children even if they exist.
void MoveToNextSkippingChildren();
// Move the current position to previous line. It is error to call other than
// line box.
void MoveToPreviousLine();
// Returns true if the current position moves to first child.
bool TryToMoveToFirstChild();
// Returns true if the current position moves to last child.
bool TryToMoveToLastChild();
// TODO(kojii): Add more variations as needed, NextSibling,
// NextSkippingChildren, Previous, etc.
private:
// Returns break token for line box. It is error to call other than line box.
const NGInlineBreakToken& CurrentInlineBreakToken() const;
// True if current position is descendant or self of |layout_object|.
// Note: This function is used for moving cursor in culled inline boxes.
bool IsInclusiveDescendantOf(const LayoutObject& layout_object) const;
// True if the current position is a last line in inline block. It is error
// to call at end or the current position is not line.
bool IsLastLineInInlineBlock() const;
// Make the current position points nothing, e.g. cursor moves over start/end
// fragment, cursor moves to first/last child to parent has no children.
void MakeNull();
// Move the cursor position to the first fragment in tree.
void MoveToFirst();
// Same as |MoveTo()| but not support culled inline.
void InternalMoveTo(const LayoutObject& layout_object);
void SetRoot(const NGFragmentItems& items);
void SetRoot(const NGFragmentItems& fragment_items, ItemsSpan items);
void SetRoot(const NGPaintFragment& root_paint_fragment);
void SetRoot(const LayoutBlockFlow& block_flow);
void MoveToItem(const ItemsSpan::iterator& iter);
void MoveToNextItem();
void MoveToNextItemSkippingChildren();
void MoveToNextSiblingItem();
void MoveToPreviousItem();
void MoveToParentPaintFragment();
void MoveToNextPaintFragment();
void MoveToNextSiblingPaintFragment();
void MoveToNextPaintFragmentSkippingChildren();
ItemsSpan items_;
ItemsSpan::iterator item_iter_;
const NGFragmentItem* current_item_ = nullptr;
const NGFragmentItems* fragment_items_ = nullptr;
const NGPaintFragment* root_paint_fragment_ = nullptr;
const NGPaintFragment* current_paint_fragment_ = nullptr;
// Used in |MoveToNextForSameLayoutObject()| to support culled inline.
const LayoutInline* layout_inline_ = nullptr;
};
CORE_EXPORT std::ostream& operator<<(std::ostream&, const NGInlineCursor&);
CORE_EXPORT std::ostream& operator<<(std::ostream&, const NGInlineCursor*);
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_INLINE_NG_INLINE_CURSOR_H_
| [
"[email protected]"
] | |
06424472a9ebe958df3a1a176cf5d4a168b3d4ac | df79ac6d682789aa9042b58981559e032fe17ad0 | /CF(Code Forces)/cf7.cpp | 415017025f45b26cdb2c693ad33689dbd5bf1e2c | [] | no_license | abnsl0014/Coding-Questions | 834516e25312fb170b4b4fcf7ff83a4a2df7dd9f | 45973b56698d40612956b95ad10498850fe9aaa8 | refs/heads/master | 2020-05-15T01:56:00.299033 | 2020-05-07T10:36:02 | 2020-05-07T10:36:02 | 182,039,113 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 684 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
string s;
int ch=0,ce=0,cl=0,cll=0,co=0;
cin>>s;
for(int i=0;i<s.size();i++)
{
if(s[i]=='h'&& ch==0)
{
ch++;
}
else if(s[i]=='e'&&ch!=0&&ce==0)
{
ce++;
}
else if(s[i]=='l'&&cl==0&&ce!=0&&ch!=0)
{
cl++;
}
else if(s[i]=='l'&&cll==0&&ce!=0&&ch!=0&&cl!=0)
{
cll++;
}
else if(s[i]=='o'&&co==0&&ce!=0&&ch!=0&&cl!=0&&cll!=0)
{
co++;
}
}
if(ch==1&&ce==1&&cl==1&&cll==1&&co==1)
{
cout<<"YES\n";
}
else{
cout<<"NO\n";
}
}
| [
"[email protected]"
] | |
ddbd53f3ea1c54ba6738df6969de6571c11c15b1 | 8d3232994e1b26a78159dd979c0dbd1379bfd3f9 | /source/extensions/filters/network/zookeeper_proxy/zookeeper_utils.h | 559ef0f63093d0aed714f27f9c86f093a4c67a06 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | theopenlab/envoy | f18f492634da9996e870d28774546e43d49982ca | 3f4e4722aaaa0dd9ad43a058da9ccad9019f988a | refs/heads/master | 2020-05-07T17:24:33.002380 | 2019-07-01T08:57:15 | 2019-07-01T08:57:15 | 180,726,774 | 0 | 0 | Apache-2.0 | 2019-07-03T01:50:56 | 2019-04-11T06:15:27 | C++ | UTF-8 | C++ | false | false | 1,300 | h | #pragma once
#include <cstdint>
#include "envoy/common/platform.h"
#include "common/buffer/buffer_impl.h"
#include "common/common/byte_order.h"
#include "common/common/logger.h"
namespace Envoy {
namespace Extensions {
namespace NetworkFilters {
namespace ZooKeeperProxy {
/**
* Helper for extracting ZooKeeper data from a buffer.
*
* If at any point a peek is tried beyond max_len, an EnvoyException
* will be thrown. This is important to protect Envoy against malformed
* requests (e.g.: when the declared and actual length don't match).
*
* Note: ZooKeeper's protocol uses network byte ordering (big-endian).
*/
class BufferHelper : public Logger::Loggable<Logger::Id::filter> {
public:
BufferHelper(uint32_t max_len) : max_len_(max_len) {}
int32_t peekInt32(Buffer::Instance& buffer, uint64_t& offset);
int64_t peekInt64(Buffer::Instance& buffer, uint64_t& offset);
std::string peekString(Buffer::Instance& buffer, uint64_t& offset);
bool peekBool(Buffer::Instance& buffer, uint64_t& offset);
void skip(uint32_t len, uint64_t& offset);
void reset() { current_ = 0; }
private:
void ensureMaxLen(uint32_t size);
uint32_t max_len_;
uint32_t current_{};
};
} // namespace ZooKeeperProxy
} // namespace NetworkFilters
} // namespace Extensions
} // namespace Envoy
| [
"[email protected]"
] | |
c07cd4c2c9892bd063008cf87358bb9169c44474 | 794cc446d2e70c6bcdc64309fe65dd8714c9f53b | /agent.cpp | 634a41dbe2f0c5d2e0476f7d330dde5336e7a69b | [] | no_license | mlebre/Boids-Project | b144878356550c409e3cfa93ff05c8825816e59a | eea6bfaccb7ccc5253cb23eddcbc1b4bfe9f245a | refs/heads/master | 2021-01-23T09:28:02.324661 | 2015-01-16T12:06:34 | 2015-01-16T12:06:34 | 28,633,564 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,177 | cpp | //*******************************************************************
// Agent
//*******************************************************************
//===================================================================
// Librairies & Project Files
//===================================================================
#include "agent.h"
//-------------------------------------------------------------------
// Definiton of static attributes
//-------------------------------------------------------------------
//-------------------------------------------------------------------
// Constructors
//-------------------------------------------------------------------
agent::agent(void)
{
speed=NULL;
xposition=0;
yposition=0;
r=0;
nb_agents=0;
}
agent::agent(double W, double H, unsigned int size)
{
srandom(time(NULL));
unsigned int i;
speed=new double [8*size];
for(i=0; i<4*size; i++)
{
speed[i]=0;
}
new_speed= new double [2*size];
for(i=0; i<4*size; i++)
{
new_speed[i]=0;
}
xposition=W*(random()/(RAND_MAX + 1.0));
yposition=H*(random()/(RAND_MAX + 1.0));
r=10;
nb_agents=size;
}
//-------------------------------------------------------------------
// Destructors
//-------------------------------------------------------------------
agent::~agent(void)
{
}
//-------------------------------------------------------------------
// Public methods
//-------------------------------------------------------------------
//-------------------------------------------------------------------
// Protected methods
//-------------------------------------------------------------------
//-------------------------------------------------------------------
// Private methods
//-------------------------------------------------------------------
//-------------------------------------------------------------------
// Non inline accesors
//-------------------------------------------------------------------
| [
"[email protected]"
] | |
dff9d26bba4f92a3730f9a088fcc91665e4ee443 | c30f5cd2df8fb046bf20191ca0c19937ae520186 | /CentipedeHeadObjectPool.cpp | 4637679abf99811dfd2a5d62d63b3edbe82d2dff | [] | no_license | ziggysmalls/Centipede | 7865aa2a7af8df4cdd4e632b68248dc0cde5e61b | 468da6142e37801ccd4d0217d0d25157d8a942dd | refs/heads/master | 2022-04-11T11:22:42.728444 | 2019-11-28T01:10:17 | 2019-11-28T01:10:17 | 224,543,567 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 851 | cpp | #include "CentipedeHeadObjectPool.h"
#include "Game Components/TEAL/CommonElements.h"
#include "CentipedeHead.h"
CentipedeHeadObjectPool::CentipedeHeadObjectPool()
{
}
CentipedeHeadObjectPool::~CentipedeHeadObjectPool()
{
while (!recycledItems.empty())
{
delete recycledItems.top();
recycledItems.pop();
}
}
CentipedeHead* CentipedeHeadObjectPool::getCentipedeHead()
{
CentipedeHead* m;
if (recycledItems.empty())
{
m = new CentipedeHead();
}
else
{
m = recycledItems.top();
recycledItems.pop(); // Remember: top doesn't pop and pop returns void...
// Tell the object to register itself to the scene
m->RegisterToCurrentScene();
}
return m;
}
void CentipedeHeadObjectPool::ReturnCentipedeHead(CentipedeHead* s)
{
recycledItems.push(static_cast<CentipedeHead*>(s));
} | [
"[email protected]"
] | |
a79efa12aca5db87c0a0278b4987eba0b4da2468 | eeb8f1df33baeb1b8454df8080ac07e7fab58da8 | /Graph/levelOrder.cpp | c1f6696bc077e7597c90c58597cb07227968f14e | [] | no_license | Nirav1510/Interviewbit-solution | 02ae5c3c0101793cc7088f4cc188fdfb34719da1 | 004a0fd3b10fac4d7347ef543df40657f2dafee0 | refs/heads/main | 2023-08-16T07:50:24.688145 | 2021-09-27T07:25:21 | 2021-09-27T07:25:21 | 365,322,719 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 659 | cpp | vector<vector<int>> ans;
void solve(TreeNode *root)
{
if (!root)
return;
queue<TreeNode *> q;
q.push(root);
while (!q.empty())
{
int n = q.size();
vector<int> temp;
while (n--)
{
auto t = q.front();
q.pop();
temp.push_back(t->val);
if (t->left)
{
q.push(t->left);
}
if (t->right)
{
q.push(t->right);
}
}
ans.push_back(temp);
}
}
vector<vector<int>> Solution::levelOrder(TreeNode *A)
{
ans.clear();
solve(A);
return ans;
}
| [
"[email protected]"
] | |
4acbaa2dc3badb44d91279e715c55f0dc4e8199b | afdc82729b1ae1e1a11fc0d63d4990a7972a9fd6 | /mace/ops/arm/base/deconv_2d_2x2.cc | faa06666fb70976b5cdb604ff16cbcd5234bdc39 | [
"Apache-2.0"
] | permissive | gasgallo/mace | 79e759ceb9548fa69d577dd28ca983f87a302a5e | 96b4089e2323d9af119f9f2eda51976ac19ae6c4 | refs/heads/master | 2021-06-23T19:09:24.230126 | 2021-03-02T12:23:05 | 2021-03-02T12:23:05 | 205,080,233 | 1 | 0 | Apache-2.0 | 2019-08-29T04:27:36 | 2019-08-29T04:27:35 | null | UTF-8 | C++ | false | false | 1,268 | cc | // Copyright 2020 The MACE 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 "mace/ops/arm/base/deconv_2d_2x2.h"
namespace mace {
namespace ops {
namespace arm {
void RegisterDeconv2dK2x2Delegator(OpDelegatorRegistry *registry) {
MACE_REGISTER_DELEGATOR(
registry, Deconv2dK2x2S1<float>, delegator::Deconv2dParam,
MACE_DELEGATOR_KEY_EX(Deconv2d, RuntimeType::RT_CPU,
float, ImplType::NEON, K2x2S1));
MACE_REGISTER_DELEGATOR(
registry, Deconv2dK2x2S2<float>, delegator::Deconv2dParam,
MACE_DELEGATOR_KEY_EX(Deconv2d, RuntimeType::RT_CPU,
float, ImplType::NEON, K2x2S2));
}
} // namespace arm
} // namespace ops
} // namespace mace
| [
"[email protected]"
] | |
a46129e7bf56301a7dade7e1f826ed7489e94250 | 9866acd66b81d25e74195a22f9f5867d166b1380 | /gc/src/qnx/control/speed/chassis.h | 63f0d316879ec0037c9576e5ee21a2465976a5e2 | [] | no_license | John-Nagle/Overbot | af45bcba87ddf1442c44830cc966cdb4b5107fef | 80c56adb16b673ff7d667ac3d6ed4a0ee36e25a3 | refs/heads/master | 2020-04-15T20:37:27.263381 | 2019-01-10T06:36:19 | 2019-01-10T06:36:19 | 165,001,886 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,386 | h | //
// File: chassis.h -- interface to the Overbot Polaris Ranger with Galil controllers
//
//
// John Nagle
// Team Overbot
// November, 2004
//
//
#ifndef CHASSIS_H
#define CHASSIS_H
#include <time.h>
#include "simplecontroller.h"
#include "throttlecontroller.h"
#include "transmissioncontroller.h"
#include "brakecontroller.h"
#include "steeringcontroller.h"
#include "speedservermsg.h"
#include "timedloop.h"
//
// class Chassis -- all the engine-related controllers
//
class Chassis {
private:
// Controllers for hardware
BrakeController m_brake; // brake controlller (GOAL is pressure)
ThrottleController m_throttle; // throttle controller (GOAL is position)
TransmissionController m_transmission; // transmission controller (GOAL is gear)
SteeringController m_steer; // steering controller (GOAL is position)
// State info
MsgSpeedSet::State m_state; // what state we are in
SimpleLowPassFilter m_speed; // filtered speed
SimpleLowPassFilter m_accel; // filtered acceleration
double m_prevodometer; // previous odometer value
double m_prevspeed; // previous speed value
double m_accumspeederror; // accumulated speed error, for I term
double m_statetimestamp; // time of last state change
double m_updatetimestamp; // time of last update
double m_dumptimestamp; // time of last dump to log
bool m_hillholder; // hill holder mode; lock brakes until RPM is up
bool m_controllersready; // controllers ready at last update?
bool m_verbose; // true if verbose mode
Fault::Faultcode m_fault; // current fault code if any
public:
Chassis(bool readonly=false); // constructor
~Chassis(); // destructor
void SetVerbose(bool verbose) { m_verbose = verbose; }
void Update(); // update incoming info from controllers.
bool SetState(MsgSpeedSet::State newstate, bool& busy); // change to new state
void SetSpeed(float desiredaccel, float desiredspeed, float desiredsteer); // actually set the speed and steering
void SetFault(Fault::Faultcode faultid, const char* msg = 0); // report a fault - causes an emergency stop
void SetFault(Fault::Faultcode faultid, Controller::Err err); // report a fault - causes an emergency stop
bool ResetFault(); // reset fault, returns true if reset allowed.
bool SetGear(MsgSpeedSet::Gear newgear, bool busy); // request gear change
// Access functions
MsgSpeedSet::State GetState() const { return(m_state); }
MsgSpeedSet::Gear GetGear();
float GetSpeed(); // get speed in m/sec
float GetAccel(); // get acceleration in m^2/sec
float GetCurvature(); // get turning curvature (1/radius in meters, > 0 means right turn)
int GetDir(); // -1 reverse, +1 forward, 0 neutral.
Fault::Faultcode GetFault() const { return(m_fault); }
MsgSpeedSetReply::Hint GetHint(); // not yet
double GetUpdateTmestamp() const { return(m_updatetimestamp); }
bool GetControllersReady() const { return(m_controllersready); }
bool GetStopped() { return(stopped()); } // export Stopped
double GetOdometer(); // get odometer value
void Dump(); // dump state (to logprintf)
private:
void UpdateState(); // update state, called on each update cycle
Controller::Err UpdateControllersTry(Fault::Faultcode& faultid); // update local copy of controller state, make sure all are up
Controller::Err UpdateControllers(Fault::Faultcode& faultid); // update local copy of controller state, make sure all are up
void StateChange(MsgSpeedSet::State newstate, const char* msg); // note a state change
void ControllerSanityCheck(); // check state of recently updated controllers
float calcThrottle(float desiredspeed); // calculate throttle setting
float calcBrake(float desiredaccel); // calculate brake setting
float calcSteering(float desiredinvrad); // convert 1/r to steering goal
float calcSteeringRadius(float goal); // convert steering goal to 1/r
bool SetGoals(float throttlesetting, float brakesetting, float steersetting); // set moving throttle, brakes, steering
bool SetGoalsStopped(); // set throttle, brakes for stopped state
bool controllersready(); // true if controllers are ready
bool brakeslocked(); // true if brake pressure is above high threshold
bool brakesreleased(); // true if brake pressure is below low threshold
bool engineabovehillholdrelease(); // true if engine above hill hold release point
bool engineaboveidle(); // true if engine RPM is above movement threshold
bool enginerunning(); // true if engine RPM is above cranking threshold
bool throttlezero(); // true if throttle is at zero
bool notmoving(); // true if not moving according to encoder
bool stopped(); // true if brakes locked and engine idle and not moving
bool indesiredgear(); // true if in desired gear
bool unpaused(); // true if not estop, not paused, not manual
bool unpaused(bool& notestop, bool& unpaused, bool& inauto); // long form
};
#endif // CHASSIS_H
| [
"[email protected]"
] | |
909b4559ac9796d88a1f75cedc016111ac22ed2a | 5ef9c03f47708bd0dc95d76a53369e51c5617944 | /lib-h3/lib-spiflashstore/src/spiflashstore.cpp | 31e4dc36644243aecfc15fd179936607980a2628 | [
"MIT"
] | permissive | hermixy/allwinner-bare-metal | 87dcc033884b990609669559428d7e35e191afa6 | ea55715ac31942d7af3a6babba29514c8a2f0d49 | refs/heads/master | 2023-09-02T08:21:25.074808 | 2021-10-12T09:57:52 | 2021-10-12T09:57:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,490 | cpp | /**
* @file spiflashstore.cpp
*
*/
/* Copyright (C) 2018-2020 by Arjan van Vught mailto:[email protected]
*
* 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.
*/
#include <stdint.h>
#include <stdio.h>
#include <cassert>
#include "spiflashstore.h"
#include "spi_flash.h"
#ifndef NDEBUG
# include "hardware.h"
#endif
#include "debug.h"
using namespace spiflashstore;
static constexpr uint8_t s_aSignature[] = {'A', 'v', 'V', 0x10};
static constexpr auto OFFSET_STORES = ((((sizeof(s_aSignature) + 15) / 16) * 16) + 16); // +16 is reserved for UUID
static constexpr uint32_t s_aStorSize[static_cast<uint32_t>(Store::LAST)] = {96, 144, 32, 64, 96, 64, 32, 32, 480, 64, 32, 96, 48, 32, 944, 48, 64, 32, 96, 32, 1024, 32, 32, 64, 96, 32, 32};
#ifndef NDEBUG
static constexpr char s_aStoreName[static_cast<uint32_t>(Store::LAST)][16] = {"Network", "Art-Net3", "DMX", "WS28xx", "E1.31", "LTC", "MIDI", "Art-Net4", "OSC Server", "TLC59711", "USB Pro", "RDM Device", "RConfig", "TCNet", "OSC Client", "Display", "LTC Display", "Monitor", "SparkFun", "Slush", "Motors", "Show", "Serial", "RDM Sensors", "RDM SubDevices", "GPS", "RGB Panel"};
#endif
SpiFlashStore *SpiFlashStore::s_pThis = nullptr;
SpiFlashStore::SpiFlashStore() {
DEBUG_ENTRY
assert(s_pThis == nullptr);
s_pThis = this;
if (spi_flash_probe(0, 0, 0) < 0) {
DEBUG_PUTS("No SPI flash chip");
} else {
printf("Detected %s with sector size %d total %d bytes\n", spi_flash_get_name(), spi_flash_get_sector_size(), spi_flash_get_size());
m_bHaveFlashChip = Init();
}
if (m_bHaveFlashChip) {
m_nSpiFlashStoreSize = OFFSET_STORES;
for (uint32_t j = 0; j < static_cast<uint32_t>(Store::LAST); j++) {
m_nSpiFlashStoreSize += s_aStorSize[j];
}
DEBUG_PRINTF("OFFSET_STORES=%d", static_cast<int>(OFFSET_STORES));
DEBUG_PRINTF("m_nSpiFlashStoreSize=%d", m_nSpiFlashStoreSize);
assert(m_nSpiFlashStoreSize <= FlashStore::SIZE);
Dump();
}
DEBUG_EXIT
}
SpiFlashStore::~SpiFlashStore() {
DEBUG_ENTRY
while (Flash())
;
DEBUG_EXIT
}
bool SpiFlashStore::Init() {
const uint32_t nEraseSize = spi_flash_get_sector_size();
assert(FlashStore::SIZE == nEraseSize);
if (FlashStore::SIZE != nEraseSize) {
return false;
}
m_nStartAddress = spi_flash_get_size() - nEraseSize;
assert(!(m_nStartAddress % nEraseSize));
if (m_nStartAddress % nEraseSize) {
return false;
}
spi_flash_cmd_read_fast(m_nStartAddress, FlashStore::SIZE, &m_aSpiFlashData);
bool bSignatureOK = true;
for (uint32_t i = 0; i < sizeof(s_aSignature); i++) {
if (s_aSignature[i] != m_aSpiFlashData[i]) {
m_aSpiFlashData[i] = s_aSignature[i];
bSignatureOK = false;
}
}
if (__builtin_expect(!bSignatureOK, 0)) {
DEBUG_PUTS("No signature");
m_bIsNew = true;
// Clear nSetList
for (uint32_t j = 0; j < static_cast<uint32_t>(Store::LAST); j++) {
const uint32_t nOffset = GetStoreOffset(static_cast<Store>(j));
uint32_t k = nOffset;
m_aSpiFlashData[k++] = 0x00;
m_aSpiFlashData[k++] = 0x00;
m_aSpiFlashData[k++] = 0x00;
m_aSpiFlashData[k++] = 0x00;
// Clear rest of data
for (; k < nOffset + s_aStorSize[j]; k++) {
m_aSpiFlashData[k] = 0xFF;
}
}
m_tState = State::CHANGED;
return true;
}
for (uint32_t j = 0; j < static_cast<uint32_t>(Store::LAST); j++) {
auto *pbSetList = &m_aSpiFlashData[GetStoreOffset(static_cast<Store>(j))];
if ((pbSetList[0] == 0xFF) && (pbSetList[1] == 0xFF) && (pbSetList[2] == 0xFF) && (pbSetList[3] == 0xFF)) {
DEBUG_PRINTF("[%s]: nSetList \'FF...FF\'", s_aStoreName[j]);
// Clear bSetList
*pbSetList++ = 0x00;
*pbSetList++ = 0x00;
*pbSetList++ = 0x00;
*pbSetList = 0x00;
m_tState = State::CHANGED;
}
}
return true;
}
uint32_t SpiFlashStore::GetStoreOffset(Store tStore) {
assert(tStore < Store::LAST);
uint32_t nOffset = OFFSET_STORES;
for (uint32_t i = 0; i < static_cast<uint32_t>(tStore); i++) {
nOffset += s_aStorSize[i];
}
DEBUG_PRINTF("nOffset=%d", nOffset);
return nOffset;
}
void SpiFlashStore::ResetSetList(Store tStore) {
assert(tStore < Store::LAST);
uint8_t *pbSetList = &m_aSpiFlashData[GetStoreOffset(tStore)];
// Clear bSetList
*pbSetList++ = 0x00;
*pbSetList++ = 0x00;
*pbSetList++ = 0x00;
*pbSetList = 0x00;
m_tState = State::CHANGED;
}
void SpiFlashStore::Update(Store tStore, uint32_t nOffset, const void *pData, uint32_t nDataLength, uint32_t nSetList, uint32_t nOffsetSetList) {
DEBUG1_ENTRY
if (__builtin_expect((!m_bHaveFlashChip),0)) {
return;
}
DEBUG_PRINTF("[%s]:%u:%p, nOffset=%d, nDataLength=%d-%u, bSetList=0x%x, nOffsetSetList=%d", s_aStoreName[static_cast<uint32_t>(tStore)], static_cast<uint32_t>(tStore), pData, nOffset, nDataLength, static_cast<uint32_t>(m_tState), nSetList, nOffsetSetList);
assert(tStore < Store::LAST);
assert(pData != nullptr);
assert((nOffset + nDataLength) <= s_aStorSize[static_cast<uint32_t>(tStore)]);
debug_dump(const_cast<void*>(pData), nDataLength);
bool bIsChanged = false;
const uint32_t nBase = nOffset + GetStoreOffset(tStore);
const auto *pSrc = static_cast<const uint8_t*>(pData);
auto *pDst = &m_aSpiFlashData[nBase];
for (uint32_t i = 0; i < nDataLength; i++) {
if (*pSrc != *pDst) {
bIsChanged = true;
*pDst = *pSrc;
}
pDst++;
pSrc++;
}
if (bIsChanged && (m_tState != State::ERASED)) {
m_tState = State::CHANGED;
}
if ((0 != nOffset) && (bIsChanged) && (nSetList != 0)) {
auto *pSet = reinterpret_cast<uint32_t*>((&m_aSpiFlashData[GetStoreOffset(tStore)] + nOffsetSetList));
*pSet |= nSetList;
}
DEBUG_PRINTF("m_tState=%u", static_cast<uint32_t>(m_tState));
DEBUG1_EXIT
}
void SpiFlashStore::Copy(Store tStore, void *pData, uint32_t nDataLength, uint32_t nOffset) {
DEBUG1_ENTRY
if (__builtin_expect((!m_bHaveFlashChip), 0)) {
DEBUG1_EXIT
return;
}
assert(tStore < Store::LAST);
assert(pData != nullptr);
assert((nDataLength + nOffset) <= s_aStorSize[static_cast<uint32_t>(tStore)]);
const auto *pSet = reinterpret_cast<uint32_t*>((&m_aSpiFlashData[GetStoreOffset(tStore)] + nOffset));
DEBUG_PRINTF("*pSet=0x%x", reinterpret_cast<uint32_t>(*pSet));
if ((__builtin_expect((m_bIsNew), 0)) || (__builtin_expect((*pSet == 0), 0))) {
Update(tStore, nOffset, pData, nDataLength);
DEBUG1_EXIT
return;
}
const auto *pSrc = const_cast<const uint8_t*>(&m_aSpiFlashData[GetStoreOffset(tStore)]) + nOffset;
auto *pDst = static_cast<uint8_t*>(pData);
for (uint32_t i = 0; i < nDataLength; i++) {
*pDst++ = *pSrc++;
}
DEBUG1_EXIT
}
void SpiFlashStore::CopyTo(Store tStore, void* pData, uint32_t& nDataLength) {
DEBUG1_ENTRY
if (__builtin_expect((tStore >= Store::LAST), 0)) {
nDataLength = 0;
return;
}
nDataLength = s_aStorSize[static_cast<uint32_t>(tStore)];
const auto *pSrc = const_cast<const uint8_t*>(&m_aSpiFlashData[GetStoreOffset(tStore)]);
auto *pDst = static_cast<uint8_t*>(pData);
for (uint32_t i = 0; i < nDataLength; i++) {
*pDst++ = *pSrc++;
}
DEBUG1_EXIT
}
bool SpiFlashStore::Flash() {
if (__builtin_expect((m_tState == State::IDLE), 1)) {
return false;
}
DEBUG_PRINTF("m_tState=%d", static_cast<uint32_t>(m_tState));
assert(m_nStartAddress != 0);
if (m_nStartAddress == 0) {
printf("!*! m_nStartAddress == 0 !*!\n");
return false;
}
switch (m_tState) {
case State::CHANGED:
spi_flash_cmd_erase(m_nStartAddress, FlashStore::SIZE);
m_tState = State::ERASED;
return true;
break;
case State::ERASED:
spi_flash_cmd_write_multi(m_nStartAddress, m_nSpiFlashStoreSize, &m_aSpiFlashData);
m_tState = State::IDLE;
break;
default:
break;
}
#ifndef NDEBUG
Dump();
#endif
return false;
}
void SpiFlashStore::Dump() {
#ifndef NDEBUG
if (__builtin_expect((!m_bHaveFlashChip), 0)) {
return;
}
const auto IsWatchDog = Hardware::Get()->IsWatchdog();
if (IsWatchDog) {
Hardware::Get()->WatchdogStop();
}
debug_dump(m_aSpiFlashData, OFFSET_STORES);
printf("\n");
for (uint32_t j = 0; j < static_cast<uint32_t>(Store::LAST); j++) {
printf("Store [%s]:%d\n", s_aStoreName[j], j);
auto *p = &m_aSpiFlashData[GetStoreOffset(static_cast<Store>(j))];
debug_dump(p, s_aStorSize[j]);
printf("\n");
}
if (IsWatchDog) {
Hardware::Get()->WatchdogInit();
}
printf("m_tState=%d\n", static_cast<uint32_t>(m_tState));
#endif
}
| [
"[email protected]"
] | |
f89713727423f428bc2432f531e222cbe90fd973 | ab0e423f50f77a8a35c9eee1eab2b867209d30ea | /leetcode/1. Array/019. find-the-highest-altitude.cpp | 63de14aa9b0ecb56fcc4728e8c0017be248eb7ed | [] | no_license | harshit9270/DSA-Practice | 094dee910fdd5396d24e026c0415ad41868051e3 | af769ffd117b9c523c52027172718c991e8bdc4d | refs/heads/main | 2023-08-21T21:21:05.779928 | 2021-10-04T17:07:45 | 2021-10-04T17:07:45 | 411,307,737 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 310 | cpp | // Optimized O(n)
class Solution {
public:
int largestAltitude(vector<int>& gain) {
int ans = 0, temp =0;
for(int i=0; i<gain.size(); i++){
temp += gain[i];
if(temp > ans){
ans = temp;
}
}
return ans;
}
}; | [
"[email protected]"
] | |
ac4fb3631e627a64372f68394563978646565895 | fea779942fbbe4e3c03cb9bc78b0a99e56cb17e5 | /cpp/m4engine/src/region.cpp | 9c5d3939a91782dd5223656b77cca2e15d308afb | [] | no_license | jesuscraf/peopletech | 66e372af07f9a3dd4660ef14b93daddf92a5e3c8 | 3ab9470cf2e7cb7a44baf4185710cb707f081ff4 | refs/heads/master | 2021-09-03T13:37:13.701453 | 2018-01-09T11:49:34 | 2018-01-09T11:49:34 | 114,750,048 | 0 | 0 | null | null | null | null | ISO-8859-3 | C++ | false | false | 11,612 | cpp | //==============================================================================
//
// (c) Copyright 1991-1997 Meta Software M.S., S.A
// All rights reserved.
//
// Module: <modulo>
// File: region.cpp
// Project:
// Author: Meta Software M.S. , S.A
// Date:7/18/97
// Language: C++
// Operating System: ALL
// Design Document:
//
// Propietary: Fernando Abad Garcia
// Modifications: Who && Date
//
// Definition:
//
// This module defines...
//
//
//==============================================================================
#include "eng.h"
#include "engdf.inl"
#include "designdt.h"
#include "region.h"
#define GROUP_ID ENG_TGI_FIELD
//==============================================================================ClENG_Line
ClENG_Line::ClENG_Line()
{
m_poInsp=GET_INSP();
m_poDvc =NULL;
}
void ClENG_Line::End()
{
m_poDvc =NULL;
}
void ClENG_Line::Init(
ClENG_OutDevice * ai_poDvc,
DvcUnit_t ai_Top, DvcUnit_t ai_Left, DvcUnit_t ai_Top2, DvcUnit_t ai_Left2,
m4bool_t ai_bAdjustLineToContainer,
DvcUnit_t ai_Width, ClENG_OutDevice::STYLE ai_Style, m4uint32_t ai_uiIdColour,
m4bool_t ai_bSwVisible )
{
ClENG_Line::End() ;
m_poDvc = ai_poDvc ;
m_Top = ai_Top ;
m_Left = ai_Left ;
m_Top2 = ai_Top2 ;
m_Left2 = ai_Left2 ;
m_Width = ai_Width ;
m_Style = ai_Style ;
m_uiIdColour = ai_uiIdColour ;
m_bSwVisible = ai_bSwVisible ;
m_bAdjustLineToContainer = ai_bAdjustLineToContainer ;
}
void ClENG_Line::Init( ClENG_Line *ai_poSource )
{
Init(
ai_poSource->m_poDvc,
ai_poSource->GetTop(), ai_poSource->GetLeft(),
ai_poSource->GetTop2(), ai_poSource->GetLeft2(),
ai_poSource->GetAdjustLineToContainer(),
ai_poSource->GetWidth(), ai_poSource->GetStyle(), ai_poSource->GetIdColour(),
ai_poSource->IsVisible() ) ;
}
void ClENG_Line::Show( m4int16_t ai_iNumPage, DvcUnit_t ai_XBase, DvcUnit_t ai_YBase )
{
if ( IsVisible() ) {
m_poDvc->SelectColour(ai_iNumPage, m_uiIdColour);
m_poDvc->PrintLine( ai_iNumPage, ai_XBase+m_Left, ai_YBase+m_Top,
ai_XBase+m_Left2, ai_YBase+m_Top2, m_Width, m_Style ) ;
} ;
}
void ClENG_Line::Show( m4int16_t ai_iNumPage, DvcUnit_t ai_XBase, DvcUnit_t ai_YBase,
DvcUnit_t ai_HeightPrinted, DvcUnit_t ai_HeightToPrint )
{
m4double_t PendX, K ;
m4bool_t Inf, SwShow ;
DvcUnit_t X1,Y1,X2,Y2 ; //Puntos de la linea ordenados de < a > por eje Y
DvcUnit_t YLim1, YLim2 ; //Limites Y de impresion
if ( IsVisible() ) {
//Ordeno puntos por eje Y, para que el signo de la pendiente sea correcto
//Opero sobre coordenadas ya reales
if (m_Top<m_Top2) {
Y1=m_Top ; X1=m_Left; Y2=m_Top2; X2=m_Left2 ;
} else {
Y2=m_Top ; X2=m_Left; Y1=m_Top2; X1=m_Left2 ;
} ;
Y1+=ai_YBase - ai_HeightPrinted ; Y2+=ai_YBase - ai_HeightPrinted ; X1+=ai_XBase ;X2+=ai_XBase ;
//Hayo f(x)=PendX*x+k.
if ( Y1==Y2 ) {
Inf=M4_TRUE ; //Pendiente infinita, linea horizontal
} else {
Inf=M4_FALSE ;
PendX=(X2-X1)*1.0/(Y2-Y1) ;
K = X1-PendX*Y1 ;
} ;
//Recalculo puntos teniendo en cuenta la intersección
YLim1=ai_YBase ;
YLim2=ai_YBase+ai_HeightToPrint-1 ;
if (Inf) {
SwShow = M4_BOOL(M4_IN_RANGE(Y1,YLim1,YLim2));
} else {
SwShow = M4_BOOL(! ( Y1>YLim2 || Y2<YLim1 ));
if (SwShow) {
if (Y1<YLim1) {
Y1=YLim1 ;
X1=Y1*PendX+K ;
} ;
if (Y2>YLim2) {
Y2=YLim2 ;
X2=Y2*PendX+K ;
} ;
} ;
} ;
if (SwShow) {
m_poDvc->SelectColour(ai_iNumPage, m_uiIdColour);
m_poDvc->PrintLine( ai_iNumPage, X1, Y1, X2, Y2, m_Width, m_Style ) ;
} ;
} ;
}
m4bool_t ClENG_Line::SetLine( m4char_t *ai_pcLineProps )
{
m4bool_t SwOk=M4_TRUE ;
m4int16_t B ;
ClMIT_Str StrAux ;
if ( ClMIT_Str::StrLenTrim(ai_pcLineProps)==0 ) {
SetVisible(M4_FALSE) ;
goto exit ;
}
if ( ClMIT_Str::StrLenTrim(ai_pcLineProps)!=GetSizeStrLine() ) {
SwOk=M4_FALSE ;
goto exit ;
} ;
StrAux.ToASCIZ( &ai_pcLineProps[0],4) ;
SetWidth( ClMetric::DPointToDvc( atol(StrAux)/10.0 ) ) ;
StrAux.ToASCIZ( &ai_pcLineProps[4],2) ;
SwOk = M4_BOOL( SwOk && ClENG_DesignTree::TestLineStyle((ClENG_OutDevice::STYLE)atol(StrAux)) ) ;
if (!SwOk) goto exit ;
SetStyle( (ClENG_OutDevice::STYLE)atol(StrAux) ) ;
StrAux.ToASCIZ( &ai_pcLineProps[6],1) ;
SetVisible( M4_BOOL(atol(StrAux)==1) ) ;
StrAux.ToASCIZ( &ai_pcLineProps[7],5) ;
SetIdColour( atol(StrAux)) ;
exit:
if (!SwOk) {
/*##Cambiar num msg*/
*m_poInsp->m_poTrace << ClMIT_Msg( ClMIT_Msg::MSG_ERROR, GROUP_ID,
"Sintax error in SetLine: parameter %0:s", ClMIT_Msg::MIXED_OUT)
<< ai_pcLineProps << SEND_MSG ;
} ;
return SwOk ;
}
//==============================================================================ClENG_Region
ClENG_Region::ClENG_Region()
{
m_poInsp=GET_INSP();
m_poDvc =NULL;
}
void ClENG_Region::End()
{
m_poDvc =NULL;
}
void ClENG_Region::Init(
ClENG_OutDevice * ai_poDvc,
DvcUnit_t ai_Top, DvcUnit_t ai_Left, DvcUnit_t ai_Width, DvcUnit_t ai_Height,
m4char_t *ai_pcBordeProps, m4uint32_t ai_uiFillColour
)
{
m4int16_t B ;
ClENG_Region::End() ;
m_poDvc = ai_poDvc ;
m_Top = ai_Top ;
m_Left = ai_Left ;
m_Width = ai_Width ;
m_Height = ai_Height ;
m_uiFillColour = ai_uiFillColour ;
for (B=0; B<LINE_COUNT; ++B ) m_Line[B].Init(m_poDvc,0,0,0,0,M4_FALSE,0,ClENG_OutDevice::SOLID,0,M4_FALSE) ;
AdjustFrameAndFillZone() ;
SetFrame(ai_pcBordeProps) ;
}
void ClENG_Region::Init( ClENG_Region *ai_poSource )
{
m4int16_t B ;
Init(
ai_poSource->m_poDvc,
ai_poSource->GetTop(), ai_poSource->GetLeft(), ai_poSource->GetWidth(),
ai_poSource->GetHeight(), "", ai_poSource->GetFillColour() ) ;
for (B=0;B<LINE_COUNT;++B) m_Line[B].Init( &ai_poSource->m_Line[B] ) ;
}
void ClENG_Region::LineIndex(LINE_ID ai_Line, m4int16_t *ao_piBeg,m4int16_t *ao_piEnd)
{
if (ai_Line==FRAME) {
*ao_piBeg=0 ; *ao_piEnd=LINE_COUNT-1 ;
} else {
*ao_piBeg=ai_Line; *ao_piEnd=ai_Line;
} ;
}
void ClENG_Region::SetStyle( LINE_ID ai_Line, ClENG_OutDevice::STYLE ai_Style)
{
m4int16_t B, Beg, End ;
LineIndex(ai_Line,&Beg,&End) ;
for (B=Beg;B<=End;++B) m_Line[B].SetStyle(ai_Style) ;
}
void ClENG_Region::SetIdColour( LINE_ID ai_Line, m4uint32_t ai_uiIdColour)
{
m4int16_t B, Beg, End ;
LineIndex(ai_Line,&Beg,&End) ;
for (B=Beg;B<=End;++B) m_Line[B].SetIdColour(ai_uiIdColour) ;
}
void ClENG_Region::SetVisible( LINE_ID ai_Line, m4bool_t ai_bSw)
{
m4int16_t B, Beg, End ;
LineIndex(ai_Line,&Beg,&End) ;
for (B=Beg;B<=End;++B) m_Line[B].SetVisible(ai_bSw) ;
}
void ClENG_Region::SetWidth( LINE_ID ai_Line, DvcUnit_t ai_Width)
{
m4int16_t B, Beg, End ;
LineIndex(ai_Line,&Beg,&End) ;
for (B=Beg;B<=End;++B) m_Line[B].SetWidth(ai_Width) ;
AdjustFrameAndFillZone() ;
}
void ClENG_Region::SetTop(DvcUnit_t ai_Top)
{
m_Top=ai_Top ;
AdjustFrameAndFillZone() ;
}
void ClENG_Region::SetLeft(DvcUnit_t ai_Left)
{
m_Left=ai_Left ;
AdjustFrameAndFillZone() ;
}
void ClENG_Region::SetWidth(DvcUnit_t ai_Width)
{
m_Width=ai_Width ;
AdjustFrameAndFillZone() ;
}
void ClENG_Region::SetHeight(DvcUnit_t ai_Height)
{
m_Height=ai_Height ;
AdjustFrameAndFillZone() ;
}
m4bool_t ClENG_Region::IsHomogeneousFrame()
{
m4bool_t SwRet=M4_TRUE ;
m4int16_t B ;
for (B=0;B<LINE_COUNT && SwRet ; ++B) {
if ( ! m_Line[B].IsVisible() ) {
SwRet=M4_FALSE ;
} else {
if (
m_Line[B].GetStyle() != m_Line[0].GetStyle() ||
m_Line[B].GetIdColour() != m_Line[0].GetIdColour() ||
m_Line[B].GetWidth() != m_Line[0].GetWidth()
)
{
SwRet=M4_FALSE ;
}
} ;
} ;
return SwRet ;
}
void ClENG_Region::AdjustFrameAndFillZone()
{
DvcUnit_t Int[LINE_COUNT],Ext[LINE_COUNT] ;
m4int16_t B ;
for (B=0; B<LINE_COUNT;++B) {
if ( m_Line[B].IsVisible() ) {
Int[B] = m_Line[B].GetWidth()/2 ;
Ext[B] = m_Line[B].GetWidth()-Int[B]*2 ;
} else {
Ext[B] = Int[B] = 0 ;
} ;
} ;
m_Line[TOP_LINE].SetTop( m_Top ) ;
m_Line[TOP_LINE].SetLeft( m_Left-Ext[LEFT_LINE]) ;
m_Line[TOP_LINE].SetTop2( m_Top ) ;
m_Line[TOP_LINE].SetLeft2( m_Left+m_Width+Ext[RIGHT_LINE] ) ;
m_Line[BOTTOM_LINE].SetTop( m_Top+m_Height-1 ) ;
m_Line[BOTTOM_LINE].SetLeft( m_Line[TOP_LINE].GetLeft() ) ;
m_Line[BOTTOM_LINE].SetTop2( m_Top+m_Height-1 ) ;
m_Line[BOTTOM_LINE].SetLeft2( m_Line[TOP_LINE].GetLeft2() ) ;
m_Line[LEFT_LINE].SetTop( m_Top-Ext[TOP_LINE] ) ;
m_Line[LEFT_LINE].SetLeft( m_Left ) ;
m_Line[LEFT_LINE].SetTop2( m_Top+m_Height-1+Ext[BOTTOM_LINE] ) ;
m_Line[LEFT_LINE].SetLeft2( m_Left ) ;
m_Line[RIGHT_LINE].SetTop( m_Top-Ext[TOP_LINE] ) ;
m_Line[RIGHT_LINE].SetLeft( m_Left+m_Width-1 ) ;
m_Line[RIGHT_LINE].SetTop2( m_Top+m_Height-1+Ext[BOTTOM_LINE] ) ;
m_Line[RIGHT_LINE].SetLeft2( m_Left+m_Width-1 ) ;
m_FillTop=m_Top+Int[TOP_LINE] ;
m_FillLeft=m_Left+Int[LEFT_LINE] ;
m_FillWidth=m_Width-Int[LEFT_LINE]-Int[RIGHT_LINE] ;
m_FillHeight=m_Height-Int[TOP_LINE]-Int[BOTTOM_LINE] ;
if( m_FillWidth<=0 || m_FillHeight<=0 ) {
m_FillTop=m_FillLeft=m_FillWidth=m_FillHeight=0;
} ;
}
void ClENG_Region::Show( m4int16_t ai_iNumPage, DvcUnit_t ai_XBase, DvcUnit_t ai_YBase )
{
m_poDvc->ShowRegion(this,ai_iNumPage,ai_XBase,ai_YBase) ;
}
void ClENG_Region::Show( m4int16_t ai_iNumPage, DvcUnit_t ai_XBase, DvcUnit_t ai_YBase,
DvcUnit_t ai_HeightPrinted, DvcUnit_t ai_HeightToPrint )
{
m_poDvc->ShowRegion(this,ai_iNumPage,ai_XBase,ai_YBase,ai_HeightPrinted,ai_HeightToPrint) ;
}
void ClENG_Region::ShowOnDvc( m4int16_t ai_iNumPage, DvcUnit_t ai_XBase, DvcUnit_t ai_YBase )
{
m4int16_t B ;
if ( m_uiFillColour!=ClENG_Colour::ID_TRANSPARENT && m_FillWidth>0) {
m_poDvc->SelectColour(ai_iNumPage, m_uiFillColour );
m_poDvc->FillZone(
ai_iNumPage, ai_XBase+m_FillLeft, ai_YBase+m_FillTop, m_FillWidth, m_FillHeight ) ;
} ;
if ( IsHomogeneousFrame() ) {
m_poDvc->SelectColour(ai_iNumPage, m_Line[0].GetIdColour() );
m_poDvc->PrintFrame(
ai_iNumPage, ai_XBase+m_Left, ai_YBase+m_Top, m_Width, m_Height,
m_Line[0].GetWidth(), m_Line[0].GetStyle() ) ;
} else {
for (B=0;B<LINE_COUNT;++B) m_Line[B].Show(ai_iNumPage,ai_XBase,ai_YBase);
} ;
}
void ClENG_Region::ShowOnDvc( m4int16_t ai_iNumPage, DvcUnit_t ai_XBase, DvcUnit_t ai_YBase,
DvcUnit_t ai_HeightPrinted, DvcUnit_t ai_HeightToPrint )
{
m4int16_t B ;
if ( ai_HeightPrinted==0 && ai_HeightToPrint>=m_Height ) {
ShowOnDvc( ai_iNumPage, ai_XBase, ai_YBase ) ;
return ;
} ;
if ( m_uiFillColour!=ClENG_Colour::ID_TRANSPARENT && m_FillWidth>0) {
m_poDvc->SelectColour(ai_iNumPage, m_uiFillColour );
m_poDvc->FillZone(
ai_iNumPage, ai_XBase+m_FillLeft,
ai_HeightPrinted==0 ? ai_YBase+m_FillTop : ai_YBase,
m_FillWidth, ai_HeightToPrint ) ;
} ;
for (B=0;B<LINE_COUNT;++B) m_Line[B].Show(
ai_iNumPage,ai_XBase,ai_YBase,ai_HeightPrinted,ai_HeightToPrint);
}
m4bool_t ClENG_Region::SetFrame( m4char_t *ai_pcBordeProps )
{
m4bool_t SwOk=M4_TRUE ;
m4int16_t B ;
ClMIT_Str StrAux ;
if ( ClMIT_Str::StrLenTrim(ai_pcBordeProps)==0 ) {
SetVisible(FRAME,M4_FALSE) ;
goto exit ;
}
if ( ClMIT_Str::StrLenTrim(ai_pcBordeProps)!= ClENG_Line::GetSizeStrLine()*4 ) {
SwOk=M4_FALSE ;
goto exit ;
} ;
for ( B=0; B<LINE_COUNT; ++B ) {
StrAux.ToASCIZ( &ai_pcBordeProps[
ClENG_Line::GetSizeStrLine()*B], ClENG_Line::GetSizeStrLine() ) ;
if ( ! m_Line[ (LINE_ID)B ].SetLine( StrAux ) ) {
SwOk=M4_FALSE ;
goto exit ;
} ;
} ;
exit:
if (!SwOk) {
/*##Cambiar num msg*/
*m_poInsp->m_poTrace << ClMIT_Msg( ClMIT_Msg::MSG_ERROR, GROUP_ID,
"Sintax error in SetFrame: parameter %0:s", ClMIT_Msg::MIXED_OUT)
<< ai_pcBordeProps << SEND_MSG ;
} ;
return SwOk ;
}
| [
"[email protected]"
] | |
cf8b207f38f2d7fb68faf8bf5479cabbb2cd9be0 | 696e35ccdf167c3f6b1a7f5458406d3bb81987c9 | /chrome/browser/extensions/api/management/chrome_management_api_delegate.cc | 6a9ab04ba5f45f02534f00d68b40b00cba949cda | [
"BSD-3-Clause"
] | permissive | mgh3326/iridium-browser | 064e91a5e37f4e8501ea971483bd1c76297261c3 | e7de6a434d2659f02e94917be364a904a442d2d0 | refs/heads/master | 2023-03-30T16:18:27.391772 | 2019-04-24T02:14:32 | 2019-04-24T02:14:32 | 183,128,065 | 0 | 0 | BSD-3-Clause | 2019-11-30T06:06:02 | 2019-04-24T02:04:51 | null | UTF-8 | C++ | false | false | 14,279 | cc | // Copyright 2014 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.
#include "chrome/browser/extensions/api/management/chrome_management_api_delegate.h"
#include <memory>
#include "base/callback_helpers.h"
#include "base/macros.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/extensions/bookmark_app_helper.h"
#include "chrome/browser/extensions/chrome_extension_function_details.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_util.h"
#include "chrome/browser/extensions/launch_util.h"
#include "chrome/browser/favicon/favicon_service_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser_dialogs.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/extensions/app_launch_params.h"
#include "chrome/browser/ui/extensions/application_launch.h"
#include "chrome/browser/ui/webui/extensions/extension_icon_source.h"
#include "chrome/common/extensions/extension_metrics.h"
#include "chrome/common/extensions/manifest_handlers/app_launch_info.h"
#include "chrome/common/web_application_info.h"
#include "components/favicon/core/favicon_service.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/service_manager_connection.h"
#include "extensions/browser/api/management/management_api.h"
#include "extensions/browser/api/management/management_api_constants.h"
#include "extensions/browser/disable_reason.h"
#include "extensions/browser/extension_prefs.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/extension_system.h"
#include "extensions/common/extension.h"
#include "services/data_decoder/public/cpp/safe_json_parser.h"
namespace {
class ManagementSetEnabledFunctionInstallPromptDelegate
: public extensions::InstallPromptDelegate {
public:
ManagementSetEnabledFunctionInstallPromptDelegate(
content::WebContents* web_contents,
content::BrowserContext* browser_context,
const extensions::Extension* extension,
const base::Callback<void(bool)>& callback)
: install_prompt_(new ExtensionInstallPrompt(web_contents)),
callback_(callback),
weak_factory_(this) {
ExtensionInstallPrompt::PromptType type =
ExtensionInstallPrompt::GetReEnablePromptTypeForExtension(
browser_context, extension);
install_prompt_->ShowDialog(
base::Bind(&ManagementSetEnabledFunctionInstallPromptDelegate::
OnInstallPromptDone,
weak_factory_.GetWeakPtr()),
extension, nullptr,
std::make_unique<ExtensionInstallPrompt::Prompt>(type),
ExtensionInstallPrompt::GetDefaultShowDialogCallback());
}
~ManagementSetEnabledFunctionInstallPromptDelegate() override {}
private:
void OnInstallPromptDone(ExtensionInstallPrompt::Result result) {
base::ResetAndReturn(&callback_).Run(
result == ExtensionInstallPrompt::Result::ACCEPTED);
}
// Used for prompting to re-enable items with permissions escalation updates.
std::unique_ptr<ExtensionInstallPrompt> install_prompt_;
base::Callback<void(bool)> callback_;
base::WeakPtrFactory<ManagementSetEnabledFunctionInstallPromptDelegate>
weak_factory_;
DISALLOW_COPY_AND_ASSIGN(ManagementSetEnabledFunctionInstallPromptDelegate);
};
class ManagementUninstallFunctionUninstallDialogDelegate
: public extensions::ExtensionUninstallDialog::Delegate,
public extensions::UninstallDialogDelegate {
public:
ManagementUninstallFunctionUninstallDialogDelegate(
extensions::ManagementUninstallFunctionBase* function,
const extensions::Extension* target_extension,
bool show_programmatic_uninstall_ui)
: function_(function) {
ChromeExtensionFunctionDetails details(function);
extension_uninstall_dialog_ = extensions::ExtensionUninstallDialog::Create(
details.GetProfile(), details.GetNativeWindowForUI(), this);
bool uninstall_from_webstore =
function->extension() &&
function->extension()->id() == extensions::kWebStoreAppId;
extensions::UninstallSource source;
extensions::UninstallReason reason;
if (uninstall_from_webstore) {
source = extensions::UNINSTALL_SOURCE_CHROME_WEBSTORE;
reason = extensions::UNINSTALL_REASON_CHROME_WEBSTORE;
} else if (function->source_context_type() ==
extensions::Feature::WEBUI_CONTEXT) {
source = extensions::UNINSTALL_SOURCE_CHROME_EXTENSIONS_PAGE;
// TODO: Update this to a new reason; it shouldn't be lumped in with
// other uninstalls if it's from the chrome://extensions page.
reason = extensions::UNINSTALL_REASON_MANAGEMENT_API;
} else {
source = extensions::UNINSTALL_SOURCE_EXTENSION;
reason = extensions::UNINSTALL_REASON_MANAGEMENT_API;
}
if (show_programmatic_uninstall_ui) {
extension_uninstall_dialog_->ConfirmUninstallByExtension(
target_extension, function->extension(), reason, source);
} else {
extension_uninstall_dialog_->ConfirmUninstall(target_extension, reason,
source);
}
}
~ManagementUninstallFunctionUninstallDialogDelegate() override {}
// ExtensionUninstallDialog::Delegate implementation.
void OnExtensionUninstallDialogClosed(bool did_start_uninstall,
const base::string16& error) override {
function_->OnExtensionUninstallDialogClosed(did_start_uninstall, error);
}
private:
extensions::ManagementUninstallFunctionBase* function_;
std::unique_ptr<extensions::ExtensionUninstallDialog>
extension_uninstall_dialog_;
DISALLOW_COPY_AND_ASSIGN(ManagementUninstallFunctionUninstallDialogDelegate);
};
class ChromeAppForLinkDelegate : public extensions::AppForLinkDelegate {
public:
ChromeAppForLinkDelegate() {}
~ChromeAppForLinkDelegate() override {}
void OnFaviconForApp(
extensions::ManagementGenerateAppForLinkFunction* function,
content::BrowserContext* context,
const std::string& title,
const GURL& launch_url,
const favicon_base::FaviconImageResult& image_result) {
WebApplicationInfo web_app;
web_app.title = base::UTF8ToUTF16(title);
web_app.app_url = launch_url;
if (!image_result.image.IsEmpty()) {
WebApplicationInfo::IconInfo icon;
icon.data = image_result.image.AsBitmap();
icon.width = icon.data.width();
icon.height = icon.data.height();
web_app.icons.push_back(icon);
}
bookmark_app_helper_.reset(new extensions::BookmarkAppHelper(
Profile::FromBrowserContext(context), web_app, nullptr,
WebappInstallSource::MANAGEMENT_API));
bookmark_app_helper_->Create(
base::Bind(&extensions::ManagementGenerateAppForLinkFunction::
FinishCreateBookmarkApp,
function));
}
std::unique_ptr<extensions::BookmarkAppHelper> bookmark_app_helper_;
// Used for favicon loading tasks.
base::CancelableTaskTracker cancelable_task_tracker_;
};
} // namespace
ChromeManagementAPIDelegate::ChromeManagementAPIDelegate() {
}
ChromeManagementAPIDelegate::~ChromeManagementAPIDelegate() {
}
void ChromeManagementAPIDelegate::LaunchAppFunctionDelegate(
const extensions::Extension* extension,
content::BrowserContext* context) const {
// Look at prefs to find the right launch container.
// If the user has not set a preference, the default launch value will be
// returned.
extensions::LaunchContainer launch_container =
GetLaunchContainer(extensions::ExtensionPrefs::Get(context), extension);
OpenApplication(AppLaunchParams(Profile::FromBrowserContext(context),
extension, launch_container,
WindowOpenDisposition::NEW_FOREGROUND_TAB,
extensions::SOURCE_MANAGEMENT_API));
extensions::RecordAppLaunchType(extension_misc::APP_LAUNCH_EXTENSION_API,
extension->GetType());
}
GURL ChromeManagementAPIDelegate::GetFullLaunchURL(
const extensions::Extension* extension) const {
return extensions::AppLaunchInfo::GetFullLaunchURL(extension);
}
extensions::LaunchType ChromeManagementAPIDelegate::GetLaunchType(
const extensions::ExtensionPrefs* prefs,
const extensions::Extension* extension) const {
return extensions::GetLaunchType(prefs, extension);
}
void ChromeManagementAPIDelegate::
GetPermissionWarningsByManifestFunctionDelegate(
extensions::ManagementGetPermissionWarningsByManifestFunction* function,
const std::string& manifest_str) const {
data_decoder::SafeJsonParser::Parse(
content::ServiceManagerConnection::GetForProcess()->GetConnector(),
manifest_str,
base::Bind(
&extensions::ManagementGetPermissionWarningsByManifestFunction::
OnParseSuccess,
function),
base::Bind(
&extensions::ManagementGetPermissionWarningsByManifestFunction::
OnParseFailure,
function));
}
std::unique_ptr<extensions::InstallPromptDelegate>
ChromeManagementAPIDelegate::SetEnabledFunctionDelegate(
content::WebContents* web_contents,
content::BrowserContext* browser_context,
const extensions::Extension* extension,
const base::Callback<void(bool)>& callback) const {
return std::unique_ptr<ManagementSetEnabledFunctionInstallPromptDelegate>(
new ManagementSetEnabledFunctionInstallPromptDelegate(
web_contents, browser_context, extension, callback));
}
std::unique_ptr<extensions::UninstallDialogDelegate>
ChromeManagementAPIDelegate::UninstallFunctionDelegate(
extensions::ManagementUninstallFunctionBase* function,
const extensions::Extension* target_extension,
bool show_programmatic_uninstall_ui) const {
return std::unique_ptr<extensions::UninstallDialogDelegate>(
new ManagementUninstallFunctionUninstallDialogDelegate(
function, target_extension, show_programmatic_uninstall_ui));
}
bool ChromeManagementAPIDelegate::CreateAppShortcutFunctionDelegate(
extensions::ManagementCreateAppShortcutFunction* function,
const extensions::Extension* extension,
std::string* error) const {
Browser* browser = chrome::FindBrowserWithProfile(
Profile::FromBrowserContext(function->browser_context()));
if (!browser) {
// Shouldn't happen if we have user gesture.
*error = extension_management_api_constants::kNoBrowserToCreateShortcut;
return false;
}
chrome::ShowCreateChromeAppShortcutsDialog(
browser->window()->GetNativeWindow(), browser->profile(), extension,
base::Bind(&extensions::ManagementCreateAppShortcutFunction::
OnCloseShortcutPrompt,
function));
return true;
}
std::unique_ptr<extensions::AppForLinkDelegate>
ChromeManagementAPIDelegate::GenerateAppForLinkFunctionDelegate(
extensions::ManagementGenerateAppForLinkFunction* function,
content::BrowserContext* context,
const std::string& title,
const GURL& launch_url) const {
favicon::FaviconService* favicon_service =
FaviconServiceFactory::GetForProfile(Profile::FromBrowserContext(context),
ServiceAccessType::EXPLICIT_ACCESS);
DCHECK(favicon_service);
ChromeAppForLinkDelegate* delegate = new ChromeAppForLinkDelegate;
favicon_service->GetFaviconImageForPageURL(
launch_url,
base::Bind(&ChromeAppForLinkDelegate::OnFaviconForApp,
base::Unretained(delegate), base::RetainedRef(function),
context, title, launch_url),
&delegate->cancelable_task_tracker_);
return std::unique_ptr<extensions::AppForLinkDelegate>(delegate);
}
bool ChromeManagementAPIDelegate::CanHostedAppsOpenInWindows() const {
return extensions::util::CanHostedAppsOpenInWindows();
}
bool ChromeManagementAPIDelegate::IsNewBookmarkAppsEnabled() const {
return extensions::util::IsNewBookmarkAppsEnabled();
}
void ChromeManagementAPIDelegate::EnableExtension(
content::BrowserContext* context,
const std::string& extension_id) const {
const extensions::Extension* extension =
extensions::ExtensionRegistry::Get(context)->GetExtensionById(
extension_id, extensions::ExtensionRegistry::EVERYTHING);
// If the extension was disabled for a permissions increase, the Management
// API will have displayed a re-enable prompt to the user, so we know it's
// safe to grant permissions here.
extensions::ExtensionSystem::Get(context)
->extension_service()
->GrantPermissionsAndEnableExtension(extension);
}
void ChromeManagementAPIDelegate::DisableExtension(
content::BrowserContext* context,
const extensions::Extension* source_extension,
const std::string& extension_id,
extensions::disable_reason::DisableReason disable_reason) const {
extensions::ExtensionSystem::Get(context)
->extension_service()
->DisableExtensionWithSource(source_extension, extension_id,
disable_reason);
}
bool ChromeManagementAPIDelegate::UninstallExtension(
content::BrowserContext* context,
const std::string& transient_extension_id,
extensions::UninstallReason reason,
base::string16* error) const {
return extensions::ExtensionSystem::Get(context)
->extension_service()
->UninstallExtension(transient_extension_id, reason, error);
}
void ChromeManagementAPIDelegate::SetLaunchType(
content::BrowserContext* context,
const std::string& extension_id,
extensions::LaunchType launch_type) const {
extensions::SetLaunchType(context, extension_id, launch_type);
}
GURL ChromeManagementAPIDelegate::GetIconURL(
const extensions::Extension* extension,
int icon_size,
ExtensionIconSet::MatchType match,
bool grayscale) const {
return extensions::ExtensionIconSource::GetIconURL(extension, icon_size,
match, grayscale);
}
| [
"[email protected]"
] | |
b03694bc631c65d65a320ebe4ccbd5bce5f089f4 | 37fe1bba682550af3d7f4808a35c84e9d2178ceb | /Source/RobCoG/Utilities/HandInformationParser.h | be5a5cb5eb9dfa020e5346dca8f041ebe90e9c7b | [
"BSD-3-Clause"
] | permissive | yukilikespie/RobCoG_FleX-4.16 | 706ba29ff21043d015f08716c8d85544c78fe6c6 | a6d1e8c0abb8ac1e36c5967cb886de8c154b2948 | refs/heads/master | 2021-06-30T18:01:21.603607 | 2017-09-21T14:20:30 | 2017-09-21T14:20:30 | 103,666,355 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,591 | h | // Copyright 2017, Institute for Artificial Intelligence - University of Bremen
#pragma once
#include "Enums/GraspType.h"
#include "Structs/HandOrientation.h"
#include "Structs/HandVelocity.h"
/**
* This class parses the HandOrientation for all Grasp types out of ini files
*/
class ROBCOG_API HandInformationParser
{
public:
HandInformationParser();
~HandInformationParser();
// Reads the initial and the closed hand orientation out of the ini file
void GetHandInformationForGraspType(FHandOrientation & InitialHandOrientation, FHandOrientation & ClosedHandOrietation, FHandVelocity & HandVelocity, const FString ConfigPath);
void SetHandInformationForGraspType(const FHandOrientation & InitialHandOrientation, const FHandOrientation & ClosedHandOrietation, const FHandVelocity & HandVelocity, const FString ConfigPath);
private:
const FString InitOrientationSection = "InitialHandOrientation";
const FString ClosedOrientationSection = "ClosedHandOrientation";
const FString VelocitySection = "HandVelocity";
// This shared pointer contains the config file
TSharedPtr<FConfigCacheIni> ConfigFileHandler;
// Writes an ini file for a grasptype
void WriteGraspTypeIni(const FHandOrientation & InitialHandOrientation, const FHandOrientation & ClosedHandOrientation, const FHandVelocity & HandVelocity, const FString ConfigPath);
// Reads the initial and the closed hand orientation out of the ini file
void ReadGraspTypeIni(FHandOrientation & InitialHandOrientation, FHandOrientation & ClosedHandOrientation, FHandVelocity & HandVelocity, const FString ConfigPath);
};
| [
"[email protected]"
] | |
bf5874f6bcd66d6c0fce37988bbf33da5b0700f0 | 9ead5fcc5efaf7a73c4c585d813c1cddcb89666d | /m5/src/base/fifo_buffer.hh | f6205330bd6179a862fcf72d5817cbe90f8def0a | [
"BSD-3-Clause"
] | permissive | x10an14/tdt4260Group | b539b6271c8f01f80a9f75249779fb277fa521a4 | 1c4dc24acac3fe6df749e0f41f4d7ab69f443514 | refs/heads/master | 2016-09-06T02:48:04.929661 | 2014-04-08T10:40:22 | 2014-04-08T10:40:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,707 | hh | /*
* Copyright (c) 2002-2005 The Regents of The University of Michigan
* 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 the copyright holders 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.
*
* Authors: Steve Raasch
* Nathan Binkert
*/
#ifndef __FIFO_BUFFER_HH__
#define __FIFO_BUFFER_HH__
#include "base/res_list.hh"
//
// The FifoBuffer requires only that the objects to be used have a default
// constructor and a dump() method
//
template<class T>
class FifoBuffer
{
public:
typedef typename res_list<T>::iterator iterator;
private:
res_list<T> *buffer;
unsigned size;
public:
FifoBuffer(unsigned sz)
{
buffer = new res_list<T>(sz, true, 0);
size = sz;
}
void add(T &item)
{
assert(buffer->num_free() > 0);
buffer->add_head(item);
}
iterator head() { return buffer->head(); }
iterator tail() { return buffer->tail(); }
unsigned count() {return buffer->count();}
unsigned free_slots() {return buffer->num_free();}
T *peek() { return (count() > 0) ? tail().data_ptr() : 0; }
T remove()
{
assert(buffer->count() > 0);
T rval = *buffer->tail();
buffer->remove_tail();
return rval;
}
void dump();
~FifoBuffer() { delete buffer; }
};
#endif
| [
"[email protected]"
] | |
bf8ff95df0190a71aa4c3971fb367832e7582b7e | a72a2e6a96adef9d7f6ad4b913f386c9a4a8e0a4 | /Lec-27/Permuatition.Cpp | f52a958c21636e77954abb8c5678f44627c4f11f | [] | no_license | Mohit29061999/StAndrews-Cpp | dc9d5e022e7ce351682525974da7445e000c28fe | 84025f53a2473ab3142f508fcbdd74e57662b0e8 | refs/heads/master | 2023-02-26T00:06:09.938805 | 2021-01-29T07:32:09 | 2021-01-29T07:32:09 | 298,160,687 | 18 | 6 | null | null | null | null | UTF-8 | C++ | false | false | 550 | cpp | #include <bits/stdc++.h>
using namespace std;
void permuation(char *arr,int i){
//base case
if(arr[i]=='\0'){
cout << arr << endl;
return;
}
//try all character for current position
for(int j=i;arr[j]!='\0';j++){
//a ke place pe c and c ke place pe a
swap(arr[i],arr[j]);
permuation(arr,i+1);
//backtracking step
//c ke place pe a and a pe c
swap(arr[i],arr[j]);
}
}
int main(){
char arr[]="abc";
permuation(arr,0);
}
| [
"[email protected]"
] | |
73e6f9477fa5a2e34b71976ebdb15787a0a8afd2 | 413ee35c5c3e88e9e20daa9bbef8fd74633f0449 | /GAM300_SkyLine/SkyLine/System/Physics/Physics.hpp | 514417e751d919c05dd952e11ea584139d4b04af | [] | no_license | heejae-kwon/Game-Project | 17807b177f7bcd4b5c4c6707e18267a4b013e60d | 810023c9408342f8cdfea499b3afefdddf0e3fd8 | refs/heads/master | 2021-07-16T12:19:36.872803 | 2020-07-05T14:53:30 | 2020-07-05T14:53:30 | 187,778,325 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,519 | hpp | #pragma once
#include <btBulletDynamicsCommon.h>
#include "Rigidbody.hpp"
// TO DO:
// Move btRigidBody ownership from Component::Rigidbodies to Physics
// Handle removing btRigidBody objects from Bullet's world simulator
class Physics {
public:
Physics() = delete;
// Make sure you set gravity to a negative float, unless you want weird gravity for some raisin
Physics(float gravity);
~Physics();
void Initialize();
void Update(float dt);
void addRigidbody(Component::Rigidbody& rb);
std::vector<Component::Rigidbody*>& getRigidBodies() { return rigidBodies_; }
btRigidBody* add_RB_Box(float width, float height, float depth, float x, float y, float z, float mass);
btRigidBody* add_RB_Sphere(float rad, float x, float y, float z, float mass);
btRigidBody* add_RB_Cylinder(float d, float h, float x, float y, float z, float mass);
btRigidBody* add_RB_Cone(float d, float h, float x, float y, float z, float mass);
btRigidBody* add_RB_StaticPlane(float x, float y, float z);
private:
float timeStepAccumulator_ = 0.0f;
std::vector<Component::Rigidbody*> rigidBodies_;
// Bullet specific stuff below
// This is simply holds configuration options
btDefaultCollisionConfiguration * collisionConfig_;
// CollisionDispatcher iterates over each pair and uses the appropriate collision algorithm to compute contact points
// TLDR: Bullet uses this to calculate WHERE and HOW two objects are colliding
btCollisionDispatcher * collisionDispatcher_;
// Broadphase is basically a fast "initial" algorithm pass to reject pairs of objects
// Broadphase adds and removes overlapping pairs from a pair cache
// Bullet has three different algorithms available all inheriting from the base btBroadPhaseInterface type:
// btBroadphaseInterface foobar =
// 1) btDbvtBroadphase : a fast dynamic bounding volume hierarchy based on AABB tree (Axis aligned bounding boxes)
// 2) btAxisSweep3 : incremental 3D sweep and prune
// 3) btCudaBroadphase : fast uniform grid using GPU hardware
// For our purposes we will be using 1)
btBroadphaseInterface* broadphaseInterface_;
btSequentialImpulseConstraintSolver* constraintSolver_;
// The actual world simulator
btDiscreteDynamicsWorld* dynamicWorld_;
// Bullet has its own array type to handle its collision objects
// This is only here because we need to delete these ourselves
btAlignedObjectArray<btRigidBody*> bodies_;
}; | [
"[email protected]"
] | |
a0c05ad6bd3465845b55a41c38c0614e5f43c2f2 | 451ff5a40071578341ca195908276992bd5396fa | /AtCoder/Educational DP/A - Frog 1.cpp | eabd2c432230555bb130bbf242acf7bddca8211b | [] | no_license | Tanjim131/Problem-Solving | ba31d31601798ba585a3f284bb169d67794af6c0 | 6dc9c0023058655ead7da7da08eed11bf48a0dfa | refs/heads/master | 2023-05-02T06:38:34.014689 | 2021-05-14T18:26:15 | 2021-05-14T18:26:15 | 267,421,671 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 828 | cpp | #include <iostream>
#include <vector>
#include <algorithm>
#include <cstdlib>
using namespace std;
int solve(const vector <int> &heights, vector <int> &dp, int current){
if(current == 0){
return 0;
}
if(dp[current] != -1){
return dp[current];
}
int cost1 = solve(heights, dp, current - 1) + abs(heights[current] - heights[current - 1]);
int cost2 = numeric_limits <int>::max();
if(current > 1) cost2 = solve(heights, dp, current - 2) + abs(heights[current] - heights[current - 2]);
return dp[current] = min(cost1, cost2);
}
int main(int argc, char const *argv[])
{
int N;
cin >> N;
vector <int> heights(N);
for(int i = 0 ; i < N ; ++i){
cin >> heights[i];
}
vector <int> dp(N, -1);
cout << solve(heights, dp, N - 1) << '\n';
return 0;
}
| [
"[email protected]"
] | |
67d22e00252008eec695916738f51e3af35b237e | 8356073845231d63c578818b3043c0d3e0973c80 | /Lightoj/1316 - A Wedding Party.cpp | 4d1944b440e06d3a4ad61267f82011721bff28c2 | [] | no_license | anis028/Problem-solving | cce12d0273afbb1573c9a1eec2659f0fc363c71b | 3bc50ed9ff4d0ed1d80423a2ed1fdb1788d776b4 | refs/heads/master | 2020-07-06T19:57:54.889585 | 2019-08-21T10:20:12 | 2019-08-21T10:20:12 | 203,124,065 | 7 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,614 | cpp | #include<bits/stdc++.h>
#define db(x) printf("**%d\n",x)
#define pb push_back
#define pii pair<int,int>
#define pip pair<int,pair<int,int> >
#define mod 1000000007
#define mm(x,y) memset(x,y,sizeof(x))
#define fs first
#define sc second
using namespace std;
typedef long long ll;
typedef double dbl;
const int INF = 0x3f3f3f3f;
vector< pii > G[505], RG[20];
int best, best_cost, shoploc[20], shopid[505], d[505], cost[17][1<<15], pops[1<<15];
void dijkstra(int s) {
int u, v, w, e, i, sz;
priority_queue< pii, vector< pii >, greater< pii > > Q;
memset(d, 0x3f, sizeof d);
Q.push(pii(0, s));
d[s] = 0;
while(!Q.empty()) {
u = Q.top().second;
w = Q.top().first;
Q.pop();
if(d[u] < w) continue;
sz = G[u].size();
for(i = 0; i < sz; i++) {
v = G[u][i].first;
e = G[u][i].second;
if(d[v] > d[u] + e) {
d[v] = d[u] + e;
Q.push(pii(d[v], v));
}
}
}
}
void dijkstra2(int s, int t, int ns) {
int mask, u, w, sz, i, v, e, nmask, nb;
priority_queue< pip, vector< pip >, greater< pip > > Q;
memset(cost, 0x3f, sizeof cost);
if(s >= ns) mask = 0; else mask = 1 << s;
Q.push(pip(0, pii(s, mask)));
cost[s][mask] = 0;
while(!Q.empty()) {
u = Q.top().second.first;
mask = Q.top().second.second;
w = Q.top().first;
Q.pop();
if(cost[u][mask] < w) continue;
sz = RG[u].size();
for(i = 0; i < sz; i++) {
v = RG[u][i].first;
e = RG[u][i].second;
nmask = mask;
if(v < ns) nmask |= (1 << v);
if(cost[v][nmask] > e + cost[u][mask]) {
cost[v][nmask] = e + cost[u][mask];
Q.push(pip(cost[v][nmask], pii(v, nmask)));
}
}
}
best = 0, best_cost = INF;
for(i = 0; i < (1 << ns); i++) {
if(cost[t][i] < INF) {
nb = pops[i];
if(nb > best) {
best = nb;
best_cost = cost[t][i];
}
else if(nb == best) {
best_cost = min(best_cost, cost[t][i]);
}
}
}
}
int main() {
int test, cs, n, rn, e, s, i, u, v, w;
scanf("%d", &test);
for(i = 0; i < (1 << 15); i++) pops[i] = __builtin_popcount(i);
for(cs = 1; cs <= test; cs++) {
scanf("%d %d %d", &n, &e, &s);
memset(shopid, -1, sizeof(shopid));
for(i = 0; i < s; i++) {
scanf("%d", &u);
shoploc[i] = u;
shopid[u] = i;
}
if(shopid[0] == -1) {
shopid[0] = i;
shoploc[i++] = 0;
}
if(shopid[n-1] == -1) {
shopid[n-1] = i;
shoploc[i++] = n-1;
}
rn = i;
for(i = 0; i < n; i++) G[i].clear();
for(i = 0; i < e; i++) {
scanf("%d %d %d", &u, &v, &w);
G[u].push_back(pii(v, w));
}
for(i = 0; i < rn; i++) {
RG[i].clear();
dijkstra(shoploc[i]);
for(u = 0; u < n; u++) {
if(u != shoploc[i] && shopid[u] != -1 && d[u] < INF) {
RG[i].push_back(pii(shopid[u], d[u]));
}
}
}
dijkstra2(shopid[0], shopid[n-1], s);
if(best_cost < INF) printf("Case %d: %d %d\n", cs, best, best_cost);
else printf("Case %d: Impossible\n", cs);
}
return 0;
}
/*sample
*/
| [
"[email protected]"
] | |
ae7d97958bbe1798a425f9f00b34d0dca4820e3b | 7df8ea3fe9e430b0f3e39afc402763edf9382c0f | /Source/ConnectFour/SelectorTile.cpp | 0a9e30ee011b7dd3dfbc74617f3f246f1fc6e30d | [
"MIT"
] | permissive | StevenCaoZRC/ConnectFour | 694bb5c9635c36dd9e0f5f815372047e9b6ea30c | 8df8bdf366d7c684736be474af130346aabfb27d | refs/heads/master | 2022-12-26T11:27:27.150038 | 2020-10-05T00:49:27 | 2020-10-05T00:49:27 | 299,800,996 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 377 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "SelectorTile.h"
ASelectorTile::ASelectorTile()
{
//Establish the Tile type for Selector tiles. This will determine its mesh
TileType = ETileTypes::SELECTOR;
}
void ASelectorTile::BeginPlay()
{
Super::BeginPlay();
//bool Initialise(_CanInteract, _Occupied);
Initialise(true);
}
| [
"[email protected]"
] | |
e06538ffb65d7be4e404db22b1b54b95bfc7ec73 | c724b322b2569cca483d2efc7e4f72891489bec6 | /arduino/IoTServer/ThingSpeak/dht11_client_dev/dht11_client_dev.ino | 15db0afd355c3a2cac033aba7b2b06b2711b4ce8 | [] | no_license | lunix983/iotelasticproject | 11417fc4359b00c4e321479a261901c23c06775f | f7509846198957d791c820901ed87729c444c79a | refs/heads/master | 2021-09-17T02:40:28.284447 | 2018-06-26T21:12:12 | 2018-06-26T21:12:12 | 124,667,788 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,674 | ino |
#include <DHT.h>
#include <SdFat.h>
#include <FreeStack.h>
#include <SdFatConfig.h>
#include <BlockDriver.h>
#include <SysCall.h>
#include <MinimumSerial.h>
#include <SPI.h>
#include <RH_RF95.h>
/*
Upload Data to IoT Server ThingSpeak (https://thingspeak.com/):
Support Devices: LoRa Shield + Arduino
Example sketch showing how to read Temperature and Humidity from DHT11 sensor,
Then send the value to LoRa Gateway, the LoRa Gateway will send the value to the
IoT server
It is designed to work with the other sketch dht11_server.
modified 24 11 2016
by Edwin Chen <[email protected]>
Dragino Technology Co., Limited
*/
/*#include <String.h>*/
RH_RF95 rf95;
#define DHTPIN 7
#define DHTTYPE DHT11
//#define dht_dpin A0 // Use A0 pin as Data pin for DHT11.
int dht_dpin = 7;
byte bGlobalErr;
char dht_dat[5]; // Store Sensor Data
char node_id[3] = {1,1,1}; //LoRa End Node ID
String stringOne;
float frequency = 868.0;
unsigned int count = 1;
DHT dht(DHTPIN, DHTTYPE);
void setup()
{
// InitDHT();
Serial.begin(9600);
if (!rf95.init())
Serial.println("init failed");
// Setup ISM frequency
rf95.setFrequency(frequency);
// Setup Power,dBm
rf95.setTxPower(13);
dht.begin();
Serial.println("LoRa End Node Example --");
Serial.println(" DHT11 Temperature and Humidity Sensor by Luix\n");
Serial.print("LoRa End Node ID: ");
for(int i = 0;i < 3; i++)
{
Serial.print(node_id[i],HEX);
}
Serial.println();
}
void InitDHT()
{
pinMode(dht_dpin,OUTPUT);//Set A0 to output
digitalWrite(dht_dpin,HIGH);//Pull high A0
}
//Get Sensor Data
void ReadDHT()
{
bGlobalErr=0;
byte dht_in;
byte i;
//pinMode(dht_dpin,OUTPUT);
digitalWrite(dht_dpin,LOW);//Pull Low A0 and send signal
delay(30);//Delay > 18ms so DHT11 can get the start signal
digitalWrite(dht_dpin,HIGH);
delayMicroseconds(40);//Check the high level time to see if the data is 0 or 1
pinMode(dht_dpin,INPUT);
// delayMicroseconds(40);
dht_in=digitalRead(dht_dpin);//Get A0 Status
// Serial.println(dht_in,DEC);
if(dht_in){
bGlobalErr=1;
return;
}
delayMicroseconds(80);//DHT11 send response, pull low A0 80us
dht_in=digitalRead(dht_dpin);
if(!dht_in){
bGlobalErr=2;
return;
}
delayMicroseconds(80);//DHT11 send response, pull low A0 80us
for (i=0; i<5; i++)//Get sensor data
dht_dat[i] = read_dht_dat();
pinMode(dht_dpin,OUTPUT);
digitalWrite(dht_dpin,HIGH);//release signal and wait for next signal
byte dht_check_sum = dht_dat[0]+dht_dat[1]+dht_dat[2]+dht_dat[3];//calculate check sum
if(dht_dat[4]!= dht_check_sum)//check sum mismatch
{bGlobalErr=3;}
};
byte read_dht_dat(){
byte i = 0;
byte result=0;
for(i=0; i< 8; i++)
{
while(digitalRead(dht_dpin)==LOW);//wait 50us
delayMicroseconds(30);//Check the high level time to see if the data is 0 or 1
if (digitalRead(dht_dpin)==HIGH)
result |=(1<<(7-i));//
while (digitalRead(dht_dpin)==HIGH);//Get High, Wait for next data sampleing.
}
return result;
}
uint16_t calcByte(uint16_t crc, uint8_t b)
{
uint32_t i;
crc = crc ^ (uint32_t)b << 8;
for ( i = 0; i < 8; i++)
{
if ((crc & 0x8000) == 0x8000)
crc = crc << 1 ^ 0x1021;
else
crc = crc << 1;
}
return crc & 0xffff;
}
uint16_t CRC16(uint8_t *pBuffer,uint32_t length)
{
uint16_t wCRC16=0;
uint32_t i;
if (( pBuffer==0 )||( length==0 ))
{
return 0;
}
for ( i = 0; i < length; i++)
{
wCRC16 = calcByte(wCRC16, pBuffer[i]);
}
return wCRC16;
}
void loop()
{
Serial.print("########### ");
Serial.print("COUNT=");
Serial.print(count);
Serial.println(" ###########");
count++;
// ReadDHT();
char data[50] = {0} ;
int dataLength = 7; // Payload Length
// Use data[0], data[1],data[2] as Node ID
data[0] = node_id[0] ;
data[1] = node_id[1] ;
data[2] = node_id[2] ;
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
int tempIntPart = t;
int tempDecPart = (t - tempIntPart) * 100;
int umIntPart = h;
int unDecPart = (h - umIntPart) * 100;
data[3] = umIntPart;
data[4] = unDecPart;
data[5] = tempIntPart;
data[6] = tempDecPart;
// String umidityIntegerStr = buffer_um[0]+ String("") + buffer_um[1];
// Serial.println(umidityIntegerStr);
switch (bGlobalErr)
{
case 0:
Serial.print("Current humidity = ");
Serial.print(data[3], DEC);//Show humidity
Serial.print(".");
Serial.print(data[4], DEC);//Show humidity
Serial.print("% ");
Serial.print("temperature = ");
Serial.print(data[5], DEC);//Show temperature
Serial.print(".");
Serial.print(data[6], DEC);//Show temperature
Serial.println("C ");
break;
case 1:
Serial.println("Error 1: DHT start condition 1 not met.");
break;
case 2:
Serial.println("Error 2: DHT start condition 2 not met.");
break;
case 3:
Serial.println("Error 3: DHT checksum error.");
break;
default:
Serial.println("Error: Unrecognized code encountered.");
break;
}
uint16_t crcData = CRC16((unsigned char*)data,dataLength);//get CRC DATA
//Serial.println(crcData,HEX);
Serial.print("Data to be sent(without CRC): ");
int i;
for(i = 0;i < dataLength; i++)
{
Serial.print(data[i],HEX);
Serial.print(" ");
}
Serial.println();
unsigned char sendBuf[50]={0};
for(i = 0;i < dataLength;i++)
{
sendBuf[i] = data[i] ;
}
sendBuf[dataLength] = (unsigned char)crcData; // Add CRC to LoRa Data
sendBuf[dataLength+1] = (unsigned char)(crcData>>8); // Add CRC to LoRa Data
Serial.print("Data to be sent(with CRC): ");
for(i = 0;i < (dataLength +2); i++)
{
Serial.print(sendBuf[i],HEX);
Serial.print(" ");
}
Serial.println();
rf95.send(sendBuf, dataLength+2);//Send LoRa Data
uint8_t buf[RH_RF95_MAX_MESSAGE_LEN];//Reply data array
uint8_t len = sizeof(buf);//reply data length
if (rf95.waitAvailableTimeout(3000))// Check If there is reply in 3 seconds.
{
// Should be a reply message for us now
if (rf95.recv(buf, &len))//check if reply message is correct
{
if(buf[0] == node_id[0] ||buf[1] == node_id[2] ||buf[2] == node_id[2] ) // Check if reply message has the our node ID
{
pinMode(4, OUTPUT);
digitalWrite(4, HIGH);
Serial.print("Got Reply from Gateway: ");//print reply
Serial.println((char*)buf);
delay(400);
digitalWrite(4, LOW);
//Serial.print("RSSI: "); // print RSSI
//Serial.println(rf95.lastRssi(), DEC);
}
}
else
{
Serial.println("recv failed");//
rf95.send(sendBuf, strlen((char*)sendBuf));//resend if no reply
}
}
else
{
Serial.println("No reply, is LoRa gateway running?");//No signal reply
rf95.send(sendBuf, strlen((char*)sendBuf));//resend data
}
delay(30000); // Send sensor data every 30 seconds
Serial.println("");
}
| [
"[email protected]"
] | |
7e882256a08ab76974f4434afd45e01eadcdcd29 | 865bfdce73e6c142ede4a7c9163c2ac9aac5ceb6 | /Source/Game/UI/Scenes/UIScene_Dialog.cpp | ab59fc9e15d29c495b77aba0eb6db79936d57ee8 | [] | no_license | TLeonardUK/ZombieGrinder | d1b77aa0fcdf4a5b765e394711147d5621c8d4e8 | 8fc3c3b7f24f9980b75a143cbf37fab32cf66bbf | refs/heads/master | 2021-03-19T14:20:54.990622 | 2019-08-26T16:35:58 | 2019-08-26T16:35:58 | 78,782,741 | 6 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 2,660 | cpp | // ===================================================================
// Copyright (C) 2013 Tim Leonard
// ===================================================================
#include "Game/UI/Scenes/UIScene_Dialog.h"
#include "Engine/UI/Transitions/UISlideInTransition.h"
#include "Engine/UI/Transitions/UIFadeOutTransition.h"
#include "Engine/UI/Layouts/UILayoutFactory.h"
#include "Engine/Platform/Platform.h"
#include "Engine/Display/GfxDisplay.h"
#include "Engine/Input/Input.h"
#include "Engine/UI/UIManager.h"
#include "Engine/UI/Elements/UIPanel.h"
#include "Engine/UI/Elements/UISlider.h"
#include "Engine/UI/Elements/UIListView.h"
#include "Engine/UI/Elements/UIProgressBar.h"
#include "Engine/UI/Elements/UILabel.h"
#include "Engine/Renderer/RenderPipeline.h"
#include "Engine/Resources/ResourceFactory.h"
#include "Engine/Localise/Locale.h"
#include "Game/UI/Scenes/UIScene_Game.h"
#include "Game/Runner/Game.h"
#include "Engine/Engine/EngineOptions.h"
#include "Game/Runner/GameOptions.h"
UIScene_Dialog::UIScene_Dialog(std::string value, std::string button_text, bool game_style, bool large_size, std::string override_layout)
: m_text(value)
, m_game_style(game_style)
{
if (override_layout != "")
{
Set_Layout(override_layout.c_str());
}
else
{
if (game_style)
{
if (large_size)
{
Set_Layout("large_dialog");
}
else
{
Set_Layout("dialog");
}
}
else
{
Set_Layout("editor_dialog");
}
}
if (button_text != "")
{
Find_Element<UILabel*>("back_button")->Set_Value(button_text.c_str());
}
}
bool UIScene_Dialog::Can_Accept_Invite()
{
return false;
}
const char* UIScene_Dialog::Get_Name()
{
return "UIScene_Dialog";
}
bool UIScene_Dialog::Should_Render_Lower_Scenes()
{
return true;
}
bool UIScene_Dialog::Should_Display_Cursor()
{
return true;
}
bool UIScene_Dialog::Should_Display_Focus_Cursor()
{
return m_game_style;
}
bool UIScene_Dialog::Is_Focusable()
{
return true;
}
void UIScene_Dialog::Enter(UIManager* manager)
{
Find_Element<UILabel*>("label")->Set_Value(S(m_text.c_str()));
}
void UIScene_Dialog::Exit(UIManager* manager)
{
}
void UIScene_Dialog::Tick(const FrameTime& time, UIManager* manager, int scene_index)
{
UIScene::Tick(time, manager, scene_index);
}
void UIScene_Dialog::Draw(const FrameTime& time, UIManager* manager, int scene_index)
{
UIScene::Draw(time, manager, scene_index);
}
void UIScene_Dialog::Recieve_Event(UIManager* manager, UIEvent e)
{
switch (e.Type)
{
case UIEventType::Button_Click:
{
if (e.Source->Get_Name() == "back_button")
{
manager->Go(UIAction::Pop(new UIFadeOutTransition()));
}
}
break;
}
}
| [
"[email protected]"
] | |
86bc20288809bb8f1215dbee660172d12e66ae8d | fa59c8294096f9019a1a10e556a1d4ba6f19eed0 | /include/eagine/memory/buffer.hpp | 1ef13377544e257d311f15cb0f09ec10e1defb58 | [
"BSL-1.0"
] | permissive | flajann2/oglplu2 | 35312df54eda8f90039127893acccc200c6f0ea3 | 5c964d52ae3fa53cbd7b8a18f735c25d166092cb | refs/heads/master | 2020-04-23T08:15:11.733546 | 2019-02-02T18:40:19 | 2019-02-02T18:40:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,129 | hpp | /**
* @file eagine/memory/buffer.hpp
*
* Copyright Matus Chochlik.
* 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
*/
#ifndef EAGINE_MEMORY_BUFFER_HPP
#define EAGINE_MEMORY_BUFFER_HPP
#include "block.hpp"
#include "default_alloc.hpp"
#include "shared_alloc.hpp"
namespace eagine {
namespace memory {
class buffer {
public:
using size_type = typename block::size_type;
using pointer = typename block::pointer;
private:
span_size_t _size;
span_size_t _align;
owned_block _storage;
shared_byte_allocator _alloc;
bool _is_ok() const noexcept {
return bool(_alloc) && size() <= capacity();
}
void _reallocate(span_size_t new_size) {
_alloc.do_reallocate(_storage, new_size, _align);
}
public:
explicit buffer(span_size_t align)
: _size(0)
, _align(align)
, _alloc(default_byte_allocator()) {
}
buffer()
: buffer(alignof(long double)) {
}
buffer(const buffer&) = delete;
~buffer() noexcept {
free();
}
auto addr() const noexcept {
return _storage.addr();
}
pointer data() const noexcept {
return _storage.data();
}
span_size_t size() const noexcept {
return _size;
}
span_size_t capacity() const noexcept {
return _storage.size();
}
void reserve(span_size_t new_size) {
if(capacity() < new_size) {
_reallocate(new_size);
}
assert(_is_ok());
}
void resize(span_size_t new_size) {
reserve(new_size);
_size = new_size;
assert(_is_ok());
}
void free() {
_alloc.deallocate(std::move(_storage), _align);
_size = 0;
}
operator block() noexcept {
assert(_is_ok());
return {_storage.begin(), _size};
}
operator const_block() const noexcept {
assert(_is_ok());
return {_storage.begin(), _size};
}
};
} // namespace memory
} // namespace eagine
#endif // EAGINE_MEMORY_BUFFER_HPP
| [
"[email protected]"
] | |
500ff0fe9435846d9cb2d8e015e0348749d49654 | 86f9dd1176a3aa6f7a9b472d91de97791c19ae2d | /Domains/RoverPOIDomain/RoverPOIDomain.cpp | 812c1a6132a73c299f144cf24635ae1c861304b6 | [] | no_license | MorS25/libraries | 6139f3e6856cdad836930fa51c4790a896ed8dc0 | d595819ab2aabbe7b34e0c33898b4682b40532d3 | refs/heads/master | 2021-05-31T05:36:47.396330 | 2015-09-19T00:53:52 | 2015-09-19T00:53:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,000 | cpp | #include "RoverPOIDomain.h"
/*
RoverPOIDomain::RoverPOIDomain(void):nPOIs(10),teleportation(false)
{
}
RoverPOIDomain::~RoverPOIDomain(void)
{
}
void RoverPOIDomain::initializeRoverDomain(bool usingTypesSet, bool teleportationSet, std::string rewardSet, bool firstInitialization){
//printf("Deprecated functions removed, needs rewrite.");
// Initialize run constants
usingTypes = usingTypesSet;
teleportation = teleportationSet;
rewardType = rewardSet;
nStateElements = NSECTORS*NDISTANCES*(2+FAILTYPECOUNT*int(usingTypes)); // first two are COUNTS of ALL POIs/rovers, failtypecount/sector for rest
// Place the POIs in the world
if (firstInitialization){
generatePOIs(); // generate POIs
generateStaticPOIPositions(); // Place POIs uniquely+save positions
}
// Place the rovers in the world
generateRovers(); // generate Rovers
generateStaticRoverPositions(); // Place rovers in graph, store original places
// initializeNeuralNetPopulation(); // initialize Neural Net (NOTE, HARDCODING IN THIS FUNCTION) // deprecated
}
std::vector<double> RoverPOIDomain::getDifferenceReward(){
//If more than two robots visit a POI, only the observations of the closest two are considered,
// and their visit distances are averaged in the computation of the system evaluation
std::vector<double> D(rovers.size(),0.0); // D for all of the rovers
typedef std::pair<double,int> P;
for (int i=0; i<POIs.size(); i++){
POI p = POIs[i];
// Get all distances to POI
PairQueueAscending q = sortedRoverDists(p.x,p.y);
// Get top 3 closest (dij, dik, dil) in order closest to farthest
double dij = q.top().first;
double j = q.top().second;
q.pop();
double dik = q.top().first;
double k = q.top().second;
q.pop();
double dil = q.top().first;
double l = q.top().second;
// BEGIN MODIFICATION
double gatheredValjk, gatheredValjl,gatheredValkl; // modification
double multiplej, multiplek,multiplel; // modification
// average the multiples based on type...
if (rovers[j].type==0){
multiplej=0.25;
} else if (rovers[j].type==2){
multiplej=0.5;
} else if (rovers[j].type==3){
multiplej=0.75;
}
if (rovers[k].type==0){
multiplek=0.25;
} else if (rovers[k].type==2){
multiplek=0.5;
} else if (rovers[k].type==3){
multiplek=0.75;
}
if (rovers[l].type==0){
multiplel=0.25;
} else if (rovers[l].type==2){
multiplel=0.5;
} else if (rovers[l].type==3){
multiplel=0.75;
}
gatheredValjk = p.val*(multiplej+multiplek);
gatheredValjl = p.val*(multiplej+multiplel);
gatheredValkl = p.val*(multiplek+multiplel);
// END MODIFICATION
if (dil<deltaO){
//D[unsigned(j)]+=2.0*p.val*(1.0/(dik+dij+2.0)-1.0/(dik+dil+2.0)); // original
//D[unsigned(k)]+=2.0*p.val*(1.0/(dik+dij+2.0)-1.0/(dij+dil+2.0)); // original
D[unsigned(j)]+=gatheredValjk/(dik+dij+2.0)-gatheredValkl/(dik+dil+2.0); // modified
} else if ((dij<deltaO) && (dik<deltaO)){
D[unsigned(j)]+=2.0*gatheredValjk/(dik+dij+2.0); // reduces to original
D[unsigned(k)]+=2.0*gatheredValjk/(dik+dij+2.0);
}
}
return D;
}
double RoverPOIDomain::getLocalReward(int me){
// Returns Pj(z)
double L = 0.0;
for (int i=0; i<POIs.size(); i++){
double deltaMe = gridDistance(POIs[i].x,POIs[i].y,rovers[me].x,rovers[me].y);
if (deltaMe<deltaO){
double gatheredVal = POIs[i].val/deltaMe;
// BEGIN VALUE MODIFICATION*********
if (rovers[me].type==0){
gatheredVal*=0.25;
} else if (rovers[me].type==2){
gatheredVal*=0.5;
} else if (rovers[me].type==3){
gatheredVal*=0.75;
}
// END VALUE MODIFICATION************
L+=gatheredVal;
}
}
return L;
}
void RoverPOIDomain::simulateRunRoverDomain(){
// Performs |maxSteps| number of epochs, consisting of some number of steps, for the rover domain.
// Randomizes starting positions between the rovers. These are reset to be the same during a single epoch though.
int maxEpochs = 1000;
for (int T=0; T<maxEpochs; T++){
//printf("T=%i\n",T);
simulateEpochRoverDomain();
generateStaticRoverPositions();
}
}
double RoverPOIDomain::getGlobalReward(){
//If more than two robots visit a POI, only the observations of the closest two are considered,
// and their visit distances are averaged in the computation of the system evaluation
rovers;
double G=0.0;
for (int i=0; i<POIs.size(); i++){
POI p = POIs[i];
// Get all distances to POI
PairQueueAscending q = sortedRoverDists(p.x,p.y);
double dij = q.top().first; // closest, DISTANCE
int jID = q.top().second; // closest, ID
q.pop();
double dik = q.top().first; // second closest, DISTANCE
int kID = q.top().second; // second closest, ID
double Nij = 0.0;
double Nik = 0.0;
if (dij<deltaO){
Nij=1.0;
}
if (dik<deltaO){
Nik=1.0;
}
// BEGIN MODIFICATION
double gatheredVal; // modification
double multiplej, multiplek; // modification
// average the multiples based on type...
if (rovers[jID].type==0){
multiplej=0.25;
} else if (rovers[jID].type==2){
multiplej=0.5;
} else if (rovers[jID].type==3){
multiplej=0.75;
} else {
multiplej=1.0;
}
if (rovers[kID].type==0){
multiplek=0.25;
} else if (rovers[kID].type==2){
multiplek=0.5;
} else if (rovers[kID].type==3){
multiplek=0.75;
} else {
multiplek = 1.0;
}
// END MODIFICATION
gatheredVal = POIs[i].val*(multiplej+multiplek);
G += 2.0*(gatheredVal*Nij*Nik)/(dij+dik+2.0);
}
return G;
}
void RoverPOIDomain::simulateEpochRoverDomain(){
if (!rovers.size()){
printf("No rovers! Aborting.");
exit(1);
}
double gAvg = 0;
int gCount = 0;
int steps;
if(teleportation) steps=1;
else steps = 10;
double travelScale;
if (teleportation) travelScale = TRAVELBOUND; // MOVE TO INITIALIZATION
else travelScale = 1.0; // MOVE TO INITIALIZATION
logRoverPositions(); // logs the starting position
for (int i=0; i<rovers.size(); i++){
rovers[i].evo.generateNewMembers();
}
while(true){
for (int i=0; i<steps; i++){
std::vector<std::vector<double> > xyActions(rovers.size()); // list of xy coordinates to move to
for (int j=0; j<rovers.size(); j++){
// select xy-coordinates here... scale selection as percent of POSSIBLE distance
xyActions[j] = rovers[j].selectNNActionMultiple(getState(j));
// scale to domain
xyActions[j][0]*=travelScale; // this is the DX ACTION
xyActions[j][1]*=travelScale; // this is the DY ACTION
}
for (int j=0; j<rovers.size(); j++){
rovers[j].walk(xyActions[j][0],xyActions[j][1],percentFail);
}
logRoverPositions();
}
// Calculate reward and update NOTE: THIS IS ONLY GLOBAL REWARD
double epG = getGlobalReward();
gAvg += epG;
gCount++;
std::vector<double> rewards(rovers.size(),0);
if (!strcmp(rewardType.c_str(),"global")){
rewards = std::vector<double>(rovers.size(),epG);
} else if (!strcmp(rewardType.c_str(),"difference")){
rewards = getDifferenceReward();
} else if (!strcmp(rewardType.c_str(),"local")){
for (int i=0; i<rovers.size(); i++){
rewards[i] = getLocalReward(i);
}
}
bool epochDone = false;
for (int i=0; i<rovers.size(); i++){
rovers[i].evo.updateMember(epG);
if (!rovers[i].evo.selectNewMember()) epochDone = true;
}
if (epochDone){
break;
gAvg /= double(gCount);
}
resetForEpoch(); // reset the domain for the next epoch, as it was before
}
for (int i=0; i<rovers.size(); i++){
rovers[i].evo.selectSurvivors();
}
performanceVals.push_back(gAvg);
}
void RoverPOIDomain::resetForEpoch(){
// Replace rovers
resetStaticRovers(); // later; make sure static positions are changed between epochs...
}
void RoverPOIDomain::generateStaticPOIPositions(){
for (int i=0; i<POIs.size(); i++){
staticPOIPositions.push_back(std::vector<double>(2,0.0));
double randX = bounds.size('x')*double(rand())/double(RAND_MAX);
double randY = bounds.size('y')*double(rand())/double(RAND_MAX);
POIs[i].x = randX;
POIs[i].y = randY;
staticPOIPositions[i][0] = randX;
staticPOIPositions[i][1] = randY;
}
}
GridWorld::PairQueueAscending RoverPOIDomain::sortedPOIDists(double xref, double yref){
typedef std::pair<double,int> P;
std::vector<P> dists(POIs.size(),std::make_pair<double,int>(0.0,0));
for (int j=0; j<POIs.size(); j++){
dists[j]=P(gridDistance(xref,yref,POIs[j].x,POIs[j].y),j);
}
PairQueueAscending q(dists.begin(),dists.end());
return q;
}
State RoverPOIDomain::getState(int me)
{
// NEW sonar state... go by quadrant AND distance...
// note here only quadrant is implemented
// State elements/init
std::vector<std::vector<double> > poisByQuadrantAndDistance(NSECTORS); // count POIs for each sector
std::vector<std::vector<double> > roversByQuadrantAndDistance(NSECTORS); // count POIs for each sector
std::vector<std::vector<std::vector<double> > > roverTypeCountByQuadrantAndDistance; // used if using types [QUADRANT][DIST][TYPE]
std::vector<double> stateInputs;
// Reserve space
for (int i=0; i<NSECTORS;i++){
poisByQuadrantAndDistance[i] = std::vector<double>(NDISTANCES,0.0);
roversByQuadrantAndDistance[i] = std::vector<double>(NDISTANCES,0.0);
}
// Counting rovers by quadrant
for (int i=0; i<POIs.size(); i++){
std::pair<Direction,DistanceDivision> quadAndDist = relativePosition(rovers[me].x,rovers[me].y,POIs[i].x,POIs[i].y);
int quadrant = int(quadAndDist.first);
int dist = int(quadAndDist.second);
poisByQuadrantAndDistance[quadrant][dist]++;
}
// Normalization
for (int i=0; i<poisByQuadrantAndDistance.size(); i++){
for (int j=0; j<poisByQuadrantAndDistance[i].size(); j++){
poisByQuadrantAndDistance[i][j] /= POIs.size();
}
}
for (int i=0; i<roversByQuadrantAndDistance.size(); i++){
for (int j=0; j<roversByQuadrantAndDistance[i].size(); j++){
roversByQuadrantAndDistance[i][j] /= rovers.size();
}
}
// Stitch this together to form state...
for (int i=0; i<poisByQuadrantAndDistance.size(); i++){
stateInputs.insert(stateInputs.end(),poisByQuadrantAndDistance[i].begin(),poisByQuadrantAndDistance[i].end());
}
for (int i=0; i<roversByQuadrantAndDistance.size(); i++){
stateInputs.insert(stateInputs.end(),roversByQuadrantAndDistance[i].begin(),roversByQuadrantAndDistance[i].end());
}
if (usingTypes){
// Collect and add type information if necessary
roverTypeCountByQuadrantAndDistance = std::vector<std::vector<std::vector<double> > >(NSECTORS);
for (int i=0; i<NSECTORS; i++){
roverTypeCountByQuadrantAndDistance[i] = std::vector<std::vector<double> >(NDISTANCES);
for (int j=0; j<NDISTANCES; j++){
roverTypeCountByQuadrantAndDistance[i][j] = std::vector<double>(FAILTYPECOUNT);
}
}
// Type count
for (int i=0; i<rovers.size(); i++){
std::pair<Direction,DistanceDivision> quadAndDist = relativePosition(rovers[me].x,rovers[me].y,rovers[i].x,rovers[i].y);
int quadrant = int(quadAndDist.first);
int dist = int(quadAndDist.second);
roversByQuadrantAndDistance[quadrant][dist]++;
roverTypeCountByQuadrantAndDistance[quadrant][dist][rovers[i].type]++;
}
// Normalization
for (int i=0; i<roverTypeCountByQuadrantAndDistance.size(); i++){
for (int j=0; j<roverTypeCountByQuadrantAndDistance[i].size(); j++){
if (roversByQuadrantAndDistance[i][j]==0) continue;
else {
for (int k=0; k<roverTypeCountByQuadrantAndDistance[i][j].size(); k++){
roverTypeCountByQuadrantAndDistance[i][j][k] /= roversByQuadrantAndDistance[i][j];
}
}
}
}
// Stitching
for (int i=0; i<roverTypeCountByQuadrantAndDistance.size(); i++){
for (int j=0; j<roverTypeCountByQuadrantAndDistance[i].size(); j++){
stateInputs.insert(stateInputs.end(), roverTypeCountByQuadrantAndDistance[i][j].begin(), roverTypeCountByQuadrantAndDistance[i][j].end());
}
}
}
// Generate state from stitched inputs
return State(stateInputs);
}
void RoverPOIDomain::generatePOIs(){
// randomly generates POIs
POIs.clear(); // clears out previous POIs
for (int i=0; i<nPOIs; i++){
POIs.push_back(POI());
}
}
*/ | [
"[email protected]"
] | |
5d413a08e8be5e8a35d0d9b54aed68a8eddecfc6 | d6bcfbc0173d84f25e9edb9aa49624f8af167a46 | /Communication/Network/DataClient.h | 9a8519839ac1631cf6ec62281cc00a449aa2c148 | [] | no_license | 15831944/DH1551 | 11bdba9b7904ccdbb1644a76ba44c3c5479176ea | 1bff86b4b6cc4bd4cc1a3c94900377c753f15089 | refs/heads/master | 2023-03-16T05:48:55.919303 | 2020-07-13T09:39:25 | 2020-07-13T09:39:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 530 | h | #ifndef DATACLIENT_H_
#define DATACLIENT_H_
#include "Network.h"
#include "../Common/UpgradeCommon.h"
class DataClient : public Network
{
public:
DataClient();
~DataClient();
public:
int StartConnectCastpalServer(char * pIPStr, unsigned short usPort);
int SendDataToCastpalServer(unsigned char *pBuffer, unsigned int unLen, unsigned int nDataType);
int RecvDataFromCastpalServer(unsigned char *pBuffer, unsigned int unLen, unsigned int & nDataType);
private:
UpgradeCommon m_UpgradeCommon;
};
#endif /* DATACLIENT_H_ */ | [
"[email protected]"
] | |
67f4af331ab9d3cb2e48a8f28291e3f09cab7aed | 73e9d2c0da0748799af2a1939c4f62d8d95c5f51 | /c++/501 - Find Mode in Binary Search Tree.cpp | 55e5459c7364cd891e6d2396d1321a8166cefc89 | [] | no_license | jaymody/leetcode | bcc95e023d30ec8a0007dbfdbfd6f6798fb64631 | 20ca7d6148a9ce66a91d6c147f34097bd681ad4d | refs/heads/master | 2021-06-28T11:35:24.038139 | 2020-12-19T20:25:48 | 2020-12-19T20:25:48 | 197,073,473 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,444 | cpp | // 501
// Find Mode in Binary Search Tree
// https://leetcode.com/problems/find-mode-in-binary-search-tree/submissions/
// c++
// easy
// O(n^2)
// O(n)
// tree
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
// initial O(n^2) O(n) solution using a hash map
// time complexity is n^2 because worst case, every entry in the BST
// is unique and so the traversal through the hash map is O(n)
// NOTE: there is a better solution out there with O(n) time O(1) space
// that I haven't solved for yet (but know exists)
class Solution {
public:
void visit(TreeNode* root, unordered_map<int,int>& map) {
if (root) {
visit(root->left, map);
visit(root->right, map);
map[root->val] += 1;
}
}
vector<int> findMode(TreeNode* root) {
unordered_map<int,int> map;
visit(root, map);
int max = 0;
vector<int> results;
for (auto& it : map) {
// cout << it.first << ": " << it.second << endl;
if (it.second > max) {
max = it.second;
results.clear();
results.push_back(it.first);
}
else if (it.second == max) {
results.push_back(it.first);
}
}
return results;
}
};
| [
"[email protected]"
] | |
e5499865f332eda3dc5194013ec99ffbbf0f9a26 | 17a529c4269ae9d5429feb976be1c249980b5334 | /ResistoMetor/ResistoMetor.ino | c11a07cb06b6b0c60b52222fb12b8b4b5459f615 | [] | no_license | Kichkun/cubesat | c05edb8a124cd4b3e0563cd502cb23a7d1463f3c | 4a5296a76b02a792824f9e4cd10545310b9cbeeb | refs/heads/master | 2020-03-06T23:05:39.249184 | 2018-07-24T08:49:15 | 2018-07-24T08:49:15 | 127,123,306 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,592 | ino | // ОММЕТР (С)2013 ALEN Studio by Little_Red_Rat
// Омметр на осное ARDUINO
//
// Подключение делителя напряжения к ARDUINO
// Arduino 5V -> R1 10kOm -> Arduino Analog 0 -> R2 -> Arduino GND
int analogPin_0 = A0; // Анлоговый вход для считывания напряжения с делителя напряжения
int analogPin_1 = A1;
float Vout = 0; // Переменная для хранения значения напряжения в средней точки делителя (0-5.0)
float R2_0 = 0; // Переменная для хранения значения резистора R2
float R2_1 = 0;
int R1_0 = 300;
int R1_1 = 180;
float V_in = 4.78;
void setup()
{
Serial.begin(9600); // Подготовка Serial Monitor для вывода информации
}
float mesure(float pin, int R1){
Vout = (V_in / 1023.0) * analogRead(pin); // Вычисляем напряжение в средней точки делителя (0-5.0)
R2_0 = R1/ ((V_in / Vout) - 1); // Вычисляем сопротивление R2 (10000 это значение R1 10 кОм)
Serial.print(" Voltage: "); //
Serial.print(Vout); // Напряжения в средней точки делителя (0-5.0) для справки
Serial.print(" R2: "); //
Serial.print(R2_0); // Значение сопротивления R2
return R2_0;
}
void loop()
{
float a = mesure(analogPin_0, R1_0);
float b = mesure(analogPin_1, R1_1);
Serial.println();
delay(1000); // Пауза 1 сек
}
| [
"[email protected]"
] |
Subsets and Splits