blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 247 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2 values | repo_name stringlengths 4 111 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 58 | visit_date timestamp[ns]date 2015-07-25 18:16:41 2023-09-06 10:45:08 | revision_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | committer_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | github_id int64 3.89k 689M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 25 values | gha_event_created_at timestamp[ns]date 2012-06-07 00:51:45 2023-09-14 21:58:52 ⌀ | gha_created_at timestamp[ns]date 2008-03-27 23:40:48 2023-08-24 19:49:39 ⌀ | gha_language stringclasses 159 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 7 10.5M | extension stringclasses 111 values | filename stringlengths 1 195 | text stringlengths 7 10.5M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
69cdbf0a5f082bfbe0479c442a4fd5bc7bfe6402 | b965c0a0f0a3b2471d58c144bbff61eab9a01b6e | /NeuralLayerConv.h | 5174f5d727ecb171f03e355c9c4b093e8c34045f | [] | no_license | Ionsto/Hunt | dac8d26ec0b35216a8dd6d514ae8dbc9a7d3527a | 24eb51fe1831648960d55ddde8790cd234fa8ee8 | refs/heads/master | 2021-01-24T20:40:13.106894 | 2018-03-06T21:24:41 | 2018-03-06T21:24:41 | 123,254,869 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 308 | h | NeuralLayerConv.h | #pragma once
#include "NeuralLayer.h"
class NeuralLayerConv :
public NeuralLayer
{
public:
int ConvSize;
int OutputSize;
NeuralLayerConv();
NeuralLayerConv(int inputsize,int convsize, int nodecount);
NeuralLayerConv(NeuralLayerConv const& layer);
int GetOutputSize();
void Update(float * input);
};
|
06e9bd174bb73ac83a3e594326a1545671e5b5d0 | 05d0cdf14776f0ba714996d86ef92e4fef50516a | /libs/directag/pwiz-src/pwiz/data/msdata/Diff.cpp | 0e397656860c9c269fd7d2bbc4d03c3d8f748285 | [
"MIT",
"Apache-2.0"
] | permissive | buotex/BICEPS | 5a10396374da2e70e262c9304cf9710a147da484 | 10ed3938af8b05e372758ebe01dcb012a671a16a | refs/heads/master | 2020-05-30T20:20:55.378536 | 2014-01-06T21:31:56 | 2014-01-06T21:31:56 | 1,382,740 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 28,723 | cpp | Diff.cpp | //
// Diff.cpp
//
//
// Original author: Darren Kessner <Darren.Kessner@cshs.org>
//
// Copyright 2007 Spielberg Family Center for Applied Proteomics
// Cedars-Sinai Medical Center, Los Angeles, California 90048
//
// 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.
//
#define PWIZ_SOURCE
#include "Diff.hpp"
#include <string>
#include <cmath>
#include <stdexcept>
namespace pwiz {
namespace msdata {
namespace diff_impl {
using namespace std;
using boost::shared_ptr;
using boost::lexical_cast;
PWIZ_API_DECL
void diff(const string& a,
const string& b,
string& a_b,
string& b_a,
const DiffConfig& config)
{
a_b.clear();
b_a.clear();
if (a != b)
{
a_b = a;
b_a = b;
}
}
template <typename T>
void diff_numeric(const T& a,
const T& b,
T& a_b,
T& b_a,
const DiffConfig& config)
{
a_b = 0;
b_a = 0;
if (a != b)
{
a_b = a;
b_a = b;
}
}
PWIZ_API_DECL
void diff(const CV& a,
const CV& b,
CV& a_b,
CV& b_a,
const DiffConfig& config)
{
diff(a.URI, b.URI, a_b.URI, b_a.URI, config);
diff(a.id, b.id, a_b.id, b_a.id, config);
diff(a.fullName, b.fullName, a_b.fullName, b_a.fullName, config);
diff(a.version, b.version, a_b.version, b_a.version, config);
}
PWIZ_API_DECL
void diff(CVID a,
CVID b,
CVID& a_b,
CVID& b_a,
const DiffConfig& config)
{
a_b = b_a = CVID_Unknown;
if (a!=b)
{
a_b = a;
b_a = b;
}
}
PWIZ_API_DECL
void diff(const CVParam& a,
const CVParam& b,
CVParam& a_b,
CVParam& b_a,
const DiffConfig& config)
{
diff(a.cvid, b.cvid, a_b.cvid, b_a.cvid, config);
diff(a.value, b.value, a_b.value, b_a.value, config);
diff(a.units, b.units, a_b.units, b_a.units, config);
// provide names for context
if (!a_b.empty() && a_b.cvid==CVID_Unknown) a_b.cvid = a.cvid;
if (!b_a.empty() && b_a.cvid==CVID_Unknown) b_a.cvid = b.cvid;
}
PWIZ_API_DECL
void diff(const UserParam& a,
const UserParam& b,
UserParam& a_b,
UserParam& b_a,
const DiffConfig& config)
{
diff(a.name, b.name, a_b.name, b_a.name, config);
diff(a.value, b.value, a_b.value, b_a.value, config);
diff(a.type, b.type, a_b.type, b_a.type, config);
diff(a.units, b.units, a_b.units, b_a.units, config);
// provide names for context
if (!a_b.empty() && a_b.name.empty()) a_b.name = a.name;
if (!b_a.empty() && b_a.name.empty()) b_a.name = b.name;
}
template <typename object_type>
void vector_diff(const vector<object_type>& a,
const vector<object_type>& b,
vector<object_type>& a_b,
vector<object_type>& b_a)
{
// calculate set differences of two vectors
a_b.clear();
b_a.clear();
for (typename vector<object_type>::const_iterator it=a.begin(); it!=a.end(); ++it)
if (find(b.begin(), b.end(), *it) == b.end())
a_b.push_back(*it);
for (typename vector<object_type>::const_iterator it=b.begin(); it!=b.end(); ++it)
if (find(a.begin(), a.end(), *it) == a.end())
b_a.push_back(*it);
}
template <typename object_type>
struct HasID
{
const string& id_;
HasID(const string& id) : id_(id) {}
bool operator()(const boost::shared_ptr<object_type>& objectPtr) {return objectPtr->id == id_;}
};
template <typename object_type>
class Same
{
public:
Same(const object_type& object,
const DiffConfig& config)
: mine_(object), config_(config)
{}
bool operator()(const object_type& yours)
{
// true iff yours is the same as mine
return !Diff<object_type>(mine_, yours, config_);
}
private:
const object_type& mine_;
const DiffConfig& config_;
};
template <typename object_type>
void vector_diff_diff(const vector<object_type>& a,
const vector<object_type>& b,
vector<object_type>& a_b,
vector<object_type>& b_a,
const DiffConfig& config)
{
// calculate set differences of two vectors, using diff on each object
a_b.clear();
b_a.clear();
for (typename vector<object_type>::const_iterator it=a.begin(); it!=a.end(); ++it)
if (find_if(b.begin(), b.end(), Same<object_type>(*it, config)) == b.end())
a_b.push_back(*it);
for (typename vector<object_type>::const_iterator it=b.begin(); it!=b.end(); ++it)
if (find_if(a.begin(), a.end(), Same<object_type>(*it, config)) == a.end())
b_a.push_back(*it);
}
template <typename object_type>
class SameDeep
{
public:
SameDeep(const object_type& object,
const DiffConfig& config)
: mine_(object), config_(config)
{}
bool operator()(const boost::shared_ptr<object_type>& yours)
{
// true iff yours is the same as mine
return !Diff<object_type>(mine_, *yours, config_);
}
private:
const object_type& mine_;
const DiffConfig& config_;
};
template <typename object_type>
void vector_diff_deep(const vector< boost::shared_ptr<object_type> >& a,
const vector< boost::shared_ptr<object_type> >& b,
vector< boost::shared_ptr<object_type> >& a_b,
vector< boost::shared_ptr<object_type> >& b_a,
const DiffConfig& config)
{
// calculate set differences of two vectors of ObjectPtrs (deep compare using diff)
a_b.clear();
b_a.clear();
for (typename vector< boost::shared_ptr<object_type> >::const_iterator it=a.begin(); it!=a.end(); ++it)
if (find_if(b.begin(), b.end(), SameDeep<object_type>(**it, config)) == b.end())
a_b.push_back(*it);
for (typename vector< boost::shared_ptr<object_type> >::const_iterator it=b.begin(); it!=b.end(); ++it)
if (find_if(a.begin(), a.end(), SameDeep<object_type>(**it, config)) == a.end())
b_a.push_back(*it);
}
PWIZ_API_DECL
void diff(const ParamContainer& a,
const ParamContainer& b,
ParamContainer& a_b,
ParamContainer& b_a,
const DiffConfig& config)
{
vector_diff_deep(a.paramGroupPtrs, b.paramGroupPtrs, a_b.paramGroupPtrs, b_a.paramGroupPtrs, config);
vector_diff(a.cvParams, b.cvParams, a_b.cvParams, b_a.cvParams);
vector_diff(a.userParams, b.userParams, a_b.userParams, b_a.userParams);
}
PWIZ_API_DECL
void diff(const ParamGroup& a,
const ParamGroup& b,
ParamGroup& a_b,
ParamGroup& b_a,
const DiffConfig& config)
{
diff(static_cast<const ParamContainer&>(a), b, a_b, b_a, config);
diff(a.id, b.id, a_b.id, b_a.id, config);
// provide id for context
if (!a_b.empty() || !b_a.empty())
{
a_b.id = a.id;
b_a.id = b.id;
}
}
PWIZ_API_DECL
void diff(const SourceFile& a,
const SourceFile& b,
SourceFile& a_b,
SourceFile& b_a,
const DiffConfig& config)
{
diff(static_cast<const ParamContainer&>(a), b, a_b, b_a, config);
diff(a.id, b.id, a_b.id, b_a.id, config);
diff(a.name, b.name, a_b.name, b_a.name, config);
diff(a.location, b.location, a_b.location, b_a.location, config);
// provide id for context
if (!a_b.empty() || !b_a.empty())
{
a_b.id = a.id;
b_a.id = b.id;
}
}
PWIZ_API_DECL
void diff(const FileDescription& a,
const FileDescription& b,
FileDescription& a_b,
FileDescription& b_a,
const DiffConfig& config)
{
diff(static_cast<const ParamContainer&>(a.fileContent), b.fileContent, a_b.fileContent, b_a.fileContent, config);
vector_diff_deep(a.sourceFilePtrs, b.sourceFilePtrs, a_b.sourceFilePtrs, b_a.sourceFilePtrs, config);
vector_diff_diff<Contact>(a.contacts, b.contacts, a_b.contacts, b_a.contacts, config);
}
PWIZ_API_DECL
void diff(const Sample& a,
const Sample& b,
Sample& a_b,
Sample& b_a,
const DiffConfig& config)
{
diff(static_cast<const ParamContainer&>(a), b, a_b, b_a, config);
diff(a.id, b.id, a_b.id, b_a.id, config);
diff(a.name, b.name, a_b.name, b_a.name, config);
// provide id for context
if (!a_b.empty() || !b_a.empty())
{
a_b.id = a.id;
b_a.id = b.id;
}
}
PWIZ_API_DECL
void diff(const Component& a,
const Component& b,
Component& a_b,
Component& b_a,
const DiffConfig& config)
{
int a_bType, b_aType; // TODO: how to take the difference of enum types?
diff(static_cast<const ParamContainer&>(a), b, a_b, b_a, config);
diff_numeric(a.order, b.order, a_b.order, b_a.order, config);
diff_numeric((int)a.type, (int)b.type, a_bType, b_aType, config);
}
PWIZ_API_DECL
void diff(const ComponentList& a,
const ComponentList& b,
ComponentList& a_b,
ComponentList& b_a,
const DiffConfig& config)
{
//size_t a_bSize, b_aSize; // TODO: what to do with this?
//diff_numeric(a.size(), b.size(), a_bSize, b_aSize, config);
//for (size_t i=0; i < a.size(); ++i)
// diff(a[i], b[i], a_b[i], b_a[i], config);
vector_diff_diff(static_cast<const vector<Component>&>(a),
static_cast<const vector<Component>&>(b),
static_cast<vector<Component>&>(a_b),
static_cast<vector<Component>&>(b_a),
config);
}
PWIZ_API_DECL
void diff(const Software& a,
const Software& b,
Software& a_b,
Software& b_a,
const DiffConfig& config)
{
diff(a.id, b.id, a_b.id, b_a.id, config);
diff(a.softwareParam, b.softwareParam, a_b.softwareParam, b_a.softwareParam, config);
diff(a.softwareParamVersion, b.softwareParamVersion, a_b.softwareParamVersion, b_a.softwareParamVersion, config);
// provide id for context
if (!a_b.empty() || !b_a.empty())
{
a_b.id = a.id;
b_a.id = b.id;
}
}
template <typename object_type>
void ptr_diff(const boost::shared_ptr<object_type>& a,
const boost::shared_ptr<object_type>& b,
boost::shared_ptr<object_type>& a_b,
boost::shared_ptr<object_type>& b_a,
const DiffConfig& config)
{
if (!a.get() && !b.get()) return;
boost::shared_ptr<object_type> a_temp = a.get() ? a : boost::shared_ptr<object_type>(new object_type);
boost::shared_ptr<object_type> b_temp = b.get() ? b : boost::shared_ptr<object_type>(new object_type);
if (!a_b.get()) a_b = boost::shared_ptr<object_type>(new object_type);
if (!b_a.get()) b_a = boost::shared_ptr<object_type>(new object_type);
diff(*a_temp, *b_temp, *a_b, *b_a, config);
if (a_b->empty()) a_b = boost::shared_ptr<object_type>();
if (b_a->empty()) b_a = boost::shared_ptr<object_type>();
}
PWIZ_API_DECL
void diff(const InstrumentConfiguration& a,
const InstrumentConfiguration& b,
InstrumentConfiguration& a_b,
InstrumentConfiguration& b_a,
const DiffConfig& config)
{
diff(a.id, b.id, a_b.id, b_a.id, config);
diff(a.componentList, b.componentList, a_b.componentList, b_a.componentList, config);
ptr_diff(a.softwarePtr, b.softwarePtr, a_b.softwarePtr, b_a.softwarePtr, config);
diff(static_cast<const ParamContainer&>(a), b, a_b, b_a, config);
// provide id for context
if (!a_b.empty() || !b_a.empty())
{
a_b.id = a.id;
b_a.id = b.id;
}
}
PWIZ_API_DECL
void diff(const ProcessingMethod& a,
const ProcessingMethod& b,
ProcessingMethod& a_b,
ProcessingMethod& b_a,
const DiffConfig& config)
{
diff(static_cast<const ParamContainer&>(a), b, a_b, b_a, config);
diff_numeric(a.order, b.order, a_b.order, b_a.order, config);
}
PWIZ_API_DECL
void diff(const DataProcessing& a,
const DataProcessing& b,
DataProcessing& a_b,
DataProcessing& b_a,
const DiffConfig& config)
{
diff(a.id, b.id, a_b.id, b_a.id, config);
ptr_diff(a.softwarePtr, b.softwarePtr, a_b.softwarePtr, b_a.softwarePtr, config);
vector_diff_diff(a.processingMethods, b.processingMethods, a_b.processingMethods, b_a.processingMethods, config);
// provide id for context
if (!a_b.empty() || !b_a.empty())
{
a_b.id = a.id;
b_a.id = b.id;
}
}
PWIZ_API_DECL
void diff(const AcquisitionSettings& a,
const AcquisitionSettings& b,
AcquisitionSettings& a_b,
AcquisitionSettings& b_a,
const DiffConfig& config)
{
diff(a.id, b.id, a_b.id, b_a.id, config);
ptr_diff(a.instrumentConfigurationPtr, b.instrumentConfigurationPtr, a_b.instrumentConfigurationPtr, b_a.instrumentConfigurationPtr, config);
vector_diff_deep(a.sourceFilePtrs, b.sourceFilePtrs, a_b.sourceFilePtrs, b_a.sourceFilePtrs, config);
vector_diff_diff(a.targets, b.targets, a_b.targets, b_a.targets, config);
// provide id for context
if (!a_b.empty() || !b_a.empty())
{
a_b.id = a.id;
b_a.id = b.id;
}
}
PWIZ_API_DECL
void diff(const Acquisition& a,
const Acquisition& b,
Acquisition& a_b,
Acquisition& b_a,
const DiffConfig& config)
{
diff_numeric(a.number, b.number, a_b.number, b_a.number, config);
ptr_diff(a.sourceFilePtr, b.sourceFilePtr, a_b.sourceFilePtr, b_a.sourceFilePtr, config);
diff(a.spectrumID, b.spectrumID, a_b.spectrumID, b_a.spectrumID, config);
// provide number for context
if (!a_b.empty() || !b_a.empty())
{
a_b.number = a.number;
b_a.number = b.number;
}
}
PWIZ_API_DECL
void diff(const AcquisitionList& a,
const AcquisitionList& b,
AcquisitionList& a_b,
AcquisitionList& b_a,
const DiffConfig& config)
{
vector_diff_diff(a.acquisitions, b.acquisitions, a_b.acquisitions, b_a.acquisitions, config);
diff(static_cast<const ParamContainer&>(a), b, a_b, b_a, config);
}
PWIZ_API_DECL
void diff(const Precursor& a,
const Precursor& b,
Precursor& a_b,
Precursor& b_a,
const DiffConfig& config)
{
a_b = Precursor();
b_a = Precursor();
// important scan metadata
vector_diff_diff<SelectedIon>(a.selectedIons, b.selectedIons, a_b.selectedIons, b_a.selectedIons, config);
if (!config.ignoreMetadata)
{
diff(a.spectrumID, b.spectrumID, a_b.spectrumID, b_a.spectrumID, config);
diff(static_cast<const ParamContainer&>(a.isolationWindow), b.isolationWindow, a_b.isolationWindow, b_a.isolationWindow, config);
diff(static_cast<const ParamContainer&>(a.activation), b.activation, a_b.activation, b_a.activation, config);
diff(static_cast<const ParamContainer&>(a), b, a_b, b_a, config);
}
// provide spectrumID for context
if (!a_b.empty() || !b_a.empty())
{
a_b.spectrumID = a.spectrumID;
b_a.spectrumID = b.spectrumID;
}
}
PWIZ_API_DECL
void diff(const Scan& a,
const Scan& b,
Scan& a_b,
Scan& b_a,
const DiffConfig& config)
{
ptr_diff(a.instrumentConfigurationPtr, b.instrumentConfigurationPtr, a_b.instrumentConfigurationPtr, b_a.instrumentConfigurationPtr, config);
vector_diff_diff(a.scanWindows, b.scanWindows, a_b.scanWindows, b_a.scanWindows, config);
diff(static_cast<const ParamContainer&>(a), b, a_b, b_a, config);
// provide instrumentConfigurationPtr for context
if (!a_b.empty() || !b_a.empty())
{
a_b.instrumentConfigurationPtr = a.instrumentConfigurationPtr;
b_a.instrumentConfigurationPtr = b.instrumentConfigurationPtr;
}
}
PWIZ_API_DECL
void diff(const SpectrumDescription& a,
const SpectrumDescription& b,
SpectrumDescription& a_b,
SpectrumDescription& b_a,
const DiffConfig& config)
{
// important scan metadata
vector_diff_diff(a.precursors, b.precursors, a_b.precursors, b_a.precursors, config);
if (!config.ignoreMetadata)
{
diff(a.acquisitionList, b.acquisitionList, a_b.acquisitionList, b_a.acquisitionList, config);
diff(a.scan, b.scan, a_b.scan, b_a.scan, config);
diff(static_cast<const ParamContainer&>(a), b, a_b, b_a, config);
}
}
double maxdiff(const vector<double>& a, const vector<double>& b)
{
if (a.size() != b.size())
throw runtime_error("[Diff::maxdiff()] Sizes differ.");
vector<double>::const_iterator i = a.begin();
vector<double>::const_iterator j = b.begin();
double max = 0;
for (; i!=a.end(); ++i, ++j)
{
double current = fabs(*i - *j);
if (max < current) max = current;
}
return max;
}
PWIZ_API_DECL
void diff(const BinaryDataArray& a,
const BinaryDataArray& b,
BinaryDataArray& a_b,
BinaryDataArray& b_a,
const DiffConfig& config)
{
if (!config.ignoreMetadata)
{
ptr_diff(a.dataProcessingPtr, b.dataProcessingPtr, a_b.dataProcessingPtr, b_a.dataProcessingPtr, config);
diff(static_cast<const ParamContainer&>(a), b, a_b, b_a, config);
}
if (a.data.size() != b.data.size())
{
a_b.userParams.push_back(UserParam("Binary data array size: " +
lexical_cast<string>(a.data.size())));
b_a.userParams.push_back(UserParam("Binary data array size: " +
lexical_cast<string>(b.data.size())));
}
else
{
double max = maxdiff(a.data, b.data);
if (max > config.precision)
{
a_b.userParams.push_back(UserParam("Binary data arrays differ (max diff = " +
lexical_cast<string>(max) + ")"));
b_a.userParams.push_back(UserParam("Binary data arrays differ (max diff = " +
lexical_cast<string>(max) + ")"));
}
}
// provide context
if (!a_b.empty() || !b_a.empty())
{
a_b.cvParams = a.cvParams;
b_a.cvParams = b.cvParams;
}
}
PWIZ_API_DECL
void diff(const vector<BinaryDataArrayPtr>& a,
const vector<BinaryDataArrayPtr>& b,
vector<BinaryDataArrayPtr>& a_b,
vector<BinaryDataArrayPtr>& b_a,
const DiffConfig& config)
{
if (a.size() != b.size())
throw runtime_error("[Diff::diff(vector<BinaryDataArrayPtr>)] Sizes differ.");
a_b.clear();
b_a.clear();
for (vector<BinaryDataArrayPtr>::const_iterator i=a.begin(), j=b.begin();
i!=a.end(); ++i, ++j)
{
BinaryDataArrayPtr temp_a_b(new BinaryDataArray);
BinaryDataArrayPtr temp_b_a(new BinaryDataArray);
diff(**i, **j, *temp_a_b, *temp_b_a, config);
if (!temp_a_b->empty() || !temp_b_a->empty())
{
a_b.push_back(temp_a_b);
b_a.push_back(temp_b_a);
}
}
}
PWIZ_API_DECL
void diff(const Spectrum& a,
const Spectrum& b,
Spectrum& a_b,
Spectrum& b_a,
const DiffConfig& config)
{
a_b = Spectrum();
b_a = Spectrum();
// important scan metadata
diff_numeric(a.index, b.index, a_b.index, b_a.index, config);
diff(a.nativeID, b.nativeID, a_b.nativeID, b_a.nativeID, config);
diff_numeric(a.defaultArrayLength, b.defaultArrayLength, a_b.defaultArrayLength, b_a.defaultArrayLength, config);
diff(a.spectrumDescription, b.spectrumDescription, a_b.spectrumDescription, b_a.spectrumDescription, config);
if (!config.ignoreMetadata)
{
diff(a.id, b.id, a_b.id, b_a.id, config);
ptr_diff(a.dataProcessingPtr, b.dataProcessingPtr, a_b.dataProcessingPtr, b_a.dataProcessingPtr, config);
ptr_diff(a.sourceFilePtr, b.sourceFilePtr, a_b.sourceFilePtr, b_a.sourceFilePtr, config);
diff(static_cast<const ParamContainer&>(a), b, a_b, b_a, config);
}
// special handling for binary data arrays
if (a.binaryDataArrayPtrs.size() != b.binaryDataArrayPtrs.size())
{
a_b.userParams.push_back(UserParam("Binary data array count: " +
lexical_cast<string>(a.binaryDataArrayPtrs.size())));
b_a.userParams.push_back(UserParam("Binary data array count: " +
lexical_cast<string>(b.binaryDataArrayPtrs.size())));
}
else
{
diff(a.binaryDataArrayPtrs, b.binaryDataArrayPtrs,
a_b.binaryDataArrayPtrs, b_a.binaryDataArrayPtrs, config);
}
// provide context
if (!a_b.empty() || !b_a.empty())
{
a_b.id = a.id;
a_b.nativeID = a.nativeID;
b_a.id = b.id;
b_a.nativeID = b.nativeID;
}
}
PWIZ_API_DECL
void diff(const Chromatogram& a,
const Chromatogram& b,
Chromatogram& a_b,
Chromatogram& b_a,
const DiffConfig& config)
{
a_b = Chromatogram();
b_a = Chromatogram();
// important scan metadata
diff_numeric(a.index, b.index, a_b.index, b_a.index, config);
diff(a.nativeID, b.nativeID, a_b.nativeID, b_a.nativeID, config);
diff_numeric(a.defaultArrayLength, b.defaultArrayLength, a_b.defaultArrayLength, b_a.defaultArrayLength, config);
if (!config.ignoreMetadata)
{
diff(a.id, b.id, a_b.id, b_a.id, config);
ptr_diff(a.dataProcessingPtr, b.dataProcessingPtr, a_b.dataProcessingPtr, b_a.dataProcessingPtr, config);
diff(static_cast<const ParamContainer&>(a), b, a_b, b_a, config);
}
// special handling for binary data arrays
if (a.binaryDataArrayPtrs.size() != b.binaryDataArrayPtrs.size())
{
a_b.userParams.push_back(UserParam("Binary data array count: " +
lexical_cast<string>(a.binaryDataArrayPtrs.size())));
b_a.userParams.push_back(UserParam("Binary data array count: " +
lexical_cast<string>(b.binaryDataArrayPtrs.size())));
}
else
{
diff(a.binaryDataArrayPtrs, b.binaryDataArrayPtrs,
a_b.binaryDataArrayPtrs, b_a.binaryDataArrayPtrs, config);
}
// provide context
if (!a_b.empty() || !b_a.empty())
{
a_b.id = a.id;
a_b.nativeID = a.nativeID;
b_a.id = b.id;
b_a.nativeID = b.nativeID;
}
}
PWIZ_API_DECL
void diff(const SpectrumList& a,
const SpectrumList& b,
SpectrumListSimple& a_b,
SpectrumListSimple& b_a,
const DiffConfig& config)
{
a_b.spectra.clear();
b_a.spectra.clear();
if (a.size() != b.size())
{
SpectrumPtr dummy(new Spectrum);
dummy->userParams.push_back(UserParam("SpectrumList sizes differ"));
a_b.spectra.push_back(dummy);
return;
}
for (unsigned int i=0; i<a.size(); i++)
{
SpectrumPtr temp_a_b(new Spectrum);
SpectrumPtr temp_b_a(new Spectrum);
diff(*a.spectrum(i, true), *b.spectrum(i, true), *temp_a_b, *temp_b_a, config);
if (!temp_a_b->empty() || !temp_b_a->empty())
{
a_b.spectra.push_back(temp_a_b);
b_a.spectra.push_back(temp_b_a);
}
}
}
PWIZ_API_DECL
void diff(const ChromatogramList& a,
const ChromatogramList& b,
ChromatogramListSimple& a_b,
ChromatogramListSimple& b_a,
const DiffConfig& config)
{
a_b.chromatograms.clear();
b_a.chromatograms.clear();
if (config.ignoreChromatograms) return;
if (a.size() != b.size())
{
ChromatogramPtr dummy(new Chromatogram);
dummy->userParams.push_back(UserParam("ChromatogramList sizes differ"));
a_b.chromatograms.push_back(dummy);
return;
}
for (unsigned int i=0; i<a.size(); i++)
{
ChromatogramPtr temp_a_b(new Chromatogram);
ChromatogramPtr temp_b_a(new Chromatogram);
diff(*a.chromatogram(i, true), *b.chromatogram(i, true), *temp_a_b, *temp_b_a, config);
if (!temp_a_b->empty() || !temp_b_a->empty())
{
a_b.chromatograms.push_back(temp_a_b);
b_a.chromatograms.push_back(temp_b_a);
}
}
}
PWIZ_API_DECL
void diff(const Run& a,
const Run& b,
Run& a_b,
Run& b_a,
const DiffConfig& config)
{
if (!config.ignoreMetadata)
{
diff(a.id, b.id, a_b.id, b_a.id, config);
ptr_diff(a.defaultInstrumentConfigurationPtr, b.defaultInstrumentConfigurationPtr, a_b.defaultInstrumentConfigurationPtr, b_a.defaultInstrumentConfigurationPtr, config);
ptr_diff(a.samplePtr, b.samplePtr, a_b.samplePtr, b_a.samplePtr, config);
diff(a.startTimeStamp, b.startTimeStamp, a_b.startTimeStamp, b_a.startTimeStamp, config);
vector_diff_deep(a.sourceFilePtrs, b.sourceFilePtrs, a_b.sourceFilePtrs, b_a.sourceFilePtrs, config);
diff(static_cast<const ParamContainer&>(a), b, a_b, b_a, config);
}
// special handling for SpectrumList diff
boost::shared_ptr<SpectrumListSimple> temp_a_b(new SpectrumListSimple);
boost::shared_ptr<SpectrumListSimple> temp_b_a(new SpectrumListSimple);
a_b.spectrumListPtr = temp_a_b;
b_a.spectrumListPtr = temp_b_a;
SpectrumListPtr temp_a = a.spectrumListPtr.get() ? a.spectrumListPtr : SpectrumListPtr(new SpectrumListSimple);
SpectrumListPtr temp_b = b.spectrumListPtr.get() ? b.spectrumListPtr : SpectrumListPtr(new SpectrumListSimple);
diff(*temp_a, *temp_b, *temp_a_b, *temp_b_a, config);
// special handling for ChromatogramList diff
boost::shared_ptr<ChromatogramListSimple> cl_temp_a_b(new ChromatogramListSimple);
boost::shared_ptr<ChromatogramListSimple> cl_temp_b_a(new ChromatogramListSimple);
a_b.chromatogramListPtr = cl_temp_a_b;
b_a.chromatogramListPtr = cl_temp_b_a;
ChromatogramListPtr cl_temp_a = a.chromatogramListPtr.get() ? a.chromatogramListPtr : ChromatogramListPtr(new ChromatogramListSimple);
ChromatogramListPtr cl_temp_b = b.chromatogramListPtr.get() ? b.chromatogramListPtr : ChromatogramListPtr(new ChromatogramListSimple);
diff(*cl_temp_a, *cl_temp_b, *cl_temp_a_b, *cl_temp_b_a, config);
// provide context
if (!a_b.empty() || !b_a.empty())
{
a_b.id = a.id;
b_a.id = b.id;
}
}
PWIZ_API_DECL
void diff(const MSData& a,
const MSData& b,
MSData& a_b,
MSData& b_a,
const DiffConfig& config)
{
if (!config.ignoreMetadata)
{
diff(a.accession, b.accession, a_b.accession, b_a.accession, config);
diff(a.id, b.id, a_b.id, b_a.id, config);
diff(a.version, b.version, a_b.version, b_a.version, config);
vector_diff_diff(a.cvs, b.cvs, a_b.cvs, b_a.cvs, config);
diff(a.fileDescription, b.fileDescription, a_b.fileDescription, b_a.fileDescription, config);
vector_diff_deep(a.paramGroupPtrs, b.paramGroupPtrs, a_b.paramGroupPtrs, b_a.paramGroupPtrs, config);
vector_diff_deep(a.samplePtrs, b.samplePtrs, a_b.samplePtrs, b_a.samplePtrs, config);
vector_diff_deep(a.instrumentConfigurationPtrs, b.instrumentConfigurationPtrs, a_b.instrumentConfigurationPtrs, b_a.instrumentConfigurationPtrs, config);
vector_diff_deep(a.softwarePtrs, b.softwarePtrs, a_b.softwarePtrs, b_a.softwarePtrs, config);
vector_diff_deep(a.dataProcessingPtrs, b.dataProcessingPtrs, a_b.dataProcessingPtrs, b_a.dataProcessingPtrs, config);
vector_diff_deep(a.acquisitionSettingsPtrs, b.acquisitionSettingsPtrs, a_b.acquisitionSettingsPtrs, b_a.acquisitionSettingsPtrs, config);
}
diff(a.run, b.run, a_b.run, b_a.run, config);
// provide context
if (!a_b.empty() || !b_a.empty())
{
a_b.id = a.id;
b_a.id = b.id;
}
}
} // namespace diff_impl
} // namespace msdata
} // namespace pwiz
|
5ba4efb54603497e57e1399682ebf33cd8cdd619 | 7d860affdeb45465951f1bca5b36bf8993248e79 | /Code/IosGameClient/Classes/UIFile/FamilyMenu.h | b3cb146582875444b513812f49c06aa46dc1a7aa | [] | no_license | Zyl85385215/Resources | 88251abaaa44300c0ca0830d52e62cd13e7a4c5f | 1e2468d03deb7b46b892a870e89c3b4a5ca25aae | refs/heads/master | 2021-02-27T02:13:28.203996 | 2020-04-10T17:08:34 | 2020-04-10T17:08:34 | 245,569,447 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,562 | h | FamilyMenu.h | #pragma once
#include "CtrlObj.h"
class FamilyInfoMenu: public TabMenuObj{
public:
FamilyInfoMenu();
~FamilyInfoMenu();
void Update();
bool m_bUpdate;
void Open(int nT);;
};
class FamilyMemberMenu: public TabMenuObj{
public:
FamilyMemberMenu();
~FamilyMemberMenu();
void Update();
bool m_bUpdate;
int m_nSelect;
bool m_bSelectPos;
void Open(int nT);
void Select(int nPos);
};
class FamilySkillMenu: public TabMenuObj{
public:
FamilySkillMenu();
~FamilySkillMenu();
void Update();
bool m_bUpdate;
void Open(int nT);;
};
class FamilyBuildMenu: public TabMenuObj{
public:
FamilyBuildMenu();
~FamilyBuildMenu();
void Update();
bool m_bUpdate;
void Open(int nT);;
};
class FamilyQuestMenu: public TabMenuObj{
public:
FamilyQuestMenu();
~FamilyQuestMenu();
void Update();
bool m_bUpdate;
void Open(int nT);
void UpViewQuestComp(DForm* pForm, QuestObj* pQBase, ClientQuest* pClientQ);
};
class FamilyListMenu: public TabMenuObj{
public:
FamilyListMenu();
~FamilyListMenu();
void Update();
bool m_bUpdate;
int m_nSelect;
void Open(int nT);
void Select(int nPos);
int m_nRqCnt;
};
class FamilyCreateMenu{
public:
FamilyCreateMenu();
//~FamilyCreateMenu();
bool m_bUseRmb;
DForm* m_pForm;
void Open();
void Refresh();
};
class FamilyJoinMenu{
public:
FamilyJoinMenu();
void Update();
bool m_bUpdate;
int m_nSelect;
void Open(int nT);
void Select(int nPos);
DForm* m_pForm;
};
class FamilyNoticeMenu{
public:
FamilyNoticeMenu();
//~FamilyCreateMenu();
DForm* m_pForm;
void Open();
}; |
be43acd2475eca7f4d0686b4d8af37f6641db443 | c7272e93df5e9f68c36385308da28a944e300d9d | /19. Remove Nth Node From End of List.h | 9c35d0d2f89f59e8d40b022a10443dd0c38d5c83 | [
"MIT"
] | permissive | Mids/LeetCode | 368a941770bc7cb96a85a7b523d77446717a1f31 | 589b9e40acfde6e2dde37916fc1c69a3ac481070 | refs/heads/master | 2023-08-13T13:39:11.476092 | 2021-09-26T09:29:18 | 2021-09-26T09:29:18 | 326,600,963 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 832 | h | 19. Remove Nth Node From End of List.h | //
// Created by jin on 2/8/2021.
//
#ifndef LEETCODE_19_REMOVE_NTH_NODE_FROM_END_OF_LIST_H
#define LEETCODE_19_REMOVE_NTH_NODE_FROM_END_OF_LIST_H
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution {
public:
ListNode *removeNthFromEnd(ListNode *head, int n) {
int i = 1;
ListNode *cur = head;
ListNode *target = head;
while (i++ <= n) {
cur = cur->next;
}
if (cur == nullptr) return head->next;
while (true) {
if (cur->next == nullptr) {
target->next = target->next->next;
return head;
}
target = target->next;
cur = cur->next;
}
return head;
}
};
#endif //LEETCODE_19_REMOVE_NTH_NODE_FROM_END_OF_LIST_H
|
ba931433e3fcee43b11926ac1948f052f2f7b4c9 | 65e3391b6afbef10ec9429ca4b43a26b5cf480af | /TRD/TRDbase/AliTRDtransform.h | 18f3b625b8ad0e33de9a45ad365670e4a21d9bb8 | [] | permissive | alisw/AliRoot | c0976f7105ae1e3d107dfe93578f819473b2b83f | d3f86386afbaac9f8b8658da6710eed2bdee977f | refs/heads/master | 2023-08-03T11:15:54.211198 | 2023-07-28T12:39:57 | 2023-07-28T12:39:57 | 53,312,169 | 61 | 299 | BSD-3-Clause | 2023-07-28T13:19:50 | 2016-03-07T09:20:12 | C++ | UTF-8 | C++ | false | false | 2,799 | h | AliTRDtransform.h | #ifndef ALITRDTRANSFORM_H
#define ALITRDTRANSFORM_H
/* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* See cxx source for full Copyright notice */
/* $Id$ */
////////////////////////////////////////////////////////////////////////////
// //
// Transforms clusters into space points with calibrated positions //
// defined in the local tracking system //
// //
////////////////////////////////////////////////////////////////////////////
#include "TObject.h"
class TGeoHMatrix;
class AliTRDgeometry;
class AliTRDcluster;
class AliTRDCommonParam;
class AliTRDcalibDB;
class AliTRDCalROC;
class AliTRDCalDet;
class AliTRDpadPlane;
class AliTRDtransform : public TObject {
public:
AliTRDtransform();
AliTRDtransform(Int_t det);
AliTRDtransform(const AliTRDtransform &t);
virtual ~AliTRDtransform();
AliTRDtransform &operator=(const AliTRDtransform &t);
virtual void Copy(TObject &t) const;
AliTRDpadPlane* GetPadPlane() const {return fPadPlane;}
virtual Bool_t Transform(AliTRDcluster *c);
virtual void Recalibrate(AliTRDcluster *c, Bool_t setDet = kTRUE);
void SetDetector(Int_t det);
static AliTRDgeometry& Geometry();
protected:
Int_t fDetector; // Detector number
AliTRDCommonParam *fParam; // TRD common parameters
AliTRDcalibDB *fCalibration; // TRD calibration interface object
AliTRDCalROC *fCalVdriftROC; // Pad wise Vdrift calibration object
AliTRDCalROC *fCalT0ROC; // Pad wise T0 calibration object
AliTRDCalROC *fCalPRFROC; // Pad wise PRF calibration object
const AliTRDCalDet *fkCalVdriftDet; // ROC wise Vdrift calibration object
const AliTRDCalDet *fkCalT0Det; // ROC wise T0 calibration object
const AliTRDCalDet *fkCalExBDet; // ROC wise ExB calibration object
Double_t fCalVdriftDetValue; // ROC wise Vdrift calibration value
Double_t fCalT0DetValue; // ROC wise T0 calibration value
Double_t fCalExBDetValue; // Det wise ExB calibration value
Double_t fSamplingFrequency; // ADC sampling frequency
AliTRDpadPlane *fPadPlane; // The current pad plane object
Double_t fZShiftIdeal; // Needed to define Z-position relative to middle of chamber
TGeoHMatrix *fMatrix; // Transformation matrix for a given chamber
ClassDef(AliTRDtransform, 3) // Transforms clusters
};
#endif
|
e924577586d8df58e1ed4a0e3245216c3050b79a | db57b19e70315c4adb79020c64a1c9d2b4e3cc94 | /Game/shield.cpp | 4d1a0704ea80b7c7e9caef459bd574d643d12595 | [] | no_license | rock3125/gforce-x | da9d5d75769780939314bf03ac008f9d7362e675 | 3a349ea799dfe1f24fb04bb14b643175730c2d95 | refs/heads/master | 2021-12-25T06:27:14.101284 | 2017-02-20T09:32:44 | 2017-02-20T09:32:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 868 | cpp | shield.cpp | //////////////////////////////////////////////////////////////////////
/// GRAVITY FORCE X
///
/// (c)Copyright Peter de Vocht, 2006
///
/// I'm releasing this code under GPL v2.1 (see included file lgpl.txt)
///
//////////////////////////////////////////////////////////////////////
#include "standardFirst.h"
#include "system/model/model.h"
#include "game/shield.h"
#include "game/commonModels.h"
///////////////////////////////////////////////////////////
Shield::Shield()
{
xa = 0;
ya = 0;
za = 0;
}
Shield::~Shield()
{
}
void Shield::EventLogic(double time)
{
xa += 0.5f;
ya += 33;
}
void Shield::Draw(double time)
{
Model* model = CommonModels::Get()->GetShield();
if (model != NULL)
{
model->SetPosition(GetPosition());
model->SetRotationEuler(D3DXVECTOR3(xa,ya,za));
model->Draw(time);
}
}
|
6aad6bb866b586258f4e76f54ea6dac84e02eb3f | 532e269c32afbd85f0b13dfccd017bb822da5a65 | /TP/taskplanning_V1/src/main.cpp | b6c5605bac7328a1024a8d49889b3fa9807b4f29 | [] | no_license | CVYang/UESTC_AA_MBZIRC205 | 2dd009be10b0920e6280073bb6736871688f094f | c0204cfe7d9a001de0eb4f627a27c4e6a2168b29 | refs/heads/master | 2020-07-19T00:07:29.139762 | 2019-09-04T14:41:09 | 2019-09-04T14:41:09 | 206,339,667 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,880 | cpp | main.cpp | #include <opencv2/opencv.hpp>
#include <opencv2/features2d/features2d.hpp>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <string.h>
#include <iostream>
#include <vector>
#include <time.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/select.h>
#include <assert.h>
#include <asm/ioctls.h>
#include <asm/termbits.h>
#include "../inc/detect.h"
#include <librealsense2/rs.hpp> // Include RealSense Cross Platform API
int colorpara[4][3]={
{30,105,130}, // Blue
{80,115,65}, // Green
{7,8,9}, // Red
{135,60,30} // orange
};
/*SIZE
------------------------
red 0.3*0.2*0.2
green 0.6*0.2*0.2
blue 1.2*0.2*0.2
orange 1.8*0.2*0.2
------------------------
Domain RGB
------------------------
red (134,59,80) (360,255,231)
green (22,37,22) (208,255,238)
blue
orange
------------------------
Domain HSV
------------------------
red (0,43,46) (10,255,255)/(156,43,46) (180,255,255)/(155,80,80) (180,255,255)
green (35,43,46) (77,255,255)
blue (100,43,46) (124,255,255)
orange (11,43,46) (25,255,255)
------------------------
*/
using namespace cv;
using namespace std;
int fd; //serialport
int param_baudrate_;
int serial_initial()
{
struct termios2 tio;
ioctl(fd, TCGETS2, &tio);
bzero(&tio, sizeof(struct termios2));
tio.c_cflag = BOTHER;
tio.c_cflag |= (CLOCAL | CREAD | CS8); //8 bit no hardware hanfddshake
tio.c_cflag &= ~CSTOPB; //1 stop bit
tio.c_cflag &= ~CRTSCTS; //No CTS
tio.c_cflag &= ~PARENB; //No Parity
#ifdef CNEW_RTSCTS
tio.c_cflag &= ~CNEW_RTSCTS; // no hw flow control
#endif
tio.c_iflag &= ~(IXON | IXOFF | IXANY); // no sw flow control
tio.c_cc[VMIN] = 0; //min chars to read
tio.c_cc[VTIME] = 0; //time in 1/10th sec wait
tio.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
// raw output mode
tio.c_oflag &= ~OPOST;
tio.c_ispeed = 115200;
tio.c_ospeed = 115200;
ioctl(fd, TCSETS2, &tio);
return 0;
}
int serial_open()
{
fd = open("/dev/ttyUSB0",O_RDWR| O_NDELAY);
if(fd == -1)
{
perror("Open UART failed!");
return -1;
}
//sleep(1000);
return fd;
}
void serial_close()
{
close(fd);
}
void serial_send(unsigned char * buf, int len)
{
int n =0;
n = write(fd,buf,len);
if(n == -1)
{
perror("write UART failed!");
}
}
typedef struct calculateDistanceOfTarget
{
double f;
double y;
double p;
double w;
double ratio;
double sx;
double sy;
double sz;
}calculateDistanceOfTarget;
calculateDistanceOfTarget target;
void FindROI(Mat& img) {
Mat gray_src;
cvtColor(img, gray_src, COLOR_BGR2GRAY);
//边缘检测
Mat canny_output;
Canny(gray_src, canny_output, 10, 100, 3, false);
//轮廓查找
vector<vector<Point> > contours;
vector<Vec4i> hireachy;
findContours(canny_output, contours, hireachy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0));
//绘制轮廓
int minw = img.cols*0.75;
int minh = img.rows*0.75;
RNG rng(12345);
Mat drawImage = Mat::zeros(img.size(), CV_8UC3);
Rect bbox;
for (size_t t = 0; t < contours.size(); t++) {
//查找可倾斜的最小外接矩
RotatedRect minRect = minAreaRect(contours[t]);
//获得倾斜角度
float degree = abs(minRect.angle);
if (minRect.size.width > minw && minRect.size.height > minh && minRect.size.width < (img.cols - 5)) {
printf("current angle : %f\n", degree);
Point2f pts[4];
minRect.points(pts);
bbox = minRect.boundingRect();
Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));
for (int i = 0; i < 4; i++) {
line(drawImage, pts[i], pts[(i + 1) % 4], color, 2, 8, 0);
}
}
}
imshow("output", drawImage);
//提取ROI区域
if (bbox.width > 0 && bbox.height > 0) {
Mat roiImg = img(bbox);
imshow("roi_win", roiImg);
}
return;
}
int main(int argc, char const *argv[])
{
map<int,int>task;
const char* depth_win="depth_Image";
cv::namedWindow(depth_win,cv::WINDOW_AUTOSIZE);
const char* color_win="color_Image";
cv::namedWindow(color_win,cv::WINDOW_AUTOSIZE);
const char* canny_win="canny_Image";
cv::namedWindow(canny_win,cv::WINDOW_AUTOSIZE);
const char* target_win="target_Image";
cv::namedWindow(target_win,cv::WINDOW_AUTOSIZE);
const char* mask_win="mask_Image";
cv::namedWindow(mask_win,cv::WINDOW_AUTOSIZE);
const char* mask_canny_win="mask_canny_Image";
cv::namedWindow(mask_canny_win,cv::WINDOW_AUTOSIZE);
//深度图像颜色map
rs2::colorizer c; // Helper to colorize depth images
rs2::align align_to(RS2_STREAM_COLOR);
//创建数据管道
rs2::pipeline pipe;
rs2::config pipe_config;
pipe_config.enable_stream(RS2_STREAM_DEPTH,1280,720,RS2_FORMAT_Z16,30);
pipe_config.enable_stream(RS2_STREAM_COLOR,1280,720,RS2_FORMAT_BGR8,30);
//start()函数返回数据管道的profile
rs2::pipeline_profile profile = pipe.start(pipe_config);
//定义一个变量去转换深度到距离
float depth_clipping_distance = 1.f;
//声明数据流
auto depth_stream=profile.get_stream(RS2_STREAM_DEPTH).as<rs2::video_stream_profile>();
auto color_stream=profile.get_stream(RS2_STREAM_COLOR).as<rs2::video_stream_profile>();
//获取内参
auto intrinDepth=depth_stream.get_intrinsics();
auto intrinColor=color_stream.get_intrinsics();
//直接获取从深度摄像头坐标系到彩色摄像头坐标系的欧式变换矩阵
//auto extrinDepth2Color=depth_stream.get_extrinsics_to(color_stream);
Mat targetImg, grayImg,hsvImg,cannyImg;
Mat dst;
Mat kernel;
Mat mask,mask_gray,mask_hsv,mask_canny,mask_dst;
sleep(5);
vector<std::vector<cv::Point> > contours;
vector<cv::Vec4i> hierarchy;
vector<std::vector<cv::Point> > mask_contours;
vector<cv::Vec4i> mask_hierarchy;
vector<std::vector<cv::Point> > target_contours;
vector<cv::Vec4i> target_hierarchy;
while(cv::waitKey(1)!='q')
{
rs2::frameset frameset = pipe.wait_for_frames();
auto processed = align_to.process(frameset);
//取深度图和彩色图
rs2::frame color_frame = processed.get_color_frame();//processed.first(align_to);
rs2::frame depth_frame = processed.get_depth_frame();
rs2::frame depth_frame_4_show = processed.get_depth_frame().apply_filter(c);
//获取宽高
const int depth_w=depth_frame.as<rs2::video_frame>().get_width();
const int depth_h=depth_frame.as<rs2::video_frame>().get_height();
const int color_w=color_frame.as<rs2::video_frame>().get_width();
const int color_h=color_frame.as<rs2::video_frame>().get_height();
//创建OPENCV类型 并传入数据
Mat depth_image(Size(depth_w,depth_h),
CV_16U,(void*)depth_frame.get_data(),Mat::AUTO_STEP);
Mat depth_image_4_show(Size(depth_w,depth_h),
CV_8UC3,(void*)depth_frame_4_show.get_data(),Mat::AUTO_STEP);
Mat color_image(Size(color_w,color_h),
CV_8UC3,(void*)color_frame.get_data(),Mat::AUTO_STEP);
GaussianBlur(color_image,color_image,cv::Size(3,3),3,3);
cvtColor(color_image,hsvImg,CV_BGR2HSV);
inRange(hsvImg,cv::Scalar(0,48,38),cv::Scalar(255,230,255), dst);
kernel = getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(13, 13));
morphologyEx(dst,dst,cv::MORPH_OPEN,kernel);
dilate(dst,dst,kernel,cv::Point(-1,-1));
Canny(dst,cannyImg,10,100,3);
cv::findContours(cannyImg,contours,hierarchy, CV_RETR_EXTERNAL , CV_CHAIN_APPROX_SIMPLE);
cv::Rect rect_;
if(contours.size()>0)
{
double maxArea=0;
for(int i=0;i<contours.size();i++)
{
double area = contourArea(contours[static_cast<int>(i)]);
if (area > maxArea)
{
maxArea = area;
rect_ = boundingRect(contours[static_cast<int>(i)]);
}
}
}
// cv::Point2d P1(rect_.x+rect_.width/2,rect_.y+rect_.height/2);
if(rect_.x != 0)
{
// cv::rectangle(color_image,cv::Point2d(rect_.x,rect_.y),cv::Point2d(rect_.x+rect_.width,rect_.y+rect_.height),cv::Scalar(0,255,0),2);
mask=color_image(rect_);
cvtColor(mask,mask_hsv,CV_BGR2HSV);
inRange(mask_hsv,cv::Scalar(0,48,38),cv::Scalar(255,230,255), mask_dst);
kernel = getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(11, 11));
morphologyEx(mask_dst,mask_dst,cv::MORPH_OPEN,kernel);
dilate(mask_dst,mask_dst,kernel,cv::Point(-1,-1));
Canny(mask_dst,mask_canny,10,80,3);
imshow(mask_canny_win,mask_canny);
cv::findContours(mask_canny,mask_contours,mask_hierarchy, CV_RETR_EXTERNAL , CV_CHAIN_APPROX_SIMPLE);
float maxw = 0;
float maxh = 0;
double degree = 0;
cv::Rect mask_rect;
int select = 0;
if(mask_contours.size()>0)
{
double mask_maxArea=0;
for(int i=0;i<mask_contours.size();i++)
{
double mask_area = contourArea(mask_contours[static_cast<int>(i)]);
if (mask_area > mask_maxArea)
{
mask_maxArea = mask_area;
mask_rect = boundingRect(mask_contours[static_cast<int>(i)]);
select = i;
}
RotatedRect rrect = minAreaRect(mask_contours[i]);
//cv::rectangle(mask,cv::Point2d(rrect.,rrect.y),cv::Point2d(rrect.x+rrect.width,rrect.y+rrect.height),cv::Scalar(0,255,0),2);
if(!rrect.size.empty())
{
degree = abs(rrect.angle);
cout<<"degree: "<<degree<<endl;
if (degree > 0)
{
maxw = max(maxw, rrect.size.width);
maxh = max(maxh, rrect.size.height);
}
}
}
for (size_t t = 0; t < mask_contours.size(); t++)
{
RotatedRect minRect = minAreaRect(mask_contours[t]);
if (maxw == minRect.size.width && maxh == minRect.size.height)
{
degree = 90+minRect.angle;
Point2f pts[4];
minRect.points(pts);
}
}
}
if(degree != 0)
{
Point2f center(mask.cols / 2, mask.rows / 2);
Mat rotm = getRotationMatrix2D(center, degree, 1.0);
//旋转图像
Mat RotateDst;
warpAffine(mask, RotateDst, rotm, mask.size(), INTER_LINEAR, 0, Scalar(255, 255, 255));
// 统计砖块信息 颜色空间
Mat target_gray,target_canny,target_temp;
Rect cut(5,5,RotateDst.cols-5,RotateDst.rows-12);
target_temp = RotateDst(cut);
cvtColor(target_temp,target_gray,CV_BGR2GRAY);
Canny(target_gray,target_canny,10,60,3);
kernel = getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(5, 5));
morphologyEx(target_canny,target_canny,cv::MORPH_CLOSE,kernel);
//dilate(mask_dst,mask_dst,kernel,cv::Point(-1,-1));
imshow("target_canny",target_canny);
findContours(target_canny,target_contours,target_hierarchy, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);
cv::Rect tarrect;
int index = 0;
if(target_contours.size()>0)
{
cout<<"------------------------"<<endl;
for(int i=0;i<target_contours.size();i++)
{
int area =contourArea(target_contours[static_cast<int>(i)]);
if(area<1600 && area > 100)
{
tarrect = boundingRect(target_contours[static_cast<int>(i)]);
cout<<tarrect.size()<<" area: "<<area<<endl;
Point org;
org.x = tarrect.x;
org.y = tarrect.y+tarrect.height/2;
char num[3];
sprintf(num,"%d",i);
putText(target_temp,(std::string)num,org,cv::FONT_HERSHEY_COMPLEX,0.3,Scalar(0,255,255),1,8,0);
//drawContours(RotateDst,target_contours,i,Scalar(0,255,0),CV_FILLED,8,target_hierarchy);
cv::rectangle(target_temp,tarrect.tl(),tarrect.br(),cv::Scalar(0,255,0),2);
}
}
cout<<"++++++++++++++++++++++++++++++"<<endl;
}
imshow("temp",target_temp);
imshow("rotatedst",RotateDst);
}
}
if(!mask.empty())
{
imshow(mask_win,mask);
}
imshow(target_win,dst);
imshow(canny_win,cannyImg);
imshow(depth_win,depth_image_4_show);
imshow(color_win,color_image);
}
// 0 255 48 230 38 255
return EXIT_SUCCESS;
}
|
c5454f12b542667e9b60f400ffe2653320af5100 | 40d77d696707499a4195497447f4c96ae46467af | /src/test1.cpp | 262c0d2cfc273c835a1aeb6dad35ac3bb4d9c38b | [] | no_license | aoyan27/pcl_tutorial | 6068130afe6e9f69f02ab32b4597db8c4eba2d12 | 3719a15bfe1b6ec0992fab7d09f709efe53cd973 | refs/heads/master | 2021-09-08T01:22:53.282843 | 2018-03-05T03:56:17 | 2018-03-05T03:56:17 | 99,441,796 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 598 | cpp | test1.cpp | // ROS headers
#include <ros/ros.h>
#include <pcl_ros/point_cloud.h>
#include <tf/transform_listener.h>
#include <tf_conversions/tf_eigen.h>
#include <eigen_conversions/eigen_msg.h>
// PCL TRUNK headers
#include <pcl/pcl_config.h>
#include <pcl/common/common.h>
#include <pcl/console/time.h>
#include <pcl/common/transforms.h>
#include <pcl/filters/filter.h>
#include <pcl/filters/voxel_grid.h>
#include <pcl/io/ply_io.h>
using namespace std;
int main (int argc, char **argv)
{
cout<< PCL_VERSION_PRETTY <<endl;
// Call a PCL 1.8.0 feature ! (don't forget the include)
return 0;
}
|
d9ad9cae9cca4740943b2daa461845fd5b68883e | aba8b646c24dd6f49a83b334d8800e3442bd49d1 | /omp/09D-OddLove/09D-OddLove-bt-TLE.cpp | 8014959a72956d7cead9403c43c1378664cfc987 | [] | no_license | marcos-dv/competitive-programming | 89c1af786c1bf2f3e5a402d0d68e5a3d965f9053 | 3709975aab501d6a0b78e8f44229730df67716fd | refs/heads/master | 2022-06-12T06:38:47.384667 | 2020-05-04T16:50:41 | 2020-05-04T16:50:41 | 261,242,535 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,935 | cpp | 09D-OddLove-bt-TLE.cpp | #include <bits/stdc++.h>
using namespace std;
//Backtracking (TLE)
int w, h;
bool ** par;
int * paresfila;
int * pri;
int * se;
int pares;
//Quedan k pares, estamos en fila f, columna c
inline int bt(int k, int f, int c, int mov) {
if (k == 0) {
return mov;
}
if (paresfila[f] == 0) {
return bt(k,f+1,c,++mov);
}
k-=paresfila[f];
//Dividir
if ((pri[f] < c) && (se[f] > c)) {
int mizq = mov;
mizq += abs(c-pri[f]);
mizq += abs(se[f]-pri[f]);
if (k != 0)
mizq++;
mizq = bt(k, f+1, se[f], mizq);
int mder = mov;
mder += abs(c-se[f]);
mder += abs(se[f]-pri[f]);
if (k != 0)
mder++;
mder = bt(k, f+1, pri[f], mder);
return min(mizq, mder);
}
else {
if (abs(c-pri[f]) < abs(c-se[f])) {
mov += abs(c-pri[f]);
mov += abs(se[f]-pri[f]);
c = se[f];
}
else {
mov += abs(c-se[f]);
mov += abs(se[f]-pri[f]);
c = pri[f];
}
if (k != 0)
mov++;
return bt(k, f+1, c, mov);
}
}
int main() {
int nc;
cin >> nc;
while (nc--) {
cin >> w >> h;
par = new bool * [h];
for(int i = 0; i < h; i++)
par[i] = new bool[w];
paresfila = new int[h];
pri = new int[h];
se = new int[h];
pares = 0;
for(int i = 0; i < h; ++i)
for(int j = 0; j < w; ++j)
par[i][j] = false;
for(int i = 0; i < h; i++) {
paresfila[i] = 0;
pri[i] = 100000;
se[i] = -1;
}
string s;
for(int i = 0; i < h; i++) {
cin >> s;
for(int j = 0; j < w; ++j) {
par[i][j] = (((s[j]-'0') % 2) == 0);
if (par[i][j]) {
pri[i] = min(pri[i], j);
se[i] = max(se[i], j);
paresfila[i]++;
pares++;
}
}
// cerr << "Fila = " << i << " | PRI = " << pri[i] << " | SEC = " << se[i] << endl;
}
/*
for(int i = 0; i < h; ++i)
for(int j = 0; j < w; ++j) {
cerr << par[i][j];
if (j == w-1)
cerr << endl;
}
*/
if (pares == 0) {
cout << '0' << endl;
continue;
for(int i = 0; i < h; i++)
delete par[i];
delete par;
delete paresfila;
delete pri;
delete se;
}
int mov = 0;
int fila = 0;
int col = 0;
mov = bt(pares, fila, col, mov);
// cerr << "pares = " << pares << endl;
/*while (pares > 0) {
if (paresfila[fila] > 0) {
//cerr << "FILA " << fila << endl;
if (abs(col-pri[fila]) < abs(col-se[fila])) {
//
mov += abs(col-pri[fila]);
mov += abs(se[fila]-pri[fila]);
col = se[fila];
}
else {
mov += abs(col-se[fila]);
mov += abs(se[fila]-pri[fila]);
col = pri[fila];
}
pares-=paresfila[fila];
}
fila++;
if (pares)
mov++;
}
*/
cout << mov << endl;
for(int i = 0; i < h; i++)
delete par[i];
delete par;
delete paresfila;
delete pri;
delete se;
}
}
/*
7
5 3
54578
36329
75241
9 1
759456785
2 2
22
22
6 6
777777
772777
777777
777727
727777
777777
7 7
1811181
1118811
1881111
8111111
1188181
1881181
1111111
2
8 3
29511211
59356961
25299669
6 4
846817
645887
715322
558583
*/
|
425f371a24e16e2e6bbe3551b6a7fe7cf074ce60 | f46faed2f30a13773c41b007cc13aecd1b200d35 | /hector_software_monitor/include/hector_software_monitor/analyzers/simple_analyzer.h | 0723c833806fc4a4c84950dd0879e840466bb989 | [] | permissive | tu-darmstadt-ros-pkg/hector_diagnostics | 53fa2066181495614e0f744f860a3c3497b83c61 | 2b4d44186379b8a455da97624458ef3c23976a90 | refs/heads/master | 2023-06-13T07:40:53.760644 | 2023-06-05T12:49:22 | 2023-06-05T12:49:22 | 24,555,244 | 1 | 0 | BSD-3-Clause | 2023-04-20T11:43:12 | 2014-09-28T09:01:34 | Python | UTF-8 | C++ | false | false | 2,929 | h | simple_analyzer.h | #pragma once
#include <ros/ros.h>
#include <diagnostic_msgs/DiagnosticStatus.h>
#include <diagnostic_aggregator/analyzer.h>
namespace hector_software_monitor
{
/*!
* @brief The SimpleAnalyzer class is a simple diagnostic analyzer that can be used as a blueprint for other
* analyzers
*
* SimpleAnalyzer provides only one matching criterion ('startswith') and removes the prefix for every status item.
* Required parameters:
* - \b type This is the class name of the analyzer, used to load the correct plugin type.
* - \b path All diagnostic items analyzed by the SimpleAnalyzer will be under "Base Path/My Path".
* - \b find_prefix Parameter for matching, item name must start with this value
* Optional parameters:
* - \b timeout Any item that doesn't update within the timeout will be marked as "Stale", and will cause an error
* in the top-level status. Default is 5.0 seconds. Any value <0 will cause stale items to be ignored. Other
* matching criteria like 'contains', 'name' etc. can be easily implemented as for the GenericAnalyzer.
*/
class SimpleAnalyzer : public diagnostic_aggregator::Analyzer
{
public:
/*!
* @brief Initializes SimpleAnalyzer from namespace, loads parameters
*
* @param base_path Prefix for all analyzers (ex: 'Robot')
* @param nh NodeHandle in full namespace
* @return True if initialization succeed, false otherwise
*/
// NOLINTNEXTLINE
bool init(const std::string base_path, const ros::NodeHandle& nh) override;
/*!
* @brief Returns true if item matches any of the given criteria, in this case starts with the given prefix
*
*/
// NOLINTNEXTLINE
bool match(const std::string name) override;
/*!
* @brief Update state with new StatusItem
*/
// NOLINTNEXTLINE
bool analyze(const boost::shared_ptr<diagnostic_aggregator::StatusItem> item) override;
/*!
* @brief Reports current state, returns vector of formatted status messages
*
* This method does not check any conditions but serves only to illustrate how report() can be used.
* @return Vector of DiagnosticStatus messages, with correct prefix for all names.
*/
std::vector<boost::shared_ptr<diagnostic_msgs::DiagnosticStatus>> report() override;
std::string getPath() const override
{
return path_;
}
std::string getName() const override
{
return nice_name_;
}
private:
/*!
* @brief Stores items by name. State of analyzer
*/
std::map<std::string, boost::shared_ptr<diagnostic_aggregator::StatusItem>> items_;
std::string path_;
std::string nice_name_;
std::string prefix_;
double timeout_ = 5.0; // Default timeout: If no new matched messages arrive within this period the analyzer reports
// all stale. This can be the case e.g. if frequency_publisher node is not running.
}; // namespace diagnostic_aggregator::Analyzer
} // namespace hector_software_monitor
|
f39fb69934585b7aca692222d34dd2d755ff80f9 | f6cee5921b9b1870574f794824a17dc8938b87c5 | /solutions/C++/926.将字符串翻转到单调递增.cpp | afb070537132b6b511751412f415f8a9bb7e5b65 | [] | no_license | DreamInvoker/leetcode | 20e00f94614749b1ecc1fdc298dba31de45dd8d7 | b98a01a7a6dd5002785471585352b3ea6ee1e5de | refs/heads/master | 2023-03-08T12:01:40.832303 | 2021-02-26T08:47:40 | 2021-02-26T08:47:40 | 248,532,813 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,959 | cpp | 926.将字符串翻转到单调递增.cpp | /*
* @lc app=leetcode.cn id=926 lang=cpp
*
* [926] 将字符串翻转到单调递增
*
* 使用前缀和的方法。
*
* 假设我们有5个字符,先不用care这5个字符是什么,那么翻转之后的最终结果要在以下字符串中选一个翻转次数最小的。
* “00000”, “00001”, “00011”, “00111”, “01111”, “11111”
* 因此我们可以把这个问题转化成为[分割问题],即划分位置左边全为0,右边全为1,
* 对于一个有N个字符的字符串来说,一共有(N+1)个划分位置,假设为5, 字符串为:101010,划分位置(以‘.’表示)可能为:.1.0.1.0.1.0.
* 这样的话,我们就可以用P数组保存好每个划分位置左边1的个数,来求出我们当前位置需要翻转的次数
*
* 假设我们在N个字符的字符串第i位置进行划分,假设P[i]是它左边为1的字符个数,那么因为我们要得到这个划分位置左边全为0,右边全为1,
* 所以左边需要翻转的个数即为左边为1的字符数,即P[i]
* 而右边的1的个数为P[N]-P[i],这些1不需要翻转,需要翻转的是0,右边的字符数为N-i,所以右边0的个数即翻转数为N-i-(P[N]-P[i])
* 所以该划分位置的总的翻转个数为P[i] + N-i-(P[N]-P[i]) = 2 * P[i] + N - i - P[N]
*
* 使用动态规划的方式来保存每个划分位置左边有多少个1 (详见代码)
*
*/
// @lc code=start
#include <string>
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int minFlipsMonoIncr(string S) {
int size = S.size();
vector<int> dp(size + 1, 0);
for(int i = 1; i <= size; ++i){
dp[i] = dp[i - 1] + (S[i - 1] == '1' ? 1 : 0);
}
int ans = 20000;
for(int i = 0; i <= size; ++i){
ans = min(ans, dp[i] + size - i - (dp[size] - dp[i]));
}
return ans;
}
};
// @lc code=end
|
acc88dcbbbb221b87b851176102565af27b6de5f | d8536fc3d415cd7862981a5035ece6362d0887d5 | /LuaClass/MyBolt/DataClass.h | 3caca4999a4796c202033ac793fcf1520e884df8 | [] | no_license | nifei/samples | 74b69341596cf1a15917604cdb8ae92658b3b80b | b5d080c079ccf625cb67f70e1647dfe36531e784 | refs/heads/master | 2016-08-07T06:36:03.404445 | 2013-11-05T10:39:02 | 2013-11-05T10:39:02 | 12,396,820 | 2 | 0 | null | null | null | null | GB18030 | C++ | false | false | 984 | h | DataClass.h | #ifndef _DATA_CLASS_H_
#define _DATA_CLASS_H_
#include <string>
class Base
{
public:
virtual void Click()
{
::MessageBoxA(0, "基类Base::Click()的实现被调用", "警告", 0);
}
virtual ~Base(){}
};
class Derived1 : public Base
{
public:
virtual void Click()
{
::MessageBoxA(0, "子类Derived1对基类方法Click()的实现被调用", "警告", 0);
}
void Click1()
{
::MessageBoxA(0, "子类Derived1的方法Click1()的实现被调用", "警告", 0);
}
};
class Derived2 : public Base
{
public:
Derived2(const std::string string = "默认")
:m_string(string){}
virtual void Click()
{
::MessageBoxA(0, "子类Derived1对基类方法Click()的实现被调用", "警告", 0);
}
void Click2()
{
::MessageBoxA(0, "子类Derived2的方法Click2()的实现被调用", "警告", 0);
}
void Click3()
{
::MessageBoxA(0, m_string.c_str(), "警告", 0);
}
private:
const std::string m_string;
};
#endif |
10d3d31ac4dd0a8858b047a3e44006023f9cc0ad | 07e6fc323f657d1fbfc24f861a278ab57338b80a | /cpp/sketches_SDL/Molecular/test_FARFF.cpp | f93c42945398fa53b22f3a7c85ec133a77a389e9 | [
"MIT"
] | permissive | ProkopHapala/SimpleSimulationEngine | 99cf2532501698ee8a03b2e40d1e4bedd9a12609 | 47543f24f106419697e82771289172d7773c7810 | refs/heads/master | 2022-09-05T01:02:42.820199 | 2022-08-28T10:22:41 | 2022-08-28T10:22:41 | 40,007,027 | 35 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 10,065 | cpp | test_FARFF.cpp |
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <vector>
#include <math.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_opengl.h>
#include "Draw.h"
#include "Draw3D.h"
#include "Solids.h"
#include "fastmath.h"
#include "Vec3.h"
#include "Mat3.h"
#include "VecN.h"
#include "AppSDL2OGL_3D.h"
#include "testUtils.h"
#include "SDL_utils.h"
#include "Plot2D.h"
#include "Draw3D_Molecular.h"
//#include "MMFF.h"
//#include "RARFFarr.h"
int i_DEBUG = 0;
#include "DynamicOpt.h"
#include "FlexibleAtomReactiveFF.h"
#include "FlexibleAtomReactiveFF_dyn.h"
// ======= THE CLASS
class TestAppFARFF: public AppSDL2OGL_3D { public:
bool bRun = false;
int perFrame = 1;
FARFF ff;
DynamicOpt opt;
Plot2D plot1;
int ogl_sph=0;
int ipicked = -1;
Vec3d ray0;
Vec3d mouse_p0;
int nbBrush = 3;
double Emin,Emax;
int npoints;
Vec3d* points =0;
double* Energies=0;
Vec3d * Forces =0;
int fontTex;
virtual void draw ();
virtual void drawHUD();
//virtual void mouseHandling( );
virtual void eventHandling ( const SDL_Event& event );
//virtual void keyStateHandling( const Uint8 *keys );
TestAppFARFF( int& id, int WIDTH_, int HEIGHT_ );
};
TestAppFARFF::TestAppFARFF( int& id, int WIDTH_, int HEIGHT_ ) : AppSDL2OGL_3D( id, WIDTH_, HEIGHT_ ) {
fontTex = makeTextureHard( "common_resources/dejvu_sans_mono_RGBA_pix.bmp" );
//srand(15480); int nat = 15; double sz = 4; double szH = 1; // Test 1
srand(1581); int nat = 30; double sz = 5; double szH = 0.5; // Test 2
//srand(1581); int nat = 40; double sz = 5; double szH = 0.1; // Test 2
ff.realloc(nat);
for(int ia=0; ia<nat; ia++){
ff.apos[ia].fromRandomBox( (Vec3d){-sz,-sz,-szH},(Vec3d){sz,sz,szH} );
ff.aconf[ia].set(4,4,4);
//double rnd=randf(); if(rnd>0.7){ if(rnd<0.9){ ff.aconf[ia].a=3; }else{ ff.aconf[ia].a=2; } }
ff.aconf[ia].a=3; double rnd=randf(); if(rnd<0.3){ ff.aconf[ia].a=4; }
for(int j=0; j<N_BOND_MAX; j++){
int io = j+ia*N_BOND_MAX;
//printf( "atom[%i] %i %i \n", ia, j, io );
ff.opos[io].fromRandomSphereSample();
}
}
//ff.atype0.Kee = -0.5;
//ff.atype0.Kpp = 0;
/*
int ia,io;
ia=0; io=ia*N_BOND_MAX;
ff.apos [ia].set( 0.0,0.0,0.0);
ff.aconf[ia].set(3,4,4);
ff.opos [io+0].set(-1.0,0.0,-0.1);
ff.opos [io+1].set(+1.0,0.0,-0.1);
ff.opos [io+2].set(0.0,+1.0, 1.3);
ff.opos [io+3].set(0.0,-1.0,-1.3);
ia=1; io=ia*N_BOND_MAX;
ff.apos [ia].set(-1.0,0.0,0.0);
ff.aconf[ia].set(3,4,4);
ff.opos [io+0].set(+1.0,0.0,-0.1);
ff.opos [io+1].set(-1.0,0.0,-0.1);
ff.opos [io+2].set(0.0,+1.0,+0.1);
ff.opos [io+3].set(0.0,-1.0,+0.1);
ia=2; io=ia*N_BOND_MAX;
ff.apos [ia].set(+1.2,0.0,0.0);
ff.aconf[ia].set(4,4,4);
ff.opos [io+0].set(-1.0,0.0,+0.1);
ff.opos [io+1].set( 1.0,0.0,+0.1);
ff.opos [io+2].set(0.0,+1.0,-0.1);
ff.opos [io+3].set(0.0,-1.0,-0.1);
*/
// =========== check numerical derivatives
/*
auto check_froce_atom0 = [&](const Vec3d& p,Vec3d& f)->double{
ff.apos[0] = p;
ff.cleanForce();
double E = ff.eval();
f = ff.aforce[0] * -1;
return E;
};
auto check_froce_orb0 = [&](Vec3d h,Vec3d& f)->double{
//printf( "check_froce_orb0 h (%g,%g,%g)\n", h.x, h.y, h.z );
ff.opos[0] = h;
ff.cleanForce();
double E = ff.eval();
ff.oforce[0].makeOrthoU(ff.opos[0]);
f = ff.oforce[0] * -1;
return E;
};
Vec3d fE,f, p = {-1.0,0.2,0.3}; p.normalize();
printf("Atom[0] "); checkDeriv(check_froce_atom0,{1.0,1.0,1.0}, 0.0001,fE, f );
printf("Orb [0] "); checkDeriv(check_froce_orb0 ,p, 0.0001,fE, f );
//exit(0);
*/
//ff.cleanForce();
//ff.eval();
opt.bindOrAlloc( 3*ff.nDOF, (double*)ff.dofs, 0, (double*)ff.fdofs, 0 );
//opt.setInvMass( 1.0 );
opt.cleanVel( );
//opt.initOpt( 0.05, 0.2 );
opt.initOpt( 0.01, 0.1 );
//exit(0);
Draw3D::makeSphereOgl( ogl_sph, 3, 0.25 );
printf( "ogl_sph %li \n", (long)ogl_sph );
ff.printAtoms();
printf( "ogl_sph %li \n", (long)ogl_sph );
//exit(0);
}
void TestAppFARFF::draw(){
glClearColor( 0.5f, 0.5f, 0.5f, 1.0f );
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glEnable(GL_DEPTH_TEST);
if( ff.tryResize( ) ){
// ToDo : We should properly convert velocities
opt.bindOrAlloc( 3*ff.nDOF, (double*)ff.dofs, 0, (double*)ff.fdofs, 0 );
opt.cleanVel( );
}
perFrame=100;
//perFrame=1;
if(bRun){
for(int itr=0;itr<perFrame;itr++){
//printf( " ==== frame %i i_DEBUG %i \n", frameCount, i_DEBUG );
double F2 = 1.0;
ff.cleanForce();
ff.eval();
//ff.apos[0].set(.0);
if(ipicked>=0){
Vec3d f = getForceSpringRay( ff.apos[ipicked], (Vec3d)cam.rot.c, ray0, -1.0 );
//printf( "f (%g,%g,%g)\n", f.x, f.y, f.z );
ff.aforce[ipicked].add( f );
};
//if(bRun)ff.moveGD(0.001, 1, 1);
F2 = opt.move_FIRE();
//for(int i=0; )printf( "", )
//printf( " |F| %g \n", sqrt(F2) );
//if(!(F2<1000000.0))perFrame=0;
}
}
//Vec3d bhs[N_BOND_MAX];
//atom1.torq = (Vec3d){0.1,0.0,0.0};
//atom1.moveRotGD(0.8);
//printf( "qrot (%g,%g,%g,%g)\n", atom1.qrot.x, atom1.qrot.y, atom1.qrot.z, atom1.qrot.w );
ray0 = (Vec3d)(cam.rot.a*mouse_begin_x + cam.rot.b*mouse_begin_y);
Draw3D::drawPointCross( ray0, 0.1 );
if(ipicked>=0) Draw3D::drawLine( ff.apos[ipicked], ray0);
glColor3f(1.0,1.0,1.0);
//drawRigidAtom( atom1 );
double fsc = 0.1;
double tsc = 0.1;
for(int i=0; i<ff.natom; i++){
if(ff.ignoreAtoms[i]) continue;
//if(!ff.ignoreAtoms[i]) {
//printf( "atom[%i] \n", i );
if(ff.aconf[i].a==4){ glColor3f(0.5,0.5,0.5); }else{ glColor3f(1.0,1.0,1.0); };
Draw3D::drawShape( ogl_sph, ff.apos[i], Mat3dIdentity, false );
glColor3f(0.0,0.0,0.0); Draw3D::drawPointCross(ff.apos[i], 0.1 );
//glColor3f(1.0,0.0,0.0); Draw3D::drawVecInPos( ff.aforce[i]*fsc, ff.apos[i] );
for(int j=0;j<N_BOND_MAX; j++){
int io = j + i*N_BOND_MAX;
if( j<ff.aconf[i].a ){
glColor3f(0.0,0.0,0.0); Draw3D::drawVecInPos( ff.opos[io], ff.apos[i] );
//glColor3f(1.0,0.0,0.0); Draw3D::drawVecInPos( ff.oforce[io], ff.apos[i]+ff.opos[io] );
}else{
glColor3f(0.0,0.5,0.0); Draw3D::drawLine ( ff.apos[i]+ff.opos[io]*0.5, ff.apos[i]-ff.opos[io]*0.5 );
}
}
//}
//glColor3f(0.0,0.0,1.0); Draw3D::drawVecInPos( ff.atoms[i].torq*tsc, ff.atoms[i].pos );
};
//Draw3D::atoms( ff.natoms, ff.apos, atypes, params, ogl_sph, 1.0, 0.25, 1.0 );
//Draw3D::shapeInPoss( ogl_sph, ff.natom, ff.apos, ff.aenergy );
//glColor3f(1.0,1.0,1.0);
//Draw3D::shapeInPoss( ogl_sph, ff.natom, ff.apos, 0 );
//Draw3D::drawAxis( 1.0);
//exit(0);
};
void TestAppFARFF::drawHUD(){
/*
glColor3f(1.0,1.0,1.0);
txt.viewHUD( {100,220}, fontTex );
gui.draw();
glTranslatef( 10.0,300.0,0.0 );
glColor3f(0.5,0.0,0.3);
Draw::drawText( "abcdefghijklmnopqrstuvwxyz \n0123456789 \nABCDEFGHIJKLMNOPQRTSTUVWXYZ \nxvfgfgdfgdfgdfgdfgdfg", fontTex, fontSizeDef, {10,5} );
*/
glTranslatef( 100.0,100.0,0.0 );
glScalef ( 10.0,10.00,1.0 );
plot1.view();
}
void TestAppFARFF::eventHandling ( const SDL_Event& event ){
//printf( "NonInert_seats::eventHandling() \n" );
switch( event.type ){
case SDL_KEYDOWN :
switch( event.key.keysym.sym ){
case SDLK_p: first_person = !first_person; break;
case SDLK_o: perspective = !perspective; break;
case SDLK_SPACE: bRun = !bRun; break;
//case SDLK_r: world.fireProjectile( warrior1 ); break;
//case SDLK_LEFTBRACKET: i_DEBUG=(i_DEBUG+1)%6; break;
case SDLK_RIGHTBRACKET: i_DEBUG=(i_DEBUG+1)%6; printf("i_DEBUG %i\n", i_DEBUG); break;
}
break;
case SDL_MOUSEBUTTONDOWN:
switch( event.button.button ){
case SDL_BUTTON_LEFT:{
ipicked = pickParticle( ray0, (Vec3d)cam.rot.c, 0.5, ff.natom, ff.apos, ff.ignoreAtoms );
mouse_p0 = (Vec3d)( cam.rot.a*mouse_begin_x + cam.rot.b*mouse_begin_y );
printf( "picked atom %i \n", ipicked );
}break;
case SDL_BUTTON_RIGHT:{
ipicked = pickParticle( ray0, (Vec3d)cam.rot.c, 0.5, ff.natom, ff.apos, ff.ignoreAtoms );
printf( "remove atom %i \n", ipicked );
ff.ignoreAtoms[ ipicked ] = true;
}break;
}break;
case SDL_MOUSEBUTTONUP:
switch( event.button.button ){
case SDL_BUTTON_LEFT:
if( (ipicked==-1) && nbBrush!=0 ){
Vec3d mouse_p = (Vec3d)( cam.rot.a*mouse_begin_x + cam.rot.b*mouse_begin_y );
Vec3d dir = mouse_p-mouse_p0;
ff.inserAtom( {nbBrush,4,4}, mouse_p0, dir, (Vec3d)cam.rot.b );
}
ipicked = -1;
break;
case SDL_BUTTON_RIGHT:
ipicked = -1;
break;
}break;
};
AppSDL2OGL::eventHandling( event );
}
// ===================== MAIN
TestAppFARFF* thisApp;
int main(int argc, char *argv[]){
SDL_Init(SDL_INIT_VIDEO);
SDL_GL_SetAttribute(SDL_GL_SHARE_WITH_CURRENT_CONTEXT, 1);
//SDL_SetRelativeMouseMode( SDL_TRUE );
int junk;
thisApp = new TestAppFARFF( junk , 800, 600 );
thisApp->loop( 1000000 );
return 0;
}
|
42eae01e54646ee1246e3eb8051051878853c058 | 5595314298a89422483706e23f86e4a6c4480325 | /OBDIIWebPageDevices.h | 8d2f7c8eff27b27867b4ec76d69d6982e6d711d5 | [
"MIT"
] | permissive | AnjinMeili/ESP32-OBDII | a802c9954644b0a8b518c5e351919d7dff6b5d3f | 7119314e5f603f85b96317c7664e9da8cf7fe84c | refs/heads/master | 2023-03-17T09:13:20.056159 | 2020-03-08T01:15:06 | 2020-03-08T01:15:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 155 | h | OBDIIWebPageDevices.h | #include <Arduino.h>
// Forward Declarations
class BTClassicDeviceLinkedList;
String* OBDIIWebPageDevicesString(BTClassicDeviceLinkedList *device_list);
|
b8a0e37e4066bc8d93c89ad0d2109b3815a43077 | 7477d3f7cceb5ec5b22ef55e897a8aefd0e98386 | /src/map.cpp | 02d083cc2e00aacb0676e41341721a818aa3eb72 | [
"MIT"
] | permissive | marchelzo/tower-defense | 2fe389e07282b3b069ac5f8c1bdf0009b99caebb | 01ebf7da9c5b7c10dcb3afde3ba1b610fba3da7b | refs/heads/master | 2020-04-06T04:52:31.314791 | 2015-01-09T01:16:41 | 2015-01-09T01:16:41 | 28,580,347 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,647 | cpp | map.cpp | #include <vector>
#include <fstream>
#include <cstdio>
#include <memory>
#include <algorithm>
#include "map.hpp"
#include "tile.hpp"
#include "sprite.hpp"
#include "textures.hpp"
#include "enemy.hpp"
#include "player.hpp"
#include "game.hpp"
static bool sprites_loaded;
/* sprites that we will use */
static std::unique_ptr<Sprite> grass { };
static std::unique_ptr<Sprite> sand_h { };
static std::unique_ptr<Sprite> sand_v { };
static std::unique_ptr<Sprite> sand_corner_top_left { };
static std::unique_ptr<Sprite> sand_corner_bottom_left { };
static std::unique_ptr<Sprite> sand_corner_top_right { };
static std::unique_ptr<Sprite> sand_corner_bottom_right { };
static std::unique_ptr<Sprite> sand_3way_up { };
static std::unique_ptr<Sprite> sand_3way_down { };
static std::unique_ptr<Sprite> sand_3way_right { };
static std::unique_ptr<Sprite> sand_3way_left { };
static std::unique_ptr<Sprite> sand_4way { };
static std::unique_ptr<Sprite> home { };
static std::unique_ptr<Sprite> spawn { };
static void should_not_happen(Enemy& e, const Map& m)
{
fputs("An enemy is on the grass\n"
"This should not happen!!!\n", stderr);
}
static void no_op(Enemy& e, const Map& m) {}
static void load_map_sprites()
{
grass = std::make_unique<Sprite>(Textures::GRASS_TEXTURE);
sand_h = std::make_unique<Sprite>(Textures::SAND_TEXTURE);
sand_v = std::make_unique<Sprite>(Textures::SAND_TEXTURE);
sand_v->rotate(90);
sand_corner_top_right = std::make_unique<Sprite>(Textures::SAND_CORNER_TEXTURE);
sand_corner_top_left = std::make_unique<Sprite>(Textures::SAND_CORNER_TEXTURE);
sand_corner_top_left->rotate(270);
sand_corner_bottom_right = std::make_unique<Sprite>(Textures::SAND_CORNER_TEXTURE);
sand_corner_bottom_right->rotate(90);
sand_corner_bottom_left = std::make_unique<Sprite>(Textures::SAND_CORNER_TEXTURE);
sand_corner_bottom_left->rotate(180);
sand_4way = std::make_unique<Sprite>(Textures::SAND_4WAY_TEXTURE);
sand_3way_down = std::make_unique<Sprite>(Textures::SAND_3WAY_TEXTURE);
sand_3way_up = std::make_unique<Sprite>(Textures::SAND_3WAY_TEXTURE);
sand_3way_up->rotate(180);
sand_3way_right = std::make_unique<Sprite>(Textures::SAND_3WAY_TEXTURE);
sand_3way_right->rotate(270);
sand_3way_left = std::make_unique<Sprite>(Textures::SAND_3WAY_TEXTURE);
sand_3way_left->rotate(90);
home = std::make_unique<Sprite>(Textures::HOME_TEXTURE);
spawn = std::make_unique<Sprite>(Textures::SPAWN_TEXTURE);
}
static void spawned(Enemy& e, const Map& m)
{
int x = e.get_x() / 48;
int y = e.get_y() / 48;
bool below = y + 1 != m.height() && m(y+1,x).get_type() != TileType::GRASS;
bool above = y > 0 && m(y-1,x).get_type() != TileType::GRASS;
bool right = x + 1 != m.width() && m(y,x+1).get_type() != TileType::GRASS;
bool left = x > 0 && m(y,x-1).get_type() != TileType::GRASS;
if (left) {
e.set_direction(Direction::LEFT);
return;
}
if (right) {
e.set_direction(Direction::RIGHT);
return;
}
if (above) {
e.set_direction(Direction::UP);
return;
}
if (below) {
e.set_direction(Direction::DOWN);
return;
}
fputs("Error: Invalid spawn position.\n", stderr);
}
static void turn_left(Enemy& e, const Map& m)
{
e.set_direction(Direction::LEFT);
}
static void turn_right(Enemy& e, const Map& m)
{
e.set_direction(Direction::RIGHT);
}
static void turn_up(Enemy& e, const Map& m)
{
e.set_direction(Direction::UP);
}
static void turn_down(Enemy& e, const Map& m)
{
e.set_direction(Direction::DOWN);
}
static void turn_random(Enemy& e, const Map& m)
{
int x = e.get_x() / 48;
int y = e.get_y() / 48;
std::vector<Direction> ds;
bool below = y + 1 != m.height() && m(y+1,x).get_type() != TileType::GRASS;
bool above = y > 0 && m(y-1,x).get_type() != TileType::GRASS;
bool right = x + 1 != m.width() && m(y,x+1).get_type() != TileType::GRASS;
bool left = x > 0 && m(y,x-1).get_type() != TileType::GRASS;
if (below && e.get_direction() != Direction::UP) ds.push_back(Direction::DOWN);
if (above && e.get_direction() != Direction::DOWN) ds.push_back(Direction::UP);
if (right && e.get_direction() != Direction::LEFT) ds.push_back(Direction::RIGHT);
if (left && e.get_direction() != Direction::RIGHT) ds.push_back(Direction::LEFT);
if (e.must_turn()) {
auto pos = std::find(ds.begin(), ds.end(), e.get_direction());
if (pos != ds.end())
ds.erase(pos);
}
if (ds.size() == 0) {
e.turn_around();
} else {
e.set_direction(ds[rand() % ds.size()]);
}
}
static void inflict_damage(Enemy& e, const Map& m)
{
Player::hp -= e.power();
e.kill();
}
static void force_next_turn(Enemy& e, const Map& m)
{
e.force_next_turn();
}
Map::Map(const std::string& file_path):
tiles {},
spawns {},
home_coord {}
{
if (!sprites_loaded)
load_map_sprites();
std::ifstream in {file_path};
std::string line;
/* consume the top border */
std::getline(in, line);
for (int y = 0; std::getline(in, line); ++y) {
tiles.emplace_back();
int x = 0;
for (char c : line) {
switch (c) {
case '#':
continue;
case ' ':
tiles[y].emplace_back(grass.get(), should_not_happen, TileType::GRASS);
break;
case '=':
tiles[y].emplace_back(sand_h.get(), no_op, TileType::SAND);
break;
case '|':
tiles[y].emplace_back(sand_v.get(), no_op, TileType::SAND);
break;
case '^':
tiles[y].emplace_back(nullptr, turn_up, TileType::SAND);
break;
case 'v':
tiles[y].emplace_back(nullptr, turn_down, TileType::SAND);
break;
case '>':
tiles[y].emplace_back(nullptr, turn_right, TileType::SAND);
break;
case '<':
tiles[y].emplace_back(nullptr, turn_left, TileType::SAND);
break;
case '@':
tiles[y].emplace_back(spawn.get(), spawned, TileType::SPAWN);
spawns.push_back({ .x = x, .y = y });
break;
case '*':
tiles[y].emplace_back(home.get(), inflict_damage, TileType::HOME);
home_coord.x = x;
home_coord.y = y;
break;
case '%':
tiles[y].emplace_back(nullptr, turn_random, TileType::SAND);
break;
case '!':
tiles[y].emplace_back(nullptr, force_next_turn, TileType::SAND);
break;
}
++x;
}
}
/* remove the last vector, because it is empty (bottom border) and will result
* in Map::height() returning the wrong value
*/
tiles.erase(tiles.end() - 1);
/* insert sprites for all of the corners / intersections */
for (unsigned int y = 0; y < tiles.size(); ++y) {
for (unsigned int x = 0; x < tiles[y].size(); ++x) {
if (tiles[y][x].get_sprite()) continue;
bool below = y + 1 != tiles.size() && tiles[y+1][x].get_type() != TileType::GRASS;
bool above = y > 0 && tiles[y-1][x].get_type() != TileType::GRASS;
bool right = x + 1 != tiles[y].size() && tiles[y][x+1].get_type() != TileType::GRASS;
bool left = x > 0 && tiles[y][x-1].get_type() != TileType::GRASS;
if (below) {
if (right) {
if (above) {
if (left) tiles[y][x].set_sprite(sand_4way.get());
else tiles[y][x].set_sprite(sand_3way_right.get());
} else if (left)
tiles[y][x].set_sprite(sand_3way_down.get());
else tiles[y][x].set_sprite(sand_corner_top_left.get());
} else if (above) {
if (left)
tiles[y][x].set_sprite(sand_3way_left.get());
else tiles[y][x].set_sprite(sand_v.get());
} else tiles[y][x].set_sprite(sand_corner_top_right.get());
} else {
if (right) {
if (left) {
if (above) {
tiles[y][x].set_sprite(sand_3way_up.get());
} else {
tiles[y][x].set_sprite(sand_h.get());
}
} else {
tiles[y][x].set_sprite(sand_corner_bottom_left.get());
}
} else {
tiles[y][x].set_sprite(sand_corner_bottom_right.get());
}
}
}
}
}
const Tile& Map::operator()(int x, int y) const
{
return tiles[x][y];
}
int Map::width() const
{
return tiles[1].size();
}
int Map::height() const
{
return tiles.size();
}
std::function<Enemy()> Map::make_enemy_spawner(const Sprite& sprite, int damage, int speed, int hp)
{
return [=](){
coord s = spawns[rand() % spawns.size()];
return Enemy(sprite, damage, s.x * Game::BLOCK_SIZE, s.y * Game::BLOCK_SIZE, speed, hp);
};
}
|
1f758ec13b113d03cf937d4d509155654ef2452c | ef0724e75f18e51327a0e19cc6718aa184077ca7 | /VASTTesting/AverageSpeed.h | 069dc373d52b367531a207199648bd4e5eb7b1fa | [] | no_license | SwiftSniper123/VAST-Test-Bed | 20dc9db5304e3ff1af3c6e09f6d7b361c3cc568a | 6ccca92dbb7fb77d87bff9a5cb4579b706d09120 | refs/heads/master | 2020-04-22T13:34:27.239527 | 2019-05-13T00:11:17 | 2019-05-13T00:11:17 | 170,413,732 | 4 | 2 | null | 2019-05-13T00:11:18 | 2019-02-13T00:37:32 | C++ | UTF-8 | C++ | false | false | 515 | h | AverageSpeed.h | #pragma once
#include "ScenarioMetric.h"
/*
calculates the average speed of the chosen vehicle
*/
class AverageSpeed : public ScenarioMetric
{
public:
//default constructor
AverageSpeed() : ScenarioMetric() {};
AverageSpeed(string name, dataMap metricData) : ScenarioMetric(name, metricData) { };
void calculate();
virtual string getName()
{
return "Average Speed";
};
VCType getVCType()
{
return VCType::ScenarioMetric;
}
private:
vector<Double*> sumAvgSpeed;
float countSpeedUpdates = 0;
};
|
3e43877d0acf6f53006f6905da9ac9b1c54ca09a | 196f4b54a03d431186058a0cbf3816f26dbb985f | /msjbcordero3-tenor.inc | 30bd32fc3be24f20bcd259e07a4b638dcb25cc12 | [] | no_license | cjsjb/corderodediosgflores | 43d7cef4c41eb04ee889288e58366d748127a011 | 7f63b1c373eca3a145ca4eaf262f52c69f84866d | refs/heads/master | 2022-11-04T13:01:08.808100 | 2022-10-14T02:15:35 | 2022-10-14T02:15:35 | 145,914,122 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,692 | inc | msjbcordero3-tenor.inc | \context Staff = "tenor" \with { \consists Ambitus_engraver } <<
\set Staff.instrumentName = "Tenor"
\set Staff.shortInstrumentName = "T."
\set Score.skipBars = ##t
\set Staff.printKeyCancellation = ##f
\new Voice \global
\new Voice \globalTempo
\context Voice = "voz-tenor" {
\override Voice.TextScript #'padding = #2.0
\override MultiMeasureRest #'expand-limit = 1
\clef "treble_8"
\key a \major
R1 |
r2 r4 r8 a |
a 8 e 4 cis 8 e 4 r8 e |
d' 8 d' cis' a d' 8. cis' d' 8 |
%% 5
cis' 8 a ~ a 2 r4 |
g 4 b 8 d' 4. r4 |
fis 4 a 8 d' 4 r8 cis' a |
b 4. ( cis' 8 ) cis' 2 |
r2 r4 r8 a |
%% 10
a 8 e 4 cis 8 e 4 r8 e |
d' 8 d' cis' a d' 8. cis' d' 8 |
cis' 8 a ~ a 2 r4 |
g 4 b 8 d' 4. r4 |
fis 4 a 8 d' 4 r8 cis' a |
%% 15
b 4. ( cis' 8 ) cis' 2 |
r2 r4 r8 a |
a 8 e 4 cis 8 e 4 r8 e |
d' 8 d' cis' a d' 8. cis' d' 8 |
cis' 8 a ~ a 2 r4 |
%% 20
g 8 g b d' 4. r4 |
fis 8 fis a d' 4. r4 |
f 4 ( a ) d' 2 |
r2 r4 cis' 8 ( a ) |
b 8 ( cis' ~ cis' 2. ) |
%% 25
R1*2 |
\bar "|."
} % Voice
\new Lyrics \lyricsto "voz-tenor" {
"Cor" -- "de" -- "ro" "de" "Dios,"
"que" "qui" -- "tas" "el" "pe" -- "ca" -- "do" "del" "mun" -- "do,"
"ten" "pie" -- "dad," "ten" "pie" -- "dad" "de" "no" -- "so" __ "tros."
"Cor" -- "de" -- "ro" "de" "Dios,"
"que" "qui" -- "tas" "el" "pe" -- "ca" -- "do" "del" "mun" -- "do,"
"ten" "pie" -- "dad," "ten" "pie" -- "dad" "de" "no" -- "so" __ "tros."
"Cor" -- "de" "ro" "de" "Dios,"
"que" "qui" -- "tas" "el" "pe" -- "ca" -- "do" "del" "mun" -- "do,"
"da" -- "nos" "la" "paz," "da" -- "nos" "la" "paz," "da" __ "nos" "la" __ "paz." __
} % Lyrics
>> % Staff
|
b5d057427af4e2d9d6bdfb548bb7c9da2d281773 | 352983bdd561c1578ec96abaaa791c39fbf6b3d5 | /HttpClient.cpp | d2052dacf731ad81e160aeb5e95c3009f415e22a | [] | no_license | jiafenggit/HttpClient | 56b6253b18aa662803bfa32eb48e1f42bfd2de5b | 7063a60772ed271e5b8a4ac41aebdc4906827c86 | refs/heads/master | 2020-04-29T07:17:48.667124 | 2018-12-26T01:52:42 | 2018-12-26T01:52:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,794 | cpp | HttpClient.cpp | #include "HttpClient.h"
#include <iostream>
using namespace std;
HttpClient::HttpClient(const std::string & host, int port)
:TcpClient(host, port), mHttpParser(HTTP_RESPONSE)
{
mConstHeaders["Accept"] = " */*";
mConstHeaders["Accept-Language"] = " zh-cn";
mConstHeaders["Host:"] = mHost;
}
HttpClient::~HttpClient()
{
}
bool HttpClient::SendRequest(const std::string & method, const std::string & path, std::map<std::string, std::string> headers, const std::string body)
{
const char *BLANK_SPACE = " ";
const char *NEW_LINE = "\r\n";
//请求行
std::string requestContent;
requestContent.append(method).append(BLANK_SPACE);
if (path.size() == 0 || path[0] != '/') {
requestContent.append("/");
}
requestContent.append(path);
requestContent.append(BLANK_SPACE).append("HTTP/1.1").append(NEW_LINE);
//请求头
for (auto it = mConstHeaders.begin(); it != mConstHeaders.end(); it++) {
if (headers.find(it->first) == headers.end()) {
requestContent.append(it->first).append(":").append(it->second).append(NEW_LINE);
}
}
for (auto it = headers.begin(); it != headers.end(); it++) {
if (headers.find(it->first) == headers.end()) {
requestContent.append(it->first).append(":").append(it->second).append(NEW_LINE);
}
}
//请求体长度
if (body.size() != 0) {
char c[64];
int length = snprintf(c, sizeof(c), "Content - Length: %d\r\n", (int)body.size());
requestContent.append(c);
}
//回车换行
requestContent.append(NEW_LINE);
//请求体
requestContent.append(body);
//发送请求
if (!Send(requestContent)) {
return false;
}
//读取结果
return ReadResponse();
}
bool HttpClient::GetHeader(std::string name, std::string & value)
{
return mHttpParser.GetHeader(name, value);
}
bool HttpClient::GetResponseBody(std::string & body)
{
body = mHttpParser.GetResponseBody();
return true;
}
bool HttpClient::ReadResponse()
{
mHttpParser.Reset();
std::string tmpBuffer;
int len;
while (Read(tmpBuffer,len)) {
int nCode = mHttpParser.Execute(tmpBuffer.c_str(), tmpBuffer.size());
if (nCode != 0) {
return false;
}
if (mHttpParser.IsReadComplete()) {
return true;
}
}
//没有 ContentLen 会返回ULLONG_MAX
if(mHttpParser.content_length == 0 || mHttpParser.content_length== ULLONG_MAX){
return true;
}
return false;
}
bool HttpClient::SendGet(const std::string & path)
{
static const std::map<std::string, std::string> myMap;
return SendRequest("GET", path, myMap, "");
}
bool HttpClient::SendPost(const std::string & path, const std::string& body)
{
static const std::map<std::string, std::string> myMap;
return SendRequest("POST", path, myMap, body);
}
|
19444db448814a6492c7343d661c6228597ee000 | 1085b5158035f5e32701a788b2727a17f95fd8b7 | /driver.h | 1549ebeeb38ce3dd81af022db3365239b7a61d56 | [] | no_license | SatwaniGovind/CPP-First-Project | cbdcd4e7758031f244332759a3f3c1f8d3931cf0 | baad78c3589fe740e902c8ebe6199c825015fa96 | refs/heads/main | 2023-04-25T19:10:04.182595 | 2021-05-27T07:45:46 | 2021-05-27T07:45:46 | 371,288,132 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 350 | h | driver.h | class student
{
protected:
char name[20];
int usn=0;
public:
void getdetail(void)
{
cout<<"\n\nEnter name :- ";
cin>>name;
cout<<"\nEnter usn :- ";
cin>>usn;
}
void dispdetail(void)
{
cout<<"\n\nNAME :- "<<name;
cout<<"\nUSN :- "<<usn;
}
}; |
ef07927b3c85304d9e99183c70c8564c68caf65f | 050c8a810d34fe125aecae582f9adfd0625356c6 | /B. Arpa and a list of numbers/main.cpp | 3473235f3dc8fe0c65300c76560fa5e5f8619251 | [] | no_license | georgerapeanu/c-sources | adff7a268121ae8c314e846726267109ba1c62e6 | af95d3ce726325dcd18b3d94fe99969006b8e138 | refs/heads/master | 2022-12-24T22:57:39.526205 | 2022-12-21T16:05:01 | 2022-12-21T16:05:01 | 144,864,608 | 11 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 933 | cpp | main.cpp | #include <iostream>
using namespace std;
long long sum[2000005];
int cnt[2000005];
int N,a,x,y;
long long cost;
int main()
{
cin.sync_with_stdio(false);
cout.sync_with_stdio(false);
cin>>N>>x>>y;
for(int i=1;i<=N;i++)
{
cin>>a;
sum[a]+=a;
cnt[a]++;
}
for(int i=1;i<=2000000;i++)
{
sum[i]+=sum[i-1];
cnt[i]+=cnt[i-1];
}
cost=1LL<<60;
for(int i=2;i<=2000000;i++)
{
long long a=0,b=0;
for(int j=i;j<=2000000;j+=i)
{
if(i-1<=x/y)
{
b+=1LL*(cnt[j]-cnt[j-i])*j-(sum[j]-sum[j-i]);
}
else
{
a+=cnt[j-x/y-1]-cnt[j-i];
b+=1LL*(cnt[j]-cnt[j-x/y-1])*j-(sum[j]-sum[j-x/y-1]);
}
}
// if(i==17)cout<<a<<" "<<b<<"\n\n\n\n";
cost=min(cost,1LL*a*x+1LL*b*y);
}
cout<<cost;
return 0;
}
|
3c7b36d4685c7eb2490e5d3999dd8a69c307cbbe | 523a47422b873e90f536034f22853a6380849e50 | /include/graph_generator.h | f5150d7f410be12a4f9cee8e6a4e4d804243688b | [] | no_license | FrankieBetanco/trust_graphs | 1e3592b63381ad05a829a1eb2e887550004bd9d0 | b6252b292e75b5c45cd0307ea827d06bcf68f934 | refs/heads/master | 2020-09-15T15:57:31.106212 | 2019-12-02T18:13:45 | 2019-12-02T18:13:45 | 223,496,095 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,524 | h | graph_generator.h | #include <vector>
#include <string>
#include <utility>
#include <limits>
class user {
public:
std::vector <std::string> attributes;
int predecessor;
double distance;
int discovery_time;
int finishing_time;
int discovered;
int node_num;
int printed;
user() {
predecessor = -1;
distance = std::numeric_limits <double>::max();
discovery_time = -1;
finishing_time = -1;
discovered = 0;
printed = 0;
}
};
class group {
public:
std::vector <int> members;
std::string group_name;
unsigned short permissions;
};
class graph {
public:
std::vector <user *> users;
std::vector <group *> groups;
std::vector <std::vector <unsigned short> > adj_privacy;
std::vector <std::vector <unsigned short> > adj_anonymity;
std::string filename;
graph(std::string filename);
void node_view(int from, int to);
void node_view_all(int from);
void add_privacy_edge(int attribute_num, int from, int to);
void remove_privacy_edge(int attribute_num, int from, int to);
void add_anonymity_edge(int attribute_num, int from, int to);
int node_out_of_range(int from, int to);
void remove_anonymity_edge(int attribute_num, int from, int to);
void print_binary_graph(int attribute_num, std::vector<std::vector <unsigned short > > &adj);
void print_privacy_graph(int attribute_num);
void print_anonymity_graph(int attribute_num);
void print_groups();
void print_group_membership_graph();
private:
void parse_input();
void construct_graph();
};
|
d84e34092d5224254c4cb53faa02b50eba545253 | 57cd401937e6e6fe2b6d37d9a5fa6ce9c3bc2d03 | /Controller/Door.cpp | 451be92b77ad7c681931a9587da2db9a81aeceb2 | [] | no_license | Sauloferraz/The-Rising-of-the-Guitar-Hero | da15339eb42b67a2e40ed93921e39ba8d6230226 | 869d3bccf44a48f109358a87648969489ff87b39 | refs/heads/master | 2020-06-23T05:17:44.771563 | 2019-09-19T23:00:21 | 2019-09-19T23:00:21 | 198,527,020 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 367 | cpp | Door.cpp | #include "Door.h"
#include "MainGame.h"
Door::Door(float x, float y, float sizeX, float sizeY) {
bbox = new Rect(-sizeX / 2, -sizeY / 2, sizeX / 2, sizeY / 2);
type = DOOR;
MoveTo(x, y);
}
Door::~Door() {
delete bbox;
}
void Door::Update() {
WorldMoving();
}
void Door::Draw() {}
void Door::WorldMoving() {
Translate(MainGame::VelX(), MainGame::VelY());
}
|
b9d8ef1cdf729fa120bc872e67e24c93985227b0 | c67a90d8aba17b6740da7b0112c06eb73e359300 | /src/dioptre/graphics/opengl/triangle_geometry.cpp | dff96b7254b2e12881c4ad9659bbedcbb1aa90d8 | [
"MIT"
] | permissive | tobscher/rts | ec717c536f0ae2fcec7a962e7f8e63088863a42d | 7f30faf6a13d309e4db828be8be3c05d28c05364 | refs/heads/master | 2016-09-06T17:16:37.615725 | 2015-10-03T11:25:35 | 2015-10-03T11:25:35 | 32,095,728 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,330 | cpp | triangle_geometry.cpp | #include "dioptre/graphics/opengl/triangle_geometry.h"
#include "dioptre/graphics/opengl.h"
namespace dioptre {
namespace graphics {
namespace opengl {
TriangleGeometry::TriangleGeometry(glm::vec3 a, glm::vec3 b, glm::vec3 c) :
dioptre::graphics::TriangleGeometry(a, b, c) {
}
void TriangleGeometry::initialize() {
// Initialize geometry
glGenBuffers(1, &vertexBuffer_);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer_);
auto bufferData = getData();
// Give our vertices to OpenGL.
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * bufferData.size(), &bufferData[0], GL_STATIC_DRAW);
}
void TriangleGeometry::update() {
auto data = getData();
// 1st attribute buffer : vertices
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer_);
glVertexAttribPointer(
0, // attribute 0. No particular reason for 0, but must match the layout in the shader.
data.size(), // size
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void*)0 // array buffer offset
);
// Draw the triangle !
glDrawArrays(GL_TRIANGLES, 0, data.size());
glDisableVertexAttribArray(0);
}
void TriangleGeometry::destroy() {
glDeleteBuffers(1, &vertexBuffer_);
}
} // opengl
} // graphics
} // dioptre
|
b7714b806e6b039df121584007a40fc4cdf29092 | 98491270427ab146d8055c63389d2d14c5a7c1b9 | /baanLib/IRegelaarInstellingenDialoog.h | fb4f9b1593a0e922a46c6fb444b717dd03a487a9 | [] | no_license | Zoev89/baan | 5a417463d318404ad7d9f98e30c95539eecb30fe | 0410aaac2d3d4b139100d78579d1c7d8a4ea446c | refs/heads/master | 2021-06-14T19:29:13.398485 | 2021-02-27T16:16:59 | 2021-02-27T16:16:59 | 52,728,071 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,644 | h | IRegelaarInstellingenDialoog.h | #ifndef IREGELAARINSTELLINGENDIALOG_H
#define IREGELAARINSTELLINGENDIALOG_H
#include <string>
class IRegelaarInstellingenDialoog
{
public:
virtual bool RunDialogOk() = 0; // returns true when ok is pressed
virtual void SetLaatsteWagonCheck(bool laatsteWagon) = 0;
virtual bool GetLaatsteWagonCheck() = 0;
virtual void SetEloc(bool eloc) = 0;
virtual bool GetEloc() = 0;
virtual void SetMinSnelheid(int snelheid) = 0;
virtual int GetMinSnelheid() = 0;
virtual void SetMaxSnelheid(int snelheid) = 0;
virtual int GetMaxSnelheid() = 0;
virtual void SetTopSnelheid(int snelheid) = 0;
virtual int GetTopSnelheid() = 0;
virtual void SetTotaalAfstand(int afstand) = 0; // in m
virtual int GetTotaalAfstand() = 0;
virtual void SetTotaalTijd(const std::string& tijd) = 0; // hh:mm
virtual std::string GetTotaalTijd() = 0;
virtual void SetLengte(int lengte) = 0; // in cm
virtual int GetLengte() = 0;
virtual void SetAlphaUitleg(const std::string &uitleg) = 0;
virtual void SetAlphaRijden(float alpha) = 0;
virtual float GetAlphaRijden() = 0;
virtual void SetClipUitleg(const std::string &uitleg) = 0;
virtual void SetClipRijden(int clip) = 0;
virtual int GetClipRijden() = 0;
virtual void SetAlphaStoppen(float alpha) = 0;
virtual float GetAlphaStoppen() = 0;
virtual void SetClipStoppen(int clip) = 0;
virtual int GetClipStoppen() = 0;
virtual void SetStandUitleg(const std::string &uitleg) = 0;
virtual void SetStand1(int snelheid) = 0;
virtual int GetStand1() = 0;
virtual void SetAfstand1(int afstand) = 0; // in cm
virtual int GetAfstand1() = 0;
virtual void SetStand2(int snelheid) = 0;
virtual int GetStand2() = 0;
virtual void SetAfstand2(int afstand) = 0; // in cm
virtual int GetAfstand2() = 0;
virtual void SetErrors(const std::string& errorString) = 0;
virtual std::string GetErrors() = 0;
virtual void SetKlpfUitleg(const std::string &uitleg) = 0;
virtual void SetKLpf(float k) = 0;
virtual float GetKLpf() = 0;
virtual void SetPlusMinusUitleg(const std::string &uitleg) = 0;
virtual void SetPlusMinus(float plusMinus) = 0;
virtual float GetPlusMinus() = 0;
virtual void SetHellingUitleg(const std::string &uitleg) = 0;
virtual void SetHelling(float helling) = 0;
virtual float GetHelling() = 0;
virtual void SetDodeTijdUitleg(const std::string &uitleg) = 0;
virtual void SetDodeTijd(float dodeTijd) = 0;
virtual float GetDodeTijd() = 0;
virtual void SetProgrammaNaam(const std::string& naam) = 0;
virtual std::string GetProgrammaNaam() = 0;
virtual void SetHerlaadProgramma(bool herlaad) = 0;
virtual bool GetHerlaadProgramma() = 0;
virtual void SetLangzaamRijdenUitleg(const std::string &uitleg) = 0;
virtual void SetLangzaam(int snelheid) = 0;
virtual int GetLangzaam() = 0;
virtual void SetRijden(int snelheid) = 0;
virtual int GetRijden() = 0;
virtual void SetLocType(const std::string& locType) = 0;
virtual std::string GetLocType() = 0;
virtual void SetLastStand1(int stand) = 0;
virtual int GetLastStand1() = 0;
virtual void SetLastGain1(float gain) = 0;
virtual float GetLastGain1() = 0;
virtual void SetLastStand2(int stand) = 0;
virtual int GetLastStand2() = 0;
virtual void SetLastGain2(float gain) = 0;
virtual float GetLastGain2() = 0;
virtual void SetLastRegelKeuze(int keuzeIndex) = 0;
virtual int GetLastRegelKeuze() = 0;
};
#endif // IREGELAARINSTELLINGDIALOG_H
|
dc03a5d6e08dd6ad5bd1b645eb6348dfc7746920 | 9858d41a366733cbe3047c122e1a71635f71bf99 | /temp_final.cpp | 96a6028203d7d5ae5eb1a3157cbf2d12e1f15b34 | [] | no_license | InabaTang/MECQ | 780350632169fdb4eba2bb593123b0efc52d8b5c | 44a461e9efdd65b1f7e4a6a0873df5db7c11775d | refs/heads/main | 2023-09-02T15:58:12.554149 | 2021-10-28T12:43:07 | 2021-10-28T12:43:07 | 370,550,140 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,074 | cpp | temp_final.cpp | #pragma GCC optimize(2)
/*#include<map>
#include<unordered_map>
#include<set>
#include<unordered_set>
#include<cmath>
#include<queue>
#include<cstdio>
#include<vector>
#include<climits>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#include<ctime>
#include <sys/io.h>
#include<stack>
#include<sstream>*/
#include<bits/stdc++.h>
//#define open_file_name "test/p_hat1000-1.clq"
//#define open_file_name "test/brock200_2.clq"
using namespace std;
int cnt = 0;
const int maxn = 1e5 + 50;
int n , m;
vector<int>fin_ans;
long long C_initial = 0;
long long C_max = 0;
int cnt_edge = 0;
vector<int>V;
long long C_stop = 5436;
long long total_w_assigned[maxn];
long long first_total_w_assigned[maxn];
long long max_upper[maxn];
struct input_edge
{
int v1;
int v2;
long long weight;
};
vector<input_edge> input_edge_cache; //from 1~n
vector<int> vertex_adject[maxn];
long long max_upper_num = 0;
unordered_map<unsigned long long , int>id_input_edge;
inline void init()
{
V.clear();
input_edge_cache.clear();
input_edge ep;
ep.v1 = -1; ep.v2 = -1; ep.weight = -1;
input_edge_cache.push_back(ep);
}
unsigned long long encode_pairID(unsigned long long v1 , unsigned long long v2)
{
unsigned long long n1 , n2;
unsigned long long pairID;
if (v1 < v2)
{
n1 = v1; n2 = v2;
}
else
{
n1 = v2; n2 = v1;
}
pairID = ( (n1 + n2 + 1) * (n1 + n2) >> 1) + n2;
return pairID;
}
inline void add(int &x , int &y , long long &c)
{
cnt_edge ++;
input_edge temp;
temp.v1 = x;
temp.v2 = y;
temp.weight = c;
unsigned long long temp_id = encode_pairID(x , y);
id_input_edge[temp_id] = cnt_edge;
input_edge_cache.push_back(temp);
/*vertex_degree[x].push_back(cnt_edge);
vertex_degree[y].push_back(cnt_edge);*/
vertex_adject[x].push_back(y);
vertex_adject[y].push_back(x);
max_upper[x] += c;
max_upper[y] += c;
}
/*void pri(set<int>W)
{
for (auto it : W)
{
cout<<it<<' ';
}
cout<<endl;
}*/
long long get_val(int &u , int &v)
{
unsigned long long temp_id = encode_pairID(u , v);
int tem = id_input_edge[temp_id];
if (tem != 0) return input_edge_cache[tem].weight;
else return 0;
}
long long vertex_upper_bound[maxn];
stack<int>vertex_sequence;
struct Node
{
int id;
int val;
bool operator < (const Node &a) const
{
//if (val == a.val) return max_upper[id] < max_upper[a.id];
return val > a.val;
}
};
int flag_X[maxn];
long long res_sum[maxn];
inline void CALC_SEQ_AND_UB(vector<int>&vertex_C , vector<int>&vertex_S)
{
while(!vertex_sequence.empty()) vertex_sequence.pop();
/*for (auto v : vertex_S)
{
long long sum = 0;
for (auto u : vertex_C)
{
unsigned long long temp_id = encode_pairID(u , v);
int tem = id_input_edge[temp_id];
if (tem != 0)
{
sum += input_edge_cache[tem].weight;
}
}
total_w_assigned[v] = sum;
}*/
for (auto v : vertex_S)
{
total_w_assigned[v] = first_total_w_assigned[v];
res_sum[v] = 0;
}
unordered_set<int>vertex_T;
vertex_T.clear();
priority_queue<Node>vertex_X;
long long max_adject_weight = 0;
for (auto it : vertex_S)
{
vertex_T.insert(it);
}
int k = 0;
long long res = 0 , sum = 0;
int temp_cnt = 0;
while(vertex_T.size() != 0)
{
for (auto it : vertex_S)
{
flag_X[it] = 0;
}
temp_cnt ++;
k ++;
vector<int>independent_set;
independent_set.clear();
while(!vertex_X.empty()) vertex_X.pop();
for (auto it : vertex_T)
{
Node temp;
temp.id = it;
temp.val = total_w_assigned[it];
vertex_X.push(temp);
}
res = 0;
while(!vertex_X.empty())
{
Node temp = vertex_X.top();
vertex_X.pop();
int v = temp.id;
if (flag_X[v])
{
continue;
}
independent_set.push_back(v);
vertex_sequence.push(v);
vertex_upper_bound[v] = total_w_assigned[v] + res_sum[v];
//cout<<"cnt = "<<cnt<<' '<<"temp_cnt = "<<temp_cnt<<' '<<"v = "<<v<<' '<<"upper = "<<vertex_upper_bound[v]<<endl;
/*priority_queue<Node>temp_X;
while(!temp_X.empty()) temp_X.pop();
while(!vertex_X.empty())
{
temp = vertex_X.top();
vertex_X.pop();
unsigned long long temp_id = encode_pairID(temp.id , v);
int tem = id_input_edge[temp_id];
if (tem == 0)
{
temp_X.push(temp);
}
}
vertex_X = temp_X;*/
flag_X[v] = 1;
for (auto it : vertex_adject[v])
{
flag_X[it] = 1;
}
vertex_T.erase(v);
}
sum += res;
for (auto v : vertex_T)
{
max_adject_weight = 0;
for (int i = independent_set.size() - 1 ; i >= 0 ; i --)
{
long long res_k = get_val(independent_set[i] , v);
if (res_k != 0)
{
res_sum[v] += total_w_assigned[independent_set[i]];
break;
}
}
for (int i = independent_set.size() - 1 ; i >= 0 ; i --)
{
long long res_k = get_val(independent_set[i] , v);
max_adject_weight = max(max_adject_weight , res_k);
}
total_w_assigned[v] = total_w_assigned[v] + max_adject_weight;
}
}
return ;
}
int vector_func[maxn];
vector<int> vector_differ(vector<int>A , vector<int>B)
{
vector<int>ans;
memset(vector_func , 0 , sizeof(vector_func));
for (auto it : B)
{
vector_func[it] = 1;
}
for (auto it : A)
{
if (vector_func[it] != 1)
{
ans.push_back(it);
}
}
return ans;
}
vector<int> vector_inter(vector<int>A , vector<int>B)
{
vector<int>ans;
memset(vector_func , 0 , sizeof(vector_func));
for (auto it : B)
{
vector_func[it] = 1;
}
for (auto it : A)
{
if (vector_func[it] == 1)
{
ans.push_back(it);
}
}
return ans;
}
void pri(vector<int> C , vector<int> T)
{
cout<<"-----------------------------"<<endl;
cout<<"cnt = "<<cnt<<endl;
/*cout<<"T = "<<endl;
for (auto it : T)
{
cout<<it<<' ';
}
cout<<endl;
cout<<"C = "<<endl;
for (auto it : C)
{
cout<<it<<' ';
}
cout<<endl;*/
cout<<"-----------------------------"<<endl;
}
inline void Expand(vector<int> vertex_C , vector<int> vertex_S , long long C_cal)
{
//pri(vertex_C , vertex_S);
if (vertex_S.size() == 0)
{
if (C_cal > C_max)
{
fin_ans = vertex_C;
C_max = C_cal;
if (C_max == C_stop)
{
return ;
}
}
return ;
}
cnt ++;
CALC_SEQ_AND_UB(vertex_C , vertex_S);
vector<int>vertex_vis;
vertex_vis.clear();
stack<int>copy_vertex_sequence;
while(!copy_vertex_sequence.empty()) copy_vertex_sequence.pop();
copy_vertex_sequence = vertex_sequence;
unordered_map<int,int> copy_vertex_upper_bound;
copy_vertex_upper_bound.clear();
for (int i = 0 ; i < vertex_S.size() ; i ++)
{
copy_vertex_upper_bound[vertex_S[i]] = vertex_upper_bound[vertex_S[i]];
}
while(!copy_vertex_sequence.empty())
{
int p = copy_vertex_sequence.top();
copy_vertex_sequence.pop();
//cout<<"p = "<<p<<' '<<"up_p = "<<vertex_upper_bound[p]<<endl;
if (C_cal + copy_vertex_upper_bound[p] > C_max)
{
vector<int>S_temp;
S_temp.clear();
vertex_C.push_back(p);
vector<int>::iterator it = vertex_S.begin();
while(it != vertex_S.end())
{
if (*it == p)
{
it = vertex_S.erase(it);
}
else
{
if (get_val(*it , p))
{
S_temp.push_back(*it);
}
it ++;
}
}
long long add_sum = 0;
for (auto it : vertex_C)
{
add_sum += get_val(it , p);
}
for (auto u : S_temp)
{
first_total_w_assigned[u] += get_val(u , p);
}
Expand(vertex_C , S_temp , C_cal + add_sum);
vertex_C.pop_back();
for (auto u : S_temp)
{
first_total_w_assigned[u] -= get_val(u , p);
}
}
}
}
string input_filename;
inline long long MECQ()
{
memset(first_total_w_assigned , 0 , sizeof(first_total_w_assigned));
C_max = C_initial;
vector<int>init;
init.clear();
Expand(init , V , 0);
return C_max;
}
int x , y;
void read()
{
string line;
string p, tmp;
string e;
istringstream is;
int cnt = 0;
do
{
cnt ++;
getline(cin, line);
is.clear();
is.str(line);
is >> p >> tmp >> n >> m;
}
while (p != "p");
for (int i = 1 ; i <= n ; i ++)
{
V.push_back(i);
}
for (int i = 1 ; i <= m ; i ++)
{
getline(cin, line);
is.clear();
is.str(line);
is >> e >> x >> y;
long long c = (x + y) % 200 + 1;
//long long c = 1;
add(x , y , c);
}
return ;
}
char file_name[maxn];
int main(int argc, char *argv[])
{
scanf("%s",file_name);
fin_ans.clear();
freopen(file_name , "r" , stdin);
ios::sync_with_stdio(false);
cout<<"The file_name is: "<<file_name<<endl;
double time=0;
double counts=0;
clock_t startTime,endTime;
startTime = clock();
init();
read();
MECQ();
endTime = clock();
time = (double)(endTime - startTime) / CLOCKS_PER_SEC;
cout<<C_max<<endl;
cout<<"Time is: "<<time<<"s"<<endl;
/*cout<<"fin_ans_num = "<<fin_ans.size()<<endl;
sort(fin_ans.begin() , fin_ans.end());
for (int i = 0 ; i < fin_ans.size() ; i ++)
{
cout<<fin_ans[i]<<endl;
}*/
system("pause");
}
|
02320a1bfabfa996f4ae7ce64ca3ccace0b45efa | 3b1d5f51e52a510210bf23505f16c282c70e0973 | /src/hal/STM32F1/adc/adc.cpp | 7bb206148a020b7d7cdd8b8fa0fe65c2d015a8f9 | [
"MIT"
] | permissive | ghsecuritylab/omef | 44abbbe83cd538f132f7ac4f414dd5ee0b6576a8 | a6b2dec8d57545c3804174883e582080ef6f3af9 | refs/heads/master | 2021-02-28T18:22:16.331910 | 2020-02-23T18:41:52 | 2020-02-23T18:41:52 | 245,722,107 | 0 | 0 | MIT | 2020-03-07T23:39:51 | 2020-03-07T23:39:50 | null | UTF-8 | C++ | false | false | 6,676 | cpp | adc.cpp | #include <string.h>
#include <stdlib.h>
#include "common/assert.h"
#include "adc.hpp"
#include "rcc/rcc.hpp"
#include "CMSIS/Device/STM32F1xx/Include/stm32f1xx.h"
using namespace hal;
#define MAX_TIM_RESOL 0xFFFF
#define V_REF (float)3.3
static TIM_TypeDef *const tim_list[adc::ADC_TIM_END] =
{
#if defined(STM32F100xB) || defined(STM32F100xE) || defined(STM32F103x6) || \
defined(STM32F103xB) || defined(STM32F103xE) || defined(STM32F103xG) || \
defined(STM32F105xC) || defined(STM32F107xC)
TIM1,
#else
NULL,
#endif
TIM2, TIM3,
#if defined(STM32F100xB) || defined(STM32F100xE) || defined(STM32F101xB) || \
defined(STM32F101xE) || defined(STM32F101xG) || defined(STM32F102xB) || \
defined(STM32F103xB) || defined(STM32F103xE) || defined(STM32F103xG) || \
defined(STM32F105xC) || defined(STM32F107xC)
TIM4,
#else
NULL,
#endif
};
static uint32_t const rcc_list[adc::ADC_TIM_END] =
{
RCC_APB2ENR_TIM1EN, RCC_APB1ENR_TIM2EN, RCC_APB1ENR_TIM3EN,
#if defined(STM32F100xB) || defined(STM32F100xE) || defined(STM32F101xB) || \
defined(STM32F101xE) || defined(STM32F101xG) || defined(STM32F102xB) || \
defined(STM32F103xB) || defined(STM32F103xE) || defined(STM32F103xG) || \
defined(STM32F105xC) || defined(STM32F107xC)
RCC_APB1ENR_TIM4EN,
#else
0,
#endif
};
static volatile uint32_t *const rcc_bus_list[adc::ADC_TIM_END] =
{
&RCC->APB2ENR, &RCC->APB1ENR, &RCC->APB1ENR, &RCC->APB1ENR
};
static rcc_src_t const rcc_src_list[adc::ADC_TIM_END] =
{
RCC_SRC_APB2, RCC_SRC_APB1, RCC_SRC_APB1, RCC_SRC_APB1
};
static void tim_init(adc::adc_tim_t tim, uint32_t freq);
static void calc_clk(adc::adc_tim_t tim, uint32_t freq, uint16_t &presc,
uint16_t &reload);
adc::adc(adc_t adc, adc_ch_t ch_list[], size_t ch_list_size, adc_tim_t tim,
hal::dma &dma, adc_resol_t resol, uint32_t freq, uint8_t num_of_samples):
_adc(adc),
_ch_list((adc_ch_t *)malloc(sizeof(adc_ch_t) * ch_list_size)),
_ch_list_size(ch_list_size),
_tim(tim),
_dma(dma),
_resol(resol),
_freq(freq),
_dma_buff((uint16_t *)malloc(sizeof(uint16_t) * ch_list_size * num_of_samples)),
_num_of_samples(num_of_samples)
{
ASSERT(_adc < ADC_END);
ASSERT(_ch_list);
ASSERT(_ch_list_size > 0);
ASSERT(_tim < ADC_TIM_END);
ASSERT(_resol < ADC_RESOL_END);
// STM32F100x supports only 12 bit resolution
ASSERT(_resol == ADC_RESOL_12BIT);
ASSERT(_freq > 0);
ASSERT(_dma.dir() == dma::DIR_PERIPH_TO_MEM);
ASSERT(_dma.inc_size() == dma::INC_SIZE_16);
ASSERT(_dma_buff);
ASSERT(_num_of_samples > 0);
memcpy(_ch_list, ch_list, sizeof(adc_ch_t) * ch_list_size);
memset(_clbks, 0, sizeof(_clbks));
RCC->APB2ENR |= RCC_APB2ENR_ADC1EN;
RCC->APB2RSTR |= RCC_APB2RSTR_ADC1RST;
RCC->APB2RSTR &= ~RCC_APB2RSTR_ADC1RST;
RCC->CFGR |= RCC_CFGR_ADCPRE_1;
// Calibrate ADC
//ADC1->CR2 |= ADC_CR2_CAL;
//while(ADC1->CR2 & ADC_CR2_CAL);
// Align results to the right
ADC1->CR2 &= ~ADC_CR2_ALIGN;
// Setup external trigger
ADC1->CR2 &= ~ADC_CR2_EXTSEL;
switch(_tim)
{
// CC1, CC2, CC3 events
case ADC_TIM_1: break;
// CC2 event
case ADC_TIM_2: ADC1->CR2 |= ADC_CR2_EXTSEL_1 | ADC_CR2_EXTSEL_0; break;
// TRGO event
case ADC_TIM_3: ADC1->CR2 |= ADC_CR2_EXTSEL_2; break;
// CC4 event
case ADC_TIM_4: ADC1->CR2 |= ADC_CR2_EXTSEL_2 | ADC_CR2_EXTSEL_0; break;
default: ASSERT(0);
}
// Enable conversation by external trigger
ADC1->CR2 |= ADC_CR2_EXTTRIG;
for(uint8_t i = 0; i < _ch_list_size; i++)
init_regular_chnls(i, _ch_list[i]);
// Enable DMA support and enable ADC
ADC1->CR2 |= ADC_CR2_DMA | ADC_CR2_ADON;
_dma.src((uint16_t *)&ADC1->DR);
_dma.dst(_dma_buff);
_dma.size(_ch_list_size * _num_of_samples);
_dma.start_cyclic(on_dma, this);
tim_init(_tim, _freq);
}
adc::~adc()
{
enable(false);
if(_dma_buff)
{
free(_dma_buff);
_dma_buff = NULL;
}
}
void adc::resol(adc_resol_t resol)
{
// STM32F100x supports only 12 bit resolution
ASSERT(resol == ADC_RESOL_12BIT);
}
void adc::freq(uint32_t freq)
{
}
void adc::add_clbk(adc_ch_t ch, adc_cb_t clbk, void *ctx)
{
ASSERT(ch < ADC_CH_END);
// Check that requested channel was initialized in constructor
uint8_t ch_idx = 0;
for(; ch_idx < _ch_list_size; ch_idx++)
{
if(ch == _ch_list[ch_idx])
break;
}
ASSERT(ch_idx < _ch_list_size); // Requested channel wasn't found
_clbks[ch] = {.clbk = clbk, .ctx = ctx};
}
void adc::enable(bool enable)
{
if(enable)
{
tim_list[_tim]->CNT = 0;
tim_list[_tim]->CR1 |= TIM_CR1_CEN;
}
else
{
tim_list[_tim]->CR1 &= ~TIM_CR1_CEN;
tim_list[_tim]->CNT = 0;
}
}
void adc::init_regular_chnls(uint8_t index, adc_ch_t ch)
{
// 0..5
if(index <= 5)
{
ADC1->SQR3 &= ~(ADC_SQR3_SQ1 << (index * 5));
ADC1->SQR3 |= ch << (index * 5);
}
// 6..11
else if(index <= 11)
{
index -= 6;
ADC1->SQR2 &= ~(ADC_SQR2_SQ7 << (index * 5));
ADC1->SQR2 |= ch << (index * 5);
}
// 12..15
else
{
index -= 12;
ADC1->SQR1 &= ~(ADC_SQR1_SQ13 << (index * 5));
ADC1->SQR1 |= ch << (index * 5);
}
}
void adc::on_dma(dma *dma, dma::event_t event, void *ctx)
{
if(event != dma::EVENT_CMPLT)
return;
adc *obj = static_cast<adc *>(ctx);
// Go through all initialized ADC channels
for(uint8_t i = 0; i < obj->_ch_list_size; i++)
{
if(!obj->_clbks[obj->_ch_list[i]].clbk)
continue;
// Calculate voltage value for specific ADC channel
float voltage = 0;
for(uint16_t j = i; j < (obj->_ch_list_size * obj->_num_of_samples);
j += obj->_ch_list_size)
{
voltage += obj->_dma_buff[j];
}
voltage /= obj->_num_of_samples;
voltage = (voltage / 4095) * V_REF;
obj->_clbks[obj->_ch_list[i]].clbk(obj, obj->_ch_list[i], voltage,
obj->_clbks[obj->_ch_list[i]].ctx);
}
}
static void tim_init(adc::adc_tim_t tim, uint32_t freq)
{
uint16_t presc = 0;
uint16_t reload = 0;
calc_clk(tim, freq, presc, reload);
*rcc_bus_list[tim] |= rcc_list[tim];
tim_list[tim]->PSC = presc;
tim_list[tim]->ARR = reload;
// Enable generation of TRGO event
tim_list[tim]->CR2 &= ~TIM_CR2_MMS;
tim_list[tim]->CR2 |= TIM_CR2_MMS_1;
}
static void calc_clk(adc::adc_tim_t tim, uint32_t freq, uint16_t &presc,
uint16_t &reload)
{
uint32_t clk_freq = rcc_get_freq(rcc_src_list[tim]);
/* If APBx prescaller no equal to 1, TIMx prescaller multiplies by 2 */
if(clk_freq != rcc_get_freq(RCC_SRC_AHB))
clk_freq *= 2;
uint32_t tmp_presc = 0;
uint32_t tmp_reload = clk_freq / freq;
if(tmp_reload <= MAX_TIM_RESOL)
tmp_presc = 1;
else
{
tmp_presc = ((tmp_reload + (MAX_TIM_RESOL / 2)) / MAX_TIM_RESOL) + 1;
tmp_reload /= tmp_presc;
}
ASSERT(tmp_presc <= MAX_TIM_RESOL);
ASSERT(tmp_reload <= MAX_TIM_RESOL);
presc = (uint16_t)(tmp_presc - 1);
reload = (uint16_t)(tmp_reload - 1);
}
|
ce33b4ae4951d24a3aaf1fcc9834e04c4cf71c0f | 799ba0cfcba13627c064ad2cccbb11c6a438737b | /include/RED4ext/GameEngine.hpp | 2d2dadd2117a9deb9a9f87095b5cbbca998c7ecb | [
"MIT"
] | permissive | MasterScott/RED4ext.SDK | 4a7a35c1dccd9ba223656a6a185726b59d448566 | 220844583ff7276f9720c76b3e1ef3d1ba27484e | refs/heads/master | 2023-02-17T07:08:28.741334 | 2021-01-14T23:19:23 | 2021-01-14T23:19:23 | 329,925,466 | 0 | 0 | MIT | 2021-01-15T13:52:45 | 2021-01-15T13:52:33 | null | UTF-8 | C++ | false | false | 2,553 | hpp | GameEngine.hpp | #pragma once
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/ISerializable.hpp>
#include <RED4ext/RTTITypes.hpp>
namespace RED4ext
{
struct CBaseEngine
{
// https://github.com/yamashi/RED4ext/commit/2d30f32826276458f86da8b4c26940924044564d
struct UnkC0
{
uint8_t pad0[0x140];
uint32_t unk140;
uint8_t pad144[0x164 - 0x144];
uint32_t unk164;
void* hWnd;
uint8_t pad170[0x9];
uint8_t isClipped;
};
virtual void sub_0() = 0;
virtual void sub_8() = 0;
virtual void sub_10() = 0;
virtual ~CBaseEngine() = 0;
virtual void sub_18() = 0;
virtual void sub_28() = 0;
virtual void sub_30() = 0;
virtual void sub_38() = 0;
virtual void sub_40() = 0;
virtual void sub_48() = 0;
virtual void sub_50() = 0;
virtual void sub_58() = 0;
virtual void sub_60() = 0;
virtual void sub_68() = 0;
virtual void sub_70() = 0;
virtual void sub_78() = 0;
virtual void sub_80() = 0;
virtual void sub_88() = 0;
virtual void sub_90() = 0;
virtual void sub_98() = 0;
virtual void sub_A0() = 0;
virtual void sub_A8() = 0;
virtual void sub_B0() = 0;
virtual void sub_B8() = 0;
virtual void sub_C0() = 0;
virtual void sub_C8() = 0;
virtual void sub_D0() = 0;
virtual void sub_D8() = 0;
virtual void sub_E0() = 0;
virtual void sub_E8() = 0;
virtual void sub_F0() = 0;
virtual void sub_F8() = 0;
virtual void sub_100() = 0;
int8_t unk8[0xB8];
UnkC0* unkC0;
int8_t unkC8[0x158];
};
RED4EXT_ASSERT_SIZE(CBaseEngine, 0x220);
RED4EXT_ASSERT_OFFSET(CBaseEngine, unkC0, 0xC0);
struct BaseGameEngine : CBaseEngine
{
int8_t unk220[0x18];
};
RED4EXT_ASSERT_SIZE(BaseGameEngine, 0x238);
RED4EXT_ASSERT_OFFSET(BaseGameEngine, unk220, 0x220);
struct CGameEngine : BaseGameEngine
{
struct CGameFramework
{
struct GameInstance
{
virtual ~GameInstance() = 0;
virtual IScriptable* GetInstance(const IRTTIType* aType) = 0;
};
RED4EXT_ASSERT_SIZE(GameInstance, 0x8);
int8_t unk0[0x10];
GameInstance* gameInstance;
};
static CGameEngine* Get();
int8_t unk238[0x28];
CGameFramework* framework;
int8_t unk268[0x30];
};
RED4EXT_ASSERT_SIZE(CGameEngine, 0x298);
RED4EXT_ASSERT_OFFSET(CGameEngine, unk238, 0x238);
RED4EXT_ASSERT_OFFSET(CGameEngine, framework, 0x260);
} // namespace RED4ext
#ifdef RED4EXT_HEADER_ONLY
#include <RED4ext/GameEngine-inl.hpp>
#endif
|
eafd8ed66293f3313c7dd29a7cadd6aecef6ae3f | 8805b9905278805b5b00b36f8e4a71bf39dae41e | /com/leet_cpp/SumOfTwoInteger.cpp | 693dc2de05393176c696b78517acb45ab721f857 | [] | no_license | mengarena/Leetcode | 96a935a10bcb289cde4c2a52e2490794a62ff553 | 76acc557df0032f0932c14d7b6ea0e90d116a0dc | refs/heads/master | 2021-04-19T01:12:22.746949 | 2021-01-13T08:59:24 | 2021-01-13T08:59:24 | 53,725,914 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 548 | cpp | SumOfTwoInteger.cpp | /*
371. Sum of Two Integers
Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
Example:
Given a = 1 and b = 2, return 3.
Hulu
Easy
*/
class Solution {
public:
int getSum(int a, int b) {
if (a == 0) return b;
if (b == 0) return a;
int carry = 0;
while (b != 0) {
carry = a & b;
a = a ^ b;
b = carry << 1;
}
return a;
}
};
|
62c38bd666fb4b0327c3911071f4703e0766f8cd | b7d8944c616bbd91a02af649f914ef7754e881ad | /C++/program_kasir_sederhana.cpp | cf382f0bcd77f635d1c7f402363bd52b3329db2d | [] | no_license | kodepi77/Program-Sederhana | 7c49d33ea6cc613145ab75e277d0e2d394e01518 | bb2233b879394910705778c607aa998dd12315cf | refs/heads/main | 2023-04-27T20:30:06.995962 | 2021-05-06T06:23:55 | 2021-05-06T06:23:55 | 363,349,173 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 601 | cpp | program_kasir_sederhana.cpp | #include <iostream>
using namespace std;
int main() {
int total, bayar, kembalian;
cout << "-- Kasir Sederhana --\n";
cout << "Masukan Jumlah yang Dipesan\n";
int bakso;
cout << "Bakso Rp 10.000 : ";
cin >> bakso;
total += bakso * 10000;
int mie;
cout << "Mie Pangsit Rp 8.000 : ";
cin >> mie;
total += mie * 8000;
int teh;
cout << "Es Teh Rp 3.000 : ";
cin >> teh;
total += teh * 3000;
cout << "---------------------\n";
cout << "Total = " << total << "\n";
cout << "Jumlah Bayar = ";
cin >> bayar;
kembalian = bayar - total;
cout << "Kembalian = " << kembalian << "\n";
}
|
22ea37aa508dc4cbaa0f7b542f7395101d64a9e2 | a5a88fbe4698223dc8bcc1d097599c4297ea0240 | /inter/Break.hpp | d3d874ac8de1cdaaa346a2706fe2f8188e2142c6 | [] | no_license | josephabero/Compiler_From_Scratch | db08bdbbe40eb8cf43c1718a8fb56431c9bfb79b | b0196947b91e57c8e4d807953c38d8735d23999f | refs/heads/master | 2020-07-19T14:49:33.854809 | 2019-10-31T05:10:32 | 2019-10-31T05:10:32 | 206,467,302 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 255 | hpp | Break.hpp | #pragma once
#include "Stmt.hpp"
class Break : public Stmt
{
public:
Break()
{
// if(Stmt.Enclosing == Stmt.Null) error("unenclosed break;")
// stmt = Stmt.Enclosing
}
std::string getNodeStr() { return "BREAK"; }
Stmt stmt;
}; |
38ae80e4ef854b64fb24656323e92f914896b0ab | a912b2ae2bf049d5d4862530286859cfb3d29f6f | /C++/Button.cpp | cac13c5ec82e206f55672190c9a2454b3986c042 | [] | no_license | RafailAndreou/MyPrograms | 3db9fe222fe55168739936ff788a1aeffe2dae13 | d1aa4fdc650fbe83799f03092034a2ae84d0ffdf | refs/heads/master | 2020-04-20T17:19:05.554531 | 2019-03-14T20:13:12 | 2019-03-14T20:13:12 | 168,985,467 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,245 | cpp | Button.cpp | #include "pch.h"
#include<iostream>
#include "SDL.h"
#include "SDL_image.h"
SDL_Window * window = nullptr;
const int Window_Width = 500;
const int Window_Height = 300;
void Init() {
window = SDL_CreateWindow("SDL", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, Window_Width, Window_Height, SDL_WINDOW_RESIZABLE);
}
void Quit() {
SDL_DestroyWindow(window);
SDL_Quit();
}
class Rect {
SDL_Renderer * olrend = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
SDL_Rect outline;
SDL_Rect rect;
public:
Rect(int x, int y, int h, int w) {
outline.x = x;
outline.y = y;
outline.h = h;
outline.w = w;
rect.x = x+1.25;
rect.y = y+1.25;
rect.h = h-2.5;
rect.w = w-2.5;
}
void draw() {
SDL_SetRenderDrawColor(olrend, 40, 40, 40,255);
SDL_RenderFillRect(olrend, &outline);
SDL_SetRenderDrawColor(olrend, 200, 200, 200, 255);
SDL_RenderFillRect(olrend, &rect);
SDL_RenderPresent(olrend);
}
};
int main(int argc, char *argv[]) {
Init();
SDL_Event event;
Rect Button(0,0,30,90);
bool running = true;
Button.draw();
while (running == true) {
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
running = false;
}
}
}
std::cout << SDL_GetError();
Quit();
return 0;
}
|
fda23f5e8a51848c78a867030aece39920a6a715 | 1d098ea7c675584627abcf8bb4b8bbf1c10bf56b | /src/integrators/IntegratorFactory.hpp | 59b7158be024edb2de20ea7dcc2d843161e68698 | [
"BSD-3-Clause"
] | permissive | OpenMD/OpenMD | 74fe0e285ab8ec62e71ce17721e222bb3e17467a | 7e4ee80742745329c48449dd509e36dc731c51ba | refs/heads/master | 2023-08-30T17:28:06.743925 | 2023-08-18T18:11:38 | 2023-08-18T18:11:38 | 32,750,591 | 73 | 45 | NOASSERTION | 2023-01-27T19:38:18 | 2015-03-23T18:22:26 | C++ | UTF-8 | C++ | false | false | 5,125 | hpp | IntegratorFactory.hpp | /*
* Copyright (c) 2004-present, The University of Notre Dame. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. Neither the name of the copyright holder 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 HOLDER 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.
*
* SUPPORT OPEN SCIENCE! If you use OpenMD or its source code in your
* research, please cite the appropriate papers when you publish your
* work. Good starting points are:
*
* [1] Meineke, et al., J. Comp. Chem. 26, 252-271 (2005).
* [2] Fennell & Gezelter, J. Chem. Phys. 124, 234104 (2006).
* [3] Sun, Lin & Gezelter, J. Chem. Phys. 128, 234107 (2008).
* [4] Vardeman, Stocker & Gezelter, J. Chem. Theory Comput. 7, 834 (2011).
* [5] Kuang & Gezelter, Mol. Phys., 110, 691-701 (2012).
* [6] Lamichhane, Gezelter & Newman, J. Chem. Phys. 141, 134109 (2014).
* [7] Lamichhane, Newman & Gezelter, J. Chem. Phys. 141, 134110 (2014).
* [8] Bhattarai, Newman & Gezelter, Phys. Rev. B 99, 094106 (2019).
*/
/**
* @file IntegratorFactory.hpp
* @author Teng Lin
* @date 10/24/2004
* @version 1.0
*/
#ifndef INTEGRATORS_INTEGRATORFACTORY_HPP
#define INTEGRATORS_INTEGRATORFACTORY_HPP
#include <cassert>
#include <iostream>
#include <map>
#include <string>
#include <vector>
namespace OpenMD {
// forward declaration
class Integrator;
class IntegratorCreator;
class SimInfo;
/**
* @class IntegratorFactory
* Factory pattern and Singleton Pattern are used to define an interface for
* creating an Integrator.
*/
class IntegratorFactory {
public:
using CreatorMapType = std::map<std::string, IntegratorCreator*>;
using IdentVectorType = std::vector<std::string>;
using IdentVectorIterator = std::vector<std::string>::iterator;
/**
* Returns an instance of Integrator factory
* @return an instance of Integrator factory
*/
static IntegratorFactory& getInstance() {
static IntegratorFactory instance {};
return instance;
}
/**
* Registers a creator with a type identifier
* @return true if registration is successful, otherwise return false
* @param creator the object responsible for creating the concrete object
*/
bool registerIntegrator(IntegratorCreator* creator);
/**
* Unregisters the creator for the given type identifier. If the type
* identifier was previously registered, the function returns true.
* @return truethe type identifier was previously registered and the creator
* is removed, otherwise return false
* @param id the identification of the concrete object
*/
bool unregisterIntegrator(const std::string& id);
/**
* Looks up the type identifier in the internal map. If it is found, it
* invokes the corresponding creator for the type identifier and returns its
* result.
* @return a pointer of the concrete object, return NULL if no creator is
* registed for creating this concrete object
* @param id the identification string of the concrete object
* @param info pointer to the concrete SimInfo object
*/
Integrator* createIntegrator(const std::string& id, SimInfo* info);
/**
* Returns all of the registed type identifiers
* @return all of the registed type identifiers
*/
IdentVectorType getIdents();
private:
IntegratorFactory() = default;
~IntegratorFactory();
IntegratorFactory(const IntegratorFactory&) = delete;
IntegratorFactory& operator=(const IntegratorFactory&) = delete;
CreatorMapType creatorMap_;
};
/** write out all of the type identifiers to an output stream */
std::ostream& operator<<(std::ostream& o, IntegratorFactory& factory);
} // namespace OpenMD
#endif // INTEGRATORS_INTEGRATORFACTORY_HPP
|
59ec0c2efe783b2b663627de407b3a3817dc4af4 | 708f517eff55a4a36a3d81fc44a60dc927d3830a | /Debug.h | 210dc5cc6ff3028d5fa5b59c1f10375c09e05992 | [] | no_license | linxuan2/sheepshead-scores | 77b27cb197b2a0340e18c32b6d4d9ced48538ca4 | 59e62e3a5eb7c9875289bf799957ef7e4b865d5f | refs/heads/master | 2021-01-18T19:10:08.065726 | 2014-03-10T02:55:53 | 2014-03-10T02:55:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 410 | h | Debug.h | #pragma once
#include <vector>
#include <string>
class Debug
{
private:
Debug() = default;
Debug(const Debug& rhs) = delete;
~Debug() = default;
Debug& operator=(const Debug& rhs) = default;
public:
static Debug& GetInstance();
void Write(const std::string& message);
bool HasMessages() const;
const std::vector<std::string>& GetMessages() const;
private:
std::vector<std::string> messages;
};
|
6d8a94aaee42fd0a9c613d844b5761114972e21f | 703d8c2b75622b37f5b7342fe710a890bdb04f2f | /27A Next Test.cpp | fb57d72c85394bab955d3735ad3101aa0f60fdb5 | [] | no_license | vicky1966/competitive-coding | 5b1a2e5e2c673af9a9b25ed46f300e5c3b2b000a | 9942fb9d5afeee81e63e33eadc96efdf6427a415 | refs/heads/master | 2021-01-19T08:46:17.956935 | 2017-02-16T17:07:53 | 2017-02-16T17:07:53 | 68,066,066 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 447 | cpp | 27A Next Test.cpp | #include<iostream>
#include<algorithm>
using namespace std;
int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0; i<n; i++)
cin>>arr[i];
sort(arr,arr+n);
//cout<<arr[0];
for(int i=0;i<n;i++)
{
if(arr[0]!=1)
{
cout<<1;
return 0;
}
else if(i!=0)
{
if(arr[i]==arr[i-1] || arr[i]==arr[i-1]+1)
{
}
else
{//cout<<arr[i]<<" "<<arr[i-1];
cout<<arr[i-1]+1;
return 0;
}
}
}
cout<<n+1;
return 0;
}
|
0ce19a5d236b74141f5245f4155934544e9e5aff | 4d839f73c42ac060733c7ef44c7e6951ef8a14bf | /Source/Main/FolderWindowDrop.h | dc2b01de04001740d2a8bb66e16ec1edf8ac9bb2 | [] | no_license | ZacWalk/ImageWalker | 8252aa6d39bde8d04bb00560082f296619168e98 | 5b7a61a4961054c4a61f9e04e10dc18161b608f4 | refs/heads/master | 2021-01-21T21:42:37.209350 | 2018-06-05T15:59:24 | 2018-06-05T15:59:24 | 3,126,103 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 8,606 | h | FolderWindowDrop.h | #pragma once
template<typename TWindow>
class CFolderWindowDropAdapter :
public CComCoClass<CFolderWindowDropAdapter<TWindow> >,
public CComObjectRootEx<CComSingleThreadModel>,
public IDropTarget,
public IDropSource
{
public:
TWindow *_pWindow;
bool m_bDragStarted; // has drag really started yet?
bool m_bInDragOver;
DWORD m_dwButtonCancel; // which button will cancel (going down)
DWORD m_dwButtonDrop; // which button will confirm (going up)
CComPtr<IDataObject> m_spDataObject;
CComPtr<IDropTarget> m_spShellDropTarget;
CFolderWindowDropAdapter(TWindow *pWindow = 0) :
_pWindow(pWindow),
m_bDragStarted(false),
m_dwButtonCancel(0),
m_dwButtonDrop(0),
m_bInDragOver(false)
{
}
BEGIN_COM_MAP(CFolderWindowDropAdapter<TWindow>)
COM_INTERFACE_ENTRY(IDropSource)
COM_INTERFACE_ENTRY(IDropTarget)
END_COM_MAP()
void SetDragOverItem(int nNewDragOverItem)
{
int nCurrentDragOverItem = _pWindow->_nDragOverItem;
if (nNewDragOverItem != nCurrentDragOverItem)
{
IW::FolderPtr pFolder = GetFolder();
if (nCurrentDragOverItem >= 0) _pWindow->InvalidateThumb(pFolder, nCurrentDragOverItem);
_pWindow->_nDragOverItem = nNewDragOverItem;
if (nNewDragOverItem >= 0) _pWindow->InvalidateThumb(pFolder, nNewDragOverItem);
}
}
int GetDragOverItem() const
{
return _pWindow->_nDragOverItem;
}
IW::FolderPtr GetFolder()
{
return _pWindow->_state.Folder.GetFolder();
}
bool IsDraging() const
{
return _pWindow->_bDraging;
}
// metrics for drag start determination
static const UINT nDragDelay = 500; // delay before drag starts
BOOL RegisterDropTarget()
{
LPUNKNOWN lpUnknown = GetUnknown();
ATLASSERT(lpUnknown != NULL);
// Has create been called window?
ATLASSERT(_pWindow->IsWindow());
// the object must be locked externally to keep LRPC connections alive
HRESULT hr = CoLockObjectExternal(lpUnknown, TRUE, FALSE);
if (hr != S_OK)
return FALSE;
// connect the HWND to the IDropTarget implementation
hr = RegisterDragDrop(_pWindow->GetHWnd(), (LPDROPTARGET)this);
if (hr != S_OK)
{
CoLockObjectExternal(lpUnknown, FALSE, FALSE);
return FALSE;
}
return TRUE;
}
void RevokeDropTarget()
{
// disconnect from OLE
RevokeDragDrop(_pWindow->GetHWnd());
CoLockObjectExternal((LPUNKNOWN)GetUnknown(), FALSE, TRUE);
}
BOOL OnBeginDrag()
{
m_bDragStarted = false;
// opposite button cancels drag operation
m_dwButtonCancel = 0;
m_dwButtonDrop = 0;
if (GetKeyState(VK_LBUTTON) < 0)
{
m_dwButtonDrop |= MK_LBUTTON;
m_dwButtonCancel |= MK_RBUTTON;
}
else if (GetKeyState(VK_RBUTTON) < 0)
{
m_dwButtonDrop |= MK_RBUTTON;
m_dwButtonCancel |= MK_LBUTTON;
}
DWORD dwLastTick = GetTickCount();
::SetCapture(_pWindow->GetHWnd());
while (!m_bDragStarted)
{
// some applications steal capture away at random times
if (::GetCapture() != _pWindow->GetHWnd())
break;
// peek for next input message
MSG msg;
if (PeekMessage(&msg, NULL, WM_MOUSEFIRST, WM_MOUSELAST, PM_REMOVE) ||
PeekMessage(&msg, NULL, WM_KEYFIRST, WM_KEYLAST, PM_REMOVE))
{
// check for button cancellation (any button down will cancel)
if (msg.message == WM_LBUTTONUP || msg.message == WM_RBUTTONUP ||
msg.message == WM_LBUTTONDOWN || msg.message == WM_RBUTTONDOWN)
break;
// check for keyboard cancellation
if (msg.message == WM_KEYDOWN && msg.wParam == VK_ESCAPE)
break;
// check for drag start transition
m_bDragStarted = !PtInRect(&(_pWindow->_rectStartDrag), msg.pt);
}
// if the user sits here long enough, we eventually start the drag
if (GetTickCount() - dwLastTick > nDragDelay)
m_bDragStarted = true;
}
ReleaseCapture();
return m_bDragStarted;
}
STDMETHODIMP Drop(IDataObject *pDataObj, DWORD grfKeyState, POINTL pt, DWORD *pdwEffect)
{
if (m_spShellDropTarget != NULL)
{
HRESULT hr = m_spShellDropTarget->Drop(pDataObj, grfKeyState, pt, pdwEffect);
DragLeave();
bool bDrag = (DRAGDROP_S_DROP == hr) && (*pdwEffect != DROPEFFECT_NONE);
return hr;
}
else if (GetDragOverItem() != -1 && IsDraging())
{
// Drag selection to new position
IW::FolderPtr pFolder = _pWindow->_state.Folder.GetFolder();
pFolder->DragSelection(GetDragOverItem());
DragLeave();
_pWindow->Invalidate();
}
return S_OK;
}
STDMETHODIMP DragEnter(IDataObject *pDataObj, DWORD grfKeyState, POINTL pt, DWORD *pdwEffect)
{
SetDragOverItem(-2);
m_spDataObject = pDataObj;
m_bInDragOver = true;
return DragOver(grfKeyState, pt, pdwEffect);
}
STDMETHODIMP DragLeave()
{
m_bInDragOver = false;
if (m_spShellDropTarget != NULL)
{
m_spShellDropTarget->DragLeave();
m_spShellDropTarget.Release();
}
if (m_spDataObject != NULL)
{
m_spDataObject.Release();
}
if (GetDragOverItem() != -1)
{
SetDragOverItem(-1);
}
return S_OK;
}
STDMETHODIMP DragOver(DWORD grfKeyState, POINTL pt, DWORD *pdwEffect)
{
IW::FolderPtr pFolder = GetFolder();
HRESULT hr = E_FAIL;
CPoint pointScreen(pt.x, pt.y);
_pWindow->ScreenToClient(&pointScreen);
const CPoint pointWithOffset = pointScreen + CSize(_pWindow->GetScrollOffset());
int i = _pWindow->GetLayout()->ThumbFromPoint(pointWithOffset);
if (i != -1)
{
if (!_pWindow->GetImageRect(i).PtInRect(pointWithOffset))
i = -1;
}
if (i != GetDragOverItem())
{
if (i != -1)
{
if (pFolder->IsItemDropTarget(i))
{
i = -1;
}
}
if (GetDragOverItem() != i)
{
SetDragOverItem(i);
if (m_spShellDropTarget != NULL)
{
m_spShellDropTarget->DragLeave();
m_spShellDropTarget.Release();
}
if (GetDragOverItem() != -1)
{
hr = pFolder->GetUIObjectOf(GetDragOverItem(), IID_IDropTarget, (LPVOID *)&m_spShellDropTarget);
}
else
{
hr = pFolder->CreateViewObject(IW::GetMainWindow(), IID_IDropTarget, (LPVOID *)&m_spShellDropTarget);
}
if (SUCCEEDED(hr))
{
if ((IsDraging() || _pWindow->_state.Folder.IsSearchMode) &&
(GetDragOverItem() == -1 || pFolder->IsItemSelected(GetDragOverItem())))
{
*pdwEffect = DROPEFFECT_NONE;
}
hr = m_spShellDropTarget->DragEnter(m_spDataObject, grfKeyState, pt, pdwEffect);
if (SUCCEEDED(hr))
{
return hr;
}
}
}
}
if (m_spShellDropTarget != NULL)
{
if ((IsDraging() || _pWindow->_state.Folder.IsSearchMode) &&
(GetDragOverItem() == -1 ||
pFolder->IsItemSelected(GetDragOverItem())))
{
*pdwEffect = DROPEFFECT_NONE;
}
return m_spShellDropTarget->DragOver(grfKeyState, pt, pdwEffect);
}
else
{
*pdwEffect = IsDraging() ? DROPEFFECT_MOVE : DROPEFFECT_NONE;
}
return S_OK;
}
// Drop source stuff
STDMETHODIMP QueryContinueDrag(BOOL bEscapePressed, DWORD dwKeyState)
{
// check escape key or right button -- and cancel
if (bEscapePressed || (dwKeyState & m_dwButtonCancel) != 0)
{
m_bDragStarted = false; // avoid unecessary cursor setting
return DRAGDROP_S_CANCEL;
}
// check left-button up to end drag/drop and do the drop
if ((dwKeyState & m_dwButtonDrop) == 0)
return m_bDragStarted ? DRAGDROP_S_DROP : DRAGDROP_S_CANCEL;
// otherwise, keep polling...
return S_OK;
}
STDMETHODIMP GiveFeedback(DROPEFFECT /*dropEffect*/)
{
//CPoint point;
//GetCursorPos(&point);
//if (_rectStartDrag.PtInRect(point))
//return S_OK;
if (m_bDragStarted && m_spShellDropTarget == NULL && GetDragOverItem() != -1 && IsDraging())
{
SetCursor(IW::Style::Cursor::Insert);
return S_OK;
}
// don't change the cursor until drag is officially started
return m_bDragStarted ? DRAGDROP_S_USEDEFAULTCURSORS : S_OK;
}
void OnTimer()
{
// Do drag scroll if we
// Are in a drag mode
if (m_bInDragOver)
{
CPoint pt;
CRect rc;
CSize sizeThumb = App.Options._sizeThumbImage;
::GetCursorPos((LPPOINT)&pt);
_pWindow->ScreenToClient(&pt);
_pWindow->GetClientRect(&rc);
int cy = sizeThumb.cy / 2;
if (pt.y < (rc.top + cy))
{
// Scroll Up
_pWindow->ScrollLineUp();
}
else if (pt.y > (rc.bottom - cy))
{
_pWindow->ScrollLineDown();
}
}
}
};
|
b098fd1f2c98f7003f7184bee50c06486b49b002 | 52c61d1f48f48e55414d5e832fb0ab8427bbf492 | /source/binding_GLUT.cpp | 6afb0cf47648a8ac0c7144f1a96fb893beab551b | [] | no_license | thenumbernine/wii-sdl-luajit | 269ad9585cf7056b8b078700da0dafd93628ad7a | 5c60fefececdbbaee55cd5dcf10a782a85450b28 | refs/heads/master | 2022-11-09T20:26:39.200374 | 2022-10-27T05:19:09 | 2022-10-27T05:19:09 | 32,558,137 | 6 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 6,890 | cpp | binding_GLUT.cpp | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <malloc.h>
#include <math.h>
#include <gccore.h>
#include <string.h>
#include <GL/glut.h>
#include "lua_util.h"
BINDFUNC(void, glutInit, int *, char **)
BINDFUNC(void, glutInitDisplayMode, unsigned int)
//BINDFUNC(void, glutInitDisplayString, const char *)
//BINDFUNC(void, glutInitWindowPosition, int, int)
BINDFUNC(void, glutInitWindowSize, int, int)
BINDFUNC(void, glutMainLoop)
BINDFUNC(int, glutCreateWindow, const char *)
//BINDFUNC(int, glutCreateSubWindow, int, int, int, int, int)
//BINDFUNC(void, glutDestroyWindow, int)
//BINDFUNC(void, glutPostRedisplay)
//BINDFUNC(void, glutPostWindowRedisplay, int)
BINDFUNC(void, glutSwapBuffers)
//BINDFUNC(int, glutGetWindow)
//BINDFUNC(void, glutSetWindow, int)
//BINDFUNC(void, glutSetWindowTitle, const char *)
//BINDFUNC(void, glutSetIconTitle, const char *)
//BINDFUNC(void, glutPositionWindow, int, int)
//BINDFUNC(void, glutReshapeWindow, int, int)
//BINDFUNC(void, glutPopWindow)
//BINDFUNC(void, glutPushWindow)
//BINDFUNC(void, glutIconifyWindow)
//BINDFUNC(void, glutShowWindow)
//BINDFUNC(void, glutHideWindow)
//BINDFUNC(void, glutFullScreen)
//BINDFUNC(void, glutSetCursor, int)
//BINDFUNC(void, glutWarpPointer, int, int)
//BINDFUNC(void, glutEstablishOverlay)
//BINDFUNC(void, glutRemoveOverlay)
//BINDFUNC(void, glutUseLayer, GLenum)
//BINDFUNC(void, glutPostOverlayRedisplay)
//BINDFUNC(void, glutPostWindowOverlayRedisplay, int)
//BINDFUNC(void, glutShowOverlay)
//BINDFUNC(void, glutHideOverlay)
//BINDFUNC(void, glutDestroyMenu, int)
//BINDFUNC(int, glutGetMenu)
//BINDFUNC(void, glutSetMenu, int)
//BINDFUNC(void, glutAddMenuEntry, const char *, int)
//BINDFUNC(void, glutAddSubMenu, const char *, int)
//BINDFUNC(void, glutChangeToMenuEntry, int, const char *, int)
//BINDFUNC(void, glutChangeToSubMenu, int, const char *, int)
//BINDFUNC(void, glutRemoveMenuItem, int)
//BINDFUNC(void, glutAttachMenu, int)
//BINDFUNC(void, glutDetachMenu, int)
//BINDFUNC(void, glutSetColor, int, GLfloat, GLfloat, GLfloat)
//BINDFUNC(GLfloat, glutGetColor, int, int)
//BINDFUNC(void, glutCopyColormap, int)
BINDFUNC(int, glutGet, GLenum)
//BINDFUNC(int, glutDeviceGet, GLenum)
BINDFUNC(int, glutExtensionSupported, const char *)
//BINDFUNC(int, glutGetModifiers)
//BINDFUNC(int, glutLayerGet, GLenum)
BINDFUNC(void, glutBitmapCharacter, void *, int)
BINDFUNC(int, glutBitmapWidth, void *, int)
BINDFUNC(void, glutStrokeCharacter, void *, int)
BINDFUNC(int, glutStrokeWidth, void *, int)
BINDFUNC(int, glutBitmapLength, void *, const unsigned char *)
BINDFUNC(int, glutStrokeLength, void *, const unsigned char *)
BINDFUNC(void, glutWireSphere, GLdouble, GLint, GLint)
BINDFUNC(void, glutSolidSphere, GLdouble, GLint, GLint)
BINDFUNC(void, glutWireCone, GLdouble, GLdouble, GLint, GLint)
BINDFUNC(void, glutSolidCone, GLdouble, GLdouble, GLint, GLint)
BINDFUNC(void, glutWireCube, GLdouble)
BINDFUNC(void, glutSolidCube, GLdouble)
BINDFUNC(void, glutWireTorus, GLdouble, GLdouble, GLint, GLint)
BINDFUNC(void, glutSolidTorus, GLdouble, GLdouble, GLint, GLint)
BINDFUNC(void, glutWireDodecahedron)
BINDFUNC(void, glutSolidDodecahedron)
BINDFUNC(void, glutWireTeapot, GLdouble)
BINDFUNC(void, glutSolidTeapot, GLdouble)
BINDFUNC(void, glutWireOctahedron)
BINDFUNC(void, glutSolidOctahedron)
BINDFUNC(void, glutWireTetrahedron)
BINDFUNC(void, glutSolidTetrahedron)
BINDFUNC(void, glutWireIcosahedron)
BINDFUNC(void, glutSolidIcosahedron)
//BINDFUNC(int, glutVideoResizeGet, GLenum)
//BINDFUNC(void, glutSetupVideoResizing)
//BINDFUNC(void, glutStopVideoResizing)
//BINDFUNC(void, glutVideoResize, int, int, int, int)
//BINDFUNC(void, glutVideoPan, int, int, int, int)
BINDFUNC(void, glutReportErrors)
//BINDFUNC(void, glutIgnoreKeyRepeat, int)
//BINDFUNC(void, glutSetKeyRepeat, int)
//BINDFUNC(void, glutForceJoystickFunc)
//BINDFUNC(void, glutGameModeString, const char *)
//BINDFUNC(int, glutEnterGameMode)
//BINDFUNC(void, glutLeaveGameMode)
//BINDFUNC(int, glutGameModeGet, GLenum)
void init_binding_GLUT(lua_State *L) {
int ffi = lua_gettop(L);
FFI_CDEF_FILE("include/GLUT_types.h");
BEGIN_PACKAGE(glut)
BINDNAME(glutInit)
BINDNAME(glutInitDisplayMode)
//BINDNAME(glutInitDisplayString)
//BINDNAME(glutInitWindowPosition)
BINDNAME(glutInitWindowSize)
BINDNAME(glutMainLoop)
BINDNAME(glutCreateWindow)
//BINDNAME(glutCreateSubWindow)
//BINDNAME(glutDestroyWindow)
//BINDNAME(glutPostRedisplay)
//BINDNAME(glutPostWindowRedisplay)
BINDNAME(glutSwapBuffers)
//BINDNAME(glutGetWindow)
//BINDNAME(glutSetWindow)
//BINDNAME(glutSetWindowTitle)
//BINDNAME(glutSetIconTitle)
//BINDNAME(glutPositionWindow)
//BINDNAME(glutReshapeWindow)
//BINDNAME(glutPopWindow)
//BINDNAME(glutPushWindow)
//BINDNAME(glutIconifyWindow)
//BINDNAME(glutShowWindow)
//BINDNAME(glutHideWindow)
//BINDNAME(glutFullScreen)
//BINDNAME(glutSetCursor)
//BINDNAME(glutWarpPointer)
//BINDNAME(glutEstablishOverlay)
//BINDNAME(glutRemoveOverlay)
//BINDNAME(glutUseLayer)
//BINDNAME(glutPostOverlayRedisplay)
//BINDNAME(glutPostWindowOverlayRedisplay)
//BINDNAME(glutShowOverlay)
//BINDNAME(glutHideOverlay)
//BINDNAME(glutDestroyMenu)
//BINDNAME(glutGetMenu)
//BINDNAME(glutSetMenu)
//BINDNAME(glutAddMenuEntry)
//BINDNAME(glutAddSubMenu)
//BINDNAME(glutChangeToMenuEntry)
//BINDNAME(glutChangeToSubMenu)
//BINDNAME(glutRemoveMenuItem)
//BINDNAME(glutAttachMenu)
//BINDNAME(glutDetachMenu)
//BINDNAME(glutSetColor)
//BINDNAME(glutGetColor)
//BINDNAME(glutCopyColormap)
BINDNAME(glutGet)
//BINDNAME(glutDeviceGet)
BINDNAME(glutExtensionSupported)
//BINDNAME(glutGetModifiers)
//BINDNAME(glutLayerGet)
BINDNAME(glutBitmapCharacter)
BINDNAME(glutBitmapWidth)
BINDNAME(glutStrokeCharacter)
BINDNAME(glutStrokeWidth)
BINDNAME(glutBitmapLength)
BINDNAME(glutStrokeLength)
BINDNAME(glutWireSphere)
BINDNAME(glutSolidSphere)
BINDNAME(glutWireCone)
BINDNAME(glutSolidCone)
BINDNAME(glutWireCube)
BINDNAME(glutSolidCube)
BINDNAME(glutWireTorus)
BINDNAME(glutSolidTorus)
BINDNAME(glutWireDodecahedron)
BINDNAME(glutSolidDodecahedron)
BINDNAME(glutWireTeapot)
BINDNAME(glutSolidTeapot)
BINDNAME(glutWireOctahedron)
BINDNAME(glutSolidOctahedron)
BINDNAME(glutWireTetrahedron)
BINDNAME(glutSolidTetrahedron)
BINDNAME(glutWireIcosahedron)
BINDNAME(glutSolidIcosahedron)
//BINDNAME(glutVideoResizeGet)
//BINDNAME(glutSetupVideoResizing)
//BINDNAME(glutStopVideoResizing)
//BINDNAME(glutVideoResize)
//BINDNAME(glutVideoPan)
BINDNAME(glutReportErrors)
//BINDNAME(glutIgnoreKeyRepeat)
//BINDNAME(glutSetKeyRepeat)
//BINDNAME(glutForceJoystickFunc)
//BINDNAME(glutGameModeString)
//BINDNAME(glutEnterGameMode)
//BINDNAME(glutLeaveGameMode)
//BINDNAME(glutGameModeGet)
END_PACKAGE()
}
|
511c262720c736fda7cc59c089d9c0bbe431e051 | bdda1522d39d04917f39818a82717c3dfec5b8e9 | /src/Subsystems/Drive.cpp | 71a71b72592046d0e4eccfdc6ba22990065fd86c | [] | no_license | pentomid/RobertQ4 | a43edab2906ca8caa8148725a9a25e6fb0f5438a | c6d965f9a7d05e89fc9809c42517a54c8372d2d4 | refs/heads/master | 2016-09-05T20:11:51.325515 | 2015-05-16T21:55:59 | 2015-05-16T21:55:59 | 34,585,500 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,189 | cpp | Drive.cpp | #include "Drive.h"
#include "../RobotMap.h"
Drive::Drive() :
Subsystem("Drive"),
left(new Talon(MOTOR_LEFT)),
right(new Talon(MOTOR_RIGHT))
{
}
float Drive::max(float x,float y) //determines which value is larger
{
return (x > y ? x : y);
}
void Drive::arcadeDrive(float move, float rotate)
{
float leftMotorOutput;
float rightMotorOutput;
if (move > 0.0) //converts joystick values to motor voltage values
{
if (rotate > 0.0)
{
leftMotorOutput = move - rotate;
rightMotorOutput = max(move,rotate);
}
else
{
leftMotorOutput = max(move,-rotate);
rightMotorOutput = move + rotate;
}
}
else
{
if (rotate > 0.0)
{
leftMotorOutput = - max(-move,rotate);
rightMotorOutput = move + rotate;
}
else
{
leftMotorOutput = move - rotate;
rightMotorOutput = - max(-move,-rotate);
}
}
left->Set(leftMotorOutput); //sends motor value to motor controller
right->Set(rightMotorOutput); //sends motor value to motor controller
}
void Drive::InitDefaultCommand()
{
// Set the default command for a subsystem here.
SetDefaultCommand(new ArcadeDrive());
}
// Put methods for controlling this subsystem
// here. Call these from Commands.
|
c54eb50d43bde12eba923e7af45ccbaeca2c9c38 | 2b0b07242be5ea756aba992e171b43fbee9bfada | /BOJ/13560/13560.cpp | 8b1be2f399db46ba78629ad5fe112f19f38c91cb | [] | no_license | newdaytrue/PS | 28f138a5e8fd4024836ea7c2b6ce59bea91dbad7 | afffef30fcb59f6abfee2d5b8f00a304e8d80c91 | refs/heads/master | 2020-03-22T13:01:46.555651 | 2018-02-13T18:25:34 | 2018-02-13T18:25:34 | 140,078,090 | 1 | 0 | null | 2018-07-07T11:21:44 | 2018-07-07T11:21:44 | null | UTF-8 | C++ | false | false | 820 | cpp | 13560.cpp | #include <bits/stdc++.h>
using namespace std;
int n;
int w[10000];
int l[10000];
int t[10000];
bool possi(int sum){
if(sum*2!=n*(n-1))
return false;
for(int i=n-1;i>=0;i--){
memset(t,0,sizeof(t));
for(int j=n-1;j>0;j--){
int k=min(l[j],w[i]);
l[j]-=k;
w[i]-=k;
t[j-1]+=k;
if(w[i]==0)
break;
}
if(w[i]!=0)
return false;
for(int j=0;j<n;j++)
l[j]+=t[j];
}
for(int i=1;i<n;i++)
if(l[i]!=0)
return false;
return true;
}
int main(){
scanf("%d",&n);
int sum=0;
for(int i=0;i<n;i++){
scanf("%d",&w[i]);
l[n-1-w[i]]++;
sum+=w[i];
}
sort(w,w+n);
printf("%d\n",possi(sum)?1:-1);
return 0;
} |
f11d4a757be2eb589feb514a25cdd79b5ce1f979 | b7d4fc29e02e1379b0d44a756b4697dc19f8a792 | /src/crowdin_gui.h | 15f98e579ec9a4818c9a48eaa552aad443f2b23e | [
"GPL-1.0-or-later",
"MIT"
] | permissive | vslavik/poedit | 45140ca86a853db58ddcbe65ab588da3873c4431 | 1b0940b026b429a10f310d98eeeaadfab271d556 | refs/heads/master | 2023-08-29T06:24:16.088676 | 2023-08-14T15:48:18 | 2023-08-14T15:48:18 | 477,156 | 1,424 | 275 | MIT | 2023-09-01T16:57:47 | 2010-01-18T08:23:13 | C++ | UTF-8 | C++ | false | false | 4,058 | h | crowdin_gui.h | /*
* This file is part of Poedit (https://poedit.net)
*
* Copyright (C) 2015-2023 Vaclav Slavik
*
* 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.
*
*/
#ifndef Poedit_crowdin_gui_h
#define Poedit_crowdin_gui_h
#include "catalog.h"
#ifdef HAVE_HTTP_CLIENT
#include "cloud_sync.h"
#include "customcontrols.h"
#include <wx/panel.h>
class WXDLLIMPEXP_FWD_CORE wxBoxSizer;
class WXDLLIMPEXP_FWD_CORE wxButton;
/**
Panel used to sign in into Crowdin.
*/
class CrowdinLoginPanel : public wxPanel
{
public:
enum Flags
{
DialogButtons = 1
};
CrowdinLoginPanel(wxWindow *parent, int flags = 0);
/// Call this when the window is first shown
void EnsureInitialized();
protected:
enum class State
{
Uninitialized,
Authenticating,
SignedIn,
SignedOut,
UpdatingInfo
};
void ChangeState(State state);
void CreateLoginInfoControls(State state);
void UpdateUserInfo();
void OnSignIn(wxCommandEvent&);
void OnSignOut(wxCommandEvent&);
virtual void OnUserSignedIn();
State m_state;
ActivityIndicator *m_activity;
wxBoxSizer *m_loginInfo;
wxButton *m_signIn, *m_signOut;
wxString m_userName, m_userLogin;
std::string m_userAvatar;
};
class CrowdinSyncDestination : public CloudSyncDestination
{
public:
wxString GetName() const override { return "Crowdin"; }
bool AuthIfNeeded(wxWindow* parent) override;
dispatch::future<void> Upload(CatalogPtr file) override;
};
/// Link to learn about Crowdin
class LearnAboutCrowdinLink : public LearnMoreLink
{
public:
LearnAboutCrowdinLink(wxWindow *parent, const wxString& text = "");
};
/// Can given file by synced to Crowdin, i.e. does it come from Crowdin and does it have required metadata?
bool CanSyncWithCrowdin(CatalogPtr cat);
/// Was the file opened directly from Crowdin and should be synced when the user saves it?
bool ShouldSyncToCrowdinAutomatically(CatalogPtr cat);
/**
Let the user choose a Crowdin file, download it and open in Poedit.
@param parent PoeditFrame the UI should be shown under.
@param onDone Called with the dialog return value (wxID_OK/CANCEL) and name of loaded PO file.
*/
void CrowdinOpenFile(wxWindow *parent, std::function<void(int, wxString)> onDone);
/**
Synces the catalog with Crowdin, uploading and downloading translations.
@param parent PoeditFrame the UI should be shown under.
@param catalog Catalog to sync.
@param onDone Called with the (new) updated catalog instance.
*/
void CrowdinSyncFile(wxWindow *parent, std::shared_ptr<Catalog> catalog,
std::function<void(std::shared_ptr<Catalog>)> onDone);
#else // !HAVE_HTTP_CLIENT
// convenience stubs to avoid additional checks all over other code:
inline bool CanSyncWithCrowdin(CatalogPtr) { return false; }
inline bool ShouldSyncToCrowdinAutomatically(CatalogPtr) { return false; }
#endif // !HAVE_HTTP_CLIENT
#endif // Poedit_crowdin_gui_h
|
efd477e4409dbbf37992e6b248fc35735c5dd373 | 7e6afb4986a53c420d40a2039240f8c5ed3f9549 | /libs/maps/include/mrpt/maps/CLogOddsGridMapLUT.h | 241669ad69e5310fbab439fbe85e8336f9e6cd9d | [
"BSD-3-Clause"
] | permissive | MRPT/mrpt | 9ea3c39a76de78eacaca61a10e7e96646647a6da | 34077ec74a90b593b587f2057d3280ea520a3609 | refs/heads/develop | 2023-08-17T23:37:29.722496 | 2023-08-17T15:39:54 | 2023-08-17T15:39:54 | 13,708,826 | 1,695 | 646 | BSD-3-Clause | 2023-09-12T22:02:53 | 2013-10-19T21:09:23 | C++ | UTF-8 | C++ | false | false | 3,986 | h | CLogOddsGridMapLUT.h | /* +------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| https://www.mrpt.org/ |
| |
| Copyright (c) 2005-2023, Individual contributors, see AUTHORS file |
| See: https://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See: https://www.mrpt.org/License |
+------------------------------------------------------------------------+ */
#pragma once
#include <mrpt/maps/logoddscell_traits.h>
#include <cmath>
#include <vector>
namespace mrpt::maps
{
/** One static instance of this struct should exist in any class implementing
* CLogOddsGridMap2D to hold the Look-up-tables (LUTs) for log-odss Bayesian
*update. Map cells must be type TCELL, which can be only:
* - int8_t or
* - int16_t
*
* \sa CLogOddsGridMap2D, see derived classes for usage examples.
* \ingroup mrpt_maps_grp
*/
template <typename TCELL>
struct CLogOddsGridMapLUT : public detail::logoddscell_traits<TCELL>
{
/** The type of */
using cell_t = TCELL;
using traits_t = detail::logoddscell_traits<TCELL>;
/** A lookup table to compute occupancy probabilities in [0,1] from integer
* log-odds values in the cells, using \f$ p(m_{xy}) =
* \frac{1}{1+exp(-log_odd)} \f$.
*/
std::vector<float> logoddsTable;
/** A lookup table to compute occupancy probabilities in the range [0,255]
* from integer log-odds values in the cells, using \f$ p(m_{xy}) =
* \frac{1}{1+exp(-log_odd)} \f$.
* This is used to speed-up conversions to grayscale images.
*/
std::vector<uint8_t> logoddsTable_255;
/** A lookup table for passing from float to log-odds as cell_t. */
std::vector<cell_t> p2lTable;
/** Constructor: computes all the required stuff. */
CLogOddsGridMapLUT()
{
// The factor for converting log2-odds into integers:
static const double LOGODD_K = 16;
static const double LOGODD_K_INV = 1.0 / LOGODD_K;
logoddsTable.resize(traits_t::LOGODDS_LUT_ENTRIES);
logoddsTable_255.resize(traits_t::LOGODDS_LUT_ENTRIES);
for (int i = traits_t::CELLTYPE_MIN; i <= traits_t::CELLTYPE_MAX; i++)
{
float f = 1.0f / (1.0f + std::exp(-i * LOGODD_K_INV));
unsigned int idx = -traits_t::CELLTYPE_MIN + i;
logoddsTable[idx] = f;
logoddsTable_255[idx] = (uint8_t)(f * 255.0f);
}
// Build the p2lTable as well:
p2lTable.resize(traits_t::P2LTABLE_SIZE + 1);
const double K = 1.0 / traits_t::P2LTABLE_SIZE;
for (int j = 0; j <= traits_t::P2LTABLE_SIZE; j++)
{
const double p = std::min(1.0 - 1e-14, std::max(1e-14, j * K));
const double logodd = log(p) - log(1 - p);
int L = round(logodd * LOGODD_K);
if (L > traits_t::CELLTYPE_MAX) L = traits_t::CELLTYPE_MAX;
else if (L < traits_t::CELLTYPE_MIN)
L = traits_t::CELLTYPE_MIN;
p2lTable[j] = L;
}
}
/** Scales an integer representation of the log-odd into a real valued
* probability in [0,1], using p=exp(l)/(1+exp(l))
*/
inline float l2p(const cell_t l)
{
if (l < traits_t::CELLTYPE_MIN)
// This is needed since min can be -127 and int8_t can be -128.
return logoddsTable[0];
else
return logoddsTable[-traits_t::CELLTYPE_MIN + l];
}
/** Scales an integer representation of the log-odd into a linear scale
* [0,255], using p=exp(l)/(1+exp(l))
*/
inline uint8_t l2p_255(const cell_t l)
{
if (l < traits_t::CELLTYPE_MIN)
// This is needed since min can be -127 and int8_t can be -128.
return logoddsTable_255[0];
else
return logoddsTable_255[-traits_t::CELLTYPE_MIN + l];
}
/** Scales a real valued probability in [0,1] to an integer representation
* of: log(p)-log(1-p) in the valid range of cell_t.
*/
inline cell_t p2l(const float p)
{
return p2lTable[static_cast<unsigned int>(p * traits_t::P2LTABLE_SIZE)];
}
};
} // namespace mrpt::maps
|
60822eba48cdf4eb2b426b13a9a39df35aa2d85e | dc07127e1ba90289a25b1479ec6bc4c791a7adca | /abpru/abpru/abprun.cpp | 14b4490e2559de780688cab6ca986b5e4c40271a | [] | no_license | s-nguyen/abpruning | bef0bfedce6c6a5b5e4d1c83eecf04cc1167133e | 56842891610d371be2f78c77de711fc3ea9948d9 | refs/heads/master | 2021-01-10T03:54:39.231970 | 2015-11-18T19:08:48 | 2015-11-18T19:08:48 | 45,885,526 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,660 | cpp | abprun.cpp | #include <iostream>
#include "Tictac.h"
using namespace std;
int main(int argc, char* argv[])
{
int moves = 0;
int state;
int depth;
int a = -2;
int b = 2;
int aTotal = 0;
int bTotal = 0;
int oldmoves = -1;
Tictac *t = new Tictac("Max");
if (argc != 2){
cout << "Usage: ./abpru startstate" << endl;
return -1;
}
t->ReadInput(argv[1]);
t->Expand();
depth = t->GetMaxLevel(t);
if (!t->GetDone())
{
state = t->MiniMax(t, depth, "Max", oldmoves);
}
moves = -1;
state = t->AlphaBeta(t, depth, a, b, "Max", moves, aTotal, bTotal, t->getCut());
t->PrintBoard2();
cout << argv[0] << " " << argv[1] << endl << endl;
cout << "Running without alpha-beta pruning" << endl;
cout << "Game Result: " << state << endl;
cout << "Moves considered without alpha-beta pruning: " << oldmoves << endl << endl;
cout << "------------------------------------------------" << endl << endl;
cout << "Running with alpha-beta pruning" << endl;
cout << "Game Result: " << state << endl;
cout << "Moves Considered with alpha-beta pruning: " << moves << endl;
cout << "Alpha cuts: " << aTotal << endl;
cout << "Beta cuts: " << bTotal << endl;
cout << endl;
cout << "------------------------------------------------" << endl << endl;
moves = -1;
a = -2;
b = 2;
aTotal = 0;
bTotal = 0;
state = t->Killer(t, depth, a, b, "Max", moves, aTotal, bTotal);
cout << "Running with Killer Heuristic" << endl;
cout << "Game Result: " << state << endl;
cout << "Moves Considered with alpha-beta pruning: " << moves << endl;
cout << "Alpha cuts: " << aTotal << endl;
cout << "Beta cuts: " << bTotal << endl;
cout << endl;
return 0;
} |
cbb269f295cb2e4a044eaab6d4ff1459f41d3639 | 7cc9f9f4beb2af797635be0845f59b149adfb5cd | /Rules.h | 1d0d66e82f756f7d8271c081d8302245499f75ad | [] | no_license | Ashaman47/CS236 | a8ae6d1e6cbb11fe051a2c7c6f2be2c8774e7bb8 | deb226398b7b7f874e1c28d55a439427c820f285 | refs/heads/master | 2022-04-08T20:10:33.307260 | 2020-03-10T16:01:51 | 2020-03-10T16:01:51 | 236,593,709 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 380 | h | Rules.h | #pragma once
#include "Predicate.h"
#include <vector>
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
using namespace std;
class Rules{
public:
Rules(){};
Rules(Predicate p);
string currentTokenList;
string toString();
Predicate Pred;
vector<Predicate>PredList;
void addRule(Predicate Pred);
Predicate getPred();
}; |
e344f8deb9c1189e5e00ab715ca201f7b7c2611f | 9125703b79eff7d9fc6a54d287992db53859758d | /main.cc | 7e9fa064dd716df939f7e5d9d1abc52d6e74a207 | [] | no_license | Bklayman/Sidequest-Tracker | 6bd75f252ed1f374bc38051338967ca053e88dad | 17e779fcb5d2d8528fe81325805398bbdd670c77 | refs/heads/master | 2022-10-09T04:19:07.091518 | 2020-06-12T18:36:36 | 2020-06-12T18:36:36 | 262,599,366 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,738 | cc | main.cc | #include <iostream>
#include <fstream>
#include <locale>
#include <sstream>
#include <string>
#include <vector>
#include "load.hh"
#include "quest.hh"
#include "questList.hh"
#include "questMenu.hh"
#include "save.hh"
//Prints a list of the possible actions to take in the main menu
void help(){
std::cout << "List of actions:\n\thelp / h: Get this list\n\texit / e: Exit this program (does not save progress)\n\tsave / s: Go to save menu\n\tstory / st: Go to story point menu\n\tquest / q: Go to quest menu\n\tprint / p: Go to print menu" << std::endl;
}
//Checks the answer when selecting actions in the story point menu
int checkStoryPointAction(std::string action){
if(action == "1"){
return 1;
} else if (action == "2"){
return 2;
} else if (action == "3"){
return 3;
}
return -1;
}
//Checks the answer when selecting a story point
int checkStoryPointChoice(std::string answer, int numStoryPoints){
int answerNum = 0;
try{
answerNum = std::stoi(answer);
} catch(std::exception& e){
std::cout << "Invalid answer." << std::endl;
return -1;
}
if(answerNum >= numStoryPoints){
std::cout << "Invalid answer." << std::endl;
return -1;
}
return answerNum;
}
//Gives a menu for story point modification
void storyPointMenu(QuestList* quests){
bool done = false;
while(!done){
std::cout << "Would you like to pass a story point (1), bring back a story point (2), or exit this menu (3)?" << std::endl;
std::string answer;
std::cin >> answer;
int actionNum = checkStoryPointAction(answer);
if(actionNum == -1){
std::cout << "Invalid response." << std::endl;
} else if (actionNum == 3){
done = !done;
} else if (actionNum == 2){
std::cout << "Which story point do you want to bring back? (Enter the number of the desired point or -1 to exit)\nAny story point after the chosen point will also be passed." << std::endl;
quests->printStoryPointsGarbage();
std::cin >> answer;
int storyPointGarbageSize = quests->getStoryPointGarbageSize();
int answerNum = checkStoryPointChoice(answer, storyPointGarbageSize);
if(answerNum != -1){
quests->reuseStoryPoint(answerNum);
}
} else {
std::cout << "Which story point do you want to pass? (Enter the number of the desired point or -1 to exit)\nAny story point before the chosen point will also be passed." << std::endl;
quests->printStoryPoints();
std::cin >> answer;
int numStoryPoints = quests->getStoryPointsSize();
int answerNum = checkStoryPointChoice(answer, numStoryPoints);
if(answerNum != -1){
quests->removeStoryPoint(answerNum);
}
}
if(!done){
std::cout << "Are you done moving story points? (yes/no)" << std::endl;
std::cin >> answer;
if(answer == "yes"){
done = !done;
} else if (answer != "no"){
std::cout << "Invalid answer." << std::endl;
}
}
}
}
//Asks the user what to print
void printMenu(QuestList* quests){
bool donePrinting = false;
while(!donePrinting){
std::cout << "Would you like to print all quest information (1) or only one information category (2)?" << std::endl;
std::string answer;
std::cin >> answer;
if(answer == "1"){
quests->printOpen();
} else if(answer == "2"){
std::cout << "What category would you like to print by?" << std::endl;
std::cin >> answer;
quests->printCategory(answer);
} else {
std::cout << "That is not an accepted input." << std::endl;
}
std::cout << "Would you like to return to the main menu? (yes/no)" << std::endl;
std::cin >> answer;
if(answer == "yes"){
donePrinting = !donePrinting;
}
}
}
//Executes the action desired from the main menu
bool takeAction(int code, QuestList* quests){
switch(code){
case -1:
std::cout << "Invalid action. Use help or h for a list of actions." << std::endl;
break;
case 1:
help();
break;
case 2:
return true;
case 3:
Save::saveMenu(quests);
break;
case 4:
storyPointMenu(quests);
break;
case 5:
QuestMenu::questMenu(quests);
break;
case 6:
printMenu(quests);
break;
default:
std::cout << "Error: Invalid action code given." << std::endl;
break;
}
return false;
}
//Checks to see if a given action at the main menu associates with a possible action (not case sensitive). Returns -1 if none are found.
//All codes should be self-explainable
int checkActions(std::string caseAction){
std::locale loc;
std::string action;
for(std::string::size_type i = 0; i < caseAction.length(); i++){
action += std::tolower(caseAction[i], loc);
}
if(action == "help" || action == "h"){
return 1;
}
if(action == "exit" || action == "e"){
return 2;
}
if(action == "save" || action == "s"){
return 3;
}
if(action == "story" || action == "st"){
return 4;
}
if(action == "quest" || action == "q"){
return 5;
}
if(action == "print" || action == "p"){
return 6;
}
return -1;
}
int main(int argc, char** argv){
if(argc != 2){
std::cout << "Usage: ./main [Base .txt file / Saved .txt file]" << std::endl;
exit(0);
}
//Checks whether this is a save or base .txt file
std::ifstream file;
file.open(argv[1]);
if(!file.is_open()){
std::cout << "ERROR: File " << argv[1] << " does not exist." << std::endl;
exit(1);
}
std::string fileLine;
std::string fileInfo = "";
while(file >> fileLine){
fileLine = Load::trim(fileLine);
fileInfo = fileInfo + fileLine;
}
bool base = true;
if(fileInfo.find("..+!L") != -1 || fileInfo.find("..+!A") != -1 || fileInfo.find("..+!W") != -1 || fileInfo.find("..+!B") != -1 || fileInfo.find("..+!U") != -1 || fileInfo.find("..-!Y") != -1 || fileInfo.find("..*!S") != -1 || fileInfo.find("..*!D") != -1){
base = false;
}
int isBase = 0;
if(base){
isBase = 1;
}
file.close();
std::string answer;
//Loads the file and uses the main menu to get user input and execute that input.
QuestList* quests = Load::getQuestList(argv[1], isBase);
bool wantExit = false;
while(!wantExit){
std::cout << "Enter what action you would like to take (type 'help' or 'h' for help)" << std::endl;
std::cin >> answer;
int actionCode = checkActions(answer);
wantExit = takeAction(actionCode, quests);
}
std::vector<Quest*> questList = quests->getQuests();
std::vector<Quest*> garbageList = quests->getQuestGarbage();
for(int i = 0; i < questList.size(); i++){
delete questList[i];
}
for(int i = 0; i < garbageList.size(); i++){
delete garbageList[i];
}
delete quests;
}
|
1b2b77ab1c05e045d7ee88a3accb8d546a0d6b3d | c7ddaad7fa061218d1e547a974fc6a7853e69c7a | /chrome/browser/autofill/billing_address_unittest.cc | 98d62f01f5a2dd28fedad428715243cab1b279f3 | [
"BSD-3-Clause"
] | permissive | cha63506/chromium-29 | 9adcc9ba819ced9dfe1f5da4807ad10516896142 | 9df275a67dc9038e300bfcad34f634b20dc9e8bc | HEAD | 2017-05-27T06:59:00.183474 | 2011-05-03T04:06:05 | 2011-05-03T04:06:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 29,662 | cc | billing_address_unittest.cc | // Copyright (c) 2010 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 <vector>
#include "base/basictypes.h"
#include "base/scoped_ptr.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/autofill/address.h"
#include "chrome/browser/autofill/billing_address.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
class BillingAddressTest : public testing::Test {
public:
BillingAddressTest() {
address_.SetInfo(AutoFillType(ADDRESS_BILLING_LINE1),
ASCIIToUTF16("123 Appian Way"));
address_.SetInfo(AutoFillType(ADDRESS_BILLING_LINE2),
ASCIIToUTF16("Unit 6"));
address_.SetInfo(AutoFillType(ADDRESS_BILLING_APT_NUM), ASCIIToUTF16("#6"));
address_.SetInfo(AutoFillType(ADDRESS_BILLING_CITY), ASCIIToUTF16("Paris"));
address_.SetInfo(AutoFillType(ADDRESS_BILLING_STATE),
ASCIIToUTF16("Texas"));
address_.SetInfo(AutoFillType(ADDRESS_BILLING_ZIP), ASCIIToUTF16("12345"));
address_.SetInfo(AutoFillType(ADDRESS_BILLING_COUNTRY),
ASCIIToUTF16("USA"));
}
protected:
BillingAddress address_;
DISALLOW_COPY_AND_ASSIGN(BillingAddressTest);
};
TEST_F(BillingAddressTest, GetPossibleFieldTypes) {
// Empty string.
FieldTypeSet possible_types;
address_.GetPossibleFieldTypes(string16(), &possible_types);
ASSERT_EQ(0U, possible_types.size());
// Only use split-chars for the address_.
possible_types.clear();
address_.GetPossibleFieldTypes(ASCIIToUTF16("-,#. "), &possible_types);
ASSERT_EQ(0U, possible_types.size());
// ADDRESS_BILLING_LINE1 =====================================================
// Exact match.
possible_types.clear();
address_.GetPossibleFieldTypes(ASCIIToUTF16("123 Appian Way"),
&possible_types);
ASSERT_EQ(1U, possible_types.size());
EXPECT_TRUE(possible_types.find(ADDRESS_BILLING_LINE1) !=
possible_types.end());
// Fields are mixed up.
possible_types.clear();
address_.GetPossibleFieldTypes(ASCIIToUTF16("Way 123 Appian"),
&possible_types);
ASSERT_EQ(1U, possible_types.size());
EXPECT_TRUE(possible_types.find(ADDRESS_BILLING_LINE1) !=
possible_types.end());
// The match is case-insensitive.
possible_types.clear();
address_.GetPossibleFieldTypes(ASCIIToUTF16("123 aPPiaN wAy"),
&possible_types);
ASSERT_EQ(1U, possible_types.size());
EXPECT_TRUE(possible_types.find(ADDRESS_BILLING_LINE1) !=
possible_types.end());
// Case-insensitive match with fields mixed up. The previous test doesn't
// do a good job of testing for case-insensitivity because the underlying
// algorithm stops search when it matches '123'.
possible_types.clear();
address_.GetPossibleFieldTypes(ASCIIToUTF16("wAy aPpIAn"), &possible_types);
ASSERT_EQ(1U, possible_types.size());
EXPECT_TRUE(possible_types.find(ADDRESS_BILLING_LINE1) !=
possible_types.end());
// The text is not complete.
possible_types.clear();
address_.GetPossibleFieldTypes(ASCIIToUTF16("123 Appian"), &possible_types);
ASSERT_EQ(1U, possible_types.size());
EXPECT_TRUE(possible_types.find(ADDRESS_BILLING_LINE1) !=
possible_types.end());
// Extra text on the line.
possible_types.clear();
address_.GetPossibleFieldTypes(ASCIIToUTF16("123 Appian Way #6"),
&possible_types);
ASSERT_EQ(0U, possible_types.size());
// Extra text in the middle
possible_types.clear();
address_.GetPossibleFieldTypes(ASCIIToUTF16("123 Middle Appian Way"),
&possible_types);
ASSERT_EQ(0U, possible_types.size());
// Whitespace doesn't matter.
possible_types.clear();
address_.GetPossibleFieldTypes(ASCIIToUTF16(" 123 Appian Way "),
&possible_types);
ASSERT_EQ(1U, possible_types.size());
EXPECT_TRUE(possible_types.find(ADDRESS_BILLING_LINE1) !=
possible_types.end());
// Address split characters don't matter.
possible_types.clear();
address_.GetPossibleFieldTypes(ASCIIToUTF16("-123, #Appian.Way"),
&possible_types);
ASSERT_EQ(1U, possible_types.size());
EXPECT_TRUE(possible_types.find(ADDRESS_BILLING_LINE1) !=
possible_types.end());
// ADDRESS_BILLING_LINE2 =====================================================
// Exact match.
possible_types.clear();
address_.GetPossibleFieldTypes(ASCIIToUTF16("Unit 6"), &possible_types);
ASSERT_EQ(1U, possible_types.size());
EXPECT_TRUE(possible_types.find(ADDRESS_BILLING_LINE2) !=
possible_types.end());
// Fields are mixed up.
possible_types.clear();
address_.GetPossibleFieldTypes(ASCIIToUTF16("6 Unit"), &possible_types);
ASSERT_EQ(1U, possible_types.size());
EXPECT_TRUE(possible_types.find(ADDRESS_BILLING_LINE2) !=
possible_types.end());
// The match is case-insensitive.
possible_types.clear();
address_.GetPossibleFieldTypes(ASCIIToUTF16("uNiT 6"), &possible_types);
ASSERT_EQ(1U, possible_types.size());
EXPECT_TRUE(possible_types.find(ADDRESS_BILLING_LINE2) !=
possible_types.end());
// The text is not complete.
possible_types.clear();
address_.GetPossibleFieldTypes(ASCIIToUTF16("Unit"), &possible_types);
ASSERT_EQ(1U, possible_types.size());
EXPECT_TRUE(possible_types.find(ADDRESS_BILLING_LINE2) !=
possible_types.end());
// Extra text on the line.
possible_types.clear();
address_.GetPossibleFieldTypes(ASCIIToUTF16("Unit 6 Extra"), &possible_types);
ASSERT_EQ(0U, possible_types.size());
// Extra text in the middle
possible_types.clear();
address_.GetPossibleFieldTypes(ASCIIToUTF16("Unit Middle 6"),
&possible_types);
ASSERT_EQ(0U, possible_types.size());
// Whitespace doesn't matter.
possible_types.clear();
address_.GetPossibleFieldTypes(ASCIIToUTF16(" Unit 6 "), &possible_types);
ASSERT_EQ(1U, possible_types.size());
EXPECT_TRUE(possible_types.find(ADDRESS_BILLING_LINE2) !=
possible_types.end());
// Address split characters don't matter.
possible_types.clear();
address_.GetPossibleFieldTypes(ASCIIToUTF16("-#Unit, .6"),
&possible_types);
ASSERT_EQ(1U, possible_types.size());
EXPECT_TRUE(possible_types.find(ADDRESS_BILLING_LINE2) !=
possible_types.end());
// ADDRESS_BILLING_APT_NUM ===================================================
// Exact match. This matches the apartment number exactly, and also matches
// 'Unit 6' because of the 6 and the fact that '#' is an address separator,
// which is ignored in the search for an address line.
possible_types.clear();
address_.GetPossibleFieldTypes(ASCIIToUTF16("#6"), &possible_types);
ASSERT_EQ(2U, possible_types.size());
EXPECT_TRUE(possible_types.find(ADDRESS_BILLING_APT_NUM) !=
possible_types.end());
EXPECT_TRUE(possible_types.find(ADDRESS_BILLING_LINE2) !=
possible_types.end());
// The match is case-insensitive.
possible_types.clear();
address_.SetInfo(AutoFillType(ADDRESS_BILLING_APT_NUM),
ASCIIToUTF16("Num 10"));
address_.GetPossibleFieldTypes(ASCIIToUTF16("nuM 10"), &possible_types);
ASSERT_EQ(1U, possible_types.size());
EXPECT_TRUE(possible_types.find(ADDRESS_BILLING_APT_NUM) !=
possible_types.end());
// The text is not complete.
possible_types.clear();
address_.GetPossibleFieldTypes(ASCIIToUTF16("Num"), &possible_types);
ASSERT_EQ(0U, possible_types.size());
// Extra text on the line.
possible_types.clear();
address_.GetPossibleFieldTypes(ASCIIToUTF16("Num 10 More"), &possible_types);
ASSERT_EQ(0U, possible_types.size());
// Extra text in the middle
possible_types.clear();
address_.GetPossibleFieldTypes(ASCIIToUTF16("Num Middle 10"),
&possible_types);
ASSERT_EQ(0U, possible_types.size());
// Whitespace does matter for apartment number.
possible_types.clear();
address_.GetPossibleFieldTypes(ASCIIToUTF16(" Num 10 "), &possible_types);
ASSERT_EQ(0U, possible_types.size());
// ADDRESS_BILLING_CITY ======================================================
// Exact match.
possible_types.clear();
address_.GetPossibleFieldTypes(ASCIIToUTF16("Paris"), &possible_types);
ASSERT_EQ(1U, possible_types.size());
EXPECT_TRUE(possible_types.find(ADDRESS_BILLING_CITY) !=
possible_types.end());
// The match is case-insensitive.
possible_types.clear();
address_.GetPossibleFieldTypes(ASCIIToUTF16("pARiS"), &possible_types);
ASSERT_EQ(1U, possible_types.size());
EXPECT_TRUE(possible_types.find(ADDRESS_BILLING_CITY) !=
possible_types.end());
// The text is not complete.
possible_types.clear();
address_.GetPossibleFieldTypes(ASCIIToUTF16("Par"), &possible_types);
ASSERT_EQ(0U, possible_types.size());
// Extra text on the line.
possible_types.clear();
address_.GetPossibleFieldTypes(ASCIIToUTF16("Paris City"), &possible_types);
ASSERT_EQ(0U, possible_types.size());
// Whitespace does matter for apartment number.
possible_types.clear();
address_.GetPossibleFieldTypes(ASCIIToUTF16(" Paris "), &possible_types);
ASSERT_EQ(0U, possible_types.size());
// ADDRESS_BILLING_STATE =====================================================
// Exact match.
possible_types.clear();
address_.GetPossibleFieldTypes(ASCIIToUTF16("Texas"), &possible_types);
ASSERT_EQ(1U, possible_types.size());
EXPECT_TRUE(possible_types.find(ADDRESS_BILLING_STATE) !=
possible_types.end());
// The match is case-insensitive.
possible_types.clear();
address_.GetPossibleFieldTypes(ASCIIToUTF16("tExAs"), &possible_types);
ASSERT_EQ(1U, possible_types.size());
EXPECT_TRUE(possible_types.find(ADDRESS_BILLING_STATE) !=
possible_types.end());
// The text is not complete.
possible_types.clear();
address_.GetPossibleFieldTypes(ASCIIToUTF16("Tex"), &possible_types);
ASSERT_EQ(0U, possible_types.size());
// Extra text on the line.
possible_types.clear();
address_.GetPossibleFieldTypes(ASCIIToUTF16("Texas State"), &possible_types);
ASSERT_EQ(0U, possible_types.size());
// Whitespace does matter for apartment number.
possible_types.clear();
address_.GetPossibleFieldTypes(ASCIIToUTF16(" Texas "), &possible_types);
ASSERT_EQ(0U, possible_types.size());
// ADDRESS_BILLING_COUNTRY ===================================================
// Exact match.
possible_types.clear();
address_.GetPossibleFieldTypes(ASCIIToUTF16("USA"), &possible_types);
ASSERT_EQ(1U, possible_types.size());
EXPECT_TRUE(possible_types.find(ADDRESS_BILLING_COUNTRY) !=
possible_types.end());
// The match is case-insensitive.
possible_types.clear();
address_.GetPossibleFieldTypes(ASCIIToUTF16("uSa"), &possible_types);
ASSERT_EQ(1U, possible_types.size());
EXPECT_TRUE(possible_types.find(ADDRESS_BILLING_COUNTRY) !=
possible_types.end());
// The text is not complete.
possible_types.clear();
address_.GetPossibleFieldTypes(ASCIIToUTF16("US"), &possible_types);
ASSERT_EQ(0U, possible_types.size());
// Extra text on the line.
possible_types.clear();
address_.GetPossibleFieldTypes(ASCIIToUTF16("US Country"), &possible_types);
ASSERT_EQ(0U, possible_types.size());
// Whitespace does matter for apartment number.
possible_types.clear();
address_.GetPossibleFieldTypes(ASCIIToUTF16(" US "), &possible_types);
ASSERT_EQ(0U, possible_types.size());
// ADDRESS_BILLING_ZIP =======================================================
// Exact match.
possible_types.clear();
address_.GetPossibleFieldTypes(ASCIIToUTF16("12345"), &possible_types);
ASSERT_EQ(1U, possible_types.size());
EXPECT_TRUE(possible_types.find(ADDRESS_BILLING_ZIP) !=
possible_types.end());
// The text is not complete.
possible_types.clear();
address_.GetPossibleFieldTypes(ASCIIToUTF16("1234"), &possible_types);
ASSERT_EQ(0U, possible_types.size());
// Extra text on the line.
possible_types.clear();
address_.GetPossibleFieldTypes(ASCIIToUTF16("12345 678"), &possible_types);
ASSERT_EQ(0U, possible_types.size());
// Whitespace does matter for apartment number.
possible_types.clear();
address_.GetPossibleFieldTypes(ASCIIToUTF16(" 12345 "), &possible_types);
ASSERT_EQ(0U, possible_types.size());
// Misc ======================================================================
// More than one type can match.
address_.SetInfo(AutoFillType(ADDRESS_BILLING_LINE1), ASCIIToUTF16("Same"));
address_.SetInfo(AutoFillType(ADDRESS_BILLING_LINE2), ASCIIToUTF16("Same"));
address_.SetInfo(AutoFillType(ADDRESS_BILLING_APT_NUM), ASCIIToUTF16("Same"));
possible_types.clear();
address_.GetPossibleFieldTypes(ASCIIToUTF16("Same"), &possible_types);
ASSERT_EQ(3U, possible_types.size());
EXPECT_TRUE(possible_types.find(ADDRESS_BILLING_LINE1) !=
possible_types.end());
EXPECT_TRUE(possible_types.find(ADDRESS_BILLING_LINE2) !=
possible_types.end());
EXPECT_TRUE(possible_types.find(ADDRESS_BILLING_APT_NUM) !=
possible_types.end());
// LINE1 is empty.
address_.SetInfo(AutoFillType(ADDRESS_BILLING_LINE1), string16());
possible_types.clear();
address_.GetPossibleFieldTypes(string16(), &possible_types);
ASSERT_EQ(0U, possible_types.size());
}
TEST_F(BillingAddressTest, FindInfoMatches) {
// ADDRESS_BILLING_LINE1 =====================================================
// Match the beginning of the string.
std::vector<string16> matches;
address_.FindInfoMatches(
AutoFillType(ADDRESS_BILLING_LINE1), ASCIIToUTF16("123"), &matches);
ASSERT_EQ(1U, matches.size());
EXPECT_EQ(ASCIIToUTF16("123 Appian Way"), matches[0]);
// Search has too many characters.
matches.clear();
address_.FindInfoMatches(
AutoFillType(ADDRESS_BILLING_LINE1), ASCIIToUTF16("123 B"), &matches);
ASSERT_EQ(0U, matches.size());
// Whitespace at the beginning of the search.
matches.clear();
address_.FindInfoMatches(
AutoFillType(ADDRESS_BILLING_LINE1), ASCIIToUTF16(" 123"), &matches);
ASSERT_EQ(0U, matches.size());
// Search includes the entire match, but adds extra characters.
matches.clear();
address_.FindInfoMatches(AutoFillType(ADDRESS_BILLING_LINE1),
ASCIIToUTF16("123 Appian Way B"),
&matches);
ASSERT_EQ(0U, matches.size());
// Matching is case-insensitive.
matches.clear();
address_.FindInfoMatches(AutoFillType(ADDRESS_BILLING_LINE1),
ASCIIToUTF16("123 aPpiAN wAy"),
&matches);
ASSERT_EQ(1U, matches.size());
EXPECT_EQ(ASCIIToUTF16("123 Appian Way"), matches[0]);
// Search is empty.
matches.clear();
address_.FindInfoMatches(
AutoFillType(ADDRESS_BILLING_LINE1), string16(), &matches);
ASSERT_EQ(1U, matches.size());
EXPECT_EQ(ASCIIToUTF16("123 Appian Way"), matches[0]);
// ADDRESS_BILLING_LINE2 =====================================================
// Match the beginning of the string.
matches.clear();
address_.FindInfoMatches(
AutoFillType(ADDRESS_BILLING_LINE2), ASCIIToUTF16("Unit"), &matches);
ASSERT_EQ(1U, matches.size());
EXPECT_EQ(ASCIIToUTF16("Unit 6"), matches[0]);
// Search has too many characters.
matches.clear();
address_.FindInfoMatches(
AutoFillType(ADDRESS_BILLING_LINE2), ASCIIToUTF16("Unita"), &matches);
ASSERT_EQ(0U, matches.size());
// Whitespace at the beginning of the search.
matches.clear();
address_.FindInfoMatches(
AutoFillType(ADDRESS_BILLING_LINE2), ASCIIToUTF16(" Unit"), &matches);
ASSERT_EQ(0U, matches.size());
// Search includes the entire match, but adds extra characters.
matches.clear();
address_.FindInfoMatches(
AutoFillType(ADDRESS_BILLING_LINE2), ASCIIToUTF16("Unit 6B"), &matches);
ASSERT_EQ(0U, matches.size());
// Matching is case-insensitive.
matches.clear();
address_.FindInfoMatches(
AutoFillType(ADDRESS_BILLING_LINE2), ASCIIToUTF16("uNiT 6"), &matches);
ASSERT_EQ(1U, matches.size());
EXPECT_EQ(ASCIIToUTF16("Unit 6"), matches[0]);
// Search is empty.
matches.clear();
address_.FindInfoMatches(
AutoFillType(ADDRESS_BILLING_LINE2), string16(), &matches);
ASSERT_EQ(1U, matches.size());
EXPECT_EQ(ASCIIToUTF16("Unit 6"), matches[0]);
// ADDRESS_BILLING_APT_NUM ===================================================
// Match the beginning of the string.
matches.clear();
address_.FindInfoMatches(
AutoFillType(ADDRESS_BILLING_APT_NUM), ASCIIToUTF16("#"), &matches);
ASSERT_EQ(1U, matches.size());
EXPECT_EQ(ASCIIToUTF16("#6"), matches[0]);
// Search has too many characters.
matches.clear();
address_.FindInfoMatches(
AutoFillType(ADDRESS_BILLING_APT_NUM), ASCIIToUTF16("#a"), &matches);
ASSERT_EQ(0U, matches.size());
// Whitespace at the beginning of the search.
matches.clear();
address_.FindInfoMatches(
AutoFillType(ADDRESS_BILLING_APT_NUM), ASCIIToUTF16(" #"), &matches);
ASSERT_EQ(0U, matches.size());
// Search includes the entire match, but adds extra characters.
matches.clear();
address_.FindInfoMatches(
AutoFillType(ADDRESS_BILLING_APT_NUM), ASCIIToUTF16("#6B"), &matches);
ASSERT_EQ(0U, matches.size());
// Matching is case-insensitive.
matches.clear();
address_.SetInfo(AutoFillType(ADDRESS_BILLING_APT_NUM), ASCIIToUTF16("6B"));
address_.FindInfoMatches(
AutoFillType(ADDRESS_BILLING_APT_NUM), ASCIIToUTF16("6b"), &matches);
ASSERT_EQ(1U, matches.size());
EXPECT_EQ(ASCIIToUTF16("6B"), matches[0]);
// Search is empty.
matches.clear();
address_.FindInfoMatches(
AutoFillType(ADDRESS_BILLING_APT_NUM), string16(), &matches);
ASSERT_EQ(1U, matches.size());
EXPECT_EQ(ASCIIToUTF16("6B"), matches[0]);
// ADDRESS_BILLING_CITY ======================================================
// Match the beginning of the string.
matches.clear();
address_.FindInfoMatches(
AutoFillType(ADDRESS_BILLING_CITY), ASCIIToUTF16("Par"), &matches);
ASSERT_EQ(1U, matches.size());
EXPECT_EQ(ASCIIToUTF16("Paris"), matches[0]);
// Search has too many characters.
matches.clear();
address_.FindInfoMatches(
AutoFillType(ADDRESS_BILLING_CITY), ASCIIToUTF16("ParA"), &matches);
ASSERT_EQ(0U, matches.size());
// Whitespace at the beginning of the search.
matches.clear();
address_.FindInfoMatches(
AutoFillType(ADDRESS_BILLING_CITY), ASCIIToUTF16(" Paris"), &matches);
ASSERT_EQ(0U, matches.size());
// Search includes the entire match, but adds extra characters.
matches.clear();
address_.FindInfoMatches(
AutoFillType(ADDRESS_BILLING_CITY), ASCIIToUTF16("ParisB"), &matches);
ASSERT_EQ(0U, matches.size());
// Matching is case-insensitive.
matches.clear();
address_.FindInfoMatches(
AutoFillType(ADDRESS_BILLING_CITY), ASCIIToUTF16("PArIs"), &matches);
ASSERT_EQ(1U, matches.size());
EXPECT_EQ(ASCIIToUTF16("Paris"), matches[0]);
// Search is empty.
matches.clear();
address_.FindInfoMatches(
AutoFillType(ADDRESS_BILLING_CITY), string16(), &matches);
ASSERT_EQ(1U, matches.size());
EXPECT_EQ(ASCIIToUTF16("Paris"), matches[0]);
// ADDRESS_BILLING_STATE =====================================================
// Match the beginning of the string.
matches.clear();
address_.FindInfoMatches(
AutoFillType(ADDRESS_BILLING_STATE), ASCIIToUTF16("Tex"), &matches);
ASSERT_EQ(1U, matches.size());
EXPECT_EQ(ASCIIToUTF16("Texas"), matches[0]);
// Search has too many characters.
matches.clear();
address_.FindInfoMatches(
AutoFillType(ADDRESS_BILLING_STATE), ASCIIToUTF16("TexC"), &matches);
ASSERT_EQ(0U, matches.size());
// Whitespace at the beginning of the search.
matches.clear();
address_.FindInfoMatches(
AutoFillType(ADDRESS_BILLING_STATE), ASCIIToUTF16(" Texas"), &matches);
ASSERT_EQ(0U, matches.size());
// Search includes the entire match, but adds extra characters.
matches.clear();
address_.FindInfoMatches(
AutoFillType(ADDRESS_BILLING_STATE), ASCIIToUTF16("TexasB"), &matches);
ASSERT_EQ(0U, matches.size());
// Matching is case-insensitive.
matches.clear();
address_.FindInfoMatches(
AutoFillType(ADDRESS_BILLING_STATE), ASCIIToUTF16("TeXaS"), &matches);
ASSERT_EQ(1U, matches.size());
EXPECT_EQ(ASCIIToUTF16("Texas"), matches[0]);
// Search is empty.
matches.clear();
address_.FindInfoMatches(
AutoFillType(ADDRESS_BILLING_STATE), string16(), &matches);
ASSERT_EQ(1U, matches.size());
EXPECT_EQ(ASCIIToUTF16("Texas"), matches[0]);
// ADDRESS_BILLING_ZIP =======================================================
// Match the beginning of the string.
matches.clear();
address_.FindInfoMatches(
AutoFillType(ADDRESS_BILLING_ZIP), ASCIIToUTF16("123"), &matches);
ASSERT_EQ(1U, matches.size());
EXPECT_EQ(ASCIIToUTF16("12345"), matches[0]);
// Search has too many characters.
matches.clear();
address_.FindInfoMatches(
AutoFillType(ADDRESS_BILLING_ZIP), ASCIIToUTF16("123a"), &matches);
ASSERT_EQ(0U, matches.size());
// Whitespace at the beginning of the search.
matches.clear();
address_.FindInfoMatches(
AutoFillType(ADDRESS_BILLING_ZIP), ASCIIToUTF16(" 123"), &matches);
ASSERT_EQ(0U, matches.size());
// Search includes the entire match, but adds extra characters.
matches.clear();
address_.FindInfoMatches(
AutoFillType(ADDRESS_BILLING_ZIP), ASCIIToUTF16("123456"), &matches);
ASSERT_EQ(0U, matches.size());
// Matching is case-sensitive because we should only have numbers in the zip.
matches.clear();
address_.SetInfo(AutoFillType(ADDRESS_BILLING_ZIP), ASCIIToUTF16("12345A"));
address_.FindInfoMatches(
AutoFillType(ADDRESS_BILLING_ZIP), ASCIIToUTF16("12345a"), &matches);
ASSERT_EQ(0U, matches.size());
// Reset the zip code.
address_.SetInfo(AutoFillType(ADDRESS_BILLING_ZIP), ASCIIToUTF16("12345"));
// Search is empty.
matches.clear();
address_.FindInfoMatches(
AutoFillType(ADDRESS_BILLING_ZIP), string16(), &matches);
ASSERT_EQ(1U, matches.size());
EXPECT_EQ(ASCIIToUTF16("12345"), matches[0]);
// ADDRESS_BILLING_COUNTRY ===================================================
// Match the beginning of the string.
matches.clear();
address_.FindInfoMatches(
AutoFillType(ADDRESS_BILLING_COUNTRY), ASCIIToUTF16("US"), &matches);
ASSERT_EQ(1U, matches.size());
EXPECT_EQ(ASCIIToUTF16("USA"), matches[0]);
// Search has too many characters.
matches.clear();
address_.FindInfoMatches(
AutoFillType(ADDRESS_BILLING_COUNTRY), ASCIIToUTF16("USb"), &matches);
ASSERT_EQ(0U, matches.size());
// Whitespace at the beginning of the search.
matches.clear();
address_.FindInfoMatches(
AutoFillType(ADDRESS_BILLING_COUNTRY), ASCIIToUTF16(" US"), &matches);
ASSERT_EQ(0U, matches.size());
// Search includes the entire match, but adds extra characters.
matches.clear();
address_.FindInfoMatches(
AutoFillType(ADDRESS_BILLING_COUNTRY), ASCIIToUTF16("USAB"), &matches);
ASSERT_EQ(0U, matches.size());
// Matching is case-insensitive.
matches.clear();
address_.FindInfoMatches(
AutoFillType(ADDRESS_BILLING_COUNTRY), ASCIIToUTF16("uSa"), &matches);
ASSERT_EQ(1U, matches.size());
EXPECT_EQ(ASCIIToUTF16("USA"), matches[0]);
// Search is empty.
matches.clear();
address_.FindInfoMatches(
AutoFillType(ADDRESS_BILLING_COUNTRY), string16(), &matches);
ASSERT_EQ(1U, matches.size());
EXPECT_EQ(ASCIIToUTF16("USA"), matches[0]);
// Misc ======================================================================
// |type| is not handled by address_.
matches.clear();
address_.FindInfoMatches(
AutoFillType(NAME_FIRST), ASCIIToUTF16("USA"), &matches);
ASSERT_EQ(0U, matches.size());
// |type| is UNKNOWN_TYPE.
matches.clear();
address_.FindInfoMatches(
AutoFillType(UNKNOWN_TYPE), ASCIIToUTF16("123"), &matches);
ASSERT_EQ(2U, matches.size());
EXPECT_EQ(ASCIIToUTF16("123 Appian Way"), matches[0]);
EXPECT_EQ(ASCIIToUTF16("12345"), matches[1]);
// |type| is UNKNOWN_TYPE. Exclude zip because of extra space.
matches.clear();
address_.FindInfoMatches(
AutoFillType(UNKNOWN_TYPE), ASCIIToUTF16("123 "), &matches);
ASSERT_EQ(1U, matches.size());
EXPECT_EQ(ASCIIToUTF16("123 Appian Way"), matches[0]);
// |type| is UNKNOWN_TYPE. Search is empty.
matches.clear();
address_.FindInfoMatches(
AutoFillType(UNKNOWN_TYPE), string16(), &matches);
ASSERT_EQ(7U, matches.size());
EXPECT_EQ(ASCIIToUTF16("123 Appian Way"), matches[0]);
EXPECT_EQ(ASCIIToUTF16("Unit 6"), matches[1]);
EXPECT_EQ(ASCIIToUTF16("6B"), matches[2]);
EXPECT_EQ(ASCIIToUTF16("Paris"), matches[3]);
EXPECT_EQ(ASCIIToUTF16("Texas"), matches[4]);
EXPECT_EQ(ASCIIToUTF16("12345"), matches[5]);
EXPECT_EQ(ASCIIToUTF16("USA"), matches[6]);
}
TEST_F(BillingAddressTest, GetFieldText) {
// Get the field text.
string16 text;
text = address_.GetFieldText(AutoFillType(ADDRESS_BILLING_LINE1));
EXPECT_EQ(ASCIIToUTF16("123 Appian Way"), text);
text = address_.GetFieldText(AutoFillType(ADDRESS_BILLING_LINE2));
EXPECT_EQ(ASCIIToUTF16("Unit 6"), text);
text = address_.GetFieldText(AutoFillType(ADDRESS_BILLING_APT_NUM));
EXPECT_EQ(ASCIIToUTF16("#6"), text);
text = address_.GetFieldText(AutoFillType(ADDRESS_BILLING_CITY));
EXPECT_EQ(ASCIIToUTF16("Paris"), text);
text = address_.GetFieldText(AutoFillType(ADDRESS_BILLING_STATE));
EXPECT_EQ(ASCIIToUTF16("Texas"), text);
text = address_.GetFieldText(AutoFillType(ADDRESS_BILLING_ZIP));
EXPECT_EQ(ASCIIToUTF16("12345"), text);
text = address_.GetFieldText(AutoFillType(ADDRESS_BILLING_COUNTRY));
EXPECT_EQ(ASCIIToUTF16("USA"), text);
// |type| is not supported by Billingaddress_.
text = address_.GetFieldText(AutoFillType(NAME_FIRST));
EXPECT_EQ(string16(), text);
}
TEST_F(BillingAddressTest, Clear) {
// Clear the info.
string16 text;
address_.Clear();
text = address_.GetFieldText(AutoFillType(ADDRESS_BILLING_LINE1));
EXPECT_EQ(string16(), text);
text = address_.GetFieldText(AutoFillType(ADDRESS_BILLING_LINE2));
EXPECT_EQ(string16(), text);
text = address_.GetFieldText(AutoFillType(ADDRESS_BILLING_APT_NUM));
EXPECT_EQ(string16(), text);
text = address_.GetFieldText(AutoFillType(ADDRESS_BILLING_CITY));
EXPECT_EQ(string16(), text);
text = address_.GetFieldText(AutoFillType(ADDRESS_BILLING_STATE));
EXPECT_EQ(string16(), text);
text = address_.GetFieldText(AutoFillType(ADDRESS_BILLING_ZIP));
EXPECT_EQ(string16(), text);
text = address_.GetFieldText(AutoFillType(ADDRESS_BILLING_COUNTRY));
EXPECT_EQ(string16(), text);
}
TEST_F(BillingAddressTest, AddressClone) {
// Clone the info.
string16 text;
BillingAddress clone;
Address* clone_ptr = &clone;
clone_ptr->Clone(address_);
text = clone.GetFieldText(AutoFillType(ADDRESS_BILLING_LINE1));
EXPECT_EQ(ASCIIToUTF16("123 Appian Way"), text);
text = clone.GetFieldText(AutoFillType(ADDRESS_BILLING_LINE2));
EXPECT_EQ(ASCIIToUTF16("Unit 6"), text);
text = clone.GetFieldText(AutoFillType(ADDRESS_BILLING_APT_NUM));
EXPECT_EQ(ASCIIToUTF16("#6"), text);
text = clone.GetFieldText(AutoFillType(ADDRESS_BILLING_CITY));
EXPECT_EQ(ASCIIToUTF16("Paris"), text);
text = clone.GetFieldText(AutoFillType(ADDRESS_BILLING_STATE));
EXPECT_EQ(ASCIIToUTF16("Texas"), text);
text = clone.GetFieldText(AutoFillType(ADDRESS_BILLING_ZIP));
EXPECT_EQ(ASCIIToUTF16("12345"), text);
text = clone.GetFieldText(AutoFillType(ADDRESS_BILLING_COUNTRY));
EXPECT_EQ(ASCIIToUTF16("USA"), text);
// Verify that the clone is a copy and not a reference.
address_.SetInfo(AutoFillType(ADDRESS_BILLING_LINE1),
ASCIIToUTF16("654 Bowling Terrace"));
text = clone.GetFieldText(AutoFillType(ADDRESS_BILLING_LINE1));
EXPECT_EQ(ASCIIToUTF16("123 Appian Way"), text);
}
TEST_F(BillingAddressTest, BillingAddressClone) {
// Clone the info.
string16 text;
scoped_ptr<FormGroup> clone(address_.Clone());
ASSERT_NE(static_cast<FormGroup*>(NULL), clone.get());
text = clone->GetFieldText(AutoFillType(ADDRESS_BILLING_LINE1));
EXPECT_EQ(ASCIIToUTF16("123 Appian Way"), text);
text = clone->GetFieldText(AutoFillType(ADDRESS_BILLING_LINE2));
EXPECT_EQ(ASCIIToUTF16("Unit 6"), text);
text = clone->GetFieldText(AutoFillType(ADDRESS_BILLING_APT_NUM));
EXPECT_EQ(ASCIIToUTF16("#6"), text);
text = clone->GetFieldText(AutoFillType(ADDRESS_BILLING_CITY));
EXPECT_EQ(ASCIIToUTF16("Paris"), text);
text = clone->GetFieldText(AutoFillType(ADDRESS_BILLING_STATE));
EXPECT_EQ(ASCIIToUTF16("Texas"), text);
text = clone->GetFieldText(AutoFillType(ADDRESS_BILLING_ZIP));
EXPECT_EQ(ASCIIToUTF16("12345"), text);
text = clone->GetFieldText(AutoFillType(ADDRESS_BILLING_COUNTRY));
EXPECT_EQ(ASCIIToUTF16("USA"), text);
// Verify that the clone is a copy and not a reference.
address_.SetInfo(AutoFillType(ADDRESS_BILLING_LINE1),
ASCIIToUTF16("654 Bowling Terrace"));
text = clone->GetFieldText(AutoFillType(ADDRESS_BILLING_LINE1));
EXPECT_EQ(ASCIIToUTF16("123 Appian Way"), text);
}
} // namespace
|
63c78daafc2923e973e43bbf8e4967e448251e41 | b4e8f3eb357023b114005d0fe29fe7218daa4c2d | /cmdholder.cpp | aef6be294c3e87cb8dd3f25d7cd5026f92ea9a9c | [] | no_license | SergeiGolovnich/YantarMonitor | c23342b5b4dd48a250baa357d6e690c9fdbc9876 | 2594dd1192d2d4568382a2efd5528aabe795fe19 | refs/heads/master | 2020-07-12T07:37:17.017236 | 2020-02-09T16:05:46 | 2020-02-09T16:05:46 | 204,756,111 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,196 | cpp | cmdholder.cpp | #include "cmdholder.h"
CmdHolder::CmdHolder(quint8 adress, CmdHolder::Function function):
deviceAdress(adress), func(function), startReg(0), regCount(0), data()
{
}
CmdHolder::CmdHolder(const CmdHolder &obj):
deviceAdress(obj.deviceAdress), func(obj.func),
startReg(obj.startReg), regCount(obj.regCount),
data(obj.data)
{
}
void CmdHolder::processResponse(const QByteArray &message)
{
//определение канала, по которому получено сообщение
QDataStream in(message);
in.device()->seek(2);
quint16 pi;//идентификатор протокола
in >> pi;
quint16 messLen;
in >> messLen;//последующая длина сообщения
//если идентификатор протокола pi == 0 и длина сообщения messLen == оставшемуся количеству байт в сообщении
if((pi == 0) && ((message.length() - 6) == messLen))
{//сообщение принято по TCP/IP
;//никаких действий не требуется
}else
{//сообщение по COM
in.device()->seek(0);//перемещаем курсор в начало
}
//считывание PDU
in >> deviceAdress;//адрес
quint8 f;
in >> f;//номер функции
func = (Function)f;
data.clear();//стирание существующих данных
if(f & 0x80)
{//ошибка
quint8 errorCode;
in >> errorCode;//номер ошибки
QDataStream dataStream(&data, QIODevice::WriteOnly);
dataStream << errorCode;//запись номера ошибки в блок данных
return;
}
if(func == ReadHoldingRegisters)//ответ на запрос чтения регистров
{
quint8 dataLen;
in >> dataLen;//длина последующих данных
QDataStream dataStream(&data, QIODevice::WriteOnly);
quint8 tempByte;
for(int i = 0; i < dataLen; ++i)
{
in >> tempByte;
dataStream << tempByte;
}
}else if(func == PresetMultipleRegisters)//ответ на запрос записи регистров
{
in >> startReg;//начальный адрес
in >> regCount;//длина записанных данных
}
//считывание контрольной суммы CRC для проверки сообщения на ошибки при передаче данных через последовательный порт
}
CmdHolder::~CmdHolder()
{
}
quint8 CmdHolder::getDeviceAdress() const
{
return deviceAdress;
}
void CmdHolder::setDeviceAdress(const quint8 &value)
{
deviceAdress = value;
}
CmdHolder::Function CmdHolder::getFunc() const
{
return func;
}
void CmdHolder::setFunc(const Function &value)
{
func = value;
}
quint16 CmdHolder::getStartReg() const
{
return startReg;
}
void CmdHolder::setStartReg(const quint16 &value)
{
startReg = value;
}
quint16 CmdHolder::getRegCount() const
{
return regCount;
}
void CmdHolder::setRegCount(const quint16 &value)
{
regCount = value;
}
QByteArray CmdHolder::getData() const
{
return data;
}
void CmdHolder::setData(const QByteArray &value)
{
data = value;
}
void CmdHolder::SwapUInt32(quint32 &num)
{
quint32 temp;
temp = num >> 16;//получение старшего слова
num = (num << 16) | temp;//смена слов местами
}
void CmdHolder::SwapFloat(float *num)
{
quint32 *floatInUint = (quint32 *)num;
SwapUInt32(*floatInUint);
}
quint16 CmdHolder::calcCRC16()
{
quint16 crc;
quint16 tempcrc = 0xFFFF;
const quint16 poly = 0xA001;//заданный полином
QByteArray::const_iterator ci;
for(ci = resultCommand.constBegin(); ci != resultCommand.constEnd(); ++ci)
{
tempcrc ^= (quint8)(*ci);
for(int i = 0; i < 8; ++i)
{
bool LSB = tempcrc & 1;
tempcrc >>= 1;
if(LSB) tempcrc ^= poly;
}
}
//байты контрольной суммы нужно поменять местами
crc = tempcrc;
crc <<= 8;
tempcrc >>= 8;
crc |= tempcrc;
return crc;
}
QByteArray CmdHolder::getQueryCommand(bool com)
{
resultCommand.clear();
QDataStream in(&resultCommand, QIODevice::WriteOnly);
//для передачи по TCP требуется свой заголовок сообщения MBAP
if(!com){
in << (quint16)0//Transaction Identifier
<< (quint16)0//Protocol Identifier = 0
<< (quint16)0;//длина последующего сообщения(пока не посчитана)
}
in << deviceAdress;//номер устройства(в сети ModBus по SerialPort)
//далее вставка Protocol Data Unit
in << (quint8)func;
//запрос имеет разное строение в зависимости от Функции
switch(func)
{
case ReadHoldingRegisters://чтение регистров
in << startReg << regCount;
break;
case PresetMultipleRegisters://запись регистров
in << startReg << regCount << (quint8)data.length();
//данные для записи в регистры устройства
if(!data.isEmpty())
{
QByteArray::const_iterator ci;
for(ci = data.constBegin(); ci != data.constEnd(); ++ci)
in << (quint8)(*ci);
}
break;
default:
//если задана неучтенная функция
break;
}
if(com)//расчет контрольной суммы для COM
in << calcCRC16();
else
{//запись длины сообщения в заголовок MBAP для TCP
quint16 len = 6;//длина в байтах
if(func == PresetMultipleRegisters)
{
len += (quint16)data.length() + 1;
}
in.device()->seek(4);
in << len;
}
return resultCommand;
}
|
0681df6ea606b69e950ccd5f64735b748f58746b | 5b072be2b68f3c7e7455ecaee82dbed25299b5b6 | /10_european and american/program10_european.cpp | ef401f92b06b07ae75fcb93d4be2f2f26b54ae68 | [] | no_license | yrz437396236/cpp_for_finance | 7e64425765b5fb007764e4f563658ac4f82d978e | 7371bd3433ad0c54ce8b4d757bab74221a9ea554 | refs/heads/master | 2020-05-16T16:08:52.957120 | 2019-04-24T05:09:58 | 2019-04-24T05:09:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,677 | cpp | program10_european.cpp | #include <iostream>
#include <iomanip>
#include <cmath>
#include <fstream>
#include <cstdlib>
#include "normdist.h" // this defines the normal distribution from Odegaard's files
using namespace std;
double up_factor, uptick_prob, risk_free_rate, strike_price, downtick_prob, notick_prob;
double initial_stock_price, expiration_time, volatility, R;
int no_of_divisions;
float max(float a, float b) {
return (b < a) ? a : b;
}
double option_price_put_black_scholes(const double& S, // spot price
const double& K, // Strike (exercise) price,
const double& r, // interest rate
const double& sigma, // volatility
const double& time) {
double time_sqrt = sqrt(time);
double d1 = (log(S / K) + r * time) / (sigma*time_sqrt) + 0.5*sigma*time_sqrt;
double d2 = d1 - (sigma*time_sqrt);
return K * exp(-r * time)*N(-d2) - S * N(-d1);
};
double option_price_call_black_scholes(const double& S, // spot (underlying) price
const double& K, // strike (exercise) price,
const double& r, // interest rate
const double& sigma, // volatility
const double& time) { // time to maturity
double time_sqrt = sqrt(time);
double d1 = (log(S / K) + r * time) / (sigma*time_sqrt) + 0.5*sigma*time_sqrt;
double d2 = d1 - (sigma*time_sqrt);
return S * N(d1) - K * exp(-r * time)*N(d2);
};
double N(const double& z) {
if (z > 6.0) { return 1.0; }; // this guards against overflow
if (z < -6.0) { return 0.0; };
double b1 = 0.31938153;
double b2 = -0.356563782;
double b3 = 1.781477937;
double b4 = -1.821255978;
double b5 = 1.330274429;
double p = 0.2316419;
double c2 = 0.3989423;
double a = fabs(z);
double t = 1.0 / (1.0 + a * p);
double b = c2 * exp((-z)*(z / 2.0));
double n = ((((b5*t + b4)*t + b3)*t + b2)*t + b1)*t;
n = 1.0 - b * n;
if (z < 0.0) n = 1.0 - n;
return n;
};
double european_call_option(int k, int i, double **memo) {
if (memo[k][i+k] != -1)
{
return memo[k][i+k];
}
else
{
if (k == no_of_divisions)
return max(0.0, (initial_stock_price*pow(up_factor, ((float)i))) - strike_price);
else
memo[k][i + k] = (((uptick_prob*european_call_option(k + 1, i + 1, memo)) +
(notick_prob*european_call_option(k + 1, i, memo)) +
(downtick_prob*european_call_option(k + 1, i - 1, memo))) / R);
return memo[k][i+k];
}
}
double european_put_option(int k, int i, double **memo) {
if (memo[k][i+k] != -1)
{
return memo[k][i+k];
}
else
{
if (k == no_of_divisions)
return max(0.0, strike_price - (initial_stock_price*pow(up_factor, ((float)i))));
else
memo[k][i+k] = (((uptick_prob*european_put_option(k + 1, i + 1, memo)) +
(notick_prob*european_put_option(k + 1, i, memo)) +
(downtick_prob*european_put_option(k + 1, i - 1, memo))) / R);
return memo[k][i+k];
}
}
int main(int argc, char* argv[])
{
clock_t start = clock();
//sscanf_s(argv[1], "%f", &expiration_time);
//sscanf_s(argv[2], "%d", &no_of_divisions);
//sscanf_s(argv[3], "%f", &risk_free_rate);
//sscanf_s(argv[4], "%f", &volatility);
//sscanf_s(argv[5], "%f", &initial_stock_price);
//sscanf_s(argv[6], "%f", &strike_price);
sscanf_s(argv[1], "%lf", &expiration_time);
sscanf_s(argv[2], "%d", &no_of_divisions);
sscanf_s(argv[3], "%lf", &risk_free_rate);
sscanf_s(argv[4], "%lf", &volatility);
sscanf_s(argv[5], "%lf", &initial_stock_price);
sscanf_s(argv[6], "%lf", &strike_price);
double **array1 = new double*[no_of_divisions+1];
for (int i = 0; i <= no_of_divisions; i++)
array1[i] = new double[2* no_of_divisions];
for (int i = 0; i <= no_of_divisions; i++)
for (int j = 0; j <= (2 * no_of_divisions - 1); j++)
{
array1[i][j] = -1;
}
double **array2 = new double*[no_of_divisions + 1];
for (int i = 0; i <= no_of_divisions; i++)
array2[i] = new double[2 * no_of_divisions];
for (int i = 0; i <= no_of_divisions; i++)
for (int j = 0; j <= (2 * no_of_divisions - 1); j++)
{
array2[i][j] = -1;
}
//pow(R,0.5) pow(up_factor, 0.5)
up_factor = exp(volatility*sqrt((2 * expiration_time) / ((double)no_of_divisions)));
R = exp(risk_free_rate*expiration_time / ((double)no_of_divisions));
uptick_prob = pow((sqrt(R) - (1 / (sqrt(up_factor)))) / ((sqrt(up_factor)) - (1 / (sqrt(up_factor)))), 2);
downtick_prob = pow((sqrt(up_factor) - (sqrt(R))) / ((sqrt(up_factor)) - (1 / (sqrt(up_factor)))), 2);
notick_prob = 1 - uptick_prob - downtick_prob;
cout << "(Memoized)Recursive Trinomial European Option Pricing" << endl;
cout << "Expiration Time (Years) = " << expiration_time << endl;
cout << "Number of Divisions = " << no_of_divisions << endl;
cout << "Risk Free Interest Rate = " << risk_free_rate << endl;
cout << "Volatility (%age of stock value) = " << volatility * 100 << endl;
cout << "Initial Stock Price = " << initial_stock_price << endl;
cout << "Strike Price = " << strike_price << endl;
cout << "--------------------------------------" << endl;
cout << "Up Factor = " << up_factor << endl;
cout << "Uptick Probability = " << uptick_prob << endl;
cout << "Downtick Probability = " << downtick_prob << endl;
cout << "Notick Probability = " << notick_prob << endl;
cout << "--------------------------------------" << endl;
double call_price = european_call_option(0, 0, array1);
cout << "Trinomial Price of an European Call Option = " << call_price << endl;
cout << "Call Price according to Black-Scholes = " <<
option_price_call_black_scholes(initial_stock_price, strike_price, risk_free_rate,
volatility, expiration_time) << endl;
cout << "--------------------------------------" << endl;
double put_price = european_put_option(0, 0, array2);
cout << "Trinomial Price of an European Put Option = " << put_price << endl;
cout << "Put Price according to Black-Scholes = " <<
option_price_put_black_scholes(initial_stock_price, strike_price, risk_free_rate,
volatility, expiration_time) << endl;
cout << "--------------------------------------" << endl;
cout << "Verifying Put-Call Parity: S+P-C = Kexp(-r*T)" << endl;
cout << initial_stock_price << " + " << put_price << " - " << call_price;
cout << " = " << strike_price << "exp(-" << risk_free_rate << " * " << expiration_time << ")" << endl;
cout << initial_stock_price + put_price - call_price << " = " << strike_price * exp(-risk_free_rate * expiration_time) << endl;
cout << "--------------------------------------" << endl;
clock_t end = clock();
cout << "It took " << (long double)(end - start) / CLOCKS_PER_SEC << " seconds to complete" << endl;
system("pause");
} |
7b660e1350feb902bf1667ba3626208f7efb88c0 | ba7e867b425823d530680945cf2ef97a4dfdaa18 | /compress.cpp | c3059b67084d878cbf5dd0dbb257906b4a474410 | [] | no_license | ejoa27/Huffman-Compression | 35003533bf85818f2eb852fea441fe381f9ed4de | cd36edb18490ef329f39494a3ce6b97cec4413a6 | refs/heads/master | 2023-03-15T05:15:07.403638 | 2014-06-28T20:39:32 | 2014-06-28T20:39:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,198 | cpp | compress.cpp | // Sergio Leon <seleon>, Michael Lee <mil039>
#include <iostream>
#include <fstream>
#include "HCTree.hpp"
using namespace std;
int main(int argc, char* argv[]) {
ifstream infile(argv[1], ios::binary); //Input file
ofstream outfile(argv[2], ios::binary); //Output file
string str; //String to input file
vector<int> freqs(256, 0); //Empty vector
HCTree tree; //Huffman code tree
int count = 0; //Amount to encode
BitInputStream bitIS(infile); //Input stream
//Exit if insufficent arguments
if(!infile || !outfile) {
cerr << "Insufficient arguments.\n" << endl;
return -1;
}
//Exit if invalid files
if(!infile.good() || !outfile.good()) return -1;
cout << "Reading from file \"" << argv[1] << "\"...";
//Send file to string
infile.seekg(0, ios::end);
str.reserve(infile.tellg());
infile.seekg(0, ios::beg);
str.assign((istreambuf_iterator<char>(infile)),
istreambuf_iterator<char>());
//Count frequency of each symbol
for(int i = 0; i < str.size(); i++) {
byte sym = str[i];
freqs[sym]++;
}
BitOutputStream bitOS(outfile); //Output stream
//Write header
for(int i = 0; i < freqs.size(); i++) {
bitOS.writeInt(freqs[i]);
if(freqs[i] > 0)
count++;
}
cout << "Building Huffman code tree... ";
//Build Huffman code tree
tree.build(freqs);
cout << "done.\nWriting to file \"" << argv[2] << "\"... ";
cout << "done.\nFound " << count << " unique symbols in input file of size "
<< infile.tellg() << " bytes.\n";
//Encode symbols to output file
for(int i = 0; i < str.size(); i++) {
//Exit loop if invalid files
if(!infile.good() || !outfile.good())
break;
tree.encode(str[i], bitOS);
}
outfile.seekp(0, ios_base::end);
cout << "Output file has size " << outfile.tellp() << " bytes.\n"
<< "Compression ratio: " << (double) outfile.tellp()/infile.tellg() << endl;
//Flush remaining bits in output stream
bitOS.flush();
//Close files
outfile.close();
infile.close();
}
|
2830aab743f686e4b1d644d580f58b4f2d18d42e | f1e99738f064cfbefe7487b88a0d098cab1f6b29 | /SD/code.ino | e245807226df6ee08e35aa52d035e7e4d6fa17b3 | [] | no_license | nhinojosa/SummerCamp2021 | 607f0ca58605c52a747c7be3eb2a74510f9667bc | b35db9a98fbf6d78a6b1226f10eca49c46923a5a | refs/heads/main | 2023-08-25T02:55:20.795069 | 2021-10-22T13:46:13 | 2021-10-22T13:46:13 | 375,058,184 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,706 | ino | code.ino | #include <LiquidCrystal_PCF8574.h>
const int LEFT_TRIG = 13;
const int FRONT_TRIG = 12;
const int RIGHT_TRIG = 11;
const int LEFT_ECHO = 10;
const int RIGHT_ECHO = 8;
const int FRONT_ECHO = 9;
LiquidCrystal_PCF8574 lcd(0x27); // set the LCD address to 0x27 for a 16 chars and 2 line display
void setup()
{
Serial.begin(9600);
pinMode(LEFT_TRIG,OUTPUT);
pinMode(RIGHT_TRIG,OUTPUT);
pinMode(FRONT_TRIG,OUTPUT);
pinMode(LEFT_ECHO, INPUT);
pinMode(RIGHT_ECHO, INPUT);
pinMode(FRONT_ECHO, INPUT);
lcd.setBacklight(255);
lcd.begin(16,2);
lcd.clear();
}
void loop()
{
lcd.setCursor(0, 0);
double left_distance = 100, right_distance = 100, front_distance = 100;
left_distance = ping(LEFT_TRIG, LEFT_ECHO);
right_distance = ping(RIGHT_TRIG, RIGHT_ECHO);
front_distance = ping(FRONT_TRIG, FRONT_ECHO);
if(left_distance < 3)
{
Serial.print("LEFT: ");
Serial.print(left_distance);
Serial.println();
lcd.print("Keep 6ft left!");
}
else if(right_distance < 3)
{
Serial.print("RIGHT: ");
Serial.print(right_distance);
Serial.println();
lcd.print("Keep 6ft right!");
}
else if(front_distance < 3)
{
Serial.print("FRONT: ");
Serial.print(front_distance);
Serial.println();
lcd.print("Keep 6ft front!");
}
else
{
Serial.println("Good Distance!");
lcd.print("Good Distance!");
}
delay(1000);
}
double ping(int TRIG, int ECHO)
{
double duration, in;
digitalWrite(TRIG, LOW);
delayMicroseconds(2);
digitalWrite(TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG, LOW);
duration = pulseIn(ECHO, HIGH);
in = duration / 74 / 2;
delay(100);
return in;
}
|
8229465c5f0fa2dfa3fe4558a62016ee32e6b5df | 6dff693c16bd231c827c9b93e0a8b0eb6e6b60ff | /BeautyFilter/mask/StickerLib/ksMatrix.cpp | ee54911328fe26e8cafb6df49457e8cab4e94143 | [] | no_license | genshengye/Archimage_Code | 7aa3a66e89d5bda6934b3dedd26ddab96f8340b4 | 55c3fa8f777ca97ceb838d4e95e00f279873e48f | refs/heads/master | 2022-11-05T03:27:41.591514 | 2019-07-03T10:41:24 | 2019-07-03T10:41:24 | 195,033,092 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,373 | cpp | ksMatrix.cpp | //
// ksMatrix.c
//
// Created by kesalin@gmail.com on 12-11-26.
// Copyright (c) 2012. http://blog.csdn.net/kesalin/. All rights reserved.
//
#include "ksMatrix.h"
#include <stdlib.h>
#include <string.h>
void * memcpy(void *, const void *, size_t);
void * memset(void *, int, size_t);
unsigned int ksNextPot(unsigned int n)
{
n--;
n |= n >> 1; n |= n >> 2;
n |= n >> 4; n |= n >> 8;
n |= n >> 16;
n++;
return n;
}
//
// Matrix math utility
//
void ksMatrixScale(ksMatrix4 * result, float sx, float sy, float sz)
{
result->m[0][0] *= sx;
result->m[0][1] *= sx;
result->m[0][2] *= sx;
result->m[0][3] *= sx;
result->m[1][0] *= sy;
result->m[1][1] *= sy;
result->m[1][2] *= sy;
result->m[1][3] *= sy;
result->m[2][0] *= sz;
result->m[2][1] *= sz;
result->m[2][2] *= sz;
result->m[2][3] *= sz;
}
void ksMatrixTranslate(ksMatrix4 * result, float tx, float ty, float tz)
{
ksMatrixLoadIdentity(result);
result->m[3][0] = tx;
result->m[3][1] = ty;
result->m[3][2] = tz;
}
ksMatrix4 ksMatrixRotate(float angle, float x, float y, float z)
{
ksMatrix4 rotMat;
rotMat.m[0][3] = 0.0f;
rotMat.m[1][3] = 0.0f;
rotMat.m[2][3] = 0.0f;
rotMat.m[3][0] = 0.0f;
rotMat.m[3][1] = 0.0f;
rotMat.m[3][2] = 0.0f;
rotMat.m[3][3] = 1.0f;
angle *= M_DEG2RAD;
float s = (float) sinf (angle);
float c = (float) cosf (angle);
if (1.0f == x && 0.0f == y && 0.0f == z) {
rotMat.m[1][1] = c; rotMat.m[2][2]= c;
rotMat.m[1][2] = s; rotMat.m[2][1] = -s;
rotMat.m[0][1] = 0; rotMat.m[0][2] = 0;
rotMat.m[1][0] = 0; rotMat.m[2][0] = 0;
rotMat.m[0][0] = 1;
} else if (0.0f == x && 1.0f == y && 0.0f == z) {
rotMat.m[0][0] = c; rotMat.m[2][2]= c;
rotMat.m[2][0] = s; rotMat.m[0][2] = -s;
rotMat.m[0][1] = 0; rotMat.m[1][0] = 0;
rotMat.m[1][2] = 0; rotMat.m[2][1] = 0;
rotMat.m[1][1] = 1;
} else if (0.0f == x && 0.0f == y && 1.0f == z) {
rotMat.m[0][0] = c; rotMat.m[1][1] = c;
rotMat.m[0][1] = s; rotMat.m[1][0] = -s;
rotMat.m[0][2] = 0; rotMat.m[1][2] = 0;
rotMat.m[2][0] = 0; rotMat.m[2][1] = 0;
rotMat.m[2][2]= 1;
} else {
float nc = 1.0f - c;
float xy = x * y;
float yz = y * z;
float zx = z * x;
float xs = x * s;
float ys = y * s;
float zs = z * s;
rotMat.m[0][0] = x*x*nc + c;
rotMat.m[1][0] = xy*nc - zs;
rotMat.m[2][0] = zx*nc + ys;
rotMat.m[0][1] = xy*nc + zs;
rotMat.m[1][1] = y*y*nc + c;
rotMat.m[2][1] = yz*nc - xs;
rotMat.m[0][2] = zx*nc - ys;
rotMat.m[1][2] = yz*nc + xs;
rotMat.m[2][2] = z*z*nc + c;
}
return rotMat;
}
void ksMatrixRotate(ksMatrix4 * result, float angle, float x, float y, float z)
{
ksMatrix4 rotMat;
rotMat.m[0][3] = 0.0f;
rotMat.m[1][3] = 0.0f;
rotMat.m[2][3] = 0.0f;
rotMat.m[3][0] = 0.0f;
rotMat.m[3][1] = 0.0f;
rotMat.m[3][2] = 0.0f;
rotMat.m[3][3] = 1.0f;
angle *= M_DEG2RAD;
float s = (float) sinf (angle);
float c = (float) cosf (angle);
if (1.0f == x && 0.0f == y && 0.0f == z) {
rotMat.m[1][1] = c; rotMat.m[2][2]= c;
rotMat.m[1][2] = s; rotMat.m[2][1] = -s;
rotMat.m[0][1] = 0; rotMat.m[0][2] = 0;
rotMat.m[1][0] = 0; rotMat.m[2][0] = 0;
rotMat.m[0][0] = 1;
} else if (0.0f == x && 1.0f == y && 0.0f == z) {
rotMat.m[0][0] = c; rotMat.m[2][2]= c;
rotMat.m[2][0] = s; rotMat.m[0][2] = -s;
rotMat.m[0][1] = 0; rotMat.m[1][0] = 0;
rotMat.m[1][2] = 0; rotMat.m[2][1] = 0;
rotMat.m[1][1] = 1;
} else if (0.0f == x && 0.0f == y && 1.0f == z) {
rotMat.m[0][0] = c; rotMat.m[1][1] = c;
rotMat.m[0][1] = s; rotMat.m[1][0] = -s;
rotMat.m[0][2] = 0; rotMat.m[1][2] = 0;
rotMat.m[2][0] = 0; rotMat.m[2][1] = 0;
rotMat.m[2][2]= 1;
} else {
float nc = 1.0f - c;
float xy = x * y;
float yz = y * z;
float zx = z * x;
float xs = x * s;
float ys = y * s;
float zs = z * s;
rotMat.m[0][0] = x*x*nc + c;
rotMat.m[1][0] = xy*nc - zs;
rotMat.m[2][0] = zx*nc + ys;
rotMat.m[0][1] = xy*nc + zs;
rotMat.m[1][1] = y*y*nc + c;
rotMat.m[2][1] = yz*nc - xs;
rotMat.m[0][2] = zx*nc - ys;
rotMat.m[1][2] = yz*nc + xs;
rotMat.m[2][2] = z*z*nc + c;
}
ksMatrixMultiply( result, &rotMat, result );
}
ksMatrix4 ksMatrixTranslateEx(ksMatrix4 & m, float x, float y, float z)
{
ksMatrix4 Result(m);
Result[3] = m[0] * x + m[1] * y + m[2] * z + m[3];
return Result;
}
ksMatrix4 ksMatrixRotateEx(ksMatrix4 m, float angle, float x, float y, float z)
{
float const a = angle;
float const c = cosf(a);
float const s = sinf(a);
ksVec3 axis(x, y, z);
ksVec3 temp;
temp.x = axis.x*(1.0f - c);
temp.y = axis.y*(1.0f - c);
temp.z = axis.z*(1.0f - c);
ksMatrix4 Rotate(1.0f);
Rotate.m[0][0] = c + temp[0] * axis[0];
Rotate.m[0][1] = 0 + temp[0] * axis[1]+ s * axis[2];
Rotate.m[0][2] = 0 + temp[0] * axis[2] - s * axis[1];
Rotate.m[1][0] = 0 + temp[1] * axis[0] - s * axis[2];
Rotate.m[1][1] = c + temp[1] * axis[1];
Rotate.m[1][2] = 0 + temp[1] * axis[2] + s * axis[0];
Rotate.m[2][0] = 0 + temp[2] * axis[0] + s * axis[1];
Rotate.m[2][1] = 0 + temp[2] * axis[1] - s * axis[0];
Rotate.m[2][2] = c + temp[2] * axis[2];
ksMatrix4 Result(1.0f);
Result.m[0] = m[0] * Rotate.m[0][0] + m[1] * Rotate.m[0][1] + m[2] * Rotate.m[0][2];
Result.m[1] = m[0] * Rotate.m[1][0] + m[1] * Rotate.m[1][1] + m[2] * Rotate.m[1][2];
Result.m[2] = m[0] * Rotate.m[2][0] + m[1] * Rotate.m[2][1] + m[2] * Rotate.m[2][2];
Result.m[3] = m[3];
return Result;
}
// result[x][y] = a[x][0]*b[0][y]+a[x][1]*b[1][y]+a[x][2]*b[2][y]+a[x][3]*b[3][y];
void ksMatrixMultiply(ksMatrix4 * result, const ksMatrix4 *a, const ksMatrix4 *b)
{
ksMatrix4 tmp;
int i;
int j;
for (i=0 ; i<4 ; i++) {
const float rhs_i0 = b->m[i][0];
float ri0 = a->m[0][0] * rhs_i0;
float ri1 = a->m[0][1] * rhs_i0;
float ri2 = a->m[0][2] * rhs_i0;
float ri3 = a->m[0][3] * rhs_i0;
for (j=1 ; j<4 ; j++) {
const float rhs_ij = b->m[i][j];
ri0 += a->m[j][0] * rhs_ij;
ri1 += a->m[j][1] * rhs_ij;
ri2 += a->m[j][2] * rhs_ij;
ri3 += a->m[j][3] * rhs_ij;
}
tmp.m[i][0] = ri0;
tmp.m[i][1] = ri1;
tmp.m[i][2] = ri2;
tmp.m[i][3] = ri3;
}
memcpy(result, &tmp, sizeof(ksMatrix4));
}
void ksMatrixDotVector(ksVec4 * out, const ksMatrix4 * m, const ksVec4 * v)
{
// out->x = m->m[0][0] * v->x + m->m[0][1] * v->y + m->m[0][2] * v->z + m->m[0][3] * v->w;
// out->y = m->m[1][0] * v->x + m->m[1][1] * v->y + m->m[1][2] * v->z + m->m[1][3] * v->w;
// out->z = m->m[2][0] * v->x + m->m[2][1] * v->y + m->m[2][2] * v->z + m->m[2][3] * v->w;
// out->w = m->m[3][0] * v->x + m->m[3][1] * v->y + m->m[3][2] * v->z + m->m[3][3] * v->w;
out->x = m->m[0][0] * v->x + m->m[1][0] * v->y + m->m[2][0] * v->z + m->m[3][0] * v->w;
out->y = m->m[0][1] * v->x + m->m[1][1] * v->y + m->m[2][1] * v->z + m->m[3][1] * v->w;
out->z = m->m[0][2] * v->x + m->m[1][2] * v->y + m->m[2][2] * v->z + m->m[3][2] * v->w;
out->w = m->m[0][3] * v->x + m->m[1][3] * v->y + m->m[2][3] * v->z + m->m[3][3] * v->w;
}
void ksMatrixCopy(ksMatrix4 * target, const ksMatrix4 * src)
{
memcpy(target, src, sizeof(ksMatrix4));
}
int ksMatrixInvert(ksMatrix4 * out, const ksMatrix4 * in)
{
float * m = (float *)(&in->m[0][0]);
float * om = (float *)(&out->m[0][0]);
double inv[16], det;
int i;
inv[0] = m[5] * m[10] * m[15] -
m[5] * m[11] * m[14] -
m[9] * m[6] * m[15] +
m[9] * m[7] * m[14] +
m[13] * m[6] * m[11] -
m[13] * m[7] * m[10];
inv[4] = -m[4] * m[10] * m[15] +
m[4] * m[11] * m[14] +
m[8] * m[6] * m[15] -
m[8] * m[7] * m[14] -
m[12] * m[6] * m[11] +
m[12] * m[7] * m[10];
inv[8] = m[4] * m[9] * m[15] -
m[4] * m[11] * m[13] -
m[8] * m[5] * m[15] +
m[8] * m[7] * m[13] +
m[12] * m[5] * m[11] -
m[12] * m[7] * m[9];
inv[12] = -m[4] * m[9] * m[14] +
m[4] * m[10] * m[13] +
m[8] * m[5] * m[14] -
m[8] * m[6] * m[13] -
m[12] * m[5] * m[10] +
m[12] * m[6] * m[9];
inv[1] = -m[1] * m[10] * m[15] +
m[1] * m[11] * m[14] +
m[9] * m[2] * m[15] -
m[9] * m[3] * m[14] -
m[13] * m[2] * m[11] +
m[13] * m[3] * m[10];
inv[5] = m[0] * m[10] * m[15] -
m[0] * m[11] * m[14] -
m[8] * m[2] * m[15] +
m[8] * m[3] * m[14] +
m[12] * m[2] * m[11] -
m[12] * m[3] * m[10];
inv[9] = -m[0] * m[9] * m[15] +
m[0] * m[11] * m[13] +
m[8] * m[1] * m[15] -
m[8] * m[3] * m[13] -
m[12] * m[1] * m[11] +
m[12] * m[3] * m[9];
inv[13] = m[0] * m[9] * m[14] -
m[0] * m[10] * m[13] -
m[8] * m[1] * m[14] +
m[8] * m[2] * m[13] +
m[12] * m[1] * m[10] -
m[12] * m[2] * m[9];
inv[2] = m[1] * m[6] * m[15] -
m[1] * m[7] * m[14] -
m[5] * m[2] * m[15] +
m[5] * m[3] * m[14] +
m[13] * m[2] * m[7] -
m[13] * m[3] * m[6];
inv[6] = -m[0] * m[6] * m[15] +
m[0] * m[7] * m[14] +
m[4] * m[2] * m[15] -
m[4] * m[3] * m[14] -
m[12] * m[2] * m[7] +
m[12] * m[3] * m[6];
inv[10] = m[0] * m[5] * m[15] -
m[0] * m[7] * m[13] -
m[4] * m[1] * m[15] +
m[4] * m[3] * m[13] +
m[12] * m[1] * m[7] -
m[12] * m[3] * m[5];
inv[14] = -m[0] * m[5] * m[14] +
m[0] * m[6] * m[13] +
m[4] * m[1] * m[14] -
m[4] * m[2] * m[13] -
m[12] * m[1] * m[6] +
m[12] * m[2] * m[5];
inv[3] = -m[1] * m[6] * m[11] +
m[1] * m[7] * m[10] +
m[5] * m[2] * m[11] -
m[5] * m[3] * m[10] -
m[9] * m[2] * m[7] +
m[9] * m[3] * m[6];
inv[7] = m[0] * m[6] * m[11] -
m[0] * m[7] * m[10] -
m[4] * m[2] * m[11] +
m[4] * m[3] * m[10] +
m[8] * m[2] * m[7] -
m[8] * m[3] * m[6];
inv[11] = -m[0] * m[5] * m[11] +
m[0] * m[7] * m[9] +
m[4] * m[1] * m[11] -
m[4] * m[3] * m[9] -
m[8] * m[1] * m[7] +
m[8] * m[3] * m[5];
inv[15] = m[0] * m[5] * m[10] -
m[0] * m[6] * m[9] -
m[4] * m[1] * m[10] +
m[4] * m[2] * m[9] +
m[8] * m[1] * m[6] -
m[8] * m[2] * m[5];
det = m[0] * inv[0] + m[1] * inv[4] + m[2] * inv[8] + m[3] * inv[12];
if (det == 0)
return 0;
det = 1.0 / det;
for (i = 0; i < 16; i++)
*om++ = (float)(inv[i] * det);
return 1;
}
void ksMatrixTranspose(ksMatrix4 * result, const ksMatrix4 * src)
{
ksMatrix4 tmp;
tmp.m[0][0] = src->m[0][0];
tmp.m[0][1] = src->m[1][0];
tmp.m[0][2] = src->m[2][0];
tmp.m[0][3] = src->m[3][0];
tmp.m[1][0] = src->m[0][1];
tmp.m[1][1] = src->m[1][1];
tmp.m[1][2] = src->m[2][1];
tmp.m[1][3] = src->m[3][1];
tmp.m[2][0] = src->m[0][2];
tmp.m[2][1] = src->m[1][2];
tmp.m[2][2] = src->m[2][2];
tmp.m[2][3] = src->m[3][2];
tmp.m[3][0] = src->m[0][3];
tmp.m[3][1] = src->m[1][3];
tmp.m[3][2] = src->m[2][3];
tmp.m[3][3] = src->m[3][3];
memcpy(result, &tmp, sizeof(ksMatrix4));
}
void ksMatrix4ToMatrix3(ksMatrix3 * result, const ksMatrix4 * src)
{
result->m[0][0] = src->m[0][0];
result->m[0][1] = src->m[0][1];
result->m[0][2] = src->m[0][2];
result->m[1][0] = src->m[1][0];
result->m[1][1] = src->m[1][1];
result->m[1][2] = src->m[1][2];
result->m[2][0] = src->m[2][0];
result->m[2][1] = src->m[2][1];
result->m[2][2] = src->m[2][2];
}
const float IDENTITY[16] = {1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
void ksMatrixLoadIdentity(ksMatrix4 * result)
{
memcpy(result, IDENTITY, sizeof(IDENTITY));
// result->m[0][0] = 1.0f;
// result->m[0][1] = 0.0f;
// result->m[0][2] = 0.0f;
// result->m[0][3] = 0.0f;
//
// result->m[1][0] = 0.0f;
// result->m[1][1] = 1.0f;
// result->m[1][2] = 0.0f;
// result->m[1][3] = 0.0f;
//
// result->m[2][0] = 0.0f;
// result->m[2][1] = 0.0f;
// result->m[2][2] = 1.0f;
// result->m[2][3] = 0.0f;
//
// result->m[3][0] = 0.0f;
// result->m[3][1] = 0.0f;
// result->m[3][2] = 0.0f;
// result->m[3][3] = 1.0f;
}
void ksFrustum(ksMatrix4 * result, float left, float right, float bottom, float top, float nearZ, float farZ)
{
float deltaX = right - left;
float deltaY = top - bottom;
float deltaZ = farZ - nearZ;
ksMatrix4 frust;
if ( (nearZ <= 0.0f) || (farZ <= 0.0f) ||
(deltaX <= 0.0f) || (deltaY <= 0.0f) || (deltaZ <= 0.0f) )
return;
frust.m[0][0] = 2.0f * nearZ / deltaX;
frust.m[0][1] = frust.m[0][2] = frust.m[0][3] = 0.0f;
frust.m[1][1] = 2.0f * nearZ / deltaY;
frust.m[1][0] = frust.m[1][2] = frust.m[1][3] = 0.0f;
frust.m[2][0] = (right + left) / deltaX;
frust.m[2][1] = (top + bottom) / deltaY;
frust.m[2][2] = -(nearZ + farZ) / deltaZ;
frust.m[2][3] = -1.0f;
frust.m[3][2] = -2.0f * nearZ * farZ / deltaZ;
frust.m[3][0] = frust.m[3][1] = frust.m[3][3] = 0.0f;
ksMatrixMultiply(result, &frust, result);
}
void ksPerspective(ksMatrix4 * result, float fovy, float aspect, float zNear, float zFar)
{
float const tanHalfFovy = tanf(fovy * 0.5f);
memset(result, 0x0, sizeof(ksMatrix4));
result->m[0][0] = 1.0f / (aspect * tanHalfFovy);
result->m[1][1] = 1.0f / (tanHalfFovy);
result->m[2][2] = - (zFar + zNear) / (zFar - zNear);
result->m[2][3] = - 1.0f ;
result->m[3][2] = - (2.0f * zFar * zNear) / (zFar - zNear);
//float frustumW, frustumH;
//frustumH = tanf( fovy / 360.0f * M_PI ) * nearZ;
//frustumW = frustumH * aspect;
//ksFrustum(result, -frustumW, frustumW, -frustumH, frustumH, nearZ, farZ);
}
ksMatrix4 ksPerspectiveEx(float fovy, float aspect, float zNear, float zFar)
{
float const tanHalfFovy = tan(fovy / 2.0f);
ksMatrix4 Result(0.0f);
Result[0][0] = 1.0f / (aspect * tanHalfFovy);
Result[1][1] = 1.0f / (tanHalfFovy);
Result[2][2] = - (zFar + zNear) / (zFar - zNear);
Result[2][3] = - 1.0f;
Result[3][2] = - (2.0f * zFar * zNear) / (zFar - zNear);
return Result;
//float frustumW, frustumH;
//frustumH = tanf( fovy / 360.0f * M_PI ) * nearZ;
//frustumW = frustumH * aspect;
//ksFrustum(result, -frustumW, frustumW, -frustumH, frustumH, nearZ, farZ);
}
void ksOrtho(ksMatrix4 * result, float left, float right, float bottom, float top, float zNear, float zFar)
{
memset(result, 0x0, sizeof(ksMatrix4));
result->m[0][0] = 1.0f;
result->m[1][1] = 1.0f;
result->m[2][2] = 1.0f;
result->m[3][3] = 1.0f;
result->m[0][0] = 2.0f / (right - left);
result->m[1][1] = 2.0f / (top - bottom);
result->m[2][2] = - 2.0f / (zFar - zNear);
result->m[3][0] = - (right + left) / (right - left);
result->m[3][1] = - (top + bottom) / (top - bottom);
result->m[3][2] = - (zFar + zNear) / (zFar - zNear);
// float deltaX = right - left;
// float deltaY = top - bottom;
// float deltaZ = farZ - nearZ;
// ksMatrix4 ortho;
//
// if ((deltaX == 0.0f) || (deltaY == 0.0f) || (deltaZ == 0.0f))
// return;
//
// ksMatrixLoadIdentity(&ortho);
// ortho.m[0][0] = 2.0f / deltaX;
// ortho.m[3][0] = -(right + left) / deltaX;
// ortho.m[1][1] = 2.0f / deltaY;
// ortho.m[3][1] = -(top + bottom) / deltaY;
// ortho.m[2][2] = -2.0f / deltaZ;
// ortho.m[3][2] = -(nearZ + farZ) / deltaZ;
//
// ksMatrixMultiply(result, &ortho, result);
}
void ksLookAt(ksMatrix4 * result, const ksVec3 * eye, const ksVec3 * center, const ksVec3 * up)
{
// tvec3<T, P> const f(normalize(center - eye));
// tvec3<T, P> const s(normalize(cross(f, up)));
// tvec3<T, P> const u(cross(s, f));
//
// tmat4x4<T, P> Result(1);
// Result[0][0] = s.x;
// Result[1][0] = s.y;
// Result[2][0] = s.z;
// Result[0][1] = u.x;
// Result[1][1] = u.y;
// Result[2][1] = u.z;
// Result[0][2] =-f.x;
// Result[1][2] =-f.y;
// Result[2][2] =-f.z;
// Result[3][0] =-dot(s, eye);
// Result[3][1] =-dot(u, eye);
// Result[3][2] = dot(f, eye);
// return Result;
ksVec3 side, up2, forward ;
//ksVec4 eyePrime;
ksMatrix4 transMat;
ksVectorSubtract(&forward, center, eye);
ksVectorNormalize(&forward);
ksCrossProduct(&side, up, &forward);
ksVectorNormalize(&side );
ksCrossProduct(&up2, &side, &forward);
ksVectorNormalize(&up2);
ksMatrixLoadIdentity(result);
result->m[0][0] = side.x;
result->m[0][1] = side.y;
result->m[0][2] = side.z;
result->m[1][0] = up2.x;
result->m[1][1] = up2.y;
result->m[1][2] = up2.z;
result->m[2][0] = -forward.x;
result->m[2][1] = -forward.y;
result->m[2][2] = -forward.z;
ksMatrixLoadIdentity(&transMat);
ksMatrixTranslate(&transMat, -eye->x, -eye->y, -eye->z);
ksMatrixMultiply(result, result, &transMat);
//eyePrime.x = -eye->x;
//eyePrime.y = -eye->y;
//eyePrime.z = -eye->z;
//eyePrime.w = 1;
//ksMatrixMultiplyVector(&eyePrime, result, &eyePrime);
//ksMatrixTranspose(result, result);
//result->m[3][0] = eyePrime.x;
//result->m[3][1] = eyePrime.y;
//result->m[3][2] = eyePrime.z;
//result->m[3][3] = eyePrime.w;
}
|
f2b0860936668eff7e058bb4fc892012f7fa5eea | 07306d96ba61d744cb54293d75ed2e9a09228916 | /EclipseStudio/Sources/ObjectsCode/Gameplay/BaseVehicleSpawnPoint.h | 0ae03ad2ede7b628063e0b9e881c8b0aaf493660 | [] | no_license | D34Dspy/warz-client | e57783a7c8adab1654f347f389c1dace35b81158 | 5262ea65e0baaf3f37ffaede5f41c9b7eafee7c1 | refs/heads/master | 2023-03-17T00:56:46.602407 | 2015-12-20T16:43:00 | 2015-12-20T16:43:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 991 | h | BaseVehicleSpawnPoint.h | #pragma once
#include "GameCommon.h"
#include "..\..\GameCode\UserProfile.h"
class BaseVehicleSpawnPoint : public MeshGameObject
{
DECLARE_CLASS(BaseVehicleSpawnPoint, MeshGameObject)
public:
struct VehicleSpawn
{
r3dPoint3D position;
float coolDown;
uint32_t vehicleID; // the vehicle id to spawn at this object.
gobjid_t spawnedVehicleId; // which vehicle was actually spawned in this location. if vehicle is taken, reset to 0.
VehicleSpawn() : position (0, 0, 0), coolDown(0.0f), vehicleID(0) {}
r3dBoundBox GetDebugBBox() const;
};
typedef r3dgameVector(VehicleSpawn) VEHICLE_SPAWN_POINT_VECTOR;
VEHICLE_SPAWN_POINT_VECTOR spawnPoints;
float tickPeriod;
float coolDown;
uint32_t lootBoxId;
public:
BaseVehicleSpawnPoint();
virtual ~BaseVehicleSpawnPoint();
virtual void WriteSerializedData(pugi::xml_node& node);
virtual void ReadSerializedData(pugi::xml_node& node);
};
extern wiInventoryItem RollVehicle(const class LootBoxConfig* lootCfg, int depth); |
6e58ac9bba818f06467be39afd1b8a9a98a49e55 | 472da2da68fbdfc32402d7e86524a38badcb70de | /computer-graphics-project/Camera.h | de83e413530af08651e67fdc3d40323e59711c59 | [] | no_license | SoerenHenning/Kjottbasaren | 4489316a25a7a587d23c70b6982f3e03f476deee | c3330712c7b91486f579353d1c69da19a70a613a | refs/heads/master | 2021-08-23T22:04:39.636010 | 2017-12-06T19:26:36 | 2017-12-06T19:26:36 | 105,449,596 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,288 | h | Camera.h | #pragma once
#include "Vector3.h"
#include "Matrix4.h"
using namespace std;
class Camera {
public:
enum class Projection { ORTHOGRAPHIC, PERSPECTIVE };
Vector3f position; // position of the camera
Vector3f target; // the direction the camera is looking at
Vector3f up; // the up vector of the camera
float fieldOfView; // camera field of view
float aspectRatio; // camera aspect ratio
float nearPlane, farPlane; // depth of the near and far plane
float zoom; // an additional scaling parameter
Camera::Projection projectionType;
public:
Camera(Vector3f, Vector3f, Vector3f);
~Camera();
Vector3f getPosition();
void moveForward(float);
void moveRight(float);
void moveUp(float);
Vector3f getTarget();
Vector3f getUp();
void rotateHorizontal(float);
void rotateVertical(float);
float getFieldOfView();
void increaseFieldOfView(float);
float getAspectRatio();
void setAspectRatio(float);
float getNearPlane();
float getFarPlane();
float getZoom();
void zoomIn(float);
Camera::Projection getProjection();
void setProjection(Camera::Projection);
void toggleProjection();
Matrix4f getTransformationMatrix();
void printStatus();
//TODO preparation for new assignment
void drive(float); //TODO temp here
};
|
cb3ef58bcce2fcb294cec7404f5aad13950634c5 | b41d190ff675c63d09bd7ca2ee781d051b7db8ec | /call_stack/extras/callStack.cpp | dc8f5868759edba57054bfa9145eb5a8b5edceaf | [] | no_license | yashparakh111/cache_features | 02c3d50e5c067908d72b476f2e95f40a3b9d35a2 | 10d46ae910dd1405e948767bb0d4a9af6e1c1854 | refs/heads/master | 2020-04-12T21:27:44.822997 | 2019-06-18T20:14:47 | 2019-06-18T20:14:47 | 162,762,660 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,422 | cpp | callStack.cpp | //
// This tool counts the number of times a routine is executed and
// the number of instructions executed in a routine
//
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string.h>
#include "pin.H"
#include <vector>
#include <unordered_map>
ofstream outFile;
// maintains the call stack for the current instruction
//vector<string> call_stack;
vector<ADDRINT> call_stack_address;
uint8_t call_stack_size;
// maintains instruction disassembly
static std::unordered_map<ADDRINT, std::string> inst_disassembly;
VOID RecordMemRead(ADDRINT *inst_ptr, ADDRINT *addr) {
// record instruction disassembly
outFile << setw(30) << inst_disassembly[(unsigned long long)inst_ptr] << " ";
// capture value read by read_instruction
ADDRINT value;
PIN_SafeCopy(&value, addr, sizeof(ADDRINT));
outFile << hex << setw(14) << (unsigned long long) inst_ptr << " "
<< setw(14) << (unsigned long long) addr << " "
<< setw(14) << (int) value << " "
<< " ";
// print call stack beginning from most recent routine call
int i = 0;
//std::vector<ADDRINT>::reverse_iterator rtn_addr_it = call_stack_address.rbegin();
for(std::vector<ADDRINT>::reverse_iterator rtn_addr_it = call_stack_address.rbegin(); rtn_addr_it != call_stack_address.rend() && i < call_stack_size; rtn_addr_it++) {
//outFile << *rtn_it << " (" << *rtn_addr_it << ")" << "\t";
outFile << *rtn_addr_it << "\t";
i++;
}
outFile << endl;
}
// push routine on call stack
VOID PushRoutine(ADDRINT rtn) {
//call_stack.push_back(RTN_FindNameByAddress(rtn));
call_stack_address.push_back(rtn);
}
// pop routine from call stack
VOID PopRoutine() {
//call_stack.pop_back();
call_stack_address.pop_back();
}
// Pin calls this function every time a new rtn is executed
VOID Routine(RTN rtn, VOID *v) {
// only consider c functions (c functions begin with "_Z")
if (!RTN_Name(rtn).compare(0, 2, "_Z") || !RTN_Name(rtn).compare("main")) {
RTN_Open(rtn);
// push routine at start of the function
RTN_InsertCall(rtn, IPOINT_BEFORE, (AFUNPTR)PushRoutine, IARG_ADDRINT, RTN_Address(rtn), IARG_END);
for (INS ins = RTN_InsHead(rtn); INS_Valid(ins); ins = INS_Next(ins)) {
// memory read encountered, record call stack
if(INS_IsMemoryRead(ins)) {
//outFile << OPCODE_StringShort(INS_Opcode(ins)) << "\t";
//outFile << INS_Disassemble(ins) << endl;
inst_disassembly[INS_Address(ins)] = INS_Disassemble(ins);
INS_InsertPredicatedCall(ins, IPOINT_BEFORE, (AFUNPTR)RecordMemRead, IARG_INST_PTR, IARG_MEMORYREAD_EA, IARG_END);
}
/*UINT32 memOperands = INS_MemoryOperandCount(ins);
for(UINT32 memOp = 0; memOp < memOperands; memOp++) {
if(INS_MemoryOperandIsRead(ins, memOp))
INS_InsertPredicatedCall(ins, IPOINT_BEFORE, (AFUNPTR)RecordMemRead, IARG_INST_PTR, IARG_MEMORYREAD_EA, IARG_END);
}*/
}
// pop routine at the end of function call
RTN_InsertCall(rtn, IPOINT_AFTER, (AFUNPTR)PopRoutine, IARG_END);
RTN_Close(rtn);
}
}
// This function is called when the application exits.
VOID Fini(INT32 code, VOID *v) {
outFile.close();
}
INT32 Usage()
{
cerr << "This Pintool records the call stack every time a read instruction is encountered" << endl;
cerr << endl << KNOB_BASE::StringKnobSummary() << endl;
return -1;
}
int main(int argc, char * argv[]) {
// declare the size of the call stack
call_stack_size = 30;
// Initialize symbol table code, needed for rtn instrumentation
PIN_InitSymbols();
outFile.open("callStack.out");
// Initialize pin
if (PIN_Init(argc, argv)) return Usage();
// Register Routine to be called to instrument rtn
RTN_AddInstrumentFunction(Routine, 0);
// Register Fini to be called when the application exits
PIN_AddFiniFunction(Fini, 0);
// set up table headers
outFile << setw(30) << "Instruction" << " "
<< setw(14) << "Instr Addr" << " "
<< setw(14) << "Data Addr" << " "
<< setw(14) << "Data Value" << " "
<< " " << "Call Stack (Most Recent to Least Recent Function)" << endl;
// Start the program, never returns
PIN_StartProgram();
return 0;
}
|
2bc3e4bc350e606c4cb4328ade6fd3c9f5bb9d1b | 60d4146419a50f66edc0ed79d00b5878017185b2 | /array/90_subsets_II.cpp | 06ae66c0602417195672829de90519caa82d3cc9 | [] | no_license | zhangzuizui/leetcode_with_cpp | 9b59ba95d20c70b1ab9cfcbf23e1fb75d4304c0f | 6ada04beefd38f19fab5f2cac404addb7d64d533 | refs/heads/master | 2020-12-30T14:34:42.341943 | 2017-07-24T16:10:34 | 2017-07-24T16:10:34 | 91,072,952 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 641 | cpp | 90_subsets_II.cpp | /**
* 标准回溯法题型
*/
void backtrack(vector<vector<int>>& ans,vector<int>& temp,vector<int> nums,int start) {
ans.push_back(temp);
for(int i = start; i < nums.size(); ++i) {
if(i > start && nums[i-1] == nums[i]) continue;
temp.push_back(nums[i]);
backtrack(ans, temp, nums, i+1);
temp.pop_back();
}
}
class Solution {
public:
vector<vector<int>> subsetsWithDup(vector<int>& nums)
{
vector< vector<int> > ans;
vector<int> temp;
sort(nums.begin(),nums.end());
backtrack(ans,temp,nums,0);
return ans;
}
}; |
20ae189b7d9559b7fd30c8643cf75a34a190566b | 409599864c7bcfb4e496c3369ce12d73a3c7e3fe | /tunguska_sources/error.h | 72aad9c3fb1c7699d0b9b2b7cb19a4dab19d7c38 | [] | no_license | vlofgren/tunguska | d1127883e76663fa85851c42c32d0a4e804cff38 | 311ffbb5edc0a96df246aef6f16a3f881f69693b | refs/heads/master | 2023-03-17T09:28:55.059298 | 2023-03-05T17:43:21 | 2023-03-05T17:43:21 | 148,545,238 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,753 | h | error.h | /* Tunguska, ternary virtual machine
*
* Copyright (C) 2007-2009 Viktor Lofgren
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* !!!! NOTICE !!!!
*
* ONLY USE THIS ERROR CLASS WITH THE ASSEMBLER.
* Throws are SLOW. It's a case of speed vs. fancy error
* management, speed is vastly preferable in this case.
*/
#ifndef error_h
#define error_h
#include <string>
using namespace std;
#define WHERE new error::where(__LINE__,__FILE__)
class error {
public:
class where;
error(where* place, string desc, error* child = 0) {
this->desc = desc;
this->place = place;
this->child = child;
}
void trace() {
if(child) child->trace();
printf("* %s[%d]: %s\n", place->get_file().c_str(),
place->get_line(),
desc.c_str());
}
class where {
public:
where(int line, string file) {
this->line = line;
this->file = file;
}
int get_line() { return line; }
string get_file() { return file; }
protected:
int line;
string file;
};
protected:
string desc;
where* place;
error* child;
};
#endif
|
7fd2b67ca51a873b7a88ba9974078d6ed7c19abd | 5b7d99ad4dc7edcfe1168d78e7e8dc1eb43b12b3 | /Overdrive/render/common_vertex_formats.h | df4aad27a943b2bddee4faf4c36f93c9e107e614 | [
"MIT"
] | permissive | png85/Overdrive | e4870fc9cf9f8335d5f04c6d790bb2f48d127fca | e763827546354c7c75395ab1a82949a685ecb880 | refs/heads/master | 2020-03-17T05:59:58.136842 | 2018-05-14T10:01:18 | 2018-05-14T10:01:18 | 133,337,058 | 0 | 0 | null | 2018-05-14T09:28:09 | 2018-05-14T09:28:09 | null | UTF-8 | C++ | false | false | 2,064 | h | common_vertex_formats.h | #pragma once
#include "../opengl.h"
#include <boost/fusion/adapted.hpp>
namespace overdrive {
namespace render {
// some common vertex attribute formats
// [NOTE] colors are typically defined in 32-bits unsigned integer format, float is pretty much only used for HDR... sooo maybe change to glm::u8vec4?
namespace attributes {
struct Position {
glm::vec3 mPosition;
};
struct PositionColor {
glm::vec3 mPosition;
glm::vec4 mColor;
};
struct PositionTexCoord {
glm::vec3 mPosition;
glm::vec2 mTexCoord;
};
struct PositionNormal {
glm::vec3 mPosition;
glm::vec3 mNormal;
};
struct PositionNormalColor {
glm::vec3 mPosition;
glm::vec3 mNormal;
glm::vec4 mColor;
};
struct PositionNormalTexCoord {
glm::vec3 mPosition;
glm::vec3 mNormal;
glm::vec2 mTexCoord;
};
struct PositionNormalTexCoordColor {
glm::vec3 mPosition;
glm::vec3 mNormal;
glm::vec2 mTexCoord;
glm::vec4 mColor;
};
}
}
}
BOOST_FUSION_ADAPT_STRUCT(
overdrive::render::attributes::Position,
(glm::vec3, mPosition)
)
BOOST_FUSION_ADAPT_STRUCT(
overdrive::render::attributes::PositionColor,
(glm::vec3, mPosition)
(glm::vec4, mColor)
)
BOOST_FUSION_ADAPT_STRUCT(
overdrive::render::attributes::PositionTexCoord,
(glm::vec3, mPosition)
(glm::vec2, mTexCoord)
)
BOOST_FUSION_ADAPT_STRUCT(
overdrive::render::attributes::PositionNormal,
(glm::vec3, mPosition)
(glm::vec3, mNormal)
)
BOOST_FUSION_ADAPT_STRUCT(
overdrive::render::attributes::PositionNormalColor,
(glm::vec3, mPosition)
(glm::vec3, mNormal)
(glm::vec4, mColor)
)
BOOST_FUSION_ADAPT_STRUCT(
overdrive::render::attributes::PositionNormalTexCoord,
(glm::vec3, mPosition)
(glm::vec3, mNormal)
(glm::vec2, mTexCoord)
)
BOOST_FUSION_ADAPT_STRUCT(
overdrive::render::attributes::PositionNormalTexCoordColor,
(glm::vec3, mPosition)
(glm::vec3, mNormal)
(glm::vec2, mTexCoord)
(glm::vec4, mColor)
)
|
7c803cf2ae5c5634589ece4463b76161f36ee211 | afa59b7b69f09b924061eade6ecfd77bed61ebac | /src/obstacle_avoidance.cpp | ca6e8cbd12e85fb3bf5dbec58eddb139bb9713f8 | [] | no_license | ekuo1/rovey2 | a8ead58269be266a7f880c6cac2da7dbc5fc5270 | db883dd7ae6b96465a16c83a57394cc2acb9b139 | refs/heads/master | 2020-04-13T14:25:15.274334 | 2019-01-05T07:29:52 | 2019-01-05T07:29:52 | 163,262,441 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,921 | cpp | obstacle_avoidance.cpp | #include "ros/ros.h"
#include <iostream>
#include <fstream>
#include <string>
#include <sensor_msgs/LaserScan.h>
#include <cstdlib>
#include <nova_common/DriveCmd.h>
using namespace std;
ros::NodeHandle *n;
std::vector <float> baseline;
static std::vector<float> lidarValues;
static int lidarResolution = 0;
static int halfResolution = 0;
void updateSpeed() {
double leftObstacle = 0.0, rightObstacle = 0.0, frontObstacle = 0.0;
for (int i = 0; i < lidarResolution; ++i)
{
if (lidarValues[i] < baseline[i] - 1 || lidarValues[i]> baseline[i] + 1) // far obstacles are ignored
{
ROS_INFO("%d : %f %f %f", i, abs(lidarValues[i]-baseline[i]), lidarValues[i], baseline[i]);
if (i < 600 && i > 500){
frontObstacle ++;
}
else if (i< 550 && i > 400){
leftObstacle ++;
}
else if (i >550 && i < 700){
rightObstacle++;
}
}
}
if (frontObstacle > leftObstacle && frontObstacle > rightObstacle){ //front is the biggest
if (rightObstacle > leftObstacle){
//turn left
}
else{
//turn right
}
}
else if (rightObstacle > leftObstacle){
//turn left
}
else if (leftObstacle > 0){
//turn right
}
else{
//go forward
}
}
void lidarCallback(const sensor_msgs::LaserScan::ConstPtr& scan) {
int scanSize = scan->ranges.size();
lidarValues.resize(scanSize);
lidarResolution = scanSize;
halfResolution = scanSize / 2;
for (int i=0; i<scanSize; ++i){
lidarValues[i] = scan->ranges[i];
//ROS_INFO("%f\n", lidarValues[i]);
}
updateSpeed();
}
int main (int argc, char** argv) {
string line;
ifstream myfile;
myfile.open("/home/turtle/catkin_ws/src/rovey2/src/laserscans.csv");
if (myfile.is_open())
{
while (std::getline(myfile, line))
{
baseline.push_back(strtof((line).c_str(),0));
//ROS_INFO("%f", strtof((line).c_str(),0));
}
}
else cout << "Unable to open file";
ros::init(argc, argv, "obstacle_avoidance");
n = new ros::NodeHandle;
ros::Subscriber sub_lidar_scan;
sub_lidar_scan = n->subscribe("pioneer3at/Hokuyo_UTM_30LX/laser_scan/layer0", 10, lidarCallback);
ROS_INFO("Topic for lidar initialized.");
/*
put these in the right place
ros::Publisher drive_pub= n->advertise<nova_common::DriveCmd>("/core_rover/driver/drive_cmd", 1);
float rpm_limit, steer_limit;
n->getParam("rpm_limit", rpm_limit);
n->getParam("steer_limit", steer_limit);
nova_common::DriveCmd drive_msg;
drive_msg.rpm = ;
drive_msg.steer_pct = ;
drive_pub.publish(drive_msg);
*/
while (ros::ok()){
ros::spinOnce();
}
return 0;
} |
5b74c1e3454870f6c3fccd47a0cebcb0751756e4 | 87a997b6db138c9c6e59835599b7e8edc24d5ddc | /ImageTool/ImageTool/ColorSeg.cpp | 5b23657e21e6978857e3c17747c9c8cf90a94935 | [] | no_license | kimho314/LUNA_project | 7c0eb4a5a2781a4f0b1114beffdc42b89443fe1f | 3427bb23282d6cc3e3da87bf6c55c37e20b3810c | refs/heads/master | 2022-12-25T18:08:08.044874 | 2020-02-17T14:33:16 | 2020-02-17T14:33:16 | 122,976,062 | 0 | 0 | null | 2022-12-16T00:02:12 | 2018-02-26T13:46:31 | HTML | UTF-8 | C++ | false | false | 2,255 | cpp | ColorSeg.cpp | #include "stdafx.h"
#include "ColorSeg.h"
int g_lt_x = 0;
int g_lt_y = 0;
int g_rd_x = 0;
int g_rd_y = 0;
void SetRectPoints(int left_top_x, int left_top_y, int right_down_x, int right_down_y)
{
g_lt_x = left_top_x;
g_lt_y = left_top_y;
g_rd_x = right_down_x;
g_rd_y = right_down_y;
}
void GetMean(CDib *src, t_bounding_box *bb)
{
int src_w = src->GetWidth();
int src_h = src->GetHeight();
RGBBYTE **src_ptr = src->GetRGBPtr();
int cnt = 0;
for (int j = g_lt_y; j < g_rd_y; j++)
{
for (int i = g_lt_x; i < g_rd_x; i++)
{
bb->mean_r += src_ptr[j][i].r;
bb->mean_g += src_ptr[j][i].g;
bb->mean_b += src_ptr[j][i].b;
cnt++;
}
}
bb->mean_r /= cnt;
bb->mean_g /= cnt;
bb->mean_b /= cnt;
}
void GetDeviation(CDib *src, t_bounding_box *bb)
{
int src_w = src->GetWidth();
int src_h = src->GetHeight();
RGBBYTE **src_ptr = src->GetRGBPtr();
int cnt = 0;
for (int j = g_lt_y; j < g_rd_y; j++)
{
for (int i = g_lt_x; i < g_rd_x; i++)
{
bb->devia_r += pow(((double)src_ptr[j][i].r - bb->mean_r), 2);
bb->devia_g += pow(((double)src_ptr[j][i].g - bb->mean_g), 2);
bb->devia_b += pow(((double)src_ptr[j][i].b - bb->mean_b), 2);
cnt++;
}
}
bb->devia_r = sqrt(bb->devia_r / (double)cnt);
bb->devia_g = sqrt(bb->devia_g / (double)cnt);
bb->devia_b = sqrt(bb->devia_b / (double)cnt);
}
void ImplementColorSegmentation(CDib *dst, CDib *src, t_bounding_box *bb)
{
int src_w = src->GetWidth();
int src_h = src->GetHeight();
RGBBYTE **src_ptr = src->GetRGBPtr();
RGBBYTE **dst_ptr = dst->GetRGBPtr();
GetMean(src, bb);
GetDeviation(src, bb);
for (int j = 0; j < src_h; j++)
{
for (int i = 0; i < src_w; i++)
{
if ((src_ptr[j][i].r >= (bb->mean_r - (1.25 * bb->devia_r))) &&
(src_ptr[j][i].r <= (bb->mean_r + (1.25 * bb->devia_r))) &&
(src_ptr[j][i].g >= (bb->mean_g - (1.25 * bb->devia_g))) &&
(src_ptr[j][i].g <= (bb->mean_g + (1.25 * bb->devia_g))) &&
(src_ptr[j][i].b >= (bb->mean_b - (1.25 * bb->devia_b))) &&
(src_ptr[j][i].b <= (bb->mean_b + (1.25 * bb->devia_b))))
{
dst_ptr[j][i].r = 255;
dst_ptr[j][i].g = 255;
dst_ptr[j][i].b = 255;
}
else
{
dst_ptr[j][i].r = 0;
dst_ptr[j][i].g = 0;
dst_ptr[j][i].b = 0;
}
}
}
} |
f0afeaa3ef104966fe744378ba4ba0e6c47f0ff3 | 9daaaa213e79751eda76dd6eb04528d487c07d40 | /ExamenesPrueba/Examen1.cpp | b5b6069b42cc054a4b096c87bdb9966239ed58b9 | [] | no_license | Firek98/Fonaments17 | 419f1a5dd7d49b495a9878632c7599fe231896fb | 54042079ca3517cf79dbb13ade6cc702a9878b2d | refs/heads/master | 2021-08-20T07:21:54.177747 | 2017-11-28T14:28:12 | 2017-11-28T14:28:12 | 107,133,058 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 1,615 | cpp | Examen1.cpp | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
//Hacer una función que modifique una variable incrementándola en uno
//Crear una array de 5 números
//Llenar la array de 5 elementos con números leídos mediante scanf
//Duplicar los valores de dentro de la array
//Printar por pantalla el número más grande
void PlusOne(int &a)
{
a++;
}
void array1()
{
int array1[5];
int aux;
for (int i = 0; i < 5; i++)
{
scanf_s("%d", &aux);
array1[i] = aux;
}
printf("Este array contiene: \n");
for (int i = 0; i < 5; i++)
{
array1[i];
printf("%d ", array1[i]);
}
printf("\n");
printf("Su multiplicacion es: \n");
for (int i = 0; i < 5; i++)
{
array1[i] *= 2;
printf("%d ", array1[i]);
}
printf("\n");
printf("Su numero mas grande es: \n");
int aux2 = array1[0];
for (int i = 1; i < 5; i++)
{
if (array1[i] > aux2)
{
aux2 = array1[i];
}
}
printf("%d ", aux2);
}
void main()
{
srand(time(NULL));
int num1 = 5;
PlusOne(num1);
array1();
printf("\n");
//Cread una struct Vector2 que tenga X y Y.
struct Vector2 {
float x;
float y;
};
//Cread una array de Vectores
Vector2 arr[5];
for (int i = 0; i < 5; i++)
{
arr[i].x = 0;
arr[i].y = 0;
} //Inicializad la array de vectores a 0
//Haced que cada vector sea un número random entre 0 y 1(ejemplo: 0.05).
for (int i = 0; i < 5; i++)
{
arr[i].x = (rand() % 11) / 10;
arr[i].y = (rand() % 11) / 10; //
}
//Imprimid por pantalla los vectores impares
for (int i = 0; i < 5; i++)
{
if (i == 1 || i == 3 || i == 5)
{
printf("%f:%f \n", arr[i].x, arr[i].y);
}
}
} |
dacef1f5fd6bb8c589dfadd9429d47dc81b51b6f | 5875b7f7f301f92956a35a61a8d1870f72b98c09 | /stack.cpp | d8d5a959db58f5dc405661a0b7545e6b3973ba6b | [
"ISC"
] | permissive | clairvoyant/lacsap | 5a4ecac3bbedc677e4a115770341cd8e0bcd1bd4 | f50dc3762841cd6edc583e958f9b25bc9aba828b | refs/heads/master | 2023-08-03T08:02:11.364749 | 2023-05-01T21:45:23 | 2023-05-01T21:45:23 | 444,054,199 | 0 | 0 | ISC | 2022-01-03T12:31:47 | 2022-01-03T12:31:46 | null | UTF-8 | C++ | false | false | 366 | cpp | stack.cpp | #include "stack.h"
#include "utils.h"
bool InterfaceList::Add(std::string name, const NamedObject* obj)
{
if (caseInsensitive)
{
strlower(name);
}
auto it = list.find(name);
if (it == list.end())
{
if (verbosity > 1)
{
std::cerr << "Adding value: " << name << std::endl;
}
list[name] = obj;
return true;
}
return false;
}
|
851e17735c80f38b7172f724d94dbffacd0a5069 | 06798d9409a751a33ade7db7fbc0c66c38a099e0 | /tests/database/repositories/podcasts_repository_tests.cpp | 119f8af6ae3de60e5ec1f13178df184f5eb985de | [
"Apache-2.0"
] | permissive | beverlyRoadGoose/Beam | 156dafb88c95667217b919d2f2a7d9c5e8299915 | e56be330df3f36068ef37a93bcbea23cfeeb481d | refs/heads/master | 2021-09-09T04:14:05.201974 | 2018-03-13T19:08:32 | 2018-03-13T19:08:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,242 | cpp | podcasts_repository_tests.cpp | /*
* Copyright 2018 Oluwatobi Adeyinka
*
* 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.
*
*/
#define CATCH_CONFIG_MAIN
#include <catch/catch.hpp>
#include <tests/testutils.h>
#include <database/repositories/podcasts_repository.h>
TEST_CASE("insert new podcast", "[podcastsRepositoryTests]") {
TestUtils::emptyDatabase();
long id = 1;
std::string title = "title";
std::string publisher = "publisher";
std::string feedUrl = "feedUrl";
std::string description = "description";
std::string imageUrl = "imageUrl";
std::string url = "url";
Podcast podcast = Podcast(id, title, publisher, feedUrl, description, imageUrl, url);
PodcastsRepository podcastsRepository = PodcastsRepository();
podcastsRepository.insert(podcast);
REQUIRE(podcastsRepository.getAll().size() == 1);
}
TEST_CASE("get podcast by id", "[podcastsRepositoryTests]") {
TestUtils::emptyDatabase();
long id = 1;
std::string title = "title";
std::string publisher = "publisher";
std::string feedUrl = "feedUrl";
std::string description = "description";
std::string imageUrl = "imageUrl";
std::string url = "url";
PodcastsRepository podcastsRepository = PodcastsRepository();
Podcast originalPodcast = Podcast(id, title, publisher, feedUrl, description, imageUrl, url);
podcastsRepository.insert(originalPodcast);
Podcast retrievedPodcast = podcastsRepository.getById(id);
REQUIRE(retrievedPodcast.getTitle() == title);
}
TEST_CASE("get all podcasts", "[podcastsRepositoryTests]") {
TestUtils::emptyDatabase();
long idA = 1;
long idB = 2;
TestUtils::createPodcastForTest(idA);
TestUtils::createPodcastForTest(idB);
PodcastsRepository podcastsRepository = PodcastsRepository();
REQUIRE(podcastsRepository.getAll().size() == 2);
}
TEST_CASE("get non existing podcast by id", "[podcastsRepositoryTests]") {
TestUtils::emptyDatabase();
long id = 1;
PodcastsRepository podcastsRepository = PodcastsRepository();
REQUIRE_THROWS(podcastsRepository.getById(id));
}
TEST_CASE("delete podcast by id", "[podcastsRepositoryTests]") {
TestUtils::emptyDatabase();
long id = 1;
Podcast podcast = TestUtils::createPodcastForTest(id);
PodcastsRepository podcastsRepository = PodcastsRepository();
podcastsRepository.deleteById(id);
REQUIRE(podcastsRepository.getAll().empty());
}
TEST_CASE("delete all podcasts", "[podcastsRepositoryTests]") {
TestUtils::emptyDatabase();
long id = 1;
TestUtils::createPodcastForTest(id);
PodcastsRepository podcastsRepository = PodcastsRepository();
podcastsRepository.deleteAll();
REQUIRE(podcastsRepository.getAll().empty());
}
|
e94c599b65ca48c6f5d6db7770d6195ce8ff01f4 | 5d24f800ad35397699dac7bf48f1aff9e256e552 | /Kamek/src/animtiles.cpp | 53a204b81350a2eef5276a0d5796721ea559b30e | [
"MIT"
] | permissive | Danster64/NSMBWer | 861c26e7440ce56af6227051224588d0141d94f7 | 05dae4ddf04745d389923670311de437d2df825c | refs/heads/master | 2022-02-12T09:10:34.846693 | 2021-10-11T05:56:06 | 2021-10-11T05:56:06 | 236,567,638 | 5 | 5 | MIT | 2022-01-30T01:47:00 | 2020-01-27T18:54:51 | C++ | UTF-8 | C++ | false | false | 1,522 | cpp | animtiles.cpp | #include <common.h>
#include <game.h>
#include "fileload.h"
struct AnimDef_Header {
u32 magic;
u32 entryCount;
};
struct AnimDef_Entry {
u16 texNameOffset;
u16 frameDelayOffset;
u16 tileNum;
u8 tilesetNum;
u8 reverse;
};
FileHandle fh;
void DoTiles(void* self) {
AnimDef_Header *header;
header = (AnimDef_Header*)LoadFile(&fh, "/NewerRes/AnimTiles.bin");
if (!header) {
OSReport("anim load fail\n");
return;
}
if (header->magic != 'NWRa') {
OSReport("anim info incorrect\n");
FreeFile(&fh);
return;
}
AnimDef_Entry *entries = (AnimDef_Entry*)(header+1);
for (int i = 0; i < header->entryCount; i++) {
AnimDef_Entry *entry = &entries[i];
char *name = (char*)fh.filePtr+entry->texNameOffset;
char *frameDelays = (char*)fh.filePtr+entry->frameDelayOffset;
char realName[0x40];
snprintf(realName, 0x40, "BG_tex/%s", name);
void *blah = BgTexMng__LoadAnimTile(self, entry->tilesetNum, entry->tileNum, realName, frameDelays, entry->reverse);
}
}
void DestroyTiles(void *self) {
FreeFile(&fh);
}
extern "C" void CopyAnimTile(u8 *target, int tileNum, u8 *source, int frameNum) {
int tileRow = tileNum >> 5; // divided by 32
int tileColumn = tileNum & 31; // modulus by 32
u8 *baseRow = target + (tileRow * 2 * 32 * 1024);
u8 *baseTile = baseRow + (tileColumn * 32 * 4 * 2);
u8 *sourceRow = source + (frameNum * 2 * 32 * 32);
for (int i = 0; i < 8; i++) {
memcpy(baseTile, sourceRow, 32*4*2);
baseTile += (2 * 4 * 1024);
sourceRow += (2 * 32 * 4);
}
}
|
8b98f04b2396bbacf001d4e5585b7f33c747b6e9 | 88bccde6090daeb9eab79b7eaa9cda3da4b289fd | /Receiver.ino | 23c32c498044a2c1e13d431a79bbe1d222fd61ae | [] | no_license | sspeedy99/GestureBot-Arduino | d869b53f444748de7e062743a5fbd7cf1808e252 | 7297eaaa60e2cb3d25d498d6a73a99b93ea99e18 | refs/heads/master | 2020-03-12T16:51:53.401238 | 2018-04-23T17:12:17 | 2018-04-23T17:12:17 | 130,725,030 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,104 | ino | Receiver.ino | /* This is the program for arduino MEGA which is used in the chassis of the car by which it recives the data which is further used to control the motors and movement of the bot.
* Author : Shashi Prakash(https://github.com/sspeedy99)
* Date : 21 April 2018.
*/
#include <VirtualWire.h>
int in1 = 6;
int in2 = 5;
int in3 = 4;
int in4 = 3;
int en1 = 8;
int en2 = 2 ;
int en3 = 41; // The third enable pin is used for hood raising mechanism.
int in5 = 42; //motor driver L298 in1 will be in5 and in2 will be in6 of the motor which is used for hood part.
int in6 = 43;
void setup()
{
Serial.begin(9600); // Debugging only
pinMode(13, OUTPUT);
pinMode(in1, OUTPUT);
pinMode(in2, OUTPUT);
pinMode(in3, OUTPUT);
pinMode(in4, OUTPUT);
pinMode(in5, OUTPUT);
pinMode(in6, OUTPUT);
pinMode(en1, OUTPUT);
pinMode(en2, OUTPUT);
pinMode(en3, OUTPUT);
//vw_set_ptt_inverted(true); // Required when using encoder/decoder
vw_setup(2000); // Bits per sec
vw_rx_start(); // Start the receiver
}
void loop()
{
digitalWrite(en1, HIGH);
digitalWrite(en2, HIGH);
digitalWrite(en3, HIGH);
uint8_t buf[VW_MAX_MESSAGE_LEN];
uint8_t buflen = VW_MAX_MESSAGE_LEN;
if (vw_get_message(buf, &buflen)) // Non-blocking
{
int i;
digitalWrite(13, HIGH); // Turn led 13 pin on
if (char(buf[0]) == 'a') // Move forward.
{
Serial.println("Forward");
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
digitalWrite(in3, HIGH);
digitalWrite(in4, LOW);
delay(1000);
}
else if (char(buf[0]) == 's') // static value.
{
Serial.println("Static");
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);
digitalWrite(in3, LOW);
digitalWrite(in4, LOW);
delay(1000);
}
else if (char(buf[0]) == 'b') // Move Left
{
Serial.println("Left");
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
digitalWrite(in3, LOW);
digitalWrite(in4, LOW);
delay(1000);
}
else if (char(buf[0]) == 'd') // Move Right.
{
Serial.println("Rght");
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);
digitalWrite(in3, HIGH);
digitalWrite(in4, LOW);
delay(1000);
}
else if (char(buf[0]) == 'p') // Move backward
{
Serial.println("Backward");
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
digitalWrite(in3, LOW);
digitalWrite(in4, HIGH);
delay(1000);
}
else if (char(buf[0]) == 'H') // Raise the hood
{
//for Clockwise in1=HIGH, in2=LOW.
//Clockwise for 20 secs.
Serial.println("hood");
digitalWrite(in5, HIGH);
digitalWrite(in6, LOW);
delay(20000);
//for brake of 1 secs.
digitalWrite(in5, HIGH);
digitalWrite(in6, HIGH);
delay(1000);
//Anti clockwise for 20secs.
digitalWrite(in5, LOW);
digitalWrite(in6, HIGH);
delay(20000);
//for brake 1 sec.
digitalWrite(in5, HIGH);
digitalWrite(in6, HIGH);
delay(1000);
}
Serial.println("");
}
}
|
f77258ef99dd2b13b377f1b04dea77681960c6ad | efee6c788d4134dc7f31774de8c0dce9f0d9e1a3 | /C++_Code/Needs-Fixing/13.cpp | 37d4219a00ed7999df2c5f638e847f00233033e3 | [] | no_license | xXxSpicyBoiiixXx/PersonalProjects | 0423f48d913ec3ff17b8d6fc0115420f6336be77 | 36e773a986715edbb7e38ee0a6e315966a23402e | refs/heads/master | 2022-12-11T05:03:01.257568 | 2020-09-13T22:11:34 | 2020-09-13T22:11:34 | 288,551,560 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 519 | cpp | 13.cpp | #include <iostream>
using namespace std;
int main()
{
cout << "This bullshit uses the char bitch" << endl;
cout << endl;
char letter;
letter = 'A';
cout << letter << endl;
letter = 'B';
cout << letter << endl;
cout << endl << endl << endl;
cout << "Storing these Char variables as ASCII <--- WTF IS THIS BOI" << endl;
cout << endl << endl;
char letter1;
letter1 = 65;
cout << letter1 << endl;
letter1 = 66;
cout << letter1 << endl;
return 0;
}
|
af6bd176dd3558192e028356c5f48fef57865635 | 7bb6b48a6b2712168140ec318905086e90b46c64 | /View.h | 7a0907c9699140851a8778d031d1ae00523ffd91 | [] | no_license | SpagetCoder/calendar | f56f704d0760ca7bfd8940f9f21f4feec35ab827 | 01dc38631aed93d755863a7f0992d24dc05548d9 | refs/heads/master | 2021-05-08T23:57:45.572691 | 2019-06-14T15:00:25 | 2019-06-14T15:00:25 | 119,726,684 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 547 | h | View.h | #pragma once
#include <iostream>
#include <string>
#include "helpers.h"
extern HANDLE console;
using namespace std;
class View
{
protected:
int firstWeekDayOfMonth, numberOfDays, month, year;
int currM = CurrMonth();
int currday = CurrDay();
int currY = CurrYear();
string months[12] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
string weekDays[7] = { "Sun","Mon","Tue","Wed","Thu","Fri","Sat" };
public:
View(int,int,int, int);
}; |
bd346b2084e9f4a5bae8bda25432d754f6d110a2 | 87163dc47f904f4dd6eb53c08b1add9776ad0c2f | /Hex/Hex.cpp | 37b0c21e4f3e4a9dec61993b64330c5ef338a40d | [] | no_license | jjimenezg93/CPP_programming | da71929cf85e8243ecd0a5c8a04f5d3e08fdc904 | 730f528858ada7d8865a34ed373e0bb87ecbc816 | refs/heads/master | 2021-01-10T09:10:54.722816 | 2015-12-28T10:48:44 | 2015-12-28T10:48:44 | 45,610,165 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 4,090 | cpp | Hex.cpp | /*
Julián Jiménez González
*/
#pragma warning(disable: 4514) //el compilador elimina funciones inline que no se utilizan (en este caso de la librería stdio)
#pragma warning(disable: 4710) //la función dada está pensada para ser optimizada por el compilador mediante inlining. el warning indica que no se está produciendo la optimización
#include <stdio.h>
#include <cstdlib>
// Ejemplo de información empaquetada.
// en un entero de 32 bits tenemos:
// 8 bits mayor peso la vida
// siguientes 8 bits: número de balas.
// Siguientes 4 bits: número de compañeros.
// bit 0: invulnerable
// bit 1: balas infinitas.
// bit 2: escudo.
// bit 3: berseker mode.
// Hacer la siguiente práctica.
// Para almacenar el estado de un personaje se utiliza la variable
// que está empaquetada según el formato de arriba.
// 1.- Hacer una función que pasado un valor retorne el número de balas
// 2.- Hacer una función que añada un número de balas a las ya existentes.
// 3.- Hacer una función que pasado un valor retorne si se tienen balas infinitas
// 4.- Hacer una función ponga modo de balas infinitas.
unsigned char returnAmmo(int player) {
unsigned char toRet;
toRet = static_cast<unsigned char>((player & 0x00FF0000) >> 16); //warning "possible loss of data" en la conversión de int a unsigned char.
//al desplazar el byte a las posiciones de menor peso, son éstas las posiciones que quedan en el paso a unsigned char, el cast es seguro
return toRet;
}
int addAmmo(int &player, unsigned int ammoToAdd) { //unsigned para evitar que pueda meterse un número negativo, que restaría ammo
unsigned char currentAmmo = returnAmmo(player);
ammoToAdd += currentAmmo;
// 8bits ammo -> 0 < ammo < 255
if (ammoToAdd >= 255)
ammoToAdd = 255;
ammoToAdd <<= 16;
player &= 0xFF00FFFF; //primero se borran las balas que hubiera
player |= ammoToAdd; //ammoToAdd es un unsigned int para que esta operación sea más sencilla, aunque su información cabría en un unsigned char
return player;
}
bool infiniteAmmo(const int &player) {
int infinite = player & 0x00000002;
if (!infinite)
return false;
else return true;
}
int activateInfiniteAmmo(int &player) {
player |= 0x00000002;
return player;
}
using namespace std;
int main()
{
unsigned char flag = 1;
unsigned char option;
int playerInfo;
unsigned char ammo = 0; //ammo sólo ocupa 1byte en playerInfo
printf_s("Introduce datos de player (hexadecimal): 0x");
scanf_s("%x", &playerInfo); //scanf_s guarda en una posición de memoria, por eso hay que pasarle referencia
fseek(stdin, 0, SEEK_END); //limpieza del buffer de scanf, para evitar que al meter un carácter hexadecimal no válido, el switch entre en bucle por default
while (flag) {
printf_s("---MENU---\n");
printf_s("Info de player: 0x%x\n", playerInfo);
printf_s("1 - Retornar numero de balas\n");
printf_s("2 - Anadir 10 balas\n");
printf_s("3 - Balas infinitas?\n");
printf_s("4 - Activar balas infinitas\n");
printf_s("5 - Salir\n");
scanf_s("%hhu", &option); //%hhu para que recoja el valor como un unsigned char
switch (option)
{
case 1:
system("CLS");
ammo = returnAmmo(playerInfo);
printf_s("Numero de balas: %hhu\n", ammo);
break;
case 2:
system("CLS");
if (returnAmmo(playerInfo) < 255) {
playerInfo = addAmmo(playerInfo, 10);
ammo = returnAmmo(playerInfo);
printf_s("Balas anadidas!\n");
printf_s("Numero de balas: %hhu\n", ammo);
} else
printf_s("Maximo de balas alcanzado\n");
break;
case 3:
system("CLS");
printf_s("Balas infinitas (0=false, 1=true)? %d\n", infiniteAmmo(playerInfo));
break;
case 4:
system("CLS");
if (!infiniteAmmo(playerInfo)) {
playerInfo = activateInfiniteAmmo(playerInfo);
printf_s("Balas infinitas activadas!\n");
printf_s("Balas infinitas? %d\n", infiniteAmmo(playerInfo));
} else
printf_s("Modo balas infinitas ya activado\n");
break;
case 5:
system("CLS");
flag = 0;
break;
default:
system("CLS");
break;
}
}
return 0;
} |
de913416ed1bdb635b40c3407f0d075510a0a02f | 1fdd1e6e908ded6f220bb606c8c8295e0cd95b19 | /315 - ALGORITHMS/Algorithms_THE3/the3.cpp | 77f604a4ca9f60dd06e2f1fc883b4ed2593c8744 | [] | no_license | CemBirbiri/Computer-Engineering-Bachelor-at-METU-2015-2021 | a00024a4217d89e0e954c0682d5bd1aed74aa663 | 416b7e9114a5d1b2ff61baf616ba4c75b443f7f2 | refs/heads/main | 2023-06-22T22:18:18.110716 | 2023-06-08T15:19:58 | 2023-06-08T15:19:58 | 349,983,329 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,571 | cpp | the3.cpp | //#include "the3.h"
#include <bits/stdc++.h>
using namespace std;
// You can define extra functions here
/* A utility function to print solution */
void printSolution(int**& edgeList,int n)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (edgeList[i][j] == 99999)
cout<<"INF"<<" ";
else
cout<<edgeList[i][j]<<" ";
}
cout<<endl;
}
}
void printScores(double *& scores, int n){
for(int i=0; i< n; i++){
cout<<scores[i]<<" ";
}
cout<<" "<<endl;
}
void printArray(int *scores, int n){
for(int i=0; i< n; i++){
cout<<scores[i]<<" ";
}
cout<<" "<<endl;
}
void make_infinity(int n, int**& dist){
for(int i=0; i< n; i++){
for(int j=0; j<n; j++){
if(i==j) continue;
else if(dist[i][j]==0)
dist[i][j]= 99999;
}
}
}
// INPUT :
// n : number of nodes in the graph
// edgeList : edges in the graph
// scores : importance scores
// return value :
// number of disconnected components
int Important (int n, int **&edgeList, double *& scores)
{
int i, j, k;
int **dist;
dist = new int*[n];
for (int i = 0; i < n; ++i) {
dist[i] = new int[n];
}
for(int i =0 ; i<n;i++){
for(int j=0; j<n;j++){
dist[i][j] = edgeList[i][j];
}
}
make_infinity(n, dist);
double sum = 0;
printSolution(dist,n);
//Finding the all shortest paths using Floyd-Warshall alg.
for (int k = 0; k < n; k++){
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++){
if (dist[i][k] + dist[k][j] < dist[i][j])
dist[i][j] = dist[i][k] + dist[k][j];
if (dist[j][k] + dist[k][i] < dist[j][i])
dist[j][i] = dist[j][k] + dist[k][i];
}
}
}
//Calculating the scores
for (k = 0; k < n; k++) {
for (i = 0; i < n; i++){
for (j = 0; j < n; j++) {
if(dist[i][k] == 99999 || dist[j][k] == 99999 || dist[i][j]==99999 ){continue;}
else if(i==k || j==k){continue;}
else if(i==j){
sum = sum + (dist[i][k] + dist[k][j]) / 1.0; }
else{
sum = sum + ( ((dist[i][k] + dist[k][j])*1.0 )/ (1.0*dist[i][j]) );}
}
}
scores[k]=sum;
sum=0;
}
int count=1;
int array[n];
for(i=0 ; i < n; i++){
array[i]=0;
}
int flag;
//int flag2;
//Finding the number of disconnected graphs
for (int i = 0; i < n; i++) {
flag = n;
//flag2=0;
for (int j = 0; j < n; j++){
if( dist[i][j] != 0 && dist[i][j] != 99999){
for(int k=0; k<n ; k++){
if(dist[j][k] != 0 && dist[j][k] != 99999){
if(array[k] == 0){
array[k]= count;
flag = flag -1 ;
//flag2= 1;
}
}
}
}
if( j == n-1 && flag==n){ //&& flag2 == 0){
//cout<< j << count<<endl;
if(array[i]==0 && i!=0){
array[i] = count;
count = count + 1;
}
}
else if( j == n-1 && flag!=n ){
count = count + 1;
}
}
//count = count +1;
}
int max=0;
for(i=0; i< n; i++){
if(array[i] > max)
max= array[i];
}
cout<<"maxxxxxxxxxx-> "<<max<<endl;
cout<<"array-> "<<endl;
printArray(array, n);
cout<<" "<<endl;
cout<<" "<<endl;
cout<<" "<<endl;
cout<<"dist-> "<<endl;
printSolution(dist ,n );
cout<<" "<<endl;
cout<<" "<<endl;
cout<<" "<<endl;
cout<<"EdgeList-> "<<endl;
printSolution(edgeList ,n );
//cout<<"Scores-> "<<endl;
//printScores(scores, n);
return max;
}
int main(){
double *scores = new double[5];
int **edgeList = new int*[5];
int edgelist[5][5] = {0, 0, 2, 5, 3,0, 0, 0, 2, 3,2, 0, 0, 1, 0,5, 2, 1, 0, 4,3, 3, 0, 4, 0};
for (int i = 0; i < 5; ++i) {
edgeList[i] = new int[5];
}
for(int i =0 ; i<5;i++){
for(int j=0; j<5;j++){
edgeList[i][j] = edgelist[i][j];
}
}
Important(5, edgeList , scores);
/*
double *scores = new double[6];
int **edgeList = new int*[6];
int edgelist[6][6] = {0, 0, 0, 3, 0, 2,
0 ,0, 3, 0, 2, 0,
0, 3, 0, 0, 0, 0,
3, 0, 0, 0, 0, 4,
0, 2, 0, 0, 0, 0,
2, 0, 0, 4, 0, 0};
for (int i = 0; i < 6; ++i) {
edgeList[i] = new int[6];
}
for(int i =0 ; i<6;i++){
for(int j=0; j<6;j++){
edgeList[i][j] = edgelist[i][j];
}
}
*/
/*
double *scores = new double[6];
int **edgeList = new int*[6];
int edgelist[6][6] = {0, 0, 1, 0, 10, 3,
0 ,0, 0, 0, 0, 0,
1, 0, 0, 0, 8, 9,
0, 0, 0, 0, 0, 0,
10, 0, 8, 0, 0, 0,
3, 0, 9, 0, 0, 0};
for (int i = 0; i < 6; ++i) {
edgeList[i] = new int[6];
}
for(int i =0 ; i<6;i++){
for(int j=0; j<6;j++){
edgeList[i][j] = edgelist[i][j];
}
}
Important(6, edgeList , scores);
*/
/*
double *scores = new double[2];
int **edgeList = new int*[2];
int edgelist[2][2] = {0, 17,
17 ,0
};
for (int i = 0; i < 2; ++i) {
edgeList[i] = new int[2];
}
for(int i =0 ; i<2;i++){
for(int j=0; j<2;j++){
edgeList[i][j] = edgelist[i][j];
}
}
Important(2, edgeList , scores);*/
return 0;
}
|
ae6c1c11d9d5dc0f1f4d90fa05e221dbd56251b5 | 53700448a09a28fa7979954599e9c2e3395b8223 | /src/KSegmentor/include/KoupledKurvolver.h | bb6cb49a874048fa3a8502fdc4bf6f3c2409fb12 | [] | no_license | radinhamidi/kslice | 8f417f287daa92f2cd24a5b56774e9d239ae83b3 | b5d71ddaadd67f0bdef6b0869cc272e7b69deb07 | refs/heads/master | 2021-01-13T03:39:34.365630 | 2015-05-16T13:52:21 | 2015-05-16T13:52:21 | 77,254,540 | 1 | 0 | null | 2016-12-23T22:49:23 | 2016-12-23T22:49:23 | null | UTF-8 | C++ | false | false | 364 | h | KoupledKurvolver.h | #ifndef KOUPLED_KURVOLVER_H
#define KOUPLED_KURVOLVER_H
class KoupledKurvolver
{
public:
struct Options {
Options(int ac, char* av [] );
// use Boost Program Options to parse and setup
};
public:
KoupledKurvolver(const KoupledKurvolver::Options& opts_in);
void Print();
private:
KoupledKurvolver() { }
};
#endif // KOUPLED_KURVOLVER_H
|
6754f87c1172c61d1fa31aed638dd6e8e90d514e | bbd54c2bc2fc923868c6f7701443a798a0e79ad2 | /leetcode/672.cpp | 62362a85af8dcc3afe9950f182fe43a0f29430cb | [] | no_license | Rearcher/OJcodes | 7e07316397b4fb957e2ff2a9ecbf5ec95d6c63a0 | 634d459ee586712bf89e404324a22534099e66a9 | refs/heads/master | 2021-06-07T18:39:23.058122 | 2019-12-10T07:25:13 | 2019-12-10T07:25:13 | 36,869,609 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 312 | cpp | 672.cpp | // 672. Bulb Switcher II
#include "leetcode.hpp"
using namespace std;
class Solution {
public:
int flipLight(int n, int m) {
if (m == 0 || n == 0) return 1;
if (n == 1) return 2;
if (n == 2) return m == 1 ? 3 : 4;
if (m == 1) return 4;
return m == 2 ? 7 : 8;
}
}; |
5023bf1a66e6d8689554094a0e258c6365ce9124 | de2c80118deaad2b89170fb25e735c8d6d2f2ba2 | /insertionSort.cpp | 9b556268507411499d24f66664b7f45f86146213 | [] | no_license | DuyTran1234/Sort | 8abe5c328e5f2ecf4d97a79b86b095f03862e267 | b8fd6355853912f93d107b3616f0ce33de47b2e1 | refs/heads/master | 2020-08-06T10:13:14.501107 | 2019-10-05T03:40:17 | 2019-10-05T03:40:17 | 212,939,353 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 356 | cpp | insertionSort.cpp | #ifndef _INSERTIONSORT_CPP
#define _INSERTIONSORT_CPP
void insertionSort(int arr[], int n)
{
for(int i = 1; i < n; i++)
{
int j = i - 1;
int temp = arr[i];
while(j >= 0 && arr[j] > temp)
{
arr[j + 1] = arr[j];
j--;
}
int key = j + 1;
arr[key] = temp;
}
}
#endif
|
925d205e2959057145a28eb0ed84c38634f195ef | ed75b1d4d9eb83a98f0688ae90418a8399c5cf7c | /linker/p4/test.cpp | d687ce2e4165ddc069d29b17daf20f645879128e | [] | no_license | vivekp/C-and-Cplusplus-Programs | df762698dcb1a4f3e0e378bf9f71ddb837ea959d | a79e49d57ce590bd1de4e31e56bae0db095eeca1 | refs/heads/master | 2016-08-08T03:22:10.805674 | 2011-11-11T14:39:23 | 2011-11-11T14:53:19 | 2,756,339 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 151 | cpp | test.cpp | #include <iostream>
using namespace std;
extern int func(int );
int j=20;
int main()
{
int num;
num=func(3);
cout<<num;
return 0;
}
|
fd8abbbe21ed0b00a65e567315f18385407469f0 | e7b656b502220c63991410c634af961e51e35c00 | /src/kicontheme.cpp | dee02ff7bba1807794ab52fe5f1cbb98158faea3 | [] | no_license | KDE/kiconthemes | f17b6cb77066ec911d27dea0395d68a5056fae60 | c367ed65ac786580f9f80186d70a7a16a92bede7 | refs/heads/master | 2023-08-08T08:56:11.349037 | 2023-08-06T02:19:49 | 2023-08-06T02:19:49 | 42,726,037 | 15 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 26,063 | cpp | kicontheme.cpp | /* vi: ts=8 sts=4 sw=4
kicontheme.cpp: Lowlevel icon theme handling.
This file is part of the KDE project, module kdecore.
SPDX-FileCopyrightText: 2000 Geert Jansen <jansen@kde.org>
SPDX-FileCopyrightText: 2000 Antonio Larrosa <larrosa@kde.org>
SPDX-License-Identifier: LGPL-2.0-only
*/
#include "kicontheme.h"
#include "debug.h"
#include <KConfigGroup>
#include <KLocalizedString> // KLocalizedString::localizedFilePath. Need such functionality in, hmm, QLocale? QStandardPaths?
#include <KSharedConfig>
#include <QAction>
#include <QCoreApplication>
#include <QDebug>
#include <QDir>
#include <QFileInfo>
#include <QMap>
#include <QResource>
#include <QSet>
#include <private/qguiapplication_p.h>
#include <qpa/qplatformtheme.h>
#include <qplatformdefs.h>
#include <array>
#include <cmath>
Q_GLOBAL_STATIC(QString, _themeOverride)
// Support for icon themes in RCC files.
// The intended use case is standalone apps on Windows / MacOS / etc.
// For this reason we use AppDataLocation: BINDIR/data on Windows, Resources on OS X
void initRCCIconTheme()
{
const QString iconThemeRcc = QStandardPaths::locate(QStandardPaths::AppDataLocation, QStringLiteral("icontheme.rcc"));
if (!iconThemeRcc.isEmpty()) {
const QString iconThemeName = QStringLiteral("kf6_rcc_theme");
const QString iconSubdir = QStringLiteral("/icons/") + iconThemeName;
if (QResource::registerResource(iconThemeRcc, iconSubdir)) {
if (QFileInfo::exists(QLatin1Char(':') + iconSubdir + QStringLiteral("/index.theme"))) {
// Tell Qt about the theme
// Note that since qtbase commit a8621a3f8, this means the QPA (i.e. KIconLoader) will NOT be used.
QIcon::setThemeName(iconThemeName); // Qt looks under :/icons automatically
// Tell KIconTheme about the theme, in case KIconLoader is used directly
*_themeOverride() = iconThemeName;
} else {
qWarning() << "No index.theme found in" << iconThemeRcc;
QResource::unregisterResource(iconThemeRcc, iconSubdir);
}
} else {
qWarning() << "Invalid rcc file" << iconThemeRcc;
}
}
}
Q_COREAPP_STARTUP_FUNCTION(initRCCIconTheme)
// Makes sure the icon theme fallback is set to breeze or one of its
// variants. Most of our apps use "lots" of icons that most of the times
// are only available with breeze, we still honour the user icon theme
// but if the icon is not found there, we go to breeze since it's almost
// sure it'll be there
static void setBreezeFallback()
{
if (const QPlatformTheme *theme = QGuiApplicationPrivate::platformTheme()) {
const QVariant themeHint = theme->themeHint(QPlatformTheme::SystemIconFallbackThemeName);
if (themeHint.isValid()) {
const QString iconTheme = themeHint.toString();
if (iconTheme.contains(QStringLiteral("breeze"), Qt::CaseInsensitive)) {
QIcon::setFallbackThemeName(iconTheme);
return;
}
}
}
QIcon::setFallbackThemeName(QStringLiteral("breeze"));
}
Q_COREAPP_STARTUP_FUNCTION(setBreezeFallback)
class KIconThemeDir;
class KIconThemePrivate
{
public:
QString example, screenshot;
bool hidden;
KSharedConfig::Ptr sharedConfig;
struct GroupInfo {
KIconLoader::Group type;
const char *name;
int defaultSize;
QList<int> availableSizes{};
};
std::array<GroupInfo, KIconLoader::LastGroup> m_iconGroups = {{
{KIconLoader::Desktop, "Desktop", 32},
{KIconLoader::Toolbar, "Toolbar", 22},
{KIconLoader::MainToolbar, "MainToolbar", 22},
{KIconLoader::Small, "Small", 16},
{KIconLoader::Panel, "Panel", 48},
{KIconLoader::Dialog, "Dialog", 32},
}};
int mDepth;
QString mDir, mName, mInternalName, mDesc;
QStringList mInherits;
QStringList mExtensions;
QVector<KIconThemeDir *> mDirs;
QVector<KIconThemeDir *> mScaledDirs;
bool followsColorScheme : 1;
/// Searches the given dirs vector for a matching icon
QString iconPath(const QVector<KIconThemeDir *> &dirs, const QString &name, int size, qreal scale, KIconLoader::MatchType match) const;
};
Q_GLOBAL_STATIC(QString, _theme)
Q_GLOBAL_STATIC(QStringList, _theme_list)
/**
* A subdirectory in an icon theme.
*/
class KIconThemeDir
{
public:
KIconThemeDir(const QString &basedir, const QString &themedir, const KConfigGroup &config);
bool isValid() const
{
return mbValid;
}
QString iconPath(const QString &name) const;
QStringList iconList() const;
QString constructFileName(const QString &file) const
{
return mBaseDir + mThemeDir + QLatin1Char('/') + file;
}
KIconLoader::Context context() const
{
return mContext;
}
KIconLoader::Type type() const
{
return mType;
}
int size() const
{
return mSize;
}
int scale() const
{
return mScale;
}
int minSize() const
{
return mMinSize;
}
int maxSize() const
{
return mMaxSize;
}
int threshold() const
{
return mThreshold;
}
private:
bool mbValid = false;
KIconLoader::Type mType = KIconLoader::Fixed;
KIconLoader::Context mContext;
int mSize = 0;
int mScale = 1;
int mMinSize = 1;
int mMaxSize = 50;
int mThreshold = 2;
const QString mBaseDir;
const QString mThemeDir;
};
QString KIconThemePrivate::iconPath(const QVector<KIconThemeDir *> &dirs, const QString &name, int size, qreal scale, KIconLoader::MatchType match) const
{
QString path;
QString tempPath; // used to cache icon path if it exists
int delta = -INT_MAX; // current icon size delta of 'icon'
int dw = INT_MAX; // icon size delta of current directory
// Rather downsample than upsample
int integerScale = std::ceil(scale);
// Search the directory that contains the icon which matches best to the requested
// size. If there is no directory which matches exactly to the requested size, the
// following criteria get applied:
// - Take a directory having icons with a minimum difference to the requested size.
// - Prefer directories that allow a downscaling even if the difference to
// the requested size is bigger than a directory where an upscaling is required.
for (KIconThemeDir *dir : dirs) {
if (dir->scale() != integerScale) {
continue;
}
if (match == KIconLoader::MatchExact) {
if ((dir->type() == KIconLoader::Fixed) && (dir->size() != size)) {
continue;
}
if ((dir->type() == KIconLoader::Scalable) //
&& ((size < dir->minSize()) || (size > dir->maxSize()))) {
continue;
}
if ((dir->type() == KIconLoader::Threshold) //
&& (abs(dir->size() - size) > dir->threshold())) {
continue;
}
} else {
// dw < 0 means need to scale up to get an icon of the requested size.
// Upscaling should only be done if no larger icon is available.
if (dir->type() == KIconLoader::Fixed) {
dw = dir->size() - size;
} else if (dir->type() == KIconLoader::Scalable) {
if (size < dir->minSize()) {
dw = dir->minSize() - size;
} else if (size > dir->maxSize()) {
dw = dir->maxSize() - size;
} else {
dw = 0;
}
} else if (dir->type() == KIconLoader::Threshold) {
if (size < dir->size() - dir->threshold()) {
dw = dir->size() - dir->threshold() - size;
} else if (size > dir->size() + dir->threshold()) {
dw = dir->size() + dir->threshold() - size;
} else {
dw = 0;
}
}
// Usually if the delta (= 'dw') of the current directory is
// not smaller than the delta (= 'delta') of the currently best
// matching icon, this candidate can be skipped. But skipping
// the candidate may only be done, if this does not imply
// in an upscaling of the icon (it is OK to use a directory with
// smaller icons that what we've already found, however).
if ((abs(dw) >= abs(delta)) && ((dw < 0) || (delta > 0))) {
continue;
}
if (match == KIconLoader::MatchBestOrGreaterSize && dw < 0) {
continue;
}
}
// cache the result of iconPath() call which checks if file exists
tempPath = dir->iconPath(name);
if (tempPath.isEmpty()) {
continue;
}
path = tempPath;
// if we got in MatchExact that far, we find no better
if (match == KIconLoader::MatchExact) {
return path;
}
delta = dw;
if (delta == 0) {
return path; // We won't find a better match anyway
}
}
return path;
}
KIconTheme::KIconTheme(const QString &name, const QString &appName, const QString &basePathHint)
: d(new KIconThemePrivate)
{
d->mInternalName = name;
QStringList themeDirs;
// Applications can have local additions to the global "locolor" and
// "hicolor" icon themes. For these, the _global_ theme description
// files are used..
/* clang-format off */
if (!appName.isEmpty()
&& (name == defaultThemeName()
|| name == QLatin1String("hicolor")
|| name == QLatin1String("locolor"))) { /* clang-format on */
const QString suffix = QLatin1Char('/') + appName + QLatin1String("/icons/") + name + QLatin1Char('/');
QStringList dataDirs = QStandardPaths::standardLocations(QStandardPaths::GenericDataLocation);
for (auto &cDir : dataDirs) {
cDir += suffix;
if (QFileInfo::exists(cDir)) {
themeDirs += cDir;
}
}
if (!basePathHint.isEmpty()) {
// Checks for dir existing are done below
themeDirs += basePathHint + QLatin1Char('/') + name + QLatin1Char('/');
}
}
// Find the theme description file. These are either locally in the :/icons resource path or global.
QStringList icnlibs;
// local embedded icons have preference
icnlibs << QStringLiteral(":/icons");
// global icons
icnlibs += QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QStringLiteral("icons"), QStandardPaths::LocateDirectory);
// These are not in the icon spec, but e.g. GNOME puts some icons there anyway.
icnlibs += QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QStringLiteral("pixmaps"), QStandardPaths::LocateDirectory);
QString fileName;
QString mainSection;
const QString pathSuffix = QLatin1Char('/') + name + QLatin1Char('/');
const QLatin1String indexTheme("index.theme");
const QLatin1String indexDesktop("theme.desktop");
for (auto &iconDir : icnlibs) {
iconDir += pathSuffix;
const QFileInfo fi(iconDir);
if (!fi.exists() || !fi.isDir()) {
continue;
}
themeDirs.append(iconDir);
if (d->mDir.isEmpty()) {
QString possiblePath;
if (possiblePath = iconDir + indexTheme; QFileInfo::exists(possiblePath)) {
d->mDir = iconDir;
fileName = possiblePath;
mainSection = QStringLiteral("Icon Theme");
} else if (possiblePath = iconDir + indexDesktop; QFileInfo::exists(possiblePath)) {
d->mDir = iconDir;
fileName = possiblePath;
mainSection = QStringLiteral("KDE Icon Theme");
}
}
}
if (d->mDir.isEmpty()) {
qCDebug(KICONTHEMES) << "Icon theme" << name << "not found.";
return;
}
// Use KSharedConfig to avoid parsing the file many times, from each component.
// Need to keep a ref to it to make this useful
d->sharedConfig = KSharedConfig::openConfig(fileName, KConfig::NoGlobals);
KConfigGroup cfg(d->sharedConfig, mainSection);
d->mName = cfg.readEntry("Name");
d->mDesc = cfg.readEntry("Comment");
d->mDepth = cfg.readEntry("DisplayDepth", 32);
d->mInherits = cfg.readEntry("Inherits", QStringList());
if (name != defaultThemeName()) {
for (auto &inheritedTheme : d->mInherits) {
if (inheritedTheme == QLatin1String("default")) {
inheritedTheme = defaultThemeName();
}
}
}
d->hidden = cfg.readEntry("Hidden", false);
d->followsColorScheme = cfg.readEntry("FollowsColorScheme", false);
d->example = cfg.readPathEntry("Example", QString());
d->screenshot = cfg.readPathEntry("ScreenShot", QString());
d->mExtensions =
cfg.readEntry("KDE-Extensions", QStringList{QStringLiteral(".png"), QStringLiteral(".svgz"), QStringLiteral(".svg"), QStringLiteral(".xpm")});
QSet<QString> addedDirs; // Used for avoiding duplicates.
const QStringList dirs = cfg.readPathEntry("Directories", QStringList()) + cfg.readPathEntry("ScaledDirectories", QStringList());
for (const auto &dirName : dirs) {
KConfigGroup cg(d->sharedConfig, dirName);
for (const auto &themeDir : std::as_const(themeDirs)) {
const QString currentDir(themeDir + dirName + QLatin1Char('/'));
if (!addedDirs.contains(currentDir) && QDir(currentDir).exists()) {
addedDirs.insert(currentDir);
KIconThemeDir *dir = new KIconThemeDir(themeDir, dirName, cg);
if (dir->isValid()) {
if (dir->scale() > 1) {
d->mScaledDirs.append(dir);
} else {
d->mDirs.append(dir);
}
} else {
delete dir;
}
}
}
}
KConfigGroup cg(d->sharedConfig, mainSection);
for (auto &iconGroup : d->m_iconGroups) {
iconGroup.defaultSize = cg.readEntry(iconGroup.name + QLatin1String("Default"), iconGroup.defaultSize);
iconGroup.availableSizes = cg.readEntry(iconGroup.name + QLatin1String("Sizes"), QList<int>());
}
}
KIconTheme::~KIconTheme()
{
qDeleteAll(d->mDirs);
qDeleteAll(d->mScaledDirs);
}
QString KIconTheme::name() const
{
return d->mName;
}
QString KIconTheme::internalName() const
{
return d->mInternalName;
}
QString KIconTheme::description() const
{
return d->mDesc;
}
QString KIconTheme::example() const
{
return d->example;
}
QString KIconTheme::screenshot() const
{
return d->screenshot;
}
QString KIconTheme::dir() const
{
return d->mDir;
}
QStringList KIconTheme::inherits() const
{
return d->mInherits;
}
bool KIconTheme::isValid() const
{
return !d->mDirs.isEmpty() || !d->mScaledDirs.isEmpty();
}
bool KIconTheme::isHidden() const
{
return d->hidden;
}
int KIconTheme::depth() const
{
return d->mDepth;
}
int KIconTheme::defaultSize(KIconLoader::Group group) const
{
if (group < 0 || group >= KIconLoader::LastGroup) {
qCWarning(KICONTHEMES) << "Invalid icon group:" << group << ", should be one of KIconLoader::Group";
return -1;
}
return d->m_iconGroups[group].defaultSize;
}
QList<int> KIconTheme::querySizes(KIconLoader::Group group) const
{
if (group < 0 || group >= KIconLoader::LastGroup) {
qCWarning(KICONTHEMES) << "Invalid icon group:" << group << ", should be one of KIconLoader::Group";
return QList<int>();
}
return d->m_iconGroups[group].availableSizes;
}
static bool isAnyOrDirContext(const KIconThemeDir *dir, KIconLoader::Context context)
{
return context == KIconLoader::Any || context == dir->context();
}
QStringList KIconTheme::queryIcons(int size, KIconLoader::Context context) const
{
// Try to find exact match
QStringList result;
const QVector<KIconThemeDir *> listDirs = d->mDirs + d->mScaledDirs;
for (const KIconThemeDir *dir : listDirs) {
if (!isAnyOrDirContext(dir, context)) {
continue;
}
const int dirSize = dir->size();
if ((dir->type() == KIconLoader::Fixed && dirSize == size) //
|| (dir->type() == KIconLoader::Scalable && size >= dir->minSize() && size <= dir->maxSize())
|| (dir->type() == KIconLoader::Threshold && abs(size - dirSize) < dir->threshold())) {
result += dir->iconList();
}
}
return result;
}
QStringList KIconTheme::queryIconsByContext(int size, KIconLoader::Context context) const
{
int dw;
// We want all the icons for a given context, but we prefer icons
// of size "size" . Note that this may (will) include duplicate icons
// QStringList iconlist[34]; // 33 == 48-16+1
QStringList iconlist[128]; // 33 == 48-16+1
// Usually, only the 0, 6 (22-16), 10 (32-22), 16 (48-32 or 32-16),
// 26 (48-22) and 32 (48-16) will be used, but who knows if someone
// will make icon themes with different icon sizes.
const auto listDirs = d->mDirs + d->mScaledDirs;
for (KIconThemeDir *dir : listDirs) {
if (!isAnyOrDirContext(dir, context)) {
continue;
}
dw = abs(dir->size() - size);
iconlist[(dw < 127) ? dw : 127] += dir->iconList();
}
QStringList iconlistResult;
for (int i = 0; i < 128; i++) {
iconlistResult += iconlist[i];
}
return iconlistResult;
}
bool KIconTheme::hasContext(KIconLoader::Context context) const
{
const auto listDirs = d->mDirs + d->mScaledDirs;
for (KIconThemeDir *dir : listDirs) {
if (isAnyOrDirContext(dir, context)) {
return true;
}
}
return false;
}
QString KIconTheme::iconPathByName(const QString &iconName, int size, KIconLoader::MatchType match) const
{
return iconPathByName(iconName, size, match, 1 /*scale*/);
}
QString KIconTheme::iconPathByName(const QString &iconName, int size, KIconLoader::MatchType match, qreal scale) const
{
for (const QString ¤t : std::as_const(d->mExtensions)) {
const QString path = iconPath(iconName + current, size, match, scale);
if (!path.isEmpty()) {
return path;
}
}
return QString();
}
bool KIconTheme::followsColorScheme() const
{
return d->followsColorScheme;
}
QString KIconTheme::iconPath(const QString &name, int size, KIconLoader::MatchType match) const
{
return iconPath(name, size, match, 1 /*scale*/);
}
QString KIconTheme::iconPath(const QString &name, int size, KIconLoader::MatchType match, qreal scale) const
{
// first look for a scaled image at exactly the requested size
QString path = d->iconPath(d->mScaledDirs, name, size, scale, KIconLoader::MatchExact);
// then look for an unscaled one but request it at larger size so it doesn't become blurry
if (path.isEmpty()) {
path = d->iconPath(d->mDirs, name, size * scale, 1, match);
}
return path;
}
// static
QString KIconTheme::current()
{
// Static pointers because of unloading problems wrt DSO's.
if (_themeOverride && !_themeOverride->isEmpty()) {
*_theme() = *_themeOverride();
}
if (!_theme()->isEmpty()) {
return *_theme();
}
QString theme;
// Check application specific config for a theme setting.
KConfigGroup app_cg(KSharedConfig::openConfig(QString(), KConfig::NoGlobals), "Icons");
theme = app_cg.readEntry("Theme", QString());
if (theme.isEmpty() || theme == QLatin1String("hicolor")) {
// No theme, try to use Qt's. A Platform plugin might have set
// a good theme there.
theme = QIcon::themeName();
}
if (theme.isEmpty() || theme == QLatin1String("hicolor")) {
// Still no theme, try config with kdeglobals.
KConfigGroup cg(KSharedConfig::openConfig(), "Icons");
theme = cg.readEntry("Theme", QStringLiteral("breeze"));
}
if (theme.isEmpty() || theme == QLatin1String("hicolor")) {
// Still no good theme, use default.
theme = defaultThemeName();
}
*_theme() = theme;
return *_theme();
}
void KIconTheme::forceThemeForTests(const QString &themeName)
{
*_themeOverride() = themeName;
_theme()->clear(); // ::current sets this again based on conditions
}
// static
QStringList KIconTheme::list()
{
// Static pointer because of unloading problems wrt DSO's.
if (!_theme_list()->isEmpty()) {
return *_theme_list();
}
// Find the theme description file. These are either locally in the :/icons resource path or global.
QStringList icnlibs;
// local embedded icons have preference
icnlibs << QStringLiteral(":/icons");
// global icons
icnlibs += QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QStringLiteral("icons"), QStandardPaths::LocateDirectory);
// These are not in the icon spec, but e.g. GNOME puts some icons there anyway.
icnlibs += QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QStringLiteral("pixmaps"), QStandardPaths::LocateDirectory);
for (const QString &iconDir : std::as_const(icnlibs)) {
QDir dir(iconDir);
const QStringList themeDirs = dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot);
for (const auto &theme : themeDirs) {
if (theme.startsWith(QLatin1String("default."))) {
continue;
}
const QString prefix = iconDir + QLatin1Char('/') + theme;
if (!QFileInfo::exists(prefix + QLatin1String("/index.desktop")) //
&& !QFileInfo::exists(prefix + QLatin1String("/index.theme"))) {
continue;
}
if (!KIconTheme(theme).isValid()) {
continue;
}
if (!_theme_list()->contains(theme)) {
_theme_list()->append(theme);
}
}
}
return *_theme_list();
}
// static
void KIconTheme::reconfigure()
{
_theme()->clear();
_theme_list()->clear();
}
// static
QString KIconTheme::defaultThemeName()
{
return QStringLiteral("hicolor");
}
/*** KIconThemeDir ***/
KIconThemeDir::KIconThemeDir(const QString &basedir, const QString &themedir, const KConfigGroup &config)
: mSize(config.readEntry("Size", 0))
, mScale(config.readEntry("Scale", 1))
, mBaseDir(basedir)
, mThemeDir(themedir)
{
if (mSize == 0) {
return;
}
QString tmp = config.readEntry(QStringLiteral("Context"));
if (tmp == QLatin1String("Devices")) {
mContext = KIconLoader::Device;
} else if (tmp == QLatin1String("MimeTypes")) {
mContext = KIconLoader::MimeType;
} else if (tmp == QLatin1String("Applications")) {
mContext = KIconLoader::Application;
} else if (tmp == QLatin1String("Actions")) {
mContext = KIconLoader::Action;
} else if (tmp == QLatin1String("Animations")) {
mContext = KIconLoader::Animation;
} else if (tmp == QLatin1String("Categories")) {
mContext = KIconLoader::Category;
} else if (tmp == QLatin1String("Emblems")) {
mContext = KIconLoader::Emblem;
} else if (tmp == QLatin1String("Emotes")) {
mContext = KIconLoader::Emote;
} else if (tmp == QLatin1String("International")) {
mContext = KIconLoader::International;
} else if (tmp == QLatin1String("Places")) {
mContext = KIconLoader::Place;
} else if (tmp == QLatin1String("Status")) {
mContext = KIconLoader::StatusIcon;
} else if (tmp == QLatin1String("Stock")) { // invalid, but often present context, skip warning
return;
} else if (tmp == QLatin1String("Legacy")) { // invalid, but often present context for Adwaita, skip warning
return;
} else if (tmp == QLatin1String("UI")) { // invalid, but often present context for Adwaita, skip warning
return;
} else if (tmp.isEmpty()) {
// do nothing. key not required
} else {
qCDebug(KICONTHEMES) << "Invalid Context=" << tmp << "line for icon theme: " << constructFileName(QString());
return;
}
tmp = config.readEntry(QStringLiteral("Type"), QStringLiteral("Threshold"));
if (tmp == QLatin1String("Fixed")) {
mType = KIconLoader::Fixed;
} else if (tmp == QLatin1String("Scalable")) {
mType = KIconLoader::Scalable;
} else if (tmp == QLatin1String("Threshold")) {
mType = KIconLoader::Threshold;
} else {
qCDebug(KICONTHEMES) << "Invalid Type=" << tmp << "line for icon theme: " << constructFileName(QString());
return;
}
if (mType == KIconLoader::Scalable) {
mMinSize = config.readEntry(QStringLiteral("MinSize"), mSize);
mMaxSize = config.readEntry(QStringLiteral("MaxSize"), mSize);
} else if (mType == KIconLoader::Threshold) {
mThreshold = config.readEntry(QStringLiteral("Threshold"), 2);
}
mbValid = true;
}
QString KIconThemeDir::iconPath(const QString &name) const
{
if (!mbValid) {
return QString();
}
const QString file = constructFileName(name);
if (QFileInfo::exists(file)) {
return KLocalizedString::localizedFilePath(file);
}
return QString();
}
QStringList KIconThemeDir::iconList() const
{
const QDir icondir = constructFileName(QString());
const QStringList formats = QStringList() << QStringLiteral("*.png") << QStringLiteral("*.svg") << QStringLiteral("*.svgz") << QStringLiteral("*.xpm");
const QStringList lst = icondir.entryList(formats, QDir::Files);
QStringList result;
result.reserve(lst.size());
for (const QString &file : lst) {
result += constructFileName(file);
}
return result;
}
|
12bba072a5796b6cf75ce4f9378ea292b1bb6039 | e679867c6c884778b3429e102e989925058d868c | /CoreModule/COMMUNICATION_MODULE/include/WindowsServer.h | 2e736cc08ee088294c38bd7b88159471cf4a9564 | [] | no_license | CharlieBr/Smeshalist | 3ce37eecc4942ec88331bc70c7ff9f95f3205db0 | 2f2963580c9700ef30eb0a7660b15d35fed7b92f | refs/heads/master | 2021-01-17T02:39:35.933778 | 2017-01-05T19:55:28 | 2017-01-05T19:55:28 | 56,520,645 | 1 | 0 | null | 2016-12-15T18:47:15 | 2016-04-18T15:42:28 | C | UTF-8 | C++ | false | false | 758 | h | WindowsServer.h | #ifndef WINDOWSSERVER_H
#define WINDOWSSERVER_H
#include "AbstractServer.h"
#include <winsock.h>
#include <thread>
#pragma comment(lib, "ws2_32.lib")
class WindowsServer : public AbstractServer
{
public:
WindowsServer();
void startServer();
void stopServer();
protected:
private:
SOCKET* createSocket(sockaddr_in*, int);
int getBytesFromSocket(char[], int);
int sendBytesToSocket(char[], int);
int getBytesFromSMsocket(char[], int);
int sendBytesToSMsocket(char[], int);
SOCKET sock;
SOCKET sockSM;
WSADATA wsa;
struct sockaddr_in sockaddr;
struct sockaddr_in sockaddrSM;
struct sockaddr client;
struct sockaddr clientSM;
int slen;
thread* t;
thread* tSM;
};
#endif // WINDOWSSERVER_H
|
cd755afd199145dcca6476aa66b21bb1583cb3cb | 575c265b54bbb7f20b74701753174678b1d5ce2c | /hpkj/Classes/gui/PropLayer.h | 65083a809f98f46886279adcc7e8cc1100266b41 | [] | no_license | larryzen/Project3.x | c8c8a0be1874647909fcb1a0eb453c46d6d674f1 | cdc2bf42ea737c317fe747255d2ff955f80dbdae | refs/heads/master | 2020-12-04T21:27:46.777239 | 2019-03-02T06:30:26 | 2019-03-02T06:30:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 532 | h | PropLayer.h | #ifndef __Game__PropLayer__
#define __Game__PropLayer__
#include "CocosUnits.h"
#include "ConfigMgr.h"
#include "AnsString.h"
#include <iostream>
#include "cocos2d.h"
#include "cocos-ext.h"
USING_NS_CC;
USING_NS_CC_EXT;
class PropLayer : public Layer
{
public:
PropLayer();
~PropLayer();
virtual bool init();
static Scene* scene();
CREATE_FUNC(PropLayer);
public:
void dismiss(Object *obj);
void makeSure(Object *obj);
private:
EditBox *m_pUserInput;
EditBox *m_pUserVerifyInput;
};
#endif //__Game__PropLayer__ |
d5974449e4edc568228432b7455e0a2ba1ee7db7 | 659959b2eda51c98ccc7866f460f1de095a71b25 | /include/BoundaryCondition.h | 30fa719e9520488b522a493b202462dc20b6c60e | [] | no_license | yfygod/AFEPack | beb7a6e68823b4eeaa2f918b6809ad8b8ea50c75 | af7a5d6377c93083944ab99b6ed534c761df6180 | refs/heads/master | 2020-09-03T07:14:12.075507 | 2019-11-11T12:55:26 | 2019-11-11T12:55:26 | 219,414,098 | 1 | 2 | null | null | null | null | GB18030 | C++ | false | false | 9,136 | h | BoundaryCondition.h | /**
* @file BoundaryCondition.h
* @author Robert Lie
* @date Mon Nov 27 12:17:41 2006
*
* @brief
*
*
*/
#ifndef __BoundaryCondition_h__
#define __BoundaryCondition_h__
#include <cstdarg>
#include <vector>
#include <set>
#include <map>
#include "Miscellaneous.h"
/**
* 边界条件的基类。这个类拥有一个边界类型整数 _type,用以表征它描述
* 的边界条件的类型,目前,这个类型事实上主要是具有象征意义,我们能
* 够自动处理的还是只有狄氏边界条件。
*
* 另外,这个类还管理着一个材料标识的数组表示具有这些材料标识的自由
* 度都将会使用本边界条件,这个数组可以通过 add_mark 函数来进行管理。
* 注意:边界条件的材料标识只能加不能减的!
*
* 两个虚函数 value 和 gradient 用来给派生类做接口,一个计算边界函数
* 的函数值,一个计算边界函数的梯度向量。
*
*/
class BCondition {
public:
/// 三种基本的边界类型,作为本类的静态变量
static const int DIRICHLET;
static const int NEUMANN;
static const int ROBIN;
public:
/*@\{*/
/// 构造函数和析构函数
BCondition() {}
BCondition(int type) : _type(type) {}
BCondition(const BCondition& b) :
_type(b._type), _bmark(b._bmark) {}
virtual ~BCondition() {}
/*@\}*/
public:
/// 拷贝操作符
BCondition& operator=(const BCondition& b) {
_type = b._type;
_bmark = b._bmark;
return *this;
}
/*@\{*/
/// 读写边界的类型
int type() const {return _type;}
int& type() {return _type;}
/*@\}*/
/*@\{*/
/// 读写材料标识数组
const std::set<int, std::less<int> >& bound_mark() const {return _bmark;}
std::set<int, std::less<int> >& bound_mark() {return _bmark;}
/*@\}*/
/*@\{*/
/// 往材料标识数组中加入材料标识
void add_mark(int bm) {add_one_mark(bm);}
void add_mark(const std::vector<int>& bm) {
u_int n = bm.size();
for (u_int i = 0;i < n;++ i) {
add_one_mark(bm[i]);
}
}
template <class V>
void add_mark(u_int n, const V& bm) {
for (u_int i = 0;i < n;i ++) {
add_one_mark(bm[i]);
}
}
void add_mark(u_int n, int bm0, int bm1, ...) {
add_one_mark(bm0);
add_one_mark(bm1);
va_list ap;
va_start(ap, bm1);
for (u_int i = 2;i < n;i ++) {
add_one_mark(va_arg(ap, int));
}
va_end(ap);
}
/*@\}*/
private:
void add_one_mark(int bm) {
if (bm == 0) {
std::cerr << "警告:材料标识 0 表示区域内部,不能加给边界条件。"
<< std::endl;
return;
}
_bmark.insert(bm);
}
public:
/// 边界条件函数的求值函数
virtual void value(const void * p, void * v) const {}
/// 边界条件函数的求梯度函数
virtual void gradient(const void * p, void * g) const {}
private:
int _type; /// 边界的类型
std::set<int, std::less<int> > _bmark; /// 材料标识数组
};
/**
* 通过使用函数指针来实现 value 和 gradient 两个函数的边界条件。
*
*/
template <class P, class V, class G = std::vector<V> >
class BCFunction : public BCondition {
public:
typedef void (*val_fun_t)(const P&, V&);
typedef void (*grad_fun_t)(const P&, G&);
private:
static void _default_val(const P& p, V& v) {v = V();}
static void _default_grad(const P& p, G& g) {g = G();}
val_fun_t _val_fun; /// 求值函数指针
grad_fun_t _grad_fun; /// 求梯度函数指针
public:
BCFunction(val_fun_t vf = &_default_val,
grad_fun_t gf = &_default_grad) :
_val_fun(vf),
_grad_fun(gf) {}
BCFunction(int type,
val_fun_t vf = &_default_val,
grad_fun_t gf = &_default_grad) :
BCondition(type),
_val_fun(vf),
_grad_fun(gf) {}
virtual ~BCFunction() {}
public:
/*@\{*/
/// 读写两个函数指针变量。
const val_fun_t& value_fun_ptr() const {
return _val_fun;
}
val_fun_t& value_fun_ptr() {
return _val_fun;
}
const grad_fun_t& gradient_fun_ptr() const {
return _grad_fun;
}
grad_fun_t& gradient_fun_ptr() {
return _grad_fun;
}
/*@\}*/
public:
/*@\{*/
/// 通过调用函数指针的变量来进行求值和求梯度。
virtual void value(const void * p, void * v) const {
(*_val_fun)(*(const P *)p, *(V *)v);
}
virtual void gradient(const void * p, void * g) const {
(*_grad_fun)(*(const P *)p, *(G *)g);
}
/*@\}*/
};
/**
* 边界条件管理器。这个类管理着一堆的边界条件,然后在具体特定的材料
* 标识的自由度处使用相应的边界条件。目前,这个类还很粗糙,只能自动
* 处理一定情况下的狄氏边值。这个一定情况指的是:
*
* - 单元上的基函数在它们的插值点上是正交的;
* - 基函数在自己插值点上的值取 1;
*
* 在其它情况下,这里的处理方法会给出错误的结果。
*
* 使用本函数中定义的这几个类的典型代码行如下:
*
* <pre>
*
* BCFunction<Point<DIM>, double> bc(BCondition::DIRICHLET, u_b);
* bc.add_mark(5, 1, 2, 3, 4, 5);
* BCAdmin bc_admin;
* bc_admin.add(bc);
* bc_admin.apply(fem_space, mat, u_h, rhs);
*
* </pre>
*
* 其中定义了一个狄氏边值,取值方式由函数 u_b 给定,然后加入了 5 个边
* 界标识,分别为 1, 2, 3, 4, 5。这个边值加入到管理器中,然后应用到矩
* 阵和向量上。
*
*/
class BCAdmin {
public:
typedef BCondition * bc_ptr_t;
private:
std::map<int, bc_ptr_t, std::less<int> > _map;
public:
/**
* 应用狄氏边值条件在一个线性系统上。
*
*/
template <
class SP, /// 有限元空间的类型
class MAT, /// 稀疏矩阵的类型,现在是设为 SparseMatrix<double>
class XVEC, /// 解向量的类型,现在是设为 Vector<double>
class BVEC /// 右端向量的类型,现在是设为 Vector<double>
>
void apply(const SP& sp,
MAT& A,
XVEC& u,
BVEC& f,
bool preserve_symmetry = true)
{
u_int n_dof = sp.n_dof();
const SparsityPatternBase<>& spA = A.get_sparsity_pattern();
const std::size_t * rowstart = spA.get_rowstart_indices();
const u_int * colnum = spA.get_column_numbers();
for (u_int i = 0;i < n_dof;++ i) {
int bm = sp.dofInfo(i).boundary_mark;
if (bm == 0) continue; /// 0 缺省指区域内部
const bc_ptr_t bc = this->find(bm);
/// 如果这个边界条件不由本对象处理,或者不是狄氏边界,则跳过去。
if (bc == NULL) continue;
if (bc->type() != BCondition::DIRICHLET) continue;
bc->value((const void *)(&sp.dofInfo(i).interp_point),
(void *)(&u(i)));
f(i) = A.diag_element(i)*u(i);
for (u_int j = rowstart[i] + 1;j < rowstart[i + 1];++ j) {
A.global_entry(j) -= A.global_entry(j);
}
if (preserve_symmetry) {
for (u_int j = rowstart[i] + 1;j < rowstart[i + 1];++ j) {
u_int k = colnum[j];
const u_int * p = std::find(&colnum[rowstart[k] + 1],
&colnum[rowstart[k + 1]], i);
if (p != &colnum[rowstart[k+1]]) {
u_int l = p - &colnum[rowstart[0]];
f(k) -= A.global_entry(l)*f(i)/A.diag_element(i);
A.global_entry(l) -= A.global_entry(l);
}
}
}
}
}
/**
* 将向量 f 中由本对象负责处理的自由度相同的指标上的元素清零。
*
*/
template <
class SP, /// 有限元空间的类型
class VEC /// 向量的类型,现在是设为 Vector<double>
>
void clear_entry(const SP& sp,
VEC& f)
{
u_int n_dof = sp.n_dof();
for (u_int i = 0;i < n_dof;++ i) {
int bm = sp.dof_info(i).bound_mark();
if (bm == 0) continue; /// 0 缺省指区域内部
const bc_ptr_t bc = find(bm);
if (bc != NULL) f(i) -= f(i);
}
}
/**
* 往本对象中加入一个边界条件。一个边界条件被加入到管理器中以后,
* 如果另外调用了 add_mark 以后,是不会自动起作用的。如果有此要求,
* 需要重新调用本函数。
*
*/
template <class BC>
void add(BC& b)
{
const std::set<int, std::less<int> >& bm = b.bound_mark();
std::set<int, std::less<int> >::const_iterator
the_bm = bm.begin(), end_bm = bm.end();
for (;the_bm != end_bm;++ the_bm) {
_map[*the_bm] = &b;
}
}
/**
* 找出对应于材料标识 bm 的边界条件的指针,如果没有找到,则返回
* NULL。
*
*/
bc_ptr_t find(int bm) const
{
std::map<int, bc_ptr_t, std::less<int> >::const_iterator
the_ptr = _map.find(bm);
if (the_ptr != _map.end()) {
return the_ptr->second;
} else {
return NULL;
}
}
};
#endif // __BoundaryCondition_h__
/**
* end of file
*
*/
|
cb27be3bfee554e312965df321fefbb43f813bac | 5915dfcedd7e954c4c76feb4bda431f8a238614f | /world/aurora_level.h | ac099642e16115d2a49def1ffd5f61176c0c6485 | [] | no_license | Boyquotes/aurora-code | f39b6997ebdf1e5eeb89c04fc9bc0e85954e8a9d | 66d0b129465004f3765dab7bd109c2367d2e33ac | refs/heads/master | 2023-05-29T19:13:06.869835 | 2020-04-26T19:44:06 | 2020-04-26T19:44:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,662 | h | aurora_level.h | #ifndef AURORA_LEVEL_H
#define AURORA_LEVEL_H
#include "core/reference.h"
#include "aurora_tile.h"
#include <vector>
#include <functional>
namespace aurora {
class AuroraLevel : public Reference {
GDCLASS(AuroraLevel, Reference)
protected:
static void _bind_methods();
public:
String const& GetName();
//static scalar const MinTileSize;
static int const TileChildEdgeCount;
static int const TileChildCount;
// TODO test
//void add(int value);
//void reset();
//int get_total() const;
AuroraLevel();
AuroraLevel(Meter2 levelBottomLeftPosition, Meter tileSize, Meter levelDepth, int tileHCount, int tileVCount, bool horizontalLoop);
//void PaintTile(Rect2 area, AuroraMaterial const& material);
//void Repack();
std::vector<Tile*>& GetTiles() { return m_tiles; }
std::vector<Tile*> const& GetTiles() const { return m_tiles; }
Meter2 GetLevelSize() const { return m_levelSize; };
Meter GetTileSize() const { return m_tileSize; }
Meter2 GetLevelBottomLeftPosition() const { return m_levelBottomLeftPosition; }
//void FindTileAt(std::vector<Tile*>& matchs, MmRect area);
//Rect2 GetArea() const;
bool IsHorizontalLoop() const { return m_horizontalLoop; }
void ForEachTransition(std::function<void(Tile* tileA, Tile* tileB, Transition::Direction direction)> callback);
Tile* GetTileAtIndex(int x, int y);
private:
String m_name;
std::vector<Tile*> m_tiles;
Meter m_tileSize;
Meter m_levelDepth;
int m_tileHCount;
int m_tileVCount;
Meter2 m_levelSize;
Meter2 m_levelBottomLeftPosition;
bool m_horizontalLoop;
};
}
#endif
|
38b92b5b77fe9d52be8599b5b5b4622c6a344949 | c8fcc1acf73585045a5c7213cfb9f90e4c1e809e | /POJ/2429.cpp | a74562726db29f3814b53dfedd50bd56bb1b9da7 | [] | no_license | Jonariguez/ACM_Code | 6db4396b20d0b0aeef30e4d47b51fb5e3ec48e03 | 465a11746d577197772f64aa11209eebd5bfcdd3 | refs/heads/master | 2020-03-24T07:09:53.482953 | 2018-11-19T09:21:33 | 2018-11-19T09:21:33 | 142,554,816 | 3 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,133 | cpp | 2429.cpp | /****************
*PID:poj2429
*Auth:Jonariguez
*****************
*/
#include <stdio.h>
#include <string.h>
#include <map>
#include <math.h>
#include <vector>
#include <stdlib.h>
#include <algorithm>
using namespace std;
typedef long long LL;
const int maxn=200000+10;
vector<int> prime;
bool vis[maxn];
LL random(LL n){
return (LL)((double)rand()/RAND_MAX*n+0.5);
}
void prime_table(){
int i,j;
vis[0]=vis[1]=1;
for(i=2;i<=200000;i++){
if(!vis[i]){
prime.push_back(i);
for(j=i*2;j<=200000;j+=i) vis[j]=1;
}
}
}
LL multi(LL a,LL b,LL m){
a=(a%m+m)%m;
b=(b%m+m)%m;
LL res=0;
while(b){
if(b&1) res=(res+a)%m;
b/=2;
a=(a*2)%m;
}
return res;
}
LL quick_pow(LL a,LL b,LL m){
a=(a%m+m)%m;
LL res=1;
while(b){
if(b&1) res=multi(res,a,m);
b/=2;
a=multi(a,a,m);
}
return res;
}
bool test(LL a,LL cnt,LL m,LL n){
LL x=quick_pow(a,m,n);
if(x==1 || x==n-1) return false;
while(cnt--){
x=multi(x,x,n);
if(x==n-1) return false; //通过测试,是强可能素数
}
return true;
}
bool isPrime(LL n){
if(n<=200000) return vis[n]==0;
if(n%2==0) return false;
LL m=n-1,cnt=0;
while(m%2==0){
cnt++;m/=2;
}
for(int i=0;i<20;i++){
LL a=random(n);
if(test(a,cnt,m,n))
return false;
}
return true;
}
LL gcd(LL a,LL b){
return b==0?a:gcd(b,a%b);
}
LL pollard_rho(LL n,int c){
LL x=2,y=2,d=1;
while(d==1){
x=multi(x,x,n)+c;
y=multi(y,y,n)+c;
y=multi(y,y,n)+c;
d=gcd(((x-y)>0?(x-y):(y-x)),n);
}
if(d==n) return pollard_rho(n,c+1);
return d;
}
map<LL,int> fact;
void factorize(LL n, map<LL, int>& fact){
if(isPrime(n)){
fact[n]++;return ;
}
int i;
for(i=0;i<prime.size();i++){
int x=prime[i];
while(n%x==0){
fact[x]++;n/=x;
}
}
if(n!=1){
if(isPrime(n))
fact[n]++;
else {
LL d;
d=pollard_rho(n,1);
factorize(d,fact);
factorize(n/d,fact);
}
}
}
pair<LL,LL> solve(LL a,LL b){
LL c=b/a;
map<LL,int> fact;
factorize(c,fact);
vector<LL> mult_fact;
map<LL,int>::iterator it;
for(it=fact.begin();it!=fact.end();it++){
LL mul=1;
while(it->second){
mul*=it->first;
it->second--;
}
mult_fact.push_back(mul);
}
LL best_sum=1e18,best_x=1,best_y=c;
for(int mask=0;mask<(1<<mult_fact.size());mask++){
LL x=1;
for(int i=0;i<mult_fact.size();i++)
if(mask&(1<<i)) x*=mult_fact[i];
LL y=c/x;
if(x<y && x+y<best_sum){
best_sum=x+y;
best_x=x;best_y=y;
}
}
return make_pair(best_x*a,best_y*a);
}
int main()
{
int i;
LL GCD,LCM;
prime_table();
while(scanf("%I64d%I64d",&GCD,&LCM)!=EOF){
pair<LL,LL> res=solve(GCD,LCM);
printf("%I64d %I64d\n",res.first,res.second);
}
return 0;
}
|
7d0cd33d028174d28b9f7ad3ffab1091c2dabcd4 | 9d37f83190969d3118b3a7ed44855e17f6e53518 | /ProyectoIntegrador2/Cuestionario.cpp | 3b0d232a34e5e3b8470ece7e7a6ab8aa758fc1c3 | [] | no_license | yknx4/ProyectoIntegrador2 | 17cb78000ccd59b06f4aa2921174c2c8d576c1e3 | 4ead54fc315e8e5f43b8a2fc7f366a118a33f001 | refs/heads/master | 2021-08-27T16:22:16.381114 | 2013-06-04T06:09:30 | 2013-06-04T06:09:30 | 10,372,856 | 0 | 0 | null | 2021-08-19T14:43:16 | 2013-05-30T01:25:11 | JavaScript | UTF-8 | C++ | false | false | 1,611 | cpp | Cuestionario.cpp | //#define _CRT_SECURE_NO_WARNINGS
#include "stdafx.h"
#include "Cuestionario.h"
#include "Preguntas.h"
#include <vector>
#include <fstream>
#include <chrono>
#include <ctime>
#include <sstream>
/*#define SEPARADOR_DATO char(31)
#define SEPARADOR_GRUPO char(29)*/
using namespace std;
Cuestionario::Cuestionario()
{
}
Cuestionario::Cuestionario( vector <Pregunta*> preguntas )
{
this->preguntas=preguntas;
}
Cuestionario::~Cuestionario()
{
}
bool Cuestionario::GuardarCuestionario()
{
typedef std::chrono::system_clock Clock;
auto now = Clock::now();
std::time_t now_c = Clock::to_time_t(now);
struct tm *parts = std::localtime(&now_c);
int anio= 1900 + parts->tm_year;
int month= 1 + parts->tm_mon;
int day = parts->tm_mday ;
ofstream myfile;
myfile.open("respuesta.txt",ios::out | ios::app);
string respues = "";
if (myfile.is_open())
{
for (size_t i=0;i<preguntas.size();i++)
{
respues+=preguntas[i]->getRespuesta()+"\t";
}
myfile << 1900 + parts->tm_year << "_";
myfile << 1 + parts->tm_mon << "_";
myfile << parts->tm_mday << "\t";
myfile << respues <<"\n";
myfile.close();
return true;
}
else cout << "No se puede guardar";
return false;
}
void Cuestionario::hacerPreguntas()
{
int numeroPreguntas = this->preguntas.size();
// cout<<preguntas.size()<<"eltama~no\n";
for (int contadorPreguntas=0;contadorPreguntas<numeroPreguntas;contadorPreguntas++)
{
preguntas[contadorPreguntas]->imprimirPregunta();
preguntas[contadorPreguntas]->responder();
}
}
void Cuestionario::addPregunta(Pregunta* input){
preguntas.push_back(input);
}
|
5b8ea190b689a3ee73fdfee914fc0d4c34617c78 | 1c8312eef18644f914991fbb9fdea3877305deca | /include/fe/GameConstants.h | ca016801f89e5a6d12ac84bedf25c3d569d2fe44 | [
"MIT"
] | permissive | TonoFilth/connect-four | 0cdba3cee93de3cc8a345d375a48776a69ac7594 | f067c086cd0ca0817f6c758525e0671bd6b3efa2 | refs/heads/master | 2016-08-05T02:33:01.988132 | 2014-03-10T11:58:55 | 2014-03-10T11:58:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,605 | h | GameConstants.h | #ifndef __GAME_CONSTANTS_H__
#define __GAME_CONSTANTS_H__
#include <iostream>
#include <SFML/Graphics.hpp>
#include "fe/BasicTypes.h"
namespace fe
{
class GameConstants
{
private:
static const std::string GameBackgroundTextureFile;
static const std::string Player1TextureFile;
static const std::string Player2TextureFile;
static const std::string SquareTextureFile;
static const std::string CursorChipATextureFile;
static const std::string CursorChipBTextureFile;
static const std::string HudFontFile;
static bool st_Initialized;
public:
GameConstants();
GameConstants(const GameConstants& toCopy);
GameConstants& operator=(const GameConstants& toCopy);
~GameConstants();
static const std::string GameTitle;
static sf::Texture GameBackgroundTexture;
static sf::Texture Player1Texture;
static sf::Texture Player2Texture;
static sf::Texture SquareTexture;
static sf::Texture CursorChipATexture;
static sf::Texture CursorChipBTexture;
static const sf::Vector2u WindowSize;
static const sf::Vector2u BoardSize;
static const sf::Vector2u SquareSize;
static const sf::Color HudBackgroundColor;
static const sf::Color HudPlayerNameColor;
static const sf::Color HudScoreboardColor;
static const sf::Color HudGameMessageColor;
static const sf::Color HudGameMessageBackgroundColor;
static const sf::Color HudGameMessageOutlineColor;
static const UI32 HudPlayerNameTextSize;
static const UI32 HudScoreboardTextSize;
static const UI32 HudGameMessageTextSize;
static const sf::Vector2f HudGameMessagePosition;
static sf::Font HudFont;
static bool Init();
};
}
#endif
|
cc71ffd629d00b83a0ec2d2af40318841c9a8d14 | 81c66c9c0b78f8e9c698dcbb8507ec2922efc8b7 | /src/domains/cg/HuScheduler/HuParProcs.h | 57c79573012480c6db5d74449e1317ca5d014d6c | [
"MIT-Modern-Variant"
] | permissive | Argonnite/ptolemy | 3394f95d3f58e0170995f926bd69052e6e8909f2 | 581de3a48a9b4229ee8c1948afbf66640568e1e6 | refs/heads/master | 2021-01-13T00:53:43.646959 | 2015-10-21T20:49:36 | 2015-10-21T20:49:36 | 44,703,423 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,101 | h | HuParProcs.h | #ifndef _HuParProcs_h
#define _HuParProcs_h
#ifdef __GNUG__
#pragma interface
#endif
/*****************************************************************
Version identification:
@(#)HuParProcs.h 1.10 7/19/95
Copyright (c) 1990-1995 The Regents of the University of California.
All rights reserved.
Permission is hereby granted, without written agreement and without
license or royalty fees, to use, copy, modify, and distribute this
software and its documentation for any purpose, provided that the
above copyright notice and the following two paragraphs appear in all
copies of this software.
IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY
FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
CALIFORNIA HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
ENHANCEMENTS, OR MODIFICATIONS.
PT_COPYRIGHT_VERSION_2
COPYRIGHTENDKEY
Programmer: Soonhoi Ha
Date of last revision:
*****************************************************************/
#include "NamedObj.h"
#include "HuGraph.h"
#include "DLParProcs.h"
/////////////////////////
// class HuParProcs //
/////////////////////////
// A class for managing the parallel processor schedules.
class HuParProcs : public DLParProcs {
public:
HuParProcs(int pNum, MultiTarget* t);
/* virtual */ void scheduleSmall(DLNode*);
protected:
// Fire a node. Check the runnability of descendants.
/* virtual */ void fireNode(DLNode*);
private:
// redefine virtual methods
/* virtual */ void prepareComm(DLNode*); // do nothing
/* virtual */ void scheduleIPC(int); // do nothing
int isCandidate(int); // determine if specified proc is in the "candidate" array
};
#endif
|
161648d17aca5582f44f7d36021cb67399c220bd | 436a112c705fe6621f0eb966c99ea5622fdbe5c2 | /Dodo-Engine/code/components/ECS.cpp | 1a5c236afa95dc24baf75c0aaedd25cde6cdb4ed | [
"MIT"
] | permissive | TKscoot/Dodo-Engine | 63f4c2b0c290fa94d5fa23dc06bcf276c1414232 | ba6c56a898d2e07e0fd7e89161cbdafd8bc02abd | refs/heads/master | 2022-03-30T23:57:45.970080 | 2020-02-05T21:30:10 | 2020-02-05T21:30:10 | 184,224,992 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 38 | cpp | ECS.cpp | #include "dodopch.h"
#include "ECS.h"
|
bc5251960206abfecdc55856d661d5a057202e6d | e148d6b1bb9569e3af87e75048381014a747a5ad | /Tameran/Hydro/Graphics/Shader/FontShader.h | 89da43f280ecf32c9d7824d6590ac3a95a4444d3 | [
"MIT"
] | permissive | Zokerus/Tameran | 40315097464e3e20fbb0e0703a8b6a41166392b8 | 7bf20aae2c5bba3db972b09862528e6a21187c1d | refs/heads/master | 2021-09-20T06:18:44.894316 | 2018-08-05T17:12:45 | 2018-08-05T17:12:45 | 104,335,754 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 828 | h | FontShader.h | #ifndef FONTSHADER
#define FONTSHADER
//My Includes
#include "IShader.h"
namespace Hydro
{
class FontShader : public IShader
{
private:
struct PixelBufferType
{
DirectX::XMVECTORF32 pixelColor;
};
public:
FontShader(ID3D11Device* device, HWND hWnd);
~FontShader();
bool Render(ID3D11DeviceContext *deviceContext, int indexCount, DirectX::XMMATRIX world, DirectX::XMMATRIX view, DirectX::XMMATRIX projection, ID3D11ShaderResourceView *texture, DirectX::XMVECTORF32 pixelColor);
private:
bool SetShaderParameters(ID3D11DeviceContext *deviceContext, DirectX::XMMATRIX world, DirectX::XMMATRIX view, DirectX::XMMATRIX projection, ID3D11ShaderResourceView *texture, DirectX::XMVECTORF32 pixelColor);
private:
ID3D11SamplerState* pSampleState;
ID3D11Buffer* pPixelBuffer;
};
}
#endif // !FONTSHADER |
e70a80fccfdf222d7481d6bb14dcca4f607d91d6 | d7acc19f9ec13f82b13072c3ede5e66268ae88a2 | /catkin_ws/devel/include/text_msgs/text_detection_array.h | 462fcdb37f611fe74b4cea0951eff123a86ba159 | [] | no_license | Richardwang0326/TTS_and_brandname | 702fac7d1cb33c40a4dd067e3e0df5b5f4a7ad35 | 5a33772158f00a3ba21595225d610c39049f6920 | refs/heads/main | 2023-01-14T04:50:28.344020 | 2020-11-25T02:36:35 | 2020-11-25T02:36:35 | 306,322,644 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,632 | h | text_detection_array.h | // Generated by gencpp from file text_msgs/text_detection_array.msg
// DO NOT EDIT!
#ifndef TEXT_MSGS_MESSAGE_TEXT_DETECTION_ARRAY_H
#define TEXT_MSGS_MESSAGE_TEXT_DETECTION_ARRAY_H
#include <string>
#include <vector>
#include <map>
#include <ros/types.h>
#include <ros/serialization.h>
#include <ros/builtin_message_traits.h>
#include <ros/message_operations.h>
#include <sensor_msgs/Image.h>
#include <sensor_msgs/Image.h>
#include <text_msgs/text_detection_msg.h>
namespace text_msgs
{
template <class ContainerAllocator>
struct text_detection_array_
{
typedef text_detection_array_<ContainerAllocator> Type;
text_detection_array_()
: status()
, image()
, depth()
, bb_count(0)
, text_array() {
}
text_detection_array_(const ContainerAllocator& _alloc)
: status(_alloc)
, image(_alloc)
, depth(_alloc)
, bb_count(0)
, text_array(_alloc) {
(void)_alloc;
}
typedef std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > _status_type;
_status_type status;
typedef ::sensor_msgs::Image_<ContainerAllocator> _image_type;
_image_type image;
typedef ::sensor_msgs::Image_<ContainerAllocator> _depth_type;
_depth_type depth;
typedef int32_t _bb_count_type;
_bb_count_type bb_count;
typedef std::vector< ::text_msgs::text_detection_msg_<ContainerAllocator> , typename ContainerAllocator::template rebind< ::text_msgs::text_detection_msg_<ContainerAllocator> >::other > _text_array_type;
_text_array_type text_array;
typedef boost::shared_ptr< ::text_msgs::text_detection_array_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::text_msgs::text_detection_array_<ContainerAllocator> const> ConstPtr;
}; // struct text_detection_array_
typedef ::text_msgs::text_detection_array_<std::allocator<void> > text_detection_array;
typedef boost::shared_ptr< ::text_msgs::text_detection_array > text_detection_arrayPtr;
typedef boost::shared_ptr< ::text_msgs::text_detection_array const> text_detection_arrayConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::text_msgs::text_detection_array_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::text_msgs::text_detection_array_<ContainerAllocator> >::stream(s, "", v);
return s;
}
template<typename ContainerAllocator1, typename ContainerAllocator2>
bool operator==(const ::text_msgs::text_detection_array_<ContainerAllocator1> & lhs, const ::text_msgs::text_detection_array_<ContainerAllocator2> & rhs)
{
return lhs.status == rhs.status &&
lhs.image == rhs.image &&
lhs.depth == rhs.depth &&
lhs.bb_count == rhs.bb_count &&
lhs.text_array == rhs.text_array;
}
template<typename ContainerAllocator1, typename ContainerAllocator2>
bool operator!=(const ::text_msgs::text_detection_array_<ContainerAllocator1> & lhs, const ::text_msgs::text_detection_array_<ContainerAllocator2> & rhs)
{
return !(lhs == rhs);
}
} // namespace text_msgs
namespace ros
{
namespace message_traits
{
template <class ContainerAllocator>
struct IsFixedSize< ::text_msgs::text_detection_array_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::text_msgs::text_detection_array_<ContainerAllocator> const>
: FalseType
{ };
template <class ContainerAllocator>
struct IsMessage< ::text_msgs::text_detection_array_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::text_msgs::text_detection_array_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::text_msgs::text_detection_array_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct HasHeader< ::text_msgs::text_detection_array_<ContainerAllocator> const>
: FalseType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::text_msgs::text_detection_array_<ContainerAllocator> >
{
static const char* value()
{
return "70b11adbdf88669325700427bf1cc417";
}
static const char* value(const ::text_msgs::text_detection_array_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0x70b11adbdf886693ULL;
static const uint64_t static_value2 = 0x25700427bf1cc417ULL;
};
template<class ContainerAllocator>
struct DataType< ::text_msgs::text_detection_array_<ContainerAllocator> >
{
static const char* value()
{
return "text_msgs/text_detection_array";
}
static const char* value(const ::text_msgs::text_detection_array_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::text_msgs::text_detection_array_<ContainerAllocator> >
{
static const char* value()
{
return "string status # O for non_return , X for return \n"
"sensor_msgs/Image image\n"
"sensor_msgs/Image depth\n"
"int32 bb_count\n"
"text_detection_msg[] text_array\n"
"================================================================================\n"
"MSG: sensor_msgs/Image\n"
"# This message contains an uncompressed image\n"
"# (0, 0) is at top-left corner of image\n"
"#\n"
"\n"
"Header header # Header timestamp should be acquisition time of image\n"
" # Header frame_id should be optical frame of camera\n"
" # origin of frame should be optical center of camera\n"
" # +x should point to the right in the image\n"
" # +y should point down in the image\n"
" # +z should point into to plane of the image\n"
" # If the frame_id here and the frame_id of the CameraInfo\n"
" # message associated with the image conflict\n"
" # the behavior is undefined\n"
"\n"
"uint32 height # image height, that is, number of rows\n"
"uint32 width # image width, that is, number of columns\n"
"\n"
"# The legal values for encoding are in file src/image_encodings.cpp\n"
"# If you want to standardize a new string format, join\n"
"# ros-users@lists.sourceforge.net and send an email proposing a new encoding.\n"
"\n"
"string encoding # Encoding of pixels -- channel meaning, ordering, size\n"
" # taken from the list of strings in include/sensor_msgs/image_encodings.h\n"
"\n"
"uint8 is_bigendian # is this data bigendian?\n"
"uint32 step # Full row length in bytes\n"
"uint8[] data # actual matrix data, size is (step * rows)\n"
"\n"
"================================================================================\n"
"MSG: std_msgs/Header\n"
"# Standard metadata for higher-level stamped data types.\n"
"# This is generally used to communicate timestamped data \n"
"# in a particular coordinate frame.\n"
"# \n"
"# sequence ID: consecutively increasing ID \n"
"uint32 seq\n"
"#Two-integer timestamp that is expressed as:\n"
"# * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')\n"
"# * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')\n"
"# time-handling sugar is provided by the client library\n"
"time stamp\n"
"#Frame this data is associated with\n"
"string frame_id\n"
"\n"
"================================================================================\n"
"MSG: text_msgs/text_detection_msg\n"
"string status # O for non_return , X for return \n"
"float64 probability\n"
"geometry_msgs/Pose pose\n"
"bb_box box\n"
"int_arr[] contour\n"
"\n"
"================================================================================\n"
"MSG: geometry_msgs/Pose\n"
"# A representation of pose in free space, composed of position and orientation. \n"
"Point position\n"
"Quaternion orientation\n"
"\n"
"================================================================================\n"
"MSG: geometry_msgs/Point\n"
"# This contains the position of a point in free space\n"
"float64 x\n"
"float64 y\n"
"float64 z\n"
"\n"
"================================================================================\n"
"MSG: geometry_msgs/Quaternion\n"
"# This represents an orientation in free space in quaternion form.\n"
"\n"
"float64 x\n"
"float64 y\n"
"float64 z\n"
"float64 w\n"
"\n"
"================================================================================\n"
"MSG: text_msgs/bb_box\n"
"int32 xmax\n"
"int32 xmin\n"
"int32 ymax\n"
"int32 ymin\n"
"================================================================================\n"
"MSG: text_msgs/int_arr\n"
"int32[] point\n"
;
}
static const char* value(const ::text_msgs::text_detection_array_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::text_msgs::text_detection_array_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.status);
stream.next(m.image);
stream.next(m.depth);
stream.next(m.bb_count);
stream.next(m.text_array);
}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct text_detection_array_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::text_msgs::text_detection_array_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::text_msgs::text_detection_array_<ContainerAllocator>& v)
{
s << indent << "status: ";
Printer<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::stream(s, indent + " ", v.status);
s << indent << "image: ";
s << std::endl;
Printer< ::sensor_msgs::Image_<ContainerAllocator> >::stream(s, indent + " ", v.image);
s << indent << "depth: ";
s << std::endl;
Printer< ::sensor_msgs::Image_<ContainerAllocator> >::stream(s, indent + " ", v.depth);
s << indent << "bb_count: ";
Printer<int32_t>::stream(s, indent + " ", v.bb_count);
s << indent << "text_array[]" << std::endl;
for (size_t i = 0; i < v.text_array.size(); ++i)
{
s << indent << " text_array[" << i << "]: ";
s << std::endl;
s << indent;
Printer< ::text_msgs::text_detection_msg_<ContainerAllocator> >::stream(s, indent + " ", v.text_array[i]);
}
}
};
} // namespace message_operations
} // namespace ros
#endif // TEXT_MSGS_MESSAGE_TEXT_DETECTION_ARRAY_H
|
0801456d22b95bb0d200cc03d0f2c3e15e38ef08 | e135145e5ec959416689a65de8ba5d6d79ab1d72 | /Chapter_2/2_2/JumpingBall/global.h | 7e686ed18f058a343378a92ff86220498d758fa9 | [] | no_license | Caproner/C_Game_Basic | bce102d4865ab94b6cf9b8b3292a2c51b0a65783 | 92d568dc42cee0e8b95103e60f46951c54d055d7 | refs/heads/master | 2020-06-19T18:20:17.842543 | 2019-09-08T10:14:36 | 2019-09-08T10:14:36 | 196,818,410 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 752 | h | global.h | #include <cstdio>
#include <cstring>
#include <ctime>
#include <conio.h>
#include <windows.h>
#include <set>
#include <vector>
#include <algorithm>
#define HEIGHT 25
#define WIDTH 40
#define VIEW_HEIGHT 100
#define VIEW_WIDTH 100
#define BALL_SPEED 10
#define BOARD_X_MIN (HEIGHT - 3)
#define BOARD_X_MAX HEIGHT
#define INIT_BOARD_X BOARD_X_MAX
#define INIT_BOARD_Y_LEFT (WIDTH / 2 - 8)
#define INIT_BOARD_Y_RIGHT (WIDTH / 2 + 9)
#define INIT_BALL_X (INIT_BOARD_X - 1)
#define INIT_BALL_Y ((INIT_BOARD_Y_LEFT + INIT_BOARD_Y_RIGHT) / 2)
#define INIT_BALL_VX 1
#define INIT_BALL_VY 1
#define INIT_BLOCK_LEFT 1
#define INIT_BLOCK_RIGHT WIDTH
#define INIT_BLOCK_TOP 1
#define INIT_BLOCK_BOTTOM (INIT_BOARD_X - 10)
#define BLOCK_GENERATE_PROBABILITY 0.6
|
142230214fcfb2a417b8d4e04a76b2fd3748e194 | 1634d4f09e2db354cf9befa24e5340ff092fd9db | /Wonderland/Wonderland/Editor/Modules/Peon/Peon.h | 5b94d8f171b6b24828875a8ca6d66ee4518829be | [
"MIT"
] | permissive | RodrigoHolztrattner/Wonderland | cd5a977bec96fda1851119a8de47b40b74bd85b7 | ffb71d47c1725e7cd537e2d1380962b5dfdc3d75 | refs/heads/master | 2021-01-10T15:29:21.940124 | 2017-10-01T17:12:57 | 2017-10-01T17:12:57 | 84,469,251 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,700 | h | Peon.h | ////////////////////////////////////////////////////////////////////////////////
// Filename: __InternalPeonJob.h
////////////////////////////////////////////////////////////////////////////////
#pragma once
//////////////
// INCLUDES //
//////////////
#include "..\NamespaceDefinitions.h"
#include "..\GlobalInstance.h"
#include "PeonSystem.h"
#include "PeonWorker.h"
#include "PeonJob.h"
/////////////
// DEFINES //
/////////////
///////////////
// NAMESPACE //
///////////////
// Peon
NamespaceBegin(Peon)
////////////
// GLOBAL //
////////////
typedef __InternalPeon::__InternalPeonWorker Worker;
typedef __InternalPeon::__InternalPeonJob Job;
// Our peon system global instance
static GlobalInstance<__InternalPeon::__InternalPeonSystem> PeonSystemGlobalInstance;
// Initialize the peon system
template <class ThreadUserDatType = unsigned char>
static bool Initialize(unsigned int _numberWorkerThreads, unsigned int _jobBufferSize, bool _useUserData = false)
{
// Initialize the peon system
return PeonSystemGlobalInstance->Initialize<ThreadUserDatType>(_numberWorkerThreads, _jobBufferSize, _useUserData);
}
// Start the working area where we can create any other peons
static Job* CreateWorkingArea(std::function<void()> _function)
{
return PeonSystemGlobalInstance->CreateJobArea(_function);
}
// Create an independent job
static Job* CreateJob(std::function<void()> _function)
{
return PeonSystemGlobalInstance->CreateJobArea(_function);
}
// Create a child job
static Job* CreateChildJob(std::function<void()> _function)
{
return PeonSystemGlobalInstance->CreateChildJob(_function);
}
// Create a child job
static Job* CreateChildJob(Job* _parentJob, std::function<void()> _function)
{
return PeonSystemGlobalInstance->CreateChildJob(_parentJob, _function);
}
// Create a job container
static Job* CreateJobContainer()
{
__InternalPeon::__InternalPeonSystem* jobSystem = (__InternalPeon::__InternalPeonSystem*)PeonSystemGlobalInstance.GetInstance(); // Remove the const
return PeonSystemGlobalInstance->CreateJob([=] { jobSystem->JobContainerHelper(nullptr); });
}
// Start a given job
static void StartJob(Job* _job)
{
PeonSystemGlobalInstance->StartJob(_job);
}
// Wait for a given job
static void WaitForJob(Job* _job)
{
PeonSystemGlobalInstance->WaitForJob(_job);
}
// Return the current job for the actual context
static Job* GetCurrentJob()
{
return __InternalPeon::__InternalPeonWorker::GetCurrentJob();
}
// Return the current worker for the actual context
static Worker* GetCurrentWorker()
{
return __InternalPeon::__InternalPeonSystem::GetCurrentPeon();
}
// Return the current worker index for the actual context
static int GetCurrentWorkerIndex()
{
return __InternalPeon::CurrentThreadIdentifier;
}
// Return the total number of worker threads
static int GetTotalWorkers()
{
return PeonSystemGlobalInstance->GetTotalWorkerThreads();
}
// Return a peon user data by index
template <class PeonUserDatType>
static PeonUserDatType* GetUserData(unsigned int _workerIndex)
{
return PeonSystemGlobalInstance->GetUserData<PeonUserDatType>(_workerIndex);
}
// Return the current peon worker user data
template <class PeonUserDatType>
static PeonUserDatType* GetUserData()
{
return PeonSystemGlobalInstance->GetUserData<PeonUserDatType>(GetCurrentWorkerIndex());
}
// Block all threads execution
static void BlockWorkerExecution()
{
PeonSystemGlobalInstance->BlockThreadsStatus(true);
}
// Release all threads execution
static void ReleaseWorkerExecution()
{
PeonSystemGlobalInstance->BlockThreadsStatus(false);
}
// Reset the work frame
static void ResetWorkFrame()
{
PeonSystemGlobalInstance->ResetWorkerFrame();
}
// Peon
NamespaceEnd(Peon) |
99baead77e0e1abfa689c3e750337cf44fc3f309 | 346c17a1b3feba55e3c8a0513ae97a4282399c05 | /MMVII/src/Topo/ctopoobsset.cpp | e7a6fbdbb11dac0907ff37e0f1b237c5b70a2816 | [
"LicenseRef-scancode-cecill-b-en"
] | permissive | micmacIGN/micmac | af4ab545c3e1d9c04b4c83ac7e926a3ff7707df6 | 6e5721ddc65cb9b480e53b5914e2e2391d5ae722 | refs/heads/master | 2023-09-01T15:06:30.805394 | 2023-07-25T09:18:43 | 2023-08-30T11:35:30 | 74,707,998 | 603 | 156 | NOASSERTION | 2023-06-19T12:53:13 | 2016-11-24T22:09:54 | C++ | UTF-8 | C++ | false | false | 3,294 | cpp | ctopoobsset.cpp | #include "ctopoobsset.h"
#include "MMVII_PhgrDist.h"
#include <memory>
namespace MMVII
{
cTopoObsSet::cTopoObsSet(TopoObsSetType type):
mType(type)
{
}
void cTopoObsSet::init()
{
createAllowedObsTypes();
createParams();
}
void cTopoObsSet::PutUknowsInSetInterval()
{
mSetInterv->AddOneInterv(mParams);
}
bool cTopoObsSet::addObs(cTopoObs obs)
{
if (std::find(mAllowedObsTypes.begin(), mAllowedObsTypes.end(), obs.getType()) == mAllowedObsTypes.end())
{
ErrOut() << "Error, " << obs.type2string()
<< " obs type is not allowed in "
<< type2string()<<" obs set!\n";
return false;
}
mObs.push_back(obs);
return true;
}
std::string cTopoObsSet::toString() const
{
std::ostringstream oss;
oss<<"TopoObsSet "<<type2string()<<":\n";
for (auto & obs: mObs)
oss<<" - "<<obs.toString()<<"\n";
if (!mParams.empty())
{
oss<<" params: ";
for (auto & param: mParams)
oss<<param<<" ";
oss<<"\n";
}
return oss.str();
}
std::vector<int> cTopoObsSet::getParamIndices() const
{
//TODO: compute it in PutUknowsInSetInterval()?
std::vector<int> indices;
for (auto & param : mParams)
{
indices.push_back((int)IndOfVal(¶m));
}
return indices;
}
//----------------------------------------------------------------
cTopoObsSetSimple::cTopoObsSetSimple() :
cTopoObsSet(TopoObsSetType::simple)
{
}
void cTopoObsSetSimple::createAllowedObsTypes()
{
mAllowedObsTypes = {TopoObsType::dist};
}
void cTopoObsSetSimple::createParams()
{
//no params
}
void cTopoObsSetSimple::OnUpdate()
{
//nothing to do
}
std::string cTopoObsSetSimple::type2string() const
{
return "simple";
}
//----------------------------------------------------------------
cTopoObsSetDistParam::cTopoObsSetDistParam() :
cTopoObsSet(TopoObsSetType::distParam)
{
}
void cTopoObsSetDistParam::createAllowedObsTypes()
{
mAllowedObsTypes = {TopoObsType::distParam};
}
void cTopoObsSetDistParam::createParams()
{
mParams.push_back(0.0); //the distance
}
void cTopoObsSetDistParam::OnUpdate()
{
//nothing to do
}
std::string cTopoObsSetDistParam::type2string() const
{
return "distParam";
}
//----------------------------------------------------------------
cTopoObsSetSubFrame::cTopoObsSetSubFrame() :
cTopoObsSet(TopoObsSetType::subFrame), mRot(cRotation3D<tREAL8>::RotFromAxiator({0.,0.,0.}))
{
}
void cTopoObsSetSubFrame::createAllowedObsTypes()
{
mAllowedObsTypes = {TopoObsType::subFrame};
}
void cTopoObsSetSubFrame::createParams()
{
mParams={0.,0.,0.}; //small rotation axiator
}
void cTopoObsSetSubFrame::OnUpdate()
{
//update rotation
mRot = mRot * cRotation3D<tREAL8>::RotFromAxiator(-cPt3dr(mParams[0],mParams[1],mParams[2]));
mParams={0.,0.,0.};
}
std::string cTopoObsSetSubFrame::type2string() const
{
return "subFrame";
}
std::vector<tREAL8> cTopoObsSetSubFrame::getRot() const
{
return
{
mRot.Mat().GetElem(0,0), mRot.Mat().GetElem(0,1), mRot.Mat().GetElem(0,2),
mRot.Mat().GetElem(1,0), mRot.Mat().GetElem(1,1), mRot.Mat().GetElem(1,2),
mRot.Mat().GetElem(2,0), mRot.Mat().GetElem(2,1), mRot.Mat().GetElem(2,2),
};
}
}
|
7a629abd13ada416defb8481ff23f76b075c9021 | 6a92f3e27284226fa9192b60014a91118b29b170 | /utils/mini-AGTK/agtkMetricInfo.h | d4e1c2e380df652fba44d42f696c36646909354a | [] | no_license | sMedX/CNN | cb9c087ae2c8ff2b2f6a1c6a957d61caab2bd6c5 | 85d179d8b6d40d3f1c983e29cfcc189c11267ff3 | refs/heads/master | 2021-03-24T12:05:41.726864 | 2018-02-28T11:55:14 | 2018-02-28T12:08:45 | 46,798,520 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 944 | h | agtkMetricInfo.h | #ifndef __agtkMetricInfo_h
#define __agtkMetricInfo_h
#include <vector>
#include "agtkExport.h"
namespace agtk
{
enum MetricUnits
{
None,
Millimeters
};
class AGTK_EXPORT MetricInfo
{
public:
MetricInfo(
double value,
const char* name,
const char* longName,
MetricUnits units = MetricUnits::None,
const char* description = "",
const char* formula = "");
double getValue() const { return m_Value; }
const char* getName() const { return m_Name; }
const char* getLongName() const { return m_LongName; }
MetricUnits getUnits() const { return m_Units; }
const char* getDescription() const { return m_Description; }
const char* getFormula() const { return m_Formula; }
private:
double m_Value;
const char* m_Name;
const char* m_LongName;
MetricUnits m_Units;
const char* m_Description;
const char* m_Formula;
};
typedef std::vector<MetricInfo> MetricsInfo;
}
#endif // __agtkMetricInfo_h
|
519255e364b29073682effd495467b2989bb0072 | 4bbc259c022331cab9d06a48fd4d8d0e9b5000e3 | /include/ai/EagerActors.hpp | bce248d1810fc1a2902205134d99b389a2614224 | [
"MIT"
] | permissive | tjakway/pyramid-scheme-simulator | 0b5579c5c2bc1efe42323e459adc2637a5311f78 | 4de02ac120b39185342f433999c2d360a7ccbf7e | refs/heads/master | 2023-07-23T20:42:38.762662 | 2018-07-15T18:28:06 | 2018-07-15T18:29:29 | 144,909,813 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,489 | hpp | EagerActors.hpp | #pragma once
#include "NamespaceDefines.hpp"
#include "Actors.hpp"
#include "Util/Unique.hpp"
#include "Types.hpp"
BEGIN_PYRAMID_NAMESPACE
class EagerConsumer : public StaticConsumer
{
public:
EagerConsumer(Unique u, Money m)
: StaticConsumer(u, m, 1.0, 1.0)
{}
virtual ~EagerConsumer() {}
};
class EagerDistributor : public StaticDistributor
{
public:
/**
* pass 1.0 for both sales and conversion chance contributions because we're eager
*/
EagerDistributor(Unique u,
Money startingMoney,
Inventory startingInventory,
Inventory desiredRestockAmount,
Inventory restockThreshold)
: StaticDistributor(u, startingMoney,
startingInventory,
desiredRestockAmount,
restockThreshold,
1.0, 1.0)
{}
EagerDistributor(Consumer& self, std::shared_ptr<Distributor> convBy)
: StaticDistributor(self, convBy)
{}
EagerDistributor(const EagerDistributor& other)
: EagerDistributor(other.id,
other.getMoney(),
other.getInventory(),
other.getDesiredRestockAmount(),
other.getRestockThreshold())
{}
virtual ~EagerDistributor() {}
virtual Inventory getDesiredRestockAmount() const override {
return 5;
}
virtual Inventory getRestockThreshold() const override {
return 1;
}
};
END_PYRAMID_NAMESPACE
|
8997bb405c4f607cfa636e7b1345204cd19eec73 | ed4fabc5b17498e598bca124f820263e5caced75 | /analysis.cpp | f0bacb970bfe91a874ab64f855b548cfe3a41fe6 | [] | no_license | jamsessionein/voight-kampff-teensy-ILI9341 | 96a11414eb7d70021c457138c6c8b25c6e7f6a8b | ef7dcb1ba80acf9a58fde493fbbc1da4af7b6ffd | refs/heads/master | 2021-08-18T21:52:22.073869 | 2017-11-24T01:48:33 | 2017-11-24T01:48:33 | 111,863,504 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,458 | cpp | analysis.cpp | #include "Arduino.h"
#include "analysis.h"
#include "graphics.c"
Analysis::Analysis(int x, int y, int fieldWidth, int fieldHeight, int columnsValue, int rowsValue,
ILI9341_t3 &tftdev, int blipWidthValue, int blipHeightValue){
tft = &tftdev;
xPos = x;
yPos = y;
width = fieldWidth;
height = fieldHeight;
columns = columnsValue;
rows = rowsValue;
blipWidth = width/columns;//blipWidthValue;
blipHeight = height/rows;//blipHeightValue;
}
void Analysis::generate(){
// A pair of variables used to provide the relative coordinates for each blip in the array.
int x = 0;
int y = 0;
for (int i = 0; i < columns*rows; i++) {
// initial test for blip visibility, 50/50 odds.
if(random(0,2)){
// This blip will show! Lets fill it in.
populateBlip(i, x*blipWidth+2, y*blipHeight, (uint16_t)pgm_read_word(&(analysisColors[random(0,3)])));
} else {
// This blip will not show, so we won't worry about it.
results[i].visible = false;
// analysisResults[i].x = 11*xPos;
// analysisResults[i].y = 6*yPos;
}
x++;
if(x == columns){
// We have reached the rightmost blip and need to step down a row when generating X and Y coordinates.
x = 0;
y++;
}
}
}
void Analysis::generateRedBlips(){
// Initial analysis pass is done - lets come up with indicies for two red 'detail' blips.
// We want this to be somewhere near the top of the rows, and would prefer it be somewhere
// on the right end of the array, for aesthetics sake
redIndex1 = random(0,2) * rows + random(3,7);
// We want to generate two unique red blips, but on separate rows so their analysis lines into the picture don't overlap.
// Easiest way is to add a fixed amount to the first Index so that we guarantee it moves down a row (8 slots).
// As a result, redIndex2 will always be below redIndex1 on the chart.
redIndex2 = redIndex1 + random(8,16);
// Populate the data for the red blip positions.
populateBlip(redIndex1, (redIndex1%columns)*blipWidth+2, (redIndex1/columns)*blipHeight, REDUI);
populateBlip(redIndex2, (redIndex2%columns)*blipWidth+2, (redIndex2/columns)*blipHeight, REDUI);
}
void Analysis::populateBlip(int index, int x, int y, uint16_t color){
results[index].x = x;
results[index].y = y;
results[index].visible = true;
results[index].color = color;
}
void Analysis::drawArray(){
tft->fillRect(xPos-1,yPos-1,width-3, height-3,DARKBLUEUI);
for(int i = 0; i<columns*rows; i++){
if(results[i].visible){
tft->fillRect(xPos+results[i].x, yPos+results[i].y, 8, 4, results[i].color);
}
}
//generateEyeTargets(0);
//generateEyeTargets(1);
//drawAnalysisLine(redIndex1);
//drawAnalysisLine(redIndex2);
}
/*void drawAnalysisLine(int index){
int anchorX = analysisResults[index].x+ui.leftMargin+11;
int anchorY = analysisResults[index].y+4+ui.topGutterY+ui.topLeftHeight;
tft.drawFastHLine(anchorX, anchorY, ui.vertGutterRight-anchorX , REDUI);
tft.drawFastHLine(anchorX, anchorY+1, ui.vertGutterRight-anchorX, BACKGROUND);
}*/
/*void generateEyeTargets(int eyeValue){
eye[eyeValue].targetX = random(eye[eyeValue].x, eye[eyeValue].x+eye[eyeValue].w);
eye[eyeValue].targetY = random(eye[eyeValue].y, eye[eyeValue].y+eye[eyeValue].h);
Serial.print((String)"Target values are X: "+eye[eyeValue].targetX+" and Y: "+eye[eyeValue].targetY);
}*/
|
6e3faed371adde3fa3e36cdb8b0859dbb2120120 | 62a81dfb697e5c2d4c79dea02826d250f9254c8d | /2_term/made_2020_algoritms_adv/homeworks/3/B/main.cpp | b5c75504e19dc2e4aae01a4e32e858be5aa3dd40 | [
"MIT"
] | permissive | exotol/made_mail.ru | e36a2bf0c66cbf34fd0de296d0dc7e6af92cd6c8 | a81bfd874ab80eb8c7eaad8a4acf723f327f2f50 | refs/heads/master | 2023-05-24T14:53:37.219268 | 2021-06-19T17:51:38 | 2021-06-19T17:51:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,798 | cpp | main.cpp | //
// main.cpp
// B
//
// Created by Илья Башаров on 14.03.2020.
// Copyright © 2020 MIPT. All rights reserved.
//
#include <iostream>
#include <vector>
long long* sieve(const long long number)
{
std::vector<long long> pr;
long long* lp = (long long*) calloc (number + 1, sizeof(long long)),
index = 0;
for (long long i = 2; i <= number; i++)
{
if (lp[i] == 0)
{
lp[i] = i;
pr.push_back(i);
}
for (auto prime : pr)
{
index = i*prime;
if (prime > lp[i] || index > number)
break;
lp[index] = prime;
}
}
return lp;
}
class count_unique_deviders
{
public:
long long unique_devider = 0;
long long counter_deviders = 0;
long long muls = 1;
long long result = 1;
};
class sum_all_deviders
{
public:
long long local_sum = 0;
long long local_mul = 1;
long long muls = 1;
long long result = 1;
};
class euler_function
{
public:
long long muls = 1;
long long result = 1;
};
int main()
{
std::ios::sync_with_stdio(false);
std::cin.tie(0);
std::cout.tie(0);
long long N = 0;
std::cin >> N;
auto lp = sieve(N);
long long d = 0, index = 0;
count_unique_deviders s_0;
sum_all_deviders s_1;
euler_function fi;
for (long long i = 2; i <= N; i++)
{
d += lp[i];
index = i;
s_0.unique_devider = lp[index];
s_0.counter_deviders = 0;
s_0.muls = s_1.muls = s_1.local_sum = fi.muls = s_1.local_mul = 1;
while (lp[index] != 0)
{
if (s_0.unique_devider != lp[index])
{
fi.muls *= s_1.local_mul / s_0.unique_devider * (s_0.unique_devider - 1);
s_1.muls *= s_1.local_sum;
s_0.unique_devider = s_1.local_mul = lp[index];
s_0.muls *= s_0.counter_deviders + 1;
s_0.counter_deviders = 1;
s_1.local_sum = 1 + s_1.local_mul;
}
else
{
s_1.local_mul *= s_0.unique_devider;
s_1.local_sum += s_1.local_mul;
s_0.counter_deviders ++;
}
index = index / lp[index];
}
s_0.muls *= s_0.counter_deviders + 1;
s_1.muls *= s_1.local_sum;
fi.muls *= s_1.local_mul / s_0.unique_devider * (s_0.unique_devider - 1);
s_0.result += s_0.muls;
s_1.result += s_1.muls;
fi.result += fi.muls;
}
free(lp);
std::cout << d << ' ' << s_0.result << ' ' << s_1.result << ' ' << fi.result << std::endl;
return 0;
}
|
e6233a248af5bc1a70a21c2b6fa10da0a061f98b | 2a58e9ed87874c4d2938a45caf8d630ae35e12c7 | /lista 8/10.cpp | 2a1b9b93de330e177f97f860850840a8a4cc20f3 | [] | no_license | Simillo/dredd | 90cbce7dae47c39d7ce40f228e29cbfb77ee962e | 7a0630082716a47ebbe96b2f3ec191e6fa83063a | refs/heads/master | 2021-01-12T14:06:21.240878 | 2017-03-16T03:30:01 | 2017-03-16T03:30:01 | 69,566,051 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 206 | cpp | 10.cpp | #include <iostream>
using namespace std;
int add(int x,int y){
if (!x)
return y;
else
return add((x & y) << 1, x ^ y);
}
int main(){
int x,y;
cin >> x >> y;
cout << add(x,y) << endl;
} |
728b4c8b6ac8c4cfcf1be656e0ac0d1a12a7c596 | 216f5252a8df73f8547d6a6c831409c916bae3e5 | /windows_embedded_compact_2013_2015M09/WINCE800/private/test/net/winsock/22/IPvX/stress/ghstres2/ghstres2_vx.cpp | d08dc658c6475c02a683c6fe5984d8efb10e8477 | [] | no_license | fanzcsoft/windows_embedded_compact_2013_2015M09 | 845fe834d84d3f0021047bc73d6cf9a75fabb74d | d04b71c517428ed2c73e94caf21a1582b34b18e3 | refs/heads/master | 2022-12-19T02:52:16.222712 | 2020-09-28T20:13:09 | 2020-09-28T20:13:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 29,245 | cpp | ghstres2_vx.cpp | //
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//
// Use of this source code is subject to the terms of the Microsoft shared
// source or premium shared source license agreement under which you licensed
// this source code. If you did not accept the terms of the license agreement,
// you are not authorized to use this source code. For the terms of the license,
// please see the license agreement between you and Microsoft or, if applicable,
// see the SOURCE.RTF on your install media or the root of your tools installation.
// THE SOURCE CODE IS PROVIDED "AS IS", WITH NO WARRANTIES OR INDEMNITIES.
//
#include <winsock2.h>
#include <ws2tcpip.h>
#include <windows.h>
#include "netmain.h"
#include <strsafe.h>
#include "Iphlpapi.h"
#define WINSOCK_VERSION_REQ MAKEWORD(2,2)
#define MAX_HOSTS 5
#define MAX_ADDR_SIZE 32
#define MAX_NAME_SIZE 256
#define DEFAULT_MSGTIME 10
#define DEFAULT_WAITTIME 0
#define DEFAULT_REPS 0
#define IP_UNSPEC 0
#define IP_V4 4
#define IP_V6 6
void PrintUsage()
{
QAMessage(TEXT("ghstres2_vX [-f Frequency] [-m Milliseconds] [-r Reps] [-a IPAddress] [-n HostName] [-ipv IPVersion] [-s] [-l]"));
QAMessage(TEXT(" f: Number of interations to perform before displaying status (default: %d)"), DEFAULT_MSGTIME);
QAMessage(TEXT(" m: Number of milliseconds to wait between iterations (default: %d)"), DEFAULT_WAITTIME);
QAMessage(TEXT(" r: Number of reps to execute the test (default: %d)"), DEFAULT_REPS);
QAMessage(TEXT(" a: IP address of a host to resolve into a name"));
QAMessage(TEXT(" n: Name of a host to resolve into an address"));
QAMessage(TEXT(" s: Flag to perform Resolution Test against primary DNS server"));
QAMessage(TEXT(" ipv: Flag to force IP Version. Bypassed by -a. [values: 4 or 6] (default: AF_UNSPEC)"));
QAMessage(TEXT(" l: Force the usage of legacy Get Host Stress - ghstres2.exe."));
QAMessage(TEXT("*** - NOTE - Multiple addresses and names can be given but they must be separated"));
QAMessage(TEXT(" with semi-colons. Up to %d names/addresses."), MAX_HOSTS);
}
DWORD g_dwMessageFrequency;
DWORD g_dwWaitTime;
DWORD g_dwReps;
DWORD g_dwIPVersion;
BOOL g_bGetHostAPIs = FALSE;
LPTSTR g_szAddresses, g_szNames;
DWORD AddressThreadVx(LPVOID *pParm);
DWORD NameThreadVx(LPVOID *pParm);
DWORD AddressThread(LPVOID *pParm);
DWORD NameThread(LPVOID *pParm);
extern "C" LPTSTR gszMainProgName = _T("ghstres2_vX");
extern "C" DWORD gdwMainInitFlags = INIT_NET_CONNECTION;
extern "C" mymain (int argc, TCHAR *argv[])
{
WSADATA WSAData;
HANDLE hAddrThread = NULL, hNameThread = NULL;
DWORD ThreadId;
if(QAWasOption(_T("?")) || QAWasOption(_T("help")))
{
PrintUsage();
return 0;
}
// Initialize globals
g_dwMessageFrequency = DEFAULT_MSGTIME;
g_dwWaitTime = DEFAULT_WAITTIME;
g_dwReps = DEFAULT_REPS;
g_dwIPVersion = 0;
g_szAddresses = g_szNames = NULL;
QAGetOptionAsDWORD(_T("m"), &g_dwWaitTime);
QAGetOptionAsDWORD(_T("ipv"), &g_dwIPVersion);
QAGetOptionAsDWORD(_T("r"), &g_dwReps);
QAGetOption(_T("a"), &g_szAddresses);
QAGetOption(_T("n"), &g_szNames);
if(QAGetOptionAsDWORD(_T("f"), &g_dwMessageFrequency) && g_dwMessageFrequency == 0)
g_dwMessageFrequency = 1; // MessageFrequency can not be 0
// Put the multiple names/addresses into they're appropriate globals
if(WSAStartup(WINSOCK_VERSION_REQ, &WSAData) != 0)
{
QAError(TEXT("WSAStartup Failed"));
return 1;
}
else
{
QAMessage(TEXT("WSAStartup SUCCESS"));
}
if (QAWasOption(_T("l")))
{
QAMessage(TEXT("Using Legacy ghstress.exe stress API."));
g_dwIPVersion = IP_V4; // Only v4 was used on old stress.
g_bGetHostAPIs = TRUE;
}
// if -s flag was set.
if (QAWasOption(_T("s")))
{
ADDRINFO AddrHints = {0};
ADDRINFO *pAddrInfo = NULL;
PIP_ADAPTER_DNS_SERVER_ADDRESS dnsServerAddresses = NULL;
CHAR szName[MAX_NAME_SIZE];
TCHAR tszAdresses[MAX_NAME_SIZE];
TCHAR tszName[MAX_NAME_SIZE];
DWORD dwAddressSize = MAX_NAME_SIZE;
size_t retVal = 0;
ULONG outBufLen = 0;
INT af = AF_UNSPEC;
PIP_ADAPTER_ADDRESSES pAddresses = NULL;
// Take the IP Address of the Currently set DNS server
// Get the Address Info and use this to extract a DNS Server
pAddresses = (IP_ADAPTER_ADDRESSES *) malloc(outBufLen);
if (pAddresses == NULL)
{
QAError(TEXT("Memory allocation failed for IP_ADAPTER_ADDRESSES struct\n"));
goto exit;
}
if (ERROR_BUFFER_OVERFLOW == GetAdaptersAddresses(AF_UNSPEC, 0, NULL, pAddresses, &outBufLen))
{
free(pAddresses);
pAddresses = NULL;
pAddresses = (IP_ADAPTER_ADDRESSES *) malloc(outBufLen);
if (pAddresses == NULL)
{
QAError(TEXT("Memory allocation failed for IP_ADAPTER_ADDRESSES struct\n"));
goto exit;
}
}
if (NO_ERROR == GetAdaptersAddresses(AF_UNSPEC, 0, NULL, pAddresses, &outBufLen))
{
PIP_ADAPTER_ADDRESSES pCurrAddresses = pAddresses;
while (pCurrAddresses)
{
if (pCurrAddresses->FirstDnsServerAddress)
{
dnsServerAddresses = pCurrAddresses->FirstDnsServerAddress;
break;
}
pCurrAddresses = pCurrAddresses->Next;
}
}
if (!dnsServerAddresses)
{
QAError(TEXT("GetAdaptersAddresses() Could not find a DNS server to use!"));
goto exit;
}
// Loop through Primary and Secondary DNS servers to find an appropriate server to use for testing.
while (dnsServerAddresses)
{
dwAddressSize = MAX_NAME_SIZE;
if(WSAAddressToString(dnsServerAddresses->Address.lpSockaddr, dnsServerAddresses->Address.iSockaddrLength, NULL, tszAdresses, &dwAddressSize))
{
QAMessage(TEXT("WSAAddressToString() error %d = %s - Converting DNS address."), WSAGetLastError(), GetLastErrorText());
goto nextServer;
}
// Get the Name of the DNS Server from the IP Address (v4 on corpnet)
// Perform rDNS to retrieve the name of the server
// Get the Name of the DNS Server for Forward Name Resolution
if(getnameinfo(dnsServerAddresses->Address.lpSockaddr, dnsServerAddresses->Address.iSockaddrLength, szName, sizeof(szName), NULL, 0, NI_NAMEREQD))
{
QAMessage(TEXT("getnameinfo() error %d = %s - Could not get DNS Name parameter."), WSAGetLastError(), GetLastErrorText());
goto nextServer;
}
StringCchPrintf( tszName, MAX_NAME_SIZE, L"%hs", szName ) ;
// Finally perform a getaddrinfo based off the name of the server address
// to find a v6 address to use.
if(IP_V6 == g_dwIPVersion || IP_UNSPEC == g_dwIPVersion)
{
// Get the IP Address of the DNS Server
memset(&AddrHints, 0, sizeof(AddrHints));
AddrHints.ai_family = AF_INET6;
if(getaddrinfo(szName, NULL, &AddrHints, &pAddrInfo))
{
QAMessage(TEXT("getaddrinfo() error %d = %s - Could not get a v6 address for DNS."), WSAGetLastError(), GetLastErrorText());
goto nextServer;
}
if (pAddrInfo)
{
TCHAR tszAdresseV6[MAX_NAME_SIZE];
dwAddressSize = MAX_NAME_SIZE;
if(WSAAddressToString(pAddrInfo->ai_addr, pAddrInfo->ai_addrlen, NULL, tszAdresseV6, &dwAddressSize))
{
QAMessage(TEXT("WSAAddressToString() error %d = %s - Converting v6 address found."), WSAGetLastError(), GetLastErrorText());
goto nextServer;
}
if (IP_UNSPEC == g_dwIPVersion)
{
TCHAR temp[MAX_NAME_SIZE];
StringCchPrintf( temp, MAX_NAME_SIZE, L";%s", tszAdresseV6 ) ;
StringCchCat( tszAdresses, MAX_NAME_SIZE, temp ) ;
}
else if (IP_V6 == g_dwIPVersion)
StringCchPrintf( tszAdresses, MAX_NAME_SIZE, L"%s", tszAdresseV6 ) ;
break;
}
}
else if (IP_V4 == g_dwIPVersion) // If v4, DNS address is already v4.
{
break;
}
nextServer:
dnsServerAddresses = dnsServerAddresses->Next;
}
// We've looped through all our DNS Servers and still didn't find any server
// suitable for forward and reverse name resolution.
if(!dnsServerAddresses)
{
QAError(TEXT("DNS servers assigned on this device are not appropriate for this test."), WSAGetLastError(), GetLastErrorText());
goto exit;
}
// Use our newly found information in our test.
g_szAddresses = tszAdresses;
g_szNames = tszName;
}
if(g_szAddresses)
{
if (g_bGetHostAPIs)
{
if ((hAddrThread =
CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) AddressThread,
NULL, 0, &ThreadId)) == NULL)
{
QAError(TEXT("BSTRESS: CreateThread(AddressToNameThread) failed %d"),
GetLastError());
goto exit;
}
}
else
{
if ((hAddrThread =
CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) AddressThreadVx,
NULL, 0, &ThreadId)) == NULL)
{
QAError(TEXT("BSTRESS: CreateThread(AddressToNameThread) failed %d"),
GetLastError());
goto exit;
}
}
}
if(g_szNames)
{
if (g_bGetHostAPIs)
{
if ((hNameThread =
CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) NameThread,
NULL, 0, &ThreadId)) == NULL)
{
QAError(TEXT("BSTRESS: CreateThread(NameToAddressThread) failed %d"),
GetLastError());
goto exit;
}
}
else
{
if ((hNameThread =
CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) NameThreadVx,
NULL, 0, &ThreadId)) == NULL)
{
QAError(TEXT("BSTRESS: CreateThread(NameToAddressThread) failed %d"),
GetLastError());
goto exit;
}
}
}
QAMessage(TEXT("Main thread waiting for completion..."));
exit:
if(hAddrThread)
{
WaitForSingleObject(hAddrThread, INFINITE);
CloseHandle(hAddrThread);
}
if(hNameThread)
{
WaitForSingleObject(hNameThread, INFINITE);
CloseHandle(hNameThread);
}
WSACleanup();
return 0;
}
//**********************************************************************************
DWORD AddressThreadVx(LPVOID *pParm)
{
char szAddressesASCII[256];
char *szAddressArray[MAX_HOSTS];
DWORD i, dwReps, dwNumAddr;
DWORD dwResolves;
char szName[MAX_HOSTS][MAX_NAME_SIZE];
char szNameASCII[MAX_NAME_SIZE];
ADDRINFO AddrHints, *pAddrInfoArray[MAX_HOSTS];
size_t retVal = 0;
QAMessage(TEXT("AddressThread++"));
for(i = 0; i < MAX_HOSTS; i++)
szAddressArray[i] = NULL;
#if defined UNICODE
wcstombs_s(&retVal, szAddressesASCII, 256, g_szAddresses, sizeof(szAddressesASCII));
#else
strncpy(szAddressesASCII, g_szAddresses, sizeof(szAddressesASCII));
#endif
dwNumAddr = 0;
szAddressArray[dwNumAddr++] = &szAddressesASCII[0];
// Here we change all the ';' characters in szAddressASCII to NULLs
// And we set each element of szAddress Array equal to the respective
// now null-terminated address.
for(i = 0; i < 256 && szAddressesASCII[i] != '\0' && dwNumAddr < MAX_HOSTS; i++)
{
if(szAddressesASCII[i] == ';')
{
szAddressesASCII[i] = '\0';
if(i == 255 || szAddressesASCII[i+1] == '\0')
break; // Don't worry about trailing semi-colons
szAddressArray[dwNumAddr++] = &szAddressesASCII[i+1];
}
}
QAMessage(TEXT("AddrThread: Using the following %d addresses:"), dwNumAddr);
for(i = 0; i < dwNumAddr; i++)
QAMessage(TEXT("AddrThread: Addr %d: %hs"), i, szAddressArray[i]);
// Initialize our values
for(i = 0; i < dwNumAddr; i++)
{
memset(&AddrHints, 0, sizeof(AddrHints));
AddrHints.ai_family = PF_UNSPEC;
AddrHints.ai_socktype = SOCK_STREAM;
AddrHints.ai_flags = AI_NUMERICHOST | AI_PASSIVE;
if(getaddrinfo(szAddressArray[i], "100", &AddrHints, &pAddrInfoArray[i]))
{
QAError(TEXT("getaddrinfo() error %d = %s - Invalid address parameter %d"), WSAGetLastError(), GetLastErrorText(), i);
goto exitThread;
}
}
for(dwResolves = 0, dwReps = 0; dwReps < g_dwReps; dwReps++)
{
for(i = 0; i < dwNumAddr; i++)
{
if(g_dwWaitTime)
Sleep(g_dwWaitTime);
if(getnameinfo(pAddrInfoArray[i]->ai_addr, pAddrInfoArray[i]->ai_addrlen,
szNameASCII, sizeof(szNameASCII), NULL, 0, NI_NAMEREQD))
{
// TODO: we currently don't support v6. Remove this once we do.
if (AF_INET6 != pAddrInfoArray[i]->ai_family)
{
QAError(TEXT("AddrThread: getnameinfo() failed, error %d = %s"),
WSAGetLastError(), GetLastErrorText());
}
}
else
{
if(dwReps == 0)
{
// Store the name
StringCchCopyA(szName[i], MAX_NAME_SIZE, szNameASCII);
QAMessage(TEXT("AddrThread: Address[%hs] --> Name[%hs]"), szAddressArray[i], szName[i]);
}
else
{
// Verify that the name given has not changed
if(_stricmp(szName[i], szNameASCII))
{
QAError(TEXT("AddrThread: Couldn't find original name %hs in %hs returned by gethostbyaddr()"),
szName[i], szNameASCII);
}
}
}
dwResolves++;
}
if((dwReps + 1) % g_dwMessageFrequency == 0)
QAMessage(TEXT("AddrThread: address resolution performed %d time(s) in %d reps"), dwResolves, dwReps + 1);
}
exitThread:
for(i = 0; i < dwNumAddr; i++)
freeaddrinfo(pAddrInfoArray[i]);
QAMessage(TEXT("AddressThread--"));
return 0;
}
//**********************************************************************************
DWORD NameThreadVx(LPVOID *pParm)
{
char szNamesASCII[256];
char *szNameArray[MAX_HOSTS];
DWORD i, dwReps, dwNumName;
DWORD dwResolves;
ADDRINFO AddrHints, *pAddrInfo, *pAI;
struct in_addr6 pAddr[MAX_HOSTS];
size_t retVal = 0;
QAMessage(TEXT("NameThread++"));
memset(pAddr, 0, sizeof(pAddr));
for(i = 0; i < MAX_HOSTS; i++)
szNameArray[i] = NULL;
#if defined UNICODE
wcstombs_s(&retVal, szNamesASCII, 256, g_szNames, sizeof(szNamesASCII));
#else
strncpy(szNamesASCII, g_szNames, sizeof(szNamesASCII));
#endif
dwNumName = 0;
szNameArray[dwNumName++] = &szNamesASCII[0];
// Here we change all the ';' characters in szNamesASCII to NULLs
// And we set each element of szNameArray equal to the respective
// now null-terminated name.
for(i = 0; i < 256 && szNamesASCII[i] != '\0' && dwNumName < MAX_HOSTS; i++)
{
if(szNamesASCII[i] == ';')
{
szNamesASCII[i] = '\0';
if(i == 255 || szNamesASCII[i+1] == '\0')
break; // Don't worry about trailing semi-colons
szNameArray[dwNumName++] = &szNamesASCII[i+1];
}
}
QAMessage(TEXT("NameThread: Using the following %d names:"), dwNumName);
for(i = 0; i < dwNumName; i++)
QAMessage(TEXT("NameThread: Name %d: %hs"), i, szNameArray[i]);
for(dwResolves = 0, dwReps = 0; dwReps < g_dwReps; dwReps++)
{
for(i = 0; i < dwNumName; i++)
{
if(g_dwWaitTime)
Sleep(g_dwWaitTime);
memset(&AddrHints, 0, sizeof(AddrHints));
AddrHints.ai_family = PF_UNSPEC;
AddrHints.ai_socktype = SOCK_STREAM;
AddrHints.ai_flags = 0;
if(getaddrinfo(szNameArray[i], "100", &AddrHints, &pAddrInfo))
{
QAError(TEXT("NameThread: getaddrinfo() failed, error %d = %s"),
WSAGetLastError(), GetLastErrorText());
}
else
{
if(dwReps == 0)
{
QAMessage(TEXT("NameThread: We only check the first address returned for persistence."));
// Store the first address
if(pAddrInfo->ai_addr->sa_family == PF_INET)
memcpy(&pAddr[i], &(((SOCKADDR_IN *)(pAddrInfo->ai_addr))->sin_addr.s_addr), sizeof(IN_ADDR));
else
memcpy(&pAddr[i], &(((SOCKADDR_IN6 *)(pAddrInfo->ai_addr))->sin6_addr.s6_addr), sizeof(struct in_addr6));
// Print all the addresses
for(pAI = pAddrInfo; pAI != NULL; pAI = pAI->ai_next)
{
if(pAI->ai_addr->sa_family == PF_INET)
{
QAMessage(TEXT("NameThrd: Name[%hs] --> AF_INET Addr[%08x]"),
szNameArray[i],
htonl((DWORD)(((SOCKADDR_IN *)(pAI->ai_addr))->sin_addr.s_addr)) );
}
else
{
QAMessage(TEXT("NameThrd: Name[%hs] --> AF_INET6 Addr[%04x%04x%04x%04x%04x%04x%04x%04x]"), szNameArray[i],
htons((*(WORD *)&(((SOCKADDR_IN6 *)(pAI->ai_addr))->sin6_addr.s6_addr[0]))),
htons((*(WORD *)&(((SOCKADDR_IN6 *)(pAI->ai_addr))->sin6_addr.s6_addr[2]))),
htons((*(WORD *)&(((SOCKADDR_IN6 *)(pAI->ai_addr))->sin6_addr.s6_addr[4]))),
htons((*(WORD *)&(((SOCKADDR_IN6 *)(pAI->ai_addr))->sin6_addr.s6_addr[6]))),
htons((*(WORD *)&(((SOCKADDR_IN6 *)(pAI->ai_addr))->sin6_addr.s6_addr[8]))),
htons((*(WORD *)&(((SOCKADDR_IN6 *)(pAI->ai_addr))->sin6_addr.s6_addr[10]))),
htons((*(WORD *)&(((SOCKADDR_IN6 *)(pAI->ai_addr))->sin6_addr.s6_addr[12]))),
htons((*(WORD *)&(((SOCKADDR_IN6 *)(pAI->ai_addr))->sin6_addr.s6_addr[14]))) );
}
}
}
else
{
// Verify that the address given has not changed
for(pAI = pAddrInfo; pAI != NULL; pAI = pAI->ai_next)
{
if(pAI->ai_addr->sa_family == PF_INET)
{
if(!memcmp(&pAddr[i], &(((SOCKADDR_IN *)(pAI->ai_addr))->sin_addr.s_addr), sizeof(IN_ADDR)))
break;
}
else
{
if(!memcmp(&pAddr[i], &(((SOCKADDR_IN6 *)(pAI->ai_addr))->sin6_addr.s6_addr), sizeof(struct in_addr6)))
break;
}
}
if(pAI == NULL)
{
QAError(TEXT("NameThread: Couldn't find original addr in info returned by getnameinfo()"));
}
}
}
freeaddrinfo(pAddrInfo);
dwResolves++;
}
if((dwReps + 1) % g_dwMessageFrequency == 0)
QAMessage(TEXT("NameThread: address resolution performed %d time(s) in %d reps"), dwResolves, dwReps + 1);
}
QAMessage(TEXT("NameThread--"));
return 0;
}
//**********************************************************************************
DWORD AddressThread(LPVOID *pParm)
{
char szAddressesASCII[256];
char *szAddressArray[MAX_HOSTS];
DWORD dwAddrArray[MAX_HOSTS], i, j, dwReps, dwNumAddr;
DWORD dwResolves;
HOSTENT *pHstData;
char szName[MAX_HOSTS][MAX_NAME_SIZE];
BOOL bMatch;
size_t retVal = 0;
QAMessage(TEXT("AddressThread++"));
for(i = 0; i < MAX_HOSTS; i++)
szAddressArray[i] = NULL;
#if defined UNICODE
wcstombs_s(&retVal, szAddressesASCII, 256, g_szAddresses, sizeof(szAddressesASCII));
#else
strncpy(szAddressesASCII, g_szAddresses, sizeof(szAddressesASCII));
#endif
dwNumAddr = 0;
szAddressArray[dwNumAddr++] = &szAddressesASCII[0];
// Here we change all the ';' characters in szAddressASCII to NULLs
// And we set each element of szAddress Array equal to the respective
// now null-terminated address.
for(i = 0; i < 256 && szAddressesASCII[i] != '\0' && dwNumAddr < MAX_HOSTS; i++)
{
if(szAddressesASCII[i] == ';')
{
szAddressesASCII[i] = '\0';
if(i == 255 || szAddressesASCII[i+1] == '\0')
break; // Don't worry about trailing semi-colons
szAddressArray[dwNumAddr++] = &szAddressesASCII[i+1];
}
}
QAMessage(TEXT("AddrThread: Using the following %d addresses:"), dwNumAddr);
for(i = 0; i < dwNumAddr; i++)
QAMessage(TEXT("AddrThread: Addr %d: %hs"), i, szAddressArray[i]);
for(i = 0; i < dwNumAddr; i++)
{
if((dwAddrArray[i] = inet_addr(szAddressArray[i])) == INADDR_NONE)
{
QAError(TEXT("Invalid address parameter = %hs\n"), szAddressArray[i]);
goto exitThread;
}
}
for(dwResolves = 0, dwReps = 0; dwReps < g_dwReps; dwReps++)
{
for(i = 0; i < dwNumAddr; i++)
{
if(g_dwWaitTime)
Sleep(g_dwWaitTime);
pHstData = gethostbyaddr( (char *)&dwAddrArray[i], sizeof(DWORD), AF_INET);
if(pHstData == NULL)
{
QAError(TEXT("AddrThread: gethostbyaddr() failed, error %d = %s"),
WSAGetLastError(), GetLastErrorText());
}
else
{
if(dwReps == 0)
{
// Store the name
StringCchCopyA(szName[i], MAX_NAME_SIZE, pHstData->h_name);
QAMessage(TEXT("AddrThread: Address[%hs] --> Name[%hs]"), szAddressArray[i], szName[i]);
}
else
{
// Verify that the name given has not changed
bMatch = FALSE;
if(_stricmp(szName[i], pHstData->h_name) == 0)
bMatch = TRUE;
else if(pHstData->h_aliases)
{
// Might be an alias
for(j = 0; pHstData->h_aliases[j] != NULL; j++)
{
if(_stricmp(szName[i], pHstData->h_aliases[j]) == 0)
{
bMatch = TRUE;
break;
}
}
}
if(!bMatch)
{
QAError(TEXT("AddrThread: Couldn't find original name %hs in info returned by gethostbyaddr()"),
szName[i]);
}
}
}
dwResolves++;
}
if((dwReps + 1) % g_dwMessageFrequency == 0)
QAMessage(TEXT("AddrThread: address resolution performed %d time(s) in %d reps"), dwResolves, dwReps + 1);
}
exitThread:
QAMessage(TEXT("AddressThread--"));
return 0;
}
//**********************************************************************************
DWORD NameThread(LPVOID *pParm)
{
char szNamesASCII[256];
char *szNameArray[MAX_HOSTS];
DWORD i, j, dwReps, dwNumName;
DWORD dwResolves;
HOSTENT *pHstData;
char pAddr[MAX_HOSTS][MAX_ADDR_SIZE];
BOOL bMatch;
size_t retVal = 0;
QAMessage(TEXT("NameThread++"));
for(i = 0; i < MAX_HOSTS; i++)
szNameArray[i] = NULL;
#if defined UNICODE
wcstombs_s(&retVal, szNamesASCII, 256, g_szNames, sizeof(szNamesASCII));
#else
strncpy(szNamesASCII, g_szNames, sizeof(szNamesASCII));
#endif
dwNumName = 0;
szNameArray[dwNumName++] = &szNamesASCII[0];
// Here we change all the ';' characters in szNamesASCII to NULLs
// And we set each element of szNameArray equal to the respective
// now null-terminated name.
for(i = 0; i < 256 && szNamesASCII[i] != '\0' && dwNumName < MAX_HOSTS; i++)
{
if(szNamesASCII[i] == ';')
{
szNamesASCII[i] = '\0';
if(i == 255 || szNamesASCII[i+1] == '\0')
break; // Don't worry about trailing semi-colons
szNameArray[dwNumName++] = &szNamesASCII[i+1];
}
}
QAMessage(TEXT("NameThread: Using the following %d names:"), dwNumName);
for(i = 0; i < dwNumName; i++)
QAMessage(TEXT("NameThread: Name %d: %hs"), i, szNameArray[i]);
for(dwResolves = 0, dwReps = 0; dwReps < g_dwReps; dwReps++)
{
for(i = 0; i < dwNumName; i++)
{
if(g_dwWaitTime)
Sleep(g_dwWaitTime);
pHstData = gethostbyname(szNameArray[i]);
if(pHstData == NULL)
{
QAError(TEXT("NameThread: gethostbyname() failed, error %d = %s"),
WSAGetLastError(), GetLastErrorText());
}
else
{
if(dwReps == 0)
{
// Store the first address
memcpy(pAddr[i], pHstData->h_addr_list[0], pHstData->h_length);
QAMessage(TEXT("NameThread: Name[%hs] --> Addr[%x]"), szNameArray[i], htonl(*((DWORD *)pAddr[i])));
}
else
{
// Verify that the address given has not changed
bMatch = FALSE;
for(j = 0; pHstData->h_addr_list[j] != NULL; j++)
{
if(memcmp(pAddr[i], pHstData->h_addr_list[j], pHstData->h_length) == 0)
{
bMatch = TRUE;
break;
}
}
if(!bMatch)
{
QAError(TEXT("NameThread: Couldn't find original addr %d in info returned by gethostbyname()"),
(DWORD *)pAddr[i]);
}
}
}
dwResolves++;
}
if((dwReps + 1) % g_dwMessageFrequency == 0)
QAMessage(TEXT("NameThread: address resolution performed %d time(s) in %d reps"), dwResolves, dwReps + 1);
}
QAMessage(TEXT("NameThread--"));
return 0;
} |
7e16469f9908228b4b90a63ac18f411f2943029b | 55540f3e86f1d5d86ef6b5d295a63518e274efe3 | /components/network/thread/openthread/src/lib/spinel/spinel_interface.hpp | 585f257aa6dae3f6777508e4c7cc86def21d8007 | [
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | permissive | bouffalolab/bl_iot_sdk | bc5eaf036b70f8c65dd389439062b169f8d09daa | b90664de0bd4c1897a9f1f5d9e360a9631d38b34 | refs/heads/master | 2023-08-31T03:38:03.369853 | 2023-08-16T08:50:33 | 2023-08-18T09:13:27 | 307,347,250 | 244 | 101 | Apache-2.0 | 2023-08-28T06:29:02 | 2020-10-26T11:16:30 | C | UTF-8 | C++ | false | false | 2,511 | hpp | spinel_interface.hpp | /*
* Copyright (c) 2019, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
* 3. Neither the name of the copyright holder 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 HOLDER 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.
*/
/**
* @file
* This file includes definitions for the spinel interface to Radio Co-processor (RCP)
*
*/
#ifndef POSIX_APP_SPINEL_INTERFACE_HPP_
#define POSIX_APP_SPINEL_INTERFACE_HPP_
#include "lib/hdlc/hdlc.hpp"
namespace ot {
namespace Spinel {
class SpinelInterface
{
public:
enum
{
kMaxFrameSize = OPENTHREAD_CONFIG_PLATFORM_RADIO_SPINEL_RX_FRAME_BUFFER_SIZE, ///< Maximum buffer size.
};
/**
* This type defines a receive frame buffer to store received spinel frame(s).
*
* @note The receive frame buffer is an `Hdlc::MultiFrameBuffer` and therefore it is capable of storing multiple
* frames in a FIFO queue manner.
*
*/
typedef Hdlc::MultiFrameBuffer<kMaxFrameSize> RxFrameBuffer;
typedef void (*ReceiveFrameCallback)(void *aContext);
};
} // namespace Spinel
} // namespace ot
#endif // POSIX_APP_SPINEL_INTERFACE_HPP_
|
75b4c367da604d13db33ce3e023a75f727359137 | 377b64e0fd93dd543898fcf0bf3b0bb052ba758e | /leetcode/Generate Parentheses.cpp | 2d9e5d464f19b248843b89bb9be491130b3e53d4 | [] | no_license | heonilp/study | 452b80f1dbae1c0f2569d5b84d4c5e1f6e7b993f | b2f47e880ffc2b9f1a44d00c8f9baf815d357484 | refs/heads/master | 2022-07-09T05:29:39.207350 | 2021-07-25T13:15:53 | 2021-07-25T13:15:53 | 191,583,274 | 7 | 1 | null | 2022-06-21T04:18:44 | 2019-06-12T14:06:36 | C++ | UTF-8 | C++ | false | false | 794 | cpp | Generate Parentheses.cpp | //-재귀 사용풀이
class Solution {
private:
vector<string> ans;
public:
void go(string s,int left,int right, int n)
{
if(right == n)
{
ans.push_back(s);
return;
}
if(left == n)
{
while(right != n)
{
s.push_back(')');
right++;
}
ans.push_back(s);
return;
}
if(right + 1 <= left)
{
go(s+')',left,right+1,n);
}
go(s+'(',left+1,right,n);
}
vector<string> generateParenthesis(int n)
{
int left = 1;
int right = 0;
string s = "(";
go(s,left,right,n);
return ans;
}
}; |
136e63584366858324cc3c147619c6f4a99430dd | 8908bb8c289e07d2b1514ca86e1d3cccaa8b5761 | /db/dao/CBDAO.cpp | f03ceb5d50ef90b75f7decff0d609bd510149182 | [
"MIT"
] | permissive | teachmlrepo/toolbox | cdb031cdf8cf1d50c75fb72a6a2db6ba14c145f3 | aaca5aca66ad6aca97737bc47a7c2de7621e54f2 | refs/heads/master | 2022-12-19T00:00:02.504308 | 2020-09-26T13:09:53 | 2020-09-26T13:09:53 | 293,242,336 | 0 | 0 | null | 2020-09-06T09:19:01 | 2020-09-06T09:19:01 | null | UTF-8 | C++ | false | false | 895 | cpp | CBDAO.cpp | /*
*
* Crypto.BI Toolbox
* https://Crypto.BI/
*
* Author: José Fonseca (https://zefonseca.com/)
*
* Distributed under the MIT software license, see the accompanying
* file COPYING or http://www.opensource.org/licenses/mit-license.php.
*
*/
#include "CBDAO.h"
namespace db::dao {
std::vector<CBDAODriver *> CBDAO::_drivers;
std::mutex CBDAO::_mutex;
int CBDAO::_driver_counter = 0;
int CBDAO::pool_size;
bool CBDAO::first_run = true;
CBDAODriver *CBDAO::get_DAO() {
std::scoped_lock<std::mutex> l{_mutex};
if (first_run) {
init_dao();
first_run = false;
}
auto ret = _drivers[_driver_counter];
++_driver_counter %= pool_size;
return ret;
}
void CBDAO::init_dao() {
_driver_counter = 0;
pool_size = std::thread::hardware_concurrency();
_drivers.reserve(pool_size);
for (int i=0;i<pool_size;i++) {
_drivers[i] = new mysql::CBMySQL();
}
}
} /* namespace db */
|
38ac17ebe118bc9473d872ec81802fa463d04e4f | f310c8add40eef95dfa6dd70ead2b3a317c9f905 | /main.cpp | e36bd6da2d1bf4a11b97d14b27676d9f8dcbb0a3 | [] | no_license | CosineGaming/Q | 405eacaae8657a9e481a3087fa1a56109f9076aa | 2d90c836b617ecd9f28e4ffd9f3d26161ae41807 | refs/heads/master | 2021-01-25T08:54:42.703951 | 2013-07-08T19:01:03 | 2013-07-08T19:01:03 | null | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 3,593 | cpp | main.cpp | #include <iostream>
#include <fstream>
#define _USE_MATH_DEFINES
#include <math.h>
#include "glut.h"
#include "color.h"
#include <stdlib.h>
#include "time.h"
#define DEPTH 3
color Color(1.0, 1.0, 1.0);
int matrix[25];
void init ()
{
glClearColor (0.2, 0.2, 0.35, 0.0); // sets background Color to black
glMatrixMode (GL_PROJECTION); // sets up viewing values (do not worry about this too much)
glLoadIdentity ();
glOrtho (-100.0, 100.0, -100.0, 100.0, -1.0, 1.0); // sets up “graph paper” for you to draw on
char * line = new char;
int i = 0;
std::ifstream file("C:/Developing/Q/Q/Matrix.txt");
if (file.is_open()) {
while (file.good() && i < 25) {
int let = file.get();
if (let != '\n' && let != ' ') {
matrix[i] = let - '0';
i++;
}
}
}
else {
std::cout << "Error opening file." << std::endl;
}
file.close();
srand(time(0));
system("start notepad C:/Developing/Q/Q/Matrix.txt");
}
void perfect(float X, float Y, int sides, float sideWidth, int degOffset=0) {
int angleEach = (360 / sides);
float halfHeight = sideWidth / 2.0 / tan(angleEach / 2 / (180.0 / M_PI));
float hyp = halfHeight / cos(angleEach / 2 / (180 / M_PI));
glBegin(GL_POLYGON);
for (int i=0; i<sides; i++) {
float deg = (i * angleEach - angleEach / 2 + degOffset) / (180.0 / M_PI);
glVertex3f(X + sin(deg) * hyp,
Y + cos(deg) * hyp, 0.0);
}
glEnd();
}
float xByIndex(int i, float size) { return (i % 5) * size ; }
float yByIndex(int i, float size) {return -1 * (i / 5 * size);}
void drawFractal(float x=-100.0, float y=100.0, float size=200.0, int frame=0) {
size = size / 5.0;
for (int i=0; i<25; i++) {
if (matrix[i]) {
if (frame < DEPTH) {
drawFractal(xByIndex(i, size) + x, yByIndex(i, size) + y, size, frame + 1);
}
else {
perfect(xByIndex(i, size) + size / 2.0 + x, yByIndex(i, size) + size / 2.0 + y, 4, size);
}
}
}
}
void display()
{
glClear (GL_COLOR_BUFFER_BIT); // clears screen
glColor3f (Color[0], Color[1], Color[2]); // sets Color for drawing operations to white
drawFractal();
glutSwapBuffers (); // makes sure commands are executed immediately
}
void update() {
char * line = new char;
int i = 0;
std::ifstream file("C:/Developing/Q/Q/Matrix.txt");
if (file.is_open()) {
while (file.good() && i < 25) {
int let = file.get();
if (let != '\n' && let != ' ') {
matrix[i] = let - '0';
i++;
}
}
}
else {
std::cout << "Error opening file." << std::endl;
}
file.close();
glutPostRedisplay();
}
void refresh(unsigned char key, int x, int y) {
if (key == 'r') {
char * line = new char;
int i = 0;
std::ifstream file("C:/Developing/Q/Q/Matrix.txt");
if (file.is_open()) {
while (file.good() && i < 25) {
int let = file.get();
if (let != '\n' && let != ' ') {
matrix[i] = let - '0';
i++;
}
}
}
else {
std::cout << "Error opening file." << std::endl;
}
file.close();
glutPostRedisplay();
}
}
int main(int argc, char** argv)
{
glutInit (&argc, argv); // initialization
glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB); // certain settings
glutInitWindowSize (500, 500); // sets window size in pixels (horizontal and vertical)
glutInitWindowPosition (10, 10); // upper left corner position
glutCreateWindow ("Indidraw!"); // sets the window title
init (); // calls the init() function
glutDisplayFunc (display); // uses the function called “display” for displaying
glutKeyboardFunc(refresh);
glutIdleFunc(update);
glutMainLoop (); // will execute OpenGL functions continuously
glutPostRedisplay();
return 0;
} |
be69f32e2d9950f413ebc2667e611c1aba565ef7 | f67008366d94d288854f7ef985f05fdc8e42c520 | /Graphs/OpenGL/GL_Font.cc | cbd1c409444ba712fe5f1e402f220018ed0ea35f | [
"MIT"
] | permissive | TrevorShelton/cplot | 6273c78a6cb888ed832cc93610b474ea78fda357 | 8bf40e94519cc4fd69b2e0677d3a3dcf8695245a | refs/heads/master | 2022-11-06T12:29:19.509338 | 2020-06-25T16:00:14 | 2020-06-25T16:00:14 | 274,957,449 | 0 | 0 | MIT | 2020-06-25T16:00:15 | 2020-06-25T15:55:44 | null | UTF-8 | C++ | false | false | 1,041 | cc | GL_Font.cc | #include "GL_Font.h"
#include "../../Utility/StringFormatting.h"
void GL_Font::save(Serializer &s) const
{
s.string_(name);
s.float_(size);
color.save(s);
}
void GL_Font::load(Deserializer &s)
{
s.string_(name);
s.float_(size);
color.load(s);
}
std::ostream &operator<<(std::ostream &os, const GL_Font &f)
{
os << '(' << f.name << ", " << f.size << "pt, " << f.color << ')';
return os;
}
std::string GL_Font::to_string() const
{
return name + format(" %d", (int)round(size));
}
GL_Font& GL_Font::operator= (const std::string &s)
{
size_t n = s.length();
if (!n)
{
// TODO: set some default font?
throw error("Not a valid font", s);
}
// split into name and size
size_t i = n;
while (i > 0 && isdigit(s[i-1])) --i;
if (i < n && i > 0 && (s[i-1]=='+' || s[i-1]=='-')) --i;
if (i < n)
{
int k; is_int(s.c_str()+i, k);
size = (float)k;
while (i > 0 && isspace(s[i-1])) --i;
if (i > 0) name = s.substr(0, i);
}
else
{
name = s;
}
// TODO: if name = "bold" and such, modify current font
return *this;
}
|
2af94fe8779ecab3fc05f881cc8383446772c879 | ab21d878c7710cef338db8745d3f4924549e7f85 | /src/Calculator/Common/TitleBarHelper.cpp | 18e8be947462d890336753ac8ab1b82c0458ed84 | [
"MIT",
"LGPL-2.1-or-later"
] | permissive | killvxk/calculator | f7083b47cd64be5f0dd142799bfef254436afc30 | 6a05ee45a8a7834143e330e8fcf18212493b2434 | refs/heads/master | 2020-04-27T10:22:31.963131 | 2019-03-11T09:56:25 | 2019-03-11T09:56:25 | 174,251,031 | 1 | 1 | MIT | 2019-03-11T09:56:26 | 2019-03-07T01:46:44 | C++ | UTF-8 | C++ | false | false | 3,016 | cpp | TitleBarHelper.cpp | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "pch.h"
#include "TitleBarHelper.h"
#include "Converters/BooleanToVisibilityConverter.h"
#include "CalcViewModel/ViewState.h"
using namespace CalculatorApp::Common;
using namespace CalculatorApp::Converters;
using namespace Platform;
using namespace std;
using namespace Windows::ApplicationModel::Core;
using namespace Windows::Foundation;
using namespace Windows::UI::Xaml;
unique_ptr<TitleBarHelper> TitleBarHelper::CreateTitleBarHelperIfNotDocked(FrameworkElement^ customTitleBar)
{
return (App::GetAppViewState() == ViewState::DockedView)
? nullptr
: CalculatorApp::Common::TitleBarHelper::CreateTitleBarHelper(customTitleBar);
}
unique_ptr<TitleBarHelper> TitleBarHelper::CreateTitleBarHelper(_In_ FrameworkElement^ customTitleBar)
{
assert(customTitleBar != nullptr);
if (customTitleBar != nullptr)
{
CoreApplicationViewTitleBar^ coreTitleBar = CoreApplication::GetCurrentView()->TitleBar;
assert(coreTitleBar != nullptr);
if (coreTitleBar != nullptr)
{
return make_unique<TitleBarHelper>(coreTitleBar, customTitleBar);
}
}
return nullptr;
}
TitleBarHelper::TitleBarHelper(_In_ CoreApplicationViewTitleBar^ coreTitleBar, _In_ FrameworkElement^ customTitleBar) :
m_coreTitleBar(coreTitleBar),
m_customTitleBar(customTitleBar)
{
RegisterForLayoutChanged();
RegisterForVisibilityChanged();
SetCustomTitleBar();
}
TitleBarHelper::~TitleBarHelper()
{
m_coreTitleBar->LayoutMetricsChanged -= m_layoutChangedToken;
m_coreTitleBar->IsVisibleChanged -= m_visibilityChangedToken;
}
void TitleBarHelper::SetTitleBarHeight(double height)
{
m_customTitleBar->Height = height;
}
void TitleBarHelper::SetTitleBarVisibility(bool isVisible)
{
m_customTitleBar->Visibility = BooleanToVisibilityConverter::Convert(isVisible);
}
void TitleBarHelper::RegisterForLayoutChanged()
{
m_layoutChangedToken =
m_coreTitleBar->LayoutMetricsChanged += ref new TypedEventHandler<CoreApplicationViewTitleBar^, Object^>(
[this](CoreApplicationViewTitleBar^ cTitleBar, Object^)
{
// Update title bar control size as needed to account for system size changes
SetTitleBarHeight(cTitleBar->Height);
});
}
void TitleBarHelper::RegisterForVisibilityChanged()
{
m_visibilityChangedToken =
m_coreTitleBar->IsVisibleChanged += ref new TypedEventHandler<CoreApplicationViewTitleBar^, Object^>(
[this](CoreApplicationViewTitleBar^ cTitleBar, Object^)
{
// Update title bar visibility
SetTitleBarVisibility(cTitleBar->IsVisible);
});
}
void TitleBarHelper::SetCustomTitleBar()
{
// Set custom XAML Title Bar
m_coreTitleBar->ExtendViewIntoTitleBar = true;
SetTitleBarHeight(m_coreTitleBar->Height);
SetTitleBarVisibility(m_coreTitleBar->IsVisible);
Window::Current->SetTitleBar(m_customTitleBar);
}
|
3480b97f20054a355f5500aca9990a391cc6ae28 | a7bdec0298f29bf530d9dc40bc09293edf7b34c4 | /generujGraf.hpp | 160bbf3d75cc67bbf245690a370d9e265bff6ab3 | [] | no_license | montsigur/PAMSI-lab06 | 19810b8e80a3ce3872be8fcf73e2338a2c95a462 | d8e0e7704c765cf22cfaac2e461e86f2281ce016 | refs/heads/master | 2016-09-14T02:47:24.383442 | 2016-05-18T16:47:03 | 2016-05-18T16:47:03 | 58,759,701 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,152 | hpp | generujGraf.hpp | // Wojciech Michałowski
// nr albumu 218705
#ifndef GENERUJGRAF_HPP
#define GENERUJGRAF_HPP
#include <ctime>
#include <cstdlib>
#include "graf.hpp"
#include "permutacje.hpp"
using namespace std;
int silnia(int n) {
if (n < 0)
return -1;
else if (n < 2)
return 1;
else
return n * silnia(n-1);
}
void polaczKlastry(wierzcholek* u, wierzcholek* v) {
vector<wierzcholek*>* klaster_u = u->klaster;
vector<wierzcholek*>* klaster_v = v->klaster;
(*klaster_u)[0] = NULL;
u->klaster = klaster_v;
klaster_v->push_back(u);
klaster_u->clear();
}
template <typename Graf>
bool czySpojny(Graf G) {
srand(time(NULL));
int indeks = rand() % G.wierzcholki.size();
kopiec krawedzie;
vector<wierzcholek*> wierzcholki_T;
vector<krawedz*> krawedzie_T;
wierzcholek *u, *v, *w;
krawedz* k;
w = G.wierzcholki[indeks];
G.przepiszIncydentneNaKopiec(w, krawedzie);
wierzcholki_T.push_back(w);
while(wierzcholki_T.size() < G.wierzcholki.size()) {
k = krawedzie.zdejmijMinimalny();
u = k->koniec1;
v = k->koniec2;
if (u != w and u->klaster->size() == 1) {
wierzcholki_T.push_back(u);
polaczKlastry(u, v);
G.przepiszIncydentneNaKopiec(u, krawedzie);
krawedzie_T.push_back(k);
}
else if (v != w and v->klaster->size() == 1) {
wierzcholki_T.push_back(v);
polaczKlastry(v, u);
G.przepiszIncydentneNaKopiec(v, krawedzie);
krawedzie_T.push_back(k);
}
}
for (int i=0; i<G.wierzcholki.size(); i++)
G.wierzcholki[i]->indeks = i;
if (krawedzie_T.size() < G.wierzcholki.size()-1)
return false;
else return true;
}
template <typename Graf>
void generujGraf(Graf &G, int n_wierzcholkow, double gestosc) {
G.wyczysc();
vector<string> permutacje, etykiety;
vector<krawedz*> krawedzie;
vector<wierzcholek*> wierzcholki;
string znaki = string("ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ");
string uzyte_znaki;
int n_znakow = 0, indeks, nty;
int n_max_krawedzi = n_wierzcholkow * (n_wierzcholkow - 1) / 2;
srand(time(NULL));
while (silnia(n_znakow) < n_wierzcholkow) n_znakow++;
uzyte_znaki = znaki.substr(rand() % 25, n_znakow);
Permutacje(uzyte_znaki, n_znakow, permutacje);
for (int i = 0; i < n_wierzcholkow; i++) {
wierzcholki.push_back(new wierzcholek(permutacje[i]));
G.dodajWierzcholek(wierzcholki[i]);
}
permutacje.clear();
for (int i = 0; i < n_wierzcholkow-1; i++)
for (int j = i+1; j < n_wierzcholkow; j++)
krawedzie.push_back(new krawedz(wierzcholki[i], wierzcholki[j], rand() % 100 + 1));
if (gestosc > 0.5 and gestosc < 1) {
nty = 1 / (1-gestosc);
for (int i = 0; i < n_max_krawedzi; i++)
if ((i+1) % nty != 0)
G.dodajKrawedz(krawedzie[i]);
}
else if (gestosc > 0 and gestosc <= 0.5) {
nty = 1 / gestosc;
for (int i = 0; i < n_max_krawedzi; i++)
if ((i+1) % nty == 0)
G.dodajKrawedz(krawedzie[i]);
}
else if (gestosc == 1)
for (int i = 0; i < n_wierzcholkow * (n_wierzcholkow - 1) / 2; i++)
G.dodajKrawedz(krawedzie[i]);
}
#endif
|
355c035011b90bab77b0151327930a9b8e5447a2 | 6afd626d3c2088da5b9574f649ec5dad97bbd779 | /leetcode/offer_ii_88/main.cc | 6713444883e95f9f604881d4332ab1e5f4a3e83e | [] | no_license | lxlenovostar/algorithm | 7acaea32d58df45002d6f87bb6d663a90df52e46 | 82c5f630157d03be8f36aea34b7d88d181f44673 | refs/heads/master | 2023-03-07T03:43:40.564903 | 2023-02-25T07:05:29 | 2023-02-25T07:05:29 | 60,962,183 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 620 | cc | main.cc | #include <vector>
#include <iostream>
using namespace std;
class Solution {
private:
int helper(vector<int>& cost, int index) {
if (index <= 1)
return cost[index];
return std::min(helper(cost, index-1), helper(cost, index-2)) + cost[index];
}
public:
int minCostClimbingStairs(vector<int>& cost) {
int n = cost.size();
return std::min(helper(cost, n-1), helper(cost, n-2));
}
};
int main() {
vector<int> cost = {10, 15, 20};
Solution *test = new Solution();
std::cout << test->minCostClimbingStairs(cost) << std::endl;
return 0;
} |
c421e7e7d7c7c7cac2e9b7179e0a7a88c0f68488 | b848d4f79256c7738b0923420d8548a0121ceb81 | /src/common/Polyline.cc | 76a117cf602bbe710532fc08dd3a8c79db0cf300 | [
"Zlib",
"LGPL-2.0-or-later",
"MIT",
"LicenseRef-scancode-other-permissive",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"xlock",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | ecmwf/magics | 57f5be3f4dcf339203688e7ce2bee92d9bc11318 | ba612c99a681547d111e4088ddc722cfb77b0666 | refs/heads/develop | 2023-08-19T02:56:24.734190 | 2023-08-04T07:37:52 | 2023-08-04T07:37:52 | 160,882,537 | 50 | 14 | Apache-2.0 | 2023-06-22T10:35:22 | 2018-12-07T22:39:04 | Jupyter Notebook | UTF-8 | C++ | false | false | 6,681 | cc | Polyline.cc | /*
* (C) Copyright 1996-2016 ECMWF.
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
* In applying this licence, ECMWF does not waive the privileges and immunities
* granted to it by virtue of its status as an intergovernmental organisation nor
* does it submit to any jurisdiction.
*/
/*! \file Polyline.cc
\brief Implementation of polyline graphics class (template).
Magics Team - ECMWF 2004
Started: Jan 2004
Changes:
*/
#include "Polyline.h"
#include "MagClipper.h"
#include "Transformation.h"
using namespace magics;
Polyline::Polyline() {}
Polyline::~Polyline() {}
void Polyline::reserve(double x) {}
bool Polyline::reproject(BasicGraphicsObjectContainer& out) const {
const Transformation& transformation = out.transformation();
transformation(*this, out);
return false;
}
Polyline* Polyline::getNew() const {
Polyline* poly = new Polyline();
poly->copy(*this);
return poly;
}
void Polyline::print(ostream& out) const {
out << "Polyline[";
out << ", nb_points = " << this->size();
if (this->size() < 2000) {
out << " Outer [";
string sep = "";
const unsigned int nb = size();
for (unsigned int i = 0; i < nb; i++) {
out << sep << get(i);
sep = ", ";
}
out << "]";
}
else {
unsigned int nb = size();
out << " Outer[" << get(0) << ", " << get(1) << ", " << get(2);
out << "...." << get(nb - 3) << ", " << get(nb - 2) << ", " << get(nb - 1);
out << "(" << nb << " elements)]";
}
out << "]";
}
void Polyline::redisplay(const BaseDriver& driver) const {
if (polygon_.size() > 1)
driver.redisplay(*this);
}
void Polyline::newHole() {
holes_.push_back(deque<PaperPoint>());
}
void Polyline::push_back_hole(const PaperPoint& point) {
holes_.back().push_back(point);
}
Polyline::Holes::const_iterator Polyline::beginHoles() const {
return holes_.begin();
}
Polyline::Holes::const_iterator Polyline::endHoles() const {
return holes_.end();
}
void Polyline::hole(Holes::const_iterator hole, vector<double>& x, vector<double>& y) const {
x.reserve(hole->size());
y.reserve(hole->size());
for (deque<PaperPoint>::const_iterator h = hole->begin(); h != hole->end(); ++h) {
x.push_back(h->x_);
y.push_back(h->y_);
}
}
void Polyline::hole(Holes::const_iterator hole, Polyline& poly) const {
for (deque<PaperPoint>::const_iterator h = hole->begin(); h != hole->end(); ++h) {
poly.push_back(*h);
}
}
struct SouthCleaner {
SouthCleaner() {}
bool operator()(PaperPoint& point) { return point.y_ < -89; }
};
struct LonFinder : std::unary_function<PaperPoint, bool> {
LonFinder() {}
bool operator()(PaperPoint& point) const { return (same(point.x_, -180.)); }
};
void Polyline::southClean(bool add) {
if (!add) {
auto from = std::remove_if(polygon_.begin(), polygon_.end(), SouthCleaner());
polygon_.erase(from, polygon_.end());
}
// rotate ..
auto it = std::find_if(polygon_.begin(), polygon_.end(), LonFinder());
if (it != polygon_.end()) {
std::rotate(polygon_.begin(), it, polygon_.end());
}
// Not South pole .. we try to force closing
close();
}
void Polyline::newHole(const Polyline& poly) {
holes_.push_back(deque<PaperPoint>());
for (auto point = poly.begin(); point != poly.end(); ++point) {
holes_.back().push_back(*point);
}
}
struct ReprojectHelper {
ReprojectHelper(const Transformation& transformation) : transformation_(transformation) {}
const Transformation& transformation_;
bool operator()(PaperPoint& point) { return !transformation_.fast_reproject(point.x_, point.y_); };
};
void Polyline::reproject(const Transformation& transformation) {
auto from = std::remove_if(polygon_.begin(), polygon_.end(), ReprojectHelper(transformation));
polygon_.erase(from, polygon_.end());
// Now the holes!
for (Holes::iterator hole = holes_.begin(); hole != holes_.end(); ++hole) {
for (auto h = hole->begin(); h != hole->end(); ++h) {
transformation.fast_reproject(h->x_, h->y_);
}
}
}
Polyline* Polyline::clone() const {
Polyline* to = getNew();
for (auto point = begin(); point != end(); ++point) {
to->push_back(*point);
}
// Now the holes!
for (Holes::const_iterator hole = holes_.begin(); hole != holes_.end(); ++hole) {
to->newHole();
for (auto h = hole->begin(); h != hole->end(); ++h) {
to->push_back_hole(*h);
}
}
return to;
}
void Polyline::intersect(const Polyline& poly, vector<Polyline*>& out) const {
// Use of a MagClipper
MagClipper::clip(poly, *this, out);
}
bool Polyline::skinny_ = false;
void feed(const deque<PaperPoint>& points, const Polyline& box, vector<Polyline*>& out) {
Polyline* poly = new Polyline();
for (auto p = points.begin(); p != points.end(); ++p) {
if (Polyline::skinny_) {
poly->push_back(*p);
continue;
}
if (!box.in(*p) || p->border()) {
if (poly->size()) {
out.push_back(poly);
poly = new Polyline();
}
}
else
poly->push_back(*p);
}
if (poly->size()) {
out.push_back(poly);
}
else
delete poly;
}
void Polyline::clip(const Polyline& poly, vector<Polyline*>& out) const {
feed(polygon_, poly, out);
for (Holes::const_iterator hole = holes_.begin(); hole != holes_.end(); ++hole) {
feed(*hole, poly, out);
}
}
// Is the pointincluded in the polyline"
bool Polyline::in(const PaperPoint& point) const {
return MagClipper::in(*this, point);
}
void Polyline::push_front(Polyline& other) {
other.polygon_.pop_back();
polygon_.insert(polygon_.begin(), other.polygon_.begin(), other.polygon_.end());
}
void Polyline::push_back(Polyline& other) {
other.polygon_.pop_front();
polygon_.insert(polygon_.end(), other.polygon_.begin(), other.polygon_.end());
}
double PaperPoint::distance(const PaperPoint& other) const {
return sqrt(((x_ - other.x_) * (x_ - other.x_)) + ((y_ - other.y_) * (y_ - other.y_)));
}
void Polyline::box(const PaperPoint& ll, const PaperPoint& ur) {
push_back(ll);
push_back(ll.x(), ur.y());
push_back(ur);
push_back(ur.x(), ll.y());
push_back(ll);
}
bool Polyline::within(const PaperPoint& point) const {
return MagClipper::in(*this, point);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.